/**
* plotly.js v3.4.0
* Copyright 2012-2026, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
(
 function(root, factory) {
  if (typeof module === "object" && module.exports) {
   module.exports = factory();
  } else {
   root.moduleName = factory();
  }
} (typeof self !== "undefined" ? self : this, () => {
"use strict";
var Plotly = (() => {
  var __create = Object.create;
  var __defProp = Object.defineProperty;
  var __defProps = Object.defineProperties;
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  var __getProtoOf = Object.getPrototypeOf;
  var __hasOwnProp = Object.prototype.hasOwnProperty;
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __spreadValues = (a, b) => {
    for (var prop in b || (b = {}))
      if (__hasOwnProp.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    if (__getOwnPropSymbols)
      for (var prop of __getOwnPropSymbols(b)) {
        if (__propIsEnum.call(b, prop))
          __defNormalProp(a, prop, b[prop]);
      }
    return a;
  };
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  var __objRest = (source, exclude) => {
    var target = {};
    for (var prop in source)
      if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
        target[prop] = source[prop];
    if (source != null && __getOwnPropSymbols)
      for (var prop of __getOwnPropSymbols(source)) {
        if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
          target[prop] = source[prop];
      }
    return target;
  };
  var __esm = (fn, res) => function __init() {
    return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  };
  var __commonJS = (cb, mod) => function __require() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target, all) => {
    for (var name2 in all)
      __defProp(target, name2, { get: all[name2], enumerable: true });
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key) && key !== except)
          __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
    }
    return to;
  };
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
    // If the importer is in node compatibility mode or this is not an ESM
    // file that has been converted to a CommonJS file using a Babel-
    // compatible transform (i.e. "__esModule" has not been set), then set
    // "default" to the CommonJS "module.exports" for node compatibility.
    isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
    mod
  ));
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

  // src/version.js
  var require_version = __commonJS({
    "src/version.js"(exports) {
      "use strict";
      exports.version = "3.4.0";
    }
  });

  // node_modules/native-promise-only/lib/npo.src.js
  var require_npo_src = __commonJS({
    "node_modules/native-promise-only/lib/npo.src.js"(exports, module) {
      (function UMD(name2, context, definition) {
        context[name2] = context[name2] || definition();
        if (typeof module != "undefined" && module.exports) {
          module.exports = context[name2];
        } else if (typeof define == "function" && false) {
          define(function $AMD$() {
            return context[name2];
          });
        }
      })("Promise", typeof window != "undefined" ? window : exports, function DEF() {
        "use strict";
        var builtInProp, cycle, scheduling_queue, ToString = Object.prototype.toString, timer = typeof setImmediate != "undefined" ? function timer2(fn) {
          return setImmediate(fn);
        } : setTimeout;
        try {
          Object.defineProperty({}, "x", {});
          builtInProp = function builtInProp2(obj, name2, val, config) {
            return Object.defineProperty(obj, name2, {
              value: val,
              writable: true,
              configurable: config !== false
            });
          };
        } catch (err) {
          builtInProp = function builtInProp2(obj, name2, val) {
            obj[name2] = val;
            return obj;
          };
        }
        scheduling_queue = /* @__PURE__ */ function Queue() {
          var first, last, item;
          function Item(fn, self2) {
            this.fn = fn;
            this.self = self2;
            this.next = void 0;
          }
          return {
            add: function add(fn, self2) {
              item = new Item(fn, self2);
              if (last) {
                last.next = item;
              } else {
                first = item;
              }
              last = item;
              item = void 0;
            },
            drain: function drain() {
              var f = first;
              first = last = cycle = void 0;
              while (f) {
                f.fn.call(f.self);
                f = f.next;
              }
            }
          };
        }();
        function schedule(fn, self2) {
          scheduling_queue.add(fn, self2);
          if (!cycle) {
            cycle = timer(scheduling_queue.drain);
          }
        }
        function isThenable(o) {
          var _then, o_type = typeof o;
          if (o != null && (o_type == "object" || o_type == "function")) {
            _then = o.then;
          }
          return typeof _then == "function" ? _then : false;
        }
        function notify() {
          for (var i = 0; i < this.chain.length; i++) {
            notifyIsolated(
              this,
              this.state === 1 ? this.chain[i].success : this.chain[i].failure,
              this.chain[i]
            );
          }
          this.chain.length = 0;
        }
        function notifyIsolated(self2, cb, chain) {
          var ret, _then;
          try {
            if (cb === false) {
              chain.reject(self2.msg);
            } else {
              if (cb === true) {
                ret = self2.msg;
              } else {
                ret = cb.call(void 0, self2.msg);
              }
              if (ret === chain.promise) {
                chain.reject(TypeError("Promise-chain cycle"));
              } else if (_then = isThenable(ret)) {
                _then.call(ret, chain.resolve, chain.reject);
              } else {
                chain.resolve(ret);
              }
            }
          } catch (err) {
            chain.reject(err);
          }
        }
        function resolve(msg) {
          var _then, self2 = this;
          if (self2.triggered) {
            return;
          }
          self2.triggered = true;
          if (self2.def) {
            self2 = self2.def;
          }
          try {
            if (_then = isThenable(msg)) {
              schedule(function() {
                var def_wrapper = new MakeDefWrapper(self2);
                try {
                  _then.call(
                    msg,
                    function $resolve$() {
                      resolve.apply(def_wrapper, arguments);
                    },
                    function $reject$() {
                      reject.apply(def_wrapper, arguments);
                    }
                  );
                } catch (err) {
                  reject.call(def_wrapper, err);
                }
              });
            } else {
              self2.msg = msg;
              self2.state = 1;
              if (self2.chain.length > 0) {
                schedule(notify, self2);
              }
            }
          } catch (err) {
            reject.call(new MakeDefWrapper(self2), err);
          }
        }
        function reject(msg) {
          var self2 = this;
          if (self2.triggered) {
            return;
          }
          self2.triggered = true;
          if (self2.def) {
            self2 = self2.def;
          }
          self2.msg = msg;
          self2.state = 2;
          if (self2.chain.length > 0) {
            schedule(notify, self2);
          }
        }
        function iteratePromises(Constructor, arr, resolver, rejecter) {
          for (var idx = 0; idx < arr.length; idx++) {
            (function IIFE(idx2) {
              Constructor.resolve(arr[idx2]).then(
                function $resolver$(msg) {
                  resolver(idx2, msg);
                },
                rejecter
              );
            })(idx);
          }
        }
        function MakeDefWrapper(self2) {
          this.def = self2;
          this.triggered = false;
        }
        function MakeDef(self2) {
          this.promise = self2;
          this.state = 0;
          this.triggered = false;
          this.chain = [];
          this.msg = void 0;
        }
        function Promise2(executor) {
          if (typeof executor != "function") {
            throw TypeError("Not a function");
          }
          if (this.__NPO__ !== 0) {
            throw TypeError("Not a promise");
          }
          this.__NPO__ = 1;
          var def = new MakeDef(this);
          this["then"] = function then(success, failure) {
            var o = {
              success: typeof success == "function" ? success : true,
              failure: typeof failure == "function" ? failure : false
            };
            o.promise = new this.constructor(function extractChain(resolve2, reject2) {
              if (typeof resolve2 != "function" || typeof reject2 != "function") {
                throw TypeError("Not a function");
              }
              o.resolve = resolve2;
              o.reject = reject2;
            });
            def.chain.push(o);
            if (def.state !== 0) {
              schedule(notify, def);
            }
            return o.promise;
          };
          this["catch"] = function $catch$(failure) {
            return this.then(void 0, failure);
          };
          try {
            executor.call(
              void 0,
              function publicResolve(msg) {
                resolve.call(def, msg);
              },
              function publicReject(msg) {
                reject.call(def, msg);
              }
            );
          } catch (err) {
            reject.call(def, err);
          }
        }
        var PromisePrototype = builtInProp(
          {},
          "constructor",
          Promise2,
          /*configurable=*/
          false
        );
        Promise2.prototype = PromisePrototype;
        builtInProp(
          PromisePrototype,
          "__NPO__",
          0,
          /*configurable=*/
          false
        );
        builtInProp(Promise2, "resolve", function Promise$resolve(msg) {
          var Constructor = this;
          if (msg && typeof msg == "object" && msg.__NPO__ === 1) {
            return msg;
          }
          return new Constructor(function executor(resolve2, reject2) {
            if (typeof resolve2 != "function" || typeof reject2 != "function") {
              throw TypeError("Not a function");
            }
            resolve2(msg);
          });
        });
        builtInProp(Promise2, "reject", function Promise$reject(msg) {
          return new this(function executor(resolve2, reject2) {
            if (typeof resolve2 != "function" || typeof reject2 != "function") {
              throw TypeError("Not a function");
            }
            reject2(msg);
          });
        });
        builtInProp(Promise2, "all", function Promise$all(arr) {
          var Constructor = this;
          if (ToString.call(arr) != "[object Array]") {
            return Constructor.reject(TypeError("Not an array"));
          }
          if (arr.length === 0) {
            return Constructor.resolve([]);
          }
          return new Constructor(function executor(resolve2, reject2) {
            if (typeof resolve2 != "function" || typeof reject2 != "function") {
              throw TypeError("Not a function");
            }
            var len = arr.length, msgs = Array(len), count = 0;
            iteratePromises(Constructor, arr, function resolver(idx, msg) {
              msgs[idx] = msg;
              if (++count === len) {
                resolve2(msgs);
              }
            }, reject2);
          });
        });
        builtInProp(Promise2, "race", function Promise$race(arr) {
          var Constructor = this;
          if (ToString.call(arr) != "[object Array]") {
            return Constructor.reject(TypeError("Not an array"));
          }
          return new Constructor(function executor(resolve2, reject2) {
            if (typeof resolve2 != "function" || typeof reject2 != "function") {
              throw TypeError("Not a function");
            }
            iteratePromises(Constructor, arr, function resolver(idx, msg) {
              resolve2(msg);
            }, reject2);
          });
        });
        return Promise2;
      });
    }
  });

  // node_modules/@plotly/d3/d3.js
  var require_d3 = __commonJS({
    "node_modules/@plotly/d3/d3.js"(exports, module) {
      !function() {
        var d3 = {
          version: "3.8.2"
        };
        var d3_arraySlice = [].slice, d3_array = function(list) {
          return d3_arraySlice.call(list);
        };
        var d3_document = self.document;
        function d3_documentElement(node) {
          return node && (node.ownerDocument || node.document || node).documentElement;
        }
        function d3_window(node) {
          return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
        }
        if (d3_document) {
          try {
            d3_array(d3_document.documentElement.childNodes)[0].nodeType;
          } catch (e) {
            d3_array = function(list) {
              var i = list.length, array = new Array(i);
              while (i--) array[i] = list[i];
              return array;
            };
          }
        }
        if (!Date.now) Date.now = function() {
          return +/* @__PURE__ */ new Date();
        };
        if (d3_document) {
          try {
            d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
          } catch (error) {
            var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
            d3_element_prototype.setAttribute = function(name2, value) {
              d3_element_setAttribute.call(this, name2, value + "");
            };
            d3_element_prototype.setAttributeNS = function(space, local, value) {
              d3_element_setAttributeNS.call(this, space, local, value + "");
            };
            d3_style_prototype.setProperty = function(name2, value, priority) {
              d3_style_setProperty.call(this, name2, value + "", priority);
            };
          }
        }
        d3.ascending = d3_ascending;
        function d3_ascending(a, b) {
          return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
        }
        d3.descending = function(a, b) {
          return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
        };
        d3.min = function(array, f) {
          var i = -1, n = array.length, a, b;
          if (arguments.length === 1) {
            while (++i < n) if ((b = array[i]) != null && b >= b) {
              a = b;
              break;
            }
            while (++i < n) if ((b = array[i]) != null && a > b) a = b;
          } else {
            while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
              a = b;
              break;
            }
            while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
          }
          return a;
        };
        d3.max = function(array, f) {
          var i = -1, n = array.length, a, b;
          if (arguments.length === 1) {
            while (++i < n) if ((b = array[i]) != null && b >= b) {
              a = b;
              break;
            }
            while (++i < n) if ((b = array[i]) != null && b > a) a = b;
          } else {
            while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
              a = b;
              break;
            }
            while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
          }
          return a;
        };
        d3.extent = function(array, f) {
          var i = -1, n = array.length, a, b, c;
          if (arguments.length === 1) {
            while (++i < n) if ((b = array[i]) != null && b >= b) {
              a = c = b;
              break;
            }
            while (++i < n) if ((b = array[i]) != null) {
              if (a > b) a = b;
              if (c < b) c = b;
            }
          } else {
            while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
              a = c = b;
              break;
            }
            while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
              if (a > b) a = b;
              if (c < b) c = b;
            }
          }
          return [a, c];
        };
        function d3_number(x) {
          return x === null ? NaN : +x;
        }
        function d3_numeric(x) {
          return !isNaN(x);
        }
        d3.sum = function(array, f) {
          var s = 0, n = array.length, a, i = -1;
          if (arguments.length === 1) {
            while (++i < n) if (d3_numeric(a = +array[i])) s += a;
          } else {
            while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
          }
          return s;
        };
        d3.mean = function(array, f) {
          var s = 0, n = array.length, a, i = -1, j = n;
          if (arguments.length === 1) {
            while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a;
            else --j;
          } else {
            while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a;
            else --j;
          }
          if (j) return s / j;
        };
        d3.quantile = function(values, p) {
          var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
          return e ? v + e * (values[h] - v) : v;
        };
        d3.median = function(array, f) {
          var numbers = [], n = array.length, a, i = -1;
          if (arguments.length === 1) {
            while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
          } else {
            while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
          }
          if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), 0.5);
        };
        d3.variance = function(array, f) {
          var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
          if (arguments.length === 1) {
            while (++i < n) {
              if (d3_numeric(a = d3_number(array[i]))) {
                d = a - m;
                m += d / ++j;
                s += d * (a - m);
              }
            }
          } else {
            while (++i < n) {
              if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
                d = a - m;
                m += d / ++j;
                s += d * (a - m);
              }
            }
          }
          if (j > 1) return s / (j - 1);
        };
        d3.deviation = function() {
          var v = d3.variance.apply(this, arguments);
          return v ? Math.sqrt(v) : v;
        };
        function d3_bisector(compare) {
          return {
            left: function(a, x, lo, hi) {
              if (arguments.length < 3) lo = 0;
              if (arguments.length < 4) hi = a.length;
              while (lo < hi) {
                var mid = lo + hi >>> 1;
                if (compare(a[mid], x) < 0) lo = mid + 1;
                else hi = mid;
              }
              return lo;
            },
            right: function(a, x, lo, hi) {
              if (arguments.length < 3) lo = 0;
              if (arguments.length < 4) hi = a.length;
              while (lo < hi) {
                var mid = lo + hi >>> 1;
                if (compare(a[mid], x) > 0) hi = mid;
                else lo = mid + 1;
              }
              return lo;
            }
          };
        }
        var d3_bisect = d3_bisector(d3_ascending);
        d3.bisectLeft = d3_bisect.left;
        d3.bisect = d3.bisectRight = d3_bisect.right;
        d3.bisector = function(f) {
          return d3_bisector(f.length === 1 ? function(d, x) {
            return d3_ascending(f(d), x);
          } : f);
        };
        d3.shuffle = function(array, i0, i1) {
          if ((m = arguments.length) < 3) {
            i1 = array.length;
            if (m < 2) i0 = 0;
          }
          var m = i1 - i0, t, i;
          while (m) {
            i = Math.random() * m-- | 0;
            t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
          }
          return array;
        };
        d3.permute = function(array, indexes) {
          var i = indexes.length, permutes = new Array(i);
          while (i--) permutes[i] = array[indexes[i]];
          return permutes;
        };
        d3.pairs = function(array) {
          var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
          while (i < n) pairs[i] = [p0 = p1, p1 = array[++i]];
          return pairs;
        };
        d3.transpose = function(matrix) {
          if (!(n = matrix.length)) return [];
          for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
            for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
              row[j] = matrix[j][i];
            }
          }
          return transpose;
        };
        function d3_transposeLength(d) {
          return d.length;
        }
        d3.zip = function() {
          return d3.transpose(arguments);
        };
        d3.keys = function(map) {
          var keys = [];
          for (var key in map) keys.push(key);
          return keys;
        };
        d3.values = function(map) {
          var values = [];
          for (var key in map) values.push(map[key]);
          return values;
        };
        d3.entries = function(map) {
          var entries = [];
          for (var key in map) entries.push({
            key,
            value: map[key]
          });
          return entries;
        };
        d3.merge = function(arrays) {
          var n = arrays.length, m, i = -1, j = 0, merged, array;
          while (++i < n) j += arrays[i].length;
          merged = new Array(j);
          while (--n >= 0) {
            array = arrays[n];
            m = array.length;
            while (--m >= 0) {
              merged[--j] = array[m];
            }
          }
          return merged;
        };
        var abs = Math.abs;
        d3.range = function(start, stop, step) {
          if (arguments.length < 3) {
            step = 1;
            if (arguments.length < 2) {
              stop = start;
              start = 0;
            }
          }
          if ((stop - start) / step === Infinity) throw new Error("infinite range");
          var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
          start *= k, stop *= k, step *= k;
          if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k);
          else while ((j = start + step * ++i) < stop) range.push(j / k);
          return range;
        };
        function d3_range_integerScale(x) {
          var k = 1;
          while (x * k % 1) k *= 10;
          return k;
        }
        function d3_class(ctor, properties) {
          for (var key in properties) {
            Object.defineProperty(ctor.prototype, key, {
              value: properties[key],
              enumerable: false
            });
          }
        }
        d3.map = function(object, f) {
          var map = new d3_Map();
          if (object instanceof d3_Map) {
            object.forEach(function(key2, value) {
              map.set(key2, value);
            });
          } else if (Array.isArray(object)) {
            var i = -1, n = object.length, o;
            if (arguments.length === 1) while (++i < n) map.set(i, object[i]);
            else while (++i < n) map.set(f.call(object, o = object[i], i), o);
          } else {
            for (var key in object) map.set(key, object[key]);
          }
          return map;
        };
        function d3_Map() {
          this._ = /* @__PURE__ */ Object.create(null);
        }
        var d3_map_proto = "__proto__", d3_map_zero = "\0";
        d3_class(d3_Map, {
          has: d3_map_has,
          get: function(key) {
            return this._[d3_map_escape(key)];
          },
          set: function(key, value) {
            return this._[d3_map_escape(key)] = value;
          },
          remove: d3_map_remove,
          keys: d3_map_keys,
          values: function() {
            var values = [];
            for (var key in this._) values.push(this._[key]);
            return values;
          },
          entries: function() {
            var entries = [];
            for (var key in this._) entries.push({
              key: d3_map_unescape(key),
              value: this._[key]
            });
            return entries;
          },
          size: d3_map_size,
          empty: d3_map_empty,
          forEach: function(f) {
            for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
          }
        });
        function d3_map_escape(key) {
          return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
        }
        function d3_map_unescape(key) {
          return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
        }
        function d3_map_has(key) {
          return d3_map_escape(key) in this._;
        }
        function d3_map_remove(key) {
          return (key = d3_map_escape(key)) in this._ && delete this._[key];
        }
        function d3_map_keys() {
          var keys = [];
          for (var key in this._) keys.push(d3_map_unescape(key));
          return keys;
        }
        function d3_map_size() {
          var size = 0;
          for (var key in this._) ++size;
          return size;
        }
        function d3_map_empty() {
          for (var key in this._) return false;
          return true;
        }
        d3.nest = function() {
          var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
          function map(mapType, array, depth) {
            if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
            var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
            while (++i < n) {
              if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
                values.push(object);
              } else {
                valuesByKey.set(keyValue, [object]);
              }
            }
            if (mapType) {
              object = mapType();
              setter = function(keyValue2, values2) {
                object.set(keyValue2, map(mapType, values2, depth));
              };
            } else {
              object = {};
              setter = function(keyValue2, values2) {
                object[keyValue2] = map(mapType, values2, depth);
              };
            }
            valuesByKey.forEach(setter);
            return object;
          }
          function entries(map2, depth) {
            if (depth >= keys.length) return map2;
            var array = [], sortKey = sortKeys[depth++];
            map2.forEach(function(key, keyMap) {
              array.push({
                key,
                values: entries(keyMap, depth)
              });
            });
            return sortKey ? array.sort(function(a, b) {
              return sortKey(a.key, b.key);
            }) : array;
          }
          nest.map = function(array, mapType) {
            return map(mapType, array, 0);
          };
          nest.entries = function(array) {
            return entries(map(d3.map, array, 0), 0);
          };
          nest.key = function(d) {
            keys.push(d);
            return nest;
          };
          nest.sortKeys = function(order) {
            sortKeys[keys.length - 1] = order;
            return nest;
          };
          nest.sortValues = function(order) {
            sortValues = order;
            return nest;
          };
          nest.rollup = function(f) {
            rollup = f;
            return nest;
          };
          return nest;
        };
        d3.set = function(array) {
          var set = new d3_Set();
          if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
          return set;
        };
        function d3_Set() {
          this._ = /* @__PURE__ */ Object.create(null);
        }
        d3_class(d3_Set, {
          has: d3_map_has,
          add: function(key) {
            this._[d3_map_escape(key += "")] = true;
            return key;
          },
          remove: d3_map_remove,
          values: d3_map_keys,
          size: d3_map_size,
          empty: d3_map_empty,
          forEach: function(f) {
            for (var key in this._) f.call(this, d3_map_unescape(key));
          }
        });
        d3.behavior = {};
        function d3_identity(d) {
          return d;
        }
        d3.rebind = function(target, source) {
          var i = 1, n = arguments.length, method;
          while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
          return target;
        };
        function d3_rebind(target, source, method) {
          return function() {
            var value = method.apply(source, arguments);
            return value === source ? target : value;
          };
        }
        function d3_vendorSymbol(object, name2) {
          if (name2 in object) return name2;
          name2 = name2.charAt(0).toUpperCase() + name2.slice(1);
          for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
            var prefixName = d3_vendorPrefixes[i] + name2;
            if (prefixName in object) return prefixName;
          }
        }
        var d3_vendorPrefixes = ["webkit", "ms", "moz", "Moz", "o", "O"];
        function d3_noop() {
        }
        d3.dispatch = function() {
          var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
          while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
          return dispatch;
        };
        function d3_dispatch() {
        }
        d3_dispatch.prototype.on = function(type, listener) {
          var i = type.indexOf("."), name2 = "";
          if (i >= 0) {
            name2 = type.slice(i + 1);
            type = type.slice(0, i);
          }
          if (type) return arguments.length < 2 ? this[type].on(name2) : this[type].on(name2, listener);
          if (arguments.length === 2) {
            if (listener == null) for (type in this) {
              if (this.hasOwnProperty(type)) this[type].on(name2, null);
            }
            return this;
          }
        };
        function d3_dispatch_event(dispatch) {
          var listeners = [], listenerByName = new d3_Map();
          function event() {
            var z = listeners, i = -1, n = z.length, l;
            while (++i < n) if (l = z[i].on) l.apply(this, arguments);
            return dispatch;
          }
          event.on = function(name2, listener) {
            var l = listenerByName.get(name2), i;
            if (arguments.length < 2) return l && l.on;
            if (l) {
              l.on = null;
              listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
              listenerByName.remove(name2);
            }
            if (listener) listeners.push(listenerByName.set(name2, {
              on: listener
            }));
            return dispatch;
          };
          return event;
        }
        d3.event = null;
        function d3_eventPreventDefault() {
          d3.event.preventDefault();
        }
        function d3_eventSource() {
          var e = d3.event, s;
          while (s = e.sourceEvent) e = s;
          return e;
        }
        function d3_eventDispatch(target) {
          var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
          while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
          dispatch.of = function(thiz, argumentz) {
            return function(e1) {
              try {
                var e0 = e1.sourceEvent = d3.event;
                e1.target = target;
                d3.event = e1;
                dispatch[e1.type].apply(thiz, argumentz);
              } finally {
                d3.event = e0;
              }
            };
          };
          return dispatch;
        }
        d3.requote = function(s) {
          return s.replace(d3_requote_re, "\\$&");
        };
        var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
        var d3_subclass = {}.__proto__ ? function(object, prototype) {
          object.__proto__ = prototype;
        } : function(object, prototype) {
          for (var property in prototype) object[property] = prototype[property];
        };
        function d3_selection(groups) {
          d3_subclass(groups, d3_selectionPrototype);
          return groups;
        }
        var d3_select = function(s, n) {
          return n.querySelector(s);
        }, d3_selectAll = function(s, n) {
          return n.querySelectorAll(s);
        }, d3_selectMatches = function(n, s) {
          var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
          d3_selectMatches = function(n2, s2) {
            return d3_selectMatcher.call(n2, s2);
          };
          return d3_selectMatches(n, s);
        };
        if (typeof Sizzle === "function") {
          d3_select = function(s, n) {
            return Sizzle(s, n)[0] || null;
          };
          d3_selectAll = Sizzle;
          d3_selectMatches = Sizzle.matchesSelector;
        }
        d3.selection = function() {
          return d3.select(d3_document.documentElement);
        };
        var d3_selectionPrototype = d3.selection.prototype = [];
        d3_selectionPrototype.select = function(selector) {
          var subgroups = [], subgroup, subnode, group, node;
          selector = d3_selection_selector(selector);
          for (var j = -1, m = this.length; ++j < m; ) {
            subgroups.push(subgroup = []);
            subgroup.parentNode = (group = this[j]).parentNode;
            for (var i = -1, n = group.length; ++i < n; ) {
              if (node = group[i]) {
                subgroup.push(subnode = selector.call(node, node.__data__, i, j));
                if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
              } else {
                subgroup.push(null);
              }
            }
          }
          return d3_selection(subgroups);
        };
        function d3_selection_selector(selector) {
          return typeof selector === "function" ? selector : function() {
            return d3_select(selector, this);
          };
        }
        d3_selectionPrototype.selectAll = function(selector) {
          var subgroups = [], subgroup, node;
          selector = d3_selection_selectorAll(selector);
          for (var j = -1, m = this.length; ++j < m; ) {
            for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
              if (node = group[i]) {
                subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
                subgroup.parentNode = node;
              }
            }
          }
          return d3_selection(subgroups);
        };
        function d3_selection_selectorAll(selector) {
          return typeof selector === "function" ? selector : function() {
            return d3_selectAll(selector, this);
          };
        }
        var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
        var d3_nsPrefix = {
          svg: "http://www.w3.org/2000/svg",
          xhtml: d3_nsXhtml,
          xlink: "http://www.w3.org/1999/xlink",
          xml: "http://www.w3.org/XML/1998/namespace",
          xmlns: "http://www.w3.org/2000/xmlns/"
        };
        d3.ns = {
          prefix: d3_nsPrefix,
          qualify: function(name2) {
            var i = name2.indexOf(":"), prefix = name2;
            if (i >= 0 && (prefix = name2.slice(0, i)) !== "xmlns") name2 = name2.slice(i + 1);
            return d3_nsPrefix.hasOwnProperty(prefix) ? {
              space: d3_nsPrefix[prefix],
              local: name2
            } : name2;
          }
        };
        d3_selectionPrototype.attr = function(name2, value) {
          if (arguments.length < 2) {
            if (typeof name2 === "string") {
              var node = this.node();
              name2 = d3.ns.qualify(name2);
              return name2.local ? node.getAttributeNS(name2.space, name2.local) : node.getAttribute(name2);
            }
            for (value in name2) this.each(d3_selection_attr(value, name2[value]));
            return this;
          }
          return this.each(d3_selection_attr(name2, value));
        };
        function d3_selection_attr(name2, value) {
          name2 = d3.ns.qualify(name2);
          function attrNull() {
            this.removeAttribute(name2);
          }
          function attrNullNS() {
            this.removeAttributeNS(name2.space, name2.local);
          }
          function attrConstant() {
            this.setAttribute(name2, value);
          }
          function attrConstantNS() {
            this.setAttributeNS(name2.space, name2.local, value);
          }
          function attrFunction() {
            var x = value.apply(this, arguments);
            if (x == null) this.removeAttribute(name2);
            else this.setAttribute(name2, x);
          }
          function attrFunctionNS() {
            var x = value.apply(this, arguments);
            if (x == null) this.removeAttributeNS(name2.space, name2.local);
            else this.setAttributeNS(name2.space, name2.local, x);
          }
          return value == null ? name2.local ? attrNullNS : attrNull : typeof value === "function" ? name2.local ? attrFunctionNS : attrFunction : name2.local ? attrConstantNS : attrConstant;
        }
        function d3_collapse(s) {
          return s.trim().replace(/\s+/g, " ");
        }
        d3_selectionPrototype.classed = function(name2, value) {
          if (arguments.length < 2) {
            if (typeof name2 === "string") {
              var node = this.node(), n = (name2 = d3_selection_classes(name2)).length, i = -1;
              if (value = node.classList) {
                while (++i < n) if (!value.contains(name2[i])) return false;
              } else {
                value = node.getAttribute("class");
                while (++i < n) if (!d3_selection_classedRe(name2[i]).test(value)) return false;
              }
              return true;
            }
            for (value in name2) this.each(d3_selection_classed(value, name2[value]));
            return this;
          }
          return this.each(d3_selection_classed(name2, value));
        };
        function d3_selection_classedRe(name2) {
          return new RegExp("(?:^|\\s+)" + d3.requote(name2) + "(?:\\s+|$)", "g");
        }
        function d3_selection_classes(name2) {
          return (name2 + "").trim().split(/^|\s+/);
        }
        function d3_selection_classed(name2, value) {
          name2 = d3_selection_classes(name2).map(d3_selection_classedName);
          var n = name2.length;
          function classedConstant() {
            var i = -1;
            while (++i < n) name2[i](this, value);
          }
          function classedFunction() {
            var i = -1, x = value.apply(this, arguments);
            while (++i < n) name2[i](this, x);
          }
          return typeof value === "function" ? classedFunction : classedConstant;
        }
        function d3_selection_classedName(name2) {
          var re = d3_selection_classedRe(name2);
          return function(node, value) {
            if (c = node.classList) return value ? c.add(name2) : c.remove(name2);
            var c = node.getAttribute("class") || "";
            if (value) {
              re.lastIndex = 0;
              if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name2));
            } else {
              node.setAttribute("class", d3_collapse(c.replace(re, " ")));
            }
          };
        }
        d3_selectionPrototype.style = function(name2, value, priority) {
          var n = arguments.length;
          if (n < 3) {
            if (typeof name2 !== "string") {
              if (n < 2) value = "";
              for (priority in name2) this.each(d3_selection_style(priority, name2[priority], value));
              return this;
            }
            if (n < 2) {
              var node = this.node();
              return d3_window(node).getComputedStyle(node, null).getPropertyValue(name2);
            }
            priority = "";
          }
          return this.each(d3_selection_style(name2, value, priority));
        };
        function d3_selection_style(name2, value, priority) {
          function styleNull() {
            this.style.removeProperty(name2);
          }
          function styleConstant() {
            this.style.setProperty(name2, value, priority);
          }
          function styleFunction() {
            var x = value.apply(this, arguments);
            if (x == null) this.style.removeProperty(name2);
            else this.style.setProperty(name2, x, priority);
          }
          return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
        }
        d3_selectionPrototype.property = function(name2, value) {
          if (arguments.length < 2) {
            if (typeof name2 === "string") return this.node()[name2];
            for (value in name2) this.each(d3_selection_property(value, name2[value]));
            return this;
          }
          return this.each(d3_selection_property(name2, value));
        };
        function d3_selection_property(name2, value) {
          function propertyNull() {
            delete this[name2];
          }
          function propertyConstant() {
            this[name2] = value;
          }
          function propertyFunction() {
            var x = value.apply(this, arguments);
            if (x == null) delete this[name2];
            else this[name2] = x;
          }
          return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
        }
        d3_selectionPrototype.text = function(value) {
          return arguments.length ? this.each(typeof value === "function" ? function() {
            var v = value.apply(this, arguments);
            this.textContent = v == null ? "" : v;
          } : value == null ? function() {
            this.textContent = "";
          } : function() {
            this.textContent = value;
          }) : this.node().textContent;
        };
        d3_selectionPrototype.html = function(value) {
          return arguments.length ? this.each(typeof value === "function" ? function() {
            var v = value.apply(this, arguments);
            this.innerHTML = v == null ? "" : v;
          } : value == null ? function() {
            this.innerHTML = "";
          } : function() {
            this.innerHTML = value;
          }) : this.node().innerHTML;
        };
        d3_selectionPrototype.append = function(name2) {
          name2 = d3_selection_creator(name2);
          return this.select(function() {
            return this.appendChild(name2.apply(this, arguments));
          });
        };
        function d3_selection_creator(name2) {
          function create() {
            var document2 = this.ownerDocument, namespace = this.namespaceURI;
            return namespace === d3_nsXhtml && document2.documentElement.namespaceURI === d3_nsXhtml ? document2.createElement(name2) : document2.createElementNS(namespace, name2);
          }
          function createNS() {
            return this.ownerDocument.createElementNS(name2.space, name2.local);
          }
          return typeof name2 === "function" ? name2 : (name2 = d3.ns.qualify(name2)).local ? createNS : create;
        }
        d3_selectionPrototype.insert = function(name2, before) {
          name2 = d3_selection_creator(name2);
          before = d3_selection_selector(before);
          return this.select(function() {
            return this.insertBefore(name2.apply(this, arguments), before.apply(this, arguments) || null);
          });
        };
        d3_selectionPrototype.remove = function() {
          return this.each(d3_selectionRemove);
        };
        function d3_selectionRemove() {
          var parent = this.parentNode;
          if (parent) parent.removeChild(this);
        }
        d3_selectionPrototype.data = function(value, key) {
          var i = -1, n = this.length, group, node;
          if (!arguments.length) {
            value = new Array(n = (group = this[0]).length);
            while (++i < n) {
              if (node = group[i]) {
                value[i] = node.__data__;
              }
            }
            return value;
          }
          function bind(group2, groupData) {
            var i2, n2 = group2.length, m = groupData.length, n0 = Math.min(n2, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n2), node2, nodeData;
            if (key) {
              var nodeByKeyValue = new d3_Map(), keyValues = new Array(n2), keyValue;
              for (i2 = -1; ++i2 < n2; ) {
                if (node2 = group2[i2]) {
                  if (nodeByKeyValue.has(keyValue = key.call(node2, node2.__data__, i2))) {
                    exitNodes[i2] = node2;
                  } else {
                    nodeByKeyValue.set(keyValue, node2);
                  }
                  keyValues[i2] = keyValue;
                }
              }
              for (i2 = -1; ++i2 < m; ) {
                if (!(node2 = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i2], i2)))) {
                  enterNodes[i2] = d3_selection_dataNode(nodeData);
                } else if (node2 !== true) {
                  updateNodes[i2] = node2;
                  node2.__data__ = nodeData;
                }
                nodeByKeyValue.set(keyValue, true);
              }
              for (i2 = -1; ++i2 < n2; ) {
                if (i2 in keyValues && nodeByKeyValue.get(keyValues[i2]) !== true) {
                  exitNodes[i2] = group2[i2];
                }
              }
            } else {
              for (i2 = -1; ++i2 < n0; ) {
                node2 = group2[i2];
                nodeData = groupData[i2];
                if (node2) {
                  node2.__data__ = nodeData;
                  updateNodes[i2] = node2;
                } else {
                  enterNodes[i2] = d3_selection_dataNode(nodeData);
                }
              }
              for (; i2 < m; ++i2) {
                enterNodes[i2] = d3_selection_dataNode(groupData[i2]);
              }
              for (; i2 < n2; ++i2) {
                exitNodes[i2] = group2[i2];
              }
            }
            enterNodes.update = updateNodes;
            enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group2.parentNode;
            enter.push(enterNodes);
            update.push(updateNodes);
            exit.push(exitNodes);
          }
          var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
          if (typeof value === "function") {
            while (++i < n) {
              bind(group = this[i], value.call(group, group.parentNode.__data__, i));
            }
          } else {
            while (++i < n) {
              bind(group = this[i], value);
            }
          }
          update.enter = function() {
            return enter;
          };
          update.exit = function() {
            return exit;
          };
          return update;
        };
        function d3_selection_dataNode(data) {
          return {
            __data__: data
          };
        }
        d3_selectionPrototype.datum = function(value) {
          return arguments.length ? this.property("__data__", value) : this.property("__data__");
        };
        d3_selectionPrototype.filter = function(filter) {
          var subgroups = [], subgroup, group, node;
          if (typeof filter !== "function") filter = d3_selection_filter(filter);
          for (var j = 0, m = this.length; j < m; j++) {
            subgroups.push(subgroup = []);
            subgroup.parentNode = (group = this[j]).parentNode;
            for (var i = 0, n = group.length; i < n; i++) {
              if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
                subgroup.push(node);
              }
            }
          }
          return d3_selection(subgroups);
        };
        function d3_selection_filter(selector) {
          return function() {
            return d3_selectMatches(this, selector);
          };
        }
        d3_selectionPrototype.order = function() {
          for (var j = -1, m = this.length; ++j < m; ) {
            for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
              if (node = group[i]) {
                if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
                next = node;
              }
            }
          }
          return this;
        };
        d3_selectionPrototype.sort = function(comparator) {
          comparator = d3_selection_sortComparator.apply(this, arguments);
          for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
          return this.order();
        };
        function d3_selection_sortComparator(comparator) {
          if (!arguments.length) comparator = d3_ascending;
          return function(a, b) {
            return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
          };
        }
        d3_selectionPrototype.each = function(callback) {
          return d3_selection_each(this, function(node, i, j) {
            callback.call(node, node.__data__, i, j);
          });
        };
        function d3_selection_each(groups, callback) {
          for (var j = 0, m = groups.length; j < m; j++) {
            for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
              if (node = group[i]) callback(node, i, j);
            }
          }
          return groups;
        }
        d3_selectionPrototype.call = function(callback) {
          var args = d3_array(arguments);
          callback.apply(args[0] = this, args);
          return this;
        };
        d3_selectionPrototype.empty = function() {
          return !this.node();
        };
        d3_selectionPrototype.node = function() {
          for (var j = 0, m = this.length; j < m; j++) {
            for (var group = this[j], i = 0, n = group.length; i < n; i++) {
              var node = group[i];
              if (node) return node;
            }
          }
          return null;
        };
        d3_selectionPrototype.size = function() {
          var n = 0;
          d3_selection_each(this, function() {
            ++n;
          });
          return n;
        };
        function d3_selection_enter(selection) {
          d3_subclass(selection, d3_selection_enterPrototype);
          return selection;
        }
        var d3_selection_enterPrototype = [];
        d3.selection.enter = d3_selection_enter;
        d3.selection.enter.prototype = d3_selection_enterPrototype;
        d3_selection_enterPrototype.append = d3_selectionPrototype.append;
        d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
        d3_selection_enterPrototype.node = d3_selectionPrototype.node;
        d3_selection_enterPrototype.call = d3_selectionPrototype.call;
        d3_selection_enterPrototype.size = d3_selectionPrototype.size;
        d3_selection_enterPrototype.select = function(selector) {
          var subgroups = [], subgroup, subnode, upgroup, group, node;
          for (var j = -1, m = this.length; ++j < m; ) {
            upgroup = (group = this[j]).update;
            subgroups.push(subgroup = []);
            subgroup.parentNode = group.parentNode;
            for (var i = -1, n = group.length; ++i < n; ) {
              if (node = group[i]) {
                subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
                subnode.__data__ = node.__data__;
              } else {
                subgroup.push(null);
              }
            }
          }
          return d3_selection(subgroups);
        };
        d3_selection_enterPrototype.insert = function(name2, before) {
          if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
          return d3_selectionPrototype.insert.call(this, name2, before);
        };
        function d3_selection_enterInsertBefore(enter) {
          var i0, j0;
          return function(d, i, j) {
            var group = enter[j].update, n = group.length, node;
            if (j != j0) j0 = j, i0 = 0;
            if (i >= i0) i0 = i + 1;
            while (!(node = group[i0]) && ++i0 < n) ;
            return node;
          };
        }
        d3.select = function(node) {
          var group;
          if (typeof node === "string") {
            group = [d3_select(node, d3_document)];
            group.parentNode = d3_document.documentElement;
          } else {
            group = [node];
            group.parentNode = d3_documentElement(node);
          }
          return d3_selection([group]);
        };
        d3.selectAll = function(nodes) {
          var group;
          if (typeof nodes === "string") {
            group = d3_array(d3_selectAll(nodes, d3_document));
            group.parentNode = d3_document.documentElement;
          } else {
            group = d3_array(nodes);
            group.parentNode = null;
          }
          return d3_selection([group]);
        };
        d3_selectionPrototype.on = function(type, listener, capture) {
          var n = arguments.length;
          if (n < 3) {
            if (typeof type !== "string") {
              if (n < 2) listener = false;
              for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
              return this;
            }
            if (n < 2) return (n = this.node()["__on" + type]) && n._;
            capture = false;
          }
          return this.each(d3_selection_on(type, listener, capture));
        };
        function d3_selection_on(type, listener, capture) {
          var name2 = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
          if (i > 0) type = type.slice(0, i);
          var filter = d3_selection_onFilters.get(type);
          if (filter) type = filter, wrap = d3_selection_onFilter;
          function onRemove() {
            var l = this[name2];
            if (l) {
              this.removeEventListener(type, l, l.$);
              delete this[name2];
            }
          }
          function onAdd() {
            var l = wrap(listener, d3_array(arguments));
            onRemove.call(this);
            this.addEventListener(type, this[name2] = l, l.$ = capture);
            l._ = listener;
          }
          function removeAll() {
            var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
            for (var name3 in this) {
              if (match = name3.match(re)) {
                var l = this[name3];
                this.removeEventListener(match[1], l, l.$);
                delete this[name3];
              }
            }
          }
          return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
        }
        var d3_selection_onFilters = d3.map({
          mouseenter: "mouseover",
          mouseleave: "mouseout"
        });
        if (d3_document) {
          d3_selection_onFilters.forEach(function(k) {
            if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
          });
        }
        function d3_selection_onListener(listener, argumentz) {
          return function(e) {
            var o = d3.event;
            d3.event = e;
            argumentz[0] = this.__data__;
            try {
              listener.apply(this, argumentz);
            } finally {
              d3.event = o;
            }
          };
        }
        function d3_selection_onFilter(listener, argumentz) {
          var l = d3_selection_onListener(listener, argumentz);
          return function(e) {
            var target = this, related = e.relatedTarget;
            if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
              l.call(target, e);
            }
          };
        }
        var d3_event_dragSelect, d3_event_dragId = 0;
        function d3_event_dragSuppress(node) {
          var name2 = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name2, w = d3.select(d3_window(node)).on("touchmove" + name2, d3_eventPreventDefault).on("dragstart" + name2, d3_eventPreventDefault).on("selectstart" + name2, d3_eventPreventDefault);
          if (d3_event_dragSelect == null) {
            d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
          }
          if (d3_event_dragSelect) {
            var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
            style[d3_event_dragSelect] = "none";
          }
          return function(suppressClick) {
            w.on(name2, null);
            if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
            if (suppressClick) {
              var off = function() {
                w.on(click, null);
              };
              w.on(click, function() {
                d3_eventPreventDefault();
                off();
              }, true);
              setTimeout(off, 0);
            }
          };
        }
        d3.mouse = function(container) {
          return d3_mousePoint(container, d3_eventSource());
        };
        var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
        function d3_mousePoint(container, e) {
          if (e.changedTouches) e = e.changedTouches[0];
          var svg = container.ownerSVGElement || container;
          if (svg.createSVGPoint) {
            var point = svg.createSVGPoint();
            if (d3_mouse_bug44083 < 0) {
              var window2 = d3_window(container);
              if (window2.scrollX || window2.scrollY) {
                svg = d3.select("body").append("svg").style({
                  position: "absolute",
                  top: 0,
                  left: 0,
                  margin: 0,
                  padding: 0,
                  border: "none"
                }, "important");
                var ctm = svg[0][0].getScreenCTM();
                d3_mouse_bug44083 = !(ctm.f || ctm.e);
                svg.remove();
              }
            }
            if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY;
            else point.x = e.clientX, point.y = e.clientY;
            point = point.matrixTransform(container.getScreenCTM().inverse());
            return [point.x, point.y];
          }
          var rect = container.getBoundingClientRect();
          return [e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop];
        }
        d3.touch = function(container, touches, identifier) {
          if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
          if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
            if ((touch = touches[i]).identifier === identifier) {
              return d3_mousePoint(container, touch);
            }
          }
        };
        d3.behavior.drag = function() {
          var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
          function drag() {
            this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
          }
          function dragstart(id, position, subject, move, end) {
            return function() {
              var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
              if (origin) {
                dragOffset = origin.apply(that, arguments);
                dragOffset = [dragOffset.x - position0[0], dragOffset.y - position0[1]];
              } else {
                dragOffset = [0, 0];
              }
              dispatch({
                type: "dragstart"
              });
              function moved() {
                var position1 = position(parent, dragId), dx, dy;
                if (!position1) return;
                dx = position1[0] - position0[0];
                dy = position1[1] - position0[1];
                dragged |= dx | dy;
                position0 = position1;
                dispatch({
                  type: "drag",
                  x: position1[0] + dragOffset[0],
                  y: position1[1] + dragOffset[1],
                  dx,
                  dy
                });
              }
              function ended() {
                if (!position(parent, dragId)) return;
                dragSubject.on(move + dragName, null).on(end + dragName, null);
                dragRestore(dragged);
                dispatch({
                  type: "dragend"
                });
              }
            };
          }
          drag.origin = function(x) {
            if (!arguments.length) return origin;
            origin = x;
            return drag;
          };
          return d3.rebind(drag, event, "on");
        };
        function d3_behavior_dragTouchId() {
          return d3.event.changedTouches[0].identifier;
        }
        d3.touches = function(container, touches) {
          if (arguments.length < 2) touches = d3_eventSource().touches;
          return touches ? d3_array(touches).map(function(touch) {
            var point = d3_mousePoint(container, touch);
            point.identifier = touch.identifier;
            return point;
          }) : [];
        };
        var \u03B5 = 1e-6, \u03B52 = \u03B5 * \u03B5, \u03C0 = Math.PI, \u03C4 = 2 * \u03C0, \u03C4\u03B5 = \u03C4 - \u03B5, half\u03C0 = \u03C0 / 2, d3_radians = \u03C0 / 180, d3_degrees = 180 / \u03C0;
        function d3_sgn(x) {
          return x > 0 ? 1 : x < 0 ? -1 : 0;
        }
        function d3_cross2d(a, b, c) {
          return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
        }
        function d3_acos(x) {
          return x > 1 ? 0 : x < -1 ? \u03C0 : Math.acos(x);
        }
        function d3_asin(x) {
          return x > 1 ? half\u03C0 : x < -1 ? -half\u03C0 : Math.asin(x);
        }
        function d3_sinh(x) {
          return ((x = Math.exp(x)) - 1 / x) / 2;
        }
        function d3_cosh(x) {
          return ((x = Math.exp(x)) + 1 / x) / 2;
        }
        function d3_tanh(x) {
          return ((x = Math.exp(2 * x)) - 1) / (x + 1);
        }
        function d3_haversin(x) {
          return (x = Math.sin(x / 2)) * x;
        }
        var \u03C1 = Math.SQRT2, \u03C12 = 2, \u03C14 = 4;
        d3.interpolateZoom = function(p0, p1) {
          var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
          if (d2 < \u03B52) {
            S = Math.log(w1 / w0) / \u03C1;
            i = function(t) {
              return [ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(\u03C1 * t * S)];
            };
          } else {
            var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + \u03C14 * d2) / (2 * w0 * \u03C12 * d1), b1 = (w1 * w1 - w0 * w0 - \u03C14 * d2) / (2 * w1 * \u03C12 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
            S = (r1 - r0) / \u03C1;
            i = function(t) {
              var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (\u03C12 * d1) * (coshr0 * d3_tanh(\u03C1 * s + r0) - d3_sinh(r0));
              return [ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(\u03C1 * s + r0)];
            };
          }
          i.duration = S * 1e3;
          return i;
        };
        d3.behavior.zoom = function() {
          var view = {
            x: 0,
            y: 0,
            k: 1
          }, translate0, center0, center, size = [960, 500], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
          if (!d3_behavior_zoomWheel) {
            d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
              return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
            }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
              return d3.event.wheelDelta;
            }, "mousewheel") : (d3_behavior_zoomDelta = function() {
              return -d3.event.detail;
            }, "MozMousePixelScroll");
          }
          function zoom(g) {
            g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
          }
          zoom.event = function(g) {
            g.each(function() {
              var dispatch = event.of(this, arguments), view1 = view;
              if (d3_transitionInheritId) {
                d3.select(this).transition().each("start.zoom", function() {
                  view = this.__chart__ || {
                    x: 0,
                    y: 0,
                    k: 1
                  };
                  zoomstarted(dispatch);
                }).tween("zoom:zoom", function() {
                  var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([(cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k], [(cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k]);
                  return function(t) {
                    var l = i(t), k = dx / l[2];
                    this.__chart__ = view = {
                      x: cx - l[0] * k,
                      y: cy - l[1] * k,
                      k
                    };
                    zoomed(dispatch);
                  };
                }).each("interrupt.zoom", function() {
                  zoomended(dispatch);
                }).each("end.zoom", function() {
                  zoomended(dispatch);
                });
              } else {
                this.__chart__ = view;
                zoomstarted(dispatch);
                zoomed(dispatch);
                zoomended(dispatch);
              }
            });
          };
          zoom.translate = function(_) {
            if (!arguments.length) return [view.x, view.y];
            view = {
              x: +_[0],
              y: +_[1],
              k: view.k
            };
            rescale();
            return zoom;
          };
          zoom.scale = function(_) {
            if (!arguments.length) return view.k;
            view = {
              x: view.x,
              y: view.y,
              k: null
            };
            scaleTo(+_);
            rescale();
            return zoom;
          };
          zoom.scaleExtent = function(_) {
            if (!arguments.length) return scaleExtent;
            scaleExtent = _ == null ? d3_behavior_zoomInfinity : [+_[0], +_[1]];
            return zoom;
          };
          zoom.center = function(_) {
            if (!arguments.length) return center;
            center = _ && [+_[0], +_[1]];
            return zoom;
          };
          zoom.size = function(_) {
            if (!arguments.length) return size;
            size = _ && [+_[0], +_[1]];
            return zoom;
          };
          zoom.duration = function(_) {
            if (!arguments.length) return duration;
            duration = +_;
            return zoom;
          };
          zoom.x = function(z) {
            if (!arguments.length) return x1;
            x1 = z;
            x0 = z.copy();
            view = {
              x: 0,
              y: 0,
              k: 1
            };
            return zoom;
          };
          zoom.y = function(z) {
            if (!arguments.length) return y1;
            y1 = z;
            y0 = z.copy();
            view = {
              x: 0,
              y: 0,
              k: 1
            };
            return zoom;
          };
          function location2(p) {
            return [(p[0] - view.x) / view.k, (p[1] - view.y) / view.k];
          }
          function point(l) {
            return [l[0] * view.k + view.x, l[1] * view.k + view.y];
          }
          function scaleTo(s) {
            view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
          }
          function translateTo(p, l) {
            l = point(l);
            view.x += p[0] - l[0];
            view.y += p[1] - l[1];
          }
          function zoomTo(that, p, l, k) {
            that.__chart__ = {
              x: view.x,
              y: view.y,
              k: view.k
            };
            scaleTo(Math.pow(2, k));
            translateTo(center0 = p, l);
            that = d3.select(that);
            if (duration > 0) that = that.transition().duration(duration);
            that.call(zoom.event);
          }
          function rescale() {
            if (x1) x1.domain(x0.range().map(function(x) {
              return (x - view.x) / view.k;
            }).map(x0.invert));
            if (y1) y1.domain(y0.range().map(function(y) {
              return (y - view.y) / view.k;
            }).map(y0.invert));
          }
          function zoomstarted(dispatch) {
            if (!zooming++) dispatch({
              type: "zoomstart"
            });
          }
          function zoomed(dispatch) {
            rescale();
            dispatch({
              type: "zoom",
              scale: view.k,
              translate: [view.x, view.y]
            });
          }
          function zoomended(dispatch) {
            if (!--zooming) dispatch({
              type: "zoomend"
            }), center0 = null;
          }
          function mousedowned() {
            var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location2(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
            d3_selection_interrupt.call(that);
            zoomstarted(dispatch);
            function moved() {
              dragged = 1;
              translateTo(d3.mouse(that), location0);
              zoomed(dispatch);
            }
            function ended() {
              subject.on(mousemove, null).on(mouseup, null);
              dragRestore(dragged);
              zoomended(dispatch);
            }
          }
          function touchstarted() {
            var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
            started();
            zoomstarted(dispatch);
            subject.on(mousedown, null).on(touchstart, started);
            function relocate() {
              var touches = d3.touches(that);
              scale0 = view.k;
              touches.forEach(function(t) {
                if (t.identifier in locations0) locations0[t.identifier] = location2(t);
              });
              return touches;
            }
            function started() {
              var target = d3.event.target;
              d3.select(target).on(touchmove, moved).on(touchend, ended);
              targets.push(target);
              var changed = d3.event.changedTouches;
              for (var i = 0, n = changed.length; i < n; ++i) {
                locations0[changed[i].identifier] = null;
              }
              var touches = relocate(), now = Date.now();
              if (touches.length === 1) {
                if (now - touchtime < 500) {
                  var p = touches[0];
                  zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
                  d3_eventPreventDefault();
                }
                touchtime = now;
              } else if (touches.length > 1) {
                var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
                distance0 = dx * dx + dy * dy;
              }
            }
            function moved() {
              var touches = d3.touches(that), p0, l0, p1, l1;
              d3_selection_interrupt.call(that);
              for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
                p1 = touches[i];
                if (l1 = locations0[p1.identifier]) {
                  if (l0) break;
                  p0 = p1, l0 = l1;
                }
              }
              if (l1) {
                var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
                p0 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
                l0 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];
                scaleTo(scale1 * scale0);
              }
              touchtime = null;
              translateTo(p0, l0);
              zoomed(dispatch);
            }
            function ended() {
              if (d3.event.touches.length) {
                var changed = d3.event.changedTouches;
                for (var i = 0, n = changed.length; i < n; ++i) {
                  delete locations0[changed[i].identifier];
                }
                for (var identifier in locations0) {
                  return void relocate();
                }
              }
              d3.selectAll(targets).on(zoomName, null);
              subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
              dragRestore();
              zoomended(dispatch);
            }
          }
          function mousewheeled() {
            var dispatch = event.of(this, arguments);
            if (mousewheelTimer) clearTimeout(mousewheelTimer);
            else d3_selection_interrupt.call(this), translate0 = location2(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
            mousewheelTimer = setTimeout(function() {
              mousewheelTimer = null;
              zoomended(dispatch);
            }, 50);
            d3_eventPreventDefault();
            scaleTo(Math.pow(2, d3_behavior_zoomDelta() * 2e-3) * view.k);
            translateTo(center0, translate0);
            zoomed(dispatch);
          }
          function dblclicked() {
            var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
            zoomTo(this, p, location2(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
          }
          return d3.rebind(zoom, event, "on");
        };
        var d3_behavior_zoomInfinity = [0, Infinity], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
        d3.color = d3_color;
        function d3_color() {
        }
        d3_color.prototype.toString = function() {
          return this.rgb() + "";
        };
        d3.hsl = d3_hsl;
        function d3_hsl(h, s, l) {
          return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
        }
        var d3_hslPrototype = d3_hsl.prototype = new d3_color();
        d3_hslPrototype.brighter = function(k) {
          k = Math.pow(0.7, arguments.length ? k : 1);
          return new d3_hsl(this.h, this.s, this.l / k);
        };
        d3_hslPrototype.darker = function(k) {
          k = Math.pow(0.7, arguments.length ? k : 1);
          return new d3_hsl(this.h, this.s, k * this.l);
        };
        d3_hslPrototype.rgb = function() {
          return d3_hsl_rgb(this.h, this.s, this.l);
        };
        function d3_hsl_rgb(h, s, l) {
          var m1, m2;
          h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
          s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
          l = l < 0 ? 0 : l > 1 ? 1 : l;
          m2 = l <= 0.5 ? l * (1 + s) : l + s - l * s;
          m1 = 2 * l - m2;
          function v(h2) {
            if (h2 > 360) h2 -= 360;
            else if (h2 < 0) h2 += 360;
            if (h2 < 60) return m1 + (m2 - m1) * h2 / 60;
            if (h2 < 180) return m2;
            if (h2 < 240) return m1 + (m2 - m1) * (240 - h2) / 60;
            return m1;
          }
          function vv(h2) {
            return Math.round(v(h2) * 255);
          }
          return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
        }
        d3.hcl = d3_hcl;
        function d3_hcl(h, c, l) {
          return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
        }
        var d3_hclPrototype = d3_hcl.prototype = new d3_color();
        d3_hclPrototype.brighter = function(k) {
          return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
        };
        d3_hclPrototype.darker = function(k) {
          return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
        };
        d3_hclPrototype.rgb = function() {
          return d3_hcl_lab(this.h, this.c, this.l).rgb();
        };
        function d3_hcl_lab(h, c, l) {
          if (isNaN(h)) h = 0;
          if (isNaN(c)) c = 0;
          return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
        }
        d3.lab = d3_lab;
        function d3_lab(l, a, b) {
          return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
        }
        var d3_lab_K = 18;
        var d3_lab_X = 0.95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
        var d3_labPrototype = d3_lab.prototype = new d3_color();
        d3_labPrototype.brighter = function(k) {
          return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
        };
        d3_labPrototype.darker = function(k) {
          return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
        };
        d3_labPrototype.rgb = function() {
          return d3_lab_rgb(this.l, this.a, this.b);
        };
        function d3_lab_rgb(l, a, b) {
          var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
          x = d3_lab_xyz(x) * d3_lab_X;
          y = d3_lab_xyz(y) * d3_lab_Y;
          z = d3_lab_xyz(z) * d3_lab_Z;
          return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), d3_xyz_rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z), d3_xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z));
        }
        function d3_lab_hcl(l, a, b) {
          return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
        }
        function d3_lab_xyz(x) {
          return x > 0.206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
        }
        function d3_xyz_lab(x) {
          return x > 8856e-6 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
        }
        function d3_xyz_rgb(r) {
          return Math.round(255 * (r <= 304e-5 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - 0.055));
        }
        d3.rgb = d3_rgb;
        function d3_rgb(r, g, b) {
          return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
        }
        function d3_rgbNumber(value) {
          return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
        }
        function d3_rgbString(value) {
          return d3_rgbNumber(value) + "";
        }
        var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
        d3_rgbPrototype.brighter = function(k) {
          k = Math.pow(0.7, arguments.length ? k : 1);
          var r = this.r, g = this.g, b = this.b, i = 30;
          if (!r && !g && !b) return new d3_rgb(i, i, i);
          if (r && r < i) r = i;
          if (g && g < i) g = i;
          if (b && b < i) b = i;
          return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
        };
        d3_rgbPrototype.darker = function(k) {
          k = Math.pow(0.7, arguments.length ? k : 1);
          return new d3_rgb(k * this.r, k * this.g, k * this.b);
        };
        d3_rgbPrototype.hsl = function() {
          return d3_rgb_hsl(this.r, this.g, this.b);
        };
        d3_rgbPrototype.toString = function() {
          return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
        };
        function d3_rgb_hex(v) {
          return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
        }
        function d3_rgb_parse(format, rgb2, hsl3) {
          var r = 0, g = 0, b = 0, m1, m2, color2;
          m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
          if (m1) {
            m2 = m1[2].split(",");
            switch (m1[1]) {
              case "hsl": {
                return hsl3(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
              }
              case "rgb": {
                return rgb2(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
              }
            }
          }
          if (color2 = d3_rgb_names.get(format)) {
            return rgb2(color2.r, color2.g, color2.b);
          }
          if (format != null && format.charAt(0) === "#" && !isNaN(color2 = parseInt(format.slice(1), 16))) {
            if (format.length === 4) {
              r = (color2 & 3840) >> 4;
              r = r >> 4 | r;
              g = color2 & 240;
              g = g >> 4 | g;
              b = color2 & 15;
              b = b << 4 | b;
            } else if (format.length === 7) {
              r = (color2 & 16711680) >> 16;
              g = (color2 & 65280) >> 8;
              b = color2 & 255;
            }
          }
          return rgb2(r, g, b);
        }
        function d3_rgb_hsl(r, g, b) {
          var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
          if (d) {
            s = l < 0.5 ? d / (max + min) : d / (2 - max - min);
            if (r == max) h = (g - b) / d + (g < b ? 6 : 0);
            else if (g == max) h = (b - r) / d + 2;
            else h = (r - g) / d + 4;
            h *= 60;
          } else {
            h = NaN;
            s = l > 0 && l < 1 ? 0 : h;
          }
          return new d3_hsl(h, s, l);
        }
        function d3_rgb_lab(r, g, b) {
          r = d3_rgb_xyz(r);
          g = d3_rgb_xyz(g);
          b = d3_rgb_xyz(b);
          var x = d3_xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / d3_lab_X), y = d3_xyz_lab((0.2126729 * r + 0.7151522 * g + 0.072175 * b) / d3_lab_Y), z = d3_xyz_lab((0.0193339 * r + 0.119192 * g + 0.9503041 * b) / d3_lab_Z);
          return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
        }
        function d3_rgb_xyz(r) {
          return (r /= 255) <= 0.04045 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4);
        }
        function d3_rgb_parseNumber(c) {
          var f = parseFloat(c);
          return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
        }
        var d3_rgb_names = d3.map({
          aliceblue: 15792383,
          antiquewhite: 16444375,
          aqua: 65535,
          aquamarine: 8388564,
          azure: 15794175,
          beige: 16119260,
          bisque: 16770244,
          black: 0,
          blanchedalmond: 16772045,
          blue: 255,
          blueviolet: 9055202,
          brown: 10824234,
          burlywood: 14596231,
          cadetblue: 6266528,
          chartreuse: 8388352,
          chocolate: 13789470,
          coral: 16744272,
          cornflowerblue: 6591981,
          cornsilk: 16775388,
          crimson: 14423100,
          cyan: 65535,
          darkblue: 139,
          darkcyan: 35723,
          darkgoldenrod: 12092939,
          darkgray: 11119017,
          darkgreen: 25600,
          darkgrey: 11119017,
          darkkhaki: 12433259,
          darkmagenta: 9109643,
          darkolivegreen: 5597999,
          darkorange: 16747520,
          darkorchid: 10040012,
          darkred: 9109504,
          darksalmon: 15308410,
          darkseagreen: 9419919,
          darkslateblue: 4734347,
          darkslategray: 3100495,
          darkslategrey: 3100495,
          darkturquoise: 52945,
          darkviolet: 9699539,
          deeppink: 16716947,
          deepskyblue: 49151,
          dimgray: 6908265,
          dimgrey: 6908265,
          dodgerblue: 2003199,
          firebrick: 11674146,
          floralwhite: 16775920,
          forestgreen: 2263842,
          fuchsia: 16711935,
          gainsboro: 14474460,
          ghostwhite: 16316671,
          gold: 16766720,
          goldenrod: 14329120,
          gray: 8421504,
          green: 32768,
          greenyellow: 11403055,
          grey: 8421504,
          honeydew: 15794160,
          hotpink: 16738740,
          indianred: 13458524,
          indigo: 4915330,
          ivory: 16777200,
          khaki: 15787660,
          lavender: 15132410,
          lavenderblush: 16773365,
          lawngreen: 8190976,
          lemonchiffon: 16775885,
          lightblue: 11393254,
          lightcoral: 15761536,
          lightcyan: 14745599,
          lightgoldenrodyellow: 16448210,
          lightgray: 13882323,
          lightgreen: 9498256,
          lightgrey: 13882323,
          lightpink: 16758465,
          lightsalmon: 16752762,
          lightseagreen: 2142890,
          lightskyblue: 8900346,
          lightslategray: 7833753,
          lightslategrey: 7833753,
          lightsteelblue: 11584734,
          lightyellow: 16777184,
          lime: 65280,
          limegreen: 3329330,
          linen: 16445670,
          magenta: 16711935,
          maroon: 8388608,
          mediumaquamarine: 6737322,
          mediumblue: 205,
          mediumorchid: 12211667,
          mediumpurple: 9662683,
          mediumseagreen: 3978097,
          mediumslateblue: 8087790,
          mediumspringgreen: 64154,
          mediumturquoise: 4772300,
          mediumvioletred: 13047173,
          midnightblue: 1644912,
          mintcream: 16121850,
          mistyrose: 16770273,
          moccasin: 16770229,
          navajowhite: 16768685,
          navy: 128,
          oldlace: 16643558,
          olive: 8421376,
          olivedrab: 7048739,
          orange: 16753920,
          orangered: 16729344,
          orchid: 14315734,
          palegoldenrod: 15657130,
          palegreen: 10025880,
          paleturquoise: 11529966,
          palevioletred: 14381203,
          papayawhip: 16773077,
          peachpuff: 16767673,
          peru: 13468991,
          pink: 16761035,
          plum: 14524637,
          powderblue: 11591910,
          purple: 8388736,
          rebeccapurple: 6697881,
          red: 16711680,
          rosybrown: 12357519,
          royalblue: 4286945,
          saddlebrown: 9127187,
          salmon: 16416882,
          sandybrown: 16032864,
          seagreen: 3050327,
          seashell: 16774638,
          sienna: 10506797,
          silver: 12632256,
          skyblue: 8900331,
          slateblue: 6970061,
          slategray: 7372944,
          slategrey: 7372944,
          snow: 16775930,
          springgreen: 65407,
          steelblue: 4620980,
          tan: 13808780,
          teal: 32896,
          thistle: 14204888,
          tomato: 16737095,
          turquoise: 4251856,
          violet: 15631086,
          wheat: 16113331,
          white: 16777215,
          whitesmoke: 16119285,
          yellow: 16776960,
          yellowgreen: 10145074
        });
        d3_rgb_names.forEach(function(key, value) {
          d3_rgb_names.set(key, d3_rgbNumber(value));
        });
        function d3_functor(v) {
          return typeof v === "function" ? v : function() {
            return v;
          };
        }
        d3.functor = d3_functor;
        d3.xhr = d3_xhrType(d3_identity);
        function d3_xhrType(response) {
          return function(url, mimeType, callback) {
            if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, mimeType = null;
            return d3_xhr(url, mimeType, response, callback);
          };
        }
        function d3_xhr(url, mimeType, response, callback) {
          var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
          if (self.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
          "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
            request.readyState > 3 && respond();
          };
          function respond() {
            var status = request.status, result;
            if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
              try {
                result = response.call(xhr, request);
              } catch (e) {
                dispatch.error.call(xhr, e);
                return;
              }
              dispatch.load.call(xhr, result);
            } else {
              dispatch.error.call(xhr, request);
            }
          }
          request.onprogress = function(event) {
            var o = d3.event;
            d3.event = event;
            try {
              dispatch.progress.call(xhr, request);
            } finally {
              d3.event = o;
            }
          };
          xhr.header = function(name2, value) {
            name2 = (name2 + "").toLowerCase();
            if (arguments.length < 2) return headers[name2];
            if (value == null) delete headers[name2];
            else headers[name2] = value + "";
            return xhr;
          };
          xhr.mimeType = function(value) {
            if (!arguments.length) return mimeType;
            mimeType = value == null ? null : value + "";
            return xhr;
          };
          xhr.responseType = function(value) {
            if (!arguments.length) return responseType;
            responseType = value;
            return xhr;
          };
          xhr.response = function(value) {
            response = value;
            return xhr;
          };
          ["get", "post"].forEach(function(method) {
            xhr[method] = function() {
              return xhr.send.apply(xhr, [method].concat(d3_array(arguments)));
            };
          });
          xhr.send = function(method, data, callback2) {
            if (arguments.length === 2 && typeof data === "function") callback2 = data, data = null;
            request.open(method, url, true);
            if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
            if (request.setRequestHeader) for (var name2 in headers) request.setRequestHeader(name2, headers[name2]);
            if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
            if (responseType != null) request.responseType = responseType;
            if (callback2 != null) xhr.on("error", callback2).on("load", function(request2) {
              callback2(null, request2);
            });
            dispatch.beforesend.call(xhr, request);
            request.send(data == null ? null : data);
            return xhr;
          };
          xhr.abort = function() {
            request.abort();
            return xhr;
          };
          d3.rebind(xhr, dispatch, "on");
          return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
        }
        function d3_xhr_fixCallback(callback) {
          return callback.length === 1 ? function(error, request) {
            callback(error == null ? request : null);
          } : callback;
        }
        function d3_xhrHasResponse(request) {
          var type = request.responseType;
          return type && type !== "text" ? request.response : request.responseText;
        }
        d3.dsv = function(delimiter, mimeType) {
          var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
          function dsv(url, row, callback) {
            if (arguments.length < 3) callback = row, row = null;
            var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
            xhr.row = function(_) {
              return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
            };
            return xhr;
          }
          function response(request) {
            return dsv.parse(request.responseText);
          }
          function typedResponse(f) {
            return function(request) {
              return dsv.parse(request.responseText, f);
            };
          }
          dsv.parse = function(text, f) {
            var o;
            return dsv.parseRows(text, function(row, i) {
              if (o) return o(row, i - 1);
              var a = function(d) {
                var obj = {};
                var len = row.length;
                for (var k = 0; k < len; ++k) {
                  obj[row[k]] = d[k];
                }
                return obj;
              };
              o = f ? function(row2, i2) {
                return f(a(row2), i2);
              } : a;
            });
          };
          dsv.parseRows = function(text, f) {
            var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
            function token() {
              if (I >= N) return EOF;
              if (eol) return eol = false, EOL;
              var j = I;
              if (text.charCodeAt(j) === 34) {
                var i = j;
                while (i++ < N) {
                  if (text.charCodeAt(i) === 34) {
                    if (text.charCodeAt(i + 1) !== 34) break;
                    ++i;
                  }
                }
                I = i + 2;
                var c = text.charCodeAt(i + 1);
                if (c === 13) {
                  eol = true;
                  if (text.charCodeAt(i + 2) === 10) ++I;
                } else if (c === 10) {
                  eol = true;
                }
                return text.slice(j + 1, i).replace(/""/g, '"');
              }
              while (I < N) {
                var c = text.charCodeAt(I++), k = 1;
                if (c === 10) eol = true;
                else if (c === 13) {
                  eol = true;
                  if (text.charCodeAt(I) === 10) ++I, ++k;
                } else if (c !== delimiterCode) continue;
                return text.slice(j, I - k);
              }
              return text.slice(j);
            }
            while ((t = token()) !== EOF) {
              var a = [];
              while (t !== EOL && t !== EOF) {
                a.push(t);
                t = token();
              }
              if (f && (a = f(a, n++)) == null) continue;
              rows.push(a);
            }
            return rows;
          };
          dsv.format = function(rows) {
            if (Array.isArray(rows[0])) return dsv.formatRows(rows);
            var fieldSet = new d3_Set(), fields = [];
            rows.forEach(function(row) {
              for (var field in row) {
                if (!fieldSet.has(field)) {
                  fields.push(fieldSet.add(field));
                }
              }
            });
            return [fields.map(formatValue).join(delimiter)].concat(rows.map(function(row) {
              return fields.map(function(field) {
                return formatValue(row[field]);
              }).join(delimiter);
            })).join("\n");
          };
          dsv.formatRows = function(rows) {
            return rows.map(formatRow).join("\n");
          };
          function formatRow(row) {
            return row.map(formatValue).join(delimiter);
          }
          function formatValue(text) {
            return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
          }
          return dsv;
        };
        d3.csv = d3.dsv(",", "text/csv");
        d3.tsv = d3.dsv("	", "text/tab-separated-values");
        var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
          setTimeout(callback, 17);
        };
        d3.timer = function() {
          d3_timer.apply(this, arguments);
        };
        function d3_timer(callback, delay, then) {
          var n = arguments.length;
          if (n < 2) delay = 0;
          if (n < 3) then = Date.now();
          var time = then + delay, timer = {
            c: callback,
            t: time,
            n: null
          };
          if (d3_timer_queueTail) d3_timer_queueTail.n = timer;
          else d3_timer_queueHead = timer;
          d3_timer_queueTail = timer;
          if (!d3_timer_interval) {
            d3_timer_timeout = clearTimeout(d3_timer_timeout);
            d3_timer_interval = 1;
            d3_timer_frame(d3_timer_step);
          }
          return timer;
        }
        function d3_timer_step() {
          var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
          if (delay > 24) {
            if (isFinite(delay)) {
              clearTimeout(d3_timer_timeout);
              d3_timer_timeout = setTimeout(d3_timer_step, delay);
            }
            d3_timer_interval = 0;
          } else {
            d3_timer_interval = 1;
            d3_timer_frame(d3_timer_step);
          }
        }
        d3.timer.flush = function() {
          d3_timer_mark();
          d3_timer_sweep();
        };
        function d3_timer_mark() {
          var now = Date.now(), timer = d3_timer_queueHead;
          while (timer) {
            if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
            timer = timer.n;
          }
          return now;
        }
        function d3_timer_sweep() {
          var t02, t12 = d3_timer_queueHead, time = Infinity;
          while (t12) {
            if (t12.c) {
              if (t12.t < time) time = t12.t;
              t12 = (t02 = t12).n;
            } else {
              t12 = t02 ? t02.n = t12.n : d3_timer_queueHead = t12.n;
            }
          }
          d3_timer_queueTail = t02;
          return time;
        }
        d3.round = function(x, n) {
          return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
        };
        d3.geom = {};
        function d3_geom_pointX(d) {
          return d[0];
        }
        function d3_geom_pointY(d) {
          return d[1];
        }
        d3.geom.hull = function(vertices) {
          var x = d3_geom_pointX, y = d3_geom_pointY;
          if (arguments.length) return hull(vertices);
          function hull(data) {
            if (data.length < 3) return [];
            var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
            for (i = 0; i < n; i++) {
              points.push([+fx.call(this, data[i], i), +fy.call(this, data[i], i), i]);
            }
            points.sort(d3_geom_hullOrder);
            for (i = 0; i < n; i++) flippedPoints.push([points[i][0], -points[i][1]]);
            var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
            var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
            for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
            for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
            return polygon;
          }
          hull.x = function(_) {
            return arguments.length ? (x = _, hull) : x;
          };
          hull.y = function(_) {
            return arguments.length ? (y = _, hull) : y;
          };
          return hull;
        };
        function d3_geom_hullUpper(points) {
          var n = points.length, hull = [0, 1], hs = 2;
          for (var i = 2; i < n; i++) {
            while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
            hull[hs++] = i;
          }
          return hull.slice(0, hs);
        }
        function d3_geom_hullOrder(a, b) {
          return a[0] - b[0] || a[1] - b[1];
        }
        d3.geom.polygon = function(coordinates) {
          d3_subclass(coordinates, d3_geom_polygonPrototype);
          return coordinates;
        };
        var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
        d3_geom_polygonPrototype.area = function() {
          var i = -1, n = this.length, a, b = this[n - 1], area = 0;
          while (++i < n) {
            a = b;
            b = this[i];
            area += a[1] * b[0] - a[0] * b[1];
          }
          return area * 0.5;
        };
        d3_geom_polygonPrototype.centroid = function(k) {
          var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
          if (!arguments.length) k = -1 / (6 * this.area());
          while (++i < n) {
            a = b;
            b = this[i];
            c = a[0] * b[1] - b[0] * a[1];
            x += (a[0] + b[0]) * c;
            y += (a[1] + b[1]) * c;
          }
          return [x * k, y * k];
        };
        d3_geom_polygonPrototype.clip = function(subject) {
          var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
          while (++i < n) {
            input = subject.slice();
            subject.length = 0;
            b = this[i];
            c = input[(m = input.length - closed) - 1];
            j = -1;
            while (++j < m) {
              d = input[j];
              if (d3_geom_polygonInside(d, a, b)) {
                if (!d3_geom_polygonInside(c, a, b)) {
                  subject.push(d3_geom_polygonIntersect(c, d, a, b));
                }
                subject.push(d);
              } else if (d3_geom_polygonInside(c, a, b)) {
                subject.push(d3_geom_polygonIntersect(c, d, a, b));
              }
              c = d;
            }
            if (closed) subject.push(subject[0]);
            a = b;
          }
          return subject;
        };
        function d3_geom_polygonInside(p, a, b) {
          return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
        }
        function d3_geom_polygonIntersect(c, d, a, b) {
          var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
          return [x1 + ua * x21, y1 + ua * y21];
        }
        function d3_geom_polygonClosed(coordinates) {
          var a = coordinates[0], b = coordinates[coordinates.length - 1];
          return !(a[0] - b[0] || a[1] - b[1]);
        }
        var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
        function d3_geom_voronoiBeach() {
          d3_geom_voronoiRedBlackNode(this);
          this.edge = this.site = this.circle = null;
        }
        function d3_geom_voronoiCreateBeach(site) {
          var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
          beach.site = site;
          return beach;
        }
        function d3_geom_voronoiDetachBeach(beach) {
          d3_geom_voronoiDetachCircle(beach);
          d3_geom_voronoiBeaches.remove(beach);
          d3_geom_voronoiBeachPool.push(beach);
          d3_geom_voronoiRedBlackNode(beach);
        }
        function d3_geom_voronoiRemoveBeach(beach) {
          var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
            x,
            y
          }, previous = beach.P, next = beach.N, disappearing = [beach];
          d3_geom_voronoiDetachBeach(beach);
          var lArc = previous;
          while (lArc.circle && abs(x - lArc.circle.x) < \u03B5 && abs(y - lArc.circle.cy) < \u03B5) {
            previous = lArc.P;
            disappearing.unshift(lArc);
            d3_geom_voronoiDetachBeach(lArc);
            lArc = previous;
          }
          disappearing.unshift(lArc);
          d3_geom_voronoiDetachCircle(lArc);
          var rArc = next;
          while (rArc.circle && abs(x - rArc.circle.x) < \u03B5 && abs(y - rArc.circle.cy) < \u03B5) {
            next = rArc.N;
            disappearing.push(rArc);
            d3_geom_voronoiDetachBeach(rArc);
            rArc = next;
          }
          disappearing.push(rArc);
          d3_geom_voronoiDetachCircle(rArc);
          var nArcs = disappearing.length, iArc;
          for (iArc = 1; iArc < nArcs; ++iArc) {
            rArc = disappearing[iArc];
            lArc = disappearing[iArc - 1];
            d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
          }
          lArc = disappearing[0];
          rArc = disappearing[nArcs - 1];
          rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
          d3_geom_voronoiAttachCircle(lArc);
          d3_geom_voronoiAttachCircle(rArc);
        }
        function d3_geom_voronoiAddBeach(site) {
          var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
          while (node) {
            dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
            if (dxl > \u03B5) node = node.L;
            else {
              dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
              if (dxr > \u03B5) {
                if (!node.R) {
                  lArc = node;
                  break;
                }
                node = node.R;
              } else {
                if (dxl > -\u03B5) {
                  lArc = node.P;
                  rArc = node;
                } else if (dxr > -\u03B5) {
                  lArc = node;
                  rArc = node.N;
                } else {
                  lArc = rArc = node;
                }
                break;
              }
            }
          }
          var newArc = d3_geom_voronoiCreateBeach(site);
          d3_geom_voronoiBeaches.insert(lArc, newArc);
          if (!lArc && !rArc) return;
          if (lArc === rArc) {
            d3_geom_voronoiDetachCircle(lArc);
            rArc = d3_geom_voronoiCreateBeach(lArc.site);
            d3_geom_voronoiBeaches.insert(newArc, rArc);
            newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
            d3_geom_voronoiAttachCircle(lArc);
            d3_geom_voronoiAttachCircle(rArc);
            return;
          }
          if (!rArc) {
            newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
            return;
          }
          d3_geom_voronoiDetachCircle(lArc);
          d3_geom_voronoiDetachCircle(rArc);
          var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
            x: (cy * hb - by * hc) / d + ax,
            y: (bx * hc - cx * hb) / d + ay
          };
          d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
          newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
          rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
          d3_geom_voronoiAttachCircle(lArc);
          d3_geom_voronoiAttachCircle(rArc);
        }
        function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
          var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
          if (!pby2) return rfocx;
          var lArc = arc.P;
          if (!lArc) return -Infinity;
          site = lArc.site;
          var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
          if (!plby2) return lfocx;
          var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
          if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
          return (rfocx + lfocx) / 2;
        }
        function d3_geom_voronoiRightBreakPoint(arc, directrix) {
          var rArc = arc.N;
          if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
          var site = arc.site;
          return site.y === directrix ? site.x : Infinity;
        }
        function d3_geom_voronoiCell(site) {
          this.site = site;
          this.edges = [];
        }
        d3_geom_voronoiCell.prototype.prepare = function() {
          var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
          while (iHalfEdge--) {
            edge = halfEdges[iHalfEdge].edge;
            if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
          }
          halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
          return halfEdges.length;
        };
        function d3_geom_voronoiCloseCells(extent) {
          var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
          while (iCell--) {
            cell = cells[iCell];
            if (!cell || !cell.prepare()) continue;
            halfEdges = cell.edges;
            nHalfEdges = halfEdges.length;
            iHalfEdge = 0;
            while (iHalfEdge < nHalfEdges) {
              end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
              start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
              if (abs(x3 - x2) > \u03B5 || abs(y3 - y2) > \u03B5) {
                halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < \u03B5 && y1 - y3 > \u03B5 ? {
                  x: x0,
                  y: abs(x2 - x0) < \u03B5 ? y2 : y1
                } : abs(y3 - y1) < \u03B5 && x1 - x3 > \u03B5 ? {
                  x: abs(y2 - y1) < \u03B5 ? x2 : x1,
                  y: y1
                } : abs(x3 - x1) < \u03B5 && y3 - y0 > \u03B5 ? {
                  x: x1,
                  y: abs(x2 - x1) < \u03B5 ? y2 : y0
                } : abs(y3 - y0) < \u03B5 && x3 - x0 > \u03B5 ? {
                  x: abs(y2 - y0) < \u03B5 ? x2 : x0,
                  y: y0
                } : null), cell.site, null));
                ++nHalfEdges;
              }
            }
          }
        }
        function d3_geom_voronoiHalfEdgeOrder(a, b) {
          return b.angle - a.angle;
        }
        function d3_geom_voronoiCircle() {
          d3_geom_voronoiRedBlackNode(this);
          this.x = this.y = this.arc = this.site = this.cy = null;
        }
        function d3_geom_voronoiAttachCircle(arc) {
          var lArc = arc.P, rArc = arc.N;
          if (!lArc || !rArc) return;
          var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
          if (lSite === rSite) return;
          var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
          var d = 2 * (ax * cy - ay * cx);
          if (d >= -\u03B52) return;
          var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
          var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
          circle.arc = arc;
          circle.site = cSite;
          circle.x = x + bx;
          circle.y = cy + Math.sqrt(x * x + y * y);
          circle.cy = cy;
          arc.circle = circle;
          var before = null, node = d3_geom_voronoiCircles._;
          while (node) {
            if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
              if (node.L) node = node.L;
              else {
                before = node.P;
                break;
              }
            } else {
              if (node.R) node = node.R;
              else {
                before = node;
                break;
              }
            }
          }
          d3_geom_voronoiCircles.insert(before, circle);
          if (!before) d3_geom_voronoiFirstCircle = circle;
        }
        function d3_geom_voronoiDetachCircle(arc) {
          var circle = arc.circle;
          if (circle) {
            if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
            d3_geom_voronoiCircles.remove(circle);
            d3_geom_voronoiCirclePool.push(circle);
            d3_geom_voronoiRedBlackNode(circle);
            arc.circle = null;
          }
        }
        function d3_geom_clipLine(x0, y0, x1, y1) {
          return function(line) {
            var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t02 = 0, t12 = 1, dx = bx - ax, dy = by - ay, r;
            r = x0 - ax;
            if (!dx && r > 0) return;
            r /= dx;
            if (dx < 0) {
              if (r < t02) return;
              if (r < t12) t12 = r;
            } else if (dx > 0) {
              if (r > t12) return;
              if (r > t02) t02 = r;
            }
            r = x1 - ax;
            if (!dx && r < 0) return;
            r /= dx;
            if (dx < 0) {
              if (r > t12) return;
              if (r > t02) t02 = r;
            } else if (dx > 0) {
              if (r < t02) return;
              if (r < t12) t12 = r;
            }
            r = y0 - ay;
            if (!dy && r > 0) return;
            r /= dy;
            if (dy < 0) {
              if (r < t02) return;
              if (r < t12) t12 = r;
            } else if (dy > 0) {
              if (r > t12) return;
              if (r > t02) t02 = r;
            }
            r = y1 - ay;
            if (!dy && r < 0) return;
            r /= dy;
            if (dy < 0) {
              if (r > t12) return;
              if (r > t02) t02 = r;
            } else if (dy > 0) {
              if (r < t02) return;
              if (r < t12) t12 = r;
            }
            if (t02 > 0) line.a = {
              x: ax + t02 * dx,
              y: ay + t02 * dy
            };
            if (t12 < 1) line.b = {
              x: ax + t12 * dx,
              y: ay + t12 * dy
            };
            return line;
          };
        }
        function d3_geom_voronoiClipEdges(extent) {
          var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
          while (i--) {
            e = edges[i];
            if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < \u03B5 && abs(e.a.y - e.b.y) < \u03B5) {
              e.a = e.b = null;
              edges.splice(i, 1);
            }
          }
        }
        function d3_geom_voronoiConnectEdge(edge, extent) {
          var vb = edge.b;
          if (vb) return true;
          var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
          if (ry === ly) {
            if (fx < x0 || fx >= x1) return;
            if (lx > rx) {
              if (!va) va = {
                x: fx,
                y: y0
              };
              else if (va.y >= y1) return;
              vb = {
                x: fx,
                y: y1
              };
            } else {
              if (!va) va = {
                x: fx,
                y: y1
              };
              else if (va.y < y0) return;
              vb = {
                x: fx,
                y: y0
              };
            }
          } else {
            fm = (lx - rx) / (ry - ly);
            fb = fy - fm * fx;
            if (fm < -1 || fm > 1) {
              if (lx > rx) {
                if (!va) va = {
                  x: (y0 - fb) / fm,
                  y: y0
                };
                else if (va.y >= y1) return;
                vb = {
                  x: (y1 - fb) / fm,
                  y: y1
                };
              } else {
                if (!va) va = {
                  x: (y1 - fb) / fm,
                  y: y1
                };
                else if (va.y < y0) return;
                vb = {
                  x: (y0 - fb) / fm,
                  y: y0
                };
              }
            } else {
              if (ly < ry) {
                if (!va) va = {
                  x: x0,
                  y: fm * x0 + fb
                };
                else if (va.x >= x1) return;
                vb = {
                  x: x1,
                  y: fm * x1 + fb
                };
              } else {
                if (!va) va = {
                  x: x1,
                  y: fm * x1 + fb
                };
                else if (va.x < x0) return;
                vb = {
                  x: x0,
                  y: fm * x0 + fb
                };
              }
            }
          }
          edge.a = va;
          edge.b = vb;
          return true;
        }
        function d3_geom_voronoiEdge(lSite, rSite) {
          this.l = lSite;
          this.r = rSite;
          this.a = this.b = null;
        }
        function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
          var edge = new d3_geom_voronoiEdge(lSite, rSite);
          d3_geom_voronoiEdges.push(edge);
          if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
          if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
          d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
          d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
          return edge;
        }
        function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
          var edge = new d3_geom_voronoiEdge(lSite, null);
          edge.a = va;
          edge.b = vb;
          d3_geom_voronoiEdges.push(edge);
          return edge;
        }
        function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
          if (!edge.a && !edge.b) {
            edge.a = vertex;
            edge.l = lSite;
            edge.r = rSite;
          } else if (edge.l === rSite) {
            edge.b = vertex;
          } else {
            edge.a = vertex;
          }
        }
        function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
          var va = edge.a, vb = edge.b;
          this.edge = edge;
          this.site = lSite;
          this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
        }
        d3_geom_voronoiHalfEdge.prototype = {
          start: function() {
            return this.edge.l === this.site ? this.edge.a : this.edge.b;
          },
          end: function() {
            return this.edge.l === this.site ? this.edge.b : this.edge.a;
          }
        };
        function d3_geom_voronoiRedBlackTree() {
          this._ = null;
        }
        function d3_geom_voronoiRedBlackNode(node) {
          node.U = node.C = node.L = node.R = node.P = node.N = null;
        }
        d3_geom_voronoiRedBlackTree.prototype = {
          insert: function(after, node) {
            var parent, grandpa, uncle;
            if (after) {
              node.P = after;
              node.N = after.N;
              if (after.N) after.N.P = node;
              after.N = node;
              if (after.R) {
                after = after.R;
                while (after.L) after = after.L;
                after.L = node;
              } else {
                after.R = node;
              }
              parent = after;
            } else if (this._) {
              after = d3_geom_voronoiRedBlackFirst(this._);
              node.P = null;
              node.N = after;
              after.P = after.L = node;
              parent = after;
            } else {
              node.P = node.N = null;
              this._ = node;
              parent = null;
            }
            node.L = node.R = null;
            node.U = parent;
            node.C = true;
            after = node;
            while (parent && parent.C) {
              grandpa = parent.U;
              if (parent === grandpa.L) {
                uncle = grandpa.R;
                if (uncle && uncle.C) {
                  parent.C = uncle.C = false;
                  grandpa.C = true;
                  after = grandpa;
                } else {
                  if (after === parent.R) {
                    d3_geom_voronoiRedBlackRotateLeft(this, parent);
                    after = parent;
                    parent = after.U;
                  }
                  parent.C = false;
                  grandpa.C = true;
                  d3_geom_voronoiRedBlackRotateRight(this, grandpa);
                }
              } else {
                uncle = grandpa.L;
                if (uncle && uncle.C) {
                  parent.C = uncle.C = false;
                  grandpa.C = true;
                  after = grandpa;
                } else {
                  if (after === parent.L) {
                    d3_geom_voronoiRedBlackRotateRight(this, parent);
                    after = parent;
                    parent = after.U;
                  }
                  parent.C = false;
                  grandpa.C = true;
                  d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
                }
              }
              parent = after.U;
            }
            this._.C = false;
          },
          remove: function(node) {
            if (node.N) node.N.P = node.P;
            if (node.P) node.P.N = node.N;
            node.N = node.P = null;
            var parent = node.U, sibling, left = node.L, right = node.R, next, red;
            if (!left) next = right;
            else if (!right) next = left;
            else next = d3_geom_voronoiRedBlackFirst(right);
            if (parent) {
              if (parent.L === node) parent.L = next;
              else parent.R = next;
            } else {
              this._ = next;
            }
            if (left && right) {
              red = next.C;
              next.C = node.C;
              next.L = left;
              left.U = next;
              if (next !== right) {
                parent = next.U;
                next.U = node.U;
                node = next.R;
                parent.L = node;
                next.R = right;
                right.U = next;
              } else {
                next.U = parent;
                parent = next;
                node = next.R;
              }
            } else {
              red = node.C;
              node = next;
            }
            if (node) node.U = parent;
            if (red) return;
            if (node && node.C) {
              node.C = false;
              return;
            }
            do {
              if (node === this._) break;
              if (node === parent.L) {
                sibling = parent.R;
                if (sibling.C) {
                  sibling.C = false;
                  parent.C = true;
                  d3_geom_voronoiRedBlackRotateLeft(this, parent);
                  sibling = parent.R;
                }
                if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
                  if (!sibling.R || !sibling.R.C) {
                    sibling.L.C = false;
                    sibling.C = true;
                    d3_geom_voronoiRedBlackRotateRight(this, sibling);
                    sibling = parent.R;
                  }
                  sibling.C = parent.C;
                  parent.C = sibling.R.C = false;
                  d3_geom_voronoiRedBlackRotateLeft(this, parent);
                  node = this._;
                  break;
                }
              } else {
                sibling = parent.L;
                if (sibling.C) {
                  sibling.C = false;
                  parent.C = true;
                  d3_geom_voronoiRedBlackRotateRight(this, parent);
                  sibling = parent.L;
                }
                if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
                  if (!sibling.L || !sibling.L.C) {
                    sibling.R.C = false;
                    sibling.C = true;
                    d3_geom_voronoiRedBlackRotateLeft(this, sibling);
                    sibling = parent.L;
                  }
                  sibling.C = parent.C;
                  parent.C = sibling.L.C = false;
                  d3_geom_voronoiRedBlackRotateRight(this, parent);
                  node = this._;
                  break;
                }
              }
              sibling.C = true;
              node = parent;
              parent = parent.U;
            } while (!node.C);
            if (node) node.C = false;
          }
        };
        function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
          var p = node, q = node.R, parent = p.U;
          if (parent) {
            if (parent.L === p) parent.L = q;
            else parent.R = q;
          } else {
            tree._ = q;
          }
          q.U = parent;
          p.U = q;
          p.R = q.L;
          if (p.R) p.R.U = p;
          q.L = p;
        }
        function d3_geom_voronoiRedBlackRotateRight(tree, node) {
          var p = node, q = node.L, parent = p.U;
          if (parent) {
            if (parent.L === p) parent.L = q;
            else parent.R = q;
          } else {
            tree._ = q;
          }
          q.U = parent;
          p.U = q;
          p.L = q.R;
          if (p.L) p.L.U = p;
          q.R = p;
        }
        function d3_geom_voronoiRedBlackFirst(node) {
          while (node.L) node = node.L;
          return node;
        }
        function d3_geom_voronoi(sites, bbox) {
          var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
          d3_geom_voronoiEdges = [];
          d3_geom_voronoiCells = new Array(sites.length);
          d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
          d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
          while (true) {
            circle = d3_geom_voronoiFirstCircle;
            if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
              if (site.x !== x0 || site.y !== y0) {
                d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
                d3_geom_voronoiAddBeach(site);
                x0 = site.x, y0 = site.y;
              }
              site = sites.pop();
            } else if (circle) {
              d3_geom_voronoiRemoveBeach(circle.arc);
            } else {
              break;
            }
          }
          if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
          var diagram = {
            cells: d3_geom_voronoiCells,
            edges: d3_geom_voronoiEdges
          };
          d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
          return diagram;
        }
        function d3_geom_voronoiVertexOrder(a, b) {
          return b.y - a.y || b.x - a.x;
        }
        d3.geom.voronoi = function(points) {
          var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
          if (points) return voronoi(points);
          function voronoi(data) {
            var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
            d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
              var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
                var s = e.start();
                return [s.x, s.y];
              }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [[x0, y1], [x1, y1], [x1, y0], [x0, y0]] : [];
              polygon.point = data[i];
            });
            return polygons;
          }
          function sites(data) {
            return data.map(function(d, i) {
              return {
                x: Math.round(fx(d, i) / \u03B5) * \u03B5,
                y: Math.round(fy(d, i) / \u03B5) * \u03B5,
                i
              };
            });
          }
          voronoi.links = function(data) {
            return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
              return edge.l && edge.r;
            }).map(function(edge) {
              return {
                source: data[edge.l.i],
                target: data[edge.r.i]
              };
            });
          };
          voronoi.triangles = function(data) {
            var triangles = [];
            d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
              var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
              while (++j < m) {
                e0 = e1;
                s0 = s1;
                e1 = edges[j].edge;
                s1 = e1.l === site ? e1.r : e1.l;
                if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
                  triangles.push([data[i], data[s0.i], data[s1.i]]);
                }
              }
            });
            return triangles;
          };
          voronoi.x = function(_) {
            return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
          };
          voronoi.y = function(_) {
            return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
          };
          voronoi.clipExtent = function(_) {
            if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
            clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
            return voronoi;
          };
          voronoi.size = function(_) {
            if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
            return voronoi.clipExtent(_ && [[0, 0], _]);
          };
          return voronoi;
        };
        var d3_geom_voronoiClipExtent = [[-1e6, -1e6], [1e6, 1e6]];
        function d3_geom_voronoiTriangleArea(a, b, c) {
          return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
        }
        d3.geom.delaunay = function(vertices) {
          return d3.geom.voronoi().triangles(vertices);
        };
        d3.geom.quadtree = function(points, x1, y1, x2, y2) {
          var x = d3_geom_pointX, y = d3_geom_pointY, compat;
          if (compat = arguments.length) {
            x = d3_geom_quadtreeCompatX;
            y = d3_geom_quadtreeCompatY;
            if (compat === 3) {
              y2 = y1;
              x2 = x1;
              y1 = x1 = 0;
            }
            return quadtree(points);
          }
          function quadtree(data) {
            var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
            if (x1 != null) {
              x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
            } else {
              x2_ = y2_ = -(x1_ = y1_ = Infinity);
              xs = [], ys = [];
              n = data.length;
              if (compat) for (i = 0; i < n; ++i) {
                d = data[i];
                if (d.x < x1_) x1_ = d.x;
                if (d.y < y1_) y1_ = d.y;
                if (d.x > x2_) x2_ = d.x;
                if (d.y > y2_) y2_ = d.y;
                xs.push(d.x);
                ys.push(d.y);
              }
              else for (i = 0; i < n; ++i) {
                var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
                if (x_ < x1_) x1_ = x_;
                if (y_ < y1_) y1_ = y_;
                if (x_ > x2_) x2_ = x_;
                if (y_ > y2_) y2_ = y_;
                xs.push(x_);
                ys.push(y_);
              }
            }
            var dx = x2_ - x1_, dy = y2_ - y1_;
            if (dx > dy) y2_ = y1_ + dx;
            else x2_ = x1_ + dy;
            function insert(n2, d2, x3, y3, x12, y12, x22, y22) {
              if (isNaN(x3) || isNaN(y3)) return;
              if (n2.leaf) {
                var nx = n2.x, ny = n2.y;
                if (nx != null) {
                  if (abs(nx - x3) + abs(ny - y3) < 0.01) {
                    insertChild(n2, d2, x3, y3, x12, y12, x22, y22);
                  } else {
                    var nPoint = n2.point;
                    n2.x = n2.y = n2.point = null;
                    insertChild(n2, nPoint, nx, ny, x12, y12, x22, y22);
                    insertChild(n2, d2, x3, y3, x12, y12, x22, y22);
                  }
                } else {
                  n2.x = x3, n2.y = y3, n2.point = d2;
                }
              } else {
                insertChild(n2, d2, x3, y3, x12, y12, x22, y22);
              }
            }
            function insertChild(n2, d2, x3, y3, x12, y12, x22, y22) {
              var xm = (x12 + x22) * 0.5, ym = (y12 + y22) * 0.5, right = x3 >= xm, below = y3 >= ym, i2 = below << 1 | right;
              n2.leaf = false;
              n2 = n2.nodes[i2] || (n2.nodes[i2] = d3_geom_quadtreeNode());
              if (right) x12 = xm;
              else x22 = xm;
              if (below) y12 = ym;
              else y22 = ym;
              insert(n2, d2, x3, y3, x12, y12, x22, y22);
            }
            var root = d3_geom_quadtreeNode();
            root.add = function(d2) {
              insert(root, d2, +fx(d2, ++i), +fy(d2, i), x1_, y1_, x2_, y2_);
            };
            root.visit = function(f) {
              d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
            };
            root.find = function(point) {
              return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
            };
            i = -1;
            if (x1 == null) {
              while (++i < n) {
                insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
              }
              --i;
            } else data.forEach(root.add);
            xs = ys = data = d = null;
            return root;
          }
          quadtree.x = function(_) {
            return arguments.length ? (x = _, quadtree) : x;
          };
          quadtree.y = function(_) {
            return arguments.length ? (y = _, quadtree) : y;
          };
          quadtree.extent = function(_) {
            if (!arguments.length) return x1 == null ? null : [[x1, y1], [x2, y2]];
            if (_ == null) x1 = y1 = x2 = y2 = null;
            else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], y2 = +_[1][1];
            return quadtree;
          };
          quadtree.size = function(_) {
            if (!arguments.length) return x1 == null ? null : [x2 - x1, y2 - y1];
            if (_ == null) x1 = y1 = x2 = y2 = null;
            else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
            return quadtree;
          };
          return quadtree;
        };
        function d3_geom_quadtreeCompatX(d) {
          return d.x;
        }
        function d3_geom_quadtreeCompatY(d) {
          return d.y;
        }
        function d3_geom_quadtreeNode() {
          return {
            leaf: true,
            nodes: [],
            point: null,
            x: null,
            y: null
          };
        }
        function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
          if (!f(node, x1, y1, x2, y2)) {
            var sx = (x1 + x2) * 0.5, sy = (y1 + y2) * 0.5, children = node.nodes;
            if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
            if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
            if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
            if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
          }
        }
        function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
          var minDistance2 = Infinity, closestPoint;
          (function find(node, x1, y1, x2, y2) {
            if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
            if (point = node.point) {
              var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
              if (distance2 < minDistance2) {
                var distance = Math.sqrt(minDistance2 = distance2);
                x0 = x - distance, y0 = y - distance;
                x3 = x + distance, y3 = y + distance;
                closestPoint = point;
              }
            }
            var children = node.nodes, xm = (x1 + x2) * 0.5, ym = (y1 + y2) * 0.5, right = x >= xm, below = y >= ym;
            for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
              if (node = children[i & 3]) switch (i & 3) {
                case 0:
                  find(node, x1, y1, xm, ym);
                  break;
                case 1:
                  find(node, xm, y1, x2, ym);
                  break;
                case 2:
                  find(node, x1, ym, xm, y2);
                  break;
                case 3:
                  find(node, xm, ym, x2, y2);
                  break;
              }
            }
          })(root, x0, y0, x3, y3);
          return closestPoint;
        }
        d3.interpolateRgb = d3_interpolateRgb;
        function d3_interpolateRgb(a, b) {
          a = d3.rgb(a);
          b = d3.rgb(b);
          var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
          return function(t) {
            return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
          };
        }
        d3.interpolateObject = d3_interpolateObject;
        function d3_interpolateObject(a, b) {
          var i = {}, c = {}, k;
          for (k in a) {
            if (k in b) {
              i[k] = d3_interpolate(a[k], b[k]);
            } else {
              c[k] = a[k];
            }
          }
          for (k in b) {
            if (!(k in a)) {
              c[k] = b[k];
            }
          }
          return function(t) {
            for (k in i) c[k] = i[k](t);
            return c;
          };
        }
        d3.interpolateNumber = d3_interpolateNumber;
        function d3_interpolateNumber(a, b) {
          a = +a, b = +b;
          return function(t) {
            return a * (1 - t) + b * t;
          };
        }
        d3.interpolateString = d3_interpolateString;
        function d3_interpolateString(a, b) {
          var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
          a = a + "", b = b + "";
          while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
            if ((bs = bm.index) > bi) {
              bs = b.slice(bi, bs);
              if (s[i]) s[i] += bs;
              else s[++i] = bs;
            }
            if ((am = am[0]) === (bm = bm[0])) {
              if (s[i]) s[i] += bm;
              else s[++i] = bm;
            } else {
              s[++i] = null;
              q.push({
                i,
                x: d3_interpolateNumber(am, bm)
              });
            }
            bi = d3_interpolate_numberB.lastIndex;
          }
          if (bi < b.length) {
            bs = b.slice(bi);
            if (s[i]) s[i] += bs;
            else s[++i] = bs;
          }
          return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
            return b(t) + "";
          }) : function() {
            return b;
          } : (b = q.length, function(t) {
            for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t);
            return s.join("");
          });
        }
        var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
        d3.interpolate = d3_interpolate;
        function d3_interpolate(a, b) {
          var i = d3.interpolators.length, f;
          while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
          return f;
        }
        d3.interpolators = [function(a, b) {
          var t = typeof b;
          return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
        }];
        d3.interpolateArray = d3_interpolateArray;
        function d3_interpolateArray(a, b) {
          var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
          for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
          for (; i < na; ++i) c[i] = a[i];
          for (; i < nb; ++i) c[i] = b[i];
          return function(t) {
            for (i = 0; i < n0; ++i) c[i] = x[i](t);
            return c;
          };
        }
        var d3_ease_default = function() {
          return d3_identity;
        };
        var d3_ease = d3.map({
          linear: d3_ease_default,
          poly: d3_ease_poly,
          quad: function() {
            return d3_ease_quad;
          },
          cubic: function() {
            return d3_ease_cubic;
          },
          sin: function() {
            return d3_ease_sin;
          },
          exp: function() {
            return d3_ease_exp;
          },
          circle: function() {
            return d3_ease_circle;
          },
          elastic: d3_ease_elastic,
          back: d3_ease_back,
          bounce: function() {
            return d3_ease_bounce;
          }
        });
        var d3_ease_mode = d3.map({
          "in": d3_identity,
          out: d3_ease_reverse,
          "in-out": d3_ease_reflect,
          "out-in": function(f) {
            return d3_ease_reflect(d3_ease_reverse(f));
          }
        });
        d3.ease = function(name2) {
          var i = name2.indexOf("-"), t = i >= 0 ? name2.slice(0, i) : name2, m = i >= 0 ? name2.slice(i + 1) : "in";
          t = d3_ease.get(t) || d3_ease_default;
          m = d3_ease_mode.get(m) || d3_identity;
          return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
        };
        function d3_ease_clamp(f) {
          return function(t) {
            return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
          };
        }
        function d3_ease_reverse(f) {
          return function(t) {
            return 1 - f(1 - t);
          };
        }
        function d3_ease_reflect(f) {
          return function(t) {
            return 0.5 * (t < 0.5 ? f(2 * t) : 2 - f(2 - 2 * t));
          };
        }
        function d3_ease_quad(t) {
          return t * t;
        }
        function d3_ease_cubic(t) {
          return t * t * t;
        }
        function d3_ease_cubicInOut(t) {
          if (t <= 0) return 0;
          if (t >= 1) return 1;
          var t22 = t * t, t32 = t22 * t;
          return 4 * (t < 0.5 ? t32 : 3 * (t - t22) + t32 - 0.75);
        }
        function d3_ease_poly(e) {
          return function(t) {
            return Math.pow(t, e);
          };
        }
        function d3_ease_sin(t) {
          return 1 - Math.cos(t * half\u03C0);
        }
        function d3_ease_exp(t) {
          return Math.pow(2, 10 * (t - 1));
        }
        function d3_ease_circle(t) {
          return 1 - Math.sqrt(1 - t * t);
        }
        function d3_ease_elastic(a, p) {
          var s;
          if (arguments.length < 2) p = 0.45;
          if (arguments.length) s = p / \u03C4 * Math.asin(1 / a);
          else a = 1, s = p / 4;
          return function(t) {
            return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * \u03C4 / p);
          };
        }
        function d3_ease_back(s) {
          if (!s) s = 1.70158;
          return function(t) {
            return t * t * ((s + 1) * t - s);
          };
        }
        function d3_ease_bounce(t) {
          return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + 0.75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375 : 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375;
        }
        d3.interpolateHcl = d3_interpolateHcl;
        function d3_interpolateHcl(a, b) {
          a = d3.hcl(a);
          b = d3.hcl(b);
          var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
          if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
          if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah;
          else if (bh > 180) bh -= 360;
          else if (bh < -180) bh += 360;
          return function(t) {
            return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
          };
        }
        d3.interpolateHsl = d3_interpolateHsl;
        function d3_interpolateHsl(a, b) {
          a = d3.hsl(a);
          b = d3.hsl(b);
          var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
          if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
          if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah;
          else if (bh > 180) bh -= 360;
          else if (bh < -180) bh += 360;
          return function(t) {
            return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
          };
        }
        d3.interpolateLab = d3_interpolateLab;
        function d3_interpolateLab(a, b) {
          a = d3.lab(a);
          b = d3.lab(b);
          var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
          return function(t) {
            return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
          };
        }
        d3.interpolateRound = d3_interpolateRound;
        function d3_interpolateRound(a, b) {
          b -= a;
          return function(t) {
            return Math.round(a + b * t);
          };
        }
        d3.transform = function(string) {
          var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
          return (d3.transform = function(string2) {
            if (string2 != null) {
              g.setAttribute("transform", string2);
              var t = g.transform.baseVal.consolidate();
            }
            return new d3_transform(t ? t.matrix : d3_transformIdentity);
          })(string);
        };
        function d3_transform(m) {
          var r0 = [m.a, m.b], r1 = [m.c, m.d], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
          if (r0[0] * r1[1] < r1[0] * r0[1]) {
            r0[0] *= -1;
            r0[1] *= -1;
            kx *= -1;
            kz *= -1;
          }
          this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
          this.translate = [m.e, m.f];
          this.scale = [kx, ky];
          this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
        }
        d3_transform.prototype.toString = function() {
          return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
        };
        function d3_transformDot(a, b) {
          return a[0] * b[0] + a[1] * b[1];
        }
        function d3_transformNormalize(a) {
          var k = Math.sqrt(d3_transformDot(a, a));
          if (k) {
            a[0] /= k;
            a[1] /= k;
          }
          return k;
        }
        function d3_transformCombine(a, b, k) {
          a[0] += k * b[0];
          a[1] += k * b[1];
          return a;
        }
        var d3_transformIdentity = {
          a: 1,
          b: 0,
          c: 0,
          d: 1,
          e: 0,
          f: 0
        };
        d3.interpolateTransform = d3_interpolateTransform;
        function d3_interpolateTransformPop(s) {
          return s.length ? s.pop() + "," : "";
        }
        function d3_interpolateTranslate(ta, tb, s, q) {
          if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
            var i = s.push("translate(", null, ",", null, ")");
            q.push({
              i: i - 4,
              x: d3_interpolateNumber(ta[0], tb[0])
            }, {
              i: i - 2,
              x: d3_interpolateNumber(ta[1], tb[1])
            });
          } else if (tb[0] || tb[1]) {
            s.push("translate(" + tb + ")");
          }
        }
        function d3_interpolateRotate(ra, rb, s, q) {
          if (ra !== rb) {
            if (ra - rb > 180) rb += 360;
            else if (rb - ra > 180) ra += 360;
            q.push({
              i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
              x: d3_interpolateNumber(ra, rb)
            });
          } else if (rb) {
            s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
          }
        }
        function d3_interpolateSkew(wa, wb, s, q) {
          if (wa !== wb) {
            q.push({
              i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
              x: d3_interpolateNumber(wa, wb)
            });
          } else if (wb) {
            s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
          }
        }
        function d3_interpolateScale(ka, kb, s, q) {
          if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
            var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
            q.push({
              i: i - 4,
              x: d3_interpolateNumber(ka[0], kb[0])
            }, {
              i: i - 2,
              x: d3_interpolateNumber(ka[1], kb[1])
            });
          } else if (kb[0] !== 1 || kb[1] !== 1) {
            s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
          }
        }
        function d3_interpolateTransform(a, b) {
          var s = [], q = [];
          a = d3.transform(a), b = d3.transform(b);
          d3_interpolateTranslate(a.translate, b.translate, s, q);
          d3_interpolateRotate(a.rotate, b.rotate, s, q);
          d3_interpolateSkew(a.skew, b.skew, s, q);
          d3_interpolateScale(a.scale, b.scale, s, q);
          a = b = null;
          return function(t) {
            var i = -1, n = q.length, o;
            while (++i < n) s[(o = q[i]).i] = o.x(t);
            return s.join("");
          };
        }
        function d3_uninterpolateNumber(a, b) {
          b = (b -= a = +a) || 1 / b;
          return function(x) {
            return (x - a) / b;
          };
        }
        function d3_uninterpolateClamp(a, b) {
          b = (b -= a = +a) || 1 / b;
          return function(x) {
            return Math.max(0, Math.min(1, (x - a) / b));
          };
        }
        d3.layout = {};
        d3.layout.bundle = function() {
          return function(links) {
            var paths = [], i = -1, n = links.length;
            while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
            return paths;
          };
        };
        function d3_layout_bundlePath(link) {
          var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [start];
          while (start !== lca) {
            start = start.parent;
            points.push(start);
          }
          var k = points.length;
          while (end !== lca) {
            points.splice(k, 0, end);
            end = end.parent;
          }
          return points;
        }
        function d3_layout_bundleAncestors(node) {
          var ancestors = [], parent = node.parent;
          while (parent != null) {
            ancestors.push(node);
            node = parent;
            parent = parent.parent;
          }
          ancestors.push(node);
          return ancestors;
        }
        function d3_layout_bundleLeastCommonAncestor(a, b) {
          if (a === b) return a;
          var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
          while (aNode === bNode) {
            sharedNode = aNode;
            aNode = aNodes.pop();
            bNode = bNodes.pop();
          }
          return sharedNode;
        }
        d3.layout.chord = function() {
          var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
          function relayout() {
            var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
            chords = [];
            groups = [];
            k = 0, i = -1;
            while (++i < n) {
              x = 0, j = -1;
              while (++j < n) {
                x += matrix[i][j];
              }
              groupSums.push(x);
              subgroupIndex.push(d3.range(n));
              k += x;
            }
            if (sortGroups) {
              groupIndex.sort(function(a, b) {
                return sortGroups(groupSums[a], groupSums[b]);
              });
            }
            if (sortSubgroups) {
              subgroupIndex.forEach(function(d, i2) {
                d.sort(function(a, b) {
                  return sortSubgroups(matrix[i2][a], matrix[i2][b]);
                });
              });
            }
            k = (\u03C4 - padding * n) / k;
            x = 0, i = -1;
            while (++i < n) {
              x0 = x, j = -1;
              while (++j < n) {
                var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
                subgroups[di + "-" + dj] = {
                  index: di,
                  subindex: dj,
                  startAngle: a0,
                  endAngle: a1,
                  value: v
                };
              }
              groups[di] = {
                index: di,
                startAngle: x0,
                endAngle: x,
                value: groupSums[di]
              };
              x += padding;
            }
            i = -1;
            while (++i < n) {
              j = i - 1;
              while (++j < n) {
                var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
                if (source.value || target.value) {
                  chords.push(source.value < target.value ? {
                    source: target,
                    target: source
                  } : {
                    source,
                    target
                  });
                }
              }
            }
            if (sortChords) resort();
          }
          function resort() {
            chords.sort(function(a, b) {
              return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
            });
          }
          chord.matrix = function(x) {
            if (!arguments.length) return matrix;
            n = (matrix = x) && matrix.length;
            chords = groups = null;
            return chord;
          };
          chord.padding = function(x) {
            if (!arguments.length) return padding;
            padding = x;
            chords = groups = null;
            return chord;
          };
          chord.sortGroups = function(x) {
            if (!arguments.length) return sortGroups;
            sortGroups = x;
            chords = groups = null;
            return chord;
          };
          chord.sortSubgroups = function(x) {
            if (!arguments.length) return sortSubgroups;
            sortSubgroups = x;
            chords = null;
            return chord;
          };
          chord.sortChords = function(x) {
            if (!arguments.length) return sortChords;
            sortChords = x;
            if (chords) resort();
            return chord;
          };
          chord.chords = function() {
            if (!chords) relayout();
            return chords;
          };
          chord.groups = function() {
            if (!groups) relayout();
            return groups;
          };
          return chord;
        };
        d3.layout.force = function() {
          var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [1, 1], drag, alpha, friction = 0.9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = 0.1, theta2 = 0.64, nodes = [], links = [], distances, strengths, charges;
          function repulse(node) {
            return function(quad, x1, _, x2) {
              if (quad.point !== node) {
                var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
                if (dw * dw / theta2 < dn) {
                  if (dn < chargeDistance2) {
                    var k = quad.charge / dn;
                    node.px -= dx * k;
                    node.py -= dy * k;
                  }
                  return true;
                }
                if (quad.point && dn && dn < chargeDistance2) {
                  var k = quad.pointCharge / dn;
                  node.px -= dx * k;
                  node.py -= dy * k;
                }
              }
              return !quad.charge;
            };
          }
          force.tick = function() {
            if ((alpha *= 0.99) < 5e-3) {
              timer = null;
              event.end({
                type: "end",
                alpha: alpha = 0
              });
              return true;
            }
            var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
            for (i = 0; i < m; ++i) {
              o = links[i];
              s = o.source;
              t = o.target;
              x = t.x - s.x;
              y = t.y - s.y;
              if (l = x * x + y * y) {
                l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
                x *= l;
                y *= l;
                t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : 0.5);
                t.y -= y * k;
                s.x += x * (k = 1 - k);
                s.y += y * k;
              }
            }
            if (k = alpha * gravity) {
              x = size[0] / 2;
              y = size[1] / 2;
              i = -1;
              if (k) while (++i < n) {
                o = nodes[i];
                o.x += (x - o.x) * k;
                o.y += (y - o.y) * k;
              }
            }
            if (charge) {
              d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
              i = -1;
              while (++i < n) {
                if (!(o = nodes[i]).fixed) {
                  q.visit(repulse(o));
                }
              }
            }
            i = -1;
            while (++i < n) {
              o = nodes[i];
              if (o.fixed) {
                o.x = o.px;
                o.y = o.py;
              } else {
                o.x -= (o.px - (o.px = o.x)) * friction;
                o.y -= (o.py - (o.py = o.y)) * friction;
              }
            }
            event.tick({
              type: "tick",
              alpha
            });
          };
          force.nodes = function(x) {
            if (!arguments.length) return nodes;
            nodes = x;
            return force;
          };
          force.links = function(x) {
            if (!arguments.length) return links;
            links = x;
            return force;
          };
          force.size = function(x) {
            if (!arguments.length) return size;
            size = x;
            return force;
          };
          force.linkDistance = function(x) {
            if (!arguments.length) return linkDistance;
            linkDistance = typeof x === "function" ? x : +x;
            return force;
          };
          force.distance = force.linkDistance;
          force.linkStrength = function(x) {
            if (!arguments.length) return linkStrength;
            linkStrength = typeof x === "function" ? x : +x;
            return force;
          };
          force.friction = function(x) {
            if (!arguments.length) return friction;
            friction = +x;
            return force;
          };
          force.charge = function(x) {
            if (!arguments.length) return charge;
            charge = typeof x === "function" ? x : +x;
            return force;
          };
          force.chargeDistance = function(x) {
            if (!arguments.length) return Math.sqrt(chargeDistance2);
            chargeDistance2 = x * x;
            return force;
          };
          force.gravity = function(x) {
            if (!arguments.length) return gravity;
            gravity = +x;
            return force;
          };
          force.theta = function(x) {
            if (!arguments.length) return Math.sqrt(theta2);
            theta2 = x * x;
            return force;
          };
          force.alpha = function(x) {
            if (!arguments.length) return alpha;
            x = +x;
            if (alpha) {
              if (x > 0) {
                alpha = x;
              } else {
                timer.c = null, timer.t = NaN, timer = null;
                event.end({
                  type: "end",
                  alpha: alpha = 0
                });
              }
            } else if (x > 0) {
              event.start({
                type: "start",
                alpha: alpha = x
              });
              timer = d3_timer(force.tick);
            }
            return force;
          };
          force.start = function() {
            var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
            for (i = 0; i < n; ++i) {
              (o = nodes[i]).index = i;
              o.weight = 0;
            }
            for (i = 0; i < m; ++i) {
              o = links[i];
              if (typeof o.source == "number") o.source = nodes[o.source];
              if (typeof o.target == "number") o.target = nodes[o.target];
              ++o.source.weight;
              ++o.target.weight;
            }
            for (i = 0; i < n; ++i) {
              o = nodes[i];
              if (isNaN(o.x)) o.x = position("x", w);
              if (isNaN(o.y)) o.y = position("y", h);
              if (isNaN(o.px)) o.px = o.x;
              if (isNaN(o.py)) o.py = o.y;
            }
            distances = [];
            if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i);
            else for (i = 0; i < m; ++i) distances[i] = linkDistance;
            strengths = [];
            if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i);
            else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
            charges = [];
            if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i);
            else for (i = 0; i < n; ++i) charges[i] = charge;
            function position(dimension, size2) {
              if (!neighbors) {
                neighbors = new Array(n);
                for (j = 0; j < n; ++j) {
                  neighbors[j] = [];
                }
                for (j = 0; j < m; ++j) {
                  var o2 = links[j];
                  neighbors[o2.source.index].push(o2.target);
                  neighbors[o2.target.index].push(o2.source);
                }
              }
              var candidates = neighbors[i], j = -1, l = candidates.length, x;
              while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
              return Math.random() * size2;
            }
            return force.resume();
          };
          force.resume = function() {
            return force.alpha(0.1);
          };
          force.stop = function() {
            return force.alpha(0);
          };
          force.drag = function() {
            if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
            if (!arguments.length) return drag;
            this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
          };
          function dragmove(d) {
            d.px = d3.event.x, d.py = d3.event.y;
            force.resume();
          }
          return d3.rebind(force, event, "on");
        };
        function d3_layout_forceDragstart(d) {
          d.fixed |= 2;
        }
        function d3_layout_forceDragend(d) {
          d.fixed &= ~6;
        }
        function d3_layout_forceMouseover(d) {
          d.fixed |= 4;
          d.px = d.x, d.py = d.y;
        }
        function d3_layout_forceMouseout(d) {
          d.fixed &= ~4;
        }
        function d3_layout_forceAccumulate(quad, alpha, charges) {
          var cx = 0, cy = 0;
          quad.charge = 0;
          if (!quad.leaf) {
            var nodes = quad.nodes, n = nodes.length, i = -1, c;
            while (++i < n) {
              c = nodes[i];
              if (c == null) continue;
              d3_layout_forceAccumulate(c, alpha, charges);
              quad.charge += c.charge;
              cx += c.charge * c.cx;
              cy += c.charge * c.cy;
            }
          }
          if (quad.point) {
            if (!quad.leaf) {
              quad.point.x += Math.random() - 0.5;
              quad.point.y += Math.random() - 0.5;
            }
            var k = alpha * charges[quad.point.index];
            quad.charge += quad.pointCharge = k;
            cx += k * quad.point.x;
            cy += k * quad.point.y;
          }
          quad.cx = cx / quad.charge;
          quad.cy = cy / quad.charge;
        }
        var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
        d3.layout.hierarchy = function() {
          var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
          function hierarchy(root) {
            var stack = [root], nodes = [], node;
            root.depth = 0;
            while ((node = stack.pop()) != null) {
              nodes.push(node);
              if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
                var n, childs, child;
                while (--n >= 0) {
                  stack.push(child = childs[n]);
                  child.parent = node;
                  child.depth = node.depth + 1;
                }
                if (value) node.value = 0;
                node.children = childs;
              } else {
                if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
                delete node.children;
              }
            }
            d3_layout_hierarchyVisitAfter(root, function(node2) {
              var childs2, parent;
              if (sort && (childs2 = node2.children)) childs2.sort(sort);
              if (value && (parent = node2.parent)) parent.value += node2.value;
            });
            return nodes;
          }
          hierarchy.sort = function(x) {
            if (!arguments.length) return sort;
            sort = x;
            return hierarchy;
          };
          hierarchy.children = function(x) {
            if (!arguments.length) return children;
            children = x;
            return hierarchy;
          };
          hierarchy.value = function(x) {
            if (!arguments.length) return value;
            value = x;
            return hierarchy;
          };
          hierarchy.revalue = function(root) {
            if (value) {
              d3_layout_hierarchyVisitBefore(root, function(node) {
                if (node.children) node.value = 0;
              });
              d3_layout_hierarchyVisitAfter(root, function(node) {
                var parent;
                if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
                if (parent = node.parent) parent.value += node.value;
              });
            }
            return root;
          };
          return hierarchy;
        };
        function d3_layout_hierarchyRebind(object, hierarchy) {
          d3.rebind(object, hierarchy, "sort", "children", "value");
          object.nodes = object;
          object.links = d3_layout_hierarchyLinks;
          return object;
        }
        function d3_layout_hierarchyVisitBefore(node, callback) {
          var nodes = [node];
          while ((node = nodes.pop()) != null) {
            callback(node);
            if ((children = node.children) && (n = children.length)) {
              var n, children;
              while (--n >= 0) nodes.push(children[n]);
            }
          }
        }
        function d3_layout_hierarchyVisitAfter(node, callback) {
          var nodes = [node], nodes2 = [];
          while ((node = nodes.pop()) != null) {
            nodes2.push(node);
            if ((children = node.children) && (n = children.length)) {
              var i = -1, n, children;
              while (++i < n) nodes.push(children[i]);
            }
          }
          while ((node = nodes2.pop()) != null) {
            callback(node);
          }
        }
        function d3_layout_hierarchyChildren(d) {
          return d.children;
        }
        function d3_layout_hierarchyValue(d) {
          return d.value;
        }
        function d3_layout_hierarchySort(a, b) {
          return b.value - a.value;
        }
        function d3_layout_hierarchyLinks(nodes) {
          return d3.merge(nodes.map(function(parent) {
            return (parent.children || []).map(function(child) {
              return {
                source: parent,
                target: child
              };
            });
          }));
        }
        d3.layout.partition = function() {
          var hierarchy = d3.layout.hierarchy(), size = [1, 1];
          function position(node, x, dx, dy) {
            var children = node.children;
            node.x = x;
            node.y = node.depth * dy;
            node.dx = dx;
            node.dy = dy;
            if (children && (n = children.length)) {
              var i = -1, n, c, d;
              dx = node.value ? dx / node.value : 0;
              while (++i < n) {
                position(c = children[i], x, d = c.value * dx, dy);
                x += d;
              }
            }
          }
          function depth(node) {
            var children = node.children, d = 0;
            if (children && (n = children.length)) {
              var i = -1, n;
              while (++i < n) d = Math.max(d, depth(children[i]));
            }
            return 1 + d;
          }
          function partition(d, i) {
            var nodes = hierarchy.call(this, d, i);
            position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
            return nodes;
          }
          partition.size = function(x) {
            if (!arguments.length) return size;
            size = x;
            return partition;
          };
          return d3_layout_hierarchyRebind(partition, hierarchy);
        };
        d3.layout.pie = function() {
          var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = \u03C4, padAngle = 0;
          function pie(data) {
            var n = data.length, values = data.map(function(d, i) {
              return +value.call(pie, d, i);
            }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
            if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
              return values[j] - values[i];
            } : function(i, j) {
              return sort(data[i], data[j]);
            });
            index.forEach(function(i) {
              arcs[i] = {
                data: data[i],
                value: v = values[i],
                startAngle: a,
                endAngle: a += v * k + pa,
                padAngle: p
              };
            });
            return arcs;
          }
          pie.value = function(_) {
            if (!arguments.length) return value;
            value = _;
            return pie;
          };
          pie.sort = function(_) {
            if (!arguments.length) return sort;
            sort = _;
            return pie;
          };
          pie.startAngle = function(_) {
            if (!arguments.length) return startAngle;
            startAngle = _;
            return pie;
          };
          pie.endAngle = function(_) {
            if (!arguments.length) return endAngle;
            endAngle = _;
            return pie;
          };
          pie.padAngle = function(_) {
            if (!arguments.length) return padAngle;
            padAngle = _;
            return pie;
          };
          return pie;
        };
        var d3_layout_pieSortByValue = {};
        d3.layout.stack = function() {
          var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
          function stack(data, index) {
            if (!(n = data.length)) return data;
            var series = data.map(function(d, i2) {
              return values.call(stack, d, i2);
            });
            var points = series.map(function(d) {
              return d.map(function(v, i2) {
                return [x.call(stack, v, i2), y.call(stack, v, i2)];
              });
            });
            var orders = order.call(stack, points, index);
            series = d3.permute(series, orders);
            points = d3.permute(points, orders);
            var offsets = offset.call(stack, points, index);
            var m = series[0].length, n, i, j, o;
            for (j = 0; j < m; ++j) {
              out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
              for (i = 1; i < n; ++i) {
                out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
              }
            }
            return data;
          }
          stack.values = function(x2) {
            if (!arguments.length) return values;
            values = x2;
            return stack;
          };
          stack.order = function(x2) {
            if (!arguments.length) return order;
            order = typeof x2 === "function" ? x2 : d3_layout_stackOrders.get(x2) || d3_layout_stackOrderDefault;
            return stack;
          };
          stack.offset = function(x2) {
            if (!arguments.length) return offset;
            offset = typeof x2 === "function" ? x2 : d3_layout_stackOffsets.get(x2) || d3_layout_stackOffsetZero;
            return stack;
          };
          stack.x = function(z) {
            if (!arguments.length) return x;
            x = z;
            return stack;
          };
          stack.y = function(z) {
            if (!arguments.length) return y;
            y = z;
            return stack;
          };
          stack.out = function(z) {
            if (!arguments.length) return out;
            out = z;
            return stack;
          };
          return stack;
        };
        function d3_layout_stackX(d) {
          return d.x;
        }
        function d3_layout_stackY(d) {
          return d.y;
        }
        function d3_layout_stackOut(d, y0, y) {
          d.y0 = y0;
          d.y = y;
        }
        var d3_layout_stackOrders = d3.map({
          "inside-out": function(data) {
            var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
              return max[a] - max[b];
            }), top = 0, bottom = 0, tops = [], bottoms = [];
            for (i = 0; i < n; ++i) {
              j = index[i];
              if (top < bottom) {
                top += sums[j];
                tops.push(j);
              } else {
                bottom += sums[j];
                bottoms.push(j);
              }
            }
            return bottoms.reverse().concat(tops);
          },
          reverse: function(data) {
            return d3.range(data.length).reverse();
          },
          "default": d3_layout_stackOrderDefault
        });
        var d3_layout_stackOffsets = d3.map({
          silhouette: function(data) {
            var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
            for (j = 0; j < m; ++j) {
              for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
              if (o > max) max = o;
              sums.push(o);
            }
            for (j = 0; j < m; ++j) {
              y0[j] = (max - sums[j]) / 2;
            }
            return y0;
          },
          wiggle: function(data) {
            var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
            y0[0] = o = o0 = 0;
            for (j = 1; j < m; ++j) {
              for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
              for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
                for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
                  s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
                }
                s2 += s3 * data[i][j][1];
              }
              y0[j] = o -= s1 ? s2 / s1 * dx : 0;
              if (o < o0) o0 = o;
            }
            for (j = 0; j < m; ++j) y0[j] -= o0;
            return y0;
          },
          expand: function(data) {
            var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
            for (j = 0; j < m; ++j) {
              for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
              if (o) for (i = 0; i < n; i++) data[i][j][1] /= o;
              else for (i = 0; i < n; i++) data[i][j][1] = k;
            }
            for (j = 0; j < m; ++j) y0[j] = 0;
            return y0;
          },
          zero: d3_layout_stackOffsetZero
        });
        function d3_layout_stackOrderDefault(data) {
          return d3.range(data.length);
        }
        function d3_layout_stackOffsetZero(data) {
          var j = -1, m = data[0].length, y0 = [];
          while (++j < m) y0[j] = 0;
          return y0;
        }
        function d3_layout_stackMaxIndex(array) {
          var i = 1, j = 0, v = array[0][1], k, n = array.length;
          for (; i < n; ++i) {
            if ((k = array[i][1]) > v) {
              j = i;
              v = k;
            }
          }
          return j;
        }
        function d3_layout_stackReduceSum(d) {
          return d.reduce(d3_layout_stackSum, 0);
        }
        function d3_layout_stackSum(p, d) {
          return p + d[1];
        }
        d3.layout.histogram = function() {
          var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
          function histogram(data, i) {
            var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
            while (++i < m) {
              bin = bins[i] = [];
              bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
              bin.y = 0;
            }
            if (m > 0) {
              i = -1;
              while (++i < n) {
                x = values[i];
                if (x >= range[0] && x <= range[1]) {
                  bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
                  bin.y += k;
                  bin.push(data[i]);
                }
              }
            }
            return bins;
          }
          histogram.value = function(x) {
            if (!arguments.length) return valuer;
            valuer = x;
            return histogram;
          };
          histogram.range = function(x) {
            if (!arguments.length) return ranger;
            ranger = d3_functor(x);
            return histogram;
          };
          histogram.bins = function(x) {
            if (!arguments.length) return binner;
            binner = typeof x === "number" ? function(range) {
              return d3_layout_histogramBinFixed(range, x);
            } : d3_functor(x);
            return histogram;
          };
          histogram.frequency = function(x) {
            if (!arguments.length) return frequency;
            frequency = !!x;
            return histogram;
          };
          return histogram;
        };
        function d3_layout_histogramBinSturges(range, values) {
          return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
        }
        function d3_layout_histogramBinFixed(range, n) {
          var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
          while (++x <= n) f[x] = m * x + b;
          return f;
        }
        function d3_layout_histogramRange(values) {
          return [d3.min(values), d3.max(values)];
        }
        d3.layout.pack = function() {
          var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [1, 1], radius;
          function pack(d, i) {
            var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
              return radius;
            };
            root.x = root.y = 0;
            d3_layout_hierarchyVisitAfter(root, function(d2) {
              d2.r = +r(d2.value);
            });
            d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
            if (padding) {
              var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
              d3_layout_hierarchyVisitAfter(root, function(d2) {
                d2.r += dr;
              });
              d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
              d3_layout_hierarchyVisitAfter(root, function(d2) {
                d2.r -= dr;
              });
            }
            d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
            return nodes;
          }
          pack.size = function(_) {
            if (!arguments.length) return size;
            size = _;
            return pack;
          };
          pack.radius = function(_) {
            if (!arguments.length) return radius;
            radius = _ == null || typeof _ === "function" ? _ : +_;
            return pack;
          };
          pack.padding = function(_) {
            if (!arguments.length) return padding;
            padding = +_;
            return pack;
          };
          return d3_layout_hierarchyRebind(pack, hierarchy);
        };
        function d3_layout_packSort(a, b) {
          return a.value - b.value;
        }
        function d3_layout_packInsert(a, b) {
          var c = a._pack_next;
          a._pack_next = b;
          b._pack_prev = a;
          b._pack_next = c;
          c._pack_prev = b;
        }
        function d3_layout_packSplice(a, b) {
          a._pack_next = b;
          b._pack_prev = a;
        }
        function d3_layout_packIntersects(a, b) {
          var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
          return 0.999 * dr * dr > dx * dx + dy * dy;
        }
        function d3_layout_packSiblings(node) {
          if (!(nodes = node.children) || !(n = nodes.length)) return;
          var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
          function bound(node2) {
            xMin = Math.min(node2.x - node2.r, xMin);
            xMax = Math.max(node2.x + node2.r, xMax);
            yMin = Math.min(node2.y - node2.r, yMin);
            yMax = Math.max(node2.y + node2.r, yMax);
          }
          nodes.forEach(d3_layout_packLink);
          a = nodes[0];
          a.x = -a.r;
          a.y = 0;
          bound(a);
          if (n > 1) {
            b = nodes[1];
            b.x = b.r;
            b.y = 0;
            bound(b);
            if (n > 2) {
              c = nodes[2];
              d3_layout_packPlace(a, b, c);
              bound(c);
              d3_layout_packInsert(a, c);
              a._pack_prev = c;
              d3_layout_packInsert(c, b);
              b = a._pack_next;
              for (i = 3; i < n; i++) {
                d3_layout_packPlace(a, b, c = nodes[i]);
                var isect = 0, s1 = 1, s2 = 1;
                for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
                  if (d3_layout_packIntersects(j, c)) {
                    isect = 1;
                    break;
                  }
                }
                if (isect == 1) {
                  for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
                    if (d3_layout_packIntersects(k, c)) {
                      break;
                    }
                  }
                }
                if (isect) {
                  if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j);
                  else d3_layout_packSplice(a = k, b);
                  i--;
                } else {
                  d3_layout_packInsert(a, c);
                  b = c;
                  bound(c);
                }
              }
            }
          }
          var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
          for (i = 0; i < n; i++) {
            c = nodes[i];
            c.x -= cx;
            c.y -= cy;
            cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
          }
          node.r = cr;
          nodes.forEach(d3_layout_packUnlink);
        }
        function d3_layout_packLink(node) {
          node._pack_next = node._pack_prev = node;
        }
        function d3_layout_packUnlink(node) {
          delete node._pack_next;
          delete node._pack_prev;
        }
        function d3_layout_packTransform(node, x, y, k) {
          var children = node.children;
          node.x = x += k * node.x;
          node.y = y += k * node.y;
          node.r *= k;
          if (children) {
            var i = -1, n = children.length;
            while (++i < n) d3_layout_packTransform(children[i], x, y, k);
          }
        }
        function d3_layout_packPlace(a, b, c) {
          var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
          if (db && (dx || dy)) {
            var da = b.r + c.r, dc = dx * dx + dy * dy;
            da *= da;
            db *= db;
            var x = 0.5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
            c.x = a.x + x * dx + y * dy;
            c.y = a.y + x * dy - y * dx;
          } else {
            c.x = a.x + db;
            c.y = a.y;
          }
        }
        d3.layout.tree = function() {
          var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [1, 1], nodeSize = null;
          function tree(d, i) {
            var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
            d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
            d3_layout_hierarchyVisitBefore(root1, secondWalk);
            if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode);
            else {
              var left = root0, right = root0, bottom = root0;
              d3_layout_hierarchyVisitBefore(root0, function(node) {
                if (node.x < left.x) left = node;
                if (node.x > right.x) right = node;
                if (node.depth > bottom.depth) bottom = node;
              });
              var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
              d3_layout_hierarchyVisitBefore(root0, function(node) {
                node.x = (node.x + tx) * kx;
                node.y = node.depth * ky;
              });
            }
            return nodes;
          }
          function wrapTree(root0) {
            var root1 = {
              A: null,
              children: [root0]
            }, queue = [root1], node1;
            while ((node1 = queue.pop()) != null) {
              for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
                queue.push((children[i] = child = {
                  _: children[i],
                  parent: node1,
                  children: (child = children[i].children) && child.slice() || [],
                  A: null,
                  a: null,
                  z: 0,
                  m: 0,
                  c: 0,
                  s: 0,
                  t: null,
                  i
                }).a = child);
              }
            }
            return root1.children[0];
          }
          function firstWalk(v) {
            var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
            if (children.length) {
              d3_layout_treeShift(v);
              var midpoint = (children[0].z + children[children.length - 1].z) / 2;
              if (w) {
                v.z = w.z + separation(v._, w._);
                v.m = v.z - midpoint;
              } else {
                v.z = midpoint;
              }
            } else if (w) {
              v.z = w.z + separation(v._, w._);
            }
            v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
          }
          function secondWalk(v) {
            v._.x = v.z + v.parent.m;
            v.m += v.parent.m;
          }
          function apportion(v, w, ancestor) {
            if (w) {
              var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
              while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
                vom = d3_layout_treeLeft(vom);
                vop = d3_layout_treeRight(vop);
                vop.a = v;
                shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
                if (shift > 0) {
                  d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
                  sip += shift;
                  sop += shift;
                }
                sim += vim.m;
                sip += vip.m;
                som += vom.m;
                sop += vop.m;
              }
              if (vim && !d3_layout_treeRight(vop)) {
                vop.t = vim;
                vop.m += sim - sop;
              }
              if (vip && !d3_layout_treeLeft(vom)) {
                vom.t = vip;
                vom.m += sip - som;
                ancestor = v;
              }
            }
            return ancestor;
          }
          function sizeNode(node) {
            node.x *= size[0];
            node.y = node.depth * size[1];
          }
          tree.separation = function(x) {
            if (!arguments.length) return separation;
            separation = x;
            return tree;
          };
          tree.size = function(x) {
            if (!arguments.length) return nodeSize ? null : size;
            nodeSize = (size = x) == null ? sizeNode : null;
            return tree;
          };
          tree.nodeSize = function(x) {
            if (!arguments.length) return nodeSize ? size : null;
            nodeSize = (size = x) == null ? null : sizeNode;
            return tree;
          };
          return d3_layout_hierarchyRebind(tree, hierarchy);
        };
        function d3_layout_treeSeparation(a, b) {
          return a.parent == b.parent ? 1 : 2;
        }
        function d3_layout_treeLeft(v) {
          var children = v.children;
          return children.length ? children[0] : v.t;
        }
        function d3_layout_treeRight(v) {
          var children = v.children, n;
          return (n = children.length) ? children[n - 1] : v.t;
        }
        function d3_layout_treeMove(wm, wp, shift) {
          var change = shift / (wp.i - wm.i);
          wp.c -= change;
          wp.s += shift;
          wm.c += change;
          wp.z += shift;
          wp.m += shift;
        }
        function d3_layout_treeShift(v) {
          var shift = 0, change = 0, children = v.children, i = children.length, w;
          while (--i >= 0) {
            w = children[i];
            w.z += shift;
            w.m += shift;
            shift += w.s + (change += w.c);
          }
        }
        function d3_layout_treeAncestor(vim, v, ancestor) {
          return vim.a.parent === v.parent ? vim.a : ancestor;
        }
        d3.layout.cluster = function() {
          var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [1, 1], nodeSize = false;
          function cluster(d, i) {
            var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
            d3_layout_hierarchyVisitAfter(root, function(node) {
              var children = node.children;
              if (children && children.length) {
                node.x = d3_layout_clusterX(children);
                node.y = d3_layout_clusterY(children);
              } else {
                node.x = previousNode ? x += separation(node, previousNode) : 0;
                node.y = 0;
                previousNode = node;
              }
            });
            var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
            d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
              node.x = (node.x - root.x) * size[0];
              node.y = (root.y - node.y) * size[1];
            } : function(node) {
              node.x = (node.x - x0) / (x1 - x0) * size[0];
              node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
            });
            return nodes;
          }
          cluster.separation = function(x) {
            if (!arguments.length) return separation;
            separation = x;
            return cluster;
          };
          cluster.size = function(x) {
            if (!arguments.length) return nodeSize ? null : size;
            nodeSize = (size = x) == null;
            return cluster;
          };
          cluster.nodeSize = function(x) {
            if (!arguments.length) return nodeSize ? size : null;
            nodeSize = (size = x) != null;
            return cluster;
          };
          return d3_layout_hierarchyRebind(cluster, hierarchy);
        };
        function d3_layout_clusterY(children) {
          return 1 + d3.max(children, function(child) {
            return child.y;
          });
        }
        function d3_layout_clusterX(children) {
          return children.reduce(function(x, child) {
            return x + child.x;
          }, 0) / children.length;
        }
        function d3_layout_clusterLeft(node) {
          var children = node.children;
          return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
        }
        function d3_layout_clusterRight(node) {
          var children = node.children, n;
          return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
        }
        d3.layout.treemap = function() {
          var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [1, 1], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = 0.5 * (1 + Math.sqrt(5));
          function scale(children, k) {
            var i = -1, n = children.length, child, area;
            while (++i < n) {
              area = (child = children[i]).value * (k < 0 ? 0 : k);
              child.area = isNaN(area) || area <= 0 ? 0 : area;
            }
          }
          function squarify(node) {
            var children = node.children;
            if (children && children.length) {
              var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
              scale(remaining, rect.dx * rect.dy / node.value);
              row.area = 0;
              while ((n = remaining.length) > 0) {
                row.push(child = remaining[n - 1]);
                row.area += child.area;
                if (mode !== "squarify" || (score = worst(row, u)) <= best) {
                  remaining.pop();
                  best = score;
                } else {
                  row.area -= row.pop().area;
                  position(row, u, rect, false);
                  u = Math.min(rect.dx, rect.dy);
                  row.length = row.area = 0;
                  best = Infinity;
                }
              }
              if (row.length) {
                position(row, u, rect, true);
                row.length = row.area = 0;
              }
              children.forEach(squarify);
            }
          }
          function stickify(node) {
            var children = node.children;
            if (children && children.length) {
              var rect = pad(node), remaining = children.slice(), child, row = [];
              scale(remaining, rect.dx * rect.dy / node.value);
              row.area = 0;
              while (child = remaining.pop()) {
                row.push(child);
                row.area += child.area;
                if (child.z != null) {
                  position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
                  row.length = row.area = 0;
                }
              }
              children.forEach(stickify);
            }
          }
          function worst(row, u) {
            var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
            while (++i < n) {
              if (!(r = row[i].area)) continue;
              if (r < rmin) rmin = r;
              if (r > rmax) rmax = r;
            }
            s *= s;
            u *= u;
            return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
          }
          function position(row, u, rect, flush) {
            var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
            if (u == rect.dx) {
              if (flush || v > rect.dy) v = rect.dy;
              while (++i < n) {
                o = row[i];
                o.x = x;
                o.y = y;
                o.dy = v;
                x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
              }
              o.z = true;
              o.dx += rect.x + rect.dx - x;
              rect.y += v;
              rect.dy -= v;
            } else {
              if (flush || v > rect.dx) v = rect.dx;
              while (++i < n) {
                o = row[i];
                o.x = x;
                o.y = y;
                o.dx = v;
                y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
              }
              o.z = false;
              o.dy += rect.y + rect.dy - y;
              rect.x += v;
              rect.dx -= v;
            }
          }
          function treemap(d) {
            var nodes = stickies || hierarchy(d), root = nodes[0];
            root.x = root.y = 0;
            if (root.value) root.dx = size[0], root.dy = size[1];
            else root.dx = root.dy = 0;
            if (stickies) hierarchy.revalue(root);
            scale([root], root.dx * root.dy / root.value);
            (stickies ? stickify : squarify)(root);
            if (sticky) stickies = nodes;
            return nodes;
          }
          treemap.size = function(x) {
            if (!arguments.length) return size;
            size = x;
            return treemap;
          };
          treemap.padding = function(x) {
            if (!arguments.length) return padding;
            function padFunction(node) {
              var p = x.call(treemap, node, node.depth);
              return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [p, p, p, p] : p);
            }
            function padConstant(node) {
              return d3_layout_treemapPad(node, x);
            }
            var type;
            pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [x, x, x, x], padConstant) : padConstant;
            return treemap;
          };
          treemap.round = function(x) {
            if (!arguments.length) return round != Number;
            round = x ? Math.round : Number;
            return treemap;
          };
          treemap.sticky = function(x) {
            if (!arguments.length) return sticky;
            sticky = x;
            stickies = null;
            return treemap;
          };
          treemap.ratio = function(x) {
            if (!arguments.length) return ratio;
            ratio = x;
            return treemap;
          };
          treemap.mode = function(x) {
            if (!arguments.length) return mode;
            mode = x + "";
            return treemap;
          };
          return d3_layout_hierarchyRebind(treemap, hierarchy);
        };
        function d3_layout_treemapPadNull(node) {
          return {
            x: node.x,
            y: node.y,
            dx: node.dx,
            dy: node.dy
          };
        }
        function d3_layout_treemapPad(node, padding) {
          var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
          if (dx < 0) {
            x += dx / 2;
            dx = 0;
          }
          if (dy < 0) {
            y += dy / 2;
            dy = 0;
          }
          return {
            x,
            y,
            dx,
            dy
          };
        }
        d3.random = {
          normal: function(mu, sigma) {
            var n = arguments.length;
            if (n < 2) sigma = 1;
            if (n < 1) mu = 0;
            return function() {
              var x, y, r;
              do {
                x = Math.random() * 2 - 1;
                y = Math.random() * 2 - 1;
                r = x * x + y * y;
              } while (!r || r > 1);
              return mu + sigma * x * Math.sqrt(-2 * Math.log(r) / r);
            };
          },
          logNormal: function() {
            var random = d3.random.normal.apply(d3, arguments);
            return function() {
              return Math.exp(random());
            };
          },
          bates: function(m) {
            var random = d3.random.irwinHall(m);
            return function() {
              return random() / m;
            };
          },
          irwinHall: function(m) {
            return function() {
              for (var s = 0, j = 0; j < m; j++) s += Math.random();
              return s;
            };
          }
        };
        d3.scale = {};
        function d3_scaleExtent(domain) {
          var start = domain[0], stop = domain[domain.length - 1];
          return start < stop ? [start, stop] : [stop, start];
        }
        function d3_scaleRange(scale) {
          return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
        }
        function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
          var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
          return function(x) {
            return i(u(x));
          };
        }
        function d3_scale_nice(domain, nice) {
          var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
          if (x1 < x0) {
            dx = i0, i0 = i1, i1 = dx;
            dx = x0, x0 = x1, x1 = dx;
          }
          domain[i0] = nice.floor(x0);
          domain[i1] = nice.ceil(x1);
          return domain;
        }
        function d3_scale_niceStep(step) {
          return step ? {
            floor: function(x) {
              return Math.floor(x / step) * step;
            },
            ceil: function(x) {
              return Math.ceil(x / step) * step;
            }
          } : d3_scale_niceIdentity;
        }
        var d3_scale_niceIdentity = {
          floor: d3_identity,
          ceil: d3_identity
        };
        function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
          var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
          if (domain[k] < domain[0]) {
            domain = domain.slice().reverse();
            range = range.slice().reverse();
          }
          while (++j <= k) {
            u.push(uninterpolate(domain[j - 1], domain[j]));
            i.push(interpolate(range[j - 1], range[j]));
          }
          return function(x) {
            var j2 = d3.bisect(domain, x, 1, k) - 1;
            return i[j2](u[j2](x));
          };
        }
        d3.scale.linear = function() {
          return d3_scale_linear([0, 1], [0, 1], d3_interpolate, false);
        };
        function d3_scale_linear(domain, range, interpolate, clamp) {
          var output, input;
          function rescale() {
            var linear2 = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
            output = linear2(domain, range, uninterpolate, interpolate);
            input = linear2(range, domain, uninterpolate, d3_interpolate);
            return scale;
          }
          function scale(x) {
            return output(x);
          }
          scale.invert = function(y) {
            return input(y);
          };
          scale.domain = function(x) {
            if (!arguments.length) return domain;
            domain = x.map(Number);
            return rescale();
          };
          scale.range = function(x) {
            if (!arguments.length) return range;
            range = x;
            return rescale();
          };
          scale.rangeRound = function(x) {
            return scale.range(x).interpolate(d3_interpolateRound);
          };
          scale.clamp = function(x) {
            if (!arguments.length) return clamp;
            clamp = x;
            return rescale();
          };
          scale.interpolate = function(x) {
            if (!arguments.length) return interpolate;
            interpolate = x;
            return rescale();
          };
          scale.ticks = function(m) {
            return d3_scale_linearTicks(domain, m);
          };
          scale.tickFormat = function(m, format) {
            return d3_scale_linearTickFormat(domain, m, format);
          };
          scale.nice = function(m) {
            d3_scale_linearNice(domain, m);
            return rescale();
          };
          scale.copy = function() {
            return d3_scale_linear(domain, range, interpolate, clamp);
          };
          return rescale();
        }
        function d3_scale_linearRebind(scale, linear2) {
          return d3.rebind(scale, linear2, "range", "rangeRound", "interpolate", "clamp");
        }
        function d3_scale_linearNice(domain, m) {
          d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
          d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
          return domain;
        }
        function d3_scale_linearTickRange(domain, m) {
          if (m == null) m = 10;
          var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
          if (err <= 0.15) step *= 10;
          else if (err <= 0.35) step *= 5;
          else if (err <= 0.75) step *= 2;
          extent[0] = Math.ceil(extent[0] / step) * step;
          extent[1] = Math.floor(extent[1] / step) * step + step * 0.5;
          extent[2] = step;
          return extent;
        }
        function d3_scale_linearTicks(domain, m) {
          return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
        }
        var d3_scale_linearFormatSignificant = {
          s: 1,
          g: 1,
          p: 1,
          r: 1,
          e: 1
        };
        function d3_scale_linearPrecision(value) {
          return -Math.floor(Math.log(value) / Math.LN10 + 0.01);
        }
        function d3_scale_linearFormatPrecision(type, range) {
          var p = d3_scale_linearPrecision(range[2]);
          return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
        }
        d3.scale.log = function() {
          return d3_scale_log(d3.scale.linear().domain([0, 1]), 10, true, [1, 10]);
        };
        function d3_scale_log(linear2, base, positive, domain) {
          function log(x) {
            return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
          }
          function pow(x) {
            return positive ? Math.pow(base, x) : -Math.pow(base, -x);
          }
          function scale(x) {
            return linear2(log(x));
          }
          scale.invert = function(x) {
            return pow(linear2.invert(x));
          };
          scale.domain = function(x) {
            if (!arguments.length) return domain;
            positive = x[0] >= 0;
            linear2.domain((domain = x.map(Number)).map(log));
            return scale;
          };
          scale.base = function(_) {
            if (!arguments.length) return base;
            base = +_;
            linear2.domain(domain.map(log));
            return scale;
          };
          scale.nice = function() {
            var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
            linear2.domain(niced);
            domain = niced.map(pow);
            return scale;
          };
          scale.ticks = function() {
            var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
            if (isFinite(j - i)) {
              if (positive) {
                for (; i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
                ticks.push(pow(i));
              } else {
                ticks.push(pow(i));
                for (; i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
              }
              for (i = 0; ticks[i] < u; i++) {
              }
              for (j = ticks.length; ticks[j - 1] > v; j--) {
              }
              ticks = ticks.slice(i, j);
            }
            return ticks;
          };
          scale.copy = function() {
            return d3_scale_log(linear2.copy(), base, positive, domain);
          };
          return d3_scale_linearRebind(scale, linear2);
        }
        var d3_scale_logNiceNegative = {
          floor: function(x) {
            return -Math.ceil(-x);
          },
          ceil: function(x) {
            return -Math.floor(-x);
          }
        };
        d3.scale.pow = function() {
          return d3_scale_pow(d3.scale.linear(), 1, [0, 1]);
        };
        function d3_scale_pow(linear2, exponent, domain) {
          var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
          function scale(x) {
            return linear2(powp(x));
          }
          scale.invert = function(x) {
            return powb(linear2.invert(x));
          };
          scale.domain = function(x) {
            if (!arguments.length) return domain;
            linear2.domain((domain = x.map(Number)).map(powp));
            return scale;
          };
          scale.ticks = function(m) {
            return d3_scale_linearTicks(domain, m);
          };
          scale.tickFormat = function(m, format) {
            return d3_scale_linearTickFormat(domain, m, format);
          };
          scale.nice = function(m) {
            return scale.domain(d3_scale_linearNice(domain, m));
          };
          scale.exponent = function(x) {
            if (!arguments.length) return exponent;
            powp = d3_scale_powPow(exponent = x);
            powb = d3_scale_powPow(1 / exponent);
            linear2.domain(domain.map(powp));
            return scale;
          };
          scale.copy = function() {
            return d3_scale_pow(linear2.copy(), exponent, domain);
          };
          return d3_scale_linearRebind(scale, linear2);
        }
        function d3_scale_powPow(e) {
          return function(x) {
            return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
          };
        }
        d3.scale.sqrt = function() {
          return d3.scale.pow().exponent(0.5);
        };
        d3.scale.ordinal = function() {
          return d3_scale_ordinal([], {
            t: "range",
            a: [[]]
          });
        };
        function d3_scale_ordinal(domain, ranger) {
          var index, range, rangeBand;
          function scale(x) {
            return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
          }
          function steps(start, step) {
            return d3.range(domain.length).map(function(i) {
              return start + step * i;
            });
          }
          scale.domain = function(x) {
            if (!arguments.length) return domain;
            domain = [];
            index = new d3_Map();
            var i = -1, n = x.length, xi;
            while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
            return scale[ranger.t].apply(scale, ranger.a);
          };
          scale.range = function(x) {
            if (!arguments.length) return range;
            range = x;
            rangeBand = 0;
            ranger = {
              t: "range",
              a: arguments
            };
            return scale;
          };
          scale.rangePoints = function(x, padding) {
            if (arguments.length < 2) padding = 0;
            var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain.length - 1 + padding);
            range = steps(start + step * padding / 2, step);
            rangeBand = 0;
            ranger = {
              t: "rangePoints",
              a: arguments
            };
            return scale;
          };
          scale.rangeRoundPoints = function(x, padding) {
            if (arguments.length < 2) padding = 0;
            var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain.length - 1 + padding) | 0;
            range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
            rangeBand = 0;
            ranger = {
              t: "rangeRoundPoints",
              a: arguments
            };
            return scale;
          };
          scale.rangeBands = function(x, padding, outerPadding) {
            if (arguments.length < 2) padding = 0;
            if (arguments.length < 3) outerPadding = padding;
            var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
            range = steps(start + step * outerPadding, step);
            if (reverse) range.reverse();
            rangeBand = step * (1 - padding);
            ranger = {
              t: "rangeBands",
              a: arguments
            };
            return scale;
          };
          scale.rangeRoundBands = function(x, padding, outerPadding) {
            if (arguments.length < 2) padding = 0;
            if (arguments.length < 3) outerPadding = padding;
            var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
            range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
            if (reverse) range.reverse();
            rangeBand = Math.round(step * (1 - padding));
            ranger = {
              t: "rangeRoundBands",
              a: arguments
            };
            return scale;
          };
          scale.rangeBand = function() {
            return rangeBand;
          };
          scale.rangeExtent = function() {
            return d3_scaleExtent(ranger.a[0]);
          };
          scale.copy = function() {
            return d3_scale_ordinal(domain, ranger);
          };
          return scale.domain(domain);
        }
        d3.scale.category10 = function() {
          return d3.scale.ordinal().range(d3_category10);
        };
        d3.scale.category20 = function() {
          return d3.scale.ordinal().range(d3_category20);
        };
        d3.scale.category20b = function() {
          return d3.scale.ordinal().range(d3_category20b);
        };
        d3.scale.category20c = function() {
          return d3.scale.ordinal().range(d3_category20c);
        };
        var d3_category10 = [2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175].map(d3_rgbString);
        var d3_category20 = [2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725].map(d3_rgbString);
        var d3_category20b = [3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654].map(d3_rgbString);
        var d3_category20c = [3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081].map(d3_rgbString);
        d3.scale.quantile = function() {
          return d3_scale_quantile([], []);
        };
        function d3_scale_quantile(domain, range) {
          var thresholds;
          function rescale() {
            var k = 0, q = range.length;
            thresholds = [];
            while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
            return scale;
          }
          function scale(x) {
            if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
          }
          scale.domain = function(x) {
            if (!arguments.length) return domain;
            domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
            return rescale();
          };
          scale.range = function(x) {
            if (!arguments.length) return range;
            range = x;
            return rescale();
          };
          scale.quantiles = function() {
            return thresholds;
          };
          scale.invertExtent = function(y) {
            y = range.indexOf(y);
            return y < 0 ? [NaN, NaN] : [y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1]];
          };
          scale.copy = function() {
            return d3_scale_quantile(domain, range);
          };
          return rescale();
        }
        d3.scale.quantize = function() {
          return d3_scale_quantize(0, 1, [0, 1]);
        };
        function d3_scale_quantize(x0, x1, range) {
          var kx, i;
          function scale(x) {
            return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
          }
          function rescale() {
            kx = range.length / (x1 - x0);
            i = range.length - 1;
            return scale;
          }
          scale.domain = function(x) {
            if (!arguments.length) return [x0, x1];
            x0 = +x[0];
            x1 = +x[x.length - 1];
            return rescale();
          };
          scale.range = function(x) {
            if (!arguments.length) return range;
            range = x;
            return rescale();
          };
          scale.invertExtent = function(y) {
            y = range.indexOf(y);
            y = y < 0 ? NaN : y / kx + x0;
            return [y, y + 1 / kx];
          };
          scale.copy = function() {
            return d3_scale_quantize(x0, x1, range);
          };
          return rescale();
        }
        d3.scale.threshold = function() {
          return d3_scale_threshold([0.5], [0, 1]);
        };
        function d3_scale_threshold(domain, range) {
          function scale(x) {
            if (x <= x) return range[d3.bisect(domain, x)];
          }
          scale.domain = function(_) {
            if (!arguments.length) return domain;
            domain = _;
            return scale;
          };
          scale.range = function(_) {
            if (!arguments.length) return range;
            range = _;
            return scale;
          };
          scale.invertExtent = function(y) {
            y = range.indexOf(y);
            return [domain[y - 1], domain[y]];
          };
          scale.copy = function() {
            return d3_scale_threshold(domain, range);
          };
          return scale;
        }
        d3.scale.identity = function() {
          return d3_scale_identity([0, 1]);
        };
        function d3_scale_identity(domain) {
          function identity2(x) {
            return +x;
          }
          identity2.invert = identity2;
          identity2.domain = identity2.range = function(x) {
            if (!arguments.length) return domain;
            domain = x.map(identity2);
            return identity2;
          };
          identity2.ticks = function(m) {
            return d3_scale_linearTicks(domain, m);
          };
          identity2.tickFormat = function(m, format) {
            return d3_scale_linearTickFormat(domain, m, format);
          };
          identity2.copy = function() {
            return d3_scale_identity(domain);
          };
          return identity2;
        }
        d3.svg = {};
        function d3_zero() {
          return 0;
        }
        d3.svg.arc = function() {
          var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
          function arc() {
            var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - half\u03C0, a1 = endAngle.apply(this, arguments) - half\u03C0, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
            if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
            if (da >= \u03C4\u03B5) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
            var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
            if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
              rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
              if (!cw) p1 *= -1;
              if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
              if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
            }
            if (r1) {
              x0 = r1 * Math.cos(a0 + p1);
              y0 = r1 * Math.sin(a0 + p1);
              x1 = r1 * Math.cos(a1 - p1);
              y1 = r1 * Math.sin(a1 - p1);
              var l1 = Math.abs(a1 - a0 - 2 * p1) <= \u03C0 ? 0 : 1;
              if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
                var h1 = (a0 + a1) / 2;
                x0 = r1 * Math.cos(h1);
                y0 = r1 * Math.sin(h1);
                x1 = y1 = null;
              }
            } else {
              x0 = y0 = 0;
            }
            if (r0) {
              x2 = r0 * Math.cos(a1 - p0);
              y2 = r0 * Math.sin(a1 - p0);
              x3 = r0 * Math.cos(a0 + p0);
              y3 = r0 * Math.sin(a0 + p0);
              var l0 = Math.abs(a0 - a1 + 2 * p0) <= \u03C0 ? 0 : 1;
              if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
                var h0 = (a0 + a1) / 2;
                x2 = r0 * Math.cos(h0);
                y2 = r0 * Math.sin(h0);
                x3 = y3 = null;
              }
            } else {
              x2 = y2 = 0;
            }
            if (da > \u03B5 && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > 1e-3) {
              cr = r0 < r1 ^ cw ? 0 : 1;
              var rc1 = rc, rc0 = rc;
              if (da < \u03C0) {
                var oc = x3 == null ? [x2, y2] : x1 == null ? [x0, y0] : d3_geom_polygonIntersect([x0, y0], [x3, y3], [x1, y1], [x2, y2]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
                rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
                rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
              }
              if (x1 != null) {
                var t30 = d3_svg_arcCornerTangents(x3 == null ? [x2, y2] : [x3, y3], [x0, y0], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([x1, y1], [x2, y2], r1, rc1, cw);
                if (rc === rc1) {
                  path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
                } else {
                  path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
                }
              } else {
                path.push("M", x0, ",", y0);
              }
              if (x3 != null) {
                var t03 = d3_svg_arcCornerTangents([x0, y0], [x3, y3], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([x2, y2], x1 == null ? [x0, y0] : [x1, y1], r0, -rc0, cw);
                if (rc === rc0) {
                  path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
                } else {
                  path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
                }
              } else {
                path.push("L", x2, ",", y2);
              }
            } else {
              path.push("M", x0, ",", y0);
              if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
              path.push("L", x2, ",", y2);
              if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
            }
            path.push("Z");
            return path.join("");
          }
          function circleSegment(r1, cw) {
            return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
          }
          arc.innerRadius = function(v) {
            if (!arguments.length) return innerRadius;
            innerRadius = d3_functor(v);
            return arc;
          };
          arc.outerRadius = function(v) {
            if (!arguments.length) return outerRadius;
            outerRadius = d3_functor(v);
            return arc;
          };
          arc.cornerRadius = function(v) {
            if (!arguments.length) return cornerRadius;
            cornerRadius = d3_functor(v);
            return arc;
          };
          arc.padRadius = function(v) {
            if (!arguments.length) return padRadius;
            padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
            return arc;
          };
          arc.startAngle = function(v) {
            if (!arguments.length) return startAngle;
            startAngle = d3_functor(v);
            return arc;
          };
          arc.endAngle = function(v) {
            if (!arguments.length) return endAngle;
            endAngle = d3_functor(v);
            return arc;
          };
          arc.padAngle = function(v) {
            if (!arguments.length) return padAngle;
            padAngle = d3_functor(v);
            return arc;
          };
          arc.centroid = function() {
            var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - half\u03C0;
            return [Math.cos(a) * r, Math.sin(a) * r];
          };
          return arc;
        };
        var d3_svg_arcAuto = "auto";
        function d3_svg_arcInnerRadius(d) {
          return d.innerRadius;
        }
        function d3_svg_arcOuterRadius(d) {
          return d.outerRadius;
        }
        function d3_svg_arcStartAngle(d) {
          return d.startAngle;
        }
        function d3_svg_arcEndAngle(d) {
          return d.endAngle;
        }
        function d3_svg_arcPadAngle(d) {
          return d && d.padAngle;
        }
        function d3_svg_arcSweep(x0, y0, x1, y1) {
          return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
        }
        function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
          var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D2 = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D2 * D2)), cx0 = (D2 * dy - dx * d) / d2, cy0 = (-D2 * dx - dy * d) / d2, cx1 = (D2 * dy + dx * d) / d2, cy1 = (-D2 * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
          if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
          return [[cx0 - ox, cy0 - oy], [cx0 * r1 / r, cy0 * r1 / r]];
        }
        function d3_true() {
          return true;
        }
        function d3_svg_line(projection) {
          var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = 0.7;
          function line(data) {
            var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
            function segment() {
              segments.push("M", interpolate(projection(points), tension));
            }
            while (++i < n) {
              if (defined.call(this, d = data[i], i)) {
                points.push([+fx.call(this, d, i), +fy.call(this, d, i)]);
              } else if (points.length) {
                segment();
                points = [];
              }
            }
            if (points.length) segment();
            return segments.length ? segments.join("") : null;
          }
          line.x = function(_) {
            if (!arguments.length) return x;
            x = _;
            return line;
          };
          line.y = function(_) {
            if (!arguments.length) return y;
            y = _;
            return line;
          };
          line.defined = function(_) {
            if (!arguments.length) return defined;
            defined = _;
            return line;
          };
          line.interpolate = function(_) {
            if (!arguments.length) return interpolateKey;
            if (typeof _ === "function") interpolateKey = interpolate = _;
            else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
            return line;
          };
          line.tension = function(_) {
            if (!arguments.length) return tension;
            tension = _;
            return line;
          };
          return line;
        }
        d3.svg.line = function() {
          return d3_svg_line(d3_identity);
        };
        var d3_svg_lineInterpolators = d3.map({
          linear: d3_svg_lineLinear,
          "linear-closed": d3_svg_lineLinearClosed,
          step: d3_svg_lineStep,
          "step-before": d3_svg_lineStepBefore,
          "step-after": d3_svg_lineStepAfter,
          basis: d3_svg_lineBasis,
          "basis-open": d3_svg_lineBasisOpen,
          "basis-closed": d3_svg_lineBasisClosed,
          bundle: d3_svg_lineBundle,
          cardinal: d3_svg_lineCardinal,
          "cardinal-open": d3_svg_lineCardinalOpen,
          "cardinal-closed": d3_svg_lineCardinalClosed,
          monotone: d3_svg_lineMonotone
        });
        d3_svg_lineInterpolators.forEach(function(key, value) {
          value.key = key;
          value.closed = /-closed$/.test(key);
        });
        function d3_svg_lineLinear(points) {
          return points.length > 1 ? points.join("L") : points + "Z";
        }
        function d3_svg_lineLinearClosed(points) {
          return points.join("L") + "Z";
        }
        function d3_svg_lineStep(points) {
          var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]];
          while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
          if (n > 1) path.push("H", p[0]);
          return path.join("");
        }
        function d3_svg_lineStepBefore(points) {
          var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]];
          while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
          return path.join("");
        }
        function d3_svg_lineStepAfter(points) {
          var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]];
          while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
          return path.join("");
        }
        function d3_svg_lineCardinalOpen(points, tension) {
          return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
        }
        function d3_svg_lineCardinalClosed(points, tension) {
          return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([points[points.length - 2]].concat(points, [points[1]]), tension));
        }
        function d3_svg_lineCardinal(points, tension) {
          return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
        }
        function d3_svg_lineHermite(points, tangents) {
          if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
            return d3_svg_lineLinear(points);
          }
          var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t02 = tangents[0], t = t02, pi = 1;
          if (quad) {
            path += "Q" + (p[0] - t02[0] * 2 / 3) + "," + (p[1] - t02[1] * 2 / 3) + "," + p[0] + "," + p[1];
            p0 = points[1];
            pi = 2;
          }
          if (tangents.length > 1) {
            t = tangents[1];
            p = points[pi];
            pi++;
            path += "C" + (p0[0] + t02[0]) + "," + (p0[1] + t02[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
            for (var i = 2; i < tangents.length; i++, pi++) {
              p = points[pi];
              t = tangents[i];
              path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
            }
          }
          if (quad) {
            var lp = points[pi];
            path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
          }
          return path;
        }
        function d3_svg_lineCardinalTangents(points, tension) {
          var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
          while (++i < n) {
            p0 = p1;
            p1 = p2;
            p2 = points[i];
            tangents.push([a * (p2[0] - p0[0]), a * (p2[1] - p0[1])]);
          }
          return tangents;
        }
        function d3_svg_lineBasis(points) {
          if (points.length < 3) return d3_svg_lineLinear(points);
          var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [x0, x0, x0, (pi = points[1])[0]], py = [y0, y0, y0, pi[1]], path = [x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)];
          points.push(points[n - 1]);
          while (++i <= n) {
            pi = points[i];
            px.shift();
            px.push(pi[0]);
            py.shift();
            py.push(pi[1]);
            d3_svg_lineBasisBezier(path, px, py);
          }
          points.pop();
          path.push("L", pi);
          return path.join("");
        }
        function d3_svg_lineBasisOpen(points) {
          if (points.length < 4) return d3_svg_lineLinear(points);
          var path = [], i = -1, n = points.length, pi, px = [0], py = [0];
          while (++i < 3) {
            pi = points[i];
            px.push(pi[0]);
            py.push(pi[1]);
          }
          path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
          --i;
          while (++i < n) {
            pi = points[i];
            px.shift();
            px.push(pi[0]);
            py.shift();
            py.push(pi[1]);
            d3_svg_lineBasisBezier(path, px, py);
          }
          return path.join("");
        }
        function d3_svg_lineBasisClosed(points) {
          var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
          while (++i < 4) {
            pi = points[i % n];
            px.push(pi[0]);
            py.push(pi[1]);
          }
          path = [d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)];
          --i;
          while (++i < m) {
            pi = points[i % n];
            px.shift();
            px.push(pi[0]);
            py.shift();
            py.push(pi[1]);
            d3_svg_lineBasisBezier(path, px, py);
          }
          return path.join("");
        }
        function d3_svg_lineBundle(points, tension) {
          var n = points.length - 1;
          if (n) {
            var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
            while (++i <= n) {
              p = points[i];
              t = i / n;
              p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
              p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
            }
          }
          return d3_svg_lineBasis(points);
        }
        function d3_svg_lineDot4(a, b) {
          return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
        }
        var d3_svg_lineBasisBezier1 = [0, 2 / 3, 1 / 3, 0], d3_svg_lineBasisBezier2 = [0, 1 / 3, 2 / 3, 0], d3_svg_lineBasisBezier3 = [0, 1 / 6, 2 / 3, 1 / 6];
        function d3_svg_lineBasisBezier(path, x, y) {
          path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
        }
        function d3_svg_lineSlope(p0, p1) {
          return (p1[1] - p0[1]) / (p1[0] - p0[0]);
        }
        function d3_svg_lineFiniteDifferences(points) {
          var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
          while (++i < j) {
            m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
          }
          m[i] = d;
          return m;
        }
        function d3_svg_lineMonotoneTangents(points) {
          var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
          while (++i < j) {
            d = d3_svg_lineSlope(points[i], points[i + 1]);
            if (abs(d) < \u03B5) {
              m[i] = m[i + 1] = 0;
            } else {
              a = m[i] / d;
              b = m[i + 1] / d;
              s = a * a + b * b;
              if (s > 9) {
                s = d * 3 / Math.sqrt(s);
                m[i] = s * a;
                m[i + 1] = s * b;
              }
            }
          }
          i = -1;
          while (++i <= j) {
            s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
            tangents.push([s || 0, m[i] * s || 0]);
          }
          return tangents;
        }
        function d3_svg_lineMonotone(points) {
          return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
        }
        d3.svg.line.radial = function() {
          var line = d3_svg_line(d3_svg_lineRadial);
          line.radius = line.x, delete line.x;
          line.angle = line.y, delete line.y;
          return line;
        };
        function d3_svg_lineRadial(points) {
          var point, i = -1, n = points.length, r, a;
          while (++i < n) {
            point = points[i];
            r = point[0];
            a = point[1] - half\u03C0;
            point[0] = r * Math.cos(a);
            point[1] = r * Math.sin(a);
          }
          return points;
        }
        function d3_svg_area(projection) {
          var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = 0.7;
          function area(data) {
            var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
              return x;
            } : d3_functor(x1), fy1 = y0 === y1 ? function() {
              return y;
            } : d3_functor(y1), x, y;
            function segment() {
              segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
            }
            while (++i < n) {
              if (defined.call(this, d = data[i], i)) {
                points0.push([x = +fx0.call(this, d, i), y = +fy0.call(this, d, i)]);
                points1.push([+fx1.call(this, d, i), +fy1.call(this, d, i)]);
              } else if (points0.length) {
                segment();
                points0 = [];
                points1 = [];
              }
            }
            if (points0.length) segment();
            return segments.length ? segments.join("") : null;
          }
          area.x = function(_) {
            if (!arguments.length) return x1;
            x0 = x1 = _;
            return area;
          };
          area.x0 = function(_) {
            if (!arguments.length) return x0;
            x0 = _;
            return area;
          };
          area.x1 = function(_) {
            if (!arguments.length) return x1;
            x1 = _;
            return area;
          };
          area.y = function(_) {
            if (!arguments.length) return y1;
            y0 = y1 = _;
            return area;
          };
          area.y0 = function(_) {
            if (!arguments.length) return y0;
            y0 = _;
            return area;
          };
          area.y1 = function(_) {
            if (!arguments.length) return y1;
            y1 = _;
            return area;
          };
          area.defined = function(_) {
            if (!arguments.length) return defined;
            defined = _;
            return area;
          };
          area.interpolate = function(_) {
            if (!arguments.length) return interpolateKey;
            if (typeof _ === "function") interpolateKey = interpolate = _;
            else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
            interpolateReverse = interpolate.reverse || interpolate;
            L = interpolate.closed ? "M" : "L";
            return area;
          };
          area.tension = function(_) {
            if (!arguments.length) return tension;
            tension = _;
            return area;
          };
          return area;
        }
        d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
        d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
        d3.svg.area = function() {
          return d3_svg_area(d3_identity);
        };
        d3.svg.area.radial = function() {
          var area = d3_svg_area(d3_svg_lineRadial);
          area.radius = area.x, delete area.x;
          area.innerRadius = area.x0, delete area.x0;
          area.outerRadius = area.x1, delete area.x1;
          area.angle = area.y, delete area.y;
          area.startAngle = area.y0, delete area.y0;
          area.endAngle = area.y1, delete area.y1;
          return area;
        };
        function d3_source(d) {
          return d.source;
        }
        function d3_target(d) {
          return d.target;
        }
        d3.svg.chord = function() {
          var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
          function chord(d, i) {
            var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
            return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
          }
          function subgroup(self2, f, d, i) {
            var subgroup2 = f.call(self2, d, i), r = radius.call(self2, subgroup2, i), a0 = startAngle.call(self2, subgroup2, i) - half\u03C0, a1 = endAngle.call(self2, subgroup2, i) - half\u03C0;
            return {
              r,
              a0,
              a1,
              p0: [r * Math.cos(a0), r * Math.sin(a0)],
              p1: [r * Math.cos(a1), r * Math.sin(a1)]
            };
          }
          function equals(a, b) {
            return a.a0 == b.a0 && a.a1 == b.a1;
          }
          function arc(r, p, a) {
            return "A" + r + "," + r + " 0 " + +(a > \u03C0) + ",1 " + p;
          }
          function curve(r0, p0, r1, p1) {
            return "Q 0,0 " + p1;
          }
          chord.radius = function(v) {
            if (!arguments.length) return radius;
            radius = d3_functor(v);
            return chord;
          };
          chord.source = function(v) {
            if (!arguments.length) return source;
            source = d3_functor(v);
            return chord;
          };
          chord.target = function(v) {
            if (!arguments.length) return target;
            target = d3_functor(v);
            return chord;
          };
          chord.startAngle = function(v) {
            if (!arguments.length) return startAngle;
            startAngle = d3_functor(v);
            return chord;
          };
          chord.endAngle = function(v) {
            if (!arguments.length) return endAngle;
            endAngle = d3_functor(v);
            return chord;
          };
          return chord;
        };
        function d3_svg_chordRadius(d) {
          return d.radius;
        }
        d3.svg.diagonal = function() {
          var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
          function diagonal(d, i) {
            var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [p0, {
              x: p0.x,
              y: m
            }, {
              x: p3.x,
              y: m
            }, p3];
            p = p.map(projection);
            return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
          }
          diagonal.source = function(x) {
            if (!arguments.length) return source;
            source = d3_functor(x);
            return diagonal;
          };
          diagonal.target = function(x) {
            if (!arguments.length) return target;
            target = d3_functor(x);
            return diagonal;
          };
          diagonal.projection = function(x) {
            if (!arguments.length) return projection;
            projection = x;
            return diagonal;
          };
          return diagonal;
        };
        function d3_svg_diagonalProjection(d) {
          return [d.x, d.y];
        }
        d3.svg.diagonal.radial = function() {
          var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
          diagonal.projection = function(x) {
            return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
          };
          return diagonal;
        };
        function d3_svg_diagonalRadialProjection(projection) {
          return function() {
            var d = projection.apply(this, arguments), r = d[0], a = d[1] - half\u03C0;
            return [r * Math.cos(a), r * Math.sin(a)];
          };
        }
        d3.svg.symbol = function() {
          var type = d3_svg_symbolType, size = d3_svg_symbolSize;
          function symbol(d, i) {
            return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
          }
          symbol.type = function(x) {
            if (!arguments.length) return type;
            type = d3_functor(x);
            return symbol;
          };
          symbol.size = function(x) {
            if (!arguments.length) return size;
            size = d3_functor(x);
            return symbol;
          };
          return symbol;
        };
        function d3_svg_symbolSize() {
          return 64;
        }
        function d3_svg_symbolType() {
          return "circle";
        }
        function d3_svg_symbolCircle(size) {
          var r = Math.sqrt(size / \u03C0);
          return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
        }
        var d3_svg_symbols = d3.map({
          circle: d3_svg_symbolCircle,
          cross: function(size) {
            var r = Math.sqrt(size / 5) / 2;
            return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
          },
          diamond: function(size) {
            var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
            return "M0," + -ry + "L" + rx + ",0 0," + ry + " " + -rx + ",0Z";
          },
          square: function(size) {
            var r = Math.sqrt(size) / 2;
            return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
          },
          "triangle-down": function(size) {
            var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
            return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
          },
          "triangle-up": function(size) {
            var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
            return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
          }
        });
        d3.svg.symbolTypes = d3_svg_symbols.keys();
        var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
        d3_selectionPrototype.transition = function(name2) {
          var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name2), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
            time: Date.now(),
            ease: d3_ease_cubicInOut,
            delay: 0,
            duration: 250
          };
          for (var j = -1, m = this.length; ++j < m; ) {
            subgroups.push(subgroup = []);
            for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
              if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
              subgroup.push(node);
            }
          }
          return d3_transition(subgroups, ns, id);
        };
        d3_selectionPrototype.interrupt = function(name2) {
          return this.each(name2 == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name2)));
        };
        var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
        function d3_selection_interruptNS(ns) {
          return function() {
            var lock, activeId, active;
            if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
              active.timer.c = null;
              active.timer.t = NaN;
              if (--lock.count) delete lock[activeId];
              else delete this[ns];
              lock.active += 0.5;
              active.event && active.event.interrupt.call(this, this.__data__, active.index);
            }
          };
        }
        function d3_transition(groups, ns, id) {
          d3_subclass(groups, d3_transitionPrototype);
          groups.namespace = ns;
          groups.id = id;
          return groups;
        }
        var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
        d3_transitionPrototype.call = d3_selectionPrototype.call;
        d3_transitionPrototype.empty = d3_selectionPrototype.empty;
        d3_transitionPrototype.node = d3_selectionPrototype.node;
        d3_transitionPrototype.size = d3_selectionPrototype.size;
        d3.transition = function(selection, name2) {
          return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name2) : selection : d3.selection().transition(selection);
        };
        d3.transition.prototype = d3_transitionPrototype;
        d3_transitionPrototype.select = function(selector) {
          var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
          selector = d3_selection_selector(selector);
          for (var j = -1, m = this.length; ++j < m; ) {
            subgroups.push(subgroup = []);
            for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
              if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
                if ("__data__" in node) subnode.__data__ = node.__data__;
                d3_transitionNode(subnode, i, ns, id, node[ns][id]);
                subgroup.push(subnode);
              } else {
                subgroup.push(null);
              }
            }
          }
          return d3_transition(subgroups, ns, id);
        };
        d3_transitionPrototype.selectAll = function(selector) {
          var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
          selector = d3_selection_selectorAll(selector);
          for (var j = -1, m = this.length; ++j < m; ) {
            for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
              if (node = group[i]) {
                transition = node[ns][id];
                subnodes = selector.call(node, node.__data__, i, j);
                subgroups.push(subgroup = []);
                for (var k = -1, o = subnodes.length; ++k < o; ) {
                  if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
                  subgroup.push(subnode);
                }
              }
            }
          }
          return d3_transition(subgroups, ns, id);
        };
        d3_transitionPrototype.filter = function(filter) {
          var subgroups = [], subgroup, group, node;
          if (typeof filter !== "function") filter = d3_selection_filter(filter);
          for (var j = 0, m = this.length; j < m; j++) {
            subgroups.push(subgroup = []);
            for (var group = this[j], i = 0, n = group.length; i < n; i++) {
              if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
                subgroup.push(node);
              }
            }
          }
          return d3_transition(subgroups, this.namespace, this.id);
        };
        d3_transitionPrototype.tween = function(name2, tween) {
          var id = this.id, ns = this.namespace;
          if (arguments.length < 2) return this.node()[ns][id].tween.get(name2);
          return d3_selection_each(this, tween == null ? function(node) {
            node[ns][id].tween.remove(name2);
          } : function(node) {
            node[ns][id].tween.set(name2, tween);
          });
        };
        function d3_transition_tween(groups, name2, value, tween) {
          var id = groups.id, ns = groups.namespace;
          return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
            node[ns][id].tween.set(name2, tween(value.call(node, node.__data__, i, j)));
          } : (value = tween(value), function(node) {
            node[ns][id].tween.set(name2, value);
          }));
        }
        d3_transitionPrototype.attr = function(nameNS, value) {
          if (arguments.length < 2) {
            for (value in nameNS) this.attr(value, nameNS[value]);
            return this;
          }
          var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name2 = d3.ns.qualify(nameNS);
          function attrNull() {
            this.removeAttribute(name2);
          }
          function attrNullNS() {
            this.removeAttributeNS(name2.space, name2.local);
          }
          function attrTween(b) {
            return b == null ? attrNull : (b += "", function() {
              var a = this.getAttribute(name2), i;
              return a !== b && (i = interpolate(a, b), function(t) {
                this.setAttribute(name2, i(t));
              });
            });
          }
          function attrTweenNS(b) {
            return b == null ? attrNullNS : (b += "", function() {
              var a = this.getAttributeNS(name2.space, name2.local), i;
              return a !== b && (i = interpolate(a, b), function(t) {
                this.setAttributeNS(name2.space, name2.local, i(t));
              });
            });
          }
          return d3_transition_tween(this, "attr." + nameNS, value, name2.local ? attrTweenNS : attrTween);
        };
        d3_transitionPrototype.attrTween = function(nameNS, tween) {
          var name2 = d3.ns.qualify(nameNS);
          function attrTween(d, i) {
            var f = tween.call(this, d, i, this.getAttribute(name2));
            return f && function(t) {
              this.setAttribute(name2, f(t));
            };
          }
          function attrTweenNS(d, i) {
            var f = tween.call(this, d, i, this.getAttributeNS(name2.space, name2.local));
            return f && function(t) {
              this.setAttributeNS(name2.space, name2.local, f(t));
            };
          }
          return this.tween("attr." + nameNS, name2.local ? attrTweenNS : attrTween);
        };
        d3_transitionPrototype.style = function(name2, value, priority) {
          var n = arguments.length;
          if (n < 3) {
            if (typeof name2 !== "string") {
              if (n < 2) value = "";
              for (priority in name2) this.style(priority, name2[priority], value);
              return this;
            }
            priority = "";
          }
          function styleNull() {
            this.style.removeProperty(name2);
          }
          function styleString(b) {
            return b == null ? styleNull : (b += "", function() {
              var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name2), i;
              return a !== b && (i = d3_interpolate(a, b), function(t) {
                this.style.setProperty(name2, i(t), priority);
              });
            });
          }
          return d3_transition_tween(this, "style." + name2, value, styleString);
        };
        d3_transitionPrototype.styleTween = function(name2, tween, priority) {
          if (arguments.length < 3) priority = "";
          function styleTween(d, i) {
            var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name2));
            return f && function(t) {
              this.style.setProperty(name2, f(t), priority);
            };
          }
          return this.tween("style." + name2, styleTween);
        };
        d3_transitionPrototype.text = function(value) {
          return d3_transition_tween(this, "text", value, d3_transition_text);
        };
        function d3_transition_text(b) {
          if (b == null) b = "";
          return function() {
            this.textContent = b;
          };
        }
        d3_transitionPrototype.remove = function() {
          var ns = this.namespace;
          return this.each("end.transition", function() {
            var p;
            if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
          });
        };
        d3_transitionPrototype.ease = function(value) {
          var id = this.id, ns = this.namespace;
          if (arguments.length < 1) return this.node()[ns][id].ease;
          if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
          return d3_selection_each(this, function(node) {
            node[ns][id].ease = value;
          });
        };
        d3_transitionPrototype.delay = function(value) {
          var id = this.id, ns = this.namespace;
          if (arguments.length < 1) return this.node()[ns][id].delay;
          return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
            node[ns][id].delay = +value.call(node, node.__data__, i, j);
          } : (value = +value, function(node) {
            node[ns][id].delay = value;
          }));
        };
        d3_transitionPrototype.duration = function(value) {
          var id = this.id, ns = this.namespace;
          if (arguments.length < 1) return this.node()[ns][id].duration;
          return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
            node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
          } : (value = Math.max(1, value), function(node) {
            node[ns][id].duration = value;
          }));
        };
        d3_transitionPrototype.each = function(type, listener) {
          var id = this.id, ns = this.namespace;
          if (arguments.length < 2) {
            var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
            try {
              d3_transitionInheritId = id;
              d3_selection_each(this, function(node, i, j) {
                d3_transitionInherit = node[ns][id];
                type.call(node, node.__data__, i, j);
              });
            } finally {
              d3_transitionInherit = inherit;
              d3_transitionInheritId = inheritId;
            }
          } else {
            d3_selection_each(this, function(node) {
              var transition = node[ns][id];
              (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
            });
          }
          return this;
        };
        d3_transitionPrototype.transition = function() {
          var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
          for (var j = 0, m = this.length; j < m; j++) {
            subgroups.push(subgroup = []);
            for (var group = this[j], i = 0, n = group.length; i < n; i++) {
              if (node = group[i]) {
                transition = node[ns][id0];
                d3_transitionNode(node, i, ns, id1, {
                  time: transition.time,
                  ease: transition.ease,
                  delay: transition.delay + transition.duration,
                  duration: transition.duration
                });
              }
              subgroup.push(node);
            }
          }
          return d3_transition(subgroups, ns, id1);
        };
        function d3_transitionNamespace(name2) {
          return name2 == null ? "__transition__" : "__transition_" + name2 + "__";
        }
        function d3_transitionNode(node, i, ns, id, inherit) {
          var lock = node[ns] || (node[ns] = {
            active: 0,
            count: 0
          }), transition = lock[id], time, timer, duration, ease, tweens;
          function schedule(elapsed) {
            var delay = transition.delay;
            timer.t = delay + time;
            if (delay <= elapsed) return start(elapsed - delay);
            timer.c = start;
          }
          function start(elapsed) {
            var activeId = lock.active, active = lock[activeId];
            if (active) {
              active.timer.c = null;
              active.timer.t = NaN;
              --lock.count;
              delete lock[activeId];
              active.event && active.event.interrupt.call(node, node.__data__, active.index);
            }
            for (var cancelId in lock) {
              if (+cancelId < id) {
                var cancel = lock[cancelId];
                cancel.timer.c = null;
                cancel.timer.t = NaN;
                --lock.count;
                delete lock[cancelId];
              }
            }
            timer.c = tick;
            d3_timer(function() {
              if (timer.c && tick(elapsed || 1)) {
                timer.c = null;
                timer.t = NaN;
              }
              return 1;
            }, 0, time);
            lock.active = id;
            transition.event && transition.event.start.call(node, node.__data__, i);
            tweens = [];
            transition.tween.forEach(function(key, value) {
              if (value = value.call(node, node.__data__, i)) {
                tweens.push(value);
              }
            });
            ease = transition.ease;
            duration = transition.duration;
          }
          function tick(elapsed) {
            var t = elapsed / duration, e = ease(t), n = tweens.length;
            while (n > 0) {
              tweens[--n].call(node, e);
            }
            if (t >= 1) {
              transition.event && transition.event.end.call(node, node.__data__, i);
              if (--lock.count) delete lock[id];
              else delete node[ns];
              return 1;
            }
          }
          if (!transition) {
            time = inherit.time;
            timer = d3_timer(schedule, 0, time);
            transition = lock[id] = {
              tween: new d3_Map(),
              time,
              timer,
              delay: inherit.delay,
              duration: inherit.duration,
              ease: inherit.ease,
              index: i
            };
            inherit = null;
            ++lock.count;
          }
        }
        d3.svg.axis = function() {
          var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [10], tickValues = null, tickFormat_;
          function axis(g) {
            g.each(function() {
              var g2 = d3.select(this);
              var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
              var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g2.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", \u03B5), tickExit = d3.transition(tick.exit()).style("opacity", \u03B5).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
              var range = d3_scaleRange(scale1), path = g2.selectAll(".domain").data([0]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d3.transition(path));
              tickEnter.append("line");
              tickEnter.append("text");
              var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
              if (orient === "bottom" || orient === "top") {
                tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
                text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
                pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
              } else {
                tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
                text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
                pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
              }
              lineEnter.attr(y2, sign * innerTickSize);
              textEnter.attr(y1, sign * tickSpacing);
              lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
              textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
              if (scale1.rangeBand) {
                var x = scale1, dx = x.rangeBand() / 2;
                scale0 = scale1 = function(d) {
                  return x(d) + dx;
                };
              } else if (scale0.rangeBand) {
                scale0 = scale1;
              } else {
                tickExit.call(tickTransform, scale1, scale0);
              }
              tickEnter.call(tickTransform, scale0, scale1);
              tickUpdate.call(tickTransform, scale1, scale1);
            });
          }
          axis.scale = function(x) {
            if (!arguments.length) return scale;
            scale = x;
            return axis;
          };
          axis.orient = function(x) {
            if (!arguments.length) return orient;
            orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
            return axis;
          };
          axis.ticks = function() {
            if (!arguments.length) return tickArguments_;
            tickArguments_ = d3_array(arguments);
            return axis;
          };
          axis.tickValues = function(x) {
            if (!arguments.length) return tickValues;
            tickValues = x;
            return axis;
          };
          axis.tickFormat = function(x) {
            if (!arguments.length) return tickFormat_;
            tickFormat_ = x;
            return axis;
          };
          axis.tickSize = function(x) {
            var n = arguments.length;
            if (!n) return innerTickSize;
            innerTickSize = +x;
            outerTickSize = +arguments[n - 1];
            return axis;
          };
          axis.innerTickSize = function(x) {
            if (!arguments.length) return innerTickSize;
            innerTickSize = +x;
            return axis;
          };
          axis.outerTickSize = function(x) {
            if (!arguments.length) return outerTickSize;
            outerTickSize = +x;
            return axis;
          };
          axis.tickPadding = function(x) {
            if (!arguments.length) return tickPadding;
            tickPadding = +x;
            return axis;
          };
          axis.tickSubdivide = function() {
            return arguments.length && axis;
          };
          return axis;
        };
        var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
          top: 1,
          right: 1,
          bottom: 1,
          left: 1
        };
        function d3_svg_axisX(selection, x0, x1) {
          selection.attr("transform", function(d) {
            var v0 = x0(d);
            return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
          });
        }
        function d3_svg_axisY(selection, y0, y1) {
          selection.attr("transform", function(d) {
            var v0 = y0(d);
            return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
          });
        }
        d3.svg.brush = function() {
          var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [0, 0], yExtent = [0, 0], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
          function brush(g) {
            g.each(function() {
              var g2 = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
              var background = g2.selectAll(".background").data([0]);
              background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
              g2.selectAll(".extent").data([0]).enter().append("rect").attr("class", "extent").style("cursor", "move");
              var resize = g2.selectAll(".resize").data(resizes, d3_identity);
              resize.exit().remove();
              resize.enter().append("g").attr("class", function(d) {
                return "resize " + d;
              }).style("cursor", function(d) {
                return d3_svg_brushCursor[d];
              }).append("rect").attr("x", function(d) {
                return /[ew]$/.test(d) ? -3 : null;
              }).attr("y", function(d) {
                return /^[ns]/.test(d) ? -3 : null;
              }).attr("width", 6).attr("height", 6).style("visibility", "hidden");
              resize.style("display", brush.empty() ? "none" : null);
              var gUpdate = d3.transition(g2), backgroundUpdate = d3.transition(background), range;
              if (x) {
                range = d3_scaleRange(x);
                backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
                redrawX(gUpdate);
              }
              if (y) {
                range = d3_scaleRange(y);
                backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
                redrawY(gUpdate);
              }
              redraw(gUpdate);
            });
          }
          brush.event = function(g) {
            g.each(function() {
              var event_ = event.of(this, arguments), extent1 = {
                x: xExtent,
                y: yExtent,
                i: xExtentDomain,
                j: yExtentDomain
              }, extent0 = this.__chart__ || extent1;
              this.__chart__ = extent1;
              if (d3_transitionInheritId) {
                d3.select(this).transition().each("start.brush", function() {
                  xExtentDomain = extent0.i;
                  yExtentDomain = extent0.j;
                  xExtent = extent0.x;
                  yExtent = extent0.y;
                  event_({
                    type: "brushstart"
                  });
                }).tween("brush:brush", function() {
                  var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
                  xExtentDomain = yExtentDomain = null;
                  return function(t) {
                    xExtent = extent1.x = xi(t);
                    yExtent = extent1.y = yi(t);
                    event_({
                      type: "brush",
                      mode: "resize"
                    });
                  };
                }).each("end.brush", function() {
                  xExtentDomain = extent1.i;
                  yExtentDomain = extent1.j;
                  event_({
                    type: "brush",
                    mode: "resize"
                  });
                  event_({
                    type: "brushend"
                  });
                });
              } else {
                event_({
                  type: "brushstart"
                });
                event_({
                  type: "brush",
                  mode: "resize"
                });
                event_({
                  type: "brushend"
                });
              }
            });
          };
          function redraw(g) {
            g.selectAll(".resize").attr("transform", function(d) {
              return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
            });
          }
          function redrawX(g) {
            g.select(".extent").attr("x", xExtent[0]);
            g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
          }
          function redrawY(g) {
            g.select(".extent").attr("y", yExtent[0]);
            g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
          }
          function brushstart() {
            var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
            var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
            if (d3.event.changedTouches) {
              w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
            } else {
              w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
            }
            g.interrupt().selectAll("*").interrupt();
            if (dragging) {
              origin[0] = xExtent[0] - origin[0];
              origin[1] = yExtent[0] - origin[1];
            } else if (resizing) {
              var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
              offset = [xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1]];
              origin[0] = xExtent[ex];
              origin[1] = yExtent[ey];
            } else if (d3.event.altKey) center = origin.slice();
            g.style("pointer-events", "none").selectAll(".resize").style("display", null);
            d3.select("body").style("cursor", eventTarget.style("cursor"));
            event_({
              type: "brushstart"
            });
            brushmove();
            function keydown() {
              if (d3.event.keyCode == 32) {
                if (!dragging) {
                  center = null;
                  origin[0] -= xExtent[1];
                  origin[1] -= yExtent[1];
                  dragging = 2;
                }
                d3_eventPreventDefault();
              }
            }
            function keyup() {
              if (d3.event.keyCode == 32 && dragging == 2) {
                origin[0] += xExtent[1];
                origin[1] += yExtent[1];
                dragging = 0;
                d3_eventPreventDefault();
              }
            }
            function brushmove() {
              var point = d3.mouse(target), moved = false;
              if (offset) {
                point[0] += offset[0];
                point[1] += offset[1];
              }
              if (!dragging) {
                if (d3.event.altKey) {
                  if (!center) center = [(xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2];
                  origin[0] = xExtent[+(point[0] < center[0])];
                  origin[1] = yExtent[+(point[1] < center[1])];
                } else center = null;
              }
              if (resizingX && move1(point, x, 0)) {
                redrawX(g);
                moved = true;
              }
              if (resizingY && move1(point, y, 1)) {
                redrawY(g);
                moved = true;
              }
              if (moved) {
                redraw(g);
                event_({
                  type: "brush",
                  mode: dragging ? "move" : "resize"
                });
              }
            }
            function move1(point, scale, i) {
              var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
              if (dragging) {
                r0 -= position;
                r1 -= size + position;
              }
              min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
              if (dragging) {
                max = (min += position) + size;
              } else {
                if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
                if (position < min) {
                  max = min;
                  min = position;
                } else {
                  max = position;
                }
              }
              if (extent[0] != min || extent[1] != max) {
                if (i) yExtentDomain = null;
                else xExtentDomain = null;
                extent[0] = min;
                extent[1] = max;
                return true;
              }
            }
            function brushend() {
              brushmove();
              g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
              d3.select("body").style("cursor", null);
              w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
              dragRestore();
              event_({
                type: "brushend"
              });
            }
          }
          brush.x = function(z) {
            if (!arguments.length) return x;
            x = z;
            resizes = d3_svg_brushResizes[!x << 1 | !y];
            return brush;
          };
          brush.y = function(z) {
            if (!arguments.length) return y;
            y = z;
            resizes = d3_svg_brushResizes[!x << 1 | !y];
            return brush;
          };
          brush.clamp = function(z) {
            if (!arguments.length) return x && y ? [xClamp, yClamp] : x ? xClamp : y ? yClamp : null;
            if (x && y) xClamp = !!z[0], yClamp = !!z[1];
            else if (x) xClamp = !!z;
            else if (y) yClamp = !!z;
            return brush;
          };
          brush.extent = function(z) {
            var x0, x1, y0, y1, t;
            if (!arguments.length) {
              if (x) {
                if (xExtentDomain) {
                  x0 = xExtentDomain[0], x1 = xExtentDomain[1];
                } else {
                  x0 = xExtent[0], x1 = xExtent[1];
                  if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
                  if (x1 < x0) t = x0, x0 = x1, x1 = t;
                }
              }
              if (y) {
                if (yExtentDomain) {
                  y0 = yExtentDomain[0], y1 = yExtentDomain[1];
                } else {
                  y0 = yExtent[0], y1 = yExtent[1];
                  if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
                  if (y1 < y0) t = y0, y0 = y1, y1 = t;
                }
              }
              return x && y ? [[x0, y0], [x1, y1]] : x ? [x0, x1] : y && [y0, y1];
            }
            if (x) {
              x0 = z[0], x1 = z[1];
              if (y) x0 = x0[0], x1 = x1[0];
              xExtentDomain = [x0, x1];
              if (x.invert) x0 = x(x0), x1 = x(x1);
              if (x1 < x0) t = x0, x0 = x1, x1 = t;
              if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [x0, x1];
            }
            if (y) {
              y0 = z[0], y1 = z[1];
              if (x) y0 = y0[1], y1 = y1[1];
              yExtentDomain = [y0, y1];
              if (y.invert) y0 = y(y0), y1 = y(y1);
              if (y1 < y0) t = y0, y0 = y1, y1 = t;
              if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [y0, y1];
            }
            return brush;
          };
          brush.clear = function() {
            if (!brush.empty()) {
              xExtent = [0, 0], yExtent = [0, 0];
              xExtentDomain = yExtentDomain = null;
            }
            return brush;
          };
          brush.empty = function() {
            return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
          };
          return d3.rebind(brush, event, "on");
        };
        var d3_svg_brushCursor = {
          n: "ns-resize",
          e: "ew-resize",
          s: "ns-resize",
          w: "ew-resize",
          nw: "nwse-resize",
          ne: "nesw-resize",
          se: "nwse-resize",
          sw: "nesw-resize"
        };
        var d3_svg_brushResizes = [["n", "e", "s", "w", "nw", "ne", "se", "sw"], ["e", "w"], ["n", "s"], []];
        d3.text = d3_xhrType(function(request) {
          return request.responseText;
        });
        d3.json = function(url, callback) {
          return d3_xhr(url, "application/json", d3_json, callback);
        };
        function d3_json(request) {
          return JSON.parse(request.responseText);
        }
        d3.html = function(url, callback) {
          return d3_xhr(url, "text/html", d3_html, callback);
        };
        function d3_html(request) {
          var range = d3_document.createRange();
          range.selectNode(d3_document.body);
          return range.createContextualFragment(request.responseText);
        }
        d3.xml = d3_xhrType(function(request) {
          return request.responseXML;
        });
        if (typeof define === "function" && false) define(d3);
        else if (typeof module === "object" && module.exports) module.exports = d3;
        else this.d3 = d3;
      }.apply(self);
    }
  });

  // node_modules/d3-time/dist/d3-time.js
  var require_d3_time = __commonJS({
    "node_modules/d3-time/dist/d3-time.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}));
      })(exports, function(exports2) {
        "use strict";
        var t02 = /* @__PURE__ */ new Date(), t12 = /* @__PURE__ */ new Date();
        function newInterval(floori, offseti, count, field) {
          function interval(date) {
            return floori(date = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date)), date;
          }
          interval.floor = function(date) {
            return floori(date = /* @__PURE__ */ new Date(+date)), date;
          };
          interval.ceil = function(date) {
            return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
          };
          interval.round = function(date) {
            var d0 = interval(date), d1 = interval.ceil(date);
            return date - d0 < d1 - date ? d0 : d1;
          };
          interval.offset = function(date, step) {
            return offseti(date = /* @__PURE__ */ new Date(+date), step == null ? 1 : Math.floor(step)), date;
          };
          interval.range = function(start, stop, step) {
            var range = [], previous;
            start = interval.ceil(start);
            step = step == null ? 1 : Math.floor(step);
            if (!(start < stop) || !(step > 0)) return range;
            do
              range.push(previous = /* @__PURE__ */ new Date(+start)), offseti(start, step), floori(start);
            while (previous < start && start < stop);
            return range;
          };
          interval.filter = function(test) {
            return newInterval(function(date) {
              if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);
            }, function(date, step) {
              if (date >= date) {
                if (step < 0) while (++step <= 0) {
                  while (offseti(date, -1), !test(date)) {
                  }
                }
                else while (--step >= 0) {
                  while (offseti(date, 1), !test(date)) {
                  }
                }
              }
            });
          };
          if (count) {
            interval.count = function(start, end) {
              t02.setTime(+start), t12.setTime(+end);
              floori(t02), floori(t12);
              return Math.floor(count(t02, t12));
            };
            interval.every = function(step) {
              step = Math.floor(step);
              return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval : interval.filter(field ? function(d) {
                return field(d) % step === 0;
              } : function(d) {
                return interval.count(0, d) % step === 0;
              });
            };
          }
          return interval;
        }
        var millisecond = newInterval(function() {
        }, function(date, step) {
          date.setTime(+date + step);
        }, function(start, end) {
          return end - start;
        });
        millisecond.every = function(k) {
          k = Math.floor(k);
          if (!isFinite(k) || !(k > 0)) return null;
          if (!(k > 1)) return millisecond;
          return newInterval(function(date) {
            date.setTime(Math.floor(date / k) * k);
          }, function(date, step) {
            date.setTime(+date + step * k);
          }, function(start, end) {
            return (end - start) / k;
          });
        };
        var milliseconds = millisecond.range;
        var durationSecond = 1e3;
        var durationMinute = 6e4;
        var durationHour = 36e5;
        var durationDay = 864e5;
        var durationWeek = 6048e5;
        var second = newInterval(function(date) {
          date.setTime(date - date.getMilliseconds());
        }, function(date, step) {
          date.setTime(+date + step * durationSecond);
        }, function(start, end) {
          return (end - start) / durationSecond;
        }, function(date) {
          return date.getUTCSeconds();
        });
        var seconds = second.range;
        var minute = newInterval(function(date) {
          date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);
        }, function(date, step) {
          date.setTime(+date + step * durationMinute);
        }, function(start, end) {
          return (end - start) / durationMinute;
        }, function(date) {
          return date.getMinutes();
        });
        var minutes = minute.range;
        var hour = newInterval(function(date) {
          date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);
        }, function(date, step) {
          date.setTime(+date + step * durationHour);
        }, function(start, end) {
          return (end - start) / durationHour;
        }, function(date) {
          return date.getHours();
        });
        var hours = hour.range;
        var day = newInterval(function(date) {
          date.setHours(0, 0, 0, 0);
        }, function(date, step) {
          date.setDate(date.getDate() + step);
        }, function(start, end) {
          return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay;
        }, function(date) {
          return date.getDate() - 1;
        });
        var days = day.range;
        function weekday(i) {
          return newInterval(function(date) {
            date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
            date.setHours(0, 0, 0, 0);
          }, function(date, step) {
            date.setDate(date.getDate() + step * 7);
          }, function(start, end) {
            return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
          });
        }
        var sunday = weekday(0);
        var monday = weekday(1);
        var tuesday = weekday(2);
        var wednesday = weekday(3);
        var thursday = weekday(4);
        var friday = weekday(5);
        var saturday = weekday(6);
        var sundays = sunday.range;
        var mondays = monday.range;
        var tuesdays = tuesday.range;
        var wednesdays = wednesday.range;
        var thursdays = thursday.range;
        var fridays = friday.range;
        var saturdays = saturday.range;
        var month = newInterval(function(date) {
          date.setDate(1);
          date.setHours(0, 0, 0, 0);
        }, function(date, step) {
          date.setMonth(date.getMonth() + step);
        }, function(start, end) {
          return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
        }, function(date) {
          return date.getMonth();
        });
        var months = month.range;
        var year = newInterval(function(date) {
          date.setMonth(0, 1);
          date.setHours(0, 0, 0, 0);
        }, function(date, step) {
          date.setFullYear(date.getFullYear() + step);
        }, function(start, end) {
          return end.getFullYear() - start.getFullYear();
        }, function(date) {
          return date.getFullYear();
        });
        year.every = function(k) {
          return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
            date.setFullYear(Math.floor(date.getFullYear() / k) * k);
            date.setMonth(0, 1);
            date.setHours(0, 0, 0, 0);
          }, function(date, step) {
            date.setFullYear(date.getFullYear() + step * k);
          });
        };
        var years = year.range;
        var utcMinute = newInterval(function(date) {
          date.setUTCSeconds(0, 0);
        }, function(date, step) {
          date.setTime(+date + step * durationMinute);
        }, function(start, end) {
          return (end - start) / durationMinute;
        }, function(date) {
          return date.getUTCMinutes();
        });
        var utcMinutes = utcMinute.range;
        var utcHour = newInterval(function(date) {
          date.setUTCMinutes(0, 0, 0);
        }, function(date, step) {
          date.setTime(+date + step * durationHour);
        }, function(start, end) {
          return (end - start) / durationHour;
        }, function(date) {
          return date.getUTCHours();
        });
        var utcHours = utcHour.range;
        var utcDay = newInterval(function(date) {
          date.setUTCHours(0, 0, 0, 0);
        }, function(date, step) {
          date.setUTCDate(date.getUTCDate() + step);
        }, function(start, end) {
          return (end - start) / durationDay;
        }, function(date) {
          return date.getUTCDate() - 1;
        });
        var utcDays = utcDay.range;
        function utcWeekday(i) {
          return newInterval(function(date) {
            date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
            date.setUTCHours(0, 0, 0, 0);
          }, function(date, step) {
            date.setUTCDate(date.getUTCDate() + step * 7);
          }, function(start, end) {
            return (end - start) / durationWeek;
          });
        }
        var utcSunday = utcWeekday(0);
        var utcMonday = utcWeekday(1);
        var utcTuesday = utcWeekday(2);
        var utcWednesday = utcWeekday(3);
        var utcThursday = utcWeekday(4);
        var utcFriday = utcWeekday(5);
        var utcSaturday = utcWeekday(6);
        var utcSundays = utcSunday.range;
        var utcMondays = utcMonday.range;
        var utcTuesdays = utcTuesday.range;
        var utcWednesdays = utcWednesday.range;
        var utcThursdays = utcThursday.range;
        var utcFridays = utcFriday.range;
        var utcSaturdays = utcSaturday.range;
        var utcMonth = newInterval(function(date) {
          date.setUTCDate(1);
          date.setUTCHours(0, 0, 0, 0);
        }, function(date, step) {
          date.setUTCMonth(date.getUTCMonth() + step);
        }, function(start, end) {
          return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
        }, function(date) {
          return date.getUTCMonth();
        });
        var utcMonths = utcMonth.range;
        var utcYear = newInterval(function(date) {
          date.setUTCMonth(0, 1);
          date.setUTCHours(0, 0, 0, 0);
        }, function(date, step) {
          date.setUTCFullYear(date.getUTCFullYear() + step);
        }, function(start, end) {
          return end.getUTCFullYear() - start.getUTCFullYear();
        }, function(date) {
          return date.getUTCFullYear();
        });
        utcYear.every = function(k) {
          return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
            date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
            date.setUTCMonth(0, 1);
            date.setUTCHours(0, 0, 0, 0);
          }, function(date, step) {
            date.setUTCFullYear(date.getUTCFullYear() + step * k);
          });
        };
        var utcYears = utcYear.range;
        exports2.timeDay = day;
        exports2.timeDays = days;
        exports2.timeFriday = friday;
        exports2.timeFridays = fridays;
        exports2.timeHour = hour;
        exports2.timeHours = hours;
        exports2.timeInterval = newInterval;
        exports2.timeMillisecond = millisecond;
        exports2.timeMilliseconds = milliseconds;
        exports2.timeMinute = minute;
        exports2.timeMinutes = minutes;
        exports2.timeMonday = monday;
        exports2.timeMondays = mondays;
        exports2.timeMonth = month;
        exports2.timeMonths = months;
        exports2.timeSaturday = saturday;
        exports2.timeSaturdays = saturdays;
        exports2.timeSecond = second;
        exports2.timeSeconds = seconds;
        exports2.timeSunday = sunday;
        exports2.timeSundays = sundays;
        exports2.timeThursday = thursday;
        exports2.timeThursdays = thursdays;
        exports2.timeTuesday = tuesday;
        exports2.timeTuesdays = tuesdays;
        exports2.timeWednesday = wednesday;
        exports2.timeWednesdays = wednesdays;
        exports2.timeWeek = sunday;
        exports2.timeWeeks = sundays;
        exports2.timeYear = year;
        exports2.timeYears = years;
        exports2.utcDay = utcDay;
        exports2.utcDays = utcDays;
        exports2.utcFriday = utcFriday;
        exports2.utcFridays = utcFridays;
        exports2.utcHour = utcHour;
        exports2.utcHours = utcHours;
        exports2.utcMillisecond = millisecond;
        exports2.utcMilliseconds = milliseconds;
        exports2.utcMinute = utcMinute;
        exports2.utcMinutes = utcMinutes;
        exports2.utcMonday = utcMonday;
        exports2.utcMondays = utcMondays;
        exports2.utcMonth = utcMonth;
        exports2.utcMonths = utcMonths;
        exports2.utcSaturday = utcSaturday;
        exports2.utcSaturdays = utcSaturdays;
        exports2.utcSecond = second;
        exports2.utcSeconds = seconds;
        exports2.utcSunday = utcSunday;
        exports2.utcSundays = utcSundays;
        exports2.utcThursday = utcThursday;
        exports2.utcThursdays = utcThursdays;
        exports2.utcTuesday = utcTuesday;
        exports2.utcTuesdays = utcTuesdays;
        exports2.utcWednesday = utcWednesday;
        exports2.utcWednesdays = utcWednesdays;
        exports2.utcWeek = utcSunday;
        exports2.utcWeeks = utcSundays;
        exports2.utcYear = utcYear;
        exports2.utcYears = utcYears;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-time-format/dist/d3-time-format.js
  var require_d3_time_format = __commonJS({
    "node_modules/d3-time-format/dist/d3-time-format.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require_d3_time()) : typeof define === "function" && false ? define(["exports", "d3-time"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}, global2.d3));
      })(exports, function(exports2, d3Time) {
        "use strict";
        function localDate(d) {
          if (0 <= d.y && d.y < 100) {
            var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
            date.setFullYear(d.y);
            return date;
          }
          return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
        }
        function utcDate(d) {
          if (0 <= d.y && d.y < 100) {
            var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
            date.setUTCFullYear(d.y);
            return date;
          }
          return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
        }
        function newDate(y, m, d) {
          return { y, m, d, H: 0, M: 0, S: 0, L: 0 };
        }
        function formatLocale(locale2) {
          var locale_dateTime = locale2.dateTime, locale_date = locale2.date, locale_time = locale2.time, locale_periods = locale2.periods, locale_weekdays = locale2.days, locale_shortWeekdays = locale2.shortDays, locale_months = locale2.months, locale_shortMonths = locale2.shortMonths;
          var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths);
          var formats = {
            "a": formatShortWeekday,
            "A": formatWeekday,
            "b": formatShortMonth,
            "B": formatMonth,
            "c": null,
            "d": formatDayOfMonth,
            "e": formatDayOfMonth,
            "f": formatMicroseconds,
            "H": formatHour24,
            "I": formatHour12,
            "j": formatDayOfYear,
            "L": formatMilliseconds,
            "m": formatMonthNumber,
            "M": formatMinutes,
            "p": formatPeriod,
            "q": formatQuarter,
            "Q": formatUnixTimestamp,
            "s": formatUnixTimestampSeconds,
            "S": formatSeconds,
            "u": formatWeekdayNumberMonday,
            "U": formatWeekNumberSunday,
            "V": formatWeekNumberISO,
            "w": formatWeekdayNumberSunday,
            "W": formatWeekNumberMonday,
            "x": null,
            "X": null,
            "y": formatYear,
            "Y": formatFullYear,
            "Z": formatZone,
            "%": formatLiteralPercent
          };
          var utcFormats = {
            "a": formatUTCShortWeekday,
            "A": formatUTCWeekday,
            "b": formatUTCShortMonth,
            "B": formatUTCMonth,
            "c": null,
            "d": formatUTCDayOfMonth,
            "e": formatUTCDayOfMonth,
            "f": formatUTCMicroseconds,
            "H": formatUTCHour24,
            "I": formatUTCHour12,
            "j": formatUTCDayOfYear,
            "L": formatUTCMilliseconds,
            "m": formatUTCMonthNumber,
            "M": formatUTCMinutes,
            "p": formatUTCPeriod,
            "q": formatUTCQuarter,
            "Q": formatUnixTimestamp,
            "s": formatUnixTimestampSeconds,
            "S": formatUTCSeconds,
            "u": formatUTCWeekdayNumberMonday,
            "U": formatUTCWeekNumberSunday,
            "V": formatUTCWeekNumberISO,
            "w": formatUTCWeekdayNumberSunday,
            "W": formatUTCWeekNumberMonday,
            "x": null,
            "X": null,
            "y": formatUTCYear,
            "Y": formatUTCFullYear,
            "Z": formatUTCZone,
            "%": formatLiteralPercent
          };
          var parses = {
            "a": parseShortWeekday,
            "A": parseWeekday,
            "b": parseShortMonth,
            "B": parseMonth,
            "c": parseLocaleDateTime,
            "d": parseDayOfMonth,
            "e": parseDayOfMonth,
            "f": parseMicroseconds,
            "H": parseHour24,
            "I": parseHour24,
            "j": parseDayOfYear,
            "L": parseMilliseconds,
            "m": parseMonthNumber,
            "M": parseMinutes,
            "p": parsePeriod,
            "q": parseQuarter,
            "Q": parseUnixTimestamp,
            "s": parseUnixTimestampSeconds,
            "S": parseSeconds,
            "u": parseWeekdayNumberMonday,
            "U": parseWeekNumberSunday,
            "V": parseWeekNumberISO,
            "w": parseWeekdayNumberSunday,
            "W": parseWeekNumberMonday,
            "x": parseLocaleDate,
            "X": parseLocaleTime,
            "y": parseYear,
            "Y": parseFullYear,
            "Z": parseZone,
            "%": parseLiteralPercent
          };
          formats.x = newFormat(locale_date, formats);
          formats.X = newFormat(locale_time, formats);
          formats.c = newFormat(locale_dateTime, formats);
          utcFormats.x = newFormat(locale_date, utcFormats);
          utcFormats.X = newFormat(locale_time, utcFormats);
          utcFormats.c = newFormat(locale_dateTime, utcFormats);
          function newFormat(specifier, formats2) {
            return function(date) {
              var string = [], i = -1, j = 0, n = specifier.length, c, pad2, format;
              if (!(date instanceof Date)) date = /* @__PURE__ */ new Date(+date);
              while (++i < n) {
                if (specifier.charCodeAt(i) === 37) {
                  string.push(specifier.slice(j, i));
                  if ((pad2 = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
                  else pad2 = c === "e" ? " " : "0";
                  if (format = formats2[c]) c = format(date, pad2);
                  string.push(c);
                  j = i + 1;
                }
              }
              string.push(specifier.slice(j, i));
              return string.join("");
            };
          }
          function newParse(specifier, Z) {
            return function(string) {
              var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string += "", 0), week, day;
              if (i != string.length) return null;
              if ("Q" in d) return new Date(d.Q);
              if ("s" in d) return new Date(d.s * 1e3 + ("L" in d ? d.L : 0));
              if (Z && !("Z" in d)) d.Z = 0;
              if ("p" in d) d.H = d.H % 12 + d.p * 12;
              if (d.m === void 0) d.m = "q" in d ? d.q : 0;
              if ("V" in d) {
                if (d.V < 1 || d.V > 53) return null;
                if (!("w" in d)) d.w = 1;
                if ("Z" in d) {
                  week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();
                  week = day > 4 || day === 0 ? d3Time.utcMonday.ceil(week) : d3Time.utcMonday(week);
                  week = d3Time.utcDay.offset(week, (d.V - 1) * 7);
                  d.y = week.getUTCFullYear();
                  d.m = week.getUTCMonth();
                  d.d = week.getUTCDate() + (d.w + 6) % 7;
                } else {
                  week = localDate(newDate(d.y, 0, 1)), day = week.getDay();
                  week = day > 4 || day === 0 ? d3Time.timeMonday.ceil(week) : d3Time.timeMonday(week);
                  week = d3Time.timeDay.offset(week, (d.V - 1) * 7);
                  d.y = week.getFullYear();
                  d.m = week.getMonth();
                  d.d = week.getDate() + (d.w + 6) % 7;
                }
              } else if ("W" in d || "U" in d) {
                if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
                day = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();
                d.m = 0;
                d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;
              }
              if ("Z" in d) {
                d.H += d.Z / 100 | 0;
                d.M += d.Z % 100;
                return utcDate(d);
              }
              return localDate(d);
            };
          }
          function parseSpecifier(d, specifier, string, j) {
            var i = 0, n = specifier.length, m = string.length, c, parse2;
            while (i < n) {
              if (j >= m) return -1;
              c = specifier.charCodeAt(i++);
              if (c === 37) {
                c = specifier.charAt(i++);
                parse2 = parses[c in pads ? specifier.charAt(i++) : c];
                if (!parse2 || (j = parse2(d, string, j)) < 0) return -1;
              } else if (c != string.charCodeAt(j++)) {
                return -1;
              }
            }
            return j;
          }
          function parsePeriod(d, string, i) {
            var n = periodRe.exec(string.slice(i));
            return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;
          }
          function parseShortWeekday(d, string, i) {
            var n = shortWeekdayRe.exec(string.slice(i));
            return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
          }
          function parseWeekday(d, string, i) {
            var n = weekdayRe.exec(string.slice(i));
            return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
          }
          function parseShortMonth(d, string, i) {
            var n = shortMonthRe.exec(string.slice(i));
            return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
          }
          function parseMonth(d, string, i) {
            var n = monthRe.exec(string.slice(i));
            return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
          }
          function parseLocaleDateTime(d, string, i) {
            return parseSpecifier(d, locale_dateTime, string, i);
          }
          function parseLocaleDate(d, string, i) {
            return parseSpecifier(d, locale_date, string, i);
          }
          function parseLocaleTime(d, string, i) {
            return parseSpecifier(d, locale_time, string, i);
          }
          function formatShortWeekday(d) {
            return locale_shortWeekdays[d.getDay()];
          }
          function formatWeekday(d) {
            return locale_weekdays[d.getDay()];
          }
          function formatShortMonth(d) {
            return locale_shortMonths[d.getMonth()];
          }
          function formatMonth(d) {
            return locale_months[d.getMonth()];
          }
          function formatPeriod(d) {
            return locale_periods[+(d.getHours() >= 12)];
          }
          function formatQuarter(d) {
            return 1 + ~~(d.getMonth() / 3);
          }
          function formatUTCShortWeekday(d) {
            return locale_shortWeekdays[d.getUTCDay()];
          }
          function formatUTCWeekday(d) {
            return locale_weekdays[d.getUTCDay()];
          }
          function formatUTCShortMonth(d) {
            return locale_shortMonths[d.getUTCMonth()];
          }
          function formatUTCMonth(d) {
            return locale_months[d.getUTCMonth()];
          }
          function formatUTCPeriod(d) {
            return locale_periods[+(d.getUTCHours() >= 12)];
          }
          function formatUTCQuarter(d) {
            return 1 + ~~(d.getUTCMonth() / 3);
          }
          return {
            format: function(specifier) {
              var f = newFormat(specifier += "", formats);
              f.toString = function() {
                return specifier;
              };
              return f;
            },
            parse: function(specifier) {
              var p = newParse(specifier += "", false);
              p.toString = function() {
                return specifier;
              };
              return p;
            },
            utcFormat: function(specifier) {
              var f = newFormat(specifier += "", utcFormats);
              f.toString = function() {
                return specifier;
              };
              return f;
            },
            utcParse: function(specifier) {
              var p = newParse(specifier += "", true);
              p.toString = function() {
                return specifier;
              };
              return p;
            }
          };
        }
        var pads = { "-": "", "_": " ", "0": "0" }, numberRe = /^\s*\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g;
        function pad(value, fill, width) {
          var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
          return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
        }
        function requote(s) {
          return s.replace(requoteRe, "\\$&");
        }
        function formatRe(names2) {
          return new RegExp("^(?:" + names2.map(requote).join("|") + ")", "i");
        }
        function formatLookup(names2) {
          var map = {}, i = -1, n = names2.length;
          while (++i < n) map[names2[i].toLowerCase()] = i;
          return map;
        }
        function parseWeekdayNumberSunday(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 1));
          return n ? (d.w = +n[0], i + n[0].length) : -1;
        }
        function parseWeekdayNumberMonday(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 1));
          return n ? (d.u = +n[0], i + n[0].length) : -1;
        }
        function parseWeekNumberSunday(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.U = +n[0], i + n[0].length) : -1;
        }
        function parseWeekNumberISO(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.V = +n[0], i + n[0].length) : -1;
        }
        function parseWeekNumberMonday(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.W = +n[0], i + n[0].length) : -1;
        }
        function parseFullYear(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 4));
          return n ? (d.y = +n[0], i + n[0].length) : -1;
        }
        function parseYear(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1;
        }
        function parseZone(d, string, i) {
          var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
          return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
        }
        function parseQuarter(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 1));
          return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
        }
        function parseMonthNumber(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
        }
        function parseDayOfMonth(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.d = +n[0], i + n[0].length) : -1;
        }
        function parseDayOfYear(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 3));
          return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
        }
        function parseHour24(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.H = +n[0], i + n[0].length) : -1;
        }
        function parseMinutes(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.M = +n[0], i + n[0].length) : -1;
        }
        function parseSeconds(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 2));
          return n ? (d.S = +n[0], i + n[0].length) : -1;
        }
        function parseMilliseconds(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 3));
          return n ? (d.L = +n[0], i + n[0].length) : -1;
        }
        function parseMicroseconds(d, string, i) {
          var n = numberRe.exec(string.slice(i, i + 6));
          return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1;
        }
        function parseLiteralPercent(d, string, i) {
          var n = percentRe.exec(string.slice(i, i + 1));
          return n ? i + n[0].length : -1;
        }
        function parseUnixTimestamp(d, string, i) {
          var n = numberRe.exec(string.slice(i));
          return n ? (d.Q = +n[0], i + n[0].length) : -1;
        }
        function parseUnixTimestampSeconds(d, string, i) {
          var n = numberRe.exec(string.slice(i));
          return n ? (d.s = +n[0], i + n[0].length) : -1;
        }
        function formatDayOfMonth(d, p) {
          return pad(d.getDate(), p, 2);
        }
        function formatHour24(d, p) {
          return pad(d.getHours(), p, 2);
        }
        function formatHour12(d, p) {
          return pad(d.getHours() % 12 || 12, p, 2);
        }
        function formatDayOfYear(d, p) {
          return pad(1 + d3Time.timeDay.count(d3Time.timeYear(d), d), p, 3);
        }
        function formatMilliseconds(d, p) {
          return pad(d.getMilliseconds(), p, 3);
        }
        function formatMicroseconds(d, p) {
          return formatMilliseconds(d, p) + "000";
        }
        function formatMonthNumber(d, p) {
          return pad(d.getMonth() + 1, p, 2);
        }
        function formatMinutes(d, p) {
          return pad(d.getMinutes(), p, 2);
        }
        function formatSeconds(d, p) {
          return pad(d.getSeconds(), p, 2);
        }
        function formatWeekdayNumberMonday(d) {
          var day = d.getDay();
          return day === 0 ? 7 : day;
        }
        function formatWeekNumberSunday(d, p) {
          return pad(d3Time.timeSunday.count(d3Time.timeYear(d) - 1, d), p, 2);
        }
        function formatWeekNumberISO(d, p) {
          var day = d.getDay();
          d = day >= 4 || day === 0 ? d3Time.timeThursday(d) : d3Time.timeThursday.ceil(d);
          return pad(d3Time.timeThursday.count(d3Time.timeYear(d), d) + (d3Time.timeYear(d).getDay() === 4), p, 2);
        }
        function formatWeekdayNumberSunday(d) {
          return d.getDay();
        }
        function formatWeekNumberMonday(d, p) {
          return pad(d3Time.timeMonday.count(d3Time.timeYear(d) - 1, d), p, 2);
        }
        function formatYear(d, p) {
          return pad(d.getFullYear() % 100, p, 2);
        }
        function formatFullYear(d, p) {
          return pad(d.getFullYear() % 1e4, p, 4);
        }
        function formatZone(d) {
          var z = d.getTimezoneOffset();
          return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2);
        }
        function formatUTCDayOfMonth(d, p) {
          return pad(d.getUTCDate(), p, 2);
        }
        function formatUTCHour24(d, p) {
          return pad(d.getUTCHours(), p, 2);
        }
        function formatUTCHour12(d, p) {
          return pad(d.getUTCHours() % 12 || 12, p, 2);
        }
        function formatUTCDayOfYear(d, p) {
          return pad(1 + d3Time.utcDay.count(d3Time.utcYear(d), d), p, 3);
        }
        function formatUTCMilliseconds(d, p) {
          return pad(d.getUTCMilliseconds(), p, 3);
        }
        function formatUTCMicroseconds(d, p) {
          return formatUTCMilliseconds(d, p) + "000";
        }
        function formatUTCMonthNumber(d, p) {
          return pad(d.getUTCMonth() + 1, p, 2);
        }
        function formatUTCMinutes(d, p) {
          return pad(d.getUTCMinutes(), p, 2);
        }
        function formatUTCSeconds(d, p) {
          return pad(d.getUTCSeconds(), p, 2);
        }
        function formatUTCWeekdayNumberMonday(d) {
          var dow = d.getUTCDay();
          return dow === 0 ? 7 : dow;
        }
        function formatUTCWeekNumberSunday(d, p) {
          return pad(d3Time.utcSunday.count(d3Time.utcYear(d) - 1, d), p, 2);
        }
        function formatUTCWeekNumberISO(d, p) {
          var day = d.getUTCDay();
          d = day >= 4 || day === 0 ? d3Time.utcThursday(d) : d3Time.utcThursday.ceil(d);
          return pad(d3Time.utcThursday.count(d3Time.utcYear(d), d) + (d3Time.utcYear(d).getUTCDay() === 4), p, 2);
        }
        function formatUTCWeekdayNumberSunday(d) {
          return d.getUTCDay();
        }
        function formatUTCWeekNumberMonday(d, p) {
          return pad(d3Time.utcMonday.count(d3Time.utcYear(d) - 1, d), p, 2);
        }
        function formatUTCYear(d, p) {
          return pad(d.getUTCFullYear() % 100, p, 2);
        }
        function formatUTCFullYear(d, p) {
          return pad(d.getUTCFullYear() % 1e4, p, 4);
        }
        function formatUTCZone() {
          return "+0000";
        }
        function formatLiteralPercent() {
          return "%";
        }
        function formatUnixTimestamp(d) {
          return +d;
        }
        function formatUnixTimestampSeconds(d) {
          return Math.floor(+d / 1e3);
        }
        var locale;
        defaultLocale({
          dateTime: "%x, %X",
          date: "%-m/%-d/%Y",
          time: "%-I:%M:%S %p",
          periods: ["AM", "PM"],
          days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
          shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
          months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
          shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        });
        function defaultLocale(definition) {
          locale = formatLocale(definition);
          exports2.timeFormat = locale.format;
          exports2.timeParse = locale.parse;
          exports2.utcFormat = locale.utcFormat;
          exports2.utcParse = locale.utcParse;
          return locale;
        }
        var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ";
        function formatIsoNative(date) {
          return date.toISOString();
        }
        var formatIso = Date.prototype.toISOString ? formatIsoNative : exports2.utcFormat(isoSpecifier);
        function parseIsoNative(string) {
          var date = new Date(string);
          return isNaN(date) ? null : date;
        }
        var parseIso = +/* @__PURE__ */ new Date("2000-01-01T00:00:00.000Z") ? parseIsoNative : exports2.utcParse(isoSpecifier);
        exports2.isoFormat = formatIso;
        exports2.isoParse = parseIso;
        exports2.timeFormatDefaultLocale = defaultLocale;
        exports2.timeFormatLocale = formatLocale;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-format/dist/d3-format.js
  var require_d3_format = __commonJS({
    "node_modules/d3-format/dist/d3-format.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.d3 = global2.d3 || {}));
      })(exports, function(exports2) {
        "use strict";
        function formatDecimal(x) {
          return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10);
        }
        function formatDecimalParts(x, p) {
          if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null;
          var i, coefficient = x.slice(0, i);
          return [
            coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
            +x.slice(i + 1)
          ];
        }
        function exponent(x) {
          return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;
        }
        function formatGroup(grouping, thousands) {
          return function(value, width) {
            var i = value.length, t = [], j = 0, g = grouping[0], length = 0;
            while (i > 0 && g > 0) {
              if (length + g + 1 > width) g = Math.max(1, width - length);
              t.push(value.substring(i -= g, i + g));
              if ((length += g + 1) > width) break;
              g = grouping[j = (j + 1) % grouping.length];
            }
            return t.reverse().join(thousands);
          };
        }
        function formatNumerals(numerals) {
          return function(value) {
            return value.replace(/[0-9]/g, function(i) {
              return numerals[+i];
            });
          };
        }
        var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
        function formatSpecifier(specifier) {
          if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
          var match;
          return new FormatSpecifier({
            fill: match[1],
            align: match[2],
            sign: match[3],
            symbol: match[4],
            zero: match[5],
            width: match[6],
            comma: match[7],
            precision: match[8] && match[8].slice(1),
            trim: match[9],
            type: match[10]
          });
        }
        formatSpecifier.prototype = FormatSpecifier.prototype;
        function FormatSpecifier(specifier) {
          this.fill = specifier.fill === void 0 ? " " : specifier.fill + "";
          this.align = specifier.align === void 0 ? ">" : specifier.align + "";
          this.sign = specifier.sign === void 0 ? "-" : specifier.sign + "";
          this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + "";
          this.zero = !!specifier.zero;
          this.width = specifier.width === void 0 ? void 0 : +specifier.width;
          this.comma = !!specifier.comma;
          this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision;
          this.trim = !!specifier.trim;
          this.type = specifier.type === void 0 ? "" : specifier.type + "";
        }
        FormatSpecifier.prototype.toString = function() {
          return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type;
        };
        function formatTrim(s) {
          out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
            switch (s[i]) {
              case ".":
                i0 = i1 = i;
                break;
              case "0":
                if (i0 === 0) i0 = i;
                i1 = i;
                break;
              default:
                if (!+s[i]) break out;
                if (i0 > 0) i0 = 0;
                break;
            }
          }
          return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
        }
        var prefixExponent;
        function formatPrefixAuto(x, p) {
          var d = formatDecimalParts(x, p);
          if (!d) return x + "";
          var coefficient = d[0], exponent2 = d[1], i = exponent2 - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent2 / 3))) * 3) + 1, n = coefficient.length;
          return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0];
        }
        function formatRounded(x, p) {
          var d = formatDecimalParts(x, p);
          if (!d) return x + "";
          var coefficient = d[0], exponent2 = d[1];
          return exponent2 < 0 ? "0." + new Array(-exponent2).join("0") + coefficient : coefficient.length > exponent2 + 1 ? coefficient.slice(0, exponent2 + 1) + "." + coefficient.slice(exponent2 + 1) : coefficient + new Array(exponent2 - coefficient.length + 2).join("0");
        }
        var formatTypes = {
          "%": function(x, p) {
            return (x * 100).toFixed(p);
          },
          "b": function(x) {
            return Math.round(x).toString(2);
          },
          "c": function(x) {
            return x + "";
          },
          "d": formatDecimal,
          "e": function(x, p) {
            return x.toExponential(p);
          },
          "f": function(x, p) {
            return x.toFixed(p);
          },
          "g": function(x, p) {
            return x.toPrecision(p);
          },
          "o": function(x) {
            return Math.round(x).toString(8);
          },
          "p": function(x, p) {
            return formatRounded(x * 100, p);
          },
          "r": formatRounded,
          "s": formatPrefixAuto,
          "X": function(x) {
            return Math.round(x).toString(16).toUpperCase();
          },
          "x": function(x) {
            return Math.round(x).toString(16);
          }
        };
        function identity2(x) {
          return x;
        }
        var map = Array.prototype.map, prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
        function formatLocale(locale2) {
          var group = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity2 : formatGroup(map.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity2 : formatNumerals(map.call(locale2.numerals, String)), percent = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "-" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + "";
          function newFormat(specifier) {
            specifier = formatSpecifier(specifier);
            var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero2 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type;
            if (type === "n") comma = true, type = "g";
            else if (!formatTypes[type]) precision === void 0 && (precision = 12), trim = true, type = "g";
            if (zero2 || fill === "0" && align === "=") zero2 = true, fill = "0", align = "=";
            var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
            var formatType = formatTypes[type], maybeSuffix = /[defgprs%]/.test(type);
            precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
            function format(value) {
              var valuePrefix = prefix, valueSuffix = suffix, i, n, c;
              if (type === "c") {
                valueSuffix = formatType(value) + valueSuffix;
                value = "";
              } else {
                value = +value;
                var valueNegative = value < 0 || 1 / value < 0;
                value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
                if (trim) value = formatTrim(value);
                if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
                valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
                valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
                if (maybeSuffix) {
                  i = -1, n = value.length;
                  while (++i < n) {
                    if (c = value.charCodeAt(i), 48 > c || c > 57) {
                      valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
                      value = value.slice(0, i);
                      break;
                    }
                  }
                }
              }
              if (comma && !zero2) value = group(value, Infinity);
              var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
              if (comma && zero2) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
              switch (align) {
                case "<":
                  value = valuePrefix + value + valueSuffix + padding;
                  break;
                case "=":
                  value = valuePrefix + padding + value + valueSuffix;
                  break;
                case "^":
                  value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
                  break;
                default:
                  value = padding + valuePrefix + value + valueSuffix;
                  break;
              }
              return numerals(value);
            }
            format.toString = function() {
              return specifier + "";
            };
            return format;
          }
          function formatPrefix(specifier, value) {
            var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3];
            return function(value2) {
              return f(k * value2) + prefix;
            };
          }
          return {
            format: newFormat,
            formatPrefix
          };
        }
        var locale;
        defaultLocale({
          decimal: ".",
          thousands: ",",
          grouping: [3],
          currency: ["$", ""],
          minus: "-"
        });
        function defaultLocale(definition) {
          locale = formatLocale(definition);
          exports2.format = locale.format;
          exports2.formatPrefix = locale.formatPrefix;
          return locale;
        }
        function precisionFixed(step) {
          return Math.max(0, -exponent(Math.abs(step)));
        }
        function precisionPrefix(step, value) {
          return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));
        }
        function precisionRound(step, max) {
          step = Math.abs(step), max = Math.abs(max) - step;
          return Math.max(0, exponent(max) - exponent(step)) + 1;
        }
        exports2.FormatSpecifier = FormatSpecifier;
        exports2.formatDefaultLocale = defaultLocale;
        exports2.formatLocale = formatLocale;
        exports2.formatSpecifier = formatSpecifier;
        exports2.precisionFixed = precisionFixed;
        exports2.precisionPrefix = precisionPrefix;
        exports2.precisionRound = precisionRound;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/is-string-blank/index.js
  var require_is_string_blank = __commonJS({
    "node_modules/is-string-blank/index.js"(exports, module) {
      "use strict";
      module.exports = function(str) {
        var l = str.length, a;
        for (var i = 0; i < l; i++) {
          a = str.charCodeAt(i);
          if ((a < 9 || a > 13) && a !== 32 && a !== 133 && a !== 160 && a !== 5760 && a !== 6158 && (a < 8192 || a > 8205) && a !== 8232 && a !== 8233 && a !== 8239 && a !== 8287 && a !== 8288 && a !== 12288 && a !== 65279) {
            return false;
          }
        }
        return true;
      };
    }
  });

  // node_modules/fast-isnumeric/index.js
  var require_fast_isnumeric = __commonJS({
    "node_modules/fast-isnumeric/index.js"(exports, module) {
      "use strict";
      var allBlankCharCodes = require_is_string_blank();
      module.exports = function(n) {
        var type = typeof n;
        if (type === "string") {
          var original = n;
          n = +n;
          if (n === 0 && allBlankCharCodes(original)) return false;
        } else if (type !== "number") return false;
        return n - n < 1;
      };
    }
  });

  // src/constants/numerical.js
  var require_numerical = __commonJS({
    "src/constants/numerical.js"(exports, module) {
      "use strict";
      module.exports = {
        /**
         * Standardize all missing data in calcdata to use undefined
         * never null or NaN.
         * That way we can use !==undefined, or !== BADNUM,
         * to test for real data
         */
        BADNUM: void 0,
        /*
         * Limit certain operations to well below floating point max value
         * to avoid glitches: Make sure that even when you multiply it by the
         * number of pixels on a giant screen it still works
         */
        FP_SAFE: Number.MAX_VALUE * 1e-4,
        /*
         * conversion of date units to milliseconds
         * year and month constants are marked "AVG"
         * to remind us that not all years and months
         * have the same length
         */
        ONEMAXYEAR: 316224e5,
        // 366 * ONEDAY
        ONEAVGYEAR: 315576e5,
        // 365.25 days
        ONEMINYEAR: 31536e6,
        // 365 * ONEDAY
        ONEMAXQUARTER: 79488e5,
        // 92 * ONEDAY
        ONEAVGQUARTER: 78894e5,
        // 1/4 of ONEAVGYEAR
        ONEMINQUARTER: 76896e5,
        // 89 * ONEDAY
        ONEMAXMONTH: 26784e5,
        // 31 * ONEDAY
        ONEAVGMONTH: 26298e5,
        // 1/12 of ONEAVGYEAR
        ONEMINMONTH: 24192e5,
        // 28 * ONEDAY
        ONEWEEK: 6048e5,
        // 7 * ONEDAY
        ONEDAY: 864e5,
        // 24 * ONEHOUR
        ONEHOUR: 36e5,
        ONEMIN: 6e4,
        ONESEC: 1e3,
        ONEMILLI: 1,
        ONEMICROSEC: 1e-3,
        /*
         * For fast conversion btwn world calendars and epoch ms, the Julian Day Number
         * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
         */
        EPOCHJD: 24405875e-1,
        /*
         * Are two values nearly equal? Compare to 1PPM
         */
        ALMOST_EQUAL: 1 - 1e-6,
        /*
         * If we're asked to clip a non-positive log value, how far off-screen
         * do we put it?
         */
        LOG_CLIP: 10,
        /*
         * not a number, but for displaying numbers: the "minus sign" symbol is
         * wider than the regular ascii dash "-"
         */
        MINUS_SIGN: "\u2212"
      };
    }
  });

  // node_modules/base64-arraybuffer/dist/base64-arraybuffer.umd.js
  var require_base64_arraybuffer_umd = __commonJS({
    "node_modules/base64-arraybuffer/dist/base64-arraybuffer.umd.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2["base64-arraybuffer"] = {}));
      })(exports, function(exports2) {
        "use strict";
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
        for (var i = 0; i < chars.length; i++) {
          lookup[chars.charCodeAt(i)] = i;
        }
        var encode = function(arraybuffer) {
          var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";
          for (i2 = 0; i2 < len; i2 += 3) {
            base64 += chars[bytes[i2] >> 2];
            base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
            base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
            base64 += chars[bytes[i2 + 2] & 63];
          }
          if (len % 3 === 2) {
            base64 = base64.substring(0, base64.length - 1) + "=";
          } else if (len % 3 === 1) {
            base64 = base64.substring(0, base64.length - 2) + "==";
          }
          return base64;
        };
        var decode = function(base64) {
          var bufferLength = base64.length * 0.75, len = base64.length, i2, p = 0, encoded1, encoded2, encoded3, encoded4;
          if (base64[base64.length - 1] === "=") {
            bufferLength--;
            if (base64[base64.length - 2] === "=") {
              bufferLength--;
            }
          }
          var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
          for (i2 = 0; i2 < len; i2 += 4) {
            encoded1 = lookup[base64.charCodeAt(i2)];
            encoded2 = lookup[base64.charCodeAt(i2 + 1)];
            encoded3 = lookup[base64.charCodeAt(i2 + 2)];
            encoded4 = lookup[base64.charCodeAt(i2 + 3)];
            bytes[p++] = encoded1 << 2 | encoded2 >> 4;
            bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
            bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
          }
          return arraybuffer;
        };
        exports2.decode = decode;
        exports2.encode = encode;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // src/lib/is_plain_object.js
  var require_is_plain_object = __commonJS({
    "src/lib/is_plain_object.js"(exports, module) {
      "use strict";
      module.exports = function isPlainObject(obj) {
        if (window && window.process && window.process.versions) {
          return Object.prototype.toString.call(obj) === "[object Object]";
        }
        return Object.prototype.toString.call(obj) === "[object Object]" && Object.getPrototypeOf(obj).hasOwnProperty("hasOwnProperty");
      };
    }
  });

  // src/lib/array.js
  var require_array = __commonJS({
    "src/lib/array.js"(exports) {
      "use strict";
      var b64decode = require_base64_arraybuffer_umd().decode;
      var isPlainObject = require_is_plain_object();
      var isArray = Array.isArray;
      var ab = ArrayBuffer;
      var dv = DataView;
      function isTypedArray(a) {
        return ab.isView(a) && !(a instanceof dv);
      }
      exports.isTypedArray = isTypedArray;
      function isArrayOrTypedArray(a) {
        return isArray(a) || isTypedArray(a);
      }
      exports.isArrayOrTypedArray = isArrayOrTypedArray;
      function isArray1D(a) {
        return !isArrayOrTypedArray(a[0]);
      }
      exports.isArray1D = isArray1D;
      exports.ensureArray = function(out, n) {
        if (!isArray(out)) out = [];
        out.length = n;
        return out;
      };
      var typedArrays = {
        u1c: typeof Uint8ClampedArray === "undefined" ? void 0 : Uint8ClampedArray,
        // not supported in numpy?
        i1: typeof Int8Array === "undefined" ? void 0 : Int8Array,
        u1: typeof Uint8Array === "undefined" ? void 0 : Uint8Array,
        i2: typeof Int16Array === "undefined" ? void 0 : Int16Array,
        u2: typeof Uint16Array === "undefined" ? void 0 : Uint16Array,
        i4: typeof Int32Array === "undefined" ? void 0 : Int32Array,
        u4: typeof Uint32Array === "undefined" ? void 0 : Uint32Array,
        f4: typeof Float32Array === "undefined" ? void 0 : Float32Array,
        f8: typeof Float64Array === "undefined" ? void 0 : Float64Array
        /* TODO: potentially add Big Int
        
            i8: typeof BigInt64Array === 'undefined' ? undefined :
                       BigInt64Array,
        
            u8: typeof BigUint64Array === 'undefined' ? undefined :
                       BigUint64Array,
            */
      };
      typedArrays.uint8c = typedArrays.u1c;
      typedArrays.uint8 = typedArrays.u1;
      typedArrays.int8 = typedArrays.i1;
      typedArrays.uint16 = typedArrays.u2;
      typedArrays.int16 = typedArrays.i2;
      typedArrays.uint32 = typedArrays.u4;
      typedArrays.int32 = typedArrays.i4;
      typedArrays.float32 = typedArrays.f4;
      typedArrays.float64 = typedArrays.f8;
      function isArrayBuffer(a) {
        return a.constructor === ArrayBuffer;
      }
      exports.isArrayBuffer = isArrayBuffer;
      exports.decodeTypedArraySpec = function(vIn) {
        var out = [];
        var v = coerceTypedArraySpec(vIn);
        var dtype = v.dtype;
        var T = typedArrays[dtype];
        if (!T) throw new Error('Error in dtype: "' + dtype + '"');
        var BYTES_PER_ELEMENT = T.BYTES_PER_ELEMENT;
        var buffer = v.bdata;
        if (!isArrayBuffer(buffer)) {
          buffer = b64decode(buffer);
        }
        var shape = v.shape === void 0 ? (
          // detect 1-d length
          [buffer.byteLength / BYTES_PER_ELEMENT]
        ) : (
          // convert number to string and split to array
          ("" + v.shape).split(",")
        );
        shape.reverse();
        var ndim = shape.length;
        var nj, j;
        var ni = +shape[0];
        var rowBytes = BYTES_PER_ELEMENT * ni;
        var pos = 0;
        if (ndim === 1) {
          out = new T(buffer);
        } else if (ndim === 2) {
          nj = +shape[1];
          for (j = 0; j < nj; j++) {
            out[j] = new T(buffer, pos, ni);
            pos += rowBytes;
          }
        } else if (ndim === 3) {
          nj = +shape[1];
          var nk = +shape[2];
          for (var k = 0; k < nk; k++) {
            out[k] = [];
            for (j = 0; j < nj; j++) {
              out[k][j] = new T(buffer, pos, ni);
              pos += rowBytes;
            }
          }
        } else {
          throw new Error("ndim: " + ndim + 'is not supported with the shape:"' + v.shape + '"');
        }
        out.bdata = v.bdata;
        out.dtype = v.dtype;
        out.shape = shape.reverse().join(",");
        vIn._inputArray = out;
        return out;
      };
      exports.isTypedArraySpec = function(v) {
        return isPlainObject(v) && v.hasOwnProperty("dtype") && typeof v.dtype === "string" && v.hasOwnProperty("bdata") && (typeof v.bdata === "string" || isArrayBuffer(v.bdata)) && (v.shape === void 0 || v.hasOwnProperty("shape") && (typeof v.shape === "string" || typeof v.shape === "number"));
      };
      function coerceTypedArraySpec(v) {
        return {
          bdata: v.bdata,
          dtype: v.dtype,
          shape: v.shape
        };
      }
      exports.concat = function() {
        var args = [];
        var allArray = true;
        var totalLen = 0;
        var _constructor, arg0, i, argi, posi, leni, out, j;
        for (i = 0; i < arguments.length; i++) {
          argi = arguments[i];
          leni = argi.length;
          if (leni) {
            if (arg0) args.push(argi);
            else {
              arg0 = argi;
              posi = leni;
            }
            if (isArray(argi)) {
              _constructor = false;
            } else {
              allArray = false;
              if (!totalLen) {
                _constructor = argi.constructor;
              } else if (_constructor !== argi.constructor) {
                _constructor = false;
              }
            }
            totalLen += leni;
          }
        }
        if (!totalLen) return [];
        if (!args.length) return arg0;
        if (allArray) return arg0.concat.apply(arg0, args);
        if (_constructor) {
          out = new _constructor(totalLen);
          out.set(arg0);
          for (i = 0; i < args.length; i++) {
            argi = args[i];
            out.set(argi, posi);
            posi += argi.length;
          }
          return out;
        }
        out = new Array(totalLen);
        for (j = 0; j < arg0.length; j++) out[j] = arg0[j];
        for (i = 0; i < args.length; i++) {
          argi = args[i];
          for (j = 0; j < argi.length; j++) out[posi + j] = argi[j];
          posi += j;
        }
        return out;
      };
      exports.maxRowLength = function(z) {
        return _rowLength(z, Math.max, 0);
      };
      exports.minRowLength = function(z) {
        return _rowLength(z, Math.min, Infinity);
      };
      function _rowLength(z, fn, len0) {
        if (isArrayOrTypedArray(z)) {
          if (isArrayOrTypedArray(z[0])) {
            var len = len0;
            for (var i = 0; i < z.length; i++) {
              len = fn(len, z[i].length);
            }
            return len;
          } else {
            return z.length;
          }
        }
        return 0;
      }
    }
  });

  // src/lib/nested_property.js
  var require_nested_property = __commonJS({
    "src/lib/nested_property.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var isArrayOrTypedArray = require_array().isArrayOrTypedArray;
      module.exports = function nestedProperty(container, propStr) {
        if (isNumeric(propStr)) propStr = String(propStr);
        else if (typeof propStr !== "string" || propStr.slice(-4) === "[-1]") {
          throw "bad property string";
        }
        var propParts = propStr.split(".");
        var indexed;
        var indices;
        var i, j;
        for (j = 0; j < propParts.length; j++) {
          if (String(propParts[j]).slice(0, 2) === "__") {
            throw "bad property string";
          }
        }
        j = 0;
        while (j < propParts.length) {
          indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
          if (indexed) {
            if (indexed[1]) propParts[j] = indexed[1];
            else if (j === 0) propParts.splice(0, 1);
            else throw "bad property string";
            indices = indexed[2].slice(1, -1).split("][");
            for (i = 0; i < indices.length; i++) {
              j++;
              propParts.splice(j, 0, Number(indices[i]));
            }
          }
          j++;
        }
        if (typeof container !== "object") {
          return badContainer(container, propStr, propParts);
        }
        return {
          set: npSet(container, propParts, propStr),
          get: npGet(container, propParts),
          astr: propStr,
          parts: propParts,
          obj: container
        };
      };
      function npGet(cont, parts) {
        return function(retainNull) {
          var curCont = cont;
          var curPart;
          var allSame;
          var out;
          var i;
          var j;
          for (i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];
            if (curPart === -1) {
              allSame = true;
              out = [];
              for (j = 0; j < curCont.length; j++) {
                out[j] = npGet(curCont[j], parts.slice(i + 1))(retainNull);
                if (out[j] !== out[0]) allSame = false;
              }
              return allSame ? out[0] : out;
            }
            if (typeof curPart === "number" && !isArrayOrTypedArray(curCont)) {
              return void 0;
            }
            curCont = curCont[curPart];
            if (typeof curCont !== "object" || curCont === null) {
              return void 0;
            }
          }
          if (typeof curCont !== "object" || curCont === null) return void 0;
          out = curCont[parts[i]];
          if (!retainNull && out === null) return void 0;
          return out;
        };
      }
      var ARGS_PATTERN = /(^|\.)args\[/;
      function isDeletable(val, propStr) {
        return val === void 0 || val === null && !propStr.match(ARGS_PATTERN);
      }
      function npSet(cont, parts, propStr) {
        return function(val) {
          var curCont = cont;
          var propPart = "";
          var containerLevels = [[cont, propPart]];
          var toDelete = isDeletable(val, propStr);
          var curPart;
          var i;
          for (i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];
            if (typeof curPart === "number" && !isArrayOrTypedArray(curCont)) {
              throw "array index but container is not an array";
            }
            if (curPart === -1) {
              toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
              if (toDelete) break;
              else return;
            }
            if (!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
              break;
            }
            curCont = curCont[curPart];
            if (typeof curCont !== "object" || curCont === null) {
              throw "container is not an object";
            }
            propPart = joinPropStr(propPart, curPart);
            containerLevels.push([curCont, propPart]);
          }
          if (toDelete) {
            if (i === parts.length - 1) {
              delete curCont[parts[i]];
              if (Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
                while (curCont.length && curCont[curCont.length - 1] === void 0) {
                  curCont.pop();
                }
              }
            }
          } else curCont[parts[i]] = val;
        };
      }
      function joinPropStr(propStr, newPart) {
        var toAdd = newPart;
        if (isNumeric(newPart)) toAdd = "[" + newPart + "]";
        else if (propStr) toAdd = "." + newPart;
        return propStr + toAdd;
      }
      function setArrayAll(containerArray, innerParts, val, propStr) {
        var arrayVal = isArrayOrTypedArray(val);
        var allSet = true;
        var thisVal = val;
        var thisPropStr = propStr.replace("-1", 0);
        var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr);
        var firstPart = innerParts[0];
        var i;
        for (i = 0; i < containerArray.length; i++) {
          thisPropStr = propStr.replace("-1", i);
          if (arrayVal) {
            thisVal = val[i % val.length];
            deleteThis = isDeletable(thisVal, thisPropStr);
          }
          if (deleteThis) allSet = false;
          if (!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
            continue;
          }
          npSet(containerArray[i], innerParts, propStr.replace("-1", i))(thisVal);
        }
        return allSet;
      }
      function checkNewContainer(container, part, nextPart, toDelete) {
        if (container[part] === void 0) {
          if (toDelete) return false;
          if (typeof nextPart === "number") container[part] = [];
          else container[part] = {};
        }
        return true;
      }
      function badContainer(container, propStr, propParts) {
        return {
          set: function() {
            throw "bad container";
          },
          get: function() {
          },
          astr: propStr,
          parts: propParts,
          obj: container
        };
      }
    }
  });

  // src/lib/keyed_container.js
  var require_keyed_container = __commonJS({
    "src/lib/keyed_container.js"(exports, module) {
      "use strict";
      var nestedProperty = require_nested_property();
      var SIMPLE_PROPERTY_REGEX = /^\w*$/;
      var NONE = 0;
      var NAME = 1;
      var VALUE = 2;
      var BOTH = 3;
      var UNSET = 4;
      module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
        keyName = keyName || "name";
        valueName = valueName || "value";
        var i, arr, baseProp;
        var changeTypes = {};
        if (path && path.length) {
          baseProp = nestedProperty(baseObj, path);
          arr = baseProp.get();
        } else {
          arr = baseObj;
        }
        path = path || "";
        var indexLookup = {};
        if (arr) {
          for (i = 0; i < arr.length; i++) {
            indexLookup[arr[i][keyName]] = i;
          }
        }
        var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);
        var obj = {
          set: function(name2, value) {
            var changeType = value === null ? UNSET : NONE;
            if (!arr) {
              if (!baseProp || changeType === UNSET) return;
              arr = [];
              baseProp.set(arr);
            }
            var idx = indexLookup[name2];
            if (idx === void 0) {
              if (changeType === UNSET) return;
              changeType = changeType | BOTH;
              idx = arr.length;
              indexLookup[name2] = idx;
            } else if (value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
              changeType = changeType | VALUE;
            }
            var newValue = arr[idx] = arr[idx] || {};
            newValue[keyName] = name2;
            if (isSimpleValueProp) {
              newValue[valueName] = value;
            } else {
              nestedProperty(newValue, valueName).set(value);
            }
            if (value !== null) {
              changeType = changeType & ~UNSET;
            }
            changeTypes[idx] = changeTypes[idx] | changeType;
            return obj;
          },
          get: function(name2) {
            if (!arr) return;
            var idx = indexLookup[name2];
            if (idx === void 0) {
              return void 0;
            } else if (isSimpleValueProp) {
              return arr[idx][valueName];
            } else {
              return nestedProperty(arr[idx], valueName).get();
            }
          },
          rename: function(name2, newName) {
            var idx = indexLookup[name2];
            if (idx === void 0) return obj;
            changeTypes[idx] = changeTypes[idx] | NAME;
            indexLookup[newName] = idx;
            delete indexLookup[name2];
            arr[idx][keyName] = newName;
            return obj;
          },
          remove: function(name2) {
            var idx = indexLookup[name2];
            if (idx === void 0) return obj;
            var object = arr[idx];
            if (Object.keys(object).length > 2) {
              changeTypes[idx] = changeTypes[idx] | VALUE;
              return obj.set(name2, null);
            }
            if (isSimpleValueProp) {
              for (i = idx; i < arr.length; i++) {
                changeTypes[i] = changeTypes[i] | BOTH;
              }
              for (i = idx; i < arr.length; i++) {
                indexLookup[arr[i][keyName]]--;
              }
              arr.splice(idx, 1);
              delete indexLookup[name2];
            } else {
              nestedProperty(object, valueName).set(null);
              changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
            }
            return obj;
          },
          constructUpdate: function() {
            var astr, idx;
            var update = {};
            var changed = Object.keys(changeTypes);
            for (var i2 = 0; i2 < changed.length; i2++) {
              idx = changed[i2];
              astr = path + "[" + idx + "]";
              if (arr[idx]) {
                if (changeTypes[idx] & NAME) {
                  update[astr + "." + keyName] = arr[idx][keyName];
                }
                if (changeTypes[idx] & VALUE) {
                  if (isSimpleValueProp) {
                    update[astr + "." + valueName] = changeTypes[idx] & UNSET ? null : arr[idx][valueName];
                  } else {
                    update[astr + "." + valueName] = changeTypes[idx] & UNSET ? null : nestedProperty(arr[idx], valueName).get();
                  }
                }
              } else {
                update[astr] = null;
              }
            }
            return update;
          }
        };
        return obj;
      };
    }
  });

  // src/lib/relative_attr.js
  var require_relative_attr = __commonJS({
    "src/lib/relative_attr.js"(exports, module) {
      "use strict";
      var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;
      var SIMPLEATTR = /^[^\.\[\]]+$/;
      module.exports = function(baseAttr, relativeAttr) {
        while (relativeAttr) {
          var match = baseAttr.match(ASCEND);
          if (match) baseAttr = match[1];
          else if (baseAttr.match(SIMPLEATTR)) baseAttr = "";
          else throw new Error("bad relativeAttr call:" + [baseAttr, relativeAttr]);
          if (relativeAttr.charAt(0) === "^") relativeAttr = relativeAttr.slice(1);
          else break;
        }
        if (baseAttr && relativeAttr.charAt(0) !== "[") {
          return baseAttr + "." + relativeAttr;
        }
        return baseAttr + relativeAttr;
      };
    }
  });

  // src/lib/to_log_range.js
  var require_to_log_range = __commonJS({
    "src/lib/to_log_range.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      module.exports = function toLogRange(val, range) {
        if (val > 0) return Math.log(val) / Math.LN10;
        var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
        if (!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
        return newVal;
      };
    }
  });

  // src/lib/relink_private.js
  var require_relink_private = __commonJS({
    "src/lib/relink_private.js"(exports, module) {
      "use strict";
      var isArrayOrTypedArray = require_array().isArrayOrTypedArray;
      var isPlainObject = require_is_plain_object();
      module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
        for (var k in fromContainer) {
          var fromVal = fromContainer[k];
          var toVal = toContainer[k];
          if (toVal === fromVal) continue;
          if (k.charAt(0) === "_" || typeof fromVal === "function") {
            if (k in toContainer) continue;
            toContainer[k] = fromVal;
          } else if (isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {
            if (k === "customdata" || k === "ids") continue;
            var minLen = Math.min(fromVal.length, toVal.length);
            for (var j = 0; j < minLen; j++) {
              if (toVal[j] !== fromVal[j] && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
                relinkPrivateKeys(toVal[j], fromVal[j]);
              }
            }
          } else if (isPlainObject(fromVal) && isPlainObject(toVal)) {
            relinkPrivateKeys(toVal, fromVal);
            if (!Object.keys(toVal).length) delete toContainer[k];
          }
        }
      };
    }
  });

  // src/lib/mod.js
  var require_mod = __commonJS({
    "src/lib/mod.js"(exports, module) {
      "use strict";
      function mod(v, d) {
        var out = v % d;
        return out < 0 ? out + d : out;
      }
      function modHalf(v, d) {
        return Math.abs(v) > d / 2 ? v - Math.round(v / d) * d : v;
      }
      module.exports = {
        mod,
        modHalf
      };
    }
  });

  // node_modules/tinycolor2/tinycolor.js
  var require_tinycolor = __commonJS({
    "node_modules/tinycolor2/tinycolor.js"(exports, module) {
      (function(Math2) {
        var trimLeft = /^\s+/, trimRight = /\s+$/, tinyCounter = 0, mathRound = Math2.round, mathMin = Math2.min, mathMax = Math2.max, mathRandom = Math2.random;
        function tinycolor(color2, opts) {
          color2 = color2 ? color2 : "";
          opts = opts || {};
          if (color2 instanceof tinycolor) {
            return color2;
          }
          if (!(this instanceof tinycolor)) {
            return new tinycolor(color2, opts);
          }
          var rgb2 = inputToRGB(color2);
          this._originalInput = color2, this._r = rgb2.r, this._g = rgb2.g, this._b = rgb2.b, this._a = rgb2.a, this._roundA = mathRound(100 * this._a) / 100, this._format = opts.format || rgb2.format;
          this._gradientType = opts.gradientType;
          if (this._r < 1) {
            this._r = mathRound(this._r);
          }
          if (this._g < 1) {
            this._g = mathRound(this._g);
          }
          if (this._b < 1) {
            this._b = mathRound(this._b);
          }
          this._ok = rgb2.ok;
          this._tc_id = tinyCounter++;
        }
        tinycolor.prototype = {
          isDark: function() {
            return this.getBrightness() < 128;
          },
          isLight: function() {
            return !this.isDark();
          },
          isValid: function() {
            return this._ok;
          },
          getOriginalInput: function() {
            return this._originalInput;
          },
          getFormat: function() {
            return this._format;
          },
          getAlpha: function() {
            return this._a;
          },
          getBrightness: function() {
            var rgb2 = this.toRgb();
            return (rgb2.r * 299 + rgb2.g * 587 + rgb2.b * 114) / 1e3;
          },
          getLuminance: function() {
            var rgb2 = this.toRgb();
            var RsRGB, GsRGB, BsRGB, R, G, B2;
            RsRGB = rgb2.r / 255;
            GsRGB = rgb2.g / 255;
            BsRGB = rgb2.b / 255;
            if (RsRGB <= 0.03928) {
              R = RsRGB / 12.92;
            } else {
              R = Math2.pow((RsRGB + 0.055) / 1.055, 2.4);
            }
            if (GsRGB <= 0.03928) {
              G = GsRGB / 12.92;
            } else {
              G = Math2.pow((GsRGB + 0.055) / 1.055, 2.4);
            }
            if (BsRGB <= 0.03928) {
              B2 = BsRGB / 12.92;
            } else {
              B2 = Math2.pow((BsRGB + 0.055) / 1.055, 2.4);
            }
            return 0.2126 * R + 0.7152 * G + 0.0722 * B2;
          },
          setAlpha: function(value) {
            this._a = boundAlpha(value);
            this._roundA = mathRound(100 * this._a) / 100;
            return this;
          },
          toHsv: function() {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
          },
          toHsvString: function() {
            var hsv = rgbToHsv(this._r, this._g, this._b);
            var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
            return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")";
          },
          toHsl: function() {
            var hsl3 = rgbToHsl(this._r, this._g, this._b);
            return { h: hsl3.h * 360, s: hsl3.s, l: hsl3.l, a: this._a };
          },
          toHslString: function() {
            var hsl3 = rgbToHsl(this._r, this._g, this._b);
            var h = mathRound(hsl3.h * 360), s = mathRound(hsl3.s * 100), l = mathRound(hsl3.l * 100);
            return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")";
          },
          toHex: function(allow3Char) {
            return rgbToHex(this._r, this._g, this._b, allow3Char);
          },
          toHexString: function(allow3Char) {
            return "#" + this.toHex(allow3Char);
          },
          toHex8: function(allow4Char) {
            return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
          },
          toHex8String: function(allow4Char) {
            return "#" + this.toHex8(allow4Char);
          },
          toRgb: function() {
            return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
          },
          toRgbString: function() {
            return this._a == 1 ? "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
          },
          toPercentageRgb: function() {
            return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
          },
          toPercentageRgbString: function() {
            return this._a == 1 ? "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
          },
          toName: function() {
            if (this._a === 0) {
              return "transparent";
            }
            if (this._a < 1) {
              return false;
            }
            return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
          },
          toFilter: function(secondColor) {
            var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a);
            var secondHex8String = hex8String;
            var gradientType = this._gradientType ? "GradientType = 1, " : "";
            if (secondColor) {
              var s = tinycolor(secondColor);
              secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a);
            }
            return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")";
          },
          toString: function(format) {
            var formatSet = !!format;
            format = format || this._format;
            var formattedString = false;
            var hasAlpha = this._a < 1 && this._a >= 0;
            var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
            if (needsAlphaFormat) {
              if (format === "name" && this._a === 0) {
                return this.toName();
              }
              return this.toRgbString();
            }
            if (format === "rgb") {
              formattedString = this.toRgbString();
            }
            if (format === "prgb") {
              formattedString = this.toPercentageRgbString();
            }
            if (format === "hex" || format === "hex6") {
              formattedString = this.toHexString();
            }
            if (format === "hex3") {
              formattedString = this.toHexString(true);
            }
            if (format === "hex4") {
              formattedString = this.toHex8String(true);
            }
            if (format === "hex8") {
              formattedString = this.toHex8String();
            }
            if (format === "name") {
              formattedString = this.toName();
            }
            if (format === "hsl") {
              formattedString = this.toHslString();
            }
            if (format === "hsv") {
              formattedString = this.toHsvString();
            }
            return formattedString || this.toHexString();
          },
          clone: function() {
            return tinycolor(this.toString());
          },
          _applyModification: function(fn, args) {
            var color2 = fn.apply(null, [this].concat([].slice.call(args)));
            this._r = color2._r;
            this._g = color2._g;
            this._b = color2._b;
            this.setAlpha(color2._a);
            return this;
          },
          lighten: function() {
            return this._applyModification(lighten, arguments);
          },
          brighten: function() {
            return this._applyModification(brighten, arguments);
          },
          darken: function() {
            return this._applyModification(darken, arguments);
          },
          desaturate: function() {
            return this._applyModification(desaturate, arguments);
          },
          saturate: function() {
            return this._applyModification(saturate, arguments);
          },
          greyscale: function() {
            return this._applyModification(greyscale, arguments);
          },
          spin: function() {
            return this._applyModification(spin, arguments);
          },
          _applyCombination: function(fn, args) {
            return fn.apply(null, [this].concat([].slice.call(args)));
          },
          analogous: function() {
            return this._applyCombination(analogous, arguments);
          },
          complement: function() {
            return this._applyCombination(complement, arguments);
          },
          monochromatic: function() {
            return this._applyCombination(monochromatic, arguments);
          },
          splitcomplement: function() {
            return this._applyCombination(splitcomplement, arguments);
          },
          triad: function() {
            return this._applyCombination(triad, arguments);
          },
          tetrad: function() {
            return this._applyCombination(tetrad, arguments);
          }
        };
        tinycolor.fromRatio = function(color2, opts) {
          if (typeof color2 == "object") {
            var newColor = {};
            for (var i in color2) {
              if (color2.hasOwnProperty(i)) {
                if (i === "a") {
                  newColor[i] = color2[i];
                } else {
                  newColor[i] = convertToPercentage(color2[i]);
                }
              }
            }
            color2 = newColor;
          }
          return tinycolor(color2, opts);
        };
        function inputToRGB(color2) {
          var rgb2 = { r: 0, g: 0, b: 0 };
          var a = 1;
          var s = null;
          var v = null;
          var l = null;
          var ok = false;
          var format = false;
          if (typeof color2 == "string") {
            color2 = stringInputToObject(color2);
          }
          if (typeof color2 == "object") {
            if (isValidCSSUnit(color2.r) && isValidCSSUnit(color2.g) && isValidCSSUnit(color2.b)) {
              rgb2 = rgbToRgb(color2.r, color2.g, color2.b);
              ok = true;
              format = String(color2.r).substr(-1) === "%" ? "prgb" : "rgb";
            } else if (isValidCSSUnit(color2.h) && isValidCSSUnit(color2.s) && isValidCSSUnit(color2.v)) {
              s = convertToPercentage(color2.s);
              v = convertToPercentage(color2.v);
              rgb2 = hsvToRgb(color2.h, s, v);
              ok = true;
              format = "hsv";
            } else if (isValidCSSUnit(color2.h) && isValidCSSUnit(color2.s) && isValidCSSUnit(color2.l)) {
              s = convertToPercentage(color2.s);
              l = convertToPercentage(color2.l);
              rgb2 = hslToRgb(color2.h, s, l);
              ok = true;
              format = "hsl";
            }
            if (color2.hasOwnProperty("a")) {
              a = color2.a;
            }
          }
          a = boundAlpha(a);
          return {
            ok,
            format: color2.format || format,
            r: mathMin(255, mathMax(rgb2.r, 0)),
            g: mathMin(255, mathMax(rgb2.g, 0)),
            b: mathMin(255, mathMax(rgb2.b, 0)),
            a
          };
        }
        function rgbToRgb(r, g, b) {
          return {
            r: bound01(r, 255) * 255,
            g: bound01(g, 255) * 255,
            b: bound01(b, 255) * 255
          };
        }
        function rgbToHsl(r, g, b) {
          r = bound01(r, 255);
          g = bound01(g, 255);
          b = bound01(b, 255);
          var max = mathMax(r, g, b), min = mathMin(r, g, b);
          var h, s, l = (max + min) / 2;
          if (max == min) {
            h = s = 0;
          } else {
            var d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
              case r:
                h = (g - b) / d + (g < b ? 6 : 0);
                break;
              case g:
                h = (b - r) / d + 2;
                break;
              case b:
                h = (r - g) / d + 4;
                break;
            }
            h /= 6;
          }
          return { h, s, l };
        }
        function hslToRgb(h, s, l) {
          var r, g, b;
          h = bound01(h, 360);
          s = bound01(s, 100);
          l = bound01(l, 100);
          function hue2rgb(p2, q2, t) {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1 / 6) return p2 + (q2 - p2) * 6 * t;
            if (t < 1 / 2) return q2;
            if (t < 2 / 3) return p2 + (q2 - p2) * (2 / 3 - t) * 6;
            return p2;
          }
          if (s === 0) {
            r = g = b = l;
          } else {
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
          }
          return { r: r * 255, g: g * 255, b: b * 255 };
        }
        function rgbToHsv(r, g, b) {
          r = bound01(r, 255);
          g = bound01(g, 255);
          b = bound01(b, 255);
          var max = mathMax(r, g, b), min = mathMin(r, g, b);
          var h, s, v = max;
          var d = max - min;
          s = max === 0 ? 0 : d / max;
          if (max == min) {
            h = 0;
          } else {
            switch (max) {
              case r:
                h = (g - b) / d + (g < b ? 6 : 0);
                break;
              case g:
                h = (b - r) / d + 2;
                break;
              case b:
                h = (r - g) / d + 4;
                break;
            }
            h /= 6;
          }
          return { h, s, v };
        }
        function hsvToRgb(h, s, v) {
          h = bound01(h, 360) * 6;
          s = bound01(s, 100);
          v = bound01(v, 100);
          var i = Math2.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod];
          return { r: r * 255, g: g * 255, b: b * 255 };
        }
        function rgbToHex(r, g, b, allow3Char) {
          var hex2 = [
            pad2(mathRound(r).toString(16)),
            pad2(mathRound(g).toString(16)),
            pad2(mathRound(b).toString(16))
          ];
          if (allow3Char && hex2[0].charAt(0) == hex2[0].charAt(1) && hex2[1].charAt(0) == hex2[1].charAt(1) && hex2[2].charAt(0) == hex2[2].charAt(1)) {
            return hex2[0].charAt(0) + hex2[1].charAt(0) + hex2[2].charAt(0);
          }
          return hex2.join("");
        }
        function rgbaToHex(r, g, b, a, allow4Char) {
          var hex2 = [
            pad2(mathRound(r).toString(16)),
            pad2(mathRound(g).toString(16)),
            pad2(mathRound(b).toString(16)),
            pad2(convertDecimalToHex(a))
          ];
          if (allow4Char && hex2[0].charAt(0) == hex2[0].charAt(1) && hex2[1].charAt(0) == hex2[1].charAt(1) && hex2[2].charAt(0) == hex2[2].charAt(1) && hex2[3].charAt(0) == hex2[3].charAt(1)) {
            return hex2[0].charAt(0) + hex2[1].charAt(0) + hex2[2].charAt(0) + hex2[3].charAt(0);
          }
          return hex2.join("");
        }
        function rgbaToArgbHex(r, g, b, a) {
          var hex2 = [
            pad2(convertDecimalToHex(a)),
            pad2(mathRound(r).toString(16)),
            pad2(mathRound(g).toString(16)),
            pad2(mathRound(b).toString(16))
          ];
          return hex2.join("");
        }
        tinycolor.equals = function(color1, color2) {
          if (!color1 || !color2) {
            return false;
          }
          return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
        };
        tinycolor.random = function() {
          return tinycolor.fromRatio({
            r: mathRandom(),
            g: mathRandom(),
            b: mathRandom()
          });
        };
        function desaturate(color2, amount) {
          amount = amount === 0 ? 0 : amount || 10;
          var hsl3 = tinycolor(color2).toHsl();
          hsl3.s -= amount / 100;
          hsl3.s = clamp01(hsl3.s);
          return tinycolor(hsl3);
        }
        function saturate(color2, amount) {
          amount = amount === 0 ? 0 : amount || 10;
          var hsl3 = tinycolor(color2).toHsl();
          hsl3.s += amount / 100;
          hsl3.s = clamp01(hsl3.s);
          return tinycolor(hsl3);
        }
        function greyscale(color2) {
          return tinycolor(color2).desaturate(100);
        }
        function lighten(color2, amount) {
          amount = amount === 0 ? 0 : amount || 10;
          var hsl3 = tinycolor(color2).toHsl();
          hsl3.l += amount / 100;
          hsl3.l = clamp01(hsl3.l);
          return tinycolor(hsl3);
        }
        function brighten(color2, amount) {
          amount = amount === 0 ? 0 : amount || 10;
          var rgb2 = tinycolor(color2).toRgb();
          rgb2.r = mathMax(0, mathMin(255, rgb2.r - mathRound(255 * -(amount / 100))));
          rgb2.g = mathMax(0, mathMin(255, rgb2.g - mathRound(255 * -(amount / 100))));
          rgb2.b = mathMax(0, mathMin(255, rgb2.b - mathRound(255 * -(amount / 100))));
          return tinycolor(rgb2);
        }
        function darken(color2, amount) {
          amount = amount === 0 ? 0 : amount || 10;
          var hsl3 = tinycolor(color2).toHsl();
          hsl3.l -= amount / 100;
          hsl3.l = clamp01(hsl3.l);
          return tinycolor(hsl3);
        }
        function spin(color2, amount) {
          var hsl3 = tinycolor(color2).toHsl();
          var hue2 = (hsl3.h + amount) % 360;
          hsl3.h = hue2 < 0 ? 360 + hue2 : hue2;
          return tinycolor(hsl3);
        }
        function complement(color2) {
          var hsl3 = tinycolor(color2).toHsl();
          hsl3.h = (hsl3.h + 180) % 360;
          return tinycolor(hsl3);
        }
        function triad(color2) {
          var hsl3 = tinycolor(color2).toHsl();
          var h = hsl3.h;
          return [
            tinycolor(color2),
            tinycolor({ h: (h + 120) % 360, s: hsl3.s, l: hsl3.l }),
            tinycolor({ h: (h + 240) % 360, s: hsl3.s, l: hsl3.l })
          ];
        }
        function tetrad(color2) {
          var hsl3 = tinycolor(color2).toHsl();
          var h = hsl3.h;
          return [
            tinycolor(color2),
            tinycolor({ h: (h + 90) % 360, s: hsl3.s, l: hsl3.l }),
            tinycolor({ h: (h + 180) % 360, s: hsl3.s, l: hsl3.l }),
            tinycolor({ h: (h + 270) % 360, s: hsl3.s, l: hsl3.l })
          ];
        }
        function splitcomplement(color2) {
          var hsl3 = tinycolor(color2).toHsl();
          var h = hsl3.h;
          return [
            tinycolor(color2),
            tinycolor({ h: (h + 72) % 360, s: hsl3.s, l: hsl3.l }),
            tinycolor({ h: (h + 216) % 360, s: hsl3.s, l: hsl3.l })
          ];
        }
        function analogous(color2, results, slices) {
          results = results || 6;
          slices = slices || 30;
          var hsl3 = tinycolor(color2).toHsl();
          var part = 360 / slices;
          var ret = [tinycolor(color2)];
          for (hsl3.h = (hsl3.h - (part * results >> 1) + 720) % 360; --results; ) {
            hsl3.h = (hsl3.h + part) % 360;
            ret.push(tinycolor(hsl3));
          }
          return ret;
        }
        function monochromatic(color2, results) {
          results = results || 6;
          var hsv = tinycolor(color2).toHsv();
          var h = hsv.h, s = hsv.s, v = hsv.v;
          var ret = [];
          var modification = 1 / results;
          while (results--) {
            ret.push(tinycolor({ h, s, v }));
            v = (v + modification) % 1;
          }
          return ret;
        }
        tinycolor.mix = function(color1, color2, amount) {
          amount = amount === 0 ? 0 : amount || 50;
          var rgb1 = tinycolor(color1).toRgb();
          var rgb2 = tinycolor(color2).toRgb();
          var p = amount / 100;
          var rgba3 = {
            r: (rgb2.r - rgb1.r) * p + rgb1.r,
            g: (rgb2.g - rgb1.g) * p + rgb1.g,
            b: (rgb2.b - rgb1.b) * p + rgb1.b,
            a: (rgb2.a - rgb1.a) * p + rgb1.a
          };
          return tinycolor(rgba3);
        };
        tinycolor.readability = function(color1, color2) {
          var c1 = tinycolor(color1);
          var c2 = tinycolor(color2);
          return (Math2.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math2.min(c1.getLuminance(), c2.getLuminance()) + 0.05);
        };
        tinycolor.isReadable = function(color1, color2, wcag2) {
          var readability = tinycolor.readability(color1, color2);
          var wcag2Parms, out;
          out = false;
          wcag2Parms = validateWCAG2Parms(wcag2);
          switch (wcag2Parms.level + wcag2Parms.size) {
            case "AAsmall":
            case "AAAlarge":
              out = readability >= 4.5;
              break;
            case "AAlarge":
              out = readability >= 3;
              break;
            case "AAAsmall":
              out = readability >= 7;
              break;
          }
          return out;
        };
        tinycolor.mostReadable = function(baseColor, colorList, args) {
          var bestColor = null;
          var bestScore = 0;
          var readability;
          var includeFallbackColors, level, size;
          args = args || {};
          includeFallbackColors = args.includeFallbackColors;
          level = args.level;
          size = args.size;
          for (var i = 0; i < colorList.length; i++) {
            readability = tinycolor.readability(baseColor, colorList[i]);
            if (readability > bestScore) {
              bestScore = readability;
              bestColor = tinycolor(colorList[i]);
            }
          }
          if (tinycolor.isReadable(baseColor, bestColor, { "level": level, "size": size }) || !includeFallbackColors) {
            return bestColor;
          } else {
            args.includeFallbackColors = false;
            return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args);
          }
        };
        var names2 = tinycolor.names = {
          aliceblue: "f0f8ff",
          antiquewhite: "faebd7",
          aqua: "0ff",
          aquamarine: "7fffd4",
          azure: "f0ffff",
          beige: "f5f5dc",
          bisque: "ffe4c4",
          black: "000",
          blanchedalmond: "ffebcd",
          blue: "00f",
          blueviolet: "8a2be2",
          brown: "a52a2a",
          burlywood: "deb887",
          burntsienna: "ea7e5d",
          cadetblue: "5f9ea0",
          chartreuse: "7fff00",
          chocolate: "d2691e",
          coral: "ff7f50",
          cornflowerblue: "6495ed",
          cornsilk: "fff8dc",
          crimson: "dc143c",
          cyan: "0ff",
          darkblue: "00008b",
          darkcyan: "008b8b",
          darkgoldenrod: "b8860b",
          darkgray: "a9a9a9",
          darkgreen: "006400",
          darkgrey: "a9a9a9",
          darkkhaki: "bdb76b",
          darkmagenta: "8b008b",
          darkolivegreen: "556b2f",
          darkorange: "ff8c00",
          darkorchid: "9932cc",
          darkred: "8b0000",
          darksalmon: "e9967a",
          darkseagreen: "8fbc8f",
          darkslateblue: "483d8b",
          darkslategray: "2f4f4f",
          darkslategrey: "2f4f4f",
          darkturquoise: "00ced1",
          darkviolet: "9400d3",
          deeppink: "ff1493",
          deepskyblue: "00bfff",
          dimgray: "696969",
          dimgrey: "696969",
          dodgerblue: "1e90ff",
          firebrick: "b22222",
          floralwhite: "fffaf0",
          forestgreen: "228b22",
          fuchsia: "f0f",
          gainsboro: "dcdcdc",
          ghostwhite: "f8f8ff",
          gold: "ffd700",
          goldenrod: "daa520",
          gray: "808080",
          green: "008000",
          greenyellow: "adff2f",
          grey: "808080",
          honeydew: "f0fff0",
          hotpink: "ff69b4",
          indianred: "cd5c5c",
          indigo: "4b0082",
          ivory: "fffff0",
          khaki: "f0e68c",
          lavender: "e6e6fa",
          lavenderblush: "fff0f5",
          lawngreen: "7cfc00",
          lemonchiffon: "fffacd",
          lightblue: "add8e6",
          lightcoral: "f08080",
          lightcyan: "e0ffff",
          lightgoldenrodyellow: "fafad2",
          lightgray: "d3d3d3",
          lightgreen: "90ee90",
          lightgrey: "d3d3d3",
          lightpink: "ffb6c1",
          lightsalmon: "ffa07a",
          lightseagreen: "20b2aa",
          lightskyblue: "87cefa",
          lightslategray: "789",
          lightslategrey: "789",
          lightsteelblue: "b0c4de",
          lightyellow: "ffffe0",
          lime: "0f0",
          limegreen: "32cd32",
          linen: "faf0e6",
          magenta: "f0f",
          maroon: "800000",
          mediumaquamarine: "66cdaa",
          mediumblue: "0000cd",
          mediumorchid: "ba55d3",
          mediumpurple: "9370db",
          mediumseagreen: "3cb371",
          mediumslateblue: "7b68ee",
          mediumspringgreen: "00fa9a",
          mediumturquoise: "48d1cc",
          mediumvioletred: "c71585",
          midnightblue: "191970",
          mintcream: "f5fffa",
          mistyrose: "ffe4e1",
          moccasin: "ffe4b5",
          navajowhite: "ffdead",
          navy: "000080",
          oldlace: "fdf5e6",
          olive: "808000",
          olivedrab: "6b8e23",
          orange: "ffa500",
          orangered: "ff4500",
          orchid: "da70d6",
          palegoldenrod: "eee8aa",
          palegreen: "98fb98",
          paleturquoise: "afeeee",
          palevioletred: "db7093",
          papayawhip: "ffefd5",
          peachpuff: "ffdab9",
          peru: "cd853f",
          pink: "ffc0cb",
          plum: "dda0dd",
          powderblue: "b0e0e6",
          purple: "800080",
          rebeccapurple: "663399",
          red: "f00",
          rosybrown: "bc8f8f",
          royalblue: "4169e1",
          saddlebrown: "8b4513",
          salmon: "fa8072",
          sandybrown: "f4a460",
          seagreen: "2e8b57",
          seashell: "fff5ee",
          sienna: "a0522d",
          silver: "c0c0c0",
          skyblue: "87ceeb",
          slateblue: "6a5acd",
          slategray: "708090",
          slategrey: "708090",
          snow: "fffafa",
          springgreen: "00ff7f",
          steelblue: "4682b4",
          tan: "d2b48c",
          teal: "008080",
          thistle: "d8bfd8",
          tomato: "ff6347",
          turquoise: "40e0d0",
          violet: "ee82ee",
          wheat: "f5deb3",
          white: "fff",
          whitesmoke: "f5f5f5",
          yellow: "ff0",
          yellowgreen: "9acd32"
        };
        var hexNames = tinycolor.hexNames = flip(names2);
        function flip(o) {
          var flipped = {};
          for (var i in o) {
            if (o.hasOwnProperty(i)) {
              flipped[o[i]] = i;
            }
          }
          return flipped;
        }
        function boundAlpha(a) {
          a = parseFloat(a);
          if (isNaN(a) || a < 0 || a > 1) {
            a = 1;
          }
          return a;
        }
        function bound01(n, max) {
          if (isOnePointZero(n)) {
            n = "100%";
          }
          var processPercent = isPercentage(n);
          n = mathMin(max, mathMax(0, parseFloat(n)));
          if (processPercent) {
            n = parseInt(n * max, 10) / 100;
          }
          if (Math2.abs(n - max) < 1e-6) {
            return 1;
          }
          return n % max / parseFloat(max);
        }
        function clamp01(val) {
          return mathMin(1, mathMax(0, val));
        }
        function parseIntFromHex(val) {
          return parseInt(val, 16);
        }
        function isOnePointZero(n) {
          return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1;
        }
        function isPercentage(n) {
          return typeof n === "string" && n.indexOf("%") != -1;
        }
        function pad2(c) {
          return c.length == 1 ? "0" + c : "" + c;
        }
        function convertToPercentage(n) {
          if (n <= 1) {
            n = n * 100 + "%";
          }
          return n;
        }
        function convertDecimalToHex(d) {
          return Math2.round(parseFloat(d) * 255).toString(16);
        }
        function convertHexToDecimal(h) {
          return parseIntFromHex(h) / 255;
        }
        var matchers = function() {
          var CSS_INTEGER = "[-\\+]?\\d+%?";
          var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
          var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
          var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
          var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
          return {
            CSS_UNIT: new RegExp(CSS_UNIT),
            rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
            rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
            hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
            hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
            hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
            hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
            hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
            hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
            hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
            hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
          };
        }();
        function isValidCSSUnit(color2) {
          return !!matchers.CSS_UNIT.exec(color2);
        }
        function stringInputToObject(color2) {
          color2 = color2.replace(trimLeft, "").replace(trimRight, "").toLowerCase();
          var named2 = false;
          if (names2[color2]) {
            color2 = names2[color2];
            named2 = true;
          } else if (color2 == "transparent") {
            return { r: 0, g: 0, b: 0, a: 0, format: "name" };
          }
          var match;
          if (match = matchers.rgb.exec(color2)) {
            return { r: match[1], g: match[2], b: match[3] };
          }
          if (match = matchers.rgba.exec(color2)) {
            return { r: match[1], g: match[2], b: match[3], a: match[4] };
          }
          if (match = matchers.hsl.exec(color2)) {
            return { h: match[1], s: match[2], l: match[3] };
          }
          if (match = matchers.hsla.exec(color2)) {
            return { h: match[1], s: match[2], l: match[3], a: match[4] };
          }
          if (match = matchers.hsv.exec(color2)) {
            return { h: match[1], s: match[2], v: match[3] };
          }
          if (match = matchers.hsva.exec(color2)) {
            return { h: match[1], s: match[2], v: match[3], a: match[4] };
          }
          if (match = matchers.hex8.exec(color2)) {
            return {
              r: parseIntFromHex(match[1]),
              g: parseIntFromHex(match[2]),
              b: parseIntFromHex(match[3]),
              a: convertHexToDecimal(match[4]),
              format: named2 ? "name" : "hex8"
            };
          }
          if (match = matchers.hex6.exec(color2)) {
            return {
              r: parseIntFromHex(match[1]),
              g: parseIntFromHex(match[2]),
              b: parseIntFromHex(match[3]),
              format: named2 ? "name" : "hex"
            };
          }
          if (match = matchers.hex4.exec(color2)) {
            return {
              r: parseIntFromHex(match[1] + "" + match[1]),
              g: parseIntFromHex(match[2] + "" + match[2]),
              b: parseIntFromHex(match[3] + "" + match[3]),
              a: convertHexToDecimal(match[4] + "" + match[4]),
              format: named2 ? "name" : "hex8"
            };
          }
          if (match = matchers.hex3.exec(color2)) {
            return {
              r: parseIntFromHex(match[1] + "" + match[1]),
              g: parseIntFromHex(match[2] + "" + match[2]),
              b: parseIntFromHex(match[3] + "" + match[3]),
              format: named2 ? "name" : "hex"
            };
          }
          return false;
        }
        function validateWCAG2Parms(parms) {
          var level, size;
          parms = parms || { "level": "AA", "size": "small" };
          level = (parms.level || "AA").toUpperCase();
          size = (parms.size || "small").toLowerCase();
          if (level !== "AA" && level !== "AAA") {
            level = "AA";
          }
          if (size !== "small" && size !== "large") {
            size = "small";
          }
          return { "level": level, "size": size };
        }
        if (typeof module !== "undefined" && module.exports) {
          module.exports = tinycolor;
        } else if (typeof define === "function" && false) {
          define(function() {
            return tinycolor;
          });
        } else {
          window.tinycolor = tinycolor;
        }
      })(Math);
    }
  });

  // src/lib/extend.js
  var require_extend = __commonJS({
    "src/lib/extend.js"(exports) {
      "use strict";
      var isPlainObject = require_is_plain_object();
      var isArray = Array.isArray;
      function primitivesLoopSplice(source, target) {
        var i, value;
        for (i = 0; i < source.length; i++) {
          value = source[i];
          if (value !== null && typeof value === "object") {
            return false;
          }
          if (value !== void 0) {
            target[i] = value;
          }
        }
        return true;
      }
      exports.extendFlat = function() {
        return _extend(arguments, false, false, false);
      };
      exports.extendDeep = function() {
        return _extend(arguments, true, false, false);
      };
      exports.extendDeepAll = function() {
        return _extend(arguments, true, true, false);
      };
      exports.extendDeepNoArrays = function() {
        return _extend(arguments, true, false, true);
      };
      function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
        var target = inputs[0];
        var length = inputs.length;
        var input, key, src, copy, copyIsArray, clone, allPrimitives;
        if (length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {
          allPrimitives = primitivesLoopSplice(inputs[1], target);
          if (allPrimitives) {
            return target;
          } else {
            target.splice(0, target.length);
          }
        }
        for (var i = 1; i < length; i++) {
          input = inputs[i];
          for (key in input) {
            src = target[key];
            copy = input[key];
            if (noArrayCopies && isArray(copy)) {
              target[key] = copy;
            } else if (isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
              if (copyIsArray) {
                copyIsArray = false;
                clone = src && isArray(src) ? src : [];
              } else {
                clone = src && isPlainObject(src) ? src : {};
              }
              target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
            } else if (typeof copy !== "undefined" || keepAllKeys) {
              target[key] = copy;
            }
          }
        }
        return target;
      }
    }
  });

  // src/plots/font_attributes.js
  var require_font_attributes = __commonJS({
    "src/plots/font_attributes.js"(exports, module) {
      "use strict";
      module.exports = function(opts) {
        var variantValues = opts.variantValues;
        var editType = opts.editType;
        var colorEditType = opts.colorEditType;
        if (colorEditType === void 0) colorEditType = editType;
        var weight = {
          editType,
          valType: "integer",
          min: 1,
          max: 1e3,
          extras: ["normal", "bold"],
          dflt: "normal"
        };
        if (opts.noNumericWeightValues) {
          weight.valType = "enumerated";
          weight.values = weight.extras;
          weight.extras = void 0;
          weight.min = void 0;
          weight.max = void 0;
        }
        var attrs = {
          family: {
            valType: "string",
            noBlank: true,
            strict: true,
            editType
          },
          size: {
            valType: "number",
            min: 1,
            editType
          },
          color: {
            valType: "color",
            editType: colorEditType
          },
          weight,
          style: {
            editType,
            valType: "enumerated",
            values: ["normal", "italic"],
            dflt: "normal"
          },
          variant: opts.noFontVariant ? void 0 : {
            editType,
            valType: "enumerated",
            values: variantValues || [
              "normal",
              "small-caps",
              "all-small-caps",
              "all-petite-caps",
              "petite-caps",
              "unicase"
            ],
            dflt: "normal"
          },
          textcase: opts.noFontTextcase ? void 0 : {
            editType,
            valType: "enumerated",
            values: ["normal", "word caps", "upper", "lower"],
            dflt: "normal"
          },
          lineposition: opts.noFontLineposition ? void 0 : {
            editType,
            valType: "flaglist",
            flags: ["under", "over", "through"],
            extras: ["none"],
            dflt: "none"
          },
          shadow: opts.noFontShadow ? void 0 : {
            editType,
            valType: "string",
            dflt: opts.autoShadowDflt ? "auto" : "none"
          },
          editType
          // blank strings so compress_attributes can remove
          // TODO - that's uber hacky... better solution?
        };
        if (opts.autoSize) attrs.size.dflt = "auto";
        if (opts.autoColor) attrs.color.dflt = "auto";
        if (opts.arrayOk) {
          attrs.family.arrayOk = true;
          attrs.weight.arrayOk = true;
          attrs.style.arrayOk = true;
          if (!opts.noFontVariant) {
            attrs.variant.arrayOk = true;
          }
          if (!opts.noFontTextcase) {
            attrs.textcase.arrayOk = true;
          }
          if (!opts.noFontLineposition) {
            attrs.lineposition.arrayOk = true;
          }
          if (!opts.noFontShadow) {
            attrs.shadow.arrayOk = true;
          }
          attrs.size.arrayOk = true;
          attrs.color.arrayOk = true;
        }
        return attrs;
      };
    }
  });

  // src/components/fx/constants.js
  var require_constants = __commonJS({
    "src/components/fx/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // hover labels for multiple horizontal bars get tilted by this angle
        YANGLE: 60,
        // size and display constants for hover text
        // pixel size of hover arrows
        HOVERARROWSIZE: 6,
        // pixels padding around text
        HOVERTEXTPAD: 3,
        // hover font
        HOVERFONTSIZE: 13,
        HOVERFONT: "Arial, sans-serif",
        // minimum time (msec) between hover calls
        HOVERMINTIME: 50,
        // ID suffix (with fullLayout._uid) for hover events in the throttle cache
        HOVERID: "-hover"
      };
    }
  });

  // src/components/fx/layout_attributes.js
  var require_layout_attributes = __commonJS({
    "src/components/fx/layout_attributes.js"(exports, module) {
      "use strict";
      var constants = require_constants();
      var fontAttrs = require_font_attributes();
      var font = fontAttrs({
        editType: "none"
      });
      font.family.dflt = constants.HOVERFONT;
      font.size.dflt = constants.HOVERFONTSIZE;
      module.exports = {
        clickmode: {
          valType: "flaglist",
          flags: ["event", "select"],
          dflt: "event",
          editType: "plot",
          extras: ["none"]
        },
        dragmode: {
          valType: "enumerated",
          values: [
            "zoom",
            "pan",
            "select",
            "lasso",
            "drawclosedpath",
            "drawopenpath",
            "drawline",
            "drawrect",
            "drawcircle",
            "orbit",
            "turntable",
            false
          ],
          dflt: "zoom",
          editType: "modebar"
        },
        hovermode: {
          valType: "enumerated",
          values: ["x", "y", "closest", false, "x unified", "y unified"],
          dflt: "closest",
          editType: "modebar"
        },
        hoversubplots: {
          valType: "enumerated",
          values: ["single", "overlaying", "axis"],
          dflt: "overlaying",
          editType: "none"
        },
        hoverdistance: {
          valType: "integer",
          min: -1,
          dflt: 20,
          editType: "none"
        },
        spikedistance: {
          valType: "integer",
          min: -1,
          dflt: -1,
          editType: "none"
        },
        hoverlabel: {
          bgcolor: {
            valType: "color",
            editType: "none"
          },
          bordercolor: {
            valType: "color",
            editType: "none"
          },
          font,
          grouptitlefont: fontAttrs({
            editType: "none"
          }),
          align: {
            valType: "enumerated",
            values: ["left", "right", "auto"],
            dflt: "auto",
            editType: "none"
          },
          namelength: {
            valType: "integer",
            min: -1,
            dflt: 15,
            editType: "none"
          },
          showarrow: {
            valType: "boolean",
            dflt: true,
            editType: "none"
          },
          editType: "none"
        },
        selectdirection: {
          valType: "enumerated",
          values: ["h", "v", "d", "any"],
          dflt: "any",
          editType: "none"
        }
      };
    }
  });

  // src/components/fx/attributes.js
  var require_attributes = __commonJS({
    "src/components/fx/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var hoverLabelAttrs = require_layout_attributes().hoverlabel;
      var extendFlat = require_extend().extendFlat;
      module.exports = {
        hoverlabel: {
          bgcolor: extendFlat({}, hoverLabelAttrs.bgcolor, {
            arrayOk: true
          }),
          bordercolor: extendFlat({}, hoverLabelAttrs.bordercolor, {
            arrayOk: true
          }),
          font: fontAttrs({
            arrayOk: true,
            editType: "none"
          }),
          align: extendFlat({}, hoverLabelAttrs.align, { arrayOk: true }),
          namelength: extendFlat({}, hoverLabelAttrs.namelength, { arrayOk: true }),
          showarrow: extendFlat({}, hoverLabelAttrs.showarrow),
          editType: "none"
        }
      };
    }
  });

  // src/plots/attributes.js
  var require_attributes2 = __commonJS({
    "src/plots/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var fxAttrs = require_attributes();
      module.exports = {
        type: {
          valType: "enumerated",
          values: [],
          // listed dynamically
          dflt: "scatter",
          editType: "calc+clearAxisTypes",
          _noTemplating: true
          // we handle this at a higher level
        },
        visible: {
          valType: "enumerated",
          values: [true, false, "legendonly"],
          dflt: true,
          editType: "calc"
        },
        showlegend: {
          valType: "boolean",
          dflt: true,
          editType: "style"
        },
        legend: {
          valType: "subplotid",
          dflt: "legend",
          editType: "style"
        },
        legendgroup: {
          valType: "string",
          dflt: "",
          editType: "style"
        },
        legendgrouptitle: {
          text: {
            valType: "string",
            dflt: "",
            editType: "style"
          },
          font: fontAttrs({
            editType: "style"
          }),
          editType: "style"
        },
        legendrank: {
          valType: "number",
          dflt: 1e3,
          editType: "style"
        },
        legendwidth: {
          valType: "number",
          min: 0,
          editType: "style"
        },
        opacity: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 1,
          editType: "style"
        },
        name: {
          valType: "string",
          editType: "style"
        },
        uid: {
          valType: "string",
          editType: "plot",
          anim: true
        },
        ids: {
          valType: "data_array",
          editType: "calc",
          anim: true
        },
        customdata: {
          valType: "data_array",
          editType: "calc"
        },
        meta: {
          valType: "any",
          arrayOk: true,
          editType: "plot"
        },
        // N.B. these cannot be 'data_array' as they do not have the same length as
        // other data arrays and arrayOk attributes in general
        //
        // Maybe add another valType:
        // https://github.com/plotly/plotly.js/issues/1894
        selectedpoints: {
          valType: "any",
          editType: "calc"
        },
        hoverinfo: {
          valType: "flaglist",
          flags: ["x", "y", "z", "text", "name"],
          extras: ["all", "none", "skip"],
          arrayOk: true,
          dflt: "all",
          editType: "none"
        },
        hoverlabel: fxAttrs.hoverlabel,
        stream: {
          token: {
            valType: "string",
            noBlank: true,
            strict: true,
            editType: "calc"
          },
          maxpoints: {
            valType: "number",
            min: 0,
            max: 1e4,
            dflt: 500,
            editType: "calc"
          },
          editType: "calc"
        },
        uirevision: {
          valType: "any",
          editType: "none"
        }
      };
    }
  });

  // src/components/colorscale/scales.js
  var require_scales = __commonJS({
    "src/components/colorscale/scales.js"(exports, module) {
      "use strict";
      var tinycolor = require_tinycolor();
      var scales = {
        Greys: [
          [0, "rgb(0,0,0)"],
          [1, "rgb(255,255,255)"]
        ],
        YlGnBu: [
          [0, "rgb(8,29,88)"],
          [0.125, "rgb(37,52,148)"],
          [0.25, "rgb(34,94,168)"],
          [0.375, "rgb(29,145,192)"],
          [0.5, "rgb(65,182,196)"],
          [0.625, "rgb(127,205,187)"],
          [0.75, "rgb(199,233,180)"],
          [0.875, "rgb(237,248,217)"],
          [1, "rgb(255,255,217)"]
        ],
        Greens: [
          [0, "rgb(0,68,27)"],
          [0.125, "rgb(0,109,44)"],
          [0.25, "rgb(35,139,69)"],
          [0.375, "rgb(65,171,93)"],
          [0.5, "rgb(116,196,118)"],
          [0.625, "rgb(161,217,155)"],
          [0.75, "rgb(199,233,192)"],
          [0.875, "rgb(229,245,224)"],
          [1, "rgb(247,252,245)"]
        ],
        YlOrRd: [
          [0, "rgb(128,0,38)"],
          [0.125, "rgb(189,0,38)"],
          [0.25, "rgb(227,26,28)"],
          [0.375, "rgb(252,78,42)"],
          [0.5, "rgb(253,141,60)"],
          [0.625, "rgb(254,178,76)"],
          [0.75, "rgb(254,217,118)"],
          [0.875, "rgb(255,237,160)"],
          [1, "rgb(255,255,204)"]
        ],
        Bluered: [
          [0, "rgb(0,0,255)"],
          [1, "rgb(255,0,0)"]
        ],
        // modified RdBu based on
        // http://www.kennethmoreland.com/color-maps/
        RdBu: [
          [0, "rgb(5,10,172)"],
          [0.35, "rgb(106,137,247)"],
          [0.5, "rgb(190,190,190)"],
          [0.6, "rgb(220,170,132)"],
          [0.7, "rgb(230,145,90)"],
          [1, "rgb(178,10,28)"]
        ],
        // Scale for non-negative numeric values
        Reds: [
          [0, "rgb(220,220,220)"],
          [0.2, "rgb(245,195,157)"],
          [0.4, "rgb(245,160,105)"],
          [1, "rgb(178,10,28)"]
        ],
        // Scale for non-positive numeric values
        Blues: [
          [0, "rgb(5,10,172)"],
          [0.35, "rgb(40,60,190)"],
          [0.5, "rgb(70,100,245)"],
          [0.6, "rgb(90,120,245)"],
          [0.7, "rgb(106,137,247)"],
          [1, "rgb(220,220,220)"]
        ],
        Picnic: [
          [0, "rgb(0,0,255)"],
          [0.1, "rgb(51,153,255)"],
          [0.2, "rgb(102,204,255)"],
          [0.3, "rgb(153,204,255)"],
          [0.4, "rgb(204,204,255)"],
          [0.5, "rgb(255,255,255)"],
          [0.6, "rgb(255,204,255)"],
          [0.7, "rgb(255,153,255)"],
          [0.8, "rgb(255,102,204)"],
          [0.9, "rgb(255,102,102)"],
          [1, "rgb(255,0,0)"]
        ],
        Rainbow: [
          [0, "rgb(150,0,90)"],
          [0.125, "rgb(0,0,200)"],
          [0.25, "rgb(0,25,255)"],
          [0.375, "rgb(0,152,255)"],
          [0.5, "rgb(44,255,150)"],
          [0.625, "rgb(151,255,0)"],
          [0.75, "rgb(255,234,0)"],
          [0.875, "rgb(255,111,0)"],
          [1, "rgb(255,0,0)"]
        ],
        Portland: [
          [0, "rgb(12,51,131)"],
          [0.25, "rgb(10,136,186)"],
          [0.5, "rgb(242,211,56)"],
          [0.75, "rgb(242,143,56)"],
          [1, "rgb(217,30,30)"]
        ],
        Jet: [
          [0, "rgb(0,0,131)"],
          [0.125, "rgb(0,60,170)"],
          [0.375, "rgb(5,255,255)"],
          [0.625, "rgb(255,255,0)"],
          [0.875, "rgb(250,0,0)"],
          [1, "rgb(128,0,0)"]
        ],
        Hot: [
          [0, "rgb(0,0,0)"],
          [0.3, "rgb(230,0,0)"],
          [0.6, "rgb(255,210,0)"],
          [1, "rgb(255,255,255)"]
        ],
        Blackbody: [
          [0, "rgb(0,0,0)"],
          [0.2, "rgb(230,0,0)"],
          [0.4, "rgb(230,210,0)"],
          [0.7, "rgb(255,255,255)"],
          [1, "rgb(160,200,255)"]
        ],
        Earth: [
          [0, "rgb(0,0,130)"],
          [0.1, "rgb(0,180,180)"],
          [0.2, "rgb(40,210,40)"],
          [0.4, "rgb(230,230,50)"],
          [0.6, "rgb(120,70,20)"],
          [1, "rgb(255,255,255)"]
        ],
        Electric: [
          [0, "rgb(0,0,0)"],
          [0.15, "rgb(30,0,100)"],
          [0.4, "rgb(120,0,100)"],
          [0.6, "rgb(160,90,0)"],
          [0.8, "rgb(230,200,0)"],
          [1, "rgb(255,250,220)"]
        ],
        Viridis: [
          [0, "#440154"],
          [0.06274509803921569, "#48186a"],
          [0.12549019607843137, "#472d7b"],
          [0.18823529411764706, "#424086"],
          [0.25098039215686274, "#3b528b"],
          [0.3137254901960784, "#33638d"],
          [0.3764705882352941, "#2c728e"],
          [0.4392156862745098, "#26828e"],
          [0.5019607843137255, "#21918c"],
          [0.5647058823529412, "#1fa088"],
          [0.6274509803921569, "#28ae80"],
          [0.6901960784313725, "#3fbc73"],
          [0.7529411764705882, "#5ec962"],
          [0.8156862745098039, "#84d44b"],
          [0.8784313725490196, "#addc30"],
          [0.9411764705882353, "#d8e219"],
          [1, "#fde725"]
        ],
        Cividis: [
          [0, "rgb(0,32,76)"],
          [0.058824, "rgb(0,42,102)"],
          [0.117647, "rgb(0,52,110)"],
          [0.176471, "rgb(39,63,108)"],
          [0.235294, "rgb(60,74,107)"],
          [0.294118, "rgb(76,85,107)"],
          [0.352941, "rgb(91,95,109)"],
          [0.411765, "rgb(104,106,112)"],
          [0.470588, "rgb(117,117,117)"],
          [0.529412, "rgb(131,129,120)"],
          [0.588235, "rgb(146,140,120)"],
          [0.647059, "rgb(161,152,118)"],
          [0.705882, "rgb(176,165,114)"],
          [0.764706, "rgb(192,177,109)"],
          [0.823529, "rgb(209,191,102)"],
          [0.882353, "rgb(225,204,92)"],
          [0.941176, "rgb(243,219,79)"],
          [1, "rgb(255,233,69)"]
        ]
      };
      var defaultScale = scales.RdBu;
      function getScale(scl, dflt) {
        if (!dflt) dflt = defaultScale;
        if (!scl) return dflt;
        function parseScale() {
          try {
            scl = scales[scl] || JSON.parse(scl);
          } catch (e) {
            scl = dflt;
          }
        }
        if (typeof scl === "string") {
          parseScale();
          if (typeof scl === "string") parseScale();
        }
        if (!isValidScaleArray(scl)) return dflt;
        return scl;
      }
      function isValidScaleArray(scl) {
        var highestVal = 0;
        if (!Array.isArray(scl) || scl.length < 2) return false;
        if (!scl[0] || !scl[scl.length - 1]) return false;
        if (+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;
        for (var i = 0; i < scl.length; i++) {
          var si = scl[i];
          if (si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
            return false;
          }
          highestVal = +si[0];
        }
        return true;
      }
      function isValidScale(scl) {
        if (scales[scl] !== void 0) return true;
        else return isValidScaleArray(scl);
      }
      module.exports = {
        scales,
        defaultScale,
        get: getScale,
        isValid: isValidScale
      };
    }
  });

  // src/components/color/attributes.js
  var require_attributes3 = __commonJS({
    "src/components/color/attributes.js"(exports) {
      "use strict";
      exports.defaults = [
        "#1f77b4",
        // muted blue
        "#ff7f0e",
        // safety orange
        "#2ca02c",
        // cooked asparagus green
        "#d62728",
        // brick red
        "#9467bd",
        // muted purple
        "#8c564b",
        // chestnut brown
        "#e377c2",
        // raspberry yogurt pink
        "#7f7f7f",
        // middle gray
        "#bcbd22",
        // curry yellow-green
        "#17becf"
        // blue-teal
      ];
      exports.defaultLine = "#444";
      exports.lightLine = "#eee";
      exports.background = "#fff";
      exports.borderLine = "#BEC8D9";
      exports.lightFraction = 100 * (14 - 4) / (15 - 4);
    }
  });

  // src/components/color/index.js
  var require_color = __commonJS({
    "src/components/color/index.js"(exports, module) {
      "use strict";
      var tinycolor = require_tinycolor();
      var isNumeric = require_fast_isnumeric();
      var isTypedArray = require_array().isTypedArray;
      var color2 = module.exports = {};
      var colorAttrs = require_attributes3();
      color2.defaults = colorAttrs.defaults;
      var defaultLine = color2.defaultLine = colorAttrs.defaultLine;
      color2.lightLine = colorAttrs.lightLine;
      var background = color2.background = colorAttrs.background;
      color2.tinyRGB = function(tc) {
        var c = tc.toRgb();
        return "rgb(" + Math.round(c.r) + ", " + Math.round(c.g) + ", " + Math.round(c.b) + ")";
      };
      color2.rgb = function(cstr) {
        return color2.tinyRGB(tinycolor(cstr));
      };
      color2.opacity = function(cstr) {
        return cstr ? tinycolor(cstr).getAlpha() : 0;
      };
      color2.addOpacity = function(cstr, op) {
        var c = tinycolor(cstr).toRgb();
        return "rgba(" + Math.round(c.r) + ", " + Math.round(c.g) + ", " + Math.round(c.b) + ", " + op + ")";
      };
      color2.combine = function(front, back) {
        var fc = tinycolor(front).toRgb();
        if (fc.a === 1) return tinycolor(front).toRgbString();
        var bc = tinycolor(back || background).toRgb();
        var bcflat = bc.a === 1 ? bc : {
          r: 255 * (1 - bc.a) + bc.r * bc.a,
          g: 255 * (1 - bc.a) + bc.g * bc.a,
          b: 255 * (1 - bc.a) + bc.b * bc.a
        };
        var fcflat = {
          r: bcflat.r * (1 - fc.a) + fc.r * fc.a,
          g: bcflat.g * (1 - fc.a) + fc.g * fc.a,
          b: bcflat.b * (1 - fc.a) + fc.b * fc.a
        };
        return tinycolor(fcflat).toRgbString();
      };
      color2.interpolate = function(first, second, factor) {
        var fc = tinycolor(first).toRgb();
        var sc = tinycolor(second).toRgb();
        var ic = {
          r: factor * fc.r + (1 - factor) * sc.r,
          g: factor * fc.g + (1 - factor) * sc.g,
          b: factor * fc.b + (1 - factor) * sc.b
        };
        return tinycolor(ic).toRgbString();
      };
      color2.contrast = function(cstr, lightAmount, darkAmount) {
        var tc = tinycolor(cstr);
        if (tc.getAlpha() !== 1) tc = tinycolor(color2.combine(cstr, background));
        var newColor = tc.isDark() ? lightAmount ? tc.lighten(lightAmount) : background : darkAmount ? tc.darken(darkAmount) : defaultLine;
        return newColor.toString();
      };
      color2.stroke = function(s, c) {
        var tc = tinycolor(c);
        s.style({ stroke: color2.tinyRGB(tc), "stroke-opacity": tc.getAlpha() });
      };
      color2.fill = function(s, c) {
        var tc = tinycolor(c);
        s.style({
          fill: color2.tinyRGB(tc),
          "fill-opacity": tc.getAlpha()
        });
      };
      color2.clean = function(container) {
        if (!container || typeof container !== "object") return;
        var keys = Object.keys(container);
        var i, j, key, val;
        for (i = 0; i < keys.length; i++) {
          key = keys[i];
          val = container[key];
          if (key.slice(-5) === "color") {
            if (Array.isArray(val)) {
              for (j = 0; j < val.length; j++) val[j] = cleanOne(val[j]);
            } else container[key] = cleanOne(val);
          } else if (key.slice(-10) === "colorscale" && Array.isArray(val)) {
            for (j = 0; j < val.length; j++) {
              if (Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]);
            }
          } else if (Array.isArray(val)) {
            var el0 = val[0];
            if (!Array.isArray(el0) && el0 && typeof el0 === "object") {
              for (j = 0; j < val.length; j++) color2.clean(val[j]);
            }
          } else if (val && typeof val === "object" && !isTypedArray(val)) color2.clean(val);
        }
      };
      function cleanOne(val) {
        if (isNumeric(val) || typeof val !== "string") return val;
        var valTrim = val.trim();
        if (valTrim.slice(0, 3) !== "rgb") return val;
        var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/);
        if (!match) return val;
        var parts = match[1].trim().split(/\s*[\s,]\s*/);
        var rgba3 = valTrim.charAt(3) === "a" && parts.length === 4;
        if (!rgba3 && parts.length !== 3) return val;
        for (var i = 0; i < parts.length; i++) {
          if (!parts[i].length) return val;
          parts[i] = Number(parts[i]);
          if (!(parts[i] >= 0)) {
            return val;
          }
          if (i === 3) {
            if (parts[i] > 1) parts[i] = 1;
          } else if (parts[i] >= 1) {
            return val;
          }
        }
        var rgbStr = Math.round(parts[0] * 255) + ", " + Math.round(parts[1] * 255) + ", " + Math.round(parts[2] * 255);
        if (rgba3) return "rgba(" + rgbStr + ", " + parts[3] + ")";
        return "rgb(" + rgbStr + ")";
      }
    }
  });

  // src/constants/interactions.js
  var require_interactions = __commonJS({
    "src/constants/interactions.js"(exports, module) {
      "use strict";
      module.exports = {
        /**
         * Timing information for interactive elements
         */
        SHOW_PLACEHOLDER: 100,
        HIDE_PLACEHOLDER: 1e3,
        // opacity dimming fraction for points that are not in selection
        DESELECTDIM: 0.2
      };
    }
  });

  // src/lib/regex.js
  var require_regex = __commonJS({
    "src/lib/regex.js"(exports) {
      "use strict";
      exports.counter = function(head, tail, openEnded, matchBeginning) {
        var fullTail = (tail || "") + (openEnded ? "" : "$");
        var startWithPrefix = matchBeginning === false ? "" : "^";
        if (head === "xy") {
          return new RegExp(startWithPrefix + "x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?" + fullTail);
        }
        return new RegExp(startWithPrefix + head + "([2-9]|[1-9][0-9]+)?" + fullTail);
      };
    }
  });

  // src/lib/coerce.js
  var require_coerce = __commonJS({
    "src/lib/coerce.js"(exports) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var tinycolor = require_tinycolor();
      var extendFlat = require_extend().extendFlat;
      var baseTraceAttrs = require_attributes2();
      var colorscales = require_scales();
      var Color2 = require_color();
      var DESELECTDIM = require_interactions().DESELECTDIM;
      var nestedProperty = require_nested_property();
      var counterRegex = require_regex().counter;
      var modHalf = require_mod().modHalf;
      var isArrayOrTypedArray = require_array().isArrayOrTypedArray;
      var isTypedArraySpec = require_array().isTypedArraySpec;
      var decodeTypedArraySpec = require_array().decodeTypedArraySpec;
      exports.valObjectMeta = {
        data_array: {
          // You can use *dflt=[] to force said array to exist though.
          coerceFunction: function(v, propOut, dflt) {
            propOut.set(
              isArrayOrTypedArray(v) ? v : isTypedArraySpec(v) ? decodeTypedArraySpec(v) : dflt
            );
          }
        },
        enumerated: {
          coerceFunction: function(v, propOut, dflt, opts) {
            if (opts.coerceNumber) v = +v;
            if (opts.values.indexOf(v) === -1) propOut.set(dflt);
            else propOut.set(v);
          },
          validateFunction: function(v, opts) {
            if (opts.coerceNumber) v = +v;
            var values = opts.values;
            for (var i = 0; i < values.length; i++) {
              var k = String(values[i]);
              if (k.charAt(0) === "/" && k.charAt(k.length - 1) === "/") {
                var regex = new RegExp(k.slice(1, -1));
                if (regex.test(v)) return true;
              } else if (v === values[i]) return true;
            }
            return false;
          }
        },
        boolean: {
          coerceFunction: function(v, propOut, dflt, opts) {
            const isBoolean = (value) => value === true || value === false;
            if (isBoolean(v) || opts.arrayOk && Array.isArray(v) && v.length > 0 && v.every(isBoolean)) {
              propOut.set(v);
            } else {
              propOut.set(dflt);
            }
          }
        },
        number: {
          coerceFunction: function(v, propOut, dflt, opts) {
            if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
            if (!isNumeric(v) || opts.min !== void 0 && v < opts.min || opts.max !== void 0 && v > opts.max) {
              propOut.set(dflt);
            } else propOut.set(+v);
          }
        },
        integer: {
          coerceFunction: function(v, propOut, dflt, opts) {
            if ((opts.extras || []).indexOf(v) !== -1) {
              propOut.set(v);
              return;
            }
            if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
            if (v % 1 || !isNumeric(v) || opts.min !== void 0 && v < opts.min || opts.max !== void 0 && v > opts.max) {
              propOut.set(dflt);
            } else propOut.set(+v);
          }
        },
        string: {
          // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
          coerceFunction: function(v, propOut, dflt, opts) {
            if (typeof v !== "string") {
              var okToCoerce = typeof v === "number";
              if (opts.strict === true || !okToCoerce) propOut.set(dflt);
              else propOut.set(String(v));
            } else if (opts.noBlank && !v) propOut.set(dflt);
            else propOut.set(v);
          }
        },
        color: {
          coerceFunction: function(v, propOut, dflt) {
            if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
            if (tinycolor(v).isValid()) propOut.set(v);
            else propOut.set(dflt);
          }
        },
        colorlist: {
          coerceFunction: function(v, propOut, dflt) {
            function isColor(color2) {
              return tinycolor(color2).isValid();
            }
            if (!Array.isArray(v) || !v.length) propOut.set(dflt);
            else if (v.every(isColor)) propOut.set(v);
            else propOut.set(dflt);
          }
        },
        colorscale: {
          coerceFunction: function(v, propOut, dflt) {
            propOut.set(colorscales.get(v, dflt));
          }
        },
        angle: {
          coerceFunction: function(v, propOut, dflt) {
            if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
            if (v === "auto") propOut.set("auto");
            else if (!isNumeric(v)) propOut.set(dflt);
            else propOut.set(modHalf(+v, 360));
          }
        },
        subplotid: {
          coerceFunction: function(v, propOut, dflt, opts) {
            var regex = opts.regex || counterRegex(dflt);
            const isSubplotId = (value) => typeof value === "string" && regex.test(value);
            if (isSubplotId(v) || opts.arrayOk && isArrayOrTypedArray(v) && v.length > 0 && v.every(isSubplotId)) {
              propOut.set(v);
            } else {
              propOut.set(dflt);
            }
          },
          validateFunction: function(v, opts) {
            var dflt = opts.dflt;
            if (v === dflt) return true;
            if (typeof v !== "string") return false;
            if (counterRegex(dflt).test(v)) return true;
            return false;
          }
        },
        flaglist: {
          coerceFunction: function(v, propOut, dflt, opts) {
            if ((opts.extras || []).indexOf(v) !== -1) {
              propOut.set(v);
              return;
            }
            if (typeof v !== "string") {
              propOut.set(dflt);
              return;
            }
            var vParts = v.split("+");
            var i = 0;
            while (i < vParts.length) {
              var vi = vParts[i];
              if (opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
                vParts.splice(i, 1);
              } else i++;
            }
            if (!vParts.length) propOut.set(dflt);
            else propOut.set(vParts.join("+"));
          }
        },
        any: {
          coerceFunction: function(v, propOut, dflt) {
            if (v === void 0) {
              propOut.set(dflt);
            } else {
              propOut.set(
                isTypedArraySpec(v) ? decodeTypedArraySpec(v) : v
              );
            }
          }
        },
        info_array: {
          // set `dimensions=2` for a 2D array or '1-2' for either
          // `items` may be a single object instead of an array, in which case
          // `freeLength` must be true.
          // if `dimensions='1-2'` and items is a 1D array, then the value can
          // either be a matching 1D array or an array of such matching 1D arrays
          coerceFunction: function(v, propOut, dflt, opts) {
            function coercePart(v2, opts2, dflt2) {
              var out;
              var propPart = { set: function(v3) {
                out = v3;
              } };
              if (dflt2 === void 0) dflt2 = opts2.dflt;
              exports.valObjectMeta[opts2.valType].coerceFunction(v2, propPart, dflt2, opts2);
              return out;
            }
            if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
            if (!isArrayOrTypedArray(v)) {
              propOut.set(dflt);
              return;
            }
            var twoD = opts.dimensions === 2 || opts.dimensions === "1-2" && Array.isArray(v) && isArrayOrTypedArray(v[0]);
            var items = opts.items;
            var vOut = [];
            var arrayItems = Array.isArray(items);
            var arrayItems2D = arrayItems && twoD && isArrayOrTypedArray(items[0]);
            var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
            var len = arrayItems && !innerItemsOnly ? items.length : v.length;
            var i, j, row, item, len2, vNew;
            dflt = Array.isArray(dflt) ? dflt : [];
            if (twoD) {
              for (i = 0; i < len; i++) {
                vOut[i] = [];
                row = isArrayOrTypedArray(v[i]) ? v[i] : [];
                if (innerItemsOnly) len2 = items.length;
                else if (arrayItems) len2 = items[i].length;
                else len2 = row.length;
                for (j = 0; j < len2; j++) {
                  if (innerItemsOnly) item = items[j];
                  else if (arrayItems) item = items[i][j];
                  else item = items;
                  vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
                  if (vNew !== void 0) vOut[i][j] = vNew;
                }
              }
            } else {
              for (i = 0; i < len; i++) {
                vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
                if (vNew !== void 0) vOut[i] = vNew;
              }
            }
            propOut.set(vOut);
          },
          validateFunction: function(v, opts) {
            if (!isArrayOrTypedArray(v)) return false;
            var items = opts.items;
            var arrayItems = Array.isArray(items);
            var twoD = opts.dimensions === 2;
            if (!opts.freeLength && v.length !== items.length) return false;
            for (var i = 0; i < v.length; i++) {
              if (twoD) {
                if (!isArrayOrTypedArray(v[i]) || !opts.freeLength && v[i].length !== items[i].length) {
                  return false;
                }
                for (var j = 0; j < v[i].length; j++) {
                  if (!validate(v[i][j], arrayItems ? items[i][j] : items)) {
                    return false;
                  }
                }
              } else if (!validate(v[i], arrayItems ? items[i] : items)) return false;
            }
            return true;
          }
        }
      };
      exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
        var opts = nestedProperty(attributes, attribute).get();
        var propIn = nestedProperty(containerIn, attribute);
        var propOut = nestedProperty(containerOut, attribute);
        var v = propIn.get();
        var template = containerOut._template;
        if (v === void 0 && template) {
          v = nestedProperty(template, attribute).get();
          template = 0;
        }
        if (dflt === void 0) dflt = opts.dflt;
        if (opts.arrayOk) {
          if (isArrayOrTypedArray(v)) {
            propOut.set(v);
            return v;
          } else {
            if (isTypedArraySpec(v)) {
              v = decodeTypedArraySpec(v);
              propOut.set(v);
              return v;
            }
          }
        }
        var coerceFunction = exports.valObjectMeta[opts.valType].coerceFunction;
        coerceFunction(v, propOut, dflt, opts);
        var out = propOut.get();
        if (template && out === dflt && !validate(v, opts)) {
          v = nestedProperty(template, attribute).get();
          coerceFunction(v, propOut, dflt, opts);
          out = propOut.get();
        }
        return out;
      };
      exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
        var propIn = nestedProperty(containerIn, attribute);
        var propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
        var valIn = propIn.get();
        return valIn !== void 0 && valIn !== null ? propOut : false;
      };
      exports.coerceFont = function(coerce, attr, dfltObj, opts) {
        if (!opts) opts = {};
        dfltObj = extendFlat({}, dfltObj);
        dfltObj = extendFlat(dfltObj, opts.overrideDflt || {});
        var out = {
          family: coerce(attr + ".family", dfltObj.family),
          size: coerce(attr + ".size", dfltObj.size),
          color: coerce(attr + ".color", dfltObj.color),
          weight: coerce(attr + ".weight", dfltObj.weight),
          style: coerce(attr + ".style", dfltObj.style)
        };
        if (!opts.noFontVariant) out.variant = coerce(attr + ".variant", dfltObj.variant);
        if (!opts.noFontLineposition) out.lineposition = coerce(attr + ".lineposition", dfltObj.lineposition);
        if (!opts.noFontTextcase) out.textcase = coerce(attr + ".textcase", dfltObj.textcase);
        if (!opts.noFontShadow) {
          var dfltShadow = dfltObj.shadow;
          if (dfltShadow === "none" && opts.autoShadowDflt) {
            dfltShadow = "auto";
          }
          out.shadow = coerce(attr + ".shadow", dfltShadow);
        }
        return out;
      };
      exports.coercePattern = function(coerce, attr, markerColor, hasMarkerColorscale) {
        var shape = coerce(attr + ".shape");
        var path;
        if (!shape) {
          path = coerce(attr + ".path");
        }
        if (shape || path) {
          if (shape) {
            coerce(attr + ".solidity");
          }
          coerce(attr + ".size");
          var fillmode = coerce(attr + ".fillmode");
          var isOverlay = fillmode === "overlay";
          if (!hasMarkerColorscale) {
            var bgcolor = coerce(
              attr + ".bgcolor",
              isOverlay ? markerColor : void 0
            );
            coerce(
              attr + ".fgcolor",
              isOverlay ? Color2.contrast(bgcolor) : markerColor
            );
          }
          coerce(
            attr + ".fgopacity",
            isOverlay ? 0.5 : 1
          );
        }
      };
      exports.coerceHoverinfo = function(traceIn, traceOut, layoutOut) {
        var moduleAttrs = traceOut._module.attributes;
        var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;
        var valObj = attrs.hoverinfo;
        var dflt;
        if (layoutOut._dataLength === 1) {
          var flags = valObj.dflt === "all" ? valObj.flags.slice() : valObj.dflt.split("+");
          flags.splice(flags.indexOf("name"), 1);
          dflt = flags.join("+");
        }
        return exports.coerce(traceIn, traceOut, attrs, "hoverinfo", dflt);
      };
      exports.coerceSelectionMarkerOpacity = function(traceOut, coerce) {
        if (!traceOut.marker) return;
        var mo = traceOut.marker.opacity;
        if (mo === void 0) return;
        var smoDflt;
        var usmoDflt;
        if (!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
          smoDflt = mo;
          usmoDflt = DESELECTDIM * mo;
        }
        coerce("selected.marker.opacity", smoDflt);
        coerce("unselected.marker.opacity", usmoDflt);
      };
      function validate(value, opts) {
        var valObjectDef = exports.valObjectMeta[opts.valType];
        if (opts.arrayOk && isArrayOrTypedArray(value)) return true;
        if (valObjectDef.validateFunction) {
          return valObjectDef.validateFunction(value, opts);
        }
        var failed = {};
        var out = failed;
        var propMock = { set: function(v) {
          out = v;
        } };
        valObjectDef.coerceFunction(value, propMock, failed, opts);
        return out !== failed;
      }
      exports.validate = validate;
    }
  });

  // src/plot_api/plot_config.js
  var require_plot_config = __commonJS({
    "src/plot_api/plot_config.js"(exports, module) {
      "use strict";
      var configAttributes = {
        staticPlot: {
          valType: "boolean",
          dflt: false
        },
        typesetMath: {
          valType: "boolean",
          dflt: true
        },
        plotlyServerURL: {
          valType: "string",
          dflt: ""
        },
        editable: {
          valType: "boolean",
          dflt: false
        },
        edits: {
          annotationPosition: {
            valType: "boolean",
            dflt: false
          },
          annotationTail: {
            valType: "boolean",
            dflt: false
          },
          annotationText: {
            valType: "boolean",
            dflt: false
          },
          axisTitleText: {
            valType: "boolean",
            dflt: false
          },
          colorbarPosition: {
            valType: "boolean",
            dflt: false
          },
          colorbarTitleText: {
            valType: "boolean",
            dflt: false
          },
          legendPosition: {
            valType: "boolean",
            dflt: false
          },
          legendText: {
            valType: "boolean",
            dflt: false
          },
          shapePosition: {
            valType: "boolean",
            dflt: false
          },
          titleText: {
            valType: "boolean",
            dflt: false
          }
        },
        editSelection: {
          valType: "boolean",
          dflt: true
        },
        autosizable: {
          valType: "boolean",
          dflt: false
        },
        responsive: {
          valType: "boolean",
          dflt: false
        },
        fillFrame: {
          valType: "boolean",
          dflt: false
        },
        frameMargins: {
          valType: "number",
          dflt: 0,
          min: 0,
          max: 0.5
        },
        scrollZoom: {
          valType: "flaglist",
          flags: ["cartesian", "gl3d", "geo", "mapbox", "map"],
          extras: [true, false],
          dflt: "gl3d+geo+map"
        },
        doubleClick: {
          valType: "enumerated",
          values: [false, "reset", "autosize", "reset+autosize"],
          dflt: "reset+autosize"
        },
        doubleClickDelay: {
          valType: "number",
          dflt: 300,
          min: 0
        },
        showAxisDragHandles: {
          valType: "boolean",
          dflt: true
        },
        showAxisRangeEntryBoxes: {
          valType: "boolean",
          dflt: true
        },
        showTips: {
          valType: "boolean",
          dflt: true
        },
        showLink: {
          valType: "boolean",
          dflt: false
        },
        linkText: {
          valType: "string",
          dflt: "Edit chart",
          noBlank: true
        },
        sendData: {
          valType: "boolean",
          dflt: true
        },
        showSources: {
          valType: "any",
          dflt: false
        },
        displayModeBar: {
          valType: "enumerated",
          values: ["hover", true, false],
          dflt: "hover"
        },
        showSendToCloud: {
          valType: "boolean",
          dflt: false
        },
        showEditInChartStudio: {
          valType: "boolean",
          dflt: false
        },
        modeBarButtonsToRemove: {
          valType: "any",
          dflt: []
        },
        modeBarButtonsToAdd: {
          valType: "any",
          dflt: []
        },
        modeBarButtons: {
          valType: "any",
          dflt: false
        },
        toImageButtonOptions: {
          valType: "any",
          dflt: {}
        },
        displaylogo: {
          valType: "boolean",
          dflt: true
        },
        watermark: {
          valType: "boolean",
          dflt: false
        },
        plotGlPixelRatio: {
          valType: "number",
          dflt: 2,
          min: 1,
          max: 4
        },
        setBackground: {
          valType: "any",
          dflt: "transparent"
        },
        topojsonURL: {
          valType: "string",
          noBlank: true,
          // TODO: Switch the default back to 'https://cdn.plot.ly/' once we remove the legacy maps
          dflt: "https://cdn.plot.ly/un/"
        },
        mapboxAccessToken: {
          valType: "string",
          dflt: null
        },
        logging: {
          valType: "integer",
          min: 0,
          max: 2,
          dflt: 1
        },
        notifyOnLogging: {
          valType: "integer",
          min: 0,
          max: 2,
          dflt: 0
        },
        queueLength: {
          valType: "integer",
          min: 0,
          dflt: 0
        },
        locale: {
          valType: "string",
          dflt: "en-US"
        },
        locales: {
          valType: "any",
          dflt: {}
        }
      };
      var dfltConfig = {};
      function crawl(src, target) {
        for (var k in src) {
          var obj = src[k];
          if (obj.valType) {
            target[k] = obj.dflt;
          } else {
            if (!target[k]) {
              target[k] = {};
            }
            crawl(obj, target[k]);
          }
        }
      }
      crawl(configAttributes, dfltConfig);
      module.exports = {
        configAttributes,
        dfltConfig
      };
    }
  });

  // src/lib/notifier.js
  var require_notifier = __commonJS({
    "src/lib/notifier.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var NOTEDATA = [];
      module.exports = function(text, displayLength) {
        if (NOTEDATA.indexOf(text) !== -1) return;
        NOTEDATA.push(text);
        var ts = 1e3;
        if (isNumeric(displayLength)) ts = displayLength;
        else if (displayLength === "long") ts = 3e3;
        var notifierContainer = d3.select("body").selectAll(".plotly-notifier").data([0]);
        notifierContainer.enter().append("div").classed("plotly-notifier", true);
        var notes = notifierContainer.selectAll(".notifier-note").data(NOTEDATA);
        function killNote(transition) {
          transition.duration(700).style("opacity", 0).each("end", function(thisText) {
            var thisIndex = NOTEDATA.indexOf(thisText);
            if (thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
            d3.select(this).remove();
          });
        }
        notes.enter().append("div").classed("notifier-note", true).style("opacity", 0).each(function(thisText) {
          var note = d3.select(this);
          note.append("button").classed("notifier-close", true).html("&times;").on("click", function() {
            note.transition().call(killNote);
          });
          var p = note.append("p");
          var lines = thisText.split(/<br\s*\/?>/g);
          for (var i = 0; i < lines.length; i++) {
            if (i) p.append("br");
            p.append("span").text(lines[i]);
          }
          if (displayLength === "stick") {
            note.transition().duration(350).style("opacity", 1);
          } else {
            note.transition().duration(700).style("opacity", 1).transition().delay(ts).call(killNote);
          }
        });
      };
    }
  });

  // src/lib/loggers.js
  var require_loggers = __commonJS({
    "src/lib/loggers.js"(exports, module) {
      "use strict";
      var dfltConfig = require_plot_config().dfltConfig;
      var notifier = require_notifier();
      var loggers = module.exports = {};
      loggers.log = function() {
        var i;
        if (dfltConfig.logging > 1) {
          var messages = ["LOG:"];
          for (i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
          }
          console.trace.apply(console, messages);
        }
        if (dfltConfig.notifyOnLogging > 1) {
          var lines = [];
          for (i = 0; i < arguments.length; i++) {
            lines.push(arguments[i]);
          }
          notifier(lines.join("<br>"), "long");
        }
      };
      loggers.warn = function() {
        var i;
        if (dfltConfig.logging > 0) {
          var messages = ["WARN:"];
          for (i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
          }
          console.trace.apply(console, messages);
        }
        if (dfltConfig.notifyOnLogging > 0) {
          var lines = [];
          for (i = 0; i < arguments.length; i++) {
            lines.push(arguments[i]);
          }
          notifier(lines.join("<br>"), "stick");
        }
      };
      loggers.error = function() {
        var i;
        if (dfltConfig.logging > 0) {
          var messages = ["ERROR:"];
          for (i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
          }
          console.error.apply(console, messages);
        }
        if (dfltConfig.notifyOnLogging > 0) {
          var lines = [];
          for (i = 0; i < arguments.length; i++) {
            lines.push(arguments[i]);
          }
          notifier(lines.join("<br>"), "stick");
        }
      };
    }
  });

  // src/lib/noop.js
  var require_noop = __commonJS({
    "src/lib/noop.js"(exports, module) {
      "use strict";
      module.exports = function noop() {
      };
    }
  });

  // src/lib/push_unique.js
  var require_push_unique = __commonJS({
    "src/lib/push_unique.js"(exports, module) {
      "use strict";
      module.exports = function pushUnique(array, item) {
        if (item instanceof RegExp) {
          var itemStr = item.toString();
          for (var i = 0; i < array.length; i++) {
            if (array[i] instanceof RegExp && array[i].toString() === itemStr) {
              return array;
            }
          }
          array.push(item);
        } else if ((item || item === 0) && array.indexOf(item) === -1) array.push(item);
        return array;
      };
    }
  });

  // node_modules/gl-mat4/create.js
  var require_create = __commonJS({
    "node_modules/gl-mat4/create.js"(exports, module) {
      module.exports = create;
      function create() {
        var out = new Float32Array(16);
        out[0] = 1;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = 1;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = 1;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/clone.js
  var require_clone = __commonJS({
    "node_modules/gl-mat4/clone.js"(exports, module) {
      module.exports = clone;
      function clone(a) {
        var out = new Float32Array(16);
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        out[4] = a[4];
        out[5] = a[5];
        out[6] = a[6];
        out[7] = a[7];
        out[8] = a[8];
        out[9] = a[9];
        out[10] = a[10];
        out[11] = a[11];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
        return out;
      }
    }
  });

  // node_modules/gl-mat4/copy.js
  var require_copy = __commonJS({
    "node_modules/gl-mat4/copy.js"(exports, module) {
      module.exports = copy;
      function copy(out, a) {
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        out[4] = a[4];
        out[5] = a[5];
        out[6] = a[6];
        out[7] = a[7];
        out[8] = a[8];
        out[9] = a[9];
        out[10] = a[10];
        out[11] = a[11];
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
        return out;
      }
    }
  });

  // node_modules/gl-mat4/identity.js
  var require_identity = __commonJS({
    "node_modules/gl-mat4/identity.js"(exports, module) {
      module.exports = identity2;
      function identity2(out) {
        out[0] = 1;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = 1;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = 1;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/transpose.js
  var require_transpose = __commonJS({
    "node_modules/gl-mat4/transpose.js"(exports, module) {
      module.exports = transpose;
      function transpose(out, a) {
        if (out === a) {
          var a01 = a[1], a02 = a[2], a03 = a[3], a12 = a[6], a13 = a[7], a23 = a[11];
          out[1] = a[4];
          out[2] = a[8];
          out[3] = a[12];
          out[4] = a01;
          out[6] = a[9];
          out[7] = a[13];
          out[8] = a02;
          out[9] = a12;
          out[11] = a[14];
          out[12] = a03;
          out[13] = a13;
          out[14] = a23;
        } else {
          out[0] = a[0];
          out[1] = a[4];
          out[2] = a[8];
          out[3] = a[12];
          out[4] = a[1];
          out[5] = a[5];
          out[6] = a[9];
          out[7] = a[13];
          out[8] = a[2];
          out[9] = a[6];
          out[10] = a[10];
          out[11] = a[14];
          out[12] = a[3];
          out[13] = a[7];
          out[14] = a[11];
          out[15] = a[15];
        }
        return out;
      }
    }
  });

  // node_modules/gl-mat4/invert.js
  var require_invert = __commonJS({
    "node_modules/gl-mat4/invert.js"(exports, module) {
      module.exports = invert;
      function invert(out, a) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        if (!det) {
          return null;
        }
        det = 1 / det;
        out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
        out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
        out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
        out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
        out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
        out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
        out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
        out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
        out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
        out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
        out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
        out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
        out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
        out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
        out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
        out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/adjoint.js
  var require_adjoint = __commonJS({
    "node_modules/gl-mat4/adjoint.js"(exports, module) {
      module.exports = adjoint;
      function adjoint(out, a) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
        out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);
        out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
        out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);
        out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
        out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
        out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);
        out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
        out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);
        out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);
        out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
        out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);
        out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
        out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
        out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);
        out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
        out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);
        return out;
      }
    }
  });

  // node_modules/gl-mat4/determinant.js
  var require_determinant = __commonJS({
    "node_modules/gl-mat4/determinant.js"(exports, module) {
      module.exports = determinant;
      function determinant(a) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
        return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
      }
    }
  });

  // node_modules/gl-mat4/multiply.js
  var require_multiply = __commonJS({
    "node_modules/gl-mat4/multiply.js"(exports, module) {
      module.exports = multiply;
      function multiply(out, a, b) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
        var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
        out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        b0 = b[4];
        b1 = b[5];
        b2 = b[6];
        b3 = b[7];
        out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        b0 = b[8];
        b1 = b[9];
        b2 = b[10];
        b3 = b[11];
        out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        b0 = b[12];
        b1 = b[13];
        b2 = b[14];
        b3 = b[15];
        out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/translate.js
  var require_translate = __commonJS({
    "node_modules/gl-mat4/translate.js"(exports, module) {
      module.exports = translate;
      function translate(out, a, v) {
        var x = v[0], y = v[1], z = v[2], a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23;
        if (a === out) {
          out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
          out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
          out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
          out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
        } else {
          a00 = a[0];
          a01 = a[1];
          a02 = a[2];
          a03 = a[3];
          a10 = a[4];
          a11 = a[5];
          a12 = a[6];
          a13 = a[7];
          a20 = a[8];
          a21 = a[9];
          a22 = a[10];
          a23 = a[11];
          out[0] = a00;
          out[1] = a01;
          out[2] = a02;
          out[3] = a03;
          out[4] = a10;
          out[5] = a11;
          out[6] = a12;
          out[7] = a13;
          out[8] = a20;
          out[9] = a21;
          out[10] = a22;
          out[11] = a23;
          out[12] = a00 * x + a10 * y + a20 * z + a[12];
          out[13] = a01 * x + a11 * y + a21 * z + a[13];
          out[14] = a02 * x + a12 * y + a22 * z + a[14];
          out[15] = a03 * x + a13 * y + a23 * z + a[15];
        }
        return out;
      }
    }
  });

  // node_modules/gl-mat4/scale.js
  var require_scale = __commonJS({
    "node_modules/gl-mat4/scale.js"(exports, module) {
      module.exports = scale;
      function scale(out, a, v) {
        var x = v[0], y = v[1], z = v[2];
        out[0] = a[0] * x;
        out[1] = a[1] * x;
        out[2] = a[2] * x;
        out[3] = a[3] * x;
        out[4] = a[4] * y;
        out[5] = a[5] * y;
        out[6] = a[6] * y;
        out[7] = a[7] * y;
        out[8] = a[8] * z;
        out[9] = a[9] * z;
        out[10] = a[10] * z;
        out[11] = a[11] * z;
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
        return out;
      }
    }
  });

  // node_modules/gl-mat4/rotate.js
  var require_rotate = __commonJS({
    "node_modules/gl-mat4/rotate.js"(exports, module) {
      module.exports = rotate;
      function rotate(out, a, rad, axis) {
        var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22;
        if (Math.abs(len) < 1e-6) {
          return null;
        }
        len = 1 / len;
        x *= len;
        y *= len;
        z *= len;
        s = Math.sin(rad);
        c = Math.cos(rad);
        t = 1 - c;
        a00 = a[0];
        a01 = a[1];
        a02 = a[2];
        a03 = a[3];
        a10 = a[4];
        a11 = a[5];
        a12 = a[6];
        a13 = a[7];
        a20 = a[8];
        a21 = a[9];
        a22 = a[10];
        a23 = a[11];
        b00 = x * x * t + c;
        b01 = y * x * t + z * s;
        b02 = z * x * t - y * s;
        b10 = x * y * t - z * s;
        b11 = y * y * t + c;
        b12 = z * y * t + x * s;
        b20 = x * z * t + y * s;
        b21 = y * z * t - x * s;
        b22 = z * z * t + c;
        out[0] = a00 * b00 + a10 * b01 + a20 * b02;
        out[1] = a01 * b00 + a11 * b01 + a21 * b02;
        out[2] = a02 * b00 + a12 * b01 + a22 * b02;
        out[3] = a03 * b00 + a13 * b01 + a23 * b02;
        out[4] = a00 * b10 + a10 * b11 + a20 * b12;
        out[5] = a01 * b10 + a11 * b11 + a21 * b12;
        out[6] = a02 * b10 + a12 * b11 + a22 * b12;
        out[7] = a03 * b10 + a13 * b11 + a23 * b12;
        out[8] = a00 * b20 + a10 * b21 + a20 * b22;
        out[9] = a01 * b20 + a11 * b21 + a21 * b22;
        out[10] = a02 * b20 + a12 * b21 + a22 * b22;
        out[11] = a03 * b20 + a13 * b21 + a23 * b22;
        if (a !== out) {
          out[12] = a[12];
          out[13] = a[13];
          out[14] = a[14];
          out[15] = a[15];
        }
        return out;
      }
    }
  });

  // node_modules/gl-mat4/rotateX.js
  var require_rotateX = __commonJS({
    "node_modules/gl-mat4/rotateX.js"(exports, module) {
      module.exports = rotateX;
      function rotateX(out, a, rad) {
        var s = Math.sin(rad), c = Math.cos(rad), a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
        if (a !== out) {
          out[0] = a[0];
          out[1] = a[1];
          out[2] = a[2];
          out[3] = a[3];
          out[12] = a[12];
          out[13] = a[13];
          out[14] = a[14];
          out[15] = a[15];
        }
        out[4] = a10 * c + a20 * s;
        out[5] = a11 * c + a21 * s;
        out[6] = a12 * c + a22 * s;
        out[7] = a13 * c + a23 * s;
        out[8] = a20 * c - a10 * s;
        out[9] = a21 * c - a11 * s;
        out[10] = a22 * c - a12 * s;
        out[11] = a23 * c - a13 * s;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/rotateY.js
  var require_rotateY = __commonJS({
    "node_modules/gl-mat4/rotateY.js"(exports, module) {
      module.exports = rotateY;
      function rotateY(out, a, rad) {
        var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
        if (a !== out) {
          out[4] = a[4];
          out[5] = a[5];
          out[6] = a[6];
          out[7] = a[7];
          out[12] = a[12];
          out[13] = a[13];
          out[14] = a[14];
          out[15] = a[15];
        }
        out[0] = a00 * c - a20 * s;
        out[1] = a01 * c - a21 * s;
        out[2] = a02 * c - a22 * s;
        out[3] = a03 * c - a23 * s;
        out[8] = a00 * s + a20 * c;
        out[9] = a01 * s + a21 * c;
        out[10] = a02 * s + a22 * c;
        out[11] = a03 * s + a23 * c;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/rotateZ.js
  var require_rotateZ = __commonJS({
    "node_modules/gl-mat4/rotateZ.js"(exports, module) {
      module.exports = rotateZ;
      function rotateZ(out, a, rad) {
        var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
        if (a !== out) {
          out[8] = a[8];
          out[9] = a[9];
          out[10] = a[10];
          out[11] = a[11];
          out[12] = a[12];
          out[13] = a[13];
          out[14] = a[14];
          out[15] = a[15];
        }
        out[0] = a00 * c + a10 * s;
        out[1] = a01 * c + a11 * s;
        out[2] = a02 * c + a12 * s;
        out[3] = a03 * c + a13 * s;
        out[4] = a10 * c - a00 * s;
        out[5] = a11 * c - a01 * s;
        out[6] = a12 * c - a02 * s;
        out[7] = a13 * c - a03 * s;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromRotation.js
  var require_fromRotation = __commonJS({
    "node_modules/gl-mat4/fromRotation.js"(exports, module) {
      module.exports = fromRotation;
      function fromRotation(out, rad, axis) {
        var s, c, t;
        var x = axis[0];
        var y = axis[1];
        var z = axis[2];
        var len = Math.sqrt(x * x + y * y + z * z);
        if (Math.abs(len) < 1e-6) {
          return null;
        }
        len = 1 / len;
        x *= len;
        y *= len;
        z *= len;
        s = Math.sin(rad);
        c = Math.cos(rad);
        t = 1 - c;
        out[0] = x * x * t + c;
        out[1] = y * x * t + z * s;
        out[2] = z * x * t - y * s;
        out[3] = 0;
        out[4] = x * y * t - z * s;
        out[5] = y * y * t + c;
        out[6] = z * y * t + x * s;
        out[7] = 0;
        out[8] = x * z * t + y * s;
        out[9] = y * z * t - x * s;
        out[10] = z * z * t + c;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromRotationTranslation.js
  var require_fromRotationTranslation = __commonJS({
    "node_modules/gl-mat4/fromRotationTranslation.js"(exports, module) {
      module.exports = fromRotationTranslation;
      function fromRotationTranslation(out, q, v) {
        var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
        out[0] = 1 - (yy + zz);
        out[1] = xy + wz;
        out[2] = xz - wy;
        out[3] = 0;
        out[4] = xy - wz;
        out[5] = 1 - (xx + zz);
        out[6] = yz + wx;
        out[7] = 0;
        out[8] = xz + wy;
        out[9] = yz - wx;
        out[10] = 1 - (xx + yy);
        out[11] = 0;
        out[12] = v[0];
        out[13] = v[1];
        out[14] = v[2];
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromScaling.js
  var require_fromScaling = __commonJS({
    "node_modules/gl-mat4/fromScaling.js"(exports, module) {
      module.exports = fromScaling;
      function fromScaling(out, v) {
        out[0] = v[0];
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = v[1];
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = v[2];
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromTranslation.js
  var require_fromTranslation = __commonJS({
    "node_modules/gl-mat4/fromTranslation.js"(exports, module) {
      module.exports = fromTranslation;
      function fromTranslation(out, v) {
        out[0] = 1;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = 1;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = 1;
        out[11] = 0;
        out[12] = v[0];
        out[13] = v[1];
        out[14] = v[2];
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromXRotation.js
  var require_fromXRotation = __commonJS({
    "node_modules/gl-mat4/fromXRotation.js"(exports, module) {
      module.exports = fromXRotation;
      function fromXRotation(out, rad) {
        var s = Math.sin(rad), c = Math.cos(rad);
        out[0] = 1;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = c;
        out[6] = s;
        out[7] = 0;
        out[8] = 0;
        out[9] = -s;
        out[10] = c;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromYRotation.js
  var require_fromYRotation = __commonJS({
    "node_modules/gl-mat4/fromYRotation.js"(exports, module) {
      module.exports = fromYRotation;
      function fromYRotation(out, rad) {
        var s = Math.sin(rad), c = Math.cos(rad);
        out[0] = c;
        out[1] = 0;
        out[2] = -s;
        out[3] = 0;
        out[4] = 0;
        out[5] = 1;
        out[6] = 0;
        out[7] = 0;
        out[8] = s;
        out[9] = 0;
        out[10] = c;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromZRotation.js
  var require_fromZRotation = __commonJS({
    "node_modules/gl-mat4/fromZRotation.js"(exports, module) {
      module.exports = fromZRotation;
      function fromZRotation(out, rad) {
        var s = Math.sin(rad), c = Math.cos(rad);
        out[0] = c;
        out[1] = s;
        out[2] = 0;
        out[3] = 0;
        out[4] = -s;
        out[5] = c;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = 1;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/fromQuat.js
  var require_fromQuat = __commonJS({
    "node_modules/gl-mat4/fromQuat.js"(exports, module) {
      module.exports = fromQuat;
      function fromQuat(out, q) {
        var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, yx = y * x2, yy = y * y2, zx = z * x2, zy = z * y2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
        out[0] = 1 - yy - zz;
        out[1] = yx + wz;
        out[2] = zx - wy;
        out[3] = 0;
        out[4] = yx - wz;
        out[5] = 1 - xx - zz;
        out[6] = zy + wx;
        out[7] = 0;
        out[8] = zx + wy;
        out[9] = zy - wx;
        out[10] = 1 - xx - yy;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/frustum.js
  var require_frustum = __commonJS({
    "node_modules/gl-mat4/frustum.js"(exports, module) {
      module.exports = frustum;
      function frustum(out, left, right, bottom, top, near, far) {
        var rl = 1 / (right - left), tb = 1 / (top - bottom), nf = 1 / (near - far);
        out[0] = near * 2 * rl;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = near * 2 * tb;
        out[6] = 0;
        out[7] = 0;
        out[8] = (right + left) * rl;
        out[9] = (top + bottom) * tb;
        out[10] = (far + near) * nf;
        out[11] = -1;
        out[12] = 0;
        out[13] = 0;
        out[14] = far * near * 2 * nf;
        out[15] = 0;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/perspective.js
  var require_perspective = __commonJS({
    "node_modules/gl-mat4/perspective.js"(exports, module) {
      module.exports = perspective;
      function perspective(out, fovy, aspect, near, far) {
        var f = 1 / Math.tan(fovy / 2), nf = 1 / (near - far);
        out[0] = f / aspect;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = f;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = (far + near) * nf;
        out[11] = -1;
        out[12] = 0;
        out[13] = 0;
        out[14] = 2 * far * near * nf;
        out[15] = 0;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/perspectiveFromFieldOfView.js
  var require_perspectiveFromFieldOfView = __commonJS({
    "node_modules/gl-mat4/perspectiveFromFieldOfView.js"(exports, module) {
      module.exports = perspectiveFromFieldOfView;
      function perspectiveFromFieldOfView(out, fov, near, far) {
        var upTan = Math.tan(fov.upDegrees * Math.PI / 180), downTan = Math.tan(fov.downDegrees * Math.PI / 180), leftTan = Math.tan(fov.leftDegrees * Math.PI / 180), rightTan = Math.tan(fov.rightDegrees * Math.PI / 180), xScale = 2 / (leftTan + rightTan), yScale = 2 / (upTan + downTan);
        out[0] = xScale;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = yScale;
        out[6] = 0;
        out[7] = 0;
        out[8] = -((leftTan - rightTan) * xScale * 0.5);
        out[9] = (upTan - downTan) * yScale * 0.5;
        out[10] = far / (near - far);
        out[11] = -1;
        out[12] = 0;
        out[13] = 0;
        out[14] = far * near / (near - far);
        out[15] = 0;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/ortho.js
  var require_ortho = __commonJS({
    "node_modules/gl-mat4/ortho.js"(exports, module) {
      module.exports = ortho;
      function ortho(out, left, right, bottom, top, near, far) {
        var lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far);
        out[0] = -2 * lr;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = -2 * bt;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = 2 * nf;
        out[11] = 0;
        out[12] = (left + right) * lr;
        out[13] = (top + bottom) * bt;
        out[14] = (far + near) * nf;
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/lookAt.js
  var require_lookAt = __commonJS({
    "node_modules/gl-mat4/lookAt.js"(exports, module) {
      var identity2 = require_identity();
      module.exports = lookAt;
      function lookAt(out, eye, center, up) {
        var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, eyex = eye[0], eyey = eye[1], eyez = eye[2], upx = up[0], upy = up[1], upz = up[2], centerx = center[0], centery = center[1], centerz = center[2];
        if (Math.abs(eyex - centerx) < 1e-6 && Math.abs(eyey - centery) < 1e-6 && Math.abs(eyez - centerz) < 1e-6) {
          return identity2(out);
        }
        z0 = eyex - centerx;
        z1 = eyey - centery;
        z2 = eyez - centerz;
        len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
        z0 *= len;
        z1 *= len;
        z2 *= len;
        x0 = upy * z2 - upz * z1;
        x1 = upz * z0 - upx * z2;
        x2 = upx * z1 - upy * z0;
        len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
        if (!len) {
          x0 = 0;
          x1 = 0;
          x2 = 0;
        } else {
          len = 1 / len;
          x0 *= len;
          x1 *= len;
          x2 *= len;
        }
        y0 = z1 * x2 - z2 * x1;
        y1 = z2 * x0 - z0 * x2;
        y2 = z0 * x1 - z1 * x0;
        len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
        if (!len) {
          y0 = 0;
          y1 = 0;
          y2 = 0;
        } else {
          len = 1 / len;
          y0 *= len;
          y1 *= len;
          y2 *= len;
        }
        out[0] = x0;
        out[1] = y0;
        out[2] = z0;
        out[3] = 0;
        out[4] = x1;
        out[5] = y1;
        out[6] = z1;
        out[7] = 0;
        out[8] = x2;
        out[9] = y2;
        out[10] = z2;
        out[11] = 0;
        out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
        out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
        out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
        out[15] = 1;
        return out;
      }
    }
  });

  // node_modules/gl-mat4/str.js
  var require_str = __commonJS({
    "node_modules/gl-mat4/str.js"(exports, module) {
      module.exports = str;
      function str(a) {
        return "mat4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ", " + a[9] + ", " + a[10] + ", " + a[11] + ", " + a[12] + ", " + a[13] + ", " + a[14] + ", " + a[15] + ")";
      }
    }
  });

  // node_modules/gl-mat4/index.js
  var require_gl_mat4 = __commonJS({
    "node_modules/gl-mat4/index.js"(exports, module) {
      module.exports = {
        create: require_create(),
        clone: require_clone(),
        copy: require_copy(),
        identity: require_identity(),
        transpose: require_transpose(),
        invert: require_invert(),
        adjoint: require_adjoint(),
        determinant: require_determinant(),
        multiply: require_multiply(),
        translate: require_translate(),
        scale: require_scale(),
        rotate: require_rotate(),
        rotateX: require_rotateX(),
        rotateY: require_rotateY(),
        rotateZ: require_rotateZ(),
        fromRotation: require_fromRotation(),
        fromRotationTranslation: require_fromRotationTranslation(),
        fromScaling: require_fromScaling(),
        fromTranslation: require_fromTranslation(),
        fromXRotation: require_fromXRotation(),
        fromYRotation: require_fromYRotation(),
        fromZRotation: require_fromZRotation(),
        fromQuat: require_fromQuat(),
        frustum: require_frustum(),
        perspective: require_perspective(),
        perspectiveFromFieldOfView: require_perspectiveFromFieldOfView(),
        ortho: require_ortho(),
        lookAt: require_lookAt(),
        str: require_str()
      };
    }
  });

  // src/lib/matrix.js
  var require_matrix = __commonJS({
    "src/lib/matrix.js"(exports) {
      "use strict";
      var mat4X4 = require_gl_mat4();
      exports.init2dArray = function(rowLength, colLength) {
        var array = new Array(rowLength);
        for (var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
        return array;
      };
      exports.transposeRagged = function(z) {
        var maxlen = 0;
        var zlen = z.length;
        var i, j;
        for (i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);
        var t = new Array(maxlen);
        for (i = 0; i < maxlen; i++) {
          t[i] = new Array(zlen);
          for (j = 0; j < zlen; j++) t[i][j] = z[j][i];
        }
        return t;
      };
      exports.dot = function(x, y) {
        if (!(x.length && y.length) || x.length !== y.length) return null;
        var len = x.length;
        var out;
        var i;
        if (x[0].length) {
          out = new Array(len);
          for (i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
        } else if (y[0].length) {
          var yTranspose = exports.transposeRagged(y);
          out = new Array(yTranspose.length);
          for (i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
        } else {
          out = 0;
          for (i = 0; i < len; i++) out += x[i] * y[i];
        }
        return out;
      };
      exports.translationMatrix = function(x, y) {
        return [[1, 0, x], [0, 1, y], [0, 0, 1]];
      };
      exports.rotationMatrix = function(alpha) {
        var a = alpha * Math.PI / 180;
        return [
          [Math.cos(a), -Math.sin(a), 0],
          [Math.sin(a), Math.cos(a), 0],
          [0, 0, 1]
        ];
      };
      exports.rotationXYMatrix = function(a, x, y) {
        return exports.dot(
          exports.dot(
            exports.translationMatrix(x, y),
            exports.rotationMatrix(a)
          ),
          exports.translationMatrix(-x, -y)
        );
      };
      exports.apply3DTransform = function(transform) {
        return function() {
          var args = arguments;
          var xyz = arguments.length === 1 ? args[0] : [args[0], args[1], args[2] || 0];
          return exports.dot(transform, [xyz[0], xyz[1], xyz[2], 1]).slice(0, 3);
        };
      };
      exports.apply2DTransform = function(transform) {
        return function() {
          var args = arguments;
          if (args.length === 3) {
            args = args[0];
          }
          var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
          return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
        };
      };
      exports.apply2DTransform2 = function(transform) {
        var at = exports.apply2DTransform(transform);
        return function(xys) {
          return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
        };
      };
      exports.convertCssMatrix = function(m) {
        if (m) {
          var len = m.length;
          if (len === 16) return m;
          if (len === 6) {
            return [
              m[0],
              m[1],
              0,
              0,
              m[2],
              m[3],
              0,
              0,
              0,
              0,
              1,
              0,
              m[4],
              m[5],
              0,
              1
            ];
          }
        }
        return [
          1,
          0,
          0,
          0,
          0,
          1,
          0,
          0,
          0,
          0,
          1,
          0,
          0,
          0,
          0,
          1
        ];
      };
      exports.inverseTransformMatrix = function(m) {
        var out = [];
        mat4X4.invert(out, m);
        return [
          [out[0], out[1], out[2], out[3]],
          [out[4], out[5], out[6], out[7]],
          [out[8], out[9], out[10], out[11]],
          [out[12], out[13], out[14], out[15]]
        ];
      };
    }
  });

  // src/lib/dom.js
  var require_dom = __commonJS({
    "src/lib/dom.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var loggers = require_loggers();
      var matrix = require_matrix();
      var mat4X4 = require_gl_mat4();
      function getGraphDiv(gd) {
        var gdElement;
        if (typeof gd === "string") {
          gdElement = document.getElementById(gd);
          if (gdElement === null) {
            throw new Error("No DOM element with id '" + gd + "' exists on the page.");
          }
          return gdElement;
        } else if (gd === null || gd === void 0) {
          throw new Error("DOM element provided is null or undefined");
        }
        return gd;
      }
      function isPlotDiv(el) {
        var el3 = d3.select(el);
        return el3.node() instanceof HTMLElement && el3.size() && el3.classed("js-plotly-plot");
      }
      function removeElement(el) {
        var elParent = el && el.parentNode;
        if (elParent) elParent.removeChild(el);
      }
      function addStyleRule(selector, styleString) {
        addRelatedStyleRule("global", selector, styleString);
      }
      function addRelatedStyleRule(uid, selector, styleString) {
        var id = "plotly.js-style-" + uid;
        var style = document.getElementById(id);
        if (style && style.matches(".no-inline-styles")) {
          return;
        }
        if (!style) {
          style = document.createElement("style");
          style.setAttribute("id", id);
          style.appendChild(document.createTextNode(""));
          document.head.appendChild(style);
        }
        var styleSheet = style.sheet;
        if (!styleSheet) {
          loggers.warn("Cannot addRelatedStyleRule, probably due to strict CSP...");
        } else if (styleSheet.insertRule) {
          styleSheet.insertRule(selector + "{" + styleString + "}", 0);
        } else if (styleSheet.addRule) {
          styleSheet.addRule(selector, styleString, 0);
        } else loggers.warn("addStyleRule failed");
      }
      function deleteRelatedStyleRule(uid) {
        var id = "plotly.js-style-" + uid;
        var style = document.getElementById(id);
        if (style) removeElement(style);
      }
      function setStyleOnHover(selector, activeSelector, childSelector, activeStyle, inactiveStyle, element) {
        var activeStyleParts = activeStyle.split(":");
        var inactiveStyleParts = inactiveStyle.split(":");
        var eventAddedAttrName = "data-btn-style-event-added";
        if (!element) {
          element = document;
        }
        element.querySelectorAll(selector).forEach(function(el) {
          if (!el.getAttribute(eventAddedAttrName)) {
            el.addEventListener("mouseenter", function() {
              var childEl = this.querySelector(childSelector);
              if (childEl) {
                childEl.style[activeStyleParts[0]] = activeStyleParts[1];
              }
            });
            el.addEventListener("mouseleave", function() {
              var childEl = this.querySelector(childSelector);
              if (childEl) {
                if (activeSelector && this.matches(activeSelector)) {
                  childEl.style[activeStyleParts[0]] = activeStyleParts[1];
                } else {
                  childEl.style[inactiveStyleParts[0]] = inactiveStyleParts[1];
                }
              }
            });
            el.setAttribute(eventAddedAttrName, true);
          }
        });
      }
      function getFullTransformMatrix(element) {
        var allElements = getElementAndAncestors(element);
        var out = [
          1,
          0,
          0,
          0,
          0,
          1,
          0,
          0,
          0,
          0,
          1,
          0,
          0,
          0,
          0,
          1
        ];
        allElements.forEach(function(e) {
          var t = getElementTransformMatrix(e);
          if (t) {
            var m = matrix.convertCssMatrix(t);
            out = mat4X4.multiply(out, out, m);
          }
        });
        return out;
      }
      function getElementTransformMatrix(element) {
        var style = window.getComputedStyle(element, null);
        var transform = style.getPropertyValue("-webkit-transform") || style.getPropertyValue("-moz-transform") || style.getPropertyValue("-ms-transform") || style.getPropertyValue("-o-transform") || style.getPropertyValue("transform");
        if (transform === "none") return null;
        return transform.replace("matrix", "").replace("3d", "").slice(1, -1).split(",").map(function(n) {
          return +n;
        });
      }
      function getElementAndAncestors(element) {
        var allElements = [];
        while (isTransformableElement(element)) {
          allElements.push(element);
          element = element.parentNode;
          if (typeof ShadowRoot === "function" && element instanceof ShadowRoot) {
            element = element.host;
          }
        }
        return allElements;
      }
      function isTransformableElement(element) {
        return element && (element instanceof Element || element instanceof HTMLElement);
      }
      function equalDomRects(a, b) {
        return a && b && a.top === b.top && a.left === b.left && a.right === b.right && a.bottom === b.bottom;
      }
      module.exports = {
        getGraphDiv,
        isPlotDiv,
        removeElement,
        addStyleRule,
        addRelatedStyleRule,
        deleteRelatedStyleRule,
        setStyleOnHover,
        getFullTransformMatrix,
        getElementTransformMatrix,
        getElementAndAncestors,
        equalDomRects
      };
    }
  });

  // src/plots/animation_attributes.js
  var require_animation_attributes = __commonJS({
    "src/plots/animation_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        mode: {
          valType: "enumerated",
          dflt: "afterall",
          values: ["immediate", "next", "afterall"]
        },
        direction: {
          valType: "enumerated",
          values: ["forward", "reverse"],
          dflt: "forward"
        },
        fromcurrent: {
          valType: "boolean",
          dflt: false
        },
        frame: {
          duration: {
            valType: "number",
            min: 0,
            dflt: 500
          },
          redraw: {
            valType: "boolean",
            dflt: true
          }
        },
        transition: {
          duration: {
            valType: "number",
            min: 0,
            dflt: 500,
            editType: "none"
          },
          easing: {
            valType: "enumerated",
            dflt: "cubic-in-out",
            values: [
              "linear",
              "quad",
              "cubic",
              "sin",
              "exp",
              "circle",
              "elastic",
              "back",
              "bounce",
              "linear-in",
              "quad-in",
              "cubic-in",
              "sin-in",
              "exp-in",
              "circle-in",
              "elastic-in",
              "back-in",
              "bounce-in",
              "linear-out",
              "quad-out",
              "cubic-out",
              "sin-out",
              "exp-out",
              "circle-out",
              "elastic-out",
              "back-out",
              "bounce-out",
              "linear-in-out",
              "quad-in-out",
              "cubic-in-out",
              "sin-in-out",
              "exp-in-out",
              "circle-in-out",
              "elastic-in-out",
              "back-in-out",
              "bounce-in-out"
            ],
            editType: "none"
          },
          ordering: {
            valType: "enumerated",
            values: ["layout first", "traces first"],
            dflt: "layout first",
            editType: "none"
          }
        }
      };
    }
  });

  // src/plot_api/edit_types.js
  var require_edit_types = __commonJS({
    "src/plot_api/edit_types.js"(exports, module) {
      "use strict";
      var extendFlat = require_extend().extendFlat;
      var isPlainObject = require_is_plain_object();
      var traceOpts = {
        valType: "flaglist",
        extras: ["none"],
        flags: ["calc", "clearAxisTypes", "plot", "style", "markerSize", "colorbars"]
      };
      var layoutOpts = {
        valType: "flaglist",
        extras: ["none"],
        flags: [
          "calc",
          "plot",
          "legend",
          "ticks",
          "axrange",
          "layoutstyle",
          "modebar",
          "camera",
          "arraydraw",
          "colorbars"
        ]
      };
      var traceEditTypeFlags = traceOpts.flags.slice().concat(["fullReplot"]);
      var layoutEditTypeFlags = layoutOpts.flags.slice().concat("layoutReplot");
      module.exports = {
        traces: traceOpts,
        layout: layoutOpts,
        /*
         * default (all false) edit flags for restyle (traces)
         * creates a new object each call, so the caller can mutate freely
         */
        traceFlags: function() {
          return falseObj(traceEditTypeFlags);
        },
        /*
         * default (all false) edit flags for relayout
         * creates a new object each call, so the caller can mutate freely
         */
        layoutFlags: function() {
          return falseObj(layoutEditTypeFlags);
        },
        /*
         * update `flags` with the `editType` values found in `attr`
         */
        update: function(flags, attr) {
          var editType = attr.editType;
          if (editType && editType !== "none") {
            var editTypeParts = editType.split("+");
            for (var i = 0; i < editTypeParts.length; i++) {
              flags[editTypeParts[i]] = true;
            }
          }
        },
        overrideAll
      };
      function falseObj(keys) {
        var out = {};
        for (var i = 0; i < keys.length; i++) out[keys[i]] = false;
        return out;
      }
      function overrideAll(attrs, editTypeOverride, overrideContainers) {
        var out = extendFlat({}, attrs);
        for (var key in out) {
          var attr = out[key];
          if (isPlainObject(attr)) {
            out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key);
          }
        }
        if (overrideContainers === "from-root") out.editType = editTypeOverride;
        return out;
      }
      function overrideOne(attr, editTypeOverride, overrideContainers, key) {
        if (attr.valType) {
          var out = extendFlat({}, attr);
          out.editType = editTypeOverride;
          if (Array.isArray(attr.items)) {
            out.items = new Array(attr.items.length);
            for (var i = 0; i < attr.items.length; i++) {
              out.items[i] = overrideOne(attr.items[i], editTypeOverride, "from-root");
            }
          }
          return out;
        } else {
          return overrideAll(
            attr,
            editTypeOverride,
            key.charAt(0) === "_" ? "nested" : "from-root"
          );
        }
      }
    }
  });

  // src/components/drawing/attributes.js
  var require_attributes4 = __commonJS({
    "src/components/drawing/attributes.js"(exports) {
      "use strict";
      exports.dash = {
        valType: "string",
        // string type usually doesn't take values... this one should really be
        // a special type or at least a special coercion function, from the GUI
        // you only get these values but elsewhere the user can supply a list of
        // dash lengths in px, and it will be honored
        values: ["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"],
        dflt: "solid",
        editType: "style"
      };
      exports.pattern = {
        shape: {
          valType: "enumerated",
          values: ["", "/", "\\", "x", "-", "|", "+", "."],
          dflt: "",
          arrayOk: true,
          editType: "style"
        },
        path: {
          valType: "string",
          arrayOk: true,
          editType: "style"
        },
        fillmode: {
          valType: "enumerated",
          values: ["replace", "overlay"],
          dflt: "replace",
          editType: "style"
        },
        bgcolor: {
          valType: "color",
          arrayOk: true,
          editType: "style"
        },
        fgcolor: {
          valType: "color",
          arrayOk: true,
          editType: "style"
        },
        fgopacity: {
          valType: "number",
          editType: "style",
          min: 0,
          max: 1
        },
        size: {
          valType: "number",
          min: 0,
          dflt: 8,
          arrayOk: true,
          editType: "style"
        },
        solidity: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0.3,
          arrayOk: true,
          editType: "style"
        },
        editType: "style"
      };
    }
  });

  // src/constants/docs.js
  var require_docs = __commonJS({
    "src/constants/docs.js"(exports, module) {
      "use strict";
      module.exports = {
        FORMAT_LINK: "https://github.com/d3/d3-format/tree/v1.4.5#d3-format",
        DATE_FORMAT_LINK: "https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format"
      };
    }
  });

  // src/plots/template_attributes.js
  var require_template_attributes = __commonJS({
    "src/plots/template_attributes.js"(exports) {
      "use strict";
      var { DATE_FORMAT_LINK, FORMAT_LINK } = require_docs();
      var MISSING_UNDEFINED_DESCRIPTION = [
        "Variables that can't be found will be replaced with the specifier.",
        'For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing.',
        "Variables with an undefined value will be replaced with the fallback value."
      ].join(" ");
      function templateFormatStringDescription({ supportOther } = {}) {
        const supportOtherText = " as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, *xother* will be added to those with different x positions from the first point. An underscore before or after *(x|y)other* will add a space on that side, only when this field is shown.";
        return [
          "Variables are inserted using %{variable},",
          'for example "y: %{y}"' + (supportOther ? supportOtherText : "."),
          `Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}".`,
          FORMAT_LINK,
          "for details on the formatting syntax.",
          `Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}".`,
          DATE_FORMAT_LINK,
          "for details on the date formatting syntax.",
          MISSING_UNDEFINED_DESCRIPTION
        ].join(" ");
      }
      exports.templateFormatStringDescription = templateFormatStringDescription;
      exports.hovertemplateAttrs = ({ editType = "none", arrayOk } = {}, extra = {}) => __spreadValues({
        valType: "string",
        dflt: "",
        editType
      }, arrayOk !== false ? { arrayOk: true } : {});
      exports.texttemplateAttrs = ({ editType = "calc", arrayOk } = {}, extra = {}) => __spreadValues({
        valType: "string",
        dflt: "",
        editType
      }, arrayOk !== false ? { arrayOk: true } : {});
      exports.shapeTexttemplateAttrs = ({ editType = "arraydraw", newshape } = {}, extra = {}) => ({
        valType: "string",
        dflt: "",
        editType
      });
      exports.templatefallbackAttrs = ({ editType = "none" } = {}) => ({
        valType: "any",
        dflt: "-",
        editType
      });
    }
  });

  // src/components/shapes/label_texttemplate.js
  var require_label_texttemplate = __commonJS({
    "src/components/shapes/label_texttemplate.js"(exports, module) {
      "use strict";
      function d2l(v, axis) {
        return axis ? axis.d2l(v) : v;
      }
      function l2d(v, axis) {
        return axis ? axis.l2d(v) : v;
      }
      function x0Fn(shape) {
        return shape.x0;
      }
      function x1Fn(shape) {
        return shape.x1;
      }
      function y0Fn(shape) {
        return shape.y0;
      }
      function y1Fn(shape) {
        return shape.y1;
      }
      function x0shiftFn(shape) {
        return shape.x0shift || 0;
      }
      function x1shiftFn(shape) {
        return shape.x1shift || 0;
      }
      function y0shiftFn(shape) {
        return shape.y0shift || 0;
      }
      function y1shiftFn(shape) {
        return shape.y1shift || 0;
      }
      function dxFn(shape, xa) {
        return d2l(shape.x1, xa) + x1shiftFn(shape) - d2l(shape.x0, xa) - x0shiftFn(shape);
      }
      function dyFn(shape, xa, ya) {
        return d2l(shape.y1, ya) + y1shiftFn(shape) - d2l(shape.y0, ya) - y0shiftFn(shape);
      }
      function widthFn(shape, xa) {
        return Math.abs(dxFn(shape, xa));
      }
      function heightFn(shape, xa, ya) {
        return Math.abs(dyFn(shape, xa, ya));
      }
      function lengthFn(shape, xa, ya) {
        return shape.type !== "line" ? void 0 : Math.sqrt(
          Math.pow(dxFn(shape, xa), 2) + Math.pow(dyFn(shape, xa, ya), 2)
        );
      }
      function xcenterFn(shape, xa) {
        return l2d((d2l(shape.x1, xa) + x1shiftFn(shape) + d2l(shape.x0, xa) + x0shiftFn(shape)) / 2, xa);
      }
      function ycenterFn(shape, xa, ya) {
        return l2d((d2l(shape.y1, ya) + y1shiftFn(shape) + d2l(shape.y0, ya) + y0shiftFn(shape)) / 2, ya);
      }
      function slopeFn(shape, xa, ya) {
        return shape.type !== "line" ? void 0 : dyFn(shape, xa, ya) / dxFn(shape, xa);
      }
      var simpleXVariables = ["x0", "x1", "y0", "y1", "dy", "height", "ycenter"];
      var simpleYVariables = ["x0", "x1", "y0", "y1", "dx", "width", "xcenter"];
      module.exports = {
        x0: x0Fn,
        x1: x1Fn,
        y0: y0Fn,
        y1: y1Fn,
        slope: slopeFn,
        dx: dxFn,
        dy: dyFn,
        width: widthFn,
        height: heightFn,
        length: lengthFn,
        xcenter: xcenterFn,
        ycenter: ycenterFn,
        simpleXVariables,
        simpleYVariables
      };
    }
  });

  // src/components/shapes/draw_newshape/attributes.js
  var require_attributes5 = __commonJS({
    "src/components/shapes/draw_newshape/attributes.js"(exports, module) {
      "use strict";
      var overrideAll = require_edit_types().overrideAll;
      var basePlotAttributes = require_attributes2();
      var fontAttrs = require_font_attributes();
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      var { shapeTexttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var shapeLabelTexttemplateVars = require_label_texttemplate();
      module.exports = overrideAll(
        {
          newshape: {
            visible: extendFlat({}, basePlotAttributes.visible, {}),
            showlegend: {
              valType: "boolean",
              dflt: false
            },
            legend: extendFlat({}, basePlotAttributes.legend, {}),
            legendgroup: extendFlat({}, basePlotAttributes.legendgroup, {}),
            legendgrouptitle: {
              text: extendFlat({}, basePlotAttributes.legendgrouptitle.text, {}),
              font: fontAttrs({})
            },
            legendrank: extendFlat({}, basePlotAttributes.legendrank, {}),
            legendwidth: extendFlat({}, basePlotAttributes.legendwidth, {}),
            line: {
              color: {
                valType: "color"
              },
              width: {
                valType: "number",
                min: 0,
                dflt: 4
              },
              dash: extendFlat({}, dash, {
                dflt: "solid"
              })
            },
            fillcolor: {
              valType: "color",
              dflt: "rgba(0,0,0,0)"
            },
            fillrule: {
              valType: "enumerated",
              values: ["evenodd", "nonzero"],
              dflt: "evenodd"
            },
            opacity: {
              valType: "number",
              min: 0,
              max: 1,
              dflt: 1
            },
            layer: {
              valType: "enumerated",
              values: ["below", "above", "between"],
              dflt: "above"
            },
            drawdirection: {
              valType: "enumerated",
              values: ["ortho", "horizontal", "vertical", "diagonal"],
              dflt: "diagonal"
            },
            name: extendFlat({}, basePlotAttributes.name, {}),
            label: {
              text: {
                valType: "string",
                dflt: ""
              },
              texttemplate: shapeTexttemplateAttrs(
                { newshape: true },
                { keys: Object.keys(shapeLabelTexttemplateVars) }
              ),
              texttemplatefallback: templatefallbackAttrs({ editType: "arraydraw" }),
              font: fontAttrs({}),
              textposition: {
                valType: "enumerated",
                values: [
                  "top left",
                  "top center",
                  "top right",
                  "middle left",
                  "middle center",
                  "middle right",
                  "bottom left",
                  "bottom center",
                  "bottom right",
                  "start",
                  "middle",
                  "end"
                ]
              },
              textangle: {
                valType: "angle",
                dflt: "auto"
              },
              xanchor: {
                valType: "enumerated",
                values: ["auto", "left", "center", "right"],
                dflt: "auto"
              },
              yanchor: {
                valType: "enumerated",
                values: ["top", "middle", "bottom"]
              },
              padding: {
                valType: "number",
                dflt: 3,
                min: 0
              }
            }
          },
          activeshape: {
            fillcolor: {
              valType: "color",
              dflt: "rgb(255,0,255)",
              description: "Sets the color filling the active shape' interior."
            },
            opacity: {
              valType: "number",
              min: 0,
              max: 1,
              dflt: 0.5
            }
          }
        },
        "none",
        "from-root"
      );
    }
  });

  // src/components/selections/draw_newselection/attributes.js
  var require_attributes6 = __commonJS({
    "src/components/selections/draw_newselection/attributes.js"(exports, module) {
      "use strict";
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      module.exports = {
        newselection: {
          mode: {
            valType: "enumerated",
            values: ["immediate", "gradual"],
            dflt: "immediate",
            editType: "none"
          },
          line: {
            color: {
              valType: "color",
              editType: "none"
            },
            width: {
              valType: "number",
              min: 1,
              dflt: 1,
              editType: "none"
            },
            dash: extendFlat({}, dash, {
              dflt: "dot",
              editType: "none"
            }),
            editType: "none"
          },
          // no drawdirection here noting that layout.selectdirection is used instead.
          editType: "none"
        },
        activeselection: {
          fillcolor: {
            valType: "color",
            dflt: "rgba(0,0,0,0)",
            editType: "none"
          },
          opacity: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 0.5,
            editType: "none"
          },
          editType: "none"
        }
      };
    }
  });

  // src/plots/pad_attributes.js
  var require_pad_attributes = __commonJS({
    "src/plots/pad_attributes.js"(exports, module) {
      "use strict";
      module.exports = function(opts) {
        var editType = opts.editType;
        return {
          t: {
            valType: "number",
            dflt: 0,
            editType
          },
          r: {
            valType: "number",
            dflt: 0,
            editType
          },
          b: {
            valType: "number",
            dflt: 0,
            editType
          },
          l: {
            valType: "number",
            dflt: 0,
            editType
          },
          editType
        };
      };
    }
  });

  // src/plots/layout_attributes.js
  var require_layout_attributes2 = __commonJS({
    "src/plots/layout_attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var animationAttrs = require_animation_attributes();
      var colorAttrs = require_attributes3();
      var drawNewShapeAttrs = require_attributes5();
      var drawNewSelectionAttrs = require_attributes6();
      var padAttrs = require_pad_attributes();
      var extendFlat = require_extend().extendFlat;
      var globalFont = fontAttrs({
        editType: "calc"
      });
      globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
      globalFont.size.dflt = 12;
      globalFont.color.dflt = colorAttrs.defaultLine;
      module.exports = {
        font: globalFont,
        title: {
          text: {
            valType: "string",
            editType: "layoutstyle"
          },
          font: fontAttrs({
            editType: "layoutstyle"
          }),
          subtitle: {
            text: {
              valType: "string",
              editType: "layoutstyle"
            },
            font: fontAttrs({
              editType: "layoutstyle"
            }),
            editType: "layoutstyle"
          },
          xref: {
            valType: "enumerated",
            dflt: "container",
            values: ["container", "paper"],
            editType: "layoutstyle"
          },
          yref: {
            valType: "enumerated",
            dflt: "container",
            values: ["container", "paper"],
            editType: "layoutstyle"
          },
          x: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 0.5,
            editType: "layoutstyle"
          },
          y: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: "auto",
            editType: "layoutstyle"
          },
          xanchor: {
            valType: "enumerated",
            dflt: "auto",
            values: ["auto", "left", "center", "right"],
            editType: "layoutstyle"
          },
          yanchor: {
            valType: "enumerated",
            dflt: "auto",
            values: ["auto", "top", "middle", "bottom"],
            editType: "layoutstyle"
          },
          pad: extendFlat(padAttrs({ editType: "layoutstyle" }), {}),
          automargin: {
            valType: "boolean",
            dflt: false,
            editType: "plot"
          },
          editType: "layoutstyle"
        },
        uniformtext: {
          mode: {
            valType: "enumerated",
            values: [false, "hide", "show"],
            dflt: false,
            editType: "plot"
          },
          minsize: {
            valType: "number",
            min: 0,
            dflt: 0,
            editType: "plot"
          },
          editType: "plot"
        },
        autosize: {
          valType: "boolean",
          dflt: false,
          // autosize, width, and height get special editType treatment in _relayout
          // so we can handle noop resizes more efficiently
          editType: "none"
        },
        width: {
          valType: "number",
          min: 10,
          dflt: 700,
          editType: "plot"
        },
        height: {
          valType: "number",
          min: 10,
          dflt: 450,
          editType: "plot"
        },
        minreducedwidth: {
          valType: "number",
          min: 2,
          dflt: 64,
          editType: "plot"
        },
        minreducedheight: {
          valType: "number",
          min: 2,
          dflt: 64,
          editType: "plot"
        },
        margin: {
          l: {
            valType: "number",
            min: 0,
            dflt: 80,
            editType: "plot"
          },
          r: {
            valType: "number",
            min: 0,
            dflt: 80,
            editType: "plot"
          },
          t: {
            valType: "number",
            min: 0,
            dflt: 100,
            editType: "plot"
          },
          b: {
            valType: "number",
            min: 0,
            dflt: 80,
            editType: "plot"
          },
          pad: {
            valType: "number",
            min: 0,
            dflt: 0,
            editType: "plot"
          },
          autoexpand: {
            valType: "boolean",
            dflt: true,
            editType: "plot"
          },
          editType: "plot"
        },
        computed: {
          valType: "any",
          editType: "none"
        },
        paper_bgcolor: {
          valType: "color",
          dflt: colorAttrs.background,
          editType: "plot"
        },
        plot_bgcolor: {
          // defined here, but set in cartesian.supplyLayoutDefaults
          // because it needs to know if there are (2D) axes or not
          valType: "color",
          dflt: colorAttrs.background,
          editType: "layoutstyle"
        },
        autotypenumbers: {
          valType: "enumerated",
          values: ["convert types", "strict"],
          dflt: "convert types",
          editType: "calc"
        },
        separators: {
          valType: "string",
          editType: "plot"
        },
        hidesources: {
          valType: "boolean",
          dflt: false,
          editType: "plot"
        },
        showlegend: {
          // handled in legend.supplyLayoutDefaults
          // but included here because it's not in the legend object
          valType: "boolean",
          editType: "legend"
        },
        colorway: {
          valType: "colorlist",
          dflt: colorAttrs.defaults,
          editType: "calc"
        },
        datarevision: {
          valType: "any",
          editType: "calc"
        },
        uirevision: {
          valType: "any",
          editType: "none"
        },
        editrevision: {
          valType: "any",
          editType: "none"
        },
        selectionrevision: {
          valType: "any",
          editType: "none"
        },
        template: {
          valType: "any",
          editType: "calc"
        },
        newshape: drawNewShapeAttrs.newshape,
        activeshape: drawNewShapeAttrs.activeshape,
        newselection: drawNewSelectionAttrs.newselection,
        activeselection: drawNewSelectionAttrs.activeselection,
        meta: {
          valType: "any",
          arrayOk: true,
          editType: "plot"
        },
        transition: extendFlat({}, animationAttrs.transition, {
          editType: "none"
        })
      };
    }
  });

  // node_modules/maplibre-gl/dist/maplibre-gl.css
  var require_maplibre_gl = __commonJS({
    "node_modules/maplibre-gl/dist/maplibre-gl.css"() {
      (function() {
        if (!document.getElementById("a75c73da1cd7a97e8992659f6aed556255838daadea9ca0c9fc3af7f1ddf63c0")) {
          var e = document.createElement("style");
          e.id = "a75c73da1cd7a97e8992659f6aed556255838daadea9ca0c9fc3af7f1ddf63c0";
          e.textContent = `.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0 0 0/0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}.maplibregl-ctrl button:not(:disabled):hover{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgb(0 0 0/5%)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(width <= 480px){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999}`;
          document.head.appendChild(e);
        }
      })();
    }
  });

  // src/registry.js
  var require_registry = __commonJS({
    "src/registry.js"(exports) {
      "use strict";
      var Loggers = require_loggers();
      var noop = require_noop();
      var pushUnique = require_push_unique();
      var isPlainObject = require_is_plain_object();
      var addStyleRule = require_dom().addStyleRule;
      var ExtendModule = require_extend();
      var basePlotAttributes = require_attributes2();
      var baseLayoutAttributes = require_layout_attributes2();
      var extendFlat = ExtendModule.extendFlat;
      var extendDeepAll = ExtendModule.extendDeepAll;
      exports.modules = {};
      exports.allCategories = {};
      exports.allTypes = [];
      exports.subplotsRegistry = {};
      exports.componentsRegistry = {};
      exports.layoutArrayContainers = [];
      exports.layoutArrayRegexes = [];
      exports.traceLayoutAttributes = {};
      exports.localeRegistry = {};
      exports.apiMethodRegistry = {};
      exports.collectableSubplotTypes = null;
      exports.register = function register(_modules) {
        exports.collectableSubplotTypes = null;
        if (!_modules) {
          throw new Error("No argument passed to Plotly.register.");
        } else if (_modules && !Array.isArray(_modules)) {
          _modules = [_modules];
        }
        for (var i = 0; i < _modules.length; i++) {
          var newModule = _modules[i];
          if (!newModule) {
            throw new Error("Invalid module was attempted to be registered!");
          }
          switch (newModule.moduleType) {
            case "trace":
              registerTraceModule(newModule);
              break;
            case "transform":
              registerTransformModule(newModule);
              break;
            case "component":
              registerComponentModule(newModule);
              break;
            case "locale":
              registerLocale(newModule);
              break;
            case "apiMethod":
              var name2 = newModule.name;
              exports.apiMethodRegistry[name2] = newModule.fn;
              break;
            default:
              throw new Error("Invalid module was attempted to be registered!");
          }
        }
      };
      exports.getModule = function(trace) {
        var _module = exports.modules[getTraceType(trace)];
        if (!_module) return false;
        return _module._module;
      };
      exports.traceIs = function(traceType, category) {
        traceType = getTraceType(traceType);
        if (traceType === "various") return false;
        var _module = exports.modules[traceType];
        if (!_module) {
          if (traceType) {
            Loggers.log("Unrecognized trace type " + traceType + ".");
          }
          _module = exports.modules[basePlotAttributes.type.dflt];
        }
        return !!_module.categories[category];
      };
      exports.getComponentMethod = function(name2, method) {
        var _module = exports.componentsRegistry[name2];
        if (!_module) return noop;
        return _module[method] || noop;
      };
      exports.call = function() {
        var name2 = arguments[0];
        var args = [].slice.call(arguments, 1);
        return exports.apiMethodRegistry[name2].apply(null, args);
      };
      function registerTraceModule(_module) {
        var thisType = _module.name;
        var categoriesIn = _module.categories;
        var meta = _module.meta;
        if (exports.modules[thisType]) {
          Loggers.log("Type " + thisType + " already registered");
          return;
        }
        if (!exports.subplotsRegistry[_module.basePlotModule.name]) {
          registerSubplot(_module.basePlotModule);
        }
        var categoryObj = {};
        for (var i = 0; i < categoriesIn.length; i++) {
          categoryObj[categoriesIn[i]] = true;
          exports.allCategories[categoriesIn[i]] = true;
        }
        exports.modules[thisType] = {
          _module,
          categories: categoryObj
        };
        if (meta && Object.keys(meta).length) {
          exports.modules[thisType].meta = meta;
        }
        exports.allTypes.push(thisType);
        for (var componentName in exports.componentsRegistry) {
          mergeComponentAttrsToTrace(componentName, thisType);
        }
        if (_module.layoutAttributes) {
          extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
        }
        var basePlotModule = _module.basePlotModule;
        var bpmName = basePlotModule.name;
        if (bpmName === "mapbox") {
          var styleRules = basePlotModule.constants.styleRules;
          for (var k in styleRules) {
            addStyleRule(".js-plotly-plot .plotly .mapboxgl-" + k, styleRules[k]);
          }
        }
        if (bpmName === "map") {
          require_maplibre_gl();
        }
        if ((bpmName === "geo" || bpmName === "mapbox" || bpmName === "map") && window.PlotlyGeoAssets === void 0) {
          window.PlotlyGeoAssets = { topojson: {} };
        }
      }
      function registerSubplot(_module) {
        var plotType = _module.name;
        if (exports.subplotsRegistry[plotType]) {
          Loggers.log("Plot type " + plotType + " already registered.");
          return;
        }
        findArrayRegexps(_module);
        exports.subplotsRegistry[plotType] = _module;
        for (var componentName in exports.componentsRegistry) {
          mergeComponentAttrsToSubplot(componentName, _module.name);
        }
      }
      function registerComponentModule(_module) {
        if (typeof _module.name !== "string") {
          throw new Error("Component module *name* must be a string.");
        }
        var name2 = _module.name;
        exports.componentsRegistry[name2] = _module;
        if (_module.layoutAttributes) {
          if (_module.layoutAttributes._isLinkedToArray) {
            pushUnique(exports.layoutArrayContainers, name2);
          }
          findArrayRegexps(_module);
        }
        for (var traceType in exports.modules) {
          mergeComponentAttrsToTrace(name2, traceType);
        }
        for (var subplotName in exports.subplotsRegistry) {
          mergeComponentAttrsToSubplot(name2, subplotName);
        }
        if (_module.schema && _module.schema.layout) {
          extendDeepAll(baseLayoutAttributes, _module.schema.layout);
        }
      }
      function registerTransformModule(_module) {
        if (typeof _module.name !== "string") {
          throw new Error("Transform module *name* must be a string.");
        }
        var prefix = "Transform module " + _module.name;
        var hasTransform = typeof _module.transform === "function";
        var hasCalcTransform = typeof _module.calcTransform === "function";
        if (!hasTransform && !hasCalcTransform) {
          throw new Error(prefix + " is missing a *transform* or *calcTransform* method.");
        }
        if (hasTransform && hasCalcTransform) {
          Loggers.log([
            prefix + " has both a *transform* and *calcTransform* methods.",
            "Please note that all *transform* methods are executed",
            "before all *calcTransform* methods."
          ].join(" "));
        }
        if (!isPlainObject(_module.attributes)) {
          Loggers.log(prefix + " registered without an *attributes* object.");
        }
        if (typeof _module.supplyDefaults !== "function") {
          Loggers.log(prefix + " registered without a *supplyDefaults* method.");
        }
      }
      function registerLocale(_module) {
        var locale = _module.name;
        var baseLocale = locale.split("-")[0];
        var newDict = _module.dictionary;
        var newFormat = _module.format;
        var hasDict = newDict && Object.keys(newDict).length;
        var hasFormat = newFormat && Object.keys(newFormat).length;
        var locales = exports.localeRegistry;
        var localeObj = locales[locale];
        if (!localeObj) locales[locale] = localeObj = {};
        if (baseLocale !== locale) {
          var baseLocaleObj = locales[baseLocale];
          if (!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};
          if (hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
            baseLocaleObj.dictionary = newDict;
          }
          if (hasFormat && baseLocaleObj.format === localeObj.format) {
            baseLocaleObj.format = newFormat;
          }
        }
        if (hasDict) localeObj.dictionary = newDict;
        if (hasFormat) localeObj.format = newFormat;
      }
      function findArrayRegexps(_module) {
        if (_module.layoutAttributes) {
          var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
          if (arrayAttrRegexps) {
            for (var i = 0; i < arrayAttrRegexps.length; i++) {
              pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
            }
          }
        }
      }
      function mergeComponentAttrsToTrace(componentName, traceType) {
        var componentSchema = exports.componentsRegistry[componentName].schema;
        if (!componentSchema || !componentSchema.traces) return;
        var traceAttrs = componentSchema.traces[traceType];
        if (traceAttrs) {
          extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
        }
      }
      function mergeComponentAttrsToSubplot(componentName, subplotName) {
        var componentSchema = exports.componentsRegistry[componentName].schema;
        if (!componentSchema || !componentSchema.subplots) return;
        var subplotModule = exports.subplotsRegistry[subplotName];
        var subplotAttrs = subplotModule.layoutAttributes;
        var subplotAttr = subplotModule.attr === "subplot" ? subplotModule.name : subplotModule.attr;
        if (Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];
        var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
        if (subplotAttrs && componentLayoutAttrs) {
          extendDeepAll(subplotAttrs, componentLayoutAttrs);
        }
      }
      function getTraceType(traceType) {
        if (typeof traceType === "object") traceType = traceType.type;
        return traceType;
      }
    }
  });

  // src/lib/dates.js
  var require_dates = __commonJS({
    "src/lib/dates.js"(exports) {
      "use strict";
      var timeFormat = require_d3_time_format().timeFormat;
      var isNumeric = require_fast_isnumeric();
      var Loggers = require_loggers();
      var mod = require_mod().mod;
      var constants = require_numerical();
      var BADNUM = constants.BADNUM;
      var ONEDAY = constants.ONEDAY;
      var ONEHOUR = constants.ONEHOUR;
      var ONEMIN = constants.ONEMIN;
      var ONESEC = constants.ONESEC;
      var EPOCHJD = constants.EPOCHJD;
      var Registry = require_registry();
      var utcFormat = require_d3_time_format().utcFormat;
      var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m;
      var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m;
      var YFIRST = (/* @__PURE__ */ new Date()).getFullYear() - 70;
      function isWorldCalendar(calendar) {
        return calendar && Registry.componentsRegistry.calendars && typeof calendar === "string" && calendar !== "gregorian";
      }
      exports.dateTick0 = function(calendar, dayOfWeek) {
        var tick0 = _dateTick0(calendar, !!dayOfWeek);
        if (dayOfWeek < 2) return tick0;
        var v = exports.dateTime2ms(tick0, calendar);
        v += ONEDAY * (dayOfWeek - 1);
        return exports.ms2DateTime(v, 0, calendar);
      };
      function _dateTick0(calendar, sunday) {
        if (isWorldCalendar(calendar)) {
          return sunday ? Registry.getComponentMethod("calendars", "CANONICAL_SUNDAY")[calendar] : Registry.getComponentMethod("calendars", "CANONICAL_TICK")[calendar];
        } else {
          return sunday ? "2000-01-02" : "2000-01-01";
        }
      }
      exports.dfltRange = function(calendar) {
        if (isWorldCalendar(calendar)) {
          return Registry.getComponentMethod("calendars", "DFLTRANGE")[calendar];
        } else {
          return ["2000-01-01", "2001-01-01"];
        }
      };
      exports.isJSDate = function(v) {
        return typeof v === "object" && v !== null && typeof v.getTime === "function";
      };
      var MIN_MS;
      var MAX_MS;
      exports.dateTime2ms = function(s, calendar) {
        if (exports.isJSDate(s)) {
          var tzOffset = s.getTimezoneOffset() * ONEMIN;
          var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN + (s.getUTCSeconds() - s.getSeconds()) * ONESEC + (s.getUTCMilliseconds() - s.getMilliseconds());
          if (offsetTweak) {
            var comb = 3 * ONEMIN;
            tzOffset = tzOffset - comb / 2 + mod(offsetTweak - tzOffset + comb / 2, comb);
          }
          s = Number(s) - tzOffset;
          if (s >= MIN_MS && s <= MAX_MS) return s;
          return BADNUM;
        }
        if (typeof s !== "string" && typeof s !== "number") return BADNUM;
        s = String(s);
        var isWorld = isWorldCalendar(calendar);
        var s0 = s.charAt(0);
        if (isWorld && (s0 === "G" || s0 === "g")) {
          s = s.slice(1);
          calendar = "";
        }
        var isChinese = isWorld && calendar.slice(0, 7) === "chinese";
        var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
        if (!match) return BADNUM;
        var y = match[1];
        var m = match[3] || "1";
        var d = Number(match[5] || 1);
        var H = Number(match[7] || 0);
        var M = Number(match[9] || 0);
        var S = Number(match[11] || 0);
        if (isWorld) {
          if (y.length === 2) return BADNUM;
          y = Number(y);
          var cDate;
          try {
            var calInstance = Registry.getComponentMethod("calendars", "getCal")(calendar);
            if (isChinese) {
              var isIntercalary = m.charAt(m.length - 1) === "i";
              m = parseInt(m, 10);
              cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
            } else {
              cDate = calInstance.newDate(y, Number(m), d);
            }
          } catch (e) {
            return BADNUM;
          }
          if (!cDate) return BADNUM;
          return (cDate.toJD() - EPOCHJD) * ONEDAY + H * ONEHOUR + M * ONEMIN + S * ONESEC;
        }
        if (y.length === 2) {
          y = (Number(y) + 2e3 - YFIRST) % 100 + YFIRST;
        } else y = Number(y);
        m -= 1;
        var date = new Date(Date.UTC(2e3, m, d, H, M));
        date.setUTCFullYear(y);
        if (date.getUTCMonth() !== m) return BADNUM;
        if (date.getUTCDate() !== d) return BADNUM;
        return date.getTime() + S * ONESEC;
      };
      MIN_MS = exports.MIN_MS = exports.dateTime2ms("-9999");
      MAX_MS = exports.MAX_MS = exports.dateTime2ms("9999-12-31 23:59:59.9999");
      exports.isDateTime = function(s, calendar) {
        return exports.dateTime2ms(s, calendar) !== BADNUM;
      };
      function lpad(val, digits) {
        return String(val + Math.pow(10, digits)).slice(1);
      }
      var NINETYDAYS = 90 * ONEDAY;
      var THREEHOURS = 3 * ONEHOUR;
      var FIVEMIN = 5 * ONEMIN;
      exports.ms2DateTime = function(ms, r, calendar) {
        if (typeof ms !== "number" || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;
        if (!r) r = 0;
        var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
        var msRounded = Math.round(ms - msecTenths / 10);
        var dateStr, h, m, s, msec10, d;
        if (isWorldCalendar(calendar)) {
          var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD;
          var timeMs = Math.floor(mod(ms, ONEDAY));
          try {
            dateStr = Registry.getComponentMethod("calendars", "getCal")(calendar).fromJD(dateJD).formatDate("yyyy-mm-dd");
          } catch (e) {
            dateStr = utcFormat("G%Y-%m-%d")(new Date(msRounded));
          }
          if (dateStr.charAt(0) === "-") {
            while (dateStr.length < 11) dateStr = "-0" + dateStr.slice(1);
          } else {
            while (dateStr.length < 10) dateStr = "0" + dateStr;
          }
          h = r < NINETYDAYS ? Math.floor(timeMs / ONEHOUR) : 0;
          m = r < NINETYDAYS ? Math.floor(timeMs % ONEHOUR / ONEMIN) : 0;
          s = r < THREEHOURS ? Math.floor(timeMs % ONEMIN / ONESEC) : 0;
          msec10 = r < FIVEMIN ? timeMs % ONESEC * 10 + msecTenths : 0;
        } else {
          d = new Date(msRounded);
          dateStr = utcFormat("%Y-%m-%d")(d);
          h = r < NINETYDAYS ? d.getUTCHours() : 0;
          m = r < NINETYDAYS ? d.getUTCMinutes() : 0;
          s = r < THREEHOURS ? d.getUTCSeconds() : 0;
          msec10 = r < FIVEMIN ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
        }
        return includeTime(dateStr, h, m, s, msec10);
      };
      exports.ms2DateTimeLocal = function(ms) {
        if (!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;
        var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
        var d = new Date(Math.round(ms - msecTenths / 10));
        var dateStr = timeFormat("%Y-%m-%d")(d);
        var h = d.getHours();
        var m = d.getMinutes();
        var s = d.getSeconds();
        var msec10 = d.getUTCMilliseconds() * 10 + msecTenths;
        return includeTime(dateStr, h, m, s, msec10);
      };
      function includeTime(dateStr, h, m, s, msec10) {
        if (h || m || s || msec10) {
          dateStr += " " + lpad(h, 2) + ":" + lpad(m, 2);
          if (s || msec10) {
            dateStr += ":" + lpad(s, 2);
            if (msec10) {
              var digits = 4;
              while (msec10 % 10 === 0) {
                digits -= 1;
                msec10 /= 10;
              }
              dateStr += "." + lpad(msec10, digits);
            }
          }
        }
        return dateStr;
      }
      exports.cleanDate = function(v, dflt, calendar) {
        if (v === BADNUM) return dflt;
        if (exports.isJSDate(v) || typeof v === "number" && isFinite(v)) {
          if (isWorldCalendar(calendar)) {
            Loggers.error("JS Dates and milliseconds are incompatible with world calendars", v);
            return dflt;
          }
          v = exports.ms2DateTimeLocal(+v);
          if (!v && dflt !== void 0) return dflt;
        } else if (!exports.isDateTime(v, calendar)) {
          Loggers.error("unrecognized date", v);
          return dflt;
        }
        return v;
      };
      var fracMatch = /%\d?f/g;
      var halfYearMatch = /%h/g;
      var quarterToHalfYear = {
        1: "1",
        2: "1",
        3: "2",
        4: "2"
      };
      function modDateFormat(fmt, x, formatter, calendar) {
        fmt = fmt.replace(fracMatch, function(match) {
          var digits = Math.min(+match.charAt(1) || 6, 6);
          var fracSecs = (x / 1e3 % 1 + 2).toFixed(digits).slice(2).replace(/0+$/, "") || "0";
          return fracSecs;
        });
        var d = new Date(Math.floor(x + 0.05));
        fmt = fmt.replace(halfYearMatch, function() {
          return quarterToHalfYear[formatter("%q")(d)];
        });
        if (isWorldCalendar(calendar)) {
          try {
            fmt = Registry.getComponentMethod("calendars", "worldCalFmt")(fmt, x, calendar);
          } catch (e) {
            return "Invalid";
          }
        }
        return formatter(fmt)(d);
      }
      var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
      function formatTime(x, tr) {
        var timePart = mod(x + 0.05, ONEDAY);
        var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ":" + lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);
        if (tr !== "M") {
          if (!isNumeric(tr)) tr = 0;
          var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);
          var secStr = (100 + sec).toFixed(tr).slice(1);
          if (tr > 0) {
            secStr = secStr.replace(/0+$/, "").replace(/[\.]$/, "");
          }
          timeStr += ":" + secStr;
        }
        return timeStr;
      }
      exports.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) {
        calendar = isWorldCalendar(calendar) && calendar;
        if (!fmt) {
          if (tr === "y") fmt = extraFormat.year;
          else if (tr === "m") fmt = extraFormat.month;
          else if (tr === "d") {
            fmt = extraFormat.dayMonth + "\n" + extraFormat.year;
          } else {
            return formatTime(x, tr) + "\n" + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
          }
        }
        return modDateFormat(fmt, x, formatter, calendar);
      };
      var THREEDAYS = 3 * ONEDAY;
      exports.incrementMonth = function(ms, dMonth, calendar) {
        calendar = isWorldCalendar(calendar) && calendar;
        var timeMs = mod(ms, ONEDAY);
        ms = Math.round(ms - timeMs);
        if (calendar) {
          try {
            var dateJD = Math.round(ms / ONEDAY) + EPOCHJD;
            var calInstance = Registry.getComponentMethod("calendars", "getCal")(calendar);
            var cDate = calInstance.fromJD(dateJD);
            if (dMonth % 12) calInstance.add(cDate, dMonth, "m");
            else calInstance.add(cDate, dMonth / 12, "y");
            return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
          } catch (e) {
            Loggers.error("invalid ms " + ms + " in calendar " + calendar);
          }
        }
        var y = new Date(ms + THREEDAYS);
        return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
      };
      exports.findExactDates = function(data, calendar) {
        var exactYears = 0;
        var exactMonths = 0;
        var exactDays = 0;
        var blankCount = 0;
        var d;
        var di;
        var calInstance = isWorldCalendar(calendar) && Registry.getComponentMethod("calendars", "getCal")(calendar);
        for (var i = 0; i < data.length; i++) {
          di = data[i];
          if (!isNumeric(di)) {
            blankCount++;
            continue;
          }
          if (di % ONEDAY) continue;
          if (calInstance) {
            try {
              d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
              if (d.day() === 1) {
                if (d.month() === 1) exactYears++;
                else exactMonths++;
              } else exactDays++;
            } catch (e) {
            }
          } else {
            d = new Date(di);
            if (d.getUTCDate() === 1) {
              if (d.getUTCMonth() === 0) exactYears++;
              else exactMonths++;
            } else exactDays++;
          }
        }
        exactMonths += exactYears;
        exactDays += exactMonths;
        var dataCount = data.length - blankCount;
        return {
          exactYears: exactYears / dataCount,
          exactMonths: exactMonths / dataCount,
          exactDays: exactDays / dataCount
        };
      };
    }
  });

  // src/lib/identity.js
  var require_identity2 = __commonJS({
    "src/lib/identity.js"(exports, module) {
      "use strict";
      module.exports = function identity2(d) {
        return d;
      };
    }
  });

  // src/lib/search.js
  var require_search = __commonJS({
    "src/lib/search.js"(exports) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var loggers = require_loggers();
      var identity2 = require_identity2();
      var BADNUM = require_numerical().BADNUM;
      var roundingError = 1e-9;
      exports.findBin = function(val, bins, linelow) {
        if (isNumeric(bins.start)) {
          return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : Math.floor((val - bins.start) / bins.size + roundingError);
        } else {
          var n1 = 0;
          var n2 = bins.length;
          var c = 0;
          var binSize = n2 > 1 ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
          var n, test;
          if (binSize >= 0) {
            test = linelow ? lessThan : lessOrEqual;
          } else {
            test = linelow ? greaterOrEqual : greaterThan;
          }
          val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
          while (n1 < n2 && c++ < 100) {
            n = Math.floor((n1 + n2) / 2);
            if (test(bins[n], val)) n1 = n + 1;
            else n2 = n;
          }
          if (c > 90) loggers.log("Long binary search...");
          return n1 - 1;
        }
      };
      function lessThan(a, b) {
        return a < b;
      }
      function lessOrEqual(a, b) {
        return a <= b;
      }
      function greaterThan(a, b) {
        return a > b;
      }
      function greaterOrEqual(a, b) {
        return a >= b;
      }
      exports.sorterAsc = function(a, b) {
        return a - b;
      };
      exports.sorterDes = function(a, b) {
        return b - a;
      };
      exports.distinctVals = function(valsIn) {
        var vals = valsIn.slice();
        vals.sort(exports.sorterAsc);
        var last;
        for (last = vals.length - 1; last > -1; last--) {
          if (vals[last] !== BADNUM) break;
        }
        var minDiff = vals[last] - vals[0] || 1;
        var errDiff = minDiff / (last || 1) / 1e4;
        var newVals = [];
        var preV;
        for (var i = 0; i <= last; i++) {
          var v = vals[i];
          var diff = v - preV;
          if (preV === void 0) {
            newVals.push(v);
            preV = v;
          } else if (diff > errDiff) {
            minDiff = Math.min(minDiff, diff);
            newVals.push(v);
            preV = v;
          }
        }
        return { vals: newVals, minDiff };
      };
      exports.roundUp = function(val, arrayIn, reverse) {
        var low = 0;
        var high = arrayIn.length - 1;
        var mid;
        var c = 0;
        var dlow = reverse ? 0 : 1;
        var dhigh = reverse ? 1 : 0;
        var rounded = reverse ? Math.ceil : Math.floor;
        while (low < high && c++ < 100) {
          mid = rounded((low + high) / 2);
          if (arrayIn[mid] <= val) low = mid + dlow;
          else high = mid - dhigh;
        }
        return arrayIn[low];
      };
      exports.sort = function(array, sortFn) {
        var notOrdered = 0;
        var notReversed = 0;
        for (var i = 1; i < array.length; i++) {
          var pairOrder = sortFn(array[i], array[i - 1]);
          if (pairOrder < 0) notOrdered = 1;
          else if (pairOrder > 0) notReversed = 1;
          if (notOrdered && notReversed) return array.sort(sortFn);
        }
        return notReversed ? array : array.reverse();
      };
      exports.findIndexOfMin = function(arr, fn) {
        fn = fn || identity2;
        var min = Infinity;
        var ind;
        for (var i = 0; i < arr.length; i++) {
          var v = fn(arr[i]);
          if (v < min) {
            min = v;
            ind = i;
          }
        }
        return ind;
      };
    }
  });

  // src/lib/sort_object_keys.js
  var require_sort_object_keys = __commonJS({
    "src/lib/sort_object_keys.js"(exports, module) {
      "use strict";
      module.exports = function sortObjectKeys(obj) {
        return Object.keys(obj).sort();
      };
    }
  });

  // src/lib/stats.js
  var require_stats = __commonJS({
    "src/lib/stats.js"(exports) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var isArrayOrTypedArray = require_array().isArrayOrTypedArray;
      exports.aggNums = function(f, v, a, len) {
        var i, b;
        if (!len || len > a.length) len = a.length;
        if (!isNumeric(v)) v = false;
        if (isArrayOrTypedArray(a[0])) {
          b = new Array(len);
          for (i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
          a = b;
        }
        for (i = 0; i < len; i++) {
          if (!isNumeric(v)) v = a[i];
          else if (isNumeric(a[i])) v = f(+v, +a[i]);
        }
        return v;
      };
      exports.len = function(data) {
        return exports.aggNums(function(a) {
          return a + 1;
        }, 0, data);
      };
      exports.mean = function(data, len) {
        if (!len) len = exports.len(data);
        return exports.aggNums(function(a, b) {
          return a + b;
        }, 0, data) / len;
      };
      exports.geometricMean = function(data, len) {
        if (!len) len = exports.len(data);
        return Math.pow(exports.aggNums(function(a, b) {
          return a * b;
        }, 1, data), 1 / len);
      };
      exports.midRange = function(numArr) {
        if (numArr === void 0 || numArr.length === 0) return void 0;
        return (exports.aggNums(Math.max, null, numArr) + exports.aggNums(Math.min, null, numArr)) / 2;
      };
      exports.variance = function(data, len, mean) {
        if (!len) len = exports.len(data);
        if (!isNumeric(mean)) mean = exports.mean(data, len);
        return exports.aggNums(function(a, b) {
          return a + Math.pow(b - mean, 2);
        }, 0, data) / len;
      };
      exports.stdev = function(data, len, mean) {
        return Math.sqrt(exports.variance(data, len, mean));
      };
      exports.median = function(data) {
        var b = data.slice().sort();
        return exports.interp(b, 0.5);
      };
      exports.interp = function(arr, n) {
        if (!isNumeric(n)) throw "n should be a finite number";
        n = n * arr.length - 0.5;
        if (n < 0) return arr[0];
        if (n > arr.length - 1) return arr[arr.length - 1];
        var frac = n % 1;
        return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
      };
    }
  });

  // src/lib/angles.js
  var require_angles = __commonJS({
    "src/lib/angles.js"(exports, module) {
      "use strict";
      var modModule = require_mod();
      var mod = modModule.mod;
      var modHalf = modModule.modHalf;
      var PI = Math.PI;
      var twoPI = 2 * PI;
      function deg2rad(deg) {
        return deg / 180 * PI;
      }
      function rad2deg(rad) {
        return rad / PI * 180;
      }
      function isFullCircle(aBnds) {
        return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-14;
      }
      function angleDelta(a, b) {
        return modHalf(b - a, twoPI);
      }
      function angleDist(a, b) {
        return Math.abs(angleDelta(a, b));
      }
      function isAngleInsideSector(a, aBnds) {
        if (isFullCircle(aBnds)) return true;
        var s0, s1;
        if (aBnds[0] < aBnds[1]) {
          s0 = aBnds[0];
          s1 = aBnds[1];
        } else {
          s0 = aBnds[1];
          s1 = aBnds[0];
        }
        s0 = mod(s0, twoPI);
        s1 = mod(s1, twoPI);
        if (s0 > s1) s1 += twoPI;
        var a0 = mod(a, twoPI);
        var a1 = a0 + twoPI;
        return a0 >= s0 && a0 <= s1 || a1 >= s0 && a1 <= s1;
      }
      function isPtInsideSector(r, a, rBnds, aBnds) {
        if (!isAngleInsideSector(a, aBnds)) return false;
        var r0, r1;
        if (rBnds[0] < rBnds[1]) {
          r0 = rBnds[0];
          r1 = rBnds[1];
        } else {
          r0 = rBnds[1];
          r1 = rBnds[0];
        }
        return r >= r0 && r <= r1;
      }
      function _path(r0, r1, a0, a1, cx, cy, isClosed) {
        cx = cx || 0;
        cy = cy || 0;
        var isCircle = isFullCircle([a0, a1]);
        var aStart, aMid, aEnd;
        var rStart, rEnd;
        if (isCircle) {
          aStart = 0;
          aMid = PI;
          aEnd = twoPI;
        } else {
          if (a0 < a1) {
            aStart = a0;
            aEnd = a1;
          } else {
            aStart = a1;
            aEnd = a0;
          }
        }
        if (r0 < r1) {
          rStart = r0;
          rEnd = r1;
        } else {
          rStart = r1;
          rEnd = r0;
        }
        function pt(r, a) {
          return [r * Math.cos(a) + cx, cy - r * Math.sin(a)];
        }
        var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1;
        function arc(r, a, cw) {
          return "A" + [r, r] + " " + [0, largeArc, cw] + " " + pt(r, a);
        }
        var p;
        if (isCircle) {
          if (rStart === null) {
            p = "M" + pt(rEnd, aStart) + arc(rEnd, aMid, 0) + arc(rEnd, aEnd, 0) + "Z";
          } else {
            p = "M" + pt(rStart, aStart) + arc(rStart, aMid, 0) + arc(rStart, aEnd, 0) + "ZM" + pt(rEnd, aStart) + arc(rEnd, aMid, 1) + arc(rEnd, aEnd, 1) + "Z";
          }
        } else {
          if (rStart === null) {
            p = "M" + pt(rEnd, aStart) + arc(rEnd, aEnd, 0);
            if (isClosed) p += "L0,0Z";
          } else {
            p = "M" + pt(rStart, aStart) + "L" + pt(rEnd, aStart) + arc(rEnd, aEnd, 0) + "L" + pt(rStart, aEnd) + arc(rStart, aStart, 1) + "Z";
          }
        }
        return p;
      }
      function pathArc(r, a0, a1, cx, cy) {
        return _path(null, r, a0, a1, cx, cy, 0);
      }
      function pathSector(r, a0, a1, cx, cy) {
        return _path(null, r, a0, a1, cx, cy, 1);
      }
      function pathAnnulus(r0, r1, a0, a1, cx, cy) {
        return _path(r0, r1, a0, a1, cx, cy, 1);
      }
      module.exports = {
        deg2rad,
        rad2deg,
        angleDelta,
        angleDist,
        isFullCircle,
        isAngleInsideSector,
        isPtInsideSector,
        pathArc,
        pathSector,
        pathAnnulus
      };
    }
  });

  // src/lib/anchor_utils.js
  var require_anchor_utils = __commonJS({
    "src/lib/anchor_utils.js"(exports) {
      "use strict";
      exports.isLeftAnchor = function isLeftAnchor(opts) {
        return opts.xanchor === "left" || opts.xanchor === "auto" && opts.x <= 1 / 3;
      };
      exports.isCenterAnchor = function isCenterAnchor(opts) {
        return opts.xanchor === "center" || opts.xanchor === "auto" && opts.x > 1 / 3 && opts.x < 2 / 3;
      };
      exports.isRightAnchor = function isRightAnchor(opts) {
        return opts.xanchor === "right" || opts.xanchor === "auto" && opts.x >= 2 / 3;
      };
      exports.isTopAnchor = function isTopAnchor(opts) {
        return opts.yanchor === "top" || opts.yanchor === "auto" && opts.y >= 2 / 3;
      };
      exports.isMiddleAnchor = function isMiddleAnchor(opts) {
        return opts.yanchor === "middle" || opts.yanchor === "auto" && opts.y > 1 / 3 && opts.y < 2 / 3;
      };
      exports.isBottomAnchor = function isBottomAnchor(opts) {
        return opts.yanchor === "bottom" || opts.yanchor === "auto" && opts.y <= 1 / 3;
      };
    }
  });

  // src/lib/geometry2d.js
  var require_geometry2d = __commonJS({
    "src/lib/geometry2d.js"(exports) {
      "use strict";
      var mod = require_mod().mod;
      exports.segmentsIntersect = segmentsIntersect;
      function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
        var a = x2 - x1;
        var b = x3 - x1;
        var c = x4 - x3;
        var d = y2 - y1;
        var e = y3 - y1;
        var f = y4 - y3;
        var det = a * f - c * d;
        if (det === 0) return null;
        var t = (b * f - c * e) / det;
        var u = (b * d - a * e) / det;
        if (u < 0 || u > 1 || t < 0 || t > 1) return null;
        return { x: x1 + a * t, y: y1 + d * t };
      }
      exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
        if (segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;
        var x12 = x2 - x1;
        var y12 = y2 - y1;
        var x34 = x4 - x3;
        var y34 = y4 - y3;
        var ll12 = x12 * x12 + y12 * y12;
        var ll34 = x34 * x34 + y34 * y34;
        var dist2 = Math.min(
          perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1),
          perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1),
          perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3),
          perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3)
        );
        return Math.sqrt(dist2);
      };
      function perpDistance2(xab, yab, llab, xac, yac) {
        var fcAB = xac * xab + yac * yab;
        if (fcAB < 0) {
          return xac * xac + yac * yac;
        } else if (fcAB > llab) {
          var xbc = xac - xab;
          var ybc = yac - yab;
          return xbc * xbc + ybc * ybc;
        } else {
          var crossProduct = xac * yab - yac * xab;
          return crossProduct * crossProduct / llab;
        }
      }
      var locationCache;
      var workingPath;
      var workingTextWidth;
      exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
        if (path !== workingPath || textWidth !== workingTextWidth) {
          locationCache = {};
          workingPath = path;
          workingTextWidth = textWidth;
        }
        if (locationCache[positionOnPath]) {
          return locationCache[positionOnPath];
        }
        var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
        var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
        var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
        var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
        var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
        var y = (pCenter.y * 4 + p0.y + p1.y) / 6;
        var out = { x, y, theta };
        locationCache[positionOnPath] = out;
        return out;
      };
      exports.clearLocationCache = function() {
        workingPath = null;
      };
      exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
        var left = bounds.left;
        var right = bounds.right;
        var top = bounds.top;
        var bottom = bounds.bottom;
        var pMin = 0;
        var pTotal = path.getTotalLength();
        var pMax = pTotal;
        var pt0, ptTotal;
        function getDistToPlot(len) {
          var pt = path.getPointAtLength(len);
          if (len === 0) pt0 = pt;
          else if (len === pTotal) ptTotal = pt;
          var dx = pt.x < left ? left - pt.x : pt.x > right ? pt.x - right : 0;
          var dy = pt.y < top ? top - pt.y : pt.y > bottom ? pt.y - bottom : 0;
          return Math.sqrt(dx * dx + dy * dy);
        }
        var distToPlot = getDistToPlot(pMin);
        while (distToPlot) {
          pMin += distToPlot + buffer;
          if (pMin > pMax) return;
          distToPlot = getDistToPlot(pMin);
        }
        distToPlot = getDistToPlot(pMax);
        while (distToPlot) {
          pMax -= distToPlot + buffer;
          if (pMin > pMax) return;
          distToPlot = getDistToPlot(pMax);
        }
        return {
          min: pMin,
          max: pMax,
          len: pMax - pMin,
          total: pTotal,
          isClosed: pMin === 0 && pMax === pTotal && Math.abs(pt0.x - ptTotal.x) < 0.1 && Math.abs(pt0.y - ptTotal.y) < 0.1
        };
      };
      exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
        opts = opts || {};
        var pathLength = opts.pathLength || path.getTotalLength();
        var tolerance = opts.tolerance || 1e-3;
        var iterationLimit = opts.iterationLimit || 30;
        var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;
        var i = 0;
        var b0 = 0;
        var b1 = pathLength;
        var mid;
        var pt;
        var diff;
        while (i < iterationLimit) {
          mid = (b0 + b1) / 2;
          pt = path.getPointAtLength(mid);
          diff = pt[coord] - val;
          if (Math.abs(diff) < tolerance) {
            return pt;
          } else {
            if (mul * diff > 0) {
              b1 = mid;
            } else {
              b0 = mid;
            }
            i++;
          }
        }
        return pt;
      };
    }
  });

  // src/lib/throttle.js
  var require_throttle = __commonJS({
    "src/lib/throttle.js"(exports) {
      "use strict";
      var timerCache = {};
      exports.throttle = function throttle(id, minInterval, callback) {
        var cache = timerCache[id];
        var now = Date.now();
        if (!cache) {
          for (var idi in timerCache) {
            if (timerCache[idi].ts < now - 6e4) {
              delete timerCache[idi];
            }
          }
          cache = timerCache[id] = { ts: 0, timer: null };
        }
        _clearTimeout(cache);
        function exec() {
          callback();
          cache.ts = Date.now();
          if (cache.onDone) {
            cache.onDone();
            cache.onDone = null;
          }
        }
        if (now > cache.ts + minInterval) {
          exec();
          return;
        }
        cache.timer = setTimeout(function() {
          exec();
          cache.timer = null;
        }, minInterval);
      };
      exports.done = function(id) {
        var cache = timerCache[id];
        if (!cache || !cache.timer) return Promise.resolve();
        return new Promise(function(resolve) {
          var previousOnDone = cache.onDone;
          cache.onDone = function onDone() {
            if (previousOnDone) previousOnDone();
            resolve();
            cache.onDone = null;
          };
        });
      };
      exports.clear = function(id) {
        if (id) {
          _clearTimeout(timerCache[id]);
          delete timerCache[id];
        } else {
          for (var idi in timerCache) exports.clear(idi);
        }
      };
      function _clearTimeout(cache) {
        if (cache && cache.timer !== null) {
          clearTimeout(cache.timer);
          cache.timer = null;
        }
      }
    }
  });

  // src/lib/clear_responsive.js
  var require_clear_responsive = __commonJS({
    "src/lib/clear_responsive.js"(exports, module) {
      "use strict";
      module.exports = function clearResponsive(gd) {
        if (gd._responsiveChartHandler) {
          window.removeEventListener("resize", gd._responsiveChartHandler);
          delete gd._responsiveChartHandler;
        }
      };
    }
  });

  // node_modules/is-mobile/index.js
  var require_is_mobile = __commonJS({
    "node_modules/is-mobile/index.js"(exports, module) {
      "use strict";
      module.exports = isMobile;
      module.exports.isMobile = isMobile;
      module.exports.default = isMobile;
      var mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|samsungbrowser.*mobile|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;
      var notMobileRE = /CrOS/;
      var tabletRE = /android|ipad|playbook|silk/i;
      function isMobile(opts) {
        if (!opts) opts = {};
        let ua = opts.ua;
        if (!ua && typeof navigator !== "undefined") ua = navigator.userAgent;
        if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") {
          ua = ua.headers["user-agent"];
        }
        if (typeof ua !== "string") return false;
        let result = mobileRE.test(ua) && !notMobileRE.test(ua) || !!opts.tablet && tabletRE.test(ua);
        if (!result && opts.tablet && opts.featureDetect && navigator && navigator.maxTouchPoints > 1 && ua.indexOf("Macintosh") !== -1 && ua.indexOf("Safari") !== -1) {
          result = true;
        }
        return result;
      }
    }
  });

  // src/lib/preserve_drawing_buffer.js
  var require_preserve_drawing_buffer = __commonJS({
    "src/lib/preserve_drawing_buffer.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var isMobileOrTablet = require_is_mobile();
      module.exports = function preserveDrawingBuffer(opts) {
        var ua;
        if (opts && opts.hasOwnProperty("userAgent")) {
          ua = opts.userAgent;
        } else {
          ua = getUserAgent();
        }
        if (typeof ua !== "string") return true;
        var enable = isMobileOrTablet({
          ua: { headers: { "user-agent": ua } },
          tablet: true,
          featureDetect: false
        });
        if (!enable) {
          var allParts = ua.split(" ");
          for (var i = 1; i < allParts.length; i++) {
            var part = allParts[i];
            if (part.indexOf("Safari") !== -1) {
              for (var k = i - 1; k > -1; k--) {
                var prevPart = allParts[k];
                if (prevPart.slice(0, 8) === "Version/") {
                  var v = prevPart.slice(8).split(".")[0];
                  if (isNumeric(v)) v = +v;
                  if (v >= 13) return true;
                }
              }
            }
          }
        }
        return enable;
      };
      function getUserAgent() {
        var ua;
        if (typeof navigator !== "undefined") {
          ua = navigator.userAgent;
        }
        if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") {
          ua = ua.headers["user-agent"];
        }
        return ua;
      }
    }
  });

  // src/lib/make_trace_groups.js
  var require_make_trace_groups = __commonJS({
    "src/lib/make_trace_groups.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      module.exports = function makeTraceGroups(traceLayer, cdModule, cls) {
        var traces = traceLayer.selectAll("g." + cls.replace(/\s/g, ".")).data(cdModule, function(cd) {
          return cd[0].trace.uid;
        });
        traces.exit().remove();
        traces.enter().append("g").attr("class", cls);
        traces.order();
        var k = traceLayer.classed("rangeplot") ? "nodeRangePlot3" : "node3";
        traces.each(function(cd) {
          cd[0][k] = d3.select(this);
        });
        return traces;
      };
    }
  });

  // src/lib/localize.js
  var require_localize = __commonJS({
    "src/lib/localize.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      module.exports = function localize(gd, s) {
        var locale = gd._context.locale;
        for (var i = 0; i < 2; i++) {
          var locales = gd._context.locales;
          for (var j = 0; j < 2; j++) {
            var dict = (locales[locale] || {}).dictionary;
            if (dict) {
              var out = dict[s];
              if (out) return out;
            }
            locales = Registry.localeRegistry;
          }
          var baseLocale = locale.split("-")[0];
          if (baseLocale === locale) break;
          locale = baseLocale;
        }
        return s;
      };
    }
  });

  // src/lib/filter_unique.js
  var require_filter_unique = __commonJS({
    "src/lib/filter_unique.js"(exports, module) {
      "use strict";
      module.exports = function filterUnique(array) {
        var seen = {};
        var out = [];
        var j = 0;
        for (var i = 0; i < array.length; i++) {
          var item = array[i];
          if (seen[item] !== 1) {
            seen[item] = 1;
            out[j++] = item;
          }
        }
        return out;
      };
    }
  });

  // src/lib/filter_visible.js
  var require_filter_visible = __commonJS({
    "src/lib/filter_visible.js"(exports, module) {
      "use strict";
      module.exports = function filterVisible(container) {
        var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
        var out = [];
        for (var i = 0; i < container.length; i++) {
          var item = container[i];
          if (filterFn(item)) out.push(item);
        }
        return out;
      };
      function baseFilter(item) {
        return item.visible === true;
      }
      function calcDataFilter(item) {
        var trace = item[0].trace;
        return trace.visible === true && trace._length !== 0;
      }
      function isCalcData(cont) {
        return Array.isArray(cont) && Array.isArray(cont[0]) && cont[0][0] && cont[0][0].trace;
      }
    }
  });

  // src/lib/increment.js
  var require_increment = __commonJS({
    "src/lib/increment.js"(exports, module) {
      "use strict";
      module.exports = function incrementNumeric(x, delta) {
        if (!delta) return x;
        var scale = 1 / Math.abs(delta);
        var newX = scale > 1 ? (scale * x + scale * delta) / scale : x + delta;
        var lenX1 = String(newX).length;
        if (lenX1 > 16) {
          var lenDt = String(delta).length;
          var lenX0 = String(x).length;
          if (lenX1 >= lenX0 + lenDt) {
            var s = parseFloat(newX).toPrecision(12);
            if (s.indexOf("e+") === -1) newX = +s;
          }
        }
        return newX;
      };
    }
  });

  // src/lib/clean_number.js
  var require_clean_number = __commonJS({
    "src/lib/clean_number.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var BADNUM = require_numerical().BADNUM;
      var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;
      module.exports = function cleanNumber(v) {
        if (typeof v === "string") {
          v = v.replace(JUNK, "");
        }
        if (isNumeric(v)) return Number(v);
        return BADNUM;
      };
    }
  });

  // src/lib/index.js
  var require_lib = __commonJS({
    "src/lib/index.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var utcFormat = require_d3_time_format().utcFormat;
      var d3Format = require_d3_format().format;
      var isNumeric = require_fast_isnumeric();
      var numConstants = require_numerical();
      var MAX_SAFE = numConstants.FP_SAFE;
      var MIN_SAFE = -MAX_SAFE;
      var BADNUM = numConstants.BADNUM;
      var lib = module.exports = {};
      lib.adjustFormat = function adjustFormat(formatStr) {
        if (!formatStr || /^\d[.]\df/.test(formatStr) || /[.]\d%/.test(formatStr)) return formatStr;
        if (formatStr === "0.f") return "~f";
        if (/^\d%/.test(formatStr)) return "~%";
        if (/^\ds/.test(formatStr)) return "~s";
        if (!/^[~,.0$]/.test(formatStr) && /[&fps]/.test(formatStr)) return "~" + formatStr;
        return formatStr;
      };
      var seenBadFormats = {};
      lib.warnBadFormat = function(f) {
        var key = String(f);
        if (!seenBadFormats[key]) {
          seenBadFormats[key] = 1;
          lib.warn('encountered bad format: "' + key + '"');
        }
      };
      lib.noFormat = function(value) {
        return String(value);
      };
      lib.numberFormat = function(formatStr) {
        var fn;
        try {
          fn = d3Format(lib.adjustFormat(formatStr));
        } catch (e) {
          lib.warnBadFormat(formatStr);
          return lib.noFormat;
        }
        return fn;
      };
      lib.nestedProperty = require_nested_property();
      lib.keyedContainer = require_keyed_container();
      lib.relativeAttr = require_relative_attr();
      lib.isPlainObject = require_is_plain_object();
      lib.toLogRange = require_to_log_range();
      lib.relinkPrivateKeys = require_relink_private();
      var arrayModule = require_array();
      lib.isArrayBuffer = arrayModule.isArrayBuffer;
      lib.isTypedArray = arrayModule.isTypedArray;
      lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray;
      lib.isArray1D = arrayModule.isArray1D;
      lib.ensureArray = arrayModule.ensureArray;
      lib.concat = arrayModule.concat;
      lib.maxRowLength = arrayModule.maxRowLength;
      lib.minRowLength = arrayModule.minRowLength;
      var modModule = require_mod();
      lib.mod = modModule.mod;
      lib.modHalf = modModule.modHalf;
      var coerceModule = require_coerce();
      lib.valObjectMeta = coerceModule.valObjectMeta;
      lib.coerce = coerceModule.coerce;
      lib.coerce2 = coerceModule.coerce2;
      lib.coerceFont = coerceModule.coerceFont;
      lib.coercePattern = coerceModule.coercePattern;
      lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
      lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
      lib.validate = coerceModule.validate;
      var datesModule = require_dates();
      lib.dateTime2ms = datesModule.dateTime2ms;
      lib.isDateTime = datesModule.isDateTime;
      lib.ms2DateTime = datesModule.ms2DateTime;
      lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
      lib.cleanDate = datesModule.cleanDate;
      lib.isJSDate = datesModule.isJSDate;
      lib.formatDate = datesModule.formatDate;
      lib.incrementMonth = datesModule.incrementMonth;
      lib.dateTick0 = datesModule.dateTick0;
      lib.dfltRange = datesModule.dfltRange;
      lib.findExactDates = datesModule.findExactDates;
      lib.MIN_MS = datesModule.MIN_MS;
      lib.MAX_MS = datesModule.MAX_MS;
      var searchModule = require_search();
      lib.findBin = searchModule.findBin;
      lib.sorterAsc = searchModule.sorterAsc;
      lib.sorterDes = searchModule.sorterDes;
      lib.distinctVals = searchModule.distinctVals;
      lib.roundUp = searchModule.roundUp;
      lib.sort = searchModule.sort;
      lib.findIndexOfMin = searchModule.findIndexOfMin;
      lib.sortObjectKeys = require_sort_object_keys();
      var statsModule = require_stats();
      lib.aggNums = statsModule.aggNums;
      lib.len = statsModule.len;
      lib.mean = statsModule.mean;
      lib.geometricMean = statsModule.geometricMean;
      lib.median = statsModule.median;
      lib.midRange = statsModule.midRange;
      lib.variance = statsModule.variance;
      lib.stdev = statsModule.stdev;
      lib.interp = statsModule.interp;
      var matrixModule = require_matrix();
      lib.init2dArray = matrixModule.init2dArray;
      lib.transposeRagged = matrixModule.transposeRagged;
      lib.dot = matrixModule.dot;
      lib.translationMatrix = matrixModule.translationMatrix;
      lib.rotationMatrix = matrixModule.rotationMatrix;
      lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
      lib.apply3DTransform = matrixModule.apply3DTransform;
      lib.apply2DTransform = matrixModule.apply2DTransform;
      lib.apply2DTransform2 = matrixModule.apply2DTransform2;
      lib.convertCssMatrix = matrixModule.convertCssMatrix;
      lib.inverseTransformMatrix = matrixModule.inverseTransformMatrix;
      var anglesModule = require_angles();
      lib.deg2rad = anglesModule.deg2rad;
      lib.rad2deg = anglesModule.rad2deg;
      lib.angleDelta = anglesModule.angleDelta;
      lib.angleDist = anglesModule.angleDist;
      lib.isFullCircle = anglesModule.isFullCircle;
      lib.isAngleInsideSector = anglesModule.isAngleInsideSector;
      lib.isPtInsideSector = anglesModule.isPtInsideSector;
      lib.pathArc = anglesModule.pathArc;
      lib.pathSector = anglesModule.pathSector;
      lib.pathAnnulus = anglesModule.pathAnnulus;
      var anchorUtils = require_anchor_utils();
      lib.isLeftAnchor = anchorUtils.isLeftAnchor;
      lib.isCenterAnchor = anchorUtils.isCenterAnchor;
      lib.isRightAnchor = anchorUtils.isRightAnchor;
      lib.isTopAnchor = anchorUtils.isTopAnchor;
      lib.isMiddleAnchor = anchorUtils.isMiddleAnchor;
      lib.isBottomAnchor = anchorUtils.isBottomAnchor;
      var geom2dModule = require_geometry2d();
      lib.segmentsIntersect = geom2dModule.segmentsIntersect;
      lib.segmentDistance = geom2dModule.segmentDistance;
      lib.getTextLocation = geom2dModule.getTextLocation;
      lib.clearLocationCache = geom2dModule.clearLocationCache;
      lib.getVisibleSegment = geom2dModule.getVisibleSegment;
      lib.findPointOnPath = geom2dModule.findPointOnPath;
      var extendModule = require_extend();
      lib.extendFlat = extendModule.extendFlat;
      lib.extendDeep = extendModule.extendDeep;
      lib.extendDeepAll = extendModule.extendDeepAll;
      lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;
      var loggersModule = require_loggers();
      lib.log = loggersModule.log;
      lib.warn = loggersModule.warn;
      lib.error = loggersModule.error;
      var regexModule = require_regex();
      lib.counterRegex = regexModule.counter;
      var throttleModule = require_throttle();
      lib.throttle = throttleModule.throttle;
      lib.throttleDone = throttleModule.done;
      lib.clearThrottle = throttleModule.clear;
      var domModule = require_dom();
      lib.getGraphDiv = domModule.getGraphDiv;
      lib.isPlotDiv = domModule.isPlotDiv;
      lib.removeElement = domModule.removeElement;
      lib.addStyleRule = domModule.addStyleRule;
      lib.addRelatedStyleRule = domModule.addRelatedStyleRule;
      lib.deleteRelatedStyleRule = domModule.deleteRelatedStyleRule;
      lib.setStyleOnHover = domModule.setStyleOnHover;
      lib.getFullTransformMatrix = domModule.getFullTransformMatrix;
      lib.getElementTransformMatrix = domModule.getElementTransformMatrix;
      lib.getElementAndAncestors = domModule.getElementAndAncestors;
      lib.equalDomRects = domModule.equalDomRects;
      lib.clearResponsive = require_clear_responsive();
      lib.preserveDrawingBuffer = require_preserve_drawing_buffer();
      lib.makeTraceGroups = require_make_trace_groups();
      lib._ = require_localize();
      lib.notifier = require_notifier();
      lib.filterUnique = require_filter_unique();
      lib.filterVisible = require_filter_visible();
      lib.pushUnique = require_push_unique();
      lib.increment = require_increment();
      lib.cleanNumber = require_clean_number();
      lib.ensureNumber = function ensureNumber(v) {
        if (!isNumeric(v)) return BADNUM;
        v = Number(v);
        return v > MAX_SAFE || v < MIN_SAFE ? BADNUM : v;
      };
      lib.isIndex = function(v, len) {
        if (len !== void 0 && v >= len) return false;
        return isNumeric(v) && v >= 0 && v % 1 === 0;
      };
      lib.noop = require_noop();
      lib.identity = require_identity2();
      lib.repeat = function(v, cnt) {
        var out = new Array(cnt);
        for (var i = 0; i < cnt; i++) {
          out[i] = v;
        }
        return out;
      };
      lib.swapAttrs = function(cont, attrList, part1, part2) {
        if (!part1) part1 = "x";
        if (!part2) part2 = "y";
        for (var i = 0; i < attrList.length; i++) {
          var attr = attrList[i];
          var xp = lib.nestedProperty(cont, attr.replace("?", part1));
          var yp = lib.nestedProperty(cont, attr.replace("?", part2));
          var temp = xp.get();
          xp.set(yp.get());
          yp.set(temp);
        }
      };
      lib.raiseToTop = function raiseToTop(elem) {
        elem.parentNode.appendChild(elem);
      };
      lib.cancelTransition = function(selection) {
        return selection.transition().duration(0);
      };
      lib.constrain = function(v, v0, v1) {
        if (v0 > v1) return Math.max(v1, Math.min(v0, v));
        return Math.max(v0, Math.min(v1, v));
      };
      lib.bBoxIntersect = function(a, b, pad) {
        pad = pad || 0;
        return a.left <= b.right + pad && b.left <= a.right + pad && a.top <= b.bottom + pad && b.top <= a.bottom + pad;
      };
      lib.simpleMap = function(array, func, x1, x2, opts) {
        var len = array.length;
        var out = new Array(len);
        for (var i = 0; i < len; i++) out[i] = func(array[i], x1, x2, opts);
        return out;
      };
      lib.randstr = function randstr(existing, bits, base, _recursion) {
        if (!base) base = 16;
        if (bits === void 0) bits = 24;
        if (bits <= 0) return "0";
        var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
        var res = "";
        var i, b, x;
        for (i = 2; digits === Infinity; i *= 2) {
          digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
        }
        var rem = digits - Math.floor(digits);
        for (i = 0; i < Math.floor(digits); i++) {
          x = Math.floor(Math.random() * base).toString(base);
          res = x + res;
        }
        if (rem) {
          b = Math.pow(base, rem);
          x = Math.floor(Math.random() * b).toString(base);
          res = x + res;
        }
        var parsed = parseInt(res, base);
        if (existing && existing[res] || parsed !== Infinity && parsed >= Math.pow(2, bits)) {
          if (_recursion > 10) {
            lib.warn("randstr failed uniqueness");
            return res;
          }
          return randstr(existing, bits, base, (_recursion || 0) + 1);
        } else return res;
      };
      lib.OptionControl = function(opt, optname) {
        if (!opt) opt = {};
        if (!optname) optname = "opt";
        var self2 = {};
        self2.optionList = [];
        self2._newoption = function(optObj) {
          optObj[optname] = opt;
          self2[optObj.name] = optObj;
          self2.optionList.push(optObj);
        };
        self2["_" + optname] = opt;
        return self2;
      };
      lib.smooth = function(arrayIn, FWHM) {
        FWHM = Math.round(FWHM) || 0;
        if (FWHM < 2) return arrayIn;
        var alen = arrayIn.length;
        var alen2 = 2 * alen;
        var wlen = 2 * FWHM - 1;
        var w = new Array(wlen);
        var arrayOut = new Array(alen);
        var i;
        var j;
        var k;
        var v;
        for (i = 0; i < wlen; i++) {
          w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
        }
        for (i = 0; i < alen; i++) {
          v = 0;
          for (j = 0; j < wlen; j++) {
            k = i + j + 1 - FWHM;
            if (k < -alen) k -= alen2 * Math.round(k / alen2);
            else if (k >= alen2) k -= alen2 * Math.floor(k / alen2);
            if (k < 0) k = -1 - k;
            else if (k >= alen) k = alen2 - 1 - k;
            v += arrayIn[k] * w[j];
          }
          arrayOut[i] = v;
        }
        return arrayOut;
      };
      lib.syncOrAsync = function(sequence, arg, finalStep) {
        var ret, fni;
        function continueAsync() {
          return lib.syncOrAsync(sequence, arg, finalStep);
        }
        while (sequence.length) {
          fni = sequence.splice(0, 1)[0];
          ret = fni(arg);
          if (ret && ret.then) {
            return ret.then(continueAsync);
          }
        }
        return finalStep && finalStep(arg);
      };
      lib.stripTrailingSlash = function(str) {
        if (str.slice(-1) === "/") return str.slice(0, -1);
        return str;
      };
      lib.noneOrAll = function(containerIn, containerOut, attrList) {
        if (!containerIn) return;
        var hasAny = false;
        var hasAll = true;
        var i;
        var val;
        for (i = 0; i < attrList.length; i++) {
          val = containerIn[attrList[i]];
          if (val !== void 0 && val !== null) hasAny = true;
          else hasAll = false;
        }
        if (hasAny && !hasAll) {
          for (i = 0; i < attrList.length; i++) {
            containerIn[attrList[i]] = containerOut[attrList[i]];
          }
        }
      };
      lib.mergeArray = function(traceAttr, cd, cdAttr, fn) {
        var hasFn = typeof fn === "function";
        if (lib.isArrayOrTypedArray(traceAttr)) {
          var imax = Math.min(traceAttr.length, cd.length);
          for (var i = 0; i < imax; i++) {
            var v = traceAttr[i];
            cd[i][cdAttr] = hasFn ? fn(v) : v;
          }
        }
      };
      lib.mergeArrayCastPositive = function(traceAttr, cd, cdAttr) {
        return lib.mergeArray(traceAttr, cd, cdAttr, function(v) {
          var w = +v;
          return !isFinite(w) ? 0 : w > 0 ? w : 0;
        });
      };
      lib.fillArray = function(traceAttr, cd, cdAttr, fn) {
        fn = fn || lib.identity;
        if (lib.isArrayOrTypedArray(traceAttr)) {
          for (var i = 0; i < cd.length; i++) {
            cd[i][cdAttr] = fn(traceAttr[i]);
          }
        }
      };
      lib.castOption = function(trace, ptNumber, astr, fn) {
        fn = fn || lib.identity;
        var val = lib.nestedProperty(trace, astr).get();
        if (lib.isArrayOrTypedArray(val)) {
          if (Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
            return fn(val[ptNumber[0]][ptNumber[1]]);
          } else {
            return fn(val[ptNumber]);
          }
        } else {
          return val;
        }
      };
      lib.extractOption = function(calcPt, trace, calcKey, traceKey) {
        if (calcKey in calcPt) return calcPt[calcKey];
        var traceVal = lib.nestedProperty(trace, traceKey).get();
        if (!Array.isArray(traceVal)) return traceVal;
      };
      function makePtIndex2PtNumber(indexToPoints) {
        var ptIndex2ptNumber = {};
        for (var k in indexToPoints) {
          var pts = indexToPoints[k];
          for (var j = 0; j < pts.length; j++) {
            ptIndex2ptNumber[pts[j]] = +k;
          }
        }
        return ptIndex2ptNumber;
      }
      lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) {
        var selectedpoints = trace.selectedpoints;
        var indexToPoints = trace._indexToPoints;
        var ptIndex2ptNumber;
        if (indexToPoints) {
          ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
        }
        function isCdIndexValid(v) {
          return v !== void 0 && v < calcTrace.length;
        }
        for (var i = 0; i < selectedpoints.length; i++) {
          var ptIndex = selectedpoints[i];
          if (lib.isIndex(ptIndex) || lib.isArrayOrTypedArray(ptIndex) && lib.isIndex(ptIndex[0]) && lib.isIndex(ptIndex[1])) {
            var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
            var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;
            if (isCdIndexValid(cdIndex)) {
              calcTrace[cdIndex].selected = 1;
            }
          }
        }
      };
      lib.selIndices2selPoints = function(trace) {
        var selectedpoints = trace.selectedpoints;
        var indexToPoints = trace._indexToPoints;
        if (indexToPoints) {
          var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
          var out = [];
          for (var i = 0; i < selectedpoints.length; i++) {
            var ptIndex = selectedpoints[i];
            if (lib.isIndex(ptIndex)) {
              var ptNumber = ptIndex2ptNumber[ptIndex];
              if (lib.isIndex(ptNumber)) {
                out.push(ptNumber);
              }
            }
          }
          return out;
        } else {
          return selectedpoints;
        }
      };
      lib.getTargetArray = function(trace, transformOpts) {
        var target = transformOpts.target;
        if (typeof target === "string" && target) {
          var array = lib.nestedProperty(trace, target).get();
          return lib.isArrayOrTypedArray(array) ? array : false;
        } else if (lib.isArrayOrTypedArray(target)) {
          return target;
        }
        return false;
      };
      function minExtend(obj1, obj2, opt) {
        var objOut = {};
        if (typeof obj2 !== "object") obj2 = {};
        var arrayLen = opt === "pieLike" ? -1 : 3;
        var keys = Object.keys(obj1);
        var i, k, v;
        for (i = 0; i < keys.length; i++) {
          k = keys[i];
          v = obj1[k];
          if (k.charAt(0) === "_" || typeof v === "function") continue;
          else if (k === "module") objOut[k] = v;
          else if (Array.isArray(v)) {
            if (k === "colorscale" || arrayLen === -1) {
              objOut[k] = v.slice();
            } else {
              objOut[k] = v.slice(0, arrayLen);
            }
          } else if (lib.isTypedArray(v)) {
            if (arrayLen === -1) {
              objOut[k] = v.subarray();
            } else {
              objOut[k] = v.subarray(0, arrayLen);
            }
          } else if (v && typeof v === "object") objOut[k] = minExtend(obj1[k], obj2[k], opt);
          else objOut[k] = v;
        }
        keys = Object.keys(obj2);
        for (i = 0; i < keys.length; i++) {
          k = keys[i];
          v = obj2[k];
          if (typeof v !== "object" || !(k in objOut) || typeof objOut[k] !== "object") {
            objOut[k] = v;
          }
        }
        return objOut;
      }
      lib.minExtend = minExtend;
      lib.titleCase = function(s) {
        return s.charAt(0).toUpperCase() + s.slice(1);
      };
      lib.containsAny = function(s, fragments) {
        for (var i = 0; i < fragments.length; i++) {
          if (s.indexOf(fragments[i]) !== -1) return true;
        }
        return false;
      };
      var IS_SAFARI_REGEX = /Version\/[\d\.]+.*Safari/;
      lib.isSafari = function() {
        return IS_SAFARI_REGEX.test(window.navigator.userAgent);
      };
      var IS_IOS_REGEX = /iPad|iPhone|iPod/;
      lib.isIOS = function() {
        return IS_IOS_REGEX.test(window.navigator.userAgent);
      };
      var IS_MAC_WKWEBVIEW_REGEX = /Macintosh.+AppleWebKit.+Gecko\)$/;
      lib.isMacWKWebView = () => IS_MAC_WKWEBVIEW_REGEX.test(window.navigator.userAgent);
      var FIREFOX_VERSION_REGEX = /Firefox\/(\d+)\.\d+/;
      lib.getFirefoxVersion = function() {
        var match = FIREFOX_VERSION_REGEX.exec(window.navigator.userAgent);
        if (match && match.length === 2) {
          var versionInt = parseInt(match[1]);
          if (!isNaN(versionInt)) {
            return versionInt;
          }
        }
        return null;
      };
      lib.isD3Selection = function(obj) {
        return obj instanceof d3.selection;
      };
      lib.ensureSingle = function(parent, nodeType, className, enterFn) {
        var sel = parent.select(nodeType + (className ? "." + className : ""));
        if (sel.size()) return sel;
        var layer = parent.append(nodeType);
        if (className) layer.classed(className, true);
        if (enterFn) layer.call(enterFn);
        return layer;
      };
      lib.ensureSingleById = function(parent, nodeType, id, enterFn) {
        var sel = parent.select(nodeType + "#" + id);
        if (sel.size()) return sel;
        var layer = parent.append(nodeType).attr("id", id);
        if (enterFn) layer.call(enterFn);
        return layer;
      };
      lib.objectFromPath = function(path, value) {
        var keys = path.split(".");
        var tmpObj;
        var obj = tmpObj = {};
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          var el = null;
          var parts = keys[i].match(/(.*)\[([0-9]+)\]/);
          if (parts) {
            key = parts[1];
            el = parts[2];
            tmpObj = tmpObj[key] = [];
            if (i === keys.length - 1) {
              tmpObj[el] = value;
            } else {
              tmpObj[el] = {};
            }
            tmpObj = tmpObj[el];
          } else {
            if (i === keys.length - 1) {
              tmpObj[key] = value;
            } else {
              tmpObj[key] = {};
            }
            tmpObj = tmpObj[key];
          }
        }
        return obj;
      };
      var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
      var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;
      function notValid(prop) {
        return prop.slice(0, 2) === "__";
      }
      lib.expandObjectPaths = function(data) {
        var match, key, prop, datum, idx, dest, trailingPath;
        if (typeof data === "object" && !Array.isArray(data)) {
          for (key in data) {
            if (data.hasOwnProperty(key)) {
              if (match = key.match(dottedPropertyRegex)) {
                datum = data[key];
                prop = match[1];
                if (notValid(prop)) continue;
                delete data[key];
                data[prop] = lib.extendDeepNoArrays(
                  data[prop] || {},
                  lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]
                );
              } else if (match = key.match(indexedPropertyRegex)) {
                datum = data[key];
                prop = match[1];
                if (notValid(prop)) continue;
                idx = parseInt(match[2]);
                delete data[key];
                data[prop] = data[prop] || [];
                if (match[3] === ".") {
                  trailingPath = match[4];
                  dest = data[prop][idx] = data[prop][idx] || {};
                  lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
                } else {
                  if (notValid(prop)) continue;
                  data[prop][idx] = lib.expandObjectPaths(datum);
                }
              } else {
                if (notValid(key)) continue;
                data[key] = lib.expandObjectPaths(data[key]);
              }
            }
          }
        }
        return data;
      };
      lib.numSeparate = function(value, separators, separatethousands) {
        if (!separatethousands) separatethousands = false;
        if (typeof separators !== "string" || separators.length === 0) {
          throw new Error("Separator string required for formatting!");
        }
        if (typeof value === "number") {
          value = String(value);
        }
        var thousandsRe = /(\d+)(\d{3})/;
        var decimalSep = separators.charAt(0);
        var thouSep = separators.charAt(1);
        var x = value.split(".");
        var x1 = x[0];
        var x2 = x.length > 1 ? decimalSep + x[1] : "";
        if (thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
          while (thousandsRe.test(x1)) {
            x1 = x1.replace(thousandsRe, "$1" + thouSep + "$2");
          }
        }
        return x1 + x2;
      };
      lib.TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)([:|\|][^}]*)?}/g;
      var SIMPLE_PROPERTY_REGEX = /^\w*$/;
      lib.templateString = function(string, obj) {
        var getterCache = {};
        return string.replace(lib.TEMPLATE_STRING_REGEX, function(dummy, key) {
          var v;
          if (SIMPLE_PROPERTY_REGEX.test(key)) {
            v = obj[key];
          } else {
            getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
            v = getterCache[key](true);
          }
          return v !== void 0 ? v : "";
        });
      };
      var hovertemplateWarnings = {
        max: 10,
        count: 0,
        name: "hovertemplate"
      };
      lib.hovertemplateString = (params) => templateFormatString(__spreadProps(__spreadValues({}, params), { opts: hovertemplateWarnings }));
      var texttemplateWarnings = {
        max: 10,
        count: 0,
        name: "texttemplate"
      };
      lib.texttemplateString = (params) => templateFormatString(__spreadProps(__spreadValues({}, params), { opts: texttemplateWarnings }));
      var MULT_DIV_REGEX = /^(\S+)([\*\/])(-?\d+(\.\d+)?)$/;
      function multDivParser(inputStr) {
        var match = inputStr.match(MULT_DIV_REGEX);
        if (match) return { key: match[1], op: match[2], number: Number(match[3]) };
        return { key: inputStr, op: null, number: null };
      }
      var texttemplateWarningsForShapes = {
        max: 10,
        count: 0,
        name: "texttemplate",
        parseMultDiv: true
      };
      lib.texttemplateStringForShapes = (params) => templateFormatString(__spreadProps(__spreadValues({}, params), { opts: texttemplateWarningsForShapes }));
      var TEMPLATE_STRING_FORMAT_SEPARATOR = /^[:|\|]/;
      function templateFormatString({ data = [], locale, fallback, labels = {}, opts, template }) {
        return template.replace(lib.TEMPLATE_STRING_REGEX, (match, key, format) => {
          const isOther = ["xother", "yother"].includes(key);
          const isSpaceOther = ["_xother", "_yother"].includes(key);
          const isSpaceOtherSpace = ["_xother_", "_yother_"].includes(key);
          const isOtherSpace = ["xother_", "yother_"].includes(key);
          const hasOther = isOther || isSpaceOther || isOtherSpace || isSpaceOtherSpace;
          if (isSpaceOther || isSpaceOtherSpace) key = key.substring(1);
          if (isOtherSpace || isSpaceOtherSpace) key = key.substring(0, key.length - 1);
          let parsedOp = null;
          let parsedNumber = null;
          if (opts.parseMultDiv) {
            var _match = multDivParser(key);
            key = _match.key;
            parsedOp = _match.op;
            parsedNumber = _match.number;
          }
          let value = void 0;
          if (hasOther) {
            if (labels[key] === void 0) return "";
            value = labels[key];
          } else {
            for (const obj of data) {
              if (!obj) continue;
              if (obj.hasOwnProperty(key)) {
                value = obj[key];
                break;
              }
              if (!SIMPLE_PROPERTY_REGEX.test(key)) {
                value = lib.nestedProperty(obj, key).get(true);
              }
              if (value !== void 0) break;
            }
          }
          if (value === void 0) {
            const { count, max, name: name2 } = opts;
            const fallbackValue = fallback === false ? match : fallback;
            if (count < max) {
              lib.warn(
                [
                  `Variable '${key}' in ${name2} could not be found!`,
                  "Please verify that the template is correct.",
                  `Using value: '${fallbackValue}'.`
                ].join(" ")
              );
            }
            if (count === max) lib.warn(`Too many '${name2}' warnings - additional warnings will be suppressed.`);
            opts.count++;
            return fallbackValue;
          }
          if (parsedOp === "*") value *= parsedNumber;
          if (parsedOp === "/") value /= parsedNumber;
          if (format) {
            var fmt;
            if (format[0] === ":") {
              fmt = locale ? locale.numberFormat : lib.numberFormat;
              if (value !== "") {
                value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ""))(value);
              }
            }
            if (format[0] === "|") {
              fmt = locale ? locale.timeFormat : utcFormat;
              var ms = lib.dateTime2ms(value);
              value = lib.formatDate(ms, format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ""), false, fmt);
            }
          } else {
            var keyLabel = key + "Label";
            if (labels.hasOwnProperty(keyLabel)) value = labels[keyLabel];
          }
          if (hasOther) {
            value = "(" + value + ")";
            if (isSpaceOther || isSpaceOtherSpace) value = " " + value;
            if (isOtherSpace || isSpaceOtherSpace) value = value + " ";
          }
          return value;
        });
      }
      var char0 = 48;
      var char9 = 57;
      lib.subplotSort = function(a, b) {
        var l = Math.min(a.length, b.length) + 1;
        var numA = 0;
        var numB = 0;
        for (var i = 0; i < l; i++) {
          var charA = a.charCodeAt(i) || 0;
          var charB = b.charCodeAt(i) || 0;
          var isNumA = charA >= char0 && charA <= char9;
          var isNumB = charB >= char0 && charB <= char9;
          if (isNumA) numA = 10 * numA + charA - char0;
          if (isNumB) numB = 10 * numB + charB - char0;
          if (!isNumA || !isNumB) {
            if (numA !== numB) return numA - numB;
            if (charA !== charB) return charA - charB;
          }
        }
        return numB - numA;
      };
      var randSeed = 2e9;
      lib.seedPseudoRandom = function() {
        randSeed = 2e9;
      };
      lib.pseudoRandom = function() {
        var lastVal = randSeed;
        randSeed = (69069 * randSeed + 1) % 4294967296;
        if (Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
        return randSeed / 4294967296;
      };
      lib.fillText = function(calcPt, trace, contOut) {
        var fill = Array.isArray(contOut) ? function(v) {
          contOut.push(v);
        } : function(v) {
          contOut.text = v;
        };
        var htx = lib.extractOption(calcPt, trace, "htx", "hovertext");
        if (lib.isValidTextValue(htx)) return fill(htx);
        var tx = lib.extractOption(calcPt, trace, "tx", "text");
        if (lib.isValidTextValue(tx)) return fill(tx);
      };
      lib.isValidTextValue = function(v) {
        return v || v === 0;
      };
      lib.formatPercent = function(ratio, n) {
        n = n || 0;
        var str = (Math.round(100 * ratio * Math.pow(10, n)) * Math.pow(0.1, n)).toFixed(n) + "%";
        for (var i = 0; i < n; i++) {
          if (str.indexOf(".") !== -1) {
            str = str.replace("0%", "%");
            str = str.replace(".%", "%");
          }
        }
        return str;
      };
      lib.isHidden = function(gd) {
        var display = window.getComputedStyle(gd).display;
        return !display || display === "none";
      };
      lib.strTranslate = function(x, y) {
        return x || y ? "translate(" + x + "," + y + ")" : "";
      };
      lib.strRotate = function(a) {
        return a ? "rotate(" + a + ")" : "";
      };
      lib.strScale = function(s) {
        return s !== 1 ? "scale(" + s + ")" : "";
      };
      lib.getTextTransform = function(transform) {
        var noCenter = transform.noCenter;
        var textX = transform.textX;
        var textY = transform.textY;
        var targetX = transform.targetX;
        var targetY = transform.targetY;
        var anchorX = transform.anchorX || 0;
        var anchorY = transform.anchorY || 0;
        var rotate = transform.rotate;
        var scale = transform.scale;
        if (!scale) scale = 0;
        else if (scale > 1) scale = 1;
        return lib.strTranslate(targetX - scale * (textX + anchorX), targetY - scale * (textY + anchorY)) + lib.strScale(scale) + (rotate ? "rotate(" + rotate + (noCenter ? "" : " " + textX + " " + textY) + ")" : "");
      };
      lib.setTransormAndDisplay = function(s, transform) {
        s.attr("transform", lib.getTextTransform(transform));
        s.style("display", transform.scale ? null : "none");
      };
      lib.ensureUniformFontSize = function(gd, baseFont) {
        var out = lib.extendFlat({}, baseFont);
        out.size = Math.max(baseFont.size, gd._fullLayout.uniformtext.minsize || 0);
        return out;
      };
      lib.join2 = function(arr, mainSeparator, lastSeparator) {
        var len = arr.length;
        if (len > 1) {
          return arr.slice(0, -1).join(mainSeparator) + lastSeparator + arr[len - 1];
        }
        return arr.join(mainSeparator);
      };
      lib.bigFont = function(size) {
        return Math.round(1.2 * size);
      };
      var firefoxVersion = lib.getFirefoxVersion();
      var isProblematicFirefox = firefoxVersion !== null && firefoxVersion < 86;
      lib.getPositionFromD3Event = function() {
        if (isProblematicFirefox) {
          return [d3.event.layerX, d3.event.layerY];
        } else {
          return [d3.event.offsetX, d3.event.offsetY];
        }
      };
    }
  });

  // build/plotcss.js
  var require_plotcss = __commonJS({
    "build/plotcss.js"() {
      "use strict";
      var Lib = require_lib();
      var rules = {
        "X,X div": 'direction:ltr;font-family:"Open Sans",verdana,arial,sans-serif;margin:0;padding:0;border:0;',
        "X input,X button": 'font-family:"Open Sans",verdana,arial,sans-serif;',
        "X input:focus,X button:focus": "outline:none;",
        "X a": "text-decoration:none;",
        "X a:hover": "text-decoration:none;",
        "X .crisp": "shape-rendering:crispEdges;",
        "X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;",
        "X svg a": "fill:#447adb;",
        "X svg a:hover": "fill:#3c6dc5;",
        "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
        "X .main-svg .draglayer": "pointer-events:all;",
        "X .cursor-default": "cursor:default;",
        "X .cursor-pointer": "cursor:pointer;",
        "X .cursor-crosshair": "cursor:crosshair;",
        "X .cursor-move": "cursor:move;",
        "X .cursor-col-resize": "cursor:col-resize;",
        "X .cursor-row-resize": "cursor:row-resize;",
        "X .cursor-ns-resize": "cursor:ns-resize;",
        "X .cursor-ew-resize": "cursor:ew-resize;",
        "X .cursor-sw-resize": "cursor:sw-resize;",
        "X .cursor-s-resize": "cursor:s-resize;",
        "X .cursor-se-resize": "cursor:se-resize;",
        "X .cursor-w-resize": "cursor:w-resize;",
        "X .cursor-e-resize": "cursor:e-resize;",
        "X .cursor-nw-resize": "cursor:nw-resize;",
        "X .cursor-n-resize": "cursor:n-resize;",
        "X .cursor-ne-resize": "cursor:ne-resize;",
        "X .cursor-grab": "cursor:-webkit-grab;cursor:grab;",
        "X .modebar": "position:absolute;top:2px;right:2px;",
        "X .ease-bg": "-webkit-transition:background-color .3s ease 0s;-moz-transition:background-color .3s ease 0s;-ms-transition:background-color .3s ease 0s;-o-transition:background-color .3s ease 0s;transition:background-color .3s ease 0s;",
        "X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity .3s ease 0s;-moz-transition:opacity .3s ease 0s;-ms-transition:opacity .3s ease 0s;-o-transition:opacity .3s ease 0s;transition:opacity .3s ease 0s;",
        "X:hover .modebar--hover .modebar-group": "opacity:1;",
        "X:focus-within .modebar--hover .modebar-group": "opacity:1;",
        "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
        "X .modebar-group a": "display:grid;place-content:center;",
        "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;border:none;background:rgba(0,0,0,0);",
        "X .modebar-btn svg": "position:relative;",
        "X .modebar-btn:focus-visible": "outline:1px solid #000;outline-offset:1px;border-radius:3px;",
        "X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;",
        "X .modebar.vertical svg": "top:-1px;",
        "X .modebar.vertical .modebar-group": "display:block;float:none;padding-left:0px;padding-bottom:8px;",
        "X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;",
        "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
        "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
        "X [data-title]:before": 'content:"";position:absolute;background:rgba(0,0,0,0);border:6px solid rgba(0,0,0,0);z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;',
        "X [data-title]:after": "content:attr(data-title);background:#69738a;color:#fff;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
        "X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;",
        "X .vertical [data-title]:before": "border:6px solid rgba(0,0,0,0);border-left-color:#69738a;margin-top:8px;margin-right:-30px;",
        Y: 'font-family:"Open Sans",verdana,arial,sans-serif;position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;',
        "Y p": "margin:0;",
        "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;",
        "Y .notifier-close": "color:#fff;opacity:.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
        "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
      };
      for (selector in rules) {
        fullSelector = selector.replace(/^,/, " ,").replace(/X/g, ".js-plotly-plot .plotly").replace(/Y/g, ".plotly-notifier");
        Lib.addStyleRule(fullSelector, rules[selector]);
      }
      var fullSelector;
      var selector;
    }
  });

  // node_modules/is-browser/client.js
  var require_client = __commonJS({
    "node_modules/is-browser/client.js"(exports, module) {
      module.exports = true;
    }
  });

  // node_modules/has-hover/index.js
  var require_has_hover = __commonJS({
    "node_modules/has-hover/index.js"(exports, module) {
      "use strict";
      var isBrowser = require_client();
      var hasHover;
      if (typeof window.matchMedia === "function") {
        hasHover = !window.matchMedia("(hover: none)").matches;
      } else {
        hasHover = isBrowser;
      }
      module.exports = hasHover;
    }
  });

  // node_modules/events/events.js
  var require_events = __commonJS({
    "node_modules/events/events.js"(exports, module) {
      "use strict";
      var R = typeof Reflect === "object" ? Reflect : null;
      var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) {
        return Function.prototype.apply.call(target, receiver, args);
      };
      var ReflectOwnKeys;
      if (R && typeof R.ownKeys === "function") {
        ReflectOwnKeys = R.ownKeys;
      } else if (Object.getOwnPropertySymbols) {
        ReflectOwnKeys = function ReflectOwnKeys2(target) {
          return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
        };
      } else {
        ReflectOwnKeys = function ReflectOwnKeys2(target) {
          return Object.getOwnPropertyNames(target);
        };
      }
      function ProcessEmitWarning(warning) {
        if (console && console.warn) console.warn(warning);
      }
      var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) {
        return value !== value;
      };
      function EventEmitter() {
        EventEmitter.init.call(this);
      }
      module.exports = EventEmitter;
      module.exports.once = once;
      EventEmitter.EventEmitter = EventEmitter;
      EventEmitter.prototype._events = void 0;
      EventEmitter.prototype._eventsCount = 0;
      EventEmitter.prototype._maxListeners = void 0;
      var defaultMaxListeners = 10;
      function checkListener(listener) {
        if (typeof listener !== "function") {
          throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
        }
      }
      Object.defineProperty(EventEmitter, "defaultMaxListeners", {
        enumerable: true,
        get: function() {
          return defaultMaxListeners;
        },
        set: function(arg) {
          if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
            throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
          }
          defaultMaxListeners = arg;
        }
      });
      EventEmitter.init = function() {
        if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
          this._events = /* @__PURE__ */ Object.create(null);
          this._eventsCount = 0;
        }
        this._maxListeners = this._maxListeners || void 0;
      };
      EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
        if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) {
          throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
        }
        this._maxListeners = n;
        return this;
      };
      function _getMaxListeners(that) {
        if (that._maxListeners === void 0)
          return EventEmitter.defaultMaxListeners;
        return that._maxListeners;
      }
      EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
        return _getMaxListeners(this);
      };
      EventEmitter.prototype.emit = function emit(type) {
        var args = [];
        for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
        var doError = type === "error";
        var events = this._events;
        if (events !== void 0)
          doError = doError && events.error === void 0;
        else if (!doError)
          return false;
        if (doError) {
          var er;
          if (args.length > 0)
            er = args[0];
          if (er instanceof Error) {
            throw er;
          }
          var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
          err.context = er;
          throw err;
        }
        var handler = events[type];
        if (handler === void 0)
          return false;
        if (typeof handler === "function") {
          ReflectApply(handler, this, args);
        } else {
          var len = handler.length;
          var listeners = arrayClone(handler, len);
          for (var i = 0; i < len; ++i)
            ReflectApply(listeners[i], this, args);
        }
        return true;
      };
      function _addListener(target, type, listener, prepend) {
        var m;
        var events;
        var existing;
        checkListener(listener);
        events = target._events;
        if (events === void 0) {
          events = target._events = /* @__PURE__ */ Object.create(null);
          target._eventsCount = 0;
        } else {
          if (events.newListener !== void 0) {
            target.emit(
              "newListener",
              type,
              listener.listener ? listener.listener : listener
            );
            events = target._events;
          }
          existing = events[type];
        }
        if (existing === void 0) {
          existing = events[type] = listener;
          ++target._eventsCount;
        } else {
          if (typeof existing === "function") {
            existing = events[type] = prepend ? [listener, existing] : [existing, listener];
          } else if (prepend) {
            existing.unshift(listener);
          } else {
            existing.push(listener);
          }
          m = _getMaxListeners(target);
          if (m > 0 && existing.length > m && !existing.warned) {
            existing.warned = true;
            var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
            w.name = "MaxListenersExceededWarning";
            w.emitter = target;
            w.type = type;
            w.count = existing.length;
            ProcessEmitWarning(w);
          }
        }
        return target;
      }
      EventEmitter.prototype.addListener = function addListener(type, listener) {
        return _addListener(this, type, listener, false);
      };
      EventEmitter.prototype.on = EventEmitter.prototype.addListener;
      EventEmitter.prototype.prependListener = function prependListener(type, listener) {
        return _addListener(this, type, listener, true);
      };
      function onceWrapper() {
        if (!this.fired) {
          this.target.removeListener(this.type, this.wrapFn);
          this.fired = true;
          if (arguments.length === 0)
            return this.listener.call(this.target);
          return this.listener.apply(this.target, arguments);
        }
      }
      function _onceWrap(target, type, listener) {
        var state = { fired: false, wrapFn: void 0, target, type, listener };
        var wrapped = onceWrapper.bind(state);
        wrapped.listener = listener;
        state.wrapFn = wrapped;
        return wrapped;
      }
      EventEmitter.prototype.once = function once2(type, listener) {
        checkListener(listener);
        this.on(type, _onceWrap(this, type, listener));
        return this;
      };
      EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
        checkListener(listener);
        this.prependListener(type, _onceWrap(this, type, listener));
        return this;
      };
      EventEmitter.prototype.removeListener = function removeListener(type, listener) {
        var list, events, position, i, originalListener;
        checkListener(listener);
        events = this._events;
        if (events === void 0)
          return this;
        list = events[type];
        if (list === void 0)
          return this;
        if (list === listener || list.listener === listener) {
          if (--this._eventsCount === 0)
            this._events = /* @__PURE__ */ Object.create(null);
          else {
            delete events[type];
            if (events.removeListener)
              this.emit("removeListener", type, list.listener || listener);
          }
        } else if (typeof list !== "function") {
          position = -1;
          for (i = list.length - 1; i >= 0; i--) {
            if (list[i] === listener || list[i].listener === listener) {
              originalListener = list[i].listener;
              position = i;
              break;
            }
          }
          if (position < 0)
            return this;
          if (position === 0)
            list.shift();
          else {
            spliceOne(list, position);
          }
          if (list.length === 1)
            events[type] = list[0];
          if (events.removeListener !== void 0)
            this.emit("removeListener", type, originalListener || listener);
        }
        return this;
      };
      EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
      EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
        var listeners, events, i;
        events = this._events;
        if (events === void 0)
          return this;
        if (events.removeListener === void 0) {
          if (arguments.length === 0) {
            this._events = /* @__PURE__ */ Object.create(null);
            this._eventsCount = 0;
          } else if (events[type] !== void 0) {
            if (--this._eventsCount === 0)
              this._events = /* @__PURE__ */ Object.create(null);
            else
              delete events[type];
          }
          return this;
        }
        if (arguments.length === 0) {
          var keys = Object.keys(events);
          var key;
          for (i = 0; i < keys.length; ++i) {
            key = keys[i];
            if (key === "removeListener") continue;
            this.removeAllListeners(key);
          }
          this.removeAllListeners("removeListener");
          this._events = /* @__PURE__ */ Object.create(null);
          this._eventsCount = 0;
          return this;
        }
        listeners = events[type];
        if (typeof listeners === "function") {
          this.removeListener(type, listeners);
        } else if (listeners !== void 0) {
          for (i = listeners.length - 1; i >= 0; i--) {
            this.removeListener(type, listeners[i]);
          }
        }
        return this;
      };
      function _listeners(target, type, unwrap) {
        var events = target._events;
        if (events === void 0)
          return [];
        var evlistener = events[type];
        if (evlistener === void 0)
          return [];
        if (typeof evlistener === "function")
          return unwrap ? [evlistener.listener || evlistener] : [evlistener];
        return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
      }
      EventEmitter.prototype.listeners = function listeners(type) {
        return _listeners(this, type, true);
      };
      EventEmitter.prototype.rawListeners = function rawListeners(type) {
        return _listeners(this, type, false);
      };
      EventEmitter.listenerCount = function(emitter, type) {
        if (typeof emitter.listenerCount === "function") {
          return emitter.listenerCount(type);
        } else {
          return listenerCount.call(emitter, type);
        }
      };
      EventEmitter.prototype.listenerCount = listenerCount;
      function listenerCount(type) {
        var events = this._events;
        if (events !== void 0) {
          var evlistener = events[type];
          if (typeof evlistener === "function") {
            return 1;
          } else if (evlistener !== void 0) {
            return evlistener.length;
          }
        }
        return 0;
      }
      EventEmitter.prototype.eventNames = function eventNames() {
        return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
      };
      function arrayClone(arr, n) {
        var copy = new Array(n);
        for (var i = 0; i < n; ++i)
          copy[i] = arr[i];
        return copy;
      }
      function spliceOne(list, index) {
        for (; index + 1 < list.length; index++)
          list[index] = list[index + 1];
        list.pop();
      }
      function unwrapListeners(arr) {
        var ret = new Array(arr.length);
        for (var i = 0; i < ret.length; ++i) {
          ret[i] = arr[i].listener || arr[i];
        }
        return ret;
      }
      function once(emitter, name2) {
        return new Promise(function(resolve, reject) {
          function errorListener(err) {
            emitter.removeListener(name2, resolver);
            reject(err);
          }
          function resolver() {
            if (typeof emitter.removeListener === "function") {
              emitter.removeListener("error", errorListener);
            }
            resolve([].slice.call(arguments));
          }
          ;
          eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true });
          if (name2 !== "error") {
            addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
          }
        });
      }
      function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
        if (typeof emitter.on === "function") {
          eventTargetAgnosticAddListener(emitter, "error", handler, flags);
        }
      }
      function eventTargetAgnosticAddListener(emitter, name2, listener, flags) {
        if (typeof emitter.on === "function") {
          if (flags.once) {
            emitter.once(name2, listener);
          } else {
            emitter.on(name2, listener);
          }
        } else if (typeof emitter.addEventListener === "function") {
          emitter.addEventListener(name2, function wrapListener(arg) {
            if (flags.once) {
              emitter.removeEventListener(name2, wrapListener);
            }
            listener(arg);
          });
        } else {
          throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
        }
      }
    }
  });

  // src/lib/events.js
  var require_events2 = __commonJS({
    "src/lib/events.js"(exports, module) {
      "use strict";
      var EventEmitter = require_events().EventEmitter;
      var Events = {
        init: function(plotObj) {
          if (plotObj._ev instanceof EventEmitter) return plotObj;
          var ev = new EventEmitter();
          var internalEv = new EventEmitter();
          plotObj._ev = ev;
          plotObj._internalEv = internalEv;
          plotObj.on = ev.on.bind(ev);
          plotObj.once = ev.once.bind(ev);
          plotObj.removeListener = ev.removeListener.bind(ev);
          plotObj.removeAllListeners = ev.removeAllListeners.bind(ev);
          plotObj._internalOn = internalEv.on.bind(internalEv);
          plotObj._internalOnce = internalEv.once.bind(internalEv);
          plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv);
          plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv);
          plotObj.emit = function(event, data) {
            ev.emit(event, data);
            internalEv.emit(event, data);
          };
          if (typeof plotObj.addEventListener === "function") {
            plotObj.addEventListener("wheel", () => {
            }, { passive: true });
          }
          return plotObj;
        },
        /*
         * This function behaves like jQuery's triggerHandler. It calls
         * all handlers for a particular event and returns the return value
         * of the LAST handler.
         */
        triggerHandler: function(plotObj, event, data) {
          var nodeEventHandlerValue;
          var ev = plotObj._ev;
          if (!ev) return;
          var handlers = ev._events[event];
          if (!handlers) return;
          function apply(handler) {
            if (handler.listener) {
              ev.removeListener(event, handler.listener);
              if (!handler.fired) {
                handler.fired = true;
                return handler.listener.apply(ev, [data]);
              }
            } else {
              return handler.apply(ev, [data]);
            }
          }
          handlers = Array.isArray(handlers) ? handlers : [handlers];
          var i;
          for (i = 0; i < handlers.length - 1; i++) {
            apply(handlers[i]);
          }
          nodeEventHandlerValue = apply(handlers[i]);
          return nodeEventHandlerValue;
        },
        purge: function(plotObj) {
          delete plotObj._ev;
          delete plotObj.on;
          delete plotObj.once;
          delete plotObj.removeListener;
          delete plotObj.removeAllListeners;
          delete plotObj.emit;
          delete plotObj._ev;
          delete plotObj._internalEv;
          delete plotObj._internalOn;
          delete plotObj._internalOnce;
          delete plotObj._removeInternalListener;
          delete plotObj._removeAllInternalListeners;
          return plotObj;
        }
      };
      module.exports = Events;
    }
  });

  // src/lib/queue.js
  var require_queue = __commonJS({
    "src/lib/queue.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var dfltConfig = require_plot_config().dfltConfig;
      function copyArgArray(gd, args) {
        var copy = [];
        var arg;
        for (var i = 0; i < args.length; i++) {
          arg = args[i];
          if (arg === gd) copy[i] = arg;
          else if (typeof arg === "object") {
            copy[i] = Array.isArray(arg) ? Lib.extendDeep([], arg) : Lib.extendDeepAll({}, arg);
          } else copy[i] = arg;
        }
        return copy;
      }
      var queue = {};
      queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) {
        var queueObj, queueIndex;
        gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false };
        queueIndex = gd.undoQueue.index;
        if (gd.autoplay) {
          if (!gd.undoQueue.inSequence) gd.autoplay = false;
          return;
        }
        if (!gd.undoQueue.sequence || gd.undoQueue.beginSequence) {
          queueObj = { undo: { calls: [], args: [] }, redo: { calls: [], args: [] } };
          gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj);
          gd.undoQueue.index += 1;
        } else {
          queueObj = gd.undoQueue.queue[queueIndex - 1];
        }
        gd.undoQueue.beginSequence = false;
        if (queueObj) {
          queueObj.undo.calls.unshift(undoFunc);
          queueObj.undo.args.unshift(undoArgs);
          queueObj.redo.calls.push(redoFunc);
          queueObj.redo.args.push(redoArgs);
        }
        if (gd.undoQueue.queue.length > dfltConfig.queueLength) {
          gd.undoQueue.queue.shift();
          gd.undoQueue.index--;
        }
      };
      queue.startSequence = function(gd) {
        gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false };
        gd.undoQueue.sequence = true;
        gd.undoQueue.beginSequence = true;
      };
      queue.stopSequence = function(gd) {
        gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false };
        gd.undoQueue.sequence = false;
        gd.undoQueue.beginSequence = false;
      };
      queue.undo = function undo(gd) {
        var queueObj, i;
        if (gd.undoQueue === void 0 || isNaN(gd.undoQueue.index) || gd.undoQueue.index <= 0) {
          return;
        }
        gd.undoQueue.index--;
        queueObj = gd.undoQueue.queue[gd.undoQueue.index];
        gd.undoQueue.inSequence = true;
        for (i = 0; i < queueObj.undo.calls.length; i++) {
          queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]);
        }
        gd.undoQueue.inSequence = false;
        gd.autoplay = false;
      };
      queue.redo = function redo(gd) {
        var queueObj, i;
        if (gd.undoQueue === void 0 || isNaN(gd.undoQueue.index) || gd.undoQueue.index >= gd.undoQueue.queue.length) {
          return;
        }
        queueObj = gd.undoQueue.queue[gd.undoQueue.index];
        gd.undoQueue.inSequence = true;
        for (i = 0; i < queueObj.redo.calls.length; i++) {
          queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]);
        }
        gd.undoQueue.inSequence = false;
        gd.autoplay = false;
        gd.undoQueue.index++;
      };
      queue.plotDo = function(gd, func, args) {
        gd.autoplay = true;
        args = copyArgArray(gd, args);
        func.apply(null, args);
      };
      module.exports = queue;
    }
  });

  // src/plots/frame_attributes.js
  var require_frame_attributes = __commonJS({
    "src/plots/frame_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        _isLinkedToArray: "frames_entry",
        group: {
          valType: "string"
        },
        name: {
          valType: "string"
        },
        traces: {
          valType: "any"
        },
        baseframe: {
          valType: "string"
        },
        data: {
          valType: "any"
        },
        layout: {
          valType: "any"
        }
      };
    }
  });

  // src/plot_api/plot_schema.js
  var require_plot_schema = __commonJS({
    "src/plot_api/plot_schema.js"(exports) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var baseAttributes = require_attributes2();
      var baseLayoutAttributes = require_layout_attributes2();
      var frameAttributes = require_frame_attributes();
      var animationAttributes = require_animation_attributes();
      var configAttributes = require_plot_config().configAttributes;
      var editTypes = require_edit_types();
      var extendDeepAll = Lib.extendDeepAll;
      var isPlainObject = Lib.isPlainObject;
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var nestedProperty = Lib.nestedProperty;
      var valObjectMeta = Lib.valObjectMeta;
      var IS_SUBPLOT_OBJ = "_isSubplotObj";
      var IS_LINKED_TO_ARRAY = "_isLinkedToArray";
      var ARRAY_ATTR_REGEXPS = "_arrayAttrRegexps";
      var DEPRECATED = "_deprecated";
      var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED];
      exports.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ;
      exports.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY;
      exports.DEPRECATED = DEPRECATED;
      exports.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS;
      exports.get = function() {
        var traces = {};
        Registry.allTypes.forEach(function(type) {
          traces[type] = getTraceAttributes(type);
        });
        return {
          defs: {
            valObjects: valObjectMeta,
            metaKeys: UNDERSCORE_ATTRS.concat(["description", "role", "editType", "impliedEdits"]),
            editType: {
              traces: editTypes.traces,
              layout: editTypes.layout
            },
            impliedEdits: {}
          },
          traces,
          layout: getLayoutAttributes(),
          frames: getFramesAttributes(),
          animation: formatAttributes(animationAttributes),
          config: formatAttributes(configAttributes)
        };
      };
      exports.crawl = function(attrs, callback, specifiedLevel, attrString) {
        var level = specifiedLevel || 0;
        attrString = attrString || "";
        Object.keys(attrs).forEach(function(attrName) {
          var attr = attrs[attrName];
          if (UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return;
          var fullAttrString = (attrString ? attrString + "." : "") + attrName;
          callback(attr, attrName, attrs, level, fullAttrString);
          if (exports.isValObject(attr)) return;
          if (isPlainObject(attr) && attrName !== "impliedEdits") {
            exports.crawl(attr, callback, level + 1, fullAttrString);
          }
        });
      };
      exports.isValObject = function(obj) {
        return obj && obj.valType !== void 0;
      };
      exports.findArrayAttributes = function(trace) {
        var arrayAttributes = [];
        var stack = [];
        var isArrayStack = [];
        var baseContainer, baseAttrName;
        function callback(attr, attrName, attrs, level) {
          stack = stack.slice(0, level).concat([attrName]);
          isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]);
          var splittableAttr = attr && (attr.valType === "data_array" || attr.arrayOk === true) && !(stack[level - 1] === "colorbar" && (attrName === "ticktext" || attrName === "tickvals"));
          if (!splittableAttr) return;
          crawlIntoTrace(baseContainer, 0, "");
        }
        function crawlIntoTrace(container, i, astrPartial) {
          var item = container[stack[i]];
          var newAstrPartial = astrPartial + stack[i];
          if (i === stack.length - 1) {
            if (isArrayOrTypedArray(item)) {
              arrayAttributes.push(baseAttrName + newAstrPartial);
            }
          } else {
            if (isArrayStack[i]) {
              if (Array.isArray(item)) {
                for (var j = 0; j < item.length; j++) {
                  if (isPlainObject(item[j])) {
                    crawlIntoTrace(item[j], i + 1, newAstrPartial + "[" + j + "].");
                  }
                }
              }
            } else if (isPlainObject(item)) {
              crawlIntoTrace(item, i + 1, newAstrPartial + ".");
            }
          }
        }
        baseContainer = trace;
        baseAttrName = "";
        exports.crawl(baseAttributes, callback);
        if (trace._module && trace._module.attributes) {
          exports.crawl(trace._module.attributes, callback);
        }
        return arrayAttributes;
      };
      exports.getTraceValObject = function(trace, parts) {
        var head = parts[0];
        var i = 1;
        var moduleAttrs, valObject;
        var _module = trace._module;
        if (!_module) _module = (Registry.modules[trace.type || baseAttributes.type.dflt] || {})._module;
        if (!_module) return false;
        moduleAttrs = _module.attributes;
        valObject = moduleAttrs && moduleAttrs[head];
        if (!valObject) {
          var subplotModule = _module.basePlotModule;
          if (subplotModule && subplotModule.attributes) {
            valObject = subplotModule.attributes[head];
          }
        }
        if (!valObject) valObject = baseAttributes[head];
        return recurseIntoValObject(valObject, parts, i);
      };
      exports.getLayoutValObject = function(fullLayout, parts) {
        var valObject = layoutHeadAttr(fullLayout, parts[0]);
        return recurseIntoValObject(valObject, parts, 1);
      };
      function layoutHeadAttr(fullLayout, head) {
        var i, key, _module, attributes;
        var basePlotModules = fullLayout._basePlotModules;
        if (basePlotModules) {
          var out;
          for (i = 0; i < basePlotModules.length; i++) {
            _module = basePlotModules[i];
            if (_module.attrRegex && _module.attrRegex.test(head)) {
              if (_module.layoutAttrOverrides) return _module.layoutAttrOverrides;
              if (!out && _module.layoutAttributes) out = _module.layoutAttributes;
            }
            var baseOverrides = _module.baseLayoutAttrOverrides;
            if (baseOverrides && head in baseOverrides) return baseOverrides[head];
          }
          if (out) return out;
        }
        var modules = fullLayout._modules;
        if (modules) {
          for (i = 0; i < modules.length; i++) {
            attributes = modules[i].layoutAttributes;
            if (attributes && head in attributes) {
              return attributes[head];
            }
          }
        }
        for (key in Registry.componentsRegistry) {
          _module = Registry.componentsRegistry[key];
          if (_module.name === "colorscale" && head.indexOf("coloraxis") === 0) {
            return _module.layoutAttributes[head];
          } else if (!_module.schema && head === _module.name) {
            return _module.layoutAttributes;
          }
        }
        if (head in baseLayoutAttributes) return baseLayoutAttributes[head];
        return false;
      }
      function recurseIntoValObject(valObject, parts, i) {
        if (!valObject) return false;
        if (valObject._isLinkedToArray) {
          if (isIndex(parts[i])) i++;
          else if (i < parts.length) return false;
        }
        for (; i < parts.length; i++) {
          var newValObject = valObject[parts[i]];
          if (isPlainObject(newValObject)) valObject = newValObject;
          else break;
          if (i === parts.length - 1) break;
          if (valObject._isLinkedToArray) {
            i++;
            if (!isIndex(parts[i])) return false;
          } else if (valObject.valType === "info_array") {
            i++;
            var index = parts[i];
            if (!isIndex(index)) return false;
            var items = valObject.items;
            if (Array.isArray(items)) {
              if (index >= items.length) return false;
              if (valObject.dimensions === 2) {
                i++;
                if (parts.length === i) return valObject;
                var index2 = parts[i];
                if (!isIndex(index2)) return false;
                valObject = items[index][index2];
              } else valObject = items[index];
            } else {
              valObject = items;
            }
          }
        }
        return valObject;
      }
      function isIndex(val) {
        return val === Math.round(val) && val >= 0;
      }
      function getTraceAttributes(type) {
        var _module, basePlotModule;
        _module = Registry.modules[type]._module, basePlotModule = _module.basePlotModule;
        var attributes = {};
        attributes.type = null;
        var copyBaseAttributes = extendDeepAll({}, baseAttributes);
        var copyModuleAttributes = extendDeepAll({}, _module.attributes);
        exports.crawl(copyModuleAttributes, function(attr, attrName, attrs, level, fullAttrString) {
          nestedProperty(copyBaseAttributes, fullAttrString).set(void 0);
          if (attr === void 0) nestedProperty(copyModuleAttributes, fullAttrString).set(void 0);
        });
        extendDeepAll(attributes, copyBaseAttributes);
        if (Registry.traceIs(type, "noOpacity")) {
          delete attributes.opacity;
        }
        if (!Registry.traceIs(type, "showLegend")) {
          delete attributes.showlegend;
          delete attributes.legendgroup;
        }
        if (Registry.traceIs(type, "noHover")) {
          delete attributes.hoverinfo;
          delete attributes.hoverlabel;
        }
        if (!_module.selectPoints) {
          delete attributes.selectedpoints;
        }
        extendDeepAll(attributes, copyModuleAttributes);
        if (basePlotModule.attributes) {
          extendDeepAll(attributes, basePlotModule.attributes);
        }
        attributes.type = type;
        var out = {
          meta: _module.meta || {},
          categories: _module.categories || {},
          animatable: Boolean(_module.animatable),
          type,
          attributes: formatAttributes(attributes)
        };
        if (_module.layoutAttributes) {
          var layoutAttributes = {};
          extendDeepAll(layoutAttributes, _module.layoutAttributes);
          out.layoutAttributes = formatAttributes(layoutAttributes);
        }
        if (!_module.animatable) {
          exports.crawl(out, function(attr) {
            if (exports.isValObject(attr) && "anim" in attr) {
              delete attr.anim;
            }
          });
        }
        return out;
      }
      function getLayoutAttributes() {
        var layoutAttributes = {};
        var key, _module;
        extendDeepAll(layoutAttributes, baseLayoutAttributes);
        for (key in Registry.subplotsRegistry) {
          _module = Registry.subplotsRegistry[key];
          if (!_module.layoutAttributes) continue;
          if (Array.isArray(_module.attr)) {
            for (var i = 0; i < _module.attr.length; i++) {
              handleBasePlotModule(layoutAttributes, _module, _module.attr[i]);
            }
          } else {
            var astr = _module.attr === "subplot" ? _module.name : _module.attr;
            handleBasePlotModule(layoutAttributes, _module, astr);
          }
        }
        for (key in Registry.componentsRegistry) {
          _module = Registry.componentsRegistry[key];
          var schema = _module.schema;
          if (schema && (schema.subplots || schema.layout)) {
            var subplots = schema.subplots;
            if (subplots && subplots.xaxis && !subplots.yaxis) {
              for (var xkey in subplots.xaxis) {
                delete layoutAttributes.yaxis[xkey];
              }
            }
            delete layoutAttributes.xaxis.shift;
            delete layoutAttributes.xaxis.autoshift;
          } else if (_module.name === "colorscale") {
            extendDeepAll(layoutAttributes, _module.layoutAttributes);
          } else if (_module.layoutAttributes) {
            insertAttrs(layoutAttributes, _module.layoutAttributes, _module.name);
          }
        }
        return {
          layoutAttributes: formatAttributes(layoutAttributes)
        };
      }
      function getFramesAttributes() {
        var attrs = {
          frames: extendDeepAll({}, frameAttributes)
        };
        formatAttributes(attrs);
        return attrs.frames;
      }
      function formatAttributes(attrs) {
        mergeValTypeAndRole(attrs);
        formatArrayContainers(attrs);
        stringify(attrs);
        return attrs;
      }
      function mergeValTypeAndRole(attrs) {
        function makeSrcAttr(attrName) {
          return {
            valType: "string",
            editType: "none"
          };
        }
        function callback(attr, attrName, attrs2) {
          if (exports.isValObject(attr)) {
            if (attr.arrayOk === true || attr.valType === "data_array") {
              attrs2[attrName + "src"] = makeSrcAttr(attrName);
            }
          } else if (isPlainObject(attr)) {
            attr.role = "object";
          }
        }
        exports.crawl(attrs, callback);
      }
      function formatArrayContainers(attrs) {
        function callback(attr, attrName, attrs2) {
          if (!attr) return;
          var itemName = attr[IS_LINKED_TO_ARRAY];
          if (!itemName) return;
          delete attr[IS_LINKED_TO_ARRAY];
          attrs2[attrName] = { items: {} };
          attrs2[attrName].items[itemName] = attr;
          attrs2[attrName].role = "object";
        }
        exports.crawl(attrs, callback);
      }
      function stringify(attrs) {
        function walk(attr) {
          for (var k in attr) {
            if (isPlainObject(attr[k])) {
              walk(attr[k]);
            } else if (Array.isArray(attr[k])) {
              for (var i = 0; i < attr[k].length; i++) {
                walk(attr[k][i]);
              }
            } else {
              if (attr[k] instanceof RegExp) {
                attr[k] = attr[k].toString();
              }
            }
          }
        }
        walk(attrs);
      }
      function handleBasePlotModule(layoutAttributes, _module, astr) {
        var np = nestedProperty(layoutAttributes, astr);
        var attrs = extendDeepAll({}, _module.layoutAttributes);
        attrs[IS_SUBPLOT_OBJ] = true;
        np.set(attrs);
      }
      function insertAttrs(baseAttrs, newAttrs, astr) {
        var np = nestedProperty(baseAttrs, astr);
        np.set(extendDeepAll(np.get() || {}, newAttrs));
      }
    }
  });

  // src/plot_api/plot_template.js
  var require_plot_template = __commonJS({
    "src/plot_api/plot_template.js"(exports) {
      "use strict";
      var Lib = require_lib();
      var plotAttributes = require_attributes2();
      var TEMPLATEITEMNAME = "templateitemname";
      var templateAttrs = {
        name: {
          valType: "string",
          editType: "none"
        }
      };
      templateAttrs[TEMPLATEITEMNAME] = {
        valType: "string",
        editType: "calc"
      };
      exports.templatedArray = function(name2, attrs) {
        attrs._isLinkedToArray = name2;
        attrs.name = templateAttrs.name;
        attrs[TEMPLATEITEMNAME] = templateAttrs[TEMPLATEITEMNAME];
        return attrs;
      };
      exports.traceTemplater = function(dataTemplate) {
        var traceCounts = {};
        var traceType, typeTemplates;
        for (traceType in dataTemplate) {
          typeTemplates = dataTemplate[traceType];
          if (Array.isArray(typeTemplates) && typeTemplates.length) {
            traceCounts[traceType] = 0;
          }
        }
        function newTrace(traceIn) {
          traceType = Lib.coerce(traceIn, {}, plotAttributes, "type");
          var traceOut = { type: traceType, _template: null };
          if (traceType in traceCounts) {
            typeTemplates = dataTemplate[traceType];
            var typei = traceCounts[traceType] % typeTemplates.length;
            traceCounts[traceType]++;
            traceOut._template = typeTemplates[typei];
          } else {
          }
          return traceOut;
        }
        return {
          newTrace
          // TODO: function to figure out what's left & what didn't work
        };
      };
      exports.newContainer = function(container, name2, baseName) {
        var template = container._template;
        var part = template && (template[name2] || baseName && template[baseName]);
        if (!Lib.isPlainObject(part)) part = null;
        var out = container[name2] = { _template: part };
        return out;
      };
      exports.arrayTemplater = function(container, name2, inclusionAttr) {
        var template = container._template;
        var defaultsTemplate = template && template[arrayDefaultKey(name2)];
        var templateItems = template && template[name2];
        if (!Array.isArray(templateItems) || !templateItems.length) {
          templateItems = [];
        }
        var usedNames = {};
        function newItem(itemIn) {
          var out = { name: itemIn.name, _input: itemIn };
          var templateItemName = out[TEMPLATEITEMNAME] = itemIn[TEMPLATEITEMNAME];
          if (!validItemName(templateItemName)) {
            out._template = defaultsTemplate;
            return out;
          }
          for (var i = 0; i < templateItems.length; i++) {
            var templateItem = templateItems[i];
            if (templateItem.name === templateItemName) {
              usedNames[templateItemName] = 1;
              out._template = templateItem;
              return out;
            }
          }
          out[inclusionAttr] = itemIn[inclusionAttr] || false;
          out._template = false;
          return out;
        }
        function defaultItems() {
          var out = [];
          for (var i = 0; i < templateItems.length; i++) {
            var templateItem = templateItems[i];
            var name3 = templateItem.name;
            if (validItemName(name3) && !usedNames[name3]) {
              var outi = {
                _template: templateItem,
                name: name3,
                _input: { _templateitemname: name3 }
              };
              outi[TEMPLATEITEMNAME] = templateItem[TEMPLATEITEMNAME];
              out.push(outi);
              usedNames[name3] = 1;
            }
          }
          return out;
        }
        return {
          newItem,
          defaultItems
        };
      };
      function validItemName(name2) {
        return name2 && typeof name2 === "string";
      }
      function arrayDefaultKey(name2) {
        var lastChar = name2.length - 1;
        if (name2.charAt(lastChar) !== "s") {
          Lib.warn("bad argument to arrayDefaultKey: " + name2);
        }
        return name2.slice(0, -1) + "defaults";
      }
      exports.arrayDefaultKey = arrayDefaultKey;
      exports.arrayEditor = function(parentIn, containerStr, itemOut) {
        var lengthIn = (Lib.nestedProperty(parentIn, containerStr).get() || []).length;
        var index = itemOut._index;
        var templateItemName = index >= lengthIn && (itemOut._input || {})._templateitemname;
        if (templateItemName) index = lengthIn;
        var itemStr = containerStr + "[" + index + "]";
        var update;
        function resetUpdate() {
          update = {};
          if (templateItemName) {
            update[itemStr] = {};
            update[itemStr][TEMPLATEITEMNAME] = templateItemName;
          }
        }
        resetUpdate();
        function modifyBase(attr, value) {
          update[attr] = value;
        }
        function modifyItem(attr, value) {
          if (templateItemName) {
            Lib.nestedProperty(update[itemStr], attr).set(value);
          } else {
            update[itemStr + "." + attr] = value;
          }
        }
        function getUpdateObj() {
          var updateOut = update;
          resetUpdate();
          return updateOut;
        }
        function applyUpdate(attr, value) {
          if (attr) modifyItem(attr, value);
          var updateToApply = getUpdateObj();
          for (var key in updateToApply) {
            Lib.nestedProperty(parentIn, key).set(updateToApply[key]);
          }
        }
        return {
          modifyBase,
          modifyItem,
          getUpdateObj,
          applyUpdate
        };
      };
    }
  });

  // src/plots/cartesian/constants.js
  var require_constants2 = __commonJS({
    "src/plots/cartesian/constants.js"(exports, module) {
      "use strict";
      var counterRegex = require_regex().counter;
      module.exports = {
        idRegex: {
          x: counterRegex("x", "( domain)?"),
          y: counterRegex("y", "( domain)?")
        },
        attrRegex: counterRegex("[xy]axis"),
        // axis match regular expression
        xAxisMatch: counterRegex("xaxis"),
        yAxisMatch: counterRegex("yaxis"),
        // pattern matching axis ids and names
        // note that this is more permissive than counterRegex, as
        // id2name, name2id, and cleanId accept "x1" etc
        AX_ID_PATTERN: /^[xyz][0-9]*( domain)?$/,
        AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,
        // and for 2D subplots
        SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/,
        HOUR_PATTERN: "hour",
        WEEKDAY_PATTERN: "day of week",
        // pixels to move mouse before you stop clamping to starting point
        MINDRAG: 8,
        // smallest dimension allowed for a zoombox
        MINZOOM: 20,
        // width of axis drag regions
        DRAGGERSIZE: 20,
        // delay before a redraw (relayout) after smooth panning and zooming
        REDRAWDELAY: 50,
        // last resort axis ranges for x and y axes if we have no data
        DFLTRANGEX: [-1, 6],
        DFLTRANGEY: [-1, 4],
        // Layers to keep trace types in the right order
        // N.B. each  'unique' plot method must have its own layer
        traceLayerClasses: [
          "imagelayer",
          "heatmaplayer",
          "contourcarpetlayer",
          "contourlayer",
          "funnellayer",
          "waterfalllayer",
          "barlayer",
          "carpetlayer",
          "violinlayer",
          "boxlayer",
          "ohlclayer",
          "scattercarpetlayer",
          "scatterlayer"
        ],
        clipOnAxisFalseQuery: [
          ".scatterlayer",
          ".barlayer",
          ".funnellayer",
          ".waterfalllayer"
        ],
        layerValue2layerClass: {
          "above traces": "above",
          "below traces": "below"
        },
        zindexSeparator: "z"
        // used for zindex of cartesian subplots e.g. xy, xyz2, xyz3, etc.
      };
    }
  });

  // src/plots/cartesian/axis_ids.js
  var require_axis_ids = __commonJS({
    "src/plots/cartesian/axis_ids.js"(exports) {
      "use strict";
      var Registry = require_registry();
      var constants = require_constants2();
      exports.id2name = function id2name(id) {
        if (typeof id !== "string" || !id.match(constants.AX_ID_PATTERN)) return;
        var axNum = id.split(" ")[0].slice(1);
        if (axNum === "1") axNum = "";
        return id.charAt(0) + "axis" + axNum;
      };
      exports.name2id = function name2id(name2) {
        if (!name2.match(constants.AX_NAME_PATTERN)) return;
        var axNum = name2.slice(5);
        if (axNum === "1") axNum = "";
        return name2.charAt(0) + axNum;
      };
      exports.cleanId = function cleanId(id, axLetter, domainId) {
        var domainTest = /( domain)$/.test(id);
        if (typeof id !== "string" || !id.match(constants.AX_ID_PATTERN)) return;
        if (axLetter && id.charAt(0) !== axLetter) return;
        if (domainTest && !domainId) return;
        var axNum = id.split(" ")[0].slice(1).replace(/^0+/, "");
        if (axNum === "1") axNum = "";
        return id.charAt(0) + axNum + (domainTest && domainId ? " domain" : "");
      };
      exports.list = function(gd, axLetter, only2d) {
        var fullLayout = gd._fullLayout;
        if (!fullLayout) return [];
        var idList = exports.listIds(gd, axLetter);
        var out = new Array(idList.length);
        var i;
        for (i = 0; i < idList.length; i++) {
          var idi = idList[i];
          out[i] = fullLayout[idi.charAt(0) + "axis" + idi.slice(1)];
        }
        if (!only2d) {
          var sceneIds3D = fullLayout._subplots.gl3d || [];
          for (i = 0; i < sceneIds3D.length; i++) {
            var scene = fullLayout[sceneIds3D[i]];
            if (axLetter) out.push(scene[axLetter + "axis"]);
            else out.push(scene.xaxis, scene.yaxis, scene.zaxis);
          }
        }
        return out;
      };
      exports.listIds = function(gd, axLetter) {
        var fullLayout = gd._fullLayout;
        if (!fullLayout) return [];
        var subplotLists = fullLayout._subplots;
        if (axLetter) return subplotLists[axLetter + "axis"];
        return subplotLists.xaxis.concat(subplotLists.yaxis);
      };
      exports.getFromId = function(gd, id, type) {
        var fullLayout = gd._fullLayout;
        id = id === void 0 || typeof id !== "string" ? id : id.replace(" domain", "");
        if (type === "x") id = id.replace(/y[0-9]*/, "");
        else if (type === "y") id = id.replace(/x[0-9]*/, "");
        return fullLayout[exports.id2name(id)];
      };
      exports.getFromTrace = function(gd, fullTrace, type) {
        var fullLayout = gd._fullLayout;
        var ax = null;
        if (Registry.traceIs(fullTrace, "gl3d")) {
          var scene = fullTrace.scene;
          if (scene.slice(0, 5) === "scene") {
            ax = fullLayout[scene][type + "axis"];
          }
        } else {
          ax = exports.getFromId(gd, fullTrace[type + "axis"] || type);
        }
        return ax;
      };
      exports.idSort = function(id1, id2) {
        var letter1 = id1.charAt(0);
        var letter2 = id2.charAt(0);
        if (letter1 !== letter2) return letter1 > letter2 ? 1 : -1;
        return +(id1.slice(1) || 1) - +(id2.slice(1) || 1);
      };
      exports.ref2id = function(ar) {
        return /^[xyz]/.test(ar) ? ar.split(" ")[0] : false;
      };
      function isFound(axId, list) {
        if (list && list.length) {
          for (var i = 0; i < list.length; i++) {
            if (list[i][axId]) return true;
          }
        }
        return false;
      }
      exports.isLinked = function(fullLayout, axId) {
        return isFound(axId, fullLayout._axisMatchGroups) || isFound(axId, fullLayout._axisConstraintGroups);
      };
    }
  });

  // src/components/shapes/handle_outline.js
  var require_handle_outline = __commonJS({
    "src/components/shapes/handle_outline.js"(exports, module) {
      "use strict";
      function clearOutlineControllers(gd) {
        var zoomLayer = gd._fullLayout._zoomlayer;
        if (zoomLayer) {
          zoomLayer.selectAll(".outline-controllers").remove();
        }
      }
      function clearOutline(gd) {
        var zoomLayer = gd._fullLayout._zoomlayer;
        if (zoomLayer) {
          zoomLayer.selectAll(".select-outline").remove();
        }
        gd._fullLayout._outlining = false;
      }
      module.exports = {
        clearOutlineControllers,
        clearOutline
      };
    }
  });

  // src/traces/scatter/layout_attributes.js
  var require_layout_attributes3 = __commonJS({
    "src/traces/scatter/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        scattermode: {
          valType: "enumerated",
          values: ["group", "overlay"],
          dflt: "overlay",
          editType: "calc"
        },
        scattergap: {
          valType: "number",
          min: 0,
          max: 1,
          editType: "calc"
        }
      };
    }
  });

  // src/plots/get_data.js
  var require_get_data = __commonJS({
    "src/plots/get_data.js"(exports) {
      "use strict";
      var Registry = require_registry();
      var SUBPLOT_PATTERN = require_constants2().SUBPLOT_PATTERN;
      exports.getSubplotCalcData = function(calcData, type, subplotId) {
        var basePlotModule = Registry.subplotsRegistry[type];
        if (!basePlotModule) return [];
        var attr = basePlotModule.attr;
        var subplotCalcData = [];
        for (var i = 0; i < calcData.length; i++) {
          var calcTrace = calcData[i];
          var trace = calcTrace[0].trace;
          if (trace[attr] === subplotId) subplotCalcData.push(calcTrace);
        }
        return subplotCalcData;
      };
      exports.getModuleCalcData = function(calcdata, arg1, arg2) {
        var moduleCalcData = [];
        var remainingCalcData = [];
        var plotMethod;
        if (typeof arg1 === "string") {
          plotMethod = Registry.getModule(arg1).plot;
        } else if (typeof arg1 === "function") {
          plotMethod = arg1;
        } else {
          plotMethod = arg1.plot;
        }
        if (!plotMethod) {
          return [moduleCalcData, calcdata];
        }
        var zorder = arg2;
        for (var i = 0; i < calcdata.length; i++) {
          var cd = calcdata[i];
          var trace = cd[0].trace;
          var filterByZ = trace.zorder !== void 0;
          if (trace.visible !== true || trace._length === 0) continue;
          if (trace._module && trace._module.plot === plotMethod && (!filterByZ || trace.zorder === zorder)) {
            moduleCalcData.push(cd);
          } else {
            remainingCalcData.push(cd);
          }
        }
        return [moduleCalcData, remainingCalcData];
      };
      exports.getSubplotData = function getSubplotData(data, type, subplotId) {
        if (!Registry.subplotsRegistry[type]) return [];
        var attr = Registry.subplotsRegistry[type].attr;
        var subplotData = [];
        var trace, subplotX, subplotY;
        for (var i = 0; i < data.length; i++) {
          trace = data[i];
          if (trace[attr] === subplotId) subplotData.push(trace);
        }
        return subplotData;
      };
    }
  });

  // src/plots/command.js
  var require_command = __commonJS({
    "src/plots/command.js"(exports) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      exports.manageCommandObserver = function(gd, container, commandList, onchange) {
        var ret = {};
        var enabled = true;
        if (container && container._commandObserver) {
          ret = container._commandObserver;
        }
        if (!ret.cache) {
          ret.cache = {};
        }
        ret.lookupTable = {};
        var binding = exports.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable);
        if (container && container._commandObserver) {
          if (!binding) {
            if (container._commandObserver.remove) {
              container._commandObserver.remove();
              container._commandObserver = null;
              return ret;
            }
          } else {
            return ret;
          }
        }
        if (binding) {
          bindingValueHasChanged(gd, binding, ret.cache);
          ret.check = function check() {
            if (!enabled) return;
            var update = bindingValueHasChanged(gd, binding, ret.cache);
            if (update.changed && onchange) {
              if (ret.lookupTable[update.value] !== void 0) {
                ret.disable();
                Promise.resolve(onchange({
                  value: update.value,
                  type: binding.type,
                  prop: binding.prop,
                  traces: binding.traces,
                  index: ret.lookupTable[update.value]
                })).then(ret.enable, ret.enable);
              }
            }
            return update.changed;
          };
          var checkEvents = [
            "plotly_relayout",
            "plotly_redraw",
            "plotly_restyle",
            "plotly_update",
            "plotly_animatingframe",
            "plotly_afterplot"
          ];
          for (var i = 0; i < checkEvents.length; i++) {
            gd._internalOn(checkEvents[i], ret.check);
          }
          ret.remove = function() {
            for (var i2 = 0; i2 < checkEvents.length; i2++) {
              gd._removeInternalListener(checkEvents[i2], ret.check);
            }
          };
        } else {
          Lib.log("Unable to automatically bind plot updates to API command");
          ret.lookupTable = {};
          ret.remove = function() {
          };
        }
        ret.disable = function disable() {
          enabled = false;
        };
        ret.enable = function enable() {
          enabled = true;
        };
        if (container) {
          container._commandObserver = ret;
        }
        return ret;
      };
      exports.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) {
        var i;
        var n = commandList.length;
        var refBinding;
        for (i = 0; i < n; i++) {
          var binding;
          var command = commandList[i];
          var method = command.method;
          var args = command.args;
          if (!Array.isArray(args)) args = [];
          if (!method) {
            return false;
          }
          var bindings = exports.computeAPICommandBindings(gd, method, args);
          if (bindings.length !== 1) {
            return false;
          }
          if (!refBinding) {
            refBinding = bindings[0];
            if (Array.isArray(refBinding.traces)) {
              refBinding.traces.sort();
            }
          } else {
            binding = bindings[0];
            if (binding.type !== refBinding.type) {
              return false;
            }
            if (binding.prop !== refBinding.prop) {
              return false;
            }
            if (Array.isArray(refBinding.traces)) {
              if (Array.isArray(binding.traces)) {
                binding.traces.sort();
                for (var j = 0; j < refBinding.traces.length; j++) {
                  if (refBinding.traces[j] !== binding.traces[j]) {
                    return false;
                  }
                }
              } else {
                return false;
              }
            } else {
              if (binding.prop !== refBinding.prop) {
                return false;
              }
            }
          }
          binding = bindings[0];
          var value = binding.value;
          if (Array.isArray(value)) {
            if (value.length === 1) {
              value = value[0];
            } else {
              return false;
            }
          }
          if (bindingsByValue) {
            bindingsByValue[value] = i;
          }
        }
        return refBinding;
      };
      function bindingValueHasChanged(gd, binding, cache) {
        var container, value, obj;
        var changed = false;
        if (binding.type === "data") {
          container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0];
        } else if (binding.type === "layout") {
          container = gd._fullLayout;
        } else {
          return false;
        }
        value = Lib.nestedProperty(container, binding.prop).get();
        obj = cache[binding.type] = cache[binding.type] || {};
        if (obj.hasOwnProperty(binding.prop)) {
          if (obj[binding.prop] !== value) {
            changed = true;
          }
        }
        obj[binding.prop] = value;
        return {
          changed,
          value
        };
      }
      exports.executeAPICommand = function(gd, method, args) {
        if (method === "skip") return Promise.resolve();
        var _method = Registry.apiMethodRegistry[method];
        var allArgs = [gd];
        if (!Array.isArray(args)) args = [];
        for (var i = 0; i < args.length; i++) {
          allArgs.push(args[i]);
        }
        return _method.apply(null, allArgs).catch(function(err) {
          Lib.warn("API call to Plotly." + method + " rejected.", err);
          return Promise.reject(err);
        });
      };
      exports.computeAPICommandBindings = function(gd, method, args) {
        var bindings;
        if (!Array.isArray(args)) args = [];
        switch (method) {
          case "restyle":
            bindings = computeDataBindings(gd, args);
            break;
          case "relayout":
            bindings = computeLayoutBindings(gd, args);
            break;
          case "update":
            bindings = computeDataBindings(gd, [args[0], args[2]]).concat(computeLayoutBindings(gd, [args[1]]));
            break;
          case "animate":
            bindings = computeAnimateBindings(gd, args);
            break;
          default:
            bindings = [];
        }
        return bindings;
      };
      function computeAnimateBindings(gd, args) {
        if (Array.isArray(args[0]) && args[0].length === 1 && ["string", "number"].indexOf(typeof args[0][0]) !== -1) {
          return [{ type: "layout", prop: "_currentFrame", value: args[0][0].toString() }];
        } else {
          return [];
        }
      }
      function computeLayoutBindings(gd, args) {
        var bindings = [];
        var astr = args[0];
        var aobj = {};
        if (typeof astr === "string") {
          aobj[astr] = args[1];
        } else if (Lib.isPlainObject(astr)) {
          aobj = astr;
        } else {
          return bindings;
        }
        crawl(aobj, function(path, attrName, attr) {
          bindings.push({ type: "layout", prop: path, value: attr });
        }, "", 0);
        return bindings;
      }
      function computeDataBindings(gd, args) {
        var traces, astr, val, aobj;
        var bindings = [];
        astr = args[0];
        val = args[1];
        traces = args[2];
        aobj = {};
        if (typeof astr === "string") {
          aobj[astr] = val;
        } else if (Lib.isPlainObject(astr)) {
          aobj = astr;
          if (traces === void 0) {
            traces = val;
          }
        } else {
          return bindings;
        }
        if (traces === void 0) {
          traces = null;
        }
        crawl(aobj, function(path, attrName, _attr) {
          var thisTraces;
          var attr;
          if (Array.isArray(_attr)) {
            attr = _attr.slice();
            var nAttr = Math.min(attr.length, gd.data.length);
            if (traces) {
              nAttr = Math.min(nAttr, traces.length);
            }
            thisTraces = [];
            for (var j = 0; j < nAttr; j++) {
              thisTraces[j] = traces ? traces[j] : j;
            }
          } else {
            attr = _attr;
            thisTraces = traces ? traces.slice() : null;
          }
          if (thisTraces === null) {
            if (Array.isArray(attr)) {
              attr = attr[0];
            }
          } else if (Array.isArray(thisTraces)) {
            if (!Array.isArray(attr)) {
              var tmp = attr;
              attr = [];
              for (var i = 0; i < thisTraces.length; i++) {
                attr[i] = tmp;
              }
            }
            attr.length = Math.min(thisTraces.length, attr.length);
          }
          bindings.push({
            type: "data",
            prop: path,
            traces: thisTraces,
            value: attr
          });
        }, "", 0);
        return bindings;
      }
      function crawl(attrs, callback, path, depth) {
        Object.keys(attrs).forEach(function(attrName) {
          var attr = attrs[attrName];
          if (attrName[0] === "_") return;
          var thisPath = path + (depth > 0 ? "." : "") + attrName;
          if (Lib.isPlainObject(attr)) {
            crawl(attr, callback, thisPath, depth + 1);
          } else {
            callback(thisPath, attrName, attr);
          }
        });
      }
    }
  });

  // src/plots/plots.js
  var require_plots = __commonJS({
    "src/plots/plots.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var timeFormatLocale = require_d3_time_format().timeFormatLocale;
      var formatLocale = require_d3_format().formatLocale;
      var isNumeric = require_fast_isnumeric();
      var b64encode = require_base64_arraybuffer_umd();
      var Registry = require_registry();
      var PlotSchema = require_plot_schema();
      var Template = require_plot_template();
      var Lib = require_lib();
      var Color2 = require_color();
      var BADNUM = require_numerical().BADNUM;
      var axisIDs = require_axis_ids();
      var clearOutline = require_handle_outline().clearOutline;
      var scatterAttrs = require_layout_attributes3();
      var animationAttrs = require_animation_attributes();
      var frameAttrs = require_frame_attributes();
      var getModuleCalcData = require_get_data().getModuleCalcData;
      var relinkPrivateKeys = Lib.relinkPrivateKeys;
      var _ = Lib._;
      var plots = module.exports = {};
      Lib.extendFlat(plots, Registry);
      plots.attributes = require_attributes2();
      plots.attributes.type.values = plots.allTypes;
      plots.fontAttrs = require_font_attributes();
      plots.layoutAttributes = require_layout_attributes2();
      var commandModule = require_command();
      plots.executeAPICommand = commandModule.executeAPICommand;
      plots.computeAPICommandBindings = commandModule.computeAPICommandBindings;
      plots.manageCommandObserver = commandModule.manageCommandObserver;
      plots.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings;
      plots.redrawText = function(gd) {
        gd = Lib.getGraphDiv(gd);
        return new Promise(function(resolve) {
          setTimeout(function() {
            if (!gd._fullLayout) return;
            Registry.getComponentMethod("annotations", "draw")(gd);
            Registry.getComponentMethod("legend", "draw")(gd);
            Registry.getComponentMethod("colorbar", "draw")(gd);
            resolve(plots.previousPromises(gd));
          }, 300);
        });
      };
      plots.resize = function(gd) {
        gd = Lib.getGraphDiv(gd);
        var resolveLastResize;
        var p = new Promise(function(resolve, reject) {
          if (!gd || Lib.isHidden(gd)) {
            reject(new Error("Resize must be passed a displayed plot div element."));
          }
          if (gd._redrawTimer) clearTimeout(gd._redrawTimer);
          if (gd._resolveResize) resolveLastResize = gd._resolveResize;
          gd._resolveResize = resolve;
          gd._redrawTimer = setTimeout(function() {
            if (!gd.layout || gd.layout.width && gd.layout.height || Lib.isHidden(gd)) {
              resolve(gd);
              return;
            }
            delete gd.layout.width;
            delete gd.layout.height;
            var oldchanged = gd.changed;
            gd.autoplay = true;
            Registry.call("relayout", gd, { autosize: true }).then(function() {
              gd.changed = oldchanged;
              if (gd._resolveResize === resolve) {
                delete gd._resolveResize;
                resolve(gd);
              }
            });
          }, 100);
        });
        if (resolveLastResize) resolveLastResize(p);
        return p;
      };
      plots.previousPromises = function(gd) {
        if ((gd._promises || []).length) {
          return Promise.all(gd._promises).then(function() {
            gd._promises = [];
          });
        }
      };
      plots.addLinks = function(gd) {
        if (!gd._context.showLink && !gd._context.showSources) return;
        var fullLayout = gd._fullLayout;
        var linkContainer = Lib.ensureSingle(fullLayout._paper, "text", "js-plot-link-container", function(s) {
          s.style({
            "font-family": '"Open Sans", Arial, sans-serif',
            "font-size": "12px",
            fill: Color2.defaultLine,
            "pointer-events": "all"
          }).each(function() {
            var links = d3.select(this);
            links.append("tspan").classed("js-link-to-tool", true);
            links.append("tspan").classed("js-link-spacer", true);
            links.append("tspan").classed("js-sourcelinks", true);
          });
        });
        var text = linkContainer.node();
        var attrs = { y: fullLayout._paper.attr("height") - 9 };
        if (document.body.contains(text) && text.getComputedTextLength() >= fullLayout.width - 20) {
          attrs["text-anchor"] = "start";
          attrs.x = 5;
        } else {
          attrs["text-anchor"] = "end";
          attrs.x = fullLayout._paper.attr("width") - 7;
        }
        linkContainer.attr(attrs);
        var toolspan = linkContainer.select(".js-link-to-tool");
        var spacespan = linkContainer.select(".js-link-spacer");
        var sourcespan = linkContainer.select(".js-sourcelinks");
        if (gd._context.showSources) gd._context.showSources(gd);
        if (gd._context.showLink) positionPlayWithData(gd, toolspan);
        spacespan.text(toolspan.text() && sourcespan.text() ? " - " : "");
      };
      function positionPlayWithData(gd, container) {
        container.text("");
        var link = container.append("a").attr({
          "xlink:xlink:href": "#",
          class: "link--impt link--embedview",
          "font-weight": "bold"
        }).text(gd._context.linkText + " " + String.fromCharCode(187));
        if (gd._context.sendData) {
          link.on("click", function() {
            plots.sendDataToCloud(gd);
          });
        } else {
          var path = window.location.pathname.split("/");
          var query = window.location.search;
          link.attr({
            "xlink:xlink:show": "new",
            "xlink:xlink:href": "/" + path[2].split(".")[0] + "/" + path[1] + query
          });
        }
      }
      plots.sendDataToCloud = function(gd) {
        var baseUrl = (window.PLOTLYENV || {}).BASE_URL || gd._context.plotlyServerURL;
        if (!baseUrl) return;
        gd.emit("plotly_beforeexport");
        var hiddenformDiv = d3.select(gd).append("div").attr("id", "hiddenform").style("display", "none");
        var hiddenform = hiddenformDiv.append("form").attr({
          action: baseUrl + "/external",
          method: "post",
          target: "_blank"
        });
        var hiddenformInput = hiddenform.append("input").attr({
          type: "text",
          name: "data"
        });
        hiddenformInput.node().value = plots.graphJson(gd, false, "keepdata");
        hiddenform.node().submit();
        hiddenformDiv.remove();
        gd.emit("plotly_afterexport");
        return false;
      };
      var d3FormatKeys = [
        "days",
        "shortDays",
        "months",
        "shortMonths",
        "periods",
        "dateTime",
        "date",
        "time",
        "decimal",
        "thousands",
        "grouping",
        "currency"
      ];
      var extraFormatKeys = [
        "year",
        "month",
        "dayMonth",
        "dayMonthYear"
      ];
      plots.supplyDefaults = function(gd, opts) {
        var skipUpdateCalc = opts && opts.skipUpdateCalc;
        var oldFullLayout = gd._fullLayout || {};
        if (oldFullLayout._skipDefaults) {
          delete oldFullLayout._skipDefaults;
          return;
        }
        var newFullLayout = gd._fullLayout = {};
        var newLayout = gd.layout || {};
        var oldFullData = gd._fullData || [];
        var newFullData = gd._fullData = [];
        var newData = gd.data || [];
        var oldCalcdata = gd.calcdata || [];
        var context = gd._context || {};
        var i;
        if (!gd._transitionData) plots.createTransitionData(gd);
        newFullLayout._dfltTitle = {
          plot: _(gd, "Click to enter Plot title"),
          subtitle: _(gd, "Click to enter Plot subtitle"),
          x: _(gd, "Click to enter X axis title"),
          y: _(gd, "Click to enter Y axis title"),
          colorbar: _(gd, "Click to enter Colorscale title"),
          annotation: _(gd, "new text")
        };
        newFullLayout._traceWord = _(gd, "trace");
        var formatObj = getFormatObj(gd, d3FormatKeys);
        newFullLayout._mapboxAccessToken = context.mapboxAccessToken;
        if (oldFullLayout._initialAutoSizeIsDone) {
          var oldWidth = oldFullLayout.width;
          var oldHeight = oldFullLayout.height;
          plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);
          if (!newLayout.width) newFullLayout.width = oldWidth;
          if (!newLayout.height) newFullLayout.height = oldHeight;
          plots.sanitizeMargins(newFullLayout);
        } else {
          plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);
          var missingWidthOrHeight = !newLayout.width || !newLayout.height;
          var autosize = newFullLayout.autosize;
          var autosizable = context.autosizable;
          var initialAutoSize = missingWidthOrHeight && (autosize || autosizable);
          if (initialAutoSize) plots.plotAutoSize(gd, newLayout, newFullLayout);
          else if (missingWidthOrHeight) plots.sanitizeMargins(newFullLayout);
          if (!autosize && missingWidthOrHeight) {
            newLayout.width = newFullLayout.width;
            newLayout.height = newFullLayout.height;
          }
        }
        newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators);
        newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys);
        newFullLayout._initialAutoSizeIsDone = true;
        newFullLayout._dataLength = newData.length;
        newFullLayout._modules = [];
        newFullLayout._visibleModules = [];
        newFullLayout._basePlotModules = [];
        var subplots = newFullLayout._subplots = emptySubplotLists();
        var splomAxes = newFullLayout._splomAxes = { x: {}, y: {} };
        var splomSubplots = newFullLayout._splomSubplots = {};
        newFullLayout._splomGridDflt = {};
        newFullLayout._scatterStackOpts = {};
        newFullLayout._firstScatter = {};
        newFullLayout._alignmentOpts = {};
        newFullLayout._colorAxes = {};
        newFullLayout._requestRangeslider = {};
        newFullLayout._traceUids = getTraceUids(oldFullData, newData);
        plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout);
        var splomXa = Object.keys(splomAxes.x);
        var splomYa = Object.keys(splomAxes.y);
        if (splomXa.length > 1 && splomYa.length > 1) {
          Registry.getComponentMethod("grid", "sizeDefaults")(newLayout, newFullLayout);
          for (i = 0; i < splomXa.length; i++) {
            Lib.pushUnique(subplots.xaxis, splomXa[i]);
          }
          for (i = 0; i < splomYa.length; i++) {
            Lib.pushUnique(subplots.yaxis, splomYa[i]);
          }
          for (var k in splomSubplots) {
            Lib.pushUnique(subplots.cartesian, k);
          }
        }
        newFullLayout._has = plots._hasPlotType.bind(newFullLayout);
        if (oldFullData.length === newFullData.length) {
          for (i = 0; i < newFullData.length; i++) {
            relinkPrivateKeys(newFullData[i], oldFullData[i]);
          }
        }
        plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData);
        var _modules = newFullLayout._visibleModules;
        var crossTraceDefaultsFuncs = [];
        for (i = 0; i < _modules.length; i++) {
          var funci = _modules[i].crossTraceDefaults;
          if (funci) Lib.pushUnique(crossTraceDefaultsFuncs, funci);
        }
        for (i = 0; i < crossTraceDefaultsFuncs.length; i++) {
          crossTraceDefaultsFuncs[i](newFullData, newFullLayout);
        }
        newFullLayout._hasOnlyLargeSploms = newFullLayout._basePlotModules.length === 1 && newFullLayout._basePlotModules[0].name === "splom" && splomXa.length > 15 && splomYa.length > 15 && newFullLayout.shapes.length === 0 && newFullLayout.images.length === 0;
        plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout);
        plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout);
        var hadCartesian = !!(oldFullLayout._has && oldFullLayout._has("cartesian"));
        var hasCartesian = !!(newFullLayout._has && newFullLayout._has("cartesian"));
        var hadBgLayer = hadCartesian;
        var hasBgLayer = hasCartesian;
        if (hadBgLayer && !hasBgLayer) {
          oldFullLayout._bgLayer.remove();
        } else if (hasBgLayer && !hadBgLayer) {
          newFullLayout._shouldCreateBgLayer = true;
        }
        if (oldFullLayout._zoomlayer && !gd._dragging) {
          clearOutline({
            // mock old gd
            _fullLayout: oldFullLayout
          });
        }
        fillMetaTextHelpers(newFullData, newFullLayout);
        relinkPrivateKeys(newFullLayout, oldFullLayout);
        Registry.getComponentMethod("colorscale", "crossTraceDefaults")(newFullData, newFullLayout);
        if (!newFullLayout._preGUI) newFullLayout._preGUI = {};
        if (!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {};
        var tracePreGUI = newFullLayout._tracePreGUI;
        var uids = {};
        var uid;
        for (uid in tracePreGUI) uids[uid] = "old";
        for (i = 0; i < newFullData.length; i++) {
          uid = newFullData[i]._fullInput.uid;
          if (!uids[uid]) tracePreGUI[uid] = {};
          uids[uid] = "new";
        }
        for (uid in uids) {
          if (uids[uid] === "old") delete tracePreGUI[uid];
        }
        initMargins(newFullLayout);
        Registry.getComponentMethod("rangeslider", "makeData")(newFullLayout);
        if (!skipUpdateCalc && oldCalcdata.length === newFullData.length) {
          plots.supplyDefaultsUpdateCalc(oldCalcdata, newFullData);
        }
      };
      plots.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) {
        for (var i = 0; i < newFullData.length; i++) {
          var newTrace = newFullData[i];
          var cd0 = (oldCalcdata[i] || [])[0];
          if (cd0 && cd0.trace) {
            var oldTrace = cd0.trace;
            if (oldTrace._hasCalcTransform) {
              var arrayAttrs = oldTrace._arrayAttrs;
              var j, astr, oldArrayVal;
              for (j = 0; j < arrayAttrs.length; j++) {
                astr = arrayAttrs[j];
                oldArrayVal = Lib.nestedProperty(oldTrace, astr).get().slice();
                Lib.nestedProperty(newTrace, astr).set(oldArrayVal);
              }
            }
            cd0.trace = newTrace;
          }
        }
      };
      function getTraceUids(oldFullData, newData) {
        var len = newData.length;
        var oldFullInput = [];
        var i, prevFullInput;
        for (i = 0; i < oldFullData.length; i++) {
          var thisFullInput = oldFullData[i]._fullInput;
          if (thisFullInput !== prevFullInput) oldFullInput.push(thisFullInput);
          prevFullInput = thisFullInput;
        }
        var oldLen = oldFullInput.length;
        var out = new Array(len);
        var seenUids = {};
        function setUid(uid, i2) {
          out[i2] = uid;
          seenUids[uid] = 1;
        }
        function tryUid(uid, i2) {
          if (uid && typeof uid === "string" && !seenUids[uid]) {
            setUid(uid, i2);
            return true;
          }
        }
        for (i = 0; i < len; i++) {
          var newUid = newData[i].uid;
          if (typeof newUid === "number") newUid = String(newUid);
          if (tryUid(newUid, i)) continue;
          if (i < oldLen && tryUid(oldFullInput[i].uid, i)) continue;
          setUid(Lib.randstr(seenUids), i);
        }
        return out;
      }
      function emptySubplotLists() {
        var collectableSubplotTypes = Registry.collectableSubplotTypes;
        var out = {};
        var i, j;
        if (!collectableSubplotTypes) {
          collectableSubplotTypes = [];
          var subplotsRegistry = Registry.subplotsRegistry;
          for (var subplotType in subplotsRegistry) {
            var subplotModule = subplotsRegistry[subplotType];
            var subplotAttr = subplotModule.attr;
            if (subplotAttr) {
              collectableSubplotTypes.push(subplotType);
              if (Array.isArray(subplotAttr)) {
                for (j = 0; j < subplotAttr.length; j++) {
                  Lib.pushUnique(collectableSubplotTypes, subplotAttr[j]);
                }
              }
            }
          }
        }
        for (i = 0; i < collectableSubplotTypes.length; i++) {
          out[collectableSubplotTypes[i]] = [];
        }
        return out;
      }
      function getFormatObj(gd, formatKeys) {
        var locale = gd._context.locale;
        if (!locale) locale = "en-US";
        var formatDone = false;
        var formatObj = {};
        function includeFormat(newFormat) {
          var formatFinished = true;
          for (var i2 = 0; i2 < formatKeys.length; i2++) {
            var formatKey = formatKeys[i2];
            if (!formatObj[formatKey]) {
              if (newFormat[formatKey]) {
                formatObj[formatKey] = newFormat[formatKey];
              } else formatFinished = false;
            }
          }
          if (formatFinished) formatDone = true;
        }
        for (var i = 0; i < 2; i++) {
          var locales = gd._context.locales;
          for (var j = 0; j < 2; j++) {
            var formatj = (locales[locale] || {}).format;
            if (formatj) {
              includeFormat(formatj);
              if (formatDone) break;
            }
            locales = Registry.localeRegistry;
          }
          var baseLocale = locale.split("-")[0];
          if (formatDone || baseLocale === locale) break;
          locale = baseLocale;
        }
        if (!formatDone) includeFormat(Registry.localeRegistry.en.format);
        return formatObj;
      }
      function getFormatter(formatObj, separators) {
        formatObj.decimal = separators.charAt(0);
        formatObj.thousands = separators.charAt(1);
        return {
          numberFormat: function(formatStr) {
            try {
              formatStr = formatLocale(formatObj).format(
                Lib.adjustFormat(formatStr)
              );
            } catch (e) {
              Lib.warnBadFormat(formatStr);
              return Lib.noFormat;
            }
            return formatStr;
          },
          timeFormat: timeFormatLocale(formatObj).utcFormat
        };
      }
      function fillMetaTextHelpers(newFullData, newFullLayout) {
        var _meta;
        var meta4data = [];
        if (newFullLayout.meta) {
          _meta = newFullLayout._meta = {
            meta: newFullLayout.meta,
            layout: { meta: newFullLayout.meta }
          };
        }
        for (var i = 0; i < newFullData.length; i++) {
          var trace = newFullData[i];
          if (trace.meta) {
            meta4data[trace.index] = trace._meta = { meta: trace.meta };
          } else if (newFullLayout.meta) {
            trace._meta = { meta: newFullLayout.meta };
          }
          if (newFullLayout.meta) {
            trace._meta.layout = { meta: newFullLayout.meta };
          }
        }
        if (meta4data.length) {
          if (!_meta) {
            _meta = newFullLayout._meta = {};
          }
          _meta.data = meta4data;
        }
      }
      plots.createTransitionData = function(gd) {
        if (!gd._transitionData) {
          gd._transitionData = {};
        }
        if (!gd._transitionData._frames) {
          gd._transitionData._frames = [];
        }
        if (!gd._transitionData._frameHash) {
          gd._transitionData._frameHash = {};
        }
        if (!gd._transitionData._counter) {
          gd._transitionData._counter = 0;
        }
        if (!gd._transitionData._interruptCallbacks) {
          gd._transitionData._interruptCallbacks = [];
        }
      };
      plots._hasPlotType = function(category) {
        var i;
        var basePlotModules = this._basePlotModules || [];
        for (i = 0; i < basePlotModules.length; i++) {
          if (basePlotModules[i].name === category) return true;
        }
        var modules = this._modules || [];
        for (i = 0; i < modules.length; i++) {
          var name2 = modules[i].name;
          if (name2 === category) return true;
          var _module = Registry.modules[name2];
          if (_module && _module.categories[category]) return true;
        }
        return false;
      };
      plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var i, j;
        var basePlotModules = oldFullLayout._basePlotModules || [];
        for (i = 0; i < basePlotModules.length; i++) {
          var _module = basePlotModules[i];
          if (_module.clean) {
            _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
          }
        }
        var hadGl = oldFullLayout._has && oldFullLayout._has("gl");
        var hasGl = newFullLayout._has && newFullLayout._has("gl");
        if (hadGl && !hasGl) {
          if (oldFullLayout._glcontainer !== void 0) {
            oldFullLayout._glcontainer.selectAll(".gl-canvas").remove();
            oldFullLayout._glcontainer.selectAll(".no-webgl").remove();
            oldFullLayout._glcanvas = null;
          }
        }
        var hasInfoLayer = !!oldFullLayout._infolayer;
        oldLoop:
          for (i = 0; i < oldFullData.length; i++) {
            var oldTrace = oldFullData[i];
            var oldUid = oldTrace.uid;
            for (j = 0; j < newFullData.length; j++) {
              var newTrace = newFullData[j];
              if (oldUid === newTrace.uid) continue oldLoop;
            }
            if (hasInfoLayer) {
              oldFullLayout._infolayer.select(".cb" + oldUid).remove();
            }
          }
      };
      plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var i, j;
        var oldSubplots = oldFullLayout._plots || {};
        var newSubplots = newFullLayout._plots = {};
        var newSubplotList = newFullLayout._subplots;
        var mockGd = {
          _fullData: newFullData,
          _fullLayout: newFullLayout
        };
        var ids = newSubplotList.cartesian || [];
        for (i = 0; i < ids.length; i++) {
          var id = ids[i];
          var oldSubplot = oldSubplots[id];
          var xaxis = axisIDs.getFromId(mockGd, id, "x");
          var yaxis = axisIDs.getFromId(mockGd, id, "y");
          var plotinfo;
          if (oldSubplot) {
            plotinfo = newSubplots[id] = oldSubplot;
          } else {
            plotinfo = newSubplots[id] = {};
            plotinfo.id = id;
          }
          xaxis._counterAxes.push(yaxis._id);
          yaxis._counterAxes.push(xaxis._id);
          xaxis._subplotsWith.push(id);
          yaxis._subplotsWith.push(id);
          plotinfo.xaxis = xaxis;
          plotinfo.yaxis = yaxis;
          plotinfo._hasClipOnAxisFalse = false;
          for (j = 0; j < newFullData.length; j++) {
            var trace = newFullData[j];
            if (trace.xaxis === plotinfo.xaxis._id && trace.yaxis === plotinfo.yaxis._id && trace.cliponaxis === false) {
              plotinfo._hasClipOnAxisFalse = true;
              break;
            }
          }
        }
        var axList = axisIDs.list(mockGd, null, true);
        var ax;
        for (i = 0; i < axList.length; i++) {
          ax = axList[i];
          var mainAx = null;
          if (ax.overlaying) {
            mainAx = axisIDs.getFromId(mockGd, ax.overlaying);
            if (mainAx && mainAx.overlaying) {
              ax.overlaying = false;
              mainAx = null;
            }
          }
          ax._mainAxis = mainAx || ax;
          if (mainAx) ax.domain = mainAx.domain.slice();
          ax._anchorAxis = ax.anchor === "free" ? null : axisIDs.getFromId(mockGd, ax.anchor);
        }
        for (i = 0; i < axList.length; i++) {
          ax = axList[i];
          ax._counterAxes.sort(axisIDs.idSort);
          ax._subplotsWith.sort(Lib.subplotSort);
          ax._mainSubplot = findMainSubplot(ax, newFullLayout);
          if (ax._counterAxes.length && (ax.spikemode && ax.spikemode.indexOf("across") !== -1 || ax.automargin && ax.mirror && ax.anchor !== "free" || Registry.getComponentMethod("rangeslider", "isVisible")(ax))) {
            var min = 1;
            var max = 0;
            for (j = 0; j < ax._counterAxes.length; j++) {
              var ax2 = axisIDs.getFromId(mockGd, ax._counterAxes[j]);
              min = Math.min(min, ax2.domain[0]);
              max = Math.max(max, ax2.domain[1]);
            }
            if (min < max) {
              ax._counterDomainMin = min;
              ax._counterDomainMax = max;
            }
          }
        }
      };
      function findMainSubplot(ax, fullLayout) {
        var mockGd = { _fullLayout: fullLayout };
        var isX = ax._id.charAt(0) === "x";
        var anchorAx = ax._mainAxis._anchorAxis;
        var mainSubplotID = "";
        var nextBestMainSubplotID = "";
        var anchorID = "";
        if (anchorAx) {
          anchorID = anchorAx._mainAxis._id;
          mainSubplotID = isX ? ax._id + anchorID : anchorID + ax._id;
        }
        if (!mainSubplotID || !fullLayout._plots[mainSubplotID]) {
          mainSubplotID = "";
          var counterIDs = ax._counterAxes;
          for (var j = 0; j < counterIDs.length; j++) {
            var counterPart = counterIDs[j];
            var id = isX ? ax._id + counterPart : counterPart + ax._id;
            if (!nextBestMainSubplotID) nextBestMainSubplotID = id;
            var counterAx = axisIDs.getFromId(mockGd, counterPart);
            if (anchorID && counterAx.overlaying === anchorID) {
              mainSubplotID = id;
              break;
            }
          }
        }
        return mainSubplotID || nextBestMainSubplotID;
      }
      plots.clearExpandedTraceDefaultColors = function(trace) {
        var colorAttrs, path, i;
        function locateColorAttrs(attr, attrName, attrs, level) {
          path[level] = attrName;
          path.length = level + 1;
          if (attr.valType === "color" && attr.dflt === void 0) {
            colorAttrs.push(path.join("."));
          }
        }
        path = [];
        colorAttrs = trace._module._colorAttrs;
        if (!colorAttrs) {
          trace._module._colorAttrs = colorAttrs = [];
          PlotSchema.crawl(
            trace._module.attributes,
            locateColorAttrs
          );
        }
        for (i = 0; i < colorAttrs.length; i++) {
          var origprop = Lib.nestedProperty(trace, "_input." + colorAttrs[i]);
          if (!origprop.get()) {
            Lib.nestedProperty(trace, colorAttrs[i]).set(null);
          }
        }
      };
      plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) {
        var modules = fullLayout._modules;
        var visibleModules = fullLayout._visibleModules;
        var basePlotModules = fullLayout._basePlotModules;
        var cnt = 0;
        var colorCnt = 0;
        var i, fullTrace, trace;
        fullLayout._transformModules = [];
        function pushModule(fullTrace2) {
          dataOut.push(fullTrace2);
          var _module = fullTrace2._module;
          if (!_module) return;
          Lib.pushUnique(modules, _module);
          if (fullTrace2.visible === true) Lib.pushUnique(visibleModules, _module);
          Lib.pushUnique(basePlotModules, fullTrace2._module.basePlotModule);
          cnt++;
          if (fullTrace2._input.visible !== false) colorCnt++;
        }
        var carpetIndex = {};
        var carpetDependents = [];
        var dataTemplate = (layout.template || {}).data || {};
        var templater = Template.traceTemplater(dataTemplate);
        for (i = 0; i < dataIn.length; i++) {
          trace = dataIn[i];
          fullTrace = templater.newTrace(trace);
          fullTrace.uid = fullLayout._traceUids[i];
          plots.supplyTraceDefaults(trace, fullTrace, colorCnt, fullLayout, i);
          fullTrace.index = i;
          fullTrace._input = trace;
          fullTrace._fullInput = fullTrace;
          pushModule(fullTrace);
          if (Registry.traceIs(fullTrace, "carpetAxis")) {
            carpetIndex[fullTrace.carpet] = fullTrace;
          }
          if (Registry.traceIs(fullTrace, "carpetDependent")) {
            carpetDependents.push(i);
          }
        }
        for (i = 0; i < carpetDependents.length; i++) {
          fullTrace = dataOut[carpetDependents[i]];
          if (!fullTrace.visible) continue;
          var carpetAxis = carpetIndex[fullTrace.carpet];
          fullTrace._carpet = carpetAxis;
          if (!carpetAxis || !carpetAxis.visible) {
            fullTrace.visible = false;
            continue;
          }
          fullTrace.xaxis = carpetAxis.xaxis;
          fullTrace.yaxis = carpetAxis.yaxis;
        }
      };
      plots.supplyAnimationDefaults = function(opts) {
        opts = opts || {};
        var i;
        var optsOut = {};
        function coerce(attr, dflt) {
          return Lib.coerce(opts || {}, optsOut, animationAttrs, attr, dflt);
        }
        coerce("mode");
        coerce("direction");
        coerce("fromcurrent");
        if (Array.isArray(opts.frame)) {
          optsOut.frame = [];
          for (i = 0; i < opts.frame.length; i++) {
            optsOut.frame[i] = plots.supplyAnimationFrameDefaults(opts.frame[i] || {});
          }
        } else {
          optsOut.frame = plots.supplyAnimationFrameDefaults(opts.frame || {});
        }
        if (Array.isArray(opts.transition)) {
          optsOut.transition = [];
          for (i = 0; i < opts.transition.length; i++) {
            optsOut.transition[i] = plots.supplyAnimationTransitionDefaults(opts.transition[i] || {});
          }
        } else {
          optsOut.transition = plots.supplyAnimationTransitionDefaults(opts.transition || {});
        }
        return optsOut;
      };
      plots.supplyAnimationFrameDefaults = function(opts) {
        var optsOut = {};
        function coerce(attr, dflt) {
          return Lib.coerce(opts || {}, optsOut, animationAttrs.frame, attr, dflt);
        }
        coerce("duration");
        coerce("redraw");
        return optsOut;
      };
      plots.supplyAnimationTransitionDefaults = function(opts) {
        var optsOut = {};
        function coerce(attr, dflt) {
          return Lib.coerce(opts || {}, optsOut, animationAttrs.transition, attr, dflt);
        }
        coerce("duration");
        coerce("easing");
        return optsOut;
      };
      plots.supplyFrameDefaults = function(frameIn) {
        var frameOut = {};
        function coerce(attr, dflt) {
          return Lib.coerce(frameIn, frameOut, frameAttrs, attr, dflt);
        }
        coerce("group");
        coerce("name");
        coerce("traces");
        coerce("baseframe");
        coerce("data");
        coerce("layout");
        return frameOut;
      };
      plots.supplyTraceDefaults = function(traceIn, traceOut, colorIndex, layout, traceInIndex) {
        var colorway = layout.colorway || Color2.defaults;
        var defaultColor = colorway[colorIndex % colorway.length];
        var i;
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
        }
        var visible = coerce("visible");
        coerce("type");
        coerce("name", layout._traceWord + " " + traceInIndex);
        coerce("uirevision", layout.uirevision);
        var _module = plots.getModule(traceOut);
        traceOut._module = _module;
        if (_module) {
          var basePlotModule = _module.basePlotModule;
          var subplotAttr = basePlotModule.attr;
          var subplotAttrs = basePlotModule.attributes;
          if (subplotAttr && subplotAttrs) {
            var subplots = layout._subplots;
            var subplotId = "";
            if (Array.isArray(subplotAttr)) {
              for (i = 0; i < subplotAttr.length; i++) {
                var attri = subplotAttr[i];
                var vali = Lib.coerce(traceIn, traceOut, subplotAttrs, attri);
                if (subplots[attri]) Lib.pushUnique(subplots[attri], vali);
                subplotId += vali;
              }
            } else {
              subplotId = Lib.coerce(traceIn, traceOut, subplotAttrs, subplotAttr);
            }
            if (subplots[basePlotModule.name]) {
              Lib.pushUnique(subplots[basePlotModule.name], subplotId);
            }
          }
        }
        if (visible) {
          coerce("customdata");
          coerce("ids");
          coerce("meta");
          if (Registry.traceIs(traceOut, "showLegend")) {
            Lib.coerce(
              traceIn,
              traceOut,
              _module.attributes.showlegend ? _module.attributes : plots.attributes,
              "showlegend"
            );
            Lib.coerce(
              traceIn,
              traceOut,
              _module.attributes.legend ? _module.attributes : plots.attributes,
              "legend"
            );
            coerce("legendwidth");
            coerce("legendgroup");
            coerce("legendgrouptitle.text");
            coerce("legendrank");
            traceOut._dfltShowLegend = true;
          } else {
            traceOut._dfltShowLegend = false;
          }
          if (_module) {
            _module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
          }
          if (!Registry.traceIs(traceOut, "noOpacity")) {
            coerce("opacity");
          }
          if (Registry.traceIs(traceOut, "notLegendIsolatable")) {
            traceOut.visible = !!traceOut.visible;
          }
          if (!Registry.traceIs(traceOut, "noHover")) {
            if (!traceOut.hovertemplate) Lib.coerceHoverinfo(traceIn, traceOut, layout);
            if (traceOut.type !== "parcats") {
              Registry.getComponentMethod("fx", "supplyDefaults")(traceIn, traceOut, defaultColor, layout);
            }
          }
          if (_module && _module.selectPoints) {
            var selectedpoints = coerce("selectedpoints");
            if (Lib.isTypedArray(selectedpoints)) {
              traceOut.selectedpoints = Array.from(selectedpoints);
            }
          }
        }
        return traceOut;
      };
      plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt);
        }
        var template = layoutIn.template;
        if (Lib.isPlainObject(template)) {
          layoutOut.template = template;
          layoutOut._template = template.layout;
          layoutOut._dataTemplate = template.data;
        }
        coerce("autotypenumbers");
        var font = Lib.coerceFont(coerce, "font");
        var fontSize = font.size;
        Lib.coerceFont(coerce, "title.font", font, { overrideDflt: {
          size: Math.round(fontSize * 1.4)
        } });
        coerce("title.text", layoutOut._dfltTitle.plot);
        coerce("title.xref");
        var titleYref = coerce("title.yref");
        coerce("title.pad.t");
        coerce("title.pad.r");
        coerce("title.pad.b");
        coerce("title.pad.l");
        var titleAutomargin = coerce("title.automargin");
        coerce("title.x");
        coerce("title.xanchor");
        coerce("title.y");
        coerce("title.yanchor");
        coerce("title.subtitle.text", layoutOut._dfltTitle.subtitle);
        Lib.coerceFont(coerce, "title.subtitle.font", font, {
          overrideDflt: {
            size: Math.round(layoutOut.title.font.size * 0.7)
          }
        });
        if (titleAutomargin) {
          if (titleYref === "paper") {
            if (layoutOut.title.y !== 0) layoutOut.title.y = 1;
            if (layoutOut.title.yanchor === "auto") {
              layoutOut.title.yanchor = layoutOut.title.y === 0 ? "top" : "bottom";
            }
          }
          if (titleYref === "container") {
            if (layoutOut.title.y === "auto") layoutOut.title.y = 1;
            if (layoutOut.title.yanchor === "auto") {
              layoutOut.title.yanchor = layoutOut.title.y < 0.5 ? "bottom" : "top";
            }
          }
        }
        var uniformtextMode = coerce("uniformtext.mode");
        if (uniformtextMode) {
          coerce("uniformtext.minsize");
        }
        coerce("autosize", !(layoutIn.width && layoutIn.height));
        coerce("width");
        coerce("height");
        coerce("minreducedwidth");
        coerce("minreducedheight");
        coerce("margin.l");
        coerce("margin.r");
        coerce("margin.t");
        coerce("margin.b");
        coerce("margin.pad");
        coerce("margin.autoexpand");
        if (layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut);
        Registry.getComponentMethod("grid", "sizeDefaults")(layoutIn, layoutOut);
        coerce("paper_bgcolor");
        coerce("separators", formatObj.decimal + formatObj.thousands);
        coerce("hidesources");
        coerce("colorway");
        coerce("datarevision");
        var uirevision = coerce("uirevision");
        coerce("editrevision", uirevision);
        coerce("selectionrevision", uirevision);
        Registry.getComponentMethod(
          "modebar",
          "supplyLayoutDefaults"
        )(layoutIn, layoutOut);
        Registry.getComponentMethod(
          "shapes",
          "supplyDrawNewShapeDefaults"
        )(layoutIn, layoutOut, coerce);
        Registry.getComponentMethod(
          "selections",
          "supplyDrawNewSelectionDefaults"
        )(layoutIn, layoutOut, coerce);
        coerce("meta");
        if (Lib.isPlainObject(layoutIn.transition)) {
          coerce("transition.duration");
          coerce("transition.easing");
          coerce("transition.ordering");
        }
        Registry.getComponentMethod(
          "calendars",
          "handleDefaults"
        )(layoutIn, layoutOut, "calendar");
        Registry.getComponentMethod(
          "fx",
          "supplyLayoutGlobalDefaults"
        )(layoutIn, layoutOut, coerce);
        Lib.coerce(layoutIn, layoutOut, scatterAttrs, "scattermode");
      };
      function getComputedSize(attr) {
        return typeof attr === "string" && attr.slice(-2) === "px" && parseFloat(attr);
      }
      plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) {
        var context = gd._context || {};
        var frameMargins = context.frameMargins;
        var newWidth;
        var newHeight;
        var isPlotDiv = Lib.isPlotDiv(gd);
        if (isPlotDiv) gd.emit("plotly_autosize");
        if (context.fillFrame) {
          newWidth = window.innerWidth;
          newHeight = window.innerHeight;
          document.body.style.overflow = "hidden";
        } else {
          var computedStyle = isPlotDiv ? window.getComputedStyle(gd) : {};
          newWidth = getComputedSize(computedStyle.width) || getComputedSize(computedStyle.maxWidth) || fullLayout.width;
          newHeight = getComputedSize(computedStyle.height) || getComputedSize(computedStyle.maxHeight) || fullLayout.height;
          if (isNumeric(frameMargins) && frameMargins > 0) {
            var factor = 1 - 2 * frameMargins;
            newWidth = Math.round(factor * newWidth);
            newHeight = Math.round(factor * newHeight);
          }
        }
        var minWidth = plots.layoutAttributes.width.min;
        var minHeight = plots.layoutAttributes.height.min;
        if (newWidth < minWidth) newWidth = minWidth;
        if (newHeight < minHeight) newHeight = minHeight;
        var widthHasChanged = !layout.width && Math.abs(fullLayout.width - newWidth) > 1;
        var heightHasChanged = !layout.height && Math.abs(fullLayout.height - newHeight) > 1;
        if (heightHasChanged || widthHasChanged) {
          if (widthHasChanged) fullLayout.width = newWidth;
          if (heightHasChanged) fullLayout.height = newHeight;
        }
        if (!gd._initialAutoSize) {
          gd._initialAutoSize = { width: newWidth, height: newHeight };
        }
        plots.sanitizeMargins(fullLayout);
      };
      plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) {
        var componentsRegistry = Registry.componentsRegistry;
        var basePlotModules = layoutOut._basePlotModules;
        var component, i, _module;
        var Cartesian = Registry.subplotsRegistry.cartesian;
        for (component in componentsRegistry) {
          _module = componentsRegistry[component];
          if (_module.includeBasePlot) {
            _module.includeBasePlot(layoutIn, layoutOut);
          }
        }
        if (!basePlotModules.length) {
          basePlotModules.push(Cartesian);
        }
        if (layoutOut._has("cartesian")) {
          Registry.getComponentMethod("grid", "contentDefaults")(layoutIn, layoutOut);
          Cartesian.finalizeSubplots(layoutIn, layoutOut);
        }
        for (var subplotType in layoutOut._subplots) {
          layoutOut._subplots[subplotType].sort(Lib.subplotSort);
        }
        for (i = 0; i < basePlotModules.length; i++) {
          _module = basePlotModules[i];
          if (_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
          }
        }
        var modules = layoutOut._modules;
        for (i = 0; i < modules.length; i++) {
          _module = modules[i];
          if (_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
          }
        }
        var transformModules = layoutOut._transformModules;
        for (i = 0; i < transformModules.length; i++) {
          _module = transformModules[i];
          if (_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData);
          }
        }
        for (component in componentsRegistry) {
          _module = componentsRegistry[component];
          if (_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
          }
        }
      };
      plots.purge = function(gd) {
        var fullLayout = gd._fullLayout || {};
        if (fullLayout._glcontainer !== void 0) {
          fullLayout._glcontainer.selectAll(".gl-canvas").remove();
          fullLayout._glcontainer.remove();
          fullLayout._glcanvas = null;
        }
        if (fullLayout._modeBar) fullLayout._modeBar.destroy();
        if (gd._transitionData) {
          if (gd._transitionData._interruptCallbacks) {
            gd._transitionData._interruptCallbacks.length = 0;
          }
          if (gd._transitionData._animationRaf) {
            window.cancelAnimationFrame(gd._transitionData._animationRaf);
          }
        }
        Lib.clearThrottle();
        Lib.clearResponsive(gd);
        delete gd.data;
        delete gd.layout;
        delete gd._fullData;
        delete gd._fullLayout;
        delete gd.calcdata;
        delete gd.empty;
        delete gd.fid;
        delete gd.undoqueue;
        delete gd.undonum;
        delete gd.autoplay;
        delete gd.changed;
        delete gd._promises;
        delete gd._redrawTimer;
        delete gd._hmlumcount;
        delete gd._hmpixcount;
        delete gd._transitionData;
        delete gd._transitioning;
        delete gd._initialAutoSize;
        delete gd._transitioningWithDuration;
        delete gd._dragging;
        delete gd._dragged;
        delete gd._dragdata;
        delete gd._hoverdata;
        delete gd._snapshotInProgress;
        delete gd._editing;
        delete gd._mouseDownTime;
        delete gd._legendMouseDownTime;
        if (gd.removeAllListeners) gd.removeAllListeners();
      };
      plots.style = function(gd) {
        var _modules = gd._fullLayout._visibleModules;
        var styleModules = [];
        var i;
        for (i = 0; i < _modules.length; i++) {
          var _module = _modules[i];
          if (_module.style) {
            Lib.pushUnique(styleModules, _module.style);
          }
        }
        for (i = 0; i < styleModules.length; i++) {
          styleModules[i](gd);
        }
      };
      plots.sanitizeMargins = function(fullLayout) {
        if (!fullLayout || !fullLayout.margin) return;
        var width = fullLayout.width;
        var height = fullLayout.height;
        var margin = fullLayout.margin;
        var plotWidth = width - (margin.l + margin.r);
        var plotHeight = height - (margin.t + margin.b);
        var correction;
        if (plotWidth < 0) {
          correction = (width - 1) / (margin.l + margin.r);
          margin.l = Math.floor(correction * margin.l);
          margin.r = Math.floor(correction * margin.r);
        }
        if (plotHeight < 0) {
          correction = (height - 1) / (margin.t + margin.b);
          margin.t = Math.floor(correction * margin.t);
          margin.b = Math.floor(correction * margin.b);
        }
      };
      plots.clearAutoMarginIds = function(gd) {
        gd._fullLayout._pushmarginIds = {};
      };
      plots.allowAutoMargin = function(gd, id) {
        gd._fullLayout._pushmarginIds[id] = 1;
      };
      function initMargins(fullLayout) {
        var margin = fullLayout.margin;
        if (!fullLayout._size) {
          var gs = fullLayout._size = {
            l: Math.round(margin.l),
            r: Math.round(margin.r),
            t: Math.round(margin.t),
            b: Math.round(margin.b),
            p: Math.round(margin.pad)
          };
          gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
          gs.h = Math.round(fullLayout.height) - gs.t - gs.b;
        }
        if (!fullLayout._pushmargin) fullLayout._pushmargin = {};
        if (!fullLayout._pushmarginIds) fullLayout._pushmarginIds = {};
        if (!fullLayout._reservedMargin) fullLayout._reservedMargin = {};
      }
      var MIN_SPECIFIED_WIDTH = 2;
      var MIN_SPECIFIED_HEIGHT = 2;
      plots.autoMargin = function(gd, id, o) {
        var fullLayout = gd._fullLayout;
        var width = fullLayout.width;
        var height = fullLayout.height;
        var margin = fullLayout.margin;
        var minreducedwidth = fullLayout.minreducedwidth;
        var minreducedheight = fullLayout.minreducedheight;
        var minFinalWidth = Lib.constrain(
          width - margin.l - margin.r,
          MIN_SPECIFIED_WIDTH,
          minreducedwidth
        );
        var minFinalHeight = Lib.constrain(
          height - margin.t - margin.b,
          MIN_SPECIFIED_HEIGHT,
          minreducedheight
        );
        var maxSpaceW = Math.max(0, width - minFinalWidth);
        var maxSpaceH = Math.max(0, height - minFinalHeight);
        var pushMargin = fullLayout._pushmargin;
        var pushMarginIds = fullLayout._pushmarginIds;
        if (margin.autoexpand !== false) {
          if (!o) {
            delete pushMargin[id];
            delete pushMarginIds[id];
          } else {
            var pad = o.pad;
            if (pad === void 0) {
              pad = Math.min(12, margin.l, margin.r, margin.t, margin.b);
            }
            if (maxSpaceW) {
              var rW = (o.l + o.r) / maxSpaceW;
              if (rW > 1) {
                o.l /= rW;
                o.r /= rW;
              }
            }
            if (maxSpaceH) {
              var rH = (o.t + o.b) / maxSpaceH;
              if (rH > 1) {
                o.t /= rH;
                o.b /= rH;
              }
            }
            var xl = o.xl !== void 0 ? o.xl : o.x;
            var xr = o.xr !== void 0 ? o.xr : o.x;
            var yt = o.yt !== void 0 ? o.yt : o.y;
            var yb = o.yb !== void 0 ? o.yb : o.y;
            pushMargin[id] = {
              l: { val: xl, size: o.l + pad },
              r: { val: xr, size: o.r + pad },
              b: { val: yb, size: o.b + pad },
              t: { val: yt, size: o.t + pad }
            };
            pushMarginIds[id] = 1;
          }
          if (!fullLayout._replotting) {
            return plots.doAutoMargin(gd);
          }
        }
      };
      function needsRedrawForShift(gd) {
        if ("_redrawFromAutoMarginCount" in gd._fullLayout) {
          return false;
        }
        var axList = axisIDs.list(gd, "", true);
        for (var ax in axList) {
          if (axList[ax].autoshift || axList[ax].shift) return true;
        }
        return false;
      }
      plots.doAutoMargin = function(gd) {
        var fullLayout = gd._fullLayout;
        var width = fullLayout.width;
        var height = fullLayout.height;
        if (!fullLayout._size) fullLayout._size = {};
        initMargins(fullLayout);
        var gs = fullLayout._size;
        var margin = fullLayout.margin;
        var reservedMargins = { t: 0, b: 0, l: 0, r: 0 };
        var oldMargins = Lib.extendFlat({}, gs);
        var ml = margin.l;
        var mr = margin.r;
        var mt = margin.t;
        var mb = margin.b;
        var pushMargin = fullLayout._pushmargin;
        var pushMarginIds = fullLayout._pushmarginIds;
        var minreducedwidth = fullLayout.minreducedwidth;
        var minreducedheight = fullLayout.minreducedheight;
        if (margin.autoexpand !== false) {
          for (var k in pushMargin) {
            if (!pushMarginIds[k]) delete pushMargin[k];
          }
          var margins = gd._fullLayout._reservedMargin;
          for (var key in margins) {
            for (var side in margins[key]) {
              var val = margins[key][side];
              reservedMargins[side] = Math.max(reservedMargins[side], val);
            }
          }
          pushMargin.base = {
            l: { val: 0, size: ml },
            r: { val: 1, size: mr },
            t: { val: 1, size: mt },
            b: { val: 0, size: mb }
          };
          for (var s in reservedMargins) {
            var autoMarginPush = 0;
            for (var m in pushMargin) {
              if (m !== "base") {
                if (isNumeric(pushMargin[m][s].size)) {
                  autoMarginPush = pushMargin[m][s].size > autoMarginPush ? pushMargin[m][s].size : autoMarginPush;
                }
              }
            }
            var extraMargin = Math.max(0, margin[s] - autoMarginPush);
            reservedMargins[s] = Math.max(0, reservedMargins[s] - extraMargin);
          }
          for (var k1 in pushMargin) {
            var pushleft = pushMargin[k1].l || {};
            var pushbottom = pushMargin[k1].b || {};
            var fl = pushleft.val;
            var pl = pushleft.size;
            var fb = pushbottom.val;
            var pb = pushbottom.size;
            var availableWidth = width - reservedMargins.r - reservedMargins.l;
            var availableHeight = height - reservedMargins.t - reservedMargins.b;
            for (var k2 in pushMargin) {
              if (isNumeric(pl) && pushMargin[k2].r) {
                var fr = pushMargin[k2].r.val;
                var pr = pushMargin[k2].r.size;
                if (fr > fl) {
                  var newL = (pl * fr + (pr - availableWidth) * fl) / (fr - fl);
                  var newR = (pr * (1 - fl) + (pl - availableWidth) * (1 - fr)) / (fr - fl);
                  if (newL + newR > ml + mr) {
                    ml = newL;
                    mr = newR;
                  }
                }
              }
              if (isNumeric(pb) && pushMargin[k2].t) {
                var ft = pushMargin[k2].t.val;
                var pt = pushMargin[k2].t.size;
                if (ft > fb) {
                  var newB = (pb * ft + (pt - availableHeight) * fb) / (ft - fb);
                  var newT = (pt * (1 - fb) + (pb - availableHeight) * (1 - ft)) / (ft - fb);
                  if (newB + newT > mb + mt) {
                    mb = newB;
                    mt = newT;
                  }
                }
              }
            }
          }
        }
        var minFinalWidth = Lib.constrain(
          width - margin.l - margin.r,
          MIN_SPECIFIED_WIDTH,
          minreducedwidth
        );
        var minFinalHeight = Lib.constrain(
          height - margin.t - margin.b,
          MIN_SPECIFIED_HEIGHT,
          minreducedheight
        );
        var maxSpaceW = Math.max(0, width - minFinalWidth);
        var maxSpaceH = Math.max(0, height - minFinalHeight);
        if (maxSpaceW) {
          var rW = (ml + mr) / maxSpaceW;
          if (rW > 1) {
            ml /= rW;
            mr /= rW;
          }
        }
        if (maxSpaceH) {
          var rH = (mb + mt) / maxSpaceH;
          if (rH > 1) {
            mb /= rH;
            mt /= rH;
          }
        }
        gs.l = Math.round(ml) + reservedMargins.l;
        gs.r = Math.round(mr) + reservedMargins.r;
        gs.t = Math.round(mt) + reservedMargins.t;
        gs.b = Math.round(mb) + reservedMargins.b;
        gs.p = Math.round(margin.pad);
        gs.w = Math.round(width) - gs.l - gs.r;
        gs.h = Math.round(height) - gs.t - gs.b;
        if (!fullLayout._replotting && (plots.didMarginChange(oldMargins, gs) || needsRedrawForShift(gd))) {
          if ("_redrawFromAutoMarginCount" in fullLayout) {
            fullLayout._redrawFromAutoMarginCount++;
          } else {
            fullLayout._redrawFromAutoMarginCount = 1;
          }
          var maxNumberOfRedraws = 3 * (1 + Object.keys(pushMarginIds).length);
          if (fullLayout._redrawFromAutoMarginCount < maxNumberOfRedraws) {
            return Registry.call("_doPlot", gd);
          } else {
            fullLayout._size = oldMargins;
            Lib.warn("Too many auto-margin redraws.");
          }
        }
        refineTicks(gd);
      };
      function refineTicks(gd) {
        var axList = axisIDs.list(gd, "", true);
        [
          "_adjustTickLabelsOverflow",
          "_hideCounterAxisInsideTickLabels"
        ].forEach(function(k) {
          for (var i = 0; i < axList.length; i++) {
            var hideFn = axList[i][k];
            if (hideFn) hideFn();
          }
        });
      }
      var marginKeys = ["l", "r", "t", "b", "p", "w", "h"];
      plots.didMarginChange = function(margin0, margin1) {
        for (var i = 0; i < marginKeys.length; i++) {
          var k = marginKeys[i];
          var m0 = margin0[k];
          var m1 = margin1[k];
          if (!isNumeric(m0) || Math.abs(m1 - m0) > 1) {
            return true;
          }
        }
        return false;
      };
      plots.graphJson = function(gd, dataonly, mode, output, useDefaults, includeConfig) {
        if (useDefaults && dataonly && !gd._fullData || useDefaults && !dataonly && !gd._fullLayout) {
          plots.supplyDefaults(gd);
        }
        var data = useDefaults ? gd._fullData : gd.data;
        var layout = useDefaults ? gd._fullLayout : gd.layout;
        var frames = (gd._transitionData || {})._frames;
        function stripObj(d, keepFunction) {
          if (typeof d === "function") {
            return keepFunction ? "_function_" : null;
          }
          if (Lib.isPlainObject(d)) {
            var o = {};
            var src;
            Object.keys(d).sort().forEach(function(v) {
              if (["_", "["].indexOf(v.charAt(0)) !== -1) return;
              if (typeof d[v] === "function") {
                if (keepFunction) o[v] = "_function";
                return;
              }
              if (mode === "keepdata") {
                if (v.slice(-3) === "src") {
                  return;
                }
              } else if (mode === "keepstream") {
                src = d[v + "src"];
                if (typeof src === "string" && src.indexOf(":") > 0) {
                  if (!Lib.isPlainObject(d.stream)) {
                    return;
                  }
                }
              } else if (mode !== "keepall") {
                src = d[v + "src"];
                if (typeof src === "string" && src.indexOf(":") > 0) {
                  return;
                }
              }
              o[v] = stripObj(d[v], keepFunction);
            });
            return o;
          }
          var dIsArray = Array.isArray(d);
          var dIsTypedArray = Lib.isTypedArray(d);
          if ((dIsArray || dIsTypedArray) && d.dtype && d.shape) {
            var bdata = d.bdata;
            return stripObj({
              dtype: d.dtype,
              shape: d.shape,
              bdata: (
                // case of ArrayBuffer
                Lib.isArrayBuffer(bdata) ? b64encode.encode(bdata) : (
                  // case of b64 string
                  bdata
                )
              )
            }, keepFunction);
          }
          if (dIsArray) {
            return d.map(function(x) {
              return stripObj(x, keepFunction);
            });
          }
          if (dIsTypedArray) {
            return Lib.simpleMap(d, Lib.identity);
          }
          if (Lib.isJSDate(d)) return Lib.ms2DateTimeLocal(+d);
          return d;
        }
        var obj = {
          data: (data || []).map(function(v) {
            var d = stripObj(v);
            if (dataonly) {
              delete d.fit;
            }
            return d;
          })
        };
        if (!dataonly) {
          obj.layout = stripObj(layout);
          if (useDefaults) {
            var gs = layout._size;
            obj.layout.computed = {
              margin: {
                b: gs.b,
                l: gs.l,
                r: gs.r,
                t: gs.t
              }
            };
          }
        }
        if (frames) obj.frames = stripObj(frames);
        if (includeConfig) obj.config = stripObj(gd._context, true);
        return output === "object" ? obj : JSON.stringify(obj);
      };
      plots.modifyFrames = function(gd, operations) {
        var i, op, frame;
        var _frames = gd._transitionData._frames;
        var _frameHash = gd._transitionData._frameHash;
        for (i = 0; i < operations.length; i++) {
          op = operations[i];
          switch (op.type) {
            // No reason this couldn't exist, but is currently unused/untested:
            /* case 'rename':
                frame = _frames[op.index];
                delete _frameHash[frame.name];
                _frameHash[op.name] = frame;
                frame.name = op.name;
                break;*/
            case "replace":
              frame = op.value;
              var oldName = (_frames[op.index] || {}).name;
              var newName = frame.name;
              _frames[op.index] = _frameHash[newName] = frame;
              if (newName !== oldName) {
                delete _frameHash[oldName];
                _frameHash[newName] = frame;
              }
              break;
            case "insert":
              frame = op.value;
              _frameHash[frame.name] = frame;
              _frames.splice(op.index, 0, frame);
              break;
            case "delete":
              frame = _frames[op.index];
              delete _frameHash[frame.name];
              _frames.splice(op.index, 1);
              break;
          }
        }
        return Promise.resolve();
      };
      plots.computeFrame = function(gd, frameName) {
        var frameLookup = gd._transitionData._frameHash;
        var i, traceIndices, traceIndex, destIndex;
        if (!frameName) {
          throw new Error("computeFrame must be given a string frame name");
        }
        var framePtr = frameLookup[frameName.toString()];
        if (!framePtr) {
          return false;
        }
        var frameStack = [framePtr];
        var frameNameStack = [framePtr.name];
        while (framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) {
          if (frameNameStack.indexOf(framePtr.name) !== -1) break;
          frameStack.push(framePtr);
          frameNameStack.push(framePtr.name);
        }
        var result = {};
        while (framePtr = frameStack.pop()) {
          if (framePtr.layout) {
            result.layout = plots.extendLayout(result.layout, framePtr.layout);
          }
          if (framePtr.data) {
            if (!result.data) {
              result.data = [];
            }
            traceIndices = framePtr.traces;
            if (!traceIndices) {
              traceIndices = [];
              for (i = 0; i < framePtr.data.length; i++) {
                traceIndices[i] = i;
              }
            }
            if (!result.traces) {
              result.traces = [];
            }
            for (i = 0; i < framePtr.data.length; i++) {
              traceIndex = traceIndices[i];
              if (traceIndex === void 0 || traceIndex === null) {
                continue;
              }
              destIndex = result.traces.indexOf(traceIndex);
              if (destIndex === -1) {
                destIndex = result.data.length;
                result.traces[destIndex] = traceIndex;
              }
              result.data[destIndex] = plots.extendTrace(result.data[destIndex], framePtr.data[i]);
            }
          }
        }
        return result;
      };
      plots.recomputeFrameHash = function(gd) {
        var hash = gd._transitionData._frameHash = {};
        var frames = gd._transitionData._frames;
        for (var i = 0; i < frames.length; i++) {
          var frame = frames[i];
          if (frame && frame.name) {
            hash[frame.name] = frame;
          }
        }
      };
      plots.extendObjectWithContainers = function(dest, src, containerPaths) {
        var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer;
        var copy = Lib.extendDeepNoArrays({}, src || {});
        var expandedObj = Lib.expandObjectPaths(copy);
        var containerObj = {};
        if (containerPaths && containerPaths.length) {
          for (i = 0; i < containerPaths.length; i++) {
            containerProp = Lib.nestedProperty(expandedObj, containerPaths[i]);
            containerVal = containerProp.get();
            if (containerVal === void 0) {
              Lib.nestedProperty(containerObj, containerPaths[i]).set(null);
            } else {
              containerProp.set(null);
              Lib.nestedProperty(containerObj, containerPaths[i]).set(containerVal);
            }
          }
        }
        dest = Lib.extendDeepNoArrays(dest || {}, expandedObj);
        if (containerPaths && containerPaths.length) {
          for (i = 0; i < containerPaths.length; i++) {
            srcProp = Lib.nestedProperty(containerObj, containerPaths[i]);
            srcContainer = srcProp.get();
            if (!srcContainer) continue;
            destProp = Lib.nestedProperty(dest, containerPaths[i]);
            destContainer = destProp.get();
            if (!Array.isArray(destContainer)) {
              destContainer = [];
              destProp.set(destContainer);
            }
            for (j = 0; j < srcContainer.length; j++) {
              var srcObj = srcContainer[j];
              if (srcObj === null) destContainer[j] = null;
              else {
                destContainer[j] = plots.extendObjectWithContainers(destContainer[j], srcObj);
              }
            }
            destProp.set(destContainer);
          }
        }
        return dest;
      };
      plots.dataArrayContainers = ["transforms", "dimensions"];
      plots.layoutArrayContainers = Registry.layoutArrayContainers;
      plots.extendTrace = function(destTrace, srcTrace) {
        return plots.extendObjectWithContainers(destTrace, srcTrace, plots.dataArrayContainers);
      };
      plots.extendLayout = function(destLayout, srcLayout) {
        return plots.extendObjectWithContainers(destLayout, srcLayout, plots.layoutArrayContainers);
      };
      plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) {
        var opts = { redraw: frameOpts.redraw };
        var transitionedTraces = {};
        var axEdits = [];
        opts.prepareFn = function() {
          var dataLength = Array.isArray(data) ? data.length : 0;
          var traceIndices = traces.slice(0, dataLength);
          for (var i = 0; i < traceIndices.length; i++) {
            var traceIdx = traceIndices[i];
            var trace = gd._fullData[traceIdx];
            var _module = trace._module;
            if (!_module) continue;
            if (_module.animatable) {
              var n = _module.basePlotModule.name;
              if (!transitionedTraces[n]) transitionedTraces[n] = [];
              transitionedTraces[n].push(traceIdx);
            }
            gd.data[traceIndices[i]] = plots.extendTrace(gd.data[traceIndices[i]], data[i]);
          }
          var layoutUpdate = Lib.expandObjectPaths(Lib.extendDeepNoArrays({}, layout));
          var axisAttrRe = /^[xy]axis[0-9]*$/;
          for (var attr in layoutUpdate) {
            if (!axisAttrRe.test(attr)) continue;
            delete layoutUpdate[attr].range;
          }
          plots.extendLayout(gd.layout, layoutUpdate);
          delete gd.calcdata;
          plots.supplyDefaults(gd);
          plots.doCalcdata(gd);
          var newLayout = Lib.expandObjectPaths(layout);
          if (newLayout) {
            var subplots = gd._fullLayout._plots;
            for (var k in subplots) {
              var plotinfo = subplots[k];
              var xa = plotinfo.xaxis;
              var ya = plotinfo.yaxis;
              var xr0 = xa.range.slice();
              var yr0 = ya.range.slice();
              var xr1 = null;
              var yr1 = null;
              var editX = null;
              var editY = null;
              if (Array.isArray(newLayout[xa._name + ".range"])) {
                xr1 = newLayout[xa._name + ".range"].slice();
              } else if (Array.isArray((newLayout[xa._name] || {}).range)) {
                xr1 = newLayout[xa._name].range.slice();
              }
              if (Array.isArray(newLayout[ya._name + ".range"])) {
                yr1 = newLayout[ya._name + ".range"].slice();
              } else if (Array.isArray((newLayout[ya._name] || {}).range)) {
                yr1 = newLayout[ya._name].range.slice();
              }
              if (xr0 && xr1 && (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1]))) {
                editX = { xr0, xr1 };
              }
              if (yr0 && yr1 && (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1]))) {
                editY = { yr0, yr1 };
              }
              if (editX || editY) {
                axEdits.push(Lib.extendFlat({ plotinfo }, editX, editY));
              }
            }
          }
          return Promise.resolve();
        };
        opts.runFn = function(makeCallback) {
          var traceTransitionOpts;
          var basePlotModules = gd._fullLayout._basePlotModules;
          var hasAxisTransition = axEdits.length;
          var i;
          if (layout) {
            for (i = 0; i < basePlotModules.length; i++) {
              if (basePlotModules[i].transitionAxes) {
                basePlotModules[i].transitionAxes(gd, axEdits, transitionOpts, makeCallback);
              }
            }
          }
          if (hasAxisTransition) {
            traceTransitionOpts = Lib.extendFlat({}, transitionOpts);
            traceTransitionOpts.duration = 0;
            delete transitionedTraces.cartesian;
          } else {
            traceTransitionOpts = transitionOpts;
          }
          for (var n in transitionedTraces) {
            var traceIndices = transitionedTraces[n];
            var _module = gd._fullData[traceIndices[0]]._module;
            _module.basePlotModule.plot(gd, traceIndices, traceTransitionOpts, makeCallback);
          }
        };
        return _transition(gd, transitionOpts, opts);
      };
      plots.transitionFromReact = function(gd, restyleFlags, relayoutFlags, oldFullLayout) {
        var fullLayout = gd._fullLayout;
        var transitionOpts = fullLayout.transition;
        var opts = {};
        var axEdits = [];
        opts.prepareFn = function() {
          var subplots = fullLayout._plots;
          opts.redraw = false;
          if (restyleFlags.anim === "some") opts.redraw = true;
          if (relayoutFlags.anim === "some") opts.redraw = true;
          for (var k in subplots) {
            var plotinfo = subplots[k];
            var xa = plotinfo.xaxis;
            var ya = plotinfo.yaxis;
            var xr0 = oldFullLayout[xa._name].range.slice();
            var yr0 = oldFullLayout[ya._name].range.slice();
            var xr1 = xa.range.slice();
            var yr1 = ya.range.slice();
            xa.setScale();
            ya.setScale();
            var editX = null;
            var editY = null;
            if (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1])) {
              editX = { xr0, xr1 };
            }
            if (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1])) {
              editY = { yr0, yr1 };
            }
            if (editX || editY) {
              axEdits.push(Lib.extendFlat({ plotinfo }, editX, editY));
            }
          }
          return Promise.resolve();
        };
        opts.runFn = function(makeCallback) {
          var fullData = gd._fullData;
          var fullLayout2 = gd._fullLayout;
          var basePlotModules = fullLayout2._basePlotModules;
          var axisTransitionOpts;
          var traceTransitionOpts;
          var transitionedTraces;
          var allTraceIndices = [];
          for (var i = 0; i < fullData.length; i++) {
            allTraceIndices.push(i);
          }
          function transitionAxes() {
            if (!gd._fullLayout) return;
            for (var j = 0; j < basePlotModules.length; j++) {
              if (basePlotModules[j].transitionAxes) {
                basePlotModules[j].transitionAxes(gd, axEdits, axisTransitionOpts, makeCallback);
              }
            }
          }
          function transitionTraces() {
            if (!gd._fullLayout) return;
            for (var j = 0; j < basePlotModules.length; j++) {
              basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
            }
          }
          if (axEdits.length && restyleFlags.anim) {
            if (transitionOpts.ordering === "traces first") {
              axisTransitionOpts = Lib.extendFlat({}, transitionOpts, { duration: 0 });
              transitionedTraces = allTraceIndices;
              traceTransitionOpts = transitionOpts;
              setTimeout(transitionAxes, transitionOpts.duration);
              transitionTraces();
            } else {
              axisTransitionOpts = transitionOpts;
              transitionedTraces = null;
              traceTransitionOpts = Lib.extendFlat({}, transitionOpts, { duration: 0 });
              setTimeout(transitionTraces, axisTransitionOpts.duration);
              transitionAxes();
            }
          } else if (axEdits.length) {
            axisTransitionOpts = transitionOpts;
            transitionAxes();
          } else if (restyleFlags.anim) {
            transitionedTraces = allTraceIndices;
            traceTransitionOpts = transitionOpts;
            transitionTraces();
          }
        };
        return _transition(gd, transitionOpts, opts);
      };
      function _transition(gd, transitionOpts, opts) {
        var aborted = false;
        function executeCallbacks(list) {
          var p = Promise.resolve();
          if (!list) return p;
          while (list.length) {
            p = p.then(list.shift());
          }
          return p;
        }
        function flushCallbacks(list) {
          if (!list) return;
          while (list.length) {
            list.shift();
          }
        }
        function executeTransitions() {
          gd.emit("plotly_transitioning", []);
          return new Promise(function(resolve) {
            gd._transitioning = true;
            if (transitionOpts.duration > 0) {
              gd._transitioningWithDuration = true;
            }
            gd._transitionData._interruptCallbacks.push(function() {
              aborted = true;
            });
            if (opts.redraw) {
              gd._transitionData._interruptCallbacks.push(function() {
                return Registry.call("redraw", gd);
              });
            }
            gd._transitionData._interruptCallbacks.push(function() {
              gd.emit("plotly_transitioninterrupted", []);
            });
            var numCallbacks = 0;
            var numCompleted = 0;
            function makeCallback() {
              numCallbacks++;
              return function() {
                numCompleted++;
                if (!aborted && numCompleted === numCallbacks) {
                  completeTransition(resolve);
                }
              };
            }
            opts.runFn(makeCallback);
            setTimeout(makeCallback());
          });
        }
        function completeTransition(callback) {
          if (!gd._transitionData) return;
          flushCallbacks(gd._transitionData._interruptCallbacks);
          return Promise.resolve().then(function() {
            if (opts.redraw) {
              return Registry.call("redraw", gd);
            }
          }).then(function() {
            gd._transitioning = false;
            gd._transitioningWithDuration = false;
            gd.emit("plotly_transitioned", []);
          }).then(callback);
        }
        function interruptPreviousTransitions() {
          if (!gd._transitionData) return;
          gd._transitioning = false;
          return executeCallbacks(gd._transitionData._interruptCallbacks);
        }
        var seq = [
          plots.previousPromises,
          interruptPreviousTransitions,
          opts.prepareFn,
          plots.rehover,
          plots.reselect,
          executeTransitions
        ];
        var transitionStarting = Lib.syncOrAsync(seq, gd);
        if (!transitionStarting || !transitionStarting.then) {
          transitionStarting = Promise.resolve();
        }
        return transitionStarting.then(function() {
          return gd;
        });
      }
      plots.doCalcdata = function(gd, traces) {
        var axList = axisIDs.list(gd);
        var fullData = gd._fullData;
        var fullLayout = gd._fullLayout;
        var trace, _module, i, j;
        var calcdata = new Array(fullData.length);
        var oldCalcdata = (gd.calcdata || []).slice();
        gd.calcdata = calcdata;
        fullLayout._numBoxes = 0;
        fullLayout._numViolins = 0;
        fullLayout._violinScaleGroupStats = {};
        gd._hmpixcount = 0;
        gd._hmlumcount = 0;
        fullLayout._piecolormap = {};
        fullLayout._sunburstcolormap = {};
        fullLayout._treemapcolormap = {};
        fullLayout._iciclecolormap = {};
        fullLayout._funnelareacolormap = {};
        for (i = 0; i < fullData.length; i++) {
          if (Array.isArray(traces) && traces.indexOf(i) === -1) {
            calcdata[i] = oldCalcdata[i];
            continue;
          }
        }
        for (i = 0; i < fullData.length; i++) {
          trace = fullData[i];
          trace._arrayAttrs = PlotSchema.findArrayAttributes(trace);
          trace._extremes = {};
        }
        var polarIds = fullLayout._subplots.polar || [];
        for (i = 0; i < polarIds.length; i++) {
          axList.push(
            fullLayout[polarIds[i]].radialaxis,
            fullLayout[polarIds[i]].angularaxis
          );
        }
        for (var k in fullLayout._colorAxes) {
          var cOpts = fullLayout[k];
          if (cOpts.cauto !== false) {
            delete cOpts.cmin;
            delete cOpts.cmax;
          }
        }
        var hasCalcTransform = false;
        function transformCalci(i2) {
          trace = fullData[i2];
          _module = trace._module;
          if (trace.visible === true && trace.transforms) {
            if (_module && _module.calc) {
              var cdi = _module.calc(gd, trace);
              if (cdi[0] && cdi[0].t && cdi[0].t._scene) {
                delete cdi[0].t._scene.dirty;
              }
            }
            for (j = 0; j < trace.transforms.length; j++) {
              var transform = trace.transforms[j];
              _module = transformsRegistry[transform.type];
              if (_module && _module.calcTransform) {
                trace._hasCalcTransform = true;
                hasCalcTransform = true;
                _module.calcTransform(gd, trace, transform);
              }
            }
          }
        }
        function calci(i2, isContainer) {
          trace = fullData[i2];
          _module = trace._module;
          if (!!_module.isContainer !== isContainer) return;
          var cd = [];
          if (trace.visible === true && trace._length !== 0) {
            delete trace._indexToPoints;
            var transforms = trace.transforms || [];
            for (j = transforms.length - 1; j >= 0; j--) {
              if (transforms[j].enabled) {
                trace._indexToPoints = transforms[j]._indexToPoints;
                break;
              }
            }
            if (_module && _module.calc) {
              cd = _module.calc(gd, trace);
            }
          }
          if (!Array.isArray(cd) || !cd[0]) {
            cd = [{ x: BADNUM, y: BADNUM }];
          }
          if (!cd[0].t) cd[0].t = {};
          cd[0].trace = trace;
          calcdata[i2] = cd;
        }
        setupAxisCategories(axList, fullData, fullLayout);
        for (i = 0; i < fullData.length; i++) calci(i, true);
        for (i = 0; i < fullData.length; i++) transformCalci(i);
        if (hasCalcTransform) setupAxisCategories(axList, fullData, fullLayout);
        for (i = 0; i < fullData.length; i++) calci(i, true);
        for (i = 0; i < fullData.length; i++) calci(i, false);
        doCrossTraceCalc(gd);
        var sorted = sortAxisCategoriesByValue(axList, gd);
        if (sorted.length) {
          fullLayout._numBoxes = 0;
          fullLayout._numViolins = 0;
          for (i = 0; i < sorted.length; i++) calci(sorted[i], true);
          for (i = 0; i < sorted.length; i++) calci(sorted[i], false);
          doCrossTraceCalc(gd);
        }
        Registry.getComponentMethod("fx", "calc")(gd);
        Registry.getComponentMethod("errorbars", "calc")(gd);
      };
      var sortAxisCategoriesByValueRegex = /(total|sum|min|max|mean|geometric mean|median) (ascending|descending)/;
      function sortAxisCategoriesByValue(axList, gd) {
        var affectedTraces = [];
        var i, j, k, l, o;
        function zMapCategory(type2, ax2, value2) {
          var axLetter2 = ax2._id.charAt(0);
          if (type2 === "histogram2dcontour") {
            var counterAxLetter = ax2._counterAxes[0];
            var counterAx = axisIDs.getFromId(gd, counterAxLetter);
            var xCategorical = axLetter2 === "x" || counterAxLetter === "x" && counterAx.type === "category";
            var yCategorical = axLetter2 === "y" || counterAxLetter === "y" && counterAx.type === "category";
            return function(o2, l2) {
              if (o2 === 0 || l2 === 0) return -1;
              if (xCategorical && o2 === value2[l2].length - 1) return -1;
              if (yCategorical && l2 === value2.length - 1) return -1;
              return (axLetter2 === "y" ? l2 : o2) - 1;
            };
          } else {
            return function(o2, l2) {
              return axLetter2 === "y" ? l2 : o2;
            };
          }
        }
        var aggFn = {
          min: function(values) {
            return Lib.aggNums(Math.min, null, values);
          },
          max: function(values) {
            return Lib.aggNums(Math.max, null, values);
          },
          sum: function(values) {
            return Lib.aggNums(function(a, b) {
              return a + b;
            }, null, values);
          },
          total: function(values) {
            return Lib.aggNums(function(a, b) {
              return a + b;
            }, null, values);
          },
          mean: function(values) {
            return Lib.mean(values);
          },
          "geometric mean": function(values) {
            return Lib.geometricMean(values);
          },
          median: function(values) {
            return Lib.median(values);
          }
        };
        function sortAscending(a, b) {
          return a[1] - b[1];
        }
        function sortDescending(a, b) {
          return b[1] - a[1];
        }
        for (i = 0; i < axList.length; i++) {
          var ax = axList[i];
          if (ax.type !== "category") continue;
          var match = ax.categoryorder.match(sortAxisCategoriesByValueRegex);
          if (match) {
            var aggregator = match[1];
            var order = match[2];
            var axLetter = ax._id.charAt(0);
            var isX = axLetter === "x";
            var categoriesValue = [];
            for (j = 0; j < ax._categories.length; j++) {
              categoriesValue.push([ax._categories[j], []]);
            }
            for (j = 0; j < ax._traceIndices.length; j++) {
              var traceIndex = ax._traceIndices[j];
              var fullTrace = gd._fullData[traceIndex];
              if (fullTrace.visible !== true) continue;
              var type = fullTrace.type;
              if (Registry.traceIs(fullTrace, "histogram")) {
                delete fullTrace._xautoBinFinished;
                delete fullTrace._yautoBinFinished;
              }
              var isSplom = type === "splom";
              var isScattergl = type === "scattergl";
              var cd = gd.calcdata[traceIndex];
              for (k = 0; k < cd.length; k++) {
                var cdi = cd[k];
                var catIndex, value;
                if (isSplom) {
                  var currentDimensionIndex = fullTrace._axesDim[ax._id];
                  if (!isX) {
                    var associatedXAxisID = fullTrace._diag[currentDimensionIndex][0];
                    if (associatedXAxisID) ax = gd._fullLayout[axisIDs.id2name(associatedXAxisID)];
                  }
                  var categories = cdi.trace.dimensions[currentDimensionIndex].values;
                  for (l = 0; l < categories.length; l++) {
                    catIndex = ax._categoriesMap[categories[l]];
                    for (o = 0; o < cdi.trace.dimensions.length; o++) {
                      if (o === currentDimensionIndex) continue;
                      var dimension = cdi.trace.dimensions[o];
                      categoriesValue[catIndex][1].push(dimension.values[l]);
                    }
                  }
                } else if (isScattergl) {
                  for (l = 0; l < cdi.t.x.length; l++) {
                    if (isX) {
                      catIndex = cdi.t.x[l];
                      value = cdi.t.y[l];
                    } else {
                      catIndex = cdi.t.y[l];
                      value = cdi.t.x[l];
                    }
                    categoriesValue[catIndex][1].push(value);
                  }
                  if (cdi.t && cdi.t._scene) {
                    delete cdi.t._scene.dirty;
                  }
                } else if (cdi.hasOwnProperty("z")) {
                  value = cdi.z;
                  var mapping = zMapCategory(fullTrace.type, ax, value);
                  for (l = 0; l < value.length; l++) {
                    for (o = 0; o < value[l].length; o++) {
                      catIndex = mapping(o, l);
                      if (catIndex + 1) categoriesValue[catIndex][1].push(value[l][o]);
                    }
                  }
                } else {
                  catIndex = cdi.p;
                  if (catIndex === void 0) catIndex = cdi[axLetter];
                  value = cdi.s;
                  if (value === void 0) value = cdi.v;
                  if (value === void 0) value = isX ? cdi.y : cdi.x;
                  if (!Array.isArray(value)) {
                    if (value === void 0) value = [];
                    else value = [value];
                  }
                  for (l = 0; l < value.length; l++) {
                    categoriesValue[catIndex][1].push(value[l]);
                  }
                }
              }
            }
            ax._categoriesValue = categoriesValue;
            var categoriesAggregatedValue = [];
            for (j = 0; j < categoriesValue.length; j++) {
              categoriesAggregatedValue.push([
                categoriesValue[j][0],
                aggFn[aggregator](categoriesValue[j][1])
              ]);
            }
            categoriesAggregatedValue.sort(order === "descending" ? sortDescending : sortAscending);
            ax._categoriesAggregatedValue = categoriesAggregatedValue;
            ax._initialCategories = categoriesAggregatedValue.map(function(c) {
              return c[0];
            });
            affectedTraces = affectedTraces.concat(ax.sortByInitialCategories());
          }
        }
        return affectedTraces;
      }
      function setupAxisCategories(axList, fullData, fullLayout) {
        var axLookup = {};
        function setupOne(ax) {
          ax.clearCalc();
          if (ax.type === "multicategory") {
            ax.setupMultiCategory(fullData);
          }
          axLookup[ax._id] = 1;
        }
        Lib.simpleMap(axList, setupOne);
        var matchGroups = fullLayout._axisMatchGroups || [];
        for (var i = 0; i < matchGroups.length; i++) {
          for (var axId in matchGroups[i]) {
            if (!axLookup[axId]) {
              setupOne(fullLayout[axisIDs.id2name(axId)]);
            }
          }
        }
      }
      function doCrossTraceCalc(gd) {
        var fullLayout = gd._fullLayout;
        var modules = fullLayout._visibleModules;
        var hash = {};
        var i, j, k;
        for (j = 0; j < modules.length; j++) {
          var _module = modules[j];
          var fn = _module.crossTraceCalc;
          if (fn) {
            var spType = _module.basePlotModule.name;
            if (hash[spType]) {
              Lib.pushUnique(hash[spType], fn);
            } else {
              hash[spType] = [fn];
            }
          }
        }
        for (k in hash) {
          var methods = hash[k];
          var subplots = fullLayout._subplots[k];
          if (Array.isArray(subplots)) {
            for (i = 0; i < subplots.length; i++) {
              var sp = subplots[i];
              var spInfo = k === "cartesian" ? fullLayout._plots[sp] : fullLayout[sp];
              for (j = 0; j < methods.length; j++) {
                methods[j](gd, spInfo, sp);
              }
            }
          } else {
            for (j = 0; j < methods.length; j++) {
              methods[j](gd);
            }
          }
        }
      }
      plots.rehover = function(gd) {
        if (gd._fullLayout._rehover) {
          gd._fullLayout._rehover();
        }
      };
      plots.redrag = function(gd) {
        if (gd._fullLayout._redrag) {
          gd._fullLayout._redrag();
        }
      };
      plots.reselect = function(gd) {
        var fullLayout = gd._fullLayout;
        var A2 = (gd.layout || {}).selections;
        var B2 = fullLayout._previousSelections;
        fullLayout._previousSelections = A2;
        var mayEmitSelected = fullLayout._reselect || JSON.stringify(A2) !== JSON.stringify(B2);
        Registry.getComponentMethod("selections", "reselect")(gd, mayEmitSelected);
      };
      plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subplotLayout) {
        var traceHashOld = subplot.traceHash;
        var traceHash = {};
        var i;
        for (i = 0; i < subplotCalcData.length; i++) {
          var calcTraces = subplotCalcData[i];
          var trace = calcTraces[0].trace;
          if (trace.visible) {
            traceHash[trace.type] = traceHash[trace.type] || [];
            traceHash[trace.type].push(calcTraces);
          }
        }
        for (var moduleNameOld in traceHashOld) {
          if (!traceHash[moduleNameOld]) {
            var fakeCalcTrace = traceHashOld[moduleNameOld][0];
            var fakeTrace = fakeCalcTrace[0].trace;
            fakeTrace.visible = false;
            traceHash[moduleNameOld] = [fakeCalcTrace];
          }
        }
        for (var moduleName in traceHash) {
          var moduleCalcData = traceHash[moduleName];
          var _module = moduleCalcData[0][0].trace._module;
          _module.plot(gd, subplot, Lib.filterVisible(moduleCalcData), subplotLayout);
        }
        subplot.traceHash = traceHash;
      };
      plots.plotBasePlot = function(desiredType, gd, traces, transitionOpts, makeOnCompleteCallback) {
        var _module = Registry.getModule(desiredType);
        var cdmodule = getModuleCalcData(gd.calcdata, _module)[0];
        _module.plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback);
      };
      plots.cleanBasePlot = function(desiredType, newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var had = oldFullLayout._has && oldFullLayout._has(desiredType);
        var has = newFullLayout._has && newFullLayout._has(desiredType);
        if (had && !has) {
          oldFullLayout["_" + desiredType + "layer"].selectAll("g.trace").remove();
        }
      };
    }
  });

  // src/constants/xmlns_namespaces.js
  var require_xmlns_namespaces = __commonJS({
    "src/constants/xmlns_namespaces.js"(exports) {
      "use strict";
      exports.xmlns = "http://www.w3.org/2000/xmlns/";
      exports.svg = "http://www.w3.org/2000/svg";
      exports.xlink = "http://www.w3.org/1999/xlink";
      exports.svgAttrs = {
        xmlns: exports.svg,
        "xmlns:xlink": exports.xlink
      };
    }
  });

  // src/constants/alignment.js
  var require_alignment = __commonJS({
    "src/constants/alignment.js"(exports, module) {
      "use strict";
      module.exports = {
        // from bottom left: this is the origin of our paper-reference
        // positioning system
        FROM_BL: {
          left: 0,
          center: 0.5,
          right: 1,
          bottom: 0,
          middle: 0.5,
          top: 1
        },
        // from top left: this is the screen pixel positioning origin
        FROM_TL: {
          left: 0,
          center: 0.5,
          right: 1,
          bottom: 1,
          middle: 0.5,
          top: 0
        },
        // from bottom right: sometimes you just need the opposite of ^^
        FROM_BR: {
          left: 1,
          center: 0.5,
          right: 0,
          bottom: 0,
          middle: 0.5,
          top: 1
        },
        // multiple of fontSize to get the vertical offset between lines
        LINE_SPACING: 1.3,
        // multiple of fontSize to shift from the baseline
        // to the cap (captical letter) line
        // (to use when we don't calculate this shift from Drawing.bBox)
        // This is an approximation since in reality cap height can differ
        // from font to font. However, according to Wikipedia
        //   an "average" font might have a cap height of 70% of the em
        // https://en.wikipedia.org/wiki/Em_(typography)#History
        CAP_SHIFT: 0.7,
        // half the cap height (distance between baseline and cap line)
        // of an "average" font (for more info see above).
        MID_SHIFT: 0.35,
        OPPOSITE_SIDE: {
          left: "right",
          right: "left",
          top: "bottom",
          bottom: "top"
        }
      };
    }
  });

  // src/lib/svg_text_utils.js
  var require_svg_text_utils = __commonJS({
    "src/lib/svg_text_utils.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var xmlnsNamespaces = require_xmlns_namespaces();
      var LINE_SPACING = require_alignment().LINE_SPACING;
      var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/;
      exports.convertToTspans = function(_context, gd, _callback) {
        var str = _context.text();
        var tex = !_context.attr("data-notex") && gd && gd._context.typesetMath && typeof MathJax !== "undefined" && str.match(FIND_TEX);
        var parent = d3.select(_context.node().parentNode);
        if (parent.empty()) return;
        var svgClass = _context.attr("class") ? _context.attr("class").split(" ")[0] : "text";
        svgClass += "-math";
        parent.selectAll("svg." + svgClass).remove();
        parent.selectAll("g." + svgClass + "-group").remove();
        _context.style("display", null).attr({
          // some callers use data-unformatted *from the <text> element* in 'cancel'
          // so we need it here even if we're going to turn it into math
          // these two (plus style and text-anchor attributes) form the key we're
          // going to use for Drawing.bBox
          "data-unformatted": str,
          "data-math": "N"
        });
        function showText() {
          if (!parent.empty()) {
            svgClass = _context.attr("class") + "-math";
            parent.select("svg." + svgClass).remove();
          }
          _context.text("").style("white-space", "pre");
          var hasLink = buildSVGText(_context.node(), str);
          if (hasLink) {
            _context.style("pointer-events", "all");
          }
          exports.positionText(_context);
          if (_callback) _callback.call(_context);
        }
        if (tex) {
          (gd && gd._promises || []).push(new Promise(function(resolve) {
            _context.style("display", "none");
            var fontSize = parseInt(_context.node().style.fontSize, 10);
            var config = { fontSize };
            texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) {
              parent.selectAll("svg." + svgClass).remove();
              parent.selectAll("g." + svgClass + "-group").remove();
              var newSvg = _svgEl && _svgEl.select("svg");
              if (!newSvg || !newSvg.node()) {
                showText();
                resolve();
                return;
              }
              var mathjaxGroup = parent.append("g").classed(svgClass + "-group", true).attr({
                "pointer-events": "none",
                "data-unformatted": str,
                "data-math": "Y"
              });
              mathjaxGroup.node().appendChild(newSvg.node());
              if (_glyphDefs && _glyphDefs.node()) {
                newSvg.node().insertBefore(
                  _glyphDefs.node().cloneNode(true),
                  newSvg.node().firstChild
                );
              }
              var w0 = _svgBBox.width;
              var h0 = _svgBBox.height;
              newSvg.attr({
                class: svgClass,
                height: h0,
                preserveAspectRatio: "xMinYMin meet"
              }).style({ overflow: "visible", "pointer-events": "none" });
              var fill = _context.node().style.fill || "black";
              var g = newSvg.select("g");
              g.attr({ fill, stroke: fill });
              var bb = g.node().getBoundingClientRect();
              var w = bb.width;
              var h = bb.height;
              if (w > w0 || h > h0) {
                newSvg.style("overflow", "hidden");
                bb = newSvg.node().getBoundingClientRect();
                w = bb.width;
                h = bb.height;
              }
              var x = +_context.attr("x");
              var y = +_context.attr("y");
              var textHeight = fontSize || _context.node().getBoundingClientRect().height;
              var dy = -textHeight / 4;
              if (svgClass[0] === "y") {
                mathjaxGroup.attr({
                  transform: "rotate(" + [-90, x, y] + ")" + strTranslate(-w / 2, dy - h / 2)
                });
              } else if (svgClass[0] === "l") {
                y = dy - h / 2;
              } else if (svgClass[0] === "a" && svgClass.indexOf("atitle") !== 0) {
                x = 0;
                y = dy;
              } else {
                var anchor = _context.attr("text-anchor");
                x = x - w * (anchor === "middle" ? 0.5 : anchor === "end" ? 1 : 0);
                y = y + dy - h / 2;
              }
              newSvg.attr({
                x,
                y
              });
              if (_callback) _callback.call(_context, mathjaxGroup);
              resolve(mathjaxGroup);
            });
          }));
        } else showText();
        return _context;
      };
      var LT_MATCH = /(<|&lt;|&#60;)/g;
      var GT_MATCH = /(>|&gt;|&#62;)/g;
      function cleanEscapesForTex(s) {
        return s.replace(LT_MATCH, "\\lt ").replace(GT_MATCH, "\\gt ");
      }
      var inlineMath = [["$", "$"], ["\\(", "\\)"]];
      function texToSVG(_texString, _config, _callback) {
        var MathJaxVersion = parseInt(
          (MathJax.version || "").split(".")[0]
        );
        if (MathJaxVersion !== 2 && MathJaxVersion !== 3) {
          Lib.warn("No MathJax version:", MathJax.version);
          return;
        }
        var originalRenderer, originalConfig, originalProcessSectionDelay, tmpDiv;
        var setConfig2 = function() {
          originalConfig = Lib.extendDeepAll({}, MathJax.Hub.config);
          originalProcessSectionDelay = MathJax.Hub.processSectionDelay;
          if (MathJax.Hub.processSectionDelay !== void 0) {
            MathJax.Hub.processSectionDelay = 0;
          }
          return MathJax.Hub.Config({
            messageStyle: "none",
            tex2jax: {
              inlineMath
            },
            displayAlign: "left"
          });
        };
        var setConfig3 = function() {
          originalConfig = Lib.extendDeepAll({}, MathJax.config);
          if (!MathJax.config.tex) {
            MathJax.config.tex = {};
          }
          MathJax.config.tex.inlineMath = inlineMath;
        };
        var setRenderer2 = function() {
          originalRenderer = MathJax.Hub.config.menuSettings.renderer;
          if (originalRenderer !== "SVG") {
            return MathJax.Hub.setRenderer("SVG");
          }
        };
        var setRenderer3 = function() {
          originalRenderer = MathJax.config.startup.output;
          if (originalRenderer !== "svg") {
            MathJax.config.startup.output = "svg";
          }
        };
        var initiateMathJax = function() {
          var randomID = "math-output-" + Lib.randstr({}, 64);
          tmpDiv = d3.select("body").append("div").attr({ id: randomID }).style({
            visibility: "hidden",
            position: "absolute",
            "font-size": _config.fontSize + "px"
          }).text(cleanEscapesForTex(_texString));
          var tmpNode = tmpDiv.node();
          return MathJaxVersion === 2 ? MathJax.Hub.Typeset(tmpNode) : MathJax.typeset([tmpNode]);
        };
        var finalizeMathJax = function() {
          var sel = tmpDiv.select(
            MathJaxVersion === 2 ? ".MathJax_SVG" : ".MathJax"
          );
          var node = !sel.empty() && tmpDiv.select("svg").node();
          if (!node) {
            Lib.log("There was an error in the tex syntax.", _texString);
            _callback();
          } else {
            var nodeBBox = node.getBoundingClientRect();
            var glyphDefs;
            if (MathJaxVersion === 2) {
              glyphDefs = d3.select("body").select("#MathJax_SVG_glyphs");
            } else {
              glyphDefs = sel.select("defs");
            }
            _callback(sel, glyphDefs, nodeBBox);
          }
          tmpDiv.remove();
        };
        var resetRenderer2 = function() {
          if (originalRenderer !== "SVG") {
            return MathJax.Hub.setRenderer(originalRenderer);
          }
        };
        var resetRenderer3 = function() {
          if (originalRenderer !== "svg") {
            MathJax.config.startup.output = originalRenderer;
          }
        };
        var resetConfig2 = function() {
          if (originalProcessSectionDelay !== void 0) {
            MathJax.Hub.processSectionDelay = originalProcessSectionDelay;
          }
          return MathJax.Hub.Config(originalConfig);
        };
        var resetConfig3 = function() {
          MathJax.config = originalConfig;
        };
        if (MathJaxVersion === 2) {
          MathJax.Hub.Queue(
            setConfig2,
            setRenderer2,
            initiateMathJax,
            finalizeMathJax,
            resetRenderer2,
            resetConfig2
          );
        } else if (MathJaxVersion === 3) {
          setConfig3();
          setRenderer3();
          MathJax.startup.defaultReady();
          MathJax.startup.promise.then(function() {
            initiateMathJax();
            finalizeMathJax();
            resetRenderer3();
            resetConfig3();
          });
        }
      }
      var TAG_STYLES = {
        // would like to use baseline-shift for sub/sup but FF doesn't support it
        // so we need to use dy along with the uber hacky shift-back-to
        // baseline below
        sup: "font-size:70%",
        sub: "font-size:70%",
        s: "text-decoration:line-through",
        u: "text-decoration:underline",
        b: "font-weight:bold",
        i: "font-style:italic",
        a: "cursor:pointer",
        span: "",
        em: "font-style:italic;font-weight:bold"
      };
      var SHIFT_DY = {
        sub: "0.3em",
        sup: "-0.6em"
      };
      var RESET_DY = {
        sub: "-0.21em",
        sup: "0.42em"
      };
      var ZERO_WIDTH_SPACE = "\u200B";
      var PROTOCOLS = ["http:", "https:", "mailto:", "", void 0, ":"];
      var NEWLINES = exports.NEWLINES = /(\r\n?|\n)/g;
      var SPLIT_TAGS = /(<[^<>]*>)/;
      var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i;
      var BR_TAG = /<br(\s+.*)?>/i;
      exports.BR_TAG_ALL = /<br(\s+.*)?>/gi;
      var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i;
      var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i;
      var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i;
      var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;
      function getQuotedMatch(_str, re) {
        if (!_str) return null;
        var match = _str.match(re);
        var result = match && (match[3] || match[4]);
        return result && convertEntities(result);
      }
      var COLORMATCH = /(^|;)\s*color:/;
      exports.plainText = function(_str, opts) {
        opts = opts || {};
        var len = opts.len !== void 0 && opts.len !== -1 ? opts.len : Infinity;
        var allowedTags = opts.allowedTags !== void 0 ? opts.allowedTags : ["br"];
        var ellipsis = "...";
        var eLen = ellipsis.length;
        var oldParts = _str.split(SPLIT_TAGS);
        var newParts = [];
        var prevTag = "";
        var l = 0;
        for (var i = 0; i < oldParts.length; i++) {
          var p = oldParts[i];
          var match = p.match(ONE_TAG);
          var tagType = match && match[2].toLowerCase();
          if (tagType) {
            if (allowedTags.indexOf(tagType) !== -1) {
              newParts.push(p);
              prevTag = tagType;
            }
          } else {
            var pLen = p.length;
            if (l + pLen < len) {
              newParts.push(p);
              l += pLen;
            } else if (l < len) {
              var pLen2 = len - l;
              if (prevTag && (prevTag !== "br" || pLen2 <= eLen || pLen <= eLen)) {
                newParts.pop();
              }
              if (len > eLen) {
                newParts.push(p.slice(0, Math.max(0, pLen2 - eLen)) + ellipsis);
              } else {
                newParts.push(p.slice(0, pLen2));
              }
              break;
            }
            prevTag = "";
          }
        }
        return newParts.join("");
      };
      var entityToUnicode = {
        mu: "\u03BC",
        amp: "&",
        lt: "<",
        gt: ">",
        nbsp: "\xA0",
        times: "\xD7",
        plusmn: "\xB1",
        deg: "\xB0"
      };
      var ENTITY_MATCH = /&(#\d+|#x[\da-fA-F]+|[a-z]+);/g;
      function convertEntities(_str) {
        return _str.replace(ENTITY_MATCH, function(fullMatch, innerMatch) {
          var outChar;
          if (innerMatch.charAt(0) === "#") {
            outChar = fromCodePoint(
              innerMatch.charAt(1) === "x" ? parseInt(innerMatch.slice(2), 16) : parseInt(innerMatch.slice(1), 10)
            );
          } else outChar = entityToUnicode[innerMatch];
          return outChar || fullMatch;
        });
      }
      exports.convertEntities = convertEntities;
      function fromCodePoint(code) {
        if (code > 1114111) return;
        var stringFromCodePoint = String.fromCodePoint;
        if (stringFromCodePoint) return stringFromCodePoint(code);
        var stringFromCharCode = String.fromCharCode;
        if (code <= 65535) return stringFromCharCode(code);
        return stringFromCharCode(
          (code >> 10) + 55232,
          code % 1024 + 56320
        );
      }
      function buildSVGText(containerNode, str) {
        str = str.replace(NEWLINES, " ");
        var hasLink = false;
        var nodeStack = [];
        var currentNode;
        var currentLine = -1;
        function newLine() {
          currentLine++;
          var lineNode = document.createElementNS(xmlnsNamespaces.svg, "tspan");
          d3.select(lineNode).attr({
            class: "line",
            dy: currentLine * LINE_SPACING + "em"
          });
          containerNode.appendChild(lineNode);
          currentNode = lineNode;
          var oldNodeStack = nodeStack;
          nodeStack = [{ node: lineNode }];
          if (oldNodeStack.length > 1) {
            for (var i2 = 1; i2 < oldNodeStack.length; i2++) {
              enterNode(oldNodeStack[i2]);
            }
          }
        }
        function enterNode(nodeSpec2) {
          var type = nodeSpec2.type;
          var nodeAttrs = {};
          var nodeType;
          if (type === "a") {
            nodeType = "a";
            var target = nodeSpec2.target;
            var href2 = nodeSpec2.href;
            var popup = nodeSpec2.popup;
            if (href2) {
              nodeAttrs = {
                "xlink:xlink:show": target === "_blank" || target.charAt(0) !== "_" ? "new" : "replace",
                target,
                "xlink:xlink:href": href2
              };
              if (popup) {
                nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' + popup + '");return false;';
              }
            }
          } else nodeType = "tspan";
          if (nodeSpec2.style) nodeAttrs.style = nodeSpec2.style;
          var newNode = document.createElementNS(xmlnsNamespaces.svg, nodeType);
          if (type === "sup" || type === "sub") {
            addTextNode(currentNode, ZERO_WIDTH_SPACE);
            currentNode.appendChild(newNode);
            var resetter = document.createElementNS(xmlnsNamespaces.svg, "tspan");
            addTextNode(resetter, ZERO_WIDTH_SPACE);
            d3.select(resetter).attr("dy", RESET_DY[type]);
            nodeAttrs.dy = SHIFT_DY[type];
            currentNode.appendChild(newNode);
            currentNode.appendChild(resetter);
          } else {
            currentNode.appendChild(newNode);
          }
          d3.select(newNode).attr(nodeAttrs);
          currentNode = nodeSpec2.node = newNode;
          nodeStack.push(nodeSpec2);
        }
        function addTextNode(node, text) {
          node.appendChild(document.createTextNode(text));
        }
        function exitNode(type) {
          if (nodeStack.length === 1) {
            Lib.log("Ignoring unexpected end tag </" + type + ">.", str);
            return;
          }
          var innerNode = nodeStack.pop();
          if (type !== innerNode.type) {
            Lib.log("Start tag <" + innerNode.type + "> doesnt match end tag <" + type + ">. Pretending it did match.", str);
          }
          currentNode = nodeStack[nodeStack.length - 1].node;
        }
        var hasLines = BR_TAG.test(str);
        if (hasLines) newLine();
        else {
          currentNode = containerNode;
          nodeStack = [{ node: containerNode }];
        }
        var parts = str.split(SPLIT_TAGS);
        for (var i = 0; i < parts.length; i++) {
          var parti = parts[i];
          var match = parti.match(ONE_TAG);
          var tagType = match && match[2].toLowerCase();
          var tagStyle = TAG_STYLES[tagType];
          if (tagType === "br") {
            newLine();
          } else if (tagStyle === void 0) {
            addTextNode(currentNode, convertEntities(parti));
          } else {
            if (match[1]) {
              exitNode(tagType);
            } else {
              var extra = match[4];
              var nodeSpec = { type: tagType };
              var css = getQuotedMatch(extra, STYLEMATCH);
              if (css) {
                css = css.replace(COLORMATCH, "$1 fill:");
                if (tagStyle) css += ";" + tagStyle;
              } else if (tagStyle) css = tagStyle;
              if (css) nodeSpec.style = css;
              if (tagType === "a") {
                hasLink = true;
                var href = getQuotedMatch(extra, HREFMATCH);
                if (href) {
                  var safeHref = sanitizeHref(href);
                  if (safeHref) {
                    nodeSpec.href = safeHref;
                    nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || "_blank";
                    nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH);
                  }
                }
              }
              enterNode(nodeSpec);
            }
          }
        }
        return hasLink;
      }
      function sanitizeHref(href) {
        var decodedHref = encodeURI(decodeURI(href));
        var dummyAnchor1 = document.createElement("a");
        var dummyAnchor2 = document.createElement("a");
        dummyAnchor1.href = href;
        dummyAnchor2.href = decodedHref;
        var p1 = dummyAnchor1.protocol;
        var p2 = dummyAnchor2.protocol;
        if (PROTOCOLS.indexOf(p1) !== -1 && PROTOCOLS.indexOf(p2) !== -1) {
          return decodedHref;
        } else {
          return "";
        }
      }
      exports.sanitizeHTML = function sanitizeHTML(str) {
        str = str.replace(NEWLINES, " ");
        var rootNode = document.createElement("p");
        var currentNode = rootNode;
        var nodeStack = [];
        var parts = str.split(SPLIT_TAGS);
        for (var i = 0; i < parts.length; i++) {
          var parti = parts[i];
          var match = parti.match(ONE_TAG);
          var tagType = match && match[2].toLowerCase();
          if (tagType in TAG_STYLES) {
            if (match[1]) {
              if (nodeStack.length) {
                currentNode = nodeStack.pop();
              }
            } else {
              var extra = match[4];
              var css = getQuotedMatch(extra, STYLEMATCH);
              var nodeAttrs = css ? { style: css } : {};
              if (tagType === "a") {
                var href = getQuotedMatch(extra, HREFMATCH);
                if (href) {
                  var safeHref = sanitizeHref(href);
                  if (safeHref) {
                    nodeAttrs.href = safeHref;
                    var target = getQuotedMatch(extra, TARGETMATCH);
                    if (target) {
                      nodeAttrs.target = target;
                    }
                  }
                }
              }
              var newNode = document.createElement(tagType);
              currentNode.appendChild(newNode);
              d3.select(newNode).attr(nodeAttrs);
              currentNode = newNode;
              nodeStack.push(newNode);
            }
          } else {
            currentNode.appendChild(
              document.createTextNode(convertEntities(parti))
            );
          }
        }
        var key = "innerHTML";
        return rootNode[key];
      };
      exports.lineCount = function lineCount(s) {
        return s.selectAll("tspan.line").size() || 1;
      };
      exports.positionText = function positionText(s, x, y) {
        return s.each(function() {
          var text = d3.select(this);
          function setOrGet(attr, val) {
            if (val === void 0) {
              val = text.attr(attr);
              if (val === null) {
                text.attr(attr, 0);
                val = 0;
              }
            } else text.attr(attr, val);
            return val;
          }
          var thisX = setOrGet("x", x);
          var thisY = setOrGet("y", y);
          if (this.nodeName === "text") {
            text.selectAll("tspan.line").attr({ x: thisX, y: thisY });
          }
        });
      };
      function alignHTMLWith(_base, container, options) {
        var alignH = options.horizontalAlign;
        var alignV = options.verticalAlign || "top";
        var bRect = _base.node().getBoundingClientRect();
        var cRect = container.node().getBoundingClientRect();
        var thisRect;
        var getTop;
        var getLeft;
        if (alignV === "bottom") {
          getTop = function() {
            return bRect.bottom - thisRect.height;
          };
        } else if (alignV === "middle") {
          getTop = function() {
            return bRect.top + (bRect.height - thisRect.height) / 2;
          };
        } else {
          getTop = function() {
            return bRect.top;
          };
        }
        if (alignH === "right") {
          getLeft = function() {
            return bRect.right - thisRect.width;
          };
        } else if (alignH === "center") {
          getLeft = function() {
            return bRect.left + (bRect.width - thisRect.width) / 2;
          };
        } else {
          getLeft = function() {
            return bRect.left;
          };
        }
        return function() {
          thisRect = this.node().getBoundingClientRect();
          var x0 = getLeft() - cRect.left;
          var y0 = getTop() - cRect.top;
          var gd = options.gd || {};
          if (options.gd) {
            gd._fullLayout._calcInverseTransform(gd);
            var transformedCoords = Lib.apply3DTransform(gd._fullLayout._invTransform)(x0, y0);
            x0 = transformedCoords[0];
            y0 = transformedCoords[1];
          }
          this.style({
            top: y0 + "px",
            left: x0 + "px",
            "z-index": 1e3
          });
          return this;
        };
      }
      var onePx = "1px ";
      exports.makeTextShadow = function(color2) {
        var x = onePx;
        var y = onePx;
        var b = onePx;
        return x + y + b + color2 + ", -" + x + "-" + y + b + color2 + ", " + x + "-" + y + b + color2 + ", -" + x + y + b + color2;
      };
      exports.makeEditable = function(context, options) {
        var gd = options.gd;
        var _delegate = options.delegate;
        var dispatch = d3.dispatch("edit", "input", "cancel");
        var handlerElement = _delegate || context;
        context.style({ "pointer-events": _delegate ? "none" : "all" });
        if (context.size() !== 1) throw new Error("boo");
        function handleClick() {
          appendEditable();
          context.style({ opacity: 0 });
          var svgClass = handlerElement.attr("class");
          var mathjaxClass;
          if (svgClass) mathjaxClass = "." + svgClass.split(" ")[0] + "-math-group";
          else mathjaxClass = "[class*=-math-group]";
          if (mathjaxClass) {
            d3.select(context.node().parentNode).select(mathjaxClass).style({ opacity: 0 });
          }
        }
        function selectElementContents(_el) {
          var el = _el.node();
          var range = document.createRange();
          range.selectNodeContents(el);
          var sel = window.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
          el.focus();
        }
        function appendEditable() {
          var plotDiv = d3.select(gd);
          var container = plotDiv.select(".svg-container");
          var div = container.append("div");
          var cStyle = context.node().style;
          var fontSize = parseFloat(cStyle.fontSize || 12);
          var initialText = options.text;
          if (initialText === void 0) initialText = context.attr("data-unformatted");
          div.classed("plugin-editable editable", true).style({
            position: "absolute",
            "font-family": cStyle.fontFamily || "Arial",
            "font-size": fontSize,
            color: options.fill || cStyle.fill || "black",
            opacity: 1,
            "background-color": options.background || "transparent",
            outline: "#ffffff33 1px solid",
            margin: [-fontSize / 8 + 1, 0, 0, -1].join("px ") + "px",
            padding: "0",
            "box-sizing": "border-box"
          }).attr({ contenteditable: true }).text(initialText).call(alignHTMLWith(context, container, options)).on("blur", function() {
            gd._editing = false;
            context.text(this.textContent).style({ opacity: 1 });
            var svgClass = d3.select(this).attr("class");
            var mathjaxClass;
            if (svgClass) mathjaxClass = "." + svgClass.split(" ")[0] + "-math-group";
            else mathjaxClass = "[class*=-math-group]";
            if (mathjaxClass) {
              d3.select(context.node().parentNode).select(mathjaxClass).style({ opacity: 0 });
            }
            var text = this.textContent;
            d3.select(this).transition().duration(0).remove();
            d3.select(document).on("mouseup", null);
            dispatch.edit.call(context, text);
          }).on("focus", function() {
            var editDiv = this;
            gd._editing = true;
            d3.select(document).on("mouseup", function() {
              if (d3.event.target === editDiv) return false;
              if (document.activeElement === div.node()) div.node().blur();
            });
          }).on("keyup", function() {
            if (d3.event.which === 27) {
              gd._editing = false;
              context.style({ opacity: 1 });
              d3.select(this).style({ opacity: 0 }).on("blur", function() {
                return false;
              }).transition().remove();
              dispatch.cancel.call(context, this.textContent);
            } else {
              dispatch.input.call(context, this.textContent);
              d3.select(this).call(alignHTMLWith(context, container, options));
            }
          }).on("keydown", function() {
            if (d3.event.which === 13) this.blur();
          }).call(selectElementContents);
        }
        if (options.immediate) handleClick();
        else handlerElement.on("click", handleClick);
        return d3.rebind(context, dispatch, "on");
      };
    }
  });

  // src/components/colorscale/helpers.js
  var require_helpers = __commonJS({
    "src/components/colorscale/helpers.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var tinycolor = require_tinycolor();
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Color2 = require_color();
      var isValidScale = require_scales().isValid;
      function hasColorscale(trace, containerStr, colorKey) {
        var container = containerStr ? Lib.nestedProperty(trace, containerStr).get() || {} : trace;
        var color2 = container[colorKey || "color"];
        if (color2 && color2._inputArray) color2 = color2._inputArray;
        var isArrayWithOneNumber = false;
        if (Lib.isArrayOrTypedArray(color2)) {
          for (var i = 0; i < color2.length; i++) {
            if (isNumeric(color2[i])) {
              isArrayWithOneNumber = true;
              break;
            }
          }
        }
        return Lib.isPlainObject(container) && (isArrayWithOneNumber || container.showscale === true || isNumeric(container.cmin) && isNumeric(container.cmax) || isValidScale(container.colorscale) || Lib.isPlainObject(container.colorbar));
      }
      var constantAttrs = ["showscale", "autocolorscale", "colorscale", "reversescale", "colorbar"];
      var letterAttrs = ["min", "max", "mid", "auto"];
      function extractOpts(cont) {
        var colorAx = cont._colorAx;
        var cont2 = colorAx ? colorAx : cont;
        var out = {};
        var cLetter;
        var i, k;
        for (i = 0; i < constantAttrs.length; i++) {
          k = constantAttrs[i];
          out[k] = cont2[k];
        }
        if (colorAx) {
          cLetter = "c";
          for (i = 0; i < letterAttrs.length; i++) {
            k = letterAttrs[i];
            out[k] = cont2["c" + k];
          }
        } else {
          var k2;
          for (i = 0; i < letterAttrs.length; i++) {
            k = letterAttrs[i];
            k2 = "c" + k;
            if (k2 in cont2) {
              out[k] = cont2[k2];
              continue;
            }
            k2 = "z" + k;
            if (k2 in cont2) {
              out[k] = cont2[k2];
            }
          }
          cLetter = k2.charAt(0);
        }
        out._sync = function(k3, v) {
          var k22 = letterAttrs.indexOf(k3) !== -1 ? cLetter + k3 : k3;
          cont2[k22] = cont2["_" + k22] = v;
        };
        return out;
      }
      function extractScale(cont) {
        var cOpts = extractOpts(cont);
        var cmin = cOpts.min;
        var cmax = cOpts.max;
        var scl = cOpts.reversescale ? flipScale(cOpts.colorscale) : cOpts.colorscale;
        var N = scl.length;
        var domain = new Array(N);
        var range = new Array(N);
        for (var i = 0; i < N; i++) {
          var si = scl[i];
          domain[i] = cmin + si[0] * (cmax - cmin);
          range[i] = si[1];
        }
        return { domain, range };
      }
      function flipScale(scl) {
        var N = scl.length;
        var sclNew = new Array(N);
        for (var i = N - 1, j = 0; i >= 0; i--, j++) {
          var si = scl[i];
          sclNew[j] = [1 - si[0], si[1]];
        }
        return sclNew;
      }
      function makeColorScaleFunc(specs, opts) {
        opts = opts || {};
        var domain = specs.domain;
        var range = specs.range;
        var N = range.length;
        var _range = new Array(N);
        for (var i = 0; i < N; i++) {
          var rgba3 = tinycolor(range[i]).toRgb();
          _range[i] = [rgba3.r, rgba3.g, rgba3.b, rgba3.a];
        }
        var _sclFunc = d3.scale.linear().domain(domain).range(_range).clamp(true);
        var noNumericCheck = opts.noNumericCheck;
        var returnArray = opts.returnArray;
        var sclFunc;
        if (noNumericCheck && returnArray) {
          sclFunc = _sclFunc;
        } else if (noNumericCheck) {
          sclFunc = function(v) {
            return colorArray2rbga(_sclFunc(v));
          };
        } else if (returnArray) {
          sclFunc = function(v) {
            if (isNumeric(v)) return _sclFunc(v);
            else if (tinycolor(v).isValid()) return v;
            else return Color2.defaultLine;
          };
        } else {
          sclFunc = function(v) {
            if (isNumeric(v)) return colorArray2rbga(_sclFunc(v));
            else if (tinycolor(v).isValid()) return v;
            else return Color2.defaultLine;
          };
        }
        sclFunc.domain = _sclFunc.domain;
        sclFunc.range = function() {
          return range;
        };
        return sclFunc;
      }
      function makeColorScaleFuncFromTrace(trace, opts) {
        return makeColorScaleFunc(extractScale(trace), opts);
      }
      function colorArray2rbga(colorArray) {
        var colorObj = {
          r: colorArray[0],
          g: colorArray[1],
          b: colorArray[2],
          a: colorArray[3]
        };
        return tinycolor(colorObj).toRgbString();
      }
      module.exports = {
        hasColorscale,
        extractOpts,
        extractScale,
        flipScale,
        makeColorScaleFunc,
        makeColorScaleFuncFromTrace
      };
    }
  });

  // src/plots/cartesian/axis_format_attributes.js
  var require_axis_format_attributes = __commonJS({
    "src/plots/cartesian/axis_format_attributes.js"(exports, module) {
      "use strict";
      var docs = require_docs();
      var FORMAT_LINK = docs.FORMAT_LINK;
      var DATE_FORMAT_LINK = docs.DATE_FORMAT_LINK;
      function axisHoverFormat(x, noDates) {
        return {
          valType: "string",
          dflt: "",
          editType: "none",
          description: (noDates ? descriptionOnlyNumbers : descriptionWithDates)("hover text", x) + [
            "By default the values are formatted using " + (noDates ? "generic number format" : "`" + x + "axis.hoverformat`") + "."
          ].join(" ")
        };
      }
      function descriptionOnlyNumbers(label, x) {
        return [
          "Sets the " + label + " formatting rule" + (x ? "for `" + x + "` " : ""),
          "using d3 formatting mini-languages",
          "which are very similar to those in Python. For numbers, see: " + FORMAT_LINK + "."
        ].join(" ");
      }
      function descriptionWithDates(label, x) {
        return descriptionOnlyNumbers(label, x) + [
          " And for dates see: " + DATE_FORMAT_LINK + ".",
          "We add two items to d3's date formatter:",
          "*%h* for half of the year as a decimal number as well as",
          "*%{n}f* for fractional seconds",
          "with n digits. For example, *2016-10-13 09:15:23.456* with tickformat",
          "*%H~%M~%S.%2f* would display *09~15~23.46*"
        ].join(" ");
      }
      module.exports = {
        axisHoverFormat,
        descriptionOnlyNumbers,
        descriptionWithDates
      };
    }
  });

  // src/plots/cartesian/layout_attributes.js
  var require_layout_attributes4 = __commonJS({
    "src/plots/cartesian/layout_attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var colorAttrs = require_attributes3();
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      var templatedArray = require_plot_template().templatedArray;
      var templateFormatStringDescription = require_template_attributes().templateFormatStringDescription;
      var descriptionWithDates = require_axis_format_attributes().descriptionWithDates;
      var ONEDAY = require_numerical().ONEDAY;
      var constants = require_constants2();
      var HOUR = constants.HOUR_PATTERN;
      var DAY_OF_WEEK = constants.WEEKDAY_PATTERN;
      var minorTickmode = {
        valType: "enumerated",
        values: ["auto", "linear", "array"],
        editType: "ticks",
        impliedEdits: { tick0: void 0, dtick: void 0 }
      };
      var tickmode = extendFlat({}, minorTickmode, {
        values: minorTickmode.values.slice().concat(["sync"])
      });
      function makeNticks(minor) {
        return {
          valType: "integer",
          min: 0,
          dflt: minor ? 5 : 0,
          editType: "ticks"
        };
      }
      var tick0 = {
        valType: "any",
        editType: "ticks",
        impliedEdits: { tickmode: "linear" }
      };
      var dtick = {
        valType: "any",
        editType: "ticks",
        impliedEdits: { tickmode: "linear" }
      };
      var tickvals = {
        valType: "data_array",
        editType: "ticks"
      };
      var ticks = {
        valType: "enumerated",
        values: ["outside", "inside", ""],
        editType: "ticks"
      };
      function makeTicklen(minor) {
        var obj = {
          valType: "number",
          min: 0,
          editType: "ticks"
        };
        if (!minor) obj.dflt = 5;
        return obj;
      }
      function makeTickwidth(minor) {
        var obj = {
          valType: "number",
          min: 0,
          editType: "ticks"
        };
        if (!minor) obj.dflt = 1;
        return obj;
      }
      var tickcolor = {
        valType: "color",
        dflt: colorAttrs.defaultLine,
        editType: "ticks"
      };
      var gridcolor = {
        valType: "color",
        dflt: colorAttrs.lightLine,
        editType: "ticks"
      };
      function makeGridwidth(minor) {
        var obj = {
          valType: "number",
          min: 0,
          editType: "ticks"
        };
        if (!minor) obj.dflt = 1;
        return obj;
      }
      var griddash = extendFlat({}, dash, { editType: "ticks" });
      var showgrid = {
        valType: "boolean",
        editType: "ticks"
      };
      module.exports = {
        visible: {
          valType: "boolean",
          editType: "plot"
        },
        color: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "ticks"
        },
        title: {
          text: {
            valType: "string",
            editType: "ticks"
          },
          font: fontAttrs({
            editType: "ticks"
          }),
          standoff: {
            valType: "number",
            min: 0,
            editType: "ticks"
          },
          editType: "ticks"
        },
        type: {
          valType: "enumerated",
          // '-' means we haven't yet run autotype or couldn't find any data
          // it gets turned into linear in gd._fullLayout but not copied back
          // to gd.data like the others are.
          values: ["-", "linear", "log", "date", "category", "multicategory"],
          dflt: "-",
          editType: "calc",
          // we forget when an axis has been autotyped, just writing the auto
          // value back to the input - so it doesn't make sense to template this.
          // Note: we do NOT prohibit this in `coerce`, so if someone enters a
          // type in the template explicitly it will be honored as the default.
          _noTemplating: true
        },
        autotypenumbers: {
          valType: "enumerated",
          values: ["convert types", "strict"],
          dflt: "convert types",
          editType: "calc"
        },
        autorange: {
          valType: "enumerated",
          values: [true, false, "reversed", "min reversed", "max reversed", "min", "max"],
          dflt: true,
          editType: "axrange",
          impliedEdits: { "range[0]": void 0, "range[1]": void 0 }
        },
        autorangeoptions: {
          minallowed: {
            valType: "any",
            editType: "plot",
            impliedEdits: { "range[0]": void 0, "range[1]": void 0 }
          },
          maxallowed: {
            valType: "any",
            editType: "plot",
            impliedEdits: { "range[0]": void 0, "range[1]": void 0 }
          },
          clipmin: {
            valType: "any",
            editType: "plot",
            impliedEdits: { "range[0]": void 0, "range[1]": void 0 }
          },
          clipmax: {
            valType: "any",
            editType: "plot",
            impliedEdits: { "range[0]": void 0, "range[1]": void 0 }
          },
          include: {
            valType: "any",
            arrayOk: true,
            editType: "plot",
            impliedEdits: { "range[0]": void 0, "range[1]": void 0 }
          },
          editType: "plot"
        },
        rangemode: {
          valType: "enumerated",
          values: ["normal", "tozero", "nonnegative"],
          dflt: "normal",
          editType: "plot"
        },
        range: {
          valType: "info_array",
          items: [
            { valType: "any", editType: "axrange", impliedEdits: { "^autorange": false }, anim: true },
            { valType: "any", editType: "axrange", impliedEdits: { "^autorange": false }, anim: true }
          ],
          editType: "axrange",
          impliedEdits: { autorange: false },
          anim: true
        },
        minallowed: {
          valType: "any",
          editType: "plot",
          impliedEdits: { "^autorange": false }
        },
        maxallowed: {
          valType: "any",
          editType: "plot",
          impliedEdits: { "^autorange": false }
        },
        fixedrange: {
          valType: "boolean",
          dflt: false,
          editType: "calc"
        },
        modebardisable: {
          valType: "flaglist",
          flags: ["autoscale", "zoominout"],
          extras: ["none"],
          dflt: "none",
          editType: "modebar"
        },
        insiderange: {
          valType: "info_array",
          items: [
            { valType: "any", editType: "plot" },
            { valType: "any", editType: "plot" }
          ],
          editType: "plot"
        },
        // scaleanchor: not used directly, just put here for reference
        // values are any opposite-letter axis id, or `false`.
        scaleanchor: {
          valType: "enumerated",
          values: [
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString(),
            false
          ],
          editType: "plot"
        },
        scaleratio: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "plot"
        },
        constrain: {
          valType: "enumerated",
          values: ["range", "domain"],
          editType: "plot"
        },
        // constraintoward: not used directly, just put here for reference
        constraintoward: {
          valType: "enumerated",
          values: ["left", "center", "right", "top", "middle", "bottom"],
          editType: "plot"
        },
        matches: {
          valType: "enumerated",
          values: [
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
          ],
          editType: "calc"
        },
        rangebreaks: templatedArray("rangebreak", {
          enabled: {
            valType: "boolean",
            dflt: true,
            editType: "calc"
          },
          bounds: {
            valType: "info_array",
            items: [
              { valType: "any", editType: "calc" },
              { valType: "any", editType: "calc" }
            ],
            editType: "calc"
          },
          pattern: {
            valType: "enumerated",
            values: [DAY_OF_WEEK, HOUR, ""],
            editType: "calc"
          },
          values: {
            valType: "info_array",
            freeLength: true,
            editType: "calc",
            items: {
              valType: "any",
              editType: "calc"
            }
          },
          dvalue: {
            // TODO could become 'any' to add support for 'months', 'years'
            valType: "number",
            editType: "calc",
            min: 0,
            dflt: ONEDAY
          },
          /*
          gap: {
              valType: 'number',
              min: 0,
              dflt: 0, // for *date* axes, maybe something else for *linear*
              editType: 'calc',
          },
          gapmode: {
              valType: 'enumerated',
              values: ['pixels', 'fraction'],
              dflt: 'pixels',
              editType: 'calc',
          },
          */
          // To complete https://github.com/plotly/plotly.js/issues/4210
          // we additionally need `gap` and make this work on *linear*, and
          // possibly all other cartesian axis types. We possibly would also need
          // some style attributes controlling the zig-zag on the corresponding
          // axis.
          editType: "calc"
        }),
        // ticks
        tickmode,
        nticks: makeNticks(),
        tick0,
        dtick,
        ticklabelstep: {
          valType: "integer",
          min: 1,
          dflt: 1,
          editType: "ticks"
        },
        tickvals,
        ticktext: {
          valType: "data_array",
          editType: "ticks"
        },
        ticks,
        tickson: {
          valType: "enumerated",
          values: ["labels", "boundaries"],
          dflt: "labels",
          editType: "ticks"
        },
        ticklabelmode: {
          valType: "enumerated",
          values: ["instant", "period"],
          dflt: "instant",
          editType: "ticks"
        },
        // ticklabelposition: not used directly, as values depend on direction (similar to side)
        // left/right options are for x axes, and top/bottom options are for y axes
        ticklabelposition: {
          valType: "enumerated",
          values: [
            "outside",
            "inside",
            "outside top",
            "inside top",
            "outside left",
            "inside left",
            "outside right",
            "inside right",
            "outside bottom",
            "inside bottom"
          ],
          dflt: "outside",
          editType: "calc"
        },
        ticklabeloverflow: {
          valType: "enumerated",
          values: [
            "allow",
            "hide past div",
            "hide past domain"
          ],
          editType: "calc"
        },
        ticklabelshift: {
          valType: "integer",
          dflt: 0,
          editType: "ticks"
        },
        ticklabelstandoff: {
          valType: "integer",
          dflt: 0,
          editType: "ticks"
        },
        ticklabelindex: {
          // in the future maybe add `extras: ['all', 'minor']` to allow showing labels for all ticks
          // or for all minor ticks.
          valType: "integer",
          arrayOk: true,
          editType: "calc"
        },
        mirror: {
          valType: "enumerated",
          values: [true, "ticks", false, "all", "allticks"],
          dflt: false,
          editType: "ticks+layoutstyle"
        },
        ticklen: makeTicklen(),
        tickwidth: makeTickwidth(),
        tickcolor,
        showticklabels: {
          valType: "boolean",
          dflt: true,
          editType: "ticks"
        },
        labelalias: {
          valType: "any",
          dflt: false,
          editType: "ticks"
        },
        automargin: {
          valType: "flaglist",
          flags: ["height", "width", "left", "right", "top", "bottom"],
          extras: [true, false],
          dflt: false,
          editType: "ticks"
        },
        showspikes: {
          valType: "boolean",
          dflt: false,
          editType: "modebar"
        },
        spikecolor: {
          valType: "color",
          dflt: null,
          editType: "none"
        },
        spikethickness: {
          valType: "number",
          dflt: 3,
          editType: "none"
        },
        spikedash: extendFlat({}, dash, { dflt: "dash", editType: "none" }),
        spikemode: {
          valType: "flaglist",
          flags: ["toaxis", "across", "marker"],
          dflt: "toaxis",
          editType: "none"
        },
        spikesnap: {
          valType: "enumerated",
          values: ["data", "cursor", "hovered data"],
          dflt: "hovered data",
          editType: "none"
        },
        tickfont: fontAttrs({
          editType: "ticks"
        }),
        tickangle: {
          valType: "angle",
          dflt: "auto",
          editType: "ticks"
        },
        autotickangles: {
          valType: "info_array",
          freeLength: true,
          items: {
            valType: "angle"
          },
          dflt: [0, 30, 90],
          editType: "ticks"
        },
        tickprefix: {
          valType: "string",
          dflt: "",
          editType: "ticks"
        },
        showtickprefix: {
          valType: "enumerated",
          values: ["all", "first", "last", "none"],
          dflt: "all",
          editType: "ticks"
        },
        ticksuffix: {
          valType: "string",
          dflt: "",
          editType: "ticks"
        },
        showticksuffix: {
          valType: "enumerated",
          values: ["all", "first", "last", "none"],
          dflt: "all",
          editType: "ticks"
        },
        showexponent: {
          valType: "enumerated",
          values: ["all", "first", "last", "none"],
          dflt: "all",
          editType: "ticks"
        },
        exponentformat: {
          valType: "enumerated",
          values: ["none", "e", "E", "power", "SI", "B", "SI extended"],
          dflt: "B",
          editType: "ticks"
        },
        minexponent: {
          valType: "number",
          dflt: 3,
          min: 0,
          editType: "ticks"
        },
        separatethousands: {
          valType: "boolean",
          dflt: false,
          editType: "ticks"
        },
        tickformat: {
          valType: "string",
          dflt: "",
          editType: "ticks",
          description: descriptionWithDates("tick label")
        },
        tickformatstops: templatedArray("tickformatstop", {
          enabled: {
            valType: "boolean",
            dflt: true,
            editType: "ticks"
          },
          dtickrange: {
            valType: "info_array",
            items: [
              { valType: "any", editType: "ticks" },
              { valType: "any", editType: "ticks" }
            ],
            editType: "ticks"
          },
          value: {
            valType: "string",
            dflt: "",
            editType: "ticks"
          },
          editType: "ticks"
        }),
        hoverformat: {
          valType: "string",
          dflt: "",
          editType: "none",
          description: descriptionWithDates("hover text")
        },
        unifiedhovertitle: {
          text: {
            valType: "string",
            dflt: "",
            editType: "none"
          },
          editType: "none"
        },
        // lines and grids
        showline: {
          valType: "boolean",
          dflt: false,
          editType: "ticks+layoutstyle"
        },
        linecolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "layoutstyle"
        },
        linewidth: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "ticks+layoutstyle"
        },
        showgrid,
        gridcolor,
        gridwidth: makeGridwidth(),
        griddash,
        zeroline: {
          valType: "boolean",
          editType: "ticks"
        },
        zerolinecolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "ticks"
        },
        zerolinelayer: {
          valType: "enumerated",
          values: ["above traces", "below traces"],
          dflt: "below traces",
          editType: "plot"
        },
        zerolinewidth: {
          valType: "number",
          dflt: 1,
          editType: "ticks"
        },
        showdividers: {
          valType: "boolean",
          dflt: true,
          editType: "ticks"
        },
        dividercolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "ticks"
        },
        dividerwidth: {
          valType: "number",
          dflt: 1,
          editType: "ticks"
        },
        // TODO dividerlen: that would override "to label base" length?
        // positioning attributes
        // anchor: not used directly, just put here for reference
        // values are any opposite-letter axis id
        anchor: {
          valType: "enumerated",
          values: [
            "free",
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
          ],
          editType: "plot"
        },
        // side: not used directly, as values depend on direction
        // values are top, bottom for x axes, and left, right for y
        side: {
          valType: "enumerated",
          values: ["top", "bottom", "left", "right"],
          editType: "plot"
        },
        // overlaying: not used directly, just put here for reference
        // values are false and any other same-letter axis id that's not
        // itself overlaying anything
        overlaying: {
          valType: "enumerated",
          values: [
            "free",
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
          ],
          editType: "plot"
        },
        minor: {
          tickmode: minorTickmode,
          nticks: makeNticks("minor"),
          tick0,
          dtick,
          tickvals,
          ticks,
          ticklen: makeTicklen("minor"),
          tickwidth: makeTickwidth("minor"),
          tickcolor,
          gridcolor,
          gridwidth: makeGridwidth("minor"),
          griddash,
          showgrid,
          editType: "ticks"
        },
        minorloglabels: {
          valType: "enumerated",
          values: ["small digits", "complete", "none"],
          dflt: "small digits",
          editType: "calc"
        },
        layer: {
          valType: "enumerated",
          values: ["above traces", "below traces"],
          dflt: "above traces",
          editType: "plot"
        },
        domain: {
          valType: "info_array",
          items: [
            { valType: "number", min: 0, max: 1, editType: "plot" },
            { valType: "number", min: 0, max: 1, editType: "plot" }
          ],
          dflt: [0, 1],
          editType: "plot"
        },
        position: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0,
          editType: "plot"
        },
        autoshift: {
          valType: "boolean",
          dflt: false,
          editType: "plot"
        },
        shift: {
          valType: "number",
          editType: "plot"
        },
        categoryorder: {
          valType: "enumerated",
          values: [
            "trace",
            "category ascending",
            "category descending",
            "array",
            "total ascending",
            "total descending",
            "min ascending",
            "min descending",
            "max ascending",
            "max descending",
            "sum ascending",
            "sum descending",
            "mean ascending",
            "mean descending",
            "geometric mean ascending",
            "geometric mean descending",
            "median ascending",
            "median descending"
          ],
          dflt: "trace",
          editType: "calc"
        },
        categoryarray: {
          valType: "data_array",
          editType: "calc"
        },
        uirevision: {
          valType: "any",
          editType: "none"
        },
        editType: "calc"
      };
    }
  });

  // src/components/colorbar/attributes.js
  var require_attributes7 = __commonJS({
    "src/components/colorbar/attributes.js"(exports, module) {
      "use strict";
      var axesAttrs = require_layout_attributes4();
      var fontAttrs = require_font_attributes();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      module.exports = overrideAll({
        orientation: {
          valType: "enumerated",
          values: ["h", "v"],
          dflt: "v"
        },
        thicknessmode: {
          valType: "enumerated",
          values: ["fraction", "pixels"],
          dflt: "pixels"
        },
        thickness: {
          valType: "number",
          min: 0,
          dflt: 30
        },
        lenmode: {
          valType: "enumerated",
          values: ["fraction", "pixels"],
          dflt: "fraction"
        },
        len: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        x: {
          valType: "number"
        },
        xref: {
          valType: "enumerated",
          dflt: "paper",
          values: ["container", "paper"],
          editType: "layoutstyle"
        },
        xanchor: {
          valType: "enumerated",
          values: ["left", "center", "right"]
        },
        xpad: {
          valType: "number",
          min: 0,
          dflt: 10
        },
        y: {
          valType: "number"
        },
        yref: {
          valType: "enumerated",
          dflt: "paper",
          values: ["container", "paper"],
          editType: "layoutstyle"
        },
        yanchor: {
          valType: "enumerated",
          values: ["top", "middle", "bottom"]
        },
        ypad: {
          valType: "number",
          min: 0,
          dflt: 10
        },
        // a possible line around the bar itself
        outlinecolor: axesAttrs.linecolor,
        outlinewidth: axesAttrs.linewidth,
        // Should outlinewidth have {dflt: 0} ?
        // another possible line outside the padding and tick labels
        bordercolor: axesAttrs.linecolor,
        borderwidth: {
          valType: "number",
          min: 0,
          dflt: 0
        },
        bgcolor: {
          valType: "color",
          dflt: "rgba(0,0,0,0)"
        },
        // tick and title properties named and function exactly as in axes
        tickmode: axesAttrs.minor.tickmode,
        nticks: axesAttrs.nticks,
        tick0: axesAttrs.tick0,
        dtick: axesAttrs.dtick,
        tickvals: axesAttrs.tickvals,
        ticktext: axesAttrs.ticktext,
        ticks: extendFlat({}, axesAttrs.ticks, { dflt: "" }),
        ticklabeloverflow: extendFlat({}, axesAttrs.ticklabeloverflow, {}),
        // ticklabelposition: not used directly, as values depend on orientation
        // left/right options are for x axes, and top/bottom options are for y axes
        ticklabelposition: {
          valType: "enumerated",
          values: [
            "outside",
            "inside",
            "outside top",
            "inside top",
            "outside left",
            "inside left",
            "outside right",
            "inside right",
            "outside bottom",
            "inside bottom"
          ],
          dflt: "outside"
        },
        ticklen: axesAttrs.ticklen,
        tickwidth: axesAttrs.tickwidth,
        tickcolor: axesAttrs.tickcolor,
        ticklabelstep: axesAttrs.ticklabelstep,
        showticklabels: axesAttrs.showticklabels,
        labelalias: axesAttrs.labelalias,
        tickfont: fontAttrs({}),
        tickangle: axesAttrs.tickangle,
        tickformat: axesAttrs.tickformat,
        tickformatstops: axesAttrs.tickformatstops,
        tickprefix: axesAttrs.tickprefix,
        showtickprefix: axesAttrs.showtickprefix,
        ticksuffix: axesAttrs.ticksuffix,
        showticksuffix: axesAttrs.showticksuffix,
        separatethousands: axesAttrs.separatethousands,
        exponentformat: axesAttrs.exponentformat,
        minexponent: axesAttrs.minexponent,
        showexponent: axesAttrs.showexponent,
        title: {
          text: {
            valType: "string"
          },
          font: fontAttrs({}),
          side: {
            valType: "enumerated",
            values: ["right", "top", "bottom"]
          }
        }
      }, "colorbars", "from-root");
    }
  });

  // src/components/colorscale/attributes.js
  var require_attributes8 = __commonJS({
    "src/components/colorscale/attributes.js"(exports, module) {
      "use strict";
      var colorbarAttrs = require_attributes7();
      var counterRegex = require_regex().counter;
      var sortObjectKeys = require_sort_object_keys();
      var palettes = require_scales().scales;
      var paletteStr = sortObjectKeys(palettes);
      function code(s) {
        return "`" + s + "`";
      }
      module.exports = function colorScaleAttrs(context, opts) {
        context = context || "";
        opts = opts || {};
        var cLetter = opts.cLetter || "c";
        var onlyIfNumerical = "onlyIfNumerical" in opts ? opts.onlyIfNumerical : Boolean(context);
        var noScale = "noScale" in opts ? opts.noScale : context === "marker.line";
        var showScaleDflt = "showScaleDflt" in opts ? opts.showScaleDflt : cLetter === "z";
        var colorscaleDflt = typeof opts.colorscaleDflt === "string" ? palettes[opts.colorscaleDflt] : null;
        var editTypeOverride = opts.editTypeOverride || "";
        var contextHead = context ? context + "." : "";
        var colorAttr, colorAttrFull;
        if ("colorAttr" in opts) {
          colorAttr = opts.colorAttr;
          colorAttrFull = opts.colorAttr;
        } else {
          colorAttr = { z: "z", c: "color" }[cLetter];
          colorAttrFull = "in " + code(contextHead + colorAttr);
        }
        var effectDesc = onlyIfNumerical ? " Has an effect only if " + colorAttrFull + " is set to a numerical array." : "";
        var auto = cLetter + "auto";
        var min = cLetter + "min";
        var max = cLetter + "max";
        var mid = cLetter + "mid";
        var autoFull = code(contextHead + auto);
        var minFull = code(contextHead + min);
        var maxFull = code(contextHead + max);
        var minmaxFull = minFull + " and " + maxFull;
        var autoImpliedEdits = {};
        autoImpliedEdits[min] = autoImpliedEdits[max] = void 0;
        var minmaxImpliedEdits = {};
        minmaxImpliedEdits[auto] = false;
        var attrs = {};
        if (colorAttr === "color") {
          attrs.color = {
            valType: "color",
            arrayOk: true,
            editType: editTypeOverride || "style"
          };
          if (opts.anim) {
            attrs.color.anim = true;
          }
        }
        attrs[auto] = {
          valType: "boolean",
          dflt: true,
          editType: "calc",
          impliedEdits: autoImpliedEdits
        };
        attrs[min] = {
          valType: "number",
          dflt: null,
          editType: editTypeOverride || "plot",
          impliedEdits: minmaxImpliedEdits
        };
        attrs[max] = {
          valType: "number",
          dflt: null,
          editType: editTypeOverride || "plot",
          impliedEdits: minmaxImpliedEdits
        };
        attrs[mid] = {
          valType: "number",
          dflt: null,
          editType: "calc",
          impliedEdits: autoImpliedEdits
        };
        attrs.colorscale = {
          valType: "colorscale",
          editType: "calc",
          dflt: colorscaleDflt,
          impliedEdits: { autocolorscale: false }
        };
        attrs.autocolorscale = {
          valType: "boolean",
          // gets overrode in 'heatmap' & 'surface' for backwards comp.
          dflt: opts.autoColorDflt === false ? false : true,
          editType: "calc",
          impliedEdits: { colorscale: void 0 }
        };
        attrs.reversescale = {
          valType: "boolean",
          dflt: false,
          editType: "plot"
        };
        if (!noScale) {
          attrs.showscale = {
            valType: "boolean",
            dflt: showScaleDflt,
            editType: "calc"
          };
          attrs.colorbar = colorbarAttrs;
        }
        if (!opts.noColorAxis) {
          attrs.coloraxis = {
            valType: "subplotid",
            regex: counterRegex("coloraxis"),
            dflt: null,
            editType: "calc"
          };
        }
        return attrs;
      };
    }
  });

  // src/components/colorscale/layout_attributes.js
  var require_layout_attributes5 = __commonJS({
    "src/components/colorscale/layout_attributes.js"(exports, module) {
      "use strict";
      var extendFlat = require_extend().extendFlat;
      var colorScaleAttrs = require_attributes8();
      var scales = require_scales().scales;
      module.exports = {
        editType: "calc",
        colorscale: {
          editType: "calc",
          sequential: {
            valType: "colorscale",
            dflt: scales.Reds,
            editType: "calc"
          },
          sequentialminus: {
            valType: "colorscale",
            dflt: scales.Blues,
            editType: "calc"
          },
          diverging: {
            valType: "colorscale",
            dflt: scales.RdBu,
            editType: "calc"
          }
        },
        coloraxis: extendFlat({
          // not really a 'subplot' attribute container,
          // but this is the flag we use to denote attributes that
          // support yaxis, yaxis2, yaxis3, ... counters
          _isSubplotObj: true,
          editType: "calc"
        }, colorScaleAttrs("", {
          colorAttr: "corresponding trace color array(s)",
          noColorAxis: true,
          showScaleDflt: true
        }))
      };
    }
  });

  // src/components/colorbar/has_colorbar.js
  var require_has_colorbar = __commonJS({
    "src/components/colorbar/has_colorbar.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function hasColorbar(container) {
        return Lib.isPlainObject(container.colorbar);
      };
    }
  });

  // src/plots/cartesian/clean_ticks.js
  var require_clean_ticks = __commonJS({
    "src/plots/cartesian/clean_ticks.js"(exports) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var constants = require_numerical();
      var ONEDAY = constants.ONEDAY;
      var ONEWEEK = constants.ONEWEEK;
      exports.dtick = function(dtick, axType) {
        var isLog = axType === "log";
        var isDate = axType === "date";
        var isCat = axType === "category";
        var dtickDflt = isDate ? ONEDAY : 1;
        if (!dtick) return dtickDflt;
        if (isNumeric(dtick)) {
          dtick = Number(dtick);
          if (dtick <= 0) return dtickDflt;
          if (isCat) {
            return Math.max(1, Math.round(dtick));
          }
          if (isDate) {
            return Math.max(0.1, dtick);
          }
          return dtick;
        }
        if (typeof dtick !== "string" || !(isDate || isLog)) {
          return dtickDflt;
        }
        var prefix = dtick.charAt(0);
        var dtickNum = dtick.slice(1);
        dtickNum = isNumeric(dtickNum) ? Number(dtickNum) : 0;
        if (dtickNum <= 0 || !// "M<n>" gives ticks every (integer) n months
        (isDate && prefix === "M" && dtickNum === Math.round(dtickNum) || // "L<f>" gives ticks linearly spaced in data (not in position) every (float) f
        isLog && prefix === "L" || // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5
        isLog && prefix === "D" && (dtickNum === 1 || dtickNum === 2))) {
          return dtickDflt;
        }
        return dtick;
      };
      exports.tick0 = function(tick0, axType, calendar, dtick) {
        if (axType === "date") {
          return Lib.cleanDate(
            tick0,
            Lib.dateTick0(calendar, dtick % ONEWEEK === 0 ? 1 : 0)
          );
        }
        if (dtick === "D1" || dtick === "D2") {
          return void 0;
        }
        return isNumeric(tick0) ? Number(tick0) : 0;
      };
    }
  });

  // src/plots/cartesian/tick_value_defaults.js
  var require_tick_value_defaults = __commonJS({
    "src/plots/cartesian/tick_value_defaults.js"(exports, module) {
      "use strict";
      var cleanTicks = require_clean_ticks();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var isTypedArraySpec = require_array().isTypedArraySpec;
      var decodeTypedArraySpec = require_array().decodeTypedArraySpec;
      module.exports = function handleTickValueDefaults(containerIn, containerOut, coerce, axType, opts) {
        if (!opts) opts = {};
        var isMinor = opts.isMinor;
        var cIn = isMinor ? containerIn.minor || {} : containerIn;
        var cOut = isMinor ? containerOut.minor : containerOut;
        var prefix = isMinor ? "minor." : "";
        function readInput(attr) {
          var v = cIn[attr];
          if (isTypedArraySpec(v)) v = decodeTypedArraySpec(v);
          return v !== void 0 ? v : (cOut._template || {})[attr];
        }
        var _tick0 = readInput("tick0");
        var _dtick = readInput("dtick");
        var _tickvals = readInput("tickvals");
        var tickmodeDefault = isArrayOrTypedArray(_tickvals) ? "array" : _dtick ? "linear" : "auto";
        var tickmode = coerce(prefix + "tickmode", tickmodeDefault);
        if (tickmode === "auto" || tickmode === "sync") {
          coerce(prefix + "nticks");
        } else if (tickmode === "linear") {
          var dtick = cOut.dtick = cleanTicks.dtick(
            _dtick,
            axType
          );
          cOut.tick0 = cleanTicks.tick0(
            _tick0,
            axType,
            containerOut.calendar,
            dtick
          );
        } else if (axType !== "multicategory") {
          var tickvals = coerce(prefix + "tickvals");
          if (tickvals === void 0) cOut.tickmode = "auto";
          else if (!isMinor) coerce("ticktext");
        }
      };
    }
  });

  // src/plots/cartesian/tick_mark_defaults.js
  var require_tick_mark_defaults = __commonJS({
    "src/plots/cartesian/tick_mark_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes4();
      module.exports = function handleTickMarkDefaults(containerIn, containerOut, coerce, options) {
        var isMinor = options.isMinor;
        var cIn = isMinor ? containerIn.minor || {} : containerIn;
        var cOut = isMinor ? containerOut.minor : containerOut;
        var lAttr = isMinor ? layoutAttributes.minor : layoutAttributes;
        var prefix = isMinor ? "minor." : "";
        var tickLen = Lib.coerce2(cIn, cOut, lAttr, "ticklen", isMinor ? (containerOut.ticklen || 5) * 0.6 : void 0);
        var tickWidth = Lib.coerce2(cIn, cOut, lAttr, "tickwidth", isMinor ? containerOut.tickwidth || 1 : void 0);
        var tickColor = Lib.coerce2(cIn, cOut, lAttr, "tickcolor", (isMinor ? containerOut.tickcolor : void 0) || cOut.color);
        var showTicks = coerce(prefix + "ticks", !isMinor && options.outerTicks || tickLen || tickWidth || tickColor ? "outside" : "");
        if (!showTicks) {
          delete cOut.ticklen;
          delete cOut.tickwidth;
          delete cOut.tickcolor;
        }
      };
    }
  });

  // src/plots/cartesian/show_dflt.js
  var require_show_dflt = __commonJS({
    "src/plots/cartesian/show_dflt.js"(exports, module) {
      "use strict";
      module.exports = function getShowAttrDflt(containerIn) {
        var showAttrsAll = ["showexponent", "showtickprefix", "showticksuffix"];
        var showAttrs = showAttrsAll.filter(function(a) {
          return containerIn[a] !== void 0;
        });
        var sameVal = function(a) {
          return containerIn[a] === containerIn[showAttrs[0]];
        };
        if (showAttrs.every(sameVal) || showAttrs.length === 1) {
          return containerIn[showAttrs[0]];
        }
      };
    }
  });

  // src/plots/array_container_defaults.js
  var require_array_container_defaults = __commonJS({
    "src/plots/array_container_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Template = require_plot_template();
      module.exports = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) {
        var name2 = opts.name;
        var inclusionAttr = opts.inclusionAttr || "visible";
        var previousContOut = parentObjOut[name2];
        var contIn = Lib.isArrayOrTypedArray(parentObjIn[name2]) ? parentObjIn[name2] : [];
        var contOut = parentObjOut[name2] = [];
        var templater = Template.arrayTemplater(parentObjOut, name2, inclusionAttr);
        var i, itemOut;
        for (i = 0; i < contIn.length; i++) {
          var itemIn = contIn[i];
          if (!Lib.isPlainObject(itemIn)) {
            itemOut = templater.newItem({});
            itemOut[inclusionAttr] = false;
          } else {
            itemOut = templater.newItem(itemIn);
          }
          itemOut._index = i;
          if (itemOut[inclusionAttr] !== false) {
            opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts);
          }
          contOut.push(itemOut);
        }
        var defaultItems = templater.defaultItems();
        for (i = 0; i < defaultItems.length; i++) {
          itemOut = defaultItems[i];
          itemOut._index = contOut.length;
          opts.handleItemDefaults({}, itemOut, parentObjOut, opts, {});
          contOut.push(itemOut);
        }
        if (Lib.isArrayOrTypedArray(previousContOut)) {
          var len = Math.min(previousContOut.length, contOut.length);
          for (i = 0; i < len; i++) {
            Lib.relinkPrivateKeys(contOut[i], previousContOut[i]);
          }
        }
        return contOut;
      };
    }
  });

  // src/plots/cartesian/tick_label_defaults.js
  var require_tick_label_defaults = __commonJS({
    "src/plots/cartesian/tick_label_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var contrast = require_color().contrast;
      var layoutAttributes = require_layout_attributes4();
      var getShowAttrDflt = require_show_dflt();
      var handleArrayContainerDefaults = require_array_container_defaults();
      module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
        if (!options) options = {};
        var labelalias = coerce("labelalias");
        if (!Lib.isPlainObject(labelalias)) delete containerOut.labelalias;
        var showAttrDflt = getShowAttrDflt(containerIn);
        var showTickLabels = coerce("showticklabels");
        if (showTickLabels) {
          if (!options.noTicklabelshift) {
            coerce("ticklabelshift");
          }
          if (!options.noTicklabelstandoff) {
            coerce("ticklabelstandoff");
          }
          var font = options.font || {};
          var contColor = containerOut.color;
          var position = containerOut.ticklabelposition || "";
          var dfltFontColor = position.indexOf("inside") !== -1 ? contrast(options.bgColor) : (
            // as with title.font.color, inherit axis.color only if one was
            // explicitly provided
            contColor && contColor !== layoutAttributes.color.dflt ? contColor : font.color
          );
          Lib.coerceFont(coerce, "tickfont", font, { overrideDflt: {
            color: dfltFontColor
          } });
          if (!options.noTicklabelstep && axType !== "multicategory" && axType !== "log") {
            coerce("ticklabelstep");
          }
          if (!options.noAng) {
            var tickAngle = coerce("tickangle");
            if (!options.noAutotickangles && tickAngle === "auto") {
              coerce("autotickangles");
            }
          }
          if (axType !== "category") {
            var tickFormat = coerce("tickformat");
            handleArrayContainerDefaults(containerIn, containerOut, {
              name: "tickformatstops",
              inclusionAttr: "enabled",
              handleItemDefaults: tickformatstopDefaults
            });
            if (!containerOut.tickformatstops.length) {
              delete containerOut.tickformatstops;
            }
            if (!options.noExp && !tickFormat && axType !== "date") {
              coerce("showexponent", showAttrDflt);
              coerce("exponentformat");
              coerce("minexponent");
              coerce("separatethousands");
            }
          }
          if (!options.noMinorloglabels && axType === "log") {
            coerce("minorloglabels");
          }
        }
      };
      function tickformatstopDefaults(valueIn, valueOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
        }
        var enabled = coerce("enabled");
        if (enabled) {
          coerce("dtickrange");
          coerce("value");
        }
      }
    }
  });

  // src/plots/cartesian/prefix_suffix_defaults.js
  var require_prefix_suffix_defaults = __commonJS({
    "src/plots/cartesian/prefix_suffix_defaults.js"(exports, module) {
      "use strict";
      var getShowAttrDflt = require_show_dflt();
      module.exports = function handlePrefixSuffixDefaults(containerIn, containerOut, coerce, axType, options) {
        if (!options) options = {};
        var tickSuffixDflt = options.tickSuffixDflt;
        var showAttrDflt = getShowAttrDflt(containerIn);
        var tickPrefix = coerce("tickprefix");
        if (tickPrefix) coerce("showtickprefix", showAttrDflt);
        var tickSuffix = coerce("ticksuffix", tickSuffixDflt);
        if (tickSuffix) coerce("showticksuffix", showAttrDflt);
      };
    }
  });

  // src/components/colorbar/defaults.js
  var require_defaults = __commonJS({
    "src/components/colorbar/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Template = require_plot_template();
      var handleTickValueDefaults = require_tick_value_defaults();
      var handleTickMarkDefaults = require_tick_mark_defaults();
      var handleTickLabelDefaults = require_tick_label_defaults();
      var handlePrefixSuffixDefaults = require_prefix_suffix_defaults();
      var attributes = require_attributes7();
      module.exports = function colorbarDefaults(containerIn, containerOut, layout) {
        var colorbarOut = Template.newContainer(containerOut, "colorbar");
        var colorbarIn = containerIn.colorbar || {};
        function coerce(attr, dflt) {
          return Lib.coerce(colorbarIn, colorbarOut, attributes, attr, dflt);
        }
        var margin = layout.margin || { t: 0, b: 0, l: 0, r: 0 };
        var w = layout.width - margin.l - margin.r;
        var h = layout.height - margin.t - margin.b;
        var orientation = coerce("orientation");
        var isVertical = orientation === "v";
        var thicknessmode = coerce("thicknessmode");
        coerce(
          "thickness",
          thicknessmode === "fraction" ? 30 / (isVertical ? w : h) : 30
        );
        var lenmode = coerce("lenmode");
        coerce(
          "len",
          lenmode === "fraction" ? 1 : isVertical ? h : w
        );
        var yref = coerce("yref");
        var xref = coerce("xref");
        var isPaperY = yref === "paper";
        var isPaperX = xref === "paper";
        var defaultX, defaultY, defaultYAnchor;
        var defaultXAnchor = "left";
        if (isVertical) {
          defaultYAnchor = "middle";
          defaultXAnchor = isPaperX ? "left" : "right";
          defaultX = isPaperX ? 1.02 : 1;
          defaultY = 0.5;
        } else {
          defaultYAnchor = isPaperY ? "bottom" : "top";
          defaultXAnchor = "center";
          defaultX = 0.5;
          defaultY = isPaperY ? 1.02 : 1;
        }
        Lib.coerce(colorbarIn, colorbarOut, {
          x: {
            valType: "number",
            min: isPaperX ? -2 : 0,
            max: isPaperX ? 3 : 1,
            dflt: defaultX
          }
        }, "x");
        Lib.coerce(colorbarIn, colorbarOut, {
          y: {
            valType: "number",
            min: isPaperY ? -2 : 0,
            max: isPaperY ? 3 : 1,
            dflt: defaultY
          }
        }, "y");
        coerce("xanchor", defaultXAnchor);
        coerce("xpad");
        coerce("yanchor", defaultYAnchor);
        coerce("ypad");
        Lib.noneOrAll(colorbarIn, colorbarOut, ["x", "y"]);
        coerce("outlinecolor");
        coerce("outlinewidth");
        coerce("bordercolor");
        coerce("borderwidth");
        coerce("bgcolor");
        var ticklabelposition = Lib.coerce(colorbarIn, colorbarOut, {
          ticklabelposition: {
            valType: "enumerated",
            dflt: "outside",
            values: isVertical ? [
              "outside",
              "inside",
              "outside top",
              "inside top",
              "outside bottom",
              "inside bottom"
            ] : [
              "outside",
              "inside",
              "outside left",
              "inside left",
              "outside right",
              "inside right"
            ]
          }
        }, "ticklabelposition");
        coerce("ticklabeloverflow", ticklabelposition.indexOf("inside") !== -1 ? "hide past domain" : "hide past div");
        handleTickValueDefaults(colorbarIn, colorbarOut, coerce, "linear");
        var font = layout.font;
        var opts = {
          noAutotickangles: true,
          noTicklabelshift: true,
          noTicklabelstandoff: true,
          outerTicks: false,
          font
        };
        if (ticklabelposition.indexOf("inside") !== -1) {
          opts.bgColor = "black";
        }
        handlePrefixSuffixDefaults(colorbarIn, colorbarOut, coerce, "linear", opts);
        handleTickLabelDefaults(colorbarIn, colorbarOut, coerce, "linear", opts);
        handleTickMarkDefaults(colorbarIn, colorbarOut, coerce, "linear", opts);
        coerce("title.text", layout._dfltTitle.colorbar);
        var tickFont = colorbarOut.showticklabels ? colorbarOut.tickfont : font;
        var dfltTitleFont = Lib.extendFlat({}, font, {
          family: tickFont.family,
          size: Lib.bigFont(tickFont.size)
        });
        Lib.coerceFont(coerce, "title.font", dfltTitleFont);
        coerce("title.side", isVertical ? "top" : "right");
      };
    }
  });

  // src/components/colorscale/defaults.js
  var require_defaults2 = __commonJS({
    "src/components/colorscale/defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var hasColorbar = require_has_colorbar();
      var colorbarDefaults = require_defaults();
      var isValidScale = require_scales().isValid;
      var traceIs = require_registry().traceIs;
      function npMaybe(parentCont, prefix) {
        var containerStr = prefix.slice(0, prefix.length - 1);
        return prefix ? Lib.nestedProperty(parentCont, containerStr).get() || {} : parentCont;
      }
      module.exports = function colorScaleDefaults(parentContIn, parentContOut, layout, coerce, opts) {
        var prefix = opts.prefix;
        var cLetter = opts.cLetter;
        var inTrace = "_module" in parentContOut;
        var containerIn = npMaybe(parentContIn, prefix);
        var containerOut = npMaybe(parentContOut, prefix);
        var template = npMaybe(parentContOut._template || {}, prefix) || {};
        var thisFn = function() {
          delete parentContIn.coloraxis;
          delete parentContOut.coloraxis;
          return colorScaleDefaults(parentContIn, parentContOut, layout, coerce, opts);
        };
        if (inTrace) {
          var colorAxes = layout._colorAxes || {};
          var colorAx = coerce(prefix + "coloraxis");
          if (colorAx) {
            var colorbarVisuals = traceIs(parentContOut, "contour") && Lib.nestedProperty(parentContOut, "contours.coloring").get() || "heatmap";
            var stash = colorAxes[colorAx];
            if (stash) {
              stash[2].push(thisFn);
              if (stash[0] !== colorbarVisuals) {
                stash[0] = false;
                Lib.warn([
                  "Ignoring coloraxis:",
                  colorAx,
                  "setting",
                  "as it is linked to incompatible colorscales."
                ].join(" "));
              }
            } else {
              colorAxes[colorAx] = [colorbarVisuals, parentContOut, [thisFn]];
            }
            return;
          }
        }
        var minIn = containerIn[cLetter + "min"];
        var maxIn = containerIn[cLetter + "max"];
        var validMinMax = isNumeric(minIn) && isNumeric(maxIn) && minIn < maxIn;
        var auto = coerce(prefix + cLetter + "auto", !validMinMax);
        if (auto) {
          coerce(prefix + cLetter + "mid");
        } else {
          coerce(prefix + cLetter + "min");
          coerce(prefix + cLetter + "max");
        }
        var sclIn = containerIn.colorscale;
        var sclTemplate = template.colorscale;
        var autoColorscaleDflt;
        if (sclIn !== void 0) autoColorscaleDflt = !isValidScale(sclIn);
        if (sclTemplate !== void 0) autoColorscaleDflt = !isValidScale(sclTemplate);
        coerce(prefix + "autocolorscale", autoColorscaleDflt);
        coerce(prefix + "colorscale");
        coerce(prefix + "reversescale");
        if (prefix !== "marker.line.") {
          var showScaleDflt;
          if (prefix && inTrace) showScaleDflt = hasColorbar(containerIn);
          var showScale = coerce(prefix + "showscale", showScaleDflt);
          if (showScale) {
            if (prefix && template) containerOut._template = template;
            colorbarDefaults(containerIn, containerOut, layout);
          }
        }
      };
    }
  });

  // src/components/colorscale/layout_defaults.js
  var require_layout_defaults = __commonJS({
    "src/components/colorscale/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Template = require_plot_template();
      var colorScaleAttrs = require_layout_attributes5();
      var colorScaleDefaults = require_defaults2();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, colorScaleAttrs, attr, dflt);
        }
        coerce("colorscale.sequential");
        coerce("colorscale.sequentialminus");
        coerce("colorscale.diverging");
        var colorAxes = layoutOut._colorAxes;
        var colorAxIn, colorAxOut;
        function coerceAx(attr, dflt) {
          return Lib.coerce(colorAxIn, colorAxOut, colorScaleAttrs.coloraxis, attr, dflt);
        }
        for (var k in colorAxes) {
          var stash = colorAxes[k];
          if (stash[0]) {
            colorAxIn = layoutIn[k] || {};
            colorAxOut = Template.newContainer(layoutOut, k, "coloraxis");
            colorAxOut._name = k;
            colorScaleDefaults(colorAxIn, colorAxOut, layoutOut, coerceAx, { prefix: "", cLetter: "c" });
          } else {
            for (var i = 0; i < stash[2].length; i++) {
              stash[2][i]();
            }
            delete layoutOut._colorAxes[k];
          }
        }
      };
    }
  });

  // src/components/colorscale/cross_trace_defaults.js
  var require_cross_trace_defaults = __commonJS({
    "src/components/colorscale/cross_trace_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var hasColorscale = require_helpers().hasColorscale;
      var extractOpts = require_helpers().extractOpts;
      module.exports = function crossTraceDefaults(fullData, fullLayout) {
        function replace(cont, k2) {
          var val = cont["_" + k2];
          if (val !== void 0) {
            cont[k2] = val;
          }
        }
        function relinkColorAttrs(outerCont, cbOpt) {
          var cont = cbOpt.container ? Lib.nestedProperty(outerCont, cbOpt.container).get() : outerCont;
          if (cont) {
            if (cont.coloraxis) {
              cont._colorAx = fullLayout[cont.coloraxis];
            } else {
              var cOpts = extractOpts(cont);
              var isAuto = cOpts.auto;
              if (isAuto || cOpts.min === void 0) {
                replace(cont, cbOpt.min);
              }
              if (isAuto || cOpts.max === void 0) {
                replace(cont, cbOpt.max);
              }
              if (cOpts.autocolorscale) {
                replace(cont, "colorscale");
              }
            }
          }
        }
        for (var i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          var cbOpts = trace._module.colorbar;
          if (cbOpts) {
            if (Array.isArray(cbOpts)) {
              for (var j = 0; j < cbOpts.length; j++) {
                relinkColorAttrs(trace, cbOpts[j]);
              }
            } else {
              relinkColorAttrs(trace, cbOpts);
            }
          }
          if (hasColorscale(trace, "marker.line")) {
            relinkColorAttrs(trace, {
              container: "marker.line",
              min: "cmin",
              max: "cmax"
            });
          }
        }
        for (var k in fullLayout._colorAxes) {
          relinkColorAttrs(fullLayout[k], { min: "cmin", max: "cmax" });
        }
      };
    }
  });

  // src/components/colorscale/calc.js
  var require_calc = __commonJS({
    "src/components/colorscale/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var extractOpts = require_helpers().extractOpts;
      module.exports = function calc(gd, trace, opts) {
        var fullLayout = gd._fullLayout;
        var vals = opts.vals;
        var containerStr = opts.containerStr;
        var container = containerStr ? Lib.nestedProperty(trace, containerStr).get() : trace;
        var cOpts = extractOpts(container);
        var auto = cOpts.auto !== false;
        var min = cOpts.min;
        var max = cOpts.max;
        var mid = cOpts.mid;
        var minVal = function() {
          return Lib.aggNums(Math.min, null, vals);
        };
        var maxVal = function() {
          return Lib.aggNums(Math.max, null, vals);
        };
        if (min === void 0) {
          min = minVal();
        } else if (auto) {
          if (container._colorAx && isNumeric(min)) {
            min = Math.min(min, minVal());
          } else {
            min = minVal();
          }
        }
        if (max === void 0) {
          max = maxVal();
        } else if (auto) {
          if (container._colorAx && isNumeric(max)) {
            max = Math.max(max, maxVal());
          } else {
            max = maxVal();
          }
        }
        if (auto && mid !== void 0) {
          if (max - mid > mid - min) {
            min = mid - (max - mid);
          } else if (max - mid < mid - min) {
            max = mid + (mid - min);
          }
        }
        if (min === max) {
          min -= 0.5;
          max += 0.5;
        }
        cOpts._sync("min", min);
        cOpts._sync("max", max);
        if (cOpts.autocolorscale) {
          var scl;
          if (min * max < 0) scl = fullLayout.colorscale.diverging;
          else if (min >= 0) scl = fullLayout.colorscale.sequential;
          else scl = fullLayout.colorscale.sequentialminus;
          cOpts._sync("colorscale", scl);
        }
      };
    }
  });

  // src/components/colorscale/index.js
  var require_colorscale = __commonJS({
    "src/components/colorscale/index.js"(exports, module) {
      "use strict";
      var scales = require_scales();
      var helpers = require_helpers();
      module.exports = {
        moduleType: "component",
        name: "colorscale",
        attributes: require_attributes8(),
        layoutAttributes: require_layout_attributes5(),
        supplyLayoutDefaults: require_layout_defaults(),
        handleDefaults: require_defaults2(),
        crossTraceDefaults: require_cross_trace_defaults(),
        calc: require_calc(),
        // ./scales.js is required in lib/coerce.js ;
        // it needs to be a separate module to avoid a circular dependency
        scales: scales.scales,
        defaultScale: scales.defaultScale,
        getScale: scales.get,
        isValidScale: scales.isValid,
        hasColorscale: helpers.hasColorscale,
        extractOpts: helpers.extractOpts,
        extractScale: helpers.extractScale,
        flipScale: helpers.flipScale,
        makeColorScaleFunc: helpers.makeColorScaleFunc,
        makeColorScaleFuncFromTrace: helpers.makeColorScaleFuncFromTrace
      };
    }
  });

  // src/traces/scatter/subtypes.js
  var require_subtypes = __commonJS({
    "src/traces/scatter/subtypes.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var isTypedArraySpec = require_array().isTypedArraySpec;
      module.exports = {
        hasLines: function(trace) {
          return trace.visible && trace.mode && trace.mode.indexOf("lines") !== -1;
        },
        hasMarkers: function(trace) {
          return trace.visible && (trace.mode && trace.mode.indexOf("markers") !== -1 || // until splom implements 'mode'
          trace.type === "splom");
        },
        hasText: function(trace) {
          return trace.visible && trace.mode && trace.mode.indexOf("text") !== -1;
        },
        isBubble: function(trace) {
          var marker = trace.marker;
          return Lib.isPlainObject(marker) && (Lib.isArrayOrTypedArray(marker.size) || isTypedArraySpec(marker.size));
        }
      };
    }
  });

  // src/traces/scatter/make_bubble_size_func.js
  var require_make_bubble_size_func = __commonJS({
    "src/traces/scatter/make_bubble_size_func.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      module.exports = function makeBubbleSizeFn(trace, factor) {
        if (!factor) {
          factor = 2;
        }
        var marker = trace.marker;
        var sizeRef = marker.sizeref || 1;
        var sizeMin = marker.sizemin || 0;
        var baseFn = marker.sizemode === "area" ? function(v) {
          return Math.sqrt(v / sizeRef);
        } : function(v) {
          return v / sizeRef;
        };
        return function(v) {
          var baseSize = baseFn(v / factor);
          return isNumeric(baseSize) && baseSize > 0 ? Math.max(baseSize, sizeMin) : 0;
        };
      };
    }
  });

  // src/components/fx/helpers.js
  var require_helpers2 = __commonJS({
    "src/components/fx/helpers.js"(exports) {
      "use strict";
      var Lib = require_lib();
      exports.getSubplot = function(trace) {
        return trace.subplot || trace.xaxis + trace.yaxis || trace.geo;
      };
      exports.isTraceInSubplots = function(trace, subplots) {
        if (trace.type === "splom") {
          var xaxes = trace.xaxes || [];
          var yaxes = trace.yaxes || [];
          for (var i = 0; i < xaxes.length; i++) {
            for (var j = 0; j < yaxes.length; j++) {
              if (subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) {
                return true;
              }
            }
          }
          return false;
        }
        return subplots.indexOf(exports.getSubplot(trace)) !== -1;
      };
      exports.flat = function(subplots, v) {
        var out = new Array(subplots.length);
        for (var i = 0; i < subplots.length; i++) {
          out[i] = v;
        }
        return out;
      };
      exports.p2c = function(axArray, v) {
        var out = new Array(axArray.length);
        for (var i = 0; i < axArray.length; i++) {
          out[i] = axArray[i].p2c(v);
        }
        return out;
      };
      exports.getDistanceFunction = function(mode, dx, dy, dxy) {
        if (mode === "closest") return dxy || exports.quadrature(dx, dy);
        return mode.charAt(0) === "x" ? dx : dy;
      };
      exports.getClosest = function(cd, distfn, pointData) {
        if (pointData.index !== false) {
          if (pointData.index >= 0 && pointData.index < cd.length) {
            pointData.distance = 0;
          } else pointData.index = false;
        } else {
          var newDistance = Infinity;
          var len = cd.length;
          for (var i = 0; i < len; i++) {
            newDistance = distfn(cd[i]);
            if (newDistance <= pointData.distance) {
              pointData.index = i;
              pointData.distance = newDistance;
            }
          }
        }
        return pointData;
      };
      exports.inbox = function(v0, v1, passVal) {
        return v0 * v1 < 0 || v0 === 0 ? passVal : Infinity;
      };
      exports.quadrature = function(dx, dy) {
        return function(di) {
          var x = dx(di);
          var y = dy(di);
          return Math.sqrt(x * x + y * y);
        };
      };
      exports.makeEventData = function(pt, trace, cd) {
        var pointNumber = "index" in pt ? pt.index : pt.pointNumber;
        var out = {
          data: trace._input,
          fullData: trace,
          curveNumber: trace.index,
          pointNumber
        };
        if (trace._indexToPoints) {
          var pointIndices = trace._indexToPoints[pointNumber];
          if (pointIndices.length === 1) {
            out.pointIndex = pointIndices[0];
          } else {
            out.pointIndices = pointIndices;
          }
        } else {
          out.pointIndex = pointNumber;
        }
        if (trace._module.eventData) {
          out = trace._module.eventData(out, pt, trace, cd, pointNumber);
        } else {
          if ("xVal" in pt) out.x = pt.xVal;
          else if ("x" in pt) out.x = pt.x;
          if ("yVal" in pt) out.y = pt.yVal;
          else if ("y" in pt) out.y = pt.y;
          if (pt.xa) out.xaxis = pt.xa;
          if (pt.ya) out.yaxis = pt.ya;
          if (pt.zLabelVal !== void 0) out.z = pt.zLabelVal;
        }
        exports.appendArrayPointValue(out, trace, pointNumber);
        return out;
      };
      exports.appendArrayPointValue = function(pointData, trace, pointNumber) {
        var arrayAttrs = trace._arrayAttrs;
        if (!arrayAttrs) {
          return;
        }
        for (var i = 0; i < arrayAttrs.length; i++) {
          var astr = arrayAttrs[i];
          var key = getPointKey(astr);
          if (pointData[key] === void 0) {
            var val = Lib.nestedProperty(trace, astr).get();
            var pointVal = getPointData(val, pointNumber);
            if (pointVal !== void 0) pointData[key] = pointVal;
          }
        }
      };
      exports.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) {
        var arrayAttrs = trace._arrayAttrs;
        if (!arrayAttrs) {
          return;
        }
        for (var i = 0; i < arrayAttrs.length; i++) {
          var astr = arrayAttrs[i];
          var key = getPointKey(astr);
          if (pointData[key] === void 0) {
            var val = Lib.nestedProperty(trace, astr).get();
            var keyVal = new Array(pointNumbers.length);
            for (var j = 0; j < pointNumbers.length; j++) {
              keyVal[j] = getPointData(val, pointNumbers[j]);
            }
            pointData[key] = keyVal;
          }
        }
      };
      var pointKeyMap = {
        ids: "id",
        locations: "location",
        labels: "label",
        values: "value",
        "marker.colors": "color",
        parents: "parent"
      };
      function getPointKey(astr) {
        return pointKeyMap[astr] || astr;
      }
      function getPointData(val, pointNumber) {
        if (Array.isArray(pointNumber)) {
          if (Lib.isArrayOrTypedArray(val) && Lib.isArrayOrTypedArray(val[pointNumber[0]])) {
            return val[pointNumber[0]][pointNumber[1]];
          }
        } else {
          return val[pointNumber];
        }
      }
      var xyHoverMode = {
        x: true,
        y: true
      };
      var unifiedHoverMode = {
        "x unified": true,
        "y unified": true
      };
      exports.isUnifiedHover = function(hovermode) {
        if (typeof hovermode !== "string") return false;
        return !!unifiedHoverMode[hovermode];
      };
      exports.isXYhover = function(hovermode) {
        if (typeof hovermode !== "string") return false;
        return !!xyHoverMode[hovermode];
      };
    }
  });

  // node_modules/parse-svg-path/index.js
  var require_parse_svg_path = __commonJS({
    "node_modules/parse-svg-path/index.js"(exports, module) {
      module.exports = parse2;
      var length = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0 };
      var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig;
      function parse2(path) {
        var data = [];
        path.replace(segment, function(_, command, args) {
          var type = command.toLowerCase();
          args = parseValues(args);
          if (type == "m" && args.length > 2) {
            data.push([command].concat(args.splice(0, 2)));
            type = "l";
            command = command == "m" ? "l" : "L";
          }
          while (true) {
            if (args.length == length[type]) {
              args.unshift(command);
              return data.push(args);
            }
            if (args.length < length[type]) throw new Error("malformed path data");
            data.push([command].concat(args.splice(0, length[type])));
          }
        });
        return data;
      }
      var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;
      function parseValues(args) {
        var numbers = args.match(number);
        return numbers ? numbers.map(Number) : [];
      }
    }
  });

  // src/components/drawing/symbol_defs.js
  var require_symbol_defs = __commonJS({
    "src/components/drawing/symbol_defs.js"(exports, module) {
      "use strict";
      var parseSvgPath = require_parse_svg_path();
      var round = (
        // require('@plotly/d3').round;
        function(x, n) {
          return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
        }
      );
      var emptyPath = "M0,0Z";
      var sqrt2 = Math.sqrt(2);
      var sqrt3 = Math.sqrt(3);
      var PI = Math.PI;
      var cos = Math.cos;
      var sin = Math.sin;
      module.exports = {
        circle: {
          n: 0,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            var circle = "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z";
            return standoff ? align(angle, standoff, circle) : circle;
          }
        },
        square: {
          n: 1,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            return align(angle, standoff, "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z");
          }
        },
        diamond: {
          n: 2,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rd = round(r * 1.3, 2);
            return align(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "Z");
          }
        },
        cross: {
          n: 3,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rc = round(r * 0.4, 2);
            var rc2 = round(r * 1.2, 2);
            return align(angle, standoff, "M" + rc2 + "," + rc + "H" + rc + "V" + rc2 + "H-" + rc + "V" + rc + "H-" + rc2 + "V-" + rc + "H-" + rc + "V-" + rc2 + "H" + rc + "V-" + rc + "H" + rc2 + "Z");
          }
        },
        x: {
          n: 4,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r * 0.8 / sqrt2, 2);
            var ne = "l" + rx + "," + rx;
            var se = "l" + rx + ",-" + rx;
            var sw = "l-" + rx + ",-" + rx;
            var nw = "l-" + rx + "," + rx;
            return align(angle, standoff, "M0," + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + "Z");
          }
        },
        "triangle-up": {
          n: 5,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rt = round(r * 2 / sqrt3, 2);
            var r2 = round(r / 2, 2);
            var rs = round(r, 2);
            return align(angle, standoff, "M-" + rt + "," + r2 + "H" + rt + "L0,-" + rs + "Z");
          }
        },
        "triangle-down": {
          n: 6,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rt = round(r * 2 / sqrt3, 2);
            var r2 = round(r / 2, 2);
            var rs = round(r, 2);
            return align(angle, standoff, "M-" + rt + ",-" + r2 + "H" + rt + "L0," + rs + "Z");
          }
        },
        "triangle-left": {
          n: 7,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rt = round(r * 2 / sqrt3, 2);
            var r2 = round(r / 2, 2);
            var rs = round(r, 2);
            return align(angle, standoff, "M" + r2 + ",-" + rt + "V" + rt + "L-" + rs + ",0Z");
          }
        },
        "triangle-right": {
          n: 8,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rt = round(r * 2 / sqrt3, 2);
            var r2 = round(r / 2, 2);
            var rs = round(r, 2);
            return align(angle, standoff, "M-" + r2 + ",-" + rt + "V" + rt + "L" + rs + ",0Z");
          }
        },
        "triangle-ne": {
          n: 9,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var r1 = round(r * 0.6, 2);
            var r2 = round(r * 1.2, 2);
            return align(angle, standoff, "M-" + r2 + ",-" + r1 + "H" + r1 + "V" + r2 + "Z");
          }
        },
        "triangle-se": {
          n: 10,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var r1 = round(r * 0.6, 2);
            var r2 = round(r * 1.2, 2);
            return align(angle, standoff, "M" + r1 + ",-" + r2 + "V" + r1 + "H-" + r2 + "Z");
          }
        },
        "triangle-sw": {
          n: 11,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var r1 = round(r * 0.6, 2);
            var r2 = round(r * 1.2, 2);
            return align(angle, standoff, "M" + r2 + "," + r1 + "H-" + r1 + "V-" + r2 + "Z");
          }
        },
        "triangle-nw": {
          n: 12,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var r1 = round(r * 0.6, 2);
            var r2 = round(r * 1.2, 2);
            return align(angle, standoff, "M-" + r1 + "," + r2 + "V-" + r1 + "H" + r2 + "Z");
          }
        },
        pentagon: {
          n: 13,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x1 = round(r * 0.951, 2);
            var x2 = round(r * 0.588, 2);
            var y0 = round(-r, 2);
            var y1 = round(r * -0.309, 2);
            var y2 = round(r * 0.809, 2);
            return align(angle, standoff, "M" + x1 + "," + y1 + "L" + x2 + "," + y2 + "H-" + x2 + "L-" + x1 + "," + y1 + "L0," + y0 + "Z");
          }
        },
        hexagon: {
          n: 14,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var y0 = round(r, 2);
            var y1 = round(r / 2, 2);
            var x = round(r * sqrt3 / 2, 2);
            return align(angle, standoff, "M" + x + ",-" + y1 + "V" + y1 + "L0," + y0 + "L-" + x + "," + y1 + "V-" + y1 + "L0,-" + y0 + "Z");
          }
        },
        hexagon2: {
          n: 15,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x0 = round(r, 2);
            var x1 = round(r / 2, 2);
            var y = round(r * sqrt3 / 2, 2);
            return align(angle, standoff, "M-" + x1 + "," + y + "H" + x1 + "L" + x0 + ",0L" + x1 + ",-" + y + "H-" + x1 + "L-" + x0 + ",0Z");
          }
        },
        octagon: {
          n: 16,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var a = round(r * 0.924, 2);
            var b = round(r * 0.383, 2);
            return align(angle, standoff, "M-" + b + ",-" + a + "H" + b + "L" + a + ",-" + b + "V" + b + "L" + b + "," + a + "H-" + b + "L-" + a + "," + b + "V-" + b + "Z");
          }
        },
        star: {
          n: 17,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = r * 1.4;
            var x1 = round(rs * 0.225, 2);
            var x2 = round(rs * 0.951, 2);
            var x3 = round(rs * 0.363, 2);
            var x4 = round(rs * 0.588, 2);
            var y0 = round(-rs, 2);
            var y1 = round(rs * -0.309, 2);
            var y3 = round(rs * 0.118, 2);
            var y4 = round(rs * 0.809, 2);
            var y5 = round(rs * 0.382, 2);
            return align(angle, standoff, "M" + x1 + "," + y1 + "H" + x2 + "L" + x3 + "," + y3 + "L" + x4 + "," + y4 + "L0," + y5 + "L-" + x4 + "," + y4 + "L-" + x3 + "," + y3 + "L-" + x2 + "," + y1 + "H-" + x1 + "L0," + y0 + "Z");
          }
        },
        hexagram: {
          n: 18,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var y = round(r * 0.66, 2);
            var x1 = round(r * 0.38, 2);
            var x2 = round(r * 0.76, 2);
            return align(angle, standoff, "M-" + x2 + ",0l-" + x1 + ",-" + y + "h" + x2 + "l" + x1 + ",-" + y + "l" + x1 + "," + y + "h" + x2 + "l-" + x1 + "," + y + "l" + x1 + "," + y + "h-" + x2 + "l-" + x1 + "," + y + "l-" + x1 + ",-" + y + "h-" + x2 + "Z");
          }
        },
        "star-triangle-up": {
          n: 19,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x = round(r * sqrt3 * 0.8, 2);
            var y1 = round(r * 0.8, 2);
            var y2 = round(r * 1.6, 2);
            var rc = round(r * 4, 2);
            var aPart = "A " + rc + "," + rc + " 0 0 1 ";
            return align(angle, standoff, "M-" + x + "," + y1 + aPart + x + "," + y1 + aPart + "0,-" + y2 + aPart + "-" + x + "," + y1 + "Z");
          }
        },
        "star-triangle-down": {
          n: 20,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x = round(r * sqrt3 * 0.8, 2);
            var y1 = round(r * 0.8, 2);
            var y2 = round(r * 1.6, 2);
            var rc = round(r * 4, 2);
            var aPart = "A " + rc + "," + rc + " 0 0 1 ";
            return align(angle, standoff, "M" + x + ",-" + y1 + aPart + "-" + x + ",-" + y1 + aPart + "0," + y2 + aPart + x + ",-" + y1 + "Z");
          }
        },
        "star-square": {
          n: 21,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rp = round(r * 1.1, 2);
            var rc = round(r * 2, 2);
            var aPart = "A " + rc + "," + rc + " 0 0 1 ";
            return align(angle, standoff, "M-" + rp + ",-" + rp + aPart + "-" + rp + "," + rp + aPart + rp + "," + rp + aPart + rp + ",-" + rp + aPart + "-" + rp + ",-" + rp + "Z");
          }
        },
        "star-diamond": {
          n: 22,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rp = round(r * 1.4, 2);
            var rc = round(r * 1.9, 2);
            var aPart = "A " + rc + "," + rc + " 0 0 1 ";
            return align(angle, standoff, "M-" + rp + ",0" + aPart + "0," + rp + aPart + rp + ",0" + aPart + "0,-" + rp + aPart + "-" + rp + ",0Z");
          }
        },
        "diamond-tall": {
          n: 23,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x = round(r * 0.7, 2);
            var y = round(r * 1.4, 2);
            return align(angle, standoff, "M0," + y + "L" + x + ",0L0,-" + y + "L-" + x + ",0Z");
          }
        },
        "diamond-wide": {
          n: 24,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x = round(r * 1.4, 2);
            var y = round(r * 0.7, 2);
            return align(angle, standoff, "M0," + y + "L" + x + ",0L0,-" + y + "L-" + x + ",0Z");
          }
        },
        hourglass: {
          n: 25,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            return align(angle, standoff, "M" + rs + "," + rs + "H-" + rs + "L" + rs + ",-" + rs + "H-" + rs + "Z");
          },
          noDot: true
        },
        bowtie: {
          n: 26,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            return align(angle, standoff, "M" + rs + "," + rs + "V-" + rs + "L-" + rs + "," + rs + "V-" + rs + "Z");
          },
          noDot: true
        },
        "circle-cross": {
          n: 27,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            return align(angle, standoff, "M0," + rs + "V-" + rs + "M" + rs + ",0H-" + rs + "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z");
          },
          needLine: true,
          noDot: true
        },
        "circle-x": {
          n: 28,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            var rc = round(r / sqrt2, 2);
            return align(angle, standoff, "M" + rc + "," + rc + "L-" + rc + ",-" + rc + "M" + rc + ",-" + rc + "L-" + rc + "," + rc + "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z");
          },
          needLine: true,
          noDot: true
        },
        "square-cross": {
          n: 29,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            return align(angle, standoff, "M0," + rs + "V-" + rs + "M" + rs + ",0H-" + rs + "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z");
          },
          needLine: true,
          noDot: true
        },
        "square-x": {
          n: 30,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rs = round(r, 2);
            return align(angle, standoff, "M" + rs + "," + rs + "L-" + rs + ",-" + rs + "M" + rs + ",-" + rs + "L-" + rs + "," + rs + "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z");
          },
          needLine: true,
          noDot: true
        },
        "diamond-cross": {
          n: 31,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rd = round(r * 1.3, 2);
            return align(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "ZM0,-" + rd + "V" + rd + "M-" + rd + ",0H" + rd);
          },
          needLine: true,
          noDot: true
        },
        "diamond-x": {
          n: 32,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rd = round(r * 1.3, 2);
            var r2 = round(r * 0.65, 2);
            return align(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "ZM-" + r2 + ",-" + r2 + "L" + r2 + "," + r2 + "M-" + r2 + "," + r2 + "L" + r2 + ",-" + r2);
          },
          needLine: true,
          noDot: true
        },
        "cross-thin": {
          n: 33,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rc = round(r * 1.4, 2);
            return align(angle, standoff, "M0," + rc + "V-" + rc + "M" + rc + ",0H-" + rc);
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "x-thin": {
          n: 34,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r, 2);
            return align(angle, standoff, "M" + rx + "," + rx + "L-" + rx + ",-" + rx + "M" + rx + ",-" + rx + "L-" + rx + "," + rx);
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        asterisk: {
          n: 35,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rc = round(r * 1.2, 2);
            var rs = round(r * 0.85, 2);
            return align(angle, standoff, "M0," + rc + "V-" + rc + "M" + rc + ",0H-" + rc + "M" + rs + "," + rs + "L-" + rs + ",-" + rs + "M" + rs + ",-" + rs + "L-" + rs + "," + rs);
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        hash: {
          n: 36,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var r1 = round(r / 2, 2);
            var r2 = round(r, 2);
            return align(angle, standoff, "M" + r1 + "," + r2 + "V-" + r2 + "M" + (r1 - r2) + ",-" + r2 + "V" + r2 + "M" + r2 + "," + r1 + "H-" + r2 + "M-" + r2 + "," + (r1 - r2) + "H" + r2);
          },
          needLine: true,
          noFill: true
        },
        "y-up": {
          n: 37,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x = round(r * 1.2, 2);
            var y0 = round(r * 1.6, 2);
            var y1 = round(r * 0.8, 2);
            return align(angle, standoff, "M-" + x + "," + y1 + "L0,0M" + x + "," + y1 + "L0,0M0,-" + y0 + "L0,0");
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "y-down": {
          n: 38,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var x = round(r * 1.2, 2);
            var y0 = round(r * 1.6, 2);
            var y1 = round(r * 0.8, 2);
            return align(angle, standoff, "M-" + x + ",-" + y1 + "L0,0M" + x + ",-" + y1 + "L0,0M0," + y0 + "L0,0");
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "y-left": {
          n: 39,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var y = round(r * 1.2, 2);
            var x0 = round(r * 1.6, 2);
            var x1 = round(r * 0.8, 2);
            return align(angle, standoff, "M" + x1 + "," + y + "L0,0M" + x1 + ",-" + y + "L0,0M-" + x0 + ",0L0,0");
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "y-right": {
          n: 40,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var y = round(r * 1.2, 2);
            var x0 = round(r * 1.6, 2);
            var x1 = round(r * 0.8, 2);
            return align(angle, standoff, "M-" + x1 + "," + y + "L0,0M-" + x1 + ",-" + y + "L0,0M" + x0 + ",0L0,0");
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "line-ew": {
          n: 41,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rc = round(r * 1.4, 2);
            return align(angle, standoff, "M" + rc + ",0H-" + rc);
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "line-ns": {
          n: 42,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rc = round(r * 1.4, 2);
            return align(angle, standoff, "M0," + rc + "V-" + rc);
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "line-ne": {
          n: 43,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r, 2);
            return align(angle, standoff, "M" + rx + ",-" + rx + "L-" + rx + "," + rx);
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "line-nw": {
          n: 44,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r, 2);
            return align(angle, standoff, "M" + rx + "," + rx + "L-" + rx + ",-" + rx);
          },
          needLine: true,
          noDot: true,
          noFill: true
        },
        "arrow-up": {
          n: 45,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r, 2);
            var ry = round(r * 2, 2);
            return align(angle, standoff, "M0,0L-" + rx + "," + ry + "H" + rx + "Z");
          },
          backoff: 1,
          noDot: true
        },
        "arrow-down": {
          n: 46,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r, 2);
            var ry = round(r * 2, 2);
            return align(angle, standoff, "M0,0L-" + rx + ",-" + ry + "H" + rx + "Z");
          },
          noDot: true
        },
        "arrow-left": {
          n: 47,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r * 2, 2);
            var ry = round(r, 2);
            return align(angle, standoff, "M0,0L" + rx + ",-" + ry + "V" + ry + "Z");
          },
          noDot: true
        },
        "arrow-right": {
          n: 48,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r * 2, 2);
            var ry = round(r, 2);
            return align(angle, standoff, "M0,0L-" + rx + ",-" + ry + "V" + ry + "Z");
          },
          noDot: true
        },
        "arrow-bar-up": {
          n: 49,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r, 2);
            var ry = round(r * 2, 2);
            return align(angle, standoff, "M-" + rx + ",0H" + rx + "M0,0L-" + rx + "," + ry + "H" + rx + "Z");
          },
          backoff: 1,
          needLine: true,
          noDot: true
        },
        "arrow-bar-down": {
          n: 50,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r, 2);
            var ry = round(r * 2, 2);
            return align(angle, standoff, "M-" + rx + ",0H" + rx + "M0,0L-" + rx + ",-" + ry + "H" + rx + "Z");
          },
          needLine: true,
          noDot: true
        },
        "arrow-bar-left": {
          n: 51,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r * 2, 2);
            var ry = round(r, 2);
            return align(angle, standoff, "M0,-" + ry + "V" + ry + "M0,0L" + rx + ",-" + ry + "V" + ry + "Z");
          },
          needLine: true,
          noDot: true
        },
        "arrow-bar-right": {
          n: 52,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var rx = round(r * 2, 2);
            var ry = round(r, 2);
            return align(angle, standoff, "M0,-" + ry + "V" + ry + "M0,0L-" + rx + ",-" + ry + "V" + ry + "Z");
          },
          needLine: true,
          noDot: true
        },
        arrow: {
          n: 53,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var headAngle = PI / 2.5;
            var x = 2 * r * cos(headAngle);
            var y = 2 * r * sin(headAngle);
            return align(
              angle,
              standoff,
              "M0,0L" + -x + "," + y + "L" + x + "," + y + "Z"
            );
          },
          backoff: 0.9,
          noDot: true
        },
        "arrow-wide": {
          n: 54,
          f: function(r, angle, standoff) {
            if (skipAngle(angle)) return emptyPath;
            var headAngle = PI / 4;
            var x = 2 * r * cos(headAngle);
            var y = 2 * r * sin(headAngle);
            return align(
              angle,
              standoff,
              "M0,0L" + -x + "," + y + "A " + 2 * r + "," + 2 * r + " 0 0 1 " + x + "," + y + "Z"
            );
          },
          backoff: 0.4,
          noDot: true
        }
      };
      function skipAngle(angle) {
        return angle === null;
      }
      var lastPathIn;
      var lastPathOut;
      var lastAngle;
      var lastStandoff;
      function align(angle, standoff, path) {
        if ((!angle || angle % 360 === 0) && !standoff) return path;
        if (lastAngle === angle && lastStandoff === standoff && lastPathIn === path) return lastPathOut;
        lastAngle = angle;
        lastStandoff = standoff;
        lastPathIn = path;
        function rotate(t4, xy) {
          var cosT = cos(t4);
          var sinT = sin(t4);
          var x2 = xy[0];
          var y2 = xy[1] + (standoff || 0);
          return [
            x2 * cosT - y2 * sinT,
            x2 * sinT + y2 * cosT
          ];
        }
        var t = angle / 180 * PI;
        var x = 0;
        var y = 0;
        var cmd = parseSvgPath(path);
        var str = "";
        for (var i = 0; i < cmd.length; i++) {
          var cmdI = cmd[i];
          var op = cmdI[0];
          var x0 = x;
          var y0 = y;
          if (op === "M" || op === "L") {
            x = +cmdI[1];
            y = +cmdI[2];
          } else if (op === "m" || op === "l") {
            x += +cmdI[1];
            y += +cmdI[2];
          } else if (op === "H") {
            x = +cmdI[1];
          } else if (op === "h") {
            x += +cmdI[1];
          } else if (op === "V") {
            y = +cmdI[1];
          } else if (op === "v") {
            y += +cmdI[1];
          } else if (op === "A") {
            x = +cmdI[1];
            y = +cmdI[2];
            var E2 = rotate(t, [+cmdI[6], +cmdI[7]]);
            cmdI[6] = E2[0];
            cmdI[7] = E2[1];
            cmdI[3] = +cmdI[3] + angle;
          }
          if (op === "H" || op === "V") op = "L";
          if (op === "h" || op === "v") op = "l";
          if (op === "m" || op === "l") {
            x -= x0;
            y -= y0;
          }
          var B2 = rotate(t, [x, y]);
          if (op === "H" || op === "V") op = "L";
          if (op === "M" || op === "L" || op === "m" || op === "l") {
            cmdI[1] = B2[0];
            cmdI[2] = B2[1];
          }
          cmdI[0] = op;
          str += cmdI[0] + cmdI.slice(1).join(",");
        }
        lastPathOut = str;
        return str;
      }
    }
  });

  // src/components/drawing/index.js
  var require_drawing = __commonJS({
    "src/components/drawing/index.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var numberFormat = Lib.numberFormat;
      var isNumeric = require_fast_isnumeric();
      var tinycolor = require_tinycolor();
      var Registry = require_registry();
      var Color2 = require_color();
      var Colorscale = require_colorscale();
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var xmlnsNamespaces = require_xmlns_namespaces();
      var alignment = require_alignment();
      var LINE_SPACING = alignment.LINE_SPACING;
      var DESELECTDIM = require_interactions().DESELECTDIM;
      var subTypes = require_subtypes();
      var makeBubbleSizeFn = require_make_bubble_size_func();
      var appendArrayPointValue = require_helpers2().appendArrayPointValue;
      var drawing = module.exports = {};
      drawing.font = function(s, font) {
        var variant = font.variant;
        var style = font.style;
        var weight = font.weight;
        var color2 = font.color;
        var size = font.size;
        var family = font.family;
        var shadow = font.shadow;
        var lineposition = font.lineposition;
        var textcase = font.textcase;
        if (family) s.style("font-family", family);
        if (size + 1) s.style("font-size", size + "px");
        if (color2) s.call(Color2.fill, color2);
        if (weight) s.style("font-weight", weight);
        if (style) s.style("font-style", style);
        if (variant) s.style("font-variant", variant);
        if (textcase) s.style("text-transform", dropNone(textcase2transform(textcase)));
        if (shadow)
          s.style(
            "text-shadow",
            shadow === "auto" ? svgTextUtils.makeTextShadow(Color2.contrast(color2)) : dropNone(shadow)
          );
        if (lineposition) s.style("text-decoration-line", dropNone(lineposition2decorationLine(lineposition)));
      };
      function dropNone(a) {
        return a === "none" ? void 0 : a;
      }
      var textcase2transformOptions = {
        normal: "none",
        lower: "lowercase",
        upper: "uppercase",
        "word caps": "capitalize"
      };
      function textcase2transform(textcase) {
        return textcase2transformOptions[textcase];
      }
      function lineposition2decorationLine(lineposition) {
        return lineposition.replace("under", "underline").replace("over", "overline").replace("through", "line-through").split("+").join(" ");
      }
      drawing.setPosition = function(s, x, y) {
        s.attr("x", x).attr("y", y);
      };
      drawing.setSize = function(s, w, h) {
        s.attr("width", w).attr("height", h);
      };
      drawing.setRect = function(s, x, y, w, h) {
        s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h);
      };
      drawing.translatePoint = function(d, sel, xa, ya) {
        var x = xa.c2p(d.x);
        var y = ya.c2p(d.y);
        if (isNumeric(x) && isNumeric(y) && sel.node()) {
          if (sel.node().nodeName === "text") {
            sel.attr("x", x).attr("y", y);
          } else {
            sel.attr("transform", strTranslate(x, y));
          }
        } else {
          return false;
        }
        return true;
      };
      drawing.translatePoints = function(s, xa, ya) {
        s.each(function(d) {
          var sel = d3.select(this);
          drawing.translatePoint(d, sel, xa, ya);
        });
      };
      drawing.hideOutsideRangePoint = function(d, sel, xa, ya, xcalendar, ycalendar) {
        sel.attr("display", xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar) ? null : "none");
      };
      drawing.hideOutsideRangePoints = function(traceGroups, subplot) {
        if (!subplot._hasClipOnAxisFalse) return;
        var xa = subplot.xaxis;
        var ya = subplot.yaxis;
        traceGroups.each(function(d) {
          var trace = d[0].trace;
          var xcalendar = trace.xcalendar;
          var ycalendar = trace.ycalendar;
          var selector = Registry.traceIs(trace, "bar-like") ? ".bartext" : ".point,.textpoint";
          traceGroups.selectAll(selector).each(function(d2) {
            drawing.hideOutsideRangePoint(d2, d3.select(this), xa, ya, xcalendar, ycalendar);
          });
        });
      };
      drawing.crispRound = function(gd, lineWidth, dflt) {
        if (!lineWidth || !isNumeric(lineWidth)) return dflt || 0;
        if (gd._context.staticPlot) return lineWidth;
        if (lineWidth < 1) return 1;
        return Math.round(lineWidth);
      };
      drawing.singleLineStyle = function(d, s, lw, lc, ld) {
        s.style("fill", "none");
        var line = (((d || [])[0] || {}).trace || {}).line || {};
        var lw1 = lw || line.width || 0;
        var dash = ld || line.dash || "";
        Color2.stroke(s, lc || line.color);
        drawing.dashLine(s, dash, lw1);
      };
      drawing.lineGroupStyle = function(s, lw, lc, ld) {
        s.style("fill", "none").each(function(d) {
          var line = (((d || [])[0] || {}).trace || {}).line || {};
          var lw1 = lw || line.width || 0;
          var dash = ld || line.dash || "";
          d3.select(this).call(Color2.stroke, lc || line.color).call(drawing.dashLine, dash, lw1);
        });
      };
      drawing.dashLine = function(s, dash, lineWidth) {
        lineWidth = +lineWidth || 0;
        dash = drawing.dashStyle(dash, lineWidth);
        s.style({
          "stroke-dasharray": dash,
          "stroke-width": lineWidth + "px"
        });
      };
      drawing.dashStyle = function(dash, lineWidth) {
        lineWidth = +lineWidth || 1;
        var dlw = Math.max(lineWidth, 3);
        if (dash === "solid") dash = "";
        else if (dash === "dot") dash = dlw + "px," + dlw + "px";
        else if (dash === "dash") dash = 3 * dlw + "px," + 3 * dlw + "px";
        else if (dash === "longdash") dash = 5 * dlw + "px," + 5 * dlw + "px";
        else if (dash === "dashdot") {
          dash = 3 * dlw + "px," + dlw + "px," + dlw + "px," + dlw + "px";
        } else if (dash === "longdashdot") {
          dash = 5 * dlw + "px," + 2 * dlw + "px," + dlw + "px," + 2 * dlw + "px";
        }
        return dash;
      };
      function setFillStyle(sel, trace, gd, forLegend) {
        var markerPattern = trace.fillpattern;
        var fillgradient = trace.fillgradient;
        var pAttr = drawing.getPatternAttr;
        var patternShape = markerPattern && (pAttr(markerPattern.shape, 0, "") || pAttr(markerPattern.path, 0, ""));
        if (patternShape) {
          var patternBGColor = pAttr(markerPattern.bgcolor, 0, null);
          var patternFGColor = pAttr(markerPattern.fgcolor, 0, null);
          var patternFGOpacity = markerPattern.fgopacity;
          var patternSize = pAttr(markerPattern.size, 0, 8);
          var patternSolidity = pAttr(markerPattern.solidity, 0, 0.3);
          var patternID = trace.uid;
          drawing.pattern(
            sel,
            "point",
            gd,
            patternID,
            patternShape,
            patternSize,
            patternSolidity,
            void 0,
            markerPattern.fillmode,
            patternBGColor,
            patternFGColor,
            patternFGOpacity
          );
        } else if (fillgradient && fillgradient.type !== "none") {
          var direction = fillgradient.type;
          var gradientID = "scatterfill-" + trace.uid;
          if (forLegend) {
            gradientID = "legendfill-" + trace.uid;
          }
          if (!forLegend && (fillgradient.start !== void 0 || fillgradient.stop !== void 0)) {
            var start, stop;
            if (direction === "horizontal") {
              start = {
                x: fillgradient.start,
                y: 0
              };
              stop = {
                x: fillgradient.stop,
                y: 0
              };
            } else if (direction === "vertical") {
              start = {
                x: 0,
                y: fillgradient.start
              };
              stop = {
                x: 0,
                y: fillgradient.stop
              };
            }
            start.x = trace._xA.c2p(start.x === void 0 ? trace._extremes.x.min[0].val : start.x, true);
            start.y = trace._yA.c2p(start.y === void 0 ? trace._extremes.y.min[0].val : start.y, true);
            stop.x = trace._xA.c2p(stop.x === void 0 ? trace._extremes.x.max[0].val : stop.x, true);
            stop.y = trace._yA.c2p(stop.y === void 0 ? trace._extremes.y.max[0].val : stop.y, true);
            sel.call(
              gradientWithBounds,
              gd,
              gradientID,
              "linear",
              fillgradient.colorscale,
              "fill",
              start,
              stop,
              true,
              false
            );
          } else {
            if (direction === "horizontal") {
              direction = direction + "reversed";
            }
            sel.call(drawing.gradient, gd, gradientID, direction, fillgradient.colorscale, "fill");
          }
        } else if (trace.fillcolor) {
          sel.call(Color2.fill, trace.fillcolor);
        }
      }
      drawing.singleFillStyle = function(sel, gd) {
        var node = d3.select(sel.node());
        var data = node.data();
        var trace = ((data[0] || [])[0] || {}).trace || {};
        setFillStyle(sel, trace, gd, false);
      };
      drawing.fillGroupStyle = function(s, gd, forLegend) {
        s.style("stroke-width", 0).each(function(d) {
          var shape = d3.select(this);
          if (d[0].trace) {
            setFillStyle(shape, d[0].trace, gd, forLegend);
          }
        });
      };
      var SYMBOLDEFS = require_symbol_defs();
      drawing.symbolNames = [];
      drawing.symbolFuncs = [];
      drawing.symbolBackOffs = [];
      drawing.symbolNeedLines = {};
      drawing.symbolNoDot = {};
      drawing.symbolNoFill = {};
      drawing.symbolList = [];
      Object.keys(SYMBOLDEFS).forEach(function(k) {
        var symDef = SYMBOLDEFS[k];
        var n = symDef.n;
        drawing.symbolList.push(
          n,
          String(n),
          k,
          n + 100,
          String(n + 100),
          k + "-open"
        );
        drawing.symbolNames[n] = k;
        drawing.symbolFuncs[n] = symDef.f;
        drawing.symbolBackOffs[n] = symDef.backoff || 0;
        if (symDef.needLine) {
          drawing.symbolNeedLines[n] = true;
        }
        if (symDef.noDot) {
          drawing.symbolNoDot[n] = true;
        } else {
          drawing.symbolList.push(
            n + 200,
            String(n + 200),
            k + "-dot",
            n + 300,
            String(n + 300),
            k + "-open-dot"
          );
        }
        if (symDef.noFill) {
          drawing.symbolNoFill[n] = true;
        }
      });
      var MAXSYMBOL = drawing.symbolNames.length;
      var DOTPATH = "M0,0.5L0.5,0L0,-0.5L-0.5,0Z";
      drawing.symbolNumber = function(v) {
        if (isNumeric(v)) {
          v = +v;
        } else if (typeof v === "string") {
          var vbase = 0;
          if (v.indexOf("-open") > 0) {
            vbase = 100;
            v = v.replace("-open", "");
          }
          if (v.indexOf("-dot") > 0) {
            vbase += 200;
            v = v.replace("-dot", "");
          }
          v = drawing.symbolNames.indexOf(v);
          if (v >= 0) {
            v += vbase;
          }
        }
        return v % 100 >= MAXSYMBOL || v >= 400 ? 0 : Math.floor(Math.max(v, 0));
      };
      function makePointPath(symbolNumber, r, t, s) {
        var base = symbolNumber % 100;
        return drawing.symbolFuncs[base](r, t, s) + (symbolNumber >= 200 ? DOTPATH : "");
      }
      var stopFormatter = numberFormat("~f");
      var gradientInfo = {
        radial: { type: "radial" },
        radialreversed: { type: "radial", reversed: true },
        horizontal: { type: "linear", start: { x: 1, y: 0 }, stop: { x: 0, y: 0 } },
        horizontalreversed: { type: "linear", start: { x: 1, y: 0 }, stop: { x: 0, y: 0 }, reversed: true },
        vertical: { type: "linear", start: { x: 0, y: 1 }, stop: { x: 0, y: 0 } },
        verticalreversed: { type: "linear", start: { x: 0, y: 1 }, stop: { x: 0, y: 0 }, reversed: true }
      };
      drawing.gradient = function(sel, gd, gradientID, type, colorscale, prop) {
        var info = gradientInfo[type];
        return gradientWithBounds(
          sel,
          gd,
          gradientID,
          info.type,
          colorscale,
          prop,
          info.start,
          info.stop,
          false,
          info.reversed
        );
      };
      function gradientWithBounds(sel, gd, gradientID, type, colorscale, prop, start, stop, inUserSpace, reversed) {
        var len = colorscale.length;
        var info;
        if (type === "linear") {
          info = {
            node: "linearGradient",
            attrs: {
              x1: start.x,
              y1: start.y,
              x2: stop.x,
              y2: stop.y,
              gradientUnits: inUserSpace ? "userSpaceOnUse" : "objectBoundingBox"
            },
            reversed
          };
        } else if (type === "radial") {
          info = {
            node: "radialGradient",
            reversed
          };
        }
        var colorStops = new Array(len);
        for (var i = 0; i < len; i++) {
          if (info.reversed) {
            colorStops[len - 1 - i] = [stopFormatter((1 - colorscale[i][0]) * 100), colorscale[i][1]];
          } else {
            colorStops[i] = [stopFormatter(colorscale[i][0] * 100), colorscale[i][1]];
          }
        }
        var fullLayout = gd._fullLayout;
        var fullID = "g" + fullLayout._uid + "-" + gradientID;
        var gradient = fullLayout._defs.select(".gradients").selectAll("#" + fullID).data([type + colorStops.join(";")], Lib.identity);
        gradient.exit().remove();
        gradient.enter().append(info.node).each(function() {
          var el = d3.select(this);
          if (info.attrs) el.attr(info.attrs);
          el.attr("id", fullID);
          var stops = el.selectAll("stop").data(colorStops);
          stops.exit().remove();
          stops.enter().append("stop");
          stops.each(function(d) {
            var tc = tinycolor(d[1]);
            d3.select(this).attr({
              offset: d[0] + "%",
              "stop-color": Color2.tinyRGB(tc),
              "stop-opacity": tc.getAlpha()
            });
          });
        });
        sel.style(prop, getFullUrl(fullID, gd)).style(prop + "-opacity", null);
        sel.classed("gradient_filled", true);
      }
      drawing.pattern = function(sel, calledBy, gd, patternID, shape, size, solidity, mcc, fillmode, bgcolor, fgcolor, fgopacity) {
        var isLegend = calledBy === "legend";
        if (mcc) {
          if (fillmode === "overlay") {
            bgcolor = mcc;
            fgcolor = Color2.contrast(bgcolor);
          } else {
            bgcolor = void 0;
            fgcolor = mcc;
          }
        }
        var fullLayout = gd._fullLayout;
        var fullID = "p" + fullLayout._uid + "-" + patternID;
        var width, height;
        var linearFn = function(x, x0, x1, y0, y1) {
          return y0 + (y1 - y0) * (x - x0) / (x1 - x0);
        };
        var path, linewidth, radius;
        var patternTag;
        var patternAttrs = {};
        var fgC = tinycolor(fgcolor);
        var fgRGB = Color2.tinyRGB(fgC);
        var fgAlpha = fgC.getAlpha();
        var opacity = fgopacity * fgAlpha;
        switch (shape) {
          case "/":
            width = size * Math.sqrt(2);
            height = size * Math.sqrt(2);
            path = "M-" + width / 4 + "," + height / 4 + "l" + width / 2 + ",-" + height / 2 + "M0," + height + "L" + width + ",0M" + width / 4 * 3 + "," + height / 4 * 5 + "l" + width / 2 + ",-" + height / 2;
            linewidth = solidity * size;
            patternTag = "path";
            patternAttrs = {
              d: path,
              opacity,
              stroke: fgRGB,
              "stroke-width": linewidth + "px"
            };
            break;
          case "\\":
            width = size * Math.sqrt(2);
            height = size * Math.sqrt(2);
            path = "M" + width / 4 * 3 + ",-" + height / 4 + "l" + width / 2 + "," + height / 2 + "M0,0L" + width + "," + height + "M-" + width / 4 + "," + height / 4 * 3 + "l" + width / 2 + "," + height / 2;
            linewidth = solidity * size;
            patternTag = "path";
            patternAttrs = {
              d: path,
              opacity,
              stroke: fgRGB,
              "stroke-width": linewidth + "px"
            };
            break;
          case "x":
            width = size * Math.sqrt(2);
            height = size * Math.sqrt(2);
            path = "M-" + width / 4 + "," + height / 4 + "l" + width / 2 + ",-" + height / 2 + "M0," + height + "L" + width + ",0M" + width / 4 * 3 + "," + height / 4 * 5 + "l" + width / 2 + ",-" + height / 2 + "M" + width / 4 * 3 + ",-" + height / 4 + "l" + width / 2 + "," + height / 2 + "M0,0L" + width + "," + height + "M-" + width / 4 + "," + height / 4 * 3 + "l" + width / 2 + "," + height / 2;
            linewidth = size - size * Math.sqrt(1 - solidity);
            patternTag = "path";
            patternAttrs = {
              d: path,
              opacity,
              stroke: fgRGB,
              "stroke-width": linewidth + "px"
            };
            break;
          case "|":
            width = size;
            height = size;
            patternTag = "path";
            path = "M" + width / 2 + ",0L" + width / 2 + "," + height;
            linewidth = solidity * size;
            patternTag = "path";
            patternAttrs = {
              d: path,
              opacity,
              stroke: fgRGB,
              "stroke-width": linewidth + "px"
            };
            break;
          case "-":
            width = size;
            height = size;
            patternTag = "path";
            path = "M0," + height / 2 + "L" + width + "," + height / 2;
            linewidth = solidity * size;
            patternTag = "path";
            patternAttrs = {
              d: path,
              opacity,
              stroke: fgRGB,
              "stroke-width": linewidth + "px"
            };
            break;
          case "+":
            width = size;
            height = size;
            patternTag = "path";
            path = "M" + width / 2 + ",0L" + width / 2 + "," + height + "M0," + height / 2 + "L" + width + "," + height / 2;
            linewidth = size - size * Math.sqrt(1 - solidity);
            patternTag = "path";
            patternAttrs = {
              d: path,
              opacity,
              stroke: fgRGB,
              "stroke-width": linewidth + "px"
            };
            break;
          case ".":
            width = size;
            height = size;
            if (solidity < Math.PI / 4) {
              radius = Math.sqrt(solidity * size * size / Math.PI);
            } else {
              radius = linearFn(solidity, Math.PI / 4, 1, size / 2, size / Math.sqrt(2));
            }
            patternTag = "circle";
            patternAttrs = {
              cx: width / 2,
              cy: height / 2,
              r: radius,
              opacity,
              fill: fgRGB
            };
            break;
          default:
            width = size;
            height = size;
            patternTag = "path";
            patternAttrs = {
              d: shape,
              opacity,
              fill: fgRGB
            };
            break;
        }
        var str = [shape || "noSh", bgcolor || "noBg", fgcolor || "noFg", size, solidity].join(";");
        var pattern = fullLayout._defs.select(".patterns").selectAll("#" + fullID).data([str], Lib.identity);
        pattern.exit().remove();
        pattern.enter().append("pattern").each(function() {
          var el = d3.select(this);
          el.attr({
            id: fullID,
            width: width + "px",
            height: height + "px",
            patternUnits: "userSpaceOnUse",
            // for legends scale down patterns just a bit so that default size (i.e 8) nicely fit in small icons
            patternTransform: isLegend ? "scale(0.8)" : ""
          });
          if (bgcolor) {
            var bgC = tinycolor(bgcolor);
            var bgRGB = Color2.tinyRGB(bgC);
            var bgAlpha = bgC.getAlpha();
            var rects = el.selectAll("rect").data([0]);
            rects.exit().remove();
            rects.enter().append("rect").attr({
              width: width + "px",
              height: height + "px",
              fill: bgRGB,
              "fill-opacity": bgAlpha
            });
          }
          var patterns = el.selectAll(patternTag).data([0]);
          patterns.exit().remove();
          patterns.enter().append(patternTag).attr(patternAttrs);
        });
        sel.style("fill", getFullUrl(fullID, gd)).style("fill-opacity", null);
        sel.classed("pattern_filled", true);
      };
      drawing.initGradients = function(gd) {
        var fullLayout = gd._fullLayout;
        var gradientsGroup = Lib.ensureSingle(fullLayout._defs, "g", "gradients");
        gradientsGroup.selectAll("linearGradient,radialGradient").remove();
        d3.select(gd).selectAll(".gradient_filled").classed("gradient_filled", false);
      };
      drawing.initPatterns = function(gd) {
        var fullLayout = gd._fullLayout;
        var patternsGroup = Lib.ensureSingle(fullLayout._defs, "g", "patterns");
        patternsGroup.selectAll("pattern").remove();
        d3.select(gd).selectAll(".pattern_filled").classed("pattern_filled", false);
      };
      drawing.getPatternAttr = function(mp, i, dflt) {
        if (mp && Lib.isArrayOrTypedArray(mp)) {
          return i < mp.length ? mp[i] : dflt;
        }
        return mp;
      };
      drawing.pointStyle = function(s, trace, gd, pt) {
        if (!s.size()) return;
        var fns = drawing.makePointStyleFns(trace);
        s.each(function(d) {
          drawing.singlePointStyle(d, d3.select(this), trace, fns, gd, pt);
        });
      };
      drawing.singlePointStyle = function(d, sel, trace, fns, gd, pt) {
        var marker = trace.marker;
        var markerLine = marker.line;
        if (pt && pt.i >= 0 && d.i === void 0) d.i = pt.i;
        sel.style("opacity", fns.selectedOpacityFn ? fns.selectedOpacityFn(d) : d.mo === void 0 ? marker.opacity : d.mo);
        if (fns.ms2mrc) {
          var r;
          if (d.ms === "various" || marker.size === "various") {
            r = 3;
          } else {
            r = fns.ms2mrc(d.ms);
          }
          d.mrc = r;
          if (fns.selectedSizeFn) {
            r = d.mrc = fns.selectedSizeFn(d);
          }
          var x = drawing.symbolNumber(d.mx || marker.symbol) || 0;
          d.om = x % 200 >= 100;
          var angle = getMarkerAngle(d, trace);
          var standoff = getMarkerStandoff(d, trace);
          sel.attr("d", makePointPath(x, r, angle, standoff));
        }
        var perPointGradient = false;
        var fillColor, lineColor, lineWidth;
        if (d.so) {
          lineWidth = markerLine.outlierwidth;
          lineColor = markerLine.outliercolor;
          fillColor = marker.outliercolor;
        } else {
          var markerLineWidth = (markerLine || {}).width;
          lineWidth = (d.mlw + 1 || markerLineWidth + 1 || // TODO: we need the latter for legends... can we get rid of it?
          (d.trace ? (d.trace.marker.line || {}).width : 0) + 1) - 1 || 0;
          if ("mlc" in d) lineColor = d.mlcc = fns.lineScale(d.mlc);
          else if (Lib.isArrayOrTypedArray(markerLine.color)) lineColor = Color2.defaultLine;
          else lineColor = markerLine.color;
          if (Lib.isArrayOrTypedArray(marker.color)) {
            fillColor = Color2.defaultLine;
            perPointGradient = true;
          }
          if ("mc" in d) {
            fillColor = d.mcc = fns.markerScale(d.mc);
          } else {
            fillColor = marker.color || marker.colors || "rgba(0,0,0,0)";
          }
          if (fns.selectedColorFn) {
            fillColor = fns.selectedColorFn(d);
          }
        }
        const lineDash = d.mld || (markerLine || {}).dash;
        if (lineDash) drawing.dashLine(sel, lineDash, lineWidth);
        if (d.om) {
          sel.call(Color2.stroke, fillColor).style({
            "stroke-width": (lineWidth || 1) + "px",
            fill: "none"
          });
        } else {
          sel.style("stroke-width", (d.isBlank ? 0 : lineWidth) + "px");
          var markerGradient = marker.gradient;
          var gradientType = d.mgt;
          if (gradientType) perPointGradient = true;
          else gradientType = markerGradient && markerGradient.type;
          if (Lib.isArrayOrTypedArray(gradientType)) {
            gradientType = gradientType[0];
            if (!gradientInfo[gradientType]) gradientType = 0;
          }
          var markerPattern = marker.pattern;
          var pAttr = drawing.getPatternAttr;
          var patternShape = markerPattern && (pAttr(markerPattern.shape, d.i, "") || pAttr(markerPattern.path, d.i, ""));
          if (gradientType && gradientType !== "none") {
            var gradientColor = d.mgc;
            if (gradientColor) perPointGradient = true;
            else gradientColor = markerGradient.color;
            var gradientID = trace.uid;
            if (perPointGradient) gradientID += "-" + d.i;
            drawing.gradient(
              sel,
              gd,
              gradientID,
              gradientType,
              [
                [0, gradientColor],
                [1, fillColor]
              ],
              "fill"
            );
          } else if (patternShape) {
            var perPointPattern = false;
            var fgcolor = markerPattern.fgcolor;
            if (!fgcolor && pt && pt.color) {
              fgcolor = pt.color;
              perPointPattern = true;
            }
            var patternFGColor = pAttr(fgcolor, d.i, pt && pt.color || null);
            var patternBGColor = pAttr(markerPattern.bgcolor, d.i, null);
            var patternFGOpacity = markerPattern.fgopacity;
            var patternSize = pAttr(markerPattern.size, d.i, 8);
            var patternSolidity = pAttr(markerPattern.solidity, d.i, 0.3);
            perPointPattern = perPointPattern || d.mcc || Lib.isArrayOrTypedArray(markerPattern.shape) || Lib.isArrayOrTypedArray(markerPattern.path) || Lib.isArrayOrTypedArray(markerPattern.bgcolor) || Lib.isArrayOrTypedArray(markerPattern.fgcolor) || Lib.isArrayOrTypedArray(markerPattern.size) || Lib.isArrayOrTypedArray(markerPattern.solidity);
            var patternID = trace.uid;
            if (perPointPattern) patternID += "-" + d.i;
            drawing.pattern(
              sel,
              "point",
              gd,
              patternID,
              patternShape,
              patternSize,
              patternSolidity,
              d.mcc,
              markerPattern.fillmode,
              patternBGColor,
              patternFGColor,
              patternFGOpacity
            );
          } else {
            Lib.isArrayOrTypedArray(fillColor) ? Color2.fill(sel, fillColor[d.i]) : Color2.fill(sel, fillColor);
          }
          if (lineWidth) {
            Color2.stroke(sel, lineColor);
          }
        }
      };
      drawing.makePointStyleFns = function(trace) {
        var out = {};
        var marker = trace.marker;
        out.markerScale = drawing.tryColorscale(marker, "");
        out.lineScale = drawing.tryColorscale(marker, "line");
        if (Registry.traceIs(trace, "symbols")) {
          out.ms2mrc = subTypes.isBubble(trace) ? makeBubbleSizeFn(trace) : function() {
            return (marker.size || 6) / 2;
          };
        }
        if (trace.selectedpoints) {
          Lib.extendFlat(out, drawing.makeSelectedPointStyleFns(trace));
        }
        return out;
      };
      drawing.makeSelectedPointStyleFns = function(trace) {
        var out = {};
        var selectedAttrs = trace.selected || {};
        var unselectedAttrs = trace.unselected || {};
        var marker = trace.marker || {};
        var selectedMarker = selectedAttrs.marker || {};
        var unselectedMarker = unselectedAttrs.marker || {};
        var mo = marker.opacity;
        var smo = selectedMarker.opacity;
        var usmo = unselectedMarker.opacity;
        var smoIsDefined = smo !== void 0;
        var usmoIsDefined = usmo !== void 0;
        if (Lib.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) {
          out.selectedOpacityFn = function(d) {
            var base = d.mo === void 0 ? marker.opacity : d.mo;
            if (d.selected) {
              return smoIsDefined ? smo : base;
            } else {
              return usmoIsDefined ? usmo : DESELECTDIM * base;
            }
          };
        }
        var mc = marker.color;
        var smc = selectedMarker.color;
        var usmc = unselectedMarker.color;
        if (smc || usmc) {
          out.selectedColorFn = function(d) {
            var base = d.mcc || mc;
            if (d.selected) {
              return smc || base;
            } else {
              return usmc || base;
            }
          };
        }
        var ms = marker.size;
        var sms = selectedMarker.size;
        var usms = unselectedMarker.size;
        var smsIsDefined = sms !== void 0;
        var usmsIsDefined = usms !== void 0;
        if (Registry.traceIs(trace, "symbols") && (smsIsDefined || usmsIsDefined)) {
          out.selectedSizeFn = function(d) {
            var base = d.mrc || ms / 2;
            if (d.selected) {
              return smsIsDefined ? sms / 2 : base;
            } else {
              return usmsIsDefined ? usms / 2 : base;
            }
          };
        }
        return out;
      };
      drawing.makeSelectedTextStyleFns = function(trace) {
        var out = {};
        var selectedAttrs = trace.selected || {};
        var unselectedAttrs = trace.unselected || {};
        var textFont = trace.textfont || {};
        var selectedTextFont = selectedAttrs.textfont || {};
        var unselectedTextFont = unselectedAttrs.textfont || {};
        var tc = textFont.color;
        var stc = selectedTextFont.color;
        var utc = unselectedTextFont.color;
        out.selectedTextColorFn = function(d) {
          var base = d.tc || tc;
          if (d.selected) {
            return stc || base;
          } else {
            if (utc) return utc;
            else return stc ? base : Color2.addOpacity(base, DESELECTDIM);
          }
        };
        return out;
      };
      drawing.selectedPointStyle = function(s, trace) {
        if (!s.size() || !trace.selectedpoints) return;
        var fns = drawing.makeSelectedPointStyleFns(trace);
        var marker = trace.marker || {};
        var seq = [];
        if (fns.selectedOpacityFn) {
          seq.push(function(pt, d) {
            pt.style("opacity", fns.selectedOpacityFn(d));
          });
        }
        if (fns.selectedColorFn) {
          seq.push(function(pt, d) {
            Color2.fill(pt, fns.selectedColorFn(d));
          });
        }
        if (fns.selectedSizeFn) {
          seq.push(function(pt, d) {
            var mx = d.mx || marker.symbol || 0;
            var mrc2 = fns.selectedSizeFn(d);
            pt.attr(
              "d",
              makePointPath(drawing.symbolNumber(mx), mrc2, getMarkerAngle(d, trace), getMarkerStandoff(d, trace))
            );
            d.mrc2 = mrc2;
          });
        }
        if (seq.length) {
          s.each(function(d) {
            var pt = d3.select(this);
            for (var i = 0; i < seq.length; i++) {
              seq[i](pt, d);
            }
          });
        }
      };
      drawing.tryColorscale = function(marker, prefix) {
        var cont = prefix ? Lib.nestedProperty(marker, prefix).get() : marker;
        if (cont) {
          var colorArray = cont.color;
          if ((cont.colorscale || cont._colorAx) && Lib.isArrayOrTypedArray(colorArray)) {
            return Colorscale.makeColorScaleFuncFromTrace(cont);
          }
        }
        return Lib.identity;
      };
      var TEXTOFFSETSIGN = {
        start: 1,
        end: -1,
        middle: 0,
        bottom: 1,
        top: -1
      };
      function textPointPosition(s, textPosition, fontSize, markerRadius, dontTouchParent) {
        var group = d3.select(s.node().parentNode);
        var v = textPosition.indexOf("top") !== -1 ? "top" : textPosition.indexOf("bottom") !== -1 ? "bottom" : "middle";
        var h = textPosition.indexOf("left") !== -1 ? "end" : textPosition.indexOf("right") !== -1 ? "start" : "middle";
        var r = markerRadius ? markerRadius / 0.8 + 1 : 0;
        var numLines = (svgTextUtils.lineCount(s) - 1) * LINE_SPACING + 1;
        var dx = TEXTOFFSETSIGN[h] * r;
        var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2;
        s.attr("text-anchor", h);
        if (!dontTouchParent) {
          group.attr("transform", strTranslate(dx, dy));
        }
      }
      function extracTextFontSize(d, trace) {
        var fontSize = d.ts || trace.textfont.size;
        return isNumeric(fontSize) && fontSize > 0 ? fontSize : 0;
      }
      drawing.textPointStyle = function(s, trace, gd) {
        if (!s.size()) return;
        var selectedTextColorFn;
        if (trace.selectedpoints) {
          var fns = drawing.makeSelectedTextStyleFns(trace);
          selectedTextColorFn = fns.selectedTextColorFn;
        }
        var texttemplate = trace.texttemplate;
        var fullLayout = gd._fullLayout;
        s.each(function(d) {
          var p = d3.select(this);
          var text = texttemplate ? Lib.extractOption(d, trace, "txt", "texttemplate") : Lib.extractOption(d, trace, "tx", "text");
          if (!text && text !== 0) {
            p.remove();
            return;
          }
          if (texttemplate) {
            var fn = trace._module.formatLabels;
            var labels = fn ? fn(d, trace, fullLayout) : {};
            var pointValues = {};
            appendArrayPointValue(pointValues, trace, d.i);
            text = Lib.texttemplateString({
              data: [pointValues, d, trace._meta],
              fallback: trace.texttemplatefallback,
              labels,
              locale: fullLayout._d3locale,
              template: text
            });
          }
          var pos = d.tp || trace.textposition;
          var fontSize = extracTextFontSize(d, trace);
          var fontColor = selectedTextColorFn ? selectedTextColorFn(d) : d.tc || trace.textfont.color;
          p.call(drawing.font, {
            family: d.tf || trace.textfont.family,
            weight: d.tw || trace.textfont.weight,
            style: d.ty || trace.textfont.style,
            variant: d.tv || trace.textfont.variant,
            textcase: d.tC || trace.textfont.textcase,
            lineposition: d.tE || trace.textfont.lineposition,
            shadow: d.tS || trace.textfont.shadow,
            size: fontSize,
            color: fontColor
          }).text(text).call(svgTextUtils.convertToTspans, gd).call(textPointPosition, pos, fontSize, d.mrc);
        });
      };
      drawing.selectedTextStyle = function(s, trace) {
        if (!s.size() || !trace.selectedpoints) return;
        var fns = drawing.makeSelectedTextStyleFns(trace);
        s.each(function(d) {
          var tx = d3.select(this);
          var tc = fns.selectedTextColorFn(d);
          var tp = d.tp || trace.textposition;
          var fontSize = extracTextFontSize(d, trace);
          Color2.fill(tx, tc);
          var dontTouchParent = Registry.traceIs(trace, "bar-like");
          textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc, dontTouchParent);
        });
      };
      var CatmullRomExp = 0.5;
      drawing.smoothopen = function(pts, smoothness) {
        if (pts.length < 3) {
          return "M" + pts.join("L");
        }
        var path = "M" + pts[0];
        var tangents = [];
        var i;
        for (i = 1; i < pts.length - 1; i++) {
          tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
        }
        path += "Q" + tangents[0][0] + " " + pts[1];
        for (i = 2; i < pts.length - 1; i++) {
          path += "C" + tangents[i - 2][1] + " " + tangents[i - 1][0] + " " + pts[i];
        }
        path += "Q" + tangents[pts.length - 3][1] + " " + pts[pts.length - 1];
        return path;
      };
      drawing.smoothclosed = function(pts, smoothness) {
        if (pts.length < 3) {
          return "M" + pts.join("L") + "Z";
        }
        var path = "M" + pts[0];
        var pLast = pts.length - 1;
        var tangents = [makeTangent(pts[pLast], pts[0], pts[1], smoothness)];
        var i;
        for (i = 1; i < pLast; i++) {
          tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
        }
        tangents.push(makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness));
        for (i = 1; i <= pLast; i++) {
          path += "C" + tangents[i - 1][1] + " " + tangents[i][0] + " " + pts[i];
        }
        path += "C" + tangents[pLast][1] + " " + tangents[0][0] + " " + pts[0] + "Z";
        return path;
      };
      var lastDrawnX;
      var lastDrawnY;
      function roundEnd(pt, isY, isLastPoint) {
        if (isLastPoint) pt = applyBackoff(pt);
        return isY ? roundY(pt[1]) : roundX(pt[0]);
      }
      function roundX(p) {
        var v = d3.round(p, 2);
        lastDrawnX = v;
        return v;
      }
      function roundY(p) {
        var v = d3.round(p, 2);
        lastDrawnY = v;
        return v;
      }
      function makeTangent(prevpt, thispt, nextpt, smoothness) {
        var d1x = prevpt[0] - thispt[0];
        var d1y = prevpt[1] - thispt[1];
        var d2x = nextpt[0] - thispt[0];
        var d2y = nextpt[1] - thispt[1];
        var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
        var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
        var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
        var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
        var denom1 = 3 * d2a * (d1a + d2a);
        var denom2 = 3 * d1a * (d1a + d2a);
        return [
          [roundX(thispt[0] + (denom1 && numx / denom1)), roundY(thispt[1] + (denom1 && numy / denom1))],
          [roundX(thispt[0] - (denom2 && numx / denom2)), roundY(thispt[1] - (denom2 && numy / denom2))]
        ];
      }
      var STEPPATH = {
        hv: function(p0, p1, isLastPoint) {
          return "H" + roundX(p1[0]) + "V" + roundEnd(p1, 1, isLastPoint);
        },
        vh: function(p0, p1, isLastPoint) {
          return "V" + roundY(p1[1]) + "H" + roundEnd(p1, 0, isLastPoint);
        },
        hvh: function(p0, p1, isLastPoint) {
          return "H" + roundX((p0[0] + p1[0]) / 2) + "V" + roundY(p1[1]) + "H" + roundEnd(p1, 0, isLastPoint);
        },
        vhv: function(p0, p1, isLastPoint) {
          return "V" + roundY((p0[1] + p1[1]) / 2) + "H" + roundX(p1[0]) + "V" + roundEnd(p1, 1, isLastPoint);
        }
      };
      var STEPLINEAR = function(p0, p1, isLastPoint) {
        return "L" + roundEnd(p1, 0, isLastPoint) + "," + roundEnd(p1, 1, isLastPoint);
      };
      drawing.steps = function(shape) {
        var onestep = STEPPATH[shape] || STEPLINEAR;
        return function(pts) {
          var path = "M" + roundX(pts[0][0]) + "," + roundY(pts[0][1]);
          var len = pts.length;
          for (var i = 1; i < len; i++) {
            path += onestep(pts[i - 1], pts[i], i === len - 1);
          }
          return path;
        };
      };
      function applyBackoff(pt, start) {
        var backoff = pt.backoff;
        var trace = pt.trace;
        var d = pt.d;
        var i = pt.i;
        if (backoff && trace && trace.marker && trace.marker.angle % 360 === 0 && trace.line && trace.line.shape !== "spline") {
          var arrayBackoff = Lib.isArrayOrTypedArray(backoff);
          var end = pt;
          var x1 = start ? start[0] : lastDrawnX || 0;
          var y1 = start ? start[1] : lastDrawnY || 0;
          var x2 = end[0];
          var y2 = end[1];
          var dx = x2 - x1;
          var dy = y2 - y1;
          var t = Math.atan2(dy, dx);
          var b = arrayBackoff ? backoff[i] : backoff;
          if (b === "auto") {
            var endI = end.i;
            if (trace.type === "scatter") endI--;
            var endMarker = end.marker;
            var endMarkerSymbol = endMarker.symbol;
            if (Lib.isArrayOrTypedArray(endMarkerSymbol)) endMarkerSymbol = endMarkerSymbol[endI];
            var endMarkerSize = endMarker.size;
            if (Lib.isArrayOrTypedArray(endMarkerSize)) endMarkerSize = endMarkerSize[endI];
            b = endMarker ? drawing.symbolBackOffs[drawing.symbolNumber(endMarkerSymbol)] * endMarkerSize : 0;
            b += drawing.getMarkerStandoff(d[endI], trace) || 0;
          }
          var x = x2 - b * Math.cos(t);
          var y = y2 - b * Math.sin(t);
          if ((x <= x2 && x >= x1 || x >= x2 && x <= x1) && (y <= y2 && y >= y1 || y >= y2 && y <= y1)) {
            pt = [x, y];
          }
        }
        return pt;
      }
      drawing.applyBackoff = applyBackoff;
      drawing.makeTester = function() {
        var tester = Lib.ensureSingleById(d3.select("body"), "svg", "js-plotly-tester", function(s) {
          s.attr(xmlnsNamespaces.svgAttrs).style({
            position: "absolute",
            left: "-10000px",
            top: "-10000px",
            width: "9000px",
            height: "9000px",
            "z-index": "1"
          });
        });
        var testref = Lib.ensureSingle(tester, "path", "js-reference-point", function(s) {
          s.attr("d", "M0,0H1V1H0Z").style({
            "stroke-width": 0,
            fill: "black"
          });
        });
        drawing.tester = tester;
        drawing.testref = testref;
      };
      drawing.savedBBoxes = {};
      var savedBBoxesCount = 0;
      var maxSavedBBoxes = 1e4;
      drawing.bBox = function(node, inTester, hash) {
        if (!hash) hash = nodeHash(node);
        var out;
        if (hash) {
          out = drawing.savedBBoxes[hash];
          if (out) return Lib.extendFlat({}, out);
        } else if (node.childNodes.length === 1) {
          var innerNode = node.childNodes[0];
          hash = nodeHash(innerNode);
          if (hash) {
            var x = +innerNode.getAttribute("x") || 0;
            var y = +innerNode.getAttribute("y") || 0;
            var transform = innerNode.getAttribute("transform");
            if (!transform) {
              var innerBB = drawing.bBox(innerNode, false, hash);
              if (x) {
                innerBB.left += x;
                innerBB.right += x;
              }
              if (y) {
                innerBB.top += y;
                innerBB.bottom += y;
              }
              return innerBB;
            }
            hash += "~" + x + "~" + y + "~" + transform;
            out = drawing.savedBBoxes[hash];
            if (out) return Lib.extendFlat({}, out);
          }
        }
        var testNode, tester;
        if (inTester) {
          testNode = node;
        } else {
          tester = drawing.tester.node();
          testNode = node.cloneNode(true);
          tester.appendChild(testNode);
        }
        d3.select(testNode).attr("transform", null).call(svgTextUtils.positionText, 0, 0);
        var testRect = testNode.getBoundingClientRect();
        var refRect = drawing.testref.node().getBoundingClientRect();
        if (!inTester) tester.removeChild(testNode);
        var bb = {
          height: testRect.height,
          width: testRect.width,
          left: testRect.left - refRect.left,
          top: testRect.top - refRect.top,
          right: testRect.right - refRect.left,
          bottom: testRect.bottom - refRect.top
        };
        if (savedBBoxesCount >= maxSavedBBoxes) {
          drawing.savedBBoxes = {};
          savedBBoxesCount = 0;
        }
        if (hash) drawing.savedBBoxes[hash] = bb;
        savedBBoxesCount++;
        return Lib.extendFlat({}, bb);
      };
      function nodeHash(node) {
        var inputText = node.getAttribute("data-unformatted");
        if (inputText === null) return;
        return inputText + node.getAttribute("data-math") + node.getAttribute("text-anchor") + node.getAttribute("style");
      }
      drawing.setClipUrl = function(s, localId, gd) {
        s.attr("clip-path", getFullUrl(localId, gd));
      };
      function getFullUrl(localId, gd) {
        if (!localId) return null;
        var context = gd._context;
        var baseUrl = context._exportedPlot ? "" : context._baseUrl || "";
        return baseUrl ? "url('" + baseUrl + "#" + localId + "')" : "url(#" + localId + ")";
      }
      drawing.getTranslate = function(element) {
        var re = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/;
        var getter = element.attr ? "attr" : "getAttribute";
        var transform = element[getter]("transform") || "";
        var translate = transform.replace(re, function(match, p1, p2) {
          return [p1, p2].join(" ");
        }).split(" ");
        return {
          x: +translate[0] || 0,
          y: +translate[1] || 0
        };
      };
      drawing.setTranslate = function(element, x, y) {
        var re = /(\btranslate\(.*?\);?)/;
        var getter = element.attr ? "attr" : "getAttribute";
        var setter = element.attr ? "attr" : "setAttribute";
        var transform = element[getter]("transform") || "";
        x = x || 0;
        y = y || 0;
        transform = transform.replace(re, "").trim();
        transform += strTranslate(x, y);
        transform = transform.trim();
        element[setter]("transform", transform);
        return transform;
      };
      drawing.getScale = function(element) {
        var re = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/;
        var getter = element.attr ? "attr" : "getAttribute";
        var transform = element[getter]("transform") || "";
        var translate = transform.replace(re, function(match, p1, p2) {
          return [p1, p2].join(" ");
        }).split(" ");
        return {
          x: +translate[0] || 1,
          y: +translate[1] || 1
        };
      };
      drawing.setScale = function(element, x, y) {
        var re = /(\bscale\(.*?\);?)/;
        var getter = element.attr ? "attr" : "getAttribute";
        var setter = element.attr ? "attr" : "setAttribute";
        var transform = element[getter]("transform") || "";
        x = x || 1;
        y = y || 1;
        transform = transform.replace(re, "").trim();
        transform += "scale(" + x + "," + y + ")";
        transform = transform.trim();
        element[setter]("transform", transform);
        return transform;
      };
      var SCALE_RE = /\s*sc.*/;
      drawing.setPointGroupScale = function(selection, xScale, yScale) {
        xScale = xScale || 1;
        yScale = yScale || 1;
        if (!selection) return;
        var scale = xScale === 1 && yScale === 1 ? "" : "scale(" + xScale + "," + yScale + ")";
        selection.each(function() {
          var t = (this.getAttribute("transform") || "").replace(SCALE_RE, "");
          t += scale;
          t = t.trim();
          this.setAttribute("transform", t);
        });
      };
      var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/;
      drawing.setTextPointsScale = function(selection, xScale, yScale) {
        if (!selection) return;
        selection.each(function() {
          var transforms;
          var el = d3.select(this);
          var text = el.select("text");
          if (!text.node()) return;
          var x = parseFloat(text.attr("x") || 0);
          var y = parseFloat(text.attr("y") || 0);
          var existingTransform = (el.attr("transform") || "").match(TEXT_POINT_LAST_TRANSLATION_RE);
          if (xScale === 1 && yScale === 1) {
            transforms = [];
          } else {
            transforms = [strTranslate(x, y), "scale(" + xScale + "," + yScale + ")", strTranslate(-x, -y)];
          }
          if (existingTransform) {
            transforms.push(existingTransform);
          }
          el.attr("transform", transforms.join(""));
        });
      };
      function getMarkerStandoff(d, trace) {
        var standoff;
        if (d) standoff = d.mf;
        if (standoff === void 0) {
          standoff = trace.marker ? trace.marker.standoff || 0 : 0;
        }
        if (!trace._geo && !trace._xA) {
          return -standoff;
        }
        return standoff;
      }
      drawing.getMarkerStandoff = getMarkerStandoff;
      var atan2 = Math.atan2;
      var cos = Math.cos;
      var sin = Math.sin;
      function rotate(t, xy) {
        var x = xy[0];
        var y = xy[1];
        return [x * cos(t) - y * sin(t), x * sin(t) + y * cos(t)];
      }
      var previousLon;
      var previousLat;
      var previousX;
      var previousY;
      var previousI;
      var previousTraceUid;
      function getMarkerAngle(d, trace) {
        var angle = d.ma;
        if (angle === void 0) {
          angle = trace.marker.angle;
          if (!angle || Lib.isArrayOrTypedArray(angle)) {
            angle = 0;
          }
        }
        var x, y;
        var ref = trace.marker.angleref;
        if (ref === "previous" || ref === "north") {
          if (trace._geo) {
            var p = trace._geo.project(d.lonlat);
            x = p[0];
            y = p[1];
          } else {
            var xa = trace._xA;
            var ya = trace._yA;
            if (xa && ya) {
              x = xa.c2p(d.x);
              y = ya.c2p(d.y);
            } else {
              return 90;
            }
          }
          if (trace._geo) {
            var lon = d.lonlat[0];
            var lat = d.lonlat[1];
            var north = trace._geo.project([
              lon,
              lat + 1e-5
              // epsilon
            ]);
            var east = trace._geo.project([
              lon + 1e-5,
              // epsilon
              lat
            ]);
            var u = atan2(east[1] - y, east[0] - x);
            var v = atan2(north[1] - y, north[0] - x);
            var t;
            if (ref === "north") {
              t = angle / 180 * Math.PI;
            } else if (ref === "previous") {
              var lon1 = lon / 180 * Math.PI;
              var lat1 = lat / 180 * Math.PI;
              var lon2 = previousLon / 180 * Math.PI;
              var lat2 = previousLat / 180 * Math.PI;
              var dLon = lon2 - lon1;
              var deltaY = cos(lat2) * sin(dLon);
              var deltaX = sin(lat2) * cos(lat1) - cos(lat2) * sin(lat1) * cos(dLon);
              t = -atan2(deltaY, deltaX) - Math.PI;
              previousLon = lon;
              previousLat = lat;
            }
            var A2 = rotate(u, [cos(t), 0]);
            var B2 = rotate(v, [sin(t), 0]);
            angle = atan2(A2[1] + B2[1], A2[0] + B2[0]) / Math.PI * 180;
            if (ref === "previous" && !(previousTraceUid === trace.uid && d.i === previousI + 1)) {
              angle = null;
            }
          }
          if (ref === "previous" && !trace._geo) {
            if (previousTraceUid === trace.uid && d.i === previousI + 1 && isNumeric(x) && isNumeric(y)) {
              var dX = x - previousX;
              var dY = y - previousY;
              var shape = trace.line ? trace.line.shape || "" : "";
              var lastShapeChar = shape.slice(shape.length - 1);
              if (lastShapeChar === "h") dY = 0;
              if (lastShapeChar === "v") dX = 0;
              angle += atan2(dY, dX) / Math.PI * 180 + 90;
            } else {
              angle = null;
            }
          }
        }
        previousX = x;
        previousY = y;
        previousI = d.i;
        previousTraceUid = trace.uid;
        return angle;
      }
      drawing.getMarkerAngle = getMarkerAngle;
    }
  });

  // src/components/titles/index.js
  var require_titles = __commonJS({
    "src/components/titles/index.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var Plots = require_plots();
      var Registry = require_registry();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var Drawing = require_drawing();
      var Color2 = require_color();
      var svgTextUtils = require_svg_text_utils();
      var interactConstants = require_interactions();
      var OPPOSITE_SIDE = require_alignment().OPPOSITE_SIDE;
      var numStripRE = / [XY][0-9]* /;
      var SUBTITLE_PADDING_MATHJAX_EM = 1.6;
      var SUBTITLE_PADDING_EM = 1.6;
      function draw(gd, titleClass, options) {
        var fullLayout = gd._fullLayout;
        var cont = options.propContainer;
        var prop = options.propName;
        var placeholder = options.placeholder;
        var traceIndex = options.traceIndex;
        var avoid = options.avoid || {};
        var attributes = options.attributes;
        var transform = options.transform;
        var group = options.containerGroup;
        var opacity = 1;
        var title = cont.title;
        var txt = (title && title.text ? title.text : "").trim();
        var titleIsPlaceholder = false;
        var font = title && title.font ? title.font : {};
        var fontFamily = font.family;
        var fontSize = font.size;
        var fontColor = font.color;
        var fontWeight = font.weight;
        var fontStyle = font.style;
        var fontVariant = font.variant;
        var fontTextcase = font.textcase;
        var fontLineposition = font.lineposition;
        var fontShadow = font.shadow;
        var subtitleProp = options.subtitlePropName;
        var subtitleEnabled = !!subtitleProp;
        var subtitlePlaceholder = options.subtitlePlaceholder;
        var subtitle = (cont.title || {}).subtitle || { text: "", font: {} };
        var subtitleTxt = (subtitle.text || "").trim();
        var subtitleIsPlaceholder = false;
        var subtitleOpacity = 1;
        var subtitleFont = subtitle.font;
        var subFontFamily = subtitleFont.family;
        var subFontSize = subtitleFont.size;
        var subFontColor = subtitleFont.color;
        var subFontWeight = subtitleFont.weight;
        var subFontStyle = subtitleFont.style;
        var subFontVariant = subtitleFont.variant;
        var subFontTextcase = subtitleFont.textcase;
        var subFontLineposition = subtitleFont.lineposition;
        var subFontShadow = subtitleFont.shadow;
        var editAttr;
        if (prop === "title.text") editAttr = "titleText";
        else if (prop.indexOf("axis") !== -1) editAttr = "axisTitleText";
        else if (prop.indexOf("colorbar") !== -1) editAttr = "colorbarTitleText";
        var editable = gd._context.edits[editAttr];
        function matchesPlaceholder(text, placeholder2) {
          if (text === void 0 || placeholder2 === void 0) return false;
          return text.replace(numStripRE, " % ") === placeholder2.replace(numStripRE, " % ");
        }
        if (txt === "") opacity = 0;
        else if (matchesPlaceholder(txt, placeholder)) {
          if (!editable) txt = "";
          opacity = 0.2;
          titleIsPlaceholder = true;
        }
        if (subtitleEnabled) {
          if (subtitleTxt === "") subtitleOpacity = 0;
          else if (matchesPlaceholder(subtitleTxt, subtitlePlaceholder)) {
            if (!editable) subtitleTxt = "";
            subtitleOpacity = 0.2;
            subtitleIsPlaceholder = true;
          }
        }
        if (options._meta) {
          txt = Lib.templateString(txt, options._meta);
        } else if (fullLayout._meta) {
          txt = Lib.templateString(txt, fullLayout._meta);
        }
        var elShouldExist = txt || subtitleTxt || editable;
        var hColorbarMoveTitle;
        if (!group) {
          group = Lib.ensureSingle(fullLayout._infolayer, "g", "g-" + titleClass);
          hColorbarMoveTitle = fullLayout._hColorbarMoveTitle;
        }
        var el = group.selectAll("text." + titleClass).data(elShouldExist ? [0] : []);
        el.enter().append("text");
        el.text(txt).attr("class", titleClass);
        el.exit().remove();
        var subtitleEl = null;
        var subtitleClass = titleClass + "-subtitle";
        var subtitleElShouldExist = subtitleTxt || editable;
        if (subtitleEnabled) {
          subtitleEl = group.selectAll("text." + subtitleClass).data(subtitleElShouldExist ? [0] : []);
          subtitleEl.enter().append("text");
          subtitleEl.text(subtitleTxt).attr("class", subtitleClass);
          subtitleEl.exit().remove();
        }
        if (!elShouldExist) return group;
        function titleLayout(titleEl, subtitleEl2) {
          Lib.syncOrAsync([drawTitle, scootTitle], { title: titleEl, subtitle: subtitleEl2 });
        }
        function drawTitle(titleAndSubtitleEls) {
          var titleEl = titleAndSubtitleEls.title;
          var subtitleEl2 = titleAndSubtitleEls.subtitle;
          var transformVal;
          if (!transform && hColorbarMoveTitle) {
            transform = {};
          }
          if (transform) {
            transformVal = "";
            if (transform.rotate) {
              transformVal += "rotate(" + [transform.rotate, attributes.x, attributes.y] + ")";
            }
            if (transform.offset || hColorbarMoveTitle) {
              transformVal += strTranslate(0, (transform.offset || 0) - (hColorbarMoveTitle || 0));
            }
          } else {
            transformVal = null;
          }
          titleEl.attr("transform", transformVal);
          function adjustSubtitlePosition(titleElMathGroup2) {
            if (!titleElMathGroup2) return;
            var subtitleElement = d3.select(titleElMathGroup2.node().parentNode).select("." + subtitleClass);
            if (!subtitleElement.empty()) {
              var titleElMathBbox2 = titleElMathGroup2.node().getBBox();
              if (titleElMathBbox2.height) {
                var subtitleY3 = titleElMathBbox2.y + titleElMathBbox2.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize;
                subtitleElement.attr("y", subtitleY3);
              }
            }
          }
          titleEl.style("opacity", opacity * Color2.opacity(fontColor)).call(Drawing.font, {
            color: Color2.rgb(fontColor),
            size: d3.round(fontSize, 2),
            family: fontFamily,
            weight: fontWeight,
            style: fontStyle,
            variant: fontVariant,
            textcase: fontTextcase,
            shadow: fontShadow,
            lineposition: fontLineposition
          }).attr(attributes).call(svgTextUtils.convertToTspans, gd, adjustSubtitlePosition);
          if (subtitleEl2 && !subtitleEl2.empty()) {
            var titleElMathGroup = group.select("." + titleClass + "-math-group");
            var titleElBbox2 = titleEl.node().getBBox();
            var titleElMathBbox = titleElMathGroup.node() ? titleElMathGroup.node().getBBox() : void 0;
            var subtitleY2 = titleElMathBbox ? titleElMathBbox.y + titleElMathBbox.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize : titleElBbox2.y + titleElBbox2.height + SUBTITLE_PADDING_EM * subFontSize;
            var subtitleAttributes = Lib.extendFlat({}, attributes, {
              y: subtitleY2
            });
            subtitleEl2.attr("transform", transformVal);
            subtitleEl2.style("opacity", subtitleOpacity * Color2.opacity(subFontColor)).call(Drawing.font, {
              color: Color2.rgb(subFontColor),
              size: d3.round(subFontSize, 2),
              family: subFontFamily,
              weight: subFontWeight,
              style: subFontStyle,
              variant: subFontVariant,
              textcase: subFontTextcase,
              shadow: subFontShadow,
              lineposition: subFontLineposition
            }).attr(subtitleAttributes).call(svgTextUtils.convertToTspans, gd);
          }
          return Plots.previousPromises(gd);
        }
        function scootTitle(titleAndSubtitleEls) {
          var titleElIn = titleAndSubtitleEls.title;
          var titleGroup = d3.select(titleElIn.node().parentNode);
          if (avoid && avoid.selection && avoid.side && txt) {
            titleGroup.attr("transform", null);
            var backside = OPPOSITE_SIDE[avoid.side];
            var shiftSign = avoid.side === "left" || avoid.side === "top" ? -1 : 1;
            var pad = isNumeric(avoid.pad) ? avoid.pad : 2;
            var titlebb = Drawing.bBox(titleGroup.node());
            var reservedMargins = { t: 0, b: 0, l: 0, r: 0 };
            var margins = gd._fullLayout._reservedMargin;
            for (var key in margins) {
              for (var side in margins[key]) {
                var val = margins[key][side];
                reservedMargins[side] = Math.max(reservedMargins[side], val);
              }
            }
            var paperbb = {
              left: reservedMargins.l,
              top: reservedMargins.t,
              right: fullLayout.width - reservedMargins.r,
              bottom: fullLayout.height - reservedMargins.b
            };
            var maxshift = avoid.maxShift || shiftSign * (paperbb[avoid.side] - titlebb[avoid.side]);
            var shift = 0;
            if (maxshift < 0) {
              shift = maxshift;
            } else {
              var offsetLeft = avoid.offsetLeft || 0;
              var offsetTop = avoid.offsetTop || 0;
              titlebb.left -= offsetLeft;
              titlebb.right -= offsetLeft;
              titlebb.top -= offsetTop;
              titlebb.bottom -= offsetTop;
              avoid.selection.each(function() {
                var avoidbb = Drawing.bBox(this);
                if (Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
                  shift = Math.max(shift, shiftSign * (avoidbb[avoid.side] - titlebb[backside]) + pad);
                }
              });
              shift = Math.min(maxshift, shift);
              cont._titleScoot = Math.abs(shift);
            }
            if (shift > 0 || maxshift < 0) {
              var shiftTemplate = {
                left: [-shift, 0],
                right: [shift, 0],
                top: [0, -shift],
                bottom: [0, shift]
              }[avoid.side];
              titleGroup.attr("transform", strTranslate(shiftTemplate[0], shiftTemplate[1]));
            }
          }
        }
        el.call(titleLayout, subtitleEl);
        function setPlaceholder(element, placeholderText) {
          element.text(placeholderText).on("mouseover.opacity", function() {
            d3.select(this).transition().duration(interactConstants.SHOW_PLACEHOLDER).style("opacity", 1);
          }).on("mouseout.opacity", function() {
            d3.select(this).transition().duration(interactConstants.HIDE_PLACEHOLDER).style("opacity", 0);
          });
        }
        if (editable) {
          if (!txt) {
            setPlaceholder(el, placeholder);
            titleIsPlaceholder = true;
          } else el.on(".opacity", null);
          el.call(svgTextUtils.makeEditable, { gd }).on("edit", function(text) {
            if (traceIndex !== void 0) {
              Registry.call("_guiRestyle", gd, prop, text, traceIndex);
            } else {
              Registry.call("_guiRelayout", gd, prop, text);
            }
          }).on("cancel", function() {
            this.text(this.attr("data-unformatted")).call(titleLayout);
          }).on("input", function(d) {
            this.text(d || " ").call(svgTextUtils.positionText, attributes.x, attributes.y);
          });
          if (subtitleEnabled) {
            if (subtitleEnabled && !txt) {
              var titleElBbox = el.node().getBBox();
              var subtitleY = titleElBbox.y + titleElBbox.height + SUBTITLE_PADDING_EM * subFontSize;
              subtitleEl.attr("y", subtitleY);
            }
            if (!subtitleTxt) {
              setPlaceholder(subtitleEl, subtitlePlaceholder);
              subtitleIsPlaceholder = true;
            } else subtitleEl.on(".opacity", null);
            subtitleEl.call(svgTextUtils.makeEditable, { gd }).on("edit", function(text) {
              Registry.call("_guiRelayout", gd, "title.subtitle.text", text);
            }).on("cancel", function() {
              this.text(this.attr("data-unformatted")).call(titleLayout);
            }).on("input", function(d) {
              this.text(d || " ").call(svgTextUtils.positionText, subtitleEl.attr("x"), subtitleEl.attr("y"));
            });
          }
        }
        el.classed("js-placeholder", titleIsPlaceholder);
        if (subtitleEl && !subtitleEl.empty()) subtitleEl.classed("js-placeholder", subtitleIsPlaceholder);
        return group;
      }
      module.exports = {
        draw,
        SUBTITLE_PADDING_EM,
        SUBTITLE_PADDING_MATHJAX_EM
      };
    }
  });

  // src/plots/cartesian/set_convert.js
  var require_set_convert = __commonJS({
    "src/plots/cartesian/set_convert.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var utcFormat = require_d3_time_format().utcFormat;
      var Lib = require_lib();
      var numberFormat = Lib.numberFormat;
      var isNumeric = require_fast_isnumeric();
      var cleanNumber = Lib.cleanNumber;
      var ms2DateTime = Lib.ms2DateTime;
      var dateTime2ms = Lib.dateTime2ms;
      var ensureNumber = Lib.ensureNumber;
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var numConstants = require_numerical();
      var FP_SAFE = numConstants.FP_SAFE;
      var BADNUM = numConstants.BADNUM;
      var LOG_CLIP = numConstants.LOG_CLIP;
      var ONEWEEK = numConstants.ONEWEEK;
      var ONEDAY = numConstants.ONEDAY;
      var ONEHOUR = numConstants.ONEHOUR;
      var ONEMIN = numConstants.ONEMIN;
      var ONESEC = numConstants.ONESEC;
      var axisIds = require_axis_ids();
      var constants = require_constants2();
      var HOUR_PATTERN = constants.HOUR_PATTERN;
      var WEEKDAY_PATTERN = constants.WEEKDAY_PATTERN;
      function fromLog(v) {
        return Math.pow(10, v);
      }
      function isValidCategory(v) {
        return v !== null && v !== void 0;
      }
      module.exports = function setConvert(ax, fullLayout) {
        fullLayout = fullLayout || {};
        var axId = ax._id || "x";
        var axLetter = axId.charAt(0);
        function toLog(v, clip) {
          if (v > 0) return Math.log(v) / Math.LN10;
          else if (v <= 0 && clip && ax.range && ax.range.length === 2) {
            var r0 = ax.range[0];
            var r1 = ax.range[1];
            return 0.5 * (r0 + r1 - 2 * LOG_CLIP * Math.abs(r0 - r1));
          } else return BADNUM;
        }
        function dt2ms(v, _, calendar, opts) {
          if ((opts || {}).msUTC && isNumeric(v)) {
            return +v;
          }
          var ms = dateTime2ms(v, calendar || ax.calendar);
          if (ms === BADNUM) {
            if (isNumeric(v)) {
              v = +v;
              var msecTenths = Math.floor(Lib.mod(v + 0.05, 1) * 10);
              var msRounded = Math.round(v - msecTenths / 10);
              ms = dateTime2ms(new Date(msRounded)) + msecTenths / 10;
            } else return BADNUM;
          }
          return ms;
        }
        function ms2dt(v, r, calendar) {
          return ms2DateTime(v, r, calendar || ax.calendar);
        }
        function getCategoryName(v) {
          return ax._categories[Math.round(v)];
        }
        function setCategoryIndex(v) {
          if (isValidCategory(v)) {
            if (ax._categoriesMap === void 0) {
              ax._categoriesMap = {};
            }
            if (ax._categoriesMap[v] !== void 0) {
              return ax._categoriesMap[v];
            } else {
              ax._categories.push(typeof v === "number" ? String(v) : v);
              var curLength = ax._categories.length - 1;
              ax._categoriesMap[v] = curLength;
              return curLength;
            }
          }
          return BADNUM;
        }
        function setMultiCategoryIndex(arrayIn, len) {
          var arrayOut = new Array(len);
          for (var i = 0; i < len; i++) {
            var v0 = (arrayIn[0] || [])[i];
            var v1 = (arrayIn[1] || [])[i];
            arrayOut[i] = getCategoryIndex([v0, v1]);
          }
          return arrayOut;
        }
        function getCategoryIndex(v) {
          if (ax._categoriesMap) {
            return ax._categoriesMap[v];
          }
        }
        function getCategoryPosition(v) {
          var index = getCategoryIndex(v);
          if (index !== void 0) return index;
          if (isNumeric(v)) return +v;
        }
        function getRangePosition(v) {
          return isNumeric(v) ? +v : getCategoryIndex(v);
        }
        function _l2p(v, m, b) {
          return d3.round(b + m * v, 2);
        }
        function _p2l(px, m, b) {
          return (px - b) / m;
        }
        var l2p = function l2p2(v) {
          if (!isNumeric(v)) return BADNUM;
          return _l2p(v, ax._m, ax._b);
        };
        var p2l = function(px) {
          return _p2l(px, ax._m, ax._b);
        };
        if (ax.rangebreaks) {
          var isY = axLetter === "y";
          l2p = function(v) {
            if (!isNumeric(v)) return BADNUM;
            var len = ax._rangebreaks.length;
            if (!len) return _l2p(v, ax._m, ax._b);
            var flip = isY;
            if (ax.range[0] > ax.range[1]) flip = !flip;
            var signAx = flip ? -1 : 1;
            var pos = signAx * v;
            var q = 0;
            for (var i = 0; i < len; i++) {
              var min = signAx * ax._rangebreaks[i].min;
              var max = signAx * ax._rangebreaks[i].max;
              if (pos < min) break;
              if (pos > max) q = i + 1;
              else {
                q = pos < (min + max) / 2 ? i : i + 1;
                break;
              }
            }
            var b2 = ax._B[q] || 0;
            if (!isFinite(b2)) return 0;
            return _l2p(v, ax._m2, b2);
          };
          p2l = function(px) {
            var len = ax._rangebreaks.length;
            if (!len) return _p2l(px, ax._m, ax._b);
            var q = 0;
            for (var i = 0; i < len; i++) {
              if (px < ax._rangebreaks[i].pmin) break;
              if (px > ax._rangebreaks[i].pmax) q = i + 1;
            }
            return _p2l(px, ax._m2, ax._B[q]);
          };
        }
        ax.c2l = ax.type === "log" ? toLog : ensureNumber;
        ax.l2c = ax.type === "log" ? fromLog : ensureNumber;
        ax.l2p = l2p;
        ax.p2l = p2l;
        ax.c2p = ax.type === "log" ? function(v, clip) {
          return l2p(toLog(v, clip));
        } : l2p;
        ax.p2c = ax.type === "log" ? function(px) {
          return fromLog(p2l(px));
        } : p2l;
        if (["linear", "-"].indexOf(ax.type) !== -1) {
          ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber;
          ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber;
          ax.d2p = ax.r2p = function(v) {
            return ax.l2p(cleanNumber(v));
          };
          ax.p2d = ax.p2r = p2l;
          ax.cleanPos = ensureNumber;
        } else if (ax.type === "log") {
          ax.d2r = ax.d2l = function(v, clip) {
            return toLog(cleanNumber(v), clip);
          };
          ax.r2d = ax.r2c = function(v) {
            return fromLog(cleanNumber(v));
          };
          ax.d2c = ax.r2l = cleanNumber;
          ax.c2d = ax.l2r = ensureNumber;
          ax.c2r = toLog;
          ax.l2d = fromLog;
          ax.d2p = function(v, clip) {
            return ax.l2p(ax.d2r(v, clip));
          };
          ax.p2d = function(px) {
            return fromLog(p2l(px));
          };
          ax.r2p = function(v) {
            return ax.l2p(cleanNumber(v));
          };
          ax.p2r = p2l;
          ax.cleanPos = ensureNumber;
        } else if (ax.type === "date") {
          ax.d2r = ax.r2d = Lib.identity;
          ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms;
          ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt;
          ax.d2p = ax.r2p = function(v, _, calendar) {
            return ax.l2p(dt2ms(v, 0, calendar));
          };
          ax.p2d = ax.p2r = function(px, r, calendar) {
            return ms2dt(p2l(px), r, calendar);
          };
          ax.cleanPos = function(v) {
            return Lib.cleanDate(v, BADNUM, ax.calendar);
          };
        } else if (ax.type === "category") {
          ax.d2c = ax.d2l = setCategoryIndex;
          ax.r2d = ax.c2d = ax.l2d = getCategoryName;
          ax.d2r = ax.d2l_noadd = getCategoryPosition;
          ax.r2c = function(v) {
            var index = getRangePosition(v);
            return index !== void 0 ? index : ax.fraction2r(0.5);
          };
          ax.l2r = ax.c2r = ensureNumber;
          ax.r2l = getRangePosition;
          ax.d2p = function(v) {
            return ax.l2p(ax.r2c(v));
          };
          ax.p2d = function(px) {
            return getCategoryName(p2l(px));
          };
          ax.r2p = ax.d2p;
          ax.p2r = p2l;
          ax.cleanPos = function(v) {
            if (typeof v === "string" && v !== "") return v;
            return ensureNumber(v);
          };
        } else if (ax.type === "multicategory") {
          ax.r2d = ax.c2d = ax.l2d = getCategoryName;
          ax.d2r = ax.d2l_noadd = getCategoryPosition;
          ax.r2c = function(v) {
            var index = getCategoryPosition(v);
            return index !== void 0 ? index : ax.fraction2r(0.5);
          };
          ax.r2c_just_indices = getCategoryIndex;
          ax.l2r = ax.c2r = ensureNumber;
          ax.r2l = getCategoryPosition;
          ax.d2p = function(v) {
            return ax.l2p(ax.r2c(v));
          };
          ax.p2d = function(px) {
            return getCategoryName(p2l(px));
          };
          ax.r2p = ax.d2p;
          ax.p2r = p2l;
          ax.cleanPos = function(v) {
            if (Array.isArray(v) || typeof v === "string" && v !== "") return v;
            return ensureNumber(v);
          };
          ax.setupMultiCategory = function(fullData) {
            var traceIndices = ax._traceIndices;
            var i, j;
            var group = ax._matchGroup;
            if (group && ax._categories.length === 0) {
              for (var axId2 in group) {
                if (axId2 !== axId) {
                  var ax2 = fullLayout[axisIds.id2name(axId2)];
                  traceIndices = traceIndices.concat(ax2._traceIndices);
                }
              }
            }
            var seen = [[0, {}], [0, {}]];
            var list = [];
            for (i = 0; i < traceIndices.length; i++) {
              var trace = fullData[traceIndices[i]];
              if (axLetter in trace) {
                var arrayIn = trace[axLetter];
                var len = trace._length || Lib.minRowLength(arrayIn);
                if (isArrayOrTypedArray(arrayIn[0]) && isArrayOrTypedArray(arrayIn[1])) {
                  for (j = 0; j < len; j++) {
                    var v0 = arrayIn[0][j];
                    var v1 = arrayIn[1][j];
                    if (isValidCategory(v0) && isValidCategory(v1)) {
                      list.push([v0, v1]);
                      if (!(v0 in seen[0][1])) {
                        seen[0][1][v0] = seen[0][0]++;
                      }
                      if (!(v1 in seen[1][1])) {
                        seen[1][1][v1] = seen[1][0]++;
                      }
                    }
                  }
                }
              }
            }
            list.sort(function(a, b) {
              var ind0 = seen[0][1];
              var d = ind0[a[0]] - ind0[b[0]];
              if (d) return d;
              var ind1 = seen[1][1];
              return ind1[a[1]] - ind1[b[1]];
            });
            for (i = 0; i < list.length; i++) {
              setCategoryIndex(list[i]);
            }
          };
        }
        ax.fraction2r = function(v) {
          var rl0 = ax.r2l(ax.range[0]);
          var rl1 = ax.r2l(ax.range[1]);
          return ax.l2r(rl0 + v * (rl1 - rl0));
        };
        ax.r2fraction = function(v) {
          var rl0 = ax.r2l(ax.range[0]);
          var rl1 = ax.r2l(ax.range[1]);
          return (ax.r2l(v) - rl0) / (rl1 - rl0);
        };
        ax.limitRange = function(rangeAttr) {
          var minallowed = ax.minallowed;
          var maxallowed = ax.maxallowed;
          if (minallowed === void 0 && maxallowed === void 0) return;
          if (!rangeAttr) rangeAttr = "range";
          var range = Lib.nestedProperty(ax, rangeAttr).get();
          var rng = Lib.simpleMap(range, ax.r2l);
          var axrev = rng[1] < rng[0];
          if (axrev) rng.reverse();
          var bounds = Lib.simpleMap([minallowed, maxallowed], ax.r2l);
          if (minallowed !== void 0 && rng[0] < bounds[0]) range[axrev ? 1 : 0] = minallowed;
          if (maxallowed !== void 0 && rng[1] > bounds[1]) range[axrev ? 0 : 1] = maxallowed;
          if (range[0] === range[1]) {
            var minL = ax.l2r(minallowed);
            var maxL = ax.l2r(maxallowed);
            if (minallowed !== void 0) {
              var _max = minL + 1;
              if (maxallowed !== void 0) _max = Math.min(_max, maxL);
              range[axrev ? 1 : 0] = _max;
            }
            if (maxallowed !== void 0) {
              var _min = maxL + 1;
              if (minallowed !== void 0) _min = Math.max(_min, minL);
              range[axrev ? 0 : 1] = _min;
            }
          }
        };
        ax.cleanRange = function(rangeAttr, opts) {
          ax._cleanRange(rangeAttr, opts);
          ax.limitRange(rangeAttr);
        };
        ax._cleanRange = function(rangeAttr, opts) {
          if (!opts) opts = {};
          if (!rangeAttr) rangeAttr = "range";
          var range = Lib.nestedProperty(ax, rangeAttr).get();
          var i, dflt;
          if (ax.type === "date") dflt = Lib.dfltRange(ax.calendar);
          else if (axLetter === "y") dflt = constants.DFLTRANGEY;
          else if (ax._name === "realaxis") dflt = [0, 1];
          else dflt = opts.dfltRange || constants.DFLTRANGEX;
          dflt = dflt.slice();
          if (ax.rangemode === "tozero" || ax.rangemode === "nonnegative") {
            dflt[0] = 0;
          }
          if (!range || range.length !== 2) {
            Lib.nestedProperty(ax, rangeAttr).set(dflt);
            return;
          }
          var nullRange0 = range[0] === null;
          var nullRange1 = range[1] === null;
          if (ax.type === "date" && !ax.autorange) {
            range[0] = Lib.cleanDate(range[0], BADNUM, ax.calendar);
            range[1] = Lib.cleanDate(range[1], BADNUM, ax.calendar);
          }
          for (i = 0; i < 2; i++) {
            if (ax.type === "date") {
              if (!Lib.isDateTime(range[i], ax.calendar)) {
                ax[rangeAttr] = dflt;
                break;
              }
              if (ax.r2l(range[0]) === ax.r2l(range[1])) {
                var linCenter = Lib.constrain(
                  ax.r2l(range[0]),
                  Lib.MIN_MS + 1e3,
                  Lib.MAX_MS - 1e3
                );
                range[0] = ax.l2r(linCenter - 1e3);
                range[1] = ax.l2r(linCenter + 1e3);
                break;
              }
            } else {
              if (!isNumeric(range[i])) {
                if (!(nullRange0 || nullRange1) && isNumeric(range[1 - i])) {
                  range[i] = range[1 - i] * (i ? 10 : 0.1);
                } else {
                  ax[rangeAttr] = dflt;
                  break;
                }
              }
              if (range[i] < -FP_SAFE) range[i] = -FP_SAFE;
              else if (range[i] > FP_SAFE) range[i] = FP_SAFE;
              if (range[0] === range[1]) {
                var inc = Math.max(1, Math.abs(range[0] * 1e-6));
                range[0] -= inc;
                range[1] += inc;
              }
            }
          }
        };
        ax.setScale = function(usePrivateRange) {
          var gs = fullLayout._size;
          if (ax.overlaying) {
            var ax2 = axisIds.getFromId({ _fullLayout: fullLayout }, ax.overlaying);
            ax.domain = ax2.domain;
          }
          var rangeAttr = usePrivateRange && ax._r ? "_r" : "range";
          var calendar = ax.calendar;
          ax.cleanRange(rangeAttr);
          var rl0 = ax.r2l(ax[rangeAttr][0], calendar);
          var rl1 = ax.r2l(ax[rangeAttr][1], calendar);
          var isY2 = axLetter === "y";
          if (isY2) {
            ax._offset = gs.t + (1 - ax.domain[1]) * gs.h;
            ax._length = gs.h * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl0 - rl1);
            ax._b = -ax._m * rl1;
          } else {
            ax._offset = gs.l + ax.domain[0] * gs.w;
            ax._length = gs.w * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl1 - rl0);
            ax._b = -ax._m * rl0;
          }
          ax._rangebreaks = [];
          ax._lBreaks = 0;
          ax._m2 = 0;
          ax._B = [];
          if (ax.rangebreaks) {
            var i, brk;
            ax._rangebreaks = ax.locateBreaks(
              Math.min(rl0, rl1),
              Math.max(rl0, rl1)
            );
            if (ax._rangebreaks.length) {
              for (i = 0; i < ax._rangebreaks.length; i++) {
                brk = ax._rangebreaks[i];
                ax._lBreaks += Math.abs(brk.max - brk.min);
              }
              var flip = isY2;
              if (rl0 > rl1) flip = !flip;
              if (flip) ax._rangebreaks.reverse();
              var sign = flip ? -1 : 1;
              ax._m2 = sign * ax._length / (Math.abs(rl1 - rl0) - ax._lBreaks);
              ax._B.push(-ax._m2 * (isY2 ? rl1 : rl0));
              for (i = 0; i < ax._rangebreaks.length; i++) {
                brk = ax._rangebreaks[i];
                ax._B.push(
                  ax._B[ax._B.length - 1] - sign * ax._m2 * (brk.max - brk.min)
                );
              }
              for (i = 0; i < ax._rangebreaks.length; i++) {
                brk = ax._rangebreaks[i];
                brk.pmin = l2p(brk.min);
                brk.pmax = l2p(brk.max);
              }
            }
          }
          if (!isFinite(ax._m) || !isFinite(ax._b) || ax._length < 0) {
            fullLayout._replotting = false;
            throw new Error("Something went wrong with axis scaling");
          }
        };
        ax.maskBreaks = function(v) {
          var rangebreaksIn = ax.rangebreaks || [];
          var bnds, b0, b1, vb, vDate;
          if (!rangebreaksIn._cachedPatterns) {
            rangebreaksIn._cachedPatterns = rangebreaksIn.map(function(brk2) {
              return brk2.enabled && brk2.bounds ? Lib.simpleMap(
                brk2.bounds,
                brk2.pattern ? cleanNumber : ax.d2c
                // case of pattern: ''
              ) : null;
            });
          }
          if (!rangebreaksIn._cachedValues) {
            rangebreaksIn._cachedValues = rangebreaksIn.map(function(brk2) {
              return brk2.enabled && brk2.values ? Lib.simpleMap(brk2.values, ax.d2c).sort(Lib.sorterAsc) : null;
            });
          }
          for (var i = 0; i < rangebreaksIn.length; i++) {
            var brk = rangebreaksIn[i];
            if (brk.enabled) {
              if (brk.bounds) {
                var pattern = brk.pattern;
                bnds = rangebreaksIn._cachedPatterns[i];
                b0 = bnds[0];
                b1 = bnds[1];
                switch (pattern) {
                  case WEEKDAY_PATTERN:
                    vDate = new Date(v);
                    vb = vDate.getUTCDay();
                    if (b0 > b1) {
                      b1 += 7;
                      if (vb < b0) vb += 7;
                    }
                    break;
                  case HOUR_PATTERN:
                    vDate = new Date(v);
                    var hours = vDate.getUTCHours();
                    var minutes = vDate.getUTCMinutes();
                    var seconds = vDate.getUTCSeconds();
                    var milliseconds = vDate.getUTCMilliseconds();
                    vb = hours + (minutes / 60 + seconds / 3600 + milliseconds / 36e5);
                    if (b0 > b1) {
                      b1 += 24;
                      if (vb < b0) vb += 24;
                    }
                    break;
                  case "":
                    vb = v;
                    break;
                }
                if (vb >= b0 && vb < b1) return BADNUM;
              } else {
                var vals = rangebreaksIn._cachedValues[i];
                for (var j = 0; j < vals.length; j++) {
                  b0 = vals[j];
                  b1 = b0 + brk.dvalue;
                  if (v >= b0 && v < b1) return BADNUM;
                }
              }
            }
          }
          return v;
        };
        ax.locateBreaks = function(r0, r1) {
          var i, bnds, b0, b1;
          var rangebreaksOut = [];
          if (!ax.rangebreaks) return rangebreaksOut;
          var rangebreaksIn = ax.rangebreaks.slice().sort(function(a, b) {
            if (a.pattern === WEEKDAY_PATTERN && b.pattern === HOUR_PATTERN) return -1;
            if (b.pattern === WEEKDAY_PATTERN && a.pattern === HOUR_PATTERN) return 1;
            return 0;
          });
          var addBreak = function(min, max) {
            min = Lib.constrain(min, r0, r1);
            max = Lib.constrain(max, r0, r1);
            if (min === max) return;
            var isNewBreak = true;
            for (var j2 = 0; j2 < rangebreaksOut.length; j2++) {
              var brkj = rangebreaksOut[j2];
              if (min < brkj.max && max >= brkj.min) {
                if (min < brkj.min) {
                  brkj.min = min;
                }
                if (max > brkj.max) {
                  brkj.max = max;
                }
                isNewBreak = false;
              }
            }
            if (isNewBreak) {
              rangebreaksOut.push({ min, max });
            }
          };
          for (i = 0; i < rangebreaksIn.length; i++) {
            var brk = rangebreaksIn[i];
            if (brk.enabled) {
              if (brk.bounds) {
                var t02 = r0;
                var t12 = r1;
                if (brk.pattern) {
                  t02 = Math.floor(t02);
                }
                bnds = Lib.simpleMap(brk.bounds, brk.pattern ? cleanNumber : ax.r2l);
                b0 = bnds[0];
                b1 = bnds[1];
                var t0Date = new Date(t02);
                var bndDelta;
                var step;
                switch (brk.pattern) {
                  case WEEKDAY_PATTERN:
                    step = ONEWEEK;
                    bndDelta = ((b1 < b0 ? 7 : 0) + (b1 - b0)) * ONEDAY;
                    t02 += b0 * ONEDAY - (t0Date.getUTCDay() * ONEDAY + t0Date.getUTCHours() * ONEHOUR + t0Date.getUTCMinutes() * ONEMIN + t0Date.getUTCSeconds() * ONESEC + t0Date.getUTCMilliseconds());
                    break;
                  case HOUR_PATTERN:
                    step = ONEDAY;
                    bndDelta = ((b1 < b0 ? 24 : 0) + (b1 - b0)) * ONEHOUR;
                    t02 += b0 * ONEHOUR - (t0Date.getUTCHours() * ONEHOUR + t0Date.getUTCMinutes() * ONEMIN + t0Date.getUTCSeconds() * ONESEC + t0Date.getUTCMilliseconds());
                    break;
                  default:
                    t02 = Math.min(bnds[0], bnds[1]);
                    t12 = Math.max(bnds[0], bnds[1]);
                    step = t12 - t02;
                    bndDelta = step;
                }
                for (var t = t02; t < t12; t += step) {
                  addBreak(t, t + bndDelta);
                }
              } else {
                var vals = Lib.simpleMap(brk.values, ax.d2c);
                for (var j = 0; j < vals.length; j++) {
                  b0 = vals[j];
                  b1 = b0 + brk.dvalue;
                  addBreak(b0, b1);
                }
              }
            }
          }
          rangebreaksOut.sort(function(a, b) {
            return a.min - b.min;
          });
          return rangebreaksOut;
        };
        ax.makeCalcdata = function(trace, axLetter2, opts) {
          var arrayIn, arrayOut, i, len;
          var axType = ax.type;
          var cal = axType === "date" && trace[axLetter2 + "calendar"];
          if (axLetter2 in trace) {
            arrayIn = trace[axLetter2];
            len = trace._length || Lib.minRowLength(arrayIn);
            if (Lib.isTypedArray(arrayIn) && (axType === "linear" || axType === "log")) {
              if (len === arrayIn.length) {
                return arrayIn;
              } else if (arrayIn.subarray) {
                return arrayIn.subarray(0, len);
              }
            }
            if (axType === "multicategory") {
              return setMultiCategoryIndex(arrayIn, len);
            }
            arrayOut = new Array(len);
            for (i = 0; i < len; i++) {
              arrayOut[i] = ax.d2c(arrayIn[i], 0, cal, opts);
            }
          } else {
            var v0 = axLetter2 + "0" in trace ? ax.d2c(trace[axLetter2 + "0"], 0, cal) : 0;
            var dv = trace["d" + axLetter2] ? Number(trace["d" + axLetter2]) : 1;
            arrayIn = trace[{ x: "y", y: "x" }[axLetter2]];
            len = trace._length || arrayIn.length;
            arrayOut = new Array(len);
            for (i = 0; i < len; i++) {
              arrayOut[i] = v0 + i * dv;
            }
          }
          if (ax.rangebreaks) {
            for (i = 0; i < len; i++) {
              arrayOut[i] = ax.maskBreaks(arrayOut[i]);
            }
          }
          return arrayOut;
        };
        ax.isValidRange = function(range, nullOk) {
          return Array.isArray(range) && range.length === 2 && (nullOk && range[0] === null || isNumeric(ax.r2l(range[0]))) && (nullOk && range[1] === null || isNumeric(ax.r2l(range[1])));
        };
        ax.getAutorangeDflt = function(range, options) {
          var autorangeDflt = !ax.isValidRange(range, "nullOk");
          if (autorangeDflt && options && options.reverseDflt) autorangeDflt = "reversed";
          else if (range) {
            if (range[0] === null && range[1] === null) {
              autorangeDflt = true;
            } else if (range[0] === null && range[1] !== null) {
              autorangeDflt = "min";
            } else if (range[0] !== null && range[1] === null) {
              autorangeDflt = "max";
            }
          }
          return autorangeDflt;
        };
        ax.isReversed = function() {
          var autorange = ax.autorange;
          return autorange === "reversed" || autorange === "min reversed" || autorange === "max reversed";
        };
        ax.isPtWithinRange = function(d, calendar) {
          var coord = ax.c2l(d[axLetter], null, calendar);
          var r0 = ax.r2l(ax.range[0]);
          var r1 = ax.r2l(ax.range[1]);
          if (r0 < r1) {
            return r0 <= coord && coord <= r1;
          } else {
            return r1 <= coord && coord <= r0;
          }
        };
        ax._emptyCategories = function() {
          ax._categories = [];
          ax._categoriesMap = {};
        };
        ax.clearCalc = function() {
          var group = ax._matchGroup;
          if (group) {
            var categories = null;
            var categoriesMap = null;
            for (var axId2 in group) {
              var ax2 = fullLayout[axisIds.id2name(axId2)];
              if (ax2._categories) {
                categories = ax2._categories;
                categoriesMap = ax2._categoriesMap;
                break;
              }
            }
            if (categories && categoriesMap) {
              ax._categories = categories;
              ax._categoriesMap = categoriesMap;
            } else {
              ax._emptyCategories();
            }
          } else {
            ax._emptyCategories();
          }
          if (ax._initialCategories) {
            for (var j = 0; j < ax._initialCategories.length; j++) {
              setCategoryIndex(ax._initialCategories[j]);
            }
          }
        };
        ax.sortByInitialCategories = function() {
          var affectedTraces = [];
          ax._emptyCategories();
          if (ax._initialCategories) {
            for (var j = 0; j < ax._initialCategories.length; j++) {
              setCategoryIndex(ax._initialCategories[j]);
            }
          }
          affectedTraces = affectedTraces.concat(ax._traceIndices);
          var group = ax._matchGroup;
          for (var axId2 in group) {
            if (axId === axId2) continue;
            var ax2 = fullLayout[axisIds.id2name(axId2)];
            ax2._categories = ax._categories;
            ax2._categoriesMap = ax._categoriesMap;
            affectedTraces = affectedTraces.concat(ax2._traceIndices);
          }
          return affectedTraces;
        };
        var locale = fullLayout._d3locale;
        if (ax.type === "date") {
          ax._dateFormat = locale ? locale.timeFormat : utcFormat;
          ax._extraFormat = fullLayout._extraFormat;
        }
        ax._separators = fullLayout.separators;
        ax._numFormat = locale ? locale.numberFormat : numberFormat;
        delete ax._minDtick;
        delete ax._forceTick0;
      };
    }
  });

  // src/plots/cartesian/axis_autotype.js
  var require_axis_autotype = __commonJS({
    "src/plots/cartesian/axis_autotype.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var BADNUM = require_numerical().BADNUM;
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var isDateTime = Lib.isDateTime;
      var cleanNumber = Lib.cleanNumber;
      var round = Math.round;
      module.exports = function autoType(array, calendar, opts) {
        var a = array;
        var noMultiCategory = opts.noMultiCategory;
        if (isArrayOrTypedArray(a) && !a.length) return "-";
        if (!noMultiCategory && multiCategory(a)) return "multicategory";
        if (noMultiCategory && Array.isArray(a[0])) {
          var b = [];
          for (var i = 0; i < a.length; i++) {
            if (isArrayOrTypedArray(a[i])) {
              for (var j = 0; j < a[i].length; j++) {
                b.push(a[i][j]);
              }
            }
          }
          a = b;
        }
        if (moreDates(a, calendar)) return "date";
        var convertNumeric = opts.autotypenumbers !== "strict";
        if (category(a, convertNumeric)) return "category";
        if (linearOK(a, convertNumeric)) return "linear";
        return "-";
      };
      function hasTypeNumber(v, convertNumeric) {
        return convertNumeric ? isNumeric(v) : typeof v === "number";
      }
      function linearOK(a, convertNumeric) {
        var len = a.length;
        for (var i = 0; i < len; i++) {
          if (hasTypeNumber(a[i], convertNumeric)) return true;
        }
        return false;
      }
      function moreDates(a, calendar) {
        var len = a.length;
        var inc = getIncrement(len);
        var dats = 0;
        var nums = 0;
        var seen = {};
        for (var f = 0; f < len; f += inc) {
          var i = round(f);
          var ai = a[i];
          var stri = String(ai);
          if (seen[stri]) continue;
          seen[stri] = 1;
          if (isDateTime(ai, calendar)) dats++;
          if (isNumeric(ai)) nums++;
        }
        return dats > nums * 2;
      }
      function getIncrement(len) {
        return Math.max(1, (len - 1) / 1e3);
      }
      function category(a, convertNumeric) {
        var len = a.length;
        var inc = getIncrement(len);
        var nums = 0;
        var cats = 0;
        var seen = {};
        for (var f = 0; f < len; f += inc) {
          var i = round(f);
          var ai = a[i];
          var stri = String(ai);
          if (seen[stri]) continue;
          seen[stri] = 1;
          var t = typeof ai;
          if (t === "boolean") cats++;
          else if (convertNumeric ? cleanNumber(ai) !== BADNUM : t === "number") nums++;
          else if (t === "string") cats++;
        }
        return cats > nums * 2;
      }
      function multiCategory(a) {
        return isArrayOrTypedArray(a[0]) && isArrayOrTypedArray(a[1]);
      }
    }
  });

  // src/plots/cartesian/autorange.js
  var require_autorange = __commonJS({
    "src/plots/cartesian/autorange.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var FP_SAFE = require_numerical().FP_SAFE;
      var Registry = require_registry();
      var Drawing = require_drawing();
      var axIds = require_axis_ids();
      var getFromId = axIds.getFromId;
      var isLinked = axIds.isLinked;
      module.exports = {
        applyAutorangeOptions,
        getAutoRange,
        makePadFn,
        doAutoRange,
        findExtremes,
        concatExtremes
      };
      function getAutoRange(gd, ax) {
        var i, j;
        var newRange = [];
        var fullLayout = gd._fullLayout;
        var getPadMin = makePadFn(fullLayout, ax, 0);
        var getPadMax = makePadFn(fullLayout, ax, 1);
        var extremes = concatExtremes(gd, ax);
        var minArray = extremes.min;
        var maxArray = extremes.max;
        if (minArray.length === 0 || maxArray.length === 0) {
          return Lib.simpleMap(ax.range, ax.r2l);
        }
        var minmin = minArray[0].val;
        var maxmax = maxArray[0].val;
        for (i = 1; i < minArray.length; i++) {
          if (minmin !== maxmax) break;
          minmin = Math.min(minmin, minArray[i].val);
        }
        for (i = 1; i < maxArray.length; i++) {
          if (minmin !== maxmax) break;
          maxmax = Math.max(maxmax, maxArray[i].val);
        }
        var autorange = ax.autorange;
        var axReverse = autorange === "reversed" || autorange === "min reversed" || autorange === "max reversed";
        if (!axReverse && ax.range) {
          var rng = Lib.simpleMap(ax.range, ax.r2l);
          axReverse = rng[1] < rng[0];
        }
        if (ax.autorange === "reversed") {
          ax.autorange = true;
        }
        var rangeMode = ax.rangemode;
        var toZero = rangeMode === "tozero";
        var nonNegative = rangeMode === "nonnegative";
        var axLen = ax._length;
        var minSpan = axLen / 10;
        var mbest = 0;
        var minpt, maxpt, minbest, maxbest, dp, dv;
        for (i = 0; i < minArray.length; i++) {
          minpt = minArray[i];
          for (j = 0; j < maxArray.length; j++) {
            maxpt = maxArray[j];
            dv = maxpt.val - minpt.val - calcBreaksLength(ax, minpt.val, maxpt.val);
            if (dv > 0) {
              dp = axLen - getPadMin(minpt) - getPadMax(maxpt);
              if (dp > minSpan) {
                if (dv / dp > mbest) {
                  minbest = minpt;
                  maxbest = maxpt;
                  mbest = dv / dp;
                }
              } else if (dv / axLen > mbest) {
                minbest = { val: minpt.val, nopad: 1 };
                maxbest = { val: maxpt.val, nopad: 1 };
                mbest = dv / axLen;
              }
            }
          }
        }
        function maximumPad(prev, pt) {
          return Math.max(prev, getPadMax(pt));
        }
        if (minmin === maxmax) {
          var lower = minmin - 1;
          var upper = minmin + 1;
          if (toZero) {
            if (minmin === 0) {
              newRange = [0, 1];
            } else {
              var maxPad = (minmin > 0 ? maxArray : minArray).reduce(maximumPad, 0);
              var rangeEnd = minmin / (1 - Math.min(0.5, maxPad / axLen));
              newRange = minmin > 0 ? [0, rangeEnd] : [rangeEnd, 0];
            }
          } else if (nonNegative) {
            newRange = [Math.max(0, lower), Math.max(1, upper)];
          } else {
            newRange = [lower, upper];
          }
        } else {
          if (toZero) {
            if (minbest.val >= 0) {
              minbest = { val: 0, nopad: 1 };
            }
            if (maxbest.val <= 0) {
              maxbest = { val: 0, nopad: 1 };
            }
          } else if (nonNegative) {
            if (minbest.val - mbest * getPadMin(minbest) < 0) {
              minbest = { val: 0, nopad: 1 };
            }
            if (maxbest.val <= 0) {
              maxbest = { val: 1, nopad: 1 };
            }
          }
          mbest = (maxbest.val - minbest.val - calcBreaksLength(ax, minpt.val, maxpt.val)) / (axLen - getPadMin(minbest) - getPadMax(maxbest));
          newRange = [
            minbest.val - mbest * getPadMin(minbest),
            maxbest.val + mbest * getPadMax(maxbest)
          ];
        }
        newRange = applyAutorangeOptions(newRange, ax);
        if (ax.limitRange) ax.limitRange();
        if (axReverse) newRange.reverse();
        return Lib.simpleMap(newRange, ax.l2r || Number);
      }
      function calcBreaksLength(ax, v0, v1) {
        var lBreaks = 0;
        if (ax.rangebreaks) {
          var rangebreaksOut = ax.locateBreaks(v0, v1);
          for (var i = 0; i < rangebreaksOut.length; i++) {
            var brk = rangebreaksOut[i];
            lBreaks += brk.max - brk.min;
          }
        }
        return lBreaks;
      }
      function makePadFn(fullLayout, ax, max) {
        var extrappad = 0.05 * ax._length;
        var anchorAxis = ax._anchorAxis || {};
        if ((ax.ticklabelposition || "").indexOf("inside") !== -1 || (anchorAxis.ticklabelposition || "").indexOf("inside") !== -1) {
          var axReverse = ax.isReversed();
          if (!axReverse) {
            var rng = Lib.simpleMap(ax.range, ax.r2l);
            axReverse = rng[1] < rng[0];
          }
          if (axReverse) max = !max;
        }
        var zero2 = 0;
        if (!isLinked(fullLayout, ax._id)) {
          zero2 = padInsideLabelsOnAnchorAxis(fullLayout, ax, max);
        }
        extrappad = Math.max(zero2, extrappad);
        if (ax.constrain === "domain" && ax._inputDomain) {
          extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) / (ax.domain[1] - ax.domain[0]);
        }
        return function getPad(pt) {
          if (pt.nopad) return 0;
          return pt.pad + (pt.extrapad ? extrappad : zero2);
        };
      }
      var TEXTPAD = 3;
      function padInsideLabelsOnAnchorAxis(fullLayout, ax, max) {
        var pad = 0;
        var isX = ax._id.charAt(0) === "x";
        for (var subplot in fullLayout._plots) {
          var plotinfo = fullLayout._plots[subplot];
          if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue;
          var anchorAxis = (isX ? plotinfo.yaxis : plotinfo.xaxis) || {};
          if ((anchorAxis.ticklabelposition || "").indexOf("inside") !== -1) {
            if (!max && (anchorAxis.side === "left" || anchorAxis.side === "bottom") || max && (anchorAxis.side === "top" || anchorAxis.side === "right")) {
              if (anchorAxis._vals) {
                var rad = Lib.deg2rad(anchorAxis._tickAngles[anchorAxis._id + "tick"] || 0);
                var cosA = Math.abs(Math.cos(rad));
                var sinA = Math.abs(Math.sin(rad));
                if (!anchorAxis._vals[0].bb) {
                  var cls = anchorAxis._id + "tick";
                  var tickLabels = anchorAxis._selections[cls];
                  tickLabels.each(function(d) {
                    var thisLabel = d3.select(this);
                    var mathjaxGroup = thisLabel.select(".text-math-group");
                    if (mathjaxGroup.empty()) {
                      d.bb = Drawing.bBox(thisLabel.node());
                    }
                  });
                }
                for (var i = 0; i < anchorAxis._vals.length; i++) {
                  var t = anchorAxis._vals[i];
                  var bb = t.bb;
                  if (bb) {
                    var w = 2 * TEXTPAD + bb.width;
                    var h = 2 * TEXTPAD + bb.height;
                    pad = Math.max(
                      pad,
                      isX ? Math.max(w * cosA, h * sinA) : Math.max(h * cosA, w * sinA)
                    );
                  }
                }
              }
              if (anchorAxis.ticks === "inside" && anchorAxis.ticklabelposition === "inside") {
                pad += anchorAxis.ticklen || 0;
              }
            }
          }
        }
        return pad;
      }
      function concatExtremes(gd, ax, noMatch) {
        var axId = ax._id;
        var fullData = gd._fullData;
        var fullLayout = gd._fullLayout;
        var minArray = [];
        var maxArray = [];
        var i, j, d;
        function _concat(cont, indices) {
          for (i = 0; i < indices.length; i++) {
            var item = cont[indices[i]];
            var extremes = (item._extremes || {})[axId];
            if (item.visible === true && extremes) {
              for (j = 0; j < extremes.min.length; j++) {
                d = extremes.min[j];
                collapseMinArray(minArray, d.val, d.pad, { extrapad: d.extrapad });
              }
              for (j = 0; j < extremes.max.length; j++) {
                d = extremes.max[j];
                collapseMaxArray(maxArray, d.val, d.pad, { extrapad: d.extrapad });
              }
            }
          }
        }
        _concat(fullData, ax._traceIndices);
        _concat(fullLayout.annotations || [], ax._annIndices || []);
        _concat(fullLayout.shapes || [], ax._shapeIndices || []);
        if (ax._matchGroup && !noMatch) {
          for (var axId2 in ax._matchGroup) {
            if (axId2 !== ax._id) {
              var ax2 = getFromId(gd, axId2);
              var extremes2 = concatExtremes(gd, ax2, true);
              var lenRatio = ax._length / ax2._length;
              for (j = 0; j < extremes2.min.length; j++) {
                d = extremes2.min[j];
                collapseMinArray(minArray, d.val, d.pad * lenRatio, { extrapad: d.extrapad });
              }
              for (j = 0; j < extremes2.max.length; j++) {
                d = extremes2.max[j];
                collapseMaxArray(maxArray, d.val, d.pad * lenRatio, { extrapad: d.extrapad });
              }
            }
          }
        }
        return { min: minArray, max: maxArray };
      }
      function doAutoRange(gd, ax, presetRange) {
        ax.setScale();
        if (ax.autorange) {
          ax.range = presetRange ? presetRange.slice() : getAutoRange(gd, ax);
          ax._r = ax.range.slice();
          ax._rl = Lib.simpleMap(ax._r, ax.r2l);
          var axIn = ax._input;
          var edits = {};
          edits[ax._attr + ".range"] = ax.range;
          edits[ax._attr + ".autorange"] = ax.autorange;
          Registry.call("_storeDirectGUIEdit", gd.layout, gd._fullLayout._preGUI, edits);
          axIn.range = ax.range.slice();
          axIn.autorange = ax.autorange;
        }
        var anchorAx = ax._anchorAxis;
        if (anchorAx && anchorAx.rangeslider) {
          var axeRangeOpts = anchorAx.rangeslider[ax._name];
          if (axeRangeOpts) {
            if (axeRangeOpts.rangemode === "auto") {
              axeRangeOpts.range = getAutoRange(gd, ax);
            }
          }
          anchorAx._input.rangeslider[ax._name] = Lib.extendFlat({}, axeRangeOpts);
        }
      }
      function findExtremes(ax, data, opts) {
        if (!opts) opts = {};
        if (!ax._m) ax.setScale();
        var minArray = [];
        var maxArray = [];
        var len = data.length;
        var extrapad = opts.padded || false;
        var tozero = opts.tozero && (ax.type === "linear" || ax.type === "-");
        var isLog = ax.type === "log";
        var hasArrayOption = false;
        var vpadLinearized = opts.vpadLinearized || false;
        var i, v, di, dmin, dmax, ppadiplus, ppadiminus, vmin, vmax;
        function makePadAccessor(item) {
          if (Array.isArray(item)) {
            hasArrayOption = true;
            return function(i2) {
              return Math.max(Number(item[i2] || 0), 0);
            };
          } else {
            var v2 = Math.max(Number(item || 0), 0);
            return function() {
              return v2;
            };
          }
        }
        var ppadplus = makePadAccessor((ax._m > 0 ? opts.ppadplus : opts.ppadminus) || opts.ppad || 0);
        var ppadminus = makePadAccessor((ax._m > 0 ? opts.ppadminus : opts.ppadplus) || opts.ppad || 0);
        var vpadplus = makePadAccessor(opts.vpadplus || opts.vpad);
        var vpadminus = makePadAccessor(opts.vpadminus || opts.vpad);
        if (!hasArrayOption) {
          vmin = Infinity;
          vmax = -Infinity;
          if (isLog) {
            for (i = 0; i < len; i++) {
              v = data[i];
              if (v < vmin && v > 0) vmin = v;
              if (v > vmax && v < FP_SAFE) vmax = v;
            }
          } else {
            for (i = 0; i < len; i++) {
              v = data[i];
              if (v < vmin && v > -FP_SAFE) vmin = v;
              if (v > vmax && v < FP_SAFE) vmax = v;
            }
          }
          data = [vmin, vmax];
          len = 2;
        }
        var collapseOpts = { tozero, extrapad };
        function addItem(i2) {
          di = data[i2];
          if (!isNumeric(di)) return;
          ppadiplus = ppadplus(i2);
          ppadiminus = ppadminus(i2);
          if (vpadLinearized) {
            dmin = ax.c2l(di) - vpadminus(i2);
            dmax = ax.c2l(di) + vpadplus(i2);
          } else {
            vmin = di - vpadminus(i2);
            vmax = di + vpadplus(i2);
            if (isLog && vmin < vmax / 10) vmin = vmax / 10;
            dmin = ax.c2l(vmin);
            dmax = ax.c2l(vmax);
          }
          if (tozero) {
            dmin = Math.min(0, dmin);
            dmax = Math.max(0, dmax);
          }
          if (goodNumber(dmin)) {
            collapseMinArray(minArray, dmin, ppadiminus, collapseOpts);
          }
          if (goodNumber(dmax)) {
            collapseMaxArray(maxArray, dmax, ppadiplus, collapseOpts);
          }
        }
        var iMax = Math.min(6, len);
        for (i = 0; i < iMax; i++) addItem(i);
        for (i = len - 1; i >= iMax; i--) addItem(i);
        return {
          min: minArray,
          max: maxArray,
          opts
        };
      }
      function collapseMinArray(array, newVal, newPad, opts) {
        collapseArray(array, newVal, newPad, opts, lessOrEqual);
      }
      function collapseMaxArray(array, newVal, newPad, opts) {
        collapseArray(array, newVal, newPad, opts, greaterOrEqual);
      }
      function collapseArray(array, newVal, newPad, opts, atLeastAsExtreme) {
        var tozero = opts.tozero;
        var extrapad = opts.extrapad;
        var includeThis = true;
        for (var j = 0; j < array.length && includeThis; j++) {
          var v = array[j];
          if (atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) {
            includeThis = false;
            break;
          } else if (atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) {
            array.splice(j, 1);
            j--;
          }
        }
        if (includeThis) {
          var clipAtZero = tozero && newVal === 0;
          array.push({
            val: newVal,
            pad: clipAtZero ? 0 : newPad,
            extrapad: clipAtZero ? false : extrapad
          });
        }
      }
      function goodNumber(v) {
        return isNumeric(v) && Math.abs(v) < FP_SAFE;
      }
      function lessOrEqual(v0, v1) {
        return v0 <= v1;
      }
      function greaterOrEqual(v0, v1) {
        return v0 >= v1;
      }
      function applyAutorangeMinOptions(v, ax) {
        var autorangeoptions = ax.autorangeoptions;
        if (autorangeoptions && autorangeoptions.minallowed !== void 0 && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) {
          return autorangeoptions.minallowed;
        }
        if (autorangeoptions && autorangeoptions.clipmin !== void 0 && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) {
          return Math.max(v, ax.d2l(autorangeoptions.clipmin));
        }
        return v;
      }
      function applyAutorangeMaxOptions(v, ax) {
        var autorangeoptions = ax.autorangeoptions;
        if (autorangeoptions && autorangeoptions.maxallowed !== void 0 && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) {
          return autorangeoptions.maxallowed;
        }
        if (autorangeoptions && autorangeoptions.clipmax !== void 0 && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) {
          return Math.min(v, ax.d2l(autorangeoptions.clipmax));
        }
        return v;
      }
      function hasValidMinAndMax(ax, min, max) {
        if (min !== void 0 && max !== void 0) {
          min = ax.d2l(min);
          max = ax.d2l(max);
          return min < max;
        }
        return true;
      }
      function applyAutorangeOptions(range, ax) {
        if (!ax || !ax.autorangeoptions) return range;
        var min = range[0];
        var max = range[1];
        var include = ax.autorangeoptions.include;
        if (include !== void 0) {
          var lMin = ax.d2l(min);
          var lMax = ax.d2l(max);
          if (!Lib.isArrayOrTypedArray(include)) include = [include];
          for (var i = 0; i < include.length; i++) {
            var v = ax.d2l(include[i]);
            if (lMin >= v) {
              lMin = v;
              min = v;
            }
            if (lMax <= v) {
              lMax = v;
              max = v;
            }
          }
        }
        min = applyAutorangeMinOptions(min, ax);
        max = applyAutorangeMaxOptions(max, ax);
        return [min, max];
      }
    }
  });

  // src/plots/cartesian/axes.js
  var require_axes = __commonJS({
    "src/plots/cartesian/axes.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var Plots = require_plots();
      var Registry = require_registry();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var Titles = require_titles();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var axAttrs = require_layout_attributes4();
      var cleanTicks = require_clean_ticks();
      var cartesianConstants = require_constants2();
      var constants = require_numerical();
      var ONEMAXYEAR = constants.ONEMAXYEAR;
      var ONEAVGYEAR = constants.ONEAVGYEAR;
      var ONEMINYEAR = constants.ONEMINYEAR;
      var ONEMAXQUARTER = constants.ONEMAXQUARTER;
      var ONEAVGQUARTER = constants.ONEAVGQUARTER;
      var ONEMINQUARTER = constants.ONEMINQUARTER;
      var ONEMAXMONTH = constants.ONEMAXMONTH;
      var ONEAVGMONTH = constants.ONEAVGMONTH;
      var ONEMINMONTH = constants.ONEMINMONTH;
      var ONEWEEK = constants.ONEWEEK;
      var ONEDAY = constants.ONEDAY;
      var HALFDAY = ONEDAY / 2;
      var ONEHOUR = constants.ONEHOUR;
      var ONEMIN = constants.ONEMIN;
      var ONESEC = constants.ONESEC;
      var ONEMILLI = constants.ONEMILLI;
      var ONEMICROSEC = constants.ONEMICROSEC;
      var MINUS_SIGN = constants.MINUS_SIGN;
      var BADNUM = constants.BADNUM;
      var ZERO_PATH = { K: "zeroline" };
      var GRID_PATH = { K: "gridline", L: "path" };
      var MINORGRID_PATH = { K: "minor-gridline", L: "path" };
      var TICK_PATH = { K: "tick", L: "path" };
      var TICK_TEXT = { K: "tick", L: "text" };
      var MARGIN_MAPPING = {
        width: ["x", "r", "l", "xl", "xr"],
        height: ["y", "t", "b", "yt", "yb"],
        right: ["r", "xr"],
        left: ["l", "xl"],
        top: ["t", "yt"],
        bottom: ["b", "yb"]
      };
      var alignmentConstants = require_alignment();
      var MID_SHIFT = alignmentConstants.MID_SHIFT;
      var CAP_SHIFT = alignmentConstants.CAP_SHIFT;
      var LINE_SPACING = alignmentConstants.LINE_SPACING;
      var OPPOSITE_SIDE = alignmentConstants.OPPOSITE_SIDE;
      var TEXTPAD = 3;
      var axes = module.exports = {};
      axes.setConvert = require_set_convert();
      var autoType = require_axis_autotype();
      var axisIds = require_axis_ids();
      var idSort = axisIds.idSort;
      var isLinked = axisIds.isLinked;
      axes.id2name = axisIds.id2name;
      axes.name2id = axisIds.name2id;
      axes.cleanId = axisIds.cleanId;
      axes.list = axisIds.list;
      axes.listIds = axisIds.listIds;
      axes.getFromId = axisIds.getFromId;
      axes.getFromTrace = axisIds.getFromTrace;
      var autorange = require_autorange();
      axes.getAutoRange = autorange.getAutoRange;
      axes.findExtremes = autorange.findExtremes;
      var epsilon = 1e-4;
      function expandRange(range) {
        var delta = (range[1] - range[0]) * epsilon;
        return [
          range[0] - delta,
          range[1] + delta
        ];
      }
      axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption) {
        var axLetter = attr.charAt(attr.length - 1);
        var axlist = gd._fullLayout._subplots[axLetter + "axis"];
        var refAttr = attr + "ref";
        var attrDef = {};
        if (!dflt) dflt = axlist[0] || (typeof extraOption === "string" ? extraOption : extraOption[0]);
        if (!extraOption) extraOption = dflt;
        axlist = axlist.concat(axlist.map(function(x) {
          return x + " domain";
        }));
        attrDef[refAttr] = {
          valType: "enumerated",
          values: axlist.concat(extraOption ? typeof extraOption === "string" ? [extraOption] : extraOption : []),
          dflt
        };
        return Lib.coerce(containerIn, containerOut, attrDef, refAttr);
      };
      axes.coerceRefArray = function(containerIn, containerOut, gd, attr, dflt, extraOption, expectedLen) {
        const axLetter = attr.charAt(attr.length - 1);
        var axlist = gd._fullLayout._subplots[axLetter + "axis"];
        const refAttr = attr + "ref";
        var axRef = containerIn[refAttr];
        if (!dflt) dflt = axlist[0] || (typeof extraOption === "string" ? extraOption : extraOption[0]);
        axlist = axlist.concat(axlist.map((x) => x + " domain"));
        axlist = axlist.concat(extraOption ? extraOption : []);
        if (axRef.length > expectedLen) {
          Lib.warn("Array attribute " + refAttr + " has more entries than expected, truncating to " + expectedLen);
          axRef = axRef.slice(0, expectedLen);
        } else if (axRef.length < expectedLen) {
          Lib.warn("Array attribute " + refAttr + " has fewer entries than expected, extending with default value");
          axRef = axRef.concat(Array(expectedLen - axRef.length).fill(dflt));
        }
        for (var i = 0; i < axRef.length; i++) {
          axRef[i] = axisIds.cleanId(axRef[i], axLetter, true) || axRef[i];
          if (!axlist.includes(axRef[i])) axRef[i] = dflt;
        }
        containerOut[refAttr] = axRef;
        return axRef;
      };
      axes.getRefType = function(ar) {
        if (ar === void 0) {
          return ar;
        }
        if (Array.isArray(ar)) {
          return "array";
        }
        if (ar === "paper") {
          return "paper";
        }
        if (ar === "pixel") {
          return "pixel";
        }
        if (/( domain)$/.test(ar)) {
          return "domain";
        } else {
          return "range";
        }
      };
      axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) {
        var cleanPos, pos;
        var axRefType = axes.getRefType(axRef);
        if (axRefType !== "range") {
          cleanPos = Lib.ensureNumber;
          pos = coerce(attr, dflt);
        } else {
          var ax = axes.getFromId(gd, axRef);
          dflt = ax.fraction2r(dflt);
          pos = coerce(attr, dflt);
          cleanPos = ax.cleanPos;
        }
        containerOut[attr] = cleanPos(pos);
      };
      axes.cleanPosition = function(pos, gd, axRef) {
        var cleanPos = axRef === "paper" || axRef === "pixel" ? Lib.ensureNumber : axes.getFromId(gd, axRef).cleanPos;
        return cleanPos(pos);
      };
      axes.redrawComponents = function(gd, axIds) {
        axIds = axIds ? axIds : axes.listIds(gd);
        var fullLayout = gd._fullLayout;
        function _redrawOneComp(moduleName, methodName, stashName, shortCircuit) {
          var method = Registry.getComponentMethod(moduleName, methodName);
          var stash = {};
          for (var i = 0; i < axIds.length; i++) {
            var ax = fullLayout[axes.id2name(axIds[i])];
            var indices = ax[stashName];
            for (var j = 0; j < indices.length; j++) {
              var ind = indices[j];
              if (!stash[ind]) {
                method(gd, ind);
                stash[ind] = 1;
                if (shortCircuit) return;
              }
            }
          }
        }
        _redrawOneComp("annotations", "drawOne", "_annIndices");
        _redrawOneComp("shapes", "drawOne", "_shapeIndices");
        _redrawOneComp("images", "draw", "_imgIndices", true);
        _redrawOneComp("selections", "drawOne", "_selectionIndices");
      };
      var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) {
        var ax;
        var d2cTarget = target === "x" || target === "y" || target === "z" ? target : targetArray;
        if (Lib.isArrayOrTypedArray(d2cTarget)) {
          ax = {
            type: autoType(targetArray, void 0, {
              autotypenumbers: gd._fullLayout.autotypenumbers
            }),
            _categories: []
          };
          axes.setConvert(ax);
          if (ax.type === "category") {
            for (var i = 0; i < targetArray.length; i++) {
              ax.d2c(targetArray[i]);
            }
          }
        } else {
          ax = axes.getFromTrace(gd, trace, d2cTarget);
        }
        if (ax) return { d2c: ax.d2c, c2d: ax.c2d };
        if (d2cTarget === "ids") return { d2c: toString, c2d: toString };
        return { d2c: toNum, c2d: toNum };
      };
      function toNum(v) {
        return +v;
      }
      function toString(v) {
        return String(v);
      }
      axes.getDataToCoordFunc = function(gd, trace, target, targetArray) {
        return getDataConversions(gd, trace, target, targetArray).d2c;
      };
      axes.counterLetter = function(id) {
        var axLetter = id.charAt(0);
        if (axLetter === "x") return "y";
        if (axLetter === "y") return "x";
      };
      axes.minDtick = function(ax, newDiff, newFirst, allow) {
        if (["log", "category", "multicategory"].indexOf(ax.type) !== -1 || !allow) {
          ax._minDtick = 0;
        } else if (ax._minDtick === void 0) {
          ax._minDtick = newDiff;
          ax._forceTick0 = newFirst;
        } else if (ax._minDtick) {
          if ((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && // existing minDtick is an integer multiple of newDiff
          // (within rounding err)
          // and forceTick0 can be shifted to newFirst
          ((newFirst - ax._forceTick0) / newDiff % 1 + 1.000001) % 1 < 2e-6) {
            ax._minDtick = newDiff;
            ax._forceTick0 = newFirst;
          } else if ((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || // if the converse is true (newDiff is a multiple of minDtick and
          // newFirst can be shifted to forceTick0) then do nothing - same
          // forcing stands. Otherwise, cancel forced minimum
          ((newFirst - ax._forceTick0) / ax._minDtick % 1 + 1.000001) % 1 > 2e-6) {
            ax._minDtick = 0;
          }
        }
      };
      axes.saveRangeInitial = function(gd, overwrite) {
        var axList = axes.list(gd, "", true);
        var hasOneAxisChanged = false;
        for (var i = 0; i < axList.length; i++) {
          var ax = axList[i];
          var isNew = ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0;
          var hasChanged = isNew || (ax.range[0] !== ax._rangeInitial0 || ax.range[1] !== ax._rangeInitial1);
          var autorange2 = ax.autorange;
          if (isNew && autorange2 !== true || overwrite && hasChanged) {
            ax._rangeInitial0 = autorange2 === "min" || autorange2 === "max reversed" ? void 0 : ax.range[0];
            ax._rangeInitial1 = autorange2 === "max" || autorange2 === "min reversed" ? void 0 : ax.range[1];
            ax._autorangeInitial = autorange2;
            hasOneAxisChanged = true;
          }
        }
        return hasOneAxisChanged;
      };
      axes.saveShowSpikeInitial = function(gd, overwrite) {
        var axList = axes.list(gd, "", true);
        var hasOneAxisChanged = false;
        var allSpikesEnabled = "on";
        for (var i = 0; i < axList.length; i++) {
          var ax = axList[i];
          var isNew = ax._showSpikeInitial === void 0;
          var hasChanged = isNew || !(ax.showspikes === ax._showspikes);
          if (isNew || overwrite && hasChanged) {
            ax._showSpikeInitial = ax.showspikes;
            hasOneAxisChanged = true;
          }
          if (allSpikesEnabled === "on" && !ax.showspikes) {
            allSpikesEnabled = "off";
          }
        }
        gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
        return hasOneAxisChanged;
      };
      axes.autoBin = function(data, ax, nbins, is2d, calendar, size) {
        var dataMin = Lib.aggNums(Math.min, null, data);
        var dataMax = Lib.aggNums(Math.max, null, data);
        if (ax.type === "category" || ax.type === "multicategory") {
          return {
            start: dataMin - 0.5,
            end: dataMax + 0.5,
            size: Math.max(1, Math.round(size) || 1),
            _dataSpan: dataMax - dataMin
          };
        }
        if (!calendar) calendar = ax.calendar;
        var dummyAx;
        if (ax.type === "log") {
          dummyAx = {
            type: "linear",
            range: [dataMin, dataMax]
          };
        } else {
          dummyAx = {
            type: ax.type,
            range: Lib.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar),
            calendar
          };
        }
        axes.setConvert(dummyAx);
        size = size && cleanTicks.dtick(size, dummyAx.type);
        if (size) {
          dummyAx.dtick = size;
          dummyAx.tick0 = cleanTicks.tick0(void 0, dummyAx.type, calendar);
        } else {
          var size0;
          if (nbins) size0 = (dataMax - dataMin) / nbins;
          else {
            var distinctData = Lib.distinctVals(data);
            var msexp = Math.pow(10, Math.floor(
              Math.log(distinctData.minDiff) / Math.LN10
            ));
            var minSize = msexp * Lib.roundUp(
              distinctData.minDiff / msexp,
              [0.9, 1.9, 4.9, 9.9],
              true
            );
            size0 = Math.max(minSize, 2 * Lib.stdev(data) / Math.pow(data.length, is2d ? 0.25 : 0.4));
            if (!isNumeric(size0)) size0 = 1;
          }
          axes.autoTicks(dummyAx, size0);
        }
        var finalSize = dummyAx.dtick;
        var binStart = axes.tickIncrement(
          axes.tickFirst(dummyAx),
          finalSize,
          "reverse",
          calendar
        );
        var binEnd, bincount;
        if (typeof finalSize === "number") {
          binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax);
          bincount = 1 + Math.floor((dataMax - binStart) / finalSize);
          binEnd = binStart + bincount * finalSize;
        } else {
          if (dummyAx.dtick.charAt(0) === "M") {
            binStart = autoShiftMonthBins(binStart, data, finalSize, dataMin, calendar);
          }
          binEnd = binStart;
          bincount = 0;
          while (binEnd <= dataMax) {
            binEnd = axes.tickIncrement(binEnd, finalSize, false, calendar);
            bincount++;
          }
        }
        return {
          start: ax.c2r(binStart, 0, calendar),
          end: ax.c2r(binEnd, 0, calendar),
          size: finalSize,
          _dataSpan: dataMax - dataMin
        };
      };
      function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) {
        var edgecount = 0;
        var midcount = 0;
        var intcount = 0;
        var blankCount = 0;
        function nearEdge(v) {
          return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2;
        }
        for (var i = 0; i < data.length; i++) {
          if (data[i] % 1 === 0) intcount++;
          else if (!isNumeric(data[i])) blankCount++;
          if (nearEdge(data[i])) edgecount++;
          if (nearEdge(data[i] + ax.dtick / 2)) midcount++;
        }
        var dataCount = data.length - blankCount;
        if (intcount === dataCount && ax.type !== "date") {
          if (ax.dtick < 1) {
            binStart = dataMin - 0.5 * ax.dtick;
          } else {
            binStart -= 0.5;
            if (binStart + ax.dtick < dataMin) binStart += ax.dtick;
          }
        } else if (midcount < dataCount * 0.1) {
          if (edgecount > dataCount * 0.3 || nearEdge(dataMin) || nearEdge(dataMax)) {
            var binshift = ax.dtick / 2;
            binStart += binStart + binshift < dataMin ? binshift : -binshift;
          }
        }
        return binStart;
      }
      function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) {
        var stats = Lib.findExactDates(data, calendar);
        var threshold = 0.8;
        if (stats.exactDays > threshold) {
          var numMonths = Number(dtick.slice(1));
          if (stats.exactYears > threshold && numMonths % 12 === 0) {
            binStart = axes.tickIncrement(binStart, "M6", "reverse") + ONEDAY * 1.5;
          } else if (stats.exactMonths > threshold) {
            binStart = axes.tickIncrement(binStart, "M1", "reverse") + ONEDAY * 15.5;
          } else {
            binStart -= HALFDAY;
          }
          var nextBinStart = axes.tickIncrement(binStart, dtick);
          if (nextBinStart <= dataMin) return nextBinStart;
        }
        return binStart;
      }
      axes.prepMinorTicks = function(mockAx, ax, opts) {
        if (!ax.minor.dtick) {
          delete mockAx.dtick;
          var hasMajor = ax.dtick && isNumeric(ax._tmin);
          var mockMinorRange;
          if (hasMajor) {
            var tick2 = axes.tickIncrement(ax._tmin, ax.dtick, true);
            mockMinorRange = [ax._tmin, tick2 * 0.99 + ax._tmin * 0.01];
          } else {
            var rl = Lib.simpleMap(ax.range, ax.r2l);
            mockMinorRange = [rl[0], 0.8 * rl[0] + 0.2 * rl[1]];
          }
          mockAx.range = Lib.simpleMap(mockMinorRange, ax.l2r);
          mockAx._isMinor = true;
          axes.prepTicks(mockAx, opts);
          if (hasMajor) {
            var numericMajor = isNumeric(ax.dtick);
            var numericMinor = isNumeric(mockAx.dtick);
            var majorNum = numericMajor ? ax.dtick : +ax.dtick.substring(1);
            var minorNum = numericMinor ? mockAx.dtick : +mockAx.dtick.substring(1);
            if (numericMajor && numericMinor) {
              if (!isMultiple(majorNum, minorNum)) {
                if (majorNum === 2 * ONEWEEK && minorNum === 3 * ONEDAY) {
                  mockAx.dtick = ONEWEEK;
                } else if (majorNum === ONEWEEK && !(ax._input.minor || {}).nticks) {
                  mockAx.dtick = ONEDAY;
                } else if (isClose(majorNum / minorNum, 2.5)) {
                  mockAx.dtick = majorNum / 2;
                } else {
                  mockAx.dtick = majorNum;
                }
              } else if (majorNum === 2 * ONEWEEK && minorNum === 2 * ONEDAY) {
                mockAx.dtick = ONEWEEK;
              }
            } else if (String(ax.dtick).charAt(0) === "M") {
              if (numericMinor) {
                mockAx.dtick = "M1";
              } else {
                if (!isMultiple(majorNum, minorNum)) {
                  mockAx.dtick = ax.dtick;
                } else if (majorNum >= 12 && minorNum === 2) {
                  mockAx.dtick = "M3";
                }
              }
            } else if (String(mockAx.dtick).charAt(0) === "L") {
              if (String(ax.dtick).charAt(0) === "L") {
                if (!isMultiple(majorNum, minorNum)) {
                  mockAx.dtick = isClose(majorNum / minorNum, 2.5) ? ax.dtick / 2 : ax.dtick;
                }
              } else {
                mockAx.dtick = "D1";
              }
            } else if (mockAx.dtick === "D2" && +ax.dtick > 1) {
              mockAx.dtick = 1;
            }
          }
          mockAx.range = ax.range;
        }
        if (ax.minor._tick0Init === void 0) {
          mockAx.tick0 = ax.tick0;
        }
      };
      function isMultiple(bigger, smaller) {
        return Math.abs((bigger / smaller + 0.5) % 1 - 0.5) < 1e-3;
      }
      function isClose(a, b) {
        return Math.abs(a / b - 1) < 1e-3;
      }
      axes.prepTicks = function(ax, opts) {
        var rng = Lib.simpleMap(ax.range, ax.r2l, void 0, void 0, opts);
        if (ax.tickmode === "auto" || !ax.dtick) {
          var nt = ax.nticks;
          var minPx;
          if (!nt) {
            if (ax.type === "category" || ax.type === "multicategory") {
              minPx = ax.tickfont ? Lib.bigFont(ax.tickfont.size || 12) : 15;
              nt = ax._length / minPx;
            } else {
              minPx = ax._id.charAt(0) === "y" ? 40 : 80;
              nt = Lib.constrain(ax._length / minPx, 4, 9) + 1;
            }
            if (ax._name === "radialaxis") nt *= 2;
          }
          if (!(ax.minor && ax.minor.tickmode !== "array")) {
            if (ax.tickmode === "array") nt *= 100;
          }
          ax._roughDTick = Math.abs(rng[1] - rng[0]) / nt;
          axes.autoTicks(ax, ax._roughDTick);
          if (ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) {
            ax.dtick = ax._minDtick;
            ax.tick0 = ax.l2r(ax._forceTick0);
          }
        }
        if (ax.ticklabelmode === "period") {
          adjustPeriodDelta(ax);
        }
        if (!ax.tick0) {
          ax.tick0 = ax.type === "date" ? "2000-01-01" : 0;
        }
        if (ax.type === "date" && ax.dtick < 0.1) ax.dtick = 0.1;
        autoTickRound(ax);
      };
      function nMonths(dtick) {
        return +dtick.substring(1);
      }
      function adjustPeriodDelta(ax) {
        var definedDelta;
        function mDate() {
          return !(isNumeric(ax.dtick) || ax.dtick.charAt(0) !== "M");
        }
        var isMDate = mDate();
        var tickformat = axes.getTickFormat(ax);
        if (tickformat) {
          var noDtick = ax._dtickInit !== ax.dtick;
          if (!/%[fLQsSMX]/.test(tickformat)) {
            if (/%[HI]/.test(tickformat)) {
              definedDelta = ONEHOUR;
              if (noDtick && !isMDate && ax.dtick < ONEHOUR) ax.dtick = ONEHOUR;
            } else if (/%p/.test(tickformat)) {
              definedDelta = HALFDAY;
              if (noDtick && !isMDate && ax.dtick < HALFDAY) ax.dtick = HALFDAY;
            } else if (/%[Aadejuwx]/.test(tickformat)) {
              definedDelta = ONEDAY;
              if (noDtick && !isMDate && ax.dtick < ONEDAY) ax.dtick = ONEDAY;
            } else if (/%[UVW]/.test(tickformat)) {
              definedDelta = ONEWEEK;
              if (noDtick && !isMDate && ax.dtick < ONEWEEK) ax.dtick = ONEWEEK;
            } else if (/%[Bbm]/.test(tickformat)) {
              definedDelta = ONEAVGMONTH;
              if (noDtick && (isMDate ? nMonths(ax.dtick) < 1 : ax.dtick < ONEMINMONTH)) ax.dtick = "M1";
            } else if (/%[q]/.test(tickformat)) {
              definedDelta = ONEAVGQUARTER;
              if (noDtick && (isMDate ? nMonths(ax.dtick) < 3 : ax.dtick < ONEMINQUARTER)) ax.dtick = "M3";
            } else if (/%[Yy]/.test(tickformat)) {
              definedDelta = ONEAVGYEAR;
              if (noDtick && (isMDate ? nMonths(ax.dtick) < 12 : ax.dtick < ONEMINYEAR)) ax.dtick = "M12";
            }
          }
        }
        isMDate = mDate();
        if (isMDate && ax.tick0 === ax._dowTick0) {
          ax.tick0 = ax._rawTick0;
        }
        ax._definedDelta = definedDelta;
      }
      function positionPeriodTicks(tickVals, ax, definedDelta) {
        for (var i = 0; i < tickVals.length; i++) {
          var v = tickVals[i].value;
          var a = i;
          var b = i + 1;
          if (i < tickVals.length - 1) {
            a = i;
            b = i + 1;
          } else if (i > 0) {
            a = i - 1;
            b = i;
          } else {
            a = i;
            b = i;
          }
          var A2 = tickVals[a].value;
          var B2 = tickVals[b].value;
          var actualDelta = Math.abs(B2 - A2);
          var delta = definedDelta || actualDelta;
          var periodLength = 0;
          if (delta >= ONEMINYEAR) {
            if (actualDelta >= ONEMINYEAR && actualDelta <= ONEMAXYEAR) {
              periodLength = actualDelta;
            } else {
              periodLength = ONEAVGYEAR;
            }
          } else if (definedDelta === ONEAVGQUARTER && delta >= ONEMINQUARTER) {
            if (actualDelta >= ONEMINQUARTER && actualDelta <= ONEMAXQUARTER) {
              periodLength = actualDelta;
            } else {
              periodLength = ONEAVGQUARTER;
            }
          } else if (delta >= ONEMINMONTH) {
            if (actualDelta >= ONEMINMONTH && actualDelta <= ONEMAXMONTH) {
              periodLength = actualDelta;
            } else {
              periodLength = ONEAVGMONTH;
            }
          } else if (definedDelta === ONEWEEK && delta >= ONEWEEK) {
            periodLength = ONEWEEK;
          } else if (delta >= ONEDAY) {
            periodLength = ONEDAY;
          } else if (definedDelta === HALFDAY && delta >= HALFDAY) {
            periodLength = HALFDAY;
          } else if (definedDelta === ONEHOUR && delta >= ONEHOUR) {
            periodLength = ONEHOUR;
          }
          var inBetween;
          if (periodLength >= actualDelta) {
            periodLength = actualDelta;
            inBetween = true;
          }
          var endPeriod = v + periodLength;
          if (ax.rangebreaks && periodLength > 0) {
            var nAll = 84;
            var n = 0;
            for (var c = 0; c < nAll; c++) {
              var r = (c + 0.5) / nAll;
              if (ax.maskBreaks(v * (1 - r) + r * endPeriod) !== BADNUM) n++;
            }
            periodLength *= n / nAll;
            if (!periodLength) {
              tickVals[i].drop = true;
            }
            if (inBetween && actualDelta > ONEWEEK) periodLength = actualDelta;
          }
          if (periodLength > 0 || // not instant
          i === 0) {
            tickVals[i].periodX = v + periodLength / 2;
          }
        }
      }
      axes.calcTicks = function calcTicks(ax, opts) {
        var type = ax.type;
        var calendar = ax.calendar;
        var ticklabelstep = ax.ticklabelstep;
        var isPeriod = ax.ticklabelmode === "period";
        var isReversed = ax.range[0] > ax.range[1];
        var ticklabelIndex = !ax.ticklabelindex || Lib.isArrayOrTypedArray(ax.ticklabelindex) ? ax.ticklabelindex : [ax.ticklabelindex];
        var rng = Lib.simpleMap(ax.range, ax.r2l, void 0, void 0, opts);
        var axrev = rng[1] < rng[0];
        var minRange = Math.min(rng[0], rng[1]);
        var maxRange = Math.max(rng[0], rng[1]);
        var maxTicks = Math.max(1e3, ax._length || 0);
        var ticksOut = [];
        var minorTicks = [];
        var tickVals = [];
        var minorTickVals = [];
        var allTicklabelVals = [];
        var hasMinor = ax.minor && (ax.minor.ticks || ax.minor.showgrid);
        for (var major = 1; major >= (hasMinor ? 0 : 1); major--) {
          var isMinor = !major;
          if (major) {
            ax._dtickInit = ax.dtick;
            ax._tick0Init = ax.tick0;
          } else {
            ax.minor._dtickInit = ax.minor.dtick;
            ax.minor._tick0Init = ax.minor.tick0;
          }
          var mockAx = major ? ax : Lib.extendFlat({}, ax, ax.minor);
          if (isMinor) {
            axes.prepMinorTicks(mockAx, ax, opts);
          } else {
            axes.prepTicks(mockAx, opts);
          }
          if (mockAx.tickmode === "array") {
            if (major) {
              tickVals = [];
              ticksOut = arrayTicks(ax, !isMinor);
            } else {
              minorTickVals = [];
              minorTicks = arrayTicks(ax, !isMinor);
            }
            continue;
          }
          if (mockAx.tickmode === "sync") {
            tickVals = [];
            ticksOut = syncTicks(ax);
            continue;
          }
          var exRng = expandRange(rng);
          var startTick = exRng[0];
          var endTick = exRng[1];
          var numDtick = isNumeric(mockAx.dtick);
          var isDLog = type === "log" && !(numDtick || mockAx.dtick.charAt(0) === "L");
          var x0 = axes.tickFirst(mockAx, opts);
          if (major) {
            ax._tmin = x0;
            if (x0 < startTick !== axrev) break;
            if (type === "category" || type === "multicategory") {
              endTick = axrev ? Math.max(-0.5, endTick) : Math.min(ax._categories.length - 0.5, endTick);
            }
          }
          var prevX = null;
          var x = x0;
          var majorId;
          if (major) {
            var _dTick;
            if (numDtick) {
              _dTick = ax.dtick;
            } else {
              if (type === "date") {
                if (typeof ax.dtick === "string" && ax.dtick.charAt(0) === "M") {
                  _dTick = ONEAVGMONTH * ax.dtick.substring(1);
                }
              } else {
                _dTick = ax._roughDTick;
              }
            }
            majorId = Math.round((ax.r2l(x) - ax.r2l(ax.tick0)) / _dTick) - 1;
          }
          var dtick = mockAx.dtick;
          if (mockAx.rangebreaks && mockAx._tick0Init !== mockAx.tick0) {
            x = moveOutsideBreak(x, ax);
            if (!axrev) {
              x = axes.tickIncrement(x, dtick, !axrev, calendar);
            }
          }
          if (major && isPeriod) {
            x = axes.tickIncrement(x, dtick, !axrev, calendar);
            majorId--;
          }
          for (; axrev ? x >= endTick : x <= endTick; x = axes.tickIncrement(
            x,
            dtick,
            axrev,
            calendar
          )) {
            if (major) majorId++;
            if (mockAx.rangebreaks) {
              if (!axrev) {
                if (x < startTick) continue;
                if (mockAx.maskBreaks(x) === BADNUM && moveOutsideBreak(x, mockAx) >= maxRange) break;
              }
            }
            if (tickVals.length > maxTicks || x === prevX) break;
            prevX = x;
            var obj = { value: x };
            if (major) {
              if (isDLog && x !== (x | 0)) {
                obj.simpleLabel = true;
              }
              if (ticklabelstep > 1 && majorId % ticklabelstep) {
                obj.skipLabel = true;
              }
              tickVals.push(obj);
            } else {
              obj.minor = true;
              minorTickVals.push(obj);
            }
          }
        }
        if (!minorTickVals || minorTickVals.length < 2) {
          ticklabelIndex = false;
        } else {
          var diff = (minorTickVals[1].value - minorTickVals[0].value) * (isReversed ? -1 : 1);
          if (!periodCompatibleWithTickformat(diff, ax.tickformat)) {
            ticklabelIndex = false;
          }
        }
        if (!ticklabelIndex) {
          allTicklabelVals = tickVals;
        } else {
          var allTickVals = tickVals.concat(minorTickVals);
          if (isPeriod && tickVals.length) {
            allTickVals = allTickVals.slice(1);
          }
          allTickVals = allTickVals.sort(function(a, b) {
            return a.value - b.value;
          }).filter(function(tick, index, self2) {
            return index === 0 || tick.value !== self2[index - 1].value;
          });
          var majorTickIndices = allTickVals.map(function(item, index) {
            return item.minor === void 0 && !item.skipLabel ? index : null;
          }).filter(function(index) {
            return index !== null;
          });
          majorTickIndices.forEach(function(majorIdx) {
            ticklabelIndex.map(function(nextLabelIdx) {
              var minorIdx = majorIdx + nextLabelIdx;
              if (minorIdx >= 0 && minorIdx < allTickVals.length) {
                Lib.pushUnique(allTicklabelVals, allTickVals[minorIdx]);
              }
            });
          });
        }
        if (hasMinor) {
          var canOverlap = ax.minor.ticks === "inside" && ax.ticks === "outside" || ax.minor.ticks === "outside" && ax.ticks === "inside";
          if (!canOverlap) {
            var majorValues = tickVals.map(function(d) {
              return d.value;
            });
            var list = [];
            for (var k = 0; k < minorTickVals.length; k++) {
              var T = minorTickVals[k];
              var v = T.value;
              if (majorValues.indexOf(v) !== -1) {
                continue;
              }
              var found = false;
              for (var q = 0; !found && q < tickVals.length; q++) {
                if (
                  // add 10e6 to eliminate problematic digits
                  1e7 + tickVals[q].value === 1e7 + v
                ) {
                  found = true;
                }
              }
              if (!found) list.push(T);
            }
            minorTickVals = list;
          }
        }
        if (isPeriod) positionPeriodTicks(allTicklabelVals, ax, ax._definedDelta);
        var i;
        if (ax.rangebreaks) {
          var flip = ax._id.charAt(0) === "y";
          var fontSize = 1;
          if (ax.tickmode === "auto") {
            fontSize = ax.tickfont ? ax.tickfont.size : 12;
          }
          var prevL = NaN;
          for (i = tickVals.length - 1; i > -1; i--) {
            if (tickVals[i].drop) {
              tickVals.splice(i, 1);
              continue;
            }
            tickVals[i].value = moveOutsideBreak(tickVals[i].value, ax);
            var l = ax.c2p(tickVals[i].value);
            if (flip ? prevL > l - fontSize : prevL < l + fontSize) {
              tickVals.splice(axrev ? i + 1 : i, 1);
            } else {
              prevL = l;
            }
          }
        }
        if (isAngular(ax) && Math.abs(rng[1] - rng[0]) === 360) {
          tickVals.pop();
        }
        ax._tmax = (tickVals[tickVals.length - 1] || {}).value;
        ax._prevDateHead = "";
        ax._inCalcTicks = true;
        var lastVisibleHead;
        var hideLabel = function(tick) {
          tick.text = "";
          ax._prevDateHead = lastVisibleHead;
        };
        tickVals = tickVals.concat(minorTickVals);
        function setTickLabel(ax2, tickVal) {
          var text = axes.tickText(
            ax2,
            tickVal.value,
            false,
            // hover
            tickVal.simpleLabel
            // noSuffixPrefix
          );
          var p = tickVal.periodX;
          if (p !== void 0) {
            text.periodX = p;
            if (p > maxRange || p < minRange) {
              if (p > maxRange) text.periodX = maxRange;
              if (p < minRange) text.periodX = minRange;
              hideLabel(text);
            }
          }
          return text;
        }
        var t;
        for (i = 0; i < tickVals.length; i++) {
          var _minor = tickVals[i].minor;
          var _value = tickVals[i].value;
          if (_minor) {
            if (ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) !== -1) {
              t = setTickLabel(ax, tickVals[i]);
            } else {
              t = { x: _value };
            }
            t.minor = true;
            minorTicks.push(t);
          } else {
            lastVisibleHead = ax._prevDateHead;
            t = setTickLabel(ax, tickVals[i]);
            if (tickVals[i].skipLabel || ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) === -1) {
              hideLabel(t);
            }
            ticksOut.push(t);
          }
        }
        ticksOut = ticksOut.concat(minorTicks);
        ax._inCalcTicks = false;
        if (isPeriod && ticksOut.length) {
          ticksOut[0].noTick = true;
        }
        return ticksOut;
      };
      function filterRangeBreaks(ax, ticksOut) {
        if (ax.rangebreaks) {
          ticksOut = ticksOut.filter(function(d) {
            return ax.maskBreaks(d.x) !== BADNUM;
          });
        }
        return ticksOut;
      }
      function syncTicks(ax) {
        var baseAxis = ax._mainAxis;
        var ticksOut = [];
        if (baseAxis._vals) {
          for (var i = 0; i < baseAxis._vals.length; i++) {
            if (baseAxis._vals[i].noTick) {
              continue;
            }
            var pos = baseAxis.l2p(baseAxis._vals[i].x);
            var vali = ax.p2l(pos);
            var obj = axes.tickText(ax, vali);
            if (baseAxis._vals[i].minor) {
              obj.minor = true;
              obj.text = "";
            }
            ticksOut.push(obj);
          }
        }
        ticksOut = filterRangeBreaks(ax, ticksOut);
        return ticksOut;
      }
      function arrayTicks(ax, majorOnly) {
        var rng = Lib.simpleMap(ax.range, ax.r2l);
        var exRng = expandRange(rng);
        var tickMin = Math.min(exRng[0], exRng[1]);
        var tickMax = Math.max(exRng[0], exRng[1]);
        var tickVal2l = ax.type === "category" ? ax.d2l_noadd : ax.d2l;
        if (ax.type === "log" && String(ax.dtick).charAt(0) !== "L") {
          ax.dtick = "L" + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1);
        }
        var ticksOut = [];
        for (var isMinor = 0; isMinor <= 1; isMinor++) {
          if (majorOnly !== void 0 && (majorOnly && isMinor || majorOnly === false && !isMinor)) continue;
          if (isMinor && !ax.minor) continue;
          var vals = !isMinor ? ax.tickvals : ax.minor.tickvals;
          var text = !isMinor ? ax.ticktext : [];
          if (!vals) continue;
          if (!Lib.isArrayOrTypedArray(text)) text = [];
          for (var i = 0; i < vals.length; i++) {
            var vali = tickVal2l(vals[i]);
            if (vali > tickMin && vali < tickMax) {
              var obj = axes.tickText(ax, vali, false, String(text[i]));
              if (isMinor) {
                obj.minor = true;
                obj.text = "";
              }
              ticksOut.push(obj);
            }
          }
        }
        ticksOut = filterRangeBreaks(ax, ticksOut);
        return ticksOut;
      }
      var roundBase10 = [2, 5, 10];
      var roundBase24 = [1, 2, 3, 6, 12];
      var roundBase60 = [1, 2, 5, 10, 15, 30];
      var roundDays = [1, 2, 3, 7, 14];
      var roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1];
      var roundLog2 = [-0.301, 0, 0.301, 0.699, 1];
      var roundAngles = [15, 30, 45, 90, 180];
      function roundDTick(roughDTick, base, roundingSet) {
        return base * Lib.roundUp(roughDTick / base, roundingSet);
      }
      axes.autoTicks = function(ax, roughDTick, isMinor) {
        var base;
        function getBase(v) {
          return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10));
        }
        if (ax.type === "date") {
          ax.tick0 = Lib.dateTick0(ax.calendar, 0);
          var roughX2 = 2 * roughDTick;
          if (roughX2 > ONEAVGYEAR) {
            roughDTick /= ONEAVGYEAR;
            base = getBase(10);
            ax.dtick = "M" + 12 * roundDTick(roughDTick, base, roundBase10);
          } else if (roughX2 > ONEAVGMONTH) {
            roughDTick /= ONEAVGMONTH;
            ax.dtick = "M" + roundDTick(roughDTick, 1, roundBase24);
          } else if (roughX2 > ONEDAY) {
            ax.dtick = roundDTick(roughDTick, ONEDAY, ax._hasDayOfWeekBreaks ? [1, 2, 7, 14] : roundDays);
            if (!isMinor) {
              var tickformat = axes.getTickFormat(ax);
              var isPeriod = ax.ticklabelmode === "period";
              if (isPeriod) ax._rawTick0 = ax.tick0;
              if (/%[uVW]/.test(tickformat)) {
                ax.tick0 = Lib.dateTick0(ax.calendar, 2);
              } else {
                ax.tick0 = Lib.dateTick0(ax.calendar, 1);
              }
              if (isPeriod) ax._dowTick0 = ax.tick0;
            }
          } else if (roughX2 > ONEHOUR) {
            ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24);
          } else if (roughX2 > ONEMIN) {
            ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60);
          } else if (roughX2 > ONESEC) {
            ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60);
          } else {
            base = getBase(10);
            ax.dtick = roundDTick(roughDTick, base, roundBase10);
          }
        } else if (ax.type === "log") {
          ax.tick0 = 0;
          var rng = Lib.simpleMap(ax.range, ax.r2l);
          if (ax._isMinor) {
            roughDTick *= 1.5;
          }
          if (roughDTick > 0.7) {
            ax.dtick = Math.ceil(roughDTick);
          } else if (Math.abs(rng[1] - rng[0]) < 1) {
            var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick);
            roughDTick = Math.abs(Math.pow(10, rng[1]) - Math.pow(10, rng[0])) / nt;
            base = getBase(10);
            ax.dtick = "L" + roundDTick(roughDTick, base, roundBase10);
          } else {
            ax.dtick = roughDTick > 0.3 ? "D2" : "D1";
          }
        } else if (ax.type === "category" || ax.type === "multicategory") {
          ax.tick0 = 0;
          ax.dtick = Math.ceil(Math.max(roughDTick, 1));
        } else if (isAngular(ax)) {
          ax.tick0 = 0;
          base = 1;
          ax.dtick = roundDTick(roughDTick, base, roundAngles);
        } else {
          ax.tick0 = 0;
          base = getBase(10);
          ax.dtick = roundDTick(roughDTick, base, roundBase10);
        }
        if (ax.dtick === 0) ax.dtick = 1;
        if (!isNumeric(ax.dtick) && typeof ax.dtick !== "string") {
          var olddtick = ax.dtick;
          ax.dtick = 1;
          throw "ax.dtick error: " + String(olddtick);
        }
      };
      function autoTickRound(ax) {
        var dtick = ax.dtick;
        ax._tickexponent = 0;
        if (!isNumeric(dtick) && typeof dtick !== "string") {
          dtick = 1;
        }
        if (ax.type === "category" || ax.type === "multicategory") {
          ax._tickround = null;
        }
        if (ax.type === "date") {
          var tick0ms = ax.r2l(ax.tick0);
          var tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, "");
          var tick0len = tick0str.length;
          if (String(dtick).charAt(0) === "M") {
            if (tick0len > 10 || tick0str.slice(5) !== "01-01") ax._tickround = "d";
            else ax._tickround = +dtick.slice(1) % 12 === 0 ? "y" : "m";
          } else if (dtick >= ONEDAY && tick0len <= 10 || dtick >= ONEDAY * 15) ax._tickround = "d";
          else if (dtick >= ONEMIN && tick0len <= 16 || dtick >= ONEHOUR) ax._tickround = "M";
          else if (dtick >= ONESEC && tick0len <= 19 || dtick >= ONEMIN) ax._tickround = "S";
          else {
            var tick1len = ax.l2r(tick0ms + dtick).replace(/^-/, "").length;
            ax._tickround = Math.max(tick0len, tick1len) - 20;
            if (ax._tickround < 0) ax._tickround = 4;
          }
        } else if (isNumeric(dtick) || dtick.charAt(0) === "L") {
          var rng = ax.range.map(ax.r2d || Number);
          if (!isNumeric(dtick)) dtick = Number(dtick.slice(1));
          ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);
          var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1]));
          var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
          var minexponent = ax.minexponent === void 0 ? 3 : ax.minexponent;
          if (Math.abs(rangeexp) > minexponent) {
            if (isSIFormat(ax.exponentformat) && ax.exponentformat !== "SI extended" && !beyondSI(rangeexp) || isSIFormat(ax.exponentformat) && ax.exponentformat === "SI extended" && !beyondSIExtended(rangeexp)) {
              ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
            } else ax._tickexponent = rangeexp;
          }
        } else {
          ax._tickround = null;
        }
      }
      axes.tickIncrement = function(x, dtick, axrev, calendar) {
        var axSign = axrev ? -1 : 1;
        if (isNumeric(dtick)) return Lib.increment(x, axSign * dtick);
        var tType = dtick.charAt(0);
        var dtSigned = axSign * Number(dtick.slice(1));
        if (tType === "M") return Lib.incrementMonth(x, dtSigned, calendar);
        if (tType === "L") return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;
        if (tType === "D") {
          var tickset = dtick === "D2" ? roundLog2 : roundLog1;
          var x2 = x + axSign * 0.01;
          var frac = Lib.roundUp(Lib.mod(x2, 1), tickset, axrev);
          return Math.floor(x2) + Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
        }
        throw "unrecognized dtick " + String(dtick);
      };
      axes.tickFirst = function(ax, opts) {
        var r2l = ax.r2l || Number;
        var rng = Lib.simpleMap(ax.range, r2l, void 0, void 0, opts);
        var axrev = rng[1] < rng[0];
        var sRound = axrev ? Math.floor : Math.ceil;
        var r0 = expandRange(rng)[0];
        var dtick = ax.dtick;
        var tick0 = r2l(ax.tick0);
        if (isNumeric(dtick)) {
          var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;
          if (ax.type === "category" || ax.type === "multicategory") {
            tmin = Lib.constrain(tmin, 0, ax._categories.length - 1);
          }
          return tmin;
        }
        var tType = dtick.charAt(0);
        var dtNum = Number(dtick.slice(1));
        if (tType === "M") {
          var cnt = 0;
          var t02 = tick0;
          var t12, mult, newDTick;
          while (cnt < 10) {
            t12 = axes.tickIncrement(t02, dtick, axrev, ax.calendar);
            if ((t12 - r0) * (t02 - r0) <= 0) {
              if (axrev) return Math.min(t02, t12);
              return Math.max(t02, t12);
            }
            mult = (r0 - (t02 + t12) / 2) / (t12 - t02);
            newDTick = tType + (Math.abs(Math.round(mult)) || 1) * dtNum;
            t02 = axes.tickIncrement(t02, newDTick, mult < 0 ? !axrev : axrev, ax.calendar);
            cnt++;
          }
          Lib.error("tickFirst did not converge", ax);
          return t02;
        } else if (tType === "L") {
          return Math.log(sRound(
            (Math.pow(10, r0) - tick0) / dtNum
          ) * dtNum + tick0) / Math.LN10;
        } else if (tType === "D") {
          var tickset = dtick === "D2" ? roundLog2 : roundLog1;
          var frac = Lib.roundUp(Lib.mod(r0, 1), tickset, axrev);
          return Math.floor(r0) + Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
        } else throw "unrecognized dtick " + String(dtick);
      };
      axes.tickText = function(ax, x, hover, noSuffixPrefix) {
        var out = tickTextObj(ax, x);
        var arrayMode = ax.tickmode === "array";
        var extraPrecision = hover || arrayMode;
        var axType = ax.type;
        var tickVal2l = axType === "category" ? ax.d2l_noadd : ax.d2l;
        var i;
        var inbounds = function(v) {
          var p = ax.l2p(v);
          return p >= 0 && p <= ax._length ? v : null;
        };
        if (arrayMode && Lib.isArrayOrTypedArray(ax.ticktext)) {
          var rng = Lib.simpleMap(ax.range, ax.r2l);
          var minDiff = (Math.abs(rng[1] - rng[0]) - (ax._lBreaks || 0)) / 1e4;
          for (i = 0; i < ax.ticktext.length; i++) {
            if (Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break;
          }
          if (i < ax.ticktext.length) {
            out.text = String(ax.ticktext[i]);
            out.xbnd = [
              inbounds(out.x - 0.5),
              inbounds(out.x + ax.dtick - 0.5)
            ];
            return out;
          }
        }
        function isHidden(showAttr) {
          if (showAttr === void 0) return true;
          if (hover) return showAttr === "none";
          var firstOrLast = {
            first: ax._tmin,
            last: ax._tmax
          }[showAttr];
          return showAttr !== "all" && x !== firstOrLast;
        }
        var hideexp = hover ? "never" : ax.exponentformat !== "none" && isHidden(ax.showexponent) ? "hide" : "";
        if (axType === "date") formatDate(ax, out, hover, extraPrecision);
        else if (axType === "log") formatLog(ax, out, hover, extraPrecision, hideexp);
        else if (axType === "category") formatCategory(ax, out);
        else if (axType === "multicategory") formatMultiCategory(ax, out, hover);
        else if (isAngular(ax)) formatAngle(ax, out, hover, extraPrecision, hideexp);
        else formatLinear(ax, out, hover, extraPrecision, hideexp);
        if (!noSuffixPrefix) {
          if (ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
          if (ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;
        }
        if (ax.labelalias && ax.labelalias.hasOwnProperty(out.text)) {
          var t = ax.labelalias[out.text];
          if (typeof t === "string") out.text = t;
        }
        if (ax.tickson === "boundaries" || ax.showdividers) {
          out.xbnd = [
            inbounds(out.x - 0.5),
            inbounds(out.x + ax.dtick - 0.5)
          ];
        }
        return out;
      };
      axes.hoverLabelText = function(ax, values, hoverformat) {
        if (hoverformat) ax = Lib.extendFlat({}, ax, { hoverformat });
        var val = Lib.isArrayOrTypedArray(values) ? values[0] : values;
        var val2 = Lib.isArrayOrTypedArray(values) ? values[1] : void 0;
        if (val2 !== void 0 && val2 !== val) {
          return axes.hoverLabelText(ax, val, hoverformat) + " - " + axes.hoverLabelText(ax, val2, hoverformat);
        }
        var logOffScale = ax.type === "log" && val <= 0;
        var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), "hover").text;
        if (logOffScale) {
          return val === 0 ? "0" : MINUS_SIGN + tx;
        }
        return tx;
      };
      function tickTextObj(ax, x, text) {
        var tf = ax.tickfont || {};
        return {
          x,
          dx: 0,
          dy: 0,
          text: text || "",
          fontSize: tf.size,
          font: tf.family,
          fontWeight: tf.weight,
          fontStyle: tf.style,
          fontVariant: tf.variant,
          fontTextcase: tf.textcase,
          fontLineposition: tf.lineposition,
          fontShadow: tf.shadow,
          fontColor: tf.color
        };
      }
      function formatDate(ax, out, hover, extraPrecision) {
        var tr = ax._tickround;
        var fmt = hover && ax.hoverformat || axes.getTickFormat(ax);
        extraPrecision = !fmt && extraPrecision;
        if (extraPrecision) {
          if (isNumeric(tr)) tr = 4;
          else tr = { y: "m", m: "d", d: "M", M: "S", S: 4 }[tr];
        }
        var dateStr = Lib.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat);
        var headStr;
        var splitIndex = dateStr.indexOf("\n");
        if (splitIndex !== -1) {
          headStr = dateStr.slice(splitIndex + 1);
          dateStr = dateStr.slice(0, splitIndex);
        }
        if (extraPrecision) {
          if (headStr !== void 0 && (dateStr === "00:00:00" || dateStr === "00:00")) {
            dateStr = headStr;
            headStr = "";
          } else if (dateStr.length === 8) {
            dateStr = dateStr.replace(/:00$/, "");
          }
        }
        if (headStr) {
          if (hover) {
            if (tr === "d") dateStr += ", " + headStr;
            else dateStr = headStr + (dateStr ? ", " + dateStr : "");
          } else {
            if (!ax._inCalcTicks || ax._prevDateHead !== headStr) {
              ax._prevDateHead = headStr;
              dateStr += "<br>" + headStr;
            } else {
              var isInside = insideTicklabelposition(ax);
              var side = ax._trueSide || ax.side;
              if (!isInside && side === "top" || isInside && side === "bottom") {
                dateStr += "<br> ";
              }
            }
          }
        }
        out.text = dateStr;
      }
      function formatLog(ax, out, hover, extraPrecision, hideexp) {
        var dtick = ax.dtick;
        var x = out.x;
        var tickformat = ax.tickformat;
        var dtChar0 = typeof dtick === "string" && dtick.charAt(0);
        if (hideexp === "never") {
          hideexp = "";
        }
        if (extraPrecision && dtChar0 !== "L") {
          dtick = "L3";
          dtChar0 = "L";
        }
        if (tickformat || dtChar0 === "L") {
          out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
        } else if (isNumeric(dtick) || dtChar0 === "D" && (ax.minorloglabels === "complete" || Lib.mod(x + 0.01, 1) < 0.1)) {
          var isMinor;
          if (ax.minorloglabels === "complete" && !(Lib.mod(x + 0.01, 1) < 0.1)) {
            isMinor = true;
            out.fontSize *= 0.75;
          }
          var exponentialString = Math.pow(10, x).toExponential(0);
          var parts = exponentialString.split("e");
          var p = +parts[1];
          var absP = Math.abs(p);
          var exponentFormat = ax.exponentformat;
          if (exponentFormat === "power" || isSIFormat(exponentFormat) && exponentFormat !== "SI extended" && beyondSI(p) || isSIFormat(exponentFormat) && exponentFormat === "SI extended" && beyondSIExtended(p)) {
            out.text = parts[0];
            if (absP > 0) out.text += "x10";
            if (out.text === "1x10") out.text = "10";
            if (p !== 0 && p !== 1) out.text += "<sup>" + (p > 0 ? "" : MINUS_SIGN) + absP + "</sup>";
            out.fontSize *= 1.25;
          } else if ((exponentFormat === "e" || exponentFormat === "E") && absP > 2) {
            out.text = parts[0] + exponentFormat + (p > 0 ? "+" : MINUS_SIGN) + absP;
          } else {
            out.text = numFormat(Math.pow(10, x), ax, "", "fakehover");
            if (dtick === "D1" && ax._id.charAt(0) === "y") {
              out.dy -= out.fontSize / 6;
            }
          }
        } else if (dtChar0 === "D") {
          out.text = ax.minorloglabels === "none" ? "" : (
            /* ax.minorloglabels === 'small digits' */
            String(Math.round(Math.pow(10, Lib.mod(x, 1))))
          );
          out.fontSize *= 0.75;
        } else throw "unrecognized dtick " + String(dtick);
        if (ax.dtick === "D1") {
          var firstChar = String(out.text).charAt(0);
          if (firstChar === "0" || firstChar === "1") {
            if (ax._id.charAt(0) === "y") {
              out.dx -= out.fontSize / 4;
            } else {
              out.dy += out.fontSize / 2;
              out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) * out.fontSize * (x < 0 ? 0.5 : 0.25);
            }
          }
        }
      }
      function formatCategory(ax, out) {
        var tt = ax._categories[Math.round(out.x)];
        if (tt === void 0) tt = "";
        out.text = String(tt);
      }
      function formatMultiCategory(ax, out, hover) {
        var v = Math.round(out.x);
        var cats = ax._categories[v] || [];
        var tt = cats[1] === void 0 ? "" : String(cats[1]);
        var tt2 = cats[0] === void 0 ? "" : String(cats[0]);
        if (hover) {
          out.text = tt2 + " - " + tt;
        } else {
          out.text = tt;
          out.text2 = tt2;
        }
      }
      function formatLinear(ax, out, hover, extraPrecision, hideexp) {
        if (hideexp === "never") {
          hideexp = "";
        } else if (ax.showexponent === "all" && Math.abs(out.x / ax.dtick) < 1e-6) {
          hideexp = "hide";
        }
        out.text = numFormat(out.x, ax, hideexp, extraPrecision);
      }
      function formatAngle(ax, out, hover, extraPrecision, hideexp) {
        if (ax.thetaunit === "radians" && !hover) {
          var num = out.x / 180;
          if (num === 0) {
            out.text = "0";
          } else {
            var frac = num2frac(num);
            if (frac[1] >= 100) {
              out.text = numFormat(Lib.deg2rad(out.x), ax, hideexp, extraPrecision);
            } else {
              var isNeg = out.x < 0;
              if (frac[1] === 1) {
                if (frac[0] === 1) out.text = "\u03C0";
                else out.text = frac[0] + "\u03C0";
              } else {
                out.text = [
                  "<sup>",
                  frac[0],
                  "</sup>",
                  "\u2044",
                  "<sub>",
                  frac[1],
                  "</sub>",
                  "\u03C0"
                ].join("");
              }
              if (isNeg) out.text = MINUS_SIGN + out.text;
            }
          }
        } else {
          out.text = numFormat(out.x, ax, hideexp, extraPrecision);
        }
      }
      function num2frac(num) {
        function almostEq(a, b) {
          return Math.abs(a - b) <= 1e-6;
        }
        function findGCD(a, b) {
          return almostEq(b, 0) ? a : findGCD(b, a % b);
        }
        function findPrecision(n) {
          var e = 1;
          while (!almostEq(Math.round(n * e) / e, n)) {
            e *= 10;
          }
          return e;
        }
        var precision = findPrecision(num);
        var number = num * precision;
        var gcd = Math.abs(findGCD(number, precision));
        return [
          // numerator
          Math.round(number / gcd),
          // denominator
          Math.round(precision / gcd)
        ];
      }
      var SIPREFIXES = ["f", "p", "n", "\u03BC", "m", "", "k", "M", "G", "T"];
      var SIPREFIXES_EXTENDED = ["q", "r", "y", "z", "a", ...SIPREFIXES, "P", "E", "Z", "Y", "R", "Q"];
      var isSIFormat = (exponentFormat) => ["SI", "SI extended", "B"].includes(exponentFormat);
      function beyondSI(exponent) {
        return exponent > 14 || exponent < -15;
      }
      function beyondSIExtended(exponent) {
        return exponent > 32 || exponent < -30;
      }
      function shouldSwitchSIToPowerFormat(exponent, exponentFormat) {
        if (!isSIFormat(exponentFormat)) return false;
        if (exponentFormat === "SI extended" && beyondSIExtended(exponent)) return true;
        if (exponentFormat !== "SI extended" && beyondSI(exponent)) return true;
        return false;
      }
      function numFormat(v, ax, fmtoverride, hover) {
        var isNeg = v < 0;
        var tickRound = ax._tickround;
        var exponentFormat = fmtoverride || ax.exponentformat || "B";
        var exponent = ax._tickexponent;
        var tickformat = axes.getTickFormat(ax);
        var separatethousands = ax.separatethousands;
        if (hover) {
          var ah = {
            exponentformat: exponentFormat,
            minexponent: ax.minexponent,
            dtick: ax.showexponent === "none" ? ax.dtick : isNumeric(v) ? Math.abs(v) || 1 : 1,
            // if not showing any exponents, don't change the exponent
            // from what we calculate
            range: ax.showexponent === "none" ? ax.range.map(ax.r2d) : [0, v || 1]
          };
          autoTickRound(ah);
          tickRound = (Number(ah._tickround) || 0) + 4;
          exponent = ah._tickexponent;
          if (ax.hoverformat) tickformat = ax.hoverformat;
        }
        if (tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN);
        var e = Math.pow(10, -tickRound) / 2;
        if (exponentFormat === "none") exponent = 0;
        v = Math.abs(v);
        if (v < e) {
          v = "0";
          isNeg = false;
        } else {
          v += e;
          if (exponent) {
            v *= Math.pow(10, -exponent);
            tickRound += exponent;
          }
          if (tickRound === 0) v = String(Math.floor(v));
          else if (tickRound < 0) {
            v = String(Math.round(v));
            v = v.slice(0, Math.max(0, v.length + tickRound));
            for (var i = tickRound; i < 0; i++) v += "0";
          } else {
            v = String(v);
            var dp = v.indexOf(".") + 1;
            if (dp) v = v.slice(0, dp + tickRound).replace(/\.?0+$/, "");
          }
          v = Lib.numSeparate(v, ax._separators, separatethousands);
        }
        if (exponent && exponentFormat !== "hide") {
          if (shouldSwitchSIToPowerFormat(exponent, exponentFormat)) exponentFormat = "power";
          var signedExponent;
          if (exponent < 0) signedExponent = MINUS_SIGN + -exponent;
          else if (exponentFormat !== "power") signedExponent = "+" + exponent;
          else signedExponent = String(exponent);
          if (exponentFormat === "e" || exponentFormat === "E") {
            v += exponentFormat + signedExponent;
          } else if (exponentFormat === "power") {
            v += "\xD710<sup>" + signedExponent + "</sup>";
          } else if (exponentFormat === "B" && exponent === 9) {
            v += "B";
          } else if (isSIFormat(exponentFormat)) {
            v += exponentFormat === "SI extended" ? SIPREFIXES_EXTENDED[exponent / 3 + 10] : SIPREFIXES[exponent / 3 + 5];
          }
        }
        if (isNeg) return MINUS_SIGN + v;
        return v;
      }
      axes.getTickFormat = function(ax) {
        var i;
        function convertToMs(dtick) {
          return typeof dtick !== "string" ? dtick : Number(dtick.replace("M", "")) * ONEAVGMONTH;
        }
        function compareLogTicks(left, right) {
          var priority = ["L", "D"];
          if (typeof left === typeof right) {
            if (typeof left === "number") {
              return left - right;
            } else {
              var leftPriority = priority.indexOf(left.charAt(0));
              var rightPriority = priority.indexOf(right.charAt(0));
              if (leftPriority === rightPriority) {
                return Number(left.replace(/(L|D)/g, "")) - Number(right.replace(/(L|D)/g, ""));
              } else {
                return leftPriority - rightPriority;
              }
            }
          } else {
            return typeof left === "number" ? 1 : -1;
          }
        }
        function isProperStop(dtick, range, convert) {
          var convertFn = convert || function(x) {
            return x;
          };
          var leftDtick = range[0];
          var rightDtick = range[1];
          return (!leftDtick && typeof leftDtick !== "number" || convertFn(leftDtick) <= convertFn(dtick)) && (!rightDtick && typeof rightDtick !== "number" || convertFn(rightDtick) >= convertFn(dtick));
        }
        function isProperLogStop(dtick, range) {
          var isLeftDtickNull = range[0] === null;
          var isRightDtickNull = range[1] === null;
          var isDtickInRangeLeft = compareLogTicks(dtick, range[0]) >= 0;
          var isDtickInRangeRight = compareLogTicks(dtick, range[1]) <= 0;
          return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight);
        }
        var tickstop, stopi;
        if (ax.tickformatstops && ax.tickformatstops.length > 0) {
          switch (ax.type) {
            case "date":
            case "linear": {
              for (i = 0; i < ax.tickformatstops.length; i++) {
                stopi = ax.tickformatstops[i];
                if (stopi.enabled && isProperStop(ax.dtick, stopi.dtickrange, convertToMs)) {
                  tickstop = stopi;
                  break;
                }
              }
              break;
            }
            case "log": {
              for (i = 0; i < ax.tickformatstops.length; i++) {
                stopi = ax.tickformatstops[i];
                if (stopi.enabled && isProperLogStop(ax.dtick, stopi.dtickrange)) {
                  tickstop = stopi;
                  break;
                }
              }
              break;
            }
            default:
          }
        }
        return tickstop ? tickstop.value : ax.tickformat;
      };
      axes.getSubplots = function(gd, ax) {
        var subplotObj = gd._fullLayout._subplots;
        var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []);
        var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots;
        out.sort(function(a, b) {
          var aParts = a.slice(1).split("y");
          var bParts = b.slice(1).split("y");
          if (aParts[0] === bParts[0]) return +aParts[1] - +bParts[1];
          return +aParts[0] - +bParts[0];
        });
        return out;
      };
      axes.findSubplotsWithAxis = function(subplots, ax) {
        var axMatch = new RegExp(
          ax._id.charAt(0) === "x" ? "^" + ax._id + "y" : ax._id + "$"
        );
        var subplotsWithAx = [];
        for (var i = 0; i < subplots.length; i++) {
          var sp = subplots[i];
          if (axMatch.test(sp)) subplotsWithAx.push(sp);
        }
        return subplotsWithAx;
      };
      axes.makeClipPaths = function(gd) {
        var fullLayout = gd._fullLayout;
        if (fullLayout._hasOnlyLargeSploms) return;
        var fullWidth = { _offset: 0, _length: fullLayout.width, _id: "" };
        var fullHeight = { _offset: 0, _length: fullLayout.height, _id: "" };
        var xaList = axes.list(gd, "x", true);
        var yaList = axes.list(gd, "y", true);
        var clipList = [];
        var i, j;
        for (i = 0; i < xaList.length; i++) {
          clipList.push({ x: xaList[i], y: fullHeight });
          for (j = 0; j < yaList.length; j++) {
            if (i === 0) clipList.push({ x: fullWidth, y: yaList[j] });
            clipList.push({ x: xaList[i], y: yaList[j] });
          }
        }
        var axClips = fullLayout._clips.selectAll(".axesclip").data(clipList, function(d) {
          return d.x._id + d.y._id;
        });
        axClips.enter().append("clipPath").classed("axesclip", true).attr("id", function(d) {
          return "clip" + fullLayout._uid + d.x._id + d.y._id;
        }).append("rect");
        axClips.exit().remove();
        axClips.each(function(d) {
          d3.select(this).select("rect").attr({
            x: d.x._offset || 0,
            y: d.y._offset || 0,
            width: d.x._length || 1,
            height: d.y._length || 1
          });
        });
      };
      axes.draw = function(gd, arg, opts) {
        var fullLayout = gd._fullLayout;
        if (arg === "redraw") {
          fullLayout._paper.selectAll("g.subplot").each(function(d) {
            var id = d[0];
            var plotinfo = fullLayout._plots[id];
            if (plotinfo) {
              var xa = plotinfo.xaxis;
              var ya = plotinfo.yaxis;
              plotinfo.xaxislayer.selectAll("." + xa._id + "tick").remove();
              plotinfo.yaxislayer.selectAll("." + ya._id + "tick").remove();
              plotinfo.xaxislayer.selectAll("." + xa._id + "tick2").remove();
              plotinfo.yaxislayer.selectAll("." + ya._id + "tick2").remove();
              plotinfo.xaxislayer.selectAll("." + xa._id + "divider").remove();
              plotinfo.yaxislayer.selectAll("." + ya._id + "divider").remove();
              if (plotinfo.minorGridlayer) plotinfo.minorGridlayer.selectAll("path").remove();
              if (plotinfo.gridlayer) plotinfo.gridlayer.selectAll("path").remove();
              if (plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll("path").remove();
              if (plotinfo.zerolinelayerAbove) plotinfo.zerolinelayerAbove.selectAll("path").remove();
              fullLayout._infolayer.select(".g-" + xa._id + "title").remove();
              fullLayout._infolayer.select(".g-" + ya._id + "title").remove();
            }
          });
        }
        var axList = !arg || arg === "redraw" ? axes.listIds(gd) : arg;
        var fullAxList = axes.list(gd);
        var overlayingShiftedAx = fullAxList.filter(function(ax) {
          return ax.autoshift;
        }).map(function(ax) {
          return ax.overlaying;
        });
        axList.map(function(axId) {
          var ax = axes.getFromId(gd, axId);
          if (ax.tickmode === "sync" && ax.overlaying) {
            var overlayingIndex = axList.findIndex(function(axis) {
              return axis === ax.overlaying;
            });
            if (overlayingIndex >= 0) {
              axList.unshift(axList.splice(overlayingIndex, 1).shift());
            }
          }
        });
        var axShifts = { false: { left: 0, right: 0 } };
        return Lib.syncOrAsync(axList.map(function(axId) {
          return function() {
            if (!axId) return;
            var ax = axes.getFromId(gd, axId);
            if (!opts) opts = {};
            opts.axShifts = axShifts;
            opts.overlayingShiftedAx = overlayingShiftedAx;
            var axDone = axes.drawOne(gd, ax, opts);
            if (ax._shiftPusher) {
              incrementShift(ax, ax._fullDepth || 0, axShifts, true);
            }
            ax._r = ax.range.slice();
            ax._rl = Lib.simpleMap(ax._r, ax.r2l);
            return axDone;
          };
        }));
      };
      axes.drawOne = function(gd, ax, opts) {
        opts = opts || {};
        var axShifts = opts.axShifts || {};
        var overlayingShiftedAx = opts.overlayingShiftedAx || [];
        var i, sp, plotinfo;
        ax.setScale();
        var fullLayout = gd._fullLayout;
        var axId = ax._id;
        var axLetter = axId.charAt(0);
        var counterLetter = axes.counterLetter(axId);
        var mainPlotinfo = fullLayout._plots[ax._mainSubplot];
        var zerolineIsAbove = ax.zerolinelayer === "above traces";
        if (!mainPlotinfo) return;
        ax._shiftPusher = ax.autoshift || overlayingShiftedAx.indexOf(ax._id) !== -1 || overlayingShiftedAx.indexOf(ax.overlaying) !== -1;
        if (ax._shiftPusher & ax.anchor === "free") {
          var selfPush = ax.linewidth / 2 || 0;
          if (ax.ticks === "inside") {
            selfPush += ax.ticklen;
          }
          incrementShift(ax, selfPush, axShifts, true);
          incrementShift(ax, ax.shift || 0, axShifts, false);
        }
        if (opts.skipTitle !== true || ax._shift === void 0) ax._shift = setShiftVal(ax, axShifts);
        var mainAxLayer = mainPlotinfo[axLetter + "axislayer"];
        var mainLinePosition = ax._mainLinePosition;
        var mainLinePositionShift = mainLinePosition += ax._shift;
        var mainMirrorPosition = ax._mainMirrorPosition;
        var vals = ax._vals = axes.calcTicks(ax);
        var axInfo = [ax.mirror, mainLinePositionShift, mainMirrorPosition].join("_");
        for (i = 0; i < vals.length; i++) {
          vals[i].axInfo = axInfo;
        }
        ax._selections = {};
        if (ax._tickAngles) ax._prevTickAngles = ax._tickAngles;
        ax._tickAngles = {};
        ax._depth = null;
        var llbboxes = {};
        function getLabelLevelBbox(suffix) {
          var cls = axId + (suffix || "tick");
          if (!llbboxes[cls]) llbboxes[cls] = calcLabelLevelBbox(ax, cls, mainLinePositionShift);
          return llbboxes[cls];
        }
        if (!ax.visible) return;
        var transTickFn = axes.makeTransTickFn(ax);
        var transTickLabelFn = axes.makeTransTickLabelFn(ax);
        var tickVals;
        var valsClipped;
        var insideTicks = ax.ticks === "inside";
        var outsideTicks = ax.ticks === "outside";
        if (ax.tickson === "boundaries") {
          var boundaryVals = getBoundaryVals(ax, vals);
          valsClipped = axes.clipEnds(ax, boundaryVals);
          tickVals = insideTicks ? valsClipped : boundaryVals;
        } else {
          valsClipped = axes.clipEnds(ax, vals);
          tickVals = insideTicks && ax.ticklabelmode !== "period" ? valsClipped : vals;
        }
        var gridVals = ax._gridVals = valsClipped;
        var dividerVals = getDividerVals(ax, vals);
        if (!fullLayout._hasOnlyLargeSploms) {
          var subplotsWithAx = ax._subplotsWith;
          var finishedGrids = {};
          for (i = 0; i < subplotsWithAx.length; i++) {
            sp = subplotsWithAx[i];
            plotinfo = fullLayout._plots[sp];
            var counterAxis = plotinfo[counterLetter + "axis"];
            var mainCounterID = counterAxis._mainAxis._id;
            if (finishedGrids[mainCounterID]) continue;
            finishedGrids[mainCounterID] = 1;
            var gridPath = axLetter === "x" ? "M0," + counterAxis._offset + "v" + counterAxis._length : "M" + counterAxis._offset + ",0h" + counterAxis._length;
            axes.drawGrid(gd, ax, {
              vals: gridVals,
              counterAxis,
              layer: plotinfo.gridlayer.select("." + axId),
              minorLayer: plotinfo.minorGridlayer.select("." + axId),
              path: gridPath,
              transFn: transTickFn
            });
            axes.drawZeroLine(gd, ax, {
              counterAxis,
              layer: zerolineIsAbove ? plotinfo.zerolinelayerAbove : plotinfo.zerolinelayer,
              path: gridPath,
              transFn: transTickFn
            });
          }
        }
        var tickPath;
        var majorTickSigns = axes.getTickSigns(ax);
        var minorTickSigns = axes.getTickSigns(ax, "minor");
        if (ax.ticks || ax.minor && ax.minor.ticks) {
          var majorTickPath = axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[2]);
          var minorTickPath = axes.makeTickPath(ax, mainLinePositionShift, minorTickSigns[2], { minor: true });
          var mirrorMajorTickPath;
          var mirrorMinorTickPath;
          var fullMajorTickPath;
          var fullMinorTickPath;
          if (ax._anchorAxis && ax.mirror && ax.mirror !== true) {
            mirrorMajorTickPath = axes.makeTickPath(ax, mainMirrorPosition, majorTickSigns[3]);
            mirrorMinorTickPath = axes.makeTickPath(ax, mainMirrorPosition, minorTickSigns[3], { minor: true });
            fullMajorTickPath = majorTickPath + mirrorMajorTickPath;
            fullMinorTickPath = minorTickPath + mirrorMinorTickPath;
          } else {
            mirrorMajorTickPath = "";
            mirrorMinorTickPath = "";
            fullMajorTickPath = majorTickPath;
            fullMinorTickPath = minorTickPath;
          }
          if (ax.showdividers && outsideTicks && ax.tickson === "boundaries") {
            var dividerLookup = {};
            for (i = 0; i < dividerVals.length; i++) {
              dividerLookup[dividerVals[i].x] = 1;
            }
            tickPath = function(d) {
              return dividerLookup[d.x] ? mirrorMajorTickPath : fullMajorTickPath;
            };
          } else {
            tickPath = function(d) {
              return d.minor ? fullMinorTickPath : fullMajorTickPath;
            };
          }
        }
        axes.drawTicks(gd, ax, {
          vals: tickVals,
          layer: mainAxLayer,
          path: tickPath,
          transFn: transTickFn
        });
        if (ax.mirror === "allticks") {
          var tickSubplots = Object.keys(ax._linepositions || {});
          for (i = 0; i < tickSubplots.length; i++) {
            sp = tickSubplots[i];
            plotinfo = fullLayout._plots[sp];
            var linepositions = ax._linepositions[sp] || [];
            var p0 = linepositions[0];
            var p1 = linepositions[1];
            var isMinor = linepositions[2];
            var spTickPath = axes.makeTickPath(
              ax,
              p0,
              isMinor ? majorTickSigns[0] : minorTickSigns[0],
              { minor: isMinor }
            ) + axes.makeTickPath(
              ax,
              p1,
              isMinor ? majorTickSigns[1] : minorTickSigns[1],
              { minor: isMinor }
            );
            axes.drawTicks(gd, ax, {
              vals: tickVals,
              layer: plotinfo[axLetter + "axislayer"],
              path: spTickPath,
              transFn: transTickFn
            });
          }
        }
        var seq = [];
        seq.push(function() {
          return axes.drawLabels(gd, ax, {
            vals,
            layer: mainAxLayer,
            plotinfo,
            transFn: transTickLabelFn,
            labelFns: axes.makeLabelFns(ax, mainLinePositionShift)
          });
        });
        if (ax.type === "multicategory") {
          var pad = { x: 2, y: 10 }[axLetter];
          seq.push(function() {
            var bboxKey = { x: "height", y: "width" }[axLetter];
            var standoff = getLabelLevelBbox()[bboxKey] + pad + (ax._tickAngles[axId + "tick"] ? ax.tickfont.size * LINE_SPACING : 0);
            return axes.drawLabels(gd, ax, {
              vals: getSecondaryLabelVals(ax, vals),
              layer: mainAxLayer,
              cls: axId + "tick2",
              repositionOnUpdate: true,
              secondary: true,
              transFn: transTickFn,
              labelFns: axes.makeLabelFns(ax, mainLinePositionShift + standoff * majorTickSigns[4])
            });
          });
          seq.push(function() {
            ax._depth = majorTickSigns[4] * (getLabelLevelBbox("tick2")[ax.side] - mainLinePositionShift);
            return drawDividers(gd, ax, {
              vals: dividerVals,
              layer: mainAxLayer,
              path: axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[4], { len: ax._depth }),
              transFn: transTickFn
            });
          });
        } else if (ax.title.hasOwnProperty("standoff")) {
          seq.push(function() {
            ax._depth = majorTickSigns[4] * (getLabelLevelBbox()[ax.side] - mainLinePositionShift);
          });
        }
        var hasRangeSlider = Registry.getComponentMethod("rangeslider", "isVisible")(ax);
        if (!opts.skipTitle && !(hasRangeSlider && ax.side === "bottom")) {
          seq.push(function() {
            return drawTitle(gd, ax);
          });
        }
        seq.push(function() {
          var s = ax.side.charAt(0);
          var sMirror = OPPOSITE_SIDE[ax.side].charAt(0);
          var pos = axes.getPxPosition(gd, ax);
          var outsideTickLen = outsideTicks ? ax.ticklen : 0;
          var llbbox;
          var push;
          var mirrorPush;
          var rangeSliderPush;
          if (ax.automargin || hasRangeSlider || ax._shiftPusher) {
            if (ax.type === "multicategory") {
              llbbox = getLabelLevelBbox("tick2");
            } else {
              llbbox = getLabelLevelBbox();
              if (axLetter === "x" && s === "b") {
                ax._depth = Math.max(llbbox.width > 0 ? llbbox.bottom - pos : 0, outsideTickLen);
              }
            }
          }
          var axDepth = 0;
          var titleDepth = 0;
          if (ax._shiftPusher) {
            axDepth = Math.max(
              outsideTickLen,
              llbbox.height > 0 ? s === "l" ? pos - llbbox.left : llbbox.right - pos : 0
            );
            if (ax.title.text !== fullLayout._dfltTitle[axLetter]) {
              titleDepth = (ax._titleStandoff || 0) + (ax._titleScoot || 0);
              if (s === "l") {
                titleDepth += approxTitleDepth(ax);
              }
            }
            ax._fullDepth = Math.max(axDepth, titleDepth);
          }
          if (ax.automargin) {
            push = { x: 0, y: 0, r: 0, l: 0, t: 0, b: 0 };
            var domainIndices = [0, 1];
            var shift = typeof ax._shift === "number" ? ax._shift : 0;
            if (axLetter === "x") {
              if (s === "b") {
                push[s] = ax._depth;
              } else {
                push[s] = ax._depth = Math.max(llbbox.width > 0 ? pos - llbbox.top : 0, outsideTickLen);
                domainIndices.reverse();
              }
              if (llbbox.width > 0) {
                var rExtra = llbbox.right - (ax._offset + ax._length);
                if (rExtra > 0) {
                  push.xr = 1;
                  push.r = rExtra;
                }
                var lExtra = ax._offset - llbbox.left;
                if (lExtra > 0) {
                  push.xl = 0;
                  push.l = lExtra;
                }
              }
            } else {
              if (s === "l") {
                ax._depth = Math.max(llbbox.height > 0 ? pos - llbbox.left : 0, outsideTickLen);
                push[s] = ax._depth - shift;
              } else {
                ax._depth = Math.max(llbbox.height > 0 ? llbbox.right - pos : 0, outsideTickLen);
                push[s] = ax._depth + shift;
                domainIndices.reverse();
              }
              if (llbbox.height > 0) {
                var bExtra = llbbox.bottom - (ax._offset + ax._length);
                if (bExtra > 0) {
                  push.yb = 0;
                  push.b = bExtra;
                }
                var tExtra = ax._offset - llbbox.top;
                if (tExtra > 0) {
                  push.yt = 1;
                  push.t = tExtra;
                }
              }
            }
            push[counterLetter] = ax.anchor === "free" ? ax.position : ax._anchorAxis.domain[domainIndices[0]];
            if (ax.title.text !== fullLayout._dfltTitle[axLetter]) {
              push[s] += approxTitleDepth(ax) + (ax.title.standoff || 0);
            }
            if (ax.mirror && ax.anchor !== "free") {
              mirrorPush = { x: 0, y: 0, r: 0, l: 0, t: 0, b: 0 };
              mirrorPush[sMirror] = ax.linewidth;
              if (ax.mirror && ax.mirror !== true) mirrorPush[sMirror] += outsideTickLen;
              if (ax.mirror === true || ax.mirror === "ticks") {
                mirrorPush[counterLetter] = ax._anchorAxis.domain[domainIndices[1]];
              } else if (ax.mirror === "all" || ax.mirror === "allticks") {
                mirrorPush[counterLetter] = [ax._counterDomainMin, ax._counterDomainMax][domainIndices[1]];
              }
            }
          }
          if (hasRangeSlider) {
            rangeSliderPush = Registry.getComponentMethod("rangeslider", "autoMarginOpts")(gd, ax);
          }
          if (typeof ax.automargin === "string") {
            filterPush(push, ax.automargin);
            filterPush(mirrorPush, ax.automargin);
          }
          Plots.autoMargin(gd, axAutoMarginID(ax), push);
          Plots.autoMargin(gd, axMirrorAutoMarginID(ax), mirrorPush);
          Plots.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush);
        });
        return Lib.syncOrAsync(seq);
      };
      function filterPush(push, automargin) {
        if (!push) return;
        var keepMargin = Object.keys(MARGIN_MAPPING).reduce(function(data, nextKey) {
          if (automargin.indexOf(nextKey) !== -1) {
            MARGIN_MAPPING[nextKey].forEach(function(key) {
              data[key] = 1;
            });
          }
          return data;
        }, {});
        Object.keys(push).forEach(function(key) {
          if (!keepMargin[key]) {
            if (key.length === 1) push[key] = 0;
            else delete push[key];
          }
        });
      }
      function getBoundaryVals(ax, vals) {
        var out = [];
        var i;
        var _push = function(d, bndIndex) {
          var xb = d.xbnd[bndIndex];
          if (xb !== null) {
            out.push(Lib.extendFlat({}, d, { x: xb }));
          }
        };
        if (vals.length) {
          for (i = 0; i < vals.length; i++) {
            _push(vals[i], 0);
          }
          _push(vals[i - 1], 1);
        }
        return out;
      }
      function getSecondaryLabelVals(ax, vals) {
        var out = [];
        var lookup = {};
        for (var i = 0; i < vals.length; i++) {
          var d = vals[i];
          if (lookup[d.text2]) {
            lookup[d.text2].push(d.x);
          } else {
            lookup[d.text2] = [d.x];
          }
        }
        for (var k in lookup) {
          out.push(tickTextObj(ax, Lib.interp(lookup[k], 0.5), k));
        }
        return out;
      }
      function getDividerVals(ax, vals) {
        var out = [];
        var i, current;
        var reversed = vals.length && vals[vals.length - 1].x < vals[0].x;
        var _push = function(d2, bndIndex) {
          var xb = d2.xbnd[bndIndex];
          if (xb !== null) {
            out.push(Lib.extendFlat({}, d2, { x: xb }));
          }
        };
        if (ax.showdividers && vals.length) {
          for (i = 0; i < vals.length; i++) {
            var d = vals[i];
            if (d.text2 !== current) {
              _push(d, reversed ? 1 : 0);
            }
            current = d.text2;
          }
          _push(vals[i - 1], reversed ? 0 : 1);
        }
        return out;
      }
      function calcLabelLevelBbox(ax, cls, mainLinePositionShift) {
        var top, bottom;
        var left, right;
        if (ax._selections[cls].size()) {
          top = Infinity;
          bottom = -Infinity;
          left = Infinity;
          right = -Infinity;
          ax._selections[cls].each(function() {
            var thisLabel = selectTickLabel(this);
            if (thisLabel.node().style.display !== "none") {
              var bb = Drawing.bBox(thisLabel.node().parentNode);
              top = Math.min(top, bb.top);
              bottom = Math.max(bottom, bb.bottom);
              left = Math.min(left, bb.left);
              right = Math.max(right, bb.right);
            }
          });
        } else {
          var dummyCalc = axes.makeLabelFns(ax, mainLinePositionShift);
          top = bottom = dummyCalc.yFn({ dx: 0, dy: 0, fontSize: 0 });
          left = right = dummyCalc.xFn({ dx: 0, dy: 0, fontSize: 0 });
        }
        return {
          top,
          bottom,
          left,
          right,
          height: bottom - top,
          width: right - left
        };
      }
      axes.getTickSigns = function(ax, minor) {
        var axLetter = ax._id.charAt(0);
        var sideOpposite = { x: "top", y: "right" }[axLetter];
        var main = ax.side === sideOpposite ? 1 : -1;
        var out = [-1, 1, main, -main];
        var ticks = minor ? (ax.minor || {}).ticks : ax.ticks;
        if (ticks !== "inside" === (axLetter === "x")) {
          out = out.map(function(v) {
            return -v;
          });
        }
        if (ax.side) {
          out.push({ l: -1, t: -1, r: 1, b: 1 }[ax.side.charAt(0)]);
        }
        return out;
      };
      axes.makeTransTickFn = function(ax) {
        return ax._id.charAt(0) === "x" ? function(d) {
          return strTranslate(ax._offset + ax.l2p(d.x), 0);
        } : function(d) {
          return strTranslate(0, ax._offset + ax.l2p(d.x));
        };
      };
      axes.makeTransTickLabelFn = function(ax) {
        var uv = getTickLabelUV(ax);
        var shift = ax.ticklabelshift || 0;
        var standoff = ax.ticklabelstandoff || 0;
        var u = uv[0];
        var v = uv[1];
        var isReversed = ax.range[0] > ax.range[1];
        var labelsInside = ax.ticklabelposition && ax.ticklabelposition.indexOf("inside") !== -1;
        var labelsOutside = !labelsInside;
        if (shift) {
          var shiftSign = isReversed ? -1 : 1;
          shift = shift * shiftSign;
        }
        if (standoff) {
          var side = ax.side;
          var standoffSign = labelsInside && (side === "top" || side === "left") || labelsOutside && (side === "bottom" || side === "right") ? 1 : -1;
          standoff = standoff * standoffSign;
        }
        return ax._id.charAt(0) === "x" ? function(d) {
          return strTranslate(
            u + ax._offset + ax.l2p(getPosX(d)) + shift,
            v + standoff
          );
        } : function(d) {
          return strTranslate(
            v + standoff,
            u + ax._offset + ax.l2p(getPosX(d)) + shift
          );
        };
      };
      function getPosX(d) {
        return d.periodX !== void 0 ? d.periodX : d.x;
      }
      function getTickLabelUV(ax) {
        var ticklabelposition = ax.ticklabelposition || "";
        var tickson = ax.tickson || "";
        var has = function(str) {
          return ticklabelposition.indexOf(str) !== -1;
        };
        var isTop = has("top");
        var isLeft = has("left");
        var isRight = has("right");
        var isBottom = has("bottom");
        var isInside = has("inside");
        var isAligned = tickson !== "boundaries" && (isBottom || isLeft || isTop || isRight);
        if (!isAligned && !isInside) return [0, 0];
        var side = ax.side;
        var u = isAligned ? (ax.tickwidth || 0) / 2 : 0;
        var v = TEXTPAD;
        var fontSize = ax.tickfont ? ax.tickfont.size : 12;
        if (isBottom || isTop) {
          u += fontSize * CAP_SHIFT;
          v += (ax.linewidth || 0) / 2;
        }
        if (isLeft || isRight) {
          u += (ax.linewidth || 0) / 2;
          v += TEXTPAD;
        }
        if (isInside && side === "top") {
          v -= fontSize * (1 - CAP_SHIFT);
        }
        if (isLeft || isTop) u = -u;
        if (side === "bottom" || side === "right") v = -v;
        return [
          isAligned ? u : 0,
          isInside ? v : 0
        ];
      }
      axes.makeTickPath = function(ax, shift, sgn, opts) {
        if (!opts) opts = {};
        var minor = opts.minor;
        if (minor && !ax.minor) return "";
        var len = opts.len !== void 0 ? opts.len : minor ? ax.minor.ticklen : ax.ticklen;
        var axLetter = ax._id.charAt(0);
        var pad = (ax.linewidth || 1) / 2;
        return axLetter === "x" ? "M0," + (shift + pad * sgn) + "v" + len * sgn : "M" + (shift + pad * sgn) + ",0h" + len * sgn;
      };
      axes.makeLabelFns = function(ax, shift, angle) {
        var ticklabelposition = ax.ticklabelposition || "";
        var tickson = ax.tickson || "";
        var has = function(str) {
          return ticklabelposition.indexOf(str) !== -1;
        };
        var isTop = has("top");
        var isLeft = has("left");
        var isRight = has("right");
        var isBottom = has("bottom");
        var isAligned = tickson !== "boundaries" && (isBottom || isLeft || isTop || isRight);
        var insideTickLabels = has("inside");
        var labelsOverTicks = ticklabelposition === "inside" && ax.ticks === "inside" || !insideTickLabels && ax.ticks === "outside" && tickson !== "boundaries";
        var labelStandoff = 0;
        var labelShift = 0;
        var tickLen = labelsOverTicks ? ax.ticklen : 0;
        if (insideTickLabels) {
          tickLen *= -1;
        } else if (isAligned) {
          tickLen = 0;
        }
        if (labelsOverTicks) {
          labelStandoff += tickLen;
          if (angle) {
            var rad = Lib.deg2rad(angle);
            labelStandoff = tickLen * Math.cos(rad) + 1;
            labelShift = tickLen * Math.sin(rad);
          }
        }
        if (ax.showticklabels && (labelsOverTicks || ax.showline)) {
          labelStandoff += 0.2 * ax.tickfont.size;
        }
        labelStandoff += (ax.linewidth || 1) / 2 * (insideTickLabels ? -1 : 1);
        var out = {
          labelStandoff,
          labelShift
        };
        var x0, y0, ff, flipIt;
        var xQ = 0;
        var side = ax.side;
        var axLetter = ax._id.charAt(0);
        var tickangle = ax.tickangle;
        var endSide;
        if (axLetter === "x") {
          endSide = !insideTickLabels && side === "bottom" || insideTickLabels && side === "top";
          flipIt = endSide ? 1 : -1;
          if (insideTickLabels) flipIt *= -1;
          x0 = labelShift * flipIt;
          y0 = shift + labelStandoff * flipIt;
          ff = endSide ? 1 : -0.2;
          if (Math.abs(tickangle) === 90) {
            if (insideTickLabels) {
              ff += MID_SHIFT;
            } else {
              if (tickangle === -90 && side === "bottom") {
                ff = CAP_SHIFT;
              } else if (tickangle === 90 && side === "top") {
                ff = MID_SHIFT;
              } else {
                ff = 0.5;
              }
            }
            xQ = MID_SHIFT / 2 * (tickangle / 90);
          }
          out.xFn = function(d) {
            return d.dx + x0 + xQ * d.fontSize;
          };
          out.yFn = function(d) {
            return d.dy + y0 + d.fontSize * ff;
          };
          out.anchorFn = function(d, a) {
            if (isAligned) {
              if (isLeft) return "end";
              if (isRight) return "start";
            }
            if (!isNumeric(a) || a === 0 || a === 180) {
              return "middle";
            }
            return a * flipIt < 0 !== insideTickLabels ? "end" : "start";
          };
          out.heightFn = function(d, a, h) {
            return a < -60 || a > 60 ? -0.5 * h : ax.side === "top" !== insideTickLabels ? -h : 0;
          };
        } else if (axLetter === "y") {
          endSide = !insideTickLabels && side === "left" || insideTickLabels && side === "right";
          flipIt = endSide ? 1 : -1;
          if (insideTickLabels) flipIt *= -1;
          x0 = labelStandoff;
          y0 = labelShift * flipIt;
          ff = 0;
          if (!insideTickLabels && Math.abs(tickangle) === 90) {
            if (tickangle === -90 && side === "left" || tickangle === 90 && side === "right") {
              ff = CAP_SHIFT;
            } else {
              ff = 0.5;
            }
          }
          if (insideTickLabels) {
            var ang = isNumeric(tickangle) ? +tickangle : 0;
            if (ang !== 0) {
              var rA = Lib.deg2rad(ang);
              xQ = Math.abs(Math.sin(rA)) * CAP_SHIFT * flipIt;
              ff = 0;
            }
          }
          out.xFn = function(d) {
            return d.dx + shift - (x0 + d.fontSize * ff) * flipIt + xQ * d.fontSize;
          };
          out.yFn = function(d) {
            return d.dy + y0 + d.fontSize * MID_SHIFT;
          };
          out.anchorFn = function(d, a) {
            if (isNumeric(a) && Math.abs(a) === 90) {
              return "middle";
            }
            return endSide ? "end" : "start";
          };
          out.heightFn = function(d, a, h) {
            if (ax.side === "right") a *= -1;
            return a < -30 ? -h : a < 30 ? -0.5 * h : 0;
          };
        }
        return out;
      };
      function tickDataFn(d) {
        return [d.text, d.x, d.axInfo, d.font, d.fontSize, d.fontColor].join("_");
      }
      axes.drawTicks = function(gd, ax, opts) {
        opts = opts || {};
        var cls = ax._id + "tick";
        var vals = [].concat(
          ax.minor && ax.minor.ticks ? (
            // minor vals
            opts.vals.filter(function(d) {
              return d.minor && !d.noTick;
            })
          ) : []
        ).concat(
          ax.ticks ? (
            // major vals
            opts.vals.filter(function(d) {
              return !d.minor && !d.noTick;
            })
          ) : []
        );
        var ticks = opts.layer.selectAll("path." + cls).data(vals, tickDataFn);
        ticks.exit().remove();
        ticks.enter().append("path").classed(cls, 1).classed("ticks", 1).classed("crisp", opts.crisp !== false).each(function(d) {
          return Color2.stroke(d3.select(this), d.minor ? ax.minor.tickcolor : ax.tickcolor);
        }).style("stroke-width", function(d) {
          return Drawing.crispRound(
            gd,
            d.minor ? ax.minor.tickwidth : ax.tickwidth,
            1
          ) + "px";
        }).attr("d", opts.path).style("display", null);
        hideCounterAxisInsideTickLabels(ax, [TICK_PATH]);
        ticks.attr("transform", opts.transFn);
      };
      axes.drawGrid = function(gd, ax, opts) {
        opts = opts || {};
        if (ax.tickmode === "sync") {
          return;
        }
        var cls = ax._id + "grid";
        var hasMinor = ax.minor && ax.minor.showgrid;
        var minorVals = hasMinor ? opts.vals.filter(function(d) {
          return d.minor;
        }) : [];
        var majorVals = ax.showgrid ? opts.vals.filter(function(d) {
          return !d.minor;
        }) : [];
        var counterAx = opts.counterAxis;
        if (counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) {
          var isArrayMode = ax.tickmode === "array";
          for (var i = 0; i < majorVals.length; i++) {
            var xi = majorVals[i].x;
            if (isArrayMode ? !xi : Math.abs(xi) < ax.dtick / 100) {
              majorVals = majorVals.slice(0, i).concat(majorVals.slice(i + 1));
              if (isArrayMode) i--;
              else break;
            }
          }
        }
        ax._gw = Drawing.crispRound(gd, ax.gridwidth, 1);
        var wMinor = !hasMinor ? 0 : Drawing.crispRound(gd, ax.minor.gridwidth, 1);
        var majorLayer = opts.layer;
        var minorLayer = opts.minorLayer;
        for (var major = 1; major >= 0; major--) {
          var layer = major ? majorLayer : minorLayer;
          if (!layer) continue;
          var grid = layer.selectAll("path." + cls).data(major ? majorVals : minorVals, tickDataFn);
          grid.exit().remove();
          grid.enter().append("path").classed(cls, 1).classed("crisp", opts.crisp !== false);
          grid.attr("transform", opts.transFn).attr("d", opts.path).each(function(d) {
            return Color2.stroke(
              d3.select(this),
              d.minor ? ax.minor.gridcolor : ax.gridcolor || "#ddd"
            );
          }).style("stroke-dasharray", function(d) {
            return Drawing.dashStyle(
              d.minor ? ax.minor.griddash : ax.griddash,
              d.minor ? ax.minor.gridwidth : ax.gridwidth
            );
          }).style("stroke-width", function(d) {
            return (d.minor ? wMinor : ax._gw) + "px";
          }).style("display", null);
          if (typeof opts.path === "function") grid.attr("d", opts.path);
        }
        hideCounterAxisInsideTickLabels(ax, [GRID_PATH, MINORGRID_PATH]);
      };
      axes.drawZeroLine = function(gd, ax, opts) {
        opts = opts || opts;
        var cls = ax._id + "zl";
        var show = axes.shouldShowZeroLine(gd, ax, opts.counterAxis);
        var zl = opts.layer.selectAll("path." + cls).data(show ? [{ x: 0, id: ax._id }] : []);
        zl.exit().remove();
        zl.enter().append("path").classed(cls, 1).classed("zl", 1).classed("crisp", opts.crisp !== false).each(function() {
          opts.layer.selectAll("path").sort(function(da, db) {
            return idSort(da.id, db.id);
          });
        });
        zl.attr("transform", opts.transFn).attr("d", opts.path).call(Color2.stroke, ax.zerolinecolor || Color2.defaultLine).style("stroke-width", Drawing.crispRound(gd, ax.zerolinewidth, ax._gw || 1) + "px").style("display", null);
        hideCounterAxisInsideTickLabels(ax, [ZERO_PATH]);
      };
      axes.drawLabels = function(gd, ax, opts) {
        opts = opts || {};
        var fullLayout = gd._fullLayout;
        var axId = ax._id;
        var zerolineIsAbove = ax.zerolinelayer === "above traces";
        var cls = opts.cls || axId + "tick";
        var vals = opts.vals.filter(function(d) {
          return d.text;
        });
        var labelFns = opts.labelFns;
        var tickAngle = opts.secondary ? 0 : ax.tickangle;
        var prevAngle = (ax._prevTickAngles || {})[cls];
        var tickLabels = opts.layer.selectAll("g." + cls).data(ax.showticklabels ? vals : [], tickDataFn);
        var labelsReady = [];
        tickLabels.enter().append("g").classed(cls, 1).append("text").attr("text-anchor", "middle").each(function(d) {
          var thisLabel = d3.select(this);
          var newPromise = gd._promises.length;
          thisLabel.call(svgTextUtils.positionText, labelFns.xFn(d), labelFns.yFn(d)).call(Drawing.font, {
            family: d.font,
            size: d.fontSize,
            color: d.fontColor,
            weight: d.fontWeight,
            style: d.fontStyle,
            variant: d.fontVariant,
            textcase: d.fontTextcase,
            lineposition: d.fontLineposition,
            shadow: d.fontShadow
          }).text(d.text).call(svgTextUtils.convertToTspans, gd);
          if (gd._promises[newPromise]) {
            labelsReady.push(gd._promises.pop().then(function() {
              positionLabels(thisLabel, tickAngle);
            }));
          } else {
            positionLabels(thisLabel, tickAngle);
          }
        });
        hideCounterAxisInsideTickLabels(ax, [TICK_TEXT]);
        tickLabels.exit().remove();
        if (opts.repositionOnUpdate) {
          tickLabels.each(function(d) {
            d3.select(this).select("text").call(svgTextUtils.positionText, labelFns.xFn(d), labelFns.yFn(d));
          });
        }
        function positionLabels(s, angle) {
          s.each(function(d) {
            var thisLabel = d3.select(this);
            var mathjaxGroup = thisLabel.select(".text-math-group");
            var anchor = labelFns.anchorFn(d, angle);
            var transform = opts.transFn.call(thisLabel.node(), d) + (isNumeric(angle) && +angle !== 0 ? " rotate(" + angle + "," + labelFns.xFn(d) + "," + (labelFns.yFn(d) - d.fontSize / 2) + ")" : "");
            var nLines = svgTextUtils.lineCount(thisLabel);
            var lineHeight = LINE_SPACING * d.fontSize;
            var anchorHeight = labelFns.heightFn(d, isNumeric(angle) ? +angle : 0, (nLines - 1) * lineHeight);
            if (anchorHeight) {
              transform += strTranslate(0, anchorHeight);
            }
            if (mathjaxGroup.empty()) {
              var thisText = thisLabel.select("text");
              thisText.attr({
                transform,
                "text-anchor": anchor
              });
              thisText.style("display", null);
              if (ax._adjustTickLabelsOverflow) {
                ax._adjustTickLabelsOverflow();
              }
            } else {
              var mjWidth = Drawing.bBox(mathjaxGroup.node()).width;
              var mjShift = mjWidth * { end: -0.5, start: 0.5 }[anchor];
              mathjaxGroup.attr("transform", transform + strTranslate(mjShift, 0));
            }
          });
        }
        ax._adjustTickLabelsOverflow = function() {
          var ticklabeloverflow = ax.ticklabeloverflow;
          if (!ticklabeloverflow || ticklabeloverflow === "allow") return;
          var hideOverflow = ticklabeloverflow.indexOf("hide") !== -1;
          var isX = ax._id.charAt(0) === "x";
          var p02 = 0;
          var p12 = isX ? gd._fullLayout.width : gd._fullLayout.height;
          if (ticklabeloverflow.indexOf("domain") !== -1) {
            var rl = Lib.simpleMap(ax.range, ax.r2l);
            p02 = ax.l2p(rl[0]) + ax._offset;
            p12 = ax.l2p(rl[1]) + ax._offset;
          }
          var min = Math.min(p02, p12);
          var max = Math.max(p02, p12);
          var side = ax.side;
          var visibleLabelMin = Infinity;
          var visibleLabelMax = -Infinity;
          tickLabels.each(function(d) {
            var thisLabel = d3.select(this);
            var mathjaxGroup = thisLabel.select(".text-math-group");
            if (mathjaxGroup.empty()) {
              var bb = Drawing.bBox(thisLabel.node());
              var adjust = 0;
              if (isX) {
                if (bb.right > max) adjust = 1;
                else if (bb.left < min) adjust = 1;
              } else {
                if (bb.bottom > max) adjust = 1;
                else if (bb.top + (ax.tickangle ? 0 : d.fontSize / 4) < min) adjust = 1;
              }
              var t = thisLabel.select("text");
              if (adjust) {
                if (hideOverflow) t.style("display", "none");
              } else if (t.node().style.display !== "none") {
                t.style("display", null);
                if (side === "bottom" || side === "right") {
                  visibleLabelMin = Math.min(visibleLabelMin, isX ? bb.top : bb.left);
                } else {
                  visibleLabelMin = -Infinity;
                }
                if (side === "top" || side === "left") {
                  visibleLabelMax = Math.max(visibleLabelMax, isX ? bb.bottom : bb.right);
                } else {
                  visibleLabelMax = Infinity;
                }
              }
            }
          });
          for (var subplot in fullLayout._plots) {
            var plotinfo = fullLayout._plots[subplot];
            if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue;
            var anchorAx2 = isX ? plotinfo.yaxis : plotinfo.xaxis;
            if (anchorAx2) {
              anchorAx2["_visibleLabelMin_" + ax._id] = visibleLabelMin;
              anchorAx2["_visibleLabelMax_" + ax._id] = visibleLabelMax;
            }
          }
        };
        ax._hideCounterAxisInsideTickLabels = function(partialOpts) {
          var isX = ax._id.charAt(0) === "x";
          var anchoredAxes = [];
          for (var subplot in fullLayout._plots) {
            var plotinfo = fullLayout._plots[subplot];
            if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue;
            anchoredAxes.push(isX ? plotinfo.yaxis : plotinfo.xaxis);
          }
          anchoredAxes.forEach(function(anchorAx2, idx) {
            if (anchorAx2 && insideTicklabelposition(anchorAx2)) {
              (partialOpts || [
                ZERO_PATH,
                MINORGRID_PATH,
                GRID_PATH,
                TICK_PATH,
                TICK_TEXT
              ]).forEach(function(e) {
                var isPeriodLabel = e.K === "tick" && e.L === "text" && ax.ticklabelmode === "period";
                var mainPlotinfo = fullLayout._plots[ax._mainSubplot];
                var sel;
                if (e.K === ZERO_PATH.K) {
                  var zerolineLayer = zerolineIsAbove ? mainPlotinfo.zerolinelayerAbove : mainPlotinfo.zerolinelayer;
                  sel = zerolineLayer.selectAll("." + ax._id + "zl");
                } else if (e.K === MINORGRID_PATH.K) sel = mainPlotinfo.minorGridlayer.selectAll("." + ax._id);
                else if (e.K === GRID_PATH.K) sel = mainPlotinfo.gridlayer.selectAll("." + ax._id);
                else sel = mainPlotinfo[ax._id.charAt(0) + "axislayer"];
                sel.each(function() {
                  var w = d3.select(this);
                  if (e.L) w = w.selectAll(e.L);
                  w.each(function(d) {
                    var q = ax.l2p(
                      isPeriodLabel ? getPosX(d) : d.x
                    ) + ax._offset;
                    var t = d3.select(this);
                    if (q < ax["_visibleLabelMax_" + anchorAx2._id] && q > ax["_visibleLabelMin_" + anchorAx2._id]) {
                      t.style("display", "none");
                    } else if (e.K === "tick" && !idx && t.node().style.display !== "none") {
                      t.style("display", null);
                    }
                  });
                });
              });
            }
          });
        };
        positionLabels(tickLabels, prevAngle + 1 ? prevAngle : tickAngle);
        function allLabelsReady() {
          return labelsReady.length && Promise.all(labelsReady);
        }
        var autoangle = null;
        function fixLabelOverlaps() {
          positionLabels(tickLabels, tickAngle);
          if (vals.length && ax.autotickangles && (ax.type !== "log" || String(ax.dtick).charAt(0) !== "D")) {
            autoangle = ax.autotickangles[0];
            var maxFontSize = 0;
            var lbbArray = [];
            var i;
            var maxLines = 1;
            tickLabels.each(function(d) {
              maxFontSize = Math.max(maxFontSize, d.fontSize);
              var x = ax.l2p(d.x);
              var thisLabel = selectTickLabel(this);
              var bb = Drawing.bBox(thisLabel.node());
              maxLines = Math.max(maxLines, svgTextUtils.lineCount(thisLabel));
              lbbArray.push({
                // ignore about y, just deal with x overlaps
                top: 0,
                bottom: 10,
                height: 10,
                left: x - bb.width / 2,
                // impose a 2px gap
                right: x + bb.width / 2 + 2,
                width: bb.width + 2
              });
            });
            var preventOverlapWithTick = (ax.tickson === "boundaries" || ax.showdividers) && !opts.secondary;
            var vLen = vals.length;
            var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1);
            var adjacent = preventOverlapWithTick ? tickSpacing / 2 : tickSpacing;
            var opposite = preventOverlapWithTick ? ax.ticklen : maxFontSize * 1.25 * maxLines;
            var hypotenuse = Math.sqrt(Math.pow(adjacent, 2) + Math.pow(opposite, 2));
            var maxCos = adjacent / hypotenuse;
            var autoTickAnglesRadians = ax.autotickangles.map(
              function(degrees3) {
                return degrees3 * Math.PI / 180;
              }
            );
            var angleRadians = autoTickAnglesRadians.find(
              function(angle) {
                return Math.abs(Math.cos(angle)) <= maxCos;
              }
            );
            if (angleRadians === void 0) {
              angleRadians = autoTickAnglesRadians.reduce(
                function(currentMax, nextAngle) {
                  return Math.abs(Math.cos(currentMax)) < Math.abs(Math.cos(nextAngle)) ? currentMax : nextAngle;
                },
                autoTickAnglesRadians[0]
              );
            }
            var newAngle = angleRadians * (180 / Math.PI);
            if (preventOverlapWithTick) {
              var gap = 2;
              if (ax.ticks) gap += ax.tickwidth / 2;
              for (i = 0; i < lbbArray.length; i++) {
                var xbnd = vals[i].xbnd;
                var lbb = lbbArray[i];
                if (xbnd[0] !== null && lbb.left - ax.l2p(xbnd[0]) < gap || xbnd[1] !== null && ax.l2p(xbnd[1]) - lbb.right < gap) {
                  autoangle = newAngle;
                  break;
                }
              }
            } else {
              var ticklabelposition = ax.ticklabelposition || "";
              var tickson = ax.tickson || "";
              var has = function(str) {
                return ticklabelposition.indexOf(str) !== -1;
              };
              var isTop = has("top");
              var isLeft = has("left");
              var isRight = has("right");
              var isBottom = has("bottom");
              var isAligned = tickson !== "boundaries" && (isBottom || isLeft || isTop || isRight);
              var pad = !isAligned ? 0 : (ax.tickwidth || 0) + 2 * TEXTPAD;
              for (i = 0; i < lbbArray.length - 1; i++) {
                if (Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1], pad)) {
                  autoangle = newAngle;
                  break;
                }
              }
            }
            if (autoangle) {
              positionLabels(tickLabels, autoangle);
            }
          }
        }
        if (ax._selections) {
          ax._selections[cls] = tickLabels;
        }
        var seq = [allLabelsReady];
        if (ax.automargin && fullLayout._redrawFromAutoMarginCount && prevAngle === 90) {
          autoangle = prevAngle;
          seq.push(function() {
            positionLabels(tickLabels, prevAngle);
          });
        } else {
          seq.push(fixLabelOverlaps);
        }
        if (ax._tickAngles) {
          seq.push(function() {
            ax._tickAngles[cls] = autoangle === null ? isNumeric(tickAngle) ? tickAngle : 0 : autoangle;
          });
        }
        var computeTickLabelBoundingBoxes = function() {
          var labelsMaxW = 0;
          var labelsMaxH = 0;
          tickLabels.each(function(d, i) {
            var thisLabel = selectTickLabel(this);
            var mathjaxGroup = thisLabel.select(".text-math-group");
            if (mathjaxGroup.empty()) {
              var bb;
              if (ax._vals[i]) {
                bb = ax._vals[i].bb || Drawing.bBox(thisLabel.node());
                ax._vals[i].bb = bb;
              }
              labelsMaxW = Math.max(labelsMaxW, bb.width);
              labelsMaxH = Math.max(labelsMaxH, bb.height);
            }
          });
          return {
            labelsMaxW,
            labelsMaxH
          };
        };
        var anchorAx = ax._anchorAxis;
        if (anchorAx && (anchorAx.autorange || anchorAx.insiderange) && insideTicklabelposition(ax) && !isLinked(fullLayout, ax._id)) {
          if (!fullLayout._insideTickLabelsUpdaterange) {
            fullLayout._insideTickLabelsUpdaterange = {};
          }
          if (anchorAx.autorange) {
            fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".autorange"] = anchorAx.autorange;
            seq.push(computeTickLabelBoundingBoxes);
          }
          if (anchorAx.insiderange) {
            var BBs = computeTickLabelBoundingBoxes();
            var move = ax._id.charAt(0) === "y" ? BBs.labelsMaxW : BBs.labelsMaxH;
            move += 2 * TEXTPAD;
            if (ax.ticklabelposition === "inside") {
              move += ax.ticklen || 0;
            }
            var sgn = ax.side === "right" || ax.side === "top" ? 1 : -1;
            var index = sgn === 1 ? 1 : 0;
            var otherIndex = sgn === 1 ? 0 : 1;
            var newRange = [];
            newRange[otherIndex] = anchorAx.range[otherIndex];
            var anchorAxRange = anchorAx.range;
            var p0 = anchorAx.r2p(anchorAxRange[index]);
            var p1 = anchorAx.r2p(anchorAxRange[otherIndex]);
            var _tempNewRange = fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".range"];
            if (_tempNewRange) {
              var q0 = anchorAx.r2p(_tempNewRange[index]);
              var q1 = anchorAx.r2p(_tempNewRange[otherIndex]);
              var dir = sgn * (ax._id.charAt(0) === "y" ? 1 : -1);
              if (dir * p0 < dir * q0) {
                p0 = q0;
                newRange[index] = anchorAxRange[index] = _tempNewRange[index];
              }
              if (dir * p1 > dir * q1) {
                p1 = q1;
                newRange[otherIndex] = anchorAxRange[otherIndex] = _tempNewRange[otherIndex];
              }
            }
            var dist = Math.abs(p1 - p0);
            if (dist - move > 0) {
              dist -= move;
              move *= 1 + move / dist;
            } else {
              move = 0;
            }
            if (ax._id.charAt(0) !== "y") move = -move;
            newRange[index] = anchorAx.p2r(
              anchorAx.r2p(anchorAxRange[index]) + sgn * move
            );
            if (anchorAx.autorange === "min" || anchorAx.autorange === "max reversed") {
              newRange[0] = null;
              anchorAx._rangeInitial0 = void 0;
              anchorAx._rangeInitial1 = void 0;
            } else if (anchorAx.autorange === "max" || anchorAx.autorange === "min reversed") {
              newRange[1] = null;
              anchorAx._rangeInitial0 = void 0;
              anchorAx._rangeInitial1 = void 0;
            }
            fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".range"] = newRange;
          }
        }
        var done = Lib.syncOrAsync(seq);
        if (done && done.then) gd._promises.push(done);
        return done;
      };
      function drawDividers(gd, ax, opts) {
        var cls = ax._id + "divider";
        var vals = opts.vals;
        var dividers = opts.layer.selectAll("path." + cls).data(vals, tickDataFn);
        dividers.exit().remove();
        dividers.enter().insert("path", ":first-child").classed(cls, 1).classed("crisp", 1).call(Color2.stroke, ax.dividercolor).style("stroke-width", Drawing.crispRound(gd, ax.dividerwidth, 1) + "px");
        dividers.attr("transform", opts.transFn).attr("d", opts.path);
      }
      axes.getPxPosition = function(gd, ax) {
        var gs = gd._fullLayout._size;
        var axLetter = ax._id.charAt(0);
        var side = ax.side;
        var anchorAxis;
        if (ax.anchor !== "free") {
          anchorAxis = ax._anchorAxis;
        } else if (axLetter === "x") {
          anchorAxis = {
            _offset: gs.t + (1 - (ax.position || 0)) * gs.h,
            _length: 0
          };
        } else if (axLetter === "y") {
          anchorAxis = {
            _offset: gs.l + (ax.position || 0) * gs.w + ax._shift,
            _length: 0
          };
        }
        if (side === "top" || side === "left") {
          return anchorAxis._offset;
        } else if (side === "bottom" || side === "right") {
          return anchorAxis._offset + anchorAxis._length;
        }
      };
      function approxTitleDepth(ax) {
        var fontSize = ax.title.font.size;
        var extraLines = (ax.title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
        if (ax.title.hasOwnProperty("standoff")) {
          return fontSize * (CAP_SHIFT + extraLines * LINE_SPACING);
        } else {
          return extraLines ? fontSize * (extraLines + 1) * LINE_SPACING : fontSize;
        }
      }
      function drawTitle(gd, ax) {
        var fullLayout = gd._fullLayout;
        var axId = ax._id;
        var axLetter = axId.charAt(0);
        var fontSize = ax.title.font.size;
        var titleStandoff;
        var extraLines = (ax.title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
        if (ax.title.hasOwnProperty("standoff")) {
          if (ax.side === "bottom" || ax.side === "right") {
            titleStandoff = ax._depth + ax.title.standoff + fontSize * CAP_SHIFT;
          } else if (ax.side === "top" || ax.side === "left") {
            titleStandoff = ax._depth + ax.title.standoff + fontSize * (MID_SHIFT + extraLines * LINE_SPACING);
          }
        } else {
          var isInside = insideTicklabelposition(ax);
          if (ax.type === "multicategory") {
            titleStandoff = ax._depth;
          } else {
            var offsetBase = 1.5 * fontSize;
            if (isInside) {
              offsetBase = 0.5 * fontSize;
              if (ax.ticks === "outside") {
                offsetBase += ax.ticklen;
              }
            }
            titleStandoff = 10 + offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0);
          }
          if (!isInside) {
            if (axLetter === "x") {
              titleStandoff += ax.side === "top" ? fontSize * (ax.showticklabels ? 1 : 0) : fontSize * (ax.showticklabels ? 1.5 : 0.5);
            } else {
              titleStandoff += ax.side === "right" ? fontSize * (ax.showticklabels ? 1 : 0.5) : fontSize * (ax.showticklabels ? 0.5 : 0);
            }
          }
        }
        var pos = axes.getPxPosition(gd, ax);
        var transform, x, y;
        if (axLetter === "x") {
          x = ax._offset + ax._length / 2;
          y = ax.side === "top" ? pos - titleStandoff : pos + titleStandoff;
        } else {
          y = ax._offset + ax._length / 2;
          x = ax.side === "right" ? pos + titleStandoff : pos - titleStandoff;
          transform = { rotate: "-90", offset: 0 };
        }
        var avoid;
        if (ax.type !== "multicategory") {
          var tickLabels = ax._selections[ax._id + "tick"];
          avoid = {
            selection: tickLabels,
            side: ax.side
          };
          if (tickLabels && tickLabels.node() && tickLabels.node().parentNode) {
            var translation = Drawing.getTranslate(tickLabels.node().parentNode);
            avoid.offsetLeft = translation.x;
            avoid.offsetTop = translation.y;
          }
          if (ax.title.hasOwnProperty("standoff")) {
            avoid.pad = 0;
          }
        }
        ax._titleStandoff = titleStandoff;
        return Titles.draw(gd, axId + "title", {
          propContainer: ax,
          propName: ax._name + ".title.text",
          placeholder: fullLayout._dfltTitle[axLetter],
          avoid,
          transform,
          attributes: { x, y, "text-anchor": "middle" }
        });
      }
      axes.shouldShowZeroLine = function(gd, ax, counterAxis) {
        var rng = Lib.simpleMap(ax.range, ax.r2l);
        return rng[0] * rng[1] <= 0 && ax.zeroline && (ax.type === "linear" || ax.type === "-") && !(ax.rangebreaks && ax.maskBreaks(0) === BADNUM) && (clipEnds(ax, 0) || !anyCounterAxLineAtZero(gd, ax, counterAxis, rng) || hasBarsOrFill(gd, ax));
      };
      axes.clipEnds = function(ax, vals) {
        return vals.filter(function(d) {
          return clipEnds(ax, d.x);
        });
      };
      function clipEnds(ax, l) {
        var p = ax.l2p(l);
        return p > 1 && p < ax._length - 1;
      }
      function anyCounterAxLineAtZero(gd, ax, counterAxis, rng) {
        var mainCounterAxis = counterAxis._mainAxis;
        if (!mainCounterAxis) return;
        var fullLayout = gd._fullLayout;
        var axLetter = ax._id.charAt(0);
        var counterLetter = axes.counterLetter(ax._id);
        var zeroPosition = ax._offset + (Math.abs(rng[0]) < Math.abs(rng[1]) === (axLetter === "x") ? 0 : ax._length);
        function lineNearZero(ax2) {
          if (!ax2.showline || !ax2.linewidth) return false;
          var tolerance = Math.max((ax2.linewidth + ax.zerolinewidth) / 2, 1);
          function closeEnough(pos2) {
            return typeof pos2 === "number" && Math.abs(pos2 - zeroPosition) < tolerance;
          }
          if (closeEnough(ax2._mainLinePosition) || closeEnough(ax2._mainMirrorPosition)) {
            return true;
          }
          var linePositions = ax2._linepositions || {};
          for (var k in linePositions) {
            if (closeEnough(linePositions[k][0]) || closeEnough(linePositions[k][1])) {
              return true;
            }
          }
        }
        var plotinfo = fullLayout._plots[counterAxis._mainSubplot];
        if (!(plotinfo.mainplotinfo || plotinfo).overlays.length) {
          return lineNearZero(counterAxis, zeroPosition);
        }
        var counterLetterAxes = axes.list(gd, counterLetter);
        for (var i = 0; i < counterLetterAxes.length; i++) {
          var counterAxis2 = counterLetterAxes[i];
          if (counterAxis2._mainAxis === mainCounterAxis && lineNearZero(counterAxis2, zeroPosition)) {
            return true;
          }
        }
      }
      function hasBarsOrFill(gd, ax) {
        var fullData = gd._fullData;
        var subplot = ax._mainSubplot;
        var axLetter = ax._id.charAt(0);
        for (var i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          if (trace.visible === true && trace.xaxis + trace.yaxis === subplot) {
            if (Registry.traceIs(trace, "bar-like") && trace.orientation === { x: "h", y: "v" }[axLetter]) return true;
            if (trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter) return true;
          }
        }
        return false;
      }
      function selectTickLabel(gTick) {
        var s = d3.select(gTick);
        var mj = s.select(".text-math-group");
        return mj.empty() ? s.select("text") : mj;
      }
      axes.allowAutoMargin = function(gd) {
        var axList = axes.list(gd, "", true);
        for (var i = 0; i < axList.length; i++) {
          var ax = axList[i];
          if (ax.automargin) {
            Plots.allowAutoMargin(gd, axAutoMarginID(ax));
            if (ax.mirror) {
              Plots.allowAutoMargin(gd, axMirrorAutoMarginID(ax));
            }
          }
          if (Registry.getComponentMethod("rangeslider", "isVisible")(ax)) {
            Plots.allowAutoMargin(gd, rangeSliderAutoMarginID(ax));
          }
        }
      };
      function axAutoMarginID(ax) {
        return ax._id + ".automargin";
      }
      function axMirrorAutoMarginID(ax) {
        return axAutoMarginID(ax) + ".mirror";
      }
      function rangeSliderAutoMarginID(ax) {
        return ax._id + ".rangeslider";
      }
      axes.swap = function(gd, traces) {
        var axGroups = makeAxisGroups(gd, traces);
        for (var i = 0; i < axGroups.length; i++) {
          swapAxisGroup(gd, axGroups[i].x, axGroups[i].y);
        }
      };
      function makeAxisGroups(gd, traces) {
        var groups = [];
        var i, j;
        for (i = 0; i < traces.length; i++) {
          var groupsi = [];
          var xi = gd._fullData[traces[i]].xaxis;
          var yi = gd._fullData[traces[i]].yaxis;
          if (!xi || !yi) continue;
          for (j = 0; j < groups.length; j++) {
            if (groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) {
              groupsi.push(j);
            }
          }
          if (!groupsi.length) {
            groups.push({ x: [xi], y: [yi] });
            continue;
          }
          var group0 = groups[groupsi[0]];
          var groupj;
          if (groupsi.length > 1) {
            for (j = 1; j < groupsi.length; j++) {
              groupj = groups[groupsi[j]];
              mergeAxisGroups(group0.x, groupj.x);
              mergeAxisGroups(group0.y, groupj.y);
            }
          }
          mergeAxisGroups(group0.x, [xi]);
          mergeAxisGroups(group0.y, [yi]);
        }
        return groups;
      }
      function mergeAxisGroups(intoSet, fromSet) {
        for (var i = 0; i < fromSet.length; i++) {
          if (intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]);
        }
      }
      function swapAxisGroup(gd, xIds, yIds) {
        var xFullAxes = [];
        var yFullAxes = [];
        var layout = gd.layout;
        var i, j;
        for (i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i]));
        for (i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i]));
        var allAxKeys = Object.keys(axAttrs);
        var noSwapAttrs = [
          "anchor",
          "domain",
          "overlaying",
          "position",
          "side",
          "tickangle",
          "editType"
        ];
        var numericTypes = ["linear", "log"];
        for (i = 0; i < allAxKeys.length; i++) {
          var keyi = allAxKeys[i];
          var xVal = xFullAxes[0][keyi];
          var yVal = yFullAxes[0][keyi];
          var allEqual = true;
          var coerceLinearX = false;
          var coerceLinearY = false;
          if (keyi.charAt(0) === "_" || typeof xVal === "function" || noSwapAttrs.indexOf(keyi) !== -1) {
            continue;
          }
          for (j = 1; j < xFullAxes.length && allEqual; j++) {
            var xVali = xFullAxes[j][keyi];
            if (keyi === "type" && numericTypes.indexOf(xVal) !== -1 && numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) {
              coerceLinearX = true;
            } else if (xVali !== xVal) allEqual = false;
          }
          for (j = 1; j < yFullAxes.length && allEqual; j++) {
            var yVali = yFullAxes[j][keyi];
            if (keyi === "type" && numericTypes.indexOf(yVal) !== -1 && numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) {
              coerceLinearY = true;
            } else if (yFullAxes[j][keyi] !== yVal) allEqual = false;
          }
          if (allEqual) {
            if (coerceLinearX) layout[xFullAxes[0]._name].type = "linear";
            if (coerceLinearY) layout[yFullAxes[0]._name].type = "linear";
            swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle);
          }
        }
        for (i = 0; i < gd._fullLayout.annotations.length; i++) {
          var ann = gd._fullLayout.annotations[i];
          if (xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) {
            Lib.swapAttrs(layout.annotations[i], ["?"]);
          }
        }
      }
      function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) {
        var np = Lib.nestedProperty;
        var xVal = np(layout[xFullAxes[0]._name], key).get();
        var yVal = np(layout[yFullAxes[0]._name], key).get();
        var i;
        if (key === "title") {
          if (xVal && xVal.text === dfltTitle.x) {
            xVal.text = dfltTitle.y;
          }
          if (yVal && yVal.text === dfltTitle.y) {
            yVal.text = dfltTitle.x;
          }
        }
        for (i = 0; i < xFullAxes.length; i++) {
          np(layout, xFullAxes[i]._name + "." + key).set(yVal);
        }
        for (i = 0; i < yFullAxes.length; i++) {
          np(layout, yFullAxes[i]._name + "." + key).set(xVal);
        }
      }
      function isAngular(ax) {
        return ax._id === "angularaxis";
      }
      function moveOutsideBreak(v, ax) {
        var len = ax._rangebreaks.length;
        for (var k = 0; k < len; k++) {
          var brk = ax._rangebreaks[k];
          if (v >= brk.min && v < brk.max) {
            return brk.max;
          }
        }
        return v;
      }
      function insideTicklabelposition(ax) {
        return (ax.ticklabelposition || "").indexOf("inside") !== -1;
      }
      function hideCounterAxisInsideTickLabels(ax, opts) {
        if (insideTicklabelposition(ax._anchorAxis || {})) {
          if (ax._hideCounterAxisInsideTickLabels) {
            ax._hideCounterAxisInsideTickLabels(opts);
          }
        }
      }
      function incrementShift(ax, shiftVal, axShifts, normalize) {
        var overlay = ax.anchor !== "free" && (ax.overlaying === void 0 || ax.overlaying === false) ? ax._id : ax.overlaying;
        var shiftValAdj;
        if (normalize) {
          shiftValAdj = ax.side === "right" ? shiftVal : -shiftVal;
        } else {
          shiftValAdj = shiftVal;
        }
        if (!(overlay in axShifts)) {
          axShifts[overlay] = {};
        }
        if (!(ax.side in axShifts[overlay])) {
          axShifts[overlay][ax.side] = 0;
        }
        axShifts[overlay][ax.side] += shiftValAdj;
      }
      function setShiftVal(ax, axShifts) {
        return ax.autoshift ? axShifts[ax.overlaying][ax.side] : ax.shift || 0;
      }
      function periodCompatibleWithTickformat(period, tickformat) {
        return /%f/.test(tickformat) ? period >= ONEMICROSEC : /%L/.test(tickformat) ? period >= ONEMILLI : /%[SX]/.test(tickformat) ? period >= ONESEC : /%M/.test(tickformat) ? period >= ONEMIN : /%[HI]/.test(tickformat) ? period >= ONEHOUR : /%p/.test(tickformat) ? period >= HALFDAY : /%[Aadejuwx]/.test(tickformat) ? period >= ONEDAY : /%[UVW]/.test(tickformat) ? period >= ONEWEEK : /%[Bbm]/.test(tickformat) ? period >= ONEMINMONTH : /%[q]/.test(tickformat) ? period >= ONEMINQUARTER : /%[Yy]/.test(tickformat) ? period >= ONEMINYEAR : true;
      }
    }
  });

  // src/plots/cartesian/autorange_options_defaults.js
  var require_autorange_options_defaults = __commonJS({
    "src/plots/cartesian/autorange_options_defaults.js"(exports, module) {
      "use strict";
      module.exports = function handleAutorangeOptionsDefaults(coerce, autorange, range) {
        var minRange, maxRange;
        if (range) {
          var isReversed = autorange === "reversed" || autorange === "min reversed" || autorange === "max reversed";
          minRange = range[isReversed ? 1 : 0];
          maxRange = range[isReversed ? 0 : 1];
        }
        var minallowed = coerce("autorangeoptions.minallowed", maxRange === null ? minRange : void 0);
        var maxallowed = coerce("autorangeoptions.maxallowed", minRange === null ? maxRange : void 0);
        if (minallowed === void 0) coerce("autorangeoptions.clipmin");
        if (maxallowed === void 0) coerce("autorangeoptions.clipmax");
        coerce("autorangeoptions.include");
      };
    }
  });

  // src/plots/cartesian/range_defaults.js
  var require_range_defaults = __commonJS({
    "src/plots/cartesian/range_defaults.js"(exports, module) {
      "use strict";
      var handleAutorangeOptionsDefaults = require_autorange_options_defaults();
      module.exports = function handleRangeDefaults(containerIn, containerOut, coerce, options) {
        var axTemplate = containerOut._template || {};
        var axType = containerOut.type || axTemplate.type || "-";
        coerce("minallowed");
        coerce("maxallowed");
        var range = coerce("range");
        if (!range) {
          var insiderange;
          if (!options.noInsiderange && axType !== "log") {
            insiderange = coerce("insiderange");
            if (insiderange && (insiderange[0] === null || insiderange[1] === null)) {
              containerOut.insiderange = false;
              insiderange = void 0;
            }
            if (insiderange) range = coerce("range", insiderange);
          }
        }
        var autorangeDflt = containerOut.getAutorangeDflt(range, options);
        var autorange = coerce("autorange", autorangeDflt);
        var shouldAutorange;
        if (range && (range[0] === null && range[1] === null || (range[0] === null || range[1] === null) && (autorange === "reversed" || autorange === true) || range[0] !== null && (autorange === "min" || autorange === "max reversed") || range[1] !== null && (autorange === "max" || autorange === "min reversed"))) {
          range = void 0;
          delete containerOut.range;
          containerOut.autorange = true;
          shouldAutorange = true;
        }
        if (!shouldAutorange) {
          autorangeDflt = containerOut.getAutorangeDflt(range, options);
          autorange = coerce("autorange", autorangeDflt);
        }
        if (autorange) {
          handleAutorangeOptionsDefaults(coerce, autorange, range);
          if (axType === "linear" || axType === "-") coerce("rangemode");
        }
        containerOut.cleanRange();
      };
    }
  });

  // node_modules/mouse-event-offset/index.js
  var require_mouse_event_offset = __commonJS({
    "node_modules/mouse-event-offset/index.js"(exports, module) {
      var rootPosition = { left: 0, top: 0 };
      module.exports = mouseEventOffset;
      function mouseEventOffset(ev, target, out) {
        target = target || ev.currentTarget || ev.srcElement;
        if (!Array.isArray(out)) {
          out = [0, 0];
        }
        var cx = ev.clientX || 0;
        var cy = ev.clientY || 0;
        var rect = getBoundingClientOffset(target);
        out[0] = cx - rect.left;
        out[1] = cy - rect.top;
        return out;
      }
      function getBoundingClientOffset(element) {
        if (element === window || element === document || element === document.body) {
          return rootPosition;
        } else {
          return element.getBoundingClientRect();
        }
      }
    }
  });

  // node_modules/has-passive-events/index.js
  var require_has_passive_events = __commonJS({
    "node_modules/has-passive-events/index.js"(exports, module) {
      "use strict";
      var isBrowser = require_client();
      function detect() {
        var supported = false;
        try {
          var opts = Object.defineProperty({}, "passive", {
            get: function() {
              supported = true;
            }
          });
          window.addEventListener("test", null, opts);
          window.removeEventListener("test", null, opts);
        } catch (e) {
          supported = false;
        }
        return supported;
      }
      module.exports = isBrowser && detect();
    }
  });

  // src/components/dragelement/align.js
  var require_align = __commonJS({
    "src/components/dragelement/align.js"(exports, module) {
      "use strict";
      module.exports = function align(v, dv, v0, v1, anchor) {
        var vmin = (v - v0) / (v1 - v0);
        var vmax = vmin + dv / (v1 - v0);
        var vc = (vmin + vmax) / 2;
        if (anchor === "left" || anchor === "bottom") return vmin;
        if (anchor === "center" || anchor === "middle") return vc;
        if (anchor === "right" || anchor === "top") return vmax;
        if (vmin < 2 / 3 - vc) return vmin;
        if (vmax > 4 / 3 - vc) return vmax;
        return vc;
      };
    }
  });

  // src/components/dragelement/cursor.js
  var require_cursor = __commonJS({
    "src/components/dragelement/cursor.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var cursorset = [
        ["sw-resize", "s-resize", "se-resize"],
        ["w-resize", "move", "e-resize"],
        ["nw-resize", "n-resize", "ne-resize"]
      ];
      module.exports = function getCursor(x, y, xanchor, yanchor) {
        if (xanchor === "left") x = 0;
        else if (xanchor === "center") x = 1;
        else if (xanchor === "right") x = 2;
        else x = Lib.constrain(Math.floor(x * 3), 0, 2);
        if (yanchor === "bottom") y = 0;
        else if (yanchor === "middle") y = 1;
        else if (yanchor === "top") y = 2;
        else y = Lib.constrain(Math.floor(y * 3), 0, 2);
        return cursorset[y][x];
      };
    }
  });

  // src/components/dragelement/unhover.js
  var require_unhover = __commonJS({
    "src/components/dragelement/unhover.js"(exports, module) {
      "use strict";
      var Events = require_events2();
      var throttle = require_throttle();
      var getGraphDiv = require_dom().getGraphDiv;
      var hoverConstants = require_constants();
      var unhover = module.exports = {};
      unhover.wrapped = function(gd, evt, subplot) {
        gd = getGraphDiv(gd);
        if (gd._fullLayout) {
          throttle.clear(gd._fullLayout._uid + hoverConstants.HOVERID);
        }
        unhover.raw(gd, evt, subplot);
      };
      unhover.raw = function raw(gd, evt) {
        var fullLayout = gd._fullLayout;
        var oldhoverdata = gd._hoverdata;
        if (!evt) evt = {};
        if (evt.target && !gd._dragged && Events.triggerHandler(gd, "plotly_beforehover", evt) === false) {
          return;
        }
        fullLayout._hoverlayer.selectAll("g").remove();
        fullLayout._hoverlayer.selectAll("line").remove();
        fullLayout._hoverlayer.selectAll("circle").remove();
        gd._hoverdata = void 0;
        if (evt.target && oldhoverdata) {
          gd.emit("plotly_unhover", {
            event: evt,
            points: oldhoverdata
          });
        }
      };
    }
  });

  // src/components/dragelement/index.js
  var require_dragelement = __commonJS({
    "src/components/dragelement/index.js"(exports, module) {
      "use strict";
      var mouseOffset = require_mouse_event_offset();
      var hasHover = require_has_hover();
      var supportsPassive = require_has_passive_events();
      var removeElement = require_lib().removeElement;
      var constants = require_constants2();
      var dragElement = module.exports = {};
      dragElement.align = require_align();
      dragElement.getCursor = require_cursor();
      var unhover = require_unhover();
      dragElement.unhover = unhover.wrapped;
      dragElement.unhoverRaw = unhover.raw;
      dragElement.init = function init(options) {
        var gd = options.gd;
        var numClicks = 1;
        var doubleClickDelay = gd._context.doubleClickDelay;
        var element = options.element;
        var startX, startY, newMouseDownTime, cursor, dragCover, initialEvent, initialTarget, rightClick;
        if (!gd._mouseDownTime) gd._mouseDownTime = 0;
        element.style.pointerEvents = "all";
        element.onmousedown = onStart;
        if (!supportsPassive) {
          element.ontouchstart = onStart;
        } else {
          if (element._ontouchstart) {
            element.removeEventListener("touchstart", element._ontouchstart);
          }
          element._ontouchstart = onStart;
          element.addEventListener("touchstart", onStart, { passive: false });
        }
        function _clampFn(dx, dy, minDrag) {
          if (Math.abs(dx) < minDrag) dx = 0;
          if (Math.abs(dy) < minDrag) dy = 0;
          return [dx, dy];
        }
        var clampFn = options.clampFn || _clampFn;
        function onStart(e) {
          gd._dragged = false;
          gd._dragging = true;
          var offset = pointerOffset(e);
          startX = offset[0];
          startY = offset[1];
          initialTarget = e.target;
          initialEvent = e;
          rightClick = e.buttons === 2 || e.ctrlKey;
          if (typeof e.clientX === "undefined" && typeof e.clientY === "undefined") {
            e.clientX = startX;
            e.clientY = startY;
          }
          newMouseDownTime = (/* @__PURE__ */ new Date()).getTime();
          if (newMouseDownTime - gd._mouseDownTime < doubleClickDelay) {
            numClicks += 1;
          } else {
            numClicks = 1;
            gd._mouseDownTime = newMouseDownTime;
          }
          if (options.prepFn) options.prepFn(e, startX, startY);
          if (hasHover && !rightClick) {
            dragCover = coverSlip();
            dragCover.style.cursor = window.getComputedStyle(element).cursor;
          } else if (!hasHover) {
            dragCover = document;
            cursor = window.getComputedStyle(document.documentElement).cursor;
            document.documentElement.style.cursor = window.getComputedStyle(element).cursor;
          }
          document.addEventListener("mouseup", onDone);
          document.addEventListener("touchend", onDone);
          if (options.dragmode !== false) {
            e.preventDefault();
            document.addEventListener("mousemove", onMove);
            document.addEventListener("touchmove", onMove, { passive: false });
          }
          return;
        }
        function onMove(e) {
          e.preventDefault();
          var offset = pointerOffset(e);
          var minDrag = options.minDrag || constants.MINDRAG;
          var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag);
          var dx = dxdy[0];
          var dy = dxdy[1];
          if (dx || dy) {
            gd._dragged = true;
            dragElement.unhover(gd, e);
          }
          if (gd._dragged && options.moveFn && !rightClick) {
            gd._dragdata = {
              element,
              dx,
              dy
            };
            options.moveFn(dx, dy);
          }
          return;
        }
        function onDone(e) {
          delete gd._dragdata;
          if (options.dragmode !== false) {
            e.preventDefault();
            document.removeEventListener("mousemove", onMove);
            document.removeEventListener("touchmove", onMove);
          }
          document.removeEventListener("mouseup", onDone);
          document.removeEventListener("touchend", onDone);
          if (hasHover) {
            removeElement(dragCover);
          } else if (cursor) {
            dragCover.documentElement.style.cursor = cursor;
            cursor = null;
          }
          if (!gd._dragging) {
            gd._dragged = false;
            return;
          }
          gd._dragging = false;
          if ((/* @__PURE__ */ new Date()).getTime() - gd._mouseDownTime > doubleClickDelay) {
            numClicks = Math.max(numClicks - 1, 1);
          }
          if (gd._dragged) {
            if (options.doneFn) options.doneFn();
          } else {
            var clickEvent;
            if (initialEvent.target === initialTarget) {
              clickEvent = initialEvent;
            } else {
              clickEvent = {
                target: initialTarget,
                srcElement: initialTarget,
                toElement: initialTarget
              };
              Object.keys(initialEvent).concat(Object.keys(initialEvent.__proto__)).forEach((k) => {
                var v = initialEvent[k];
                if (!clickEvent[k] && typeof v !== "function") {
                  clickEvent[k] = v;
                }
              });
            }
            if (options.clickFn) options.clickFn(numClicks, clickEvent);
            if (!rightClick) {
              initialTarget.dispatchEvent(new MouseEvent("click", e));
            }
          }
          gd._dragging = false;
          gd._dragged = false;
          return;
        }
      };
      function coverSlip() {
        var cover = document.createElement("div");
        cover.className = "dragcover";
        var cStyle = cover.style;
        cStyle.position = "fixed";
        cStyle.left = 0;
        cStyle.right = 0;
        cStyle.top = 0;
        cStyle.bottom = 0;
        cStyle.zIndex = 999999999;
        cStyle.background = "none";
        document.body.appendChild(cover);
        return cover;
      }
      dragElement.coverSlip = coverSlip;
      function pointerOffset(e) {
        return mouseOffset(
          e.changedTouches ? e.changedTouches[0] : e,
          document.body
        );
      }
    }
  });

  // src/lib/setcursor.js
  var require_setcursor = __commonJS({
    "src/lib/setcursor.js"(exports, module) {
      "use strict";
      module.exports = function setCursor(el3, csr) {
        (el3.attr("class") || "").split(" ").forEach(function(cls) {
          if (cls.indexOf("cursor-") === 0) el3.classed(cls, false);
        });
        if (csr) el3.classed("cursor-" + csr, true);
      };
    }
  });

  // src/lib/override_cursor.js
  var require_override_cursor = __commonJS({
    "src/lib/override_cursor.js"(exports, module) {
      "use strict";
      var setCursor = require_setcursor();
      var STASHATTR = "data-savedcursor";
      var NO_CURSOR = "!!";
      module.exports = function overrideCursor(el3, csr) {
        var savedCursor = el3.attr(STASHATTR);
        if (csr) {
          if (!savedCursor) {
            var classes = (el3.attr("class") || "").split(" ");
            for (var i = 0; i < classes.length; i++) {
              var cls = classes[i];
              if (cls.indexOf("cursor-") === 0) {
                el3.attr(STASHATTR, cls.slice(7)).classed(cls, false);
              }
            }
            if (!el3.attr(STASHATTR)) {
              el3.attr(STASHATTR, NO_CURSOR);
            }
          }
          setCursor(el3, csr);
        } else if (savedCursor) {
          el3.attr(STASHATTR, null);
          if (savedCursor === NO_CURSOR) setCursor(el3);
          else setCursor(el3, savedCursor);
        }
      };
    }
  });

  // src/components/legend/attributes.js
  var require_attributes9 = __commonJS({
    "src/components/legend/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var colorAttrs = require_attributes3();
      module.exports = {
        // not really a 'subplot' attribute container,
        // but this is the flag we use to denote attributes that
        // support yaxis, yaxis2, yaxis3, ... counters
        _isSubplotObj: true,
        visible: {
          valType: "boolean",
          dflt: true,
          editType: "legend"
        },
        bgcolor: {
          valType: "color",
          editType: "legend"
        },
        bordercolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "legend"
        },
        maxheight: {
          valType: "number",
          min: 0,
          editType: "legend"
        },
        borderwidth: {
          valType: "number",
          min: 0,
          dflt: 0,
          editType: "legend"
        },
        font: fontAttrs({
          editType: "legend"
        }),
        grouptitlefont: fontAttrs({
          editType: "legend"
        }),
        orientation: {
          valType: "enumerated",
          values: ["v", "h"],
          dflt: "v",
          editType: "legend"
        },
        traceorder: {
          valType: "flaglist",
          flags: ["reversed", "grouped"],
          extras: ["normal"],
          editType: "legend"
        },
        tracegroupgap: {
          valType: "number",
          min: 0,
          dflt: 10,
          editType: "legend"
        },
        entrywidth: {
          valType: "number",
          min: 0,
          editType: "legend"
        },
        entrywidthmode: {
          valType: "enumerated",
          values: ["fraction", "pixels"],
          dflt: "pixels",
          editType: "legend"
        },
        indentation: {
          valType: "number",
          min: -15,
          dflt: 0,
          editType: "legend"
        },
        itemsizing: {
          valType: "enumerated",
          values: ["trace", "constant"],
          dflt: "trace",
          editType: "legend"
        },
        itemwidth: {
          valType: "number",
          min: 30,
          dflt: 30,
          editType: "legend"
        },
        itemclick: {
          valType: "enumerated",
          values: ["toggle", "toggleothers", false],
          dflt: "toggle",
          editType: "legend"
        },
        itemdoubleclick: {
          valType: "enumerated",
          values: ["toggle", "toggleothers", false],
          dflt: "toggleothers",
          editType: "legend"
        },
        groupclick: {
          valType: "enumerated",
          values: ["toggleitem", "togglegroup"],
          dflt: "togglegroup",
          editType: "legend"
        },
        titleclick: {
          valType: "enumerated",
          values: ["toggle", "toggleothers", false],
          editType: "legend"
        },
        titledoubleclick: {
          valType: "enumerated",
          values: ["toggle", "toggleothers", false],
          editType: "legend"
        },
        x: {
          valType: "number",
          editType: "legend"
        },
        xref: {
          valType: "enumerated",
          dflt: "paper",
          values: ["container", "paper"],
          editType: "layoutstyle"
        },
        xanchor: {
          valType: "enumerated",
          values: ["auto", "left", "center", "right"],
          dflt: "left",
          editType: "legend"
        },
        y: {
          valType: "number",
          editType: "legend"
        },
        yref: {
          valType: "enumerated",
          dflt: "paper",
          values: ["container", "paper"],
          editType: "layoutstyle"
        },
        yanchor: {
          valType: "enumerated",
          values: ["auto", "top", "middle", "bottom"],
          editType: "legend"
        },
        uirevision: {
          valType: "any",
          editType: "none"
        },
        valign: {
          valType: "enumerated",
          values: ["top", "middle", "bottom"],
          dflt: "middle",
          editType: "legend"
        },
        title: {
          text: {
            valType: "string",
            dflt: "",
            editType: "legend"
          },
          font: fontAttrs({
            editType: "legend"
          }),
          side: {
            valType: "enumerated",
            values: ["top", "left", "top left", "top center", "top right"],
            editType: "legend"
          },
          editType: "legend"
        },
        editType: "legend"
      };
    }
  });

  // src/components/legend/helpers.js
  var require_helpers3 = __commonJS({
    "src/components/legend/helpers.js"(exports) {
      "use strict";
      exports.isGrouped = function isGrouped(legendLayout) {
        return (legendLayout.traceorder || "").indexOf("grouped") !== -1;
      };
      exports.isVertical = function isVertical(legendLayout) {
        return legendLayout.orientation !== "h";
      };
      exports.isReversed = function isReversed(legendLayout) {
        return (legendLayout.traceorder || "").indexOf("reversed") !== -1;
      };
      exports.getId = function getId(legendObj) {
        return legendObj._id || "legend";
      };
    }
  });

  // src/components/legend/defaults.js
  var require_defaults3 = __commonJS({
    "src/components/legend/defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var Template = require_plot_template();
      var plotsAttrs = require_attributes2();
      var attributes = require_attributes9();
      var basePlotLayoutAttributes = require_layout_attributes2();
      var helpers = require_helpers3();
      function groupDefaults(legendId, layoutIn, layoutOut, fullData, legendCount) {
        var containerIn = layoutIn[legendId] || {};
        var containerOut = Template.newContainer(layoutOut, legendId);
        function coerce(attr, dflt) {
          return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
        }
        var itemFont = Lib.coerceFont(coerce, "font", layoutOut.font);
        coerce("bgcolor", layoutOut.paper_bgcolor);
        coerce("bordercolor");
        var visible = coerce("visible");
        if (!visible) return;
        var trace;
        var traceCoerce = function(attr, dflt) {
          var traceIn = trace._input;
          var traceOut = trace;
          return Lib.coerce(traceIn, traceOut, plotsAttrs, attr, dflt);
        };
        var globalFont = layoutOut.font || {};
        var grouptitlefont = Lib.coerceFont(coerce, "grouptitlefont", globalFont, {
          overrideDflt: {
            size: Math.round(globalFont.size * 1.1)
          }
        });
        var legendTraceCount = 0;
        var legendReallyHasATrace = false;
        var defaultOrder = "normal";
        var shapesWithLegend = (layoutOut.shapes || []).filter(function(d) {
          return d.showlegend;
        });
        function isPieWithLegendArray(trace2) {
          return Registry.traceIs(trace2, "pie-like") && trace2._length != null && (Array.isArray(trace2.legend) || Array.isArray(trace2.showlegend));
        }
        ;
        fullData.filter(isPieWithLegendArray).forEach(function(trace2) {
          if (trace2.visible) {
            legendTraceCount++;
          }
          for (var index = 0; index < trace2._length; index++) {
            var legend = (Array.isArray(trace2.legend) ? trace2.legend[index] : trace2.legend) || "legend";
            if (legend === legendId) {
              const showInLegend = Array.isArray(trace2.showlegend) ? trace2.showlegend[index] : trace2.showlegend;
              if (showInLegend || trace2._dfltShowLegend) {
                legendReallyHasATrace = true;
                legendTraceCount++;
              }
            }
          }
          if (legendId === "legend" && trace2._length > trace2.legend.length) {
            for (var idx = trace2.legend.length; idx < trace2._length; idx++) {
              legendReallyHasATrace = true;
              legendTraceCount++;
            }
          }
        });
        var allLegendItems = fullData.concat(shapesWithLegend).filter(function(d) {
          return !isPieWithLegendArray(trace) && legendId === (d.legend || "legend");
        });
        for (var i = 0; i < allLegendItems.length; i++) {
          trace = allLegendItems[i];
          if (!trace.visible) continue;
          var isShape = trace._isShape;
          if (trace.showlegend || trace._dfltShowLegend && !(trace._module && trace._module.attributes && trace._module.attributes.showlegend && trace._module.attributes.showlegend.dflt === false)) {
            legendTraceCount++;
            if (trace.showlegend) {
              legendReallyHasATrace = true;
              if (!isShape && Registry.traceIs(trace, "pie-like") || trace._input.showlegend === true) {
                legendTraceCount++;
              }
            }
            Lib.coerceFont(traceCoerce, "legendgrouptitle.font", grouptitlefont);
          }
          if (!isShape && Registry.traceIs(trace, "bar") && layoutOut.barmode === "stack" || ["tonextx", "tonexty"].indexOf(trace.fill) !== -1) {
            defaultOrder = helpers.isGrouped({ traceorder: defaultOrder }) ? "grouped+reversed" : "reversed";
          }
          if (trace.legendgroup !== void 0 && trace.legendgroup !== "") {
            defaultOrder = helpers.isReversed({ traceorder: defaultOrder }) ? "reversed+grouped" : "grouped";
          }
        }
        var showLegend = Lib.coerce(
          layoutIn,
          layoutOut,
          basePlotLayoutAttributes,
          "showlegend",
          layoutOut.showlegend || legendReallyHasATrace && legendTraceCount > (legendId === "legend" ? 1 : 0)
        );
        if (showLegend === false) layoutOut[legendId] = void 0;
        if (showLegend === false && !containerIn.uirevision) return;
        coerce("uirevision", layoutOut.uirevision);
        if (showLegend === false) return;
        coerce("borderwidth");
        var orientation = coerce("orientation");
        var yref = coerce("yref");
        var xref = coerce("xref");
        var isHorizontal = orientation === "h";
        var isPaperY = yref === "paper";
        var isPaperX = xref === "paper";
        var defaultX, defaultY, defaultYAnchor;
        var defaultXAnchor = "left";
        if (isHorizontal) {
          defaultX = 0;
          if (Registry.getComponentMethod("rangeslider", "isVisible")(layoutIn.xaxis)) {
            if (isPaperY) {
              defaultY = 1.1;
              defaultYAnchor = "bottom";
            } else {
              defaultY = 1;
              defaultYAnchor = "top";
            }
          } else {
            if (isPaperY) {
              defaultY = -0.1;
              defaultYAnchor = "top";
            } else {
              defaultY = 0;
              defaultYAnchor = "bottom";
            }
          }
        } else {
          defaultY = 1;
          defaultYAnchor = "auto";
          if (isPaperX) {
            defaultX = 1.02;
          } else {
            defaultX = 1;
            defaultXAnchor = "right";
          }
        }
        Lib.coerce(containerIn, containerOut, {
          x: {
            valType: "number",
            editType: "legend",
            min: isPaperX ? -2 : 0,
            max: isPaperX ? 3 : 1,
            dflt: defaultX
          }
        }, "x");
        Lib.coerce(containerIn, containerOut, {
          y: {
            valType: "number",
            editType: "legend",
            min: isPaperY ? -2 : 0,
            max: isPaperY ? 3 : 1,
            dflt: defaultY
          }
        }, "y");
        coerce("traceorder", defaultOrder);
        if (helpers.isGrouped(layoutOut[legendId])) coerce("tracegroupgap");
        coerce("entrywidth");
        coerce("entrywidthmode");
        coerce("indentation");
        coerce("itemsizing");
        coerce("itemwidth");
        coerce("itemclick");
        coerce("itemdoubleclick");
        coerce("groupclick");
        coerce("xanchor", defaultXAnchor);
        coerce("yanchor", defaultYAnchor);
        coerce("maxheight");
        coerce("valign");
        Lib.noneOrAll(containerIn, containerOut, ["x", "y"]);
        var titleText = coerce("title.text");
        if (titleText) {
          coerce("title.side", isHorizontal ? "left" : "top");
          var dfltTitleFont = Lib.extendFlat({}, itemFont, {
            size: Lib.bigFont(itemFont.size)
          });
          Lib.coerceFont(coerce, "title.font", dfltTitleFont);
          const hasMultipleLegends = legendCount > 1;
          coerce("titleclick", hasMultipleLegends ? "toggle" : false);
          coerce("titledoubleclick", hasMultipleLegends ? "toggleothers" : false);
        }
      }
      module.exports = function legendDefaults(layoutIn, layoutOut, fullData) {
        var i;
        var allLegendsData = fullData.slice();
        var shapes = layoutOut.shapes;
        if (shapes) {
          for (i = 0; i < shapes.length; i++) {
            var shape = shapes[i];
            if (!shape.showlegend) continue;
            var mockTrace = {
              _input: shape._input,
              visible: shape.visible,
              showlegend: shape.showlegend,
              legend: shape.legend
            };
            allLegendsData.push(mockTrace);
          }
        }
        var legends = ["legend"];
        for (i = 0; i < allLegendsData.length; i++) {
          if (Array.isArray(allLegendsData[i].legend)) {
            legends = legends.concat(allLegendsData[i].legend);
          } else {
            Lib.pushUnique(legends, allLegendsData[i].legend);
          }
        }
        layoutOut._legends = [];
        for (i = 0; i < legends.length; i++) {
          var legendId = legends[i];
          groupDefaults(legendId, layoutIn, layoutOut, allLegendsData, legends.length);
          if (layoutOut[legendId]) {
            layoutOut[legendId]._id = legendId;
          }
          layoutOut._legends.push(legendId);
        }
      };
    }
  });

  // src/components/legend/handle_click.js
  var require_handle_click = __commonJS({
    "src/components/legend/handle_click.js"(exports) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var pushUnique = Lib.pushUnique;
      var helpers = require_helpers3();
      var SHOWISOLATETIP = true;
      exports.handleItemClick = function handleItemClick(g, gd, legendObj, mode) {
        var fullLayout = gd._fullLayout;
        if (gd._dragged || gd._editing) return;
        var legendItem = g.data()[0][0];
        if (legendItem.groupTitle && legendItem.noClick) return;
        var groupClick = legendObj.groupclick;
        if (mode === "toggle" && legendObj.itemdoubleclick === "toggleothers" && SHOWISOLATETIP && gd.data && gd._context.showTips) {
          Lib.notifier(Lib._(gd, "Double-click on legend to isolate one trace"), "long");
          SHOWISOLATETIP = false;
        }
        var toggleGroup = groupClick === "togglegroup";
        var hiddenSlices = fullLayout.hiddenlabels ? fullLayout.hiddenlabels.slice() : [];
        var fullData = gd._fullData;
        var shapesWithLegend = (fullLayout.shapes || []).filter(function(d2) {
          return d2.showlegend;
        });
        var allLegendItems = fullData.concat(shapesWithLegend);
        var fullTrace = legendItem.trace;
        if (fullTrace._isShape) {
          fullTrace = fullTrace._fullInput;
        }
        var legendgroup = fullTrace.legendgroup;
        var i, j, kcont, key, keys, val;
        var dataUpdate = {};
        var dataIndices = [];
        var carrs = [];
        var carrIdx = [];
        function insertDataUpdate(traceIndex, value) {
          var attrIndex = dataIndices.indexOf(traceIndex);
          var valueArray = dataUpdate.visible;
          if (!valueArray) {
            valueArray = dataUpdate.visible = [];
          }
          if (dataIndices.indexOf(traceIndex) === -1) {
            dataIndices.push(traceIndex);
            attrIndex = dataIndices.length - 1;
          }
          valueArray[attrIndex] = value;
          return attrIndex;
        }
        var updatedShapes = (fullLayout.shapes || []).map(function(d2) {
          return d2._input;
        });
        var shapesUpdated = false;
        function insertShapesUpdate(shapeIndex, value) {
          updatedShapes[shapeIndex].visible = value;
          shapesUpdated = true;
        }
        function setVisibility(fullTrace2, visibility) {
          if (legendItem.groupTitle && !toggleGroup) return;
          var fullInput2 = fullTrace2._fullInput || fullTrace2;
          var isShape2 = fullInput2._isShape;
          var index = fullInput2.index;
          if (index === void 0) index = fullInput2._index;
          var nextVisibility2 = fullInput2.visible === false ? false : visibility;
          if (isShape2) {
            insertShapesUpdate(index, nextVisibility2);
          } else {
            insertDataUpdate(index, nextVisibility2);
          }
        }
        var thisLegend = fullTrace.legend;
        var fullInput = fullTrace._fullInput;
        var isShape = fullInput && fullInput._isShape;
        if (!isShape && Registry.traceIs(fullTrace, "pie-like")) {
          var thisLabel = legendItem.label;
          var thisLabelIndex = hiddenSlices.indexOf(thisLabel);
          if (mode === "toggle") {
            if (thisLabelIndex === -1) hiddenSlices.push(thisLabel);
            else hiddenSlices.splice(thisLabelIndex, 1);
          } else if (mode === "toggleothers") {
            var changed = thisLabelIndex !== -1;
            var unhideList = [];
            for (i = 0; i < gd.calcdata.length; i++) {
              var cdi = gd.calcdata[i];
              for (j = 0; j < cdi.length; j++) {
                var d = cdi[j];
                var dLabel = d.label;
                if (thisLegend === cdi[0].trace.legend) {
                  if (thisLabel !== dLabel) {
                    if (hiddenSlices.indexOf(dLabel) === -1) changed = true;
                    pushUnique(hiddenSlices, dLabel);
                    unhideList.push(dLabel);
                  }
                }
              }
            }
            if (!changed) {
              for (var q = 0; q < unhideList.length; q++) {
                var pos = hiddenSlices.indexOf(unhideList[q]);
                if (pos !== -1) {
                  hiddenSlices.splice(pos, 1);
                }
              }
            }
          }
          Registry.call("_guiRelayout", gd, "hiddenlabels", hiddenSlices);
        } else {
          var hasLegendgroup = legendgroup && legendgroup.length;
          var traceIndicesInGroup = [];
          var tracei;
          if (hasLegendgroup) {
            for (i = 0; i < allLegendItems.length; i++) {
              tracei = allLegendItems[i];
              if (!tracei.visible) continue;
              if (tracei.legendgroup === legendgroup) {
                traceIndicesInGroup.push(i);
              }
            }
          }
          if (mode === "toggle") {
            var nextVisibility;
            switch (fullTrace.visible) {
              case true:
                nextVisibility = "legendonly";
                break;
              case false:
                nextVisibility = false;
                break;
              case "legendonly":
                nextVisibility = true;
                break;
            }
            if (hasLegendgroup) {
              if (toggleGroup) {
                for (i = 0; i < allLegendItems.length; i++) {
                  var item = allLegendItems[i];
                  if (item.visible !== false && item.legendgroup === legendgroup) {
                    setVisibility(item, nextVisibility);
                  }
                }
              } else {
                setVisibility(fullTrace, nextVisibility);
              }
            } else {
              setVisibility(fullTrace, nextVisibility);
            }
          } else if (mode === "toggleothers") {
            var isClicked, isInGroup, notInLegend, otherState, _item;
            var isIsolated = true;
            for (i = 0; i < allLegendItems.length; i++) {
              _item = allLegendItems[i];
              isClicked = _item === fullTrace;
              notInLegend = _item.showlegend !== true;
              if (isClicked || notInLegend) continue;
              isInGroup = hasLegendgroup && _item.legendgroup === legendgroup;
              if (!isInGroup && _item.legend === thisLegend && _item.visible === true && !Registry.traceIs(_item, "notLegendIsolatable")) {
                isIsolated = false;
                break;
              }
            }
            for (i = 0; i < allLegendItems.length; i++) {
              _item = allLegendItems[i];
              if (_item.visible === false || _item.legend !== thisLegend) continue;
              if (Registry.traceIs(_item, "notLegendIsolatable")) {
                continue;
              }
              switch (fullTrace.visible) {
                case "legendonly":
                  setVisibility(_item, true);
                  break;
                case true:
                  otherState = isIsolated ? true : "legendonly";
                  isClicked = _item === fullTrace;
                  notInLegend = _item.showlegend !== true && !_item.legendgroup;
                  isInGroup = isClicked || hasLegendgroup && _item.legendgroup === legendgroup;
                  setVisibility(_item, isInGroup || notInLegend ? true : otherState);
                  break;
              }
            }
          }
          for (i = 0; i < carrs.length; i++) {
            kcont = carrs[i];
            if (!kcont) continue;
            var update = kcont.constructUpdate();
            var updateKeys = Object.keys(update);
            for (j = 0; j < updateKeys.length; j++) {
              key = updateKeys[j];
              val = dataUpdate[key] = dataUpdate[key] || [];
              val[carrIdx[i]] = update[key];
            }
          }
          keys = Object.keys(dataUpdate);
          for (i = 0; i < keys.length; i++) {
            key = keys[i];
            for (j = 0; j < dataIndices.length; j++) {
              if (!dataUpdate[key].hasOwnProperty(j)) {
                dataUpdate[key][j] = void 0;
              }
            }
          }
          if (shapesUpdated) {
            Registry.call("_guiUpdate", gd, dataUpdate, { shapes: updatedShapes }, dataIndices);
          } else {
            Registry.call("_guiRestyle", gd, dataUpdate, dataIndices);
          }
        }
      };
      exports.handleTitleClick = function handleTitleClick(gd, legendObj, mode) {
        const fullLayout = gd._fullLayout;
        const fullData = gd._fullData;
        const legendId = helpers.getId(legendObj);
        const shapesWithLegend = (fullLayout.shapes || []).filter(function(d) {
          return d.showlegend;
        });
        const allLegendItems = fullData.concat(shapesWithLegend);
        function isInLegend(item) {
          return (item.legend || "legend") === legendId;
        }
        var toggleThisLegend;
        var toggleOtherLegends;
        if (mode === "toggle") {
          const anyVisibleHere = allLegendItems.some(function(item) {
            return isInLegend(item) && item.visible === true;
          });
          toggleThisLegend = !anyVisibleHere;
          toggleOtherLegends = false;
        } else {
          const anyVisibleElsewhere = allLegendItems.some(function(item) {
            return !isInLegend(item) && item.visible === true && item.showlegend !== false;
          });
          toggleThisLegend = true;
          toggleOtherLegends = !anyVisibleElsewhere;
        }
        const dataUpdate = { visible: [] };
        const dataIndices = [];
        const updatedShapes = (fullLayout.shapes || []).map(function(d) {
          return d._input;
        });
        var shapesUpdated = false;
        for (var i = 0; i < allLegendItems.length; i++) {
          const item = allLegendItems[i];
          const inThisLegend = isInLegend(item);
          if (!inThisLegend) {
            const notDisplayed = item.showlegend !== true && !item.legendgroup;
            if (mode === "toggle" || notDisplayed) continue;
          }
          const shouldShow = inThisLegend ? toggleThisLegend : toggleOtherLegends;
          const newVis = shouldShow ? true : "legendonly";
          if (item.visible !== false && item.visible !== newVis) {
            if (item._isShape) {
              updatedShapes[item._index].visible = newVis;
              shapesUpdated = true;
            } else {
              dataIndices.push(item.index);
              dataUpdate.visible.push(newVis);
            }
          }
        }
        if (shapesUpdated) {
          Registry.call("_guiUpdate", gd, dataUpdate, { shapes: updatedShapes }, dataIndices);
        } else if (dataIndices.length) {
          Registry.call("_guiRestyle", gd, dataUpdate, dataIndices);
        }
      };
    }
  });

  // src/components/legend/constants.js
  var require_constants3 = __commonJS({
    "src/components/legend/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        scrollBarWidth: 6,
        scrollBarMinHeight: 20,
        scrollBarColor: "#808BA4",
        scrollBarMargin: 4,
        scrollBarEnterAttrs: { rx: 20, ry: 3, width: 0, height: 0 },
        // number of px between legend title and (left) side of legend (always in x direction and from inner border)
        titlePad: 2,
        // number of px between each legend item (x and/or y direction)
        itemGap: 5
      };
    }
  });

  // src/components/legend/get_legend_data.js
  var require_get_legend_data = __commonJS({
    "src/components/legend/get_legend_data.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var helpers = require_helpers3();
      module.exports = function getLegendData(calcdata, opts, hasMultipleLegends) {
        var inHover = opts._inHover;
        var grouped = helpers.isGrouped(opts);
        var reversed = helpers.isReversed(opts);
        var lgroupToTraces = {};
        var lgroups = [];
        var hasOneNonBlankGroup = false;
        var slicesShown = {};
        var lgroupi = 0;
        var maxNameLength = 0;
        var i, j;
        function addOneItem(legendId, legendGroup, legendItem) {
          if (opts.visible === false) return;
          if (hasMultipleLegends && legendId !== opts._id) return;
          if (legendGroup === "" || !helpers.isGrouped(opts)) {
            var uniqueGroup = "~~i" + lgroupi;
            lgroups.push(uniqueGroup);
            lgroupToTraces[uniqueGroup] = [legendItem];
            lgroupi++;
          } else if (lgroups.indexOf(legendGroup) === -1) {
            lgroups.push(legendGroup);
            hasOneNonBlankGroup = true;
            lgroupToTraces[legendGroup] = [legendItem];
          } else {
            lgroupToTraces[legendGroup].push(legendItem);
          }
        }
        for (i = 0; i < calcdata.length; i++) {
          var cd = calcdata[i];
          var cd0 = cd[0];
          var trace = cd0.trace;
          var lid = trace.legend;
          var lgroup = trace.legendgroup;
          if (!inHover && (!trace.visible || !trace.showlegend)) continue;
          if (Registry.traceIs(trace, "pie-like")) {
            var legendPerSlice = Array.isArray(trace.legend);
            var showlegendPerSlice = Array.isArray(trace.showlegend);
            if (!slicesShown[lgroup]) slicesShown[lgroup] = {};
            for (j = 0; j < cd.length; j++) {
              if (showlegendPerSlice && trace.showlegend[cd[j].i] === false) {
                continue;
              }
              if (legendPerSlice) {
                lid = trace.legend[cd[j].i] || "legend";
              }
              var labelj = cd[j].label;
              if (!slicesShown[lgroup][labelj]) {
                addOneItem(lid, lgroup, {
                  label: labelj,
                  color: cd[j].color,
                  i: cd[j].i,
                  trace,
                  pts: cd[j].pts
                });
                slicesShown[lgroup][labelj] = true;
                maxNameLength = Math.max(maxNameLength, (labelj || "").length);
              }
            }
          } else {
            addOneItem(lid, lgroup, cd0);
            maxNameLength = Math.max(maxNameLength, (trace.name || "").length);
          }
        }
        if (!lgroups.length) return [];
        var shouldCollapse = !hasOneNonBlankGroup || !grouped;
        var legendData = [];
        for (i = 0; i < lgroups.length; i++) {
          var t = lgroupToTraces[lgroups[i]];
          if (shouldCollapse) {
            legendData.push(t[0]);
          } else {
            legendData.push(t);
          }
        }
        if (shouldCollapse) legendData = [legendData];
        for (i = 0; i < legendData.length; i++) {
          var groupMinRank = Infinity;
          for (j = 0; j < legendData[i].length; j++) {
            var rank = legendData[i][j].trace.legendrank;
            if (groupMinRank > rank) groupMinRank = rank;
          }
          legendData[i][0]._groupMinRank = groupMinRank;
          legendData[i][0]._preGroupSort = i;
        }
        var orderFn1 = function(a, b) {
          return a[0]._groupMinRank - b[0]._groupMinRank || a[0]._preGroupSort - b[0]._preGroupSort;
        };
        var orderFn2 = function(a, b) {
          return a.trace.legendrank - b.trace.legendrank || a._preSort - b._preSort;
        };
        legendData.forEach(function(a, k) {
          a[0]._preGroupSort = k;
        });
        legendData.sort(orderFn1);
        for (i = 0; i < legendData.length; i++) {
          legendData[i].forEach(function(a, k) {
            a._preSort = k;
          });
          legendData[i].sort(orderFn2);
          var firstItemTrace = legendData[i][0].trace;
          var groupTitle = null;
          for (j = 0; j < legendData[i].length; j++) {
            var gt = legendData[i][j].trace.legendgrouptitle;
            if (gt && gt.text) {
              groupTitle = gt;
              if (inHover) gt.font = opts._groupTitleFont;
              break;
            }
          }
          if (reversed) legendData[i].reverse();
          if (groupTitle) {
            var hasPieLike = false;
            for (j = 0; j < legendData[i].length; j++) {
              if (Registry.traceIs(legendData[i][j].trace, "pie-like")) {
                hasPieLike = true;
                break;
              }
            }
            legendData[i].unshift({
              i: -1,
              groupTitle,
              noClick: hasPieLike,
              trace: {
                showlegend: firstItemTrace.showlegend,
                legendgroup: firstItemTrace.legendgroup,
                legend: firstItemTrace.legend,
                visible: opts.groupclick === "toggleitem" ? true : firstItemTrace.visible
              }
            });
          }
          for (j = 0; j < legendData[i].length; j++) {
            legendData[i][j] = [
              legendData[i][j]
            ];
          }
        }
        opts._lgroupsLength = legendData.length;
        opts._maxNameLength = maxNameLength;
        return legendData;
      };
    }
  });

  // src/traces/pie/helpers.js
  var require_helpers4 = __commonJS({
    "src/traces/pie/helpers.js"(exports) {
      "use strict";
      var Lib = require_lib();
      function format(vRounded) {
        return vRounded.indexOf("e") !== -1 ? vRounded.replace(/[.]?0+e/, "e") : vRounded.indexOf(".") !== -1 ? vRounded.replace(/[.]?0+$/, "") : vRounded;
      }
      exports.formatPiePercent = function formatPiePercent(v, separators) {
        var vRounded = format((v * 100).toPrecision(3));
        return Lib.numSeparate(vRounded, separators) + "%";
      };
      exports.formatPieValue = function formatPieValue(v, separators) {
        var vRounded = format(v.toPrecision(10));
        return Lib.numSeparate(vRounded, separators);
      };
      exports.getFirstFilled = function getFirstFilled(array, indices) {
        if (!Lib.isArrayOrTypedArray(array)) return;
        for (var i = 0; i < indices.length; i++) {
          var v = array[indices[i]];
          if (v || v === 0 || v === "") return v;
        }
      };
      exports.castOption = function castOption(item, indices) {
        if (Lib.isArrayOrTypedArray(item)) return exports.getFirstFilled(item, indices);
        else if (item) return item;
      };
      exports.getRotationAngle = function(rotation) {
        return (rotation === "auto" ? 0 : rotation) * Math.PI / 180;
      };
    }
  });

  // src/traces/pie/fill_one.js
  var require_fill_one = __commonJS({
    "src/traces/pie/fill_one.js"(exports, module) {
      "use strict";
      var Drawing = require_drawing();
      var Color2 = require_color();
      module.exports = function fillOne(s, pt, trace, gd) {
        var pattern = trace.marker.pattern;
        if (pattern && pattern.shape) {
          Drawing.pointStyle(s, trace, gd, pt);
        } else {
          Color2.fill(s, pt.color);
        }
      };
    }
  });

  // src/traces/pie/style_one.js
  var require_style_one = __commonJS({
    "src/traces/pie/style_one.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var castOption = require_helpers4().castOption;
      var fillOne = require_fill_one();
      module.exports = function styleOne(s, pt, trace, gd) {
        var line = trace.marker.line;
        var lineColor = castOption(line.color, pt.pts) || Color2.defaultLine;
        var lineWidth = castOption(line.width, pt.pts) || 0;
        s.call(fillOne, pt, trace, gd).style("stroke-width", lineWidth).call(Color2.stroke, lineColor);
      };
    }
  });

  // src/components/legend/style.js
  var require_style = __commonJS({
    "src/components/legend/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var Drawing = require_drawing();
      var Color2 = require_color();
      var extractOpts = require_helpers().extractOpts;
      var subTypes = require_subtypes();
      var stylePie = require_style_one();
      var pieCastOption = require_helpers4().castOption;
      var constants = require_constants3();
      var CST_MARKER_SIZE = 12;
      var CST_LINE_WIDTH = 5;
      var CST_MARKER_LINE_WIDTH = 2;
      var MAX_LINE_WIDTH = 10;
      var MAX_MARKER_LINE_WIDTH = 5;
      module.exports = function style(s, gd, legend) {
        var fullLayout = gd._fullLayout;
        if (!legend) legend = fullLayout.legend;
        var constantItemSizing = legend.itemsizing === "constant";
        var itemWidth = legend.itemwidth;
        var centerPos = (itemWidth + constants.itemGap * 2) / 2;
        var centerTransform = strTranslate(centerPos, 0);
        var boundLineWidth = function(mlw, cont, max, cst) {
          var v;
          if (mlw + 1) {
            v = mlw;
          } else if (cont && cont.width > 0) {
            v = cont.width;
          } else {
            return 0;
          }
          return constantItemSizing ? cst : Math.min(v, max);
        };
        s.each(function(d) {
          var traceGroup = d3.select(this);
          var layers = Lib.ensureSingle(traceGroup, "g", "layers");
          layers.style("opacity", d[0].trace.opacity);
          var indentation = legend.indentation;
          var valign = legend.valign;
          var lineHeight = d[0].lineHeight;
          var height = d[0].height;
          if (valign === "middle" && indentation === 0 || !lineHeight || !height) {
            layers.attr("transform", null);
          } else {
            var factor = { top: 1, bottom: -1 }[valign];
            var markerOffsetY = factor * (0.5 * (lineHeight - height + 3)) || 0;
            var markerOffsetX = legend.indentation;
            layers.attr("transform", strTranslate(markerOffsetX, markerOffsetY));
          }
          var fill = layers.selectAll("g.legendfill").data([d]);
          fill.enter().append("g").classed("legendfill", true);
          var line = layers.selectAll("g.legendlines").data([d]);
          line.enter().append("g").classed("legendlines", true);
          var symbol = layers.selectAll("g.legendsymbols").data([d]);
          symbol.enter().append("g").classed("legendsymbols", true);
          symbol.selectAll("g.legendpoints").data([d]).enter().append("g").classed("legendpoints", true);
        }).each(styleSpatial).each(styleWaterfalls).each(styleFunnels).each(styleBars).each(styleBoxes).each(styleFunnelareas).each(stylePies).each(styleLines).each(stylePoints).each(styleCandles).each(styleOHLC);
        function styleLines(d) {
          var styleGuide = getStyleGuide(d);
          var showFill = styleGuide.showFill;
          var showLine = styleGuide.showLine;
          var showGradientLine = styleGuide.showGradientLine;
          var showGradientFill = styleGuide.showGradientFill;
          var anyFill = styleGuide.anyFill;
          var anyLine = styleGuide.anyLine;
          var d0 = d[0];
          var trace = d0.trace;
          var dMod, tMod;
          var cOpts = extractOpts(trace);
          var colorscale = cOpts.colorscale;
          var reversescale = cOpts.reversescale;
          var fillStyle = function(s2) {
            if (s2.size()) {
              if (showFill) {
                Drawing.fillGroupStyle(s2, gd, true);
              } else {
                var gradientID = "legendfill-" + trace.uid;
                Drawing.gradient(s2, gd, gradientID, getGradientDirection(reversescale), colorscale, "fill");
              }
            }
          };
          var lineGradient = function(s2) {
            if (s2.size()) {
              var gradientID = "legendline-" + trace.uid;
              Drawing.lineGroupStyle(s2);
              Drawing.gradient(s2, gd, gradientID, getGradientDirection(reversescale), colorscale, "stroke");
            }
          };
          var pathStart = subTypes.hasMarkers(trace) || !anyFill ? "M5,0" : (
            // with a line leave it slightly below center, to leave room for the
            // line thickness and because the line is usually more prominent
            anyLine ? "M5,-2" : "M5,-3"
          );
          var this3 = d3.select(this);
          var fill = this3.select(".legendfill").selectAll("path").data(showFill || showGradientFill ? [d] : []);
          fill.enter().append("path").classed("js-fill", true);
          fill.exit().remove();
          fill.attr("d", pathStart + "h" + itemWidth + "v6h-" + itemWidth + "z").call(fillStyle);
          if (showLine || showGradientLine) {
            var lw = boundLineWidth(void 0, trace.line, MAX_LINE_WIDTH, CST_LINE_WIDTH);
            tMod = Lib.minExtend(trace, { line: { width: lw } });
            dMod = [Lib.minExtend(d0, { trace: tMod })];
          }
          var line = this3.select(".legendlines").selectAll("path").data(showLine || showGradientLine ? [dMod] : []);
          line.enter().append("path").classed("js-line", true);
          line.exit().remove();
          line.attr("d", pathStart + (showGradientLine ? "l" + itemWidth + ",0.0001" : "h" + itemWidth)).call(
            showLine ? Drawing.lineGroupStyle : lineGradient
          );
        }
        function stylePoints(d) {
          var styleGuide = getStyleGuide(d);
          var anyFill = styleGuide.anyFill;
          var anyLine = styleGuide.anyLine;
          var showLine = styleGuide.showLine;
          var showMarker = styleGuide.showMarker;
          var d0 = d[0];
          var trace = d0.trace;
          var showText = !showMarker && !anyLine && !anyFill && subTypes.hasText(trace);
          var dMod, tMod;
          function boundVal(attrIn, arrayToValFn, bounds, cst) {
            var valIn = Lib.nestedProperty(trace, attrIn).get();
            var valToBound = Lib.isArrayOrTypedArray(valIn) && arrayToValFn ? arrayToValFn(valIn) : valIn;
            if (constantItemSizing && valToBound && cst !== void 0) {
              valToBound = cst;
            }
            if (bounds) {
              if (valToBound < bounds[0]) return bounds[0];
              else if (valToBound > bounds[1]) return bounds[1];
            }
            return valToBound;
          }
          function pickFirst(array) {
            if (d0._distinct && d0.index && array[d0.index]) return array[d0.index];
            return array[0];
          }
          if (showMarker || showText || showLine) {
            var dEdit = {};
            var tEdit = {};
            if (showMarker) {
              dEdit.mc = boundVal("marker.color", pickFirst);
              dEdit.mx = boundVal("marker.symbol", pickFirst);
              dEdit.mo = boundVal("marker.opacity", Lib.mean, [0.2, 1]);
              dEdit.mlc = boundVal("marker.line.color", pickFirst);
              dEdit.mlw = boundVal("marker.line.width", Lib.mean, [0, 5], CST_MARKER_LINE_WIDTH);
              dEdit.mld = trace._isShape ? "solid" : boundVal("marker.line.dash", pickFirst);
              tEdit.marker = {
                sizeref: 1,
                sizemin: 1,
                sizemode: "diameter"
              };
              var ms = boundVal("marker.size", Lib.mean, [2, 16], CST_MARKER_SIZE);
              dEdit.ms = ms;
              tEdit.marker.size = ms;
            }
            if (showLine) {
              tEdit.line = {
                width: boundVal("line.width", pickFirst, [0, 10], CST_LINE_WIDTH)
              };
            }
            if (showText) {
              dEdit.tx = "Aa";
              dEdit.tp = boundVal("textposition", pickFirst);
              dEdit.ts = 10;
              dEdit.tc = boundVal("textfont.color", pickFirst);
              dEdit.tf = boundVal("textfont.family", pickFirst);
              dEdit.tw = boundVal("textfont.weight", pickFirst);
              dEdit.ty = boundVal("textfont.style", pickFirst);
              dEdit.tv = boundVal("textfont.variant", pickFirst);
              dEdit.tC = boundVal("textfont.textcase", pickFirst);
              dEdit.tE = boundVal("textfont.lineposition", pickFirst);
              dEdit.tS = boundVal("textfont.shadow", pickFirst);
            }
            dMod = [Lib.minExtend(d0, dEdit)];
            tMod = Lib.minExtend(trace, tEdit);
            tMod.selectedpoints = null;
            tMod.texttemplate = null;
          }
          var ptgroup = d3.select(this).select("g.legendpoints");
          var pts = ptgroup.selectAll("path.scatterpts").data(showMarker ? dMod : []);
          pts.enter().insert("path", ":first-child").classed("scatterpts", true).attr("transform", centerTransform);
          pts.exit().remove();
          pts.call(Drawing.pointStyle, tMod, gd);
          if (showMarker) dMod[0].mrc = 3;
          var txt = ptgroup.selectAll("g.pointtext").data(showText ? dMod : []);
          txt.enter().append("g").classed("pointtext", true).append("text").attr("transform", centerTransform);
          txt.exit().remove();
          txt.selectAll("text").call(Drawing.textPointStyle, tMod, gd);
        }
        function styleWaterfalls(d) {
          var trace = d[0].trace;
          var isWaterfall = trace.type === "waterfall";
          if (d[0]._distinct && isWaterfall) {
            var cont = d[0].trace[d[0].dir].marker;
            d[0].mc = cont.color;
            d[0].mlw = cont.line.width;
            d[0].mlc = cont.line.color;
            return styleBarLike(d, this, "waterfall");
          }
          var ptsData = [];
          if (trace.visible && isWaterfall) {
            ptsData = d[0].hasTotals ? [
              ["increasing", "M-6,-6V6H0Z"],
              ["totals", "M6,6H0L-6,-6H-0Z"],
              ["decreasing", "M6,6V-6H0Z"]
            ] : [
              ["increasing", "M-6,-6V6H6Z"],
              ["decreasing", "M6,6V-6H-6Z"]
            ];
          }
          var pts = d3.select(this).select("g.legendpoints").selectAll("path.legendwaterfall").data(ptsData);
          pts.enter().append("path").classed("legendwaterfall", true).attr("transform", centerTransform).style("stroke-miterlimit", 1);
          pts.exit().remove();
          pts.each(function(dd) {
            var pt = d3.select(this);
            var cont2 = trace[dd[0]].marker;
            var lw = boundLineWidth(void 0, cont2.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
            pt.attr("d", dd[1]).style("stroke-width", lw + "px").call(Color2.fill, cont2.color);
            if (lw) {
              pt.call(Color2.stroke, cont2.line.color);
            }
          });
        }
        function styleBars(d) {
          styleBarLike(d, this);
        }
        function styleFunnels(d) {
          styleBarLike(d, this, "funnel");
        }
        function styleBarLike(d, lThis, desiredType) {
          var trace = d[0].trace;
          var marker = trace.marker || {};
          var markerLine = marker.line || {};
          var pathStr = marker.cornerradius ? "M6,3a3,3,0,0,1-3,3H-3a3,3,0,0,1-3-3V-3a3,3,0,0,1,3-3H3a3,3,0,0,1,3,3Z" : (
            // Square with rounded corners
            "M6,6H-6V-6H6Z"
          );
          var isVisible = !desiredType ? Registry.traceIs(trace, "bar") : trace.visible && trace.type === desiredType;
          var barpath = d3.select(lThis).select("g.legendpoints").selectAll("path.legend" + desiredType).data(isVisible ? [d] : []);
          barpath.enter().append("path").classed("legend" + desiredType, true).attr("d", pathStr).attr("transform", centerTransform);
          barpath.exit().remove();
          barpath.each(function(d2) {
            var p = d3.select(this);
            var d0 = d2[0];
            var w = boundLineWidth(d0.mlw, marker.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
            p.style("stroke-width", w + "px");
            var mcc = d0.mcc;
            if (!legend._inHover && "mc" in d0) {
              var cOpts = extractOpts(marker);
              var mid = cOpts.mid;
              if (mid === void 0) mid = (cOpts.max + cOpts.min) / 2;
              mcc = Drawing.tryColorscale(marker, "")(mid);
            }
            var fillColor = mcc || d0.mc || marker.color;
            var markerPattern = marker.pattern;
            var pAttr = Drawing.getPatternAttr;
            var patternShape = markerPattern && (pAttr(markerPattern.shape, 0, "") || pAttr(markerPattern.path, 0, ""));
            if (patternShape) {
              var patternBGColor = pAttr(markerPattern.bgcolor, 0, null);
              var patternFGColor = pAttr(markerPattern.fgcolor, 0, null);
              var patternFGOpacity = markerPattern.fgopacity;
              var patternSize = dimAttr(markerPattern.size, 8, 10);
              var patternSolidity = dimAttr(markerPattern.solidity, 0.5, 1);
              var patternID = "legend-" + trace.uid;
              p.call(
                Drawing.pattern,
                "legend",
                gd,
                patternID,
                patternShape,
                patternSize,
                patternSolidity,
                mcc,
                markerPattern.fillmode,
                patternBGColor,
                patternFGColor,
                patternFGOpacity
              );
            } else {
              p.call(Color2.fill, fillColor);
            }
            if (w) Color2.stroke(p, d0.mlc || markerLine.color);
          });
        }
        function styleBoxes(d) {
          var trace = d[0].trace;
          var pts = d3.select(this).select("g.legendpoints").selectAll("path.legendbox").data(trace.visible && Registry.traceIs(trace, "box-violin") ? [d] : []);
          pts.enter().append("path").classed("legendbox", true).attr("d", "M6,6H-6V-6H6Z").attr("transform", centerTransform);
          pts.exit().remove();
          pts.each(function() {
            var p = d3.select(this);
            if ((trace.boxpoints === "all" || trace.points === "all") && Color2.opacity(trace.fillcolor) === 0 && Color2.opacity((trace.line || {}).color) === 0) {
              var tMod = Lib.minExtend(trace, {
                marker: {
                  size: constantItemSizing ? CST_MARKER_SIZE : Lib.constrain(trace.marker.size, 2, 16),
                  sizeref: 1,
                  sizemin: 1,
                  sizemode: "diameter"
                }
              });
              pts.call(Drawing.pointStyle, tMod, gd);
            } else {
              var w = boundLineWidth(void 0, trace.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
              p.style("stroke-width", w + "px").call(Color2.fill, trace.fillcolor);
              if (w) Color2.stroke(p, trace.line.color);
            }
          });
        }
        function styleCandles(d) {
          var trace = d[0].trace;
          var pts = d3.select(this).select("g.legendpoints").selectAll("path.legendcandle").data(trace.visible && trace.type === "candlestick" ? [d, d] : []);
          pts.enter().append("path").classed("legendcandle", true).attr("d", function(_, i) {
            if (i) return "M-15,0H-8M-8,6V-6H8Z";
            return "M15,0H8M8,-6V6H-8Z";
          }).attr("transform", centerTransform).style("stroke-miterlimit", 1);
          pts.exit().remove();
          pts.each(function(_, i) {
            var p = d3.select(this);
            var cont = trace[i ? "increasing" : "decreasing"];
            var w = boundLineWidth(void 0, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
            p.style("stroke-width", w + "px").call(Color2.fill, cont.fillcolor);
            if (w) Color2.stroke(p, cont.line.color);
          });
        }
        function styleOHLC(d) {
          var trace = d[0].trace;
          var pts = d3.select(this).select("g.legendpoints").selectAll("path.legendohlc").data(trace.visible && trace.type === "ohlc" ? [d, d] : []);
          pts.enter().append("path").classed("legendohlc", true).attr("d", function(_, i) {
            if (i) return "M-15,0H0M-8,-6V0";
            return "M15,0H0M8,6V0";
          }).attr("transform", centerTransform).style("stroke-miterlimit", 1);
          pts.exit().remove();
          pts.each(function(_, i) {
            var p = d3.select(this);
            var cont = trace[i ? "increasing" : "decreasing"];
            var w = boundLineWidth(void 0, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);
            p.style("fill", "none").call(Drawing.dashLine, cont.line.dash, w);
            if (w) Color2.stroke(p, cont.line.color);
          });
        }
        function stylePies(d) {
          stylePieLike(d, this, "pie");
        }
        function styleFunnelareas(d) {
          stylePieLike(d, this, "funnelarea");
        }
        function stylePieLike(d, lThis, desiredType) {
          var d0 = d[0];
          var trace = d0.trace;
          var isVisible = !desiredType ? Registry.traceIs(trace, desiredType) : trace.visible && trace.type === desiredType;
          var pts = d3.select(lThis).select("g.legendpoints").selectAll("path.legend" + desiredType).data(isVisible ? [d] : []);
          pts.enter().append("path").classed("legend" + desiredType, true).attr("d", "M6,6H-6V-6H6Z").attr("transform", centerTransform);
          pts.exit().remove();
          if (pts.size()) {
            var cont = trace.marker || {};
            var lw = boundLineWidth(
              pieCastOption(cont.line.width, d0.pts),
              cont.line,
              MAX_MARKER_LINE_WIDTH,
              CST_MARKER_LINE_WIDTH
            );
            var opt = "pieLike";
            var tMod = Lib.minExtend(trace, { marker: { line: { width: lw } } }, opt);
            var d0Mod = Lib.minExtend(d0, { trace: tMod }, opt);
            stylePie(pts, d0Mod, tMod, gd);
          }
        }
        function styleSpatial(d) {
          var trace = d[0].trace;
          var useGradient;
          var ptsData = [];
          if (trace.visible) {
            switch (trace.type) {
              case "histogram2d":
              case "heatmap":
                ptsData = [
                  ["M-15,-2V4H15V-2Z"]
                  // similar to contour
                ];
                useGradient = true;
                break;
              case "choropleth":
              case "choroplethmapbox":
              case "choroplethmap":
                ptsData = [["M-6,-6V6H6V-6Z"]];
                useGradient = true;
                break;
              case "densitymapbox":
              case "densitymap":
                ptsData = [["M-6,0 a6,6 0 1,0 12,0 a 6,6 0 1,0 -12,0"]];
                useGradient = "radial";
                break;
              case "cone":
                ptsData = [
                  ["M-6,2 A2,2 0 0,0 -6,6 V6L6,4Z"],
                  ["M-6,-6 A2,2 0 0,0 -6,-2 L6,-4Z"],
                  ["M-6,-2 A2,2 0 0,0 -6,2 L6,0Z"]
                ];
                useGradient = false;
                break;
              case "streamtube":
                ptsData = [
                  ["M-6,2 A2,2 0 0,0 -6,6 H6 A2,2 0 0,1 6,2 Z"],
                  ["M-6,-6 A2,2 0 0,0 -6,-2 H6 A2,2 0 0,1 6,-6 Z"],
                  ["M-6,-2 A2,2 0 0,0 -6,2 H6 A2,2 0 0,1 6,-2 Z"]
                ];
                useGradient = false;
                break;
              case "surface":
                ptsData = [
                  ["M-6,-6 A2,3 0 0,0 -6,0 H6 A2,3 0 0,1 6,-6 Z"],
                  ["M-6,1 A2,3 0 0,1 -6,6 H6 A2,3 0 0,0 6,0 Z"]
                ];
                useGradient = true;
                break;
              case "mesh3d":
                ptsData = [["M-6,6H0L-6,-6Z"], ["M6,6H0L6,-6Z"], ["M-6,-6H6L0,6Z"]];
                useGradient = false;
                break;
              case "volume":
                ptsData = [["M-6,6H0L-6,-6Z"], ["M6,6H0L6,-6Z"], ["M-6,-6H6L0,6Z"]];
                useGradient = true;
                break;
              case "isosurface":
                ptsData = [["M-6,6H0L-6,-6Z"], ["M6,6H0L6,-6Z"], ["M-6,-6 A12,24 0 0,0 6,-6 L0,6Z"]];
                useGradient = false;
                break;
            }
          }
          var pts = d3.select(this).select("g.legendpoints").selectAll("path.legend3dandfriends").data(ptsData);
          pts.enter().append("path").classed("legend3dandfriends", true).attr("transform", centerTransform).style("stroke-miterlimit", 1);
          pts.exit().remove();
          pts.each(function(dd, i) {
            var pt = d3.select(this);
            var cOpts = extractOpts(trace);
            var colorscale = cOpts.colorscale;
            var reversescale = cOpts.reversescale;
            var fillGradient = function(s2) {
              if (s2.size()) {
                var gradientID = "legendfill-" + trace.uid;
                Drawing.gradient(
                  s2,
                  gd,
                  gradientID,
                  getGradientDirection(reversescale, useGradient === "radial"),
                  colorscale,
                  "fill"
                );
              }
            };
            var fillColor;
            if (!colorscale) {
              var color2 = trace.vertexcolor || trace.facecolor || trace.color;
              fillColor = Lib.isArrayOrTypedArray(color2) ? color2[i] || color2[0] : color2;
            } else {
              if (!useGradient) {
                var len = colorscale.length;
                fillColor = i === 0 ? colorscale[reversescale ? len - 1 : 0][1] : (
                  // minimum
                  i === 1 ? colorscale[reversescale ? 0 : len - 1][1] : (
                    // maximum
                    colorscale[Math.floor((len - 1) / 2)][1]
                  )
                );
              }
            }
            pt.attr("d", dd[0]);
            if (fillColor) {
              pt.call(Color2.fill, fillColor);
            } else {
              pt.call(fillGradient);
            }
          });
        }
      };
      function getGradientDirection(reversescale, isRadial) {
        var str = isRadial ? "radial" : "horizontal";
        return str + (reversescale ? "" : "reversed");
      }
      function getStyleGuide(d) {
        var trace = d[0].trace;
        var contours = trace.contours;
        var showLine = subTypes.hasLines(trace);
        var showMarker = subTypes.hasMarkers(trace);
        var showFill = trace.visible && trace.fill && trace.fill !== "none";
        var showGradientLine = false;
        var showGradientFill = false;
        if (contours) {
          var coloring = contours.coloring;
          if (coloring === "lines") {
            showGradientLine = true;
          } else {
            showLine = coloring === "none" || coloring === "heatmap" || contours.showlines;
          }
          if (contours.type === "constraint") {
            showFill = contours._operation !== "=";
          } else if (coloring === "fill" || coloring === "heatmap") {
            showGradientFill = true;
          }
        }
        return {
          showMarker,
          showLine,
          showFill,
          showGradientLine,
          showGradientFill,
          anyLine: showLine || showGradientLine,
          anyFill: showFill || showGradientFill
        };
      }
      function dimAttr(v, dflt, max) {
        if (v && Lib.isArrayOrTypedArray(v)) return dflt;
        if (v > max) return max;
        return v;
      }
    }
  });

  // src/components/legend/draw.js
  var require_draw = __commonJS({
    "src/components/legend/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Plots = require_plots();
      var Registry = require_registry();
      var Events = require_events2();
      var dragElement = require_dragelement();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var svgTextUtils = require_svg_text_utils();
      var handleItemClick = require_handle_click().handleItemClick;
      var handleTitleClick = require_handle_click().handleTitleClick;
      var constants = require_constants3();
      var alignmentConstants = require_alignment();
      var LINE_SPACING = alignmentConstants.LINE_SPACING;
      var FROM_TL = alignmentConstants.FROM_TL;
      var FROM_BR = alignmentConstants.FROM_BR;
      var getLegendData = require_get_legend_data();
      var style = require_style();
      var helpers = require_helpers3();
      var MAIN_TITLE = 1;
      var LEGEND_PATTERN = /^legend[0-9]*$/;
      module.exports = function draw(gd, opts) {
        if (opts) {
          drawOne(gd, opts);
        } else {
          var fullLayout = gd._fullLayout;
          var newLegends = fullLayout._legends;
          var oldLegends = fullLayout._infolayer.selectAll('[class^="legend"]');
          oldLegends.each(function() {
            var el = d3.select(this);
            var classes = el.attr("class");
            var cls = classes.split(" ")[0];
            if (cls.match(LEGEND_PATTERN) && newLegends.indexOf(cls) === -1) {
              el.remove();
            }
          });
          for (var i = 0; i < newLegends.length; i++) {
            var legendId = newLegends[i];
            var legendObj = gd._fullLayout[legendId];
            drawOne(gd, legendObj);
          }
        }
      };
      function horizontalAlignTitle(titleEl, legendObj, bw) {
        if (legendObj.title.side !== "top center" && legendObj.title.side !== "top right") return;
        var font = legendObj.title.font;
        var lineHeight = font.size * LINE_SPACING;
        var titleOffset = 0;
        var textNode = titleEl.node();
        var width = Drawing.bBox(textNode).width;
        if (legendObj.title.side === "top center") {
          titleOffset = 0.5 * (legendObj._width - 2 * bw - 2 * constants.titlePad - width);
        } else if (legendObj.title.side === "top right") {
          titleOffset = legendObj._width - 2 * bw - 2 * constants.titlePad - width;
        }
        svgTextUtils.positionText(
          titleEl,
          bw + constants.titlePad + titleOffset,
          bw + lineHeight
        );
      }
      function drawOne(gd, opts) {
        var legendObj = opts || {};
        var fullLayout = gd._fullLayout;
        var legendId = helpers.getId(legendObj);
        var clipId, layer;
        var inHover = legendObj._inHover;
        if (inHover) {
          layer = legendObj.layer;
          clipId = "hover";
        } else {
          layer = fullLayout._infolayer;
          clipId = legendId;
        }
        if (!layer) return;
        clipId += fullLayout._uid;
        if (!gd._legendMouseDownTime) gd._legendMouseDownTime = 0;
        var legendData;
        if (!inHover) {
          var calcdata = (gd.calcdata || []).slice();
          var shapes = fullLayout.shapes;
          for (var i = 0; i < shapes.length; i++) {
            var shape = shapes[i];
            if (!shape.showlegend) continue;
            var shapeLegend = {
              _isShape: true,
              _fullInput: shape,
              index: shape._index,
              name: shape.name || shape.label.text || "shape " + shape._index,
              legend: shape.legend,
              legendgroup: shape.legendgroup,
              legendgrouptitle: shape.legendgrouptitle,
              legendrank: shape.legendrank,
              legendwidth: shape.legendwidth,
              showlegend: shape.showlegend,
              visible: shape.visible,
              opacity: shape.opacity,
              mode: shape.type === "line" ? "lines" : "markers",
              line: shape.line,
              marker: {
                line: shape.line,
                color: shape.fillcolor,
                size: 12,
                symbol: shape.type === "rect" ? "square" : shape.type === "circle" ? "circle" : (
                  // case of path
                  "hexagon2"
                )
              }
            };
            calcdata.push([{ trace: shapeLegend }]);
          }
          legendData = fullLayout.showlegend && getLegendData(calcdata, legendObj, fullLayout._legends.length > 1);
        } else {
          if (!legendObj.entries) return;
          legendData = getLegendData(legendObj.entries, legendObj);
        }
        var hiddenSlices = fullLayout.hiddenlabels || [];
        if (!inHover && (!fullLayout.showlegend || !legendData.length)) {
          layer.selectAll("." + legendId).remove();
          fullLayout._topdefs.select("#" + clipId).remove();
          return Plots.autoMargin(gd, legendId);
        }
        var legend = Lib.ensureSingle(layer, "g", legendId, function(s) {
          if (!inHover) s.attr("pointer-events", "all");
        });
        var clipPath = Lib.ensureSingleById(fullLayout._topdefs, "clipPath", clipId, function(s) {
          s.append("rect");
        });
        var bg = Lib.ensureSingle(legend, "rect", "bg", function(s) {
          s.attr("shape-rendering", "crispEdges");
        });
        bg.call(Color2.stroke, legendObj.bordercolor).call(Color2.fill, legendObj.bgcolor).style("stroke-width", legendObj.borderwidth + "px");
        var scrollBox = Lib.ensureSingle(legend, "g", "scrollbox");
        var title = legendObj.title;
        legendObj._titleWidth = 0;
        legendObj._titleHeight = 0;
        var titleEl;
        if (title.text) {
          titleEl = Lib.ensureSingle(scrollBox, "text", legendId + "titletext");
          titleEl.attr("text-anchor", "start").call(Drawing.font, title.font).text(title.text);
          textLayout(titleEl, scrollBox, gd, legendObj, MAIN_TITLE);
          if (!inHover && (legendObj.titleclick || legendObj.titledoubleclick)) {
            setupTitleToggle(scrollBox, gd, legendObj, legendId);
          }
        } else {
          scrollBox.selectAll("." + legendId + "titletext").remove();
          scrollBox.selectAll("." + legendId + "titletoggle").remove();
        }
        var scrollBar = Lib.ensureSingle(legend, "rect", "scrollbar", function(s) {
          s.attr(constants.scrollBarEnterAttrs).call(Color2.fill, constants.scrollBarColor);
        });
        var groups = scrollBox.selectAll("g.groups").data(legendData);
        groups.enter().append("g").attr("class", "groups");
        groups.exit().remove();
        var traces = groups.selectAll("g.traces").data(Lib.identity);
        traces.enter().append("g").attr("class", "traces");
        traces.exit().remove();
        traces.style("opacity", function(d) {
          const legendItem = d[0];
          const trace = legendItem.trace;
          if (legendItem.groupTitle) {
            const groupName = trace.legendgroup;
            const shapes2 = (fullLayout.shapes || []).filter(function(s) {
              return s.showlegend;
            });
            const anyVisible = gd._fullData.concat(shapes2).some(function(item) {
              return item.legendgroup === groupName && (item.legend || "legend") === legendId && item.visible === true;
            });
            return anyVisible ? 1 : 0.5;
          }
          if (Registry.traceIs(trace, "pie-like")) {
            return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1;
          } else {
            return trace.visible === "legendonly" ? 0.5 : 1;
          }
        }).each(function() {
          d3.select(this).call(drawTexts, gd, legendObj);
        }).call(style, gd, legendObj).each(function(d) {
          if (inHover) return;
          if (d[0].groupTitle && legendObj.groupclick === "toggleitem") return;
          d3.select(this).call(setupTraceToggle, gd, legendId);
        });
        Lib.syncOrAsync([
          Plots.previousPromises,
          function() {
            return computeLegendDimensions(gd, groups, traces, legendObj, scrollBox);
          },
          function() {
            var gs = fullLayout._size;
            var bw = legendObj.borderwidth;
            var isPaperX = legendObj.xref === "paper";
            var isPaperY = legendObj.yref === "paper";
            if (title.text) {
              const shapes2 = (fullLayout.shapes || []).filter(function(s) {
                return s.showlegend;
              });
              const anyVisible = gd._fullData.concat(shapes2).some(function(item) {
                const legendAttr = item.legend || "legend";
                var inThisLegend = Array.isArray(legendAttr) ? legendAttr.includes(legendId) : legendAttr === legendId;
                return inThisLegend && item.visible === true;
              });
              titleEl.style("opacity", anyVisible ? 1 : 0.5);
            }
            if (!inHover) {
              var lx, ly;
              if (isPaperX) {
                lx = gs.l + gs.w * legendObj.x - FROM_TL[getXanchor(legendObj)] * legendObj._width;
              } else {
                lx = fullLayout.width * legendObj.x - FROM_TL[getXanchor(legendObj)] * legendObj._width;
              }
              if (isPaperY) {
                ly = gs.t + gs.h * (1 - legendObj.y) - FROM_TL[getYanchor(legendObj)] * legendObj._effHeight;
              } else {
                ly = fullLayout.height * (1 - legendObj.y) - FROM_TL[getYanchor(legendObj)] * legendObj._effHeight;
              }
              var expMargin = expandMargin(gd, legendId, lx, ly);
              if (expMargin) return;
              if (fullLayout.margin.autoexpand) {
                var lx0 = lx;
                var ly0 = ly;
                lx = isPaperX ? Lib.constrain(lx, 0, fullLayout.width - legendObj._width) : lx0;
                ly = isPaperY ? Lib.constrain(ly, 0, fullLayout.height - legendObj._effHeight) : ly0;
                if (lx !== lx0) {
                  Lib.log("Constrain " + legendId + ".x to make legend fit inside graph");
                }
                if (ly !== ly0) {
                  Lib.log("Constrain " + legendId + ".y to make legend fit inside graph");
                }
              }
              Drawing.setTranslate(legend, lx, ly);
            }
            scrollBar.on(".drag", null);
            legend.on("wheel", null);
            if (inHover || legendObj._height <= legendObj._maxHeight || gd._context.staticPlot) {
              var height = legendObj._effHeight;
              if (inHover) height = legendObj._height;
              bg.attr({
                width: legendObj._width - bw,
                height: height - bw,
                x: bw / 2,
                y: bw / 2
              });
              Drawing.setTranslate(scrollBox, 0, 0);
              clipPath.select("rect").attr({
                width: legendObj._width - 2 * bw,
                height: height - 2 * bw,
                x: bw,
                y: bw
              });
              Drawing.setClipUrl(scrollBox, clipId, gd);
              Drawing.setRect(scrollBar, 0, 0, 0, 0);
              delete legendObj._scrollY;
            } else {
              var scrollBarHeight = Math.max(
                constants.scrollBarMinHeight,
                legendObj._effHeight * legendObj._effHeight / legendObj._height
              );
              var scrollBarYMax = legendObj._effHeight - scrollBarHeight - 2 * constants.scrollBarMargin;
              var scrollBoxYMax = legendObj._height - legendObj._effHeight;
              var scrollRatio = scrollBarYMax / scrollBoxYMax;
              var scrollBoxY = Math.min(legendObj._scrollY || 0, scrollBoxYMax);
              bg.attr({
                width: legendObj._width - 2 * bw + constants.scrollBarWidth + constants.scrollBarMargin,
                height: legendObj._effHeight - bw,
                x: bw / 2,
                y: bw / 2
              });
              clipPath.select("rect").attr({
                width: legendObj._width - 2 * bw + constants.scrollBarWidth + constants.scrollBarMargin,
                height: legendObj._effHeight - 2 * bw,
                x: bw,
                y: bw + scrollBoxY
              });
              Drawing.setClipUrl(scrollBox, clipId, gd);
              scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
              legend.on("wheel", function() {
                scrollBoxY = Lib.constrain(
                  legendObj._scrollY + d3.event.deltaY / scrollBoxYMax * scrollBarYMax,
                  0,
                  scrollBoxYMax
                );
                scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
                if (scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) {
                  d3.event.preventDefault();
                }
              });
              var eventY0, eventY1, scrollBoxY0;
              var getScrollBarDragY = function(scrollBoxY02, eventY02, eventY12) {
                var y = (eventY12 - eventY02) / scrollRatio + scrollBoxY02;
                return Lib.constrain(y, 0, scrollBoxYMax);
              };
              var getNaturalDragY = function(scrollBoxY02, eventY02, eventY12) {
                var y = (eventY02 - eventY12) / scrollRatio + scrollBoxY02;
                return Lib.constrain(y, 0, scrollBoxYMax);
              };
              var scrollBarDrag = d3.behavior.drag().on("dragstart", function() {
                var e = d3.event.sourceEvent;
                if (e.type === "touchstart") {
                  eventY0 = e.changedTouches[0].clientY;
                } else {
                  eventY0 = e.clientY;
                }
                scrollBoxY0 = scrollBoxY;
              }).on("drag", function() {
                var e = d3.event.sourceEvent;
                if (e.buttons === 2 || e.ctrlKey) return;
                if (e.type === "touchmove") {
                  eventY1 = e.changedTouches[0].clientY;
                } else {
                  eventY1 = e.clientY;
                }
                scrollBoxY = getScrollBarDragY(scrollBoxY0, eventY0, eventY1);
                scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
              });
              scrollBar.call(scrollBarDrag);
              var scrollBoxTouchDrag = d3.behavior.drag().on("dragstart", function() {
                var e = d3.event.sourceEvent;
                if (e.type === "touchstart") {
                  eventY0 = e.changedTouches[0].clientY;
                  scrollBoxY0 = scrollBoxY;
                }
              }).on("drag", function() {
                var e = d3.event.sourceEvent;
                if (e.type === "touchmove") {
                  eventY1 = e.changedTouches[0].clientY;
                  scrollBoxY = getNaturalDragY(scrollBoxY0, eventY0, eventY1);
                  scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
                }
              });
              scrollBox.call(scrollBoxTouchDrag);
            }
            function scrollHandler(scrollBoxY2, scrollBarHeight2, scrollRatio2) {
              legendObj._scrollY = gd._fullLayout[legendId]._scrollY = scrollBoxY2;
              Drawing.setTranslate(scrollBox, 0, -scrollBoxY2);
              Drawing.setRect(
                scrollBar,
                legendObj._width,
                constants.scrollBarMargin + scrollBoxY2 * scrollRatio2,
                constants.scrollBarWidth,
                scrollBarHeight2
              );
              clipPath.select("rect").attr("y", bw + scrollBoxY2);
            }
            if (gd._context.edits.legendPosition) {
              var xf, yf, x0, y0;
              legend.classed("cursor-move", true);
              dragElement.init({
                element: legend.node(),
                gd,
                prepFn: function(e) {
                  if (e.target === scrollBar.node()) {
                    return;
                  }
                  var transform = Drawing.getTranslate(legend);
                  x0 = transform.x;
                  y0 = transform.y;
                },
                moveFn: function(dx, dy) {
                  if (x0 !== void 0 && y0 !== void 0) {
                    var newX = x0 + dx;
                    var newY = y0 + dy;
                    Drawing.setTranslate(legend, newX, newY);
                    xf = dragElement.align(newX, legendObj._width, gs.l, gs.l + gs.w, legendObj.xanchor);
                    yf = dragElement.align(newY + legendObj._height, -legendObj._height, gs.t + gs.h, gs.t, legendObj.yanchor);
                  }
                },
                doneFn: function() {
                  if (xf !== void 0 && yf !== void 0) {
                    var obj = {};
                    obj[legendId + ".x"] = xf;
                    obj[legendId + ".y"] = yf;
                    Registry.call("_guiRelayout", gd, obj);
                  }
                },
                clickFn: function(numClicks, e) {
                  var clickedTrace = layer.selectAll("g.traces").filter(function() {
                    var bbox = this.getBoundingClientRect();
                    return e.clientX >= bbox.left && e.clientX <= bbox.right && e.clientY >= bbox.top && e.clientY <= bbox.bottom;
                  });
                  if (clickedTrace.size() > 0) {
                    clickOrDoubleClick(gd, legendObj, clickedTrace, numClicks, e);
                  }
                }
              });
            }
          }
        ], gd);
      }
      function getTraceWidth(d, legendObj, textGap) {
        var legendItem = d[0];
        var legendWidth = legendItem.width;
        var mode = legendObj.entrywidthmode;
        var traceLegendWidth = legendItem.trace.legendwidth || legendObj.entrywidth;
        if (mode === "fraction") return legendObj._maxWidth * traceLegendWidth;
        return textGap + (traceLegendWidth || legendWidth);
      }
      function clickOrDoubleClick(gd, legend, legendItem, numClicks, evt) {
        var fullLayout = gd._fullLayout;
        var trace = legendItem.data()[0][0].trace;
        var itemClick = legend.itemclick;
        var itemDoubleClick = legend.itemdoubleclick;
        var evtData = {
          event: evt,
          node: legendItem.node(),
          curveNumber: trace.index,
          expandedIndex: trace.index,
          data: gd.data,
          layout: gd.layout,
          frames: gd._transitionData._frames,
          config: gd._context,
          fullData: gd._fullData,
          fullLayout
        };
        if (trace._group) {
          evtData.group = trace._group;
        }
        if (Registry.traceIs(trace, "pie-like")) {
          evtData.label = legendItem.datum()[0].label;
        }
        var clickVal = Events.triggerHandler(gd, "plotly_legendclick", evtData);
        if (numClicks === 1) {
          if (clickVal === false) return;
          legend._clickTimeout = setTimeout(function() {
            if (!gd._fullLayout) return;
            if (itemClick) handleItemClick(legendItem, gd, legend, itemClick);
          }, gd._context.doubleClickDelay);
        } else if (numClicks === 2) {
          if (legend._clickTimeout) clearTimeout(legend._clickTimeout);
          gd._legendMouseDownTime = 0;
          var dblClickVal = Events.triggerHandler(gd, "plotly_legenddoubleclick", evtData);
          if (dblClickVal !== false && clickVal !== false && itemDoubleClick) {
            handleItemClick(legendItem, gd, legend, itemDoubleClick);
          }
        }
      }
      function drawTexts(g, gd, legendObj) {
        var legendId = helpers.getId(legendObj);
        var legendItem = g.data()[0][0];
        var trace = legendItem.trace;
        var isPieLike = Registry.traceIs(trace, "pie-like");
        var isEditable = !legendObj._inHover && gd._context.edits.legendText && !isPieLike;
        var maxNameLength = legendObj._maxNameLength;
        var name2, font;
        if (legendItem.groupTitle) {
          name2 = legendItem.groupTitle.text;
          font = legendItem.groupTitle.font;
        } else {
          font = legendObj.font;
          if (!legendObj.entries) {
            name2 = isPieLike ? legendItem.label : trace.name;
            if (trace._meta) {
              name2 = Lib.templateString(name2, trace._meta);
            }
          } else {
            name2 = legendItem.text;
          }
        }
        var textEl = Lib.ensureSingle(g, "text", legendId + "text");
        textEl.attr("text-anchor", "start").call(Drawing.font, font).text(isEditable ? ensureLength(name2, maxNameLength) : name2);
        var textGap = legendObj.indentation + legendObj.itemwidth + constants.itemGap * 2;
        svgTextUtils.positionText(textEl, textGap, 0);
        if (isEditable) {
          textEl.call(svgTextUtils.makeEditable, { gd, text: name2 }).call(textLayout, g, gd, legendObj).on("edit", function(newName) {
            this.text(ensureLength(newName, maxNameLength)).call(textLayout, g, gd, legendObj);
            var fullInput = legendItem.trace._fullInput || {};
            var update = {};
            update.name = newName;
            if (fullInput._isShape) {
              return Registry.call("_guiRelayout", gd, "shapes[" + trace.index + "].name", update.name);
            } else {
              return Registry.call("_guiRestyle", gd, update, trace.index);
            }
          });
        } else {
          textLayout(textEl, g, gd, legendObj);
        }
      }
      function ensureLength(str, maxLength) {
        var targetLength = Math.max(4, maxLength);
        if (str && str.trim().length >= targetLength / 2) return str;
        str = str || "";
        for (var i = targetLength - str.length; i > 0; i--) str += " ";
        return str;
      }
      function setupTraceToggle(g, gd, legendId) {
        var doubleClickDelay = gd._context.doubleClickDelay;
        var newMouseDownTime;
        var numClicks = 1;
        var traceToggle = Lib.ensureSingle(g, "rect", legendId + "toggle", function(s) {
          if (!gd._context.staticPlot) {
            s.style("cursor", "pointer").attr("pointer-events", "all");
          }
          s.call(Color2.fill, "rgba(0,0,0,0)");
        });
        if (gd._context.staticPlot) return;
        traceToggle.on("mousedown", function() {
          newMouseDownTime = (/* @__PURE__ */ new Date()).getTime();
          if (newMouseDownTime - gd._legendMouseDownTime < doubleClickDelay) {
            numClicks += 1;
          } else {
            numClicks = 1;
            gd._legendMouseDownTime = newMouseDownTime;
          }
        });
        traceToggle.on("mouseup", function() {
          if (gd._dragged || gd._editing) return;
          var legend = gd._fullLayout[legendId];
          if ((/* @__PURE__ */ new Date()).getTime() - gd._legendMouseDownTime > doubleClickDelay) {
            numClicks = Math.max(numClicks - 1, 1);
          }
          clickOrDoubleClick(gd, legend, g, numClicks, d3.event);
        });
      }
      function setupTitleToggle(scrollBox, gd, legendObj, legendId) {
        const hasPie = gd._fullData.some(function(trace) {
          const legend = trace.legend || "legend";
          const inThisLegend = Array.isArray(legend) ? legend.includes(legendId) : legend === legendId;
          return inThisLegend && Registry.traceIs(trace, "pie-like");
        });
        if (hasPie) return;
        const doubleClickDelay = gd._context.doubleClickDelay;
        var newMouseDownTime;
        var numClicks = 1;
        const titleToggle = Lib.ensureSingle(scrollBox, "rect", legendId + "titletoggle", function(s) {
          if (!gd._context.staticPlot) {
            s.style("cursor", "pointer").attr("pointer-events", "all");
          }
          s.call(Color2.fill, "rgba(0,0,0,0)");
        });
        if (gd._context.staticPlot) return;
        titleToggle.on("mousedown", function() {
          newMouseDownTime = (/* @__PURE__ */ new Date()).getTime();
          if (newMouseDownTime - gd._legendMouseDownTime < doubleClickDelay) {
            numClicks += 1;
          } else {
            numClicks = 1;
            gd._legendMouseDownTime = newMouseDownTime;
          }
        });
        titleToggle.on("mouseup", function() {
          if (gd._dragged || gd._editing) return;
          if ((/* @__PURE__ */ new Date()).getTime() - gd._legendMouseDownTime > doubleClickDelay) {
            numClicks = Math.max(numClicks - 1, 1);
          }
          const evtData = {
            event: d3.event,
            legendId,
            data: gd.data,
            layout: gd.layout,
            fullData: gd._fullData,
            fullLayout: gd._fullLayout
          };
          if (numClicks === 1 && legendObj.titleclick) {
            const clickVal = Events.triggerHandler(gd, "plotly_legendtitleclick", evtData);
            if (clickVal === false) return;
            legendObj._titleClickTimeout = setTimeout(function() {
              if (gd._fullLayout) handleTitleClick(gd, legendObj, legendObj.titleclick);
            }, doubleClickDelay);
          } else if (numClicks === 2) {
            if (legendObj._titleClickTimeout) clearTimeout(legendObj._titleClickTimeout);
            gd._legendMouseDownTime = 0;
            const dblClickVal = Events.triggerHandler(gd, "plotly_legendtitledoubleclick", evtData);
            if (dblClickVal !== false && legendObj.titledoubleclick) handleTitleClick(gd, legendObj, legendObj.titledoubleclick);
          }
        });
      }
      function textLayout(s, g, gd, legendObj, aTitle) {
        if (legendObj._inHover) s.attr("data-notex", true);
        svgTextUtils.convertToTspans(s, gd, function() {
          computeTextDimensions(g, gd, legendObj, aTitle);
        });
      }
      function computeTextDimensions(g, gd, legendObj, aTitle) {
        var legendItem = g.data()[0][0];
        var showlegend = legendItem && legendItem.trace.showlegend;
        if (Array.isArray(showlegend)) {
          showlegend = showlegend[legendItem.i] !== false;
        }
        if (!legendObj._inHover && legendItem && !showlegend) {
          g.remove();
          return;
        }
        var mathjaxGroup = g.select("g[class*=math-group]");
        var mathjaxNode = mathjaxGroup.node();
        var legendId = helpers.getId(legendObj);
        if (!legendObj) {
          legendObj = gd._fullLayout[legendId];
        }
        var bw = legendObj.borderwidth;
        var font;
        if (aTitle === MAIN_TITLE) {
          font = legendObj.title.font;
        } else if (legendItem.groupTitle) {
          font = legendItem.groupTitle.font;
        } else {
          font = legendObj.font;
        }
        var lineHeight = font.size * LINE_SPACING;
        var height, width;
        if (mathjaxNode) {
          var mathjaxBB = Drawing.bBox(mathjaxNode);
          height = mathjaxBB.height;
          width = mathjaxBB.width;
          if (aTitle === MAIN_TITLE) {
            Drawing.setTranslate(mathjaxGroup, bw, bw + height * 0.75);
          } else {
            Drawing.setTranslate(mathjaxGroup, 0, height * 0.25);
          }
        } else {
          var cls = "." + legendId + (aTitle === MAIN_TITLE ? "title" : "") + "text";
          var textEl = g.select(cls);
          var textLines = svgTextUtils.lineCount(textEl);
          var textNode = textEl.node();
          height = lineHeight * textLines;
          width = textNode ? Drawing.bBox(textNode).width : 0;
          if (aTitle === MAIN_TITLE) {
            if (legendObj.title.side === "left") {
              width += constants.itemGap * 2;
            }
            svgTextUtils.positionText(
              textEl,
              bw + constants.titlePad,
              bw + lineHeight
            );
          } else {
            var x = constants.itemGap * 2 + legendObj.indentation + legendObj.itemwidth;
            if (legendItem.groupTitle) {
              x = constants.itemGap;
              width -= legendObj.indentation + legendObj.itemwidth;
            }
            svgTextUtils.positionText(
              textEl,
              x,
              -lineHeight * ((textLines - 1) / 2 - 0.3)
            );
          }
        }
        if (aTitle === MAIN_TITLE) {
          legendObj._titleWidth = width;
          legendObj._titleHeight = height;
        } else {
          legendItem.lineHeight = lineHeight;
          legendItem.height = Math.max(height, 16) + 3;
          legendItem.width = width;
        }
      }
      function getTitleSize(legendObj) {
        var w = 0;
        var h = 0;
        var side = legendObj.title.side;
        if (side) {
          if (side.indexOf("left") !== -1) {
            w = legendObj._titleWidth;
          }
          if (side.indexOf("top") !== -1) {
            h = legendObj._titleHeight;
          }
        }
        return [w, h];
      }
      function computeLegendDimensions(gd, groups, traces, legendObj, scrollBox) {
        var fullLayout = gd._fullLayout;
        var legendId = helpers.getId(legendObj);
        if (!legendObj) {
          legendObj = fullLayout[legendId];
        }
        var gs = fullLayout._size;
        var isVertical = helpers.isVertical(legendObj);
        var isGrouped = helpers.isGrouped(legendObj);
        var isFraction = legendObj.entrywidthmode === "fraction";
        var bw = legendObj.borderwidth;
        var bw2 = 2 * bw;
        var itemGap = constants.itemGap;
        var textGap = legendObj.indentation + legendObj.itemwidth + itemGap * 2;
        var endPad = 2 * (bw + itemGap);
        var yanchor = getYanchor(legendObj);
        var isBelowPlotArea = legendObj.y < 0 || legendObj.y === 0 && yanchor === "top";
        var isAbovePlotArea = legendObj.y > 1 || legendObj.y === 1 && yanchor === "bottom";
        var traceGroupGap = legendObj.tracegroupgap;
        var legendGroupWidths = {};
        const { orientation, yref } = legendObj;
        let { maxheight } = legendObj;
        const useFullLayoutHeight = isBelowPlotArea || isAbovePlotArea || orientation !== "v" || yref !== "paper";
        maxheight || (maxheight = useFullLayoutHeight ? 0.5 : 1);
        const heightToBeScaled = useFullLayoutHeight ? fullLayout.height : gs.h;
        legendObj._maxHeight = Math.max(maxheight > 1 ? maxheight : maxheight * heightToBeScaled, 30);
        var toggleRectWidth = 0;
        legendObj._width = 0;
        legendObj._height = 0;
        var titleSize = getTitleSize(legendObj);
        if (isVertical) {
          traces.each(function(d) {
            var h = d[0].height;
            Drawing.setTranslate(
              this,
              bw + titleSize[0],
              bw + titleSize[1] + legendObj._height + h / 2 + itemGap
            );
            legendObj._height += h;
            legendObj._width = Math.max(legendObj._width, d[0].width);
          });
          toggleRectWidth = textGap + legendObj._width;
          legendObj._width += itemGap + textGap + bw2;
          legendObj._height += endPad;
          if (isGrouped) {
            groups.each(function(d, i) {
              Drawing.setTranslate(this, 0, i * legendObj.tracegroupgap);
            });
            legendObj._height += (legendObj._lgroupsLength - 1) * legendObj.tracegroupgap;
          }
        } else {
          var xanchor = getXanchor(legendObj);
          var isLeftOfPlotArea = legendObj.x < 0 || legendObj.x === 0 && xanchor === "right";
          var isRightOfPlotArea = legendObj.x > 1 || legendObj.x === 1 && xanchor === "left";
          var isBeyondPlotAreaY = isAbovePlotArea || isBelowPlotArea;
          var hw = fullLayout.width / 2;
          legendObj._maxWidth = Math.max(
            isLeftOfPlotArea ? isBeyondPlotAreaY && xanchor === "left" ? gs.l + gs.w : hw : isRightOfPlotArea ? isBeyondPlotAreaY && xanchor === "right" ? gs.r + gs.w : hw : gs.w,
            2 * textGap
          );
          var maxItemWidth = 0;
          var combinedItemWidth = 0;
          traces.each(function(d) {
            var w = getTraceWidth(d, legendObj, textGap);
            maxItemWidth = Math.max(maxItemWidth, w);
            combinedItemWidth += w;
          });
          toggleRectWidth = null;
          var maxRowWidth = 0;
          if (isGrouped) {
            var maxGroupHeightInRow = 0;
            var groupOffsetX = 0;
            var groupOffsetY = 0;
            groups.each(function() {
              var maxWidthInGroup = 0;
              var offsetY2 = 0;
              d3.select(this).selectAll("g.traces").each(function(d) {
                var w = getTraceWidth(d, legendObj, textGap);
                var h = d[0].height;
                Drawing.setTranslate(
                  this,
                  titleSize[0],
                  titleSize[1] + bw + itemGap + h / 2 + offsetY2
                );
                offsetY2 += h;
                maxWidthInGroup = Math.max(maxWidthInGroup, w);
                legendGroupWidths[d[0].trace.legendgroup] = maxWidthInGroup;
              });
              var next = maxWidthInGroup + itemGap;
              if (
                // not on the first column already
                groupOffsetX > 0 && // goes beyound limit
                next + bw + groupOffsetX > legendObj._maxWidth
              ) {
                maxRowWidth = Math.max(maxRowWidth, groupOffsetX);
                groupOffsetX = 0;
                groupOffsetY += maxGroupHeightInRow + traceGroupGap;
                maxGroupHeightInRow = offsetY2;
              } else {
                maxGroupHeightInRow = Math.max(maxGroupHeightInRow, offsetY2);
              }
              Drawing.setTranslate(this, groupOffsetX, groupOffsetY);
              groupOffsetX += next;
            });
            legendObj._width = Math.max(maxRowWidth, groupOffsetX) + bw;
            legendObj._height = groupOffsetY + maxGroupHeightInRow + endPad;
          } else {
            var nTraces = traces.size();
            var oneRowLegend = combinedItemWidth + bw2 + (nTraces - 1) * itemGap < legendObj._maxWidth;
            var maxItemHeightInRow = 0;
            var offsetX = 0;
            var offsetY = 0;
            var rowWidth = 0;
            traces.each(function(d) {
              var h = d[0].height;
              var w = getTraceWidth(d, legendObj, textGap, isGrouped);
              var next = oneRowLegend ? w : maxItemWidth;
              if (!isFraction) {
                next += itemGap;
              }
              if (next + bw + offsetX - itemGap >= legendObj._maxWidth) {
                maxRowWidth = Math.max(maxRowWidth, rowWidth);
                offsetX = 0;
                offsetY += maxItemHeightInRow;
                legendObj._height += maxItemHeightInRow;
                maxItemHeightInRow = 0;
              }
              Drawing.setTranslate(
                this,
                titleSize[0] + bw + offsetX,
                titleSize[1] + bw + offsetY + h / 2 + itemGap
              );
              rowWidth = offsetX + w + itemGap;
              offsetX += next;
              maxItemHeightInRow = Math.max(maxItemHeightInRow, h);
            });
            if (oneRowLegend) {
              legendObj._width = offsetX + bw2;
              legendObj._height = maxItemHeightInRow + endPad;
            } else {
              legendObj._width = Math.max(maxRowWidth, rowWidth) + bw2;
              legendObj._height += maxItemHeightInRow + endPad;
            }
          }
        }
        legendObj._width = Math.ceil(
          Math.max(
            legendObj._width + titleSize[0],
            legendObj._titleWidth + 2 * (bw + constants.titlePad)
          )
        );
        legendObj._height = Math.ceil(
          Math.max(
            legendObj._height + titleSize[1],
            legendObj._titleHeight + 2 * (bw + constants.itemGap)
          )
        );
        legendObj._effHeight = Math.min(legendObj._height, legendObj._maxHeight);
        var edits = gd._context.edits;
        var isEditable = edits.legendText || edits.legendPosition;
        traces.each(function(d) {
          var traceToggle = d3.select(this).select("." + legendId + "toggle");
          var h = d[0].height;
          var legendgroup = d[0].trace.legendgroup;
          var traceWidth = getTraceWidth(d, legendObj, textGap);
          if (isGrouped && legendgroup !== "") {
            traceWidth = legendGroupWidths[legendgroup];
          }
          var w = isEditable ? textGap : toggleRectWidth || traceWidth;
          if (!isVertical && !isFraction) {
            w += itemGap / 2;
          }
          Drawing.setRect(traceToggle, 0, -h / 2, w, h);
        });
        var titleEl = scrollBox.select("." + legendId + "titletext");
        if (titleEl.node()) {
          horizontalAlignTitle(titleEl, legendObj, bw);
        }
        var titleToggle = scrollBox.select("." + legendId + "titletoggle");
        if (titleToggle.size() && titleEl.node()) {
          var titleX = titleEl.attr("x") || 0;
          var pad = constants.titlePad;
          Drawing.setRect(
            titleToggle,
            titleX - pad,
            bw,
            legendObj._titleWidth + 2 * pad,
            legendObj._titleHeight + 2 * pad
          );
        }
      }
      function expandMargin(gd, legendId, lx, ly) {
        var fullLayout = gd._fullLayout;
        var legendObj = fullLayout[legendId];
        var xanchor = getXanchor(legendObj);
        var yanchor = getYanchor(legendObj);
        var isPaperX = legendObj.xref === "paper";
        var isPaperY = legendObj.yref === "paper";
        gd._fullLayout._reservedMargin[legendId] = {};
        var sideY = legendObj.y < 0.5 ? "b" : "t";
        var sideX = legendObj.x < 0.5 ? "l" : "r";
        var possibleReservedMargins = {
          r: fullLayout.width - lx,
          l: lx + legendObj._width,
          b: fullLayout.height - ly,
          t: ly + legendObj._effHeight
        };
        if (isPaperX && isPaperY) {
          return Plots.autoMargin(gd, legendId, {
            x: legendObj.x,
            y: legendObj.y,
            l: legendObj._width * FROM_TL[xanchor],
            r: legendObj._width * FROM_BR[xanchor],
            b: legendObj._effHeight * FROM_BR[yanchor],
            t: legendObj._effHeight * FROM_TL[yanchor]
          });
        } else if (isPaperX) {
          gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY];
        } else if (isPaperY) {
          gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX];
        } else {
          if (legendObj.orientation === "v") {
            gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX];
          } else {
            gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY];
          }
        }
      }
      function getXanchor(legendObj) {
        return Lib.isRightAnchor(legendObj) ? "right" : Lib.isCenterAnchor(legendObj) ? "center" : "left";
      }
      function getYanchor(legendObj) {
        return Lib.isBottomAnchor(legendObj) ? "bottom" : Lib.isMiddleAnchor(legendObj) ? "middle" : "top";
      }
    }
  });

  // src/components/fx/hover.js
  var require_hover = __commonJS({
    "src/components/fx/hover.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var tinycolor = require_tinycolor();
      var Lib = require_lib();
      var pushUnique = Lib.pushUnique;
      var strTranslate = Lib.strTranslate;
      var strRotate = Lib.strRotate;
      var Events = require_events2();
      var svgTextUtils = require_svg_text_utils();
      var overrideCursor = require_override_cursor();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var dragElement = require_dragelement();
      var Axes = require_axes();
      var zindexSeparator = require_constants2().zindexSeparator;
      var Registry = require_registry();
      var helpers = require_helpers2();
      var constants = require_constants();
      var legendSupplyDefaults = require_defaults3();
      var legendDraw = require_draw();
      var YANGLE = constants.YANGLE;
      var YA_RADIANS = Math.PI * YANGLE / 180;
      var YFACTOR = 1 / Math.sin(YA_RADIANS);
      var YSHIFTX = Math.cos(YA_RADIANS);
      var YSHIFTY = Math.sin(YA_RADIANS);
      var HOVERARROWSIZE = constants.HOVERARROWSIZE;
      var HOVERTEXTPAD = constants.HOVERTEXTPAD;
      var multipleHoverPoints = {
        box: true,
        ohlc: true,
        violin: true,
        candlestick: true
      };
      var cartesianScatterPoints = {
        scatter: true,
        scattergl: true,
        splom: true
      };
      function distanceSort(a, b) {
        return a.distance - b.distance;
      }
      exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
        gd = Lib.getGraphDiv(gd);
        var eventTarget = evt.target;
        Lib.throttle(gd._fullLayout._uid + constants.HOVERID, constants.HOVERMINTIME, function() {
          _hover(gd, evt, subplot, noHoverEvent, eventTarget);
        });
      };
      exports.loneHover = function loneHover(hoverItems, opts) {
        var multiHover = true;
        if (!Array.isArray(hoverItems)) {
          multiHover = false;
          hoverItems = [hoverItems];
        }
        var gd = opts.gd;
        var gTop = getTopOffset(gd);
        var gLeft = getLeftOffset(gd);
        var pointsData = hoverItems.map(function(hoverItem) {
          var _x0 = hoverItem._x0 || hoverItem.x0 || hoverItem.x || 0;
          var _x1 = hoverItem._x1 || hoverItem.x1 || hoverItem.x || 0;
          var _y0 = hoverItem._y0 || hoverItem.y0 || hoverItem.y || 0;
          var _y1 = hoverItem._y1 || hoverItem.y1 || hoverItem.y || 0;
          var eventData = hoverItem.eventData;
          if (eventData) {
            var x0 = Math.min(_x0, _x1);
            var x1 = Math.max(_x0, _x1);
            var y0 = Math.min(_y0, _y1);
            var y1 = Math.max(_y0, _y1);
            var trace = hoverItem.trace;
            if (Registry.traceIs(trace, "gl3d")) {
              var container = gd._fullLayout[trace.scene]._scene.container;
              var dx = container.offsetLeft;
              var dy = container.offsetTop;
              x0 += dx;
              x1 += dx;
              y0 += dy;
              y1 += dy;
            }
            eventData.bbox = {
              x0: x0 + gLeft,
              x1: x1 + gLeft,
              y0: y0 + gTop,
              y1: y1 + gTop
            };
            if (opts.inOut_bbox) {
              opts.inOut_bbox.push(eventData.bbox);
            }
          } else {
            eventData = false;
          }
          return {
            color: hoverItem.color || Color2.defaultLine,
            x0: hoverItem.x0 || hoverItem.x || 0,
            x1: hoverItem.x1 || hoverItem.x || 0,
            y0: hoverItem.y0 || hoverItem.y || 0,
            y1: hoverItem.y1 || hoverItem.y || 0,
            xLabel: hoverItem.xLabel,
            yLabel: hoverItem.yLabel,
            zLabel: hoverItem.zLabel,
            text: hoverItem.text,
            name: hoverItem.name,
            idealAlign: hoverItem.idealAlign,
            // optional extra bits of styling
            borderColor: hoverItem.borderColor,
            fontFamily: hoverItem.fontFamily,
            fontSize: hoverItem.fontSize,
            fontColor: hoverItem.fontColor,
            fontWeight: hoverItem.fontWeight,
            fontStyle: hoverItem.fontStyle,
            fontVariant: hoverItem.fontVariant,
            nameLength: hoverItem.nameLength,
            textAlign: hoverItem.textAlign,
            // filler to make createHoverText happy
            trace: hoverItem.trace || {
              index: 0,
              hoverinfo: ""
            },
            xa: { _offset: 0 },
            ya: { _offset: 0 },
            index: 0,
            hovertemplate: hoverItem.hovertemplate || false,
            hovertemplateLabels: hoverItem.hovertemplateLabels || false,
            eventData
          };
        });
        var rotateLabels = false;
        var hoverText = createHoverText(pointsData, {
          gd,
          hovermode: "closest",
          rotateLabels,
          bgColor: opts.bgColor || Color2.background,
          container: d3.select(opts.container),
          outerContainer: opts.outerContainer || opts.container
        });
        var hoverLabel = hoverText.hoverLabels;
        var tooltipSpacing = 5;
        var lastBottomY = 0;
        var anchor = 0;
        hoverLabel.sort(function(a, b) {
          return a.y0 - b.y0;
        }).each(function(d, i) {
          var topY = d.y0 - d.by / 2;
          if (topY - tooltipSpacing < lastBottomY) {
            d.offset = lastBottomY - topY + tooltipSpacing;
          } else {
            d.offset = 0;
          }
          lastBottomY = topY + d.by + d.offset;
          if (i === opts.anchorIndex || 0) anchor = d.offset;
        }).each(function(d) {
          d.offset -= anchor;
        });
        var scaleX = gd._fullLayout._invScaleX;
        var scaleY = gd._fullLayout._invScaleY;
        alignHoverText(hoverLabel, rotateLabels, scaleX, scaleY);
        return multiHover ? hoverLabel : hoverLabel.node();
      };
      function _hover(gd, evt, subplot, noHoverEvent, eventTarget) {
        if (!subplot) subplot = "xy";
        if (typeof subplot === "string") {
          subplot = subplot.split(zindexSeparator)[0];
        }
        var subplots = Array.isArray(subplot) ? subplot : [subplot];
        var spId;
        var fullLayout = gd._fullLayout;
        var hoversubplots = fullLayout.hoversubplots;
        var plots = fullLayout._plots || [];
        var plotinfo = plots[subplot];
        var hasCartesian = fullLayout._has("cartesian");
        var hovermode = evt.hovermode || fullLayout.hovermode;
        var hovermodeHasX = (hovermode || "").charAt(0) === "x";
        var hovermodeHasY = (hovermode || "").charAt(0) === "y";
        var firstXaxis;
        var firstYaxis;
        if (hasCartesian && (hovermodeHasX || hovermodeHasY) && hoversubplots === "axis") {
          var subplotsLength = subplots.length;
          for (var p = 0; p < subplotsLength; p++) {
            spId = subplots[p];
            if (plots[spId]) {
              firstXaxis = Axes.getFromId(gd, spId, "x");
              firstYaxis = Axes.getFromId(gd, spId, "y");
              var subplotsWith = (hovermodeHasX ? firstXaxis : firstYaxis)._subplotsWith;
              if (subplotsWith && subplotsWith.length) {
                for (var q = 0; q < subplotsWith.length; q++) {
                  pushUnique(subplots, subplotsWith[q]);
                }
              }
            }
          }
        }
        if (plotinfo && hoversubplots !== "single") {
          var overlayedSubplots = plotinfo.overlays.map(function(pi) {
            return pi.id;
          });
          subplots = subplots.concat(overlayedSubplots);
        }
        var len = subplots.length;
        var xaArray = new Array(len);
        var yaArray = new Array(len);
        var supportsCompare = false;
        for (var i = 0; i < len; i++) {
          spId = subplots[i];
          if (plots[spId]) {
            supportsCompare = true;
            xaArray[i] = plots[spId].xaxis;
            yaArray[i] = plots[spId].yaxis;
          } else if (fullLayout[spId] && fullLayout[spId]._subplot) {
            var _subplot = fullLayout[spId]._subplot;
            xaArray[i] = _subplot.xaxis;
            yaArray[i] = _subplot.yaxis;
          } else {
            Lib.warn("Unrecognized subplot: " + spId);
            return;
          }
        }
        if (hovermode && !supportsCompare) hovermode = "closest";
        if (["x", "y", "closest", "x unified", "y unified"].indexOf(hovermode) === -1 || !gd.calcdata || gd.querySelector(".zoombox") || gd._dragging) {
          return dragElement.unhoverRaw(gd, evt);
        }
        var hoverdistance = fullLayout.hoverdistance;
        if (hoverdistance === -1) hoverdistance = Infinity;
        var spikedistance = fullLayout.spikedistance;
        if (spikedistance === -1) spikedistance = Infinity;
        var hoverData = [];
        var searchData = [];
        var xvalArray, yvalArray;
        var itemnum, curvenum, cd, trace, subplotId, subploti, _mode, xval, yval, pointData, closedataPreviousLength;
        var spikePoints = {
          hLinePoint: null,
          vLinePoint: null
        };
        var hasOneHorizontalTrace = false;
        if (Array.isArray(evt)) {
          hovermode = "array";
          for (itemnum = 0; itemnum < evt.length; itemnum++) {
            cd = gd.calcdata[evt[itemnum].curveNumber || 0];
            if (cd) {
              trace = cd[0].trace;
              if (cd[0].trace.hoverinfo !== "skip") {
                searchData.push(cd);
                if (trace.orientation === "h") {
                  hasOneHorizontalTrace = true;
                }
              }
            }
          }
        } else {
          var zorderedCalcdata = gd.calcdata.slice();
          zorderedCalcdata.sort(function(a, b) {
            var aZorder = a[0].trace.zorder || 0;
            var bZorder = b[0].trace.zorder || 0;
            return aZorder - bZorder;
          });
          for (curvenum = 0; curvenum < zorderedCalcdata.length; curvenum++) {
            cd = zorderedCalcdata[curvenum];
            trace = cd[0].trace;
            if (trace.hoverinfo !== "skip" && helpers.isTraceInSubplots(trace, subplots)) {
              searchData.push(cd);
              if (trace.orientation === "h") {
                hasOneHorizontalTrace = true;
              }
            }
          }
          var hasUserCalledHover = !eventTarget;
          var xpx, ypx;
          if (hasUserCalledHover) {
            if ("xpx" in evt) xpx = evt.xpx;
            else xpx = xaArray[0]._length / 2;
            if ("ypx" in evt) ypx = evt.ypx;
            else ypx = yaArray[0]._length / 2;
          } else {
            if (Events.triggerHandler(gd, "plotly_beforehover", evt) === false) {
              return;
            }
            var dbb = eventTarget.getBoundingClientRect();
            xpx = evt.clientX - dbb.left;
            ypx = evt.clientY - dbb.top;
            fullLayout._calcInverseTransform(gd);
            var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(xpx, ypx);
            xpx = transformedCoords[0];
            ypx = transformedCoords[1];
            if (xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
              return dragElement.unhoverRaw(gd, evt);
            }
          }
          evt.pointerX = xpx + xaArray[0]._offset;
          evt.pointerY = ypx + yaArray[0]._offset;
          if ("xval" in evt) xvalArray = helpers.flat(subplots, evt.xval);
          else xvalArray = helpers.p2c(xaArray, xpx);
          if ("yval" in evt) yvalArray = helpers.flat(subplots, evt.yval);
          else yvalArray = helpers.p2c(yaArray, ypx);
          if (!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
            Lib.warn("Fx.hover failed", evt, gd);
            return dragElement.unhoverRaw(gd, evt);
          }
        }
        var distance = Infinity;
        function findHoverPoints(customXVal, customYVal) {
          for (curvenum = 0; curvenum < searchData.length; curvenum++) {
            cd = searchData[curvenum];
            if (!cd || !cd[0] || !cd[0].trace) continue;
            trace = cd[0].trace;
            if (trace.visible !== true || trace._length === 0) continue;
            if (["carpet", "contourcarpet"].indexOf(trace._module.name) !== -1) continue;
            _mode = hovermode;
            if (helpers.isUnifiedHover(_mode)) {
              _mode = _mode.charAt(0);
            }
            if (trace.type === "splom") {
              subploti = 0;
              subplotId = subplots[subploti];
            } else {
              subplotId = helpers.getSubplot(trace);
              subploti = subplots.indexOf(subplotId);
            }
            pointData = {
              // trace properties
              cd,
              trace,
              xa: xaArray[subploti],
              ya: yaArray[subploti],
              // max distances for hover and spikes - for points that want to show but do not
              // want to override other points, set distance/spikeDistance equal to max*Distance
              // and it will not get filtered out but it will be guaranteed to have a greater
              // distance than any point that calculated a real distance.
              maxHoverDistance: hoverdistance,
              maxSpikeDistance: spikedistance,
              // point properties - override all of these
              index: false,
              // point index in trace - only used by plotly.js hoverdata consumers
              distance: Math.min(distance, hoverdistance),
              // pixel distance or pseudo-distance
              // distance/pseudo-distance for spikes. This distance should always be calculated
              // as if in "closest" mode, and should only be set if this point should
              // generate a spike.
              spikeDistance: Infinity,
              // in some cases the spikes have different positioning from the hover label
              // they don't need x0/x1, just one position
              xSpike: void 0,
              ySpike: void 0,
              // where and how to display the hover label
              color: Color2.defaultLine,
              // trace color
              name: trace.name,
              x0: void 0,
              x1: void 0,
              y0: void 0,
              y1: void 0,
              xLabelVal: void 0,
              yLabelVal: void 0,
              zLabelVal: void 0,
              text: void 0
            };
            if (fullLayout[subplotId]) {
              pointData.subplot = fullLayout[subplotId]._subplot;
            }
            if (fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) {
              pointData.scene = fullLayout._splomScenes[trace.uid];
            }
            if (_mode === "array") {
              var selection = evt[curvenum];
              if ("pointNumber" in selection) {
                pointData.index = selection.pointNumber;
                _mode = "closest";
              } else {
                _mode = "";
                if ("xval" in selection) {
                  xval = selection.xval;
                  _mode = "x";
                }
                if ("yval" in selection) {
                  yval = selection.yval;
                  _mode = _mode ? "closest" : "y";
                }
              }
            } else if (customXVal !== void 0 && customYVal !== void 0) {
              xval = customXVal;
              yval = customYVal;
            } else {
              xval = xvalArray[subploti];
              yval = yvalArray[subploti];
            }
            closedataPreviousLength = hoverData.length;
            if (hoverdistance !== 0) {
              if (trace._module && trace._module.hoverPoints) {
                var newPoints = trace._module.hoverPoints(pointData, xval, yval, _mode, {
                  finiteRange: true,
                  hoverLayer: fullLayout._hoverlayer,
                  // options for splom when hovering on same axis
                  hoversubplots,
                  gd
                });
                if (newPoints) {
                  var newPoint;
                  for (var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
                    newPoint = newPoints[newPointNum];
                    if (isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
                      hoverData.push(cleanPoint(newPoint, hovermode));
                    }
                  }
                }
              } else {
                Lib.log("Unrecognized trace type in hover:", trace);
              }
            }
            if (hovermode === "closest" && hoverData.length > closedataPreviousLength) {
              hoverData.splice(0, closedataPreviousLength);
              distance = hoverData[0].distance;
            }
            if (hasCartesian && spikedistance !== 0) {
              if (hoverData.length === 0) {
                pointData.distance = spikedistance;
                pointData.index = false;
                var closestPoints = trace._module.hoverPoints(pointData, xval, yval, "closest", {
                  hoverLayer: fullLayout._hoverlayer
                });
                if (closestPoints) {
                  closestPoints = closestPoints.filter(function(point) {
                    return point.spikeDistance <= spikedistance;
                  });
                }
                if (closestPoints && closestPoints.length) {
                  var tmpPoint;
                  var closestVPoints = closestPoints.filter(function(point) {
                    return point.xa.showspikes && point.xa.spikesnap !== "hovered data";
                  });
                  if (closestVPoints.length) {
                    var closestVPt = closestVPoints[0];
                    if (isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
                      tmpPoint = fillSpikePoint(closestVPt);
                      if (!spikePoints.vLinePoint || spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance) {
                        spikePoints.vLinePoint = tmpPoint;
                      }
                    }
                  }
                  var closestHPoints = closestPoints.filter(function(point) {
                    return point.ya.showspikes && point.ya.spikesnap !== "hovered data";
                  });
                  if (closestHPoints.length) {
                    var closestHPt = closestHPoints[0];
                    if (isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
                      tmpPoint = fillSpikePoint(closestHPt);
                      if (!spikePoints.hLinePoint || spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance) {
                        spikePoints.hLinePoint = tmpPoint;
                      }
                    }
                  }
                }
              }
            }
          }
        }
        findHoverPoints();
        function selectClosestPoint(pointsData, spikedistance2, spikeOnWinning2) {
          var resultPoint = null;
          var minDistance = Infinity;
          var thisSpikeDistance;
          for (var i2 = 0; i2 < pointsData.length; i2++) {
            if (firstXaxis && firstXaxis._id !== pointsData[i2].xa._id) continue;
            if (firstYaxis && firstYaxis._id !== pointsData[i2].ya._id) continue;
            thisSpikeDistance = pointsData[i2].spikeDistance;
            if (spikeOnWinning2 && i2 === 0) thisSpikeDistance = -Infinity;
            if (thisSpikeDistance <= minDistance && thisSpikeDistance <= spikedistance2) {
              resultPoint = pointsData[i2];
              minDistance = thisSpikeDistance;
            }
          }
          return resultPoint;
        }
        function fillSpikePoint(point) {
          if (!point) return null;
          return {
            xa: point.xa,
            ya: point.ya,
            x: point.xSpike !== void 0 ? point.xSpike : (point.x0 + point.x1) / 2,
            y: point.ySpike !== void 0 ? point.ySpike : (point.y0 + point.y1) / 2,
            distance: point.distance,
            spikeDistance: point.spikeDistance,
            curveNumber: point.trace.index,
            color: point.color,
            pointNumber: point.index
          };
        }
        var spikelineOpts = {
          fullLayout,
          container: fullLayout._hoverlayer,
          event: evt
        };
        var oldspikepoints = gd._spikepoints;
        var newspikepoints = {
          vLinePoint: spikePoints.vLinePoint,
          hLinePoint: spikePoints.hLinePoint
        };
        gd._spikepoints = newspikepoints;
        var sortHoverData = function() {
          var hoverDataInSubplot = hoverData.filter(function(a) {
            return firstXaxis && firstXaxis._id === a.xa._id && firstYaxis && firstYaxis._id === a.ya._id;
          });
          var hoverDataOutSubplot = hoverData.filter(function(a) {
            return !(firstXaxis && firstXaxis._id === a.xa._id && firstYaxis && firstYaxis._id === a.ya._id);
          });
          hoverDataInSubplot.sort(distanceSort);
          hoverDataOutSubplot.sort(distanceSort);
          hoverData = hoverDataInSubplot.concat(hoverDataOutSubplot);
          hoverData = orderRangePoints(hoverData, hovermode);
        };
        sortHoverData();
        var axLetter = hovermode.charAt(0);
        var spikeOnWinning = (axLetter === "x" || axLetter === "y") && hoverData[0] && cartesianScatterPoints[hoverData[0].trace.type];
        if (hasCartesian && spikedistance !== 0) {
          if (hoverData.length !== 0) {
            var tmpHPointData = hoverData.filter(function(point) {
              return point.ya.showspikes;
            });
            var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance, spikeOnWinning);
            spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);
            var tmpVPointData = hoverData.filter(function(point) {
              return point.xa.showspikes;
            });
            var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance, spikeOnWinning);
            spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
          }
        }
        if (hoverData.length === 0) {
          var result = dragElement.unhoverRaw(gd, evt);
          if (hasCartesian && (spikePoints.hLinePoint !== null || spikePoints.vLinePoint !== null)) {
            if (spikesChanged(oldspikepoints)) {
              createSpikelines(gd, spikePoints, spikelineOpts);
            }
          }
          return result;
        }
        if (hasCartesian) {
          if (spikesChanged(oldspikepoints)) {
            createSpikelines(gd, spikePoints, spikelineOpts);
          }
        }
        if (helpers.isXYhover(_mode) && hoverData[0].length !== 0 && hoverData[0].trace.type !== "splom") {
          var winningPoint = hoverData[0];
          if (multipleHoverPoints[winningPoint.trace.type]) {
            hoverData = hoverData.filter((d) => d.trace.index === winningPoint.trace.index);
          } else {
            hoverData = [winningPoint];
          }
          var initLen = hoverData.length;
          var winX = getCoord("x", winningPoint, fullLayout);
          var winY = getCoord("y", winningPoint, fullLayout);
          findHoverPoints(winX, winY);
          var finalPoints = [];
          var seen = {};
          var id = 0;
          var insert = function(newHd) {
            var key = multipleHoverPoints[newHd.trace.type] ? hoverDataKey(newHd) : newHd.trace.index;
            if (!seen[key]) {
              id++;
              seen[key] = id;
              finalPoints.push(newHd);
            } else {
              var oldId = seen[key] - 1;
              var oldHd = finalPoints[oldId];
              if (oldId > 0 && Math.abs(newHd.distance) < Math.abs(oldHd.distance)) {
                finalPoints[oldId] = newHd;
              }
            }
          };
          var k;
          for (k = 0; k < initLen; k++) {
            insert(hoverData[k]);
          }
          for (k = hoverData.length - 1; k > initLen - 1; k--) {
            insert(hoverData[k]);
          }
          hoverData = finalPoints;
          sortHoverData();
        }
        var oldhoverdata = gd._hoverdata;
        var newhoverdata = [];
        var gTop = getTopOffset(gd);
        var gLeft = getLeftOffset(gd);
        for (const pt of hoverData) {
          var eventData = helpers.makeEventData(pt, pt.trace, pt.cd);
          if (pt.hovertemplate !== false) {
            var ht = false;
            if (pt.cd[pt.index] && pt.cd[pt.index].ht) {
              ht = pt.cd[pt.index].ht;
            }
            pt.hovertemplate = ht || pt.trace.hovertemplate || false;
          }
          if (pt.xa && pt.ya) {
            var _x0 = pt.x0 + pt.xa._offset;
            var _x1 = pt.x1 + pt.xa._offset;
            var _y0 = pt.y0 + pt.ya._offset;
            var _y1 = pt.y1 + pt.ya._offset;
            var x0 = Math.min(_x0, _x1);
            var x1 = Math.max(_x0, _x1);
            var y0 = Math.min(_y0, _y1);
            var y1 = Math.max(_y0, _y1);
            eventData.bbox = {
              x0: x0 + gLeft,
              x1: x1 + gLeft,
              y0: y0 + gTop,
              y1: y1 + gTop
            };
          }
          pt.eventData = [eventData];
          newhoverdata.push(eventData);
        }
        gd._hoverdata = newhoverdata;
        var rotateLabels = hovermode === "y" && (searchData.length > 1 || hoverData.length > 1) || hovermode === "closest" && hasOneHorizontalTrace && hoverData.length > 1;
        var bgColor = Color2.combine(fullLayout.plot_bgcolor || Color2.background, fullLayout.paper_bgcolor);
        var hoverText = createHoverText(hoverData, {
          gd,
          hovermode,
          rotateLabels,
          bgColor,
          container: fullLayout._hoverlayer,
          outerContainer: fullLayout._paper.node(),
          commonLabelOpts: fullLayout.hoverlabel,
          hoverdistance: fullLayout.hoverdistance
        });
        var hoverLabels = hoverText.hoverLabels;
        if (!helpers.isUnifiedHover(hovermode)) {
          hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, hoverText.commonLabelBoundingBox);
          alignHoverText(hoverLabels, rotateLabels, fullLayout._invScaleX, fullLayout._invScaleY);
        }
        if (eventTarget && eventTarget.tagName) {
          var hasClickToShow = Registry.getComponentMethod("annotations", "hasClickToShow")(gd, newhoverdata);
          overrideCursor(d3.select(eventTarget), hasClickToShow ? "pointer" : "");
        }
        if (!eventTarget || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;
        if (oldhoverdata) {
          gd.emit("plotly_unhover", {
            event: evt,
            points: oldhoverdata
          });
        }
        gd.emit("plotly_hover", {
          event: evt,
          points: gd._hoverdata,
          xaxes: xaArray,
          yaxes: yaArray,
          xvals: xvalArray,
          yvals: yvalArray
        });
      }
      function hoverDataKey(d) {
        return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa ? d.xa._id : "", d.ya ? d.ya._id : ""].join(",");
      }
      var EXTRA_STRING_REGEX = /<extra>([\s\S]*)<\/extra>/;
      function createHoverText(hoverData, opts) {
        var gd = opts.gd;
        var fullLayout = gd._fullLayout;
        var hovermode = opts.hovermode;
        var rotateLabels = opts.rotateLabels;
        var bgColor = opts.bgColor;
        var container = opts.container;
        var outerContainer = opts.outerContainer;
        var commonLabelOpts = opts.commonLabelOpts || {};
        if (hoverData.length === 0) return [[]];
        var fontFamily = opts.fontFamily || constants.HOVERFONT;
        var fontSize = opts.fontSize || constants.HOVERFONTSIZE;
        var fontWeight = opts.fontWeight || fullLayout.font.weight;
        var fontStyle = opts.fontStyle || fullLayout.font.style;
        var fontVariant = opts.fontVariant || fullLayout.font.variant;
        var fontTextcase = opts.fontTextcase || fullLayout.font.textcase;
        var fontLineposition = opts.fontLineposition || fullLayout.font.lineposition;
        var fontShadow = opts.fontShadow || fullLayout.font.shadow;
        var c0 = hoverData[0];
        var xa = c0.xa;
        var ya = c0.ya;
        var axLetter = hovermode.charAt(0);
        var axLabel = axLetter + "Label";
        var t02 = c0[axLabel];
        if (t02 === void 0 && xa.type === "multicategory") {
          for (var q = 0; q < hoverData.length; q++) {
            t02 = hoverData[q][axLabel];
            if (t02 !== void 0) break;
          }
        }
        var outerContainerBB = getBoundingClientRect(gd, outerContainer);
        var outerTop = outerContainerBB.top;
        var outerWidth = outerContainerBB.width;
        var outerHeight = outerContainerBB.height;
        var showCommonLabel = t02 !== void 0 && c0.distance <= opts.hoverdistance && (hovermode === "x" || hovermode === "y");
        if (showCommonLabel) {
          var allHaveZ = true;
          var i, traceHoverinfo;
          for (i = 0; i < hoverData.length; i++) {
            if (allHaveZ && hoverData[i].zLabel === void 0) allHaveZ = false;
            traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
            if (traceHoverinfo) {
              var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split("+");
              if (parts.indexOf("all") === -1 && parts.indexOf(hovermode) === -1) {
                showCommonLabel = false;
                break;
              }
            }
          }
          if (allHaveZ) showCommonLabel = false;
        }
        var commonLabel = container.selectAll("g.axistext").data(showCommonLabel ? [0] : []);
        commonLabel.enter().append("g").classed("axistext", true);
        commonLabel.exit().remove();
        var commonLabelRect = {
          minX: 0,
          maxX: 0,
          minY: 0,
          maxY: 0
        };
        commonLabel.each(function() {
          var label = d3.select(this);
          var lpath = Lib.ensureSingle(label, "path", "", function(s) {
            s.style({ "stroke-width": "1px" });
          });
          var ltext = Lib.ensureSingle(label, "text", "", function(s) {
            s.attr("data-notex", 1);
          });
          var commonBgColor = commonLabelOpts.bgcolor || Color2.defaultLine;
          var commonStroke = commonLabelOpts.bordercolor || Color2.contrast(commonBgColor);
          var contrastColor = Color2.contrast(commonBgColor);
          var commonLabelOptsFont = commonLabelOpts.font;
          var commonLabelFont = {
            weight: commonLabelOptsFont.weight || fontWeight,
            style: commonLabelOptsFont.style || fontStyle,
            variant: commonLabelOptsFont.variant || fontVariant,
            textcase: commonLabelOptsFont.textcase || fontTextcase,
            lineposition: commonLabelOptsFont.lineposition || fontLineposition,
            shadow: commonLabelOptsFont.shadow || fontShadow,
            family: commonLabelOptsFont.family || fontFamily,
            size: commonLabelOptsFont.size || fontSize,
            color: commonLabelOptsFont.color || contrastColor
          };
          lpath.style({
            fill: commonBgColor,
            stroke: commonStroke
          });
          ltext.text(t02).call(Drawing.font, commonLabelFont).call(svgTextUtils.positionText, 0, 0).call(svgTextUtils.convertToTspans, gd);
          label.attr("transform", "");
          var tbb2 = getBoundingClientRect(gd, ltext.node());
          var lx2, ly2;
          if (hovermode === "x") {
            var topsign = xa.side === "top" ? "-" : "";
            ltext.attr("text-anchor", "middle").call(
              svgTextUtils.positionText,
              0,
              xa.side === "top" ? outerTop - tbb2.bottom - HOVERARROWSIZE - HOVERTEXTPAD : outerTop - tbb2.top + HOVERARROWSIZE + HOVERTEXTPAD
            );
            lx2 = xa._offset + (c0.x0 + c0.x1) / 2;
            ly2 = ya._offset + (xa.side === "top" ? 0 : ya._length);
            var halfWidth = tbb2.width / 2 + HOVERTEXTPAD;
            var tooltipMidX = lx2;
            if (lx2 < halfWidth) {
              tooltipMidX = halfWidth;
            } else if (lx2 > fullLayout.width - halfWidth) {
              tooltipMidX = fullLayout.width - halfWidth;
            }
            lpath.attr(
              "d",
              "M" + (lx2 - tooltipMidX) + ",0L" + (lx2 - tooltipMidX + HOVERARROWSIZE) + "," + topsign + HOVERARROWSIZE + "H" + halfWidth + "v" + topsign + (HOVERTEXTPAD * 2 + tbb2.height) + "H" + -halfWidth + "V" + topsign + HOVERARROWSIZE + "H" + (lx2 - tooltipMidX - HOVERARROWSIZE) + "Z"
            );
            lx2 = tooltipMidX;
            commonLabelRect.minX = lx2 - halfWidth;
            commonLabelRect.maxX = lx2 + halfWidth;
            if (xa.side === "top") {
              commonLabelRect.minY = ly2 - (HOVERTEXTPAD * 2 + tbb2.height);
              commonLabelRect.maxY = ly2 - HOVERTEXTPAD;
            } else {
              commonLabelRect.minY = ly2 + HOVERTEXTPAD;
              commonLabelRect.maxY = ly2 + (HOVERTEXTPAD * 2 + tbb2.height);
            }
          } else {
            var anchor;
            var sgn;
            var leftsign;
            if (ya.side === "right") {
              anchor = "start";
              sgn = 1;
              leftsign = "";
              lx2 = xa._offset + xa._length;
            } else {
              anchor = "end";
              sgn = -1;
              leftsign = "-";
              lx2 = xa._offset;
            }
            ly2 = ya._offset + (c0.y0 + c0.y1) / 2;
            ltext.attr("text-anchor", anchor);
            lpath.attr(
              "d",
              "M0,0L" + leftsign + HOVERARROWSIZE + "," + HOVERARROWSIZE + "V" + (HOVERTEXTPAD + tbb2.height / 2) + "h" + leftsign + (HOVERTEXTPAD * 2 + tbb2.width) + "V-" + (HOVERTEXTPAD + tbb2.height / 2) + "H" + leftsign + HOVERARROWSIZE + "V-" + HOVERARROWSIZE + "Z"
            );
            commonLabelRect.minY = ly2 - (HOVERTEXTPAD + tbb2.height / 2);
            commonLabelRect.maxY = ly2 + (HOVERTEXTPAD + tbb2.height / 2);
            if (ya.side === "right") {
              commonLabelRect.minX = lx2 + HOVERARROWSIZE;
              commonLabelRect.maxX = lx2 + HOVERARROWSIZE + (HOVERTEXTPAD * 2 + tbb2.width);
            } else {
              commonLabelRect.minX = lx2 - HOVERARROWSIZE - (HOVERTEXTPAD * 2 + tbb2.width);
              commonLabelRect.maxX = lx2 - HOVERARROWSIZE;
            }
            var halfHeight = tbb2.height / 2;
            var lty = outerTop - tbb2.top - halfHeight;
            var clipId = "clip" + fullLayout._uid + "commonlabel" + ya._id;
            var clipPath;
            if (lx2 < tbb2.width + 2 * HOVERTEXTPAD + HOVERARROWSIZE) {
              clipPath = "M-" + (HOVERARROWSIZE + HOVERTEXTPAD) + "-" + halfHeight + "h-" + (tbb2.width - HOVERTEXTPAD) + "V" + halfHeight + "h" + (tbb2.width - HOVERTEXTPAD) + "Z";
              var ltx = tbb2.width - lx2 + HOVERTEXTPAD;
              svgTextUtils.positionText(ltext, ltx, lty);
              if (anchor === "end") {
                ltext.selectAll("tspan").each(function() {
                  var s = d3.select(this);
                  var dummy = Drawing.tester.append("text").text(s.text()).call(Drawing.font, commonLabelFont);
                  var dummyBB = getBoundingClientRect(gd, dummy.node());
                  if (Math.round(dummyBB.width) < Math.round(tbb2.width)) {
                    s.attr("x", ltx - dummyBB.width);
                  }
                  dummy.remove();
                });
              }
            } else {
              svgTextUtils.positionText(ltext, sgn * (HOVERTEXTPAD + HOVERARROWSIZE), lty);
              clipPath = null;
            }
            var textClip = fullLayout._topclips.selectAll("#" + clipId).data(clipPath ? [0] : []);
            textClip.enter().append("clipPath").attr("id", clipId).append("path");
            textClip.exit().remove();
            textClip.select("path").attr("d", clipPath);
            Drawing.setClipUrl(ltext, clipPath ? clipId : null, gd);
          }
          label.attr("transform", strTranslate(lx2, ly2));
        });
        if (helpers.isUnifiedHover(hovermode)) {
          container.selectAll("g.hovertext").remove();
          const groupedHoverData = hoverData.filter((data) => data.hoverinfo !== "none");
          if (groupedHoverData.length === 0) return [];
          var hoverlabel = fullLayout.hoverlabel;
          var font = hoverlabel.font;
          var item0 = groupedHoverData[0];
          var unifiedhovertitleText = ((hovermode === "x unified" ? item0.xa : item0.ya).unifiedhovertitle || {}).text;
          var mainText = !unifiedhovertitleText ? t02 : Lib.hovertemplateString({
            data: hovermode === "x unified" ? [{ xa: item0.xa, x: item0.xVal }] : [{ ya: item0.ya, y: item0.yVal }],
            fallback: item0.trace.hovertemplatefallback,
            locale: fullLayout._d3locale,
            template: unifiedhovertitleText
          });
          var mockLayoutIn = {
            showlegend: true,
            legend: {
              title: { text: mainText, font },
              font,
              bgcolor: hoverlabel.bgcolor,
              bordercolor: hoverlabel.bordercolor,
              borderwidth: 1,
              tracegroupgap: 7,
              traceorder: fullLayout.legend ? fullLayout.legend.traceorder : void 0,
              orientation: "v"
            }
          };
          var mockLayoutOut = {
            font
          };
          legendSupplyDefaults(mockLayoutIn, mockLayoutOut, gd._fullData);
          var mockLegend = mockLayoutOut.legend;
          mockLegend.entries = [];
          for (var j = 0; j < groupedHoverData.length; j++) {
            var pt = groupedHoverData[j];
            if (pt.hoverinfo === "none") continue;
            var texts = getHoverLabelText(pt, true, hovermode, fullLayout, t02);
            var text = texts[0];
            var name2 = texts[1];
            pt.name = name2;
            if (name2 !== "") {
              pt.text = name2 + " : " + text;
            } else {
              pt.text = text;
            }
            var cd = pt.cd[pt.index];
            if (cd) {
              if (cd.mc) pt.mc = cd.mc;
              if (cd.mcc) pt.mc = cd.mcc;
              if (cd.mlc) pt.mlc = cd.mlc;
              if (cd.mlcc) pt.mlc = cd.mlcc;
              if (cd.mlw) pt.mlw = cd.mlw;
              if (cd.mrc) pt.mrc = cd.mrc;
              if (cd.dir) pt.dir = cd.dir;
            }
            pt._distinct = true;
            mockLegend.entries.push([pt]);
          }
          mockLegend.entries.sort(function(a, b) {
            return a[0].trace.index - b[0].trace.index;
          });
          mockLegend.layer = container;
          mockLegend._inHover = true;
          mockLegend._groupTitleFont = hoverlabel.grouptitlefont;
          legendDraw(gd, mockLegend);
          var legendContainer = container.select("g.legend");
          var tbb = getBoundingClientRect(gd, legendContainer.node());
          var tWidth = tbb.width + 2 * HOVERTEXTPAD;
          var tHeight = tbb.height + 2 * HOVERTEXTPAD;
          var winningPoint = groupedHoverData[0];
          var avgX = (winningPoint.x0 + winningPoint.x1) / 2;
          var avgY = (winningPoint.y0 + winningPoint.y1) / 2;
          var pointWon = !(Registry.traceIs(winningPoint.trace, "bar-like") || Registry.traceIs(winningPoint.trace, "box-violin"));
          var lyBottom, lyTop;
          if (axLetter === "y") {
            if (pointWon) {
              lyTop = avgY - HOVERTEXTPAD;
              lyBottom = avgY + HOVERTEXTPAD;
            } else {
              lyTop = Math.min.apply(
                null,
                groupedHoverData.map(function(c) {
                  return Math.min(c.y0, c.y1);
                })
              );
              lyBottom = Math.max.apply(
                null,
                groupedHoverData.map(function(c) {
                  return Math.max(c.y0, c.y1);
                })
              );
            }
          } else {
            lyTop = lyBottom = Lib.mean(
              groupedHoverData.map(function(c) {
                return (c.y0 + c.y1) / 2;
              })
            ) - tHeight / 2;
          }
          var lxRight, lxLeft;
          if (axLetter === "x") {
            if (pointWon) {
              lxRight = avgX + HOVERTEXTPAD;
              lxLeft = avgX - HOVERTEXTPAD;
            } else {
              lxRight = Math.max.apply(
                null,
                groupedHoverData.map(function(c) {
                  return Math.max(c.x0, c.x1);
                })
              );
              lxLeft = Math.min.apply(
                null,
                groupedHoverData.map(function(c) {
                  return Math.min(c.x0, c.x1);
                })
              );
            }
          } else {
            lxRight = lxLeft = Lib.mean(
              groupedHoverData.map(function(c) {
                return (c.x0 + c.x1) / 2;
              })
            ) - tWidth / 2;
          }
          var xOffset = xa._offset;
          var yOffset = ya._offset;
          lyBottom += yOffset;
          lxRight += xOffset;
          lxLeft += xOffset - tWidth;
          lyTop += yOffset - tHeight;
          var lx, ly;
          if (lxRight + tWidth < outerWidth && lxRight >= 0) {
            lx = lxRight;
          } else if (lxLeft + tWidth < outerWidth && lxLeft >= 0) {
            lx = lxLeft;
          } else if (xOffset + tWidth < outerWidth) {
            lx = xOffset;
          } else {
            if (lxRight - avgX < avgX - lxLeft + tWidth) {
              lx = outerWidth - tWidth;
            } else {
              lx = 0;
            }
          }
          lx += HOVERTEXTPAD;
          if (lyBottom + tHeight < outerHeight && lyBottom >= 0) {
            ly = lyBottom;
          } else if (lyTop + tHeight < outerHeight && lyTop >= 0) {
            ly = lyTop;
          } else if (yOffset + tHeight < outerHeight) {
            ly = yOffset;
          } else {
            if (lyBottom - avgY < avgY - lyTop + tHeight) {
              ly = outerHeight - tHeight;
            } else {
              ly = 0;
            }
          }
          ly += HOVERTEXTPAD;
          legendContainer.attr("transform", strTranslate(lx - 1, ly - 1));
          return legendContainer;
        }
        var hoverLabels = container.selectAll("g.hovertext").data(hoverData, function(d) {
          return hoverDataKey(d);
        });
        hoverLabels.enter().append("g").classed("hovertext", true).each(function() {
          var g = d3.select(this);
          g.append("rect").call(Color2.fill, Color2.addOpacity(bgColor, 0.8));
          g.append("text").classed("name", true);
          g.append("path").style("stroke-width", "1px");
          g.append("text").classed("nums", true).call(Drawing.font, {
            weight: fontWeight,
            style: fontStyle,
            variant: fontVariant,
            textcase: fontTextcase,
            lineposition: fontLineposition,
            shadow: fontShadow,
            family: fontFamily,
            size: fontSize
          });
        });
        hoverLabels.exit().remove();
        hoverLabels.each(function(d) {
          var g = d3.select(this).attr("transform", "");
          var dColor = d.color;
          if (Array.isArray(dColor)) {
            dColor = dColor[d.eventData[0].pointNumber];
          }
          var color0 = d.bgcolor || dColor;
          var numsColor = Color2.combine(Color2.opacity(color0) ? color0 : Color2.defaultLine, bgColor);
          var nameColor = Color2.combine(Color2.opacity(dColor) ? dColor : Color2.defaultLine, bgColor);
          var contrastColor = d.borderColor || Color2.contrast(numsColor);
          var texts2 = getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t02, g);
          var text2 = texts2[0];
          var name3 = texts2[1];
          var tx = g.select("text.nums").call(Drawing.font, {
            family: d.fontFamily || fontFamily,
            size: d.fontSize || fontSize,
            color: d.fontColor || contrastColor,
            weight: d.fontWeight || fontWeight,
            style: d.fontStyle || fontStyle,
            variant: d.fontVariant || fontVariant,
            textcase: d.fontTextcase || fontTextcase,
            lineposition: d.fontLineposition || fontLineposition,
            shadow: d.fontShadow || fontShadow
          }).text(text2).attr("data-notex", 1).call(svgTextUtils.positionText, 0, 0).call(svgTextUtils.convertToTspans, gd);
          var tx2 = g.select("text.name");
          var tx2width = 0;
          var tx2height = 0;
          if (name3 && name3 !== text2) {
            tx2.call(Drawing.font, {
              family: d.fontFamily || fontFamily,
              size: d.fontSize || fontSize,
              color: nameColor,
              weight: d.fontWeight || fontWeight,
              style: d.fontStyle || fontStyle,
              variant: d.fontVariant || fontVariant,
              textcase: d.fontTextcase || fontTextcase,
              lineposition: d.fontLineposition || fontLineposition,
              shadow: d.fontShadow || fontShadow
            }).text(name3).attr("data-notex", 1).call(svgTextUtils.positionText, 0, 0).call(svgTextUtils.convertToTspans, gd);
            var t2bb = getBoundingClientRect(gd, tx2.node());
            tx2width = t2bb.width + 2 * HOVERTEXTPAD;
            tx2height = t2bb.height + 2 * HOVERTEXTPAD;
          } else {
            tx2.remove();
            g.select("rect").remove();
          }
          g.select("path").style({
            fill: numsColor,
            stroke: contrastColor
          });
          var htx = d.xa._offset + (d.x0 + d.x1) / 2;
          var hty = d.ya._offset + (d.y0 + d.y1) / 2;
          var dx = Math.abs(d.x1 - d.x0);
          var dy = Math.abs(d.y1 - d.y0);
          var tbb2 = getBoundingClientRect(gd, tx.node());
          var tbbWidth = tbb2.width / fullLayout._invScaleX;
          var tbbHeight = tbb2.height / fullLayout._invScaleY;
          d.ty0 = (outerTop - tbb2.top) / fullLayout._invScaleY;
          d.bx = tbbWidth + 2 * HOVERTEXTPAD;
          d.by = Math.max(tbbHeight + 2 * HOVERTEXTPAD, tx2height);
          d.anchor = "start";
          d.txwidth = tbbWidth;
          d.tx2width = tx2width;
          d.offset = 0;
          var txTotalWidth = (tbbWidth + HOVERARROWSIZE + HOVERTEXTPAD + tx2width) * fullLayout._invScaleX;
          var anchorStartOK, anchorEndOK;
          if (rotateLabels) {
            d.pos = htx;
            anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
            anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
            if ((d.idealAlign === "top" || !anchorStartOK) && anchorEndOK) {
              hty -= dy / 2;
              d.anchor = "end";
            } else if (anchorStartOK) {
              hty += dy / 2;
              d.anchor = "start";
            } else {
              d.anchor = "middle";
            }
            d.crossPos = hty;
          } else {
            d.pos = hty;
            anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
            anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
            if ((d.idealAlign === "left" || !anchorStartOK) && anchorEndOK) {
              htx -= dx / 2;
              d.anchor = "end";
            } else if (anchorStartOK) {
              htx += dx / 2;
              d.anchor = "start";
            } else {
              d.anchor = "middle";
              var txHalfWidth = txTotalWidth / 2;
              var overflowR = htx + txHalfWidth - outerWidth;
              var overflowL = htx - txHalfWidth;
              if (overflowR > 0) htx -= overflowR;
              if (overflowL < 0) htx += -overflowL;
            }
            d.crossPos = htx;
          }
          tx.attr("text-anchor", d.anchor);
          if (tx2width) tx2.attr("text-anchor", d.anchor);
          g.attr("transform", strTranslate(htx, hty) + (rotateLabels ? strRotate(YANGLE) : ""));
        });
        return {
          hoverLabels,
          commonLabelBoundingBox: commonLabelRect
        };
      }
      function getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t02, g) {
        var _a, _b;
        var name2 = "";
        var text = "";
        if (d.nameOverride !== void 0) d.name = d.nameOverride;
        if (d.name) {
          if (d.trace._meta) d.name = Lib.templateString(d.name, d.trace._meta);
          name2 = plainText(d.name, d.nameLength);
        }
        var h0 = hovermode.charAt(0);
        var h1 = h0 === "x" ? "y" : "x";
        if (d.zLabel !== void 0) {
          if (d.xLabel !== void 0) text += "x: " + d.xLabel + "<br>";
          if (d.yLabel !== void 0) text += "y: " + d.yLabel + "<br>";
          if (d.trace.type !== "choropleth" && d.trace.type !== "choroplethmapbox" && d.trace.type !== "choroplethmap") {
            text += (text ? "z: " : "") + d.zLabel;
          }
        } else if (showCommonLabel && d[h0 + "Label"] === t02) {
          text = d[h1 + "Label"] || "";
        } else if (d.xLabel === void 0) {
          if (d.yLabel !== void 0 && d.trace.type !== "scattercarpet") {
            text = d.yLabel;
          }
        } else if (d.yLabel === void 0) text = d.xLabel;
        else text = "(" + d.xLabel + ", " + d.yLabel + ")";
        if ((d.text || d.text === 0) && !Array.isArray(d.text)) {
          text += (text ? "<br>" : "") + d.text;
        }
        if (d.extraText !== void 0) text += (text ? "<br>" : "") + d.extraText;
        if (g && text === "" && !d.hovertemplate) {
          if (name2 === "") g.remove();
          text = name2;
        }
        if ((_b = (_a = d.trace) == null ? void 0 : _a.hoverlabel) == null ? void 0 : _b.split) d.hovertemplate = "";
        const { hovertemplate = false } = d;
        if (hovertemplate) {
          const labels = d.hovertemplateLabels || d;
          if (d[h0 + "Label"] !== t02) {
            labels[h0 + "other"] = labels[h0 + "Val"];
            labels[h0 + "otherLabel"] = labels[h0 + "Label"];
          }
          text = Lib.hovertemplateString({
            data: [d.eventData[0] || {}, d.trace._meta],
            fallback: d.trace.hovertemplatefallback,
            labels,
            locale: fullLayout._d3locale,
            template: hovertemplate
          });
          text = text.replace(EXTRA_STRING_REGEX, (_, extra) => {
            name2 = plainText(extra, d.nameLength);
            return "";
          });
        }
        return [text, name2];
      }
      function hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, commonLabelBoundingBox) {
        var axKey = rotateLabels ? "xa" : "ya";
        var crossAxKey = rotateLabels ? "ya" : "xa";
        var nummoves = 0;
        var axSign = 1;
        var nLabels = hoverLabels.size();
        var pointgroups = new Array(nLabels);
        var k = 0;
        var axisLabelMinX = commonLabelBoundingBox.minX;
        var axisLabelMaxX = commonLabelBoundingBox.maxX;
        var axisLabelMinY = commonLabelBoundingBox.minY;
        var axisLabelMaxY = commonLabelBoundingBox.maxY;
        var pX = function(x) {
          return x * fullLayout._invScaleX;
        };
        var pY = function(y) {
          return y * fullLayout._invScaleY;
        };
        hoverLabels.each(function(d) {
          var ax = d[axKey];
          var crossAx = d[crossAxKey];
          var axIsX = ax._id.charAt(0) === "x";
          var rng = ax.range;
          if (k === 0 && rng && rng[0] > rng[1] !== axIsX) {
            axSign = -1;
          }
          var pmin = 0;
          var pmax = axIsX ? fullLayout.width : fullLayout.height;
          if (fullLayout.hovermode === "x" || fullLayout.hovermode === "y") {
            var offsets = getHoverLabelOffsets(d, rotateLabels);
            var anchor = d.anchor;
            var horzSign = anchor === "end" ? -1 : 1;
            var labelMin;
            var labelMax;
            if (anchor === "middle") {
              labelMin = d.crossPos + (axIsX ? pY(offsets.y - d.by / 2) : pX(d.bx / 2 + d.tx2width / 2));
              labelMax = labelMin + (axIsX ? pY(d.by) : pX(d.bx));
            } else {
              if (axIsX) {
                labelMin = d.crossPos + pY(HOVERARROWSIZE + offsets.y) - pY(d.by / 2 - HOVERARROWSIZE);
                labelMax = labelMin + pY(d.by);
              } else {
                var startX = pX(horzSign * HOVERARROWSIZE + offsets.x);
                var endX = startX + pX(horzSign * d.bx);
                labelMin = d.crossPos + Math.min(startX, endX);
                labelMax = d.crossPos + Math.max(startX, endX);
              }
            }
            if (axIsX) {
              if (axisLabelMinY !== void 0 && axisLabelMaxY !== void 0 && Math.min(labelMax, axisLabelMaxY) - Math.max(labelMin, axisLabelMinY) > 1) {
                if (crossAx.side === "left") {
                  pmin = crossAx._mainLinePosition;
                  pmax = fullLayout.width;
                } else {
                  pmax = crossAx._mainLinePosition;
                }
              }
            } else {
              if (axisLabelMinX !== void 0 && axisLabelMaxX !== void 0 && Math.min(labelMax, axisLabelMaxX) - Math.max(labelMin, axisLabelMinX) > 1) {
                if (crossAx.side === "top") {
                  pmin = crossAx._mainLinePosition;
                  pmax = fullLayout.height;
                } else {
                  pmax = crossAx._mainLinePosition;
                }
              }
            }
          }
          pointgroups[k++] = [
            {
              datum: d,
              traceIndex: d.trace.index,
              dp: 0,
              pos: d.pos,
              posref: d.posref,
              size: d.by * (axIsX ? YFACTOR : 1) / 2,
              pmin,
              pmax
            }
          ];
        });
        pointgroups.sort(function(a, b) {
          return a[0].posref - b[0].posref || // for equal positions, sort trace indices increasing or decreasing
          // depending on whether the axis is reversed or not... so stacked
          // traces will generally keep their order even if one trace adds
          // nothing to the stack.
          axSign * (b[0].traceIndex - a[0].traceIndex);
        });
        var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp;
        function constrainGroup(grp2) {
          var minPt = grp2[0];
          var maxPt = grp2[grp2.length - 1];
          topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;
          bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;
          if (topOverlap > 0.01) {
            for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp += topOverlap;
            donepositioning = false;
          }
          if (bottomOverlap < 0.01) return;
          if (topOverlap < -0.01) {
            for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp -= bottomOverlap;
            donepositioning = false;
          }
          if (!donepositioning) return;
          var deleteCount = 0;
          for (i = 0; i < grp2.length; i++) {
            pti = grp2[i];
            if (pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
          }
          for (i = grp2.length - 1; i >= 0; i--) {
            if (deleteCount <= 0) break;
            pti = grp2[i];
            if (pti.pos > minPt.pmax - 1) {
              pti.del = true;
              deleteCount--;
            }
          }
          for (i = 0; i < grp2.length; i++) {
            if (deleteCount <= 0) break;
            pti = grp2[i];
            if (pti.pos < minPt.pmin + 1) {
              pti.del = true;
              deleteCount--;
              bottomOverlap = pti.size * 2;
              for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp -= bottomOverlap;
            }
          }
          for (i = grp2.length - 1; i >= 0; i--) {
            if (deleteCount <= 0) break;
            pti = grp2[i];
            if (pti.pos + pti.dp + pti.size > minPt.pmax) {
              pti.del = true;
              deleteCount--;
            }
          }
        }
        while (!donepositioning && nummoves <= nLabels) {
          nummoves++;
          donepositioning = true;
          i = 0;
          while (i < pointgroups.length - 1) {
            var g0 = pointgroups[i];
            var g1 = pointgroups[i + 1];
            var p0 = g0[g0.length - 1];
            var p1 = g1[0];
            topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;
            if (topOverlap > 0.01) {
              for (j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;
              g0.push.apply(g0, g1);
              pointgroups.splice(i + 1, 1);
              sumdp = 0;
              for (j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
              bottomOverlap = sumdp / g0.length;
              for (j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
              donepositioning = false;
            } else i++;
          }
          pointgroups.forEach(constrainGroup);
        }
        for (i = pointgroups.length - 1; i >= 0; i--) {
          var grp = pointgroups[i];
          for (j = grp.length - 1; j >= 0; j--) {
            var pt = grp[j];
            var hoverPt = pt.datum;
            hoverPt.offset = pt.dp;
            hoverPt.del = pt.del;
          }
        }
      }
      function getHoverLabelOffsets(hoverLabel, rotateLabels) {
        var offsetX = 0;
        var offsetY = hoverLabel.offset;
        if (rotateLabels) {
          offsetY *= -YSHIFTY;
          offsetX = hoverLabel.offset * YSHIFTX;
        }
        return {
          x: offsetX,
          y: offsetY
        };
      }
      function getTextShiftX(hoverLabel) {
        var alignShift = { start: 1, end: -1, middle: 0 }[hoverLabel.anchor];
        var textShiftX = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD);
        var text2ShiftX = textShiftX + alignShift * (hoverLabel.txwidth + HOVERTEXTPAD);
        var isMiddle = hoverLabel.anchor === "middle";
        if (isMiddle) {
          textShiftX -= hoverLabel.tx2width / 2;
          text2ShiftX += hoverLabel.txwidth / 2 + HOVERTEXTPAD;
        }
        return {
          alignShift,
          textShiftX,
          text2ShiftX
        };
      }
      function alignHoverText(hoverLabels, rotateLabels, scaleX, scaleY) {
        var pX = function(x) {
          return x * scaleX;
        };
        var pY = function(y) {
          return y * scaleY;
        };
        hoverLabels.each(function(d) {
          var g = d3.select(this);
          if (d.del) return g.remove();
          var tx = g.select("text.nums");
          var anchor = d.anchor;
          var horzSign = anchor === "end" ? -1 : 1;
          var shiftX = getTextShiftX(d);
          var offsets = getHoverLabelOffsets(d, rotateLabels);
          var offsetX = offsets.x;
          var offsetY = offsets.y;
          var isMiddle = anchor === "middle";
          var showArrow = "hoverlabel" in d.trace ? d.trace.hoverlabel.showarrow : true;
          var pathStr;
          if (isMiddle) {
            pathStr = "M-" + pX(d.bx / 2 + d.tx2width / 2) + "," + pY(offsetY - d.by / 2) + "h" + pX(d.bx) + "v" + pY(d.by) + "h-" + pX(d.bx) + "Z";
          } else if (showArrow) {
            pathStr = "M0,0L" + pX(horzSign * HOVERARROWSIZE + offsetX) + "," + pY(HOVERARROWSIZE + offsetY) + "v" + pY(d.by / 2 - HOVERARROWSIZE) + "h" + pX(horzSign * d.bx) + "v-" + pY(d.by) + "H" + pX(horzSign * HOVERARROWSIZE + offsetX) + "V" + pY(offsetY - HOVERARROWSIZE) + "Z";
          } else {
            pathStr = "M" + pX(horzSign * HOVERARROWSIZE + offsetX) + "," + pY(offsetY - d.by / 2) + "h" + pX(horzSign * d.bx) + "v" + pY(d.by) + "h" + pX(-horzSign * d.bx) + "Z";
          }
          g.select("path").attr("d", pathStr);
          var posX = offsetX + shiftX.textShiftX;
          var posY = offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD;
          var textAlign = d.textAlign || "auto";
          if (textAlign !== "auto") {
            if (textAlign === "left" && anchor !== "start") {
              tx.attr("text-anchor", "start");
              posX = isMiddle ? -d.bx / 2 - d.tx2width / 2 + HOVERTEXTPAD : -d.bx - HOVERTEXTPAD;
            } else if (textAlign === "right" && anchor !== "end") {
              tx.attr("text-anchor", "end");
              posX = isMiddle ? d.bx / 2 - d.tx2width / 2 - HOVERTEXTPAD : d.bx + HOVERTEXTPAD;
            }
          }
          tx.call(svgTextUtils.positionText, pX(posX), pY(posY));
          if (d.tx2width) {
            g.select("text.name").call(
              svgTextUtils.positionText,
              pX(shiftX.text2ShiftX + shiftX.alignShift * HOVERTEXTPAD + offsetX),
              pY(offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD)
            );
            g.select("rect").call(
              Drawing.setRect,
              pX(shiftX.text2ShiftX + (shiftX.alignShift - 1) * d.tx2width / 2 + offsetX),
              pY(offsetY - d.by / 2 - 1),
              pX(d.tx2width),
              pY(d.by + 2)
            );
          }
        });
      }
      function cleanPoint(d, hovermode) {
        var index = d.index;
        var trace = d.trace || {};
        var cd0 = d.cd[0];
        var cd = d.cd[index] || {};
        function pass(v) {
          return v || isNumeric(v) && v === 0;
        }
        var getVal = Array.isArray(index) ? function(calcKey, traceKey) {
          var v = Lib.castOption(cd0, index, calcKey);
          return pass(v) ? v : Lib.extractOption({}, trace, "", traceKey);
        } : function(calcKey, traceKey) {
          return Lib.extractOption(cd, trace, calcKey, traceKey);
        };
        function fill(key, calcKey, traceKey) {
          var val = getVal(calcKey, traceKey);
          if (pass(val)) d[key] = val;
        }
        fill("hoverinfo", "hi", "hoverinfo");
        fill("bgcolor", "hbg", "hoverlabel.bgcolor");
        fill("borderColor", "hbc", "hoverlabel.bordercolor");
        fill("fontFamily", "htf", "hoverlabel.font.family");
        fill("fontSize", "hts", "hoverlabel.font.size");
        fill("fontColor", "htc", "hoverlabel.font.color");
        fill("fontWeight", "htw", "hoverlabel.font.weight");
        fill("fontStyle", "hty", "hoverlabel.font.style");
        fill("fontVariant", "htv", "hoverlabel.font.variant");
        fill("nameLength", "hnl", "hoverlabel.namelength");
        fill("textAlign", "hta", "hoverlabel.align");
        d.posref = hovermode === "y" || hovermode === "closest" && trace.orientation === "h" ? d.xa._offset + (d.x0 + d.x1) / 2 : d.ya._offset + (d.y0 + d.y1) / 2;
        d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
        d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
        d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
        d.y1 = Lib.constrain(d.y1, 0, d.ya._length);
        if (d.xLabelVal !== void 0) {
          d.xLabel = "xLabel" in d ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal, trace.xhoverformat);
          d.xVal = d.xa.c2d(d.xLabelVal);
        }
        if (d.yLabelVal !== void 0) {
          d.yLabel = "yLabel" in d ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal, trace.yhoverformat);
          d.yVal = d.ya.c2d(d.yLabelVal);
        }
        if (d.zLabelVal !== void 0 && d.zLabel === void 0) {
          d.zLabel = String(d.zLabelVal);
        }
        if (!isNaN(d.xerr) && !(d.xa.type === "log" && d.xerr <= 0)) {
          var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), "hover").text;
          if (d.xerrneg !== void 0) {
            d.xLabel += " +" + xeText + " / -" + Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), "hover").text;
          } else d.xLabel += " \xB1 " + xeText;
          if (hovermode === "x") d.distance += 1;
        }
        if (!isNaN(d.yerr) && !(d.ya.type === "log" && d.yerr <= 0)) {
          var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), "hover").text;
          if (d.yerrneg !== void 0) {
            d.yLabel += " +" + yeText + " / -" + Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), "hover").text;
          } else d.yLabel += " \xB1 " + yeText;
          if (hovermode === "y") d.distance += 1;
        }
        var infomode = d.hoverinfo || d.trace.hoverinfo;
        if (infomode && infomode !== "all") {
          infomode = Array.isArray(infomode) ? infomode : infomode.split("+");
          if (infomode.indexOf("x") === -1) d.xLabel = void 0;
          if (infomode.indexOf("y") === -1) d.yLabel = void 0;
          if (infomode.indexOf("z") === -1) d.zLabel = void 0;
          if (infomode.indexOf("text") === -1) d.text = void 0;
          if (infomode.indexOf("name") === -1) d.name = void 0;
        }
        return d;
      }
      function createSpikelines(gd, closestPoints, opts) {
        var container = opts.container;
        var fullLayout = opts.fullLayout;
        var gs = fullLayout._size;
        var evt = opts.event;
        var showY = !!closestPoints.hLinePoint;
        var showX = !!closestPoints.vLinePoint;
        var xa, ya;
        container.selectAll(".spikeline").remove();
        if (!(showX || showY)) return;
        var contrastColor = Color2.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);
        if (showY) {
          var hLinePoint = closestPoints.hLinePoint;
          var hLinePointX, hLinePointY;
          xa = hLinePoint && hLinePoint.xa;
          ya = hLinePoint && hLinePoint.ya;
          var ySnap = ya.spikesnap;
          if (ySnap === "cursor") {
            hLinePointX = evt.pointerX;
            hLinePointY = evt.pointerY;
          } else {
            hLinePointX = xa._offset + hLinePoint.x;
            hLinePointY = ya._offset + hLinePoint.y;
          }
          var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ? Color2.contrast(contrastColor) : hLinePoint.color;
          var yMode = ya.spikemode;
          var yThickness = ya.spikethickness;
          var yColor = ya.spikecolor || dfltHLineColor;
          var xEdge = Axes.getPxPosition(gd, ya);
          var xBase, xEndSpike;
          if (yMode.indexOf("toaxis") !== -1 || yMode.indexOf("across") !== -1) {
            if (yMode.indexOf("toaxis") !== -1) {
              xBase = xEdge;
              xEndSpike = hLinePointX;
            }
            if (yMode.indexOf("across") !== -1) {
              var xAcross0 = ya._counterDomainMin;
              var xAcross1 = ya._counterDomainMax;
              if (ya.anchor === "free") {
                xAcross0 = Math.min(xAcross0, ya.position);
                xAcross1 = Math.max(xAcross1, ya.position);
              }
              xBase = gs.l + xAcross0 * gs.w;
              xEndSpike = gs.l + xAcross1 * gs.w;
            }
            container.insert("line", ":first-child").attr({
              x1: xBase,
              x2: xEndSpike,
              y1: hLinePointY,
              y2: hLinePointY,
              "stroke-width": yThickness,
              stroke: yColor,
              "stroke-dasharray": Drawing.dashStyle(ya.spikedash, yThickness)
            }).classed("spikeline", true).classed("crisp", true);
            container.insert("line", ":first-child").attr({
              x1: xBase,
              x2: xEndSpike,
              y1: hLinePointY,
              y2: hLinePointY,
              "stroke-width": yThickness + 2,
              stroke: contrastColor
            }).classed("spikeline", true).classed("crisp", true);
          }
          if (yMode.indexOf("marker") !== -1) {
            container.insert("circle", ":first-child").attr({
              cx: xEdge + (ya.side !== "right" ? yThickness : -yThickness),
              cy: hLinePointY,
              r: yThickness,
              fill: yColor
            }).classed("spikeline", true);
          }
        }
        if (showX) {
          var vLinePoint = closestPoints.vLinePoint;
          var vLinePointX, vLinePointY;
          xa = vLinePoint && vLinePoint.xa;
          ya = vLinePoint && vLinePoint.ya;
          var xSnap = xa.spikesnap;
          if (xSnap === "cursor") {
            vLinePointX = evt.pointerX;
            vLinePointY = evt.pointerY;
          } else {
            vLinePointX = xa._offset + vLinePoint.x;
            vLinePointY = ya._offset + vLinePoint.y;
          }
          var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ? Color2.contrast(contrastColor) : vLinePoint.color;
          var xMode = xa.spikemode;
          var xThickness = xa.spikethickness;
          var xColor = xa.spikecolor || dfltVLineColor;
          var yEdge = Axes.getPxPosition(gd, xa);
          var yBase, yEndSpike;
          if (xMode.indexOf("toaxis") !== -1 || xMode.indexOf("across") !== -1) {
            if (xMode.indexOf("toaxis") !== -1) {
              yBase = yEdge;
              yEndSpike = vLinePointY;
            }
            if (xMode.indexOf("across") !== -1) {
              var yAcross0 = xa._counterDomainMin;
              var yAcross1 = xa._counterDomainMax;
              if (xa.anchor === "free") {
                yAcross0 = Math.min(yAcross0, xa.position);
                yAcross1 = Math.max(yAcross1, xa.position);
              }
              yBase = gs.t + (1 - yAcross1) * gs.h;
              yEndSpike = gs.t + (1 - yAcross0) * gs.h;
            }
            container.insert("line", ":first-child").attr({
              x1: vLinePointX,
              x2: vLinePointX,
              y1: yBase,
              y2: yEndSpike,
              "stroke-width": xThickness,
              stroke: xColor,
              "stroke-dasharray": Drawing.dashStyle(xa.spikedash, xThickness)
            }).classed("spikeline", true).classed("crisp", true);
            container.insert("line", ":first-child").attr({
              x1: vLinePointX,
              x2: vLinePointX,
              y1: yBase,
              y2: yEndSpike,
              "stroke-width": xThickness + 2,
              stroke: contrastColor
            }).classed("spikeline", true).classed("crisp", true);
          }
          if (xMode.indexOf("marker") !== -1) {
            container.insert("circle", ":first-child").attr({
              cx: vLinePointX,
              cy: yEdge - (xa.side !== "top" ? xThickness : -xThickness),
              r: xThickness,
              fill: xColor
            }).classed("spikeline", true);
          }
        }
      }
      function hoverChanged(gd, evt, oldhoverdata) {
        if (!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;
        for (var i = oldhoverdata.length - 1; i >= 0; i--) {
          var oldPt = oldhoverdata[i];
          var newPt = gd._hoverdata[i];
          if (oldPt.curveNumber !== newPt.curveNumber || String(oldPt.pointNumber) !== String(newPt.pointNumber) || String(oldPt.pointNumbers) !== String(newPt.pointNumbers) || oldPt.binNumber !== newPt.binNumber) {
            return true;
          }
        }
        return false;
      }
      function spikesChanged(gd, oldspikepoints) {
        if (!oldspikepoints) return true;
        if (oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint)
          return true;
        return false;
      }
      function plainText(s, len) {
        return svgTextUtils.plainText(s || "", {
          len,
          allowedTags: ["br", "sub", "sup", "b", "i", "em", "s", "u"]
        });
      }
      function orderRangePoints(hoverData, hovermode) {
        var axLetter = hovermode.charAt(0);
        var first = [];
        var second = [];
        var last = [];
        for (var i = 0; i < hoverData.length; i++) {
          var d = hoverData[i];
          if (Registry.traceIs(d.trace, "bar-like") || Registry.traceIs(d.trace, "box-violin")) {
            last.push(d);
          } else if (d.trace[axLetter + "period"]) {
            second.push(d);
          } else {
            first.push(d);
          }
        }
        return first.concat(second).concat(last);
      }
      function getCoord(axLetter, winningPoint, fullLayout) {
        var ax = winningPoint[axLetter + "a"];
        var val = winningPoint[axLetter + "Val"];
        var cd0 = winningPoint.cd[0];
        if (ax.type === "category" || ax.type === "multicategory") val = ax._categoriesMap[val];
        else if (ax.type === "date") {
          var periodalignment = winningPoint.trace[axLetter + "periodalignment"];
          if (periodalignment) {
            var d = winningPoint.cd[winningPoint.index];
            var start = d[axLetter + "Start"];
            if (start === void 0) start = d[axLetter];
            var end = d[axLetter + "End"];
            if (end === void 0) end = d[axLetter];
            var diff = end - start;
            if (periodalignment === "end") {
              val += diff;
            } else if (periodalignment === "middle") {
              val += diff / 2;
            }
          }
          val = ax.d2c(val);
        }
        if (cd0 && cd0.t && cd0.t.posLetter === ax._id) {
          if (fullLayout.boxmode === "group" || fullLayout.violinmode === "group") {
            val += cd0.t.dPos;
          }
        }
        return val;
      }
      var getTopOffset = (gd) => gd.offsetTop + gd.clientTop;
      var getLeftOffset = (gd) => gd.offsetLeft + gd.clientLeft;
      function getBoundingClientRect(gd, node) {
        var fullLayout = gd._fullLayout;
        var rect = node.getBoundingClientRect();
        var x0 = rect.left;
        var y0 = rect.top;
        var x1 = x0 + rect.width;
        var y1 = y0 + rect.height;
        var A2 = Lib.apply3DTransform(fullLayout._invTransform)(x0, y0);
        var B2 = Lib.apply3DTransform(fullLayout._invTransform)(x1, y1);
        var Ax = A2[0];
        var Ay = A2[1];
        var Bx = B2[0];
        var By = B2[1];
        return {
          x: Ax,
          y: Ay,
          width: Bx - Ax,
          height: By - Ay,
          top: Math.min(Ay, By),
          left: Math.min(Ax, Bx),
          right: Math.max(Ax, Bx),
          bottom: Math.max(Ay, By)
        };
      }
    }
  });

  // src/components/fx/hoverlabel_defaults.js
  var require_hoverlabel_defaults = __commonJS({
    "src/components/fx/hoverlabel_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var isUnifiedHover = require_helpers2().isUnifiedHover;
      module.exports = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) {
        opts = opts || {};
        var hasLegend = contOut.legend;
        function inheritFontAttr(attr) {
          if (!opts.font[attr]) {
            opts.font[attr] = hasLegend ? contOut.legend.font[attr] : contOut.font[attr];
          }
        }
        if (contOut && isUnifiedHover(contOut.hovermode)) {
          if (!opts.font) opts.font = {};
          inheritFontAttr("size");
          inheritFontAttr("family");
          inheritFontAttr("color");
          inheritFontAttr("weight");
          inheritFontAttr("style");
          inheritFontAttr("variant");
          if (hasLegend) {
            if (!opts.bgcolor) opts.bgcolor = Color2.combine(contOut.legend.bgcolor, contOut.paper_bgcolor);
            if (!opts.bordercolor) opts.bordercolor = contOut.legend.bordercolor;
          } else {
            if (!opts.bgcolor) opts.bgcolor = contOut.paper_bgcolor;
          }
        }
        coerce("hoverlabel.bgcolor", opts.bgcolor);
        coerce("hoverlabel.bordercolor", opts.bordercolor);
        coerce("hoverlabel.namelength", opts.namelength);
        coerce("hoverlabel.showarrow", opts.showarrow);
        Lib.coerceFont(coerce, "hoverlabel.font", opts.font);
        coerce("hoverlabel.align", opts.align);
      };
    }
  });

  // src/components/fx/layout_global_defaults.js
  var require_layout_global_defaults = __commonJS({
    "src/components/fx/layout_global_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleHoverLabelDefaults = require_hoverlabel_defaults();
      var layoutAttributes = require_layout_attributes();
      module.exports = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
      };
    }
  });

  // src/components/fx/defaults.js
  var require_defaults4 = __commonJS({
    "src/components/fx/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes();
      var handleHoverLabelDefaults = require_hoverlabel_defaults();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var opts = Lib.extendFlat({}, layout.hoverlabel);
        if (traceOut.hovertemplate) opts.namelength = -1;
        handleHoverLabelDefaults(traceIn, traceOut, coerce, opts);
      };
    }
  });

  // src/components/fx/hovermode_defaults.js
  var require_hovermode_defaults = __commonJS({
    "src/components/fx/hovermode_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes();
      module.exports = function handleHoverModeDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          if (layoutOut[attr] !== void 0) return layoutOut[attr];
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        coerce("clickmode");
        coerce("hoversubplots");
        return coerce("hovermode");
      };
    }
  });

  // src/components/fx/layout_defaults.js
  var require_layout_defaults2 = __commonJS({
    "src/components/fx/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes();
      var handleHoverModeDefaults = require_hovermode_defaults();
      var handleHoverLabelDefaults = require_hoverlabel_defaults();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        var hoverMode = handleHoverModeDefaults(layoutIn, layoutOut);
        if (hoverMode) {
          coerce("hoverdistance");
          coerce("spikedistance");
        }
        var dragMode = coerce("dragmode");
        if (dragMode === "select") coerce("selectdirection");
        var hasMapbox = layoutOut._has("mapbox");
        var hasMap = layoutOut._has("map");
        var hasGeo = layoutOut._has("geo");
        var len = layoutOut._basePlotModules.length;
        if (layoutOut.dragmode === "zoom" && ((hasMapbox || hasMap || hasGeo) && len === 1 || (hasMapbox || hasMap) && hasGeo && len === 2)) {
          layoutOut.dragmode = "pan";
        }
        handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
        Lib.coerceFont(coerce, "hoverlabel.grouptitlefont", layoutOut.hoverlabel.font);
      };
    }
  });

  // src/components/fx/calc.js
  var require_calc2 = __commonJS({
    "src/components/fx/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Registry = require_registry();
      module.exports = function calc(gd) {
        var calcdata = gd.calcdata;
        var fullLayout = gd._fullLayout;
        function makeCoerceHoverInfo(trace2) {
          return function(val) {
            return Lib.coerceHoverinfo({ hoverinfo: val }, { _module: trace2._module }, fullLayout);
          };
        }
        for (var i = 0; i < calcdata.length; i++) {
          var cd = calcdata[i];
          var trace = cd[0].trace;
          if (Registry.traceIs(trace, "pie-like")) continue;
          var fillFn = Registry.traceIs(trace, "2dMap") ? paste : Lib.fillArray;
          fillFn(trace.hoverinfo, cd, "hi", makeCoerceHoverInfo(trace));
          if (trace.hovertemplate) fillFn(trace.hovertemplate, cd, "ht");
          if (!trace.hoverlabel) continue;
          fillFn(trace.hoverlabel.bgcolor, cd, "hbg");
          fillFn(trace.hoverlabel.bordercolor, cd, "hbc");
          fillFn(trace.hoverlabel.font.size, cd, "hts");
          fillFn(trace.hoverlabel.font.color, cd, "htc");
          fillFn(trace.hoverlabel.font.family, cd, "htf");
          fillFn(trace.hoverlabel.font.weight, cd, "htw");
          fillFn(trace.hoverlabel.font.style, cd, "hty");
          fillFn(trace.hoverlabel.font.variant, cd, "htv");
          fillFn(trace.hoverlabel.namelength, cd, "hnl");
          fillFn(trace.hoverlabel.align, cd, "hta");
          fillFn(trace.hoverlabel.showarrow, cd, "htsa");
        }
      };
      function paste(traceAttr, cd, cdAttr, fn) {
        fn = fn || Lib.identity;
        if (Array.isArray(traceAttr)) {
          cd[0][cdAttr] = fn(traceAttr);
        }
      }
    }
  });

  // src/components/fx/click.js
  var require_click = __commonJS({
    "src/components/fx/click.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var hover = require_hover().hover;
      module.exports = function click(gd, evt, subplot) {
        var annotationsDone = Registry.getComponentMethod("annotations", "onClick")(gd, gd._hoverdata);
        if (subplot !== void 0) {
          hover(gd, evt, subplot, true);
        }
        function emitClick() {
          gd.emit("plotly_click", { points: gd._hoverdata, event: evt });
        }
        if (gd._hoverdata && evt && evt.target) {
          if (annotationsDone && annotationsDone.then) {
            annotationsDone.then(emitClick);
          } else emitClick();
          if (evt.stopImmediatePropagation) evt.stopImmediatePropagation();
        }
      };
    }
  });

  // src/components/fx/index.js
  var require_fx = __commonJS({
    "src/components/fx/index.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var dragElement = require_dragelement();
      var helpers = require_helpers2();
      var layoutAttributes = require_layout_attributes();
      var hoverModule = require_hover();
      module.exports = {
        moduleType: "component",
        name: "fx",
        constants: require_constants(),
        schema: {
          layout: layoutAttributes
        },
        attributes: require_attributes(),
        layoutAttributes,
        supplyLayoutGlobalDefaults: require_layout_global_defaults(),
        supplyDefaults: require_defaults4(),
        supplyLayoutDefaults: require_layout_defaults2(),
        calc: require_calc2(),
        getDistanceFunction: helpers.getDistanceFunction,
        getClosest: helpers.getClosest,
        inbox: helpers.inbox,
        quadrature: helpers.quadrature,
        appendArrayPointValue: helpers.appendArrayPointValue,
        castHoverOption,
        castHoverinfo,
        hover: hoverModule.hover,
        unhover: dragElement.unhover,
        loneHover: hoverModule.loneHover,
        loneUnhover,
        click: require_click()
      };
      function loneUnhover(containerOrSelection) {
        var selection = Lib.isD3Selection(containerOrSelection) ? containerOrSelection : d3.select(containerOrSelection);
        selection.selectAll("g.hovertext").remove();
        selection.selectAll(".spikeline").remove();
      }
      function castHoverOption(trace, ptNumber, attr) {
        return Lib.castOption(trace, ptNumber, "hoverlabel." + attr);
      }
      function castHoverinfo(trace, fullLayout, ptNumber) {
        function _coerce(val) {
          return Lib.coerceHoverinfo({ hoverinfo: val }, { _module: trace._module }, fullLayout);
        }
        return Lib.castOption(trace, ptNumber, "hoverinfo", _coerce);
      }
    }
  });

  // src/components/dragelement/helpers.js
  var require_helpers5 = __commonJS({
    "src/components/dragelement/helpers.js"(exports) {
      "use strict";
      exports.selectMode = function(dragmode) {
        return dragmode === "lasso" || dragmode === "select";
      };
      exports.drawMode = function(dragmode) {
        return dragmode === "drawclosedpath" || dragmode === "drawopenpath" || dragmode === "drawline" || dragmode === "drawrect" || dragmode === "drawcircle";
      };
      exports.openMode = function(dragmode) {
        return dragmode === "drawline" || dragmode === "drawopenpath";
      };
      exports.rectMode = function(dragmode) {
        return dragmode === "select" || dragmode === "drawline" || dragmode === "drawrect" || dragmode === "drawcircle";
      };
      exports.freeMode = function(dragmode) {
        return dragmode === "lasso" || dragmode === "drawclosedpath" || dragmode === "drawopenpath";
      };
      exports.selectingOrDrawing = function(dragmode) {
        return exports.freeMode(dragmode) || exports.rectMode(dragmode);
      };
    }
  });

  // src/lib/clear_gl_canvases.js
  var require_clear_gl_canvases = __commonJS({
    "src/lib/clear_gl_canvases.js"(exports, module) {
      "use strict";
      module.exports = function clearGlCanvases(gd) {
        var fullLayout = gd._fullLayout;
        if (fullLayout._glcanvas && fullLayout._glcanvas.size()) {
          fullLayout._glcanvas.each(function(d) {
            if (d.regl) d.regl.clear({ color: true, depth: true });
          });
        }
      };
    }
  });

  // src/fonts/ploticon.js
  var require_ploticon = __commonJS({
    "src/fonts/ploticon.js"(exports, module) {
      "use strict";
      module.exports = {
        undo: {
          width: 857.1,
          height: 1e3,
          path: "m857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        home: {
          width: 928.6,
          height: 1e3,
          path: "m786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        "camera-retro": {
          width: 1e3,
          height: 1e3,
          path: "m518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        zoombox: {
          width: 1e3,
          height: 1e3,
          path: "m1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        pan: {
          width: 1e3,
          height: 1e3,
          path: "m1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        zoom_plus: {
          width: 875,
          height: 1e3,
          path: "m1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        zoom_minus: {
          width: 875,
          height: 1e3,
          path: "m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        autoscale: {
          width: 1e3,
          height: 1e3,
          path: "m250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        tooltip_basic: {
          width: 1500,
          height: 1e3,
          path: "m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        tooltip_compare: {
          width: 1125,
          height: 1e3,
          path: "m187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        plotlylogo: {
          width: 1542,
          height: 1e3,
          path: "m0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        "z-axis": {
          width: 1e3,
          height: 1e3,
          path: "m833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        "3d_rotate": {
          width: 1e3,
          height: 1e3,
          path: "m922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        camera: {
          width: 1e3,
          height: 1e3,
          path: "m500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        movie: {
          width: 1e3,
          height: 1e3,
          path: "m938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        question: {
          width: 857.1,
          height: 1e3,
          path: "m500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        disk: {
          width: 857.1,
          height: 1e3,
          path: "m214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        drawopenpath: {
          width: 70,
          height: 70,
          path: "M33.21,85.65a7.31,7.31,0,0,1-2.59-.48c-8.16-3.11-9.27-19.8-9.88-41.3-.1-3.58-.19-6.68-.35-9-.15-2.1-.67-3.48-1.43-3.79-2.13-.88-7.91,2.32-12,5.86L3,32.38c1.87-1.64,11.55-9.66,18.27-6.9,2.13.87,4.75,3.14,5.17,9,.17,2.43.26,5.59.36,9.25a224.17,224.17,0,0,0,1.5,23.4c1.54,10.76,4,12.22,4.48,12.4.84.32,2.79-.46,5.76-3.59L43,80.07C41.53,81.57,37.68,85.64,33.21,85.65ZM74.81,69a11.34,11.34,0,0,0,6.09-6.72L87.26,44.5,74.72,32,56.9,38.35c-2.37.86-5.57,3.42-6.61,6L38.65,72.14l8.42,8.43ZM55,46.27a7.91,7.91,0,0,1,3.64-3.17l14.8-5.3,8,8L76.11,60.6l-.06.19a6.37,6.37,0,0,1-3,3.43L48.25,74.59,44.62,71Zm16.57,7.82A6.9,6.9,0,1,0,64.64,61,6.91,6.91,0,0,0,71.54,54.09Zm-4.05,0a2.85,2.85,0,1,1-2.85-2.85A2.86,2.86,0,0,1,67.49,54.09Zm-4.13,5.22L60.5,56.45,44.26,72.7l2.86,2.86ZM97.83,35.67,84.14,22l-8.57,8.57L89.26,44.24Zm-13.69-8,8,8-2.85,2.85-8-8Z",
          transform: "matrix(1 0 0 1 -15 -15)"
        },
        drawclosedpath: {
          width: 90,
          height: 90,
          path: "M88.41,21.12a26.56,26.56,0,0,0-36.18,0l-2.07,2-2.07-2a26.57,26.57,0,0,0-36.18,0,23.74,23.74,0,0,0,0,34.8L48,90.12a3.22,3.22,0,0,0,4.42,0l36-34.21a23.73,23.73,0,0,0,0-34.79ZM84,51.24,50.16,83.35,16.35,51.25a17.28,17.28,0,0,1,0-25.47,20,20,0,0,1,27.3,0l4.29,4.07a3.23,3.23,0,0,0,4.44,0l4.29-4.07a20,20,0,0,1,27.3,0,17.27,17.27,0,0,1,0,25.46ZM66.76,47.68h-33v6.91h33ZM53.35,35H46.44V68h6.91Z",
          transform: "matrix(1 0 0 1 -5 -5)"
        },
        lasso: {
          width: 1031,
          height: 1e3,
          path: "m1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        selectbox: {
          width: 1e3,
          height: 1e3,
          path: "m0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z",
          transform: "matrix(1 0 0 -1 0 850)"
        },
        drawline: {
          width: 70,
          height: 70,
          path: "M60.64,62.3a11.29,11.29,0,0,0,6.09-6.72l6.35-17.72L60.54,25.31l-17.82,6.4c-2.36.86-5.57,3.41-6.6,6L24.48,65.5l8.42,8.42ZM40.79,39.63a7.89,7.89,0,0,1,3.65-3.17l14.79-5.31,8,8L61.94,54l-.06.19a6.44,6.44,0,0,1-3,3.43L34.07,68l-3.62-3.63Zm16.57,7.81a6.9,6.9,0,1,0-6.89,6.9A6.9,6.9,0,0,0,57.36,47.44Zm-4,0a2.86,2.86,0,1,1-2.85-2.85A2.86,2.86,0,0,1,53.32,47.44Zm-4.13,5.22L46.33,49.8,30.08,66.05l2.86,2.86ZM83.65,29,70,15.34,61.4,23.9,75.09,37.59ZM70,21.06l8,8-2.84,2.85-8-8ZM87,80.49H10.67V87H87Z",
          transform: "matrix(1 0 0 1 -15 -15)"
        },
        drawrect: {
          width: 80,
          height: 80,
          path: "M78,22V79H21V22H78m9-9H12V88H87V13ZM68,46.22H31V54H68ZM53,32H45.22V69H53Z",
          transform: "matrix(1 0 0 1 -10 -10)"
        },
        drawcircle: {
          width: 80,
          height: 80,
          path: "M50,84.72C26.84,84.72,8,69.28,8,50.3S26.84,15.87,50,15.87,92,31.31,92,50.3,73.16,84.72,50,84.72Zm0-60.59c-18.6,0-33.74,11.74-33.74,26.17S31.4,76.46,50,76.46,83.74,64.72,83.74,50.3,68.6,24.13,50,24.13Zm17.15,22h-34v7.11h34Zm-13.8-13H46.24v34h7.11Z",
          transform: "matrix(1 0 0 1 -10 -10)"
        },
        eraseshape: {
          width: 80,
          height: 80,
          path: "M82.77,78H31.85L6,49.57,31.85,21.14H82.77a8.72,8.72,0,0,1,8.65,8.77V69.24A8.72,8.72,0,0,1,82.77,78ZM35.46,69.84H82.77a.57.57,0,0,0,.49-.6V29.91a.57.57,0,0,0-.49-.61H35.46L17,49.57Zm32.68-34.7-24,24,5,5,24-24Zm-19,.53-5,5,24,24,5-5Z",
          transform: "matrix(1 0 0 1 -10 -10)"
        },
        spikeline: {
          width: 1e3,
          height: 1e3,
          path: "M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z",
          transform: "matrix(1.5 0 0 -1.5 0 850)"
        },
        pencil: {
          width: 1792,
          height: 1792,
          path: "M491 1536l91-91-235-235-91 91v107h128v128h107zm523-928q0-22-22-22-10 0-17 7l-542 542q-7 7-7 17 0 22 22 22 10 0 17-7l542-542q7-7 7-17zm-54-192l416 416-832 832h-416v-416zm683 96q0 53-37 90l-166 166-416-416 166-165q36-38 90-38 53 0 91 38l235 234q37 39 37 91z",
          transform: "matrix(1 0 0 1 0 1)"
        },
        newplotlylogo: {
          name: "newplotlylogo",
          svg: [
            "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 132 132'>",
            " <title>plotly-logomark</title>",
            " <g id='symbol'>",
            "  <rect fill='#000' x='0' y='0' width='132' height='132' rx='18' ry='18'/>",
            "  <circle fill='#9EF' cx='102' cy='30' r='6'/>",
            "  <circle fill='#BAC' cx='78' cy='30' r='6'/>",
            "  <circle fill='#BAC' cx='78' cy='54' r='6'/>",
            "  <circle fill='#D69' cx='54' cy='30' r='6'/>",
            "  <circle fill='#F26' cx='30' cy='30' r='6'/>",
            "  <circle fill='#F26' cx='30' cy='54' r='6'/>",
            "  <path fill='#FFF' d='M30,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,30,72Z'/>",
            "  <path fill='#FFF' d='M78,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,78,72Z'/>",
            "  <path fill='#FFF' d='M54,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,54,48Z'/>",
            "  <path fill='#FFF' d='M102,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,102,48Z'/>",
            " </g>",
            "</svg>"
          ].join("")
        }
      };
    }
  });

  // src/components/shapes/draw_newshape/constants.js
  var require_constants4 = __commonJS({
    "src/components/shapes/draw_newshape/constants.js"(exports, module) {
      "use strict";
      var CIRCLE_SIDES = 32;
      module.exports = {
        CIRCLE_SIDES,
        i000: 0,
        i090: CIRCLE_SIDES / 4,
        i180: CIRCLE_SIDES / 2,
        i270: CIRCLE_SIDES / 4 * 3,
        cos45: Math.cos(Math.PI / 4),
        sin45: Math.sin(Math.PI / 4),
        SQRT2: Math.sqrt(2)
      };
    }
  });

  // src/components/selections/helpers.js
  var require_helpers6 = __commonJS({
    "src/components/selections/helpers.js"(exports, module) {
      "use strict";
      var strTranslate = require_lib().strTranslate;
      function p2r(ax, v) {
        switch (ax.type) {
          case "log":
            return ax.p2d(v);
          case "date":
            return ax.p2r(v, 0, ax.calendar);
          default:
            return ax.p2r(v);
        }
      }
      function r2p(ax, v) {
        switch (ax.type) {
          case "log":
            return ax.d2p(v);
          case "date":
            return ax.r2p(v, 0, ax.calendar);
          default:
            return ax.r2p(v);
        }
      }
      function axValue(ax) {
        var index = ax._id.charAt(0) === "y" ? 1 : 0;
        return function(v) {
          return p2r(ax, v[index]);
        };
      }
      function getTransform(plotinfo) {
        return strTranslate(
          plotinfo.xaxis._offset,
          plotinfo.yaxis._offset
        );
      }
      module.exports = {
        p2r,
        r2p,
        axValue,
        getTransform
      };
    }
  });

  // src/components/shapes/draw_newshape/helpers.js
  var require_helpers7 = __commonJS({
    "src/components/shapes/draw_newshape/helpers.js"(exports) {
      "use strict";
      var parseSvgPath = require_parse_svg_path();
      var constants = require_constants4();
      var CIRCLE_SIDES = constants.CIRCLE_SIDES;
      var SQRT2 = constants.SQRT2;
      var cartesianHelpers = require_helpers6();
      var p2r = cartesianHelpers.p2r;
      var r2p = cartesianHelpers.r2p;
      var iC = [0, 3, 4, 5, 6, 1, 2];
      var iQS = [0, 3, 4, 1, 2];
      exports.writePaths = function(polygons) {
        var nI = polygons.length;
        if (!nI) return "M0,0Z";
        var str = "";
        for (var i = 0; i < nI; i++) {
          var nJ = polygons[i].length;
          for (var j = 0; j < nJ; j++) {
            var w = polygons[i][j][0];
            if (w === "Z") {
              str += "Z";
            } else {
              var nK = polygons[i][j].length;
              for (var k = 0; k < nK; k++) {
                var realK = k;
                if (w === "Q" || w === "S") {
                  realK = iQS[k];
                } else if (w === "C") {
                  realK = iC[k];
                }
                str += polygons[i][j][realK];
                if (k > 0 && k < nK - 1) {
                  str += ",";
                }
              }
            }
          }
        }
        return str;
      };
      exports.readPaths = function(str, gd, plotinfo, isActiveShape) {
        var cmd = parseSvgPath(str);
        var polys = [];
        var n = -1;
        var newPoly = function() {
          n++;
          polys[n] = [];
        };
        var k;
        var x = 0;
        var y = 0;
        var initX;
        var initY;
        var recStart = function() {
          initX = x;
          initY = y;
        };
        recStart();
        for (var i = 0; i < cmd.length; i++) {
          var newPos = [];
          var x1, x2, y1, y2;
          var c = cmd[i][0];
          var w = c;
          switch (c) {
            case "M":
              newPoly();
              x = +cmd[i][1];
              y = +cmd[i][2];
              newPos.push([w, x, y]);
              recStart();
              break;
            case "Q":
            case "S":
              x1 = +cmd[i][1];
              y1 = +cmd[i][2];
              x = +cmd[i][3];
              y = +cmd[i][4];
              newPos.push([w, x, y, x1, y1]);
              break;
            case "C":
              x1 = +cmd[i][1];
              y1 = +cmd[i][2];
              x2 = +cmd[i][3];
              y2 = +cmd[i][4];
              x = +cmd[i][5];
              y = +cmd[i][6];
              newPos.push([w, x, y, x1, y1, x2, y2]);
              break;
            case "T":
            case "L":
              x = +cmd[i][1];
              y = +cmd[i][2];
              newPos.push([w, x, y]);
              break;
            case "H":
              w = "L";
              x = +cmd[i][1];
              newPos.push([w, x, y]);
              break;
            case "V":
              w = "L";
              y = +cmd[i][1];
              newPos.push([w, x, y]);
              break;
            case "A":
              w = "L";
              var rx = +cmd[i][1];
              var ry = +cmd[i][2];
              if (!+cmd[i][4]) {
                rx = -rx;
                ry = -ry;
              }
              var cenX = x - rx;
              var cenY = y;
              for (k = 1; k <= CIRCLE_SIDES / 2; k++) {
                var t = 2 * Math.PI * k / CIRCLE_SIDES;
                newPos.push([
                  w,
                  cenX + rx * Math.cos(t),
                  cenY + ry * Math.sin(t)
                ]);
              }
              break;
            case "Z":
              if (x !== initX || y !== initY) {
                x = initX;
                y = initY;
                newPos.push([w, x, y]);
              }
              break;
          }
          var domain = (plotinfo || {}).domain;
          var size = gd._fullLayout._size;
          var xPixelSized = plotinfo && plotinfo.xsizemode === "pixel";
          var yPixelSized = plotinfo && plotinfo.ysizemode === "pixel";
          var noOffset = isActiveShape === false;
          for (var j = 0; j < newPos.length; j++) {
            for (k = 0; k + 2 < 7; k += 2) {
              var _x = newPos[j][k + 1];
              var _y = newPos[j][k + 2];
              if (_x === void 0 || _y === void 0) continue;
              x = _x;
              y = _y;
              if (plotinfo) {
                if (plotinfo.xaxis && plotinfo.xaxis.p2r) {
                  if (noOffset) _x -= plotinfo.xaxis._offset;
                  if (xPixelSized) {
                    _x = r2p(plotinfo.xaxis, plotinfo.xanchor) + _x;
                  } else {
                    _x = p2r(plotinfo.xaxis, _x);
                  }
                } else {
                  if (noOffset) _x -= size.l;
                  if (domain) _x = domain.x[0] + _x / size.w;
                  else _x = _x / size.w;
                }
                if (plotinfo.yaxis && plotinfo.yaxis.p2r) {
                  if (noOffset) _y -= plotinfo.yaxis._offset;
                  if (yPixelSized) {
                    _y = r2p(plotinfo.yaxis, plotinfo.yanchor) - _y;
                  } else {
                    _y = p2r(plotinfo.yaxis, _y);
                  }
                } else {
                  if (noOffset) _y -= size.t;
                  if (domain) _y = domain.y[1] - _y / size.h;
                  else _y = 1 - _y / size.h;
                }
              }
              newPos[j][k + 1] = _x;
              newPos[j][k + 2] = _y;
            }
            polys[n].push(
              newPos[j].slice()
            );
          }
        }
        return polys;
      };
      function almostEq(a, b) {
        return Math.abs(a - b) <= 1e-6;
      }
      function dist(a, b) {
        var dx = b[1] - a[1];
        var dy = b[2] - a[2];
        return Math.sqrt(
          dx * dx + dy * dy
        );
      }
      exports.pointsOnRectangle = function(cell) {
        var len = cell.length;
        if (len !== 5) return false;
        for (var j = 1; j < 3; j++) {
          var e01 = cell[0][j] - cell[1][j];
          var e32 = cell[3][j] - cell[2][j];
          if (!almostEq(e01, e32)) return false;
          var e03 = cell[0][j] - cell[3][j];
          var e12 = cell[1][j] - cell[2][j];
          if (!almostEq(e03, e12)) return false;
        }
        if (!almostEq(cell[0][1], cell[1][1]) && !almostEq(cell[0][1], cell[3][1])) return false;
        return !!(dist(cell[0], cell[1]) * dist(cell[0], cell[3]));
      };
      exports.pointsOnEllipse = function(cell) {
        var len = cell.length;
        if (len !== CIRCLE_SIDES + 1) return false;
        len = CIRCLE_SIDES;
        for (var i = 0; i < len; i++) {
          var k = (len * 2 - i) % len;
          var k2 = (len / 2 + k) % len;
          var i2 = (len / 2 + i) % len;
          if (!almostEq(
            dist(cell[i], cell[i2]),
            dist(cell[k], cell[k2])
          )) return false;
        }
        return true;
      };
      exports.handleEllipse = function(isEllipse, start, end) {
        if (!isEllipse) return [start, end];
        var pos = exports.ellipseOver({
          x0: start[0],
          y0: start[1],
          x1: end[0],
          y1: end[1]
        });
        var cx = (pos.x1 + pos.x0) / 2;
        var cy = (pos.y1 + pos.y0) / 2;
        var rx = (pos.x1 - pos.x0) / 2;
        var ry = (pos.y1 - pos.y0) / 2;
        if (!rx) rx = ry = ry / SQRT2;
        if (!ry) ry = rx = rx / SQRT2;
        var cell = [];
        for (var i = 0; i < CIRCLE_SIDES; i++) {
          var t = i * 2 * Math.PI / CIRCLE_SIDES;
          cell.push([
            cx + rx * Math.cos(t),
            cy + ry * Math.sin(t)
          ]);
        }
        return cell;
      };
      exports.ellipseOver = function(pos) {
        var x0 = pos.x0;
        var y0 = pos.y0;
        var x1 = pos.x1;
        var y1 = pos.y1;
        var dx = x1 - x0;
        var dy = y1 - y0;
        x0 -= dx;
        y0 -= dy;
        var cx = (x0 + x1) / 2;
        var cy = (y0 + y1) / 2;
        var scale = SQRT2;
        dx *= scale;
        dy *= scale;
        return {
          x0: cx - dx,
          y0: cy - dy,
          x1: cx + dx,
          y1: cy + dy
        };
      };
      exports.fixDatesForPaths = function(polygons, xaxis, yaxis) {
        var xIsDate = xaxis.type === "date";
        var yIsDate = yaxis.type === "date";
        if (!xIsDate && !yIsDate) return polygons;
        for (var i = 0; i < polygons.length; i++) {
          for (var j = 0; j < polygons[i].length; j++) {
            for (var k = 0; k + 2 < polygons[i][j].length; k += 2) {
              if (xIsDate) polygons[i][j][k + 1] = polygons[i][j][k + 1].replace(" ", "_");
              if (yIsDate) polygons[i][j][k + 2] = polygons[i][j][k + 2].replace(" ", "_");
            }
          }
        }
        return polygons;
      };
    }
  });

  // src/components/shapes/draw_newshape/newshapes.js
  var require_newshapes = __commonJS({
    "src/components/shapes/draw_newshape/newshapes.js"(exports, module) {
      "use strict";
      var axis_ids = require_axis_ids();
      var dragHelpers = require_helpers5();
      var drawMode = dragHelpers.drawMode;
      var openMode = dragHelpers.openMode;
      var constants = require_constants4();
      var i000 = constants.i000;
      var i090 = constants.i090;
      var i180 = constants.i180;
      var i270 = constants.i270;
      var cos45 = constants.cos45;
      var sin45 = constants.sin45;
      var cartesianHelpers = require_helpers6();
      var p2r = cartesianHelpers.p2r;
      var r2p = cartesianHelpers.r2p;
      var handleOutline = require_handle_outline();
      var clearOutline = handleOutline.clearOutline;
      var helpers = require_helpers7();
      var readPaths = helpers.readPaths;
      var writePaths = helpers.writePaths;
      var ellipseOver = helpers.ellipseOver;
      var fixDatesForPaths = helpers.fixDatesForPaths;
      function newShapes(outlines, dragOptions) {
        if (!outlines.length) return;
        var e = outlines[0][0];
        if (!e) return;
        var gd = dragOptions.gd;
        var isActiveShape = dragOptions.isActiveShape;
        var dragmode = dragOptions.dragmode;
        var shapes = (gd.layout || {}).shapes || [];
        if (!drawMode(dragmode) && isActiveShape !== void 0) {
          var id = gd._fullLayout._activeShapeIndex;
          if (id < shapes.length) {
            switch (gd._fullLayout.shapes[id].type) {
              case "rect":
                dragmode = "drawrect";
                break;
              case "circle":
                dragmode = "drawcircle";
                break;
              case "line":
                dragmode = "drawline";
                break;
              case "path":
                var path = shapes[id].path || "";
                if (path[path.length - 1] === "Z") {
                  dragmode = "drawclosedpath";
                } else {
                  dragmode = "drawopenpath";
                }
                break;
            }
          }
        }
        var newShape = createShapeObj(outlines, dragOptions, dragmode);
        clearOutline(gd);
        var editHelpers = dragOptions.editHelpers;
        var modifyItem = (editHelpers || {}).modifyItem;
        var allShapes = [];
        for (var q = 0; q < shapes.length; q++) {
          var beforeEdit = gd._fullLayout.shapes[q];
          allShapes[q] = beforeEdit._input;
          if (isActiveShape !== void 0 && q === gd._fullLayout._activeShapeIndex) {
            var afterEdit = newShape;
            switch (beforeEdit.type) {
              case "line":
              case "rect":
              case "circle":
                var xaxis = axis_ids.getFromId(gd, beforeEdit.xref);
                if (beforeEdit.xref.charAt(0) === "x" && xaxis.type.includes("category")) {
                  modifyItem("x0", afterEdit.x0 - (beforeEdit.x0shift || 0));
                  modifyItem("x1", afterEdit.x1 - (beforeEdit.x1shift || 0));
                } else {
                  modifyItem("x0", afterEdit.x0);
                  modifyItem("x1", afterEdit.x1);
                }
                var yaxis = axis_ids.getFromId(gd, beforeEdit.yref);
                if (beforeEdit.yref.charAt(0) === "y" && yaxis.type.includes("category")) {
                  modifyItem("y0", afterEdit.y0 - (beforeEdit.y0shift || 0));
                  modifyItem("y1", afterEdit.y1 - (beforeEdit.y1shift || 0));
                } else {
                  modifyItem("y0", afterEdit.y0);
                  modifyItem("y1", afterEdit.y1);
                }
                break;
              case "path":
                modifyItem("path", afterEdit.path);
                break;
            }
          }
        }
        if (isActiveShape === void 0) {
          allShapes.push(newShape);
          return allShapes;
        }
        return editHelpers ? editHelpers.getUpdateObj() : {};
      }
      function createShapeObj(outlines, dragOptions, dragmode) {
        var e = outlines[0][0];
        var gd = dragOptions.gd;
        var d = e.getAttribute("d");
        var newStyle = gd._fullLayout.newshape;
        var plotinfo = dragOptions.plotinfo;
        var isActiveShape = dragOptions.isActiveShape;
        var xaxis = plotinfo.xaxis;
        var yaxis = plotinfo.yaxis;
        var xPaper = !!plotinfo.domain || !plotinfo.xaxis;
        var yPaper = !!plotinfo.domain || !plotinfo.yaxis;
        var isOpenMode = openMode(dragmode);
        var polygons = readPaths(d, gd, plotinfo, isActiveShape);
        var newShape = {
          editable: true,
          visible: newStyle.visible,
          name: newStyle.name,
          showlegend: newStyle.showlegend,
          legend: newStyle.legend,
          legendwidth: newStyle.legendwidth,
          legendgroup: newStyle.legendgroup,
          legendgrouptitle: {
            text: newStyle.legendgrouptitle.text,
            font: newStyle.legendgrouptitle.font
          },
          legendrank: newStyle.legendrank,
          label: newStyle.label,
          xref: xPaper ? "paper" : xaxis._id,
          yref: yPaper ? "paper" : yaxis._id,
          layer: newStyle.layer,
          opacity: newStyle.opacity,
          line: {
            color: newStyle.line.color,
            width: newStyle.line.width,
            dash: newStyle.line.dash
          }
        };
        if (!isOpenMode) {
          newShape.fillcolor = newStyle.fillcolor;
          newShape.fillrule = newStyle.fillrule;
        }
        var cell;
        if (polygons.length === 1) cell = polygons[0];
        if (cell && cell.length === 5 && // ensure we only have 4 corners for a rect
        dragmode === "drawrect") {
          newShape.type = "rect";
          newShape.x0 = cell[0][1];
          newShape.y0 = cell[0][2];
          newShape.x1 = cell[2][1];
          newShape.y1 = cell[2][2];
        } else if (cell && dragmode === "drawline") {
          newShape.type = "line";
          newShape.x0 = cell[0][1];
          newShape.y0 = cell[0][2];
          newShape.x1 = cell[1][1];
          newShape.y1 = cell[1][2];
        } else if (cell && dragmode === "drawcircle") {
          newShape.type = "circle";
          var xA = cell[i000][1];
          var xB = cell[i090][1];
          var xC = cell[i180][1];
          var xD = cell[i270][1];
          var yA = cell[i000][2];
          var yB = cell[i090][2];
          var yC = cell[i180][2];
          var yD = cell[i270][2];
          var xDateOrLog = plotinfo.xaxis && (plotinfo.xaxis.type === "date" || plotinfo.xaxis.type === "log");
          var yDateOrLog = plotinfo.yaxis && (plotinfo.yaxis.type === "date" || plotinfo.yaxis.type === "log");
          if (xDateOrLog) {
            xA = r2p(plotinfo.xaxis, xA);
            xB = r2p(plotinfo.xaxis, xB);
            xC = r2p(plotinfo.xaxis, xC);
            xD = r2p(plotinfo.xaxis, xD);
          }
          if (yDateOrLog) {
            yA = r2p(plotinfo.yaxis, yA);
            yB = r2p(plotinfo.yaxis, yB);
            yC = r2p(plotinfo.yaxis, yC);
            yD = r2p(plotinfo.yaxis, yD);
          }
          var x0 = (xB + xD) / 2;
          var y0 = (yA + yC) / 2;
          var rx = (xD - xB + xC - xA) / 2;
          var ry = (yD - yB + yC - yA) / 2;
          var pos = ellipseOver({
            x0,
            y0,
            x1: x0 + rx * cos45,
            y1: y0 + ry * sin45
          });
          if (xDateOrLog) {
            pos.x0 = p2r(plotinfo.xaxis, pos.x0);
            pos.x1 = p2r(plotinfo.xaxis, pos.x1);
          }
          if (yDateOrLog) {
            pos.y0 = p2r(plotinfo.yaxis, pos.y0);
            pos.y1 = p2r(plotinfo.yaxis, pos.y1);
          }
          newShape.x0 = pos.x0;
          newShape.y0 = pos.y0;
          newShape.x1 = pos.x1;
          newShape.y1 = pos.y1;
        } else {
          newShape.type = "path";
          if (xaxis && yaxis) fixDatesForPaths(polygons, xaxis, yaxis);
          newShape.path = writePaths(polygons);
          cell = null;
        }
        return newShape;
      }
      module.exports = {
        newShapes,
        createShapeObj
      };
    }
  });

  // src/components/selections/draw_newselection/newselections.js
  var require_newselections = __commonJS({
    "src/components/selections/draw_newselection/newselections.js"(exports, module) {
      "use strict";
      var dragHelpers = require_helpers5();
      var selectMode = dragHelpers.selectMode;
      var handleOutline = require_handle_outline();
      var clearOutline = handleOutline.clearOutline;
      var helpers = require_helpers7();
      var readPaths = helpers.readPaths;
      var writePaths = helpers.writePaths;
      var fixDatesForPaths = helpers.fixDatesForPaths;
      module.exports = function newSelections(outlines, dragOptions) {
        if (!outlines.length) return;
        var e = outlines[0][0];
        if (!e) return;
        var d = e.getAttribute("d");
        var gd = dragOptions.gd;
        var newStyle = gd._fullLayout.newselection;
        var plotinfo = dragOptions.plotinfo;
        var xaxis = plotinfo.xaxis;
        var yaxis = plotinfo.yaxis;
        var isActiveSelection = dragOptions.isActiveSelection;
        var dragmode = dragOptions.dragmode;
        var selections = (gd.layout || {}).selections || [];
        if (!selectMode(dragmode) && isActiveSelection !== void 0) {
          var id = gd._fullLayout._activeSelectionIndex;
          if (id < selections.length) {
            switch (gd._fullLayout.selections[id].type) {
              case "rect":
                dragmode = "select";
                break;
              case "path":
                dragmode = "lasso";
                break;
            }
          }
        }
        var polygons = readPaths(d, gd, plotinfo, isActiveSelection);
        var newSelection = {
          xref: xaxis._id,
          yref: yaxis._id,
          opacity: newStyle.opacity,
          line: {
            color: newStyle.line.color,
            width: newStyle.line.width,
            dash: newStyle.line.dash
          }
        };
        var cell;
        if (polygons.length === 1) cell = polygons[0];
        if (cell && cell.length === 5 && // ensure we only have 4 corners for a rect
        dragmode === "select") {
          newSelection.type = "rect";
          newSelection.x0 = cell[0][1];
          newSelection.y0 = cell[0][2];
          newSelection.x1 = cell[2][1];
          newSelection.y1 = cell[2][2];
        } else {
          newSelection.type = "path";
          if (xaxis && yaxis) fixDatesForPaths(polygons, xaxis, yaxis);
          newSelection.path = writePaths(polygons);
          cell = null;
        }
        clearOutline(gd);
        var editHelpers = dragOptions.editHelpers;
        var modifyItem = (editHelpers || {}).modifyItem;
        var allSelections = [];
        for (var q = 0; q < selections.length; q++) {
          var beforeEdit = gd._fullLayout.selections[q];
          if (!beforeEdit) {
            allSelections[q] = beforeEdit;
            continue;
          }
          allSelections[q] = beforeEdit._input;
          if (isActiveSelection !== void 0 && q === gd._fullLayout._activeSelectionIndex) {
            var afterEdit = newSelection;
            switch (beforeEdit.type) {
              case "rect":
                modifyItem("x0", afterEdit.x0);
                modifyItem("x1", afterEdit.x1);
                modifyItem("y0", afterEdit.y0);
                modifyItem("y1", afterEdit.y1);
                break;
              case "path":
                modifyItem("path", afterEdit.path);
                break;
            }
          }
        }
        if (isActiveSelection === void 0) {
          allSelections.push(newSelection);
          return allSelections;
        }
        return editHelpers ? editHelpers.getUpdateObj() : {};
      };
    }
  });

  // src/components/shapes/constants.js
  var require_constants5 = __commonJS({
    "src/components/shapes/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g,
        paramRE: /[^\s,]+/g,
        // which numbers in each path segment are x (or y) values
        // drawn is which param is a drawn point, as opposed to a
        // control point (which doesn't count toward autorange.
        // TODO: this means curved paths could extend beyond the
        // autorange bounds. This is a bit tricky to get right
        // unless we revert to bounding boxes, but perhaps there's
        // a calculation we could do...)
        paramIsX: {
          M: { 0: true, drawn: 0 },
          L: { 0: true, drawn: 0 },
          H: { 0: true, drawn: 0 },
          V: {},
          Q: { 0: true, 2: true, drawn: 2 },
          C: { 0: true, 2: true, 4: true, drawn: 4 },
          T: { 0: true, drawn: 0 },
          S: { 0: true, 2: true, drawn: 2 },
          // A: {0: true, 5: true},
          Z: {}
        },
        paramIsY: {
          M: { 1: true, drawn: 1 },
          L: { 1: true, drawn: 1 },
          H: {},
          V: { 0: true, drawn: 0 },
          Q: { 1: true, 3: true, drawn: 3 },
          C: { 1: true, 3: true, 5: true, drawn: 5 },
          T: { 1: true, drawn: 1 },
          S: { 1: true, 3: true, drawn: 3 },
          // A: {1: true, 6: true},
          Z: {}
        },
        numParams: {
          M: 2,
          L: 2,
          H: 1,
          V: 1,
          Q: 4,
          C: 6,
          T: 2,
          S: 4,
          // A: 7,
          Z: 0
        }
      };
    }
  });

  // src/components/shapes/helpers.js
  var require_helpers8 = __commonJS({
    "src/components/shapes/helpers.js"(exports) {
      "use strict";
      var constants = require_constants5();
      var Lib = require_lib();
      var Axes = require_axes();
      exports.rangeToShapePosition = function(ax) {
        return ax.type === "log" ? ax.r2d : function(v) {
          return v;
        };
      };
      exports.shapePositionToRange = function(ax) {
        return ax.type === "log" ? ax.d2r : function(v) {
          return v;
        };
      };
      exports.decodeDate = function(convertToPx) {
        return function(v) {
          if (v.replace) v = v.replace("_", " ");
          return convertToPx(v);
        };
      };
      exports.encodeDate = function(convertToDate) {
        return function(v) {
          return convertToDate(v).replace(" ", "_");
        };
      };
      exports.extractPathCoords = function(path, paramsToUse, isRaw) {
        var extractedCoordinates = [];
        var segments = path.match(constants.segmentRE);
        segments.forEach(function(segment) {
          var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn;
          if (relevantParamIdx === void 0) return;
          var params = segment.slice(1).match(constants.paramRE);
          if (!params || params.length < relevantParamIdx) return;
          var str = params[relevantParamIdx];
          var pos = isRaw ? str : Lib.cleanNumber(str);
          extractedCoordinates.push(pos);
        });
        return extractedCoordinates;
      };
      exports.countDefiningCoords = function(shapeType, path, axLetter) {
        if (shapeType !== "path") return 2;
        if (!path) return 0;
        const segments = path.match(constants.segmentRE);
        if (!segments) return 0;
        const paramIsAxis = axLetter === "x" ? constants.paramIsX : constants.paramIsY;
        return segments.reduce((coordCount, segment) => {
          const segmentType = segment.charAt(0);
          const hasDrawn = paramIsAxis[segmentType].drawn !== void 0;
          return coordCount + (hasDrawn ? 1 : 0);
        }, 0);
      };
      exports.getDataToPixel = function(gd, axis, shift, isVertical, refType) {
        var gs = gd._fullLayout._size;
        var dataToPixel;
        if (axis) {
          if (refType === "domain") {
            dataToPixel = function(v) {
              return axis._length * (isVertical ? 1 - v : v) + axis._offset;
            };
          } else {
            var d2r = exports.shapePositionToRange(axis);
            dataToPixel = function(v) {
              var shiftPixels = getPixelShift(axis, shift);
              return axis._offset + axis.r2p(d2r(v, true)) + shiftPixels;
            };
            if (axis.type === "date") dataToPixel = exports.decodeDate(dataToPixel);
          }
        } else if (isVertical) {
          dataToPixel = function(v) {
            return gs.t + gs.h * (1 - v);
          };
        } else {
          dataToPixel = function(v) {
            return gs.l + gs.w * v;
          };
        }
        return dataToPixel;
      };
      exports.getPixelToData = function(gd, axis, isVertical, opt) {
        var gs = gd._fullLayout._size;
        var pixelToData;
        if (axis) {
          if (opt === "domain") {
            pixelToData = function(p) {
              var q = (p - axis._offset) / axis._length;
              return isVertical ? 1 - q : q;
            };
          } else {
            var r2d = exports.rangeToShapePosition(axis);
            pixelToData = function(p) {
              return r2d(axis.p2r(p - axis._offset));
            };
          }
        } else if (isVertical) {
          pixelToData = function(p) {
            return 1 - (p - gs.t) / gs.h;
          };
        } else {
          pixelToData = function(p) {
            return (p - gs.l) / gs.w;
          };
        }
        return pixelToData;
      };
      exports.roundPositionForSharpStrokeRendering = function(pos, strokeWidth) {
        var strokeWidthIsOdd = Math.round(strokeWidth % 2) === 1;
        var posValAsInt = Math.round(pos);
        return strokeWidthIsOdd ? posValAsInt + 0.5 : posValAsInt;
      };
      exports.makeShapesOptionsAndPlotinfo = function(gd, index) {
        var options = gd._fullLayout.shapes[index] || {};
        var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
        var hasPlotinfo = !!plotinfo;
        if (hasPlotinfo) {
          plotinfo._hadPlotinfo = true;
        } else {
          plotinfo = {};
          if (options.xref && options.xref !== "paper") plotinfo.xaxis = gd._fullLayout[options.xref + "axis"];
          if (options.yref && options.yref !== "paper") plotinfo.yaxis = gd._fullLayout[options.yref + "axis"];
        }
        plotinfo.xsizemode = options.xsizemode;
        plotinfo.ysizemode = options.ysizemode;
        plotinfo.xanchor = options.xanchor;
        plotinfo.yanchor = options.yanchor;
        return {
          options,
          plotinfo
        };
      };
      exports.makeSelectionsOptionsAndPlotinfo = function(gd, index) {
        var options = gd._fullLayout.selections[index] || {};
        var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
        var hasPlotinfo = !!plotinfo;
        if (hasPlotinfo) {
          plotinfo._hadPlotinfo = true;
        } else {
          plotinfo = {};
          if (options.xref) plotinfo.xaxis = gd._fullLayout[options.xref + "axis"];
          if (options.yref) plotinfo.yaxis = gd._fullLayout[options.yref + "axis"];
        }
        return {
          options,
          plotinfo
        };
      };
      exports.getPathString = function(gd, options) {
        const shapeType = options.type;
        const xRefType = Axes.getRefType(options.xref);
        const yRefType = Axes.getRefType(options.yref);
        const gs = gd._fullLayout._size;
        var xa, ya;
        var xShiftStart, xShiftEnd, yShiftStart, yShiftEnd;
        var x2p, y2p;
        var x0, x1, y0, y1;
        function getConverter(axis, refType, shapeType2, isVertical) {
          var converter;
          if (axis) {
            if (refType === "domain") {
              if (isVertical) {
                converter = function(v) {
                  return axis._offset + axis._length * (1 - v);
                };
              } else {
                converter = function(v) {
                  return axis._offset + axis._length * v;
                };
              }
            } else {
              const d2r = exports.shapePositionToRange(axis);
              converter = function(v) {
                return axis._offset + axis.r2p(d2r(v, true));
              };
              if (shapeType2 === "path" && axis.type === "date") converter = exports.decodeDate(converter);
            }
          } else {
            if (isVertical) {
              converter = function(v) {
                return gs.t + gs.h * (1 - v);
              };
            } else {
              converter = function(v) {
                return gs.l + gs.w * v;
              };
            }
          }
          return converter;
        }
        if (xRefType === "array") {
          x2p = [];
          xa = options.xref.map(function(ref) {
            return Axes.getFromId(gd, ref);
          });
          x2p = options.xref.map(function(ref, i) {
            return getConverter(xa[i], Axes.getRefType(ref), shapeType, false);
          });
        } else {
          xa = Axes.getFromId(gd, options.xref);
          x2p = getConverter(xa, xRefType, shapeType, false);
        }
        if (yRefType === "array") {
          y2p = [];
          ya = options.yref.map(function(ref) {
            return Axes.getFromId(gd, ref);
          });
          y2p = options.yref.map(function(ref, i) {
            return getConverter(ya[i], Axes.getRefType(ref), shapeType, true);
          });
        } else {
          ya = Axes.getFromId(gd, options.yref);
          y2p = getConverter(ya, yRefType, shapeType, true);
        }
        if (shapeType === "path") {
          return convertPath(options, x2p, y2p);
        }
        if (xRefType === "array") {
          xShiftStart = getPixelShift(xa[0], options.x0shift);
          xShiftEnd = getPixelShift(xa[1], options.x1shift);
          x0 = x2p[0](options.x0) + xShiftStart;
          x1 = x2p[1](options.x1) + xShiftEnd;
        } else {
          xShiftStart = getPixelShift(xa, options.x0shift);
          xShiftEnd = getPixelShift(xa, options.x1shift);
          if (options.xsizemode === "pixel") {
            const xAnchorPos = x2p(options.xanchor);
            x0 = xAnchorPos + options.x0 + xShiftStart;
            x1 = xAnchorPos + options.x1 + xShiftEnd;
          } else {
            x0 = x2p(options.x0) + xShiftStart;
            x1 = x2p(options.x1) + xShiftEnd;
          }
        }
        if (yRefType === "array") {
          yShiftStart = getPixelShift(ya[0], options.y0shift);
          yShiftEnd = getPixelShift(ya[1], options.y1shift);
          y0 = y2p[0](options.y0) + yShiftStart;
          y1 = y2p[1](options.y1) + yShiftEnd;
        } else {
          yShiftStart = getPixelShift(ya, options.y0shift);
          yShiftEnd = getPixelShift(ya, options.y1shift);
          if (options.ysizemode === "pixel") {
            const yAnchorPos = y2p(options.yanchor);
            y0 = yAnchorPos - options.y0 + yShiftStart;
            y1 = yAnchorPos - options.y1 + yShiftEnd;
          } else {
            y0 = y2p(options.y0) + yShiftStart;
            y1 = y2p(options.y1) + yShiftEnd;
          }
        }
        if (shapeType === "line") return "M" + x0 + "," + y0 + "L" + x1 + "," + y1;
        if (shapeType === "rect") return "M" + x0 + "," + y0 + "H" + x1 + "V" + y1 + "H" + x0 + "Z";
        var cx = (x0 + x1) / 2;
        var cy = (y0 + y1) / 2;
        var rx = Math.abs(cx - x0);
        var ry = Math.abs(cy - y0);
        var rArc = "A" + rx + "," + ry;
        var rightPt = cx + rx + "," + cy;
        var topPt = cx + "," + (cy - ry);
        return "M" + rightPt + rArc + " 0 1,1 " + topPt + rArc + " 0 0,1 " + rightPt + "Z";
      };
      function convertPath(options, x2p, y2p) {
        const pathIn = options.path;
        const xSizemode = options.xsizemode;
        const ySizemode = options.ysizemode;
        const xAnchor = options.xanchor;
        const yAnchor = options.yanchor;
        const isArrayXref = Array.isArray(options.xref);
        const isArrayYref = Array.isArray(options.yref);
        var xVertexIndex = 0;
        var yVertexIndex = 0;
        return pathIn.replace(constants.segmentRE, function(segment) {
          var paramNumber = 0;
          var segmentType = segment.charAt(0);
          var xParams = constants.paramIsX[segmentType];
          var yParams = constants.paramIsY[segmentType];
          var nParams = constants.numParams[segmentType];
          const hasDrawnX = xParams.drawn !== void 0;
          const hasDrawnY = yParams.drawn !== void 0;
          const segmentX2p = isArrayXref ? x2p[xVertexIndex] : x2p;
          const segmentY2p = isArrayYref ? y2p[yVertexIndex] : y2p;
          var paramString = segment.slice(1).replace(constants.paramRE, function(param) {
            if (xParams[paramNumber]) {
              if (xSizemode === "pixel") param = segmentX2p(xAnchor) + Number(param);
              else param = segmentX2p(param);
            } else if (yParams[paramNumber]) {
              if (ySizemode === "pixel") param = segmentY2p(yAnchor) - Number(param);
              else param = segmentY2p(param);
            }
            paramNumber++;
            if (paramNumber > nParams) param = "X";
            return param;
          });
          if (paramNumber > nParams) {
            paramString = paramString.replace(/[\s,]*X.*/, "");
            Lib.log("Ignoring extra params in segment " + segment);
          }
          if (hasDrawnX) xVertexIndex++;
          if (hasDrawnY) yVertexIndex++;
          return segmentType + paramString;
        });
      }
      function getPixelShift(axis, shift) {
        shift = shift || 0;
        var shiftPixels = 0;
        if (shift && axis && (axis.type === "category" || axis.type === "multicategory")) {
          shiftPixels = (axis.r2p(1) - axis.r2p(0)) * shift;
        }
        return shiftPixels;
      }
    }
  });

  // src/components/shapes/display_labels.js
  var require_display_labels = __commonJS({
    "src/components/shapes/display_labels.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var svgTextUtils = require_svg_text_utils();
      var Drawing = require_drawing();
      var readPaths = require_helpers7().readPaths;
      var helpers = require_helpers8();
      var getPathString = helpers.getPathString;
      var shapeLabelTexttemplateVars = require_label_texttemplate();
      var FROM_TL = require_alignment().FROM_TL;
      module.exports = function drawLabel(gd, index, options, shapeGroup) {
        shapeGroup.selectAll(".shape-label").remove();
        if (!(options.label.text || options.label.texttemplate)) return;
        var text;
        if (options.label.texttemplate) {
          var templateValues = {};
          if (options.type !== "path") {
            var _xa = Axes.getFromId(gd, options.xref);
            var _ya = Axes.getFromId(gd, options.yref);
            const isMultiAxisX = Array.isArray(options.xref);
            const isMultiAxisY = Array.isArray(options.yref);
            for (var key in shapeLabelTexttemplateVars) {
              var isFunction = typeof shapeLabelTexttemplateVars[key] === "function";
              var isValidForX = !isMultiAxisX || shapeLabelTexttemplateVars.simpleXVariables.includes(key);
              var isValidForY = !isMultiAxisY || shapeLabelTexttemplateVars.simpleYVariables.includes(key);
              if (isFunction && isValidForX && isValidForY) {
                var val = shapeLabelTexttemplateVars[key](options, _xa, _ya);
                if (val !== void 0) templateValues[key] = val;
              }
            }
          }
          text = Lib.texttemplateStringForShapes({
            data: [templateValues],
            fallback: options.label.texttemplatefallback,
            locale: gd._fullLayout._d3locale,
            template: options.label.texttemplate
          });
        } else {
          text = options.label.text;
        }
        var labelGroupAttrs = {
          "data-index": index
        };
        var font = options.label.font;
        var labelTextAttrs = {
          "data-notex": 1
        };
        var labelGroup = shapeGroup.append("g").attr(labelGroupAttrs).classed("shape-label", true);
        var labelText = labelGroup.append("text").attr(labelTextAttrs).classed("shape-label-text", true).text(text);
        var shapex0, shapex1, shapey0, shapey1;
        if (options.path) {
          var d = getPathString(gd, options);
          var polygons = readPaths(d, gd);
          shapex0 = Infinity;
          shapey0 = Infinity;
          shapex1 = -Infinity;
          shapey1 = -Infinity;
          for (var i = 0; i < polygons.length; i++) {
            for (var j = 0; j < polygons[i].length; j++) {
              var p = polygons[i][j];
              for (var k = 1; k < p.length; k += 2) {
                var _x = p[k];
                var _y = p[k + 1];
                shapex0 = Math.min(shapex0, _x);
                shapex1 = Math.max(shapex1, _x);
                shapey0 = Math.min(shapey0, _y);
                shapey1 = Math.max(shapey1, _y);
              }
            }
          }
        } else {
          const isArrayXref = Array.isArray(options.xref);
          const isArrayYref = Array.isArray(options.yref);
          const xa0 = Axes.getFromId(gd, isArrayXref ? options.xref[0] : options.xref);
          const xa1 = Axes.getFromId(gd, isArrayXref ? options.xref[1] : options.xref);
          const ya0 = Axes.getFromId(gd, isArrayYref ? options.yref[0] : options.yref);
          const ya1 = Axes.getFromId(gd, isArrayYref ? options.yref[1] : options.yref);
          const xRefType0 = Axes.getRefType(isArrayXref ? options.xref[0] : options.xref);
          const xRefType1 = Axes.getRefType(isArrayXref ? options.xref[1] : options.xref);
          const yRefType0 = Axes.getRefType(isArrayYref ? options.yref[0] : options.yref);
          const yRefType1 = Axes.getRefType(isArrayYref ? options.yref[1] : options.yref);
          const x2p = function(v, shift, xa, xRefType) {
            return helpers.getDataToPixel(gd, xa, shift, false, xRefType)(v);
          };
          const y2p = function(v, shift, ya, yRefType) {
            return helpers.getDataToPixel(gd, ya, shift, true, yRefType)(v);
          };
          shapex0 = x2p(options.x0, options.x0shift, xa0, xRefType0);
          shapex1 = x2p(options.x1, options.x1shift, xa1, xRefType1);
          shapey0 = y2p(options.y0, options.y0shift, ya0, yRefType0);
          shapey1 = y2p(options.y1, options.y1shift, ya1, yRefType1);
        }
        var textangle = options.label.textangle;
        if (textangle === "auto") {
          if (options.type === "line") {
            textangle = calcTextAngle(shapex0, shapey0, shapex1, shapey1);
          } else {
            textangle = 0;
          }
        }
        labelText.call(function(s) {
          s.call(Drawing.font, font).attr({});
          svgTextUtils.convertToTspans(s, gd);
          return s;
        });
        var textBB = Drawing.bBox(labelText.node());
        var textPos = calcTextPosition(shapex0, shapey0, shapex1, shapey1, options, textangle, textBB);
        var textx = textPos.textx;
        var texty = textPos.texty;
        var xanchor = textPos.xanchor;
        labelText.attr({
          "text-anchor": {
            left: "start",
            center: "middle",
            right: "end"
          }[xanchor],
          y: texty,
          x: textx,
          transform: "rotate(" + textangle + "," + textx + "," + texty + ")"
        }).call(svgTextUtils.positionText, textx, texty);
      };
      function calcTextAngle(shapex0, shapey0, shapex1, shapey1) {
        var dy, dx;
        dx = Math.abs(shapex1 - shapex0);
        if (shapex1 >= shapex0) {
          dy = shapey0 - shapey1;
        } else {
          dy = shapey1 - shapey0;
        }
        return -180 / Math.PI * Math.atan2(dy, dx);
      }
      function calcTextPosition(shapex0, shapey0, shapex1, shapey1, shapeOptions, actualTextAngle, textBB) {
        var textPosition = shapeOptions.label.textposition;
        var textAngle = shapeOptions.label.textangle;
        var textPadding = shapeOptions.label.padding;
        var shapeType = shapeOptions.type;
        var textAngleRad = Math.PI / 180 * actualTextAngle;
        var sinA = Math.sin(textAngleRad);
        var cosA = Math.cos(textAngleRad);
        var xanchor = shapeOptions.label.xanchor;
        var yanchor = shapeOptions.label.yanchor;
        var textx, texty, paddingX, paddingY;
        if (shapeType === "line") {
          if (textPosition === "start") {
            textx = shapex0;
            texty = shapey0;
          } else if (textPosition === "end") {
            textx = shapex1;
            texty = shapey1;
          } else {
            textx = (shapex0 + shapex1) / 2;
            texty = (shapey0 + shapey1) / 2;
          }
          if (xanchor === "auto") {
            if (textPosition === "start") {
              if (textAngle === "auto") {
                if (shapex1 > shapex0) xanchor = "left";
                else if (shapex1 < shapex0) xanchor = "right";
                else xanchor = "center";
              } else {
                if (shapex1 > shapex0) xanchor = "right";
                else if (shapex1 < shapex0) xanchor = "left";
                else xanchor = "center";
              }
            } else if (textPosition === "end") {
              if (textAngle === "auto") {
                if (shapex1 > shapex0) xanchor = "right";
                else if (shapex1 < shapex0) xanchor = "left";
                else xanchor = "center";
              } else {
                if (shapex1 > shapex0) xanchor = "left";
                else if (shapex1 < shapex0) xanchor = "right";
                else xanchor = "center";
              }
            } else {
              xanchor = "center";
            }
          }
          var paddingConstantsX = { left: 1, center: 0, right: -1 };
          var paddingConstantsY = { bottom: -1, middle: 0, top: 1 };
          if (textAngle === "auto") {
            var paddingDirection = paddingConstantsY[yanchor];
            paddingX = -textPadding * sinA * paddingDirection;
            paddingY = textPadding * cosA * paddingDirection;
          } else {
            var paddingDirectionX = paddingConstantsX[xanchor];
            var paddingDirectionY = paddingConstantsY[yanchor];
            paddingX = textPadding * paddingDirectionX;
            paddingY = textPadding * paddingDirectionY;
          }
          textx = textx + paddingX;
          texty = texty + paddingY;
        } else {
          paddingX = textPadding + 3;
          if (textPosition.indexOf("right") !== -1) {
            textx = Math.max(shapex0, shapex1) - paddingX;
            if (xanchor === "auto") xanchor = "right";
          } else if (textPosition.indexOf("left") !== -1) {
            textx = Math.min(shapex0, shapex1) + paddingX;
            if (xanchor === "auto") xanchor = "left";
          } else {
            textx = (shapex0 + shapex1) / 2;
            if (xanchor === "auto") xanchor = "center";
          }
          if (textPosition.indexOf("top") !== -1) {
            texty = Math.min(shapey0, shapey1);
          } else if (textPosition.indexOf("bottom") !== -1) {
            texty = Math.max(shapey0, shapey1);
          } else {
            texty = (shapey0 + shapey1) / 2;
          }
          paddingY = textPadding;
          if (yanchor === "bottom") {
            texty = texty - paddingY;
          } else if (yanchor === "top") {
            texty = texty + paddingY;
          }
        }
        var shiftFraction = FROM_TL[yanchor];
        var baselineAdjust = shapeOptions.label.font.size;
        var textHeight = textBB.height;
        var xshift = (textHeight * shiftFraction - baselineAdjust) * sinA;
        var yshift = -(textHeight * shiftFraction - baselineAdjust) * cosA;
        return { textx: textx + xshift, texty: texty + yshift, xanchor };
      }
    }
  });

  // src/components/shapes/display_outlines.js
  var require_display_outlines = __commonJS({
    "src/components/shapes/display_outlines.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var dragElement = require_dragelement();
      var dragHelpers = require_helpers5();
      var drawMode = dragHelpers.drawMode;
      var selectMode = dragHelpers.selectMode;
      var Registry = require_registry();
      var Color2 = require_color();
      var constants = require_constants4();
      var i000 = constants.i000;
      var i090 = constants.i090;
      var i180 = constants.i180;
      var i270 = constants.i270;
      var handleOutline = require_handle_outline();
      var clearOutlineControllers = handleOutline.clearOutlineControllers;
      var helpers = require_helpers7();
      var pointsOnRectangle = helpers.pointsOnRectangle;
      var pointsOnEllipse = helpers.pointsOnEllipse;
      var writePaths = helpers.writePaths;
      var newShapes = require_newshapes().newShapes;
      var createShapeObj = require_newshapes().createShapeObj;
      var newSelections = require_newselections();
      var drawLabel = require_display_labels();
      module.exports = function displayOutlines(polygons, outlines, dragOptions, nCalls) {
        if (!nCalls) nCalls = 0;
        var gd = dragOptions.gd;
        function redraw() {
          displayOutlines(polygons, outlines, dragOptions, nCalls++);
          if (pointsOnEllipse(polygons[0]) || dragOptions.hasText) {
            update({ redrawing: true });
          }
        }
        function update(opts) {
          var updateObject = {};
          if (dragOptions.isActiveShape !== void 0) {
            dragOptions.isActiveShape = false;
            updateObject = newShapes(outlines, dragOptions);
          }
          if (dragOptions.isActiveSelection !== void 0) {
            dragOptions.isActiveSelection = false;
            updateObject = newSelections(outlines, dragOptions);
            gd._fullLayout._reselect = true;
          }
          if (Object.keys(updateObject).length) {
            Registry.call((opts || {}).redrawing ? "relayout" : "_guiRelayout", gd, updateObject);
          }
        }
        var fullLayout = gd._fullLayout;
        var zoomLayer = fullLayout._zoomlayer;
        var dragmode = dragOptions.dragmode;
        var isDrawMode = drawMode(dragmode);
        var isSelectMode = selectMode(dragmode);
        if (isDrawMode || isSelectMode) {
          gd._fullLayout._outlining = true;
        }
        clearOutlineControllers(gd);
        outlines.attr("d", writePaths(polygons));
        var vertexDragOptions;
        var groupDragOptions;
        var indexI;
        var indexJ;
        var copyPolygons;
        if (!nCalls && (dragOptions.isActiveShape || dragOptions.isActiveSelection)) {
          copyPolygons = recordPositions([], polygons);
          var g = zoomLayer.append("g").attr("class", "outline-controllers");
          addVertexControllers(g);
          addGroupControllers();
        }
        if (isDrawMode && dragOptions.hasText) {
          var shapeGroup = zoomLayer.select(".label-temp");
          var shapeOptions = createShapeObj(outlines, dragOptions, dragOptions.dragmode);
          drawLabel(gd, "label-temp", shapeOptions, shapeGroup);
        }
        function startDragVertex(evt) {
          indexI = +evt.srcElement.getAttribute("data-i");
          indexJ = +evt.srcElement.getAttribute("data-j");
          vertexDragOptions[indexI][indexJ].moveFn = moveVertexController;
        }
        function moveVertexController(dx, dy) {
          if (!polygons.length) return;
          var x0 = copyPolygons[indexI][indexJ][1];
          var y0 = copyPolygons[indexI][indexJ][2];
          var cell = polygons[indexI];
          var len = cell.length;
          if (pointsOnRectangle(cell)) {
            var _dx = dx;
            var _dy = dy;
            if (dragOptions.isActiveSelection) {
              var nextPoint = getNextPoint(cell, indexJ);
              if (nextPoint[1] === cell[indexJ][1]) {
                _dy = 0;
              } else {
                _dx = 0;
              }
            }
            for (var q = 0; q < len; q++) {
              if (q === indexJ) continue;
              var pos = cell[q];
              if (pos[1] === cell[indexJ][1]) {
                pos[1] = x0 + _dx;
              }
              if (pos[2] === cell[indexJ][2]) {
                pos[2] = y0 + _dy;
              }
            }
            cell[indexJ][1] = x0 + _dx;
            cell[indexJ][2] = y0 + _dy;
            if (!pointsOnRectangle(cell)) {
              for (var j = 0; j < len; j++) {
                for (var k = 0; k < cell[j].length; k++) {
                  cell[j][k] = copyPolygons[indexI][j][k];
                }
              }
            }
          } else {
            cell[indexJ][1] = x0 + dx;
            cell[indexJ][2] = y0 + dy;
          }
          redraw();
        }
        function endDragVertexController() {
          update();
        }
        function removeVertex() {
          if (!polygons.length) return;
          if (!polygons[indexI]) return;
          if (!polygons[indexI].length) return;
          var newPolygon = [];
          for (var j = 0; j < polygons[indexI].length; j++) {
            if (j !== indexJ) {
              newPolygon.push(
                polygons[indexI][j]
              );
            }
          }
          if (newPolygon.length > 1 && !(newPolygon.length === 2 && newPolygon[1][0] === "Z")) {
            if (indexJ === 0) {
              newPolygon[0][0] = "M";
            }
            polygons[indexI] = newPolygon;
            redraw();
            update();
          }
        }
        function clickVertexController(numClicks, evt) {
          if (numClicks === 2) {
            indexI = +evt.srcElement.getAttribute("data-i");
            indexJ = +evt.srcElement.getAttribute("data-j");
            var cell = polygons[indexI];
            if (!pointsOnRectangle(cell) && !pointsOnEllipse(cell)) {
              removeVertex();
            }
          }
        }
        function addVertexControllers(g2) {
          vertexDragOptions = [];
          for (var i = 0; i < polygons.length; i++) {
            var cell = polygons[i];
            var onRect = pointsOnRectangle(cell);
            var onEllipse = !onRect && pointsOnEllipse(cell);
            vertexDragOptions[i] = [];
            var len = cell.length;
            for (var j = 0; j < len; j++) {
              if (cell[j][0] === "Z") continue;
              if (onEllipse && j !== i000 && j !== i090 && j !== i180 && j !== i270) {
                continue;
              }
              var rectSelection = onRect && dragOptions.isActiveSelection;
              var nextPoint;
              if (rectSelection) nextPoint = getNextPoint(cell, j);
              var x = cell[j][1];
              var y = cell[j][2];
              var vertex = g2.append(rectSelection ? "rect" : "circle").attr("data-i", i).attr("data-j", j).style({
                fill: Color2.background,
                stroke: Color2.defaultLine,
                "stroke-width": 1,
                "shape-rendering": "crispEdges"
              });
              if (rectSelection) {
                var dx = nextPoint[1] - x;
                var dy = nextPoint[2] - y;
                var width = dy ? 5 : Math.max(Math.min(25, Math.abs(dx) - 5), 5);
                var height = dx ? 5 : Math.max(Math.min(25, Math.abs(dy) - 5), 5);
                vertex.classed(dy ? "cursor-ew-resize" : "cursor-ns-resize", true).attr("width", width).attr("height", height).attr("x", x - width / 2).attr("y", y - height / 2).attr("transform", strTranslate(dx / 2, dy / 2));
              } else {
                vertex.classed("cursor-grab", true).attr("r", 5).attr("cx", x).attr("cy", y);
              }
              vertexDragOptions[i][j] = {
                element: vertex.node(),
                gd,
                prepFn: startDragVertex,
                doneFn: endDragVertexController,
                clickFn: clickVertexController
              };
              dragElement.init(vertexDragOptions[i][j]);
            }
          }
        }
        function moveGroup(dx, dy) {
          if (!polygons.length) return;
          for (var i = 0; i < polygons.length; i++) {
            for (var j = 0; j < polygons[i].length; j++) {
              for (var k = 0; k + 2 < polygons[i][j].length; k += 2) {
                polygons[i][j][k + 1] = copyPolygons[i][j][k + 1] + dx;
                polygons[i][j][k + 2] = copyPolygons[i][j][k + 2] + dy;
              }
            }
          }
        }
        function moveGroupController(dx, dy) {
          moveGroup(dx, dy);
          redraw();
        }
        function startDragGroupController(evt) {
          indexI = +evt.srcElement.getAttribute("data-i");
          if (!indexI) indexI = 0;
          groupDragOptions[indexI].moveFn = moveGroupController;
        }
        function endDragGroupController() {
          update();
        }
        function clickGroupController(numClicks) {
          if (numClicks === 2) {
            eraseActiveSelection(gd);
          }
        }
        function addGroupControllers() {
          groupDragOptions = [];
          if (!polygons.length) return;
          var i = 0;
          groupDragOptions[i] = {
            element: outlines[0][0],
            gd,
            prepFn: startDragGroupController,
            doneFn: endDragGroupController,
            clickFn: clickGroupController
          };
          dragElement.init(groupDragOptions[i]);
        }
      };
      function recordPositions(polygonsOut, polygonsIn) {
        for (var i = 0; i < polygonsIn.length; i++) {
          var cell = polygonsIn[i];
          polygonsOut[i] = [];
          for (var j = 0; j < cell.length; j++) {
            polygonsOut[i][j] = [];
            for (var k = 0; k < cell[j].length; k++) {
              polygonsOut[i][j][k] = cell[j][k];
            }
          }
        }
        return polygonsOut;
      }
      function getNextPoint(cell, j) {
        var x = cell[j][1];
        var y = cell[j][2];
        var len = cell.length;
        var nextJ, nextX, nextY;
        nextJ = (j + 1) % len;
        nextX = cell[nextJ][1];
        nextY = cell[nextJ][2];
        if (nextX === x && nextY === y) {
          nextJ = (j + 2) % len;
          nextX = cell[nextJ][1];
          nextY = cell[nextJ][2];
        }
        return [nextJ, nextX, nextY];
      }
      function eraseActiveSelection(gd) {
        if (!selectMode(gd._fullLayout.dragmode)) return;
        clearOutlineControllers(gd);
        var id = gd._fullLayout._activeSelectionIndex;
        var selections = (gd.layout || {}).selections || [];
        if (id < selections.length) {
          var list = [];
          for (var q = 0; q < selections.length; q++) {
            if (q !== id) {
              list.push(selections[q]);
            }
          }
          delete gd._fullLayout._activeSelectionIndex;
          var erasedSelection = gd._fullLayout.selections[id];
          gd._fullLayout._deselect = {
            xref: erasedSelection.xref,
            yref: erasedSelection.yref
          };
          Registry.call("_guiRelayout", gd, {
            selections: list
          });
        }
      }
    }
  });

  // src/components/shapes/draw.js
  var require_draw2 = __commonJS({
    "src/components/shapes/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Lib = require_lib();
      var Axes = require_axes();
      var readPaths = require_helpers7().readPaths;
      var displayOutlines = require_display_outlines();
      var drawLabel = require_display_labels();
      var clearOutlineControllers = require_handle_outline().clearOutlineControllers;
      var Color2 = require_color();
      var Drawing = require_drawing();
      var arrayEditor = require_plot_template().arrayEditor;
      var dragElement = require_dragelement();
      var setCursor = require_setcursor();
      var constants = require_constants5();
      var helpers = require_helpers8();
      var getPathString = helpers.getPathString;
      module.exports = {
        draw,
        drawOne,
        eraseActiveShape,
        drawLabel
      };
      function draw(gd) {
        var fullLayout = gd._fullLayout;
        fullLayout._shapeUpperLayer.selectAll("path").remove();
        fullLayout._shapeLowerLayer.selectAll("path").remove();
        fullLayout._shapeUpperLayer.selectAll("text").remove();
        fullLayout._shapeLowerLayer.selectAll("text").remove();
        for (var k in fullLayout._plots) {
          var shapelayer = fullLayout._plots[k].shapelayer;
          if (shapelayer) {
            shapelayer.selectAll("path").remove();
            shapelayer.selectAll("text").remove();
          }
        }
        for (var i = 0; i < fullLayout.shapes.length; i++) {
          if (fullLayout.shapes[i].visible === true) {
            drawOne(gd, i);
          }
        }
      }
      function shouldSkipEdits(gd) {
        return !!gd._fullLayout._outlining;
      }
      function couldHaveActiveShape(gd) {
        return !gd._context.edits.shapePosition;
      }
      function drawOne(gd, index) {
        gd._fullLayout._paperdiv.selectAll('.shapelayer [data-index="' + index + '"]').remove();
        var o = helpers.makeShapesOptionsAndPlotinfo(gd, index);
        var options = o.options;
        var plotinfo = o.plotinfo;
        if (!options._input || options.visible !== true) return;
        const isMultiAxisShape = Array.isArray(options.xref) || Array.isArray(options.yref);
        if (options.layer === "above") {
          drawShape(gd._fullLayout._shapeUpperLayer);
        } else if (options.xref.includes("paper") || options.yref.includes("paper")) {
          drawShape(gd._fullLayout._shapeLowerLayer);
        } else if (options.layer === "between" && !isMultiAxisShape) {
          drawShape(plotinfo.shapelayerBetween);
        } else {
          if (plotinfo._hadPlotinfo) {
            var mainPlot = plotinfo.mainplotinfo || plotinfo;
            drawShape(mainPlot.shapelayer);
          } else {
            drawShape(gd._fullLayout._shapeLowerLayer);
          }
        }
        function drawShape(shapeLayer) {
          var d = getPathString(gd, options);
          var attrs = {
            "data-index": index,
            "fill-rule": options.fillrule,
            d
          };
          var opacity = options.opacity;
          var fillColor = options.fillcolor;
          var lineColor = options.line.width ? options.line.color : "rgba(0,0,0,0)";
          var lineWidth = options.line.width;
          var lineDash = options.line.dash;
          if (!lineWidth && options.editable === true) {
            lineWidth = 5;
            lineDash = "solid";
          }
          var isOpen = d[d.length - 1] !== "Z";
          var isActiveShape = couldHaveActiveShape(gd) && options.editable && gd._fullLayout._activeShapeIndex === index;
          if (isActiveShape) {
            fillColor = isOpen ? "rgba(0,0,0,0)" : gd._fullLayout.activeshape.fillcolor;
            opacity = gd._fullLayout.activeshape.opacity;
          }
          var shapeGroup = shapeLayer.append("g").classed("shape-group", true).attr({ "data-index": index });
          var path = shapeGroup.append("path").attr(attrs).style("opacity", opacity).call(Color2.stroke, lineColor).call(Color2.fill, fillColor).call(Drawing.dashLine, lineDash, lineWidth);
          setClipPath(shapeGroup, gd, options);
          drawLabel(gd, index, options, shapeGroup);
          var editHelpers;
          if (isActiveShape || gd._context.edits.shapePosition) editHelpers = arrayEditor(gd.layout, "shapes", options);
          if (isActiveShape) {
            path.style({
              cursor: "move"
            });
            var dragOptions = {
              element: path.node(),
              plotinfo,
              gd,
              editHelpers,
              hasText: options.label.text || options.label.texttemplate,
              isActiveShape: true
              // i.e. to enable controllers
            };
            var polygons = readPaths(d, gd);
            displayOutlines(polygons, path, dragOptions);
          } else {
            if (gd._context.edits.shapePosition) {
              setupDragElement(gd, path, options, index, shapeLayer, editHelpers);
            } else if (options.editable === true) {
              path.style(
                "pointer-events",
                isOpen || Color2.opacity(fillColor) * opacity <= 0.5 ? "stroke" : "all"
              );
            }
          }
          path.node().addEventListener("click", function() {
            return activateShape(gd, path);
          });
        }
      }
      function setClipPath(shapePath, gd, shapeOptions) {
        const xref = shapeOptions.xref;
        const yref = shapeOptions.yref;
        if (Array.isArray(xref) || Array.isArray(yref)) {
          const clipId = "clip" + gd._fullLayout._uid + "shape" + shapeOptions._index;
          const rect = getMultiAxisClipRect(gd, xref, yref);
          Lib.ensureSingleById(gd._fullLayout._clips, "clipPath", clipId, function(s) {
            s.append("rect");
          }).select("rect").attr(rect);
          Drawing.setClipUrl(shapePath, clipId, gd);
        } else {
          const clipAxes = (xref + yref).replace(/paper/g, "").replace(/[xyz][0-9]* *domain/g, "");
          Drawing.setClipUrl(shapePath, clipAxes ? "clip" + gd._fullLayout._uid + clipAxes : null, gd);
        }
      }
      function getMultiAxisClipRect(gd, xref, yref) {
        const gs = gd._fullLayout._size;
        function getBounds(refs, isVertical) {
          const axes = (Array.isArray(refs) ? refs : [refs]).map((r) => Axes.getFromId(gd, r)).filter(Boolean);
          if (!axes.length) {
            return isVertical ? [gs.t, gs.t + gs.h] : [gs.l, gs.l + gs.w];
          }
          const startBounds = axes.map(function(ax) {
            return ax._offset;
          });
          const endBounds = axes.map(function(ax) {
            return ax._offset + ax._length;
          });
          return [Math.min(...startBounds), Math.max(...endBounds)];
        }
        const xb = getBounds(xref, false);
        const yb = getBounds(yref, true);
        return { x: xb[0], y: yb[0], width: xb[1] - xb[0], height: yb[1] - yb[0] };
      }
      function setupDragElement(gd, shapePath, shapeOptions, index, shapeLayer, editHelpers) {
        var MINWIDTH = 10;
        var MINHEIGHT = 10;
        var xPixelSized = shapeOptions.xsizemode === "pixel";
        var yPixelSized = shapeOptions.ysizemode === "pixel";
        var isLine = shapeOptions.type === "line";
        var isPath = shapeOptions.type === "path";
        var modifyItem = editHelpers.modifyItem;
        var x0, y0, x1, y1, xAnchor, yAnchor;
        var n0, s0, w0, e0, optN, optS, optW, optE;
        var pathIn;
        var shapeGroup = d3.select(shapePath.node().parentNode);
        var xa = Axes.getFromId(gd, shapeOptions.xref);
        var xRefType = Axes.getRefType(shapeOptions.xref);
        var ya = Axes.getFromId(gd, shapeOptions.yref);
        var yRefType = Axes.getRefType(shapeOptions.yref);
        var shiftXStart = shapeOptions.x0shift;
        var shiftXEnd = shapeOptions.x1shift;
        var shiftYStart = shapeOptions.y0shift;
        var shiftYEnd = shapeOptions.y1shift;
        var x2p = function(v, shift) {
          var dataToPixel = helpers.getDataToPixel(gd, xa, shift, false, xRefType);
          return dataToPixel(v);
        };
        var y2p = function(v, shift) {
          var dataToPixel = helpers.getDataToPixel(gd, ya, shift, true, yRefType);
          return dataToPixel(v);
        };
        var p2x = helpers.getPixelToData(gd, xa, false, xRefType);
        var p2y = helpers.getPixelToData(gd, ya, true, yRefType);
        var sensoryElement = obtainSensoryElement();
        var dragOptions = {
          element: sensoryElement.node(),
          gd,
          prepFn: startDrag,
          doneFn: endDrag,
          clickFn: abortDrag
        };
        var dragMode;
        dragElement.init(dragOptions);
        sensoryElement.node().onmousemove = updateDragMode;
        function obtainSensoryElement() {
          return isLine ? createLineDragHandles() : shapePath;
        }
        function createLineDragHandles() {
          var minSensoryWidth = 10;
          var sensoryWidth = Math.max(shapeOptions.line.width, minSensoryWidth);
          var g = shapeLayer.append("g").attr("data-index", index).attr("drag-helper", true);
          g.append("path").attr("d", shapePath.attr("d")).style({
            cursor: "move",
            "stroke-width": sensoryWidth,
            "stroke-opacity": "0"
            // ensure not visible
          });
          var circleStyle = {
            "fill-opacity": "0"
            // ensure not visible
          };
          var circleRadius = Math.max(sensoryWidth / 2, minSensoryWidth);
          g.append("circle").attr({
            "data-line-point": "start-point",
            cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0, shiftXStart),
            cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0, shiftYStart),
            r: circleRadius
          }).style(circleStyle).classed("cursor-grab", true);
          g.append("circle").attr({
            "data-line-point": "end-point",
            cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x1 : x2p(shapeOptions.x1, shiftXEnd),
            cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1, shiftYEnd),
            r: circleRadius
          }).style(circleStyle).classed("cursor-grab", true);
          return g;
        }
        function updateDragMode(evt) {
          if (shouldSkipEdits(gd)) {
            dragMode = null;
            return;
          }
          if (isLine) {
            if (evt.target.tagName === "path") {
              dragMode = "move";
            } else {
              dragMode = evt.target.attributes["data-line-point"].value === "start-point" ? "resize-over-start-point" : "resize-over-end-point";
            }
          } else {
            var dragBBox = dragOptions.element.getBoundingClientRect();
            var w = dragBBox.right - dragBBox.left;
            var h = dragBBox.bottom - dragBBox.top;
            var x = evt.clientX - dragBBox.left;
            var y = evt.clientY - dragBBox.top;
            var cursor = !isPath && w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey ? dragElement.getCursor(x / w, 1 - y / h) : "move";
            setCursor(shapePath, cursor);
            dragMode = cursor.split("-")[0];
          }
        }
        function startDrag(evt) {
          if (shouldSkipEdits(gd)) return;
          if (xPixelSized) {
            xAnchor = x2p(shapeOptions.xanchor);
          }
          if (yPixelSized) {
            yAnchor = y2p(shapeOptions.yanchor);
          }
          if (shapeOptions.type === "path") {
            pathIn = shapeOptions.path;
          } else {
            x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0);
            y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0);
            x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1);
            y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1);
          }
          if (x0 < x1) {
            w0 = x0;
            optW = "x0";
            e0 = x1;
            optE = "x1";
          } else {
            w0 = x1;
            optW = "x1";
            e0 = x0;
            optE = "x0";
          }
          if (!yPixelSized && y0 < y1 || yPixelSized && y0 > y1) {
            n0 = y0;
            optN = "y0";
            s0 = y1;
            optS = "y1";
          } else {
            n0 = y1;
            optN = "y1";
            s0 = y0;
            optS = "y0";
          }
          updateDragMode(evt);
          renderVisualCues(shapeLayer, shapeOptions);
          deactivateClipPathTemporarily(shapePath, shapeOptions, gd);
          dragOptions.moveFn = dragMode === "move" ? moveShape : resizeShape;
          dragOptions.altKey = evt.altKey;
        }
        function endDrag() {
          if (shouldSkipEdits(gd)) return;
          setCursor(shapePath);
          removeVisualCues(shapeLayer);
          setClipPath(shapePath, gd, shapeOptions);
          Registry.call("_guiRelayout", gd, editHelpers.getUpdateObj());
        }
        function abortDrag() {
          if (shouldSkipEdits(gd)) return;
          removeVisualCues(shapeLayer);
        }
        function moveShape(dx, dy) {
          if (shapeOptions.type === "path") {
            var noOp = function(coord) {
              return coord;
            };
            var moveX = noOp;
            var moveY = noOp;
            if (xPixelSized) {
              modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
              moveX = function moveX2(x) {
                return p2x(x2p(x) + dx);
              };
              if (xa && xa.type === "date") moveX = helpers.encodeDate(moveX);
            }
            if (yPixelSized) {
              modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
              moveY = function moveY2(y) {
                return p2y(y2p(y) + dy);
              };
              if (ya && ya.type === "date") moveY = helpers.encodeDate(moveY);
            }
            modifyItem("path", shapeOptions.path = movePath(pathIn, moveX, moveY));
          } else {
            if (xPixelSized) {
              modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
              modifyItem("x0", shapeOptions.x0 = p2x(x0 + dx));
              modifyItem("x1", shapeOptions.x1 = p2x(x1 + dx));
            }
            if (yPixelSized) {
              modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
              modifyItem("y0", shapeOptions.y0 = p2y(y0 + dy));
              modifyItem("y1", shapeOptions.y1 = p2y(y1 + dy));
            }
          }
          shapePath.attr("d", getPathString(gd, shapeOptions));
          renderVisualCues(shapeLayer, shapeOptions);
          drawLabel(gd, index, shapeOptions, shapeGroup);
        }
        function resizeShape(dx, dy) {
          if (isPath) {
            var noOp = function(coord) {
              return coord;
            };
            var moveX = noOp;
            var moveY = noOp;
            if (xPixelSized) {
              modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx));
            } else {
              moveX = function moveX2(x) {
                return p2x(x2p(x) + dx);
              };
              if (xa && xa.type === "date") moveX = helpers.encodeDate(moveX);
            }
            if (yPixelSized) {
              modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy));
            } else {
              moveY = function moveY2(y) {
                return p2y(y2p(y) + dy);
              };
              if (ya && ya.type === "date") moveY = helpers.encodeDate(moveY);
            }
            modifyItem("path", shapeOptions.path = movePath(pathIn, moveX, moveY));
          } else if (isLine) {
            if (dragMode === "resize-over-start-point") {
              var newX0 = x0 + dx;
              var newY0 = yPixelSized ? y0 - dy : y0 + dy;
              modifyItem("x0", shapeOptions.x0 = xPixelSized ? newX0 : p2x(newX0));
              modifyItem("y0", shapeOptions.y0 = yPixelSized ? newY0 : p2y(newY0));
            } else if (dragMode === "resize-over-end-point") {
              var newX1 = x1 + dx;
              var newY1 = yPixelSized ? y1 - dy : y1 + dy;
              modifyItem("x1", shapeOptions.x1 = xPixelSized ? newX1 : p2x(newX1));
              modifyItem("y1", shapeOptions.y1 = yPixelSized ? newY1 : p2y(newY1));
            }
          } else {
            var has = function(str) {
              return dragMode.indexOf(str) !== -1;
            };
            var hasN = has("n");
            var hasS = has("s");
            var hasW = has("w");
            var hasE = has("e");
            var newN = hasN ? n0 + dy : n0;
            var newS = hasS ? s0 + dy : s0;
            var newW = hasW ? w0 + dx : w0;
            var newE = hasE ? e0 + dx : e0;
            if (yPixelSized) {
              if (hasN) newN = n0 - dy;
              if (hasS) newS = s0 - dy;
            }
            if (!yPixelSized && newS - newN > MINHEIGHT || yPixelSized && newN - newS > MINHEIGHT) {
              modifyItem(optN, shapeOptions[optN] = yPixelSized ? newN : p2y(newN));
              modifyItem(optS, shapeOptions[optS] = yPixelSized ? newS : p2y(newS));
            }
            if (newE - newW > MINWIDTH) {
              modifyItem(optW, shapeOptions[optW] = xPixelSized ? newW : p2x(newW));
              modifyItem(optE, shapeOptions[optE] = xPixelSized ? newE : p2x(newE));
            }
          }
          shapePath.attr("d", getPathString(gd, shapeOptions));
          renderVisualCues(shapeLayer, shapeOptions);
          drawLabel(gd, index, shapeOptions, shapeGroup);
        }
        function renderVisualCues(shapeLayer2, shapeOptions2) {
          if (xPixelSized || yPixelSized) {
            renderAnchor();
          }
          function renderAnchor() {
            var isNotPath = shapeOptions2.type !== "path";
            var visualCues = shapeLayer2.selectAll(".visual-cue").data([0]);
            var strokeWidth = 1;
            visualCues.enter().append("path").attr({
              fill: "#fff",
              "fill-rule": "evenodd",
              stroke: "#000",
              "stroke-width": strokeWidth
            }).classed("visual-cue", true);
            var posX = x2p(
              xPixelSized ? shapeOptions2.xanchor : Lib.midRange(
                isNotPath ? [shapeOptions2.x0, shapeOptions2.x1] : helpers.extractPathCoords(shapeOptions2.path, constants.paramIsX)
              )
            );
            var posY = y2p(
              yPixelSized ? shapeOptions2.yanchor : Lib.midRange(
                isNotPath ? [shapeOptions2.y0, shapeOptions2.y1] : helpers.extractPathCoords(shapeOptions2.path, constants.paramIsY)
              )
            );
            posX = helpers.roundPositionForSharpStrokeRendering(posX, strokeWidth);
            posY = helpers.roundPositionForSharpStrokeRendering(posY, strokeWidth);
            if (xPixelSized && yPixelSized) {
              var crossPath = "M" + (posX - 1 - strokeWidth) + "," + (posY - 1 - strokeWidth) + "h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z";
              visualCues.attr("d", crossPath);
            } else if (xPixelSized) {
              var vBarPath = "M" + (posX - 1 - strokeWidth) + "," + (posY - 9 - strokeWidth) + "v18 h2 v-18 Z";
              visualCues.attr("d", vBarPath);
            } else {
              var hBarPath = "M" + (posX - 9 - strokeWidth) + "," + (posY - 1 - strokeWidth) + "h18 v2 h-18 Z";
              visualCues.attr("d", hBarPath);
            }
          }
        }
        function removeVisualCues(shapeLayer2) {
          shapeLayer2.selectAll(".visual-cue").remove();
        }
        function deactivateClipPathTemporarily(shapePath2, shapeOptions2, gd2) {
          var xref = shapeOptions2.xref;
          var yref = shapeOptions2.yref;
          var xa2 = Axes.getFromId(gd2, xref);
          var ya2 = Axes.getFromId(gd2, yref);
          var clipAxes = "";
          if (xref !== "paper" && !xa2.autorange) clipAxes += xref;
          if (yref !== "paper" && !ya2.autorange) clipAxes += yref;
          Drawing.setClipUrl(
            shapePath2,
            clipAxes ? "clip" + gd2._fullLayout._uid + clipAxes : null,
            gd2
          );
        }
      }
      function movePath(pathIn, moveX, moveY) {
        return pathIn.replace(constants.segmentRE, function(segment) {
          var paramNumber = 0;
          var segmentType = segment.charAt(0);
          var xParams = constants.paramIsX[segmentType];
          var yParams = constants.paramIsY[segmentType];
          var nParams = constants.numParams[segmentType];
          var paramString = segment.slice(1).replace(constants.paramRE, function(param) {
            if (paramNumber >= nParams) return param;
            if (xParams[paramNumber]) param = moveX(param);
            else if (yParams[paramNumber]) param = moveY(param);
            paramNumber++;
            return param;
          });
          return segmentType + paramString;
        });
      }
      function activateShape(gd, path) {
        if (!couldHaveActiveShape(gd)) return;
        var element = path.node();
        var id = +element.getAttribute("data-index");
        if (id >= 0) {
          if (id === gd._fullLayout._activeShapeIndex) {
            deactivateShape(gd);
            return;
          }
          gd._fullLayout._activeShapeIndex = id;
          gd._fullLayout._deactivateShape = deactivateShape;
          draw(gd);
        }
      }
      function deactivateShape(gd) {
        if (!couldHaveActiveShape(gd)) return;
        var id = gd._fullLayout._activeShapeIndex;
        if (id >= 0) {
          clearOutlineControllers(gd);
          delete gd._fullLayout._activeShapeIndex;
          draw(gd);
        }
      }
      function eraseActiveShape(gd) {
        if (!couldHaveActiveShape(gd)) return;
        clearOutlineControllers(gd);
        var id = gd._fullLayout._activeShapeIndex;
        var shapes = (gd.layout || {}).shapes || [];
        if (id < shapes.length) {
          var list = [];
          for (var q = 0; q < shapes.length; q++) {
            if (q !== id) {
              list.push(shapes[q]);
            }
          }
          delete gd._fullLayout._activeShapeIndex;
          return Registry.call("_guiRelayout", gd, {
            shapes: list
          });
        }
      }
    }
  });

  // src/components/modebar/buttons.js
  var require_buttons = __commonJS({
    "src/components/modebar/buttons.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Plots = require_plots();
      var axisIds = require_axis_ids();
      var Icons = require_ploticon();
      var eraseActiveShape = require_draw2().eraseActiveShape;
      var Lib = require_lib();
      var _ = Lib._;
      var modeBarButtons = module.exports = {};
      modeBarButtons.toImage = {
        name: "toImage",
        title: function(gd) {
          var opts = gd._context.toImageButtonOptions || {};
          var format = opts.format || "png";
          return format === "png" ? _(gd, "Download plot as a PNG") : (
            // legacy text
            _(gd, "Download plot")
          );
        },
        icon: Icons.camera,
        click: function(gd) {
          var toImageButtonOptions = gd._context.toImageButtonOptions;
          var opts = { format: toImageButtonOptions.format || "png" };
          Lib.notifier(_(gd, "Taking snapshot - this may take a few seconds"), "long");
          ["filename", "width", "height", "scale"].forEach(function(key) {
            if (key in toImageButtonOptions) {
              opts[key] = toImageButtonOptions[key];
            }
          });
          Registry.call("downloadImage", gd, opts).then(function(filename) {
            Lib.notifier(_(gd, "Snapshot succeeded") + " - " + filename, "long");
          }).catch(function() {
            Lib.notifier(_(gd, "Sorry, there was a problem downloading your snapshot!"), "long");
          });
        }
      };
      modeBarButtons.sendDataToCloud = {
        name: "sendDataToCloud",
        title: function(gd) {
          return _(gd, "Edit in Chart Studio");
        },
        icon: Icons.disk,
        click: function(gd) {
          Plots.sendDataToCloud(gd);
        }
      };
      modeBarButtons.editInChartStudio = {
        name: "editInChartStudio",
        title: function(gd) {
          return _(gd, "Edit in Chart Studio");
        },
        icon: Icons.pencil,
        click: function(gd) {
          Plots.sendDataToCloud(gd);
        }
      };
      modeBarButtons.zoom2d = {
        name: "zoom2d",
        _cat: "zoom",
        title: function(gd) {
          return _(gd, "Zoom");
        },
        attr: "dragmode",
        val: "zoom",
        icon: Icons.zoombox,
        click: handleCartesian
      };
      modeBarButtons.pan2d = {
        name: "pan2d",
        _cat: "pan",
        title: function(gd) {
          return _(gd, "Pan");
        },
        attr: "dragmode",
        val: "pan",
        icon: Icons.pan,
        click: handleCartesian
      };
      modeBarButtons.select2d = {
        name: "select2d",
        _cat: "select",
        title: function(gd) {
          return _(gd, "Box Select");
        },
        attr: "dragmode",
        val: "select",
        icon: Icons.selectbox,
        click: handleCartesian
      };
      modeBarButtons.lasso2d = {
        name: "lasso2d",
        _cat: "lasso",
        title: function(gd) {
          return _(gd, "Lasso Select");
        },
        attr: "dragmode",
        val: "lasso",
        icon: Icons.lasso,
        click: handleCartesian
      };
      modeBarButtons.drawclosedpath = {
        name: "drawclosedpath",
        title: function(gd) {
          return _(gd, "Draw closed freeform");
        },
        attr: "dragmode",
        val: "drawclosedpath",
        icon: Icons.drawclosedpath,
        click: handleCartesian
      };
      modeBarButtons.drawopenpath = {
        name: "drawopenpath",
        title: function(gd) {
          return _(gd, "Draw open freeform");
        },
        attr: "dragmode",
        val: "drawopenpath",
        icon: Icons.drawopenpath,
        click: handleCartesian
      };
      modeBarButtons.drawline = {
        name: "drawline",
        title: function(gd) {
          return _(gd, "Draw line");
        },
        attr: "dragmode",
        val: "drawline",
        icon: Icons.drawline,
        click: handleCartesian
      };
      modeBarButtons.drawrect = {
        name: "drawrect",
        title: function(gd) {
          return _(gd, "Draw rectangle");
        },
        attr: "dragmode",
        val: "drawrect",
        icon: Icons.drawrect,
        click: handleCartesian
      };
      modeBarButtons.drawcircle = {
        name: "drawcircle",
        title: function(gd) {
          return _(gd, "Draw circle");
        },
        attr: "dragmode",
        val: "drawcircle",
        icon: Icons.drawcircle,
        click: handleCartesian
      };
      modeBarButtons.eraseshape = {
        name: "eraseshape",
        title: function(gd) {
          return _(gd, "Erase active shape");
        },
        icon: Icons.eraseshape,
        click: eraseActiveShape
      };
      modeBarButtons.zoomIn2d = {
        name: "zoomIn2d",
        _cat: "zoomin",
        title: function(gd) {
          return _(gd, "Zoom in");
        },
        attr: "zoom",
        val: "in",
        icon: Icons.zoom_plus,
        click: handleCartesian
      };
      modeBarButtons.zoomOut2d = {
        name: "zoomOut2d",
        _cat: "zoomout",
        title: function(gd) {
          return _(gd, "Zoom out");
        },
        attr: "zoom",
        val: "out",
        icon: Icons.zoom_minus,
        click: handleCartesian
      };
      modeBarButtons.autoScale2d = {
        name: "autoScale2d",
        _cat: "autoscale",
        title: function(gd) {
          return _(gd, "Autoscale");
        },
        attr: "zoom",
        val: "auto",
        icon: Icons.autoscale,
        click: handleCartesian
      };
      modeBarButtons.resetScale2d = {
        name: "resetScale2d",
        _cat: "resetscale",
        title: function(gd) {
          return _(gd, "Reset axes");
        },
        attr: "zoom",
        val: "reset",
        icon: Icons.home,
        click: handleCartesian
      };
      modeBarButtons.hoverClosestCartesian = {
        name: "hoverClosestCartesian",
        _cat: "hoverclosest",
        title: function(gd) {
          return _(gd, "Show closest data on hover");
        },
        attr: "hovermode",
        val: "closest",
        icon: Icons.tooltip_basic,
        gravity: "ne",
        click: handleCartesian
      };
      modeBarButtons.hoverCompareCartesian = {
        name: "hoverCompareCartesian",
        _cat: "hoverCompare",
        title: function(gd) {
          return _(gd, "Compare data on hover");
        },
        attr: "hovermode",
        val: function(gd) {
          return gd._fullLayout._isHoriz ? "y" : "x";
        },
        icon: Icons.tooltip_compare,
        gravity: "ne",
        click: handleCartesian
      };
      function handleCartesian(gd, ev) {
        var button = ev.currentTarget;
        var astr = button.getAttribute("data-attr");
        var val = button.getAttribute("data-val") || true;
        var fullLayout = gd._fullLayout;
        var aobj = {};
        var axList = axisIds.list(gd, null, true);
        var allSpikesEnabled = fullLayout._cartesianSpikesEnabled;
        var ax, i;
        if (astr === "zoom") {
          var mag = val === "in" ? 0.5 : 2;
          var r0 = (1 + mag) / 2;
          var r1 = (1 - mag) / 2;
          var axName, allowed;
          for (i = 0; i < axList.length; i++) {
            ax = axList[i];
            allowed = ax.modebardisable === "none" || ax.modebardisable.indexOf(
              val === "auto" || val === "reset" ? "autoscale" : "zoominout"
            ) === -1;
            if (allowed && !ax.fixedrange) {
              axName = ax._name;
              if (val === "auto") {
                aobj[axName + ".autorange"] = true;
              } else if (val === "reset") {
                if (ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0) {
                  aobj[axName + ".autorange"] = true;
                } else if (ax._rangeInitial0 === void 0) {
                  aobj[axName + ".autorange"] = ax._autorangeInitial;
                  aobj[axName + ".range"] = [null, ax._rangeInitial1];
                } else if (ax._rangeInitial1 === void 0) {
                  aobj[axName + ".range"] = [ax._rangeInitial0, null];
                  aobj[axName + ".autorange"] = ax._autorangeInitial;
                } else {
                  aobj[axName + ".range"] = [ax._rangeInitial0, ax._rangeInitial1];
                }
                if (ax._showSpikeInitial !== void 0) {
                  aobj[axName + ".showspikes"] = ax._showSpikeInitial;
                  if (allSpikesEnabled === "on" && !ax._showSpikeInitial) {
                    allSpikesEnabled = "off";
                  }
                }
              } else {
                var rangeNow = [
                  ax.r2l(ax.range[0]),
                  ax.r2l(ax.range[1])
                ];
                var rangeNew = [
                  r0 * rangeNow[0] + r1 * rangeNow[1],
                  r0 * rangeNow[1] + r1 * rangeNow[0]
                ];
                aobj[axName + ".range[0]"] = ax.l2r(rangeNew[0]);
                aobj[axName + ".range[1]"] = ax.l2r(rangeNew[1]);
              }
            }
          }
        } else {
          if (astr === "hovermode" && (val === "x" || val === "y")) {
            val = fullLayout._isHoriz ? "y" : "x";
            button.setAttribute("data-val", val);
          }
          aobj[astr] = val;
        }
        fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
        Registry.call("_guiRelayout", gd, aobj);
      }
      modeBarButtons.zoom3d = {
        name: "zoom3d",
        _cat: "zoom",
        title: function(gd) {
          return _(gd, "Zoom");
        },
        attr: "scene.dragmode",
        val: "zoom",
        icon: Icons.zoombox,
        click: handleDrag3d
      };
      modeBarButtons.pan3d = {
        name: "pan3d",
        _cat: "pan",
        title: function(gd) {
          return _(gd, "Pan");
        },
        attr: "scene.dragmode",
        val: "pan",
        icon: Icons.pan,
        click: handleDrag3d
      };
      modeBarButtons.orbitRotation = {
        name: "orbitRotation",
        title: function(gd) {
          return _(gd, "Orbital rotation");
        },
        attr: "scene.dragmode",
        val: "orbit",
        icon: Icons["3d_rotate"],
        click: handleDrag3d
      };
      modeBarButtons.tableRotation = {
        name: "tableRotation",
        title: function(gd) {
          return _(gd, "Turntable rotation");
        },
        attr: "scene.dragmode",
        val: "turntable",
        icon: Icons["z-axis"],
        click: handleDrag3d
      };
      function handleDrag3d(gd, ev) {
        var button = ev.currentTarget;
        var attr = button.getAttribute("data-attr");
        var val = button.getAttribute("data-val") || true;
        var sceneIds = gd._fullLayout._subplots.gl3d || [];
        var layoutUpdate = {};
        var parts = attr.split(".");
        for (var i = 0; i < sceneIds.length; i++) {
          layoutUpdate[sceneIds[i] + "." + parts[1]] = val;
        }
        var val2d = val === "pan" ? val : "zoom";
        layoutUpdate.dragmode = val2d;
        Registry.call("_guiRelayout", gd, layoutUpdate);
      }
      modeBarButtons.resetCameraDefault3d = {
        name: "resetCameraDefault3d",
        _cat: "resetCameraDefault",
        title: function(gd) {
          return _(gd, "Reset camera to default");
        },
        attr: "resetDefault",
        icon: Icons.home,
        click: handleCamera3d
      };
      modeBarButtons.resetCameraLastSave3d = {
        name: "resetCameraLastSave3d",
        _cat: "resetCameraLastSave",
        title: function(gd) {
          return _(gd, "Reset camera to last save");
        },
        attr: "resetLastSave",
        icon: Icons.movie,
        click: handleCamera3d
      };
      function handleCamera3d(gd, ev) {
        var button = ev.currentTarget;
        var attr = button.getAttribute("data-attr");
        var resetLastSave = attr === "resetLastSave";
        var resetDefault = attr === "resetDefault";
        var fullLayout = gd._fullLayout;
        var sceneIds = fullLayout._subplots.gl3d || [];
        var aobj = {};
        for (var i = 0; i < sceneIds.length; i++) {
          var sceneId = sceneIds[i];
          var camera = sceneId + ".camera";
          var aspectratio = sceneId + ".aspectratio";
          var aspectmode = sceneId + ".aspectmode";
          var scene = fullLayout[sceneId]._scene;
          var didUpdate;
          if (resetLastSave) {
            aobj[camera + ".up"] = scene.viewInitial.up;
            aobj[camera + ".eye"] = scene.viewInitial.eye;
            aobj[camera + ".center"] = scene.viewInitial.center;
            didUpdate = true;
          } else if (resetDefault) {
            aobj[camera + ".up"] = null;
            aobj[camera + ".eye"] = null;
            aobj[camera + ".center"] = null;
            didUpdate = true;
          }
          if (didUpdate) {
            aobj[aspectratio + ".x"] = scene.viewInitial.aspectratio.x;
            aobj[aspectratio + ".y"] = scene.viewInitial.aspectratio.y;
            aobj[aspectratio + ".z"] = scene.viewInitial.aspectratio.z;
            aobj[aspectmode] = scene.viewInitial.aspectmode;
          }
        }
        Registry.call("_guiRelayout", gd, aobj);
      }
      modeBarButtons.hoverClosest3d = {
        name: "hoverClosest3d",
        _cat: "hoverclosest",
        title: function(gd) {
          return _(gd, "Toggle show closest data on hover");
        },
        attr: "hovermode",
        val: null,
        toggle: true,
        icon: Icons.tooltip_basic,
        gravity: "ne",
        click: handleHover3d
      };
      function getNextHover3d(gd, ev) {
        var button = ev.currentTarget;
        var val = button._previousVal;
        var fullLayout = gd._fullLayout;
        var sceneIds = fullLayout._subplots.gl3d || [];
        var axes = ["xaxis", "yaxis", "zaxis"];
        var currentSpikes = {};
        var layoutUpdate = {};
        if (val) {
          layoutUpdate = val;
          button._previousVal = null;
        } else {
          for (var i = 0; i < sceneIds.length; i++) {
            var sceneId = sceneIds[i];
            var sceneLayout = fullLayout[sceneId];
            var hovermodeAStr = sceneId + ".hovermode";
            currentSpikes[hovermodeAStr] = sceneLayout.hovermode;
            layoutUpdate[hovermodeAStr] = false;
            for (var j = 0; j < 3; j++) {
              var axis = axes[j];
              var spikeAStr = sceneId + "." + axis + ".showspikes";
              layoutUpdate[spikeAStr] = false;
              currentSpikes[spikeAStr] = sceneLayout[axis].showspikes;
            }
          }
          button._previousVal = currentSpikes;
        }
        return layoutUpdate;
      }
      function handleHover3d(gd, ev) {
        var layoutUpdate = getNextHover3d(gd, ev);
        Registry.call("_guiRelayout", gd, layoutUpdate);
      }
      modeBarButtons.zoomInGeo = {
        name: "zoomInGeo",
        _cat: "zoomin",
        title: function(gd) {
          return _(gd, "Zoom in");
        },
        attr: "zoom",
        val: "in",
        icon: Icons.zoom_plus,
        click: handleGeo
      };
      modeBarButtons.zoomOutGeo = {
        name: "zoomOutGeo",
        _cat: "zoomout",
        title: function(gd) {
          return _(gd, "Zoom out");
        },
        attr: "zoom",
        val: "out",
        icon: Icons.zoom_minus,
        click: handleGeo
      };
      modeBarButtons.resetGeo = {
        name: "resetGeo",
        _cat: "reset",
        title: function(gd) {
          return _(gd, "Reset");
        },
        attr: "reset",
        val: null,
        icon: Icons.autoscale,
        click: handleGeo
      };
      modeBarButtons.hoverClosestGeo = {
        name: "hoverClosestGeo",
        _cat: "hoverclosest",
        title: function(gd) {
          return _(gd, "Toggle show closest data on hover");
        },
        attr: "hovermode",
        val: null,
        toggle: true,
        icon: Icons.tooltip_basic,
        gravity: "ne",
        click: toggleHover
      };
      function handleGeo(gd, ev) {
        var button = ev.currentTarget;
        var attr = button.getAttribute("data-attr");
        var val = button.getAttribute("data-val") || true;
        var fullLayout = gd._fullLayout;
        var geoIds = fullLayout._subplots.geo || [];
        for (var i = 0; i < geoIds.length; i++) {
          var id = geoIds[i];
          var geoLayout = fullLayout[id];
          if (attr === "zoom") {
            var scale = geoLayout.projection.scale;
            var newScale = val === "in" ? 2 * scale : 0.5 * scale;
            Registry.call("_guiRelayout", gd, id + ".projection.scale", newScale);
          }
        }
        if (attr === "reset") {
          resetView(gd, "geo");
        }
      }
      modeBarButtons.hoverClosestPie = {
        name: "hoverClosestPie",
        _cat: "hoverclosest",
        title: function(gd) {
          return _(gd, "Toggle show closest data on hover");
        },
        attr: "hovermode",
        val: "closest",
        icon: Icons.tooltip_basic,
        gravity: "ne",
        click: toggleHover
      };
      function getNextHover(gd) {
        var fullLayout = gd._fullLayout;
        if (fullLayout.hovermode) return false;
        if (fullLayout._has("cartesian")) {
          return fullLayout._isHoriz ? "y" : "x";
        }
        return "closest";
      }
      function toggleHover(gd) {
        var newHover = getNextHover(gd);
        Registry.call("_guiRelayout", gd, "hovermode", newHover);
      }
      modeBarButtons.resetViewSankey = {
        name: "resetSankeyGroup",
        title: function(gd) {
          return _(gd, "Reset view");
        },
        icon: Icons.home,
        click: function(gd) {
          var aObj = {
            "node.groups": [],
            "node.x": [],
            "node.y": []
          };
          for (var i = 0; i < gd._fullData.length; i++) {
            var viewInitial = gd._fullData[i]._viewInitial;
            aObj["node.groups"].push(viewInitial.node.groups.slice());
            aObj["node.x"].push(viewInitial.node.x.slice());
            aObj["node.y"].push(viewInitial.node.y.slice());
          }
          Registry.call("restyle", gd, aObj);
        }
      };
      modeBarButtons.toggleHover = {
        name: "toggleHover",
        title: function(gd) {
          return _(gd, "Toggle show closest data on hover");
        },
        attr: "hovermode",
        val: null,
        toggle: true,
        icon: Icons.tooltip_basic,
        gravity: "ne",
        click: function(gd, ev) {
          var layoutUpdate = getNextHover3d(gd, ev);
          layoutUpdate.hovermode = getNextHover(gd);
          Registry.call("_guiRelayout", gd, layoutUpdate);
        }
      };
      modeBarButtons.resetViews = {
        name: "resetViews",
        title: function(gd) {
          return _(gd, "Reset views");
        },
        icon: Icons.home,
        click: function(gd, ev) {
          var button = ev.currentTarget;
          button.setAttribute("data-attr", "zoom");
          button.setAttribute("data-val", "reset");
          handleCartesian(gd, ev);
          button.setAttribute("data-attr", "resetLastSave");
          handleCamera3d(gd, ev);
          resetView(gd, "geo");
          resetView(gd, "mapbox");
          resetView(gd, "map");
        }
      };
      modeBarButtons.toggleSpikelines = {
        name: "toggleSpikelines",
        title: function(gd) {
          return _(gd, "Toggle Spike Lines");
        },
        icon: Icons.spikeline,
        attr: "_cartesianSpikesEnabled",
        val: "on",
        click: function(gd) {
          var fullLayout = gd._fullLayout;
          var allSpikesEnabled = fullLayout._cartesianSpikesEnabled;
          fullLayout._cartesianSpikesEnabled = allSpikesEnabled === "on" ? "off" : "on";
          Registry.call("_guiRelayout", gd, setSpikelineVisibility(gd));
        }
      };
      function setSpikelineVisibility(gd) {
        var fullLayout = gd._fullLayout;
        var areSpikesOn = fullLayout._cartesianSpikesEnabled === "on";
        var axList = axisIds.list(gd, null, true);
        var aobj = {};
        for (var i = 0; i < axList.length; i++) {
          var ax = axList[i];
          aobj[ax._name + ".showspikes"] = areSpikesOn ? true : ax._showSpikeInitial;
        }
        return aobj;
      }
      modeBarButtons.resetViewMapbox = {
        name: "resetViewMapbox",
        _cat: "resetView",
        title: function(gd) {
          return _(gd, "Reset view");
        },
        attr: "reset",
        icon: Icons.home,
        click: function(gd) {
          resetView(gd, "mapbox");
        }
      };
      modeBarButtons.resetViewMap = {
        name: "resetViewMap",
        _cat: "resetView",
        title: function(gd) {
          return _(gd, "Reset view");
        },
        attr: "reset",
        icon: Icons.home,
        click: function(gd) {
          resetView(gd, "map");
        }
      };
      modeBarButtons.zoomInMapbox = {
        name: "zoomInMapbox",
        _cat: "zoomin",
        title: function(gd) {
          return _(gd, "Zoom in");
        },
        attr: "zoom",
        val: "in",
        icon: Icons.zoom_plus,
        click: handleMapboxZoom
      };
      modeBarButtons.zoomInMap = {
        name: "zoomInMap",
        _cat: "zoomin",
        title: function(gd) {
          return _(gd, "Zoom in");
        },
        attr: "zoom",
        val: "in",
        icon: Icons.zoom_plus,
        click: handleMapZoom
      };
      modeBarButtons.zoomOutMapbox = {
        name: "zoomOutMapbox",
        _cat: "zoomout",
        title: function(gd) {
          return _(gd, "Zoom out");
        },
        attr: "zoom",
        val: "out",
        icon: Icons.zoom_minus,
        click: handleMapboxZoom
      };
      modeBarButtons.zoomOutMap = {
        name: "zoomOutMap",
        _cat: "zoomout",
        title: function(gd) {
          return _(gd, "Zoom out");
        },
        attr: "zoom",
        val: "out",
        icon: Icons.zoom_minus,
        click: handleMapZoom
      };
      function handleMapboxZoom(gd, ev) {
        _handleMapZoom(gd, ev, "mapbox");
      }
      function handleMapZoom(gd, ev) {
        _handleMapZoom(gd, ev, "map");
      }
      function _handleMapZoom(gd, ev, mapType) {
        var button = ev.currentTarget;
        var val = button.getAttribute("data-val");
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[mapType] || [];
        var scalar = 1.05;
        var aObj = {};
        for (var i = 0; i < subplotIds.length; i++) {
          var id = subplotIds[i];
          var current = fullLayout[id].zoom;
          var next = val === "in" ? scalar * current : current / scalar;
          aObj[id + ".zoom"] = next;
        }
        Registry.call("_guiRelayout", gd, aObj);
      }
      function resetView(gd, subplotType) {
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[subplotType] || [];
        var aObj = {};
        for (var i = 0; i < subplotIds.length; i++) {
          var id = subplotIds[i];
          var subplotObj = fullLayout[id]._subplot;
          var viewInitial = subplotObj.viewInitial;
          var viewKeys = Object.keys(viewInitial);
          for (var j = 0; j < viewKeys.length; j++) {
            var key = viewKeys[j];
            aObj[id + "." + key] = viewInitial[key];
          }
        }
        Registry.call("_guiRelayout", gd, aObj);
      }
    }
  });

  // src/components/modebar/constants.js
  var require_constants6 = __commonJS({
    "src/components/modebar/constants.js"(exports, module) {
      "use strict";
      var modeBarButtons = require_buttons();
      var buttonList = Object.keys(modeBarButtons);
      var DRAW_MODES = [
        "drawline",
        "drawopenpath",
        "drawclosedpath",
        "drawcircle",
        "drawrect",
        "eraseshape"
      ];
      var backButtons = [
        "v1hovermode",
        "hoverclosest",
        "hovercompare",
        "togglehover",
        "togglespikelines"
      ].concat(DRAW_MODES);
      var foreButtons = [];
      var addToForeButtons = function(b) {
        if (backButtons.indexOf(b._cat || b.name) !== -1) return;
        var name2 = b.name;
        var _cat = (b._cat || b.name).toLowerCase();
        if (foreButtons.indexOf(name2) === -1) foreButtons.push(name2);
        if (foreButtons.indexOf(_cat) === -1) foreButtons.push(_cat);
      };
      buttonList.forEach(function(k) {
        addToForeButtons(modeBarButtons[k]);
      });
      foreButtons.sort();
      module.exports = {
        DRAW_MODES,
        backButtons,
        foreButtons
      };
    }
  });

  // src/components/modebar/attributes.js
  var require_attributes10 = __commonJS({
    "src/components/modebar/attributes.js"(exports, module) {
      "use strict";
      var constants = require_constants6();
      module.exports = {
        editType: "modebar",
        orientation: {
          valType: "enumerated",
          values: ["v", "h"],
          dflt: "h",
          editType: "modebar"
        },
        bgcolor: {
          valType: "color",
          editType: "modebar"
        },
        color: {
          valType: "color",
          editType: "modebar"
        },
        activecolor: {
          valType: "color",
          editType: "modebar"
        },
        uirevision: {
          valType: "any",
          editType: "none"
        },
        add: {
          valType: "string",
          arrayOk: true,
          dflt: "",
          editType: "modebar"
        },
        remove: {
          valType: "string",
          arrayOk: true,
          dflt: "",
          editType: "modebar"
        }
      };
    }
  });

  // src/components/modebar/defaults.js
  var require_defaults5 = __commonJS({
    "src/components/modebar/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var Template = require_plot_template();
      var attributes = require_attributes10();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        var containerIn = layoutIn.modebar || {};
        var containerOut = Template.newContainer(layoutOut, "modebar");
        function coerce(attr, dflt) {
          return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
        }
        coerce("orientation");
        coerce("bgcolor", Color2.addOpacity(layoutOut.paper_bgcolor, 0.5));
        var defaultColor = Color2.contrast(Color2.rgb(layoutOut.modebar.bgcolor));
        coerce("color", Color2.addOpacity(defaultColor, 0.3));
        coerce("activecolor", Color2.addOpacity(defaultColor, 0.7));
        coerce("uirevision", layoutOut.uirevision);
        coerce("add");
        coerce("remove");
      };
    }
  });

  // src/components/modebar/modebar.js
  var require_modebar = __commonJS({
    "src/components/modebar/modebar.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Icons = require_ploticon();
      var version = require_version().version;
      var Parser = new DOMParser();
      function ModeBar(opts) {
        this.container = opts.container;
        this.element = document.createElement("div");
        this.update(opts.graphInfo, opts.buttons);
        this.container.appendChild(this.element);
      }
      var proto = ModeBar.prototype;
      proto.update = function(graphInfo, buttons) {
        this.graphInfo = graphInfo;
        var context = this.graphInfo._context;
        var fullLayout = this.graphInfo._fullLayout;
        var modeBarId = "modebar-" + fullLayout._uid;
        this.element.setAttribute("id", modeBarId);
        this.element.setAttribute("role", "toolbar");
        this._uid = modeBarId;
        this.element.className = "modebar modebar--custom";
        if (context.displayModeBar === "hover") this.element.className += " modebar--hover ease-bg";
        if (fullLayout.modebar.orientation === "v") {
          this.element.className += " vertical";
          buttons = buttons.reverse();
        }
        var style = fullLayout.modebar;
        var groupSelector = "#" + modeBarId + " .modebar-group";
        document.querySelectorAll(groupSelector).forEach(function(group) {
          group.style.backgroundColor = style.bgcolor;
        });
        var needsNewButtons = !this.hasButtons(buttons);
        var needsNewLogo = this.hasLogo !== context.displaylogo;
        var needsNewLocale = this.locale !== context.locale;
        this.locale = context.locale;
        if (needsNewButtons || needsNewLogo || needsNewLocale) {
          this.removeAllButtons();
          this.updateButtons(buttons);
          if (context.watermark || context.displaylogo) {
            var logoGroup = this.getLogo();
            if (context.watermark) {
              logoGroup.className = logoGroup.className + " watermark";
            }
            if (fullLayout.modebar.orientation === "v") {
              this.element.insertBefore(logoGroup, this.element.childNodes[0]);
            } else {
              this.element.appendChild(logoGroup);
            }
            this.hasLogo = true;
          }
        }
        this.updateActiveButton();
        Lib.setStyleOnHover("#" + modeBarId + " .modebar-btn", ".active", ".icon path", "fill: " + style.activecolor, "fill: " + style.color, this.element);
      };
      proto.updateButtons = function(buttons) {
        var _this = this;
        this.buttons = buttons;
        this.buttonElements = [];
        this.buttonsNames = [];
        this.buttons.forEach(function(buttonGroup) {
          var group = _this.createGroup();
          buttonGroup.forEach(function(buttonConfig) {
            var buttonName = buttonConfig.name;
            if (!buttonName) {
              throw new Error("must provide button 'name' in button config");
            }
            if (_this.buttonsNames.indexOf(buttonName) !== -1) {
              throw new Error("button name '" + buttonName + "' is taken");
            }
            _this.buttonsNames.push(buttonName);
            var button = _this.createButton(buttonConfig);
            _this.buttonElements.push(button);
            group.appendChild(button);
          });
          _this.element.appendChild(group);
        });
      };
      proto.createGroup = function() {
        var group = document.createElement("div");
        group.className = "modebar-group";
        var style = this.graphInfo._fullLayout.modebar;
        group.style.backgroundColor = style.bgcolor;
        return group;
      };
      proto.createButton = function(config) {
        var _this = this;
        var button = document.createElement("button");
        button.setAttribute("type", "button");
        button.setAttribute("rel", "tooltip");
        button.className = "modebar-btn";
        var title = config.title;
        if (title === void 0) title = config.name;
        else if (typeof title === "function") title = title(this.graphInfo);
        if (title || title === 0) {
          button.setAttribute("data-title", title);
          button.setAttribute("aria-label", title);
        }
        ;
        if (config.attr !== void 0) button.setAttribute("data-attr", config.attr);
        var val = config.val;
        if (val !== void 0) {
          if (typeof val === "function") val = val(this.graphInfo);
          button.setAttribute("data-val", val);
        }
        var click = config.click;
        if (typeof click !== "function") {
          throw new Error("must provide button 'click' function in button config");
        } else {
          button.addEventListener("click", function(ev) {
            config.click(_this.graphInfo, ev);
            _this.updateActiveButton(ev.currentTarget);
          });
        }
        button.setAttribute("data-toggle", config.toggle || false);
        if (config.toggle) d3.select(button).classed("active", true);
        var icon = config.icon;
        if (typeof icon === "function") {
          button.appendChild(icon());
        } else {
          button.appendChild(this.createIcon(icon || Icons.question));
        }
        button.setAttribute("data-gravity", config.gravity || "n");
        return button;
      };
      proto.createIcon = function(thisIcon) {
        var iconHeight = isNumeric(thisIcon.height) ? Number(thisIcon.height) : thisIcon.ascent - thisIcon.descent;
        var svgNS = "http://www.w3.org/2000/svg";
        var icon;
        if (thisIcon.path) {
          icon = document.createElementNS(svgNS, "svg");
          icon.setAttribute("viewBox", [0, 0, thisIcon.width, iconHeight].join(" "));
          icon.setAttribute("class", "icon");
          var path = document.createElementNS(svgNS, "path");
          path.setAttribute("d", thisIcon.path);
          if (thisIcon.transform) {
            path.setAttribute("transform", thisIcon.transform);
          } else if (thisIcon.ascent !== void 0) {
            path.setAttribute("transform", "matrix(1 0 0 -1 0 " + thisIcon.ascent + ")");
          }
          icon.appendChild(path);
        }
        if (thisIcon.svg) {
          var svgDoc = Parser.parseFromString(thisIcon.svg, "application/xml");
          icon = svgDoc.childNodes[0];
        }
        icon.setAttribute("height", "1em");
        icon.setAttribute("width", "1em");
        return icon;
      };
      proto.updateActiveButton = function(buttonClicked) {
        var fullLayout = this.graphInfo._fullLayout;
        var dataAttrClicked = buttonClicked !== void 0 ? buttonClicked.getAttribute("data-attr") : null;
        this.buttonElements.forEach(function(button) {
          var thisval = button.getAttribute("data-val") || true;
          var dataAttr = button.getAttribute("data-attr");
          var isToggleButton = button.getAttribute("data-toggle") === "true";
          var button3 = d3.select(button);
          var updateButtonStyle = function(button2, isActive2) {
            var style = fullLayout.modebar;
            var childEl = button2.querySelector(".icon path");
            if (childEl) {
              if (isActive2 || button2.matches(":hover")) {
                childEl.style.fill = style.activecolor;
              } else {
                childEl.style.fill = style.color;
              }
            }
          };
          if (isToggleButton) {
            if (dataAttr === dataAttrClicked) {
              var isActive = !button3.classed("active");
              button3.classed("active", isActive);
              updateButtonStyle(button, isActive);
            }
          } else {
            var val = dataAttr === null ? dataAttr : Lib.nestedProperty(fullLayout, dataAttr).get();
            button3.classed("active", val === thisval);
            updateButtonStyle(button, val === thisval);
          }
        });
      };
      proto.hasButtons = function(buttons) {
        var currentButtons = this.buttons;
        if (!currentButtons) return false;
        if (buttons.length !== currentButtons.length) return false;
        for (var i = 0; i < buttons.length; ++i) {
          if (buttons[i].length !== currentButtons[i].length) return false;
          for (var j = 0; j < buttons[i].length; j++) {
            if (buttons[i][j].name !== currentButtons[i][j].name) return false;
          }
        }
        return true;
      };
      function jsVersion(str) {
        return str + " (v" + version + ")";
      }
      proto.getLogo = function() {
        var group = this.createGroup();
        var a = document.createElement("a");
        a.href = "https://plotly.com/";
        a.target = "_blank";
        a.setAttribute("data-title", jsVersion(Lib._(this.graphInfo, "Produced with Plotly.js")));
        a.className = "modebar-btn plotlyjsicon modebar-btn--logo";
        a.appendChild(this.createIcon(Icons.newplotlylogo));
        group.appendChild(a);
        return group;
      };
      proto.removeAllButtons = function() {
        while (this.element.firstChild) {
          this.element.removeChild(this.element.firstChild);
        }
        this.hasLogo = false;
      };
      proto.destroy = function() {
        Lib.removeElement(this.container.querySelector(".modebar"));
      };
      function createModeBar(gd, buttons) {
        var fullLayout = gd._fullLayout;
        var modeBar = new ModeBar({
          graphInfo: gd,
          container: fullLayout._modebardiv.node(),
          buttons
        });
        if (fullLayout._privateplot) {
          d3.select(modeBar.element).append("span").classed("badge-private float--left", true).text("PRIVATE");
        }
        return modeBar;
      }
      module.exports = createModeBar;
    }
  });

  // src/components/modebar/manage.js
  var require_manage = __commonJS({
    "src/components/modebar/manage.js"(exports, module) {
      "use strict";
      var axisIds = require_axis_ids();
      var scatterSubTypes = require_subtypes();
      var Registry = require_registry();
      var isUnifiedHover = require_helpers2().isUnifiedHover;
      var createModeBar = require_modebar();
      var modeBarButtons = require_buttons();
      var DRAW_MODES = require_constants6().DRAW_MODES;
      var extendDeep = require_lib().extendDeep;
      module.exports = function manageModeBar(gd) {
        var fullLayout = gd._fullLayout;
        var context = gd._context;
        var modeBar = fullLayout._modeBar;
        if (!context.displayModeBar && !context.watermark) {
          if (modeBar) {
            modeBar.destroy();
            delete fullLayout._modeBar;
          }
          return;
        }
        if (!Array.isArray(context.modeBarButtonsToRemove)) {
          throw new Error([
            "*modeBarButtonsToRemove* configuration options",
            "must be an array."
          ].join(" "));
        }
        if (!Array.isArray(context.modeBarButtonsToAdd)) {
          throw new Error([
            "*modeBarButtonsToAdd* configuration options",
            "must be an array."
          ].join(" "));
        }
        var customButtons = context.modeBarButtons;
        var buttonGroups;
        if (Array.isArray(customButtons) && customButtons.length) {
          buttonGroups = fillCustomButton(customButtons);
        } else if (!context.displayModeBar && context.watermark) {
          buttonGroups = [];
        } else {
          buttonGroups = getButtonGroups(gd);
        }
        if (modeBar) modeBar.update(gd, buttonGroups);
        else fullLayout._modeBar = createModeBar(gd, buttonGroups);
      };
      function getButtonGroups(gd) {
        var fullLayout = gd._fullLayout;
        var fullData = gd._fullData;
        var context = gd._context;
        function match(name2, B2) {
          if (typeof B2 === "string") {
            if (B2.toLowerCase() === name2.toLowerCase()) return true;
          } else {
            var v0 = B2.name;
            var v1 = B2._cat || B2.name;
            if (v0 === name2 || v1 === name2.toLowerCase()) return true;
          }
          return false;
        }
        var layoutAdd = fullLayout.modebar.add;
        if (typeof layoutAdd === "string") layoutAdd = [layoutAdd];
        var layoutRemove = fullLayout.modebar.remove;
        if (typeof layoutRemove === "string") layoutRemove = [layoutRemove];
        var buttonsToAdd = context.modeBarButtonsToAdd.concat(
          layoutAdd.filter(function(e) {
            for (var i2 = 0; i2 < context.modeBarButtonsToRemove.length; i2++) {
              if (match(e, context.modeBarButtonsToRemove[i2])) return false;
            }
            return true;
          })
        );
        var buttonsToRemove = context.modeBarButtonsToRemove.concat(
          layoutRemove.filter(function(e) {
            for (var i2 = 0; i2 < context.modeBarButtonsToAdd.length; i2++) {
              if (match(e, context.modeBarButtonsToAdd[i2])) return false;
            }
            return true;
          })
        );
        var hasCartesian = fullLayout._has("cartesian");
        var hasGL3D = fullLayout._has("gl3d");
        var hasGeo = fullLayout._has("geo");
        var hasPie = fullLayout._has("pie");
        var hasFunnelarea = fullLayout._has("funnelarea");
        var hasTernary = fullLayout._has("ternary");
        var hasMapbox = fullLayout._has("mapbox");
        var hasMap = fullLayout._has("map");
        var hasPolar = fullLayout._has("polar");
        var hasSmith = fullLayout._has("smith");
        var hasSankey = fullLayout._has("sankey");
        var allAxesFixed = areAllAxesFixed(fullLayout);
        var hasUnifiedHoverLabel = isUnifiedHover(fullLayout.hovermode);
        var groups = [];
        function addGroup(newGroup) {
          if (!newGroup.length) return;
          var out = [];
          for (var i2 = 0; i2 < newGroup.length; i2++) {
            var name2 = newGroup[i2];
            var B2 = modeBarButtons[name2];
            var v0 = B2.name.toLowerCase();
            var v1 = (B2._cat || B2.name).toLowerCase();
            var found = false;
            for (var q = 0; q < buttonsToRemove.length; q++) {
              var t = buttonsToRemove[q].toLowerCase();
              if (t === v0 || t === v1) {
                found = true;
                break;
              }
            }
            if (found) continue;
            out.push(modeBarButtons[name2]);
          }
          groups.push(out);
        }
        var commonGroup = ["toImage"];
        if (context.showEditInChartStudio) commonGroup.push("editInChartStudio");
        else if (context.showSendToCloud) commonGroup.push("sendDataToCloud");
        addGroup(commonGroup);
        var zoomGroup = [];
        var hoverGroup = [];
        var resetGroup = [];
        var dragModeGroup = [];
        if ((hasCartesian || hasPie || hasFunnelarea || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasMap + hasPolar + hasSmith > 1) {
          hoverGroup = ["toggleHover"];
          resetGroup = ["resetViews"];
        } else if (hasGeo) {
          zoomGroup = ["zoomInGeo", "zoomOutGeo"];
          hoverGroup = ["hoverClosestGeo"];
          resetGroup = ["resetGeo"];
        } else if (hasGL3D) {
          hoverGroup = ["hoverClosest3d"];
          resetGroup = ["resetCameraDefault3d", "resetCameraLastSave3d"];
        } else if (hasMapbox) {
          zoomGroup = ["zoomInMapbox", "zoomOutMapbox"];
          hoverGroup = ["toggleHover"];
          resetGroup = ["resetViewMapbox"];
        } else if (hasMap) {
          zoomGroup = ["zoomInMap", "zoomOutMap"];
          hoverGroup = ["toggleHover"];
          resetGroup = ["resetViewMap"];
        } else if (hasPie) {
          hoverGroup = ["hoverClosestPie"];
        } else if (hasSankey) {
          hoverGroup = ["hoverClosestCartesian", "hoverCompareCartesian"];
          resetGroup = ["resetViewSankey"];
        } else {
          hoverGroup = ["toggleHover"];
        }
        if (hasCartesian) {
          hoverGroup.push("toggleSpikelines", "hoverClosestCartesian", "hoverCompareCartesian");
        }
        if (hasNoHover(fullData) || hasUnifiedHoverLabel) {
          hoverGroup = [];
        }
        if (hasCartesian && !allAxesFixed) {
          zoomGroup = ["zoomIn2d", "zoomOut2d", "autoScale2d"];
          if (resetGroup[0] !== "resetViews") resetGroup = ["resetScale2d"];
        }
        if (hasGL3D) {
          dragModeGroup = ["zoom3d", "pan3d", "orbitRotation", "tableRotation"];
        } else if (hasCartesian && !allAxesFixed || hasTernary) {
          dragModeGroup = ["zoom2d", "pan2d"];
        } else if (hasMapbox || hasMap || hasGeo) {
          dragModeGroup = ["pan2d"];
        } else if (hasPolar) {
          dragModeGroup = ["zoom2d"];
        }
        if (isSelectable(fullData)) {
          dragModeGroup.push("select2d", "lasso2d");
        }
        var enabledHoverGroup = [];
        var enableHover = function(a) {
          if (enabledHoverGroup.indexOf(a) !== -1) return;
          if (hoverGroup.indexOf(a) !== -1) {
            enabledHoverGroup.push(a);
          }
        };
        if (Array.isArray(buttonsToAdd)) {
          var newList = [];
          for (var i = 0; i < buttonsToAdd.length; i++) {
            var b = buttonsToAdd[i];
            if (typeof b === "string") {
              b = b.toLowerCase();
              if (DRAW_MODES.indexOf(b) !== -1) {
                if (fullLayout._has("mapbox") || fullLayout._has("map") || // draw shapes in paper coordinate (could be improved in future to support data coordinate, when there is no pitch)
                fullLayout._has("cartesian")) {
                  dragModeGroup.push(b);
                }
              } else if (b === "togglespikelines") {
                enableHover("toggleSpikelines");
              } else if (b === "togglehover") {
                enableHover("toggleHover");
              } else if (b === "hovercompare") {
                enableHover("hoverCompareCartesian");
              } else if (b === "hoverclosest") {
                enableHover("hoverClosestCartesian");
                enableHover("hoverClosestGeo");
                enableHover("hoverClosest3d");
                enableHover("hoverClosestPie");
              } else if (b === "v1hovermode") {
                enableHover("hoverClosestCartesian");
                enableHover("hoverCompareCartesian");
                enableHover("hoverClosestGeo");
                enableHover("hoverClosest3d");
                enableHover("hoverClosestPie");
              }
            } else newList.push(b);
          }
          buttonsToAdd = newList;
        }
        addGroup(dragModeGroup);
        addGroup(zoomGroup.concat(resetGroup));
        addGroup(enabledHoverGroup);
        return appendButtonsToGroups(groups, buttonsToAdd);
      }
      function areAllAxesFixed(fullLayout) {
        var axList = axisIds.list({ _fullLayout: fullLayout }, null, true);
        for (var i = 0; i < axList.length; i++) {
          var disabled = axList[i].modebardisable;
          if (!axList[i].fixedrange && disabled !== "autoscale+zoominout" && disabled !== "zoominout+autoscale") {
            return false;
          }
        }
        return true;
      }
      function isSelectable(fullData) {
        var selectable = false;
        for (var i = 0; i < fullData.length; i++) {
          if (selectable) break;
          var trace = fullData[i];
          if (!trace._module || !trace._module.selectPoints) continue;
          if (Registry.traceIs(trace, "scatter-like")) {
            if (scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) {
              selectable = true;
            }
          } else if (Registry.traceIs(trace, "box-violin")) {
            if (trace.boxpoints === "all" || trace.points === "all") {
              selectable = true;
            }
          } else {
            selectable = true;
          }
        }
        return selectable;
      }
      function hasNoHover(fullData) {
        for (var i = 0; i < fullData.length; i++) {
          if (!Registry.traceIs(fullData[i], "noHover")) return false;
        }
        return true;
      }
      function appendButtonsToGroups(groups, buttons) {
        if (buttons.length) {
          if (Array.isArray(buttons[0])) {
            for (var i = 0; i < buttons.length; i++) {
              groups.push(buttons[i]);
            }
          } else groups.push(buttons);
        }
        return groups;
      }
      function fillCustomButton(originalModeBarButtons) {
        var customButtons = extendDeep([], originalModeBarButtons);
        for (var i = 0; i < customButtons.length; i++) {
          var buttonGroup = customButtons[i];
          for (var j = 0; j < buttonGroup.length; j++) {
            var button = buttonGroup[j];
            if (typeof button === "string") {
              if (modeBarButtons[button] !== void 0) {
                customButtons[i][j] = modeBarButtons[button];
              } else {
                throw new Error([
                  "*modeBarButtons* configuration options",
                  "invalid button name"
                ].join(" "));
              }
            }
          }
        }
        return customButtons;
      }
    }
  });

  // src/components/modebar/index.js
  var require_modebar2 = __commonJS({
    "src/components/modebar/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "component",
        name: "modebar",
        layoutAttributes: require_attributes10(),
        supplyLayoutDefaults: require_defaults5(),
        manage: require_manage()
      };
    }
  });

  // src/plots/cartesian/scale_zoom.js
  var require_scale_zoom = __commonJS({
    "src/plots/cartesian/scale_zoom.js"(exports, module) {
      "use strict";
      var FROM_BL = require_alignment().FROM_BL;
      module.exports = function scaleZoom(ax, factor, centerFraction) {
        if (centerFraction === void 0) {
          centerFraction = FROM_BL[ax.constraintoward || "center"];
        }
        var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])];
        var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction;
        ax.range = ax._input.range = [
          ax.l2r(center + (rangeLinear[0] - center) * factor),
          ax.l2r(center + (rangeLinear[1] - center) * factor)
        ];
        ax.setScale();
      };
    }
  });

  // src/plots/cartesian/constraints.js
  var require_constraints = __commonJS({
    "src/plots/cartesian/constraints.js"(exports) {
      "use strict";
      var Lib = require_lib();
      var autorange = require_autorange();
      var id2name = require_axis_ids().id2name;
      var layoutAttributes = require_layout_attributes4();
      var scaleZoom = require_scale_zoom();
      var setConvert = require_set_convert();
      var ALMOST_EQUAL = require_numerical().ALMOST_EQUAL;
      var FROM_BL = require_alignment().FROM_BL;
      exports.handleDefaults = function(layoutIn, layoutOut, opts) {
        var axIds = opts.axIds;
        var axHasImage = opts.axHasImage;
        var constraintGroups = layoutOut._axisConstraintGroups = [];
        var matchGroups = layoutOut._axisMatchGroups = [];
        var i, group, axId, axName, axIn, axOut, attr, val;
        for (i = 0; i < axIds.length; i++) {
          axName = id2name(axIds[i]);
          axIn = layoutIn[axName];
          axOut = layoutOut[axName];
          handleOneAxDefaults(axIn, axOut, {
            axIds,
            layoutOut,
            hasImage: axHasImage[axName]
          });
        }
        function stash(groups, stashAttr) {
          for (i = 0; i < groups.length; i++) {
            group = groups[i];
            for (axId in group) {
              layoutOut[id2name(axId)][stashAttr] = group;
            }
          }
        }
        stash(matchGroups, "_matchGroup");
        for (i = 0; i < constraintGroups.length; i++) {
          group = constraintGroups[i];
          for (axId in group) {
            axOut = layoutOut[id2name(axId)];
            if (axOut.fixedrange) {
              for (var axId2 in group) {
                var axName2 = id2name(axId2);
                if ((layoutIn[axName2] || {}).fixedrange === false) {
                  Lib.warn(
                    "fixedrange was specified as false for axis " + axName2 + " but was overridden because another axis in its constraint group has fixedrange true"
                  );
                }
                layoutOut[axName2].fixedrange = true;
              }
              break;
            }
          }
        }
        i = 0;
        while (i < constraintGroups.length) {
          group = constraintGroups[i];
          for (axId in group) {
            axOut = layoutOut[id2name(axId)];
            if (axOut._matchGroup && Object.keys(axOut._matchGroup).length === Object.keys(group).length) {
              constraintGroups.splice(i, 1);
              i--;
            }
            break;
          }
          i++;
        }
        stash(constraintGroups, "_constraintGroup");
        var matchAttrs = [
          "constrain",
          "range",
          "autorange",
          "rangemode",
          "rangebreaks",
          "categoryorder",
          "categoryarray"
        ];
        var hasRange = false;
        var hasDayOfWeekBreaks = false;
        function setAttrVal() {
          val = axOut[attr];
          if (attr === "rangebreaks") {
            hasDayOfWeekBreaks = axOut._hasDayOfWeekBreaks;
          }
        }
        for (i = 0; i < matchGroups.length; i++) {
          group = matchGroups[i];
          for (var j = 0; j < matchAttrs.length; j++) {
            attr = matchAttrs[j];
            val = null;
            var baseAx;
            for (axId in group) {
              axName = id2name(axId);
              axIn = layoutIn[axName];
              axOut = layoutOut[axName];
              if (!(attr in axOut)) {
                continue;
              }
              if (!axOut.matches) {
                baseAx = axOut;
                if (attr in axIn) {
                  setAttrVal();
                  break;
                }
              }
              if (val === null && attr in axIn) {
                setAttrVal();
              }
            }
            if (attr === "range" && val && axIn.range && axIn.range.length === 2 && axIn.range[0] !== null && axIn.range[1] !== null) {
              hasRange = true;
            }
            if (attr === "autorange" && val === null && hasRange) {
              val = false;
            }
            if (val === null && attr in baseAx) {
              val = baseAx[attr];
            }
            if (val !== null) {
              for (axId in group) {
                axOut = layoutOut[id2name(axId)];
                axOut[attr] = attr === "range" ? val.slice() : val;
                if (attr === "rangebreaks") {
                  axOut._hasDayOfWeekBreaks = hasDayOfWeekBreaks;
                  setConvert(axOut, layoutOut);
                }
              }
            }
          }
        }
      };
      function handleOneAxDefaults(axIn, axOut, opts) {
        var axIds = opts.axIds;
        var layoutOut = opts.layoutOut;
        var hasImage = opts.hasImage;
        var constraintGroups = layoutOut._axisConstraintGroups;
        var matchGroups = layoutOut._axisMatchGroups;
        var axId = axOut._id;
        var axLetter = axId.charAt(0);
        var splomStash = ((layoutOut._splomAxes || {})[axLetter] || {})[axId] || {};
        var thisID = axOut._id;
        var isX = thisID.charAt(0) === "x";
        axOut._matchGroup = null;
        axOut._constraintGroup = null;
        function coerce(attr, dflt) {
          return Lib.coerce(axIn, axOut, layoutAttributes, attr, dflt);
        }
        coerce("constrain", hasImage ? "domain" : "range");
        Lib.coerce(axIn, axOut, {
          constraintoward: {
            valType: "enumerated",
            values: isX ? ["left", "center", "right"] : ["bottom", "middle", "top"],
            dflt: isX ? "center" : "middle"
          }
        }, "constraintoward");
        var thisType = axOut.type;
        var i, idi;
        var linkableAxes = [];
        for (i = 0; i < axIds.length; i++) {
          idi = axIds[i];
          if (idi === thisID) continue;
          var axi = layoutOut[id2name(idi)];
          if (axi.type === thisType) {
            linkableAxes.push(idi);
          }
        }
        var thisGroup = getConstraintGroup(constraintGroups, thisID);
        if (thisGroup) {
          var linkableAxesNoLoops = [];
          for (i = 0; i < linkableAxes.length; i++) {
            idi = linkableAxes[i];
            if (!thisGroup[idi]) linkableAxesNoLoops.push(idi);
          }
          linkableAxes = linkableAxesNoLoops;
        }
        var canLink = linkableAxes.length;
        var matches, scaleanchor;
        if (canLink && (axIn.matches || splomStash.matches)) {
          matches = Lib.coerce(axIn, axOut, {
            matches: {
              valType: "enumerated",
              values: linkableAxes,
              dflt: linkableAxes.indexOf(splomStash.matches) !== -1 ? splomStash.matches : void 0
            }
          }, "matches");
        }
        var scaleanchorDflt = hasImage && !isX ? axOut.anchor : void 0;
        if (canLink && !matches && (axIn.scaleanchor || scaleanchorDflt)) {
          scaleanchor = Lib.coerce(axIn, axOut, {
            scaleanchor: {
              valType: "enumerated",
              values: linkableAxes.concat([false])
            }
          }, "scaleanchor", scaleanchorDflt);
        }
        if (matches) {
          axOut._matchGroup = updateConstraintGroups(matchGroups, thisID, matches, 1);
          var matchedAx = layoutOut[id2name(matches)];
          var matchRatio = extent(layoutOut, axOut) / extent(layoutOut, matchedAx);
          if (isX !== (matches.charAt(0) === "x")) {
            matchRatio = (isX ? "x" : "y") + matchRatio;
          }
          updateConstraintGroups(constraintGroups, thisID, matches, matchRatio);
        } else if (axIn.matches && axIds.indexOf(axIn.matches) !== -1) {
          Lib.warn("ignored " + axOut._name + '.matches: "' + axIn.matches + '" to avoid an infinite loop');
        }
        if (scaleanchor) {
          var scaleratio = coerce("scaleratio");
          if (!scaleratio) scaleratio = axOut.scaleratio = 1;
          updateConstraintGroups(constraintGroups, thisID, scaleanchor, scaleratio);
        } else if (axIn.scaleanchor && axIds.indexOf(axIn.scaleanchor) !== -1) {
          Lib.warn("ignored " + axOut._name + '.scaleanchor: "' + axIn.scaleanchor + '" to avoid either an infinite loop and possibly inconsistent scaleratios, or because this axis declares a *matches* constraint.');
        }
      }
      function extent(layoutOut, ax) {
        var domain = ax.domain;
        if (!domain) {
          domain = layoutOut[id2name(ax.overlaying)].domain;
        }
        return domain[1] - domain[0];
      }
      function getConstraintGroup(groups, thisID) {
        for (var i = 0; i < groups.length; i++) {
          if (groups[i][thisID]) {
            return groups[i];
          }
        }
        return null;
      }
      function updateConstraintGroups(constraintGroups, thisID, thatID, scaleratio) {
        var i, j, groupi, keyj, thisGroupIndex;
        var thisGroup = getConstraintGroup(constraintGroups, thisID);
        if (thisGroup === null) {
          thisGroup = {};
          thisGroup[thisID] = 1;
          thisGroupIndex = constraintGroups.length;
          constraintGroups.push(thisGroup);
        } else {
          thisGroupIndex = constraintGroups.indexOf(thisGroup);
        }
        var thisGroupKeys = Object.keys(thisGroup);
        for (i = 0; i < constraintGroups.length; i++) {
          groupi = constraintGroups[i];
          if (i !== thisGroupIndex && groupi[thatID]) {
            var baseScale = groupi[thatID];
            for (j = 0; j < thisGroupKeys.length; j++) {
              keyj = thisGroupKeys[j];
              groupi[keyj] = multiplyScales(baseScale, multiplyScales(scaleratio, thisGroup[keyj]));
            }
            constraintGroups.splice(thisGroupIndex, 1);
            return;
          }
        }
        if (scaleratio !== 1) {
          for (j = 0; j < thisGroupKeys.length; j++) {
            var key = thisGroupKeys[j];
            thisGroup[key] = multiplyScales(scaleratio, thisGroup[key]);
          }
        }
        thisGroup[thatID] = 1;
      }
      function multiplyScales(a, b) {
        var aPrefix = "";
        var bPrefix = "";
        var aLen, bLen;
        if (typeof a === "string") {
          aPrefix = a.match(/^[xy]*/)[0];
          aLen = aPrefix.length;
          a = +a.slice(aLen);
        }
        if (typeof b === "string") {
          bPrefix = b.match(/^[xy]*/)[0];
          bLen = bPrefix.length;
          b = +b.slice(bLen);
        }
        var c = a * b;
        if (!aLen && !bLen) {
          return c;
        }
        if (!aLen || !bLen || aPrefix.charAt(0) === bPrefix.charAt(0)) {
          return aPrefix + bPrefix + a * b;
        }
        if (aLen === bLen) {
          return c;
        }
        return (aLen > bLen ? aPrefix.slice(bLen) : bPrefix.slice(aLen)) + c;
      }
      function finalRatios(group, fullLayout) {
        var size = fullLayout._size;
        var yRatio = size.h / size.w;
        var out = {};
        var keys = Object.keys(group);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          var val = group[key];
          if (typeof val === "string") {
            var prefix = val.match(/^[xy]*/)[0];
            var pLen = prefix.length;
            val = +val.slice(pLen);
            var mult = prefix.charAt(0) === "y" ? yRatio : 1 / yRatio;
            for (var j = 0; j < pLen; j++) {
              val *= mult;
            }
          }
          out[key] = val;
        }
        return out;
      }
      exports.enforce = function enforce(gd) {
        var fullLayout = gd._fullLayout;
        var constraintGroups = fullLayout._axisConstraintGroups || [];
        var i, j, group, axisID, ax, normScale, mode, factor;
        for (i = 0; i < constraintGroups.length; i++) {
          group = finalRatios(constraintGroups[i], fullLayout);
          var axisIDs = Object.keys(group);
          var minScale = Infinity;
          var maxScale = 0;
          var matchScale = Infinity;
          var normScales = {};
          var axes = {};
          var hasAnyDomainConstraint = false;
          for (j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            axes[axisID] = ax = fullLayout[id2name(axisID)];
            if (ax._inputDomain) ax.domain = ax._inputDomain.slice();
            else ax._inputDomain = ax.domain.slice();
            if (!ax._inputRange) ax._inputRange = ax.range.slice();
            ax.setScale();
            normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID];
            minScale = Math.min(minScale, normScale);
            if (ax.constrain === "domain" || !ax._constraintShrinkable) {
              matchScale = Math.min(matchScale, normScale);
            }
            delete ax._constraintShrinkable;
            maxScale = Math.max(maxScale, normScale);
            if (ax.constrain === "domain") hasAnyDomainConstraint = true;
          }
          if (minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue;
          for (j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            normScale = normScales[axisID];
            ax = axes[axisID];
            mode = ax.constrain;
            if (normScale !== matchScale || mode === "domain") {
              factor = normScale / matchScale;
              if (mode === "range") {
                scaleZoom(ax, factor);
              } else {
                var inputDomain = ax._inputDomain;
                var domainShrunk = (ax.domain[1] - ax.domain[0]) / (inputDomain[1] - inputDomain[0]);
                var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) / (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0]));
                factor /= domainShrunk;
                if (factor * rangeShrunk < 1) {
                  ax.domain = ax._input.domain = inputDomain.slice();
                  scaleZoom(ax, factor);
                  continue;
                }
                if (rangeShrunk < 1) {
                  ax.range = ax._input.range = ax._inputRange.slice();
                  factor *= rangeShrunk;
                }
                if (ax.autorange) {
                  var rl0 = ax.r2l(ax.range[0]);
                  var rl1 = ax.r2l(ax.range[1]);
                  var rangeCenter = (rl0 + rl1) / 2;
                  var rangeMin = rangeCenter;
                  var rangeMax = rangeCenter;
                  var halfRange = Math.abs(rl1 - rangeCenter);
                  var outerMin = rangeCenter - halfRange * factor * 1.0001;
                  var outerMax = rangeCenter + halfRange * factor * 1.0001;
                  var getPadMin = autorange.makePadFn(fullLayout, ax, 0);
                  var getPadMax = autorange.makePadFn(fullLayout, ax, 1);
                  updateDomain(ax, factor);
                  var m = Math.abs(ax._m);
                  var extremes = autorange.concatExtremes(gd, ax);
                  var minArray = extremes.min;
                  var maxArray = extremes.max;
                  var newVal;
                  var k;
                  for (k = 0; k < minArray.length; k++) {
                    newVal = minArray[k].val - getPadMin(minArray[k]) / m;
                    if (newVal > outerMin && newVal < rangeMin) {
                      rangeMin = newVal;
                    }
                  }
                  for (k = 0; k < maxArray.length; k++) {
                    newVal = maxArray[k].val + getPadMax(maxArray[k]) / m;
                    if (newVal < outerMax && newVal > rangeMax) {
                      rangeMax = newVal;
                    }
                  }
                  var domainExpand = (rangeMax - rangeMin) / (2 * halfRange);
                  factor /= domainExpand;
                  rangeMin = ax.l2r(rangeMin);
                  rangeMax = ax.l2r(rangeMax);
                  ax.range = ax._input.range = rl0 < rl1 ? [rangeMin, rangeMax] : [rangeMax, rangeMin];
                }
                updateDomain(ax, factor);
              }
            }
          }
        }
      };
      exports.getAxisGroup = function getAxisGroup(fullLayout, axId) {
        var matchGroups = fullLayout._axisMatchGroups;
        for (var i = 0; i < matchGroups.length; i++) {
          var group = matchGroups[i];
          if (group[axId]) return "g" + i;
        }
        return axId;
      };
      exports.clean = function clean(gd, ax) {
        if (ax._inputDomain) {
          var isConstrained = false;
          var axId = ax._id;
          var constraintGroups = gd._fullLayout._axisConstraintGroups;
          for (var j = 0; j < constraintGroups.length; j++) {
            if (constraintGroups[j][axId]) {
              isConstrained = true;
              break;
            }
          }
          if (!isConstrained || ax.constrain !== "domain") {
            ax._input.domain = ax.domain = ax._inputDomain;
            delete ax._inputDomain;
          }
        }
      };
      function updateDomain(ax, factor) {
        var inputDomain = ax._inputDomain;
        var centerFraction = FROM_BL[ax.constraintoward];
        var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction;
        ax.domain = ax._input.domain = [
          center + (inputDomain[0] - center) / factor,
          center + (inputDomain[1] - center) / factor
        ];
        ax.setScale();
      }
    }
  });

  // src/plot_api/subroutines.js
  var require_subroutines = __commonJS({
    "src/plot_api/subroutines.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Plots = require_plots();
      var Lib = require_lib();
      var svgTextUtils = require_svg_text_utils();
      var clearGlCanvases = require_clear_gl_canvases();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Titles = require_titles();
      var ModeBar = require_modebar2();
      var Axes = require_axes();
      var alignmentConstants = require_alignment();
      var axisConstraints = require_constraints();
      var enforceAxisConstraints = axisConstraints.enforce;
      var cleanAxisConstraints = axisConstraints.clean;
      var doAutoRange = require_autorange().doAutoRange;
      var SVG_TEXT_ANCHOR_START = "start";
      var SVG_TEXT_ANCHOR_MIDDLE = "middle";
      var SVG_TEXT_ANCHOR_END = "end";
      var zindexSeparator = require_constants2().zindexSeparator;
      exports.layoutStyles = function(gd) {
        return Lib.syncOrAsync([Plots.doAutoMargin, lsInner], gd);
      };
      function overlappingDomain(xDomain, yDomain, domains) {
        for (var i = 0; i < domains.length; i++) {
          var existingX = domains[i][0];
          var existingY = domains[i][1];
          if (existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
            continue;
          }
          if (existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
            return true;
          }
        }
        return false;
      }
      function lsInner(gd) {
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        var pad = gs.p;
        var axList = Axes.list(gd, "", true);
        var i, subplot, plotinfo, ax, xa, ya;
        fullLayout._paperdiv.style({
          width: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width ? "100%" : fullLayout.width + "px",
          height: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height ? "100%" : fullLayout.height + "px"
        }).selectAll(".main-svg").call(Drawing.setSize, fullLayout.width, fullLayout.height);
        gd._context.setBackground(gd, fullLayout.paper_bgcolor);
        exports.drawMainTitle(gd);
        ModeBar.manage(gd);
        if (!fullLayout._has("cartesian")) {
          return Plots.previousPromises(gd);
        }
        function getLinePosition(ax2, counterAx2, side) {
          var lwHalf = ax2._lw / 2;
          if (ax2._id.charAt(0) === "x") {
            if (!counterAx2) return gs.t + gs.h * (1 - (ax2.position || 0)) + lwHalf % 1;
            else if (side === "top") return counterAx2._offset - pad - lwHalf;
            return counterAx2._offset + counterAx2._length + pad + lwHalf;
          }
          if (!counterAx2) return gs.l + gs.w * (ax2.position || 0) + lwHalf % 1;
          else if (side === "right") return counterAx2._offset + counterAx2._length + pad + lwHalf;
          return counterAx2._offset - pad - lwHalf;
        }
        for (i = 0; i < axList.length; i++) {
          ax = axList[i];
          var counterAx = ax._anchorAxis;
          ax._linepositions = {};
          ax._lw = Drawing.crispRound(gd, ax.linewidth, 1);
          ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side);
          ax._mainMirrorPosition = ax.mirror && counterAx ? getLinePosition(
            ax,
            counterAx,
            alignmentConstants.OPPOSITE_SIDE[ax.side]
          ) : null;
        }
        var lowerBackgroundIDs = [];
        var backgroundIds = [];
        var lowerDomains = [];
        var noNeedForBg = Color2.opacity(fullLayout.paper_bgcolor) === 1 && Color2.opacity(fullLayout.plot_bgcolor) === 1 && fullLayout.paper_bgcolor === fullLayout.plot_bgcolor;
        for (subplot in fullLayout._plots) {
          plotinfo = fullLayout._plots[subplot];
          if (plotinfo.mainplot) {
            if (plotinfo.bg) {
              plotinfo.bg.remove();
            }
            plotinfo.bg = void 0;
          } else {
            var xDomain = plotinfo.xaxis.domain;
            var yDomain = plotinfo.yaxis.domain;
            var plotgroup = plotinfo.plotgroup;
            if (overlappingDomain(xDomain, yDomain, lowerDomains) && subplot.indexOf(zindexSeparator) === -1) {
              var pgNode = plotgroup.node();
              var plotgroupBg = plotinfo.bg = Lib.ensureSingle(plotgroup, "rect", "bg");
              pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]);
              backgroundIds.push(subplot);
            } else {
              plotgroup.select("rect.bg").remove();
              lowerDomains.push([xDomain, yDomain]);
              if (!noNeedForBg) {
                lowerBackgroundIDs.push(subplot);
                backgroundIds.push(subplot);
              }
            }
          }
        }
        var lowerBackgrounds = fullLayout._bgLayer.selectAll(".bg").data(lowerBackgroundIDs);
        lowerBackgrounds.enter().append("rect").classed("bg", true);
        lowerBackgrounds.exit().remove();
        lowerBackgrounds.each(function(subplot2) {
          fullLayout._plots[subplot2].bg = d3.select(this);
        });
        for (i = 0; i < backgroundIds.length; i++) {
          plotinfo = fullLayout._plots[backgroundIds[i]];
          xa = plotinfo.xaxis;
          ya = plotinfo.yaxis;
          if (plotinfo.bg && xa._offset !== void 0 && ya._offset !== void 0) {
            plotinfo.bg.call(
              Drawing.setRect,
              xa._offset - pad,
              ya._offset - pad,
              xa._length + 2 * pad,
              ya._length + 2 * pad
            ).call(Color2.fill, fullLayout.plot_bgcolor).style("stroke-width", 0);
          }
        }
        if (!fullLayout._hasOnlyLargeSploms) {
          for (subplot in fullLayout._plots) {
            plotinfo = fullLayout._plots[subplot];
            xa = plotinfo.xaxis;
            ya = plotinfo.yaxis;
            var clipId = plotinfo.clipId = "clip" + fullLayout._uid + subplot + "plot";
            var plotClip = Lib.ensureSingleById(fullLayout._clips, "clipPath", clipId, function(s) {
              s.classed("plotclip", true).append("rect");
            });
            plotinfo.clipRect = plotClip.select("rect").attr({
              width: xa._length,
              height: ya._length
            });
            Drawing.setTranslate(plotinfo.plot, xa._offset, ya._offset);
            var plotClipId;
            var layerClipId;
            if (plotinfo._hasClipOnAxisFalse) {
              plotClipId = null;
              layerClipId = clipId;
            } else {
              plotClipId = clipId;
              layerClipId = null;
            }
            Drawing.setClipUrl(plotinfo.plot, plotClipId, gd);
            plotinfo.layerClipId = layerClipId;
          }
        }
        var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop, leftYLineWidth, rightYLineWidth;
        var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight, connectYBottom, connectYTop;
        var extraSubplot;
        function xLinePath(y) {
          return "M" + xLinesXLeft + "," + y + "H" + xLinesXRight;
        }
        function xLinePathFree(y) {
          return "M" + xa._offset + "," + y + "h" + xa._length;
        }
        function yLinePath(x) {
          return "M" + x + "," + yLinesYTop + "V" + yLinesYBottom;
        }
        function yLinePathFree(x) {
          if (ya._shift !== void 0) {
            x += ya._shift;
          }
          return "M" + x + "," + ya._offset + "v" + ya._length;
        }
        function mainPath(ax2, pathFn, pathFnFree) {
          if (!ax2.showline || subplot !== ax2._mainSubplot) return "";
          if (!ax2._anchorAxis) return pathFnFree(ax2._mainLinePosition);
          var out = pathFn(ax2._mainLinePosition);
          if (ax2.mirror) out += pathFn(ax2._mainMirrorPosition);
          return out;
        }
        for (subplot in fullLayout._plots) {
          plotinfo = fullLayout._plots[subplot];
          xa = plotinfo.xaxis;
          ya = plotinfo.yaxis;
          var xPath = "M0,0";
          if (shouldShowLinesOrTicks(xa, subplot)) {
            leftYLineWidth = findCounterAxisLineWidth(xa, "left", ya, axList);
            xLinesXLeft = xa._offset - (leftYLineWidth ? pad + leftYLineWidth : 0);
            rightYLineWidth = findCounterAxisLineWidth(xa, "right", ya, axList);
            xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? pad + rightYLineWidth : 0);
            xLinesYBottom = getLinePosition(xa, ya, "bottom");
            xLinesYTop = getLinePosition(xa, ya, "top");
            extraSubplot = !xa._anchorAxis || subplot !== xa._mainSubplot;
            if (extraSubplot && (xa.mirror === "allticks" || xa.mirror === "all")) {
              xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop];
            }
            xPath = mainPath(xa, xLinePath, xLinePathFree);
            if (extraSubplot && xa.showline && (xa.mirror === "all" || xa.mirror === "allticks")) {
              xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop);
            }
            plotinfo.xlines.style("stroke-width", xa._lw + "px").call(Color2.stroke, xa.showline ? xa.linecolor : "rgba(0,0,0,0)");
          }
          plotinfo.xlines.attr("d", xPath);
          var yPath = "M0,0";
          if (shouldShowLinesOrTicks(ya, subplot)) {
            connectYBottom = findCounterAxisLineWidth(ya, "bottom", xa, axList);
            yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad : 0);
            connectYTop = findCounterAxisLineWidth(ya, "top", xa, axList);
            yLinesYTop = ya._offset - (connectYTop ? pad : 0);
            yLinesXLeft = getLinePosition(ya, xa, "left");
            yLinesXRight = getLinePosition(ya, xa, "right");
            extraSubplot = !ya._anchorAxis || subplot !== ya._mainSubplot;
            if (extraSubplot && (ya.mirror === "allticks" || ya.mirror === "all")) {
              ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight];
            }
            yPath = mainPath(ya, yLinePath, yLinePathFree);
            if (extraSubplot && ya.showline && (ya.mirror === "all" || ya.mirror === "allticks")) {
              yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight);
            }
            plotinfo.ylines.style("stroke-width", ya._lw + "px").call(Color2.stroke, ya.showline ? ya.linecolor : "rgba(0,0,0,0)");
          }
          plotinfo.ylines.attr("d", yPath);
        }
        Axes.makeClipPaths(gd);
        return Plots.previousPromises(gd);
      }
      function shouldShowLinesOrTicks(ax, subplot) {
        return (ax.ticks || ax.showline) && (subplot === ax._mainSubplot || ax.mirror === "all" || ax.mirror === "allticks");
      }
      function shouldShowLineThisSide(ax, side, counterAx) {
        if (!counterAx.showline || !counterAx._lw) return false;
        if (counterAx.mirror === "all" || counterAx.mirror === "allticks") return true;
        var anchorAx = counterAx._anchorAxis;
        if (!anchorAx) return false;
        var sideIndex = alignmentConstants.FROM_BL[side];
        if (counterAx.side === side) {
          return anchorAx.domain[sideIndex] === ax.domain[sideIndex];
        }
        return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex];
      }
      function findCounterAxisLineWidth(ax, side, counterAx, axList) {
        if (shouldShowLineThisSide(ax, side, counterAx)) {
          return counterAx._lw;
        }
        for (var i = 0; i < axList.length; i++) {
          var axi = axList[i];
          if (axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) {
            return axi._lw;
          }
        }
        return 0;
      }
      exports.drawMainTitle = function(gd) {
        var title = gd._fullLayout.title;
        var fullLayout = gd._fullLayout;
        var textAnchor = getMainTitleTextAnchor(fullLayout);
        var dy = getMainTitleDy(fullLayout);
        var y = getMainTitleY(fullLayout, dy);
        var x = getMainTitleX(fullLayout, textAnchor);
        Titles.draw(gd, "gtitle", {
          propContainer: fullLayout,
          propName: "title.text",
          subtitlePropName: "title.subtitle.text",
          placeholder: fullLayout._dfltTitle.plot,
          subtitlePlaceholder: fullLayout._dfltTitle.subtitle,
          attributes: {
            x,
            y,
            "text-anchor": textAnchor,
            dy
          }
        });
        if (title.text && title.automargin) {
          var titleObj = d3.select(gd).selectAll(".gtitle");
          var titleHeight = Drawing.bBox(d3.select(gd).selectAll(".g-gtitle").node()).height;
          var pushMargin = needsMarginPush(gd, title, titleHeight);
          if (pushMargin > 0) {
            applyTitleAutoMargin(gd, y, pushMargin, titleHeight);
            titleObj.attr({
              x,
              y,
              "text-anchor": textAnchor,
              dy: getMainTitleDyAdj(title.yanchor)
            }).call(svgTextUtils.positionText, x, y);
            var extraLines = (title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
            if (extraLines) {
              var delta = alignmentConstants.LINE_SPACING * extraLines + alignmentConstants.MID_SHIFT;
              if (title.y === 0) {
                delta = -delta;
              }
              titleObj.selectAll(".line").each(function() {
                var newDy = +this.getAttribute("dy").slice(0, -2) - delta + "em";
                this.setAttribute("dy", newDy);
              });
            }
            var subtitleObj = d3.select(gd).selectAll(".gtitle-subtitle");
            if (subtitleObj.node()) {
              var titleBB = titleObj.node().getBBox();
              var titleBottom = titleBB.y + titleBB.height;
              var subtitleY = titleBottom + Titles.SUBTITLE_PADDING_EM * title.subtitle.font.size;
              subtitleObj.attr({
                x,
                y: subtitleY,
                "text-anchor": textAnchor,
                dy: getMainTitleDyAdj(title.yanchor)
              }).call(svgTextUtils.positionText, x, subtitleY);
            }
          }
        }
      };
      function isOutsideContainer(gd, title, position, y, titleHeight) {
        var plotHeight = title.yref === "paper" ? gd._fullLayout._size.h : gd._fullLayout.height;
        var yPosTop = Lib.isTopAnchor(title) ? y : y - titleHeight;
        var yPosRel = position === "b" ? plotHeight - yPosTop : yPosTop;
        if (Lib.isTopAnchor(title) && position === "t" || Lib.isBottomAnchor(title) && position === "b") {
          return false;
        } else {
          return yPosRel < titleHeight;
        }
      }
      function containerPushVal(position, titleY, titleYanchor, height, titleDepth) {
        var push = 0;
        if (titleYanchor === "middle") {
          push += titleDepth / 2;
        }
        if (position === "t") {
          if (titleYanchor === "top") {
            push += titleDepth;
          }
          push += height - titleY * height;
        } else {
          if (titleYanchor === "bottom") {
            push += titleDepth;
          }
          push += titleY * height;
        }
        return push;
      }
      function needsMarginPush(gd, title, titleHeight) {
        var titleY = title.y;
        var titleYanchor = title.yanchor;
        var position = titleY > 0.5 ? "t" : "b";
        var curMargin = gd._fullLayout.margin[position];
        var pushMargin = 0;
        if (title.yref === "paper") {
          pushMargin = titleHeight + title.pad.t + title.pad.b;
        } else if (title.yref === "container") {
          pushMargin = containerPushVal(position, titleY, titleYanchor, gd._fullLayout.height, titleHeight) + title.pad.t + title.pad.b;
        }
        if (pushMargin > curMargin) {
          return pushMargin;
        }
        return 0;
      }
      function applyTitleAutoMargin(gd, y, pushMargin, titleHeight) {
        var titleID = "title.automargin";
        var title = gd._fullLayout.title;
        var position = title.y > 0.5 ? "t" : "b";
        var push = {
          x: title.x,
          y: title.y,
          t: 0,
          b: 0
        };
        var reservedPush = {};
        if (title.yref === "paper" && isOutsideContainer(gd, title, position, y, titleHeight)) {
          push[position] = pushMargin;
        } else if (title.yref === "container") {
          reservedPush[position] = pushMargin;
          gd._fullLayout._reservedMargin[titleID] = reservedPush;
        }
        Plots.allowAutoMargin(gd, titleID);
        Plots.autoMargin(gd, titleID, push);
      }
      function getMainTitleX(fullLayout, textAnchor) {
        var title = fullLayout.title;
        var gs = fullLayout._size;
        var hPadShift = 0;
        if (textAnchor === SVG_TEXT_ANCHOR_START) {
          hPadShift = title.pad.l;
        } else if (textAnchor === SVG_TEXT_ANCHOR_END) {
          hPadShift = -title.pad.r;
        }
        switch (title.xref) {
          case "paper":
            return gs.l + gs.w * title.x + hPadShift;
          case "container":
          default:
            return fullLayout.width * title.x + hPadShift;
        }
      }
      function getMainTitleY(fullLayout, dy) {
        var title = fullLayout.title;
        var gs = fullLayout._size;
        var vPadShift = 0;
        if (dy === "0em" || !dy) {
          vPadShift = -title.pad.b;
        } else if (dy === alignmentConstants.CAP_SHIFT + "em") {
          vPadShift = title.pad.t;
        }
        if (title.y === "auto") {
          return gs.t / 2;
        } else {
          switch (title.yref) {
            case "paper":
              return gs.t + gs.h - gs.h * title.y + vPadShift;
            case "container":
            default:
              return fullLayout.height - fullLayout.height * title.y + vPadShift;
          }
        }
      }
      function getMainTitleDyAdj(yanchor) {
        if (yanchor === "top") {
          return alignmentConstants.CAP_SHIFT + 0.3 + "em";
        } else if (yanchor === "bottom") {
          return "-0.3em";
        } else {
          return alignmentConstants.MID_SHIFT + "em";
        }
      }
      function getMainTitleTextAnchor(fullLayout) {
        var title = fullLayout.title;
        var textAnchor = SVG_TEXT_ANCHOR_MIDDLE;
        if (Lib.isRightAnchor(title)) {
          textAnchor = SVG_TEXT_ANCHOR_END;
        } else if (Lib.isLeftAnchor(title)) {
          textAnchor = SVG_TEXT_ANCHOR_START;
        }
        return textAnchor;
      }
      function getMainTitleDy(fullLayout) {
        var title = fullLayout.title;
        var dy = "0em";
        if (Lib.isTopAnchor(title)) {
          dy = alignmentConstants.CAP_SHIFT + "em";
        } else if (Lib.isMiddleAnchor(title)) {
          dy = alignmentConstants.MID_SHIFT + "em";
        }
        return dy;
      }
      exports.doTraceStyle = function(gd) {
        var calcdata = gd.calcdata;
        var editStyleCalls = [];
        var i;
        for (i = 0; i < calcdata.length; i++) {
          var cd = calcdata[i];
          var cd0 = cd[0] || {};
          var trace = cd0.trace || {};
          var _module = trace._module || {};
          var arraysToCalcdata = _module.arraysToCalcdata;
          if (arraysToCalcdata) arraysToCalcdata(cd, trace);
          var editStyle = _module.editStyle;
          if (editStyle) editStyleCalls.push({ fn: editStyle, cd0 });
        }
        if (editStyleCalls.length) {
          for (i = 0; i < editStyleCalls.length; i++) {
            var edit = editStyleCalls[i];
            edit.fn(gd, edit.cd0);
          }
          clearGlCanvases(gd);
          exports.redrawReglTraces(gd);
        }
        Plots.style(gd);
        Registry.getComponentMethod("legend", "draw")(gd);
        return Plots.previousPromises(gd);
      };
      exports.doColorBars = function(gd) {
        Registry.getComponentMethod("colorbar", "draw")(gd);
        return Plots.previousPromises(gd);
      };
      exports.layoutReplot = function(gd) {
        var layout = gd.layout;
        gd.layout = void 0;
        return Registry.call("_doPlot", gd, "", layout);
      };
      exports.doLegend = function(gd) {
        Registry.getComponentMethod("legend", "draw")(gd);
        return Plots.previousPromises(gd);
      };
      exports.doTicksRelayout = function(gd) {
        Axes.draw(gd, "redraw");
        if (gd._fullLayout._hasOnlyLargeSploms) {
          Registry.subplotsRegistry.splom.updateGrid(gd);
          clearGlCanvases(gd);
          exports.redrawReglTraces(gd);
        }
        exports.drawMainTitle(gd);
        return Plots.previousPromises(gd);
      };
      exports.doModeBar = function(gd) {
        var fullLayout = gd._fullLayout;
        ModeBar.manage(gd);
        for (var i = 0; i < fullLayout._basePlotModules.length; i++) {
          var updateFx = fullLayout._basePlotModules[i].updateFx;
          if (updateFx) updateFx(gd);
        }
        return Plots.previousPromises(gd);
      };
      exports.doCamera = function(gd) {
        var fullLayout = gd._fullLayout;
        var sceneIds = fullLayout._subplots.gl3d;
        for (var i = 0; i < sceneIds.length; i++) {
          var sceneLayout = fullLayout[sceneIds[i]];
          var scene = sceneLayout._scene;
          scene.setViewport(sceneLayout);
        }
      };
      exports.drawData = function(gd) {
        var fullLayout = gd._fullLayout;
        clearGlCanvases(gd);
        var basePlotModules = fullLayout._basePlotModules;
        for (var i = 0; i < basePlotModules.length; i++) {
          basePlotModules[i].plot(gd);
        }
        exports.redrawReglTraces(gd);
        Plots.style(gd);
        Registry.getComponentMethod("selections", "draw")(gd);
        Registry.getComponentMethod("shapes", "draw")(gd);
        Registry.getComponentMethod("annotations", "draw")(gd);
        Registry.getComponentMethod("images", "draw")(gd);
        fullLayout._replotting = false;
        return Plots.previousPromises(gd);
      };
      exports.redrawReglTraces = function(gd) {
        var fullLayout = gd._fullLayout;
        if (fullLayout._has("regl")) {
          var fullData = gd._fullData;
          var cartesianIds = [];
          var polarIds = [];
          var i, sp;
          if (fullLayout._hasOnlyLargeSploms) {
            fullLayout._splomGrid.draw();
          }
          for (i = 0; i < fullData.length; i++) {
            var trace = fullData[i];
            if (trace.visible === true && trace._length !== 0) {
              if (trace.type === "splom") {
                fullLayout._splomScenes[trace.uid].draw();
              } else if (trace.type === "scattergl") {
                Lib.pushUnique(cartesianIds, trace.xaxis + trace.yaxis);
              } else if (trace.type === "scatterpolargl") {
                Lib.pushUnique(polarIds, trace.subplot);
              }
            }
          }
          for (i = 0; i < cartesianIds.length; i++) {
            sp = fullLayout._plots[cartesianIds[i]];
            if (sp._scene) sp._scene.draw();
          }
          for (i = 0; i < polarIds.length; i++) {
            sp = fullLayout[polarIds[i]]._subplot;
            if (sp._scene) sp._scene.draw();
          }
        }
      };
      exports.doAutoRangeAndConstraints = function(gd) {
        var axList = Axes.list(gd, "", true);
        var ax;
        var autoRangeDone = {};
        for (var i = 0; i < axList.length; i++) {
          ax = axList[i];
          if (!autoRangeDone[ax._id]) {
            autoRangeDone[ax._id] = 1;
            cleanAxisConstraints(gd, ax);
            doAutoRange(gd, ax);
            var matchGroup = ax._matchGroup;
            if (matchGroup) {
              for (var id2 in matchGroup) {
                var ax2 = Axes.getFromId(gd, id2);
                doAutoRange(gd, ax2, ax.range);
                autoRangeDone[id2] = 1;
              }
            }
          }
        }
        enforceAxisConstraints(gd);
      };
      exports.finalDraw = function(gd) {
        Registry.getComponentMethod("rangeslider", "draw")(gd);
        Registry.getComponentMethod("rangeselector", "draw")(gd);
      };
      exports.drawMarginPushers = function(gd) {
        Registry.getComponentMethod("legend", "draw")(gd);
        Registry.getComponentMethod("rangeselector", "draw")(gd);
        Registry.getComponentMethod("sliders", "draw")(gd);
        Registry.getComponentMethod("updatemenus", "draw")(gd);
        Registry.getComponentMethod("colorbar", "draw")(gd);
      };
    }
  });

  // src/components/selections/draw.js
  var require_draw3 = __commonJS({
    "src/components/selections/draw.js"(exports, module) {
      "use strict";
      var readPaths = require_helpers7().readPaths;
      var displayOutlines = require_display_outlines();
      var clearOutlineControllers = require_handle_outline().clearOutlineControllers;
      var Color2 = require_color();
      var Drawing = require_drawing();
      var arrayEditor = require_plot_template().arrayEditor;
      var helpers = require_helpers8();
      var getPathString = helpers.getPathString;
      module.exports = {
        draw,
        drawOne,
        activateLastSelection
      };
      function draw(gd) {
        var fullLayout = gd._fullLayout;
        clearOutlineControllers(gd);
        fullLayout._selectionLayer.selectAll("path").remove();
        for (var k in fullLayout._plots) {
          var selectionLayer = fullLayout._plots[k].selectionLayer;
          if (selectionLayer) selectionLayer.selectAll("path").remove();
        }
        for (var i = 0; i < fullLayout.selections.length; i++) {
          drawOne(gd, i);
        }
      }
      function couldHaveActiveSelection(gd) {
        return gd._context.editSelection;
      }
      function drawOne(gd, index) {
        gd._fullLayout._paperdiv.selectAll('.selectionlayer [data-index="' + index + '"]').remove();
        var o = helpers.makeSelectionsOptionsAndPlotinfo(gd, index);
        var options = o.options;
        var plotinfo = o.plotinfo;
        if (!options._input) return;
        drawSelection(gd._fullLayout._selectionLayer);
        function drawSelection(selectionLayer) {
          var d = getPathString(gd, options);
          var attrs = {
            "data-index": index,
            "fill-rule": "evenodd",
            d
          };
          var opacity = options.opacity;
          var fillColor = "rgba(0,0,0,0)";
          var lineColor = options.line.color || Color2.contrast(gd._fullLayout.plot_bgcolor);
          var lineWidth = options.line.width;
          var lineDash = options.line.dash;
          if (!lineWidth) {
            lineWidth = 5;
            lineDash = "solid";
          }
          var isActiveSelection = couldHaveActiveSelection(gd) && gd._fullLayout._activeSelectionIndex === index;
          if (isActiveSelection) {
            fillColor = gd._fullLayout.activeselection.fillcolor;
            opacity = gd._fullLayout.activeselection.opacity;
          }
          var allPaths = [];
          for (var sensory = 1; sensory >= 0; sensory--) {
            var path = selectionLayer.append("path").attr(attrs).style("opacity", sensory ? 0.1 : opacity).call(Color2.stroke, lineColor).call(Color2.fill, fillColor).call(
              Drawing.dashLine,
              sensory ? "solid" : lineDash,
              sensory ? 4 + lineWidth : lineWidth
            );
            setClipPath(path, gd, options);
            if (isActiveSelection) {
              var editHelpers = arrayEditor(gd.layout, "selections", options);
              path.style({
                cursor: "move"
              });
              var dragOptions = {
                element: path.node(),
                plotinfo,
                gd,
                editHelpers,
                isActiveSelection: true
                // i.e. to enable controllers
              };
              var polygons = readPaths(d, gd);
              displayOutlines(polygons, path, dragOptions);
            } else {
              path.style("pointer-events", sensory ? "all" : "none");
            }
            allPaths[sensory] = path;
          }
          var forePath = allPaths[0];
          var backPath = allPaths[1];
          backPath.node().addEventListener("click", function() {
            return activateSelection(gd, forePath);
          });
        }
      }
      function setClipPath(selectionPath, gd, selectionOptions) {
        var clipAxes = selectionOptions.xref + selectionOptions.yref;
        Drawing.setClipUrl(
          selectionPath,
          "clip" + gd._fullLayout._uid + clipAxes,
          gd
        );
      }
      function activateSelection(gd, path) {
        if (!couldHaveActiveSelection(gd)) return;
        var element = path.node();
        var id = +element.getAttribute("data-index");
        if (id >= 0) {
          if (id === gd._fullLayout._activeSelectionIndex) {
            deactivateSelection(gd);
            return;
          }
          gd._fullLayout._activeSelectionIndex = id;
          gd._fullLayout._deactivateSelection = deactivateSelection;
          draw(gd);
        }
      }
      function activateLastSelection(gd) {
        if (!couldHaveActiveSelection(gd)) return;
        var id = gd._fullLayout.selections.length - 1;
        gd._fullLayout._activeSelectionIndex = id;
        gd._fullLayout._deactivateSelection = deactivateSelection;
        draw(gd);
      }
      function deactivateSelection(gd) {
        if (!couldHaveActiveSelection(gd)) return;
        var id = gd._fullLayout._activeSelectionIndex;
        if (id >= 0) {
          clearOutlineControllers(gd);
          delete gd._fullLayout._activeSelectionIndex;
          draw(gd);
        }
      }
    }
  });

  // node_modules/polybooljs/lib/build-log.js
  var require_build_log = __commonJS({
    "node_modules/polybooljs/lib/build-log.js"(exports, module) {
      function BuildLog() {
        var my;
        var nextSegmentId = 0;
        var curVert = false;
        function push(type, data) {
          my.list.push({
            type,
            data: data ? JSON.parse(JSON.stringify(data)) : void 0
          });
          return my;
        }
        my = {
          list: [],
          segmentId: function() {
            return nextSegmentId++;
          },
          checkIntersection: function(seg1, seg2) {
            return push("check", { seg1, seg2 });
          },
          segmentChop: function(seg, end) {
            push("div_seg", { seg, pt: end });
            return push("chop", { seg, pt: end });
          },
          statusRemove: function(seg) {
            return push("pop_seg", { seg });
          },
          segmentUpdate: function(seg) {
            return push("seg_update", { seg });
          },
          segmentNew: function(seg, primary) {
            return push("new_seg", { seg, primary });
          },
          segmentRemove: function(seg) {
            return push("rem_seg", { seg });
          },
          tempStatus: function(seg, above, below) {
            return push("temp_status", { seg, above, below });
          },
          rewind: function(seg) {
            return push("rewind", { seg });
          },
          status: function(seg, above, below) {
            return push("status", { seg, above, below });
          },
          vert: function(x) {
            if (x === curVert)
              return my;
            curVert = x;
            return push("vert", { x });
          },
          log: function(data) {
            if (typeof data !== "string")
              data = JSON.stringify(data, false, "  ");
            return push("log", { txt: data });
          },
          reset: function() {
            return push("reset");
          },
          selected: function(segs) {
            return push("selected", { segs });
          },
          chainStart: function(seg) {
            return push("chain_start", { seg });
          },
          chainRemoveHead: function(index, pt) {
            return push("chain_rem_head", { index, pt });
          },
          chainRemoveTail: function(index, pt) {
            return push("chain_rem_tail", { index, pt });
          },
          chainNew: function(pt1, pt2) {
            return push("chain_new", { pt1, pt2 });
          },
          chainMatch: function(index) {
            return push("chain_match", { index });
          },
          chainClose: function(index) {
            return push("chain_close", { index });
          },
          chainAddHead: function(index, pt) {
            return push("chain_add_head", { index, pt });
          },
          chainAddTail: function(index, pt) {
            return push("chain_add_tail", { index, pt });
          },
          chainConnect: function(index1, index2) {
            return push("chain_con", { index1, index2 });
          },
          chainReverse: function(index) {
            return push("chain_rev", { index });
          },
          chainJoin: function(index1, index2) {
            return push("chain_join", { index1, index2 });
          },
          done: function() {
            return push("done");
          }
        };
        return my;
      }
      module.exports = BuildLog;
    }
  });

  // node_modules/polybooljs/lib/epsilon.js
  var require_epsilon = __commonJS({
    "node_modules/polybooljs/lib/epsilon.js"(exports, module) {
      function Epsilon(eps) {
        if (typeof eps !== "number")
          eps = 1e-10;
        var my = {
          epsilon: function(v) {
            if (typeof v === "number")
              eps = v;
            return eps;
          },
          pointAboveOrOnLine: function(pt, left, right) {
            var Ax = left[0];
            var Ay = left[1];
            var Bx = right[0];
            var By = right[1];
            var Cx = pt[0];
            var Cy = pt[1];
            return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps;
          },
          pointBetween: function(p, left, right) {
            var d_py_ly = p[1] - left[1];
            var d_rx_lx = right[0] - left[0];
            var d_px_lx = p[0] - left[0];
            var d_ry_ly = right[1] - left[1];
            var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly;
            if (dot < eps)
              return false;
            var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly;
            if (dot - sqlen > -eps)
              return false;
            return true;
          },
          pointsSameX: function(p1, p2) {
            return Math.abs(p1[0] - p2[0]) < eps;
          },
          pointsSameY: function(p1, p2) {
            return Math.abs(p1[1] - p2[1]) < eps;
          },
          pointsSame: function(p1, p2) {
            return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2);
          },
          pointsCompare: function(p1, p2) {
            if (my.pointsSameX(p1, p2))
              return my.pointsSameY(p1, p2) ? 0 : p1[1] < p2[1] ? -1 : 1;
            return p1[0] < p2[0] ? -1 : 1;
          },
          pointsCollinear: function(pt1, pt2, pt3) {
            var dx1 = pt1[0] - pt2[0];
            var dy1 = pt1[1] - pt2[1];
            var dx2 = pt2[0] - pt3[0];
            var dy2 = pt2[1] - pt3[1];
            return Math.abs(dx1 * dy2 - dx2 * dy1) < eps;
          },
          linesIntersect: function(a0, a1, b0, b1) {
            var adx = a1[0] - a0[0];
            var ady = a1[1] - a0[1];
            var bdx = b1[0] - b0[0];
            var bdy = b1[1] - b0[1];
            var axb = adx * bdy - ady * bdx;
            if (Math.abs(axb) < eps)
              return false;
            var dx = a0[0] - b0[0];
            var dy = a0[1] - b0[1];
            var A2 = (bdx * dy - bdy * dx) / axb;
            var B2 = (adx * dy - ady * dx) / axb;
            var ret = {
              alongA: 0,
              alongB: 0,
              pt: [
                a0[0] + A2 * adx,
                a0[1] + A2 * ady
              ]
            };
            if (A2 <= -eps)
              ret.alongA = -2;
            else if (A2 < eps)
              ret.alongA = -1;
            else if (A2 - 1 <= -eps)
              ret.alongA = 0;
            else if (A2 - 1 < eps)
              ret.alongA = 1;
            else
              ret.alongA = 2;
            if (B2 <= -eps)
              ret.alongB = -2;
            else if (B2 < eps)
              ret.alongB = -1;
            else if (B2 - 1 <= -eps)
              ret.alongB = 0;
            else if (B2 - 1 < eps)
              ret.alongB = 1;
            else
              ret.alongB = 2;
            return ret;
          },
          pointInsideRegion: function(pt, region) {
            var x = pt[0];
            var y = pt[1];
            var last_x = region[region.length - 1][0];
            var last_y = region[region.length - 1][1];
            var inside = false;
            for (var i = 0; i < region.length; i++) {
              var curr_x = region[i][0];
              var curr_y = region[i][1];
              if (curr_y - y > eps != last_y - y > eps && (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps)
                inside = !inside;
              last_x = curr_x;
              last_y = curr_y;
            }
            return inside;
          }
        };
        return my;
      }
      module.exports = Epsilon;
    }
  });

  // node_modules/polybooljs/lib/linked-list.js
  var require_linked_list = __commonJS({
    "node_modules/polybooljs/lib/linked-list.js"(exports, module) {
      var LinkedList = {
        create: function() {
          var my = {
            root: { root: true, next: null },
            exists: function(node) {
              if (node === null || node === my.root)
                return false;
              return true;
            },
            isEmpty: function() {
              return my.root.next === null;
            },
            getHead: function() {
              return my.root.next;
            },
            insertBefore: function(node, check) {
              var last = my.root;
              var here = my.root.next;
              while (here !== null) {
                if (check(here)) {
                  node.prev = here.prev;
                  node.next = here;
                  here.prev.next = node;
                  here.prev = node;
                  return;
                }
                last = here;
                here = here.next;
              }
              last.next = node;
              node.prev = last;
              node.next = null;
            },
            findTransition: function(check) {
              var prev = my.root;
              var here = my.root.next;
              while (here !== null) {
                if (check(here))
                  break;
                prev = here;
                here = here.next;
              }
              return {
                before: prev === my.root ? null : prev,
                after: here,
                insert: function(node) {
                  node.prev = prev;
                  node.next = here;
                  prev.next = node;
                  if (here !== null)
                    here.prev = node;
                  return node;
                }
              };
            }
          };
          return my;
        },
        node: function(data) {
          data.prev = null;
          data.next = null;
          data.remove = function() {
            data.prev.next = data.next;
            if (data.next)
              data.next.prev = data.prev;
            data.prev = null;
            data.next = null;
          };
          return data;
        }
      };
      module.exports = LinkedList;
    }
  });

  // node_modules/polybooljs/lib/intersecter.js
  var require_intersecter = __commonJS({
    "node_modules/polybooljs/lib/intersecter.js"(exports, module) {
      var LinkedList = require_linked_list();
      function Intersecter(selfIntersection, eps, buildLog) {
        function segmentNew(start, end) {
          return {
            id: buildLog ? buildLog.segmentId() : -1,
            start,
            end,
            myFill: {
              above: null,
              // is there fill above us?
              below: null
              // is there fill below us?
            },
            otherFill: null
          };
        }
        function segmentCopy(start, end, seg) {
          return {
            id: buildLog ? buildLog.segmentId() : -1,
            start,
            end,
            myFill: {
              above: seg.myFill.above,
              below: seg.myFill.below
            },
            otherFill: null
          };
        }
        var event_root = LinkedList.create();
        function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2) {
          var comp = eps.pointsCompare(p1_1, p2_1);
          if (comp !== 0)
            return comp;
          if (eps.pointsSame(p1_2, p2_2))
            return 0;
          if (p1_isStart !== p2_isStart)
            return p1_isStart ? 1 : -1;
          return eps.pointAboveOrOnLine(
            p1_2,
            p2_isStart ? p2_1 : p2_2,
            // order matters
            p2_isStart ? p2_2 : p2_1
          ) ? 1 : -1;
        }
        function eventAdd(ev, other_pt) {
          event_root.insertBefore(ev, function(here) {
            var comp = eventCompare(
              ev.isStart,
              ev.pt,
              other_pt,
              here.isStart,
              here.pt,
              here.other.pt
            );
            return comp < 0;
          });
        }
        function eventAddSegmentStart(seg, primary) {
          var ev_start = LinkedList.node({
            isStart: true,
            pt: seg.start,
            seg,
            primary,
            other: null,
            status: null
          });
          eventAdd(ev_start, seg.end);
          return ev_start;
        }
        function eventAddSegmentEnd(ev_start, seg, primary) {
          var ev_end = LinkedList.node({
            isStart: false,
            pt: seg.end,
            seg,
            primary,
            other: ev_start,
            status: null
          });
          ev_start.other = ev_end;
          eventAdd(ev_end, ev_start.pt);
        }
        function eventAddSegment(seg, primary) {
          var ev_start = eventAddSegmentStart(seg, primary);
          eventAddSegmentEnd(ev_start, seg, primary);
          return ev_start;
        }
        function eventUpdateEnd(ev, end) {
          if (buildLog)
            buildLog.segmentChop(ev.seg, end);
          ev.other.remove();
          ev.seg.end = end;
          ev.other.pt = end;
          eventAdd(ev.other, ev.pt);
        }
        function eventDivide(ev, pt) {
          var ns = segmentCopy(pt, ev.seg.end, ev.seg);
          eventUpdateEnd(ev, pt);
          return eventAddSegment(ns, ev.primary);
        }
        function calculate(primaryPolyInverted, secondaryPolyInverted) {
          var status_root = LinkedList.create();
          function statusCompare(ev1, ev2) {
            var a1 = ev1.seg.start;
            var a2 = ev1.seg.end;
            var b1 = ev2.seg.start;
            var b2 = ev2.seg.end;
            if (eps.pointsCollinear(a1, b1, b2)) {
              if (eps.pointsCollinear(a2, b1, b2))
                return 1;
              return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1;
            }
            return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1;
          }
          function statusFindSurrounding(ev2) {
            return status_root.findTransition(function(here) {
              var comp = statusCompare(ev2, here.ev);
              return comp > 0;
            });
          }
          function checkIntersection(ev1, ev2) {
            var seg1 = ev1.seg;
            var seg2 = ev2.seg;
            var a1 = seg1.start;
            var a2 = seg1.end;
            var b1 = seg2.start;
            var b2 = seg2.end;
            if (buildLog)
              buildLog.checkIntersection(seg1, seg2);
            var i = eps.linesIntersect(a1, a2, b1, b2);
            if (i === false) {
              if (!eps.pointsCollinear(a1, a2, b1))
                return false;
              if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1))
                return false;
              var a1_equ_b1 = eps.pointsSame(a1, b1);
              var a2_equ_b2 = eps.pointsSame(a2, b2);
              if (a1_equ_b1 && a2_equ_b2)
                return ev2;
              var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2);
              var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2);
              if (a1_equ_b1) {
                if (a2_between) {
                  eventDivide(ev2, a2);
                } else {
                  eventDivide(ev1, b2);
                }
                return ev2;
              } else if (a1_between) {
                if (!a2_equ_b2) {
                  if (a2_between) {
                    eventDivide(ev2, a2);
                  } else {
                    eventDivide(ev1, b2);
                  }
                }
                eventDivide(ev2, a1);
              }
            } else {
              if (i.alongA === 0) {
                if (i.alongB === -1)
                  eventDivide(ev1, b1);
                else if (i.alongB === 0)
                  eventDivide(ev1, i.pt);
                else if (i.alongB === 1)
                  eventDivide(ev1, b2);
              }
              if (i.alongB === 0) {
                if (i.alongA === -1)
                  eventDivide(ev2, a1);
                else if (i.alongA === 0)
                  eventDivide(ev2, i.pt);
                else if (i.alongA === 1)
                  eventDivide(ev2, a2);
              }
            }
            return false;
          }
          var segments = [];
          while (!event_root.isEmpty()) {
            var ev = event_root.getHead();
            if (buildLog)
              buildLog.vert(ev.pt[0]);
            if (ev.isStart) {
              let checkBothIntersections2 = function() {
                if (above) {
                  var eve2 = checkIntersection(ev, above);
                  if (eve2)
                    return eve2;
                }
                if (below)
                  return checkIntersection(ev, below);
                return false;
              };
              var checkBothIntersections = checkBothIntersections2;
              if (buildLog)
                buildLog.segmentNew(ev.seg, ev.primary);
              var surrounding = statusFindSurrounding(ev);
              var above = surrounding.before ? surrounding.before.ev : null;
              var below = surrounding.after ? surrounding.after.ev : null;
              if (buildLog) {
                buildLog.tempStatus(
                  ev.seg,
                  above ? above.seg : false,
                  below ? below.seg : false
                );
              }
              var eve = checkBothIntersections2();
              if (eve) {
                if (selfIntersection) {
                  var toggle;
                  if (ev.seg.myFill.below === null)
                    toggle = true;
                  else
                    toggle = ev.seg.myFill.above !== ev.seg.myFill.below;
                  if (toggle)
                    eve.seg.myFill.above = !eve.seg.myFill.above;
                } else {
                  eve.seg.otherFill = ev.seg.myFill;
                }
                if (buildLog)
                  buildLog.segmentUpdate(eve.seg);
                ev.other.remove();
                ev.remove();
              }
              if (event_root.getHead() !== ev) {
                if (buildLog)
                  buildLog.rewind(ev.seg);
                continue;
              }
              if (selfIntersection) {
                var toggle;
                if (ev.seg.myFill.below === null)
                  toggle = true;
                else
                  toggle = ev.seg.myFill.above !== ev.seg.myFill.below;
                if (!below) {
                  ev.seg.myFill.below = primaryPolyInverted;
                } else {
                  ev.seg.myFill.below = below.seg.myFill.above;
                }
                if (toggle)
                  ev.seg.myFill.above = !ev.seg.myFill.below;
                else
                  ev.seg.myFill.above = ev.seg.myFill.below;
              } else {
                if (ev.seg.otherFill === null) {
                  var inside;
                  if (!below) {
                    inside = ev.primary ? secondaryPolyInverted : primaryPolyInverted;
                  } else {
                    if (ev.primary === below.primary)
                      inside = below.seg.otherFill.above;
                    else
                      inside = below.seg.myFill.above;
                  }
                  ev.seg.otherFill = {
                    above: inside,
                    below: inside
                  };
                }
              }
              if (buildLog) {
                buildLog.status(
                  ev.seg,
                  above ? above.seg : false,
                  below ? below.seg : false
                );
              }
              ev.other.status = surrounding.insert(LinkedList.node({ ev }));
            } else {
              var st = ev.status;
              if (st === null) {
                throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");
              }
              if (status_root.exists(st.prev) && status_root.exists(st.next))
                checkIntersection(st.prev.ev, st.next.ev);
              if (buildLog)
                buildLog.statusRemove(st.ev.seg);
              st.remove();
              if (!ev.primary) {
                var s = ev.seg.myFill;
                ev.seg.myFill = ev.seg.otherFill;
                ev.seg.otherFill = s;
              }
              segments.push(ev.seg);
            }
            event_root.getHead().remove();
          }
          if (buildLog)
            buildLog.done();
          return segments;
        }
        if (!selfIntersection) {
          return {
            calculate: function(segments1, inverted1, segments2, inverted2) {
              segments1.forEach(function(seg) {
                eventAddSegment(segmentCopy(seg.start, seg.end, seg), true);
              });
              segments2.forEach(function(seg) {
                eventAddSegment(segmentCopy(seg.start, seg.end, seg), false);
              });
              return calculate(inverted1, inverted2);
            }
          };
        }
        return {
          addRegion: function(region) {
            var pt1;
            var pt2 = region[region.length - 1];
            for (var i = 0; i < region.length; i++) {
              pt1 = pt2;
              pt2 = region[i];
              var forward = eps.pointsCompare(pt1, pt2);
              if (forward === 0)
                continue;
              eventAddSegment(
                segmentNew(
                  forward < 0 ? pt1 : pt2,
                  forward < 0 ? pt2 : pt1
                ),
                true
              );
            }
          },
          calculate: function(inverted) {
            return calculate(inverted, false);
          }
        };
      }
      module.exports = Intersecter;
    }
  });

  // node_modules/polybooljs/lib/segment-chainer.js
  var require_segment_chainer = __commonJS({
    "node_modules/polybooljs/lib/segment-chainer.js"(exports, module) {
      function SegmentChainer(segments, eps, buildLog) {
        var chains = [];
        var regions = [];
        segments.forEach(function(seg) {
          var pt1 = seg.start;
          var pt2 = seg.end;
          if (eps.pointsSame(pt1, pt2)) {
            console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large");
            return;
          }
          if (buildLog)
            buildLog.chainStart(seg);
          var first_match = {
            index: 0,
            matches_head: false,
            matches_pt1: false
          };
          var second_match = {
            index: 0,
            matches_head: false,
            matches_pt1: false
          };
          var next_match = first_match;
          function setMatch(index2, matches_head, matches_pt1) {
            next_match.index = index2;
            next_match.matches_head = matches_head;
            next_match.matches_pt1 = matches_pt1;
            if (next_match === first_match) {
              next_match = second_match;
              return false;
            }
            next_match = null;
            return true;
          }
          for (var i = 0; i < chains.length; i++) {
            var chain = chains[i];
            var head = chain[0];
            var head2 = chain[1];
            var tail = chain[chain.length - 1];
            var tail2 = chain[chain.length - 2];
            if (eps.pointsSame(head, pt1)) {
              if (setMatch(i, true, true))
                break;
            } else if (eps.pointsSame(head, pt2)) {
              if (setMatch(i, true, false))
                break;
            } else if (eps.pointsSame(tail, pt1)) {
              if (setMatch(i, false, true))
                break;
            } else if (eps.pointsSame(tail, pt2)) {
              if (setMatch(i, false, false))
                break;
            }
          }
          if (next_match === first_match) {
            chains.push([pt1, pt2]);
            if (buildLog)
              buildLog.chainNew(pt1, pt2);
            return;
          }
          if (next_match === second_match) {
            if (buildLog)
              buildLog.chainMatch(first_match.index);
            var index = first_match.index;
            var pt = first_match.matches_pt1 ? pt2 : pt1;
            var addToHead = first_match.matches_head;
            var chain = chains[index];
            var grow = addToHead ? chain[0] : chain[chain.length - 1];
            var grow2 = addToHead ? chain[1] : chain[chain.length - 2];
            var oppo = addToHead ? chain[chain.length - 1] : chain[0];
            var oppo2 = addToHead ? chain[chain.length - 2] : chain[1];
            if (eps.pointsCollinear(grow2, grow, pt)) {
              if (addToHead) {
                if (buildLog)
                  buildLog.chainRemoveHead(first_match.index, pt);
                chain.shift();
              } else {
                if (buildLog)
                  buildLog.chainRemoveTail(first_match.index, pt);
                chain.pop();
              }
              grow = grow2;
            }
            if (eps.pointsSame(oppo, pt)) {
              chains.splice(index, 1);
              if (eps.pointsCollinear(oppo2, oppo, grow)) {
                if (addToHead) {
                  if (buildLog)
                    buildLog.chainRemoveTail(first_match.index, grow);
                  chain.pop();
                } else {
                  if (buildLog)
                    buildLog.chainRemoveHead(first_match.index, grow);
                  chain.shift();
                }
              }
              if (buildLog)
                buildLog.chainClose(first_match.index);
              regions.push(chain);
              return;
            }
            if (addToHead) {
              if (buildLog)
                buildLog.chainAddHead(first_match.index, pt);
              chain.unshift(pt);
            } else {
              if (buildLog)
                buildLog.chainAddTail(first_match.index, pt);
              chain.push(pt);
            }
            return;
          }
          function reverseChain(index2) {
            if (buildLog)
              buildLog.chainReverse(index2);
            chains[index2].reverse();
          }
          function appendChain(index1, index2) {
            var chain1 = chains[index1];
            var chain2 = chains[index2];
            var tail3 = chain1[chain1.length - 1];
            var tail22 = chain1[chain1.length - 2];
            var head3 = chain2[0];
            var head22 = chain2[1];
            if (eps.pointsCollinear(tail22, tail3, head3)) {
              if (buildLog)
                buildLog.chainRemoveTail(index1, tail3);
              chain1.pop();
              tail3 = tail22;
            }
            if (eps.pointsCollinear(tail3, head3, head22)) {
              if (buildLog)
                buildLog.chainRemoveHead(index2, head3);
              chain2.shift();
            }
            if (buildLog)
              buildLog.chainJoin(index1, index2);
            chains[index1] = chain1.concat(chain2);
            chains.splice(index2, 1);
          }
          var F = first_match.index;
          var S = second_match.index;
          if (buildLog)
            buildLog.chainConnect(F, S);
          var reverseF = chains[F].length < chains[S].length;
          if (first_match.matches_head) {
            if (second_match.matches_head) {
              if (reverseF) {
                reverseChain(F);
                appendChain(F, S);
              } else {
                reverseChain(S);
                appendChain(S, F);
              }
            } else {
              appendChain(S, F);
            }
          } else {
            if (second_match.matches_head) {
              appendChain(F, S);
            } else {
              if (reverseF) {
                reverseChain(F);
                appendChain(S, F);
              } else {
                reverseChain(S);
                appendChain(F, S);
              }
            }
          }
        });
        return regions;
      }
      module.exports = SegmentChainer;
    }
  });

  // node_modules/polybooljs/lib/segment-selector.js
  var require_segment_selector = __commonJS({
    "node_modules/polybooljs/lib/segment-selector.js"(exports, module) {
      function select(segments, selection, buildLog) {
        var result = [];
        segments.forEach(function(seg) {
          var index = (seg.myFill.above ? 8 : 0) + (seg.myFill.below ? 4 : 0) + (seg.otherFill && seg.otherFill.above ? 2 : 0) + (seg.otherFill && seg.otherFill.below ? 1 : 0);
          if (selection[index] !== 0) {
            result.push({
              id: buildLog ? buildLog.segmentId() : -1,
              start: seg.start,
              end: seg.end,
              myFill: {
                above: selection[index] === 1,
                // 1 if filled above
                below: selection[index] === 2
                // 2 if filled below
              },
              otherFill: null
            });
          }
        });
        if (buildLog)
          buildLog.selected(result);
        return result;
      }
      var SegmentSelector = {
        union: function(segments, buildLog) {
          return select(segments, [
            0,
            2,
            1,
            0,
            2,
            2,
            0,
            0,
            1,
            0,
            1,
            0,
            0,
            0,
            0,
            0
          ], buildLog);
        },
        intersect: function(segments, buildLog) {
          return select(segments, [
            0,
            0,
            0,
            0,
            0,
            2,
            0,
            2,
            0,
            0,
            1,
            1,
            0,
            2,
            1,
            0
          ], buildLog);
        },
        difference: function(segments, buildLog) {
          return select(segments, [
            0,
            0,
            0,
            0,
            2,
            0,
            2,
            0,
            1,
            1,
            0,
            0,
            0,
            1,
            2,
            0
          ], buildLog);
        },
        differenceRev: function(segments, buildLog) {
          return select(segments, [
            0,
            2,
            1,
            0,
            0,
            0,
            1,
            1,
            0,
            2,
            0,
            2,
            0,
            0,
            0,
            0
          ], buildLog);
        },
        xor: function(segments, buildLog) {
          return select(segments, [
            0,
            2,
            1,
            0,
            2,
            0,
            0,
            1,
            1,
            0,
            0,
            2,
            0,
            1,
            2,
            0
          ], buildLog);
        }
      };
      module.exports = SegmentSelector;
    }
  });

  // node_modules/polybooljs/lib/geojson.js
  var require_geojson = __commonJS({
    "node_modules/polybooljs/lib/geojson.js"(exports, module) {
      var GeoJSON = {
        // convert a GeoJSON object to a PolyBool polygon
        toPolygon: function(PolyBool, geojson) {
          function GeoPoly(coords) {
            if (coords.length <= 0)
              return PolyBool.segments({ inverted: false, regions: [] });
            function LineString(ls) {
              var reg = ls.slice(0, ls.length - 1);
              return PolyBool.segments({ inverted: false, regions: [reg] });
            }
            var out2 = LineString(coords[0]);
            for (var i2 = 1; i2 < coords.length; i2++)
              out2 = PolyBool.selectDifference(PolyBool.combine(out2, LineString(coords[i2])));
            return out2;
          }
          if (geojson.type === "Polygon") {
            return PolyBool.polygon(GeoPoly(geojson.coordinates));
          } else if (geojson.type === "MultiPolygon") {
            var out = PolyBool.segments({ inverted: false, regions: [] });
            for (var i = 0; i < geojson.coordinates.length; i++)
              out = PolyBool.selectUnion(PolyBool.combine(out, GeoPoly(geojson.coordinates[i])));
            return PolyBool.polygon(out);
          }
          throw new Error("PolyBool: Cannot convert GeoJSON object to PolyBool polygon");
        },
        // convert a PolyBool polygon to a GeoJSON object
        fromPolygon: function(PolyBool, eps, poly) {
          poly = PolyBool.polygon(PolyBool.segments(poly));
          function regionInsideRegion(r1, r2) {
            return eps.pointInsideRegion([
              (r1[0][0] + r1[1][0]) * 0.5,
              (r1[0][1] + r1[1][1]) * 0.5
            ], r2);
          }
          function newNode(region2) {
            return {
              region: region2,
              children: []
            };
          }
          var roots = newNode(null);
          function addChild(root, region2) {
            for (var i2 = 0; i2 < root.children.length; i2++) {
              var child = root.children[i2];
              if (regionInsideRegion(region2, child.region)) {
                addChild(child, region2);
                return;
              }
            }
            var node = newNode(region2);
            for (var i2 = 0; i2 < root.children.length; i2++) {
              var child = root.children[i2];
              if (regionInsideRegion(child.region, region2)) {
                node.children.push(child);
                root.children.splice(i2, 1);
                i2--;
              }
            }
            root.children.push(node);
          }
          for (var i = 0; i < poly.regions.length; i++) {
            var region = poly.regions[i];
            if (region.length < 3)
              continue;
            addChild(roots, region);
          }
          function forceWinding(region2, clockwise) {
            var winding = 0;
            var last_x = region2[region2.length - 1][0];
            var last_y = region2[region2.length - 1][1];
            var copy = [];
            for (var i2 = 0; i2 < region2.length; i2++) {
              var curr_x = region2[i2][0];
              var curr_y = region2[i2][1];
              copy.push([curr_x, curr_y]);
              winding += curr_y * last_x - curr_x * last_y;
              last_x = curr_x;
              last_y = curr_y;
            }
            var isclockwise = winding < 0;
            if (isclockwise !== clockwise)
              copy.reverse();
            copy.push([copy[0][0], copy[0][1]]);
            return copy;
          }
          var geopolys = [];
          function addExterior(node) {
            var poly2 = [forceWinding(node.region, false)];
            geopolys.push(poly2);
            for (var i2 = 0; i2 < node.children.length; i2++)
              poly2.push(getInterior(node.children[i2]));
          }
          function getInterior(node) {
            for (var i2 = 0; i2 < node.children.length; i2++)
              addExterior(node.children[i2]);
            return forceWinding(node.region, true);
          }
          for (var i = 0; i < roots.children.length; i++)
            addExterior(roots.children[i]);
          if (geopolys.length <= 0)
            return { type: "Polygon", coordinates: [] };
          if (geopolys.length == 1)
            return { type: "Polygon", coordinates: geopolys[0] };
          return {
            // otherwise, use a GeoJSON MultiPolygon
            type: "MultiPolygon",
            coordinates: geopolys
          };
        }
      };
      module.exports = GeoJSON;
    }
  });

  // node_modules/polybooljs/index.js
  var require_polybooljs = __commonJS({
    "node_modules/polybooljs/index.js"(exports, module) {
      var BuildLog = require_build_log();
      var Epsilon = require_epsilon();
      var Intersecter = require_intersecter();
      var SegmentChainer = require_segment_chainer();
      var SegmentSelector = require_segment_selector();
      var GeoJSON = require_geojson();
      var buildLog = false;
      var epsilon = Epsilon();
      var PolyBool;
      PolyBool = {
        // getter/setter for buildLog
        buildLog: function(bl) {
          if (bl === true)
            buildLog = BuildLog();
          else if (bl === false)
            buildLog = false;
          return buildLog === false ? false : buildLog.list;
        },
        // getter/setter for epsilon
        epsilon: function(v) {
          return epsilon.epsilon(v);
        },
        // core API
        segments: function(poly) {
          var i = Intersecter(true, epsilon, buildLog);
          poly.regions.forEach(i.addRegion);
          return {
            segments: i.calculate(poly.inverted),
            inverted: poly.inverted
          };
        },
        combine: function(segments1, segments2) {
          var i3 = Intersecter(false, epsilon, buildLog);
          return {
            combined: i3.calculate(
              segments1.segments,
              segments1.inverted,
              segments2.segments,
              segments2.inverted
            ),
            inverted1: segments1.inverted,
            inverted2: segments2.inverted
          };
        },
        selectUnion: function(combined) {
          return {
            segments: SegmentSelector.union(combined.combined, buildLog),
            inverted: combined.inverted1 || combined.inverted2
          };
        },
        selectIntersect: function(combined) {
          return {
            segments: SegmentSelector.intersect(combined.combined, buildLog),
            inverted: combined.inverted1 && combined.inverted2
          };
        },
        selectDifference: function(combined) {
          return {
            segments: SegmentSelector.difference(combined.combined, buildLog),
            inverted: combined.inverted1 && !combined.inverted2
          };
        },
        selectDifferenceRev: function(combined) {
          return {
            segments: SegmentSelector.differenceRev(combined.combined, buildLog),
            inverted: !combined.inverted1 && combined.inverted2
          };
        },
        selectXor: function(combined) {
          return {
            segments: SegmentSelector.xor(combined.combined, buildLog),
            inverted: combined.inverted1 !== combined.inverted2
          };
        },
        polygon: function(segments) {
          return {
            regions: SegmentChainer(segments.segments, epsilon, buildLog),
            inverted: segments.inverted
          };
        },
        // GeoJSON converters
        polygonFromGeoJSON: function(geojson) {
          return GeoJSON.toPolygon(PolyBool, geojson);
        },
        polygonToGeoJSON: function(poly) {
          return GeoJSON.fromPolygon(PolyBool, epsilon, poly);
        },
        // helper functions for common operations
        union: function(poly1, poly2) {
          return operate(poly1, poly2, PolyBool.selectUnion);
        },
        intersect: function(poly1, poly2) {
          return operate(poly1, poly2, PolyBool.selectIntersect);
        },
        difference: function(poly1, poly2) {
          return operate(poly1, poly2, PolyBool.selectDifference);
        },
        differenceRev: function(poly1, poly2) {
          return operate(poly1, poly2, PolyBool.selectDifferenceRev);
        },
        xor: function(poly1, poly2) {
          return operate(poly1, poly2, PolyBool.selectXor);
        }
      };
      function operate(poly1, poly2, selector) {
        var seg1 = PolyBool.segments(poly1);
        var seg2 = PolyBool.segments(poly2);
        var comb = PolyBool.combine(seg1, seg2);
        var seg3 = selector(comb);
        return PolyBool.polygon(seg3);
      }
      if (typeof window === "object")
        window.PolyBool = PolyBool;
      module.exports = PolyBool;
    }
  });

  // node_modules/point-in-polygon/nested.js
  var require_nested = __commonJS({
    "node_modules/point-in-polygon/nested.js"(exports, module) {
      module.exports = function pointInPolygonNested(point, vs, start, end) {
        var x = point[0], y = point[1];
        var inside = false;
        if (start === void 0) start = 0;
        if (end === void 0) end = vs.length;
        var len = end - start;
        for (var i = 0, j = len - 1; i < len; j = i++) {
          var xi = vs[i + start][0], yi = vs[i + start][1];
          var xj = vs[j + start][0], yj = vs[j + start][1];
          var intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi;
          if (intersect) inside = !inside;
        }
        return inside;
      };
    }
  });

  // src/lib/polygon.js
  var require_polygon = __commonJS({
    "src/lib/polygon.js"(exports, module) {
      "use strict";
      var dot = require_matrix().dot;
      var BADNUM = require_numerical().BADNUM;
      var polygon = module.exports = {};
      polygon.tester = function tester(ptsIn) {
        var pts = ptsIn.slice();
        var xmin = pts[0][0];
        var xmax = xmin;
        var ymin = pts[0][1];
        var ymax = ymin;
        var i;
        if (pts[pts.length - 1][0] !== pts[0][0] || pts[pts.length - 1][1] !== pts[0][1]) {
          pts.push(pts[0]);
        }
        for (i = 1; i < pts.length; i++) {
          xmin = Math.min(xmin, pts[i][0]);
          xmax = Math.max(xmax, pts[i][0]);
          ymin = Math.min(ymin, pts[i][1]);
          ymax = Math.max(ymax, pts[i][1]);
        }
        var isRect = false;
        var rectFirstEdgeTest;
        if (pts.length === 5) {
          if (pts[0][0] === pts[1][0]) {
            if (pts[2][0] === pts[3][0] && pts[0][1] === pts[3][1] && pts[1][1] === pts[2][1]) {
              isRect = true;
              rectFirstEdgeTest = function(pt) {
                return pt[0] === pts[0][0];
              };
            }
          } else if (pts[0][1] === pts[1][1]) {
            if (pts[2][1] === pts[3][1] && pts[0][0] === pts[3][0] && pts[1][0] === pts[2][0]) {
              isRect = true;
              rectFirstEdgeTest = function(pt) {
                return pt[1] === pts[0][1];
              };
            }
          }
        }
        function rectContains(pt, omitFirstEdge) {
          var x = pt[0];
          var y = pt[1];
          if (x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            return false;
          }
          if (omitFirstEdge && rectFirstEdgeTest(pt)) return false;
          return true;
        }
        function contains(pt, omitFirstEdge) {
          var x = pt[0];
          var y = pt[1];
          if (x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            return false;
          }
          var imax = pts.length;
          var x1 = pts[0][0];
          var y1 = pts[0][1];
          var crossings = 0;
          var i2;
          var x0;
          var y0;
          var xmini;
          var ycross;
          for (i2 = 1; i2 < imax; i2++) {
            x0 = x1;
            y0 = y1;
            x1 = pts[i2][0];
            y1 = pts[i2][1];
            xmini = Math.min(x0, x1);
            if (x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) {
              continue;
            } else if (y < Math.min(y0, y1)) {
              if (x !== xmini) crossings++;
            } else {
              if (x1 === x0) ycross = y;
              else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0);
              if (y === ycross) {
                if (i2 === 1 && omitFirstEdge) return false;
                return true;
              }
              if (y <= ycross && x !== xmini) crossings++;
            }
          }
          return crossings % 2 === 1;
        }
        var degenerate = true;
        var lastPt = pts[0];
        for (i = 1; i < pts.length; i++) {
          if (lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) {
            degenerate = false;
            break;
          }
        }
        return {
          xmin,
          xmax,
          ymin,
          ymax,
          pts,
          contains: isRect ? rectContains : contains,
          isRect,
          degenerate
        };
      };
      polygon.isSegmentBent = function isSegmentBent(pts, start, end, tolerance) {
        var startPt = pts[start];
        var segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]];
        var segmentSquared = dot(segment, segment);
        var segmentLen = Math.sqrt(segmentSquared);
        var unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen];
        var i;
        var part;
        var partParallel;
        for (i = start + 1; i < end; i++) {
          part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]];
          partParallel = dot(part, segment);
          if (partParallel < 0 || partParallel > segmentSquared || Math.abs(dot(part, unitPerp)) > tolerance) return true;
        }
        return false;
      };
      polygon.filter = function filter(pts, tolerance) {
        var ptsFiltered = [pts[0]];
        var doneRawIndex = 0;
        var doneFilteredIndex = 0;
        function addPt(pt) {
          pts.push(pt);
          var prevFilterLen = ptsFiltered.length;
          var iLast = doneRawIndex;
          ptsFiltered.splice(doneFilteredIndex + 1);
          for (var i = iLast + 1; i < pts.length; i++) {
            if (i === pts.length - 1 || polygon.isSegmentBent(pts, iLast, i + 1, tolerance)) {
              ptsFiltered.push(pts[i]);
              if (ptsFiltered.length < prevFilterLen - 2) {
                doneRawIndex = i;
                doneFilteredIndex = ptsFiltered.length - 1;
              }
              iLast = i;
            }
          }
        }
        if (pts.length > 1) {
          var lastPt = pts.pop();
          addPt(lastPt);
        }
        return {
          addPt,
          raw: pts,
          filtered: ptsFiltered
        };
      };
    }
  });

  // src/components/selections/constants.js
  var require_constants7 = __commonJS({
    "src/components/selections/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // max pixels off straight before a lasso select line counts as bent
        BENDPX: 1.5,
        // smallest dimension allowed for a select box
        MINSELECT: 12,
        // throttling limit (ms) for selectPoints calls
        SELECTDELAY: 100,
        // cache ID suffix for throttle
        SELECTID: "-select"
      };
    }
  });

  // src/components/selections/select.js
  var require_select = __commonJS({
    "src/components/selections/select.js"(exports, module) {
      "use strict";
      var polybool = require_polybooljs();
      var pointInPolygon = require_nested();
      var Registry = require_registry();
      var dashStyle = require_drawing().dashStyle;
      var Color2 = require_color();
      var Fx = require_fx();
      var makeEventData = require_helpers2().makeEventData;
      var dragHelpers = require_helpers5();
      var freeMode = dragHelpers.freeMode;
      var rectMode = dragHelpers.rectMode;
      var drawMode = dragHelpers.drawMode;
      var openMode = dragHelpers.openMode;
      var selectMode = dragHelpers.selectMode;
      var shapeHelpers = require_helpers8();
      var shapeConstants = require_constants5();
      var displayOutlines = require_display_outlines();
      var clearOutline = require_handle_outline().clearOutline;
      var newShapeHelpers = require_helpers7();
      var handleEllipse = newShapeHelpers.handleEllipse;
      var readPaths = newShapeHelpers.readPaths;
      var newShapes = require_newshapes().newShapes;
      var newSelections = require_newselections();
      var activateLastSelection = require_draw3().activateLastSelection;
      var Lib = require_lib();
      var ascending = Lib.sorterAsc;
      var libPolygon = require_polygon();
      var throttle = require_throttle();
      var getFromId = require_axis_ids().getFromId;
      var clearGlCanvases = require_clear_gl_canvases();
      var redrawReglTraces = require_subroutines().redrawReglTraces;
      var constants = require_constants7();
      var MINSELECT = constants.MINSELECT;
      var filteredPolygon = libPolygon.filter;
      var polygonTester = libPolygon.tester;
      var helpers = require_helpers6();
      var p2r = helpers.p2r;
      var axValue = helpers.axValue;
      var getTransform = helpers.getTransform;
      function hasSubplot(dragOptions) {
        return dragOptions.subplot !== void 0;
      }
      function prepSelect(evt, startX, startY, dragOptions, mode) {
        var isCartesian = !hasSubplot(dragOptions);
        var isFreeMode = freeMode(mode);
        var isRectMode = rectMode(mode);
        var isOpenMode = openMode(mode);
        var isDrawMode = drawMode(mode);
        var isSelectMode = selectMode(mode);
        var isLine = mode === "drawline";
        var isEllipse = mode === "drawcircle";
        var isLineOrEllipse = isLine || isEllipse;
        var gd = dragOptions.gd;
        var fullLayout = gd._fullLayout;
        var immediateSelect = isSelectMode && fullLayout.newselection.mode === "immediate" && isCartesian;
        var zoomLayer = fullLayout._zoomlayer;
        var dragBBox = dragOptions.element.getBoundingClientRect();
        var plotinfo = dragOptions.plotinfo;
        var transform = getTransform(plotinfo);
        var x0 = startX - dragBBox.left;
        var y0 = startY - dragBBox.top;
        fullLayout._calcInverseTransform(gd);
        var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(x0, y0);
        x0 = transformedCoords[0];
        y0 = transformedCoords[1];
        var scaleX = fullLayout._invScaleX;
        var scaleY = fullLayout._invScaleY;
        var x1 = x0;
        var y1 = y0;
        var path0 = "M" + x0 + "," + y0;
        var xAxis = dragOptions.xaxes[0];
        var yAxis = dragOptions.yaxes[0];
        var pw = xAxis._length;
        var ph = yAxis._length;
        var subtract = evt.altKey && !(drawMode(mode) && isOpenMode);
        var filterPoly, selectionTesters, mergedPolygons, currentPolygon;
        var i, searchInfo, eventData;
        coerceSelectionsCache(evt, gd, dragOptions);
        if (isFreeMode) {
          filterPoly = filteredPolygon([[x0, y0]], constants.BENDPX);
        }
        var outlines = zoomLayer.selectAll("path.select-outline-" + plotinfo.id).data([1]);
        var newStyle = isDrawMode ? fullLayout.newshape : fullLayout.newselection;
        if (isDrawMode) {
          dragOptions.hasText = newStyle.label.text || newStyle.label.texttemplate;
        }
        var fillC = isDrawMode && !isOpenMode ? newStyle.fillcolor : "rgba(0,0,0,0)";
        var strokeC = newStyle.line.color || (isCartesian ? Color2.contrast(gd._fullLayout.plot_bgcolor) : "#7f7f7f");
        outlines.enter().append("path").attr("class", "select-outline select-outline-" + plotinfo.id).style({
          opacity: isDrawMode ? newStyle.opacity / 2 : 1,
          "stroke-dasharray": dashStyle(newStyle.line.dash, newStyle.line.width),
          "stroke-width": newStyle.line.width + "px",
          "shape-rendering": "crispEdges"
        }).call(Color2.stroke, strokeC).call(Color2.fill, fillC).attr("fill-rule", "evenodd").classed("cursor-move", isDrawMode ? true : false).attr("transform", transform).attr("d", path0 + "Z");
        var corners = zoomLayer.append("path").attr("class", "zoombox-corners").style({
          fill: Color2.background,
          stroke: Color2.defaultLine,
          "stroke-width": 1
        }).attr("transform", transform).attr("d", "M0,0Z");
        if (isDrawMode && dragOptions.hasText) {
          var shapeGroup = zoomLayer.select(".label-temp");
          if (shapeGroup.empty()) {
            shapeGroup = zoomLayer.append("g").classed("label-temp", true).classed("select-outline", true).style({ opacity: 0.8 });
          }
        }
        var throttleID = fullLayout._uid + constants.SELECTID;
        var selection = [];
        var searchTraces = determineSearchTraces(
          gd,
          dragOptions.xaxes,
          dragOptions.yaxes,
          dragOptions.subplot
        );
        if (immediateSelect && !evt.shiftKey) {
          dragOptions._clearSubplotSelections = function() {
            if (!isCartesian) return;
            var xRef = xAxis._id;
            var yRef = yAxis._id;
            deselectSubplot(gd, xRef, yRef, searchTraces);
            var selections = (gd.layout || {}).selections || [];
            var list = [];
            var selectionErased = false;
            for (var q = 0; q < selections.length; q++) {
              var s = fullLayout.selections[q];
              if (!s || s.xref !== xRef || s.yref !== yRef) {
                list.push(selections[q]);
              } else {
                selectionErased = true;
              }
            }
            if (selectionErased) {
              gd._fullLayout._noEmitSelectedAtStart = true;
              Registry.call("_guiRelayout", gd, {
                selections: list
              });
            }
          };
        }
        var fillRangeItems = getFillRangeItems(dragOptions);
        dragOptions.moveFn = function(dx0, dy0) {
          if (dragOptions._clearSubplotSelections) {
            dragOptions._clearSubplotSelections();
            dragOptions._clearSubplotSelections = void 0;
          }
          x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0));
          y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0));
          var dx = Math.abs(x1 - x0);
          var dy = Math.abs(y1 - y0);
          if (isRectMode) {
            var direction;
            var start, end;
            if (isSelectMode) {
              var q = fullLayout.selectdirection;
              if (q === "any") {
                if (dy < Math.min(dx * 0.6, MINSELECT)) {
                  direction = "h";
                } else if (dx < Math.min(dy * 0.6, MINSELECT)) {
                  direction = "v";
                } else {
                  direction = "d";
                }
              } else {
                direction = q;
              }
              switch (direction) {
                case "h":
                  start = isEllipse ? ph / 2 : 0;
                  end = ph;
                  break;
                case "v":
                  start = isEllipse ? pw / 2 : 0;
                  end = pw;
                  break;
              }
            }
            if (isDrawMode) {
              switch (fullLayout.newshape.drawdirection) {
                case "vertical":
                  direction = "h";
                  start = isEllipse ? ph / 2 : 0;
                  end = ph;
                  break;
                case "horizontal":
                  direction = "v";
                  start = isEllipse ? pw / 2 : 0;
                  end = pw;
                  break;
                case "ortho":
                  if (dx < dy) {
                    direction = "h";
                    start = y0;
                    end = y1;
                  } else {
                    direction = "v";
                    start = x0;
                    end = x1;
                  }
                  break;
                default:
                  direction = "d";
              }
            }
            if (direction === "h") {
              currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x1, start], [x1, end]) : (
                // using x1 instead of x0 allows adjusting the line while drawing
                [[x0, start], [x0, end], [x1, end], [x1, start]]
              );
              currentPolygon.xmin = isLineOrEllipse ? x1 : Math.min(x0, x1);
              currentPolygon.xmax = isLineOrEllipse ? x1 : Math.max(x0, x1);
              currentPolygon.ymin = Math.min(start, end);
              currentPolygon.ymax = Math.max(start, end);
              corners.attr("d", "M" + currentPolygon.xmin + "," + (y0 - MINSELECT) + "h-4v" + 2 * MINSELECT + "h4ZM" + (currentPolygon.xmax - 1) + "," + (y0 - MINSELECT) + "h4v" + 2 * MINSELECT + "h-4Z");
            } else if (direction === "v") {
              currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [start, y1], [end, y1]) : (
                // using y1 instead of y0 allows adjusting the line while drawing
                [[start, y0], [start, y1], [end, y1], [end, y0]]
              );
              currentPolygon.xmin = Math.min(start, end);
              currentPolygon.xmax = Math.max(start, end);
              currentPolygon.ymin = isLineOrEllipse ? y1 : Math.min(y0, y1);
              currentPolygon.ymax = isLineOrEllipse ? y1 : Math.max(y0, y1);
              corners.attr("d", "M" + (x0 - MINSELECT) + "," + currentPolygon.ymin + "v-4h" + 2 * MINSELECT + "v4ZM" + (x0 - MINSELECT) + "," + (currentPolygon.ymax - 1) + "v4h" + 2 * MINSELECT + "v-4Z");
            } else if (direction === "d") {
              currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x0, y0], [x1, y1]) : [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
              currentPolygon.xmin = Math.min(x0, x1);
              currentPolygon.xmax = Math.max(x0, x1);
              currentPolygon.ymin = Math.min(y0, y1);
              currentPolygon.ymax = Math.max(y0, y1);
              corners.attr("d", "M0,0Z");
            }
          } else if (isFreeMode) {
            filterPoly.addPt([x1, y1]);
            currentPolygon = filterPoly.filtered;
          }
          if (dragOptions.selectionDefs && dragOptions.selectionDefs.length) {
            mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract);
            currentPolygon.subtract = subtract;
            selectionTesters = multiTester(dragOptions.selectionDefs.concat([currentPolygon]));
          } else {
            mergedPolygons = [currentPolygon];
            selectionTesters = polygonTester(currentPolygon);
          }
          displayOutlines(convertPoly(mergedPolygons, isOpenMode), outlines, dragOptions);
          if (isSelectMode) {
            var _res = reselect(gd, false);
            var extraPoints = _res.eventData ? _res.eventData.points.slice() : [];
            _res = reselect(gd, false, selectionTesters, searchTraces, dragOptions);
            selectionTesters = _res.selectionTesters;
            eventData = _res.eventData;
            var poly;
            if (filterPoly) {
              poly = filterPoly.filtered;
            } else {
              poly = castMultiPolygon(mergedPolygons);
            }
            throttle.throttle(
              throttleID,
              constants.SELECTDELAY,
              function() {
                selection = _doSelect(selectionTesters, searchTraces);
                var newPoints = selection.slice();
                for (var w = 0; w < extraPoints.length; w++) {
                  var p = extraPoints[w];
                  var found = false;
                  for (var u = 0; u < newPoints.length; u++) {
                    if (newPoints[u].curveNumber === p.curveNumber && newPoints[u].pointNumber === p.pointNumber) {
                      found = true;
                      break;
                    }
                  }
                  if (!found) newPoints.push(p);
                }
                if (newPoints.length) {
                  if (!eventData) eventData = {};
                  eventData.points = newPoints;
                }
                fillRangeItems(eventData, poly);
                emitSelecting(gd, eventData);
              }
            );
          }
        };
        dragOptions.clickFn = function(numClicks, evt2) {
          corners.remove();
          if (gd._fullLayout._activeShapeIndex >= 0) {
            gd._fullLayout._deactivateShape(gd);
            return;
          }
          if (isDrawMode) return;
          var clickmode = fullLayout.clickmode;
          throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            if (numClicks === 2) {
              outlines.remove();
              for (i = 0; i < searchTraces.length; i++) {
                searchInfo = searchTraces[i];
                searchInfo._module.selectPoints(searchInfo, false);
              }
              updateSelectedState(gd, searchTraces);
              clearSelectionsCache(dragOptions);
              emitDeselect(gd);
              if (searchTraces.length) {
                var clickedXaxis = searchTraces[0].xaxis;
                var clickedYaxis = searchTraces[0].yaxis;
                if (clickedXaxis && clickedYaxis) {
                  var subSelections = [];
                  var allSelections = gd._fullLayout.selections;
                  for (var k = 0; k < allSelections.length; k++) {
                    var s = allSelections[k];
                    if (!s) continue;
                    if (s.xref !== clickedXaxis._id || s.yref !== clickedYaxis._id) {
                      subSelections.push(s);
                    }
                  }
                  if (subSelections.length < allSelections.length) {
                    gd._fullLayout._noEmitSelectedAtStart = true;
                    Registry.call("_guiRelayout", gd, {
                      selections: subSelections
                    });
                  }
                }
              }
            } else {
              if (clickmode.indexOf("select") > -1) {
                selectOnClick(
                  evt2,
                  gd,
                  dragOptions.xaxes,
                  dragOptions.yaxes,
                  dragOptions.subplot,
                  dragOptions,
                  outlines
                );
              }
              if (clickmode === "event") {
                emitSelected(gd, void 0);
              }
            }
            Fx.click(gd, evt2, plotinfo.id);
          }).catch(Lib.error);
        };
        dragOptions.doneFn = function() {
          corners.remove();
          throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            if (!immediateSelect && currentPolygon && dragOptions.selectionDefs) {
              currentPolygon.subtract = subtract;
              dragOptions.selectionDefs.push(currentPolygon);
              dragOptions.mergedPolygons.length = 0;
              [].push.apply(dragOptions.mergedPolygons, mergedPolygons);
            }
            if (immediateSelect || isDrawMode) {
              clearSelectionsCache(dragOptions, immediateSelect);
            }
            if (dragOptions.doneFnCompleted) {
              dragOptions.doneFnCompleted(selection);
            }
            if (isSelectMode) {
              emitSelected(gd, eventData);
            }
          }).catch(Lib.error);
        };
      }
      function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) {
        var hoverData = gd._hoverdata;
        var fullLayout = gd._fullLayout;
        var clickmode = fullLayout.clickmode;
        var sendEvents = clickmode.indexOf("event") > -1;
        var selection = [];
        var searchTraces, searchInfo, currentSelectionDef, selectionTesters, traceSelection;
        var thisTracesSelection, pointOrBinSelected, subtract, eventData, i;
        if (isHoverDataSet(hoverData)) {
          coerceSelectionsCache(evt, gd, dragOptions);
          searchTraces = determineSearchTraces(gd, xAxes, yAxes, subplot);
          var clickedPtInfo = extractClickedPtInfo(hoverData, searchTraces);
          var isBinnedTrace = clickedPtInfo.pointNumbers.length > 0;
          if (isBinnedTrace ? isOnlyThisBinSelected(searchTraces, clickedPtInfo) : isOnlyOnePointSelected(searchTraces) && (pointOrBinSelected = isPointOrBinSelected(clickedPtInfo))) {
            if (polygonOutlines) polygonOutlines.remove();
            for (i = 0; i < searchTraces.length; i++) {
              searchInfo = searchTraces[i];
              searchInfo._module.selectPoints(searchInfo, false);
            }
            updateSelectedState(gd, searchTraces);
            clearSelectionsCache(dragOptions);
            if (sendEvents) {
              emitDeselect(gd);
            }
          } else {
            subtract = evt.shiftKey && (pointOrBinSelected !== void 0 ? pointOrBinSelected : isPointOrBinSelected(clickedPtInfo));
            currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract);
            var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]);
            selectionTesters = multiTester(allSelectionDefs, selectionTesters);
            for (i = 0; i < searchTraces.length; i++) {
              traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTesters);
              thisTracesSelection = fillSelectionItem(traceSelection, searchTraces[i]);
              if (selection.length) {
                for (var j = 0; j < thisTracesSelection.length; j++) {
                  selection.push(thisTracesSelection[j]);
                }
              } else selection = thisTracesSelection;
            }
            eventData = { points: selection };
            updateSelectedState(gd, searchTraces, eventData);
            if (currentSelectionDef && dragOptions) {
              dragOptions.selectionDefs.push(currentSelectionDef);
            }
            if (polygonOutlines) {
              var polygons = dragOptions.mergedPolygons;
              var isOpenMode = openMode(dragOptions.dragmode);
              displayOutlines(convertPoly(polygons, isOpenMode), polygonOutlines, dragOptions);
            }
            if (sendEvents) {
              emitSelected(gd, eventData);
            }
          }
        }
      }
      function newPointSelectionDef(pointNumber, searchInfo, subtract) {
        return {
          pointNumber,
          searchInfo,
          subtract: !!subtract
        };
      }
      function isPointSelectionDef(o) {
        return "pointNumber" in o && "searchInfo" in o;
      }
      function newPointNumTester(pointSelectionDef) {
        return {
          xmin: 0,
          xmax: 0,
          ymin: 0,
          ymax: 0,
          pts: [],
          contains: function(pt, omitFirstEdge, pointNumber, searchInfo) {
            var idxWantedTrace = pointSelectionDef.searchInfo.cd[0].trace.index;
            var idxActualTrace = searchInfo.cd[0].trace.index;
            return idxActualTrace === idxWantedTrace && pointNumber === pointSelectionDef.pointNumber;
          },
          isRect: false,
          degenerate: false,
          subtract: !!pointSelectionDef.subtract
        };
      }
      function multiTester(list) {
        if (!list.length) return;
        var testers = [];
        var xmin = isPointSelectionDef(list[0]) ? 0 : list[0][0][0];
        var xmax = xmin;
        var ymin = isPointSelectionDef(list[0]) ? 0 : list[0][0][1];
        var ymax = ymin;
        for (var i = 0; i < list.length; i++) {
          if (isPointSelectionDef(list[i])) {
            testers.push(newPointNumTester(list[i]));
          } else {
            var tester = polygonTester(list[i]);
            tester.subtract = !!list[i].subtract;
            testers.push(tester);
            xmin = Math.min(xmin, tester.xmin);
            xmax = Math.max(xmax, tester.xmax);
            ymin = Math.min(ymin, tester.ymin);
            ymax = Math.max(ymax, tester.ymax);
          }
        }
        function contains(pt, arg, pointNumber, searchInfo) {
          var contained = false;
          for (var i2 = 0; i2 < testers.length; i2++) {
            if (testers[i2].contains(pt, arg, pointNumber, searchInfo)) {
              contained = !testers[i2].subtract;
            }
          }
          return contained;
        }
        return {
          xmin,
          xmax,
          ymin,
          ymax,
          pts: [],
          contains,
          isRect: false,
          degenerate: false
        };
      }
      function coerceSelectionsCache(evt, gd, dragOptions) {
        var fullLayout = gd._fullLayout;
        var plotinfo = dragOptions.plotinfo;
        var dragmode = dragOptions.dragmode;
        var selectingOnSameSubplot = fullLayout._lastSelectedSubplot && fullLayout._lastSelectedSubplot === plotinfo.id;
        var hasModifierKey = (evt.shiftKey || evt.altKey) && !(drawMode(dragmode) && openMode(dragmode));
        if (selectingOnSameSubplot && hasModifierKey && plotinfo.selection && plotinfo.selection.selectionDefs && !dragOptions.selectionDefs) {
          dragOptions.selectionDefs = plotinfo.selection.selectionDefs;
          dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons;
        } else if (!hasModifierKey || !plotinfo.selection) {
          clearSelectionsCache(dragOptions);
        }
        if (!selectingOnSameSubplot) {
          clearOutline(gd);
          fullLayout._lastSelectedSubplot = plotinfo.id;
        }
      }
      function hasActiveShape(gd) {
        return gd._fullLayout._activeShapeIndex >= 0;
      }
      function hasActiveSelection(gd) {
        return gd._fullLayout._activeSelectionIndex >= 0;
      }
      function clearSelectionsCache(dragOptions, immediateSelect) {
        var dragmode = dragOptions.dragmode;
        var plotinfo = dragOptions.plotinfo;
        var gd = dragOptions.gd;
        if (hasActiveShape(gd)) {
          gd._fullLayout._deactivateShape(gd);
        }
        if (hasActiveSelection(gd)) {
          gd._fullLayout._deactivateSelection(gd);
        }
        var fullLayout = gd._fullLayout;
        var zoomLayer = fullLayout._zoomlayer;
        var isDrawMode = drawMode(dragmode);
        var isSelectMode = selectMode(dragmode);
        if (isDrawMode || isSelectMode) {
          var outlines = zoomLayer.selectAll(".select-outline-" + plotinfo.id);
          if (outlines && gd._fullLayout._outlining) {
            var shapes;
            if (isDrawMode) {
              shapes = newShapes(outlines, dragOptions);
            }
            if (shapes) {
              Registry.call("_guiRelayout", gd, {
                shapes
              });
            }
            var selections;
            if (isSelectMode && !hasSubplot(dragOptions)) {
              selections = newSelections(outlines, dragOptions);
            }
            if (selections) {
              gd._fullLayout._noEmitSelectedAtStart = true;
              Registry.call("_guiRelayout", gd, {
                selections
              }).then(function() {
                if (immediateSelect) {
                  activateLastSelection(gd);
                }
              });
            }
            gd._fullLayout._outlining = false;
          }
        }
        plotinfo.selection = {};
        plotinfo.selection.selectionDefs = dragOptions.selectionDefs = [];
        plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = [];
      }
      function getAxId(ax) {
        return ax._id;
      }
      function determineSearchTraces(gd, xAxes, yAxes, subplot) {
        if (!gd.calcdata) return [];
        var searchTraces = [];
        var xAxisIds = xAxes.map(getAxId);
        var yAxisIds = yAxes.map(getAxId);
        var cd, trace, i;
        for (i = 0; i < gd.calcdata.length; i++) {
          cd = gd.calcdata[i];
          trace = cd[0].trace;
          if (trace.visible !== true || !trace._module || !trace._module.selectPoints) continue;
          if (hasSubplot({ subplot }) && (trace.subplot === subplot || trace.geo === subplot)) {
            searchTraces.push(createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]));
          } else if (trace.type === "splom") {
            if (trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]) {
              var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
              info.scene = gd._fullLayout._splomScenes[trace.uid];
              searchTraces.push(info);
            }
          } else if (trace.type === "sankey") {
            var sankeyInfo = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
            searchTraces.push(sankeyInfo);
          } else {
            if (xAxisIds.indexOf(trace.xaxis) === -1 && (!trace._xA || !trace._xA.overlaying)) continue;
            if (yAxisIds.indexOf(trace.yaxis) === -1 && (!trace._yA || !trace._yA.overlaying)) continue;
            searchTraces.push(createSearchInfo(
              trace._module,
              cd,
              getFromId(gd, trace.xaxis),
              getFromId(gd, trace.yaxis)
            ));
          }
        }
        return searchTraces;
      }
      function createSearchInfo(module2, calcData, xaxis, yaxis) {
        return {
          _module: module2,
          cd: calcData,
          xaxis,
          yaxis
        };
      }
      function isHoverDataSet(hoverData) {
        return hoverData && Array.isArray(hoverData) && hoverData[0].hoverOnBox !== true;
      }
      function extractClickedPtInfo(hoverData, searchTraces) {
        var hoverDatum = hoverData[0];
        var pointNumber = -1;
        var pointNumbers = [];
        var searchInfo, i;
        for (i = 0; i < searchTraces.length; i++) {
          searchInfo = searchTraces[i];
          if (hoverDatum.fullData.index === searchInfo.cd[0].trace.index) {
            if (hoverDatum.hoverOnBox === true) {
              break;
            }
            if (hoverDatum.pointNumber !== void 0) {
              pointNumber = hoverDatum.pointNumber;
            } else if (hoverDatum.binNumber !== void 0) {
              pointNumber = hoverDatum.binNumber;
              pointNumbers = hoverDatum.pointNumbers;
            }
            break;
          }
        }
        return {
          pointNumber,
          pointNumbers,
          searchInfo
        };
      }
      function isPointOrBinSelected(clickedPtInfo) {
        var trace = clickedPtInfo.searchInfo.cd[0].trace;
        var ptNum = clickedPtInfo.pointNumber;
        var ptNums = clickedPtInfo.pointNumbers;
        var ptNumsSet = ptNums.length > 0;
        var ptNumToTest = ptNumsSet ? ptNums[0] : ptNum;
        return trace.selectedpoints ? trace.selectedpoints.indexOf(ptNumToTest) > -1 : false;
      }
      function isOnlyThisBinSelected(searchTraces, clickedPtInfo) {
        var tracesWithSelectedPts = [];
        var searchInfo, trace, isSameTrace, i;
        for (i = 0; i < searchTraces.length; i++) {
          searchInfo = searchTraces[i];
          if (searchInfo.cd[0].trace.selectedpoints && searchInfo.cd[0].trace.selectedpoints.length > 0) {
            tracesWithSelectedPts.push(searchInfo);
          }
        }
        if (tracesWithSelectedPts.length === 1) {
          isSameTrace = tracesWithSelectedPts[0] === clickedPtInfo.searchInfo;
          if (isSameTrace) {
            trace = clickedPtInfo.searchInfo.cd[0].trace;
            if (trace.selectedpoints.length === clickedPtInfo.pointNumbers.length) {
              for (i = 0; i < clickedPtInfo.pointNumbers.length; i++) {
                if (trace.selectedpoints.indexOf(clickedPtInfo.pointNumbers[i]) < 0) {
                  return false;
                }
              }
              return true;
            }
          }
        }
        return false;
      }
      function isOnlyOnePointSelected(searchTraces) {
        var len = 0;
        var searchInfo, trace, i;
        for (i = 0; i < searchTraces.length; i++) {
          searchInfo = searchTraces[i];
          trace = searchInfo.cd[0].trace;
          if (trace.selectedpoints) {
            if (trace.selectedpoints.length > 1) return false;
            len += trace.selectedpoints.length;
            if (len > 1) return false;
          }
        }
        return len === 1;
      }
      function updateSelectedState(gd, searchTraces, eventData) {
        var i;
        for (i = 0; i < searchTraces.length; i++) {
          var fullInputTrace = searchTraces[i].cd[0].trace._fullInput;
          var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid] || {};
          if (tracePreGUI.selectedpoints === void 0) {
            tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null;
          }
        }
        var trace;
        if (eventData) {
          var pts = eventData.points || [];
          for (i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            trace._input.selectedpoints = trace._fullInput.selectedpoints = [];
            if (trace._fullInput !== trace) trace.selectedpoints = [];
          }
          for (var k = 0; k < pts.length; k++) {
            var pt = pts[k];
            var data = pt.data;
            var fullData = pt.fullData;
            var pointIndex = pt.pointIndex;
            var pointIndices = pt.pointIndices;
            if (pointIndices) {
              [].push.apply(data.selectedpoints, pointIndices);
              if (trace._fullInput !== trace) {
                [].push.apply(fullData.selectedpoints, pointIndices);
              }
            } else {
              data.selectedpoints.push(pointIndex);
              if (trace._fullInput !== trace) {
                fullData.selectedpoints.push(pointIndex);
              }
            }
          }
        } else {
          for (i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            delete trace.selectedpoints;
            delete trace._input.selectedpoints;
            if (trace._fullInput !== trace) {
              delete trace._fullInput.selectedpoints;
            }
          }
        }
        updateReglSelectedState(gd, searchTraces);
      }
      function updateReglSelectedState(gd, searchTraces) {
        var hasRegl = false;
        for (var i = 0; i < searchTraces.length; i++) {
          var searchInfo = searchTraces[i];
          var cd = searchInfo.cd;
          if (Registry.traceIs(cd[0].trace, "regl")) {
            hasRegl = true;
          }
          var _module = searchInfo._module;
          var fn = _module.styleOnSelect || _module.style;
          if (fn) {
            fn(gd, cd, cd[0].node3);
            if (cd[0].nodeRangePlot3) fn(gd, cd, cd[0].nodeRangePlot3);
          }
        }
        if (hasRegl) {
          clearGlCanvases(gd);
          redrawReglTraces(gd);
        }
      }
      function mergePolygons(list, poly, subtract) {
        var fn = subtract ? polybool.difference : polybool.union;
        var res = fn({
          regions: list
        }, {
          regions: [poly]
        });
        var allPolygons = res.regions.reverse();
        for (var i = 0; i < allPolygons.length; i++) {
          var polygon = allPolygons[i];
          polygon.subtract = getSubtract(polygon, allPolygons.slice(0, i));
        }
        return allPolygons;
      }
      function fillSelectionItem(selection, searchInfo) {
        if (Array.isArray(selection)) {
          var cd = searchInfo.cd;
          var trace = searchInfo.cd[0].trace;
          for (var i = 0; i < selection.length; i++) {
            selection[i] = makeEventData(selection[i], trace, cd);
          }
        }
        return selection;
      }
      function convertPoly(polygonsIn, isOpenMode) {
        var polygonsOut = [];
        for (var i = 0; i < polygonsIn.length; i++) {
          polygonsOut[i] = [];
          for (var j = 0; j < polygonsIn[i].length; j++) {
            polygonsOut[i][j] = [];
            polygonsOut[i][j][0] = j ? "L" : "M";
            for (var k = 0; k < polygonsIn[i][j].length; k++) {
              polygonsOut[i][j].push(
                polygonsIn[i][j][k]
              );
            }
          }
          if (!isOpenMode) {
            polygonsOut[i].push([
              "Z",
              polygonsOut[i][0][1],
              // initial x
              polygonsOut[i][0][2]
              // initial y
            ]);
          }
        }
        return polygonsOut;
      }
      function _doSelect(selectionTesters, searchTraces) {
        var allSelections = [];
        var thisSelection;
        var traceSelections = [];
        var traceSelection;
        for (var i = 0; i < searchTraces.length; i++) {
          var searchInfo = searchTraces[i];
          traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTesters);
          traceSelections.push(traceSelection);
          thisSelection = fillSelectionItem(traceSelection, searchInfo);
          allSelections = allSelections.concat(thisSelection);
        }
        return allSelections;
      }
      function reselect(gd, mayEmitSelected, selectionTesters, searchTraces, dragOptions) {
        var hadSearchTraces = !!searchTraces;
        var plotinfo, xRef, yRef;
        if (dragOptions) {
          plotinfo = dragOptions.plotinfo;
          xRef = dragOptions.xaxes[0]._id;
          yRef = dragOptions.yaxes[0]._id;
        }
        var allSelections = [];
        var allSearchTraces = [];
        var layoutPolygons = getLayoutPolygons(gd);
        var fullLayout = gd._fullLayout;
        if (plotinfo) {
          var zoomLayer = fullLayout._zoomlayer;
          var mode = fullLayout.dragmode;
          var isDrawMode = drawMode(mode);
          var isSelectMode = selectMode(mode);
          if (isDrawMode || isSelectMode) {
            var xaxis = getFromId(gd, xRef, "x");
            var yaxis = getFromId(gd, yRef, "y");
            if (xaxis && yaxis) {
              var outlines = zoomLayer.selectAll(".select-outline-" + plotinfo.id);
              if (outlines && gd._fullLayout._outlining) {
                if (outlines.length) {
                  var e = outlines[0][0];
                  var d = e.getAttribute("d");
                  var outlinePolys = readPaths(d, gd, plotinfo);
                  var draftPolygons = [];
                  for (var u = 0; u < outlinePolys.length; u++) {
                    var p = outlinePolys[u];
                    var polygon = [];
                    for (var t = 0; t < p.length; t++) {
                      polygon.push([
                        convert(xaxis, p[t][1]),
                        convert(yaxis, p[t][2])
                      ]);
                    }
                    polygon.xref = xRef;
                    polygon.yref = yRef;
                    polygon.subtract = getSubtract(polygon, draftPolygons);
                    draftPolygons.push(polygon);
                  }
                  layoutPolygons = layoutPolygons.concat(draftPolygons);
                }
              }
            }
          }
        }
        var subplots = xRef && yRef ? [xRef + yRef] : fullLayout._subplots.cartesian;
        epmtySplomSelectionBatch(gd);
        var seenSplom = {};
        for (var i = 0; i < subplots.length; i++) {
          var subplot = subplots[i];
          var yAt = subplot.indexOf("y");
          var _xRef = subplot.slice(0, yAt);
          var _yRef = subplot.slice(yAt);
          var _selectionTesters = xRef && yRef ? selectionTesters : void 0;
          _selectionTesters = addTester(layoutPolygons, _xRef, _yRef, _selectionTesters);
          if (_selectionTesters) {
            var _searchTraces = searchTraces;
            if (!hadSearchTraces) {
              var _xA = getFromId(gd, _xRef, "x");
              var _yA = getFromId(gd, _yRef, "y");
              _searchTraces = determineSearchTraces(
                gd,
                [_xA],
                [_yA],
                subplot
              );
              for (var w = 0; w < _searchTraces.length; w++) {
                var s = _searchTraces[w];
                var cd0 = s.cd[0];
                var trace = cd0.trace;
                if (s._module.name === "scattergl" && !cd0.t.xpx) {
                  var x = trace.x;
                  var y = trace.y;
                  var len = trace._length;
                  cd0.t.xpx = [];
                  cd0.t.ypx = [];
                  for (var j = 0; j < len; j++) {
                    cd0.t.xpx[j] = _xA.c2p(x[j]);
                    cd0.t.ypx[j] = _yA.c2p(y[j]);
                  }
                }
                if (s._module.name === "splom") {
                  if (!seenSplom[trace.uid]) {
                    seenSplom[trace.uid] = true;
                  }
                }
              }
            }
            var selection = _doSelect(_selectionTesters, _searchTraces);
            allSelections = allSelections.concat(selection);
            allSearchTraces = allSearchTraces.concat(_searchTraces);
          }
        }
        var eventData = { points: allSelections };
        updateSelectedState(gd, allSearchTraces, eventData);
        var clickmode = fullLayout.clickmode;
        var sendEvents = clickmode.indexOf("event") > -1 && mayEmitSelected;
        if (!plotinfo && // get called from plot_api & plots
        mayEmitSelected) {
          var activePolygons = getLayoutPolygons(gd, true);
          if (activePolygons.length) {
            var xref = activePolygons[0].xref;
            var yref = activePolygons[0].yref;
            if (xref && yref) {
              var poly = castMultiPolygon(activePolygons);
              var fillRangeItems = makeFillRangeItems([
                getFromId(gd, xref, "x"),
                getFromId(gd, yref, "y")
              ]);
              fillRangeItems(eventData, poly);
            }
          }
          if (gd._fullLayout._noEmitSelectedAtStart) {
            gd._fullLayout._noEmitSelectedAtStart = false;
          } else {
            if (sendEvents) emitSelected(gd, eventData);
          }
          fullLayout._reselect = false;
        }
        if (!plotinfo && // get called from plot_api & plots
        fullLayout._deselect) {
          var deselect = fullLayout._deselect;
          xRef = deselect.xref;
          yRef = deselect.yref;
          if (!subplotSelected(xRef, yRef, allSearchTraces)) {
            deselectSubplot(gd, xRef, yRef, searchTraces);
          }
          if (sendEvents) {
            if (eventData.points.length) {
              emitSelected(gd, eventData);
            } else {
              emitDeselect(gd);
            }
          }
          fullLayout._deselect = false;
        }
        return {
          eventData,
          selectionTesters
        };
      }
      function epmtySplomSelectionBatch(gd) {
        var cd = gd.calcdata;
        if (!cd) return;
        for (var i = 0; i < cd.length; i++) {
          var cd0 = cd[i][0];
          var trace = cd0.trace;
          var splomScenes = gd._fullLayout._splomScenes;
          if (splomScenes) {
            var scene = splomScenes[trace.uid];
            if (scene) {
              scene.selectBatch = [];
            }
          }
        }
      }
      function subplotSelected(xRef, yRef, searchTraces) {
        for (var i = 0; i < searchTraces.length; i++) {
          var s = searchTraces[i];
          if (s.xaxis && s.xaxis._id === xRef && (s.yaxis && s.yaxis._id === yRef)) {
            return true;
          }
        }
        return false;
      }
      function deselectSubplot(gd, xRef, yRef, searchTraces) {
        searchTraces = determineSearchTraces(
          gd,
          [getFromId(gd, xRef, "x")],
          [getFromId(gd, yRef, "y")],
          xRef + yRef
        );
        for (var k = 0; k < searchTraces.length; k++) {
          var searchInfo = searchTraces[k];
          searchInfo._module.selectPoints(searchInfo, false);
        }
        updateSelectedState(gd, searchTraces);
      }
      function addTester(layoutPolygons, xRef, yRef, selectionTesters) {
        var mergedPolygons;
        for (var i = 0; i < layoutPolygons.length; i++) {
          var currentPolygon = layoutPolygons[i];
          if (xRef !== currentPolygon.xref || yRef !== currentPolygon.yref) continue;
          if (mergedPolygons) {
            var subtract = !!currentPolygon.subtract;
            mergedPolygons = mergePolygons(mergedPolygons, currentPolygon, subtract);
            selectionTesters = multiTester(mergedPolygons);
          } else {
            mergedPolygons = [currentPolygon];
            selectionTesters = polygonTester(currentPolygon);
          }
        }
        return selectionTesters;
      }
      function getLayoutPolygons(gd, onlyActiveOnes) {
        var allPolygons = [];
        var fullLayout = gd._fullLayout;
        var allSelections = fullLayout.selections;
        var len = allSelections.length;
        for (var i = 0; i < len; i++) {
          if (onlyActiveOnes && i !== fullLayout._activeSelectionIndex) continue;
          var selection = allSelections[i];
          if (!selection) continue;
          var xref = selection.xref;
          var yref = selection.yref;
          var xaxis = getFromId(gd, xref, "x");
          var yaxis = getFromId(gd, yref, "y");
          var xmin, xmax, ymin, ymax;
          var polygon;
          if (selection.type === "rect") {
            polygon = [];
            var x0 = convert(xaxis, selection.x0);
            var x1 = convert(xaxis, selection.x1);
            var y0 = convert(yaxis, selection.y0);
            var y1 = convert(yaxis, selection.y1);
            polygon = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
            xmin = Math.min(x0, x1);
            xmax = Math.max(x0, x1);
            ymin = Math.min(y0, y1);
            ymax = Math.max(y0, y1);
            polygon.xmin = xmin;
            polygon.xmax = xmax;
            polygon.ymin = ymin;
            polygon.ymax = ymax;
            polygon.xref = xref;
            polygon.yref = yref;
            polygon.subtract = false;
            polygon.isRect = true;
            allPolygons.push(polygon);
          } else if (selection.type === "path") {
            var segments = selection.path.split("Z");
            var multiPolygons = [];
            for (var j = 0; j < segments.length; j++) {
              var path = segments[j];
              if (!path) continue;
              path += "Z";
              var allX = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsX, "raw");
              var allY = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsY, "raw");
              xmin = Infinity;
              xmax = -Infinity;
              ymin = Infinity;
              ymax = -Infinity;
              polygon = [];
              for (var k = 0; k < allX.length; k++) {
                var x = convert(xaxis, allX[k]);
                var y = convert(yaxis, allY[k]);
                polygon.push([x, y]);
                xmin = Math.min(x, xmin);
                xmax = Math.max(x, xmax);
                ymin = Math.min(y, ymin);
                ymax = Math.max(y, ymax);
              }
              polygon.xmin = xmin;
              polygon.xmax = xmax;
              polygon.ymin = ymin;
              polygon.ymax = ymax;
              polygon.xref = xref;
              polygon.yref = yref;
              polygon.subtract = getSubtract(polygon, multiPolygons);
              multiPolygons.push(polygon);
              allPolygons.push(polygon);
            }
          }
        }
        return allPolygons;
      }
      function getSubtract(polygon, previousPolygons) {
        var subtract = false;
        for (var i = 0; i < previousPolygons.length; i++) {
          var previousPolygon = previousPolygons[i];
          for (var k = 0; k < polygon.length; k++) {
            if (pointInPolygon(polygon[k], previousPolygon)) {
              subtract = !subtract;
              break;
            }
          }
        }
        return subtract;
      }
      function convert(ax, d) {
        if (ax.type === "date") d = d.replace("_", " ");
        return ax.type === "log" ? ax.c2p(d) : ax.r2p(d, null, ax.calendar);
      }
      function castMultiPolygon(allPolygons) {
        var len = allPolygons.length;
        var p = [];
        for (var i = 0; i < len; i++) {
          var polygon = allPolygons[i];
          p = p.concat(polygon);
          p = p.concat([polygon[0]]);
        }
        return computeRectAndRanges(p);
      }
      function computeRectAndRanges(poly) {
        poly.isRect = poly.length === 5 && poly[0][0] === poly[4][0] && poly[0][1] === poly[4][1] && (poly[0][0] === poly[1][0] && poly[2][0] === poly[3][0] && poly[0][1] === poly[3][1] && poly[1][1] === poly[2][1]) || poly[0][1] === poly[1][1] && poly[2][1] === poly[3][1] && poly[0][0] === poly[3][0] && poly[1][0] === poly[2][0];
        if (poly.isRect) {
          poly.xmin = Math.min(poly[0][0], poly[2][0]);
          poly.xmax = Math.max(poly[0][0], poly[2][0]);
          poly.ymin = Math.min(poly[0][1], poly[2][1]);
          poly.ymax = Math.max(poly[0][1], poly[2][1]);
        }
        return poly;
      }
      function makeFillRangeItems(allAxes) {
        return function(eventData, poly) {
          var range;
          var lassoPoints;
          for (var i = 0; i < allAxes.length; i++) {
            var ax = allAxes[i];
            var id = ax._id;
            var axLetter = id.charAt(0);
            if (poly.isRect) {
              if (!range) range = {};
              var min = poly[axLetter + "min"];
              var max = poly[axLetter + "max"];
              if (min !== void 0 && max !== void 0) {
                range[id] = [
                  p2r(ax, min),
                  p2r(ax, max)
                ].sort(ascending);
              }
            } else {
              if (!lassoPoints) lassoPoints = {};
              lassoPoints[id] = poly.map(axValue(ax));
            }
          }
          if (range) {
            eventData.range = range;
          }
          if (lassoPoints) {
            eventData.lassoPoints = lassoPoints;
          }
        };
      }
      function getFillRangeItems(dragOptions) {
        var plotinfo = dragOptions.plotinfo;
        return plotinfo.fillRangeItems || // allow subplots (i.e. geo, mapbox, map, sankey) to override fillRangeItems routine
        makeFillRangeItems(dragOptions.xaxes.concat(dragOptions.yaxes));
      }
      function emitSelecting(gd, eventData) {
        gd.emit("plotly_selecting", eventData);
      }
      function emitSelected(gd, eventData) {
        if (eventData) {
          eventData.selections = (gd.layout || {}).selections || [];
        }
        gd.emit("plotly_selected", eventData);
      }
      function emitDeselect(gd) {
        gd.emit("plotly_deselect", null);
      }
      module.exports = {
        reselect,
        prepSelect,
        clearOutline,
        clearSelectionsCache,
        selectOnClick
      };
    }
  });

  // src/components/annotations/arrow_paths.js
  var require_arrow_paths = __commonJS({
    "src/components/annotations/arrow_paths.js"(exports, module) {
      "use strict";
      module.exports = [
        // no arrow
        {
          path: "",
          backoff: 0
        },
        // wide with flat back
        {
          path: "M-2.4,-3V3L0.6,0Z",
          backoff: 0.6
        },
        // narrower with flat back
        {
          path: "M-3.7,-2.5V2.5L1.3,0Z",
          backoff: 1.3
        },
        // barbed
        {
          path: "M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",
          backoff: 1.55
        },
        // wide line-drawn
        {
          path: "M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",
          backoff: 1.6
        },
        // narrower line-drawn
        {
          path: "M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",
          backoff: 2
        },
        // circle
        {
          path: "M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",
          backoff: 0,
          noRotate: true
        },
        // square
        {
          path: "M2,2V-2H-2V2Z",
          backoff: 0,
          noRotate: true
        }
      ];
    }
  });

  // src/constants/axis_placeable_objects.js
  var require_axis_placeable_objects = __commonJS({
    "src/constants/axis_placeable_objects.js"(exports, module) {
      "use strict";
      module.exports = {
        axisRefDescription: function(axisname, lower, upper) {
          return [
            "If set to a",
            axisname,
            "axis id (e.g. *" + axisname + "* or",
            "*" + axisname + "2*), the `" + axisname + "` position refers to a",
            axisname,
            "coordinate. If set to *paper*, the `" + axisname + "`",
            "position refers to the distance from the",
            lower,
            "of the plotting",
            "area in normalized coordinates where *0* (*1*) corresponds to the",
            lower,
            "(" + upper + "). If set to a",
            axisname,
            "axis ID followed by",
            "*domain* (separated by a space), the position behaves like for",
            "*paper*, but refers to the distance in fractions of the domain",
            "length from the",
            lower,
            "of the domain of that axis: e.g.,",
            "*" + axisname + "2 domain* refers to the domain of the second",
            axisname,
            " axis and a",
            axisname,
            "position of 0.5 refers to the",
            "point between the",
            lower,
            "and the",
            upper,
            "of the domain of the",
            "second",
            axisname,
            "axis."
          ].join(" ");
        }
      };
    }
  });

  // src/components/annotations/attributes.js
  var require_attributes11 = __commonJS({
    "src/components/annotations/attributes.js"(exports, module) {
      "use strict";
      var ARROWPATHS = require_arrow_paths();
      var fontAttrs = require_font_attributes();
      var cartesianConstants = require_constants2();
      var templatedArray = require_plot_template().templatedArray;
      var axisPlaceableObjs = require_axis_placeable_objects();
      module.exports = templatedArray("annotation", {
        visible: {
          valType: "boolean",
          dflt: true,
          editType: "calc+arraydraw"
        },
        text: {
          valType: "string",
          editType: "calc+arraydraw"
        },
        textangle: {
          valType: "angle",
          dflt: 0,
          editType: "calc+arraydraw"
        },
        font: fontAttrs({
          editType: "calc+arraydraw",
          colorEditType: "arraydraw"
        }),
        width: {
          valType: "number",
          min: 1,
          dflt: null,
          editType: "calc+arraydraw"
        },
        height: {
          valType: "number",
          min: 1,
          dflt: null,
          editType: "calc+arraydraw"
        },
        opacity: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 1,
          editType: "arraydraw"
        },
        align: {
          valType: "enumerated",
          values: ["left", "center", "right"],
          dflt: "center",
          editType: "arraydraw"
        },
        valign: {
          valType: "enumerated",
          values: ["top", "middle", "bottom"],
          dflt: "middle",
          editType: "arraydraw"
        },
        bgcolor: {
          valType: "color",
          dflt: "rgba(0,0,0,0)",
          editType: "arraydraw"
        },
        bordercolor: {
          valType: "color",
          dflt: "rgba(0,0,0,0)",
          editType: "arraydraw"
        },
        borderpad: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "calc+arraydraw"
        },
        borderwidth: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "calc+arraydraw"
        },
        // arrow
        showarrow: {
          valType: "boolean",
          dflt: true,
          editType: "calc+arraydraw"
        },
        arrowcolor: {
          valType: "color",
          editType: "arraydraw"
        },
        arrowhead: {
          valType: "integer",
          min: 0,
          max: ARROWPATHS.length,
          dflt: 1,
          editType: "arraydraw"
        },
        startarrowhead: {
          valType: "integer",
          min: 0,
          max: ARROWPATHS.length,
          dflt: 1,
          editType: "arraydraw"
        },
        arrowside: {
          valType: "flaglist",
          flags: ["end", "start"],
          extras: ["none"],
          dflt: "end",
          editType: "arraydraw"
        },
        arrowsize: {
          valType: "number",
          min: 0.3,
          dflt: 1,
          editType: "calc+arraydraw"
        },
        startarrowsize: {
          valType: "number",
          min: 0.3,
          dflt: 1,
          editType: "calc+arraydraw"
        },
        arrowwidth: {
          valType: "number",
          min: 0.1,
          editType: "calc+arraydraw"
        },
        standoff: {
          valType: "number",
          min: 0,
          dflt: 0,
          editType: "calc+arraydraw"
        },
        startstandoff: {
          valType: "number",
          min: 0,
          dflt: 0,
          editType: "calc+arraydraw"
        },
        ax: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        ay: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        axref: {
          valType: "enumerated",
          dflt: "pixel",
          values: [
            "pixel",
            cartesianConstants.idRegex.x.toString()
          ],
          editType: "calc"
        },
        ayref: {
          valType: "enumerated",
          dflt: "pixel",
          values: [
            "pixel",
            cartesianConstants.idRegex.y.toString()
          ],
          editType: "calc"
        },
        // positioning
        xref: {
          valType: "enumerated",
          values: [
            "paper",
            cartesianConstants.idRegex.x.toString()
          ],
          editType: "calc"
        },
        x: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        xanchor: {
          valType: "enumerated",
          values: ["auto", "left", "center", "right"],
          dflt: "auto",
          editType: "calc+arraydraw"
        },
        xshift: {
          valType: "number",
          dflt: 0,
          editType: "calc+arraydraw"
        },
        yref: {
          valType: "enumerated",
          values: [
            "paper",
            cartesianConstants.idRegex.y.toString()
          ],
          editType: "calc"
        },
        y: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        yanchor: {
          valType: "enumerated",
          values: ["auto", "top", "middle", "bottom"],
          dflt: "auto",
          editType: "calc+arraydraw"
        },
        yshift: {
          valType: "number",
          dflt: 0,
          editType: "calc+arraydraw"
        },
        clicktoshow: {
          valType: "enumerated",
          values: [false, "onoff", "onout"],
          dflt: false,
          editType: "arraydraw"
        },
        xclick: {
          valType: "any",
          editType: "arraydraw"
        },
        yclick: {
          valType: "any",
          editType: "arraydraw"
        },
        hovertext: {
          valType: "string",
          editType: "arraydraw"
        },
        hoverlabel: {
          bgcolor: {
            valType: "color",
            editType: "arraydraw"
          },
          bordercolor: {
            valType: "color",
            editType: "arraydraw"
          },
          font: fontAttrs({
            editType: "arraydraw"
          }),
          editType: "arraydraw"
        },
        captureevents: {
          valType: "boolean",
          editType: "arraydraw"
        },
        editType: "calc"
      });
    }
  });

  // src/traces/scatter/constants.js
  var require_constants8 = __commonJS({
    "src/traces/scatter/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        PTS_LINESONLY: 20,
        // fixed parameters of clustering and clipping algorithms
        // fraction of clustering tolerance "so close we don't even consider it a new point"
        minTolerance: 0.2,
        // how fast does clustering tolerance increase as you get away from the visible region
        toleranceGrowth: 10,
        // number of viewport sizes away from the visible region
        // at which we clip all lines to the perimeter
        maxScreensAway: 20,
        eventDataKeys: []
      };
    }
  });

  // src/traces/scatter/fillcolor_attribute.js
  var require_fillcolor_attribute = __commonJS({
    "src/traces/scatter/fillcolor_attribute.js"(exports, module) {
      "use strict";
      module.exports = function makeFillcolorAttr(hasFillgradient) {
        return {
          valType: "color",
          editType: "style",
          anim: true
        };
      };
    }
  });

  // src/traces/scatter/attributes.js
  var require_attributes12 = __commonJS({
    "src/traces/scatter/attributes.js"(exports, module) {
      "use strict";
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorScaleAttrs = require_attributes8();
      var fontAttrs = require_font_attributes();
      var dash = require_attributes4().dash;
      var pattern = require_attributes4().pattern;
      var Drawing = require_drawing();
      var constants = require_constants8();
      var extendFlat = require_extend().extendFlat;
      var makeFillcolorAttr = require_fillcolor_attribute();
      function axisPeriod(axis) {
        return {
          valType: "any",
          dflt: 0,
          editType: "calc"
        };
      }
      function axisPeriod0(axis) {
        return {
          valType: "any",
          editType: "calc"
        };
      }
      function axisPeriodAlignment(axis) {
        return {
          valType: "enumerated",
          values: ["start", "middle", "end"],
          dflt: "middle",
          editType: "calc"
        };
      }
      module.exports = {
        x: {
          valType: "data_array",
          editType: "calc+clearAxisTypes",
          anim: true
        },
        x0: {
          valType: "any",
          dflt: 0,
          editType: "calc+clearAxisTypes",
          anim: true
        },
        dx: {
          valType: "number",
          dflt: 1,
          editType: "calc",
          anim: true
        },
        y: {
          valType: "data_array",
          editType: "calc+clearAxisTypes",
          anim: true
        },
        y0: {
          valType: "any",
          dflt: 0,
          editType: "calc+clearAxisTypes",
          anim: true
        },
        dy: {
          valType: "number",
          dflt: 1,
          editType: "calc",
          anim: true
        },
        xperiod: axisPeriod("x"),
        yperiod: axisPeriod("y"),
        xperiod0: axisPeriod0("x0"),
        yperiod0: axisPeriod0("y0"),
        xperiodalignment: axisPeriodAlignment("x"),
        yperiodalignment: axisPeriodAlignment("y"),
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        offsetgroup: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        alignmentgroup: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        stackgroup: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        orientation: {
          valType: "enumerated",
          values: ["v", "h"],
          editType: "calc"
        },
        groupnorm: {
          valType: "enumerated",
          values: ["", "fraction", "percent"],
          dflt: "",
          editType: "calc"
        },
        stackgaps: {
          valType: "enumerated",
          values: ["infer zero", "interpolate"],
          dflt: "infer zero",
          editType: "calc"
        },
        text: {
          valType: "string",
          dflt: "",
          arrayOk: true,
          editType: "calc"
        },
        texttemplate: texttemplateAttrs(),
        texttemplatefallback: templatefallbackAttrs({ editType: "calc" }),
        hovertext: {
          valType: "string",
          dflt: "",
          arrayOk: true,
          editType: "style"
        },
        mode: {
          valType: "flaglist",
          flags: ["lines", "markers", "text"],
          extras: ["none"],
          editType: "calc"
        },
        hoveron: {
          valType: "flaglist",
          flags: ["points", "fills"],
          editType: "style"
        },
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        line: {
          color: {
            valType: "color",
            editType: "style",
            anim: true
          },
          width: {
            valType: "number",
            min: 0,
            dflt: 2,
            editType: "style",
            anim: true
          },
          shape: {
            valType: "enumerated",
            values: ["linear", "spline", "hv", "vh", "hvh", "vhv"],
            dflt: "linear",
            editType: "plot"
          },
          smoothing: {
            valType: "number",
            min: 0,
            max: 1.3,
            dflt: 1,
            editType: "plot"
          },
          dash: extendFlat({}, dash, { editType: "style" }),
          backoff: {
            // we want to have a similar option for the start of the line
            valType: "number",
            min: 0,
            dflt: "auto",
            arrayOk: true,
            editType: "plot"
          },
          simplify: {
            valType: "boolean",
            dflt: true,
            editType: "plot"
          },
          editType: "plot"
        },
        connectgaps: {
          valType: "boolean",
          dflt: false,
          editType: "calc"
        },
        cliponaxis: {
          valType: "boolean",
          dflt: true,
          editType: "plot"
        },
        fill: {
          valType: "enumerated",
          values: ["none", "tozeroy", "tozerox", "tonexty", "tonextx", "toself", "tonext"],
          editType: "calc"
        },
        fillcolor: makeFillcolorAttr(true),
        fillgradient: extendFlat({
          type: {
            valType: "enumerated",
            values: ["radial", "horizontal", "vertical", "none"],
            dflt: "none",
            editType: "calc"
          },
          start: {
            valType: "number",
            editType: "calc"
          },
          stop: {
            valType: "number",
            editType: "calc"
          },
          colorscale: {
            valType: "colorscale",
            editType: "style"
          },
          editType: "calc"
        }),
        fillpattern: pattern,
        marker: extendFlat(
          {
            symbol: {
              valType: "enumerated",
              values: Drawing.symbolList,
              dflt: "circle",
              arrayOk: true,
              editType: "style"
            },
            opacity: {
              valType: "number",
              min: 0,
              max: 1,
              arrayOk: true,
              editType: "style",
              anim: true
            },
            angle: {
              valType: "angle",
              dflt: 0,
              arrayOk: true,
              editType: "plot",
              anim: false
              // TODO: possibly set to true in future
            },
            angleref: {
              valType: "enumerated",
              values: ["previous", "up"],
              dflt: "up",
              editType: "plot",
              anim: false
            },
            standoff: {
              valType: "number",
              min: 0,
              dflt: 0,
              arrayOk: true,
              editType: "plot",
              anim: true
            },
            size: {
              valType: "number",
              min: 0,
              dflt: 6,
              arrayOk: true,
              editType: "calc",
              anim: true
            },
            maxdisplayed: {
              valType: "number",
              min: 0,
              dflt: 0,
              editType: "plot"
            },
            sizeref: {
              valType: "number",
              dflt: 1,
              editType: "calc"
            },
            sizemin: {
              valType: "number",
              min: 0,
              dflt: 0,
              editType: "calc"
            },
            sizemode: {
              valType: "enumerated",
              values: ["diameter", "area"],
              dflt: "diameter",
              editType: "calc"
            },
            line: extendFlat(
              {
                width: {
                  valType: "number",
                  min: 0,
                  arrayOk: true,
                  editType: "style",
                  anim: true
                },
                dash: extendFlat({}, dash, {
                  arrayOk: true
                }),
                editType: "calc"
              },
              colorScaleAttrs("marker.line", { anim: true })
            ),
            gradient: {
              type: {
                valType: "enumerated",
                values: ["radial", "horizontal", "vertical", "none"],
                arrayOk: true,
                dflt: "none",
                editType: "calc"
              },
              color: {
                valType: "color",
                arrayOk: true,
                editType: "calc"
              },
              editType: "calc"
            },
            editType: "calc"
          },
          colorScaleAttrs("marker", { anim: true })
        ),
        selected: {
          marker: {
            opacity: {
              valType: "number",
              min: 0,
              max: 1,
              editType: "style"
            },
            color: {
              valType: "color",
              editType: "style"
            },
            size: {
              valType: "number",
              min: 0,
              editType: "style"
            },
            editType: "style"
          },
          textfont: {
            color: {
              valType: "color",
              editType: "style"
            },
            editType: "style"
          },
          editType: "style"
        },
        unselected: {
          marker: {
            opacity: {
              valType: "number",
              min: 0,
              max: 1,
              editType: "style"
            },
            color: {
              valType: "color",
              editType: "style"
            },
            size: {
              valType: "number",
              min: 0,
              editType: "style"
            },
            editType: "style"
          },
          textfont: {
            color: {
              valType: "color",
              editType: "style"
            },
            editType: "style"
          },
          editType: "style"
        },
        textposition: {
          valType: "enumerated",
          values: [
            "top left",
            "top center",
            "top right",
            "middle left",
            "middle center",
            "middle right",
            "bottom left",
            "bottom center",
            "bottom right"
          ],
          dflt: "middle center",
          arrayOk: true,
          editType: "calc"
        },
        textfont: fontAttrs({
          editType: "calc",
          colorEditType: "style",
          arrayOk: true
        }),
        zorder: {
          valType: "integer",
          dflt: 0,
          editType: "plot"
        }
      };
    }
  });

  // src/components/selections/attributes.js
  var require_attributes13 = __commonJS({
    "src/components/selections/attributes.js"(exports, module) {
      "use strict";
      var annAttrs = require_attributes11();
      var scatterLineAttrs = require_attributes12().line;
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var templatedArray = require_plot_template().templatedArray;
      var axisPlaceableObjs = require_axis_placeable_objects();
      module.exports = overrideAll(templatedArray("selection", {
        type: {
          valType: "enumerated",
          values: ["rect", "path"]
        },
        xref: extendFlat({}, annAttrs.xref, {}),
        yref: extendFlat({}, annAttrs.yref, {}),
        x0: {
          valType: "any"
        },
        x1: {
          valType: "any"
        },
        y0: {
          valType: "any"
        },
        y1: {
          valType: "any"
        },
        path: {
          valType: "string",
          editType: "arraydraw"
        },
        opacity: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0.7,
          editType: "arraydraw"
        },
        line: {
          color: scatterLineAttrs.color,
          width: extendFlat({}, scatterLineAttrs.width, {
            min: 1,
            dflt: 1
          }),
          dash: extendFlat({}, dash, {
            dflt: "dot"
          })
        }
      }), "arraydraw", "from-root");
    }
  });

  // src/components/selections/defaults.js
  var require_defaults6 = __commonJS({
    "src/components/selections/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes13();
      var helpers = require_helpers8();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        handleArrayContainerDefaults(layoutIn, layoutOut, {
          name: "selections",
          handleItemDefaults: handleSelectionDefaults
        });
        var selections = layoutOut.selections;
        for (var i = 0; i < selections.length; i++) {
          var selection = selections[i];
          if (!selection) continue;
          if (selection.path === void 0) {
            if (selection.x0 === void 0 || selection.x1 === void 0 || selection.y0 === void 0 || selection.y1 === void 0) {
              layoutOut.selections[i] = null;
            }
          }
        }
      };
      function handleSelectionDefaults(selectionIn, selectionOut, fullLayout) {
        function coerce(attr, dflt) {
          return Lib.coerce(selectionIn, selectionOut, attributes, attr, dflt);
        }
        var path = coerce("path");
        var dfltType = path ? "path" : "rect";
        var selectionType = coerce("type", dfltType);
        var noPath = selectionType !== "path";
        if (noPath) delete selectionOut.path;
        coerce("opacity");
        coerce("line.color");
        coerce("line.width");
        coerce("line.dash");
        var axLetters = ["x", "y"];
        for (var i = 0; i < 2; i++) {
          var axLetter = axLetters[i];
          var gdMock = { _fullLayout: fullLayout };
          var ax;
          var pos2r;
          var r2pos;
          var axRef = Axes.coerceRef(selectionIn, selectionOut, gdMock, axLetter);
          ax = Axes.getFromId(gdMock, axRef);
          ax._selectionIndices.push(selectionOut._index);
          r2pos = helpers.rangeToShapePosition(ax);
          pos2r = helpers.shapePositionToRange(ax);
          if (noPath) {
            var attr0 = axLetter + "0";
            var attr1 = axLetter + "1";
            var in0 = selectionIn[attr0];
            var in1 = selectionIn[attr1];
            selectionIn[attr0] = pos2r(selectionIn[attr0], true);
            selectionIn[attr1] = pos2r(selectionIn[attr1], true);
            Axes.coercePosition(selectionOut, gdMock, coerce, axRef, attr0);
            Axes.coercePosition(selectionOut, gdMock, coerce, axRef, attr1);
            var p0 = selectionOut[attr0];
            var p1 = selectionOut[attr1];
            if (p0 !== void 0 && p1 !== void 0) {
              selectionOut[attr0] = r2pos(p0);
              selectionOut[attr1] = r2pos(p1);
              selectionIn[attr0] = in0;
              selectionIn[attr1] = in1;
            }
          }
        }
        if (noPath) {
          Lib.noneOrAll(selectionIn, selectionOut, ["x0", "x1", "y0", "y1"]);
        }
      }
    }
  });

  // src/components/selections/draw_newselection/defaults.js
  var require_defaults7 = __commonJS({
    "src/components/selections/draw_newselection/defaults.js"(exports, module) {
      "use strict";
      module.exports = function supplyDrawNewSelectionDefaults(layoutIn, layoutOut, coerce) {
        coerce("newselection.mode");
        var newselectionLineWidth = coerce("newselection.line.width");
        if (newselectionLineWidth) {
          coerce("newselection.line.color");
          coerce("newselection.line.dash");
        }
        coerce("activeselection.fillcolor");
        coerce("activeselection.opacity");
      };
    }
  });

  // src/plots/cartesian/include_components.js
  var require_include_components = __commonJS({
    "src/plots/cartesian/include_components.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var axisIds = require_axis_ids();
      module.exports = function makeIncludeComponents(containerArrayName) {
        return function includeComponents(layoutIn, layoutOut) {
          var array = layoutIn[containerArrayName];
          if (!Array.isArray(array)) return;
          var Cartesian = Registry.subplotsRegistry.cartesian;
          var idRegex = Cartesian.idRegex;
          var subplots = layoutOut._subplots;
          var xaList = subplots.xaxis;
          var yaList = subplots.yaxis;
          var cartesianList = subplots.cartesian;
          var hasCartesian = layoutOut._has("cartesian");
          for (var i = 0; i < array.length; i++) {
            var itemi = array[i];
            if (!Lib.isPlainObject(itemi)) continue;
            var xref = axisIds.cleanId(itemi.xref, "x", false);
            var yref = axisIds.cleanId(itemi.yref, "y", false);
            var hasXref = idRegex.x.test(xref);
            var hasYref = idRegex.y.test(yref);
            if (hasXref || hasYref) {
              if (!hasCartesian) Lib.pushUnique(layoutOut._basePlotModules, Cartesian);
              var newAxis = false;
              if (hasXref && xaList.indexOf(xref) === -1) {
                xaList.push(xref);
                newAxis = true;
              }
              if (hasYref && yaList.indexOf(yref) === -1) {
                yaList.push(yref);
                newAxis = true;
              }
              if (newAxis && hasXref && hasYref) {
                cartesianList.push(xref + yref);
              }
            }
          }
        };
      };
    }
  });

  // src/components/selections/index.js
  var require_selections = __commonJS({
    "src/components/selections/index.js"(exports, module) {
      "use strict";
      var drawModule = require_draw3();
      var select = require_select();
      module.exports = {
        moduleType: "component",
        name: "selections",
        layoutAttributes: require_attributes13(),
        supplyLayoutDefaults: require_defaults6(),
        supplyDrawNewSelectionDefaults: require_defaults7(),
        includeBasePlot: require_include_components()("selections"),
        draw: drawModule.draw,
        drawOne: drawModule.drawOne,
        reselect: select.reselect,
        prepSelect: select.prepSelect,
        clearOutline: select.clearOutline,
        clearSelectionsCache: select.clearSelectionsCache,
        selectOnClick: select.selectOnClick
      };
    }
  });

  // src/plots/cartesian/dragbox.js
  var require_dragbox = __commonJS({
    "src/plots/cartesian/dragbox.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var numberFormat = Lib.numberFormat;
      var tinycolor = require_tinycolor();
      var supportsPassive = require_has_passive_events();
      var Registry = require_registry();
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Fx = require_fx();
      var Axes = require_axes();
      var setCursor = require_setcursor();
      var dragElement = require_dragelement();
      var helpers = require_helpers5();
      var selectingOrDrawing = helpers.selectingOrDrawing;
      var freeMode = helpers.freeMode;
      var FROM_TL = require_alignment().FROM_TL;
      var clearGlCanvases = require_clear_gl_canvases();
      var redrawReglTraces = require_subroutines().redrawReglTraces;
      var Plots = require_plots();
      var getFromId = require_axis_ids().getFromId;
      var prepSelect = require_selections().prepSelect;
      var clearOutline = require_selections().clearOutline;
      var selectOnClick = require_selections().selectOnClick;
      var scaleZoom = require_scale_zoom();
      var constants = require_constants2();
      var MINDRAG = constants.MINDRAG;
      var MINZOOM = constants.MINZOOM;
      var SHOWZOOMOUTTIP = true;
      function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) {
        var zoomlayer = gd._fullLayout._zoomlayer;
        var isMainDrag = ns + ew === "nsew";
        var singleEnd = (ns + ew).length === 1;
        var xa0, ya0;
        var xaHash, yaHash;
        var xaxes, yaxes;
        var xs, ys;
        var pw, ph;
        var links;
        var matches;
        var xActive, yActive;
        var allFixedRanges;
        var editX, editY;
        var hasScatterGl, hasSplom, hasSVG;
        var updates;
        var scaleX;
        var scaleY;
        x += plotinfo.yaxis._shift;
        function recomputeAxisLists() {
          xa0 = plotinfo.xaxis;
          ya0 = plotinfo.yaxis;
          pw = xa0._length;
          ph = ya0._length;
          xs = xa0._offset;
          ys = ya0._offset;
          xaHash = {};
          xaHash[xa0._id] = xa0;
          yaHash = {};
          yaHash[ya0._id] = ya0;
          if (ns && ew) {
            var overlays = plotinfo.overlays;
            for (var i = 0; i < overlays.length; i++) {
              var xa = overlays[i].xaxis;
              xaHash[xa._id] = xa;
              var ya = overlays[i].yaxis;
              yaHash[ya._id] = ya;
            }
          }
          xaxes = hashValues(xaHash);
          yaxes = hashValues(yaHash);
          xActive = isDirectionActive(xaxes, ew);
          yActive = isDirectionActive(yaxes, ns);
          allFixedRanges = !yActive && !xActive;
          matches = calcLinks(gd, gd._fullLayout._axisMatchGroups, xaHash, yaHash);
          links = calcLinks(gd, gd._fullLayout._axisConstraintGroups, xaHash, yaHash, matches);
          var spConstrained = links.isSubplotConstrained || matches.isSubplotConstrained;
          editX = ew || spConstrained;
          editY = ns || spConstrained;
          var fullLayout = gd._fullLayout;
          hasScatterGl = fullLayout._has("scattergl");
          hasSplom = fullLayout._has("splom");
          hasSVG = fullLayout._has("svg");
        }
        recomputeAxisLists();
        var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag);
        var dragger = makeRectDragger(plotinfo, ns + ew + "drag", cursor, x, y, w, h);
        if (allFixedRanges && !isMainDrag) {
          dragger.onmousedown = null;
          dragger.style.pointerEvents = "none";
          return dragger;
        }
        var dragOptions = {
          element: dragger,
          gd,
          plotinfo
        };
        dragOptions.prepFn = function(e, startX, startY) {
          var dragModePrev = dragOptions.dragmode;
          var dragModeNow = gd._fullLayout.dragmode;
          if (dragModeNow !== dragModePrev) {
            dragOptions.dragmode = dragModeNow;
          }
          recomputeAxisLists();
          scaleX = gd._fullLayout._invScaleX;
          scaleY = gd._fullLayout._invScaleY;
          if (!allFixedRanges) {
            if (isMainDrag) {
              if (e.shiftKey) {
                if (dragModeNow === "pan") dragModeNow = "zoom";
                else if (!selectingOrDrawing(dragModeNow)) dragModeNow = "pan";
              } else if (e.ctrlKey) {
                dragModeNow = "pan";
              }
            } else {
              dragModeNow = "pan";
            }
          }
          if (freeMode(dragModeNow)) dragOptions.minDrag = 1;
          else dragOptions.minDrag = void 0;
          if (selectingOrDrawing(dragModeNow)) {
            dragOptions.xaxes = xaxes;
            dragOptions.yaxes = yaxes;
            prepSelect(e, startX, startY, dragOptions, dragModeNow);
          } else {
            dragOptions.clickFn = clickFn;
            if (selectingOrDrawing(dragModePrev)) {
              clearAndResetSelect();
            }
            if (!allFixedRanges) {
              if (dragModeNow === "zoom") {
                dragOptions.moveFn = zoomMove;
                dragOptions.doneFn = zoomDone;
                dragOptions.minDrag = 1;
                zoomPrep(e, startX, startY);
              } else if (dragModeNow === "pan") {
                dragOptions.moveFn = plotDrag;
                dragOptions.doneFn = dragTail;
              }
            }
          }
          gd._fullLayout._redrag = function() {
            var dragDataNow = gd._dragdata;
            if (dragDataNow && dragDataNow.element === dragger) {
              var dragModeNow2 = gd._fullLayout.dragmode;
              if (!selectingOrDrawing(dragModeNow2)) {
                recomputeAxisLists();
                updateSubplots([0, 0, pw, ph]);
                dragOptions.moveFn(dragDataNow.dx, dragDataNow.dy);
              }
            }
          };
        };
        function clearAndResetSelect() {
          dragOptions.plotinfo.selection = false;
          clearOutline(gd);
        }
        function clickFn(numClicks, evt) {
          var gd2 = dragOptions.gd;
          if (gd2._fullLayout._activeShapeIndex >= 0) {
            gd2._fullLayout._deactivateShape(gd2);
            return;
          }
          var clickmode = gd2._fullLayout.clickmode;
          removeZoombox(gd2);
          if (numClicks === 2 && !singleEnd) doubleClick();
          if (isMainDrag) {
            if (clickmode.indexOf("select") > -1) {
              selectOnClick(evt, gd2, xaxes, yaxes, plotinfo.id, dragOptions);
            }
            if (clickmode.indexOf("event") > -1) {
              Fx.click(gd2, evt, plotinfo.id);
            }
          } else if (numClicks === 1 && singleEnd) {
            var ax = ns ? ya0 : xa0;
            var end = ns === "s" || ew === "w" ? 0 : 1;
            var attrStr = ax._name + ".range[" + end + "]";
            var initialText = getEndText(ax, end);
            var hAlign = "left";
            var vAlign = "middle";
            if (ax.fixedrange) return;
            if (ns) {
              vAlign = ns === "n" ? "top" : "bottom";
              if (ax.side === "right") hAlign = "right";
            } else if (ew === "e") hAlign = "right";
            if (gd2._context.showAxisRangeEntryBoxes) {
              d3.select(dragger).call(svgTextUtils.makeEditable, {
                gd: gd2,
                immediate: true,
                background: gd2._fullLayout.paper_bgcolor,
                text: String(initialText),
                fill: ax.tickfont ? ax.tickfont.color : "#444",
                horizontalAlign: hAlign,
                verticalAlign: vAlign
              }).on("edit", function(text) {
                var v = ax.d2r(text);
                if (v !== void 0) {
                  Registry.call("_guiRelayout", gd2, attrStr, v);
                }
              });
            }
          }
        }
        dragElement.init(dragOptions);
        var x0, y0;
        var box;
        var lum;
        var path0;
        var dimmed;
        var zoomMode;
        var zb;
        var corners;
        var zoomDragged;
        function zoomPrep(e, startX, startY) {
          var dragBBox = dragger.getBoundingClientRect();
          x0 = startX - dragBBox.left;
          y0 = startY - dragBBox.top;
          gd._fullLayout._calcInverseTransform(gd);
          var transformedCoords = Lib.apply3DTransform(gd._fullLayout._invTransform)(x0, y0);
          x0 = transformedCoords[0];
          y0 = transformedCoords[1];
          box = { l: x0, r: x0, w: 0, t: y0, b: y0, h: 0 };
          lum = gd._hmpixcount ? gd._hmlumcount / gd._hmpixcount : tinycolor(gd._fullLayout.plot_bgcolor).getLuminance();
          path0 = "M0,0H" + pw + "V" + ph + "H0V0";
          dimmed = false;
          zoomMode = "xy";
          zoomDragged = false;
          zb = makeZoombox(zoomlayer, lum, xs, ys, path0);
          corners = makeCorners(zoomlayer, xs, ys);
        }
        function zoomMove(dx0, dy0) {
          if (gd._transitioningWithDuration) {
            return false;
          }
          var x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0));
          var y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0));
          var dx = Math.abs(x1 - x0);
          var dy = Math.abs(y1 - y0);
          box.l = Math.min(x0, x1);
          box.r = Math.max(x0, x1);
          box.t = Math.min(y0, y1);
          box.b = Math.max(y0, y1);
          function noZoom() {
            zoomMode = "";
            box.r = box.l;
            box.t = box.b;
            corners.attr("d", "M0,0Z");
          }
          if (links.isSubplotConstrained) {
            if (dx > MINZOOM || dy > MINZOOM) {
              zoomMode = "xy";
              if (dx / pw > dy / ph) {
                dy = dx * ph / pw;
                if (y0 > y1) box.t = y0 - dy;
                else box.b = y0 + dy;
              } else {
                dx = dy * pw / ph;
                if (x0 > x1) box.l = x0 - dx;
                else box.r = x0 + dx;
              }
              corners.attr("d", xyCorners(box));
            } else {
              noZoom();
            }
          } else if (matches.isSubplotConstrained) {
            if (dx > MINZOOM || dy > MINZOOM) {
              zoomMode = "xy";
              var r0 = Math.min(box.l / pw, (ph - box.b) / ph);
              var r1 = Math.max(box.r / pw, (ph - box.t) / ph);
              box.l = r0 * pw;
              box.r = r1 * pw;
              box.b = (1 - r0) * ph;
              box.t = (1 - r1) * ph;
              corners.attr("d", xyCorners(box));
            } else {
              noZoom();
            }
          } else if (!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) {
            if (dx < MINDRAG || !xActive) {
              noZoom();
            } else {
              box.t = 0;
              box.b = ph;
              zoomMode = "x";
              corners.attr("d", xCorners(box, y0));
            }
          } else if (!xActive || dx < Math.min(dy * 0.6, MINZOOM)) {
            box.l = 0;
            box.r = pw;
            zoomMode = "y";
            corners.attr("d", yCorners(box, x0));
          } else {
            zoomMode = "xy";
            corners.attr("d", xyCorners(box));
          }
          box.w = box.r - box.l;
          box.h = box.b - box.t;
          if (zoomMode) zoomDragged = true;
          gd._dragged = zoomDragged;
          updateZoombox(zb, corners, box, path0, dimmed, lum);
          computeZoomUpdates();
          gd.emit("plotly_relayouting", updates);
          dimmed = true;
        }
        function computeZoomUpdates() {
          updates = {};
          if (zoomMode === "xy" || zoomMode === "x") {
            zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes);
            updateMatchedAxRange("x", updates);
          }
          if (zoomMode === "xy" || zoomMode === "y") {
            zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes);
            updateMatchedAxRange("y", updates);
          }
        }
        function zoomDone() {
          computeZoomUpdates();
          removeZoombox(gd);
          dragTail();
          showDoubleClickNotifier(gd);
        }
        var scrollViewBox = [0, 0, pw, ph];
        var redrawTimer = null;
        var REDRAWDELAY = constants.REDRAWDELAY;
        var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo;
        function zoomWheel(e) {
          if (!gd._context._scrollZoom.cartesian && !gd._fullLayout._enablescrollzoom) {
            return;
          }
          clearAndResetSelect();
          if (gd._transitioningWithDuration) {
            e.preventDefault();
            e.stopPropagation();
            return;
          }
          recomputeAxisLists();
          clearTimeout(redrawTimer);
          var wheelDelta = -e.deltaY;
          if (!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10;
          if (!isFinite(wheelDelta)) {
            Lib.log("Did not find wheel motion attributes: ", e);
            return;
          }
          var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200);
          var gbb = mainplot.draglayer.select(".nsewdrag").node().getBoundingClientRect();
          var xfrac = (e.clientX - gbb.left) / gbb.width;
          var yfrac = (gbb.bottom - e.clientY) / gbb.height;
          var i;
          function zoomWheelOneAxis(ax, centerFraction, zoom2) {
            if (ax.fixedrange) return;
            var axRange = Lib.simpleMap(ax.range, ax.r2l);
            var v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction;
            function doZoom(v) {
              return ax.l2r(v0 + (v - v0) * zoom2);
            }
            ax.range = axRange.map(doZoom);
          }
          if (editX) {
            if (!ew) xfrac = 0.5;
            for (i = 0; i < xaxes.length; i++) {
              zoomWheelOneAxis(xaxes[i], xfrac, zoom);
            }
            updateMatchedAxRange("x");
            scrollViewBox[2] *= zoom;
            scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1);
          }
          if (editY) {
            if (!ns) yfrac = 0.5;
            for (i = 0; i < yaxes.length; i++) {
              zoomWheelOneAxis(yaxes[i], yfrac, zoom);
            }
            updateMatchedAxRange("y");
            scrollViewBox[3] *= zoom;
            scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1);
          }
          updateSubplots(scrollViewBox);
          ticksAndAnnotations();
          gd.emit("plotly_relayouting", updates);
          redrawTimer = setTimeout(function() {
            if (!gd._fullLayout) return;
            scrollViewBox = [0, 0, pw, ph];
            dragTail();
          }, REDRAWDELAY);
          e.preventDefault();
          return;
        }
        if (ns.length * ew.length !== 1) {
          attachWheelEventHandler(dragger, zoomWheel);
        }
        function plotDrag(dx, dy) {
          dx = dx * scaleX;
          dy = dy * scaleY;
          if (gd._transitioningWithDuration) {
            return;
          }
          gd._fullLayout._replotting = true;
          if (xActive === "ew" || yActive === "ns") {
            var spDx = xActive ? -dx : 0;
            var spDy = yActive ? -dy : 0;
            if (matches.isSubplotConstrained) {
              if (xActive && yActive) {
                var frac = (dx / pw - dy / ph) / 2;
                dx = frac * pw;
                dy = -frac * ph;
                spDx = -dx;
                spDy = -dy;
              }
              if (yActive) {
                spDx = -spDy * pw / ph;
              } else {
                spDy = -spDx * ph / pw;
              }
            }
            if (xActive) {
              dragAxList(xaxes, dx);
              updateMatchedAxRange("x");
            }
            if (yActive) {
              dragAxList(yaxes, dy);
              updateMatchedAxRange("y");
            }
            updateSubplots([spDx, spDy, pw, ph]);
            ticksAndAnnotations();
            gd.emit("plotly_relayouting", updates);
            return;
          }
          function dz(axArray, end, d) {
            var otherEnd = 1 - end;
            var movedAx;
            var newLinearizedEnd;
            for (var i2 = 0; i2 < axArray.length; i2++) {
              var axi = axArray[i2];
              if (axi.fixedrange) continue;
              movedAx = axi;
              newLinearizedEnd = axi._rl[otherEnd] + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length);
              var newEnd = axi.l2r(newLinearizedEnd);
              if (newEnd !== false && newEnd !== void 0) axi.range[end] = newEnd;
            }
            return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / (movedAx._rl[end] - movedAx._rl[otherEnd]);
          }
          var dxySign = xActive === "w" === (yActive === "n") ? 1 : -1;
          if (xActive && yActive && (links.isSubplotConstrained || matches.isSubplotConstrained)) {
            var dxyFraction = (dx / pw + dxySign * dy / ph) / 2;
            dx = dxyFraction * pw;
            dy = dxySign * dxyFraction * ph;
          }
          var xStart, yStart;
          if (xActive === "w") dx = dz(xaxes, 0, dx);
          else if (xActive === "e") dx = dz(xaxes, 1, -dx);
          else if (!xActive) dx = 0;
          if (yActive === "n") dy = dz(yaxes, 1, dy);
          else if (yActive === "s") dy = dz(yaxes, 0, -dy);
          else if (!yActive) dy = 0;
          xStart = xActive === "w" ? dx : 0;
          yStart = yActive === "n" ? dy : 0;
          if (links.isSubplotConstrained && !matches.isSubplotConstrained || // NW or SE on matching axes - create a symmetric zoom
          matches.isSubplotConstrained && xActive && yActive && dxySign > 0) {
            var i;
            if (matches.isSubplotConstrained || !xActive && yActive.length === 1) {
              for (i = 0; i < xaxes.length; i++) {
                xaxes[i].range = xaxes[i]._r.slice();
                scaleZoom(xaxes[i], 1 - dy / ph);
              }
              dx = dy * pw / ph;
              xStart = dx / 2;
            }
            if (matches.isSubplotConstrained || !yActive && xActive.length === 1) {
              for (i = 0; i < yaxes.length; i++) {
                yaxes[i].range = yaxes[i]._r.slice();
                scaleZoom(yaxes[i], 1 - dx / pw);
              }
              dy = dx * ph / pw;
              yStart = dy / 2;
            }
          }
          if (!matches.isSubplotConstrained || !yActive) {
            updateMatchedAxRange("x");
          }
          if (!matches.isSubplotConstrained || !xActive) {
            updateMatchedAxRange("y");
          }
          var xSize = pw - dx;
          var ySize = ph - dy;
          if (matches.isSubplotConstrained && !(xActive && yActive)) {
            if (xActive) {
              yStart = xStart ? 0 : dx * ph / pw;
              ySize = xSize * ph / pw;
            } else {
              xStart = yStart ? 0 : dy * pw / ph;
              xSize = ySize * pw / ph;
            }
          }
          updateSubplots([xStart, yStart, xSize, ySize]);
          ticksAndAnnotations();
          gd.emit("plotly_relayouting", updates);
        }
        function updateMatchedAxRange(axLetter, out) {
          var matchedAxes = matches.isSubplotConstrained ? { x: yaxes, y: xaxes }[axLetter] : matches[axLetter + "axes"];
          var constrainedAxes = matches.isSubplotConstrained ? { x: xaxes, y: yaxes }[axLetter] : [];
          for (var i = 0; i < matchedAxes.length; i++) {
            var ax = matchedAxes[i];
            var axId = ax._id;
            var axId2 = matches.xLinks[axId] || matches.yLinks[axId];
            var ax2 = constrainedAxes[0] || xaHash[axId2] || yaHash[axId2];
            if (ax2) {
              if (out) {
                out[ax._name + ".range[0]"] = out[ax2._name + ".range[0]"];
                out[ax._name + ".range[1]"] = out[ax2._name + ".range[1]"];
              } else {
                ax.range = ax2.range.slice();
              }
            }
          }
        }
        function ticksAndAnnotations() {
          var activeAxIds = [];
          var i;
          function pushActiveAxIds(axList) {
            for (i = 0; i < axList.length; i++) {
              if (!axList[i].fixedrange) activeAxIds.push(axList[i]._id);
            }
          }
          function pushActiveAxIdsSynced(axList, axisType) {
            for (i = 0; i < axList.length; i++) {
              var axListI = axList[i];
              var axListIType = axListI[axisType];
              if (!axListI.fixedrange && axListIType.tickmode === "sync") activeAxIds.push(axListIType._id);
            }
          }
          if (editX) {
            pushActiveAxIds(xaxes);
            pushActiveAxIds(links.xaxes);
            pushActiveAxIds(matches.xaxes);
            pushActiveAxIdsSynced(plotinfo.overlays, "xaxis");
          }
          if (editY) {
            pushActiveAxIds(yaxes);
            pushActiveAxIds(links.yaxes);
            pushActiveAxIds(matches.yaxes);
            pushActiveAxIdsSynced(plotinfo.overlays, "yaxis");
          }
          updates = {};
          for (i = 0; i < activeAxIds.length; i++) {
            var axId = activeAxIds[i];
            var ax = getFromId(gd, axId);
            Axes.drawOne(gd, ax, { skipTitle: true });
            updates[ax._name + ".range[0]"] = ax.range[0];
            updates[ax._name + ".range[1]"] = ax.range[1];
          }
          Axes.redrawComponents(gd, activeAxIds);
        }
        function doubleClick() {
          if (gd._transitioningWithDuration) return;
          var doubleClickConfig = gd._context.doubleClick;
          var axList = [];
          if (xActive) axList = axList.concat(xaxes);
          if (yActive) axList = axList.concat(yaxes);
          if (matches.xaxes) axList = axList.concat(matches.xaxes);
          if (matches.yaxes) axList = axList.concat(matches.yaxes);
          var attrs = {};
          var ax, i;
          if (doubleClickConfig === "reset+autosize") {
            doubleClickConfig = "autosize";
            for (i = 0; i < axList.length; i++) {
              ax = axList[i];
              var r0 = ax._rangeInitial0;
              var r1 = ax._rangeInitial1;
              var hasRangeInitial = r0 !== void 0 || r1 !== void 0;
              if (hasRangeInitial && (r0 !== void 0 && r0 !== ax.range[0] || r1 !== void 0 && r1 !== ax.range[1]) || !hasRangeInitial && ax.autorange !== true) {
                doubleClickConfig = "reset";
                break;
              }
            }
          }
          if (doubleClickConfig === "autosize") {
            for (i = 0; i < axList.length; i++) {
              ax = axList[i];
              if (!ax.fixedrange) attrs[ax._name + ".autorange"] = true;
            }
          } else if (doubleClickConfig === "reset") {
            if (xActive || links.isSubplotConstrained) axList = axList.concat(links.xaxes);
            if (yActive && !links.isSubplotConstrained) axList = axList.concat(links.yaxes);
            if (links.isSubplotConstrained) {
              if (!xActive) axList = axList.concat(xaxes);
              else if (!yActive) axList = axList.concat(yaxes);
            }
            for (i = 0; i < axList.length; i++) {
              ax = axList[i];
              if (!ax.fixedrange) {
                var axName = ax._name;
                var autorangeInitial = ax._autorangeInitial;
                if (ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0) {
                  attrs[axName + ".autorange"] = true;
                } else if (ax._rangeInitial0 === void 0) {
                  attrs[axName + ".autorange"] = autorangeInitial;
                  attrs[axName + ".range"] = [null, ax._rangeInitial1];
                } else if (ax._rangeInitial1 === void 0) {
                  attrs[axName + ".range"] = [ax._rangeInitial0, null];
                  attrs[axName + ".autorange"] = autorangeInitial;
                } else {
                  attrs[axName + ".range"] = [ax._rangeInitial0, ax._rangeInitial1];
                }
              }
            }
          }
          gd.emit("plotly_doubleclick", null);
          Registry.call("_guiRelayout", gd, attrs);
        }
        function dragTail() {
          updateSubplots([0, 0, pw, ph]);
          Lib.syncOrAsync([
            Plots.previousPromises,
            function() {
              gd._fullLayout._replotting = false;
              Registry.call("_guiRelayout", gd, updates);
            }
          ], gd);
        }
        function updateSubplots(viewBox) {
          var fullLayout = gd._fullLayout;
          var plotinfos = fullLayout._plots;
          var subplots = fullLayout._subplots.cartesian;
          var i, sp, xa, ya;
          if (hasSplom) {
            Registry.subplotsRegistry.splom.drag(gd);
          }
          if (hasScatterGl) {
            for (i = 0; i < subplots.length; i++) {
              sp = plotinfos[subplots[i]];
              xa = sp.xaxis;
              ya = sp.yaxis;
              if (sp._scene) {
                if (xa.limitRange) xa.limitRange();
                if (ya.limitRange) ya.limitRange();
                var xrng = Lib.simpleMap(xa.range, xa.r2l);
                var yrng = Lib.simpleMap(ya.range, ya.r2l);
                sp._scene.update({ range: [xrng[0], yrng[0], xrng[1], yrng[1]] });
              }
            }
          }
          if (hasSplom || hasScatterGl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
          }
          if (hasSVG) {
            var xScaleFactor = viewBox[2] / xa0._length;
            var yScaleFactor = viewBox[3] / ya0._length;
            for (i = 0; i < subplots.length; i++) {
              sp = plotinfos[subplots[i]];
              xa = sp.xaxis;
              ya = sp.yaxis;
              var editX2 = (editX || matches.isSubplotConstrained) && !xa.fixedrange && xaHash[xa._id];
              var editY2 = (editY || matches.isSubplotConstrained) && !ya.fixedrange && yaHash[ya._id];
              var xScaleFactor2, yScaleFactor2;
              var clipDx, clipDy;
              if (editX2) {
                xScaleFactor2 = xScaleFactor;
                clipDx = ew || matches.isSubplotConstrained ? viewBox[0] : getShift(xa, xScaleFactor2);
              } else if (matches.xaHash[xa._id]) {
                xScaleFactor2 = xScaleFactor;
                clipDx = viewBox[0] * xa._length / xa0._length;
              } else if (matches.yaHash[xa._id]) {
                xScaleFactor2 = yScaleFactor;
                clipDx = yActive === "ns" ? -viewBox[1] * xa._length / ya0._length : getShift(xa, xScaleFactor2, { n: "top", s: "bottom" }[yActive]);
              } else {
                xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor);
                clipDx = scaleAndGetShift(xa, xScaleFactor2);
              }
              if (xScaleFactor2 > 1 && (xa.maxallowed !== void 0 && editX === (xa.range[0] < xa.range[1] ? "e" : "w") || xa.minallowed !== void 0 && editX === (xa.range[0] < xa.range[1] ? "w" : "e"))) {
                xScaleFactor2 = 1;
                clipDx = 0;
              }
              if (editY2) {
                yScaleFactor2 = yScaleFactor;
                clipDy = ns || matches.isSubplotConstrained ? viewBox[1] : getShift(ya, yScaleFactor2);
              } else if (matches.yaHash[ya._id]) {
                yScaleFactor2 = yScaleFactor;
                clipDy = viewBox[1] * ya._length / ya0._length;
              } else if (matches.xaHash[ya._id]) {
                yScaleFactor2 = xScaleFactor;
                clipDy = xActive === "ew" ? -viewBox[0] * ya._length / xa0._length : getShift(ya, yScaleFactor2, { e: "right", w: "left" }[xActive]);
              } else {
                yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor);
                clipDy = scaleAndGetShift(ya, yScaleFactor2);
              }
              if (yScaleFactor2 > 1 && (ya.maxallowed !== void 0 && editY === (ya.range[0] < ya.range[1] ? "n" : "s") || ya.minallowed !== void 0 && editY === (ya.range[0] < ya.range[1] ? "s" : "n"))) {
                yScaleFactor2 = 1;
                clipDy = 0;
              }
              if (!xScaleFactor2 && !yScaleFactor2) {
                continue;
              }
              if (!xScaleFactor2) xScaleFactor2 = 1;
              if (!yScaleFactor2) yScaleFactor2 = 1;
              var plotDx = xa._offset - clipDx / xScaleFactor2;
              var plotDy = ya._offset - clipDy / yScaleFactor2;
              sp.clipRect.call(Drawing.setTranslate, clipDx, clipDy).call(Drawing.setScale, xScaleFactor2, yScaleFactor2);
              sp.plot.call(Drawing.setTranslate, plotDx, plotDy).call(Drawing.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2);
              if (xScaleFactor2 !== sp.xScaleFactor || yScaleFactor2 !== sp.yScaleFactor) {
                Drawing.setPointGroupScale(sp.zoomScalePts, xScaleFactor2, yScaleFactor2);
                Drawing.setTextPointsScale(sp.zoomScaleTxt, xScaleFactor2, yScaleFactor2);
              }
              Drawing.hideOutsideRangePoints(sp.clipOnAxisFalseTraces, sp);
              sp.xScaleFactor = xScaleFactor2;
              sp.yScaleFactor = yScaleFactor2;
            }
          }
        }
        function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) {
          if (ax.fixedrange) return 0;
          if (editX && links.xaHash[ax._id]) {
            return xScaleFactor;
          }
          if (editY && (links.isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) {
            return yScaleFactor;
          }
          return 0;
        }
        function scaleAndGetShift(ax, scaleFactor) {
          if (scaleFactor) {
            ax.range = ax._r.slice();
            scaleZoom(ax, scaleFactor);
            return getShift(ax, scaleFactor);
          }
          return 0;
        }
        function getShift(ax, scaleFactor, from) {
          return ax._length * (1 - scaleFactor) * FROM_TL[from || ax.constraintoward || "middle"];
        }
        return dragger;
      }
      function makeDragger(plotinfo, nodeName, dragClass, cursor) {
        var dragger3 = Lib.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) {
          s.classed("drag", true).style({ fill: "transparent", "stroke-width": 0 }).attr("data-subplot", plotinfo.id);
        });
        dragger3.call(setCursor, cursor);
        return dragger3.node();
      }
      function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) {
        var dragger = makeDragger(plotinfo, "rect", dragClass, cursor);
        d3.select(dragger).call(Drawing.setRect, x, y, w, h);
        return dragger;
      }
      function isDirectionActive(axList, activeVal) {
        for (var i = 0; i < axList.length; i++) {
          if (!axList[i].fixedrange) return activeVal;
        }
        return "";
      }
      function getEndText(ax, end) {
        var initialVal = ax.range[end];
        var diff = Math.abs(initialVal - ax.range[1 - end]);
        var dig;
        if (ax.type === "date") {
          return initialVal;
        } else if (ax.type === "log") {
          dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
          return numberFormat("." + dig + "g")(Math.pow(10, initialVal));
        } else {
          dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - Math.floor(Math.log(diff) / Math.LN10) + 4;
          return numberFormat("." + String(dig) + "g")(initialVal);
        }
      }
      function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) {
        for (var i = 0; i < axList.length; i++) {
          var axi = axList[i];
          if (axi.fixedrange) continue;
          if (axi.rangebreaks) {
            var isY = axi._id.charAt(0) === "y";
            var r0F = isY ? 1 - r0Fraction : r0Fraction;
            var r1F = isY ? 1 - r1Fraction : r1Fraction;
            updates[axi._name + ".range[0]"] = axi.l2r(axi.p2l(r0F * axi._length));
            updates[axi._name + ".range[1]"] = axi.l2r(axi.p2l(r1F * axi._length));
          } else {
            var axRangeLinear0 = axi._rl[0];
            var axRangeLinearSpan = axi._rl[1] - axRangeLinear0;
            updates[axi._name + ".range[0]"] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction);
            updates[axi._name + ".range[1]"] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction);
          }
        }
        if (linkedAxes && linkedAxes.length) {
          var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2;
          zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates, []);
        }
      }
      function dragAxList(axList, pix) {
        for (var i = 0; i < axList.length; i++) {
          var axi = axList[i];
          if (!axi.fixedrange) {
            if (axi.rangebreaks) {
              var p0 = 0;
              var p1 = axi._length;
              var d0 = axi.p2l(p0 + pix) - axi.p2l(p0);
              var d1 = axi.p2l(p1 + pix) - axi.p2l(p1);
              var delta = (d0 + d1) / 2;
              axi.range = [
                axi.l2r(axi._rl[0] - delta),
                axi.l2r(axi._rl[1] - delta)
              ];
            } else {
              axi.range = [
                axi.l2r(axi._rl[0] - pix / axi._m),
                axi.l2r(axi._rl[1] - pix / axi._m)
              ];
            }
            if (axi.limitRange) axi.limitRange();
          }
        }
      }
      function dZoom(d) {
        return 1 - (d >= 0 ? Math.min(d, 0.9) : 1 / (1 / Math.max(d, -0.3) + 3.222));
      }
      function getDragCursor(nsew, dragmode, isMainDrag) {
        if (!nsew) return "pointer";
        if (nsew === "nsew") {
          if (isMainDrag) return "";
          if (dragmode === "pan") return "move";
          return "crosshair";
        }
        return nsew.toLowerCase() + "-resize";
      }
      function makeZoombox(zoomlayer, lum, xs, ys, path0) {
        return zoomlayer.append("path").attr("class", "zoombox").style({
          fill: lum > 0.2 ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)",
          "stroke-width": 0
        }).attr("transform", strTranslate(xs, ys)).attr("d", path0 + "Z");
      }
      function makeCorners(zoomlayer, xs, ys) {
        return zoomlayer.append("path").attr("class", "zoombox-corners").style({
          fill: Color2.background,
          stroke: Color2.defaultLine,
          "stroke-width": 1,
          opacity: 0
        }).attr("transform", strTranslate(xs, ys)).attr("d", "M0,0Z");
      }
      function updateZoombox(zb, corners, box, path0, dimmed, lum) {
        zb.attr(
          "d",
          path0 + "M" + box.l + "," + box.t + "v" + box.h + "h" + box.w + "v-" + box.h + "h-" + box.w + "Z"
        );
        transitionZoombox(zb, corners, dimmed, lum);
      }
      function transitionZoombox(zb, corners, dimmed, lum) {
        if (!dimmed) {
          zb.transition().style("fill", lum > 0.2 ? "rgba(0,0,0,0.4)" : "rgba(255,255,255,0.3)").duration(200);
          corners.transition().style("opacity", 1).duration(200);
        }
      }
      function removeZoombox(gd) {
        d3.select(gd).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove();
      }
      function showDoubleClickNotifier(gd) {
        if (SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
          Lib.notifier(Lib._(gd, "Double-click to zoom back out"), "long");
          SHOWZOOMOUTTIP = false;
        }
      }
      function xCorners(box, y0) {
        return "M" + (box.l - 0.5) + "," + (y0 - MINZOOM - 0.5) + "h-3v" + (2 * MINZOOM + 1) + "h3ZM" + (box.r + 0.5) + "," + (y0 - MINZOOM - 0.5) + "h3v" + (2 * MINZOOM + 1) + "h-3Z";
      }
      function yCorners(box, x0) {
        return "M" + (x0 - MINZOOM - 0.5) + "," + (box.t - 0.5) + "v-3h" + (2 * MINZOOM + 1) + "v3ZM" + (x0 - MINZOOM - 0.5) + "," + (box.b + 0.5) + "v3h" + (2 * MINZOOM + 1) + "v-3Z";
      }
      function xyCorners(box) {
        var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2);
        return "M" + (box.l - 3.5) + "," + (box.t - 0.5 + clen) + "h3v" + -clen + "h" + clen + "v-3h-" + (clen + 3) + "ZM" + (box.r + 3.5) + "," + (box.t - 0.5 + clen) + "h-3v" + -clen + "h" + -clen + "v-3h" + (clen + 3) + "ZM" + (box.r + 3.5) + "," + (box.b + 0.5 - clen) + "h-3v" + clen + "h" + -clen + "v3h" + (clen + 3) + "ZM" + (box.l - 3.5) + "," + (box.b + 0.5 - clen) + "h3v" + clen + "h" + clen + "v3h-" + (clen + 3) + "Z";
      }
      function calcLinks(gd, groups, xaHash, yaHash, exclude) {
        var isSubplotConstrained = false;
        var xLinks = {};
        var yLinks = {};
        var xID, yID, xLinkID, yLinkID;
        var xExclude = (exclude || {}).xaHash;
        var yExclude = (exclude || {}).yaHash;
        for (var i = 0; i < groups.length; i++) {
          var group = groups[i];
          for (xID in xaHash) {
            if (group[xID]) {
              for (xLinkID in group) {
                if (!(exclude && (xExclude[xLinkID] || yExclude[xLinkID])) && !(xLinkID.charAt(0) === "x" ? xaHash : yaHash)[xLinkID]) {
                  xLinks[xLinkID] = xID;
                }
              }
              for (yID in yaHash) {
                if (!(exclude && (xExclude[yID] || yExclude[yID])) && group[yID]) {
                  isSubplotConstrained = true;
                }
              }
            }
          }
          for (yID in yaHash) {
            if (group[yID]) {
              for (yLinkID in group) {
                if (!(exclude && (xExclude[yLinkID] || yExclude[yLinkID])) && !(yLinkID.charAt(0) === "x" ? xaHash : yaHash)[yLinkID]) {
                  yLinks[yLinkID] = yID;
                }
              }
            }
          }
        }
        if (isSubplotConstrained) {
          Lib.extendFlat(xLinks, yLinks);
          yLinks = {};
        }
        var xaHashLinked = {};
        var xaxesLinked = [];
        for (xLinkID in xLinks) {
          var xa = getFromId(gd, xLinkID);
          xaxesLinked.push(xa);
          xaHashLinked[xa._id] = xa;
        }
        var yaHashLinked = {};
        var yaxesLinked = [];
        for (yLinkID in yLinks) {
          var ya = getFromId(gd, yLinkID);
          yaxesLinked.push(ya);
          yaHashLinked[ya._id] = ya;
        }
        return {
          xaHash: xaHashLinked,
          yaHash: yaHashLinked,
          xaxes: xaxesLinked,
          yaxes: yaxesLinked,
          xLinks,
          yLinks,
          isSubplotConstrained
        };
      }
      function attachWheelEventHandler(element, handler) {
        if (!supportsPassive) {
          if (element.onwheel !== void 0) element.onwheel = handler;
          else if (element.onmousewheel !== void 0) element.onmousewheel = handler;
          else if (!element.isAddedWheelEvent) {
            element.isAddedWheelEvent = true;
            element.addEventListener("wheel", handler, { passive: false });
          }
        } else {
          var wheelEventName = element.onwheel !== void 0 ? "wheel" : "mousewheel";
          if (element._onwheel) {
            element.removeEventListener(wheelEventName, element._onwheel);
          }
          element._onwheel = handler;
          element.addEventListener(wheelEventName, handler, { passive: false });
        }
      }
      function hashValues(hash) {
        var out = [];
        for (var k in hash) out.push(hash[k]);
        return out;
      }
      module.exports = {
        makeDragBox,
        makeDragger,
        makeRectDragger,
        makeZoombox,
        makeCorners,
        updateZoombox,
        xyCorners,
        transitionZoombox,
        removeZoombox,
        showDoubleClickNotifier,
        attachWheelEventHandler
      };
    }
  });

  // src/plots/cartesian/graph_interact.js
  var require_graph_interact = __commonJS({
    "src/plots/cartesian/graph_interact.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var Fx = require_fx();
      var dragElement = require_dragelement();
      var setCursor = require_setcursor();
      var makeDragBox = require_dragbox().makeDragBox;
      var DRAGGERSIZE = require_constants2().DRAGGERSIZE;
      exports.initInteractions = function initInteractions(gd) {
        var fullLayout = gd._fullLayout;
        if (gd._context.staticPlot) {
          d3.select(gd).selectAll(".drag").remove();
          return;
        }
        if (!fullLayout._has("cartesian") && !fullLayout._has("splom")) return;
        var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
          if ((fullLayout._plots[a].mainplot && true) === (fullLayout._plots[b].mainplot && true)) {
            var aParts = a.split("y");
            var bParts = b.split("y");
            return aParts[0] === bParts[0] ? Number(aParts[1] || 1) - Number(bParts[1] || 1) : Number(aParts[0] || 1) - Number(bParts[0] || 1);
          }
          return fullLayout._plots[a].mainplot ? 1 : -1;
        });
        subplots.forEach(function(subplot) {
          var plotinfo = fullLayout._plots[subplot];
          var xa = plotinfo.xaxis;
          var ya = plotinfo.yaxis;
          if (!plotinfo.mainplot) {
            var maindrag = makeDragBox(
              gd,
              plotinfo,
              xa._offset,
              ya._offset,
              xa._length,
              ya._length,
              "ns",
              "ew"
            );
            maindrag.onmousemove = function(evt) {
              gd._fullLayout._rehover = function() {
                if (gd._fullLayout._hoversubplot === subplot && gd._fullLayout._plots[subplot]) {
                  Fx.hover(gd, evt, subplot);
                }
              };
              Fx.hover(gd, evt, subplot);
              gd._fullLayout._lasthover = maindrag;
              gd._fullLayout._hoversubplot = subplot;
            };
            maindrag.onmouseout = function(evt) {
              if (gd._dragging) return;
              gd._fullLayout._hoversubplot = null;
              dragElement.unhover(gd, evt);
            };
            if (gd._context.showAxisDragHandles) {
              makeDragBox(
                gd,
                plotinfo,
                xa._offset - DRAGGERSIZE,
                ya._offset - DRAGGERSIZE,
                DRAGGERSIZE,
                DRAGGERSIZE,
                "n",
                "w"
              );
              makeDragBox(
                gd,
                plotinfo,
                xa._offset + xa._length,
                ya._offset - DRAGGERSIZE,
                DRAGGERSIZE,
                DRAGGERSIZE,
                "n",
                "e"
              );
              makeDragBox(
                gd,
                plotinfo,
                xa._offset - DRAGGERSIZE,
                ya._offset + ya._length,
                DRAGGERSIZE,
                DRAGGERSIZE,
                "s",
                "w"
              );
              makeDragBox(
                gd,
                plotinfo,
                xa._offset + xa._length,
                ya._offset + ya._length,
                DRAGGERSIZE,
                DRAGGERSIZE,
                "s",
                "e"
              );
            }
          }
          if (gd._context.showAxisDragHandles) {
            if (subplot === xa._mainSubplot) {
              var y0 = xa._mainLinePosition;
              if (xa.side === "top") y0 -= DRAGGERSIZE;
              makeDragBox(
                gd,
                plotinfo,
                xa._offset + xa._length * 0.1,
                y0,
                xa._length * 0.8,
                DRAGGERSIZE,
                "",
                "ew"
              );
              makeDragBox(
                gd,
                plotinfo,
                xa._offset,
                y0,
                xa._length * 0.1,
                DRAGGERSIZE,
                "",
                "w"
              );
              makeDragBox(
                gd,
                plotinfo,
                xa._offset + xa._length * 0.9,
                y0,
                xa._length * 0.1,
                DRAGGERSIZE,
                "",
                "e"
              );
            }
            if (subplot === ya._mainSubplot) {
              var x0 = ya._mainLinePosition;
              if (ya.side !== "right") x0 -= DRAGGERSIZE;
              makeDragBox(
                gd,
                plotinfo,
                x0,
                ya._offset + ya._length * 0.1,
                DRAGGERSIZE,
                ya._length * 0.8,
                "ns",
                ""
              );
              makeDragBox(
                gd,
                plotinfo,
                x0,
                ya._offset + ya._length * 0.9,
                DRAGGERSIZE,
                ya._length * 0.1,
                "s",
                ""
              );
              makeDragBox(
                gd,
                plotinfo,
                x0,
                ya._offset,
                DRAGGERSIZE,
                ya._length * 0.1,
                "n",
                ""
              );
            }
          }
        });
        var hoverLayer = fullLayout._hoverlayer.node();
        hoverLayer.onmousemove = function(evt) {
          evt.target = gd._fullLayout._lasthover;
          Fx.hover(gd, evt, fullLayout._hoversubplot);
        };
        hoverLayer.onclick = function(evt) {
          evt.target = gd._fullLayout._lasthover;
          Fx.click(gd, evt);
        };
        hoverLayer.onmousedown = function(evt) {
          gd._fullLayout._lasthover.onmousedown(evt);
        };
        exports.updateFx(gd);
      };
      exports.updateFx = function(gd) {
        var fullLayout = gd._fullLayout;
        var cursor = fullLayout.dragmode === "pan" ? "move" : "crosshair";
        setCursor(fullLayout._draggers, cursor);
      };
    }
  });

  // src/plot_api/container_array_match.js
  var require_container_array_match = __commonJS({
    "src/plot_api/container_array_match.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      module.exports = function containerArrayMatch(astr) {
        var rootContainers = Registry.layoutArrayContainers;
        var regexpContainers = Registry.layoutArrayRegexes;
        var rootPart = astr.split("[")[0];
        var arrayStr;
        var match;
        for (var i = 0; i < regexpContainers.length; i++) {
          match = astr.match(regexpContainers[i]);
          if (match && match.index === 0) {
            arrayStr = match[0];
            break;
          }
        }
        if (!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)];
        if (!arrayStr) return false;
        var tail = astr.slice(arrayStr.length);
        if (!tail) return { array: arrayStr, index: "", property: "" };
        match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/);
        if (!match) return false;
        return { array: arrayStr, index: Number(match[1]), property: match[3] || "" };
      };
    }
  });

  // src/plot_api/manage_arrays.js
  var require_manage_arrays = __commonJS({
    "src/plot_api/manage_arrays.js"(exports) {
      "use strict";
      var isPlainObject = require_is_plain_object();
      var noop = require_noop();
      var Loggers = require_loggers();
      var sorterAsc = require_search().sorterAsc;
      var Registry = require_registry();
      exports.containerArrayMatch = require_container_array_match();
      var isAddVal = exports.isAddVal = function isAddVal2(val) {
        return val === "add" || isPlainObject(val);
      };
      var isRemoveVal = exports.isRemoveVal = function isRemoveVal2(val) {
        return val === null || val === "remove";
      };
      exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) {
        var componentType = np.astr;
        var supplyComponentDefaults = Registry.getComponentMethod(componentType, "supplyLayoutDefaults");
        var draw = Registry.getComponentMethod(componentType, "draw");
        var drawOne = Registry.getComponentMethod(componentType, "drawOne");
        var replotLater = flags.replot || flags.recalc || supplyComponentDefaults === noop || draw === noop;
        var layout = gd.layout;
        var fullLayout = gd._fullLayout;
        if (edits[""]) {
          if (Object.keys(edits).length > 1) {
            Loggers.warn(
              "Full array edits are incompatible with other edits",
              componentType
            );
          }
          var fullVal = edits[""][""];
          if (isRemoveVal(fullVal)) np.set(null);
          else if (Array.isArray(fullVal)) np.set(fullVal);
          else {
            Loggers.warn("Unrecognized full array edit value", componentType, fullVal);
            return true;
          }
          if (replotLater) return false;
          supplyComponentDefaults(layout, fullLayout);
          draw(gd);
          return true;
        }
        var componentNums = Object.keys(edits).map(Number).sort(sorterAsc);
        var componentArrayIn = np.get();
        var componentArray = componentArrayIn || [];
        var componentArrayFull = _nestedProperty(fullLayout, componentType).get();
        var deletes = [];
        var firstIndexChange = -1;
        var maxIndex = componentArray.length;
        var i;
        var j;
        var componentNum;
        var objEdits;
        var objKeys;
        var objVal;
        var adding, prefix;
        for (i = 0; i < componentNums.length; i++) {
          componentNum = componentNums[i];
          objEdits = edits[componentNum];
          objKeys = Object.keys(objEdits);
          objVal = objEdits[""], adding = isAddVal(objVal);
          if (componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) {
            Loggers.warn("index out of range", componentType, componentNum);
            continue;
          }
          if (objVal !== void 0) {
            if (objKeys.length > 1) {
              Loggers.warn(
                "Insertion & removal are incompatible with edits to the same index.",
                componentType,
                componentNum
              );
            }
            if (isRemoveVal(objVal)) {
              deletes.push(componentNum);
            } else if (adding) {
              if (objVal === "add") objVal = {};
              componentArray.splice(componentNum, 0, objVal);
              if (componentArrayFull) componentArrayFull.splice(componentNum, 0, {});
            } else {
              Loggers.warn(
                "Unrecognized full object edit value",
                componentType,
                componentNum,
                objVal
              );
            }
            if (firstIndexChange === -1) firstIndexChange = componentNum;
          } else {
            for (j = 0; j < objKeys.length; j++) {
              prefix = componentType + "[" + componentNum + "].";
              _nestedProperty(componentArray[componentNum], objKeys[j], prefix).set(objEdits[objKeys[j]]);
            }
          }
        }
        for (i = deletes.length - 1; i >= 0; i--) {
          componentArray.splice(deletes[i], 1);
          if (componentArrayFull) componentArrayFull.splice(deletes[i], 1);
        }
        if (!componentArray.length) np.set(null);
        else if (!componentArrayIn) np.set(componentArray);
        if (replotLater) return false;
        supplyComponentDefaults(layout, fullLayout);
        if (drawOne !== noop) {
          var indicesToDraw;
          if (firstIndexChange === -1) {
            indicesToDraw = componentNums;
          } else {
            maxIndex = Math.max(componentArray.length, maxIndex);
            indicesToDraw = [];
            for (i = 0; i < componentNums.length; i++) {
              componentNum = componentNums[i];
              if (componentNum >= firstIndexChange) break;
              indicesToDraw.push(componentNum);
            }
            for (i = firstIndexChange; i < maxIndex; i++) {
              indicesToDraw.push(i);
            }
          }
          for (i = 0; i < indicesToDraw.length; i++) {
            drawOne(gd, indicesToDraw[i]);
          }
        } else draw(gd);
        return true;
      };
    }
  });

  // src/plot_api/helpers.js
  var require_helpers9 = __commonJS({
    "src/plot_api/helpers.js"(exports) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Registry = require_registry();
      var Lib = require_lib();
      var Plots = require_plots();
      var AxisIds = require_axis_ids();
      var Color2 = require_color();
      var cleanId = AxisIds.cleanId;
      var getFromTrace = AxisIds.getFromTrace;
      var traceIs = Registry.traceIs;
      var AX_LETTERS = ["x", "y", "z"];
      exports.clearPromiseQueue = function(gd) {
        if (Array.isArray(gd._promises) && gd._promises.length > 0) {
          Lib.log("Clearing previous rejected promises from queue.");
        }
        gd._promises = [];
      };
      exports.cleanLayout = function(layout) {
        var i, j;
        if (!layout) layout = {};
        if (layout.xaxis1) {
          if (!layout.xaxis) layout.xaxis = layout.xaxis1;
          delete layout.xaxis1;
        }
        if (layout.yaxis1) {
          if (!layout.yaxis) layout.yaxis = layout.yaxis1;
          delete layout.yaxis1;
        }
        if (layout.scene1) {
          if (!layout.scene) layout.scene = layout.scene1;
          delete layout.scene1;
        }
        var axisAttrRegex = (Plots.subplotsRegistry.cartesian || {}).attrRegex;
        var polarAttrRegex = (Plots.subplotsRegistry.polar || {}).attrRegex;
        var ternaryAttrRegex = (Plots.subplotsRegistry.ternary || {}).attrRegex;
        var sceneAttrRegex = (Plots.subplotsRegistry.gl3d || {}).attrRegex;
        var keys = Object.keys(layout);
        for (i = 0; i < keys.length; i++) {
          var key = keys[i];
          if (axisAttrRegex && axisAttrRegex.test(key)) {
            var ax = layout[key];
            if (ax.anchor && ax.anchor !== "free") {
              ax.anchor = cleanId(ax.anchor);
            }
            if (ax.overlaying) ax.overlaying = cleanId(ax.overlaying);
            if (!ax.type) {
              if (ax.isdate) ax.type = "date";
              else if (ax.islog) ax.type = "log";
              else if (ax.isdate === false && ax.islog === false) ax.type = "linear";
            }
            if (ax.autorange === "withzero" || ax.autorange === "tozero") {
              ax.autorange = true;
              ax.rangemode = "tozero";
            }
            if (ax.insiderange) delete ax.range;
            delete ax.islog;
            delete ax.isdate;
            delete ax.categories;
            if (emptyContainer(ax, "domain")) delete ax.domain;
          }
        }
        var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0;
        for (i = 0; i < annotationsLen; i++) {
          var ann = layout.annotations[i];
          if (!Lib.isPlainObject(ann)) continue;
          cleanAxRef(ann, "xref");
          cleanAxRef(ann, "yref");
        }
        var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0;
        for (i = 0; i < shapesLen; i++) {
          var shape = layout.shapes[i];
          if (!Lib.isPlainObject(shape)) continue;
          cleanAxRef(shape, "xref", true);
          cleanAxRef(shape, "yref", true);
        }
        var imagesLen = Array.isArray(layout.images) ? layout.images.length : 0;
        for (i = 0; i < imagesLen; i++) {
          var image = layout.images[i];
          if (!Lib.isPlainObject(image)) continue;
          cleanAxRef(image, "xref");
          cleanAxRef(image, "yref");
        }
        var legend = layout.legend;
        if (legend) {
          if (legend.x > 3) {
            legend.x = 1.02;
            legend.xanchor = "left";
          } else if (legend.x < -2) {
            legend.x = -0.02;
            legend.xanchor = "right";
          }
          if (legend.y > 3) {
            legend.y = 1.02;
            legend.yanchor = "bottom";
          } else if (legend.y < -2) {
            legend.y = -0.02;
            legend.yanchor = "top";
          }
        }
        if (layout.dragmode === "rotate") layout.dragmode = "orbit";
        Color2.clean(layout);
        if (layout.template && layout.template.layout) {
          exports.cleanLayout(layout.template.layout);
        }
        return layout;
      };
      function cleanAxRef(container, attr, isShape = false) {
        var valIn = container[attr];
        var axLetter = attr.charAt(0);
        if (isShape && Array.isArray(valIn)) return;
        if (valIn && valIn !== "paper") {
          container[attr] = cleanId(valIn, axLetter, true);
        }
      }
      exports.cleanData = function(data) {
        for (var tracei = 0; tracei < data.length; tracei++) {
          var trace = data[tracei];
          var i;
          if (trace.type === "histogramy" && "xbins" in trace && !("ybins" in trace)) {
            trace.ybins = trace.xbins;
            delete trace.xbins;
          }
          if (trace.type === "histogramy") exports.swapXYData(trace);
          if (trace.type === "histogramx" || trace.type === "histogramy") {
            trace.type = "histogram";
          }
          if ("scl" in trace && !("colorscale" in trace)) {
            trace.colorscale = trace.scl;
            delete trace.scl;
          }
          if ("reversescl" in trace && !("reversescale" in trace)) {
            trace.reversescale = trace.reversescl;
            delete trace.reversescl;
          }
          if (trace.xaxis) trace.xaxis = cleanId(trace.xaxis, "x");
          if (trace.yaxis) trace.yaxis = cleanId(trace.yaxis, "y");
          if (traceIs(trace, "gl3d") && trace.scene) {
            trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
          }
          if (!traceIs(trace, "pie-like") && !traceIs(trace, "bar-like")) {
            if (Array.isArray(trace.textposition)) {
              for (i = 0; i < trace.textposition.length; i++) {
                trace.textposition[i] = cleanTextPosition(trace.textposition[i]);
              }
            } else if (trace.textposition) {
              trace.textposition = cleanTextPosition(trace.textposition);
            }
          }
          var _module = Registry.getModule(trace);
          if (_module && _module.colorbar) {
            var containerName = _module.colorbar.container;
            var container = containerName ? trace[containerName] : trace;
            if (container && container.colorscale) {
              if (container.colorscale === "YIGnBu") container.colorscale = "YlGnBu";
              if (container.colorscale === "YIOrRd") container.colorscale = "YlOrRd";
            }
          }
          if (trace.type === "surface" && Lib.isPlainObject(trace.contours)) {
            var dims = ["x", "y", "z"];
            for (i = 0; i < dims.length; i++) {
              var opts = trace.contours[dims[i]];
              if (!Lib.isPlainObject(opts)) continue;
              if (opts.highlightColor) {
                opts.highlightcolor = opts.highlightColor;
                delete opts.highlightColor;
              }
              if (opts.highlightWidth) {
                opts.highlightwidth = opts.highlightWidth;
                delete opts.highlightWidth;
              }
            }
          }
          if (trace.type === "candlestick" || trace.type === "ohlc") {
            var increasingShowlegend = (trace.increasing || {}).showlegend !== false;
            var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false;
            var increasingName = cleanFinanceDir(trace.increasing);
            var decreasingName = cleanFinanceDir(trace.decreasing);
            if (increasingName !== false && decreasingName !== false) {
              var newName = commonPrefix(increasingName, decreasingName, increasingShowlegend, decreasingShowlegend);
              if (newName) trace.name = newName;
            } else if ((increasingName || decreasingName) && !trace.name) {
              trace.name = increasingName || decreasingName;
            }
          }
          if (emptyContainer(trace, "line")) delete trace.line;
          if ("marker" in trace) {
            if (emptyContainer(trace.marker, "line")) delete trace.marker.line;
            if (emptyContainer(trace, "marker")) delete trace.marker;
          }
          Color2.clean(trace);
          if (trace.autobinx) {
            delete trace.autobinx;
            delete trace.xbins;
          }
          if (trace.autobiny) {
            delete trace.autobiny;
            delete trace.ybins;
          }
        }
      };
      function cleanFinanceDir(dirContainer) {
        if (!Lib.isPlainObject(dirContainer)) return false;
        var dirName = dirContainer.name;
        delete dirContainer.name;
        delete dirContainer.showlegend;
        return (typeof dirName === "string" || typeof dirName === "number") && String(dirName);
      }
      function commonPrefix(name1, name2, show1, show2) {
        if (show1 && !show2) return name1;
        if (show2 && !show1) return name2;
        if (!name1.trim()) return name2;
        if (!name2.trim()) return name1;
        var minLen = Math.min(name1.length, name2.length);
        var i;
        for (i = 0; i < minLen; i++) {
          if (name1.charAt(i) !== name2.charAt(i)) break;
        }
        var out = name1.slice(0, i);
        return out.trim();
      }
      function cleanTextPosition(textposition) {
        var posY = "middle";
        var posX = "center";
        if (typeof textposition === "string") {
          if (textposition.indexOf("top") !== -1) posY = "top";
          else if (textposition.indexOf("bottom") !== -1) posY = "bottom";
          if (textposition.indexOf("left") !== -1) posX = "left";
          else if (textposition.indexOf("right") !== -1) posX = "right";
        }
        return posY + " " + posX;
      }
      function emptyContainer(outer, innerStr) {
        return innerStr in outer && typeof outer[innerStr] === "object" && Object.keys(outer[innerStr]).length === 0;
      }
      exports.swapXYData = function(trace) {
        var i;
        Lib.swapAttrs(trace, ["?", "?0", "d?", "?bins", "nbins?", "autobin?", "?src", "error_?"]);
        if (Array.isArray(trace.z) && Array.isArray(trace.z[0])) {
          if (trace.transpose) delete trace.transpose;
          else trace.transpose = true;
        }
        if (trace.error_x && trace.error_y) {
          var errorY = trace.error_y;
          var copyYstyle = "copy_ystyle" in errorY ? errorY.copy_ystyle : !(errorY.color || errorY.thickness || errorY.width);
          Lib.swapAttrs(trace, ["error_?.copy_ystyle"]);
          if (copyYstyle) {
            Lib.swapAttrs(trace, ["error_?.color", "error_?.thickness", "error_?.width"]);
          }
        }
        if (typeof trace.hoverinfo === "string") {
          var hoverInfoParts = trace.hoverinfo.split("+");
          for (i = 0; i < hoverInfoParts.length; i++) {
            if (hoverInfoParts[i] === "x") hoverInfoParts[i] = "y";
            else if (hoverInfoParts[i] === "y") hoverInfoParts[i] = "x";
          }
          trace.hoverinfo = hoverInfoParts.join("+");
        }
      };
      exports.coerceTraceIndices = function(gd, traceIndices) {
        if (isNumeric(traceIndices)) {
          return [traceIndices];
        } else if (!Array.isArray(traceIndices) || !traceIndices.length) {
          return gd.data.map(function(_, i2) {
            return i2;
          });
        } else if (Array.isArray(traceIndices)) {
          var traceIndicesOut = [];
          for (var i = 0; i < traceIndices.length; i++) {
            if (Lib.isIndex(traceIndices[i], gd.data.length)) {
              traceIndicesOut.push(traceIndices[i]);
            } else {
              Lib.warn("trace index (", traceIndices[i], ") is not a number or is out of bounds");
            }
          }
          return traceIndicesOut;
        }
        return traceIndices;
      };
      exports.manageArrayContainers = function(np, newVal, undoit) {
        var obj = np.obj;
        var parts = np.parts;
        var pLength = parts.length;
        var pLast = parts[pLength - 1];
        var pLastIsNumber = isNumeric(pLast);
        if (pLastIsNumber && newVal === null) {
          var contPath = parts.slice(0, pLength - 1).join(".");
          var cont = Lib.nestedProperty(obj, contPath).get();
          cont.splice(pLast, 1);
        } else if (pLastIsNumber && np.get() === void 0) {
          if (np.get() === void 0) undoit[np.astr] = null;
          np.set(newVal);
        } else {
          np.set(newVal);
        }
      };
      var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;
      function getParent(attr) {
        var tail = attr.search(ATTR_TAIL_RE);
        if (tail > 0) return attr.slice(0, tail);
      }
      exports.hasParent = function(aobj, attr) {
        var attrParent = getParent(attr);
        while (attrParent) {
          if (attrParent in aobj) return true;
          attrParent = getParent(attrParent);
        }
        return false;
      };
      exports.clearAxisTypes = function(gd, traces, layoutUpdate) {
        for (var i = 0; i < traces.length; i++) {
          var trace = gd._fullData[i];
          for (var j = 0; j < 3; j++) {
            var ax = getFromTrace(gd, trace, AX_LETTERS[j]);
            if (ax && ax.type !== "log") {
              var axAttr = ax._name;
              var sceneName = ax._id.slice(1);
              if (sceneName.slice(0, 5) === "scene") {
                if (layoutUpdate[sceneName] !== void 0) continue;
                axAttr = sceneName + "." + axAttr;
              }
              var typeAttr = axAttr + ".type";
              if (layoutUpdate[axAttr] === void 0 && layoutUpdate[typeAttr] === void 0) {
                Lib.nestedProperty(gd.layout, typeAttr).set(null);
              }
            }
          }
        }
      };
      var collectionsAreEqual = (collection1, collection2) => {
        const isArrayOrObject = (...vals) => vals.every((v) => Lib.isPlainObject(v)) || vals.every((v) => Array.isArray(v));
        if ([collection1, collection2].every((a) => Array.isArray(a))) {
          if (collection1.length !== collection2.length) return false;
          for (let i = 0; i < collection1.length; i++) {
            const oldVal = collection1[i];
            const newVal = collection2[i];
            if (oldVal !== newVal) {
              const equal = isArrayOrObject(oldVal, newVal) ? collectionsAreEqual(oldVal, newVal) : false;
              if (!equal) return false;
            }
          }
          return true;
        } else if ([collection1, collection2].every((a) => Lib.isPlainObject(a))) {
          if (Object.keys(collection1).length !== Object.keys(collection2).length) return false;
          for (const k in collection1) {
            if (k.startsWith("_")) continue;
            const oldVal = collection1[k];
            const newVal = collection2[k];
            if (oldVal !== newVal) {
              const equal = isArrayOrObject(oldVal, newVal) ? collectionsAreEqual(oldVal, newVal) : false;
              if (!equal) return false;
            }
          }
          return true;
        }
        return false;
      };
      exports.collectionsAreEqual = collectionsAreEqual;
    }
  });

  // src/plot_api/plot_api.js
  var require_plot_api = __commonJS({
    "src/plot_api/plot_api.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var hasHover = require_has_hover();
      var Lib = require_lib();
      var nestedProperty = Lib.nestedProperty;
      var Events = require_events2();
      var Queue = require_queue();
      var Registry = require_registry();
      var PlotSchema = require_plot_schema();
      var Plots = require_plots();
      var Axes = require_axes();
      var handleRangeDefaults = require_range_defaults();
      var cartesianLayoutAttributes = require_layout_attributes4();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var initInteractions = require_graph_interact().initInteractions;
      var xmlnsNamespaces = require_xmlns_namespaces();
      var clearOutline = require_selections().clearOutline;
      var dfltConfig = require_plot_config().dfltConfig;
      var manageArrays = require_manage_arrays();
      var helpers = require_helpers9();
      var subroutines = require_subroutines();
      var editTypes = require_edit_types();
      var AX_NAME_PATTERN = require_constants2().AX_NAME_PATTERN;
      var numericNameWarningCount = 0;
      var numericNameWarningCountLimit = 5;
      function _doPlot(gd, data, layout, config) {
        var frames;
        gd = Lib.getGraphDiv(gd);
        Events.init(gd);
        if (Lib.isPlainObject(data)) {
          var obj = data;
          data = obj.data;
          layout = obj.layout;
          config = obj.config;
          frames = obj.frames;
        }
        var okToPlot = Events.triggerHandler(gd, "plotly_beforeplot", [data, layout, config]);
        if (okToPlot === false) return Promise.reject();
        if (!data && !layout && !Lib.isPlotDiv(gd)) {
          Lib.warn("Calling _doPlot as if redrawing but this container doesn't yet have a plot.", gd);
        }
        function addFrames2() {
          if (frames) {
            return exports.addFrames(gd, frames);
          }
        }
        setPlotContext(gd, config);
        if (!layout) layout = {};
        d3.select(gd).classed("js-plotly-plot", true);
        Drawing.makeTester();
        if (!Array.isArray(gd._promises)) gd._promises = [];
        var graphWasEmpty = (gd.data || []).length === 0 && Array.isArray(data);
        if (Array.isArray(data)) {
          helpers.cleanData(data);
          if (graphWasEmpty) gd.data = data;
          else gd.data.push.apply(gd.data, data);
          gd.empty = false;
        }
        if (!gd.layout || graphWasEmpty) {
          gd.layout = helpers.cleanLayout(layout);
        }
        Plots.supplyDefaults(gd);
        var fullLayout = gd._fullLayout;
        var hasCartesian = fullLayout._has("cartesian");
        fullLayout._replotting = true;
        if (graphWasEmpty || fullLayout._shouldCreateBgLayer) {
          makePlotFramework(gd);
          if (fullLayout._shouldCreateBgLayer) {
            delete fullLayout._shouldCreateBgLayer;
          }
        }
        Drawing.initGradients(gd);
        Drawing.initPatterns(gd);
        if (graphWasEmpty) Axes.saveShowSpikeInitial(gd);
        var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length;
        if (recalc) Plots.doCalcdata(gd);
        for (var i = 0; i < gd.calcdata.length; i++) {
          gd.calcdata[i][0].trace = gd._fullData[i];
        }
        if (gd._context.responsive) {
          if (!gd._responsiveChartHandler) {
            gd._responsiveChartHandler = function() {
              if (!Lib.isHidden(gd)) Plots.resize(gd);
            };
            window.addEventListener("resize", gd._responsiveChartHandler);
          }
        } else {
          Lib.clearResponsive(gd);
        }
        var oldMargins = Lib.extendFlat({}, fullLayout._size);
        var drawFrameworkCalls = 0;
        function drawFramework() {
          var basePlotModules = fullLayout._basePlotModules;
          for (var i2 = 0; i2 < basePlotModules.length; i2++) {
            if (basePlotModules[i2].drawFramework) {
              basePlotModules[i2].drawFramework(gd);
            }
          }
          if (!fullLayout._glcanvas && fullLayout._has("gl")) {
            fullLayout._glcanvas = fullLayout._glcontainer.selectAll(".gl-canvas").data(
              [
                {
                  key: "contextLayer",
                  context: true,
                  pick: false
                },
                {
                  key: "focusLayer",
                  context: false,
                  pick: false
                },
                {
                  key: "pickLayer",
                  context: false,
                  pick: true
                }
              ],
              function(d) {
                return d.key;
              }
            );
            fullLayout._glcanvas.enter().append("canvas").attr("class", function(d) {
              return "gl-canvas gl-canvas-" + d.key.replace("Layer", "");
            }).style({
              position: "absolute",
              top: 0,
              left: 0,
              overflow: "visible",
              "pointer-events": "none"
            });
          }
          var plotGlPixelRatio = gd._context.plotGlPixelRatio;
          if (fullLayout._glcanvas) {
            fullLayout._glcanvas.attr("width", fullLayout.width * plotGlPixelRatio).attr("height", fullLayout.height * plotGlPixelRatio).style("width", fullLayout.width + "px").style("height", fullLayout.height + "px");
            var regl = fullLayout._glcanvas.data()[0].regl;
            if (regl) {
              if (Math.floor(fullLayout.width * plotGlPixelRatio) !== regl._gl.drawingBufferWidth || Math.floor(fullLayout.height * plotGlPixelRatio) !== regl._gl.drawingBufferHeight) {
                var msg = "WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug.";
                if (drawFrameworkCalls) {
                  Lib.error(msg);
                } else {
                  Lib.log(msg + " Clearing graph and plotting again.");
                  Plots.cleanPlot([], {}, gd._fullData, fullLayout);
                  Plots.supplyDefaults(gd);
                  fullLayout = gd._fullLayout;
                  Plots.doCalcdata(gd);
                  drawFrameworkCalls++;
                  return drawFramework();
                }
              }
            }
          }
          if (fullLayout.modebar.orientation === "h") {
            fullLayout._modebardiv.style("height", null).style("width", "100%");
          } else {
            fullLayout._modebardiv.style("width", null).style("height", fullLayout.height + "px");
          }
          return Plots.previousPromises(gd);
        }
        function marginPushers() {
          Plots.clearAutoMarginIds(gd);
          subroutines.drawMarginPushers(gd);
          Axes.allowAutoMargin(gd);
          if (gd._fullLayout.title.text && gd._fullLayout.title.automargin) Plots.allowAutoMargin(gd, "title.automargin");
          if (fullLayout._has("pie")) {
            var fullData = gd._fullData;
            for (var i2 = 0; i2 < fullData.length; i2++) {
              var trace = fullData[i2];
              if (trace.type === "pie" && trace.automargin) {
                Plots.allowAutoMargin(gd, "pie." + trace.uid + ".automargin");
              }
            }
          }
          Plots.doAutoMargin(gd);
          return Plots.previousPromises(gd);
        }
        function marginPushersAgain() {
          if (!Plots.didMarginChange(oldMargins, fullLayout._size)) return;
          return Lib.syncOrAsync([marginPushers, subroutines.layoutStyles], gd);
        }
        function positionAndAutorange() {
          if (!recalc) {
            doAutoRangeAndConstraints();
            return;
          }
          return Lib.syncOrAsync(
            [
              Registry.getComponentMethod("shapes", "calcAutorange"),
              Registry.getComponentMethod("annotations", "calcAutorange"),
              doAutoRangeAndConstraints
            ],
            gd
          );
        }
        function doAutoRangeAndConstraints() {
          if (gd._transitioning) return;
          subroutines.doAutoRangeAndConstraints(gd);
          if (graphWasEmpty) Axes.saveRangeInitial(gd);
          Registry.getComponentMethod("rangeslider", "calcAutorange")(gd);
        }
        function drawAxes() {
          return Axes.draw(gd, graphWasEmpty ? "" : "redraw");
        }
        var seq = [Plots.previousPromises, addFrames2, drawFramework, marginPushers, marginPushersAgain];
        if (hasCartesian) seq.push(positionAndAutorange);
        seq.push(subroutines.layoutStyles);
        if (hasCartesian) {
          seq.push(drawAxes, function insideTickLabelsAutorange(gd2) {
            var insideTickLabelsUpdaterange = gd2._fullLayout._insideTickLabelsUpdaterange;
            if (insideTickLabelsUpdaterange) {
              gd2._fullLayout._insideTickLabelsUpdaterange = void 0;
              return relayout(gd2, insideTickLabelsUpdaterange).then(function() {
                Axes.saveRangeInitial(gd2, true);
              });
            }
          });
        }
        seq.push(
          subroutines.drawData,
          subroutines.finalDraw,
          initInteractions,
          Plots.addLinks,
          Plots.rehover,
          Plots.redrag,
          Plots.reselect,
          // TODO: doAutoMargin is only needed here for axis automargin, which
          // happens outside of marginPushers where all the other automargins are
          // calculated. Would be much better to separate margin calculations from
          // component drawing - see https://github.com/plotly/plotly.js/issues/2704
          Plots.doAutoMargin,
          Plots.previousPromises
        );
        var plotDone = Lib.syncOrAsync(seq, gd);
        if (!plotDone || !plotDone.then) plotDone = Promise.resolve();
        return plotDone.then(function() {
          emitAfterPlot(gd);
          return gd;
        });
      }
      function emitAfterPlot(gd) {
        var fullLayout = gd._fullLayout;
        if (fullLayout._redrawFromAutoMarginCount) {
          fullLayout._redrawFromAutoMarginCount--;
        } else {
          gd.emit("plotly_afterplot");
        }
      }
      function setPlotConfig(obj) {
        return Lib.extendFlat(dfltConfig, obj);
      }
      function setBackground(gd, bgColor) {
        try {
          gd._fullLayout._paper.style("background", bgColor);
        } catch (e) {
          Lib.error(e);
        }
      }
      function opaqueSetBackground(gd, bgColor) {
        var blend = Color2.combine(bgColor, "white");
        setBackground(gd, blend);
      }
      function setPlotContext(gd, config) {
        if (!gd._context) {
          gd._context = Lib.extendDeep({}, dfltConfig);
          var base = d3.select("base");
          gd._context._baseUrl = base.size() && base.attr("href") ? window.location.href.split("#")[0] : "";
        }
        var context = gd._context;
        var i, keys, key;
        if (config) {
          keys = Object.keys(config);
          for (i = 0; i < keys.length; i++) {
            key = keys[i];
            if (key === "editable" || key === "edits") continue;
            if (key in context) {
              if (key === "setBackground" && config[key] === "opaque") {
                context[key] = opaqueSetBackground;
              } else {
                context[key] = config[key];
              }
            }
          }
          var editable = config.editable;
          if (editable !== void 0) {
            context.editable = editable;
            keys = Object.keys(context.edits);
            for (i = 0; i < keys.length; i++) {
              context.edits[keys[i]] = editable;
            }
          }
          if (config.edits) {
            keys = Object.keys(config.edits);
            for (i = 0; i < keys.length; i++) {
              key = keys[i];
              if (key in context.edits) {
                context.edits[key] = config.edits[key];
              }
            }
          }
          context._exportedPlot = config._exportedPlot;
        }
        if (context.staticPlot) {
          context.editable = false;
          context.edits = {};
          context.autosizable = false;
          context.scrollZoom = false;
          context.doubleClick = false;
          context.showTips = false;
          context.showLink = false;
          context.displayModeBar = false;
        }
        if (context.displayModeBar === "hover" && !hasHover) {
          context.displayModeBar = true;
        }
        if (context.setBackground === "transparent" || typeof context.setBackground !== "function") {
          context.setBackground = setBackground;
        }
        context._hasZeroHeight = context._hasZeroHeight || gd.clientHeight === 0;
        context._hasZeroWidth = context._hasZeroWidth || gd.clientWidth === 0;
        var szIn = context.scrollZoom;
        var szOut = context._scrollZoom = {};
        if (szIn === true) {
          szOut.cartesian = 1;
          szOut.gl3d = 1;
          szOut.geo = 1;
          szOut.mapbox = 1;
          szOut.map = 1;
        } else if (typeof szIn === "string") {
          var parts = szIn.split("+");
          for (i = 0; i < parts.length; i++) {
            szOut[parts[i]] = 1;
          }
        } else if (szIn !== false) {
          szOut.gl3d = 1;
          szOut.geo = 1;
          szOut.mapbox = 1;
          szOut.map = 1;
        }
      }
      function redraw(gd) {
        gd = Lib.getGraphDiv(gd);
        if (!Lib.isPlotDiv(gd)) {
          throw new Error("This element is not a Plotly plot: " + gd);
        }
        helpers.cleanData(gd.data);
        helpers.cleanLayout(gd.layout);
        gd.calcdata = void 0;
        return exports._doPlot(gd).then(function() {
          gd.emit("plotly_redraw");
          return gd;
        });
      }
      function newPlot(gd, data, layout, config) {
        gd = Lib.getGraphDiv(gd);
        Plots.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {});
        Plots.purge(gd);
        return exports._doPlot(gd, data, layout, config);
      }
      function positivifyIndices(indices, maxIndex) {
        var parentLength = maxIndex + 1;
        var positiveIndices = [];
        var i;
        var index;
        for (i = 0; i < indices.length; i++) {
          index = indices[i];
          if (index < 0) {
            positiveIndices.push(parentLength + index);
          } else {
            positiveIndices.push(index);
          }
        }
        return positiveIndices;
      }
      function assertIndexArray(gd, indices, arrayName) {
        var i, index;
        for (i = 0; i < indices.length; i++) {
          index = indices[i];
          if (index !== parseInt(index, 10)) {
            throw new Error("all values in " + arrayName + " must be integers");
          }
          if (index >= gd.data.length || index < -gd.data.length) {
            throw new Error(arrayName + " must be valid indices for gd.data.");
          }
          if (indices.indexOf(index, i + 1) > -1 || index >= 0 && indices.indexOf(-gd.data.length + index) > -1 || index < 0 && indices.indexOf(gd.data.length + index) > -1) {
            throw new Error("each index in " + arrayName + " must be unique.");
          }
        }
      }
      function checkMoveTracesArgs(gd, currentIndices, newIndices) {
        if (!Array.isArray(gd.data)) {
          throw new Error("gd.data must be an array.");
        }
        if (typeof currentIndices === "undefined") {
          throw new Error("currentIndices is a required argument.");
        } else if (!Array.isArray(currentIndices)) {
          currentIndices = [currentIndices];
        }
        assertIndexArray(gd, currentIndices, "currentIndices");
        if (typeof newIndices !== "undefined" && !Array.isArray(newIndices)) {
          newIndices = [newIndices];
        }
        if (typeof newIndices !== "undefined") {
          assertIndexArray(gd, newIndices, "newIndices");
        }
        if (typeof newIndices !== "undefined" && currentIndices.length !== newIndices.length) {
          throw new Error("current and new indices must be of equal length.");
        }
      }
      function checkAddTracesArgs(gd, traces, newIndices) {
        var i, value;
        if (!Array.isArray(gd.data)) {
          throw new Error("gd.data must be an array.");
        }
        if (typeof traces === "undefined") {
          throw new Error("traces must be defined.");
        }
        if (!Array.isArray(traces)) {
          traces = [traces];
        }
        for (i = 0; i < traces.length; i++) {
          value = traces[i];
          if (typeof value !== "object" || Array.isArray(value) || value === null) {
            throw new Error("all values in traces array must be non-array objects");
          }
        }
        if (typeof newIndices !== "undefined" && !Array.isArray(newIndices)) {
          newIndices = [newIndices];
        }
        if (typeof newIndices !== "undefined" && newIndices.length !== traces.length) {
          throw new Error("if indices is specified, traces.length must equal indices.length");
        }
      }
      function assertExtendTracesArgs(gd, update2, indices, maxPoints) {
        var maxPointsIsObject = Lib.isPlainObject(maxPoints);
        if (!Array.isArray(gd.data)) {
          throw new Error("gd.data must be an array");
        }
        if (!Lib.isPlainObject(update2)) {
          throw new Error("update must be a key:value object");
        }
        if (typeof indices === "undefined") {
          throw new Error("indices must be an integer or array of integers");
        }
        assertIndexArray(gd, indices, "indices");
        for (var key in update2) {
          if (!Array.isArray(update2[key]) || update2[key].length !== indices.length) {
            throw new Error("attribute " + key + " must be an array of length equal to indices array length");
          }
          if (maxPointsIsObject && (!(key in maxPoints) || !Array.isArray(maxPoints[key]) || maxPoints[key].length !== update2[key].length)) {
            throw new Error(
              "when maxPoints is set as a key:value object it must contain a 1:1 correspondence with the keys and number of traces in the update object"
            );
          }
        }
      }
      function getExtendProperties(gd, update2, indices, maxPoints) {
        var maxPointsIsObject = Lib.isPlainObject(maxPoints);
        var updateProps = [];
        var trace, target, prop, insert, maxp;
        if (!Array.isArray(indices)) indices = [indices];
        indices = positivifyIndices(indices, gd.data.length - 1);
        for (var key in update2) {
          for (var j = 0; j < indices.length; j++) {
            trace = gd.data[indices[j]];
            prop = nestedProperty(trace, key);
            target = prop.get();
            insert = update2[key][j];
            if (!Lib.isArrayOrTypedArray(insert)) {
              throw new Error("attribute: " + key + " index: " + j + " must be an array");
            }
            if (!Lib.isArrayOrTypedArray(target)) {
              throw new Error("cannot extend missing or non-array attribute: " + key);
            }
            if (target.constructor !== insert.constructor) {
              throw new Error("cannot extend array with an array of a different type: " + key);
            }
            maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;
            if (!isNumeric(maxp)) maxp = -1;
            updateProps.push({
              prop,
              target,
              insert,
              maxp: Math.floor(maxp)
            });
          }
        }
        return updateProps;
      }
      function spliceTraces(gd, update2, indices, maxPoints, updateArray) {
        assertExtendTracesArgs(gd, update2, indices, maxPoints);
        var updateProps = getExtendProperties(gd, update2, indices, maxPoints);
        var undoUpdate = {};
        var undoPoints = {};
        for (var i = 0; i < updateProps.length; i++) {
          var prop = updateProps[i].prop;
          var maxp = updateProps[i].maxp;
          var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp);
          prop.set(out[0]);
          if (!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
          undoUpdate[prop.astr].push(out[1]);
          if (!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
          undoPoints[prop.astr].push(updateProps[i].target.length);
        }
        return { update: undoUpdate, maxPoints: undoPoints };
      }
      function concatTypedArray(arr0, arr1) {
        var arr2 = new arr0.constructor(arr0.length + arr1.length);
        arr2.set(arr0);
        arr2.set(arr1, arr0.length);
        return arr2;
      }
      function extendTraces(gd, update2, indices, maxPoints) {
        gd = Lib.getGraphDiv(gd);
        function updateArray(target, insert, maxp) {
          var newArray, remainder;
          if (Lib.isTypedArray(target)) {
            if (maxp < 0) {
              var none = new target.constructor(0);
              var both = concatTypedArray(target, insert);
              if (maxp < 0) {
                newArray = both;
                remainder = none;
              } else {
                newArray = none;
                remainder = both;
              }
            } else {
              newArray = new target.constructor(maxp);
              remainder = new target.constructor(target.length + insert.length - maxp);
              if (maxp === insert.length) {
                newArray.set(insert);
                remainder.set(target);
              } else if (maxp < insert.length) {
                var numberOfItemsFromInsert = insert.length - maxp;
                newArray.set(insert.subarray(numberOfItemsFromInsert));
                remainder.set(target);
                remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length);
              } else {
                var numberOfItemsFromTarget = maxp - insert.length;
                var targetBegin = target.length - numberOfItemsFromTarget;
                newArray.set(target.subarray(targetBegin));
                newArray.set(insert, numberOfItemsFromTarget);
                remainder.set(target.subarray(0, targetBegin));
              }
            }
          } else {
            newArray = target.concat(insert);
            remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(0, newArray.length - maxp) : [];
          }
          return [newArray, remainder];
        }
        var undo = spliceTraces(gd, update2, indices, maxPoints, updateArray);
        var promise = exports.redraw(gd);
        var undoArgs = [gd, undo.update, indices, undo.maxPoints];
        Queue.add(gd, exports.prependTraces, undoArgs, extendTraces, arguments);
        return promise;
      }
      function prependTraces(gd, update2, indices, maxPoints) {
        gd = Lib.getGraphDiv(gd);
        function updateArray(target, insert, maxp) {
          var newArray, remainder;
          if (Lib.isTypedArray(target)) {
            if (maxp <= 0) {
              var none = new target.constructor(0);
              var both = concatTypedArray(insert, target);
              if (maxp < 0) {
                newArray = both;
                remainder = none;
              } else {
                newArray = none;
                remainder = both;
              }
            } else {
              newArray = new target.constructor(maxp);
              remainder = new target.constructor(target.length + insert.length - maxp);
              if (maxp === insert.length) {
                newArray.set(insert);
                remainder.set(target);
              } else if (maxp < insert.length) {
                var numberOfItemsFromInsert = insert.length - maxp;
                newArray.set(insert.subarray(0, numberOfItemsFromInsert));
                remainder.set(insert.subarray(numberOfItemsFromInsert));
                remainder.set(target, numberOfItemsFromInsert);
              } else {
                var numberOfItemsFromTarget = maxp - insert.length;
                newArray.set(insert);
                newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length);
                remainder.set(target.subarray(numberOfItemsFromTarget));
              }
            }
          } else {
            newArray = insert.concat(target);
            remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(maxp, newArray.length) : [];
          }
          return [newArray, remainder];
        }
        var undo = spliceTraces(gd, update2, indices, maxPoints, updateArray);
        var promise = exports.redraw(gd);
        var undoArgs = [gd, undo.update, indices, undo.maxPoints];
        Queue.add(gd, exports.extendTraces, undoArgs, prependTraces, arguments);
        return promise;
      }
      function addTraces(gd, traces, newIndices) {
        gd = Lib.getGraphDiv(gd);
        var currentIndices = [];
        var undoFunc = exports.deleteTraces;
        var redoFunc = addTraces;
        var undoArgs = [gd, currentIndices];
        var redoArgs = [gd, traces];
        var i;
        var promise;
        checkAddTracesArgs(gd, traces, newIndices);
        if (!Array.isArray(traces)) {
          traces = [traces];
        }
        traces = traces.map(function(trace) {
          return Lib.extendFlat({}, trace);
        });
        helpers.cleanData(traces);
        for (i = 0; i < traces.length; i++) {
          gd.data.push(traces[i]);
        }
        for (i = 0; i < traces.length; i++) {
          currentIndices.push(-traces.length + i);
        }
        if (typeof newIndices === "undefined") {
          promise = exports.redraw(gd);
          Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
          return promise;
        }
        if (!Array.isArray(newIndices)) {
          newIndices = [newIndices];
        }
        try {
          checkMoveTracesArgs(gd, currentIndices, newIndices);
        } catch (error) {
          gd.data.splice(gd.data.length - traces.length, traces.length);
          throw error;
        }
        Queue.startSequence(gd);
        Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        promise = exports.moveTraces(gd, currentIndices, newIndices);
        Queue.stopSequence(gd);
        return promise;
      }
      function deleteTraces(gd, indices) {
        gd = Lib.getGraphDiv(gd);
        var traces = [];
        var undoFunc = exports.addTraces;
        var redoFunc = deleteTraces;
        var undoArgs = [gd, traces, indices];
        var redoArgs = [gd, indices];
        var i;
        var deletedTrace;
        if (typeof indices === "undefined") {
          throw new Error("indices must be an integer or array of integers.");
        } else if (!Array.isArray(indices)) {
          indices = [indices];
        }
        assertIndexArray(gd, indices, "indices");
        indices = positivifyIndices(indices, gd.data.length - 1);
        indices.sort(Lib.sorterDes);
        for (i = 0; i < indices.length; i += 1) {
          deletedTrace = gd.data.splice(indices[i], 1)[0];
          traces.push(deletedTrace);
        }
        var promise = exports.redraw(gd);
        Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        return promise;
      }
      function moveTraces(gd, currentIndices, newIndices) {
        gd = Lib.getGraphDiv(gd);
        var newData = [];
        var movingTraceMap = [];
        var undoFunc = moveTraces;
        var redoFunc = moveTraces;
        var undoArgs = [gd, newIndices, currentIndices];
        var redoArgs = [gd, currentIndices, newIndices];
        var i;
        checkMoveTracesArgs(gd, currentIndices, newIndices);
        currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices];
        if (typeof newIndices === "undefined") {
          newIndices = [];
          for (i = 0; i < currentIndices.length; i++) {
            newIndices.push(-currentIndices.length + i);
          }
        }
        newIndices = Array.isArray(newIndices) ? newIndices : [newIndices];
        currentIndices = positivifyIndices(currentIndices, gd.data.length - 1);
        newIndices = positivifyIndices(newIndices, gd.data.length - 1);
        for (i = 0; i < gd.data.length; i++) {
          if (currentIndices.indexOf(i) === -1) {
            newData.push(gd.data[i]);
          }
        }
        for (i = 0; i < currentIndices.length; i++) {
          movingTraceMap.push({ newIndex: newIndices[i], trace: gd.data[currentIndices[i]] });
        }
        movingTraceMap.sort(function(a, b) {
          return a.newIndex - b.newIndex;
        });
        for (i = 0; i < movingTraceMap.length; i += 1) {
          newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace);
        }
        gd.data = newData;
        var promise = exports.redraw(gd);
        Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        return promise;
      }
      function restyle(gd, astr, val, _traces) {
        gd = Lib.getGraphDiv(gd);
        helpers.clearPromiseQueue(gd);
        var aobj = {};
        if (typeof astr === "string") aobj[astr] = val;
        else if (Lib.isPlainObject(astr)) {
          aobj = Lib.extendFlat({}, astr);
          if (_traces === void 0) _traces = val;
        } else {
          Lib.warn("Restyle fail.", astr, val, _traces);
          return Promise.reject();
        }
        if (Object.keys(aobj).length) gd.changed = true;
        var traces = helpers.coerceTraceIndices(gd, _traces);
        var specs = _restyle(gd, aobj, traces);
        var flags = specs.flags;
        if (flags.calc) gd.calcdata = void 0;
        if (flags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, {});
        var seq = [];
        if (flags.fullReplot) {
          seq.push(exports._doPlot);
        } else {
          seq.push(Plots.previousPromises);
          Plots.supplyDefaults(gd);
          if (flags.markerSize) {
            Plots.doCalcdata(gd);
            addAxRangeSequence(seq);
          }
          if (flags.style) seq.push(subroutines.doTraceStyle);
          if (flags.colorbars) seq.push(subroutines.doColorBars);
          seq.push(emitAfterPlot);
        }
        seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
        Queue.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces]);
        var plotDone = Lib.syncOrAsync(seq, gd);
        if (!plotDone || !plotDone.then) plotDone = Promise.resolve();
        return plotDone.then(function() {
          gd.emit("plotly_restyle", specs.eventData);
          return gd;
        });
      }
      function undefinedToNull(val) {
        if (val === void 0) return null;
        return val;
      }
      function makeNP(preGUI, guiEditFlag) {
        if (!guiEditFlag) return nestedProperty;
        return function(container, attr, prefix) {
          var np = nestedProperty(container, attr);
          var npSet = np.set;
          np.set = function(val) {
            var fullAttr = (prefix || "") + attr;
            storeCurrent(fullAttr, np.get(), val, preGUI);
            npSet(val);
          };
          return np;
        };
      }
      function storeCurrent(attr, val, newVal, preGUI) {
        if (Array.isArray(val) || Array.isArray(newVal)) {
          var arrayVal = Array.isArray(val) ? val : [];
          var arrayNew = Array.isArray(newVal) ? newVal : [];
          var maxLen = Math.max(arrayVal.length, arrayNew.length);
          for (var i = 0; i < maxLen; i++) {
            storeCurrent(attr + "[" + i + "]", arrayVal[i], arrayNew[i], preGUI);
          }
        } else if (Lib.isPlainObject(val) || Lib.isPlainObject(newVal)) {
          var objVal = Lib.isPlainObject(val) ? val : {};
          var objNew = Lib.isPlainObject(newVal) ? newVal : {};
          var objBoth = Lib.extendFlat({}, objVal, objNew);
          for (var key in objBoth) {
            storeCurrent(attr + "." + key, objVal[key], objNew[key], preGUI);
          }
        } else if (preGUI[attr] === void 0) {
          preGUI[attr] = undefinedToNull(val);
        }
      }
      function _storeDirectGUIEdit(container, preGUI, edits) {
        for (var attr in edits) {
          var np = nestedProperty(container, attr);
          storeCurrent(attr, np.get(), edits[attr], preGUI);
        }
      }
      function _restyle(gd, aobj, traces) {
        var fullLayout = gd._fullLayout;
        var fullData = gd._fullData;
        var data = gd.data;
        var guiEditFlag = fullLayout._guiEditing;
        var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
        var eventData = Lib.extendDeepAll({}, aobj);
        var i;
        var flags = editTypes.traceFlags();
        var redoit = {};
        var undoit = {};
        var axlist;
        function a0() {
          return traces.map(function() {
            return void 0;
          });
        }
        function addToAxlist(axid) {
          var axName = Axes.id2name(axid);
          if (axlist.indexOf(axName) === -1) axlist.push(axName);
        }
        function autorangeAttr(axName) {
          return "LAYOUT" + axName + ".autorange";
        }
        function rangeAttr(axName) {
          return "LAYOUT" + axName + ".range";
        }
        function getFullTrace(traceIndex) {
          for (var j = traceIndex; j < fullData.length; j++) {
            if (fullData[j]._input === data[traceIndex]) return fullData[j];
          }
        }
        function doextra(attr, val, i2) {
          if (Array.isArray(attr)) {
            attr.forEach(function(a) {
              doextra(a, val, i2);
            });
            return;
          }
          if (attr in aobj || helpers.hasParent(aobj, attr)) return;
          var extraparam;
          if (attr.slice(0, 6) === "LAYOUT") {
            extraparam = layoutNP(gd.layout, attr.replace("LAYOUT", ""));
          } else {
            var tracei = traces[i2];
            var preGUI2 = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid];
            extraparam = makeNP(preGUI2, guiEditFlag)(data[tracei], attr);
          }
          if (!(attr in undoit)) {
            undoit[attr] = a0();
          }
          if (undoit[attr][i2] === void 0) {
            undoit[attr][i2] = undefinedToNull(extraparam.get());
          }
          if (val !== void 0) {
            extraparam.set(val);
          }
        }
        function allBins(binAttr) {
          return function(j) {
            return fullData[j][binAttr];
          };
        }
        function arrayBins(binAttr) {
          return function(vij, j) {
            return vij === false ? fullData[traces[j]][binAttr] : null;
          };
        }
        for (var ai in aobj) {
          if (helpers.hasParent(aobj, ai)) {
            throw new Error("cannot set " + ai + " and a parent attribute simultaneously");
          }
          var vi = aobj[ai];
          var cont;
          var contFull;
          var param;
          var oldVal;
          var newVal;
          var valObject;
          if (ai === "autobinx" || ai === "autobiny") {
            ai = ai.charAt(ai.length - 1) + "bins";
            if (Array.isArray(vi)) vi = vi.map(arrayBins(ai));
            else if (vi === false) vi = traces.map(allBins(ai));
            else vi = null;
          }
          redoit[ai] = vi;
          if (ai.slice(0, 6) === "LAYOUT") {
            param = layoutNP(gd.layout, ai.replace("LAYOUT", ""));
            undoit[ai] = [undefinedToNull(param.get())];
            param.set(Array.isArray(vi) ? vi[0] : vi);
            flags.calc = true;
            continue;
          }
          undoit[ai] = a0();
          for (i = 0; i < traces.length; i++) {
            cont = data[traces[i]];
            contFull = getFullTrace(traces[i]);
            var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid];
            param = makeNP(preGUI, guiEditFlag)(cont, ai);
            oldVal = param.get();
            newVal = Array.isArray(vi) ? vi[i % vi.length] : vi;
            if (newVal === void 0) continue;
            var finalPart = param.parts[param.parts.length - 1];
            var prefix = ai.slice(0, ai.length - finalPart.length - 1);
            var prefixDot = prefix ? prefix + "." : "";
            var innerContFull = prefix ? nestedProperty(contFull, prefix).get() : contFull;
            valObject = PlotSchema.getTraceValObject(contFull, param.parts);
            if (valObject && valObject.impliedEdits && newVal !== null) {
              for (var impliedKey in valObject.impliedEdits) {
                doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i);
              }
            } else if ((finalPart === "thicknessmode" || finalPart === "lenmode") && oldVal !== newVal && (newVal === "fraction" || newVal === "pixels") && innerContFull) {
              var gs = fullLayout._size;
              var orient = innerContFull.orient;
              var topOrBottom = orient === "top" || orient === "bottom";
              if (finalPart === "thicknessmode") {
                var thicknorm = topOrBottom ? gs.h : gs.w;
                doextra(
                  prefixDot + "thickness",
                  innerContFull.thickness * (newVal === "fraction" ? 1 / thicknorm : thicknorm),
                  i
                );
              } else {
                var lennorm = topOrBottom ? gs.w : gs.h;
                doextra(prefixDot + "len", innerContFull.len * (newVal === "fraction" ? 1 / lennorm : lennorm), i);
              }
            } else if (ai === "type" && (newVal === "pie" !== (oldVal === "pie") || newVal === "funnelarea" !== (oldVal === "funnelarea"))) {
              var labelsTo = "x";
              var valuesTo = "y";
              if ((newVal === "bar" || oldVal === "bar") && cont.orientation === "h") {
                labelsTo = "y";
                valuesTo = "x";
              }
              Lib.swapAttrs(cont, ["?", "?src"], "labels", labelsTo);
              Lib.swapAttrs(cont, ["d?", "?0"], "label", labelsTo);
              Lib.swapAttrs(cont, ["?", "?src"], "values", valuesTo);
              if (oldVal === "pie" || oldVal === "funnelarea") {
                nestedProperty(cont, "marker.color").set(nestedProperty(cont, "marker.colors").get());
                fullLayout._pielayer.selectAll("g.trace").remove();
              } else if (Registry.traceIs(cont, "cartesian")) {
                nestedProperty(cont, "marker.colors").set(nestedProperty(cont, "marker.color").get());
              }
            }
            undoit[ai][i] = undefinedToNull(oldVal);
            var swapAttrs = ["swapxy", "swapxyaxes", "orientation", "orientationaxes"];
            if (swapAttrs.indexOf(ai) !== -1) {
              if (ai === "orientation") {
                param.set(newVal);
                var defaultOrientation = cont.x && !cont.y ? "h" : "v";
                if ((param.get() || defaultOrientation) === contFull.orientation) {
                  continue;
                }
              } else if (ai === "orientationaxes") {
                cont.orientation = { v: "h", h: "v" }[contFull.orientation];
              }
              helpers.swapXYData(cont);
              flags.calc = flags.clearAxisTypes = true;
            } else if (Plots.dataArrayContainers.indexOf(param.parts[0]) !== -1) {
              helpers.manageArrayContainers(param, newVal, undoit);
              flags.calc = true;
            } else {
              if (valObject) {
                if (valObject.arrayOk && !Registry.traceIs(contFull, "regl") && (Lib.isArrayOrTypedArray(newVal) || Lib.isArrayOrTypedArray(oldVal))) {
                  flags.calc = true;
                } else editTypes.update(flags, valObject);
              } else {
                flags.calc = true;
              }
              param.set(newVal);
            }
          }
          if (["swapxyaxes", "orientationaxes"].indexOf(ai) !== -1) {
            Axes.swap(gd, traces);
          }
          if (ai === "orientationaxes") {
            var hovermode = nestedProperty(gd.layout, "hovermode");
            var h = hovermode.get();
            if (h === "x") {
              hovermode.set("y");
            } else if (h === "y") {
              hovermode.set("x");
            } else if (h === "x unified") {
              hovermode.set("y unified");
            } else if (h === "y unified") {
              hovermode.set("x unified");
            }
          }
          if (["orientation", "type"].indexOf(ai) !== -1) {
            axlist = [];
            for (i = 0; i < traces.length; i++) {
              var trace = data[traces[i]];
              if (Registry.traceIs(trace, "cartesian")) {
                addToAxlist(trace.xaxis || "x");
                addToAxlist(trace.yaxis || "y");
              }
            }
            doextra(axlist.map(autorangeAttr), true, 0);
            doextra(axlist.map(rangeAttr), [0, 1], 0);
          }
        }
        if (flags.calc || flags.plot) {
          flags.fullReplot = true;
        }
        return {
          flags,
          undoit,
          redoit,
          traces,
          eventData: Lib.extendDeepNoArrays([], [eventData, traces])
        };
      }
      function relayout(gd, astr, val) {
        gd = Lib.getGraphDiv(gd);
        helpers.clearPromiseQueue(gd);
        var aobj = {};
        if (typeof astr === "string") {
          aobj[astr] = val;
        } else if (Lib.isPlainObject(astr)) {
          aobj = Lib.extendFlat({}, astr);
        } else {
          Lib.warn("Relayout fail.", astr, val);
          return Promise.reject();
        }
        if (Object.keys(aobj).length) gd.changed = true;
        var specs = _relayout(gd, aobj);
        var flags = specs.flags;
        if (flags.calc) gd.calcdata = void 0;
        var seq = [Plots.previousPromises];
        if (flags.layoutReplot) {
          seq.push(subroutines.layoutReplot);
        } else if (Object.keys(aobj).length) {
          axRangeSupplyDefaultsByPass(gd, flags, specs) || Plots.supplyDefaults(gd);
          if (flags.legend) seq.push(subroutines.doLegend);
          if (flags.layoutstyle) seq.push(subroutines.layoutStyles);
          if (flags.axrange) addAxRangeSequence(seq, specs.rangesAltered);
          if (flags.ticks) seq.push(subroutines.doTicksRelayout);
          if (flags.modebar) seq.push(subroutines.doModeBar);
          if (flags.camera) seq.push(subroutines.doCamera);
          if (flags.colorbars) seq.push(subroutines.doColorBars);
          seq.push(emitAfterPlot);
        }
        seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
        Queue.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit]);
        var plotDone = Lib.syncOrAsync(seq, gd);
        if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
        return plotDone.then(function() {
          gd.emit("plotly_relayout", specs.eventData);
          return gd;
        });
      }
      function axRangeSupplyDefaultsByPass(gd, flags, specs) {
        var fullLayout = gd._fullLayout;
        if (!flags.axrange) return false;
        for (var k in flags) {
          if (k !== "axrange" && flags[k]) return false;
        }
        var axIn, axOut;
        var coerce = function(attr, dflt) {
          return Lib.coerce(axIn, axOut, cartesianLayoutAttributes, attr, dflt);
        };
        var options = {};
        for (var axId in specs.rangesAltered) {
          var axName = Axes.id2name(axId);
          axIn = gd.layout[axName];
          axOut = fullLayout[axName];
          handleRangeDefaults(axIn, axOut, coerce, options);
          if (axOut._matchGroup) {
            for (var axId2 in axOut._matchGroup) {
              if (axId2 !== axId) {
                var ax2 = fullLayout[Axes.id2name(axId2)];
                ax2.autorange = axOut.autorange;
                ax2.range = axOut.range.slice();
                ax2._input.range = axOut.range.slice();
              }
            }
          }
        }
        return true;
      }
      function addAxRangeSequence(seq, rangesAltered) {
        var drawAxes = rangesAltered ? function(gd) {
          var axIds = [];
          var skipTitle = true;
          for (var id in rangesAltered) {
            var ax = Axes.getFromId(gd, id);
            axIds.push(id);
            if ((ax.ticklabelposition || "").indexOf("inside") !== -1) {
              if (ax._anchorAxis) {
                axIds.push(ax._anchorAxis._id);
              }
            }
            if (ax._matchGroup) {
              for (var id2 in ax._matchGroup) {
                if (!rangesAltered[id2]) {
                  axIds.push(id2);
                }
              }
            }
          }
          return Axes.draw(gd, axIds, { skipTitle });
        } : function(gd) {
          return Axes.draw(gd, "redraw");
        };
        seq.push(
          clearOutline,
          subroutines.doAutoRangeAndConstraints,
          drawAxes,
          subroutines.drawData,
          subroutines.finalDraw
        );
      }
      var AX_RANGE_RE = /^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/;
      var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/;
      var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;
      function _relayout(gd, aobj) {
        var layout = gd.layout;
        var fullLayout = gd._fullLayout;
        var guiEditFlag = fullLayout._guiEditing;
        var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
        var keys = Object.keys(aobj);
        var axes = Axes.list(gd);
        var eventData = Lib.extendDeepAll({}, aobj);
        var arrayEdits = {};
        var arrayStr, i, j;
        keys = Object.keys(aobj);
        for (i = 0; i < keys.length; i++) {
          if (keys[i].indexOf("allaxes") === 0) {
            for (j = 0; j < axes.length; j++) {
              var scene = axes[j]._id.slice(1);
              var axisAttr = scene.indexOf("scene") !== -1 ? scene + "." : "";
              var newkey = keys[i].replace("allaxes", axisAttr + axes[j]._name);
              if (!aobj[newkey]) aobj[newkey] = aobj[keys[i]];
            }
            delete aobj[keys[i]];
          }
        }
        var flags = editTypes.layoutFlags();
        var redoit = {};
        var undoit = {};
        function doextra(attr, val) {
          if (Array.isArray(attr)) {
            attr.forEach(function(a) {
              doextra(a, val);
            });
            return;
          }
          if (attr in aobj || helpers.hasParent(aobj, attr)) return;
          var p2 = layoutNP(layout, attr);
          if (!(attr in undoit)) {
            undoit[attr] = undefinedToNull(p2.get());
          }
          if (val !== void 0) p2.set(val);
        }
        var rangesAltered = {};
        var ax;
        function recordAlteredAxis(pleafPlus2) {
          var axId2 = Axes.name2id(pleafPlus2.split(".")[0]);
          rangesAltered[axId2] = 1;
          return axId2;
        }
        for (var ai in aobj) {
          if (helpers.hasParent(aobj, ai)) {
            throw new Error("cannot set " + ai + " and a parent attribute simultaneously");
          }
          var p = layoutNP(layout, ai);
          var vi = aobj[ai];
          var plen = p.parts.length;
          var pend = plen - 1;
          while (pend > 0 && typeof p.parts[pend] !== "string") pend--;
          var pleaf = p.parts[pend];
          var pleafPlus = p.parts[pend - 1] + "." + pleaf;
          var ptrunk = p.parts.slice(0, pend).join(".");
          var parentIn = nestedProperty(gd.layout, ptrunk).get();
          var parentFull = nestedProperty(fullLayout, ptrunk).get();
          var vOld = p.get();
          if (vi === void 0) continue;
          redoit[ai] = vi;
          undoit[ai] = pleaf === "reverse" ? vi : undefinedToNull(vOld);
          var valObject = PlotSchema.getLayoutValObject(fullLayout, p.parts);
          if (valObject && valObject.impliedEdits && vi !== null) {
            for (var impliedKey in valObject.impliedEdits) {
              doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]);
            }
          }
          if (["width", "height"].indexOf(ai) !== -1) {
            if (vi) {
              doextra("autosize", null);
              var oppositeAttr = ai === "height" ? "width" : "height";
              doextra(oppositeAttr, fullLayout[oppositeAttr]);
            } else {
              fullLayout[ai] = gd._initialAutoSize[ai];
            }
          } else if (ai === "autosize") {
            doextra("width", vi ? null : fullLayout.width);
            doextra("height", vi ? null : fullLayout.height);
          } else if (pleafPlus.match(AX_RANGE_RE)) {
            recordAlteredAxis(pleafPlus);
            nestedProperty(fullLayout, ptrunk + "._inputRange").set(null);
          } else if (pleafPlus.match(AX_AUTORANGE_RE)) {
            recordAlteredAxis(pleafPlus);
            nestedProperty(fullLayout, ptrunk + "._inputRange").set(null);
            var axFull = nestedProperty(fullLayout, ptrunk).get();
            if (axFull._inputDomain) {
              axFull._input.domain = axFull._inputDomain.slice();
            }
          } else if (pleafPlus.match(AX_DOMAIN_RE)) {
            nestedProperty(fullLayout, ptrunk + "._inputDomain").set(null);
          }
          if (pleaf === "type") {
            ax = parentIn;
            var toLog = parentFull.type === "linear" && vi === "log";
            var fromLog = parentFull.type === "log" && vi === "linear";
            if (toLog || fromLog) {
              if (!ax || !ax.range) {
                doextra(ptrunk + ".autorange", true);
              } else if (!parentFull.autorange) {
                var r0 = ax.range[0];
                var r1 = ax.range[1];
                if (toLog) {
                  if (r0 <= 0 && r1 <= 0) {
                    doextra(ptrunk + ".autorange", true);
                  }
                  if (r0 <= 0) r0 = r1 / 1e6;
                  else if (r1 <= 0) r1 = r0 / 1e6;
                  doextra(ptrunk + ".range[0]", Math.log(r0) / Math.LN10);
                  doextra(ptrunk + ".range[1]", Math.log(r1) / Math.LN10);
                } else {
                  doextra(ptrunk + ".range[0]", Math.pow(10, r0));
                  doextra(ptrunk + ".range[1]", Math.pow(10, r1));
                }
              } else if (toLog) {
                ax.range = ax.range[1] > ax.range[0] ? [1, 2] : [2, 1];
              }
              if (Array.isArray(fullLayout._subplots.polar) && fullLayout._subplots.polar.length && fullLayout[p.parts[0]] && p.parts[1] === "radialaxis") {
                delete fullLayout[p.parts[0]]._subplot.viewInitial["radialaxis.range"];
              }
              Registry.getComponentMethod("annotations", "convertCoords")(gd, parentFull, vi, doextra);
              Registry.getComponentMethod("images", "convertCoords")(gd, parentFull, vi, doextra);
            } else {
              doextra(ptrunk + ".autorange", true);
              doextra(ptrunk + ".range", null);
            }
            nestedProperty(fullLayout, ptrunk + "._inputRange").set(null);
          } else if (pleaf.match(AX_NAME_PATTERN)) {
            var fullProp = nestedProperty(fullLayout, ai).get();
            var newType = (vi || {}).type;
            if (!newType || newType === "-") newType = "linear";
            Registry.getComponentMethod("annotations", "convertCoords")(gd, fullProp, newType, doextra);
            Registry.getComponentMethod("images", "convertCoords")(gd, fullProp, newType, doextra);
          }
          var containerArrayMatch = manageArrays.containerArrayMatch(ai);
          if (containerArrayMatch) {
            arrayStr = containerArrayMatch.array;
            i = containerArrayMatch.index;
            var propStr = containerArrayMatch.property;
            var updateValObject = valObject || { editType: "calc" };
            if (i !== "" && propStr === "") {
              if (manageArrays.isAddVal(vi)) {
                undoit[ai] = null;
              } else if (manageArrays.isRemoveVal(vi)) {
                undoit[ai] = (nestedProperty(layout, arrayStr).get() || [])[i];
              } else {
                Lib.warn("unrecognized full object value", aobj);
              }
            }
            editTypes.update(flags, updateValObject);
            if (!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {};
            var objEdits = arrayEdits[arrayStr][i];
            if (!objEdits) objEdits = arrayEdits[arrayStr][i] = {};
            objEdits[propStr] = vi;
            delete aobj[ai];
          } else if (pleaf === "reverse") {
            if (parentIn.range) parentIn.range.reverse();
            else {
              doextra(ptrunk + ".autorange", true);
              parentIn.range = [1, 0];
            }
            if (parentFull.autorange) flags.calc = true;
            else flags.plot = true;
          } else {
            if (ai === "dragmode" && (vi === false && vOld !== false || vi !== false && vOld === false)) {
              flags.plot = true;
            } else if (fullLayout._has("scatter-like") && fullLayout._has("regl") && ai === "dragmode" && (vi === "lasso" || vi === "select") && !(vOld === "lasso" || vOld === "select")) {
              flags.plot = true;
            } else if (valObject) editTypes.update(flags, valObject);
            else flags.calc = true;
            p.set(vi);
          }
        }
        for (arrayStr in arrayEdits) {
          var finished = manageArrays.applyContainerArrayChanges(
            gd,
            layoutNP(layout, arrayStr),
            arrayEdits[arrayStr],
            flags,
            layoutNP
          );
          if (!finished) flags.plot = true;
        }
        for (var axId in rangesAltered) {
          ax = Axes.getFromId(gd, axId);
          var group = ax && ax._constraintGroup;
          if (group) {
            flags.calc = true;
            for (var groupAxId in group) {
              if (!rangesAltered[groupAxId]) {
                Axes.getFromId(gd, groupAxId)._constraintShrinkable = true;
              }
            }
          }
        }
        if (updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true;
        var shapes = fullLayout.shapes;
        for (i = 0; i < shapes.length; i++) {
          if (shapes[i].showlegend) {
            flags.calc = true;
            break;
          }
        }
        if (flags.plot || flags.calc) {
          flags.layoutReplot = true;
        }
        return {
          flags,
          rangesAltered,
          undoit,
          redoit,
          eventData
        };
      }
      function updateAutosize(gd) {
        var fullLayout = gd._fullLayout;
        var oldWidth = fullLayout.width;
        var oldHeight = fullLayout.height;
        if (gd.layout.autosize) Plots.plotAutoSize(gd, gd.layout, fullLayout);
        return fullLayout.width !== oldWidth || fullLayout.height !== oldHeight;
      }
      function update(gd, traceUpdate, layoutUpdate, _traces) {
        gd = Lib.getGraphDiv(gd);
        helpers.clearPromiseQueue(gd);
        if (!Lib.isPlainObject(traceUpdate)) traceUpdate = {};
        if (!Lib.isPlainObject(layoutUpdate)) layoutUpdate = {};
        if (Object.keys(traceUpdate).length) gd.changed = true;
        if (Object.keys(layoutUpdate).length) gd.changed = true;
        var traces = helpers.coerceTraceIndices(gd, _traces);
        var restyleSpecs = _restyle(gd, Lib.extendFlat({}, traceUpdate), traces);
        var restyleFlags = restyleSpecs.flags;
        var relayoutSpecs = _relayout(gd, Lib.extendFlat({}, layoutUpdate));
        var relayoutFlags = relayoutSpecs.flags;
        if (restyleFlags.calc || relayoutFlags.calc) gd.calcdata = void 0;
        if (restyleFlags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, layoutUpdate);
        var seq = [];
        if (relayoutFlags.layoutReplot) {
          seq.push(subroutines.layoutReplot);
        } else if (restyleFlags.fullReplot) {
          seq.push(exports._doPlot);
        } else {
          seq.push(Plots.previousPromises);
          axRangeSupplyDefaultsByPass(gd, relayoutFlags, relayoutSpecs) || Plots.supplyDefaults(gd);
          if (restyleFlags.style) seq.push(subroutines.doTraceStyle);
          if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines.doColorBars);
          if (relayoutFlags.legend) seq.push(subroutines.doLegend);
          if (relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
          if (relayoutFlags.axrange) addAxRangeSequence(seq, relayoutSpecs.rangesAltered);
          if (relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
          if (relayoutFlags.modebar) seq.push(subroutines.doModeBar);
          if (relayoutFlags.camera) seq.push(subroutines.doCamera);
          seq.push(emitAfterPlot);
        }
        seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
        Queue.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [
          gd,
          restyleSpecs.redoit,
          relayoutSpecs.redoit,
          restyleSpecs.traces
        ]);
        var plotDone = Lib.syncOrAsync(seq, gd);
        if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
        return plotDone.then(function() {
          gd.emit("plotly_update", {
            data: restyleSpecs.eventData,
            layout: relayoutSpecs.eventData
          });
          return gd;
        });
      }
      function guiEdit(func) {
        return function wrappedEdit(gd) {
          gd._fullLayout._guiEditing = true;
          var p = func.apply(null, arguments);
          gd._fullLayout._guiEditing = false;
          return p;
        };
      }
      var layoutUIControlPatterns = [
        { pattern: /^hiddenlabels/, attr: "legend.uirevision" },
        { pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/ },
        // showspikes and modes include those nested inside scenes
        { pattern: /axis\d*\.showspikes$/, attr: "modebar.uirevision" },
        { pattern: /(hover|drag)mode$/, attr: "modebar.uirevision" },
        { pattern: /^(scene\d*)\.camera/ },
        { pattern: /^(geo\d*)\.(projection|center|fitbounds)/ },
        { pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/ },
        { pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/ },
        { pattern: /^(polar\d*\.angularaxis)\.rotation/ },
        { pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/ },
        { pattern: /^(map\d*)\.(center|zoom|bearing|pitch)/ },
        { pattern: /^legend\.(x|y)$/, attr: "editrevision" },
        { pattern: /^(shapes|annotations)/, attr: "editrevision" },
        { pattern: /^title\.text$/, attr: "editrevision" }
      ];
      var traceUIControlPatterns = [
        { pattern: /^selectedpoints$/, attr: "selectionrevision" },
        // "visible" includes trace.transforms[i].styles[j].value.visible
        { pattern: /(^|value\.)visible$/, attr: "legend.uirevision" },
        { pattern: /^dimensions\[\d+\]\.constraintrange/ },
        { pattern: /^node\.(x|y|groups)/ },
        // for Sankey nodes
        { pattern: /^level$/ },
        // for Sunburst, Treemap and Icicle traces
        // below this you must be in editable: true mode
        // TODO: I still put name and title with `trace.uirevision`
        // reasonable or should these be `editrevision`?
        // Also applies to axis titles up in the layout section
        // "name" also includes transform.styles
        { pattern: /(^|value\.)name$/ },
        // including nested colorbar attributes (ie marker.colorbar)
        { pattern: /colorbar\.title\.text$/ },
        { pattern: /colorbar\.(x|y)$/, attr: "editrevision" }
      ];
      function findUIPattern(key, patternSpecs) {
        for (var i = 0; i < patternSpecs.length; i++) {
          var spec = patternSpecs[i];
          var match = key.match(spec.pattern);
          if (match) {
            var head = match[1] || "";
            return { head, tail: key.slice(head.length + 1), attr: spec.attr };
          }
        }
      }
      function getNewRev(revAttr, container) {
        var newRev = nestedProperty(container, revAttr).get();
        if (newRev !== void 0) return newRev;
        var parts = revAttr.split(".");
        parts.pop();
        while (parts.length > 1) {
          parts.pop();
          newRev = nestedProperty(container, parts.join(".") + ".uirevision").get();
          if (newRev !== void 0) return newRev;
        }
        return container.uirevision;
      }
      function getFullTraceIndexFromUid(uid, fullData) {
        for (var i = 0; i < fullData.length; i++) {
          if (fullData[i]._fullInput.uid === uid) return i;
        }
        return -1;
      }
      function getTraceIndexFromUid(uid, data, tracei) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].uid === uid) return i;
        }
        return !data[tracei] || data[tracei].uid ? -1 : tracei;
      }
      function valsMatch(v1, v2) {
        var v1IsObj = Lib.isPlainObject(v1);
        var v1IsArray = Array.isArray(v1);
        if (v1IsObj || v1IsArray) {
          return (v1IsObj && Lib.isPlainObject(v2) || v1IsArray && Array.isArray(v2)) && JSON.stringify(v1) === JSON.stringify(v2);
        }
        return v1 === v2;
      }
      function applyUIRevisions(data, layout, oldFullData, oldFullLayout) {
        var layoutPreGUI = oldFullLayout._preGUI;
        var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal, head, tail;
        var bothInheritAutorange = [];
        var newAutorangeIn = {};
        var newRangeAccepted = {};
        for (key in layoutPreGUI) {
          match = findUIPattern(key, layoutUIControlPatterns);
          if (match) {
            head = match.head;
            tail = match.tail;
            revAttr = match.attr || head + ".uirevision";
            oldRev = nestedProperty(oldFullLayout, revAttr).get();
            newRev = oldRev && getNewRev(revAttr, layout);
            if (newRev && newRev === oldRev) {
              preGUIVal = layoutPreGUI[key];
              if (preGUIVal === null) preGUIVal = void 0;
              newNP = nestedProperty(layout, key);
              newVal = newNP.get();
              if (valsMatch(newVal, preGUIVal)) {
                if (newVal === void 0 && tail === "autorange") {
                  bothInheritAutorange.push(head);
                }
                newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get()));
                continue;
              } else if (tail === "autorange" || tail.slice(0, 6) === "range[") {
                var pre0 = layoutPreGUI[head + ".range[0]"];
                var pre1 = layoutPreGUI[head + ".range[1]"];
                var preAuto = layoutPreGUI[head + ".autorange"];
                if (preAuto || preAuto === null && pre0 === null && pre1 === null) {
                  if (!(head in newAutorangeIn)) {
                    var newContainer = nestedProperty(layout, head).get();
                    newAutorangeIn[head] = newContainer && (newContainer.autorange || newContainer.autorange !== false && (!newContainer.range || newContainer.range.length !== 2));
                  }
                  if (newAutorangeIn[head]) {
                    newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get()));
                    continue;
                  }
                }
              }
            }
          } else {
            Lib.warn("unrecognized GUI edit: " + key);
          }
          delete layoutPreGUI[key];
          if (match && match.tail.slice(0, 6) === "range[") {
            newRangeAccepted[match.head] = 1;
          }
        }
        for (var i = 0; i < bothInheritAutorange.length; i++) {
          var axAttr = bothInheritAutorange[i];
          if (newRangeAccepted[axAttr]) {
            var newAx = nestedProperty(layout, axAttr).get();
            if (newAx) delete newAx.autorange;
          }
        }
        var allTracePreGUI = oldFullLayout._tracePreGUI;
        for (var uid in allTracePreGUI) {
          var tracePreGUI = allTracePreGUI[uid];
          var newTrace = null;
          var fullInput;
          for (key in tracePreGUI) {
            if (!newTrace) {
              var fulli = getFullTraceIndexFromUid(uid, oldFullData);
              if (fulli < 0) {
                delete allTracePreGUI[uid];
                break;
              }
              var fullTrace = oldFullData[fulli];
              fullInput = fullTrace._fullInput;
              var newTracei = getTraceIndexFromUid(uid, data, fullInput.index);
              if (newTracei < 0) {
                delete allTracePreGUI[uid];
                break;
              }
              newTrace = data[newTracei];
            }
            match = findUIPattern(key, traceUIControlPatterns);
            if (match) {
              if (match.attr) {
                oldRev = nestedProperty(oldFullLayout, match.attr).get();
                newRev = oldRev && getNewRev(match.attr, layout);
              } else {
                oldRev = fullInput.uirevision;
                newRev = newTrace.uirevision;
                if (newRev === void 0) newRev = layout.uirevision;
              }
              if (newRev && newRev === oldRev) {
                preGUIVal = tracePreGUI[key];
                if (preGUIVal === null) preGUIVal = void 0;
                newNP = nestedProperty(newTrace, key);
                newVal = newNP.get();
                if (valsMatch(newVal, preGUIVal)) {
                  newNP.set(undefinedToNull(nestedProperty(fullInput, key).get()));
                  continue;
                }
              }
            } else {
              Lib.warn("unrecognized GUI edit: " + key + " in trace uid " + uid);
            }
            delete tracePreGUI[key];
          }
        }
      }
      function react(gd, data, layout, config) {
        var frames, plotDone;
        function addFrames2() {
          return exports.addFrames(gd, frames);
        }
        gd = Lib.getGraphDiv(gd);
        helpers.clearPromiseQueue(gd);
        var oldFullData = gd._fullData;
        var oldFullLayout = gd._fullLayout;
        if (!Lib.isPlotDiv(gd) || !oldFullData || !oldFullLayout) {
          plotDone = exports.newPlot(gd, data, layout, config);
        } else {
          if (Lib.isPlainObject(data)) {
            var obj = data;
            data = obj.data;
            layout = obj.layout;
            config = obj.config;
            frames = obj.frames;
          }
          var configChanged = false;
          if (config) {
            const oldConfig = Lib.extendDeepAll({}, gd._context);
            gd._context = void 0;
            setPlotContext(gd, config);
            configChanged = !helpers.collectionsAreEqual(oldConfig, gd._context);
          }
          if (configChanged) {
            const eventListeners = gd._ev.eventNames().map((name3) => [name3, gd._ev.listeners(name3)]);
            plotDone = exports.newPlot(gd, data, layout, config).then(() => {
              for (const [name3, callbacks] of eventListeners) {
                callbacks.forEach((cb) => gd.on(name3, cb));
              }
              return exports.react(gd, data, layout, config);
            });
          } else {
            gd.data = data || [];
            helpers.cleanData(gd.data);
            gd.layout = layout || {};
            helpers.cleanLayout(gd.layout);
            applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout);
            Plots.supplyDefaults(gd, { skipUpdateCalc: true });
            var newFullData = gd._fullData;
            var newFullLayout = gd._fullLayout;
            var immutable = newFullLayout.datarevision === void 0;
            var transition = newFullLayout.transition;
            var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition);
            var newDataRevision = relayoutFlags.newDataRevision;
            var restyleFlags = diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision);
            if (updateAutosize(gd)) relayoutFlags.layoutReplot = true;
            if (restyleFlags.calc || relayoutFlags.calc) {
              gd.calcdata = void 0;
              var allNames = Object.getOwnPropertyNames(newFullLayout);
              for (var q = 0; q < allNames.length; q++) {
                var name2 = allNames[q];
                var start = name2.substring(0, 5);
                if (start === "xaxis" || start === "yaxis") {
                  var emptyCategories = newFullLayout[name2]._emptyCategories;
                  if (emptyCategories) emptyCategories();
                }
              }
            } else {
              Plots.supplyDefaultsUpdateCalc(gd.calcdata, newFullData);
            }
            var seq = [];
            if (frames) {
              gd._transitionData = {};
              Plots.createTransitionData(gd);
              seq.push(addFrames2);
            }
            if (newFullLayout.transition && (restyleFlags.anim || relayoutFlags.anim)) {
              if (relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
              Plots.doCalcdata(gd);
              subroutines.doAutoRangeAndConstraints(gd);
              seq.push(function() {
                return Plots.transitionFromReact(gd, restyleFlags, relayoutFlags, oldFullLayout);
              });
            } else if (restyleFlags.fullReplot || relayoutFlags.layoutReplot) {
              gd._fullLayout._skipDefaults = true;
              seq.push(exports._doPlot);
            } else {
              for (var componentType in relayoutFlags.arrays) {
                var indices = relayoutFlags.arrays[componentType];
                if (indices.length) {
                  var drawOne = Registry.getComponentMethod(componentType, "drawOne");
                  if (drawOne !== Lib.noop) {
                    for (var i = 0; i < indices.length; i++) {
                      drawOne(gd, indices[i]);
                    }
                  } else {
                    var draw = Registry.getComponentMethod(componentType, "draw");
                    if (draw === Lib.noop) {
                      throw new Error("cannot draw components: " + componentType);
                    }
                    draw(gd);
                  }
                }
              }
              seq.push(Plots.previousPromises);
              if (restyleFlags.style) seq.push(subroutines.doTraceStyle);
              if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines.doColorBars);
              if (relayoutFlags.legend) seq.push(subroutines.doLegend);
              if (relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
              if (relayoutFlags.axrange) addAxRangeSequence(seq);
              if (relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
              if (relayoutFlags.modebar) seq.push(subroutines.doModeBar);
              if (relayoutFlags.camera) seq.push(subroutines.doCamera);
              seq.push(emitAfterPlot);
            }
            seq.push(Plots.rehover, Plots.redrag, Plots.reselect);
            plotDone = Lib.syncOrAsync(seq, gd);
            if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
          }
        }
        return plotDone.then(() => {
          if (!configChanged) gd.emit("plotly_react", { config, data, layout });
          return gd;
        });
      }
      function diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision) {
        var sameTraceLength = oldFullData.length === newFullData.length;
        if (!transition && !sameTraceLength) {
          return {
            fullReplot: true,
            calc: true
          };
        }
        var flags = editTypes.traceFlags();
        flags.arrays = {};
        flags.nChanges = 0;
        flags.nChangesAnim = 0;
        var i, trace;
        function getTraceValObject(parts) {
          var out = PlotSchema.getTraceValObject(trace, parts);
          if (!trace._module.animatable && out.anim) {
            out.anim = false;
          }
          return out;
        }
        var diffOpts = {
          getValObject: getTraceValObject,
          flags,
          immutable,
          transition,
          newDataRevision,
          gd
        };
        var seenUIDs = {};
        for (i = 0; i < oldFullData.length; i++) {
          if (newFullData[i]) {
            trace = newFullData[i]._fullInput;
            if (seenUIDs[trace.uid]) continue;
            seenUIDs[trace.uid] = 1;
            getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts);
          }
        }
        if (flags.calc || flags.plot) {
          flags.fullReplot = true;
        }
        if (transition && flags.nChanges && flags.nChangesAnim) {
          flags.anim = flags.nChanges === flags.nChangesAnim && sameTraceLength ? "all" : "some";
        }
        return flags;
      }
      function diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition) {
        var flags = editTypes.layoutFlags();
        flags.arrays = {};
        flags.rangesAltered = {};
        flags.nChanges = 0;
        flags.nChangesAnim = 0;
        function getLayoutValObject(parts) {
          return PlotSchema.getLayoutValObject(newFullLayout, parts);
        }
        for (var key in newFullLayout) {
          if (!key.startsWith("xaxis") && !key.startsWith("yaxis")) {
            continue;
          }
          if (!oldFullLayout[key]) {
            continue;
          }
          var newDomain = newFullLayout[key].domain;
          var oldDomain = oldFullLayout[key].domain;
          var oldInputDomain = oldFullLayout[key]._inputDomain;
          if (oldFullLayout[key]._inputDomain) {
            if (newDomain[0] === oldInputDomain[0] && newDomain[1] === oldInputDomain[1]) {
              newFullLayout[key].domain = oldFullLayout[key].domain;
            } else if (newDomain[0] !== oldDomain[0] || newDomain[1] !== oldDomain[1]) {
              newFullLayout[key]._inputDomain = null;
            }
          }
        }
        var diffOpts = {
          getValObject: getLayoutValObject,
          flags,
          immutable,
          transition,
          gd
        };
        getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts);
        if (flags.plot || flags.calc) {
          flags.layoutReplot = true;
        }
        if (transition && flags.nChanges && flags.nChangesAnim) {
          flags.anim = flags.nChanges === flags.nChangesAnim ? "all" : "some";
        }
        return flags;
      }
      function getDiffFlags(oldContainer, newContainer, outerparts, opts) {
        var valObject, key, astr;
        var getValObject = opts.getValObject;
        var flags = opts.flags;
        var immutable = opts.immutable;
        var inArray = opts.inArray;
        var arrayIndex = opts.arrayIndex;
        function changed() {
          var editType = valObject.editType;
          if (inArray && editType.indexOf("arraydraw") !== -1) {
            Lib.pushUnique(flags.arrays[inArray], arrayIndex);
            return;
          }
          editTypes.update(flags, valObject);
          if (editType !== "none") {
            flags.nChanges++;
          }
          if (opts.transition && valObject.anim) {
            flags.nChangesAnim++;
          }
          if (AX_RANGE_RE.test(astr) || AX_AUTORANGE_RE.test(astr)) {
            flags.rangesAltered[outerparts[0]] = 1;
          }
          if (key === "datarevision") {
            flags.newDataRevision = 1;
          }
        }
        function valObjectCanBeDataArray(valObject2) {
          return valObject2.valType === "data_array" || valObject2.arrayOk;
        }
        for (key in oldContainer) {
          if (flags.calc && !opts.transition) return;
          var oldVal = oldContainer[key];
          var newVal = newContainer[key];
          var parts = outerparts.concat(key);
          astr = parts.join(".");
          if (key.charAt(0) === "_" || typeof oldVal === "function" || oldVal === newVal) continue;
          if ((key === "tick0" || key === "dtick") && outerparts[0] !== "geo") {
            var tickMode = newContainer.tickmode;
            if (tickMode === "auto" || tickMode === "array" || !tickMode) continue;
          }
          if (key === "range" && newContainer.autorange) continue;
          if ((key === "zmin" || key === "zmax") && newContainer.type === "contourcarpet") continue;
          valObject = getValObject(parts);
          if (!valObject) continue;
          if (valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;
          var valType = valObject.valType;
          var i;
          var canBeDataArray = valObjectCanBeDataArray(valObject);
          var wasArray = Array.isArray(oldVal);
          var nowArray = Array.isArray(newVal);
          if (wasArray && nowArray) {
            var inputKey = "_input_" + key;
            var oldValIn = oldContainer[inputKey];
            var newValIn = newContainer[inputKey];
            if (Array.isArray(oldValIn) && oldValIn === newValIn) continue;
          }
          if (newVal === void 0) {
            if (canBeDataArray && wasArray) flags.calc = true;
            else changed();
          } else if (valObject._isLinkedToArray) {
            var arrayEditIndices = [];
            var extraIndices = false;
            if (!inArray) flags.arrays[key] = arrayEditIndices;
            var minLen = Math.min(oldVal.length, newVal.length);
            var maxLen = Math.max(oldVal.length, newVal.length);
            if (minLen !== maxLen) {
              if (valObject.editType === "arraydraw") {
                extraIndices = true;
              } else {
                changed();
                continue;
              }
            }
            for (i = 0; i < minLen; i++) {
              getDiffFlags(
                oldVal[i],
                newVal[i],
                parts.concat(i),
                // add array indices, but not if we're already in an array
                Lib.extendFlat({ inArray: key, arrayIndex: i }, opts)
              );
            }
            if (extraIndices) {
              for (i = minLen; i < maxLen; i++) {
                arrayEditIndices.push(i);
              }
            }
          } else if (!valType && Lib.isPlainObject(oldVal)) {
            getDiffFlags(oldVal, newVal, parts, opts);
          } else if (canBeDataArray) {
            if (wasArray && nowArray) {
              if (immutable) {
                flags.calc = true;
              }
              if (immutable || opts.newDataRevision) {
                changed();
              }
            } else if (wasArray !== nowArray) {
              flags.calc = true;
            } else changed();
          } else if (wasArray && nowArray) {
            if (oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) {
              changed();
            }
          } else {
            changed();
          }
        }
        for (key in newContainer) {
          if (!(key in oldContainer || key.charAt(0) === "_" || typeof newContainer[key] === "function")) {
            valObject = getValObject(outerparts.concat(key));
            if (valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) {
              flags.calc = true;
              return;
            } else changed();
          }
        }
      }
      function animate(gd, frameOrGroupNameOrFrameList, animationOpts) {
        gd = Lib.getGraphDiv(gd);
        if (!Lib.isPlotDiv(gd)) {
          throw new Error(
            "This element is not a Plotly plot: " + gd + ". It's likely that you've failed to create a plot before animating it. For more details, see https://plotly.com/javascript/animations/"
          );
        }
        var trans = gd._transitionData;
        if (!trans._frameQueue) {
          trans._frameQueue = [];
        }
        animationOpts = Plots.supplyAnimationDefaults(animationOpts);
        var transitionOpts = animationOpts.transition;
        var frameOpts = animationOpts.frame;
        if (trans._frameWaitingCnt === void 0) {
          trans._frameWaitingCnt = 0;
        }
        function getTransitionOpts(i) {
          if (Array.isArray(transitionOpts)) {
            if (i >= transitionOpts.length) {
              return transitionOpts[0];
            } else {
              return transitionOpts[i];
            }
          } else {
            return transitionOpts;
          }
        }
        function getFrameOpts(i) {
          if (Array.isArray(frameOpts)) {
            if (i >= frameOpts.length) {
              return frameOpts[0];
            } else {
              return frameOpts[i];
            }
          } else {
            return frameOpts;
          }
        }
        function callbackOnNthTime(cb, n) {
          var cnt = 0;
          return function() {
            if (cb && ++cnt === n) {
              return cb();
            }
          };
        }
        return new Promise(function(resolve, reject) {
          function discardExistingFrames() {
            if (trans._frameQueue.length === 0) {
              return;
            }
            while (trans._frameQueue.length) {
              var next = trans._frameQueue.pop();
              if (next.onInterrupt) {
                next.onInterrupt();
              }
            }
            gd.emit("plotly_animationinterrupted", []);
          }
          function queueFrames(frameList2) {
            if (frameList2.length === 0) return;
            for (var i2 = 0; i2 < frameList2.length; i2++) {
              var computedFrame;
              if (frameList2[i2].type === "byname") {
                computedFrame = Plots.computeFrame(gd, frameList2[i2].name);
              } else {
                computedFrame = frameList2[i2].data;
              }
              var frameOpts2 = getFrameOpts(i2);
              var transitionOpts2 = getTransitionOpts(i2);
              transitionOpts2.duration = Math.min(transitionOpts2.duration, frameOpts2.duration);
              var nextFrame2 = {
                frame: computedFrame,
                name: frameList2[i2].name,
                frameOpts: frameOpts2,
                transitionOpts: transitionOpts2
              };
              if (i2 === frameList2.length - 1) {
                nextFrame2.onComplete = callbackOnNthTime(resolve, 2);
                nextFrame2.onInterrupt = reject;
              }
              trans._frameQueue.push(nextFrame2);
            }
            if (animationOpts.mode === "immediate") {
              trans._lastFrameAt = -Infinity;
            }
            if (!trans._animationRaf) {
              beginAnimationLoop();
            }
          }
          function stopAnimationLoop() {
            gd.emit("plotly_animated");
            window.cancelAnimationFrame(trans._animationRaf);
            trans._animationRaf = null;
          }
          function nextFrame() {
            if (trans._currentFrame && trans._currentFrame.onComplete) {
              trans._currentFrame.onComplete();
            }
            var newFrame = trans._currentFrame = trans._frameQueue.shift();
            if (newFrame) {
              var stringName = newFrame.name ? newFrame.name.toString() : null;
              gd._fullLayout._currentFrame = stringName;
              trans._lastFrameAt = Date.now();
              trans._timeToNext = newFrame.frameOpts.duration;
              Plots.transition(
                gd,
                newFrame.frame.data,
                newFrame.frame.layout,
                helpers.coerceTraceIndices(gd, newFrame.frame.traces),
                newFrame.frameOpts,
                newFrame.transitionOpts
              ).then(function() {
                if (newFrame.onComplete) {
                  newFrame.onComplete();
                }
              });
              gd.emit("plotly_animatingframe", {
                name: stringName,
                frame: newFrame.frame,
                animation: {
                  frame: newFrame.frameOpts,
                  transition: newFrame.transitionOpts
                }
              });
            } else {
              stopAnimationLoop();
            }
          }
          function beginAnimationLoop() {
            gd.emit("plotly_animating");
            trans._lastFrameAt = -Infinity;
            trans._timeToNext = 0;
            trans._runningTransitions = 0;
            trans._currentFrame = null;
            var doFrame = function() {
              trans._animationRaf = window.requestAnimationFrame(doFrame);
              if (Date.now() - trans._lastFrameAt > trans._timeToNext) {
                nextFrame();
              }
            };
            doFrame();
          }
          var configCounter = 0;
          function setTransitionConfig(frame2) {
            if (Array.isArray(transitionOpts)) {
              if (configCounter >= transitionOpts.length) {
                frame2.transitionOpts = transitionOpts[configCounter];
              } else {
                frame2.transitionOpts = transitionOpts[0];
              }
            } else {
              frame2.transitionOpts = transitionOpts;
            }
            configCounter++;
            return frame2;
          }
          var i, frame;
          var frameList = [];
          var allFrames = frameOrGroupNameOrFrameList === void 0 || frameOrGroupNameOrFrameList === null;
          var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList);
          var isSingleFrame = !allFrames && !isFrameArray && Lib.isPlainObject(frameOrGroupNameOrFrameList);
          if (isSingleFrame) {
            frameList.push({
              type: "object",
              data: setTransitionConfig(Lib.extendFlat({}, frameOrGroupNameOrFrameList))
            });
          } else if (allFrames || ["string", "number"].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) {
            for (i = 0; i < trans._frames.length; i++) {
              frame = trans._frames[i];
              if (!frame) continue;
              if (allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) {
                frameList.push({
                  type: "byname",
                  name: String(frame.name),
                  data: setTransitionConfig({ name: frame.name })
                });
              }
            }
          } else if (isFrameArray) {
            for (i = 0; i < frameOrGroupNameOrFrameList.length; i++) {
              var frameOrName = frameOrGroupNameOrFrameList[i];
              if (["number", "string"].indexOf(typeof frameOrName) !== -1) {
                frameOrName = String(frameOrName);
                frameList.push({
                  type: "byname",
                  name: frameOrName,
                  data: setTransitionConfig({ name: frameOrName })
                });
              } else if (Lib.isPlainObject(frameOrName)) {
                frameList.push({
                  type: "object",
                  data: setTransitionConfig(Lib.extendFlat({}, frameOrName))
                });
              }
            }
          }
          for (i = 0; i < frameList.length; i++) {
            frame = frameList[i];
            if (frame.type === "byname" && !trans._frameHash[frame.data.name]) {
              Lib.warn('animate failure: frame not found: "' + frame.data.name + '"');
              reject();
              return;
            }
          }
          if (["next", "immediate"].indexOf(animationOpts.mode) !== -1) {
            discardExistingFrames();
          }
          if (animationOpts.direction === "reverse") {
            frameList.reverse();
          }
          var currentFrame = gd._fullLayout._currentFrame;
          if (currentFrame && animationOpts.fromcurrent) {
            var idx = -1;
            for (i = 0; i < frameList.length; i++) {
              frame = frameList[i];
              if (frame.type === "byname" && frame.name === currentFrame) {
                idx = i;
                break;
              }
            }
            if (idx > 0 && idx < frameList.length - 1) {
              var filteredFrameList = [];
              for (i = 0; i < frameList.length; i++) {
                frame = frameList[i];
                if (frameList[i].type !== "byname" || i > idx) {
                  filteredFrameList.push(frame);
                }
              }
              frameList = filteredFrameList;
            }
          }
          if (frameList.length > 0) {
            queueFrames(frameList);
          } else {
            gd.emit("plotly_animated");
            resolve();
          }
        });
      }
      function addFrames(gd, frameList, indices) {
        gd = Lib.getGraphDiv(gd);
        if (frameList === null || frameList === void 0) {
          return Promise.resolve();
        }
        if (!Lib.isPlotDiv(gd)) {
          throw new Error(
            "This element is not a Plotly plot: " + gd + ". It's likely that you've failed to create a plot before adding frames. For more details, see https://plotly.com/javascript/animations/"
          );
        }
        var i, frame, j, idx;
        var _frames = gd._transitionData._frames;
        var _frameHash = gd._transitionData._frameHash;
        if (!Array.isArray(frameList)) {
          throw new Error("addFrames failure: frameList must be an Array of frame definitions" + frameList);
        }
        var bigIndex = _frames.length + frameList.length * 2;
        var insertions = [];
        var _frameHashLocal = {};
        for (i = frameList.length - 1; i >= 0; i--) {
          if (!Lib.isPlainObject(frameList[i])) continue;
          var lookupName = frameList[i].name;
          var name2 = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name;
          var newName = frameList[i].name;
          var collisionPresent = _frameHash[name2] || _frameHashLocal[name2];
          if (name2 && newName && typeof newName === "number" && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) {
            numericNameWarningCount++;
            Lib.warn(
              'addFrames: overwriting frame "' + (_frameHash[name2] || _frameHashLocal[name2]).name + '" with a frame whose name of type "number" also equates to "' + name2 + '". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'
            );
            if (numericNameWarningCount === numericNameWarningCountLimit) {
              Lib.warn(
                "addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed."
              );
            }
          }
          _frameHashLocal[lookupName] = { name: lookupName };
          insertions.push({
            frame: Plots.supplyFrameDefaults(frameList[i]),
            index: indices && indices[i] !== void 0 && indices[i] !== null ? indices[i] : bigIndex + i
          });
        }
        insertions.sort(function(a, b) {
          if (a.index > b.index) return -1;
          if (a.index < b.index) return 1;
          return 0;
        });
        var ops = [];
        var revops = [];
        var frameCount = _frames.length;
        for (i = insertions.length - 1; i >= 0; i--) {
          frame = insertions[i].frame;
          if (typeof frame.name === "number") {
            Lib.warn(
              "Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"
            );
          }
          if (!frame.name) {
            while (_frameHash[frame.name = "frame " + gd._transitionData._counter++]) ;
          }
          if (_frameHash[frame.name]) {
            for (j = 0; j < _frames.length; j++) {
              if ((_frames[j] || {}).name === frame.name) break;
            }
            ops.push({ type: "replace", index: j, value: frame });
            revops.unshift({ type: "replace", index: j, value: _frames[j] });
          } else {
            idx = Math.max(0, Math.min(insertions[i].index, frameCount));
            ops.push({ type: "insert", index: idx, value: frame });
            revops.unshift({ type: "delete", index: idx });
            frameCount++;
          }
        }
        var undoFunc = Plots.modifyFrames;
        var redoFunc = Plots.modifyFrames;
        var undoArgs = [gd, revops];
        var redoArgs = [gd, ops];
        if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        return Plots.modifyFrames(gd, ops);
      }
      function deleteFrames(gd, frameList) {
        gd = Lib.getGraphDiv(gd);
        if (!Lib.isPlotDiv(gd)) {
          throw new Error("This element is not a Plotly plot: " + gd);
        }
        var i, idx;
        var _frames = gd._transitionData._frames;
        var ops = [];
        var revops = [];
        if (!frameList) {
          frameList = [];
          for (i = 0; i < _frames.length; i++) {
            frameList.push(i);
          }
        }
        frameList = frameList.slice();
        frameList.sort();
        for (i = frameList.length - 1; i >= 0; i--) {
          idx = frameList[i];
          ops.push({ type: "delete", index: idx });
          revops.unshift({ type: "insert", index: idx, value: _frames[idx] });
        }
        var undoFunc = Plots.modifyFrames;
        var redoFunc = Plots.modifyFrames;
        var undoArgs = [gd, revops];
        var redoArgs = [gd, ops];
        if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        return Plots.modifyFrames(gd, ops);
      }
      function purge(gd) {
        gd = Lib.getGraphDiv(gd);
        var fullLayout = gd._fullLayout || {};
        var fullData = gd._fullData || [];
        Plots.cleanPlot([], {}, fullData, fullLayout);
        Plots.purge(gd);
        Events.purge(gd);
        if (fullLayout._container) fullLayout._container.remove();
        delete gd._context;
        return gd;
      }
      function calcInverseTransform(gd) {
        var fullLayout = gd._fullLayout;
        var newBBox = gd.getBoundingClientRect();
        if (Lib.equalDomRects(newBBox, fullLayout._lastBBox)) return;
        var m = fullLayout._invTransform = Lib.inverseTransformMatrix(Lib.getFullTransformMatrix(gd));
        fullLayout._invScaleX = Math.sqrt(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]);
        fullLayout._invScaleY = Math.sqrt(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]);
        fullLayout._lastBBox = newBBox;
      }
      function makePlotFramework(gd) {
        var gd3 = d3.select(gd);
        var fullLayout = gd._fullLayout;
        fullLayout._calcInverseTransform = calcInverseTransform;
        fullLayout._calcInverseTransform(gd);
        fullLayout._container = gd3.selectAll(".plot-container").data([0]);
        fullLayout._container.enter().insert("div", ":first-child").classed("plot-container", true).classed("plotly", true).style({
          width: "100%",
          height: "100%"
        });
        fullLayout._paperdiv = fullLayout._container.selectAll(".svg-container").data([0]);
        fullLayout._paperdiv.enter().append("div").classed("user-select-none", true).classed("svg-container", true).style("position", "relative");
        fullLayout._glcontainer = fullLayout._paperdiv.selectAll(".gl-container").data([{}]);
        fullLayout._glcontainer.enter().append("div").classed("gl-container", true);
        fullLayout._paperdiv.selectAll(".main-svg").remove();
        fullLayout._paperdiv.select(".modebar-container").remove();
        fullLayout._paper = fullLayout._paperdiv.insert("svg", ":first-child").classed("main-svg", true);
        fullLayout._toppaper = fullLayout._paperdiv.append("svg").classed("main-svg", true);
        fullLayout._modebardiv = fullLayout._paperdiv.append("div");
        delete fullLayout._modeBar;
        fullLayout._hoverpaper = fullLayout._paperdiv.append("svg").classed("main-svg", true);
        if (!fullLayout._uid) {
          var otherUids = {};
          d3.selectAll("defs").each(function() {
            if (this.id) otherUids[this.id.split("-")[1]] = 1;
          });
          fullLayout._uid = Lib.randstr(otherUids);
        }
        fullLayout._paperdiv.selectAll(".main-svg").attr(xmlnsNamespaces.svgAttrs);
        fullLayout._defs = fullLayout._paper.append("defs").attr("id", "defs-" + fullLayout._uid);
        fullLayout._clips = fullLayout._defs.append("g").classed("clips", true);
        fullLayout._topdefs = fullLayout._toppaper.append("defs").attr("id", "topdefs-" + fullLayout._uid);
        fullLayout._topclips = fullLayout._topdefs.append("g").classed("clips", true);
        fullLayout._bgLayer = fullLayout._paper.append("g").classed("bglayer", true);
        fullLayout._draggers = fullLayout._paper.append("g").classed("draglayer", true);
        var layerBelow = fullLayout._paper.append("g").classed("layer-below", true);
        fullLayout._imageLowerLayer = layerBelow.append("g").classed("imagelayer", true);
        fullLayout._shapeLowerLayer = layerBelow.append("g").classed("shapelayer", true);
        fullLayout._cartesianlayer = fullLayout._paper.append("g").classed("cartesianlayer", true);
        fullLayout._polarlayer = fullLayout._paper.append("g").classed("polarlayer", true);
        fullLayout._smithlayer = fullLayout._paper.append("g").classed("smithlayer", true);
        fullLayout._ternarylayer = fullLayout._paper.append("g").classed("ternarylayer", true);
        fullLayout._geolayer = fullLayout._paper.append("g").classed("geolayer", true);
        fullLayout._funnelarealayer = fullLayout._paper.append("g").classed("funnelarealayer", true);
        fullLayout._pielayer = fullLayout._paper.append("g").classed("pielayer", true);
        fullLayout._iciclelayer = fullLayout._paper.append("g").classed("iciclelayer", true);
        fullLayout._treemaplayer = fullLayout._paper.append("g").classed("treemaplayer", true);
        fullLayout._sunburstlayer = fullLayout._paper.append("g").classed("sunburstlayer", true);
        fullLayout._indicatorlayer = fullLayout._toppaper.append("g").classed("indicatorlayer", true);
        fullLayout._glimages = fullLayout._paper.append("g").classed("glimages", true);
        var layerAbove = fullLayout._toppaper.append("g").classed("layer-above", true);
        fullLayout._imageUpperLayer = layerAbove.append("g").classed("imagelayer", true);
        fullLayout._shapeUpperLayer = layerAbove.append("g").classed("shapelayer", true);
        fullLayout._selectionLayer = fullLayout._toppaper.append("g").classed("selectionlayer", true);
        fullLayout._infolayer = fullLayout._toppaper.append("g").classed("infolayer", true);
        fullLayout._menulayer = fullLayout._toppaper.append("g").classed("menulayer", true);
        fullLayout._zoomlayer = fullLayout._toppaper.append("g").classed("zoomlayer", true);
        fullLayout._hoverlayer = fullLayout._hoverpaper.append("g").classed("hoverlayer", true);
        fullLayout._modebardiv.classed("modebar-container", true).style("position", "absolute").style("top", "0px").style("right", "0px");
        gd.emit("plotly_framework");
      }
      exports.animate = animate;
      exports.addFrames = addFrames;
      exports.deleteFrames = deleteFrames;
      exports.addTraces = addTraces;
      exports.deleteTraces = deleteTraces;
      exports.extendTraces = extendTraces;
      exports.moveTraces = moveTraces;
      exports.prependTraces = prependTraces;
      exports.newPlot = newPlot;
      exports._doPlot = _doPlot;
      exports.purge = purge;
      exports.react = react;
      exports.redraw = redraw;
      exports.relayout = relayout;
      exports.restyle = restyle;
      exports.setPlotConfig = setPlotConfig;
      exports.update = update;
      exports._guiRelayout = guiEdit(relayout);
      exports._guiRestyle = guiEdit(restyle);
      exports._guiUpdate = guiEdit(update);
      exports._storeDirectGUIEdit = _storeDirectGUIEdit;
    }
  });

  // src/snapshot/helpers.js
  var require_helpers10 = __commonJS({
    "src/snapshot/helpers.js"(exports) {
      "use strict";
      var Registry = require_registry();
      exports.getDelay = function(fullLayout) {
        if (!fullLayout._has) return 0;
        return fullLayout._has("gl3d") || fullLayout._has("mapbox") || fullLayout._has("map") ? 500 : 0;
      };
      exports.getRedrawFunc = function(gd) {
        return function() {
          Registry.getComponentMethod("colorbar", "draw")(gd);
        };
      };
      exports.encodeSVG = function(svg) {
        return "data:image/svg+xml," + encodeURIComponent(svg);
      };
      exports.encodeJSON = function(json) {
        return "data:application/json," + encodeURIComponent(json);
      };
      var DOM_URL = window.URL || window.webkitURL;
      exports.createObjectURL = function(blob) {
        return DOM_URL.createObjectURL(blob);
      };
      exports.revokeObjectURL = function(url) {
        return DOM_URL.revokeObjectURL(url);
      };
      exports.createBlob = function(url, format) {
        if (format === "svg") {
          return new window.Blob([url], { type: "image/svg+xml;charset=utf-8" });
        } else if (format === "full-json") {
          return new window.Blob([url], { type: "application/json;charset=utf-8" });
        } else {
          var binary = fixBinary(window.atob(url));
          return new window.Blob([binary], { type: "image/" + format });
        }
      };
      exports.octetStream = function(s) {
        document.location.href = "data:application/octet-stream" + s;
      };
      function fixBinary(b) {
        var len = b.length;
        var buf = new ArrayBuffer(len);
        var arr = new Uint8Array(buf);
        for (var i = 0; i < len; i++) {
          arr[i] = b.charCodeAt(i);
        }
        return buf;
      }
      exports.IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;
    }
  });

  // src/snapshot/tosvg.js
  var require_tosvg = __commonJS({
    "src/snapshot/tosvg.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var xmlnsNamespaces = require_xmlns_namespaces();
      var DOUBLEQUOTE_REGEX = /"/g;
      var DUMMY_SUB = "TOBESTRIPPED";
      var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ")|(" + DUMMY_SUB + '")', "g");
      function htmlEntityDecode(s) {
        var hiddenDiv = d3.select("body").append("div").style({ display: "none" }).html("");
        var replaced = s.replace(/(&[^;]*;)/gi, function(d) {
          if (d === "&lt;") {
            return "&#60;";
          }
          if (d === "&rt;") {
            return "&#62;";
          }
          if (d.indexOf("<") !== -1 || d.indexOf(">") !== -1) {
            return "";
          }
          return hiddenDiv.html(d).text();
        });
        hiddenDiv.remove();
        return replaced;
      }
      function xmlEntityEncode(str) {
        return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, "&amp;");
      }
      module.exports = function toSVG(gd, format, scale) {
        var fullLayout = gd._fullLayout;
        var svg = fullLayout._paper;
        var toppaper = fullLayout._toppaper;
        var width = fullLayout.width;
        var height = fullLayout.height;
        var i;
        svg.insert("rect", ":first-child").call(Drawing.setRect, 0, 0, width, height).call(Color2.fill, fullLayout.paper_bgcolor);
        var basePlotModules = fullLayout._basePlotModules || [];
        for (i = 0; i < basePlotModules.length; i++) {
          var _module = basePlotModules[i];
          if (_module.toSVG) _module.toSVG(gd);
        }
        if (toppaper) {
          var nodes = toppaper.node().childNodes;
          var topGroups = Array.prototype.slice.call(nodes);
          for (i = 0; i < topGroups.length; i++) {
            var topGroup = topGroups[i];
            if (topGroup.childNodes.length) svg.node().appendChild(topGroup);
          }
        }
        if (fullLayout._draggers) {
          fullLayout._draggers.remove();
        }
        svg.node().style.background = "";
        svg.selectAll("text").attr({ "data-unformatted": null, "data-math": null }).each(function() {
          var txt = d3.select(this);
          if (this.style.visibility === "hidden" || this.style.display === "none") {
            txt.remove();
            return;
          } else {
            txt.style({ visibility: null, display: null });
          }
          var ff = this.style.fontFamily;
          if (ff && ff.indexOf('"') !== -1) {
            txt.style("font-family", ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
          }
          var fw = this.style.fontWeight;
          if (fw && (fw === "normal" || fw === "400")) {
            txt.style("font-weight", void 0);
          }
          var fs = this.style.fontStyle;
          if (fs && fs === "normal") {
            txt.style("font-style", void 0);
          }
          var fv = this.style.fontVariant;
          if (fv && fv === "normal") {
            txt.style("font-variant", void 0);
          }
        });
        svg.selectAll(".gradient_filled,.pattern_filled").each(function() {
          var pt = d3.select(this);
          var fill = this.style.fill;
          if (fill && fill.indexOf("url(") !== -1) {
            pt.style("fill", fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
          }
          var stroke = this.style.stroke;
          if (stroke && stroke.indexOf("url(") !== -1) {
            pt.style("stroke", stroke.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
          }
        });
        if (format === "pdf" || format === "eps") {
          svg.selectAll("#MathJax_SVG_glyphs path").attr("stroke-width", 0);
        }
        if (format === "svg" && scale) {
          svg.attr("width", scale * width);
          svg.attr("height", scale * height);
          svg.attr("viewBox", "0 0 " + width + " " + height);
        }
        var s = new window.XMLSerializer().serializeToString(svg.node());
        s = htmlEntityDecode(s);
        s = xmlEntityEncode(s);
        s = s.replace(DUMMY_REGEX, "'");
        return s;
      };
    }
  });

  // src/snapshot/svgtoimg.js
  var require_svgtoimg = __commonJS({
    "src/snapshot/svgtoimg.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var EventEmitter = require_events().EventEmitter;
      var helpers = require_helpers10();
      function svgToImg(opts) {
        var ev = opts.emitter || new EventEmitter();
        var promise = new Promise(function(resolve, reject) {
          var Image2 = window.Image;
          var svg = opts.svg;
          var format = opts.format || "png";
          var canvas = opts.canvas;
          var scale = opts.scale || 1;
          var w0 = opts.width || 300;
          var h0 = opts.height || 150;
          var w1 = scale * w0;
          var h1 = scale * h0;
          var ctx = canvas.getContext("2d", { willReadFrequently: true });
          var img = new Image2();
          var svgBlob, url;
          if (format === "svg" || Lib.isSafari()) {
            url = helpers.encodeSVG(svg);
          } else {
            svgBlob = helpers.createBlob(svg, "svg");
            url = helpers.createObjectURL(svgBlob);
          }
          canvas.width = w1;
          canvas.height = h1;
          img.onload = function() {
            var imgData;
            svgBlob = null;
            helpers.revokeObjectURL(url);
            if (format !== "svg") {
              ctx.drawImage(img, 0, 0, w1, h1);
            }
            switch (format) {
              case "jpeg":
                imgData = canvas.toDataURL("image/jpeg");
                break;
              case "png":
                imgData = canvas.toDataURL("image/png");
                break;
              case "webp":
                imgData = canvas.toDataURL("image/webp");
                break;
              case "svg":
                imgData = url;
                break;
              default:
                var errorMsg = "Image format is not jpeg, png, svg or webp.";
                reject(new Error(errorMsg));
                if (!opts.promise) {
                  return ev.emit("error", errorMsg);
                }
            }
            resolve(imgData);
            if (!opts.promise) {
              ev.emit("success", imgData);
            }
          };
          img.onerror = function(err) {
            svgBlob = null;
            helpers.revokeObjectURL(url);
            reject(err);
            if (!opts.promise) {
              return ev.emit("error", err);
            }
          };
          img.src = url;
        });
        if (opts.promise) {
          return promise;
        }
        return ev;
      }
      module.exports = svgToImg;
    }
  });

  // src/plot_api/to_image.js
  var require_to_image = __commonJS({
    "src/plot_api/to_image.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var plotApi = require_plot_api();
      var plots = require_plots();
      var Lib = require_lib();
      var helpers = require_helpers10();
      var toSVG = require_tosvg();
      var svgToImg = require_svgtoimg();
      var version = require_version().version;
      var attrs = {
        format: {
          valType: "enumerated",
          values: ["png", "jpeg", "webp", "svg", "full-json"],
          dflt: "png"
        },
        width: {
          valType: "number",
          min: 1
        },
        height: {
          valType: "number",
          min: 1
        },
        scale: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        setBackground: {
          valType: "any",
          dflt: false
        },
        imageDataOnly: {
          valType: "boolean",
          dflt: false
        }
      };
      function toImage(gd, opts) {
        opts = opts || {};
        var data;
        var layout;
        var config;
        var fullLayout;
        if (Lib.isPlainObject(gd)) {
          data = gd.data || [];
          layout = gd.layout || {};
          config = gd.config || {};
          fullLayout = {};
        } else {
          gd = Lib.getGraphDiv(gd);
          data = Lib.extendDeep([], gd.data);
          layout = Lib.extendDeep({}, gd.layout);
          config = gd._context;
          fullLayout = gd._fullLayout || {};
        }
        function isImpliedOrValid(attr) {
          return !(attr in opts) || Lib.validate(opts[attr], attrs[attr]);
        }
        if (!isImpliedOrValid("width") && opts.width !== null || !isImpliedOrValid("height") && opts.height !== null) {
          throw new Error("Height and width should be pixel values.");
        }
        if (!isImpliedOrValid("format")) {
          throw new Error("Export format is not " + Lib.join2(attrs.format.values, ", ", " or ") + ".");
        }
        var fullOpts = {};
        function coerce(attr, dflt) {
          return Lib.coerce(opts, fullOpts, attrs, attr, dflt);
        }
        var format = coerce("format");
        var width = coerce("width");
        var height = coerce("height");
        var scale = coerce("scale");
        var setBackground = coerce("setBackground");
        var imageDataOnly = coerce("imageDataOnly");
        var clonedGd = document.createElement("div");
        clonedGd.style.position = "absolute";
        clonedGd.style.left = "-5000px";
        document.body.appendChild(clonedGd);
        var layoutImage = Lib.extendFlat({}, layout);
        if (width) {
          layoutImage.width = width;
        } else if (opts.width === null && isNumeric(fullLayout.width)) {
          layoutImage.width = fullLayout.width;
        }
        if (height) {
          layoutImage.height = height;
        } else if (opts.height === null && isNumeric(fullLayout.height)) {
          layoutImage.height = fullLayout.height;
        }
        var configImage = Lib.extendFlat({}, config, {
          _exportedPlot: true,
          staticPlot: true,
          setBackground
        });
        var redrawFunc = helpers.getRedrawFunc(clonedGd);
        function wait() {
          return new Promise(function(resolve) {
            setTimeout(resolve, helpers.getDelay(clonedGd._fullLayout));
          });
        }
        function convert() {
          return new Promise(function(resolve, reject) {
            var svg = toSVG(clonedGd, format, scale);
            var width2 = clonedGd._fullLayout.width;
            var height2 = clonedGd._fullLayout.height;
            function cleanup() {
              plotApi.purge(clonedGd);
              document.body.removeChild(clonedGd);
            }
            if (format === "full-json") {
              var json = plots.graphJson(clonedGd, false, "keepdata", "object", true, true);
              json.version = version;
              json = JSON.stringify(json);
              cleanup();
              if (imageDataOnly) {
                return resolve(json);
              } else {
                return resolve(helpers.encodeJSON(json));
              }
            }
            cleanup();
            if (format === "svg") {
              if (imageDataOnly) {
                return resolve(svg);
              } else {
                return resolve(helpers.encodeSVG(svg));
              }
            }
            var canvas = document.createElement("canvas");
            canvas.id = Lib.randstr();
            svgToImg({
              format,
              width: width2,
              height: height2,
              scale,
              canvas,
              svg,
              // ask svgToImg to return a Promise
              //  rather than EventEmitter
              //  leave EventEmitter for backward
              //  compatibility
              promise: true
            }).then(resolve).catch(reject);
          });
        }
        function urlToImageData(url) {
          if (imageDataOnly) {
            return url.replace(helpers.IMAGE_URL_PREFIX, "");
          } else {
            return url;
          }
        }
        return new Promise(function(resolve, reject) {
          plotApi.newPlot(clonedGd, data, layoutImage, configImage).then(redrawFunc).then(wait).then(convert).then(function(url) {
            resolve(urlToImageData(url));
          }).catch(function(err) {
            reject(err);
          });
        });
      }
      module.exports = toImage;
    }
  });

  // src/plot_api/validate.js
  var require_validate = __commonJS({
    "src/plot_api/validate.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Plots = require_plots();
      var PlotSchema = require_plot_schema();
      var dfltConfig = require_plot_config().dfltConfig;
      var isPlainObject = Lib.isPlainObject;
      var isArray = Array.isArray;
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      module.exports = function validate(data, layout) {
        if (data === void 0) data = [];
        if (layout === void 0) layout = {};
        var schema = PlotSchema.get();
        var errorList = [];
        var gd = { _context: Lib.extendFlat({}, dfltConfig) };
        var dataIn, layoutIn;
        if (isArray(data)) {
          gd.data = Lib.extendDeep([], data);
          dataIn = data;
        } else {
          gd.data = [];
          dataIn = [];
          errorList.push(format("array", "data"));
        }
        if (isPlainObject(layout)) {
          gd.layout = Lib.extendDeep({}, layout);
          layoutIn = layout;
        } else {
          gd.layout = {};
          layoutIn = {};
          if (arguments.length > 1) {
            errorList.push(format("object", "layout"));
          }
        }
        Plots.supplyDefaults(gd);
        var dataOut = gd._fullData;
        var len = dataIn.length;
        for (var i = 0; i < len; i++) {
          var traceIn = dataIn[i];
          var base = ["data", i];
          if (!isPlainObject(traceIn)) {
            errorList.push(format("object", base));
            continue;
          }
          var traceOut = dataOut[i];
          var traceType = traceOut.type;
          var traceSchema = schema.traces[traceType].attributes;
          traceSchema.type = {
            valType: "enumerated",
            values: [traceType]
          };
          if (traceOut.visible === false && traceIn.visible !== false) {
            errorList.push(format("invisible", base));
          }
          crawl(traceIn, traceOut, traceSchema, errorList, base);
        }
        var layoutOut = gd._fullLayout;
        var layoutSchema = fillLayoutSchema(schema, dataOut);
        crawl(layoutIn, layoutOut, layoutSchema, errorList, "layout");
        return errorList.length === 0 ? void 0 : errorList;
      };
      function crawl(objIn, objOut, schema, list, base, path) {
        path = path || [];
        var keys = Object.keys(objIn);
        for (var i = 0; i < keys.length; i++) {
          var k = keys[i];
          var p = path.slice();
          p.push(k);
          var valIn = objIn[k];
          var valOut = objOut[k];
          var nestedSchema = getNestedSchema(schema, k);
          var nestedValType = (nestedSchema || {}).valType;
          var isInfoArray = nestedValType === "info_array";
          var isColorscale = nestedValType === "colorscale";
          var items = (nestedSchema || {}).items;
          if (!isInSchema(schema, k)) {
            list.push(format("schema", base, p));
          } else if (isPlainObject(valIn) && isPlainObject(valOut) && nestedValType !== "any") {
            crawl(valIn, valOut, nestedSchema, list, base, p);
          } else if (isInfoArray && isArray(valIn)) {
            if (valIn.length > valOut.length) {
              list.push(format("unused", base, p.concat(valOut.length)));
            }
            var len = valOut.length;
            var arrayItems = Array.isArray(items);
            if (arrayItems) len = Math.min(len, items.length);
            var m, n, item, valInPart, valOutPart;
            if (nestedSchema.dimensions === 2) {
              for (n = 0; n < len; n++) {
                if (isArray(valIn[n])) {
                  if (valIn[n].length > valOut[n].length) {
                    list.push(format("unused", base, p.concat(n, valOut[n].length)));
                  }
                  var len2 = valOut[n].length;
                  for (m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) {
                    item = arrayItems ? items[n][m] : items;
                    valInPart = valIn[n][m];
                    valOutPart = valOut[n][m];
                    if (!Lib.validate(valInPart, item)) {
                      list.push(format("value", base, p.concat(n, m), valInPart));
                    } else if (valOutPart !== valInPart && valOutPart !== +valInPart) {
                      list.push(format("dynamic", base, p.concat(n, m), valInPart, valOutPart));
                    }
                  }
                } else {
                  list.push(format("array", base, p.concat(n), valIn[n]));
                }
              }
            } else {
              for (n = 0; n < len; n++) {
                item = arrayItems ? items[n] : items;
                valInPart = valIn[n];
                valOutPart = valOut[n];
                if (!Lib.validate(valInPart, item)) {
                  list.push(format("value", base, p.concat(n), valInPart));
                } else if (valOutPart !== valInPart && valOutPart !== +valInPart) {
                  list.push(format("dynamic", base, p.concat(n), valInPart, valOutPart));
                }
              }
            }
          } else if (nestedSchema.items && !isInfoArray && isArray(valIn)) {
            var _nestedSchema = items[Object.keys(items)[0]];
            var indexList = [];
            var j, _p;
            for (j = 0; j < valOut.length; j++) {
              var _index = valOut[j]._index || j;
              _p = p.slice();
              _p.push(_index);
              if (isPlainObject(valIn[_index]) && isPlainObject(valOut[j])) {
                indexList.push(_index);
                var valInj = valIn[_index];
                var valOutj = valOut[j];
                if (isPlainObject(valInj) && valInj.visible !== false && valOutj.visible === false) {
                  list.push(format("invisible", base, _p));
                } else crawl(valInj, valOutj, _nestedSchema, list, base, _p);
              }
            }
            for (j = 0; j < valIn.length; j++) {
              _p = p.slice();
              _p.push(j);
              if (!isPlainObject(valIn[j])) {
                list.push(format("object", base, _p, valIn[j]));
              } else if (indexList.indexOf(j) === -1) {
                list.push(format("unused", base, _p));
              }
            }
          } else if (!isPlainObject(valIn) && isPlainObject(valOut)) {
            list.push(format("object", base, p, valIn));
          } else if (!isArrayOrTypedArray(valIn) && isArrayOrTypedArray(valOut) && !isInfoArray && !isColorscale) {
            list.push(format("array", base, p, valIn));
          } else if (!(k in objOut)) {
            list.push(format("unused", base, p, valIn));
          } else if (!Lib.validate(valIn, nestedSchema)) {
            list.push(format("value", base, p, valIn));
          } else if (nestedSchema.valType === "enumerated" && (nestedSchema.coerceNumber && valIn !== +valOut || !isArrayOrTypedArray(valIn) && valIn !== valOut || String(valIn) !== String(valOut))) {
            list.push(format("dynamic", base, p, valIn, valOut));
          }
        }
        return list;
      }
      function fillLayoutSchema(schema, dataOut) {
        var layoutSchema = schema.layout.layoutAttributes;
        for (var i = 0; i < dataOut.length; i++) {
          var traceOut = dataOut[i];
          var traceSchema = schema.traces[traceOut.type];
          var traceLayoutAttr = traceSchema.layoutAttributes;
          if (traceLayoutAttr) {
            if (traceOut.subplot) {
              Lib.extendFlat(layoutSchema[traceSchema.attributes.subplot.dflt], traceLayoutAttr);
            } else {
              Lib.extendFlat(layoutSchema, traceLayoutAttr);
            }
          }
        }
        return layoutSchema;
      }
      var code2msgFunc = {
        object: function(base, astr) {
          var prefix;
          if (base === "layout" && astr === "") prefix = "The layout argument";
          else if (base[0] === "data" && astr === "") {
            prefix = "Trace " + base[1] + " in the data argument";
          } else prefix = inBase(base) + "key " + astr;
          return prefix + " must be linked to an object container";
        },
        array: function(base, astr) {
          var prefix;
          if (base === "data") prefix = "The data argument";
          else prefix = inBase(base) + "key " + astr;
          return prefix + " must be linked to an array container";
        },
        schema: function(base, astr) {
          return inBase(base) + "key " + astr + " is not part of the schema";
        },
        unused: function(base, astr, valIn) {
          var target = isPlainObject(valIn) ? "container" : "key";
          return inBase(base) + target + " " + astr + " did not get coerced";
        },
        dynamic: function(base, astr, valIn, valOut) {
          return [
            inBase(base) + "key",
            astr,
            "(set to '" + valIn + "')",
            "got reset to",
            "'" + valOut + "'",
            "during defaults."
          ].join(" ");
        },
        invisible: function(base, astr) {
          return (astr ? inBase(base) + "item " + astr : "Trace " + base[1]) + " got defaulted to be not visible";
        },
        value: function(base, astr, valIn) {
          return [
            inBase(base) + "key " + astr,
            "is set to an invalid value (" + valIn + ")"
          ].join(" ");
        }
      };
      function inBase(base) {
        if (isArray(base)) return "In data trace " + base[1] + ", ";
        return "In " + base + ", ";
      }
      function format(code, base, path, valIn, valOut) {
        path = path || "";
        var container, trace;
        if (isArray(base)) {
          container = base[0];
          trace = base[1];
        } else {
          container = base;
          trace = null;
        }
        var astr = convertPathToAttributeString(path);
        var msg = code2msgFunc[code](base, astr, valIn, valOut);
        Lib.log(msg);
        return {
          code,
          container,
          trace,
          path,
          astr,
          msg
        };
      }
      function isInSchema(schema, key) {
        var parts = splitKey(key);
        var keyMinusId = parts.keyMinusId;
        var id = parts.id;
        if (keyMinusId in schema && schema[keyMinusId]._isSubplotObj && id) {
          return true;
        }
        return key in schema;
      }
      function getNestedSchema(schema, key) {
        if (key in schema) return schema[key];
        var parts = splitKey(key);
        return schema[parts.keyMinusId];
      }
      var idRegex = Lib.counterRegex("([a-z]+)");
      function splitKey(key) {
        var idMatch = key.match(idRegex);
        return {
          keyMinusId: idMatch && idMatch[1],
          id: idMatch && idMatch[2]
        };
      }
      function convertPathToAttributeString(path) {
        if (!isArray(path)) return String(path);
        var astr = "";
        for (var i = 0; i < path.length; i++) {
          var p = path[i];
          if (typeof p === "number") {
            astr = astr.slice(0, -1) + "[" + p + "]";
          } else {
            astr += p;
          }
          if (i < path.length - 1) astr += ".";
        }
        return astr;
      }
    }
  });

  // src/snapshot/filesaver.js
  var require_filesaver = __commonJS({
    "src/snapshot/filesaver.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var helpers = require_helpers10();
      function fileSaver(url, name2, format) {
        var saveLink = document.createElement("a");
        var canUseSaveLink = "download" in saveLink;
        var promise = new Promise(function(resolve, reject) {
          var blob;
          var objectUrl;
          if (canUseSaveLink) {
            blob = helpers.createBlob(url, format);
            objectUrl = helpers.createObjectURL(blob);
            saveLink.href = objectUrl;
            saveLink.download = name2;
            document.body.appendChild(saveLink);
            saveLink.click();
            document.body.removeChild(saveLink);
            helpers.revokeObjectURL(objectUrl);
            blob = null;
            return resolve(name2);
          }
          if (Lib.isSafari()) {
            var prefix = format === "svg" ? "," : ";base64,";
            helpers.octetStream(prefix + encodeURIComponent(url));
            return resolve(name2);
          }
          reject(new Error("download error"));
        });
        return promise;
      }
      module.exports = fileSaver;
    }
  });

  // src/snapshot/download.js
  var require_download = __commonJS({
    "src/snapshot/download.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var toImage = require_to_image();
      var fileSaver = require_filesaver();
      var helpers = require_helpers10();
      function downloadImage(gd, opts) {
        var _gd;
        if (!Lib.isPlainObject(gd)) _gd = Lib.getGraphDiv(gd);
        opts = opts || {};
        opts.format = opts.format || "png";
        opts.width = opts.width || null;
        opts.height = opts.height || null;
        opts.imageDataOnly = true;
        return new Promise(function(resolve, reject) {
          if (_gd && _gd._snapshotInProgress) {
            reject(new Error("Snapshotting already in progress."));
          }
          if (_gd) _gd._snapshotInProgress = true;
          var promise = toImage(gd, opts);
          var filename = opts.filename || gd.fn || "newplot";
          filename += "." + opts.format.replace("-", ".");
          promise.then(function(result) {
            if (_gd) _gd._snapshotInProgress = false;
            return fileSaver(result, filename, opts.format);
          }).then(function(name2) {
            resolve(name2);
          }).catch(function(err) {
            if (_gd) _gd._snapshotInProgress = false;
            reject(err);
          });
        });
      }
      module.exports = downloadImage;
    }
  });

  // src/plot_api/template_api.js
  var require_template_api = __commonJS({
    "src/plot_api/template_api.js"(exports) {
      "use strict";
      var Lib = require_lib();
      var isPlainObject = Lib.isPlainObject;
      var PlotSchema = require_plot_schema();
      var Plots = require_plots();
      var plotAttributes = require_attributes2();
      var Template = require_plot_template();
      var dfltConfig = require_plot_config().dfltConfig;
      exports.makeTemplate = function(figure) {
        figure = Lib.isPlainObject(figure) ? figure : Lib.getGraphDiv(figure);
        figure = Lib.extendDeep({ _context: dfltConfig }, { data: figure.data, layout: figure.layout });
        Plots.supplyDefaults(figure);
        var data = figure.data || [];
        var layout = figure.layout || {};
        layout._basePlotModules = figure._fullLayout._basePlotModules;
        layout._modules = figure._fullLayout._modules;
        var template = {
          data: {},
          layout: {}
        };
        data.forEach(function(trace) {
          var traceTemplate = {};
          walkStyleKeys(trace, traceTemplate, getTraceInfo.bind(null, trace));
          var traceType2 = Lib.coerce(trace, {}, plotAttributes, "type");
          var typeTemplates2 = template.data[traceType2];
          if (!typeTemplates2) typeTemplates2 = template.data[traceType2] = [];
          typeTemplates2.push(traceTemplate);
        });
        walkStyleKeys(layout, template.layout, getLayoutInfo.bind(null, layout));
        delete template.layout.template;
        var oldTemplate = layout.template;
        if (isPlainObject(oldTemplate)) {
          var oldLayoutTemplate = oldTemplate.layout;
          var i, traceType, oldTypeTemplates, oldTypeLen, typeTemplates, typeLen;
          if (isPlainObject(oldLayoutTemplate)) {
            mergeTemplates(oldLayoutTemplate, template.layout);
          }
          var oldDataTemplate = oldTemplate.data;
          if (isPlainObject(oldDataTemplate)) {
            for (traceType in template.data) {
              oldTypeTemplates = oldDataTemplate[traceType];
              if (Array.isArray(oldTypeTemplates)) {
                typeTemplates = template.data[traceType];
                typeLen = typeTemplates.length;
                oldTypeLen = oldTypeTemplates.length;
                for (i = 0; i < typeLen; i++) {
                  mergeTemplates(oldTypeTemplates[i % oldTypeLen], typeTemplates[i]);
                }
                for (i = typeLen; i < oldTypeLen; i++) {
                  typeTemplates.push(Lib.extendDeep({}, oldTypeTemplates[i]));
                }
              }
            }
            for (traceType in oldDataTemplate) {
              if (!(traceType in template.data)) {
                template.data[traceType] = Lib.extendDeep([], oldDataTemplate[traceType]);
              }
            }
          }
        }
        return template;
      };
      function mergeTemplates(oldTemplate, newTemplate) {
        oldTemplate = Lib.extendDeep({}, oldTemplate);
        var oldKeys = Object.keys(oldTemplate).sort();
        var i, j;
        function mergeOne(oldVal2, newVal, key3) {
          if (isPlainObject(newVal) && isPlainObject(oldVal2)) {
            mergeTemplates(oldVal2, newVal);
          } else if (Array.isArray(newVal) && Array.isArray(oldVal2)) {
            var templater = Template.arrayTemplater({ _template: oldTemplate }, key3);
            for (j = 0; j < newVal.length; j++) {
              var item = newVal[j];
              var oldItem = templater.newItem(item)._template;
              if (oldItem) mergeTemplates(oldItem, item);
            }
            var defaultItems = templater.defaultItems();
            for (j = 0; j < defaultItems.length; j++) newVal.push(defaultItems[j]._template);
            for (j = 0; j < newVal.length; j++) delete newVal[j].templateitemname;
          }
        }
        for (i = 0; i < oldKeys.length; i++) {
          var key = oldKeys[i];
          var oldVal = oldTemplate[key];
          if (key in newTemplate) {
            mergeOne(oldVal, newTemplate[key], key);
          } else newTemplate[key] = oldVal;
          if (getBaseKey(key) === key) {
            for (var key2 in newTemplate) {
              var baseKey2 = getBaseKey(key2);
              if (key2 !== baseKey2 && baseKey2 === key && !(key2 in oldTemplate)) {
                mergeOne(oldVal, newTemplate[key2], key);
              }
            }
          }
        }
      }
      function getBaseKey(key) {
        return key.replace(/[0-9]+$/, "");
      }
      function walkStyleKeys(parent, templateOut, getAttributeInfo, path, basePath) {
        var pathAttr = basePath && getAttributeInfo(basePath);
        for (var key in parent) {
          var child = parent[key];
          var nextPath = getNextPath(parent, key, path);
          var nextBasePath = getNextPath(parent, key, basePath);
          var attr = getAttributeInfo(nextBasePath);
          if (!attr) {
            var baseKey = getBaseKey(key);
            if (baseKey !== key) {
              nextBasePath = getNextPath(parent, baseKey, basePath);
              attr = getAttributeInfo(nextBasePath);
            }
          }
          if (pathAttr && pathAttr === attr) continue;
          if (!attr || attr._noTemplating || attr.valType === "data_array" || attr.arrayOk && Array.isArray(child)) {
            continue;
          }
          if (!attr.valType && isPlainObject(child)) {
            walkStyleKeys(child, templateOut, getAttributeInfo, nextPath, nextBasePath);
          } else if (attr._isLinkedToArray && Array.isArray(child)) {
            var dfltDone = false;
            var namedIndex = 0;
            var usedNames = {};
            for (var i = 0; i < child.length; i++) {
              var item = child[i];
              if (isPlainObject(item)) {
                var name2 = item.name;
                if (name2) {
                  if (!usedNames[name2]) {
                    walkStyleKeys(
                      item,
                      templateOut,
                      getAttributeInfo,
                      getNextPath(child, namedIndex, nextPath),
                      getNextPath(child, namedIndex, nextBasePath)
                    );
                    namedIndex++;
                    usedNames[name2] = 1;
                  }
                } else if (!dfltDone) {
                  var dfltKey = Template.arrayDefaultKey(key);
                  var dfltPath = getNextPath(parent, dfltKey, path);
                  var pathInArray = getNextPath(child, namedIndex, nextPath);
                  walkStyleKeys(
                    item,
                    templateOut,
                    getAttributeInfo,
                    pathInArray,
                    getNextPath(child, namedIndex, nextBasePath)
                  );
                  var itemPropInArray = Lib.nestedProperty(templateOut, pathInArray);
                  var dfltProp = Lib.nestedProperty(templateOut, dfltPath);
                  dfltProp.set(itemPropInArray.get());
                  itemPropInArray.set(null);
                  dfltDone = true;
                }
              }
            }
          } else {
            var templateProp = Lib.nestedProperty(templateOut, nextPath);
            templateProp.set(child);
          }
        }
      }
      function getLayoutInfo(layout, path) {
        return PlotSchema.getLayoutValObject(
          layout,
          Lib.nestedProperty({}, path).parts
        );
      }
      function getTraceInfo(trace, path) {
        return PlotSchema.getTraceValObject(
          trace,
          Lib.nestedProperty({}, path).parts
        );
      }
      function getNextPath(parent, key, path) {
        var nextPath;
        if (!path) nextPath = key;
        else if (Array.isArray(parent)) nextPath = path + "[" + key + "]";
        else nextPath = path + "." + key;
        return nextPath;
      }
      exports.validateTemplate = function(figureIn, template) {
        var figure = Lib.extendDeep({}, {
          _context: dfltConfig,
          data: figureIn.data,
          layout: figureIn.layout
        });
        var layout = figure.layout || {};
        if (!isPlainObject(template)) template = layout.template || {};
        var layoutTemplate = template.layout;
        var dataTemplate = template.data;
        var errorList = [];
        figure.layout = layout;
        figure.layout.template = template;
        Plots.supplyDefaults(figure);
        var fullLayout = figure._fullLayout;
        var fullData = figure._fullData;
        var layoutPaths = {};
        function crawlLayoutForContainers(obj, paths) {
          for (var key in obj) {
            if (key.charAt(0) !== "_" && isPlainObject(obj[key])) {
              var baseKey = getBaseKey(key);
              var nextPaths = [];
              var i2;
              for (i2 = 0; i2 < paths.length; i2++) {
                nextPaths.push(getNextPath(obj, key, paths[i2]));
                if (baseKey !== key) nextPaths.push(getNextPath(obj, baseKey, paths[i2]));
              }
              for (i2 = 0; i2 < nextPaths.length; i2++) {
                layoutPaths[nextPaths[i2]] = 1;
              }
              crawlLayoutForContainers(obj[key], nextPaths);
            }
          }
        }
        function crawlLayoutTemplateForContainers(obj, path) {
          for (var key in obj) {
            if (key.indexOf("defaults") === -1 && isPlainObject(obj[key])) {
              var nextPath = getNextPath(obj, key, path);
              if (layoutPaths[nextPath]) {
                crawlLayoutTemplateForContainers(obj[key], nextPath);
              } else {
                errorList.push({ code: "unused", path: nextPath });
              }
            }
          }
        }
        if (!isPlainObject(layoutTemplate)) {
          errorList.push({ code: "layout" });
        } else {
          crawlLayoutForContainers(fullLayout, ["layout"]);
          crawlLayoutTemplateForContainers(layoutTemplate, "layout");
        }
        if (!isPlainObject(dataTemplate)) {
          errorList.push({ code: "data" });
        } else {
          var typeCount = {};
          var traceType;
          for (var i = 0; i < fullData.length; i++) {
            var fullTrace = fullData[i];
            traceType = fullTrace.type;
            typeCount[traceType] = (typeCount[traceType] || 0) + 1;
            if (!fullTrace._fullInput._template) {
              errorList.push({
                code: "missing",
                index: fullTrace.index,
                traceType
              });
            }
          }
          for (traceType in dataTemplate) {
            var templateCount = dataTemplate[traceType].length;
            var dataCount = typeCount[traceType] || 0;
            if (templateCount > dataCount) {
              errorList.push({
                code: "unused",
                traceType,
                templateCount,
                dataCount
              });
            } else if (dataCount > templateCount) {
              errorList.push({
                code: "reused",
                traceType,
                templateCount,
                dataCount
              });
            }
          }
        }
        function crawlForMissingTemplates(obj, path) {
          for (var key in obj) {
            if (key.charAt(0) === "_") continue;
            var val = obj[key];
            var nextPath = getNextPath(obj, key, path);
            if (isPlainObject(val)) {
              if (Array.isArray(obj) && val._template === false && val.templateitemname) {
                errorList.push({
                  code: "missing",
                  path: nextPath,
                  templateitemname: val.templateitemname
                });
              }
              crawlForMissingTemplates(val, nextPath);
            } else if (Array.isArray(val) && hasPlainObject(val)) {
              crawlForMissingTemplates(val, nextPath);
            }
          }
        }
        crawlForMissingTemplates({ data: fullData, layout: fullLayout }, "");
        if (errorList.length) return errorList.map(format);
      };
      function hasPlainObject(arr) {
        for (var i = 0; i < arr.length; i++) {
          if (isPlainObject(arr[i])) return true;
        }
      }
      function format(opts) {
        var msg;
        switch (opts.code) {
          case "data":
            msg = "The template has no key data.";
            break;
          case "layout":
            msg = "The template has no key layout.";
            break;
          case "missing":
            if (opts.path) {
              msg = "There are no templates for item " + opts.path + " with name " + opts.templateitemname;
            } else {
              msg = "There are no templates for trace " + opts.index + ", of type " + opts.traceType + ".";
            }
            break;
          case "unused":
            if (opts.path) {
              msg = "The template item at " + opts.path + " was not used in constructing the plot.";
            } else if (opts.dataCount) {
              msg = "Some of the templates of type " + opts.traceType + " were not used. The template has " + opts.templateCount + " traces, the data only has " + opts.dataCount + " of this type.";
            } else {
              msg = "The template has " + opts.templateCount + " traces of type " + opts.traceType + " but there are none in the data.";
            }
            break;
          case "reused":
            msg = "Some of the templates of type " + opts.traceType + " were used more than once. The template has " + opts.templateCount + " traces, the data has " + opts.dataCount + " of this type.";
            break;
        }
        opts.msg = msg;
        return opts;
      }
    }
  });

  // src/plot_api/index.js
  var require_plot_api2 = __commonJS({
    "src/plot_api/index.js"(exports) {
      "use strict";
      var main = require_plot_api();
      exports._doPlot = main._doPlot;
      exports.newPlot = main.newPlot;
      exports.restyle = main.restyle;
      exports.relayout = main.relayout;
      exports.redraw = main.redraw;
      exports.update = main.update;
      exports._guiRestyle = main._guiRestyle;
      exports._guiRelayout = main._guiRelayout;
      exports._guiUpdate = main._guiUpdate;
      exports._storeDirectGUIEdit = main._storeDirectGUIEdit;
      exports.react = main.react;
      exports.extendTraces = main.extendTraces;
      exports.prependTraces = main.prependTraces;
      exports.addTraces = main.addTraces;
      exports.deleteTraces = main.deleteTraces;
      exports.moveTraces = main.moveTraces;
      exports.purge = main.purge;
      exports.addFrames = main.addFrames;
      exports.deleteFrames = main.deleteFrames;
      exports.animate = main.animate;
      exports.setPlotConfig = main.setPlotConfig;
      var getGraphDiv = require_dom().getGraphDiv;
      var eraseActiveShape = require_draw2().eraseActiveShape;
      exports.deleteActiveShape = function(gd) {
        return eraseActiveShape(getGraphDiv(gd));
      };
      exports.toImage = require_to_image();
      exports.validate = require_validate();
      exports.downloadImage = require_download();
      var templateApi = require_template_api();
      exports.makeTemplate = templateApi.makeTemplate;
      exports.validateTemplate = templateApi.validateTemplate;
    }
  });

  // src/traces/scatter/xy_defaults.js
  var require_xy_defaults = __commonJS({
    "src/traces/scatter/xy_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Registry = require_registry();
      module.exports = function handleXYDefaults(traceIn, traceOut, layout, coerce) {
        var x = coerce("x");
        var y = coerce("y");
        var len;
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout);
        if (x) {
          var xlen = Lib.minRowLength(x);
          if (y) {
            len = Math.min(xlen, Lib.minRowLength(y));
          } else {
            len = xlen;
            coerce("y0");
            coerce("dy");
          }
        } else {
          if (!y) return 0;
          len = Lib.minRowLength(y);
          coerce("x0");
          coerce("dx");
        }
        traceOut._length = len;
        return len;
      };
    }
  });

  // src/traces/scatter/period_defaults.js
  var require_period_defaults = __commonJS({
    "src/traces/scatter/period_defaults.js"(exports, module) {
      "use strict";
      var dateTick0 = require_lib().dateTick0;
      var numConstants = require_numerical();
      var ONEWEEK = numConstants.ONEWEEK;
      function getPeriod0Dflt(period, calendar) {
        if (period % ONEWEEK === 0) {
          return dateTick0(calendar, 1);
        }
        return dateTick0(calendar, 0);
      }
      module.exports = function handlePeriodDefaults(traceIn, traceOut, layout, coerce, opts) {
        if (!opts) {
          opts = {
            x: true,
            y: true
          };
        }
        if (opts.x) {
          var xperiod = coerce("xperiod");
          if (xperiod) {
            coerce("xperiod0", getPeriod0Dflt(xperiod, traceOut.xcalendar));
            coerce("xperiodalignment");
          }
        }
        if (opts.y) {
          var yperiod = coerce("yperiod");
          if (yperiod) {
            coerce("yperiod0", getPeriod0Dflt(yperiod, traceOut.ycalendar));
            coerce("yperiodalignment");
          }
        }
      };
    }
  });

  // src/traces/scatter/stack_defaults.js
  var require_stack_defaults = __commonJS({
    "src/traces/scatter/stack_defaults.js"(exports, module) {
      "use strict";
      var perStackAttrs = ["orientation", "groupnorm", "stackgaps"];
      module.exports = function handleStackDefaults(traceIn, traceOut, layout, coerce) {
        var stackOpts = layout._scatterStackOpts;
        var stackGroup = coerce("stackgroup");
        if (stackGroup) {
          var subplot = traceOut.xaxis + traceOut.yaxis;
          var subplotStackOpts = stackOpts[subplot];
          if (!subplotStackOpts) subplotStackOpts = stackOpts[subplot] = {};
          var groupOpts = subplotStackOpts[stackGroup];
          var firstTrace = false;
          if (groupOpts) {
            groupOpts.traces.push(traceOut);
          } else {
            groupOpts = subplotStackOpts[stackGroup] = {
              // keep track of trace indices for use during stacking calculations
              // this will be filled in during `calc` and used during `crossTraceCalc`
              // so it's OK if we don't recreate it during a non-calc edit
              traceIndices: [],
              // Hold on to the whole set of prior traces
              // First one is most important, so we can clear defaults
              // there if we find explicit values only in later traces.
              // We're only going to *use* the values stored in groupOpts,
              // but for the editor and validate we want things self-consistent
              // The full set of traces is used only to fix `fill` default if
              // we find `orientation: 'h'` beyond the first trace
              traces: [traceOut]
            };
            firstTrace = true;
          }
          var dflts = {
            orientation: traceOut.x && !traceOut.y ? "h" : "v"
          };
          for (var i = 0; i < perStackAttrs.length; i++) {
            var attr = perStackAttrs[i];
            var attrFound = attr + "Found";
            if (!groupOpts[attrFound]) {
              var traceHasAttr = traceIn[attr] !== void 0;
              var isOrientation = attr === "orientation";
              if (traceHasAttr || firstTrace) {
                groupOpts[attr] = coerce(attr, dflts[attr]);
                if (isOrientation) {
                  groupOpts.fillDflt = groupOpts[attr] === "h" ? "tonextx" : "tonexty";
                }
                if (traceHasAttr) {
                  groupOpts[attrFound] = true;
                  if (!firstTrace) {
                    delete groupOpts.traces[0][attr];
                    if (isOrientation) {
                      for (var j = 0; j < groupOpts.traces.length - 1; j++) {
                        var trace2 = groupOpts.traces[j];
                        if (trace2._input.fill !== trace2.fill) {
                          trace2.fill = groupOpts.fillDflt;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
          return groupOpts;
        }
      };
    }
  });

  // src/traces/scatter/marker_defaults.js
  var require_marker_defaults = __commonJS({
    "src/traces/scatter/marker_defaults.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleDefaults = require_defaults2();
      var subTypes = require_subtypes();
      module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts = {}) {
        var isBubble = subTypes.isBubble(traceIn);
        var lineColor = (traceIn.line || {}).color;
        var defaultMLC;
        if (lineColor) defaultColor = lineColor;
        coerce("marker.symbol");
        coerce("marker.opacity", isBubble ? 0.7 : 1);
        coerce("marker.size");
        if (!opts.noAngle) {
          coerce("marker.angle");
          if (!opts.noAngleRef) coerce("marker.angleref");
          if (!opts.noStandOff) coerce("marker.standoff");
        }
        coerce("marker.color", defaultColor);
        if (hasColorscale(traceIn, "marker")) {
          colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "marker.", cLetter: "c" });
        }
        if (!opts.noSelect) {
          coerce("selected.marker.color");
          coerce("unselected.marker.color");
          coerce("selected.marker.size");
          coerce("unselected.marker.size");
        }
        if (!opts.noLine) {
          if (lineColor && !Array.isArray(lineColor) && traceOut.marker.color !== lineColor) {
            defaultMLC = lineColor;
          } else if (isBubble) {
            defaultMLC = Color2.background;
          } else {
            defaultMLC = Color2.defaultLine;
          }
          coerce("marker.line.color", defaultMLC);
          if (hasColorscale(traceIn, "marker.line")) {
            colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "marker.line.", cLetter: "c" });
          }
          coerce("marker.line.width", isBubble ? 1 : 0);
          if (!opts.noLineDash) coerce("marker.line.dash");
        }
        if (isBubble) {
          coerce("marker.sizeref");
          coerce("marker.sizemin");
          coerce("marker.sizemode");
        }
        if (opts.gradient) {
          var gradientType = coerce("marker.gradient.type");
          if (gradientType !== "none") coerce("marker.gradient.color");
        }
      };
    }
  });

  // src/traces/scatter/line_defaults.js
  var require_line_defaults = __commonJS({
    "src/traces/scatter/line_defaults.js"(exports, module) {
      "use strict";
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleDefaults = require_defaults2();
      module.exports = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
        if (!opts) opts = {};
        var markerColor = (traceIn.marker || {}).color;
        if (markerColor && markerColor._inputArray) markerColor = markerColor._inputArray;
        coerce("line.color", defaultColor);
        if (hasColorscale(traceIn, "line")) {
          colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "line.", cLetter: "c" });
        } else {
          var lineColorDflt = (isArrayOrTypedArray(markerColor) ? false : markerColor) || defaultColor;
          coerce("line.color", lineColorDflt);
        }
        coerce("line.width");
        if (!opts.noDash) coerce("line.dash");
        if (opts.backoff) coerce("line.backoff");
      };
    }
  });

  // src/traces/scatter/line_shape_defaults.js
  var require_line_shape_defaults = __commonJS({
    "src/traces/scatter/line_shape_defaults.js"(exports, module) {
      "use strict";
      module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) {
        var shape = coerce("line.shape");
        if (shape === "spline") coerce("line.smoothing");
      };
    }
  });

  // src/traces/scatter/text_defaults.js
  var require_text_defaults = __commonJS({
    "src/traces/scatter/text_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function(traceIn, traceOut, layout, coerce, opts) {
        opts = opts || {};
        coerce("textposition");
        Lib.coerceFont(coerce, "textfont", opts.font || layout.font, opts);
        if (!opts.noSelect) {
          coerce("selected.textfont.color");
          coerce("unselected.textfont.color");
        }
      };
    }
  });

  // src/traces/scatter/fillcolor_defaults.js
  var require_fillcolor_defaults = __commonJS({
    "src/traces/scatter/fillcolor_defaults.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      function averageColors(colorscale) {
        var color2 = Color2.interpolate(colorscale[0][1], colorscale[1][1], 0.5);
        for (var i = 2; i < colorscale.length; i++) {
          var averageColorI = Color2.interpolate(colorscale[i - 1][1], colorscale[i][1], 0.5);
          color2 = Color2.interpolate(color2, averageColorI, colorscale[i - 1][0] / colorscale[i][0]);
        }
        return color2;
      }
      module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce, opts) {
        if (!opts) opts = {};
        var inheritColorFromMarker = false;
        if (traceOut.marker) {
          var markerColor = traceOut.marker.color;
          var markerLineColor = (traceOut.marker.line || {}).color;
          if (markerColor && !isArrayOrTypedArray(markerColor)) {
            inheritColorFromMarker = markerColor;
          } else if (markerLineColor && !isArrayOrTypedArray(markerLineColor)) {
            inheritColorFromMarker = markerLineColor;
          }
        }
        var averageGradientColor;
        if (opts.moduleHasFillgradient) {
          var gradientOrientation = coerce("fillgradient.type");
          if (gradientOrientation !== "none") {
            coerce("fillgradient.start");
            coerce("fillgradient.stop");
            var gradientColorscale = coerce("fillgradient.colorscale");
            if (gradientColorscale) {
              averageGradientColor = averageColors(gradientColorscale);
            }
          }
        }
        coerce("fillcolor", Color2.addOpacity(
          (traceOut.line || {}).color || inheritColorFromMarker || averageGradientColor || defaultColor,
          0.5
        ));
      };
    }
  });

  // src/traces/scatter/defaults.js
  var require_defaults8 = __commonJS({
    "src/traces/scatter/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Registry = require_registry();
      var attributes = require_attributes12();
      var constants = require_constants8();
      var subTypes = require_subtypes();
      var handleXYDefaults = require_xy_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var handleStackDefaults = require_stack_defaults();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleLineShapeDefaults = require_line_shape_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var coercePattern = require_lib().coercePattern;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
        if (!len) traceOut.visible = false;
        if (!traceOut.visible) return;
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("zorder");
        var stackGroupOpts = handleStackDefaults(traceIn, traceOut, layout, coerce);
        if (layout.scattermode === "group" && traceOut.orientation === void 0) {
          coerce("orientation", "v");
        }
        var defaultMode = !stackGroupOpts && len < constants.PTS_LINESONLY ? "lines+markers" : "lines";
        coerce("text");
        coerce("hovertext");
        coerce("mode", defaultMode);
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { gradient: true });
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, { backoff: true });
          handleLineShapeDefaults(traceIn, traceOut, coerce);
          coerce("connectgaps");
          coerce("line.simplify");
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce);
        }
        var dfltHoverOn = [];
        if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
          coerce("cliponaxis");
          coerce("marker.maxdisplayed");
          dfltHoverOn.push("points");
        }
        coerce("fill", stackGroupOpts ? stackGroupOpts.fillDflt : "none");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce, {
            moduleHasFillgradient: true
          });
          if (!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
          coercePattern(coerce, "fillpattern", traceOut.fillcolor, false);
        }
        var lineColor = (traceOut.line || {}).color;
        var markerColor = (traceOut.marker || {}).color;
        if (traceOut.fill === "tonext" || traceOut.fill === "toself") {
          dfltHoverOn.push("fills");
        }
        coerce("hoveron", dfltHoverOn.join("+") || "points");
        if (traceOut.hoveron !== "fills") {
          coerce("hovertemplate");
          coerce("hovertemplatefallback");
        }
        var errorBarsSupplyDefaults = Registry.getComponentMethod("errorbars", "supplyDefaults");
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "y" });
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "x", inherit: "y" });
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/scatter/grouping_defaults.js
  var require_grouping_defaults = __commonJS({
    "src/traces/scatter/grouping_defaults.js"(exports, module) {
      "use strict";
      var getAxisGroup = require_constraints().getAxisGroup;
      module.exports = function handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce, barmode) {
        var orientation = traceOut.orientation;
        var posAxId = traceOut[{ v: "x", h: "y" }[orientation] + "axis"];
        var groupId = getAxisGroup(fullLayout, posAxId) + orientation;
        var alignmentOpts = fullLayout._alignmentOpts || {};
        var alignmentgroup = coerce("alignmentgroup");
        var alignmentGroups = alignmentOpts[groupId];
        if (!alignmentGroups) alignmentGroups = alignmentOpts[groupId] = {};
        var alignmentGroupOpts = alignmentGroups[alignmentgroup];
        if (alignmentGroupOpts) {
          alignmentGroupOpts.traces.push(traceOut);
        } else {
          alignmentGroupOpts = alignmentGroups[alignmentgroup] = {
            traces: [traceOut],
            alignmentIndex: Object.keys(alignmentGroups).length,
            offsetGroups: {}
          };
        }
        var offsetgroup = coerce("offsetgroup") || "";
        var offsetGroups = alignmentGroupOpts.offsetGroups;
        var offsetGroupOpts = offsetGroups[offsetgroup];
        traceOut._offsetIndex = 0;
        if (barmode !== "group" || offsetgroup) {
          if (!offsetGroupOpts) {
            offsetGroupOpts = offsetGroups[offsetgroup] = {
              offsetIndex: Object.keys(offsetGroups).length
            };
          }
          traceOut._offsetIndex = offsetGroupOpts.offsetIndex;
        }
      };
    }
  });

  // src/traces/scatter/cross_trace_defaults.js
  var require_cross_trace_defaults2 = __commonJS({
    "src/traces/scatter/cross_trace_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleGroupingDefaults = require_grouping_defaults();
      var attributes = require_attributes12();
      module.exports = function crossTraceDefaults(fullData, fullLayout) {
        var traceIn, traceOut, i;
        var scattermode = fullLayout.scattermode;
        function coerce(attr) {
          return Lib.coerce(traceOut._input, traceOut, attributes, attr);
        }
        if (fullLayout.scattermode === "group") {
          for (i = 0; i < fullData.length; i++) {
            traceOut = fullData[i];
            if (traceOut.type === "scatter") {
              traceIn = traceOut._input;
              handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce, scattermode);
            }
          }
        }
        for (i = 0; i < fullData.length; i++) {
          var tracei = fullData[i];
          if (tracei.type !== "scatter") continue;
          var filli = tracei.fill;
          if (filli === "none" || filli === "toself") continue;
          tracei.opacity = void 0;
          if (filli === "tonexty" || filli === "tonextx") {
            for (var j = i - 1; j >= 0; j--) {
              var tracej = fullData[j];
              if (tracej.type === "scatter" && tracej.xaxis === tracei.xaxis && tracej.yaxis === tracei.yaxis) {
                tracej.opacity = void 0;
                break;
              }
            }
          }
        }
      };
    }
  });

  // src/traces/scatter/layout_defaults.js
  var require_layout_defaults3 = __commonJS({
    "src/traces/scatter/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes3();
      module.exports = function(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        var groupBarmode = layoutOut.barmode === "group";
        if (layoutOut.scattermode === "group") {
          coerce("scattergap", groupBarmode ? layoutOut.bargap : 0.2);
        }
      };
    }
  });

  // src/plots/cartesian/align_period.js
  var require_align_period = __commonJS({
    "src/plots/cartesian/align_period.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var dateTime2ms = Lib.dateTime2ms;
      var incrementMonth = Lib.incrementMonth;
      var constants = require_numerical();
      var ONEAVGMONTH = constants.ONEAVGMONTH;
      module.exports = function alignPeriod(trace, ax, axLetter, vals) {
        if (ax.type !== "date") return { vals };
        var alignment = trace[axLetter + "periodalignment"];
        if (!alignment) return { vals };
        var period = trace[axLetter + "period"];
        var mPeriod;
        if (isNumeric(period)) {
          period = +period;
          if (period <= 0) return { vals };
        } else if (typeof period === "string" && period.charAt(0) === "M") {
          var n = +period.substring(1);
          if (n > 0 && Math.round(n) === n) {
            mPeriod = n;
          } else return { vals };
        }
        var calendar = ax.calendar;
        var isStart = "start" === alignment;
        var isEnd = "end" === alignment;
        var period0 = trace[axLetter + "period0"];
        var base = dateTime2ms(period0, calendar) || 0;
        var newVals = [];
        var starts = [];
        var ends = [];
        var len = vals.length;
        for (var i = 0; i < len; i++) {
          var v = vals[i];
          var nEstimated, startTime, endTime;
          if (mPeriod) {
            nEstimated = Math.round((v - base) / (mPeriod * ONEAVGMONTH));
            endTime = incrementMonth(base, mPeriod * nEstimated, calendar);
            while (endTime > v) {
              endTime = incrementMonth(endTime, -mPeriod, calendar);
            }
            while (endTime <= v) {
              endTime = incrementMonth(endTime, mPeriod, calendar);
            }
            startTime = incrementMonth(endTime, -mPeriod, calendar);
          } else {
            nEstimated = Math.round((v - base) / period);
            endTime = base + nEstimated * period;
            while (endTime > v) {
              endTime -= period;
            }
            while (endTime <= v) {
              endTime += period;
            }
            startTime = endTime - period;
          }
          newVals[i] = isStart ? startTime : isEnd ? endTime : (startTime + endTime) / 2;
          starts[i] = startTime;
          ends[i] = endTime;
        }
        return {
          vals: newVals,
          starts,
          ends
        };
      };
    }
  });

  // src/traces/scatter/colorscale_calc.js
  var require_colorscale_calc = __commonJS({
    "src/traces/scatter/colorscale_calc.js"(exports, module) {
      "use strict";
      var hasColorscale = require_helpers().hasColorscale;
      var calcColorscale = require_calc();
      var subTypes = require_subtypes();
      module.exports = function calcMarkerColorscale(gd, trace) {
        if (subTypes.hasLines(trace) && hasColorscale(trace, "line")) {
          calcColorscale(gd, trace, {
            vals: trace.line.color,
            containerStr: "line",
            cLetter: "c"
          });
        }
        if (subTypes.hasMarkers(trace)) {
          if (hasColorscale(trace, "marker")) {
            calcColorscale(gd, trace, {
              vals: trace.marker.color,
              containerStr: "marker",
              cLetter: "c"
            });
          }
          if (hasColorscale(trace, "marker.line")) {
            calcColorscale(gd, trace, {
              vals: trace.marker.line.color,
              containerStr: "marker.line",
              cLetter: "c"
            });
          }
        }
      };
    }
  });

  // src/traces/scatter/arrays_to_calcdata.js
  var require_arrays_to_calcdata = __commonJS({
    "src/traces/scatter/arrays_to_calcdata.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function arraysToCalcdata(cd, trace) {
        for (var i = 0; i < cd.length; i++) cd[i].i = i;
        Lib.mergeArray(trace.text, cd, "tx");
        Lib.mergeArray(trace.texttemplate, cd, "txt");
        Lib.mergeArray(trace.hovertext, cd, "htx");
        Lib.mergeArray(trace.customdata, cd, "data");
        Lib.mergeArray(trace.textposition, cd, "tp");
        if (trace.textfont) {
          Lib.mergeArrayCastPositive(trace.textfont.size, cd, "ts");
          Lib.mergeArray(trace.textfont.color, cd, "tc");
          Lib.mergeArray(trace.textfont.family, cd, "tf");
          Lib.mergeArray(trace.textfont.weight, cd, "tw");
          Lib.mergeArray(trace.textfont.style, cd, "ty");
          Lib.mergeArray(trace.textfont.variant, cd, "tv");
          Lib.mergeArray(trace.textfont.textcase, cd, "tC");
          Lib.mergeArray(trace.textfont.lineposition, cd, "tE");
          Lib.mergeArray(trace.textfont.shadow, cd, "tS");
        }
        var marker = trace.marker;
        if (marker) {
          Lib.mergeArrayCastPositive(marker.size, cd, "ms");
          Lib.mergeArrayCastPositive(marker.opacity, cd, "mo");
          Lib.mergeArray(marker.symbol, cd, "mx");
          Lib.mergeArray(marker.angle, cd, "ma");
          Lib.mergeArray(marker.standoff, cd, "mf");
          Lib.mergeArray(marker.color, cd, "mc");
          var markerLine = marker.line;
          if (marker.line) {
            Lib.mergeArray(markerLine.color, cd, "mlc");
            Lib.mergeArrayCastPositive(markerLine.width, cd, "mlw");
            Lib.mergeArray(markerLine.dash, cd, "mld");
          }
          var markerGradient = marker.gradient;
          if (markerGradient && markerGradient.type !== "none") {
            Lib.mergeArray(markerGradient.type, cd, "mgt");
            Lib.mergeArray(markerGradient.color, cd, "mgc");
          }
        }
      };
    }
  });

  // src/traces/scatter/calc_selection.js
  var require_calc_selection = __commonJS({
    "src/traces/scatter/calc_selection.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function calcSelection(cd, trace) {
        if (Lib.isArrayOrTypedArray(trace.selectedpoints)) {
          Lib.tagSelected(cd, trace);
        }
      };
    }
  });

  // src/traces/scatter/calc.js
  var require_calc3 = __commonJS({
    "src/traces/scatter/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var BADNUM = require_numerical().BADNUM;
      var subTypes = require_subtypes();
      var calcColorscale = require_colorscale_calc();
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcSelection = require_calc_selection();
      function calc(gd, trace) {
        var fullLayout = gd._fullLayout;
        var xa = trace._xA = Axes.getFromId(gd, trace.xaxis || "x", "x");
        var ya = trace._yA = Axes.getFromId(gd, trace.yaxis || "y", "y");
        var origX = xa.makeCalcdata(trace, "x");
        var origY = ya.makeCalcdata(trace, "y");
        var xObj = alignPeriod(trace, xa, "x", origX);
        var yObj = alignPeriod(trace, ya, "y", origY);
        var x = xObj.vals;
        var y = yObj.vals;
        var serieslen = trace._length;
        var cd = new Array(serieslen);
        var ids = trace.ids;
        var stackGroupOpts = getStackOpts(trace, fullLayout, xa, ya);
        var interpolateGaps = false;
        var isV, i, j, k, interpolate, vali;
        setFirstScatter(fullLayout, trace);
        var xAttr = "x";
        var yAttr = "y";
        var posAttr;
        if (stackGroupOpts) {
          Lib.pushUnique(stackGroupOpts.traceIndices, trace.index);
          isV = stackGroupOpts.orientation === "v";
          if (isV) {
            yAttr = "s";
            posAttr = "x";
          } else {
            xAttr = "s";
            posAttr = "y";
          }
          interpolate = stackGroupOpts.stackgaps === "interpolate";
        } else {
          var ppad = calcMarkerSize(trace, serieslen);
          calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
        }
        var hasPeriodX = !!trace.xperiodalignment;
        var hasPeriodY = !!trace.yperiodalignment;
        for (i = 0; i < serieslen; i++) {
          var cdi = cd[i] = {};
          var xValid = isNumeric(x[i]);
          var yValid = isNumeric(y[i]);
          if (xValid && yValid) {
            cdi[xAttr] = x[i];
            cdi[yAttr] = y[i];
            if (hasPeriodX) {
              cdi.orig_x = origX[i];
              cdi.xEnd = xObj.ends[i];
              cdi.xStart = xObj.starts[i];
            }
            if (hasPeriodY) {
              cdi.orig_y = origY[i];
              cdi.yEnd = yObj.ends[i];
              cdi.yStart = yObj.starts[i];
            }
          } else if (stackGroupOpts && (isV ? xValid : yValid)) {
            cdi[posAttr] = isV ? x[i] : y[i];
            cdi.gap = true;
            if (interpolate) {
              cdi.s = BADNUM;
              interpolateGaps = true;
            } else {
              cdi.s = 0;
            }
          } else {
            cdi[xAttr] = cdi[yAttr] = BADNUM;
          }
          if (ids) {
            cdi.id = String(ids[i]);
          }
        }
        arraysToCalcdata(cd, trace);
        calcColorscale(gd, trace);
        calcSelection(cd, trace);
        if (stackGroupOpts) {
          i = 0;
          while (i < cd.length) {
            if (cd[i][posAttr] === BADNUM) {
              cd.splice(i, 1);
            } else i++;
          }
          Lib.sort(cd, function(a, b) {
            return a[posAttr] - b[posAttr] || a.i - b.i;
          });
          if (interpolateGaps) {
            i = 0;
            while (i < cd.length - 1 && cd[i].gap) {
              i++;
            }
            vali = cd[i].s;
            if (!vali) vali = cd[i].s = 0;
            for (j = 0; j < i; j++) {
              cd[j].s = vali;
            }
            k = cd.length - 1;
            while (k > i && cd[k].gap) {
              k--;
            }
            vali = cd[k].s;
            for (j = cd.length - 1; j > k; j--) {
              cd[j].s = vali;
            }
            while (i < k) {
              i++;
              if (cd[i].gap) {
                j = i + 1;
                while (cd[j].gap) {
                  j++;
                }
                var pos0 = cd[i - 1][posAttr];
                var size0 = cd[i - 1].s;
                var m = (cd[j].s - size0) / (cd[j][posAttr] - pos0);
                while (i < j) {
                  cd[i].s = size0 + (cd[i][posAttr] - pos0) * m;
                  i++;
                }
              }
            }
          }
        }
        return cd;
      }
      function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) {
        var serieslen = trace._length;
        var fullLayout = gd._fullLayout;
        var xId = xa._id;
        var yId = ya._id;
        var firstScatter = fullLayout._firstScatter[firstScatterGroup(trace)] === trace.uid;
        var stackOrientation = (getStackOpts(trace, fullLayout, xa, ya) || {}).orientation;
        var fill = trace.fill;
        xa._minDtick = 0;
        ya._minDtick = 0;
        var xOptions = { padded: true };
        var yOptions = { padded: true };
        if (ppad) {
          xOptions.ppad = yOptions.ppad = ppad;
        }
        var openEnded = serieslen < 2 || x[0] !== x[serieslen - 1] || y[0] !== y[serieslen - 1];
        if (openEnded && (fill === "tozerox" || fill === "tonextx" && (firstScatter || stackOrientation === "h"))) {
          xOptions.tozero = true;
        } else if (!(trace.error_y || {}).visible && // if no error bars, markers or text, or fill to y=0 remove x padding
        (fill === "tonexty" || fill === "tozeroy" || !subTypes.hasMarkers(trace) && !subTypes.hasText(trace))) {
          xOptions.padded = false;
          xOptions.ppad = 0;
        }
        if (openEnded && (fill === "tozeroy" || fill === "tonexty" && (firstScatter || stackOrientation === "v"))) {
          yOptions.tozero = true;
        } else if (fill === "tonextx" || fill === "tozerox") {
          yOptions.padded = false;
        }
        if (xId) trace._extremes[xId] = Axes.findExtremes(xa, x, xOptions);
        if (yId) trace._extremes[yId] = Axes.findExtremes(ya, y, yOptions);
      }
      function calcMarkerSize(trace, serieslen) {
        if (!subTypes.hasMarkers(trace)) return;
        var marker = trace.marker;
        var sizeref = 1.6 * (trace.marker.sizeref || 1);
        var markerTrans;
        if (trace.marker.sizemode === "area") {
          markerTrans = function(v) {
            return Math.max(Math.sqrt((v || 0) / sizeref), 3);
          };
        } else {
          markerTrans = function(v) {
            return Math.max((v || 0) / sizeref, 3);
          };
        }
        if (Lib.isArrayOrTypedArray(marker.size)) {
          var ax = { type: "linear" };
          Axes.setConvert(ax);
          var s = ax.makeCalcdata(trace.marker, "size");
          var sizeOut = new Array(serieslen);
          for (var i = 0; i < serieslen; i++) {
            sizeOut[i] = markerTrans(s[i]);
          }
          return sizeOut;
        } else {
          return markerTrans(marker.size);
        }
      }
      function setFirstScatter(fullLayout, trace) {
        var group = firstScatterGroup(trace);
        var firstScatter = fullLayout._firstScatter;
        if (!firstScatter[group]) firstScatter[group] = trace.uid;
      }
      function firstScatterGroup(trace) {
        var stackGroup = trace.stackgroup;
        return trace.xaxis + trace.yaxis + trace.type + (stackGroup ? "-" + stackGroup : "");
      }
      function getStackOpts(trace, fullLayout, xa, ya) {
        var stackGroup = trace.stackgroup;
        if (!stackGroup) return;
        var stackOpts = fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup];
        var stackAx = stackOpts.orientation === "v" ? ya : xa;
        if (stackAx.type === "linear" || stackAx.type === "log") return stackOpts;
      }
      module.exports = {
        calc,
        calcMarkerSize,
        calcAxisExpansion,
        setFirstScatter,
        getStackOpts
      };
    }
  });

  // src/traces/bar/sieve.js
  var require_sieve = __commonJS({
    "src/traces/bar/sieve.js"(exports, module) {
      "use strict";
      module.exports = Sieve;
      var distinctVals = require_lib().distinctVals;
      function Sieve(traces, opts) {
        this.traces = traces;
        this.sepNegVal = opts.sepNegVal;
        this.overlapNoMerge = opts.overlapNoMerge;
        var width1 = Infinity;
        var axLetter = opts.posAxis._id.charAt(0);
        var positions = [];
        for (var i = 0; i < traces.length; i++) {
          var trace = traces[i];
          for (var j = 0; j < trace.length; j++) {
            var bar = trace[j];
            var pos = bar.p;
            if (pos === void 0) {
              pos = bar[axLetter];
            }
            if (pos !== void 0) positions.push(pos);
          }
          if (trace[0] && trace[0].width1) {
            width1 = Math.min(trace[0].width1, width1);
          }
        }
        this.positions = positions;
        var dv = distinctVals(positions);
        this.distinctPositions = dv.vals;
        if (dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1;
        else this.minDiff = Math.min(dv.minDiff, width1);
        var type = (opts.posAxis || {}).type;
        if (type === "category" || type === "multicategory") {
          this.minDiff = 1;
        }
        this.binWidth = this.minDiff;
        this.bins = {};
      }
      Sieve.prototype.put = function put(position, group, value) {
        var label = this.getLabel(position, group, value);
        var oldValue = this.bins[label] || 0;
        this.bins[label] = oldValue + value;
        return oldValue;
      };
      Sieve.prototype.get = function get(position, group, value) {
        var label = this.getLabel(position, group, value);
        return this.bins[label] || 0;
      };
      Sieve.prototype.getLabel = function getLabel(position, group, value) {
        var prefix = value < 0 && this.sepNegVal ? "v" : "^";
        var label = this.overlapNoMerge ? position : Math.round(position / this.binWidth);
        return prefix + label + "g" + group;
      };
    }
  });

  // src/traces/bar/constants.js
  var require_constants9 = __commonJS({
    "src/traces/bar/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // padding in pixels around text
        TEXTPAD: 3,
        // 'value' and 'label' are not really necessary for bar traces,
        // but they were made available to `texttemplate` (maybe by accident)
        // via tokens `%{value}` and `%{label}` starting in 1.50.0,
        // so let's include them in the event data also.
        eventDataKeys: ["value", "label"]
      };
    }
  });

  // src/traces/bar/cross_trace_calc.js
  var require_cross_trace_calc = __commonJS({
    "src/traces/bar/cross_trace_calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var { isArrayOrTypedArray } = require_lib();
      var { BADNUM } = require_numerical();
      var Registry = require_registry();
      var Axes = require_axes();
      var { getAxisGroup } = require_constraints();
      var Sieve = require_sieve();
      var { TEXTPAD } = require_constants9();
      var { LINE_SPACING } = require_alignment();
      var { BR_TAG_ALL } = require_svg_text_utils();
      function crossTraceCalc(gd, plotinfo) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var fullLayout = gd._fullLayout;
        var fullTraces = gd._fullData;
        var calcTraces = gd.calcdata;
        var calcTracesHorz = [];
        var calcTracesVert = [];
        for (var i = 0; i < fullTraces.length; i++) {
          var fullTrace = fullTraces[i];
          if (fullTrace.visible === true && Registry.traceIs(fullTrace, "bar") && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) {
            if (fullTrace.orientation === "h") {
              calcTracesHorz.push(calcTraces[i]);
            } else {
              calcTracesVert.push(calcTraces[i]);
            }
            if (fullTrace._computePh) {
              var cd = gd.calcdata[i];
              for (var j = 0; j < cd.length; j++) {
                if (typeof cd[j].ph0 === "function") cd[j].ph0 = cd[j].ph0();
                if (typeof cd[j].ph1 === "function") cd[j].ph1 = cd[j].ph1();
              }
            }
          }
        }
        var opts = {
          xCat: xa.type === "category" || xa.type === "multicategory",
          yCat: ya.type === "category" || ya.type === "multicategory",
          mode: fullLayout.barmode,
          norm: fullLayout.barnorm,
          gap: fullLayout.bargap,
          groupgap: fullLayout.bargroupgap
        };
        setGroupPositions(gd, xa, ya, calcTracesVert, opts);
        setGroupPositions(gd, ya, xa, calcTracesHorz, opts);
      }
      function setGroupPositions(gd, pa, sa, calcTraces, opts) {
        if (!calcTraces.length) return;
        var excluded;
        var included;
        var i, calcTrace, fullTrace;
        initBase(sa, calcTraces);
        switch (opts.mode) {
          case "overlay":
            setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces, opts);
            break;
          case "group":
            excluded = [];
            included = [];
            for (i = 0; i < calcTraces.length; i++) {
              calcTrace = calcTraces[i];
              fullTrace = calcTrace[0].trace;
              if (fullTrace.offset === void 0) included.push(calcTrace);
              else excluded.push(calcTrace);
            }
            if (included.length) {
              setGroupPositionsInGroupMode(gd, pa, sa, included, opts);
            }
            if (excluded.length) {
              setGroupPositionsInOverlayMode(gd, pa, sa, excluded, opts);
            }
            break;
          case "stack":
          case "relative":
            excluded = [];
            included = [];
            for (i = 0; i < calcTraces.length; i++) {
              calcTrace = calcTraces[i];
              fullTrace = calcTrace[0].trace;
              if (fullTrace.base === void 0) included.push(calcTrace);
              else excluded.push(calcTrace);
            }
            standardizeCornerradius(included);
            if (included.length) {
              setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included, opts);
            }
            if (excluded.length) {
              setGroupPositionsInOverlayMode(gd, pa, sa, excluded, opts);
            }
            break;
        }
        setCornerradius(calcTraces);
        collectExtents(calcTraces, pa);
      }
      function setCornerradius(calcTraces) {
        var i, calcTrace, fullTrace, t, cr, crValue, crForm;
        for (i = 0; i < calcTraces.length; i++) {
          calcTrace = calcTraces[i];
          fullTrace = calcTrace[0].trace;
          t = calcTrace[0].t;
          if (t.cornerradiusvalue === void 0) {
            cr = fullTrace.marker ? fullTrace.marker.cornerradius : void 0;
            if (cr !== void 0) {
              crValue = isNumeric(cr) ? +cr : +cr.slice(0, -1);
              crForm = isNumeric(cr) ? "px" : "%";
              t.cornerradiusvalue = crValue;
              t.cornerradiusform = crForm;
            }
          }
        }
      }
      function standardizeCornerradius(calcTraces) {
        if (calcTraces.length < 2) return;
        var i, calcTrace, fullTrace, t;
        var cr, crValue, crForm;
        for (i = 0; i < calcTraces.length; i++) {
          calcTrace = calcTraces[i];
          fullTrace = calcTrace[0].trace;
          cr = fullTrace.marker ? fullTrace.marker.cornerradius : void 0;
          if (cr !== void 0) break;
        }
        if (cr !== void 0) {
          crValue = isNumeric(cr) ? +cr : +cr.slice(0, -1);
          crForm = isNumeric(cr) ? "px" : "%";
          for (i = 0; i < calcTraces.length; i++) {
            calcTrace = calcTraces[i];
            t = calcTrace[0].t;
            t.cornerradiusvalue = crValue;
            t.cornerradiusform = crForm;
          }
        }
      }
      function initBase(sa, calcTraces) {
        var i, j;
        for (i = 0; i < calcTraces.length; i++) {
          var cd = calcTraces[i];
          var trace = cd[0].trace;
          var base = trace.type === "funnel" ? trace._base : trace.base;
          var b;
          var scalendar = trace.orientation === "h" ? trace.xcalendar : trace.ycalendar;
          var d2c = sa.type === "category" || sa.type === "multicategory" ? function() {
            return null;
          } : sa.d2c;
          if (isArrayOrTypedArray(base)) {
            for (j = 0; j < Math.min(base.length, cd.length); j++) {
              b = d2c(base[j], 0, scalendar);
              if (isNumeric(b)) {
                cd[j].b = +b;
                cd[j].hasB = 1;
              } else cd[j].b = 0;
            }
            for (; j < cd.length; j++) {
              cd[j].b = 0;
            }
          } else {
            b = d2c(base, 0, scalendar);
            var hasBase = isNumeric(b);
            b = hasBase ? b : 0;
            for (j = 0; j < cd.length; j++) {
              cd[j].b = b;
              if (hasBase) cd[j].hasB = 1;
            }
          }
        }
      }
      function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces, opts) {
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var sieve = new Sieve([calcTrace], {
            posAxis: pa,
            sepNegVal: false,
            overlapNoMerge: !opts.norm
          });
          setOffsetAndWidth(gd, pa, sieve, opts);
          if (opts.norm) {
            sieveBars(sieve);
            normalizeBars(sa, sieve, opts);
          } else {
            setBaseAndTop(sa, sieve);
          }
        }
      }
      function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces, opts) {
        var sieve = new Sieve(calcTraces, {
          posAxis: pa,
          sepNegVal: false,
          overlapNoMerge: !opts.norm
        });
        setOffsetAndWidth(gd, pa, sieve, opts);
        unhideBarsWithinTrace(sieve, pa);
        if (opts.norm) {
          sieveBars(sieve);
          normalizeBars(sa, sieve, opts);
        } else {
          setBaseAndTop(sa, sieve);
        }
      }
      function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces, opts) {
        var sieve = new Sieve(calcTraces, {
          posAxis: pa,
          sepNegVal: opts.mode === "relative",
          overlapNoMerge: !(opts.norm || opts.mode === "stack" || opts.mode === "relative")
        });
        setOffsetAndWidth(gd, pa, sieve, opts);
        stackBars(sa, sieve, opts);
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var offsetIndex = calcTrace[0].t.offsetindex;
          for (var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];
            if (bar.s !== BADNUM) {
              var isOutmostBar = bar.b + bar.s === sieve.get(bar.p, offsetIndex, bar.s);
              if (isOutmostBar) bar._outmost = true;
            }
          }
        }
        if (opts.norm) normalizeBars(sa, sieve, opts);
      }
      function setOffsetAndWidth(gd, pa, sieve, opts) {
        var fullLayout = gd._fullLayout;
        var positions = sieve.positions;
        var distinctPositions = sieve.distinctPositions;
        var minDiff = sieve.minDiff;
        var calcTraces = sieve.traces;
        var nTraces = calcTraces.length;
        var overlap = positions.length !== distinctPositions.length;
        var barGroupWidth = minDiff * (1 - opts.gap);
        var barWidthPlusGap;
        var barWidth;
        var offsetFromCenter;
        var alignmentGroups;
        if (pa._id === "angularaxis") {
          barWidthPlusGap = barGroupWidth;
          barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0));
          offsetFromCenter = -barWidth / 2;
        } else {
          var groupId = getAxisGroup(fullLayout, pa._id) + calcTraces[0][0].trace.orientation;
          alignmentGroups = fullLayout._alignmentOpts[groupId] || {};
        }
        for (var i = 0; i < nTraces; i++) {
          var calcTrace = calcTraces[i];
          var trace = calcTrace[0].trace;
          if (pa._id !== "angularaxis") {
            var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {};
            var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length;
            if (nOffsetGroups) {
              barWidthPlusGap = barGroupWidth / nOffsetGroups;
            } else {
              barWidthPlusGap = overlap ? barGroupWidth / nTraces : barGroupWidth;
            }
            barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0));
            if (nOffsetGroups) {
              offsetFromCenter = ((2 * trace._offsetIndex + 1 - nOffsetGroups) * barWidthPlusGap - barWidth) / 2;
            } else {
              offsetFromCenter = overlap ? ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : -barWidth / 2;
            }
          }
          var t = calcTrace[0].t;
          t.barwidth = barWidth;
          t.offsetindex = trace._offsetIndex || 0;
          t.poffset = offsetFromCenter;
          t.bargroupwidth = barGroupWidth;
          t.bardelta = minDiff;
        }
        sieve.binWidth = calcTraces[0][0].t.barwidth / 100;
        applyAttributes(sieve);
        setBarCenterAndWidth(pa, sieve);
        if (pa._id === "angularaxis") {
          updatePositionAxis(pa, sieve);
        } else {
          updatePositionAxis(pa, sieve, overlap);
        }
      }
      function applyAttributes(sieve) {
        var calcTraces = sieve.traces;
        var i, j;
        for (i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var calcTrace0 = calcTrace[0];
          var fullTrace = calcTrace0.trace;
          var t = calcTrace0.t;
          var offset = fullTrace._offset || fullTrace.offset;
          var initialPoffset = t.poffset;
          var newPoffset;
          if (isArrayOrTypedArray(offset)) {
            newPoffset = Array.prototype.slice.call(offset, 0, calcTrace.length);
            for (j = 0; j < newPoffset.length; j++) {
              if (!isNumeric(newPoffset[j])) {
                newPoffset[j] = initialPoffset;
              }
            }
            for (j = newPoffset.length; j < calcTrace.length; j++) {
              newPoffset.push(initialPoffset);
            }
            t.poffset = newPoffset;
          } else if (offset !== void 0) {
            t.poffset = offset;
          }
          var width = fullTrace._width || fullTrace.width;
          var initialBarwidth = t.barwidth;
          if (isArrayOrTypedArray(width)) {
            var newBarwidth = Array.prototype.slice.call(width, 0, calcTrace.length);
            for (j = 0; j < newBarwidth.length; j++) {
              if (!isNumeric(newBarwidth[j])) newBarwidth[j] = initialBarwidth;
            }
            for (j = newBarwidth.length; j < calcTrace.length; j++) {
              newBarwidth.push(initialBarwidth);
            }
            t.barwidth = newBarwidth;
            if (offset === void 0) {
              newPoffset = [];
              for (j = 0; j < calcTrace.length; j++) {
                newPoffset.push(initialPoffset + (initialBarwidth - newBarwidth[j]) / 2);
              }
              t.poffset = newPoffset;
            }
          } else if (width !== void 0) {
            t.barwidth = width;
            if (offset === void 0) {
              t.poffset = initialPoffset + (initialBarwidth - width) / 2;
            }
          }
        }
      }
      function setBarCenterAndWidth(pa, sieve) {
        var calcTraces = sieve.traces;
        var pLetter = getAxisLetter(pa);
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var t = calcTrace[0].t;
          var poffset = t.poffset;
          var poffsetIsArray = isArrayOrTypedArray(poffset);
          var barwidth = t.barwidth;
          var barwidthIsArray = isArrayOrTypedArray(barwidth);
          for (var j = 0; j < calcTrace.length; j++) {
            var calcBar = calcTrace[j];
            var width = calcBar.w = barwidthIsArray ? barwidth[j] : barwidth;
            if (calcBar.p === void 0) {
              calcBar.p = calcBar[pLetter];
              calcBar["orig_" + pLetter] = calcBar[pLetter];
            }
            var delta = (poffsetIsArray ? poffset[j] : poffset) + width / 2;
            calcBar[pLetter] = calcBar.p + delta;
          }
        }
      }
      function updatePositionAxis(pa, sieve, allowMinDtick) {
        var calcTraces = sieve.traces;
        var minDiff = sieve.minDiff;
        var vpad = minDiff / 2;
        Axes.minDtick(pa, sieve.minDiff, sieve.distinctPositions[0], allowMinDtick);
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var calcTrace0 = calcTrace[0];
          var fullTrace = calcTrace0.trace;
          var pts = [];
          var bar, l, r, j;
          for (j = 0; j < calcTrace.length; j++) {
            bar = calcTrace[j];
            l = bar.p - vpad;
            r = bar.p + vpad;
            pts.push(l, r);
          }
          if (fullTrace.width || fullTrace.offset) {
            var t = calcTrace0.t;
            var poffset = t.poffset;
            var barwidth = t.barwidth;
            var poffsetIsArray = isArrayOrTypedArray(poffset);
            var barwidthIsArray = isArrayOrTypedArray(barwidth);
            for (j = 0; j < calcTrace.length; j++) {
              bar = calcTrace[j];
              var calcBarOffset = poffsetIsArray ? poffset[j] : poffset;
              var calcBarWidth = barwidthIsArray ? barwidth[j] : barwidth;
              l = bar.p + calcBarOffset;
              r = l + calcBarWidth;
              pts.push(l, r);
            }
          }
          fullTrace._extremes[pa._id] = Axes.findExtremes(pa, pts, { padded: false });
        }
      }
      function setBaseAndTop(sa, sieve) {
        var calcTraces = sieve.traces;
        var sLetter = getAxisLetter(sa);
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var fullTrace = calcTrace[0].trace;
          var isScatter = fullTrace.type === "scatter";
          var isVertical = fullTrace.orientation === "v";
          var pts = [];
          var tozero = false;
          for (var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];
            var base = isScatter ? 0 : bar.b;
            var top = isScatter ? isVertical ? bar.y : bar.x : base + bar.s;
            bar[sLetter] = top;
            pts.push(top);
            if (bar.hasB) pts.push(base);
            if (!bar.hasB || !bar.b) {
              tozero = true;
            }
          }
          const { ppadminus, ppadplus } = estimateAxisPaddingForText(fullTrace, calcTrace);
          fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
            tozero,
            padded: true,
            ppadplus,
            ppadminus
          });
        }
      }
      function stackBars(sa, sieve, opts) {
        var sLetter = getAxisLetter(sa);
        var calcTraces = sieve.traces;
        var calcTrace;
        var fullTrace;
        var isFunnel;
        var i, j;
        var bar;
        var offsetIndex;
        for (i = 0; i < calcTraces.length; i++) {
          calcTrace = calcTraces[i];
          fullTrace = calcTrace[0].trace;
          if (fullTrace.type === "funnel") {
            offsetIndex = calcTrace[0].t.offsetindex;
            for (j = 0; j < calcTrace.length; j++) {
              bar = calcTrace[j];
              if (bar.s !== BADNUM) {
                sieve.put(bar.p, offsetIndex, -0.5 * bar.s);
              }
            }
          }
        }
        for (i = 0; i < calcTraces.length; i++) {
          calcTrace = calcTraces[i];
          fullTrace = calcTrace[0].trace;
          isFunnel = fullTrace.type === "funnel";
          offsetIndex = fullTrace.type === "barpolar" ? 0 : calcTrace[0].t.offsetindex;
          var pts = [];
          for (j = 0; j < calcTrace.length; j++) {
            bar = calcTrace[j];
            if (bar.s !== BADNUM) {
              var value;
              if (isFunnel) {
                value = bar.s;
              } else {
                value = bar.s + bar.b;
              }
              var base = sieve.put(bar.p, offsetIndex, value);
              var top = base + value;
              bar.b = base;
              bar[sLetter] = top;
              if (!opts.norm) {
                pts.push(top);
                if (bar.hasB) {
                  pts.push(base);
                }
              }
            }
          }
          if (!opts.norm) {
            const { ppadminus, ppadplus } = estimateAxisPaddingForText(fullTrace, calcTrace);
            fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
              // N.B. we don't stack base with 'base',
              // so set tozero:true always!
              tozero: true,
              padded: true,
              ppadplus,
              ppadminus
            });
          }
        }
      }
      function sieveBars(sieve) {
        var calcTraces = sieve.traces;
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var offsetIndex = calcTrace[0].t.offsetindex;
          for (var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];
            if (bar.s !== BADNUM) {
              sieve.put(bar.p, offsetIndex, bar.b + bar.s);
            }
          }
        }
      }
      function unhideBarsWithinTrace(sieve, pa) {
        var calcTraces = sieve.traces;
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var fullTrace = calcTrace[0].trace;
          var offsetIndex = calcTrace[0].t.offsetindex;
          if (fullTrace.base === void 0) {
            var inTraceSieve = new Sieve([calcTrace], {
              posAxis: pa,
              sepNegVal: true,
              overlapNoMerge: true
            });
            for (var j = 0; j < calcTrace.length; j++) {
              var bar = calcTrace[j];
              if (bar.p !== BADNUM) {
                var base = inTraceSieve.put(bar.p, offsetIndex, bar.b + bar.s);
                if (base) bar.b = base;
              }
            }
          }
        }
      }
      function normalizeBars(sa, sieve, opts) {
        var calcTraces = sieve.traces;
        var sLetter = getAxisLetter(sa);
        var sTop = opts.norm === "fraction" ? 1 : 100;
        var sTiny = sTop / 1e9;
        var sMin = sa.l2c(sa.c2l(0));
        var sMax = opts.mode === "stack" ? sTop : sMin;
        function needsPadding(v) {
          return isNumeric(sa.c2l(v)) && (v < sMin - sTiny || v > sMax + sTiny || !isNumeric(sMin));
        }
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          var offsetIndex = calcTrace[0].t.offsetindex;
          var fullTrace = calcTrace[0].trace;
          var pts = [];
          var tozero = false;
          var padded = false;
          for (var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];
            if (bar.s !== BADNUM) {
              var scale = Math.abs(sTop / sieve.get(bar.p, offsetIndex, bar.s));
              bar.b *= scale;
              bar.s *= scale;
              var base = bar.b;
              var top = base + bar.s;
              bar[sLetter] = top;
              pts.push(top);
              padded = padded || needsPadding(top);
              if (bar.hasB) {
                pts.push(base);
                padded = padded || needsPadding(base);
              }
              if (!bar.hasB || !bar.b) {
                tozero = true;
              }
            }
          }
          const { ppadminus, ppadplus } = estimateAxisPaddingForText(fullTrace, calcTrace);
          fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
            tozero,
            padded,
            ppadplus,
            ppadminus
          });
        }
      }
      function estimateAxisPaddingForText(trace, calcTrace) {
        if (trace.orientation === "v" && (trace.text || trace.texttemplate) && trace.textposition === "outside" && (trace.textangle === "auto" || trace.textangle === 0)) {
          let countLines = function(text) {
            if (!text || typeof text !== "string") return 0;
            return (text.match(BR_TAG_ALL) || []).length + 1;
          };
          var nLines;
          if (trace.texttemplate) {
            nLines = countLines(trace.texttemplate);
          } else {
            nLines = isArrayOrTypedArray(trace.text) ? Math.max(...trace.text.map((t) => countLines(t))) : countLines(trace.text);
          }
          const padAmount = trace.outsidetextfont.size * LINE_SPACING * nLines + TEXTPAD;
          return {
            // ppadplus corresponds to the negative-direction bars and
            // ppadminus corresponds to the positive-direction bars (for some reason)
            ppadplus: calcTrace.some((bar) => bar.s < 0) ? padAmount : 0,
            ppadminus: calcTrace.some((bar) => bar.s >= 0) ? padAmount : 0
          };
        }
        return { ppadplus: void 0, ppadminus: void 0 };
      }
      function setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa) {
        var pLetter = getAxisLetter(pa);
        for (var i = 0; i < calcTraces.length; i++) {
          var calcTrace = calcTraces[i];
          for (var j = 0; j < calcTrace.length; j++) {
            var bar = calcTrace[j];
            var pos = bar[pLetter];
            bar._sMin = sMinByPos[pos];
            bar._sMax = sMaxByPos[pos];
          }
        }
      }
      function collectExtents(calcTraces, pa) {
        var pLetter = getAxisLetter(pa);
        var extents = {};
        var i, j, cd;
        var pMin = Infinity;
        var pMax = -Infinity;
        for (i = 0; i < calcTraces.length; i++) {
          cd = calcTraces[i];
          for (j = 0; j < cd.length; j++) {
            var p = cd[j].p;
            if (isNumeric(p)) {
              pMin = Math.min(pMin, p);
              pMax = Math.max(pMax, p);
            }
          }
        }
        var roundFactor = 1e4 / (pMax - pMin);
        var round = extents.round = function(p2) {
          return String(Math.round(roundFactor * (p2 - pMin)));
        };
        var sMinByPos = {};
        var sMaxByPos = {};
        var anyTraceHasCornerradius = calcTraces.some(function(x) {
          var trace = x[0].trace;
          return "marker" in trace && trace.marker.cornerradius;
        });
        for (i = 0; i < calcTraces.length; i++) {
          cd = calcTraces[i];
          cd[0].t.extents = extents;
          var poffset = cd[0].t.poffset;
          var poffsetIsArray = isArrayOrTypedArray(poffset);
          for (j = 0; j < cd.length; j++) {
            var di = cd[j];
            var p0 = di[pLetter] - di.w / 2;
            if (isNumeric(p0)) {
              var p1 = di[pLetter] + di.w / 2;
              var pVal = round(di.p);
              if (extents[pVal]) {
                extents[pVal] = [Math.min(p0, extents[pVal][0]), Math.max(p1, extents[pVal][1])];
              } else {
                extents[pVal] = [p0, p1];
              }
            }
            di.p0 = di.p + (poffsetIsArray ? poffset[j] : poffset);
            di.p1 = di.p0 + di.w;
            di.s0 = di.b;
            di.s1 = di.s0 + di.s;
            if (anyTraceHasCornerradius) {
              var sMin = Math.min(di.s0, di.s1) || 0;
              var sMax = Math.max(di.s0, di.s1) || 0;
              var pos = di[pLetter];
              sMinByPos[pos] = pos in sMinByPos ? Math.min(sMinByPos[pos], sMin) : sMin;
              sMaxByPos[pos] = pos in sMaxByPos ? Math.max(sMaxByPos[pos], sMax) : sMax;
            }
          }
        }
        if (anyTraceHasCornerradius) {
          setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa);
        }
      }
      function getAxisLetter(ax) {
        return ax._id.charAt(0);
      }
      module.exports = {
        crossTraceCalc,
        setGroupPositions
      };
    }
  });

  // src/traces/scatter/cross_trace_calc.js
  var require_cross_trace_calc2 = __commonJS({
    "src/traces/scatter/cross_trace_calc.js"(exports, module) {
      "use strict";
      var calc = require_calc3();
      var setGroupPositions = require_cross_trace_calc().setGroupPositions;
      function groupCrossTraceCalc(gd, plotinfo) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var fullLayout = gd._fullLayout;
        var fullTraces = gd._fullData;
        var calcTraces = gd.calcdata;
        var calcTracesHorz = [];
        var calcTracesVert = [];
        for (var i = 0; i < fullTraces.length; i++) {
          var fullTrace = fullTraces[i];
          if (fullTrace.visible === true && fullTrace.type === "scatter" && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) {
            if (fullTrace.orientation === "h") {
              calcTracesHorz.push(calcTraces[i]);
            } else if (fullTrace.orientation === "v") {
              calcTracesVert.push(calcTraces[i]);
            }
          }
        }
        var opts = {
          mode: fullLayout.scattermode,
          gap: fullLayout.scattergap
        };
        setGroupPositions(gd, xa, ya, calcTracesVert, opts);
        setGroupPositions(gd, ya, xa, calcTracesHorz, opts);
      }
      module.exports = function crossTraceCalc(gd, plotinfo) {
        if (gd._fullLayout.scattermode === "group") {
          groupCrossTraceCalc(gd, plotinfo);
        }
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var subplot = xa._id + ya._id;
        var subplotStackOpts = gd._fullLayout._scatterStackOpts[subplot];
        if (!subplotStackOpts) return;
        var calcTraces = gd.calcdata;
        var i, j, k, i2, cd, cd0, posj, sumj, norm;
        var groupOpts, interpolate, groupnorm, posAttr, valAttr;
        var hasAnyBlanks;
        for (var stackGroup in subplotStackOpts) {
          groupOpts = subplotStackOpts[stackGroup];
          var indices = groupOpts.traceIndices;
          if (!indices.length) continue;
          interpolate = groupOpts.stackgaps === "interpolate";
          groupnorm = groupOpts.groupnorm;
          if (groupOpts.orientation === "v") {
            posAttr = "x";
            valAttr = "y";
          } else {
            posAttr = "y";
            valAttr = "x";
          }
          hasAnyBlanks = new Array(indices.length);
          for (i = 0; i < hasAnyBlanks.length; i++) {
            hasAnyBlanks[i] = false;
          }
          cd0 = calcTraces[indices[0]];
          var allPositions = new Array(cd0.length);
          for (i = 0; i < cd0.length; i++) {
            allPositions[i] = cd0[i][posAttr];
          }
          for (i = 1; i < indices.length; i++) {
            cd = calcTraces[indices[i]];
            for (j = k = 0; j < cd.length; j++) {
              posj = cd[j][posAttr];
              for (; posj > allPositions[k] && k < allPositions.length; k++) {
                insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
                j++;
              }
              if (posj !== allPositions[k]) {
                for (i2 = 0; i2 < i; i2++) {
                  insertBlank(calcTraces[indices[i2]], k, posj, i2, hasAnyBlanks, interpolate, posAttr);
                }
                allPositions.splice(k, 0, posj);
              }
              k++;
            }
            for (; k < allPositions.length; k++) {
              insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
              j++;
            }
          }
          var serieslen = allPositions.length;
          for (j = 0; j < cd0.length; j++) {
            sumj = cd0[j][valAttr] = cd0[j].s;
            for (i = 1; i < indices.length; i++) {
              cd = calcTraces[indices[i]];
              cd[0].trace._rawLength = cd[0].trace._length;
              cd[0].trace._length = serieslen;
              sumj += cd[j].s;
              cd[j][valAttr] = sumj;
            }
            if (groupnorm) {
              norm = (groupnorm === "fraction" ? sumj : sumj / 100) || 1;
              for (i = 0; i < indices.length; i++) {
                var cdj = calcTraces[indices[i]][j];
                cdj[valAttr] /= norm;
                cdj.sNorm = cdj.s / norm;
              }
            }
          }
          for (i = 0; i < indices.length; i++) {
            cd = calcTraces[indices[i]];
            var trace = cd[0].trace;
            var ppad = calc.calcMarkerSize(trace, trace._rawLength);
            var arrayPad = Array.isArray(ppad);
            if (ppad && hasAnyBlanks[i] || arrayPad) {
              var ppadRaw = ppad;
              ppad = new Array(serieslen);
              for (j = 0; j < serieslen; j++) {
                ppad[j] = cd[j].gap ? 0 : arrayPad ? ppadRaw[cd[j].i] : ppadRaw;
              }
            }
            var x = new Array(serieslen);
            var y = new Array(serieslen);
            for (j = 0; j < serieslen; j++) {
              x[j] = cd[j].x;
              y[j] = cd[j].y;
            }
            calc.calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
            cd[0].t.orientation = groupOpts.orientation;
          }
        }
      };
      function insertBlank(calcTrace, index, position, traceIndex, hasAnyBlanks, interpolate, posAttr) {
        hasAnyBlanks[traceIndex] = true;
        var newEntry = {
          i: null,
          gap: true,
          s: 0
        };
        newEntry[posAttr] = position;
        calcTrace.splice(index, 0, newEntry);
        if (index && position === calcTrace[index - 1][posAttr]) {
          var prevEntry = calcTrace[index - 1];
          newEntry.s = prevEntry.s;
          newEntry.i = prevEntry.i;
          newEntry.gap = prevEntry.gap;
        } else if (interpolate) {
          newEntry.s = getInterp(calcTrace, index, position, posAttr);
        }
        if (!index) {
          calcTrace[0].t = calcTrace[1].t;
          calcTrace[0].trace = calcTrace[1].trace;
          delete calcTrace[1].t;
          delete calcTrace[1].trace;
        }
      }
      function getInterp(calcTrace, index, position, posAttr) {
        var pt0 = calcTrace[index - 1];
        var pt1 = calcTrace[index + 1];
        if (!pt1) return pt0.s;
        if (!pt0) return pt1.s;
        return pt0.s + (pt1.s - pt0.s) * (position - pt0[posAttr]) / (pt1[posAttr] - pt0[posAttr]);
      }
    }
  });

  // src/traces/scatter/line_points.js
  var require_line_points = __commonJS({
    "src/traces/scatter/line_points.js"(exports, module) {
      "use strict";
      var Drawing = require_drawing();
      var numConstants = require_numerical();
      var BADNUM = numConstants.BADNUM;
      var LOG_CLIP = numConstants.LOG_CLIP;
      var LOG_CLIP_PLUS = LOG_CLIP + 0.5;
      var LOG_CLIP_MINUS = LOG_CLIP - 0.5;
      var Lib = require_lib();
      var segmentsIntersect = Lib.segmentsIntersect;
      var constrain = Lib.constrain;
      var constants = require_constants8();
      module.exports = function linePoints(d, opts) {
        var trace = opts.trace || {};
        var xa = opts.xaxis;
        var ya = opts.yaxis;
        var xLog = xa.type === "log";
        var yLog = ya.type === "log";
        var xLen = xa._length;
        var yLen = ya._length;
        var backoff = opts.backoff;
        var marker = trace.marker;
        var connectGaps = opts.connectGaps;
        var baseTolerance = opts.baseTolerance;
        var shape = opts.shape;
        var linear2 = shape === "linear";
        var fill = trace.fill && trace.fill !== "none";
        var segments = [];
        var minTolerance = constants.minTolerance;
        var len = d.length;
        var pts = new Array(len);
        var pti = 0;
        var i;
        var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt;
        var thisPt;
        var clusterHighFirst;
        var clusterUnitVector;
        var thisVector;
        var clusterRefDist, clusterHighVal, clusterLowVal, thisVal;
        var clusterMinDeviation, clusterMaxDeviation, thisDeviation;
        function getPt(index) {
          var di = d[index];
          if (!di) return false;
          var x = opts.linearized ? xa.l2p(di.x) : xa.c2p(di.x);
          var y = opts.linearized ? ya.l2p(di.y) : ya.c2p(di.y);
          if (x === BADNUM) {
            if (xLog) x = xa.c2p(di.x, true);
            if (x === BADNUM) return false;
            if (yLog && y === BADNUM) {
              x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) / (ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS)));
            }
            x *= 1e3;
          }
          if (y === BADNUM) {
            if (yLog) y = ya.c2p(di.y, true);
            if (y === BADNUM) return false;
            y *= 1e3;
          }
          return [x, y];
        }
        function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) {
          var dx = xFrac1 - xFrac0;
          var dy = yFrac1 - yFrac0;
          var dx0 = 0.5 - xFrac0;
          var dy0 = 0.5 - yFrac0;
          var norm2 = dx * dx + dy * dy;
          var dot = dx * dx0 + dy * dy0;
          if (dot > 0 && dot < norm2) {
            var cross = dx0 * dy - dy0 * dx;
            if (cross * cross < norm2) return true;
          }
        }
        var latestXFrac, latestYFrac;
        function getTolerance(pt, nextPt2) {
          var xFrac = pt[0] / xLen;
          var yFrac = pt[1] / yLen;
          var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1);
          if (offScreenFraction && latestXFrac !== void 0 && crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)) {
            offScreenFraction = 0;
          }
          if (offScreenFraction && nextPt2 && crossesViewport(xFrac, yFrac, nextPt2[0] / xLen, nextPt2[1] / yLen)) {
            offScreenFraction = 0;
          }
          return (1 + constants.toleranceGrowth * offScreenFraction) * baseTolerance;
        }
        function ptDist(pt1, pt2) {
          var dx = pt1[0] - pt2[0];
          var dy = pt1[1] - pt2[1];
          return Math.sqrt(dx * dx + dy * dy);
        }
        var maxScreensAway = constants.maxScreensAway;
        var xEdge0 = -xLen * maxScreensAway;
        var xEdge1 = xLen * (1 + maxScreensAway);
        var yEdge0 = -yLen * maxScreensAway;
        var yEdge1 = yLen * (1 + maxScreensAway);
        var edges = [
          [xEdge0, yEdge0, xEdge1, yEdge0],
          [xEdge1, yEdge0, xEdge1, yEdge1],
          [xEdge1, yEdge1, xEdge0, yEdge1],
          [xEdge0, yEdge1, xEdge0, yEdge0]
        ];
        var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt;
        function getLinearEdgeIntersections(pt1, pt2) {
          var out = [];
          var ptCount = 0;
          for (var i2 = 0; i2 < 4; i2++) {
            var edge = edges[i2];
            var ptInt = segmentsIntersect(
              pt1[0],
              pt1[1],
              pt2[0],
              pt2[1],
              edge[0],
              edge[1],
              edge[2],
              edge[3]
            );
            if (ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || Math.abs(ptInt.y - out[0][1]) > 1)) {
              ptInt = [ptInt.x, ptInt.y];
              if (ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt);
              else out.push(ptInt);
              ptCount++;
            }
          }
          return out;
        }
        function onlyConstrainedPoint(pt) {
          if (pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) {
            return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)];
          }
        }
        function sameEdge(pt1, pt2) {
          if (pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true;
          if (pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true;
        }
        function getHVEdgeIntersections(pt1, pt2) {
          var out = [];
          var ptInt1 = onlyConstrainedPoint(pt1);
          var ptInt2 = onlyConstrainedPoint(pt2);
          if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
          if (ptInt1) out.push(ptInt1);
          if (ptInt2) out.push(ptInt2);
          return out;
        }
        function getABAEdgeIntersections(dim, limit0, limit1) {
          return function(pt1, pt2) {
            var ptInt1 = onlyConstrainedPoint(pt1);
            var ptInt2 = onlyConstrainedPoint(pt2);
            var out = [];
            if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
            if (ptInt1) out.push(ptInt1);
            if (ptInt2) out.push(ptInt2);
            var midShift = 2 * Lib.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]);
            if (midShift) {
              var ptToAlter;
              if (ptInt1 && ptInt2) {
                ptToAlter = midShift > 0 === ptInt1[dim] > ptInt2[dim] ? ptInt1 : ptInt2;
              } else ptToAlter = ptInt1 || ptInt2;
              ptToAlter[dim] += midShift;
            }
            return out;
          };
        }
        var getEdgeIntersections;
        if (shape === "linear" || shape === "spline") {
          getEdgeIntersections = getLinearEdgeIntersections;
        } else if (shape === "hv" || shape === "vh") {
          getEdgeIntersections = getHVEdgeIntersections;
        } else if (shape === "hvh") getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1);
        else if (shape === "vhv") getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1);
        function getClosestCorner(pt1, pt2) {
          var dx = pt2[0] - pt1[0];
          var m = (pt2[1] - pt1[1]) / dx;
          var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;
          if (b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];
          else return [m > 0 ? xEdge1 : xEdge0, yEdge0];
        }
        function updateEdge(pt) {
          var x = pt[0];
          var y = pt[1];
          var xSame = x === pts[pti - 1][0];
          var ySame = y === pts[pti - 1][1];
          if (xSame && ySame) return;
          if (pti > 1) {
            var xSame2 = x === pts[pti - 2][0];
            var ySame2 = y === pts[pti - 2][1];
            if (xSame && (x === xEdge0 || x === xEdge1) && xSame2) {
              if (ySame2) pti--;
              else pts[pti - 1] = pt;
            } else if (ySame && (y === yEdge0 || y === yEdge1) && ySame2) {
              if (xSame2) pti--;
              else pts[pti - 1] = pt;
            } else pts[pti++] = pt;
          } else pts[pti++] = pt;
        }
        function updateEdgesForReentry(pt) {
          if (pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) {
            updateEdge([lastXEdge, lastYEdge]);
          }
          updateEdge(pt);
          lastFarPt = null;
          lastXEdge = lastYEdge = 0;
        }
        var arrayMarker = Lib.isArrayOrTypedArray(marker);
        function addPt(pt) {
          if (pt && backoff) {
            pt.i = i;
            pt.d = d;
            pt.trace = trace;
            pt.marker = arrayMarker ? marker[pt.i] : marker;
            pt.backoff = backoff;
          }
          latestXFrac = pt[0] / xLen;
          latestYFrac = pt[1] / yLen;
          xEdge = pt[0] < xEdge0 ? xEdge0 : pt[0] > xEdge1 ? xEdge1 : 0;
          yEdge = pt[1] < yEdge0 ? yEdge0 : pt[1] > yEdge1 ? yEdge1 : 0;
          if (xEdge || yEdge) {
            if (!pti) {
              pts[pti++] = [xEdge || pt[0], yEdge || pt[1]];
            } else if (lastFarPt) {
              var intersections = getEdgeIntersections(lastFarPt, pt);
              if (intersections.length > 1) {
                updateEdgesForReentry(intersections[0]);
                pts[pti++] = intersections[1];
              }
            } else {
              edgePt = getEdgeIntersections(pts[pti - 1], pt)[0];
              pts[pti++] = edgePt;
            }
            var lastPt = pts[pti - 1];
            if (xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) {
              if (lastFarPt) {
                if (lastXEdge !== xEdge && lastYEdge !== yEdge) {
                  if (lastXEdge && lastYEdge) {
                    updateEdge(getClosestCorner(lastFarPt, pt));
                  } else {
                    updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]);
                  }
                } else if (lastXEdge && lastYEdge) {
                  updateEdge([lastXEdge, lastYEdge]);
                }
              }
              updateEdge([xEdge, yEdge]);
            } else if (lastXEdge - xEdge && lastYEdge - yEdge) {
              updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]);
            }
            lastFarPt = pt;
            lastXEdge = xEdge;
            lastYEdge = yEdge;
          } else {
            if (lastFarPt) {
              updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]);
            }
            pts[pti++] = pt;
          }
        }
        for (i = 0; i < len; i++) {
          clusterStartPt = getPt(i);
          if (!clusterStartPt) continue;
          pti = 0;
          lastFarPt = null;
          addPt(clusterStartPt);
          for (i++; i < len; i++) {
            clusterHighPt = getPt(i);
            if (!clusterHighPt) {
              if (connectGaps) continue;
              else break;
            }
            if (!linear2 || !opts.simplify) {
              addPt(clusterHighPt);
              continue;
            }
            var nextPt = getPt(i + 1);
            clusterRefDist = ptDist(clusterHighPt, clusterStartPt);
            if (!(fill && (pti === 0 || pti === len - 1)) && clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue;
            clusterUnitVector = [
              (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist,
              (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist
            ];
            clusterLowPt = clusterStartPt;
            clusterHighVal = clusterRefDist;
            clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
            clusterHighFirst = false;
            clusterEndPt = clusterHighPt;
            for (i++; i < d.length; i++) {
              thisPt = nextPt;
              nextPt = getPt(i + 1);
              if (!thisPt) {
                if (connectGaps) continue;
                else break;
              }
              thisVector = [
                thisPt[0] - clusterStartPt[0],
                thisPt[1] - clusterStartPt[1]
              ];
              thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
              clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
              clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);
              if (clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break;
              clusterEndPt = thisPt;
              thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];
              if (thisVal > clusterHighVal) {
                clusterHighVal = thisVal;
                clusterHighPt = thisPt;
                clusterHighFirst = false;
              } else if (thisVal < clusterLowVal) {
                clusterLowVal = thisVal;
                clusterLowPt = thisPt;
                clusterHighFirst = true;
              }
            }
            if (clusterHighFirst) {
              addPt(clusterHighPt);
              if (clusterEndPt !== clusterLowPt) addPt(clusterLowPt);
            } else {
              if (clusterLowPt !== clusterStartPt) addPt(clusterLowPt);
              if (clusterEndPt !== clusterHighPt) addPt(clusterHighPt);
            }
            addPt(clusterEndPt);
            if (i >= d.length || !thisPt) break;
            addPt(thisPt);
            clusterStartPt = thisPt;
          }
          if (lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]);
          segments.push(pts.slice(0, pti));
        }
        var lastShapeChar = shape.slice(shape.length - 1);
        if (backoff && lastShapeChar !== "h" && lastShapeChar !== "v") {
          var trimmed = false;
          var n = -1;
          var newSegments = [];
          for (var j = 0; j < segments.length; j++) {
            for (var k = 0; k < segments[j].length - 1; k++) {
              var start = segments[j][k];
              var end = segments[j][k + 1];
              var xy = Drawing.applyBackoff(end, start);
              if (xy[0] !== end[0] || xy[1] !== end[1]) {
                trimmed = true;
              }
              if (!newSegments[n + 1]) {
                n++;
                newSegments[n] = [
                  start,
                  [xy[0], xy[1]]
                ];
              }
            }
          }
          return trimmed ? newSegments : segments;
        }
        return segments;
      };
    }
  });

  // src/traces/scatter/link_traces.js
  var require_link_traces = __commonJS({
    "src/traces/scatter/link_traces.js"(exports, module) {
      "use strict";
      var LINKEDFILLS = { tonextx: 1, tonexty: 1, tonext: 1 };
      module.exports = function linkTraces(gd, plotinfo, cdscatter) {
        var trace, i, group, prevtrace, groupIndex;
        var groupIndices = {};
        var needsSort = false;
        var prevGroupIndex = -1;
        var nextGroupIndex = 0;
        var prevUnstackedGroupIndex = -1;
        for (i = 0; i < cdscatter.length; i++) {
          trace = cdscatter[i][0].trace;
          group = trace.stackgroup || "";
          if (group) {
            if (group in groupIndices) {
              groupIndex = groupIndices[group];
            } else {
              groupIndex = groupIndices[group] = nextGroupIndex;
              nextGroupIndex++;
            }
          } else if (trace.fill in LINKEDFILLS && prevUnstackedGroupIndex >= 0) {
            groupIndex = prevUnstackedGroupIndex;
          } else {
            groupIndex = prevUnstackedGroupIndex = nextGroupIndex;
            nextGroupIndex++;
          }
          if (groupIndex < prevGroupIndex) needsSort = true;
          trace._groupIndex = prevGroupIndex = groupIndex;
        }
        var cdscatterSorted = cdscatter.slice();
        if (needsSort) {
          cdscatterSorted.sort(function(a, b) {
            var traceA = a[0].trace;
            var traceB = b[0].trace;
            return traceA._groupIndex - traceB._groupIndex || traceA.index - traceB.index;
          });
        }
        var prevtraces = {};
        for (i = 0; i < cdscatterSorted.length; i++) {
          trace = cdscatterSorted[i][0].trace;
          group = trace.stackgroup || "";
          if (trace.visible === true) {
            trace._nexttrace = null;
            if (trace.fill in LINKEDFILLS) {
              prevtrace = prevtraces[group];
              trace._prevtrace = prevtrace || null;
              if (prevtrace) {
                prevtrace._nexttrace = trace;
              }
            }
            trace._ownfill = trace.fill && (trace.fill.slice(0, 6) === "tozero" || trace.fill === "toself" || trace.fill.slice(0, 2) === "to" && !trace._prevtrace);
            prevtraces[group] = trace;
          } else {
            trace._prevtrace = trace._nexttrace = trace._ownfill = null;
          }
        }
        return cdscatterSorted;
      };
    }
  });

  // src/traces/scatter/plot.js
  var require_plot = __commonJS({
    "src/traces/scatter/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Lib = require_lib();
      var ensureSingle = Lib.ensureSingle;
      var identity2 = Lib.identity;
      var Drawing = require_drawing();
      var subTypes = require_subtypes();
      var linePoints = require_line_points();
      var linkTraces = require_link_traces();
      var polygonTester = require_polygon().tester;
      module.exports = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) {
        var join, onComplete;
        var isFullReplot = !transitionOpts;
        var hasTransition = !!transitionOpts && transitionOpts.duration > 0;
        var cdscatterSorted = linkTraces(gd, plotinfo, cdscatter);
        join = scatterLayer.selectAll("g.trace").data(cdscatterSorted, function(d) {
          return d[0].trace.uid;
        });
        join.enter().append("g").attr("class", function(d) {
          return "trace scatter trace" + d[0].trace.uid;
        }).style("stroke-miterlimit", 2);
        join.order();
        createFills(gd, join, plotinfo);
        if (hasTransition) {
          if (makeOnCompleteCallback) {
            onComplete = makeOnCompleteCallback();
          }
          var transition = d3.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() {
            onComplete && onComplete();
          }).each("interrupt", function() {
            onComplete && onComplete();
          });
          transition.each(function() {
            scatterLayer.selectAll("g.trace").each(function(d, i) {
              plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
            });
          });
        } else {
          join.each(function(d, i) {
            plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
          });
        }
        if (isFullReplot) {
          join.exit().remove();
        }
        scatterLayer.selectAll("path:not([d])").remove();
      };
      function createFills(gd, traceJoin, plotinfo) {
        traceJoin.each(function(d) {
          var fills = ensureSingle(d3.select(this), "g", "fills");
          Drawing.setClipUrl(fills, plotinfo.layerClipId, gd);
          var trace = d[0].trace;
          trace._ownFill = null;
          trace._nextFill = null;
          var fillData = [];
          if (trace._ownfill) fillData.push("_ownFill");
          if (trace._nexttrace) fillData.push("_nextFill");
          var fillJoin = fills.selectAll("g").data(fillData, identity2);
          fillJoin.enter().append("g");
          fillJoin.exit().remove();
          fillJoin.order().each(function(d2) {
            trace[d2] = ensureSingle(d3.select(this), "path", "js-fill");
          });
        });
      }
      function plotOne(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) {
        var isStatic = gd._context.staticPlot;
        var i;
        selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll);
        var hasTransition = !!transitionOpts && transitionOpts.duration > 0;
        function transition(selection) {
          return hasTransition ? selection.transition() : selection;
        }
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var trace = cdscatter[0].trace;
        var line = trace.line;
        var tr = d3.select(element);
        var errorBarGroup = ensureSingle(tr, "g", "errorbars");
        var lines = ensureSingle(tr, "g", "lines");
        var points = ensureSingle(tr, "g", "points");
        var text = ensureSingle(tr, "g", "text");
        Registry.getComponentMethod("errorbars", "plot")(gd, errorBarGroup, plotinfo, transitionOpts);
        if (trace.visible !== true) return;
        transition(tr).style("opacity", trace.opacity);
        var ownFillEl3, tonext;
        var ownFillDir = trace.fill.charAt(trace.fill.length - 1);
        if (ownFillDir !== "x" && ownFillDir !== "y") ownFillDir = "";
        var fillAxisIndex, fillAxisZero;
        if (ownFillDir === "y") {
          fillAxisIndex = 1;
          fillAxisZero = ya.c2p(0, true);
        } else if (ownFillDir === "x") {
          fillAxisIndex = 0;
          fillAxisZero = xa.c2p(0, true);
        }
        cdscatter[0][plotinfo.isRangePlot ? "nodeRangePlot3" : "node3"] = tr;
        var prevRevpath = "";
        var prevPolygons = [];
        var prevtrace = trace._prevtrace;
        var prevFillsegments = null;
        var prevFillElement = null;
        if (prevtrace) {
          prevRevpath = prevtrace._prevRevpath || "";
          tonext = prevtrace._nextFill;
          prevPolygons = prevtrace._ownPolygons;
          prevFillsegments = prevtrace._fillsegments;
          prevFillElement = prevtrace._fillElement;
        }
        var thispath;
        var thisrevpath;
        var fullpath = "";
        var revpath = "";
        var pathfn, revpathbase, revpathfn;
        var pt0, lastSegment, pt1;
        var thisPolygons = [];
        trace._polygons = [];
        var fillsegments = [];
        var segments = [];
        var makeUpdate = Lib.noop;
        ownFillEl3 = trace._ownFill;
        if (subTypes.hasLines(trace) || trace.fill !== "none") {
          if (tonext) {
            tonext.datum(cdscatter);
          }
          if (["hv", "vh", "hvh", "vhv"].indexOf(line.shape) !== -1) {
            pathfn = Drawing.steps(line.shape);
            revpathbase = Drawing.steps(
              line.shape.split("").reverse().join("")
            );
          } else if (line.shape === "spline") {
            pathfn = revpathbase = function(pts2) {
              var pLast = pts2[pts2.length - 1];
              if (pts2.length > 1 && pts2[0][0] === pLast[0] && pts2[0][1] === pLast[1]) {
                return Drawing.smoothclosed(pts2.slice(1), line.smoothing);
              } else {
                return Drawing.smoothopen(pts2, line.smoothing);
              }
            };
          } else {
            pathfn = revpathbase = function(pts2) {
              return "M" + pts2.join("L");
            };
          }
          revpathfn = function(pts2) {
            return revpathbase(pts2.reverse());
          };
          segments = linePoints(cdscatter, {
            xaxis: xa,
            yaxis: ya,
            trace,
            connectGaps: trace.connectgaps,
            baseTolerance: Math.max(line.width || 1, 3) / 4,
            shape: line.shape,
            backoff: line.backoff,
            simplify: line.simplify,
            fill: trace.fill
          });
          fillsegments = new Array(segments.length);
          var fillsegmentCount = 0;
          for (i = 0; i < segments.length; i++) {
            var curpoints;
            var pts = segments[i];
            if (!curpoints || !ownFillDir) {
              curpoints = pts.slice();
              fillsegments[fillsegmentCount] = curpoints;
              fillsegmentCount++;
            } else {
              curpoints.push.apply(curpoints, pts);
            }
          }
          trace._fillElement = null;
          trace._fillExclusionElement = prevFillElement;
          trace._fillsegments = fillsegments.slice(0, fillsegmentCount);
          fillsegments = trace._fillsegments;
          if (segments.length) {
            pt0 = segments[0][0].slice();
            lastSegment = segments[segments.length - 1];
            pt1 = lastSegment[lastSegment.length - 1].slice();
          }
          makeUpdate = function(isEnter) {
            return function(pts2) {
              thispath = pathfn(pts2);
              thisrevpath = revpathfn(pts2);
              if (!fullpath) {
                fullpath = thispath;
                revpath = thisrevpath;
              } else if (ownFillDir) {
                fullpath += "L" + thispath.slice(1);
                revpath = thisrevpath + ("L" + revpath.slice(1));
              } else {
                fullpath += "Z" + thispath;
                revpath = thisrevpath + "Z" + revpath;
              }
              if (subTypes.hasLines(trace)) {
                var el = d3.select(this);
                el.datum(cdscatter);
                if (isEnter) {
                  transition(el.style("opacity", 0).attr("d", thispath).call(Drawing.lineGroupStyle)).style("opacity", 1);
                } else {
                  var sel = transition(el);
                  sel.attr("d", thispath);
                  Drawing.singleLineStyle(cdscatter, sel);
                }
              }
            };
          };
        }
        var lineJoin = lines.selectAll(".js-line").data(segments);
        transition(lineJoin.exit()).style("opacity", 0).remove();
        lineJoin.each(makeUpdate(false));
        lineJoin.enter().append("path").classed("js-line", true).style("vector-effect", isStatic ? "none" : "non-scaling-stroke").call(Drawing.lineGroupStyle).each(makeUpdate(true));
        Drawing.setClipUrl(lineJoin, plotinfo.layerClipId, gd);
        function clearFill(selection) {
          transition(selection).attr("d", "M0,0Z");
        }
        var makeSelfPolygons = function() {
          var polygons = new Array(fillsegments.length);
          for (i = 0; i < fillsegments.length; i++) {
            polygons[i] = polygonTester(fillsegments[i]);
          }
          return polygons;
        };
        var makePolygonsToPrevious = function(prevFillsegments2) {
          var polygons, i2;
          if (!prevFillsegments2 || prevFillsegments2.length === 0) {
            polygons = new Array(fillsegments.length);
            for (i2 = 0; i2 < fillsegments.length; i2++) {
              var pt02 = fillsegments[i2][0].slice();
              var pt12 = fillsegments[i2][fillsegments[i2].length - 1].slice();
              pt02[fillAxisIndex] = pt12[fillAxisIndex] = fillAxisZero;
              var zeropoints = [pt12, pt02];
              var polypoints = zeropoints.concat(fillsegments[i2]);
              polygons[i2] = polygonTester(polypoints);
            }
          } else {
            polygons = new Array(prevFillsegments2.length - 1 + fillsegments.length);
            for (i2 = 0; i2 < prevFillsegments2.length - 1; i2++) {
              polygons[i2] = polygonTester(prevFillsegments2[i2]);
            }
            var reversedPrevFillsegment = prevFillsegments2[prevFillsegments2.length - 1].slice();
            reversedPrevFillsegment.reverse();
            for (i2 = 0; i2 < fillsegments.length; i2++) {
              polygons[prevFillsegments2.length - 1 + i2] = polygonTester(fillsegments[i2].concat(reversedPrevFillsegment));
            }
          }
          return polygons;
        };
        if (segments.length) {
          if (ownFillEl3) {
            ownFillEl3.datum(cdscatter);
            if (pt0 && pt1) {
              if (ownFillDir) {
                pt0[fillAxisIndex] = pt1[fillAxisIndex] = fillAxisZero;
                transition(ownFillEl3).attr("d", "M" + pt1 + "L" + pt0 + "L" + fullpath.slice(1)).call(Drawing.singleFillStyle, gd);
                thisPolygons = makePolygonsToPrevious(null);
              } else {
                transition(ownFillEl3).attr("d", fullpath + "Z").call(Drawing.singleFillStyle, gd);
                thisPolygons = makeSelfPolygons();
              }
            }
            trace._polygons = thisPolygons;
            trace._fillElement = ownFillEl3;
          } else if (tonext) {
            if (trace.fill.slice(0, 6) === "tonext" && fullpath && prevRevpath) {
              if (trace.fill === "tonext") {
                transition(tonext).attr("d", fullpath + "Z" + prevRevpath + "Z").call(Drawing.singleFillStyle, gd);
                thisPolygons = makeSelfPolygons();
                trace._polygons = thisPolygons.concat(prevPolygons);
              } else {
                transition(tonext).attr("d", fullpath + "L" + prevRevpath.slice(1) + "Z").call(Drawing.singleFillStyle, gd);
                thisPolygons = makePolygonsToPrevious(prevFillsegments);
                trace._polygons = thisPolygons;
              }
              trace._fillElement = tonext;
            } else {
              clearFill(tonext);
            }
          }
          trace._prevRevpath = revpath;
        } else {
          if (ownFillEl3) clearFill(ownFillEl3);
          else if (tonext) clearFill(tonext);
          trace._prevRevpath = null;
        }
        trace._ownPolygons = thisPolygons;
        function visFilter(d) {
          return d.filter(function(v) {
            return !v.gap && v.vis;
          });
        }
        function visFilterWithGaps(d) {
          return d.filter(function(v) {
            return v.vis;
          });
        }
        function gapFilter(d) {
          return d.filter(function(v) {
            return !v.gap;
          });
        }
        function keyFunc(d) {
          return d.id;
        }
        function getKeyFunc(trace2) {
          if (trace2.ids) {
            return keyFunc;
          }
        }
        function hideFilter() {
          return false;
        }
        function makePoints(points2, text2, cdscatter2) {
          var join, selection, hasNode;
          var trace2 = cdscatter2[0].trace;
          var showMarkers = subTypes.hasMarkers(trace2);
          var showText = subTypes.hasText(trace2);
          var keyFunc2 = getKeyFunc(trace2);
          var markerFilter = hideFilter;
          var textFilter = hideFilter;
          if (showMarkers || showText) {
            var showFilter = identity2;
            var stackGroup = trace2.stackgroup;
            var isInferZero = stackGroup && gd._fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup].stackgaps === "infer zero";
            if (trace2.marker.maxdisplayed || trace2._needsCull) {
              showFilter = isInferZero ? visFilterWithGaps : visFilter;
            } else if (stackGroup && !isInferZero) {
              showFilter = gapFilter;
            }
            if (showMarkers) markerFilter = showFilter;
            if (showText) textFilter = showFilter;
          }
          selection = points2.selectAll("path.point");
          join = selection.data(markerFilter, keyFunc2);
          var enter = join.enter().append("path").classed("point", true);
          if (hasTransition) {
            enter.call(Drawing.pointStyle, trace2, gd).call(Drawing.translatePoints, xa, ya).style("opacity", 0).transition().style("opacity", 1);
          }
          join.order();
          var styleFns;
          if (showMarkers) {
            styleFns = Drawing.makePointStyleFns(trace2);
          }
          join.each(function(d) {
            var el = d3.select(this);
            var sel = transition(el);
            hasNode = Drawing.translatePoint(d, sel, xa, ya);
            if (hasNode) {
              Drawing.singlePointStyle(d, sel, trace2, styleFns, gd);
              if (plotinfo.layerClipId) {
                Drawing.hideOutsideRangePoint(d, sel, xa, ya, trace2.xcalendar, trace2.ycalendar);
              }
              if (trace2.customdata) {
                el.classed("plotly-customdata", d.data !== null && d.data !== void 0);
              }
            } else {
              sel.remove();
            }
          });
          if (hasTransition) {
            join.exit().transition().style("opacity", 0).remove();
          } else {
            join.exit().remove();
          }
          selection = text2.selectAll("g");
          join = selection.data(textFilter, keyFunc2);
          join.enter().append("g").classed("textpoint", true).append("text");
          join.order();
          join.each(function(d) {
            var g = d3.select(this);
            var sel = transition(g.select("text"));
            hasNode = Drawing.translatePoint(d, sel, xa, ya);
            if (hasNode) {
              if (plotinfo.layerClipId) {
                Drawing.hideOutsideRangePoint(d, g, xa, ya, trace2.xcalendar, trace2.ycalendar);
              }
            } else {
              g.remove();
            }
          });
          join.selectAll("text").call(Drawing.textPointStyle, trace2, gd).each(function(d) {
            var x = xa.c2p(d.x);
            var y = ya.c2p(d.y);
            d3.select(this).selectAll("tspan.line").each(function() {
              transition(d3.select(this)).attr({ x, y });
            });
          });
          join.exit().remove();
        }
        points.datum(cdscatter);
        text.datum(cdscatter);
        makePoints(points, text, cdscatter);
        var hasClipOnAxisFalse = trace.cliponaxis === false;
        var clipUrl = hasClipOnAxisFalse ? null : plotinfo.layerClipId;
        Drawing.setClipUrl(points, clipUrl, gd);
        Drawing.setClipUrl(text, clipUrl, gd);
      }
      function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var xr = d3.extent(Lib.simpleMap(xa.range, xa.r2c));
        var yr = d3.extent(Lib.simpleMap(ya.range, ya.r2c));
        var trace = cdscatter[0].trace;
        if (!subTypes.hasMarkers(trace)) return;
        var mnum = trace.marker.maxdisplayed;
        if (mnum === 0) return;
        var cd = cdscatter.filter(function(v) {
          return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1];
        });
        var inc = Math.ceil(cd.length / mnum);
        var tnum = 0;
        cdscatterAll.forEach(function(cdj, j) {
          var tracei = cdj[0].trace;
          if (subTypes.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) {
            tnum++;
          }
        });
        var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1);
        cdscatter.forEach(function(v) {
          delete v.vis;
        });
        cd.forEach(function(v, i) {
          if (Math.round((i + i0) % inc) === 0) v.vis = true;
        });
      }
    }
  });

  // src/traces/scatter/marker_colorbar.js
  var require_marker_colorbar = __commonJS({
    "src/traces/scatter/marker_colorbar.js"(exports, module) {
      "use strict";
      module.exports = {
        container: "marker",
        min: "cmin",
        max: "cmax"
      };
    }
  });

  // src/traces/scatter/format_labels.js
  var require_format_labels = __commonJS({
    "src/traces/scatter/format_labels.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var labels = {};
        var mockGd = { _fullLayout: fullLayout };
        var xa = Axes.getFromTrace(mockGd, trace, "x");
        var ya = Axes.getFromTrace(mockGd, trace, "y");
        var x = cdi.orig_x;
        if (x === void 0) x = cdi.x;
        var y = cdi.orig_y;
        if (y === void 0) y = cdi.y;
        labels.xLabel = Axes.tickText(xa, xa.c2l(x), true).text;
        labels.yLabel = Axes.tickText(ya, ya.c2l(y), true).text;
        return labels;
      };
    }
  });

  // src/traces/scatter/style.js
  var require_style2 = __commonJS({
    "src/traces/scatter/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var Registry = require_registry();
      function style(gd) {
        var s = d3.select(gd).selectAll("g.trace.scatter");
        s.style("opacity", function(d) {
          return d[0].trace.opacity;
        });
        s.selectAll("g.points").each(function(d) {
          var sel = d3.select(this);
          var trace = d.trace || d[0].trace;
          stylePoints(sel, trace, gd);
        });
        s.selectAll("g.text").each(function(d) {
          var sel = d3.select(this);
          var trace = d.trace || d[0].trace;
          styleText(sel, trace, gd);
        });
        s.selectAll("g.trace path.js-line").call(Drawing.lineGroupStyle);
        s.selectAll("g.trace path.js-fill").call(Drawing.fillGroupStyle, gd, false);
        Registry.getComponentMethod("errorbars", "style")(s);
      }
      function stylePoints(sel, trace, gd) {
        Drawing.pointStyle(sel.selectAll("path.point"), trace, gd);
      }
      function styleText(sel, trace, gd) {
        Drawing.textPointStyle(sel.selectAll("text"), trace, gd);
      }
      function styleOnSelect(gd, cd, sel) {
        var trace = cd[0].trace;
        if (trace.selectedpoints) {
          Drawing.selectedPointStyle(sel.selectAll("path.point"), trace);
          Drawing.selectedTextStyle(sel.selectAll("text"), trace);
        } else {
          stylePoints(sel, trace, gd);
          styleText(sel, trace, gd);
        }
      }
      module.exports = {
        style,
        stylePoints,
        styleText,
        styleOnSelect
      };
    }
  });

  // src/traces/scatter/get_trace_color.js
  var require_get_trace_color = __commonJS({
    "src/traces/scatter/get_trace_color.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var subtypes = require_subtypes();
      module.exports = function getTraceColor(trace, di) {
        var lc, tc;
        if (trace.mode === "lines") {
          lc = trace.line.color;
          return lc && Color2.opacity(lc) ? lc : trace.fillcolor;
        } else if (trace.mode === "none") {
          return trace.fill ? trace.fillcolor : "";
        } else {
          var mc = di.mcc || (trace.marker || {}).color;
          var mlc = di.mlcc || ((trace.marker || {}).line || {}).color;
          tc = mc && Color2.opacity(mc) ? mc : mlc && Color2.opacity(mlc) && (di.mlw || ((trace.marker || {}).line || {}).width) ? mlc : "";
          if (tc) {
            if (Color2.opacity(tc) < 0.3) {
              return Color2.addOpacity(tc, 0.3);
            } else return tc;
          } else {
            lc = (trace.line || {}).color;
            return lc && Color2.opacity(lc) && subtypes.hasLines(trace) && trace.line.width ? lc : trace.fillcolor;
          }
        }
      };
    }
  });

  // src/traces/scatter/hover.js
  var require_hover2 = __commonJS({
    "src/traces/scatter/hover.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Fx = require_fx();
      var Registry = require_registry();
      var getTraceColor = require_get_trace_color();
      var Color2 = require_color();
      var fillText = Lib.fillText;
      module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var xpx = xa.c2p(xval);
        var ypx = ya.c2p(yval);
        var pt = [xpx, ypx];
        var hoveron = trace.hoveron || "";
        var minRad = trace.mode.indexOf("markers") !== -1 ? 3 : 0.5;
        var xPeriod = !!trace.xperiodalignment;
        var yPeriod = !!trace.yperiodalignment;
        if (hoveron.indexOf("points") !== -1) {
          var dx = function(di2) {
            if (xPeriod) {
              var x0 = xa.c2p(di2.xStart);
              var x1 = xa.c2p(di2.xEnd);
              return xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity;
            }
            var rad2 = Math.max(3, di2.mrc || 0);
            var kink = 1 - 1 / rad2;
            var dxRaw = Math.abs(xa.c2p(di2.x) - xpx);
            return dxRaw < rad2 ? kink * dxRaw / rad2 : dxRaw - rad2 + kink;
          };
          var dy = function(di2) {
            if (yPeriod) {
              var y0 = ya.c2p(di2.yStart);
              var y1 = ya.c2p(di2.yEnd);
              return ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity;
            }
            var rad2 = Math.max(3, di2.mrc || 0);
            var kink = 1 - 1 / rad2;
            var dyRaw = Math.abs(ya.c2p(di2.y) - ypx);
            return dyRaw < rad2 ? kink * dyRaw / rad2 : dyRaw - rad2 + kink;
          };
          var dxy = function(di2) {
            var rad2 = Math.max(minRad, di2.mrc || 0);
            var dx2 = xa.c2p(di2.x) - xpx;
            var dy2 = ya.c2p(di2.y) - ypx;
            return Math.max(Math.sqrt(dx2 * dx2 + dy2 * dy2) - rad2, 1 - minRad / rad2);
          };
          var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
          Fx.getClosest(cd, distfn, pointData);
          if (pointData.index !== false) {
            var di = cd[pointData.index];
            var xc = xa.c2p(di.x, true);
            var yc = ya.c2p(di.y, true);
            var rad = di.mrc || 1;
            pointData.index = di.i;
            var orientation = cd[0].t.orientation;
            var sizeVal = orientation && (di.sNorm || di.s);
            var xLabelVal = orientation === "h" ? sizeVal : di.orig_x !== void 0 ? di.orig_x : di.x;
            var yLabelVal = orientation === "v" ? sizeVal : di.orig_y !== void 0 ? di.orig_y : di.y;
            Lib.extendFlat(pointData, {
              color: getTraceColor(trace, di),
              x0: xc - rad,
              x1: xc + rad,
              xLabelVal,
              y0: yc - rad,
              y1: yc + rad,
              yLabelVal,
              spikeDistance: dxy(di),
              hovertemplate: trace.hovertemplate
            });
            fillText(di, trace, pointData);
            Registry.getComponentMethod("errorbars", "hoverInfo")(di, trace, pointData);
            return [pointData];
          }
        }
        function isHoverPointInFillElement(el) {
          if (!el) {
            return false;
          }
          var svgElement = el.node();
          try {
            var domPoint = new DOMPoint(pt[0], pt[1]);
            return svgElement.isPointInFill(domPoint);
          } catch (TypeError2) {
            var svgPoint = svgElement.ownerSVGElement.createSVGPoint();
            svgPoint.x = pt[0];
            svgPoint.y = pt[1];
            return svgElement.isPointInFill(svgPoint);
          }
        }
        function getHoverLabelPosition(polygons) {
          var i;
          var polygonsIn = [];
          var xmin = Infinity;
          var xmax = -Infinity;
          var ymin = Infinity;
          var ymax = -Infinity;
          var yPos;
          for (i = 0; i < polygons.length; i++) {
            var polygon = polygons[i];
            if (polygon.contains(pt)) {
              polygonsIn.push(polygon);
              ymin = Math.min(ymin, polygon.ymin);
              ymax = Math.max(ymax, polygon.ymax);
            }
          }
          if (polygonsIn.length === 0) {
            return null;
          }
          ymin = Math.max(ymin, 0);
          ymax = Math.min(ymax, ya._length);
          yPos = (ymin + ymax) / 2;
          var j, pts, xAtYPos, x0, x1, y0, y1;
          for (i = 0; i < polygonsIn.length; i++) {
            pts = polygonsIn[i].pts;
            for (j = 1; j < pts.length; j++) {
              y0 = pts[j - 1][1];
              y1 = pts[j][1];
              if (y0 > yPos !== y1 >= yPos) {
                x0 = pts[j - 1][0];
                x1 = pts[j][0];
                if (y1 - y0) {
                  xAtYPos = x0 + (x1 - x0) * (yPos - y0) / (y1 - y0);
                  xmin = Math.min(xmin, xAtYPos);
                  xmax = Math.max(xmax, xAtYPos);
                }
              }
            }
          }
          xmin = Math.max(xmin, 0);
          xmax = Math.min(xmax, xa._length);
          return {
            x0: xmin,
            x1: xmax,
            y0: yPos,
            y1: yPos
          };
        }
        if (hoveron.indexOf("fills") !== -1 && trace._fillElement) {
          var inside = isHoverPointInFillElement(trace._fillElement) && !isHoverPointInFillElement(trace._fillExclusionElement);
          if (inside) {
            var hoverLabelCoords = getHoverLabelPosition(trace._polygons);
            if (hoverLabelCoords === null) {
              hoverLabelCoords = {
                x0: pt[0],
                x1: pt[0],
                y0: pt[1],
                y1: pt[1]
              };
            }
            var color2 = Color2.defaultLine;
            if (Color2.opacity(trace.fillcolor)) color2 = trace.fillcolor;
            else if (Color2.opacity((trace.line || {}).color)) {
              color2 = trace.line.color;
            }
            Lib.extendFlat(pointData, {
              // never let a 2D override 1D type as closest point
              // also: no spikeDistance, it's not allowed for fills
              distance: pointData.maxHoverDistance,
              x0: hoverLabelCoords.x0,
              x1: hoverLabelCoords.x1,
              y0: hoverLabelCoords.y0,
              y1: hoverLabelCoords.y1,
              color: color2,
              hovertemplate: false
            });
            delete pointData.index;
            if (trace.text && !Lib.isArrayOrTypedArray(trace.text)) {
              pointData.text = String(trace.text);
            } else pointData.text = trace.name;
            return [pointData];
          }
        }
      };
    }
  });

  // src/traces/scatter/select.js
  var require_select2 = __commonJS({
    "src/traces/scatter/select.js"(exports, module) {
      "use strict";
      var subtypes = require_subtypes();
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var trace = cd[0].trace;
        var i;
        var di;
        var x;
        var y;
        var hasOnlyLines = !subtypes.hasMarkers(trace) && !subtypes.hasText(trace);
        if (hasOnlyLines) return [];
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            di = cd[i];
            x = xa.c2p(di.x);
            y = ya.c2p(di.y);
            if (di.i !== null && selectionTester.contains([x, y], false, i, searchInfo)) {
              selection.push({
                pointNumber: di.i,
                x: xa.c2d(di.x),
                y: ya.c2d(di.y)
              });
              di.selected = 1;
            } else {
              di.selected = 0;
            }
          }
        }
        return selection;
      };
    }
  });

  // src/plots/cartesian/attributes.js
  var require_attributes14 = __commonJS({
    "src/plots/cartesian/attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        xaxis: {
          valType: "subplotid",
          dflt: "x",
          editType: "calc+clearAxisTypes"
        },
        yaxis: {
          valType: "subplotid",
          dflt: "y",
          editType: "calc+clearAxisTypes"
        }
      };
    }
  });

  // src/plots/cartesian/type_defaults.js
  var require_type_defaults = __commonJS({
    "src/plots/cartesian/type_defaults.js"(exports, module) {
      "use strict";
      var traceIs = require_registry().traceIs;
      var autoType = require_axis_autotype();
      module.exports = function handleTypeDefaults(containerIn, containerOut, coerce, options) {
        coerce("autotypenumbers", options.autotypenumbersDflt);
        var axType = coerce("type", (options.splomStash || {}).type);
        if (axType === "-") {
          setAutoType(containerOut, options.data);
          if (containerOut.type === "-") {
            containerOut.type = "linear";
          } else {
            containerIn.type = containerOut.type;
          }
        }
      };
      function setAutoType(ax, data) {
        if (ax.type !== "-") return;
        var id = ax._id;
        var axLetter = id.charAt(0);
        var i;
        if (id.indexOf("scene") !== -1) id = axLetter;
        var d0 = getFirstNonEmptyTrace(data, id, axLetter);
        if (!d0) return;
        if (d0.type === "histogram" && axLetter === { v: "y", h: "x" }[d0.orientation || "v"]) {
          ax.type = "linear";
          return;
        }
        var calAttr = axLetter + "calendar";
        var calendar = d0[calAttr];
        var opts = { noMultiCategory: !traceIs(d0, "cartesian") || traceIs(d0, "noMultiCategory") };
        if (d0.type === "box" && d0._hasPreCompStats && axLetter === { h: "x", v: "y" }[d0.orientation || "v"]) {
          opts.noMultiCategory = true;
        }
        opts.autotypenumbers = ax.autotypenumbers;
        if (isBoxWithoutPositionCoords(d0, axLetter)) {
          var posLetter = getBoxPosLetter(d0);
          var boxPositions = [];
          for (i = 0; i < data.length; i++) {
            var trace = data[i];
            if (!traceIs(trace, "box-violin") || (trace[axLetter + "axis"] || axLetter) !== id) continue;
            if (trace[posLetter] !== void 0) boxPositions.push(trace[posLetter][0]);
            else if (trace.name !== void 0) boxPositions.push(trace.name);
            else boxPositions.push("text");
            if (trace[calAttr] !== calendar) calendar = void 0;
          }
          ax.type = autoType(boxPositions, calendar, opts);
        } else if (d0.type === "splom") {
          var dimensions = d0.dimensions;
          var dim = dimensions[d0._axesDim[id]];
          if (dim.visible) ax.type = autoType(dim.values, calendar, opts);
        } else {
          ax.type = autoType(d0[axLetter] || [d0[axLetter + "0"]], calendar, opts);
        }
      }
      function getFirstNonEmptyTrace(data, id, axLetter) {
        for (var i = 0; i < data.length; i++) {
          var trace = data[i];
          if (trace.type === "splom" && trace._length > 0 && (trace["_" + axLetter + "axes"] || {})[id]) {
            return trace;
          }
          if ((trace[axLetter + "axis"] || axLetter) === id) {
            if (isBoxWithoutPositionCoords(trace, axLetter)) {
              return trace;
            } else if ((trace[axLetter] || []).length || trace[axLetter + "0"]) {
              return trace;
            }
          }
        }
      }
      function getBoxPosLetter(trace) {
        return { v: "x", h: "y" }[trace.orientation || "v"];
      }
      function isBoxWithoutPositionCoords(trace, axLetter) {
        var posLetter = getBoxPosLetter(trace);
        var isBox = traceIs(trace, "box-violin");
        var isCandlestick = traceIs(trace._fullInput || {}, "candlestick");
        return isBox && !isCandlestick && axLetter === posLetter && trace[posLetter] === void 0 && trace[posLetter + "0"] === void 0;
      }
    }
  });

  // src/plots/cartesian/category_order_defaults.js
  var require_category_order_defaults = __commonJS({
    "src/plots/cartesian/category_order_defaults.js"(exports, module) {
      "use strict";
      var isTypedArraySpec = require_array().isTypedArraySpec;
      function findCategories(ax, opts) {
        var dataAttr = opts.dataAttr || ax._id.charAt(0);
        var lookup = {};
        var axData;
        var i, j;
        if (opts.axData) {
          axData = opts.axData;
        } else {
          axData = [];
          for (i = 0; i < opts.data.length; i++) {
            var trace = opts.data[i];
            if (trace[dataAttr + "axis"] === ax._id) {
              axData.push(trace);
            }
          }
        }
        for (i = 0; i < axData.length; i++) {
          var vals = axData[i][dataAttr];
          for (j = 0; j < vals.length; j++) {
            var v = vals[j];
            if (v !== null && v !== void 0) {
              lookup[v] = 1;
            }
          }
        }
        return Object.keys(lookup);
      }
      module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) {
        if (containerOut.type !== "category") return;
        var arrayIn = containerIn.categoryarray;
        var isValidArray = Array.isArray(arrayIn) && arrayIn.length > 0 || isTypedArraySpec(arrayIn);
        var orderDefault;
        if (isValidArray) orderDefault = "array";
        var order = coerce("categoryorder", orderDefault);
        var array;
        if (order === "array") {
          array = coerce("categoryarray");
        }
        if (!isValidArray && order === "array") {
          order = containerOut.categoryorder = "trace";
        }
        if (order === "trace") {
          containerOut._initialCategories = [];
        } else if (order === "array") {
          containerOut._initialCategories = array.slice();
        } else {
          array = findCategories(containerOut, opts).sort();
          if (order === "category ascending") {
            containerOut._initialCategories = array;
          } else if (order === "category descending") {
            containerOut._initialCategories = array.reverse();
          }
        }
      };
    }
  });

  // src/plots/cartesian/line_grid_defaults.js
  var require_line_grid_defaults = __commonJS({
    "src/plots/cartesian/line_grid_defaults.js"(exports, module) {
      "use strict";
      var colorMix = require_tinycolor().mix;
      var colorAttrs = require_attributes3();
      var Lib = require_lib();
      module.exports = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) {
        opts = opts || {};
        var dfltColor = opts.dfltColor;
        function coerce2(attr, dflt) {
          return Lib.coerce2(containerIn, containerOut, opts.attributes, attr, dflt);
        }
        var lineColor = coerce2("linecolor", dfltColor);
        var lineWidth = coerce2("linewidth");
        var showLine = coerce("showline", opts.showLine || !!lineColor || !!lineWidth);
        if (!showLine) {
          delete containerOut.linecolor;
          delete containerOut.linewidth;
        }
        var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || colorAttrs.lightFraction).toRgbString();
        var gridColor = coerce2("gridcolor", gridColorDflt);
        var gridWidth = coerce2("gridwidth");
        var gridDash = coerce2("griddash");
        var showGridLines = coerce(
          "showgrid",
          opts.showGrid || !!gridColor || !!gridWidth || !!gridDash
        );
        if (!showGridLines) {
          delete containerOut.gridcolor;
          delete containerOut.gridwidth;
          delete containerOut.griddash;
        }
        if (opts.hasMinor) {
          var minorGridColorDflt = colorMix(containerOut.gridcolor, opts.bgColor, 67).toRgbString();
          var minorGridColor = coerce2("minor.gridcolor", minorGridColorDflt);
          var minorGridWidth = coerce2("minor.gridwidth", containerOut.gridwidth || 1);
          var minorGridDash = coerce2("minor.griddash", containerOut.griddash || "solid");
          var minorShowGridLines = coerce(
            "minor.showgrid",
            !!minorGridColor || !!minorGridWidth || !!minorGridDash
          );
          if (!minorShowGridLines) {
            delete containerOut.minor.gridcolor;
            delete containerOut.minor.gridwidth;
            delete containerOut.minor.griddash;
          }
        }
        if (!opts.noZeroLine) {
          var zeroLineLayer = coerce2("zerolinelayer");
          var zeroLineColor = coerce2("zerolinecolor", dfltColor);
          var zeroLineWidth = coerce2("zerolinewidth");
          var showZeroLine = coerce("zeroline", opts.showGrid || !!zeroLineColor || !!zeroLineWidth);
          if (!showZeroLine) {
            delete containerOut.zerolinelayer;
            delete containerOut.zerolinecolor;
            delete containerOut.zerolinewidth;
          }
        }
      };
    }
  });

  // src/plots/cartesian/axis_defaults.js
  var require_axis_defaults = __commonJS({
    "src/plots/cartesian/axis_defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Registry = require_registry();
      var Lib = require_lib();
      var Template = require_plot_template();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var layoutAttributes = require_layout_attributes4();
      var handleTickValueDefaults = require_tick_value_defaults();
      var handleTickMarkDefaults = require_tick_mark_defaults();
      var handleTickLabelDefaults = require_tick_label_defaults();
      var handlePrefixSuffixDefaults = require_prefix_suffix_defaults();
      var handleCategoryOrderDefaults = require_category_order_defaults();
      var handleLineGridDefaults = require_line_grid_defaults();
      var handleRangeDefaults = require_range_defaults();
      var setConvert = require_set_convert();
      var DAY_OF_WEEK = require_constants2().WEEKDAY_PATTERN;
      var HOUR = require_constants2().HOUR_PATTERN;
      module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) {
        var letter = options.letter;
        var font = options.font || {};
        var splomStash = options.splomStash || {};
        var visible = coerce("visible", !options.visibleDflt);
        var axTemplate = containerOut._template || {};
        var axType = containerOut.type || axTemplate.type || "-";
        var ticklabelmode;
        if (axType === "date") {
          var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleDefaults");
          handleCalendarDefaults(containerIn, containerOut, "calendar", options.calendar);
          if (!options.noTicklabelmode) {
            ticklabelmode = coerce("ticklabelmode");
          }
        }
        if (!options.noTicklabelindex && (axType === "date" || axType === "linear")) {
          coerce("ticklabelindex");
        }
        var ticklabelposition = "";
        if (!options.noTicklabelposition || axType === "multicategory") {
          ticklabelposition = Lib.coerce(containerIn, containerOut, {
            ticklabelposition: {
              valType: "enumerated",
              dflt: "outside",
              values: ticklabelmode === "period" ? ["outside", "inside"] : letter === "x" ? [
                "outside",
                "inside",
                "outside left",
                "inside left",
                "outside right",
                "inside right"
              ] : [
                "outside",
                "inside",
                "outside top",
                "inside top",
                "outside bottom",
                "inside bottom"
              ]
            }
          }, "ticklabelposition");
        }
        if (!options.noTicklabeloverflow) {
          coerce(
            "ticklabeloverflow",
            ticklabelposition.indexOf("inside") !== -1 ? "hide past domain" : axType === "category" || axType === "multicategory" ? "allow" : "hide past div"
          );
        }
        setConvert(containerOut, layoutOut);
        handleRangeDefaults(containerIn, containerOut, coerce, options);
        handleCategoryOrderDefaults(containerIn, containerOut, coerce, options);
        if (!options.noHover) {
          if (axType !== "category") coerce("hoverformat");
          if (!options.noUnifiedhovertitle) {
            coerce("unifiedhovertitle.text");
          }
        }
        var dfltColor = coerce("color");
        var dfltFontColor = dfltColor !== layoutAttributes.color.dflt ? dfltColor : font.color;
        var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter];
        handlePrefixSuffixDefaults(containerIn, containerOut, coerce, axType, options);
        if (!visible) return containerOut;
        coerce("title.text", dfltTitle);
        Lib.coerceFont(coerce, "title.font", font, { overrideDflt: {
          size: Lib.bigFont(font.size),
          color: dfltFontColor
        } });
        handleTickValueDefaults(containerIn, containerOut, coerce, axType);
        var hasMinor = options.hasMinor;
        if (hasMinor) {
          Template.newContainer(containerOut, "minor");
          handleTickValueDefaults(containerIn, containerOut, coerce, axType, { isMinor: true });
        }
        handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
        handleTickMarkDefaults(containerIn, containerOut, coerce, options);
        if (hasMinor) {
          var keepIsMinor = options.isMinor;
          options.isMinor = true;
          handleTickMarkDefaults(containerIn, containerOut, coerce, options);
          options.isMinor = keepIsMinor;
        }
        handleLineGridDefaults(containerIn, containerOut, coerce, {
          dfltColor,
          bgColor: options.bgColor,
          showGrid: options.showGrid,
          hasMinor,
          attributes: layoutAttributes
        });
        if (hasMinor && !containerOut.minor.ticks && !containerOut.minor.showgrid) {
          delete containerOut.minor;
        }
        if (containerOut.showline || containerOut.ticks) coerce("mirror");
        var isMultiCategory = axType === "multicategory";
        if (!options.noTickson && (axType === "category" || isMultiCategory) && (containerOut.ticks || containerOut.showgrid)) {
          if (isMultiCategory) {
            coerce("tickson", "boundaries");
            delete containerOut.ticklabelposition;
          } else {
            coerce("tickson");
          }
        }
        if (isMultiCategory) {
          var showDividers = coerce("showdividers");
          if (showDividers) {
            coerce("dividercolor");
            coerce("dividerwidth");
          }
        }
        if (axType === "date") {
          handleArrayContainerDefaults(containerIn, containerOut, {
            name: "rangebreaks",
            inclusionAttr: "enabled",
            handleItemDefaults: rangebreaksDefaults
          });
          if (!containerOut.rangebreaks.length) {
            delete containerOut.rangebreaks;
          } else {
            for (var k = 0; k < containerOut.rangebreaks.length; k++) {
              if (containerOut.rangebreaks[k].pattern === DAY_OF_WEEK) {
                containerOut._hasDayOfWeekBreaks = true;
                break;
              }
            }
            setConvert(containerOut, layoutOut);
            if (layoutOut._has("scattergl") || layoutOut._has("splom")) {
              for (var i = 0; i < options.data.length; i++) {
                var trace = options.data[i];
                if (trace.type === "scattergl" || trace.type === "splom") {
                  trace.visible = false;
                  Lib.warn(trace.type + " traces do not work on axes with rangebreaks. Setting trace " + trace.index + " to `visible: false`.");
                }
              }
            }
          }
        }
        return containerOut;
      };
      function rangebreaksDefaults(itemIn, itemOut, containerOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(itemIn, itemOut, layoutAttributes.rangebreaks, attr, dflt);
        }
        var enabled = coerce("enabled");
        if (enabled) {
          var bnds = coerce("bounds");
          if (bnds && bnds.length >= 2) {
            var dfltPattern = "";
            var i, q;
            if (bnds.length === 2) {
              for (i = 0; i < 2; i++) {
                q = indexOfDay(bnds[i]);
                if (q) {
                  dfltPattern = DAY_OF_WEEK;
                  break;
                }
              }
            }
            var pattern = coerce("pattern", dfltPattern);
            if (pattern === DAY_OF_WEEK) {
              for (i = 0; i < 2; i++) {
                q = indexOfDay(bnds[i]);
                if (q) {
                  itemOut.bounds[i] = bnds[i] = q - 1;
                }
              }
            }
            if (pattern) {
              for (i = 0; i < 2; i++) {
                q = bnds[i];
                switch (pattern) {
                  case DAY_OF_WEEK:
                    if (!isNumeric(q)) {
                      itemOut.enabled = false;
                      return;
                    }
                    q = +q;
                    if (q !== Math.floor(q) || // don't accept fractional days for mow
                    q < 0 || q >= 7) {
                      itemOut.enabled = false;
                      return;
                    }
                    itemOut.bounds[i] = bnds[i] = q;
                    break;
                  case HOUR:
                    if (!isNumeric(q)) {
                      itemOut.enabled = false;
                      return;
                    }
                    q = +q;
                    if (q < 0 || q > 24) {
                      itemOut.enabled = false;
                      return;
                    }
                    itemOut.bounds[i] = bnds[i] = q;
                    break;
                }
              }
            }
            if (containerOut.autorange === false) {
              var rng = containerOut.range;
              if (rng[0] < rng[1]) {
                if (bnds[0] < rng[0] && bnds[1] > rng[1]) {
                  itemOut.enabled = false;
                  return;
                }
              } else if (bnds[0] > rng[0] && bnds[1] < rng[1]) {
                itemOut.enabled = false;
                return;
              }
            }
          } else {
            var values = coerce("values");
            if (values && values.length) {
              coerce("dvalue");
            } else {
              itemOut.enabled = false;
              return;
            }
          }
        }
      }
      var dayStrToNum = {
        sun: 1,
        mon: 2,
        tue: 3,
        wed: 4,
        thu: 5,
        fri: 6,
        sat: 7
      };
      function indexOfDay(v) {
        if (typeof v !== "string") return;
        return dayStrToNum[v.slice(0, 3).toLowerCase()];
      }
    }
  });

  // src/plots/cartesian/position_defaults.js
  var require_position_defaults = __commonJS({
    "src/plots/cartesian/position_defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      module.exports = function handlePositionDefaults(containerIn, containerOut, coerce, options) {
        var counterAxes = options.counterAxes || [];
        var overlayableAxes = options.overlayableAxes || [];
        var letter = options.letter;
        var grid = options.grid;
        var overlayingDomain = options.overlayingDomain;
        var dfltAnchor, dfltDomain, dfltSide, dfltPosition, dfltShift, dfltAutomargin;
        if (grid) {
          dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]];
          dfltAnchor = grid._anchors[containerOut._id];
          if (dfltDomain) {
            dfltSide = grid[letter + "side"].split(" ")[0];
            dfltPosition = grid.domain[letter][dfltSide === "right" || dfltSide === "top" ? 1 : 0];
          }
        }
        dfltDomain = dfltDomain || [0, 1];
        dfltAnchor = dfltAnchor || (isNumeric(containerIn.position) ? "free" : counterAxes[0] || "free");
        dfltSide = dfltSide || (letter === "x" ? "bottom" : "left");
        dfltPosition = dfltPosition || 0;
        dfltShift = 0;
        dfltAutomargin = false;
        var anchor = Lib.coerce(containerIn, containerOut, {
          anchor: {
            valType: "enumerated",
            values: ["free"].concat(counterAxes),
            dflt: dfltAnchor
          }
        }, "anchor");
        var side = Lib.coerce(containerIn, containerOut, {
          side: {
            valType: "enumerated",
            values: letter === "x" ? ["bottom", "top"] : ["left", "right"],
            dflt: dfltSide
          }
        }, "side");
        if (anchor === "free") {
          if (letter === "y") {
            var autoshift = coerce("autoshift");
            if (autoshift) {
              dfltPosition = side === "left" ? overlayingDomain[0] : overlayingDomain[1];
              dfltAutomargin = containerOut.automargin ? containerOut.automargin : true;
              dfltShift = side === "left" ? -3 : 3;
            }
            coerce("shift", dfltShift);
          }
          coerce("position", dfltPosition);
        }
        coerce("automargin", dfltAutomargin);
        var overlaying = false;
        if (overlayableAxes.length) {
          overlaying = Lib.coerce(containerIn, containerOut, {
            overlaying: {
              valType: "enumerated",
              values: [false].concat(overlayableAxes),
              dflt: false
            }
          }, "overlaying");
        }
        if (!overlaying) {
          var domain = coerce("domain", dfltDomain);
          if (domain[0] > domain[1] - 1 / 4096) containerOut.domain = dfltDomain;
          Lib.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain);
          if (containerOut.tickmode === "sync") {
            containerOut.tickmode = "auto";
          }
        }
        coerce("layer");
        return containerOut;
      };
    }
  });

  // src/plots/cartesian/layout_defaults.js
  var require_layout_defaults4 = __commonJS({
    "src/plots/cartesian/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var isUnifiedHover = require_helpers2().isUnifiedHover;
      var handleHoverModeDefaults = require_hovermode_defaults();
      var Template = require_plot_template();
      var basePlotLayoutAttributes = require_layout_attributes2();
      var layoutAttributes = require_layout_attributes4();
      var handleTypeDefaults = require_type_defaults();
      var handleAxisDefaults = require_axis_defaults();
      var constraints = require_constraints();
      var handlePositionDefaults = require_position_defaults();
      var axisIds = require_axis_ids();
      var id2name = axisIds.id2name;
      var name2id = axisIds.name2id;
      var AX_ID_PATTERN = require_constants2().AX_ID_PATTERN;
      var Registry = require_registry();
      var traceIs = Registry.traceIs;
      var getComponentMethod = Registry.getComponentMethod;
      function appendList(cont, k, item) {
        if (Array.isArray(cont[k])) cont[k].push(item);
        else cont[k] = [item];
      }
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        var autotypenumbersDflt = layoutOut.autotypenumbers;
        var ax2traces = {};
        var xaMayHide = {};
        var yaMayHide = {};
        var xaMustDisplay = {};
        var yaMustDisplay = {};
        var yaMustNotReverse = {};
        var yaMayReverse = {};
        var axHasImage = {};
        var outerTicks = {};
        var noGrids = {};
        var i, j;
        for (i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          if (!traceIs(trace, "cartesian")) continue;
          var xaName;
          if (trace.xaxis) {
            xaName = id2name(trace.xaxis);
            appendList(ax2traces, xaName, trace);
          } else if (trace.xaxes) {
            for (j = 0; j < trace.xaxes.length; j++) {
              appendList(ax2traces, id2name(trace.xaxes[j]), trace);
            }
          }
          var yaName;
          if (trace.yaxis) {
            yaName = id2name(trace.yaxis);
            appendList(ax2traces, yaName, trace);
          } else if (trace.yaxes) {
            for (j = 0; j < trace.yaxes.length; j++) {
              appendList(ax2traces, id2name(trace.yaxes[j]), trace);
            }
          }
          if (trace.type === "funnel") {
            if (trace.orientation === "h") {
              if (xaName) xaMayHide[xaName] = true;
              if (yaName) yaMayReverse[yaName] = true;
            } else {
              if (yaName) yaMayHide[yaName] = true;
            }
          } else if (trace.type === "image") {
            if (yaName) axHasImage[yaName] = true;
            if (xaName) axHasImage[xaName] = true;
          } else {
            if (yaName) {
              yaMustDisplay[yaName] = true;
              yaMustNotReverse[yaName] = true;
            }
            if (!traceIs(trace, "carpet") || trace.type === "carpet" && !trace._cheater) {
              if (xaName) xaMustDisplay[xaName] = true;
            }
          }
          if (trace.type === "carpet" && trace._cheater) {
            if (xaName) xaMayHide[xaName] = true;
          }
          if (traceIs(trace, "2dMap")) {
            outerTicks[xaName] = true;
            outerTicks[yaName] = true;
          }
          if (traceIs(trace, "oriented")) {
            var positionAxis = trace.orientation === "h" ? yaName : xaName;
            noGrids[positionAxis] = true;
          }
        }
        var subplots = layoutOut._subplots;
        var xIds = subplots.xaxis;
        var yIds = subplots.yaxis;
        var xNames = Lib.simpleMap(xIds, id2name);
        var yNames = Lib.simpleMap(yIds, id2name);
        var axNames = xNames.concat(yNames);
        var plotBgColor = Color2.background;
        if (xIds.length && yIds.length) {
          plotBgColor = Lib.coerce(layoutIn, layoutOut, basePlotLayoutAttributes, "plot_bgcolor");
        }
        var bgColor = Color2.combine(plotBgColor, layoutOut.paper_bgcolor);
        var axName;
        var axId;
        var axLetter;
        var axLayoutIn;
        var axLayoutOut;
        function newAxLayoutOut() {
          var traces = ax2traces[axName] || [];
          axLayoutOut._traceIndices = traces.map(function(t) {
            return t.index;
          });
          axLayoutOut._annIndices = [];
          axLayoutOut._shapeIndices = [];
          axLayoutOut._selectionIndices = [];
          axLayoutOut._imgIndices = [];
          axLayoutOut._subplotsWith = [];
          axLayoutOut._counterAxes = [];
          axLayoutOut._name = axLayoutOut._attr = axName;
          axLayoutOut._id = axId;
        }
        function coerce(attr, dflt) {
          return Lib.coerce(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
        }
        function coerce2(attr, dflt) {
          return Lib.coerce2(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
        }
        function getCounterAxes(axLetter2) {
          return axLetter2 === "x" ? yIds : xIds;
        }
        function getOverlayableAxes(axLetter2, axName2) {
          var list = axLetter2 === "x" ? xNames : yNames;
          var out = [];
          for (var j2 = 0; j2 < list.length; j2++) {
            var axName22 = list[j2];
            if (axName22 !== axName2 && !(layoutIn[axName22] || {}).overlaying) {
              out.push(name2id(axName22));
            }
          }
          return out;
        }
        var counterAxes = { x: getCounterAxes("x"), y: getCounterAxes("y") };
        var allAxisIds = counterAxes.x.concat(counterAxes.y);
        var missingMatchedAxisIdsLookup = {};
        var missingMatchedAxisIds = [];
        function addMissingMatchedAxis() {
          var matchesIn = axLayoutIn.matches;
          if (AX_ID_PATTERN.test(matchesIn) && allAxisIds.indexOf(matchesIn) === -1) {
            missingMatchedAxisIdsLookup[matchesIn] = axLayoutIn.type;
            missingMatchedAxisIds = Object.keys(missingMatchedAxisIdsLookup);
          }
        }
        var hovermode = handleHoverModeDefaults(layoutIn, layoutOut);
        var unifiedHover = isUnifiedHover(hovermode);
        for (i = 0; i < axNames.length; i++) {
          axName = axNames[i];
          axId = name2id(axName);
          axLetter = axName.charAt(0);
          if (!Lib.isPlainObject(layoutIn[axName])) {
            layoutIn[axName] = {};
          }
          axLayoutIn = layoutIn[axName];
          axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + "axis");
          newAxLayoutOut();
          var visibleDflt = axLetter === "x" && !xaMustDisplay[axName] && xaMayHide[axName] || axLetter === "y" && !yaMustDisplay[axName] && yaMayHide[axName];
          var reverseDflt = axLetter === "y" && (!yaMustNotReverse[axName] && yaMayReverse[axName] || axHasImage[axName]);
          var defaultOptions = {
            hasMinor: true,
            letter: axLetter,
            font: layoutOut.font,
            outerTicks: outerTicks[axName],
            showGrid: !noGrids[axName],
            data: ax2traces[axName] || [],
            bgColor,
            calendar: layoutOut.calendar,
            automargin: true,
            visibleDflt,
            reverseDflt,
            autotypenumbersDflt,
            splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId],
            noAutotickangles: axLetter === "y"
          };
          coerce("uirevision", layoutOut.uirevision);
          handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions);
          handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut);
          var unifiedSpike = unifiedHover && axLetter === hovermode.charAt(0);
          var spikecolor = coerce2("spikecolor", unifiedHover ? axLayoutOut.color : void 0);
          var spikethickness = coerce2("spikethickness", unifiedHover ? 1.5 : void 0);
          var spikedash = coerce2("spikedash", unifiedHover ? "dot" : void 0);
          var spikemode = coerce2("spikemode", unifiedHover ? "across" : void 0);
          var spikesnap = coerce2("spikesnap");
          var showSpikes = coerce("showspikes", !!unifiedSpike || !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap);
          if (!showSpikes) {
            delete axLayoutOut.spikecolor;
            delete axLayoutOut.spikethickness;
            delete axLayoutOut.spikedash;
            delete axLayoutOut.spikemode;
            delete axLayoutOut.spikesnap;
          }
          var overlayingAxis = id2name(axLayoutIn.overlaying);
          var overlayingAnchorDomain = [0, 1];
          if (layoutOut[overlayingAxis] !== void 0) {
            var overlayingAnchor = id2name(layoutOut[overlayingAxis].anchor);
            if (layoutOut[overlayingAnchor] !== void 0) {
              overlayingAnchorDomain = layoutOut[overlayingAnchor].domain;
            }
          }
          handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, {
            letter: axLetter,
            counterAxes: counterAxes[axLetter],
            overlayableAxes: getOverlayableAxes(axLetter, axName),
            grid: layoutOut.grid,
            overlayingDomain: overlayingAnchorDomain
          });
          coerce("title.standoff");
          addMissingMatchedAxis();
          axLayoutOut._input = axLayoutIn;
        }
        i = 0;
        while (i < missingMatchedAxisIds.length) {
          axId = missingMatchedAxisIds[i++];
          axName = id2name(axId);
          axLetter = axName.charAt(0);
          if (!Lib.isPlainObject(layoutIn[axName])) {
            layoutIn[axName] = {};
          }
          axLayoutIn = layoutIn[axName];
          axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + "axis");
          newAxLayoutOut();
          var defaultOptions2 = {
            letter: axLetter,
            font: layoutOut.font,
            outerTicks: outerTicks[axName],
            showGrid: !noGrids[axName],
            data: [],
            bgColor,
            calendar: layoutOut.calendar,
            automargin: true,
            visibleDflt: false,
            reverseDflt: false,
            autotypenumbersDflt,
            splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId]
          };
          coerce("uirevision", layoutOut.uirevision);
          axLayoutOut.type = missingMatchedAxisIdsLookup[axId] || "linear";
          handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions2, layoutOut);
          handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, {
            letter: axLetter,
            counterAxes: counterAxes[axLetter],
            overlayableAxes: getOverlayableAxes(axLetter, axName),
            grid: layoutOut.grid
          });
          coerce("fixedrange");
          coerce("modebardisable");
          addMissingMatchedAxis();
          axLayoutOut._input = axLayoutIn;
        }
        var rangeSliderDefaults = getComponentMethod("rangeslider", "handleDefaults");
        var rangeSelectorDefaults = getComponentMethod("rangeselector", "handleDefaults");
        for (i = 0; i < xNames.length; i++) {
          axName = xNames[i];
          axLayoutIn = layoutIn[axName];
          axLayoutOut = layoutOut[axName];
          rangeSliderDefaults(layoutIn, layoutOut, axName);
          if (axLayoutOut.type === "date") {
            rangeSelectorDefaults(
              axLayoutIn,
              axLayoutOut,
              layoutOut,
              yNames,
              axLayoutOut.calendar
            );
          }
          coerce("fixedrange");
          coerce("modebardisable");
        }
        for (i = 0; i < yNames.length; i++) {
          axName = yNames[i];
          axLayoutIn = layoutIn[axName];
          axLayoutOut = layoutOut[axName];
          var anchoredAxis = layoutOut[id2name(axLayoutOut.anchor)];
          var fixedRangeDflt = getComponentMethod("rangeslider", "isVisible")(anchoredAxis);
          coerce("fixedrange", fixedRangeDflt);
          coerce("modebardisable");
        }
        constraints.handleDefaults(layoutIn, layoutOut, {
          axIds: allAxisIds.concat(missingMatchedAxisIds).sort(axisIds.idSort),
          axHasImage
        });
      };
    }
  });

  // src/plots/cartesian/transition_axes.js
  var require_transition_axes = __commonJS({
    "src/plots/cartesian/transition_axes.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var Axes = require_axes();
      module.exports = function transitionAxes(gd, edits, transitionOpts, makeOnCompleteCallback) {
        var fullLayout = gd._fullLayout;
        if (edits.length === 0) {
          Axes.redrawComponents(gd);
          return;
        }
        function unsetSubplotTransform(subplot) {
          var xa = subplot.xaxis;
          var ya = subplot.yaxis;
          fullLayout._defs.select("#" + subplot.clipId + "> rect").call(Drawing.setTranslate, 0, 0).call(Drawing.setScale, 1, 1);
          subplot.plot.call(Drawing.setTranslate, xa._offset, ya._offset).call(Drawing.setScale, 1, 1);
          var traceGroups = subplot.plot.selectAll(".scatterlayer .trace");
          traceGroups.selectAll(".point").call(Drawing.setPointGroupScale, 1, 1);
          traceGroups.selectAll(".textpoint").call(Drawing.setTextPointsScale, 1, 1);
          traceGroups.call(Drawing.hideOutsideRangePoints, subplot);
        }
        function updateSubplot(edit, progress) {
          var plotinfo = edit.plotinfo;
          var xa = plotinfo.xaxis;
          var ya = plotinfo.yaxis;
          var xlen = xa._length;
          var ylen = ya._length;
          var editX = !!edit.xr1;
          var editY = !!edit.yr1;
          var viewBox = [];
          if (editX) {
            var xr0 = Lib.simpleMap(edit.xr0, xa.r2l);
            var xr1 = Lib.simpleMap(edit.xr1, xa.r2l);
            var dx0 = xr0[1] - xr0[0];
            var dx1 = xr1[1] - xr1[0];
            viewBox[0] = (xr0[0] * (1 - progress) + progress * xr1[0] - xr0[0]) / (xr0[1] - xr0[0]) * xlen;
            viewBox[2] = xlen * (1 - progress + progress * dx1 / dx0);
            xa.range[0] = xa.l2r(xr0[0] * (1 - progress) + progress * xr1[0]);
            xa.range[1] = xa.l2r(xr0[1] * (1 - progress) + progress * xr1[1]);
          } else {
            viewBox[0] = 0;
            viewBox[2] = xlen;
          }
          if (editY) {
            var yr0 = Lib.simpleMap(edit.yr0, ya.r2l);
            var yr1 = Lib.simpleMap(edit.yr1, ya.r2l);
            var dy0 = yr0[1] - yr0[0];
            var dy1 = yr1[1] - yr1[0];
            viewBox[1] = (yr0[1] * (1 - progress) + progress * yr1[1] - yr0[1]) / (yr0[0] - yr0[1]) * ylen;
            viewBox[3] = ylen * (1 - progress + progress * dy1 / dy0);
            ya.range[0] = xa.l2r(yr0[0] * (1 - progress) + progress * yr1[0]);
            ya.range[1] = ya.l2r(yr0[1] * (1 - progress) + progress * yr1[1]);
          } else {
            viewBox[1] = 0;
            viewBox[3] = ylen;
          }
          Axes.drawOne(gd, xa, { skipTitle: true });
          Axes.drawOne(gd, ya, { skipTitle: true });
          Axes.redrawComponents(gd, [xa._id, ya._id]);
          var xScaleFactor = editX ? xlen / viewBox[2] : 1;
          var yScaleFactor = editY ? ylen / viewBox[3] : 1;
          var clipDx = editX ? viewBox[0] : 0;
          var clipDy = editY ? viewBox[1] : 0;
          var fracDx = editX ? viewBox[0] / viewBox[2] * xlen : 0;
          var fracDy = editY ? viewBox[1] / viewBox[3] * ylen : 0;
          var plotDx = xa._offset - fracDx;
          var plotDy = ya._offset - fracDy;
          plotinfo.clipRect.call(Drawing.setTranslate, clipDx, clipDy).call(Drawing.setScale, 1 / xScaleFactor, 1 / yScaleFactor);
          plotinfo.plot.call(Drawing.setTranslate, plotDx, plotDy).call(Drawing.setScale, xScaleFactor, yScaleFactor);
          Drawing.setPointGroupScale(plotinfo.zoomScalePts, 1 / xScaleFactor, 1 / yScaleFactor);
          Drawing.setTextPointsScale(plotinfo.zoomScaleTxt, 1 / xScaleFactor, 1 / yScaleFactor);
        }
        var onComplete;
        if (makeOnCompleteCallback) {
          onComplete = makeOnCompleteCallback();
        }
        function transitionComplete() {
          var aobj = {};
          for (var i = 0; i < edits.length; i++) {
            var edit = edits[i];
            var xa = edit.plotinfo.xaxis;
            var ya = edit.plotinfo.yaxis;
            if (edit.xr1) aobj[xa._name + ".range"] = edit.xr1.slice();
            if (edit.yr1) aobj[ya._name + ".range"] = edit.yr1.slice();
          }
          onComplete && onComplete();
          return Registry.call("relayout", gd, aobj).then(function() {
            for (var i2 = 0; i2 < edits.length; i2++) {
              unsetSubplotTransform(edits[i2].plotinfo);
            }
          });
        }
        function transitionInterrupt() {
          var aobj = {};
          for (var i = 0; i < edits.length; i++) {
            var edit = edits[i];
            var xa = edit.plotinfo.xaxis;
            var ya = edit.plotinfo.yaxis;
            if (edit.xr0) aobj[xa._name + ".range"] = edit.xr0.slice();
            if (edit.yr0) aobj[ya._name + ".range"] = edit.yr0.slice();
          }
          return Registry.call("relayout", gd, aobj).then(function() {
            for (var i2 = 0; i2 < edits.length; i2++) {
              unsetSubplotTransform(edits[i2].plotinfo);
            }
          });
        }
        var t12, t22, raf;
        var easeFn = d3.ease(transitionOpts.easing);
        gd._transitionData._interruptCallbacks.push(function() {
          window.cancelAnimationFrame(raf);
          raf = null;
          return transitionInterrupt();
        });
        function doFrame() {
          t22 = Date.now();
          var tInterp = Math.min(1, (t22 - t12) / transitionOpts.duration);
          var progress = easeFn(tInterp);
          for (var i = 0; i < edits.length; i++) {
            updateSubplot(edits[i], progress);
          }
          if (t22 - t12 > transitionOpts.duration) {
            transitionComplete();
            raf = window.cancelAnimationFrame(doFrame);
          } else {
            raf = window.requestAnimationFrame(doFrame);
          }
        }
        t12 = Date.now();
        raf = window.requestAnimationFrame(doFrame);
        return Promise.resolve();
      };
    }
  });

  // src/plots/cartesian/index.js
  var require_cartesian = __commonJS({
    "src/plots/cartesian/index.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Lib = require_lib();
      var Plots = require_plots();
      var Drawing = require_drawing();
      var getModuleCalcData = require_get_data().getModuleCalcData;
      var axisIds = require_axis_ids();
      var constants = require_constants2();
      var xmlnsNamespaces = require_xmlns_namespaces();
      var ensureSingle = Lib.ensureSingle;
      function ensureSingleAndAddDatum(parent, nodeType, className) {
        return Lib.ensureSingle(parent, nodeType, className, function(s) {
          s.datum(className);
        });
      }
      var zindexSeparator = constants.zindexSeparator;
      exports.name = "cartesian";
      exports.attr = ["xaxis", "yaxis"];
      exports.idRoot = ["x", "y"];
      exports.idRegex = constants.idRegex;
      exports.attrRegex = constants.attrRegex;
      exports.attributes = require_attributes14();
      exports.layoutAttributes = require_layout_attributes4();
      exports.supplyLayoutDefaults = require_layout_defaults4();
      exports.transitionAxes = require_transition_axes();
      exports.finalizeSubplots = function(layoutIn, layoutOut) {
        var subplots = layoutOut._subplots;
        var xList = subplots.xaxis;
        var yList = subplots.yaxis;
        var spSVG = subplots.cartesian;
        var spAll = spSVG;
        var allX = {};
        var allY = {};
        var i, xi, yi;
        for (i = 0; i < spAll.length; i++) {
          var parts = spAll[i].split("y");
          allX[parts[0]] = 1;
          allY["y" + parts[1]] = 1;
        }
        for (i = 0; i < xList.length; i++) {
          xi = xList[i];
          if (!allX[xi]) {
            yi = (layoutIn[axisIds.id2name(xi)] || {}).anchor;
            if (!constants.idRegex.y.test(yi)) yi = "y";
            spSVG.push(xi + yi);
            spAll.push(xi + yi);
            if (!allY[yi]) {
              allY[yi] = 1;
              Lib.pushUnique(yList, yi);
            }
          }
        }
        for (i = 0; i < yList.length; i++) {
          yi = yList[i];
          if (!allY[yi]) {
            xi = (layoutIn[axisIds.id2name(yi)] || {}).anchor;
            if (!constants.idRegex.x.test(xi)) xi = "x";
            spSVG.push(xi + yi);
            spAll.push(xi + yi);
            if (!allX[xi]) {
              allX[xi] = 1;
              Lib.pushUnique(xList, xi);
            }
          }
        }
        if (!spAll.length) {
          xi = "";
          yi = "";
          for (var ki in layoutIn) {
            if (constants.attrRegex.test(ki)) {
              var axLetter = ki.charAt(0);
              if (axLetter === "x") {
                if (!xi || +ki.slice(5) < +xi.slice(5)) {
                  xi = ki;
                }
              } else if (!yi || +ki.slice(5) < +yi.slice(5)) {
                yi = ki;
              }
            }
          }
          xi = xi ? axisIds.name2id(xi) : "x";
          yi = yi ? axisIds.name2id(yi) : "y";
          xList.push(xi);
          yList.push(yi);
          spSVG.push(xi + yi);
        }
      };
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        var fullLayout = gd._fullLayout;
        var subplots = fullLayout._subplots.cartesian;
        var calcdata = gd.calcdata;
        var i;
        if (!Array.isArray(traces)) {
          traces = [];
          for (i = 0; i < calcdata.length; i++) traces.push(i);
        }
        var zindices = fullLayout._zindices;
        for (var z = 0; z < zindices.length; z++) {
          var zorder = zindices[z];
          for (i = 0; i < subplots.length; i++) {
            var subplot = subplots[i];
            var subplotInfo = fullLayout._plots[subplot];
            if (z > 0) {
              var idWithZ = subplotInfo.id;
              if (idWithZ.indexOf(zindexSeparator) !== -1) continue;
              idWithZ += zindexSeparator + (z + 1);
              subplotInfo = Lib.extendFlat({}, subplotInfo, {
                id: idWithZ,
                plot: fullLayout._cartesianlayer.selectAll(".subplot").select("." + idWithZ)
              });
            }
            var cdSubplot = [];
            var pcd;
            for (var j = 0; j < calcdata.length; j++) {
              var cd = calcdata[j];
              var trace = cd[0].trace;
              if (zorder !== (trace.zorder || 0)) continue;
              if (trace.xaxis + trace.yaxis === subplot) {
                if (traces.indexOf(trace.index) !== -1 || trace.carpet) {
                  if (pcd && pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && ["tonextx", "tonexty", "tonext"].indexOf(trace.fill) !== -1 && cdSubplot.indexOf(pcd) === -1) {
                    cdSubplot.push(pcd);
                  }
                  cdSubplot.push(cd);
                }
                pcd = cd;
              }
            }
            plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback);
          }
        }
      };
      function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) {
        var traceLayerClasses = constants.traceLayerClasses;
        var fullLayout = gd._fullLayout;
        var zindices = fullLayout._zindices;
        var modules = fullLayout._modules;
        var _module, cdModuleAndOthers, cdModule;
        var layerData = [];
        var zoomScaleQueryParts = [];
        for (var z = 0; z < zindices.length; z++) {
          var zorder = zindices[z];
          for (var i = 0; i < modules.length; i++) {
            _module = modules[i];
            var name2 = _module.name;
            var categories = Registry.modules[name2].categories;
            if (categories.svg) {
              var classBaseName = _module.layerName || name2 + "layer";
              var className = classBaseName + (z ? Number(z) + 1 : "");
              var plotMethod = _module.plot;
              cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod, zorder);
              cdModule = cdModuleAndOthers[0];
              cdSubplot = cdModuleAndOthers[1];
              if (cdModule.length) {
                layerData.push({
                  i: traceLayerClasses.indexOf(classBaseName),
                  zindex: z,
                  className,
                  plotMethod,
                  cdModule
                });
              }
              if (categories.zoomScale) {
                zoomScaleQueryParts.push("." + className);
              }
            }
          }
        }
        layerData.sort(function(a, b) {
          return (a.zindex || 0) - (b.zindex || 0) || a.i - b.i;
        });
        var layers = plotinfo.plot.selectAll("g.mlayer").data(layerData, function(d) {
          return d.className;
        });
        layers.enter().append("g").attr("class", function(d) {
          return d.className;
        }).classed("mlayer", true).classed("rangeplot", plotinfo.isRangePlot);
        layers.exit().remove();
        layers.order();
        layers.each(function(d) {
          var sel = d3.select(this);
          var className2 = d.className;
          d.plotMethod(
            gd,
            plotinfo,
            d.cdModule,
            sel,
            transitionOpts,
            makeOnCompleteCallback
          );
          if (constants.clipOnAxisFalseQuery.indexOf("." + className2) === -1) {
            Drawing.setClipUrl(sel, plotinfo.layerClipId, gd);
          }
        });
        if (fullLayout._has("scattergl")) {
          _module = Registry.getModule("scattergl");
          cdModule = getModuleCalcData(cdSubplot, _module)[0];
          _module.plot(gd, plotinfo, cdModule);
        }
        if (!gd._context.staticPlot) {
          if (plotinfo._hasClipOnAxisFalse) {
            plotinfo.clipOnAxisFalseTraces = plotinfo.plot.selectAll(constants.clipOnAxisFalseQuery.join(",")).selectAll(".trace");
          }
          if (zoomScaleQueryParts.length) {
            var traces = plotinfo.plot.selectAll(zoomScaleQueryParts.join(",")).selectAll(".trace");
            plotinfo.zoomScalePts = traces.selectAll("path.point");
            plotinfo.zoomScaleTxt = traces.selectAll(".textpoint");
          }
        }
      }
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldPlots = oldFullLayout._plots || {};
        var newPlots = newFullLayout._plots || {};
        var oldSubplotList = oldFullLayout._subplots || {};
        var plotinfo;
        var i, k;
        if (oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) {
          for (k in oldPlots) {
            plotinfo = oldPlots[k];
            if (plotinfo.plotgroup) plotinfo.plotgroup.remove();
          }
        }
        var hadGl = oldFullLayout._has && oldFullLayout._has("gl");
        var hasGl = newFullLayout._has && newFullLayout._has("gl");
        if (hadGl && !hasGl) {
          for (k in oldPlots) {
            plotinfo = oldPlots[k];
            if (plotinfo._scene) plotinfo._scene.destroy();
          }
        }
        if (oldSubplotList.xaxis && oldSubplotList.yaxis) {
          var oldAxIDs = axisIds.listIds({ _fullLayout: oldFullLayout });
          for (i = 0; i < oldAxIDs.length; i++) {
            var oldAxId = oldAxIDs[i];
            if (!newFullLayout[axisIds.id2name(oldAxId)]) {
              oldFullLayout._infolayer.selectAll(".g-" + oldAxId + "title").remove();
            }
          }
        }
        var hadCartesian = oldFullLayout._has && oldFullLayout._has("cartesian");
        var hasCartesian = newFullLayout._has && newFullLayout._has("cartesian");
        if (hadCartesian && !hasCartesian) {
          purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll(".subplot"), oldFullLayout);
          oldFullLayout._defs.selectAll(".axesclip").remove();
          delete oldFullLayout._axisConstraintGroups;
          delete oldFullLayout._axisMatchGroups;
        } else if (oldSubplotList.cartesian) {
          for (i = 0; i < oldSubplotList.cartesian.length; i++) {
            var oldSubplotId = oldSubplotList.cartesian[i];
            if (oldSubplotId.indexOf(zindexSeparator) !== -1) continue;
            if (!newPlots[oldSubplotId]) {
              var selector = "." + oldSubplotId + ",." + oldSubplotId + "-x,." + oldSubplotId + "-y";
              oldFullLayout._cartesianlayer.selectAll(selector).remove();
              removeSubplotExtras(oldSubplotId, oldFullLayout);
            }
          }
        }
      };
      exports.drawFramework = function(gd) {
        var fullLayout = gd._fullLayout;
        var calcdata = gd.calcdata;
        var i;
        var traceZorderGroups = {};
        for (i = 0; i < calcdata.length; i++) {
          var cdi = calcdata[i][0];
          var trace = cdi.trace;
          var zi = trace.zorder || 0;
          if (!traceZorderGroups[zi]) traceZorderGroups[zi] = [];
          traceZorderGroups[zi].push(cdi);
        }
        var zindices = Object.keys(traceZorderGroups).map(Number).sort(Lib.sorterAsc);
        if (!zindices.length) zindices = [0];
        fullLayout._zindices = zindices;
        var initialSubplotData = makeSubplotData(gd);
        var len = initialSubplotData.length;
        var subplotData = [];
        for (i = 0; i < len; i++) {
          subplotData[i] = initialSubplotData[i].slice();
        }
        for (var z = 1; z < zindices.length; z++) {
          var newSubplotData = [];
          for (i = 0; i < len; i++) {
            newSubplotData[i] = initialSubplotData[i].slice();
            newSubplotData[i][0] += zindexSeparator + (z + 1);
          }
          subplotData = subplotData.concat(newSubplotData);
        }
        var subplotLayers = fullLayout._cartesianlayer.selectAll(".subplot").data(subplotData, String);
        subplotLayers.enter().append("g").attr("class", function(d) {
          return "subplot " + d[0];
        });
        subplotLayers.order();
        subplotLayers.exit().call(purgeSubplotLayers, fullLayout);
        subplotLayers.each(function(d) {
          var id = d[0];
          var posZ = id.indexOf(zindexSeparator);
          var hasZ = posZ !== -1;
          var idWithoutZ = hasZ ? id.slice(0, posZ) : id;
          var plotinfo = fullLayout._plots[id];
          if (!plotinfo) {
            plotinfo = Lib.extendFlat({}, fullLayout._plots[idWithoutZ]);
            if (plotinfo) {
              plotinfo.id = id;
              fullLayout._plots[id] = plotinfo;
              fullLayout._subplots.cartesian.push(id);
            }
          }
          if (plotinfo) {
            plotinfo.plotgroup = d3.select(this);
            makeSubplotLayer(gd, plotinfo);
            if (!hasZ) {
              plotinfo.draglayer = ensureSingle(fullLayout._draggers, "g", id);
            }
          }
        });
      };
      exports.rangePlot = function(gd, plotinfo, cdSubplot) {
        makeSubplotLayer(gd, plotinfo);
        plotOne(gd, plotinfo, cdSubplot);
        Plots.style(gd);
      };
      function makeSubplotData(gd) {
        var fullLayout = gd._fullLayout;
        var numZ = fullLayout._zindices.length;
        var ids = fullLayout._subplots.cartesian;
        var len = ids.length;
        var i, j, id, plotinfo, xa, ya;
        var regulars = [];
        var overlays = [];
        for (i = 0; i < len; i++) {
          id = ids[i];
          plotinfo = fullLayout._plots[id];
          xa = plotinfo.xaxis;
          ya = plotinfo.yaxis;
          var xa2 = xa._mainAxis;
          var ya2 = ya._mainAxis;
          var mainplot = xa2._id + ya2._id;
          var mainplotinfo = fullLayout._plots[mainplot];
          plotinfo.overlays = [];
          if (mainplot !== id && mainplotinfo) {
            plotinfo.mainplot = mainplot;
            plotinfo.mainplotinfo = mainplotinfo;
            overlays.push(id);
          } else {
            plotinfo.mainplot = void 0;
            plotinfo.mainplotinfo = void 0;
            regulars.push(id);
          }
        }
        for (i = 0; i < overlays.length; i++) {
          id = overlays[i];
          plotinfo = fullLayout._plots[id];
          plotinfo.mainplotinfo.overlays.push(plotinfo);
        }
        var subplotIds = regulars.concat(overlays);
        var subplotData = [];
        for (i = 0; i < len; i++) {
          id = subplotIds[i];
          plotinfo = fullLayout._plots[id];
          xa = plotinfo.xaxis;
          ya = plotinfo.yaxis;
          var d = [];
          for (var z = 1; z <= numZ; z++) {
            var zStr = "";
            if (z > 1) zStr += zindexSeparator + z;
            d.push(id + zStr);
            for (j = 0; j < plotinfo.overlays.length; j++) {
              d.push(plotinfo.overlays[j].id + zStr);
            }
          }
          d = d.concat([
            xa.layer,
            ya.layer,
            xa.overlaying || "",
            ya.overlaying || ""
          ]);
          subplotData.push(d);
        }
        return subplotData;
      }
      function makeSubplotLayer(gd, plotinfo) {
        var fullLayout = gd._fullLayout;
        var plotgroup = plotinfo.plotgroup;
        var id = plotinfo.id;
        var posZ = id.indexOf(zindexSeparator);
        var hasZ = posZ !== -1;
        var xLayer = constants.layerValue2layerClass[plotinfo.xaxis.layer];
        var yLayer = constants.layerValue2layerClass[plotinfo.yaxis.layer];
        var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms;
        var hasMultipleZ = fullLayout._zindices.length > 1;
        var mainplotinfo = plotinfo.mainplotinfo;
        if (!plotinfo.mainplot || hasMultipleZ) {
          if (hasOnlyLargeSploms) {
            plotinfo.xlines = ensureSingle(plotgroup, "path", "xlines-above");
            plotinfo.ylines = ensureSingle(plotgroup, "path", "ylines-above");
            plotinfo.xaxislayer = ensureSingle(plotgroup, "g", "xaxislayer-above");
            plotinfo.yaxislayer = ensureSingle(plotgroup, "g", "yaxislayer-above");
          } else {
            if (!hasZ) {
              var backLayer = ensureSingle(plotgroup, "g", "layer-subplot");
              plotinfo.shapelayer = ensureSingle(backLayer, "g", "shapelayer");
              plotinfo.imagelayer = ensureSingle(backLayer, "g", "imagelayer");
              if (mainplotinfo && hasMultipleZ) {
                plotinfo.minorGridlayer = mainplotinfo.minorGridlayer;
                plotinfo.gridlayer = mainplotinfo.gridlayer;
                plotinfo.zerolinelayer = mainplotinfo.zerolinelayer;
              } else {
                plotinfo.minorGridlayer = ensureSingle(plotgroup, "g", "minor-gridlayer");
                plotinfo.gridlayer = ensureSingle(plotgroup, "g", "gridlayer");
                plotinfo.zerolinelayer = ensureSingle(plotgroup, "g", "zerolinelayer");
              }
              var betweenLayer = ensureSingle(plotgroup, "g", "layer-between");
              plotinfo.shapelayerBetween = ensureSingle(betweenLayer, "g", "shapelayer");
              plotinfo.imagelayerBetween = ensureSingle(betweenLayer, "g", "imagelayer");
              ensureSingle(plotgroup, "path", "xlines-below");
              ensureSingle(plotgroup, "path", "ylines-below");
              plotinfo.overlinesBelow = ensureSingle(plotgroup, "g", "overlines-below");
              ensureSingle(plotgroup, "g", "xaxislayer-below");
              ensureSingle(plotgroup, "g", "yaxislayer-below");
              plotinfo.overaxesBelow = ensureSingle(plotgroup, "g", "overaxes-below");
            }
            plotinfo.overplot = ensureSingle(plotgroup, "g", "overplot");
            plotinfo.plot = ensureSingle(plotinfo.overplot, "g", id);
            if (mainplotinfo && hasMultipleZ) {
              plotinfo.zerolinelayerAbove = mainplotinfo.zerolinelayerAbove;
            } else {
              plotinfo.zerolinelayerAbove = ensureSingle(plotgroup, "g", "zerolinelayer-above");
            }
            if (!hasZ) {
              plotinfo.xlines = ensureSingle(plotgroup, "path", "xlines-above");
              plotinfo.ylines = ensureSingle(plotgroup, "path", "ylines-above");
              plotinfo.overlinesAbove = ensureSingle(plotgroup, "g", "overlines-above");
              ensureSingle(plotgroup, "g", "xaxislayer-above");
              ensureSingle(plotgroup, "g", "yaxislayer-above");
              plotinfo.overaxesAbove = ensureSingle(plotgroup, "g", "overaxes-above");
              plotinfo.xlines = plotgroup.select(".xlines-" + xLayer);
              plotinfo.ylines = plotgroup.select(".ylines-" + yLayer);
              plotinfo.xaxislayer = plotgroup.select(".xaxislayer-" + xLayer);
              plotinfo.yaxislayer = plotgroup.select(".yaxislayer-" + yLayer);
            }
          }
        } else {
          var mainplotgroup = mainplotinfo.plotgroup;
          var xId = id + "-x";
          var yId = id + "-y";
          plotinfo.minorGridlayer = mainplotinfo.minorGridlayer;
          plotinfo.gridlayer = mainplotinfo.gridlayer;
          plotinfo.zerolinelayer = mainplotinfo.zerolinelayer;
          plotinfo.zerolinelayerAbove = mainplotinfo.zerolinelayerAbove;
          ensureSingle(mainplotinfo.overlinesBelow, "path", xId);
          ensureSingle(mainplotinfo.overlinesBelow, "path", yId);
          ensureSingle(mainplotinfo.overaxesBelow, "g", xId);
          ensureSingle(mainplotinfo.overaxesBelow, "g", yId);
          plotinfo.plot = ensureSingle(mainplotinfo.overplot, "g", id);
          ensureSingle(mainplotinfo.overlinesAbove, "path", xId);
          ensureSingle(mainplotinfo.overlinesAbove, "path", yId);
          ensureSingle(mainplotinfo.overaxesAbove, "g", xId);
          ensureSingle(mainplotinfo.overaxesAbove, "g", yId);
          plotinfo.xlines = mainplotgroup.select(".overlines-" + xLayer).select("." + xId);
          plotinfo.ylines = mainplotgroup.select(".overlines-" + yLayer).select("." + yId);
          plotinfo.xaxislayer = mainplotgroup.select(".overaxes-" + xLayer).select("." + xId);
          plotinfo.yaxislayer = mainplotgroup.select(".overaxes-" + yLayer).select("." + yId);
        }
        if (!hasZ) {
          if (!hasOnlyLargeSploms) {
            ensureSingleAndAddDatum(plotinfo.minorGridlayer, "g", plotinfo.xaxis._id);
            ensureSingleAndAddDatum(plotinfo.minorGridlayer, "g", plotinfo.yaxis._id);
            plotinfo.minorGridlayer.selectAll("g").map(function(d) {
              return d[0];
            }).sort(axisIds.idSort);
            ensureSingleAndAddDatum(plotinfo.gridlayer, "g", plotinfo.xaxis._id);
            ensureSingleAndAddDatum(plotinfo.gridlayer, "g", plotinfo.yaxis._id);
            plotinfo.gridlayer.selectAll("g").map(function(d) {
              return d[0];
            }).sort(axisIds.idSort);
          }
          plotinfo.xlines.style("fill", "none").classed("crisp", true);
          plotinfo.ylines.style("fill", "none").classed("crisp", true);
        }
      }
      function purgeSubplotLayers(layers, fullLayout) {
        if (!layers) return;
        var overlayIdsToRemove = {};
        layers.each(function(d) {
          var id = d[0];
          var plotgroup = d3.select(this);
          plotgroup.remove();
          removeSubplotExtras(id, fullLayout);
          overlayIdsToRemove[id] = true;
        });
        for (var k in fullLayout._plots) {
          var subplotInfo = fullLayout._plots[k];
          var overlays = subplotInfo.overlays || [];
          for (var j = 0; j < overlays.length; j++) {
            var overlayInfo = overlays[j];
            if (overlayIdsToRemove[overlayInfo.id]) {
              overlayInfo.plot.selectAll(".trace").remove();
            }
          }
        }
      }
      function removeSubplotExtras(subplotId, fullLayout) {
        fullLayout._draggers.selectAll("g." + subplotId).remove();
        fullLayout._defs.select("#clip" + fullLayout._uid + subplotId + "plot").remove();
      }
      exports.toSVG = function(gd) {
        var imageRoot = gd._fullLayout._glimages;
        var root = d3.select(gd).selectAll(".svg-container");
        var canvases = root.filter(function(d, i) {
          return i === root.size() - 1;
        }).selectAll(".gl-canvas-context, .gl-canvas-focus");
        function canvasToImage() {
          var canvas = this;
          var imageData = canvas.toDataURL("image/png");
          var image = imageRoot.append("svg:image");
          image.attr({
            xmlns: xmlnsNamespaces.svg,
            "xlink:href": imageData,
            preserveAspectRatio: "none",
            x: 0,
            y: 0,
            width: canvas.style.width,
            height: canvas.style.height
          });
        }
        canvases.each(canvasToImage);
      };
      exports.updateFx = require_graph_interact().updateFx;
    }
  });

  // src/traces/scatter/index.js
  var require_scatter = __commonJS({
    "src/traces/scatter/index.js"(exports, module) {
      "use strict";
      var subtypes = require_subtypes();
      module.exports = {
        hasLines: subtypes.hasLines,
        hasMarkers: subtypes.hasMarkers,
        hasText: subtypes.hasText,
        isBubble: subtypes.isBubble,
        attributes: require_attributes12(),
        layoutAttributes: require_layout_attributes3(),
        supplyDefaults: require_defaults8(),
        crossTraceDefaults: require_cross_trace_defaults2(),
        supplyLayoutDefaults: require_layout_defaults3(),
        calc: require_calc3().calc,
        crossTraceCalc: require_cross_trace_calc2(),
        arraysToCalcdata: require_arrays_to_calcdata(),
        plot: require_plot(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels(),
        style: require_style2().style,
        styleOnSelect: require_style2().styleOnSelect,
        hoverPoints: require_hover2(),
        selectPoints: require_select2(),
        animatable: true,
        moduleType: "trace",
        name: "scatter",
        basePlotModule: require_cartesian(),
        categories: [
          "cartesian",
          "svg",
          "symbols",
          "errorBarsOK",
          "showLegend",
          "scatter-like",
          "zoomScale"
        ],
        meta: {}
      };
    }
  });

  // src/components/annotations/draw_arrow_head.js
  var require_draw_arrow_head = __commonJS({
    "src/components/annotations/draw_arrow_head.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var ARROWPATHS = require_arrow_paths();
      var Lib = require_lib();
      var strScale = Lib.strScale;
      var strRotate = Lib.strRotate;
      var strTranslate = Lib.strTranslate;
      module.exports = function drawArrowHead(el3, ends, options) {
        var el = el3.node();
        var headStyle = ARROWPATHS[options.arrowhead || 0];
        var startHeadStyle = ARROWPATHS[options.startarrowhead || 0];
        var scale = (options.arrowwidth || 1) * (options.arrowsize || 1);
        var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1);
        var doStart = ends.indexOf("start") >= 0;
        var doEnd = ends.indexOf("end") >= 0;
        var backOff = headStyle.backoff * scale + options.standoff;
        var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff;
        var start, end, startRot, endRot;
        if (el.nodeName === "line") {
          start = { x: +el3.attr("x1"), y: +el3.attr("y1") };
          end = { x: +el3.attr("x2"), y: +el3.attr("y2") };
          var dx = start.x - end.x;
          var dy = start.y - end.y;
          startRot = Math.atan2(dy, dx);
          endRot = startRot + Math.PI;
          if (backOff && startBackOff) {
            if (backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) {
              hideLine();
              return;
            }
          }
          if (backOff) {
            if (backOff * backOff > dx * dx + dy * dy) {
              hideLine();
              return;
            }
            var backOffX = backOff * Math.cos(startRot);
            var backOffY = backOff * Math.sin(startRot);
            end.x += backOffX;
            end.y += backOffY;
            el3.attr({ x2: end.x, y2: end.y });
          }
          if (startBackOff) {
            if (startBackOff * startBackOff > dx * dx + dy * dy) {
              hideLine();
              return;
            }
            var startBackOffX = startBackOff * Math.cos(startRot);
            var startbackOffY = startBackOff * Math.sin(startRot);
            start.x -= startBackOffX;
            start.y -= startbackOffY;
            el3.attr({ x1: start.x, y1: start.y });
          }
        } else if (el.nodeName === "path") {
          var pathlen = el.getTotalLength();
          var dashArray = "";
          if (pathlen < backOff + startBackOff) {
            hideLine();
            return;
          }
          var start0 = el.getPointAtLength(0);
          var dstart = el.getPointAtLength(0.1);
          startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x);
          start = el.getPointAtLength(Math.min(startBackOff, pathlen));
          dashArray = "0px," + startBackOff + "px,";
          var end0 = el.getPointAtLength(pathlen);
          var dend = el.getPointAtLength(pathlen - 0.1);
          endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x);
          end = el.getPointAtLength(Math.max(0, pathlen - backOff));
          var shortening = dashArray ? startBackOff + backOff : backOff;
          dashArray += pathlen - shortening + "px," + pathlen + "px";
          el3.style("stroke-dasharray", dashArray);
        }
        function hideLine() {
          el3.style("stroke-dasharray", "0px,100px");
        }
        function drawhead(arrowHeadStyle, p, rot, arrowScale) {
          if (!arrowHeadStyle.path) return;
          if (arrowHeadStyle.noRotate) rot = 0;
          d3.select(el.parentNode).append("path").attr({
            class: el3.attr("class"),
            d: arrowHeadStyle.path,
            transform: strTranslate(p.x, p.y) + strRotate(rot * 180 / Math.PI) + strScale(arrowScale)
          }).style({
            fill: Color2.rgb(options.arrowcolor),
            "stroke-width": 0
          });
        }
        if (doStart) drawhead(startHeadStyle, start, startRot, startScale);
        if (doEnd) drawhead(headStyle, end, endRot, scale);
      };
    }
  });

  // src/components/annotations/draw.js
  var require_draw4 = __commonJS({
    "src/components/annotations/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Plots = require_plots();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var Axes = require_axes();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Fx = require_fx();
      var svgTextUtils = require_svg_text_utils();
      var setCursor = require_setcursor();
      var dragElement = require_dragelement();
      var arrayEditor = require_plot_template().arrayEditor;
      var drawArrowHead = require_draw_arrow_head();
      module.exports = {
        draw,
        drawOne,
        drawRaw
      };
      function draw(gd) {
        var fullLayout = gd._fullLayout;
        fullLayout._infolayer.selectAll(".annotation").remove();
        for (var i = 0; i < fullLayout.annotations.length; i++) {
          if (fullLayout.annotations[i].visible) {
            drawOne(gd, i);
          }
        }
        return Plots.previousPromises(gd);
      }
      function drawOne(gd, index) {
        var fullLayout = gd._fullLayout;
        var options = fullLayout.annotations[index] || {};
        var xa = Axes.getFromId(gd, options.xref);
        var ya = Axes.getFromId(gd, options.yref);
        if (xa) xa.setScale();
        if (ya) ya.setScale();
        drawRaw(gd, options, index, false, xa, ya);
      }
      function shiftPosition(axa, dAx, axLetter, gs, options) {
        var optAx = options[axLetter];
        var axRef = options[axLetter + "ref"];
        var vertical = axLetter.indexOf("y") !== -1;
        var axDomainRef = Axes.getRefType(axRef) === "domain";
        var gsDim = vertical ? gs.h : gs.w;
        if (axa) {
          if (axDomainRef) {
            return optAx + (vertical ? -dAx : dAx) / axa._length;
          } else {
            return axa.p2r(axa.r2p(optAx) + dAx);
          }
        } else {
          return optAx + (vertical ? -dAx : dAx) / gsDim;
        }
      }
      function drawRaw(gd, options, index, subplotId, xa, ya) {
        var fullLayout = gd._fullLayout;
        var gs = gd._fullLayout._size;
        var edits = gd._context.edits;
        var className, containerStr;
        if (subplotId) {
          className = "annotation-" + subplotId;
          containerStr = subplotId + ".annotations";
        } else {
          className = "annotation";
          containerStr = "annotations";
        }
        var editHelpers = arrayEditor(gd.layout, containerStr, options);
        var modifyBase = editHelpers.modifyBase;
        var modifyItem = editHelpers.modifyItem;
        var getUpdateObj = editHelpers.getUpdateObj;
        fullLayout._infolayer.selectAll("." + className + '[data-index="' + index + '"]').remove();
        var annClipID = "clip" + fullLayout._uid + "_ann" + index;
        if (!options._input || options.visible === false) {
          d3.selectAll("#" + annClipID).remove();
          return;
        }
        var annPosPx = { x: {}, y: {} };
        var textangle = +options.textangle || 0;
        var annGroup = fullLayout._infolayer.append("g").classed(className, true).attr("data-index", String(index)).style("opacity", options.opacity);
        var annTextGroup = annGroup.append("g").classed("annotation-text-g", true);
        var editTextPosition = edits[options.showarrow ? "annotationTail" : "annotationPosition"];
        var textEvents = options.captureevents || edits.annotationText || editTextPosition;
        function makeEventData(initialEvent) {
          var eventData = {
            index,
            annotation: options._input,
            fullAnnotation: options,
            event: initialEvent
          };
          if (subplotId) {
            eventData.subplotId = subplotId;
          }
          return eventData;
        }
        var annTextGroupInner = annTextGroup.append("g").style("pointer-events", textEvents ? "all" : null).call(setCursor, "pointer").on("click", function() {
          gd._dragging = false;
          gd.emit("plotly_clickannotation", makeEventData(d3.event));
        });
        if (options.hovertext) {
          annTextGroupInner.on("mouseover", function() {
            var hoverOptions = options.hoverlabel;
            var hoverFont = hoverOptions.font;
            var bBox = this.getBoundingClientRect();
            var bBoxRef = gd.getBoundingClientRect();
            Fx.loneHover({
              x0: bBox.left - bBoxRef.left,
              x1: bBox.right - bBoxRef.left,
              y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top,
              text: options.hovertext,
              color: hoverOptions.bgcolor,
              borderColor: hoverOptions.bordercolor,
              fontFamily: hoverFont.family,
              fontSize: hoverFont.size,
              fontColor: hoverFont.color,
              fontWeight: hoverFont.weight,
              fontStyle: hoverFont.style,
              fontVariant: hoverFont.variant,
              fontShadow: hoverFont.fontShadow,
              fontLineposition: hoverFont.fontLineposition,
              fontTextcase: hoverFont.fontTextcase
            }, {
              container: fullLayout._hoverlayer.node(),
              outerContainer: fullLayout._paper.node(),
              gd
            });
          }).on("mouseout", function() {
            Fx.loneUnhover(fullLayout._hoverlayer.node());
          });
        }
        var borderwidth = options.borderwidth;
        var borderpad = options.borderpad;
        var borderfull = borderwidth + borderpad;
        var annTextBG = annTextGroupInner.append("rect").attr("class", "bg").style("stroke-width", borderwidth + "px").call(Color2.stroke, options.bordercolor).call(Color2.fill, options.bgcolor);
        var isSizeConstrained = options.width || options.height;
        var annTextClip = fullLayout._topclips.selectAll("#" + annClipID).data(isSizeConstrained ? [0] : []);
        annTextClip.enter().append("clipPath").classed("annclip", true).attr("id", annClipID).append("rect");
        annTextClip.exit().remove();
        var font = options.font;
        var text = fullLayout._meta ? Lib.templateString(options.text, fullLayout._meta) : options.text;
        var annText = annTextGroupInner.append("text").classed("annotation-text", true).text(text);
        function textLayout(s) {
          s.call(Drawing.font, font).attr({
            "text-anchor": {
              left: "start",
              right: "end"
            }[options.align] || "middle"
          });
          svgTextUtils.convertToTspans(s, gd, drawGraphicalElements);
          return s;
        }
        function drawGraphicalElements() {
          var anchor3 = annText.selectAll("a");
          if (anchor3.size() === 1 && anchor3.text() === annText.text()) {
            var wholeLink = annTextGroupInner.insert("a", ":first-child").attr({
              "xlink:xlink:href": anchor3.attr("xlink:href"),
              "xlink:xlink:show": anchor3.attr("xlink:show")
            }).style({ cursor: "pointer" });
            wholeLink.node().appendChild(annTextBG.node());
          }
          var mathjaxGroup = annTextGroupInner.select(".annotation-text-math-group");
          var hasMathjax = !mathjaxGroup.empty();
          var anntextBB = Drawing.bBox(
            (hasMathjax ? mathjaxGroup : annText).node()
          );
          var textWidth = anntextBB.width;
          var textHeight = anntextBB.height;
          var annWidth = options.width || textWidth;
          var annHeight = options.height || textHeight;
          var outerWidth = Math.round(annWidth + 2 * borderfull);
          var outerHeight = Math.round(annHeight + 2 * borderfull);
          function shiftFraction(v, anchor2) {
            if (anchor2 === "auto") {
              if (v < 1 / 3) anchor2 = "left";
              else if (v > 2 / 3) anchor2 = "right";
              else anchor2 = "center";
            }
            return {
              center: 0,
              middle: 0,
              left: 0.5,
              bottom: -0.5,
              right: -0.5,
              top: 0.5
            }[anchor2];
          }
          var annotationIsOffscreen = false;
          var letters = ["x", "y"];
          for (var i = 0; i < letters.length; i++) {
            var axLetter = letters[i];
            var axRef = options[axLetter + "ref"] || axLetter;
            var tailRef = options["a" + axLetter + "ref"];
            var ax = { x: xa, y: ya }[axLetter];
            var dimAngle = (textangle + (axLetter === "x" ? 0 : -90)) * Math.PI / 180;
            var annSizeFromWidth = outerWidth * Math.cos(dimAngle);
            var annSizeFromHeight = outerHeight * Math.sin(dimAngle);
            var annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight);
            var anchor = options[axLetter + "anchor"];
            var overallShift = options[axLetter + "shift"] * (axLetter === "x" ? 1 : -1);
            var posPx = annPosPx[axLetter];
            var basePx;
            var textPadShift;
            var alignPosition;
            var autoAlignFraction;
            var textShift;
            var axRefType = Axes.getRefType(axRef);
            if (ax && axRefType !== "domain") {
              var posFraction = ax.r2fraction(options[axLetter]);
              if (posFraction < 0 || posFraction > 1) {
                if (tailRef === axRef) {
                  posFraction = ax.r2fraction(options["a" + axLetter]);
                  if (posFraction < 0 || posFraction > 1) {
                    annotationIsOffscreen = true;
                  }
                } else {
                  annotationIsOffscreen = true;
                }
              }
              basePx = ax._offset + ax.r2p(options[axLetter]);
              autoAlignFraction = 0.5;
            } else {
              var axRefTypeEqDomain = axRefType === "domain";
              if (axLetter === "x") {
                alignPosition = options[axLetter];
                basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.l + gs.w * alignPosition;
              } else {
                alignPosition = 1 - options[axLetter];
                basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.t + gs.h * alignPosition;
              }
              autoAlignFraction = options.showarrow ? 0.5 : alignPosition;
            }
            if (options.showarrow) {
              posPx.head = basePx;
              var arrowLength = options["a" + axLetter];
              textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - annSizeFromHeight * shiftFraction(0.5, options.yanchor);
              if (tailRef === axRef) {
                var tailRefType = Axes.getRefType(tailRef);
                if (tailRefType === "domain") {
                  if (axLetter === "y") {
                    arrowLength = 1 - arrowLength;
                  }
                  posPx.tail = ax._offset + ax._length * arrowLength;
                } else if (tailRefType === "paper") {
                  if (axLetter === "y") {
                    arrowLength = 1 - arrowLength;
                    posPx.tail = gs.t + gs.h * arrowLength;
                  } else {
                    posPx.tail = gs.l + gs.w * arrowLength;
                  }
                } else {
                  posPx.tail = ax._offset + ax.r2p(arrowLength);
                }
                textPadShift = textShift;
              } else {
                posPx.tail = basePx + arrowLength;
                textPadShift = textShift + arrowLength;
              }
              posPx.text = posPx.tail + textShift;
              var maxPx = fullLayout[axLetter === "x" ? "width" : "height"];
              if (axRef === "paper") {
                posPx.head = Lib.constrain(posPx.head, 1, maxPx - 1);
              }
              if (tailRef === "pixel") {
                var shiftPlus = -Math.max(posPx.tail - 3, posPx.text);
                var shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx;
                if (shiftPlus > 0) {
                  posPx.tail += shiftPlus;
                  posPx.text += shiftPlus;
                } else if (shiftMinus > 0) {
                  posPx.tail -= shiftMinus;
                  posPx.text -= shiftMinus;
                }
              }
              posPx.tail += overallShift;
              posPx.head += overallShift;
            } else {
              textShift = annSize * shiftFraction(autoAlignFraction, anchor);
              textPadShift = textShift;
              posPx.text = basePx + textShift;
            }
            posPx.text += overallShift;
            textShift += overallShift;
            textPadShift += overallShift;
            options["_" + axLetter + "padplus"] = annSize / 2 + textPadShift;
            options["_" + axLetter + "padminus"] = annSize / 2 - textPadShift;
            options["_" + axLetter + "size"] = annSize;
            options["_" + axLetter + "shift"] = textShift;
          }
          if (annotationIsOffscreen) {
            annTextGroupInner.remove();
            return;
          }
          var xShift = 0;
          var yShift = 0;
          if (options.align !== "left") {
            xShift = (annWidth - textWidth) * (options.align === "center" ? 0.5 : 1);
          }
          if (options.valign !== "top") {
            yShift = (annHeight - textHeight) * (options.valign === "middle" ? 0.5 : 1);
          }
          if (hasMathjax) {
            mathjaxGroup.select("svg").attr({
              x: borderfull + xShift - 1,
              y: borderfull + yShift
            }).call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
          } else {
            var texty = borderfull + yShift - anntextBB.top;
            var textx = borderfull + xShift - anntextBB.left;
            annText.call(svgTextUtils.positionText, textx, texty).call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
          }
          annTextClip.select("rect").call(
            Drawing.setRect,
            borderfull,
            borderfull,
            annWidth,
            annHeight
          );
          annTextBG.call(
            Drawing.setRect,
            borderwidth / 2,
            borderwidth / 2,
            outerWidth - borderwidth,
            outerHeight - borderwidth
          );
          annTextGroupInner.call(
            Drawing.setTranslate,
            Math.round(annPosPx.x.text - outerWidth / 2),
            Math.round(annPosPx.y.text - outerHeight / 2)
          );
          annTextGroup.attr({ transform: "rotate(" + textangle + "," + annPosPx.x.text + "," + annPosPx.y.text + ")" });
          var drawArrow = function(dx, dy) {
            annGroup.selectAll(".annotation-arrow-g").remove();
            var headX = annPosPx.x.head;
            var headY = annPosPx.y.head;
            var tailX = annPosPx.x.tail + dx;
            var tailY = annPosPx.y.tail + dy;
            var textX = annPosPx.x.text + dx;
            var textY = annPosPx.y.text + dy;
            var transform = Lib.rotationXYMatrix(textangle, textX, textY);
            var applyTransform = Lib.apply2DTransform(transform);
            var applyTransform2 = Lib.apply2DTransform2(transform);
            var width = +annTextBG.attr("width");
            var height = +annTextBG.attr("height");
            var xLeft = textX - 0.5 * width;
            var xRight = xLeft + width;
            var yTop = textY - 0.5 * height;
            var yBottom = yTop + height;
            var edges = [
              [xLeft, yTop, xLeft, yBottom],
              [xLeft, yBottom, xRight, yBottom],
              [xRight, yBottom, xRight, yTop],
              [xRight, yTop, xLeft, yTop]
            ].map(applyTransform2);
            if (edges.reduce(function(a, x) {
              return a ^ !!Lib.segmentsIntersect(
                headX,
                headY,
                headX + 1e6,
                headY + 1e6,
                x[0],
                x[1],
                x[2],
                x[3]
              );
            }, false)) {
              return;
            }
            edges.forEach(function(x) {
              var p = Lib.segmentsIntersect(
                tailX,
                tailY,
                headX,
                headY,
                x[0],
                x[1],
                x[2],
                x[3]
              );
              if (p) {
                tailX = p.x;
                tailY = p.y;
              }
            });
            var strokewidth = options.arrowwidth;
            var arrowColor = options.arrowcolor;
            var arrowSide = options.arrowside;
            var arrowGroup = annGroup.append("g").style({ opacity: Color2.opacity(arrowColor) }).classed("annotation-arrow-g", true);
            var arrow = arrowGroup.append("path").attr("d", "M" + tailX + "," + tailY + "L" + headX + "," + headY).style("stroke-width", strokewidth + "px").call(Color2.stroke, Color2.rgb(arrowColor));
            drawArrowHead(arrow, arrowSide, options);
            if (edits.annotationPosition && arrow.node().parentNode && !subplotId) {
              var arrowDragHeadX = headX;
              var arrowDragHeadY = headY;
              if (options.standoff) {
                var arrowLength2 = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2));
                arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength2;
                arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength2;
              }
              var arrowDrag = arrowGroup.append("path").classed("annotation-arrow", true).classed("anndrag", true).classed("cursor-move", true).attr({
                d: "M3,3H-3V-3H3ZM0,0L" + (tailX - arrowDragHeadX) + "," + (tailY - arrowDragHeadY),
                transform: strTranslate(arrowDragHeadX, arrowDragHeadY)
              }).style("stroke-width", strokewidth + 6 + "px").call(Color2.stroke, "rgba(0,0,0,0)").call(Color2.fill, "rgba(0,0,0,0)");
              var annx0, anny0;
              dragElement.init({
                element: arrowDrag.node(),
                gd,
                prepFn: function() {
                  var pos = Drawing.getTranslate(annTextGroupInner);
                  annx0 = pos.x;
                  anny0 = pos.y;
                  if (xa && xa.autorange) {
                    modifyBase(xa._name + ".autorange", true);
                  }
                  if (ya && ya.autorange) {
                    modifyBase(ya._name + ".autorange", true);
                  }
                },
                moveFn: function(dx2, dy2) {
                  var annxy0 = applyTransform(annx0, anny0);
                  var xcenter = annxy0[0] + dx2;
                  var ycenter = annxy0[1] + dy2;
                  annTextGroupInner.call(Drawing.setTranslate, xcenter, ycenter);
                  modifyItem(
                    "x",
                    shiftPosition(xa, dx2, "x", gs, options)
                  );
                  modifyItem(
                    "y",
                    shiftPosition(ya, dy2, "y", gs, options)
                  );
                  if (options.axref === options.xref) {
                    modifyItem("ax", shiftPosition(xa, dx2, "ax", gs, options));
                  }
                  if (options.ayref === options.yref) {
                    modifyItem("ay", shiftPosition(ya, dy2, "ay", gs, options));
                  }
                  arrowGroup.attr("transform", strTranslate(dx2, dy2));
                  annTextGroup.attr({
                    transform: "rotate(" + textangle + "," + xcenter + "," + ycenter + ")"
                  });
                },
                doneFn: function() {
                  Registry.call("_guiRelayout", gd, getUpdateObj());
                  var notesBox = document.querySelector(".js-notes-box-panel");
                  if (notesBox) notesBox.redraw(notesBox.selectedObj);
                }
              });
            }
          };
          if (options.showarrow) drawArrow(0, 0);
          if (editTextPosition) {
            var baseTextTransform;
            dragElement.init({
              element: annTextGroupInner.node(),
              gd,
              prepFn: function() {
                baseTextTransform = annTextGroup.attr("transform");
              },
              moveFn: function(dx, dy) {
                var csr = "pointer";
                if (options.showarrow) {
                  if (options.axref === options.xref) {
                    modifyItem("ax", shiftPosition(xa, dx, "ax", gs, options));
                  } else {
                    modifyItem("ax", options.ax + dx);
                  }
                  if (options.ayref === options.yref) {
                    modifyItem("ay", shiftPosition(ya, dy, "ay", gs.w, options));
                  } else {
                    modifyItem("ay", options.ay + dy);
                  }
                  drawArrow(dx, dy);
                } else if (!subplotId) {
                  var xUpdate, yUpdate;
                  if (xa) {
                    xUpdate = shiftPosition(xa, dx, "x", gs, options);
                  } else {
                    var widthFraction = options._xsize / gs.w;
                    var xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2;
                    xUpdate = dragElement.align(
                      xLeft + dx / gs.w,
                      widthFraction,
                      0,
                      1,
                      options.xanchor
                    );
                  }
                  if (ya) {
                    yUpdate = shiftPosition(ya, dy, "y", gs, options);
                  } else {
                    var heightFraction = options._ysize / gs.h;
                    var yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2;
                    yUpdate = dragElement.align(
                      yBottom - dy / gs.h,
                      heightFraction,
                      0,
                      1,
                      options.yanchor
                    );
                  }
                  modifyItem("x", xUpdate);
                  modifyItem("y", yUpdate);
                  if (!xa || !ya) {
                    csr = dragElement.getCursor(
                      xa ? 0.5 : xUpdate,
                      ya ? 0.5 : yUpdate,
                      options.xanchor,
                      options.yanchor
                    );
                  }
                } else return;
                annTextGroup.attr({
                  transform: strTranslate(dx, dy) + baseTextTransform
                });
                setCursor(annTextGroupInner, csr);
              },
              clickFn: function(_, initialEvent) {
                if (options.captureevents) {
                  gd.emit("plotly_clickannotation", makeEventData(initialEvent));
                }
              },
              doneFn: function() {
                setCursor(annTextGroupInner);
                Registry.call("_guiRelayout", gd, getUpdateObj());
                var notesBox = document.querySelector(".js-notes-box-panel");
                if (notesBox) notesBox.redraw(notesBox.selectedObj);
              }
            });
          }
        }
        if (edits.annotationText) {
          annText.call(svgTextUtils.makeEditable, { delegate: annTextGroupInner, gd }).call(textLayout).on("edit", function(_text) {
            options.text = _text;
            this.call(textLayout);
            modifyItem("text", _text);
            if (xa && xa.autorange) {
              modifyBase(xa._name + ".autorange", true);
            }
            if (ya && ya.autorange) {
              modifyBase(ya._name + ".autorange", true);
            }
            Registry.call("_guiRelayout", gd, getUpdateObj());
          });
        } else annText.call(textLayout);
      }
    }
  });

  // src/components/annotations/click.js
  var require_click2 = __commonJS({
    "src/components/annotations/click.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Registry = require_registry();
      var arrayEditor = require_plot_template().arrayEditor;
      module.exports = {
        hasClickToShow,
        onClick
      };
      function hasClickToShow(gd, hoverData) {
        var sets = getToggleSets(gd, hoverData);
        return sets.on.length > 0 || sets.explicitOff.length > 0;
      }
      function onClick(gd, hoverData) {
        var toggleSets = getToggleSets(gd, hoverData);
        var onSet = toggleSets.on;
        var offSet = toggleSets.off.concat(toggleSets.explicitOff);
        var update = {};
        var annotationsOut = gd._fullLayout.annotations;
        var i, editHelpers;
        if (!(onSet.length || offSet.length)) return;
        for (i = 0; i < onSet.length; i++) {
          editHelpers = arrayEditor(gd.layout, "annotations", annotationsOut[onSet[i]]);
          editHelpers.modifyItem("visible", true);
          Lib.extendFlat(update, editHelpers.getUpdateObj());
        }
        for (i = 0; i < offSet.length; i++) {
          editHelpers = arrayEditor(gd.layout, "annotations", annotationsOut[offSet[i]]);
          editHelpers.modifyItem("visible", false);
          Lib.extendFlat(update, editHelpers.getUpdateObj());
        }
        return Registry.call("update", gd, {}, update);
      }
      function getToggleSets(gd, hoverData) {
        var annotations = gd._fullLayout.annotations;
        var onSet = [];
        var offSet = [];
        var explicitOffSet = [];
        var hoverLen = (hoverData || []).length;
        var i, j, anni, showMode, pointj, xa, ya, toggleType;
        for (i = 0; i < annotations.length; i++) {
          anni = annotations[i];
          showMode = anni.clicktoshow;
          if (showMode) {
            for (j = 0; j < hoverLen; j++) {
              pointj = hoverData[j];
              xa = pointj.xaxis;
              ya = pointj.yaxis;
              if (xa._id === anni.xref && ya._id === anni.yref && xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) && ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)) {
                if (anni.visible) {
                  if (showMode === "onout") toggleType = offSet;
                  else toggleType = explicitOffSet;
                } else {
                  toggleType = onSet;
                }
                toggleType.push(i);
                break;
              }
            }
            if (j === hoverLen) {
              if (anni.visible && showMode === "onout") offSet.push(i);
            }
          }
        }
        return { on: onSet, off: offSet, explicitOff: explicitOffSet };
      }
      function clickData2r(d, ax) {
        return ax.type === "log" ? ax.l2r(d) : ax.d2r(d);
      }
    }
  });

  // src/components/annotations/common_defaults.js
  var require_common_defaults = __commonJS({
    "src/components/annotations/common_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      module.exports = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) {
        coerce("opacity");
        var bgColor = coerce("bgcolor");
        var borderColor = coerce("bordercolor");
        var borderOpacity = Color2.opacity(borderColor);
        coerce("borderpad");
        var borderWidth = coerce("borderwidth");
        var showArrow = coerce("showarrow");
        coerce("text", showArrow ? " " : fullLayout._dfltTitle.annotation);
        coerce("textangle");
        Lib.coerceFont(coerce, "font", fullLayout.font);
        coerce("width");
        coerce("align");
        var h = coerce("height");
        if (h) coerce("valign");
        if (showArrow) {
          var arrowside = coerce("arrowside");
          var arrowhead;
          var arrowsize;
          if (arrowside.indexOf("end") !== -1) {
            arrowhead = coerce("arrowhead");
            arrowsize = coerce("arrowsize");
          }
          if (arrowside.indexOf("start") !== -1) {
            coerce("startarrowhead", arrowhead);
            coerce("startarrowsize", arrowsize);
          }
          coerce("arrowcolor", borderOpacity ? annOut.bordercolor : Color2.defaultLine);
          coerce("arrowwidth", (borderOpacity && borderWidth || 1) * 2);
          coerce("standoff");
          coerce("startstandoff");
        }
        var hoverText = coerce("hovertext");
        var globalHoverLabel = fullLayout.hoverlabel || {};
        if (hoverText) {
          var hoverBG = coerce(
            "hoverlabel.bgcolor",
            globalHoverLabel.bgcolor || (Color2.opacity(bgColor) ? Color2.rgb(bgColor) : Color2.defaultLine)
          );
          var hoverBorder = coerce(
            "hoverlabel.bordercolor",
            globalHoverLabel.bordercolor || Color2.contrast(hoverBG)
          );
          var fontDflt = Lib.extendFlat({}, globalHoverLabel.font);
          if (!fontDflt.color) {
            fontDflt.color = hoverBorder;
          }
          Lib.coerceFont(coerce, "hoverlabel.font", fontDflt);
        }
        coerce("captureevents", !!hoverText);
      };
    }
  });

  // src/components/annotations/defaults.js
  var require_defaults9 = __commonJS({
    "src/components/annotations/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var handleAnnotationCommonDefaults = require_common_defaults();
      var attributes = require_attributes11();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        handleArrayContainerDefaults(layoutIn, layoutOut, {
          name: "annotations",
          handleItemDefaults: handleAnnotationDefaults
        });
      };
      function handleAnnotationDefaults(annIn, annOut, fullLayout) {
        function coerce(attr, dflt) {
          return Lib.coerce(annIn, annOut, attributes, attr, dflt);
        }
        var visible = coerce("visible");
        var clickToShow = coerce("clicktoshow");
        if (!(visible || clickToShow)) return;
        handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce);
        var showArrow = annOut.showarrow;
        var axLetters = ["x", "y"];
        var arrowPosDflt = [-10, -30];
        var gdMock = { _fullLayout: fullLayout };
        for (var i = 0; i < 2; i++) {
          var axLetter = axLetters[i];
          var axRef = Axes.coerceRef(annIn, annOut, gdMock, axLetter, "", "paper");
          if (axRef !== "paper") {
            var ax = Axes.getFromId(gdMock, axRef);
            ax._annIndices.push(annOut._index);
          }
          Axes.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5);
          if (showArrow) {
            var arrowPosAttr = "a" + axLetter;
            var aaxRef = Axes.coerceRef(
              annIn,
              annOut,
              gdMock,
              arrowPosAttr,
              "pixel",
              ["pixel", "paper"]
            );
            if (aaxRef !== "pixel" && aaxRef !== axRef) {
              aaxRef = annOut[arrowPosAttr] = "pixel";
            }
            var aDflt = aaxRef === "pixel" ? arrowPosDflt[i] : 0.4;
            Axes.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt);
          }
          coerce(axLetter + "anchor");
          coerce(axLetter + "shift");
        }
        Lib.noneOrAll(annIn, annOut, ["x", "y"]);
        if (showArrow) {
          Lib.noneOrAll(annIn, annOut, ["ax", "ay"]);
        }
        if (clickToShow) {
          var xClick = coerce("xclick");
          var yClick = coerce("yclick");
          annOut._xclick = xClick === void 0 ? annOut.x : Axes.cleanPosition(xClick, gdMock, annOut.xref);
          annOut._yclick = yClick === void 0 ? annOut.y : Axes.cleanPosition(yClick, gdMock, annOut.yref);
        }
      }
    }
  });

  // src/components/annotations/calc_autorange.js
  var require_calc_autorange = __commonJS({
    "src/components/annotations/calc_autorange.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var draw = require_draw4().draw;
      module.exports = function calcAutorange(gd) {
        var fullLayout = gd._fullLayout;
        var annotationList = Lib.filterVisible(fullLayout.annotations);
        if (annotationList.length && gd._fullData.length) {
          return Lib.syncOrAsync([draw, annAutorange], gd);
        }
      };
      function annAutorange(gd) {
        var fullLayout = gd._fullLayout;
        Lib.filterVisible(fullLayout.annotations).forEach(function(ann) {
          var xa = Axes.getFromId(gd, ann.xref);
          var ya = Axes.getFromId(gd, ann.yref);
          var xRefType = Axes.getRefType(ann.xref);
          var yRefType = Axes.getRefType(ann.yref);
          ann._extremes = {};
          if (xRefType === "range") calcAxisExpansion(ann, xa);
          if (yRefType === "range") calcAxisExpansion(ann, ya);
        });
      }
      function calcAxisExpansion(ann, ax) {
        var axId = ax._id;
        var letter = axId.charAt(0);
        var pos = ann[letter];
        var apos = ann["a" + letter];
        var ref = ann[letter + "ref"];
        var aref = ann["a" + letter + "ref"];
        var padplus = ann["_" + letter + "padplus"];
        var padminus = ann["_" + letter + "padminus"];
        var shift = { x: 1, y: -1 }[letter] * ann[letter + "shift"];
        var headSize = 3 * ann.arrowsize * ann.arrowwidth || 0;
        var headPlus = headSize + shift;
        var headMinus = headSize - shift;
        var startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0;
        var startHeadPlus = startHeadSize + shift;
        var startHeadMinus = startHeadSize - shift;
        var extremes;
        if (aref === ref) {
          var extremeArrowHead = Axes.findExtremes(ax, [ax.r2c(pos)], {
            ppadplus: headPlus,
            ppadminus: headMinus
          });
          var extremeText = Axes.findExtremes(ax, [ax.r2c(apos)], {
            ppadplus: Math.max(padplus, startHeadPlus),
            ppadminus: Math.max(padminus, startHeadMinus)
          });
          extremes = {
            min: [extremeArrowHead.min[0], extremeText.min[0]],
            max: [extremeArrowHead.max[0], extremeText.max[0]]
          };
        } else {
          startHeadPlus = apos ? startHeadPlus + apos : startHeadPlus;
          startHeadMinus = apos ? startHeadMinus - apos : startHeadMinus;
          extremes = Axes.findExtremes(ax, [ax.r2c(pos)], {
            ppadplus: Math.max(padplus, headPlus, startHeadPlus),
            ppadminus: Math.max(padminus, headMinus, startHeadMinus)
          });
        }
        ann._extremes[axId] = extremes;
      }
    }
  });

  // src/components/annotations/convert_coords.js
  var require_convert_coords = __commonJS({
    "src/components/annotations/convert_coords.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var toLogRange = require_to_log_range();
      module.exports = function convertCoords(gd, ax, newType, doExtra) {
        ax = ax || {};
        var toLog = newType === "log" && ax.type === "linear";
        var fromLog = newType === "linear" && ax.type === "log";
        if (!(toLog || fromLog)) return;
        var annotations = gd._fullLayout.annotations;
        var axLetter = ax._id.charAt(0);
        var ann;
        var attrPrefix;
        function convert(attr) {
          var currentVal = ann[attr];
          var newVal = null;
          if (toLog) newVal = toLogRange(currentVal, ax.range);
          else newVal = Math.pow(10, currentVal);
          if (!isNumeric(newVal)) newVal = null;
          doExtra(attrPrefix + attr, newVal);
        }
        for (var i = 0; i < annotations.length; i++) {
          ann = annotations[i];
          attrPrefix = "annotations[" + i + "].";
          if (ann[axLetter + "ref"] === ax._id) convert(axLetter);
          if (ann["a" + axLetter + "ref"] === ax._id) convert("a" + axLetter);
        }
      };
    }
  });

  // src/components/annotations/index.js
  var require_annotations = __commonJS({
    "src/components/annotations/index.js"(exports, module) {
      "use strict";
      var drawModule = require_draw4();
      var clickModule = require_click2();
      module.exports = {
        moduleType: "component",
        name: "annotations",
        layoutAttributes: require_attributes11(),
        supplyLayoutDefaults: require_defaults9(),
        includeBasePlot: require_include_components()("annotations"),
        calcAutorange: require_calc_autorange(),
        draw: drawModule.draw,
        drawOne: drawModule.drawOne,
        drawRaw: drawModule.drawRaw,
        hasClickToShow: clickModule.hasClickToShow,
        onClick: clickModule.onClick,
        convertCoords: require_convert_coords()
      };
    }
  });

  // src/components/annotations3d/attributes.js
  var require_attributes15 = __commonJS({
    "src/components/annotations3d/attributes.js"(exports, module) {
      "use strict";
      var annAttrs = require_attributes11();
      var overrideAll = require_edit_types().overrideAll;
      var templatedArray = require_plot_template().templatedArray;
      module.exports = overrideAll(templatedArray("annotation", {
        visible: annAttrs.visible,
        x: {
          valType: "any"
        },
        y: {
          valType: "any"
        },
        z: {
          valType: "any"
        },
        ax: {
          valType: "number"
        },
        ay: {
          valType: "number"
        },
        xanchor: annAttrs.xanchor,
        xshift: annAttrs.xshift,
        yanchor: annAttrs.yanchor,
        yshift: annAttrs.yshift,
        text: annAttrs.text,
        textangle: annAttrs.textangle,
        font: annAttrs.font,
        width: annAttrs.width,
        height: annAttrs.height,
        opacity: annAttrs.opacity,
        align: annAttrs.align,
        valign: annAttrs.valign,
        bgcolor: annAttrs.bgcolor,
        bordercolor: annAttrs.bordercolor,
        borderpad: annAttrs.borderpad,
        borderwidth: annAttrs.borderwidth,
        showarrow: annAttrs.showarrow,
        arrowcolor: annAttrs.arrowcolor,
        arrowhead: annAttrs.arrowhead,
        startarrowhead: annAttrs.startarrowhead,
        arrowside: annAttrs.arrowside,
        arrowsize: annAttrs.arrowsize,
        startarrowsize: annAttrs.startarrowsize,
        arrowwidth: annAttrs.arrowwidth,
        standoff: annAttrs.standoff,
        startstandoff: annAttrs.startstandoff,
        hovertext: annAttrs.hovertext,
        hoverlabel: annAttrs.hoverlabel,
        captureevents: annAttrs.captureevents
        // maybes later?
        // clicktoshow: annAttrs.clicktoshow,
        // xclick: annAttrs.xclick,
        // yclick: annAttrs.yclick,
        // not needed!
        // axref: 'pixel'
        // ayref: 'pixel'
        // xref: 'x'
        // yref: 'y
        // zref: 'z'
      }), "calc", "from-root");
    }
  });

  // src/components/annotations3d/defaults.js
  var require_defaults10 = __commonJS({
    "src/components/annotations3d/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var handleAnnotationCommonDefaults = require_common_defaults();
      var attributes = require_attributes15();
      module.exports = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) {
        handleArrayContainerDefaults(sceneLayoutIn, sceneLayoutOut, {
          name: "annotations",
          handleItemDefaults: handleAnnotationDefaults,
          fullLayout: opts.fullLayout
        });
      };
      function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts) {
        function coerce(attr, dflt) {
          return Lib.coerce(annIn, annOut, attributes, attr, dflt);
        }
        function coercePosition(axLetter) {
          var axName = axLetter + "axis";
          var gdMock = { _fullLayout: {} };
          gdMock._fullLayout[axName] = sceneLayout[axName];
          return Axes.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5);
        }
        var visible = coerce("visible");
        if (!visible) return;
        handleAnnotationCommonDefaults(annIn, annOut, opts.fullLayout, coerce);
        coercePosition("x");
        coercePosition("y");
        coercePosition("z");
        Lib.noneOrAll(annIn, annOut, ["x", "y", "z"]);
        annOut.xref = "x";
        annOut.yref = "y";
        annOut.zref = "z";
        coerce("xanchor");
        coerce("yanchor");
        coerce("xshift");
        coerce("yshift");
        if (annOut.showarrow) {
          annOut.axref = "pixel";
          annOut.ayref = "pixel";
          coerce("ax", -10);
          coerce("ay", -30);
          Lib.noneOrAll(annIn, annOut, ["ax", "ay"]);
        }
      }
    }
  });

  // src/components/annotations3d/convert.js
  var require_convert = __commonJS({
    "src/components/annotations3d/convert.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      module.exports = function convert(scene) {
        var fullSceneLayout = scene.fullSceneLayout;
        var anns = fullSceneLayout.annotations;
        for (var i = 0; i < anns.length; i++) {
          mockAnnAxes(anns[i], scene);
        }
        scene.fullLayout._infolayer.selectAll(".annotation-" + scene.id).remove();
      };
      function mockAnnAxes(ann, scene) {
        var fullSceneLayout = scene.fullSceneLayout;
        var domain = fullSceneLayout.domain;
        var size = scene.fullLayout._size;
        var base = {
          // this gets fill in on render
          pdata: null,
          // to get setConvert to not execute cleanly
          type: "linear",
          // don't try to update them on `editable: true`
          autorange: false,
          // set infinite range so that annotation draw routine
          // does not try to remove 'outside-range' annotations,
          // this case is handled in the render loop
          range: [-Infinity, Infinity]
        };
        ann._xa = {};
        Lib.extendFlat(ann._xa, base);
        Axes.setConvert(ann._xa);
        ann._xa._offset = size.l + domain.x[0] * size.w;
        ann._xa.l2p = function() {
          return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]);
        };
        ann._ya = {};
        Lib.extendFlat(ann._ya, base);
        Axes.setConvert(ann._ya);
        ann._ya._offset = size.t + (1 - domain.y[1]) * size.h;
        ann._ya.l2p = function() {
          return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]);
        };
      }
    }
  });

  // src/plots/gl3d/project.js
  var require_project = __commonJS({
    "src/plots/gl3d/project.js"(exports, module) {
      "use strict";
      function xformMatrix(m, v) {
        var out = [0, 0, 0, 0];
        var i, j;
        for (i = 0; i < 4; ++i) {
          for (j = 0; j < 4; ++j) {
            out[j] += m[4 * i + j] * v[i];
          }
        }
        return out;
      }
      function project(camera, v) {
        var p = xformMatrix(
          camera.projection,
          xformMatrix(
            camera.view,
            xformMatrix(camera.model, [v[0], v[1], v[2], 1])
          )
        );
        return p;
      }
      module.exports = project;
    }
  });

  // src/components/annotations3d/draw.js
  var require_draw5 = __commonJS({
    "src/components/annotations3d/draw.js"(exports, module) {
      "use strict";
      var drawRaw = require_draw4().drawRaw;
      var project = require_project();
      var axLetters = ["x", "y", "z"];
      module.exports = function draw(scene) {
        var fullSceneLayout = scene.fullSceneLayout;
        var dataScale = scene.dataScale;
        var anns = fullSceneLayout.annotations;
        for (var i = 0; i < anns.length; i++) {
          var ann = anns[i];
          var annotationIsOffscreen = false;
          for (var j = 0; j < 3; j++) {
            var axLetter = axLetters[j];
            var pos = ann[axLetter];
            var ax = fullSceneLayout[axLetter + "axis"];
            var posFraction = ax.r2fraction(pos);
            if (posFraction < 0 || posFraction > 1) {
              annotationIsOffscreen = true;
              break;
            }
          }
          if (annotationIsOffscreen) {
            scene.fullLayout._infolayer.select(".annotation-" + scene.id + '[data-index="' + i + '"]').remove();
          } else {
            ann._pdata = project(scene.glplot.cameraParams, [
              fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0],
              fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1],
              fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2]
            ]);
            drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya);
          }
        }
      };
    }
  });

  // src/components/annotations3d/index.js
  var require_annotations3d = __commonJS({
    "src/components/annotations3d/index.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      module.exports = {
        moduleType: "component",
        name: "annotations3d",
        schema: {
          subplots: {
            scene: { annotations: require_attributes15() }
          }
        },
        layoutAttributes: require_attributes15(),
        handleDefaults: require_defaults10(),
        includeBasePlot: includeGL3D,
        convert: require_convert(),
        draw: require_draw5()
      };
      function includeGL3D(layoutIn, layoutOut) {
        var GL3D = Registry.subplotsRegistry.gl3d;
        if (!GL3D) return;
        var attrRegex = GL3D.attrRegex;
        var keys = Object.keys(layoutIn);
        for (var i = 0; i < keys.length; i++) {
          var k = keys[i];
          if (attrRegex.test(k) && (layoutIn[k].annotations || []).length) {
            Lib.pushUnique(layoutOut._basePlotModules, GL3D);
            Lib.pushUnique(layoutOut._subplots.gl3d, k);
          }
        }
      }
    }
  });

  // src/components/shapes/attributes.js
  var require_attributes16 = __commonJS({
    "src/components/shapes/attributes.js"(exports, module) {
      "use strict";
      var cartesianConstants = require_constants2();
      var fontAttrs = require_font_attributes();
      var scatterLineAttrs = require_attributes12().line;
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      var templatedArray = require_plot_template().templatedArray;
      var axisPlaceableObjs = require_axis_placeable_objects();
      var basePlotAttributes = require_attributes2();
      var annAttrs = require_attributes11();
      var { shapeTexttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var shapeLabelTexttemplateVars = require_label_texttemplate();
      module.exports = templatedArray("shape", {
        visible: extendFlat({}, basePlotAttributes.visible, {
          editType: "calc+arraydraw"
        }),
        showlegend: {
          valType: "boolean",
          dflt: false,
          editType: "calc+arraydraw"
        },
        legend: extendFlat({}, basePlotAttributes.legend, {
          editType: "calc+arraydraw"
        }),
        legendgroup: extendFlat({}, basePlotAttributes.legendgroup, {
          editType: "calc+arraydraw"
        }),
        legendgrouptitle: {
          text: extendFlat({}, basePlotAttributes.legendgrouptitle.text, {
            editType: "calc+arraydraw"
          }),
          font: fontAttrs({
            editType: "calc+arraydraw"
          }),
          editType: "calc+arraydraw"
        },
        legendrank: extendFlat({}, basePlotAttributes.legendrank, {
          editType: "calc+arraydraw"
        }),
        legendwidth: extendFlat({}, basePlotAttributes.legendwidth, {
          editType: "calc+arraydraw"
        }),
        type: {
          valType: "enumerated",
          values: ["circle", "rect", "path", "line"],
          editType: "calc+arraydraw"
        },
        layer: {
          valType: "enumerated",
          values: ["below", "above", "between"],
          dflt: "above",
          editType: "arraydraw"
        },
        xref: extendFlat({}, annAttrs.xref, {
          arrayOk: true
        }),
        xsizemode: {
          valType: "enumerated",
          values: ["scaled", "pixel"],
          dflt: "scaled",
          editType: "calc+arraydraw"
        },
        xanchor: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        x0: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        x1: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        x0shift: {
          valType: "number",
          dflt: 0,
          min: -1,
          max: 1,
          editType: "calc"
        },
        x1shift: {
          valType: "number",
          dflt: 0,
          min: -1,
          max: 1,
          editType: "calc"
        },
        yref: extendFlat({}, annAttrs.yref, {
          arrayOk: true
        }),
        ysizemode: {
          valType: "enumerated",
          values: ["scaled", "pixel"],
          dflt: "scaled",
          editType: "calc+arraydraw"
        },
        yanchor: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        y0: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        y1: {
          valType: "any",
          editType: "calc+arraydraw"
        },
        y0shift: {
          valType: "number",
          dflt: 0,
          min: -1,
          max: 1,
          editType: "calc"
        },
        y1shift: {
          valType: "number",
          dflt: 0,
          min: -1,
          max: 1,
          editType: "calc"
        },
        path: {
          valType: "string",
          editType: "calc+arraydraw"
        },
        opacity: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 1,
          editType: "arraydraw"
        },
        line: {
          color: extendFlat({}, scatterLineAttrs.color, { editType: "arraydraw" }),
          width: extendFlat({}, scatterLineAttrs.width, { editType: "calc+arraydraw" }),
          dash: extendFlat({}, dash, { editType: "arraydraw" }),
          editType: "calc+arraydraw"
        },
        fillcolor: {
          valType: "color",
          dflt: "rgba(0,0,0,0)",
          editType: "arraydraw"
        },
        fillrule: {
          valType: "enumerated",
          values: ["evenodd", "nonzero"],
          dflt: "evenodd",
          editType: "arraydraw"
        },
        editable: {
          valType: "boolean",
          dflt: false,
          editType: "calc+arraydraw"
        },
        label: {
          text: {
            valType: "string",
            dflt: "",
            editType: "arraydraw"
          },
          texttemplate: shapeTexttemplateAttrs({}, { keys: Object.keys(shapeLabelTexttemplateVars) }),
          texttemplatefallback: templatefallbackAttrs({ editType: "arraydraw" }),
          font: fontAttrs({
            editType: "calc+arraydraw",
            colorEditType: "arraydraw"
          }),
          textposition: {
            valType: "enumerated",
            values: [
              "top left",
              "top center",
              "top right",
              "middle left",
              "middle center",
              "middle right",
              "bottom left",
              "bottom center",
              "bottom right",
              "start",
              "middle",
              "end"
            ],
            editType: "arraydraw"
          },
          textangle: {
            valType: "angle",
            dflt: "auto",
            editType: "calc+arraydraw"
          },
          xanchor: {
            valType: "enumerated",
            values: ["auto", "left", "center", "right"],
            dflt: "auto",
            editType: "calc+arraydraw"
          },
          yanchor: {
            valType: "enumerated",
            values: ["top", "middle", "bottom"],
            editType: "calc+arraydraw"
          },
          padding: {
            valType: "number",
            dflt: 3,
            min: 0,
            editType: "arraydraw"
          },
          editType: "arraydraw"
        },
        editType: "arraydraw"
      });
    }
  });

  // src/components/shapes/defaults.js
  var require_defaults11 = __commonJS({
    "src/components/shapes/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes16();
      var helpers = require_helpers8();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        handleArrayContainerDefaults(layoutIn, layoutOut, {
          name: "shapes",
          handleItemDefaults: handleShapeDefaults
        });
      };
      function dfltLabelYanchor(isLine, labelTextPosition) {
        return isLine ? "bottom" : labelTextPosition.indexOf("top") !== -1 ? "top" : labelTextPosition.indexOf("bottom") !== -1 ? "bottom" : "middle";
      }
      function handleShapeDefaults(shapeIn, shapeOut, fullLayout) {
        function coerce(attr, dflt) {
          return Lib.coerce(shapeIn, shapeOut, attributes, attr, dflt);
        }
        shapeOut._isShape = true;
        var visible = coerce("visible");
        if (!visible) return;
        var showlegend = coerce("showlegend");
        if (showlegend) {
          coerce("legend");
          coerce("legendwidth");
          coerce("legendgroup");
          coerce("legendgrouptitle.text");
          Lib.coerceFont(coerce, "legendgrouptitle.font");
          coerce("legendrank");
        }
        var path = coerce("path");
        var dfltType = path ? "path" : "rect";
        var shapeType = coerce("type", dfltType);
        var noPath = shapeType !== "path";
        if (noPath) delete shapeOut.path;
        coerce("editable");
        coerce("layer");
        coerce("opacity");
        coerce("fillcolor");
        coerce("fillrule");
        var lineWidth = coerce("line.width");
        if (lineWidth) {
          coerce("line.color");
          coerce("line.dash");
        }
        var xSizeMode = coerce("xsizemode");
        var ySizeMode = coerce("ysizemode");
        const dflts = [0.25, 0.75];
        const pixelDflts = [0, 10];
        ["x", "y"].forEach((axLetter) => {
          var attrAnchor = axLetter + "anchor";
          var sizeMode = axLetter === "x" ? xSizeMode : ySizeMode;
          var gdMock = { _fullLayout: fullLayout };
          var ax;
          var pos2r;
          var r2pos;
          var axRef;
          const refAttr = axLetter + "ref";
          const inputRef = shapeIn[refAttr];
          if (Array.isArray(inputRef) && inputRef.length > 0) {
            const expectedLen = helpers.countDefiningCoords(shapeType, path, axLetter);
            axRef = Axes.coerceRefArray(shapeIn, shapeOut, gdMock, axLetter, void 0, "paper", expectedLen);
            shapeOut["_" + axLetter + "refArray"] = true;
          } else {
            axRef = Axes.coerceRef(shapeIn, shapeOut, gdMock, axLetter, void 0, "paper");
          }
          if (Array.isArray(axRef)) {
            axRef.forEach(function(ref) {
              if (Axes.getRefType(ref) === "range") {
                ax = Axes.getFromId(gdMock, ref);
                if (ax && ax._shapeIndices.indexOf(shapeOut._index) === -1) {
                  ax._shapeIndices.push(shapeOut._index);
                }
              }
            });
            if (noPath) {
              [0, 1].forEach(function(i) {
                const ref = axRef[i];
                const refType = Axes.getRefType(ref);
                if (refType === "range") {
                  ax = Axes.getFromId(gdMock, ref);
                  pos2r = helpers.shapePositionToRange(ax);
                  r2pos = helpers.rangeToShapePosition(ax);
                  if (ax.type === "category" || ax.type === "multicategory") {
                    coerce(axLetter + i + "shift");
                  }
                } else {
                  pos2r = r2pos = Lib.identity;
                }
                const attr = axLetter + i;
                const inValue = shapeIn[attr];
                shapeIn[attr] = pos2r(shapeIn[attr], true);
                if (sizeMode === "pixel") {
                  coerce(attr, pixelDflts[i]);
                } else {
                  Axes.coercePosition(shapeOut, gdMock, coerce, ref, attr, dflts[i]);
                }
                shapeOut[attr] = r2pos(shapeOut[attr]);
                shapeIn[attr] = inValue;
                if (i === 0 && sizeMode === "pixel") {
                  const inAnchor = shapeIn[attrAnchor];
                  shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true);
                  Axes.coercePosition(shapeOut, gdMock, coerce, ref, attrAnchor, 0.25);
                  shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]);
                  shapeIn[attrAnchor] = inAnchor;
                }
              });
            }
          } else {
            const axRefType = Axes.getRefType(axRef);
            if (axRefType === "range") {
              ax = Axes.getFromId(gdMock, axRef);
              ax._shapeIndices.push(shapeOut._index);
              r2pos = helpers.rangeToShapePosition(ax);
              pos2r = helpers.shapePositionToRange(ax);
              if (noPath && (ax.type === "category" || ax.type === "multicategory")) {
                coerce(axLetter + "0shift");
                coerce(axLetter + "1shift");
              }
            } else {
              pos2r = r2pos = Lib.identity;
            }
            if (noPath) {
              const attr0 = axLetter + "0";
              const attr1 = axLetter + "1";
              const in0 = shapeIn[attr0];
              const in1 = shapeIn[attr1];
              shapeIn[attr0] = pos2r(shapeIn[attr0], true);
              shapeIn[attr1] = pos2r(shapeIn[attr1], true);
              if (sizeMode === "pixel") {
                coerce(attr0, pixelDflts[0]);
                coerce(attr1, pixelDflts[1]);
              } else {
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflts[0]);
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflts[1]);
              }
              shapeOut[attr0] = r2pos(shapeOut[attr0]);
              shapeOut[attr1] = r2pos(shapeOut[attr1]);
              shapeIn[attr0] = in0;
              shapeIn[attr1] = in1;
            }
            if (sizeMode === "pixel") {
              const inAnchor = shapeIn[attrAnchor];
              shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true);
              Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25);
              shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]);
              shapeIn[attrAnchor] = inAnchor;
            }
          }
        });
        if (noPath) {
          Lib.noneOrAll(shapeIn, shapeOut, ["x0", "x1", "y0", "y1"]);
        }
        var isLine = shapeType === "line";
        var labelTextTemplate, labelText;
        if (noPath) {
          labelTextTemplate = coerce("label.texttemplate");
          coerce("label.texttemplatefallback");
        }
        if (!labelTextTemplate) {
          labelText = coerce("label.text");
        }
        if (labelText || labelTextTemplate) {
          coerce("label.textangle");
          var labelTextPosition = coerce("label.textposition", isLine ? "middle" : "middle center");
          coerce("label.xanchor");
          coerce("label.yanchor", dfltLabelYanchor(isLine, labelTextPosition));
          coerce("label.padding");
          Lib.coerceFont(coerce, "label.font", fullLayout.font);
        }
      }
    }
  });

  // src/components/shapes/draw_newshape/defaults.js
  var require_defaults12 = __commonJS({
    "src/components/shapes/draw_newshape/defaults.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var Lib = require_lib();
      function dfltLabelYanchor(isLine, labelTextPosition) {
        return isLine ? "bottom" : labelTextPosition.indexOf("top") !== -1 ? "top" : labelTextPosition.indexOf("bottom") !== -1 ? "bottom" : "middle";
      }
      module.exports = function supplyDrawNewShapeDefaults(layoutIn, layoutOut, coerce) {
        coerce("newshape.visible");
        coerce("newshape.name");
        coerce("newshape.showlegend");
        coerce("newshape.legend");
        coerce("newshape.legendwidth");
        coerce("newshape.legendgroup");
        coerce("newshape.legendgrouptitle.text");
        Lib.coerceFont(coerce, "newshape.legendgrouptitle.font");
        coerce("newshape.legendrank");
        coerce("newshape.drawdirection");
        coerce("newshape.layer");
        coerce("newshape.fillcolor");
        coerce("newshape.fillrule");
        coerce("newshape.opacity");
        var newshapeLineWidth = coerce("newshape.line.width");
        if (newshapeLineWidth) {
          var bgcolor = (layoutIn || {}).plot_bgcolor || "#FFF";
          coerce("newshape.line.color", Color2.contrast(bgcolor));
          coerce("newshape.line.dash");
        }
        var isLine = layoutIn.dragmode === "drawline";
        var labelText = coerce("newshape.label.text");
        var labelTextTemplate = coerce("newshape.label.texttemplate");
        coerce("newshape.label.texttemplatefallback");
        if (labelText || labelTextTemplate) {
          coerce("newshape.label.textangle");
          var labelTextPosition = coerce("newshape.label.textposition", isLine ? "middle" : "middle center");
          coerce("newshape.label.xanchor");
          coerce("newshape.label.yanchor", dfltLabelYanchor(isLine, labelTextPosition));
          coerce("newshape.label.padding");
          Lib.coerceFont(coerce, "newshape.label.font", layoutOut.font);
        }
        coerce("activeshape.fillcolor");
        coerce("activeshape.opacity");
      };
    }
  });

  // src/components/shapes/calc_autorange.js
  var require_calc_autorange2 = __commonJS({
    "src/components/shapes/calc_autorange.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var constants = require_constants5();
      var helpers = require_helpers8();
      module.exports = function calcAutorange(gd) {
        var fullLayout = gd._fullLayout;
        var shapeList = Lib.filterVisible(fullLayout.shapes);
        if (!shapeList.length || !gd._fullData.length) return;
        for (var i = 0; i < shapeList.length; i++) {
          var shape = shapeList[i];
          shape._extremes = {};
          var ax;
          var bounds;
          var xRefType = Axes.getRefType(shape.xref);
          var yRefType = Axes.getRefType(shape.yref);
          if (xRefType === "array") {
            const extremesForRefArray = calcArrayRefAutorange(gd, shape, "x");
            Object.entries(extremesForRefArray).forEach(([axID, axExtremes]) => {
              ax = Axes.getFromId(gd, axID);
              shape._extremes[ax._id] = Axes.findExtremes(ax, axExtremes, calcXPaddingOptions(shape));
            });
          } else if (shape.xref !== "paper" && xRefType !== "domain") {
            ax = Axes.getFromId(gd, shape.xref);
            bounds = shapeBounds(ax, shape, constants.paramIsX);
            if (bounds) {
              shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcXPaddingOptions(shape));
            }
          }
          if (yRefType === "array") {
            const extremesForRefArray = calcArrayRefAutorange(gd, shape, "y");
            Object.entries(extremesForRefArray).forEach(([axID, axExtremes]) => {
              ax = Axes.getFromId(gd, axID);
              shape._extremes[ax._id] = Axes.findExtremes(ax, axExtremes, calcYPaddingOptions(shape));
            });
          } else if (shape.yref !== "paper" && yRefType !== "domain") {
            ax = Axes.getFromId(gd, shape.yref);
            bounds = shapeBounds(ax, shape, constants.paramIsY);
            if (bounds) {
              shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcYPaddingOptions(shape));
            }
          }
        }
      };
      function calcArrayRefAutorange(gd, shape, axLetter) {
        const refs = shape[axLetter + "ref"];
        const paramsToUse = axLetter === "x" ? constants.paramIsX : constants.paramIsY;
        function addToAxisGroup(ref, val) {
          if (ref === "paper" || Axes.getRefType(ref) === "domain") return;
          if (!axisGroups[ref]) axisGroups[ref] = [];
          axisGroups[ref].push(val);
        }
        const axisGroups = {};
        if (shape.type === "path" && shape.path) {
          const segments = shape.path.match(constants.segmentRE) || [];
          var refIndex = 0;
          for (var i = 0; i < segments.length; i++) {
            const segment = segments[i];
            const command = segment.charAt(0);
            const drawnIndex = paramsToUse[command].drawn;
            if (drawnIndex === void 0) continue;
            const params = segment.slice(1).match(constants.paramRE);
            if (params && params.length > drawnIndex) {
              addToAxisGroup(refs[refIndex], params[drawnIndex]);
              refIndex++;
            }
          }
        } else {
          addToAxisGroup(refs[0], shape[axLetter + "0"]);
          addToAxisGroup(refs[1], shape[axLetter + "1"]);
        }
        const convertedGroups = {};
        for (const axId in axisGroups) {
          const ax = Axes.getFromId(gd, axId);
          if (!ax) continue;
          var convertVal = ax.type === "category" || ax.type === "multicategory" ? ax.r2c : ax.d2c;
          if (ax.type === "date") convertVal = helpers.decodeDate(convertVal);
          convertedGroups[ax._id] = axisGroups[axId].map(convertVal);
        }
        return convertedGroups;
      }
      function calcXPaddingOptions(shape) {
        return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false);
      }
      function calcYPaddingOptions(shape) {
        return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true);
      }
      function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) {
        var ppad = lineWidth / 2;
        var axisDirectionReverted = isYAxis;
        if (sizeMode === "pixel") {
          var coords = path ? helpers.extractPathCoords(path, isYAxis ? constants.paramIsY : constants.paramIsX) : [v0, v1];
          var maxValue = Lib.aggNums(Math.max, null, coords);
          var minValue = Lib.aggNums(Math.min, null, coords);
          var beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad;
          var afterPad = maxValue > 0 ? maxValue + ppad : ppad;
          return {
            ppad,
            ppadplus: axisDirectionReverted ? beforePad : afterPad,
            ppadminus: axisDirectionReverted ? afterPad : beforePad
          };
        } else {
          return { ppad };
        }
      }
      function shapeBounds(ax, shape, paramsToUse) {
        var dim = ax._id.charAt(0) === "x" ? "x" : "y";
        var isCategory = ax.type === "category" || ax.type === "multicategory";
        var v0;
        var v1;
        var shiftStart = 0;
        var shiftEnd = 0;
        var convertVal = isCategory ? ax.r2c : ax.d2c;
        var isSizeModeScale = shape[dim + "sizemode"] === "scaled";
        if (isSizeModeScale) {
          v0 = shape[dim + "0"];
          v1 = shape[dim + "1"];
          if (isCategory) {
            shiftStart = shape[dim + "0shift"];
            shiftEnd = shape[dim + "1shift"];
          }
        } else {
          v0 = shape[dim + "anchor"];
          v1 = shape[dim + "anchor"];
        }
        if (v0 !== void 0) return [convertVal(v0) + shiftStart, convertVal(v1) + shiftEnd];
        if (!shape.path) return;
        var min = Infinity;
        var max = -Infinity;
        var segments = shape.path.match(constants.segmentRE);
        var i;
        var segment;
        var drawnParam;
        var params;
        var val;
        if (ax.type === "date") convertVal = helpers.decodeDate(convertVal);
        for (i = 0; i < segments.length; i++) {
          segment = segments[i];
          drawnParam = paramsToUse[segment.charAt(0)].drawn;
          if (drawnParam === void 0) continue;
          params = segments[i].slice(1).match(constants.paramRE);
          if (!params || params.length < drawnParam) continue;
          val = convertVal(params[drawnParam]);
          if (val < min) min = val;
          if (val > max) max = val;
        }
        if (max >= min) return [min, max];
      }
    }
  });

  // src/components/shapes/index.js
  var require_shapes = __commonJS({
    "src/components/shapes/index.js"(exports, module) {
      "use strict";
      var drawModule = require_draw2();
      module.exports = {
        moduleType: "component",
        name: "shapes",
        layoutAttributes: require_attributes16(),
        supplyLayoutDefaults: require_defaults11(),
        supplyDrawNewShapeDefaults: require_defaults12(),
        includeBasePlot: require_include_components()("shapes"),
        calcAutorange: require_calc_autorange2(),
        draw: drawModule.draw,
        drawOne: drawModule.drawOne
      };
    }
  });

  // src/components/images/attributes.js
  var require_attributes17 = __commonJS({
    "src/components/images/attributes.js"(exports, module) {
      "use strict";
      var cartesianConstants = require_constants2();
      var templatedArray = require_plot_template().templatedArray;
      var axisPlaceableObjs = require_axis_placeable_objects();
      module.exports = templatedArray("image", {
        visible: {
          valType: "boolean",
          dflt: true,
          editType: "arraydraw"
        },
        source: {
          valType: "string",
          editType: "arraydraw"
        },
        layer: {
          valType: "enumerated",
          values: ["below", "above"],
          dflt: "above",
          editType: "arraydraw"
        },
        sizex: {
          valType: "number",
          dflt: 0,
          editType: "arraydraw"
        },
        sizey: {
          valType: "number",
          dflt: 0,
          editType: "arraydraw"
        },
        sizing: {
          valType: "enumerated",
          values: ["fill", "contain", "stretch"],
          dflt: "contain",
          editType: "arraydraw"
        },
        opacity: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 1,
          editType: "arraydraw"
        },
        x: {
          valType: "any",
          dflt: 0,
          editType: "arraydraw"
        },
        y: {
          valType: "any",
          dflt: 0,
          editType: "arraydraw"
        },
        xanchor: {
          valType: "enumerated",
          values: ["left", "center", "right"],
          dflt: "left",
          editType: "arraydraw"
        },
        yanchor: {
          valType: "enumerated",
          values: ["top", "middle", "bottom"],
          dflt: "top",
          editType: "arraydraw"
        },
        xref: {
          valType: "enumerated",
          values: [
            "paper",
            cartesianConstants.idRegex.x.toString()
          ],
          dflt: "paper",
          editType: "arraydraw"
        },
        yref: {
          valType: "enumerated",
          values: [
            "paper",
            cartesianConstants.idRegex.y.toString()
          ],
          dflt: "paper",
          editType: "arraydraw"
        },
        editType: "arraydraw"
      });
    }
  });

  // src/components/images/defaults.js
  var require_defaults13 = __commonJS({
    "src/components/images/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes17();
      var name2 = "images";
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        var opts = {
          name: name2,
          handleItemDefaults: imageDefaults
        };
        handleArrayContainerDefaults(layoutIn, layoutOut, opts);
      };
      function imageDefaults(imageIn, imageOut, fullLayout) {
        function coerce(attr, dflt) {
          return Lib.coerce(imageIn, imageOut, attributes, attr, dflt);
        }
        var source = coerce("source");
        var visible = coerce("visible", !!source);
        if (!visible) return imageOut;
        coerce("layer");
        coerce("xanchor");
        coerce("yanchor");
        coerce("sizex");
        coerce("sizey");
        coerce("sizing");
        coerce("opacity");
        var gdMock = { _fullLayout: fullLayout };
        var axLetters = ["x", "y"];
        for (var i = 0; i < 2; i++) {
          var axLetter = axLetters[i];
          var axRef = Axes.coerceRef(imageIn, imageOut, gdMock, axLetter, "paper", void 0);
          if (axRef !== "paper") {
            var ax = Axes.getFromId(gdMock, axRef);
            ax._imgIndices.push(imageOut._index);
          }
          Axes.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0);
        }
        return imageOut;
      }
    }
  });

  // src/components/images/draw.js
  var require_draw6 = __commonJS({
    "src/components/images/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var Axes = require_axes();
      var axisIds = require_axis_ids();
      var xmlnsNamespaces = require_xmlns_namespaces();
      module.exports = function draw(gd) {
        var fullLayout = gd._fullLayout;
        var imageDataAbove = [];
        var imageDataSubplot = {};
        var imageDataBelow = [];
        var subplot;
        var i;
        for (i = 0; i < fullLayout.images.length; i++) {
          var img = fullLayout.images[i];
          if (img.visible) {
            if (img.layer === "below" && img.xref !== "paper" && img.yref !== "paper") {
              subplot = axisIds.ref2id(img.xref) + axisIds.ref2id(img.yref);
              var plotinfo = fullLayout._plots[subplot];
              if (!plotinfo) {
                imageDataBelow.push(img);
                continue;
              }
              if (plotinfo.mainplot) {
                subplot = plotinfo.mainplot.id;
              }
              if (!imageDataSubplot[subplot]) {
                imageDataSubplot[subplot] = [];
              }
              imageDataSubplot[subplot].push(img);
            } else if (img.layer === "above") {
              imageDataAbove.push(img);
            } else {
              imageDataBelow.push(img);
            }
          }
        }
        var anchors = {
          x: {
            left: { sizing: "xMin", offset: 0 },
            center: { sizing: "xMid", offset: -1 / 2 },
            right: { sizing: "xMax", offset: -1 }
          },
          y: {
            top: { sizing: "YMin", offset: 0 },
            middle: { sizing: "YMid", offset: -1 / 2 },
            bottom: { sizing: "YMax", offset: -1 }
          }
        };
        function setImage(d) {
          var thisImage = d3.select(this);
          if (this._imgSrc === d.source) {
            return;
          }
          thisImage.attr("xmlns", xmlnsNamespaces.svg);
          if (!gd._context.staticPlot || d.source && d.source.slice(0, 5) === "data:") {
            thisImage.attr("xlink:href", d.source);
            this._imgSrc = d.source;
          } else {
            var imagePromise = new Promise(function(resolve) {
              var img2 = new Image();
              this.img = img2;
              img2.setAttribute("crossOrigin", "anonymous");
              img2.onerror = errorHandler;
              img2.onload = function() {
                var canvas = document.createElement("canvas");
                canvas.width = this.width;
                canvas.height = this.height;
                var ctx = canvas.getContext("2d", { willReadFrequently: true });
                ctx.drawImage(this, 0, 0);
                var dataURL = canvas.toDataURL("image/png");
                thisImage.attr("xlink:href", dataURL);
                resolve();
              };
              thisImage.on("error", errorHandler);
              img2.src = d.source;
              this._imgSrc = d.source;
              function errorHandler() {
                thisImage.remove();
                resolve();
              }
            }.bind(this));
            gd._promises.push(imagePromise);
          }
        }
        function applyAttributes(d) {
          var thisImage = d3.select(this);
          var xa = Axes.getFromId(gd, d.xref);
          var ya = Axes.getFromId(gd, d.yref);
          var xIsDomain = Axes.getRefType(d.xref) === "domain";
          var yIsDomain = Axes.getRefType(d.yref) === "domain";
          var size = fullLayout._size;
          var width, height;
          if (xa !== void 0) {
            width = typeof d.xref === "string" && xIsDomain ? xa._length * d.sizex : Math.abs(xa.l2p(d.sizex) - xa.l2p(0));
          } else {
            width = d.sizex * size.w;
          }
          if (ya !== void 0) {
            height = typeof d.yref === "string" && yIsDomain ? ya._length * d.sizey : Math.abs(ya.l2p(d.sizey) - ya.l2p(0));
          } else {
            height = d.sizey * size.h;
          }
          var xOffset = width * anchors.x[d.xanchor].offset;
          var yOffset = height * anchors.y[d.yanchor].offset;
          var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing;
          var xPos, yPos;
          if (xa !== void 0) {
            xPos = typeof d.xref === "string" && xIsDomain ? xa._length * d.x + xa._offset : xa.r2p(d.x) + xa._offset;
          } else {
            xPos = d.x * size.w + size.l;
          }
          xPos += xOffset;
          if (ya !== void 0) {
            yPos = typeof d.yref === "string" && yIsDomain ? (
              // consistent with "paper" yref value, where positive values
              // move up the page
              ya._length * (1 - d.y) + ya._offset
            ) : ya.r2p(d.y) + ya._offset;
          } else {
            yPos = size.h - d.y * size.h + size.t;
          }
          yPos += yOffset;
          switch (d.sizing) {
            case "fill":
              sizing += " slice";
              break;
            case "stretch":
              sizing = "none";
              break;
          }
          thisImage.attr({
            x: xPos,
            y: yPos,
            width,
            height,
            preserveAspectRatio: sizing,
            opacity: d.opacity
          });
          var xId = xa && Axes.getRefType(d.xref) !== "domain" ? xa._id : "";
          var yId = ya && Axes.getRefType(d.yref) !== "domain" ? ya._id : "";
          var clipAxes = xId + yId;
          Drawing.setClipUrl(
            thisImage,
            clipAxes ? "clip" + fullLayout._uid + clipAxes : null,
            gd
          );
        }
        function imgDataFunc(d) {
          return [d.xref, d.x, d.sizex, d.yref, d.y, d.sizey].join("_");
        }
        function imgSort(a, b) {
          return a._index - b._index;
        }
        var imagesBelow = fullLayout._imageLowerLayer.selectAll("image").data(imageDataBelow, imgDataFunc);
        var imagesAbove = fullLayout._imageUpperLayer.selectAll("image").data(imageDataAbove, imgDataFunc);
        imagesBelow.enter().append("image");
        imagesAbove.enter().append("image");
        imagesBelow.exit().remove();
        imagesAbove.exit().remove();
        imagesBelow.each(function(d) {
          setImage.bind(this)(d);
          applyAttributes.bind(this)(d);
        });
        imagesAbove.each(function(d) {
          setImage.bind(this)(d);
          applyAttributes.bind(this)(d);
        });
        imagesBelow.sort(imgSort);
        imagesAbove.sort(imgSort);
        var allSubplots = Object.keys(fullLayout._plots);
        for (i = 0; i < allSubplots.length; i++) {
          subplot = allSubplots[i];
          var subplotObj = fullLayout._plots[subplot];
          if (!subplotObj.imagelayer) continue;
          var imagesOnSubplot = subplotObj.imagelayer.selectAll("image").data(imageDataSubplot[subplot] || [], imgDataFunc);
          imagesOnSubplot.enter().append("image");
          imagesOnSubplot.exit().remove();
          imagesOnSubplot.each(function(d) {
            setImage.bind(this)(d);
            applyAttributes.bind(this)(d);
          });
          imagesOnSubplot.sort(imgSort);
        }
      };
    }
  });

  // src/components/images/convert_coords.js
  var require_convert_coords2 = __commonJS({
    "src/components/images/convert_coords.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var toLogRange = require_to_log_range();
      module.exports = function convertCoords(gd, ax, newType, doExtra) {
        ax = ax || {};
        var toLog = newType === "log" && ax.type === "linear";
        var fromLog = newType === "linear" && ax.type === "log";
        if (!(toLog || fromLog)) return;
        var images = gd._fullLayout.images;
        var axLetter = ax._id.charAt(0);
        var image;
        var attrPrefix;
        for (var i = 0; i < images.length; i++) {
          image = images[i];
          attrPrefix = "images[" + i + "].";
          if (image[axLetter + "ref"] === ax._id) {
            var currentPos = image[axLetter];
            var currentSize = image["size" + axLetter];
            var newPos = null;
            var newSize = null;
            if (toLog) {
              newPos = toLogRange(currentPos, ax.range);
              var dx = currentSize / Math.pow(10, newPos) / 2;
              newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10;
            } else {
              newPos = Math.pow(10, currentPos);
              newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2));
            }
            if (!isNumeric(newPos)) {
              newPos = null;
              newSize = null;
            } else if (!isNumeric(newSize)) newSize = null;
            doExtra(attrPrefix + axLetter, newPos);
            doExtra(attrPrefix + "size" + axLetter, newSize);
          }
        }
      };
    }
  });

  // src/components/images/index.js
  var require_images = __commonJS({
    "src/components/images/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "component",
        name: "images",
        layoutAttributes: require_attributes17(),
        supplyLayoutDefaults: require_defaults13(),
        includeBasePlot: require_include_components()("images"),
        draw: require_draw6(),
        convertCoords: require_convert_coords2()
      };
    }
  });

  // src/components/updatemenus/constants.js
  var require_constants10 = __commonJS({
    "src/components/updatemenus/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // layout attribute name
        name: "updatemenus",
        // class names
        containerClassName: "updatemenu-container",
        headerGroupClassName: "updatemenu-header-group",
        headerClassName: "updatemenu-header",
        headerArrowClassName: "updatemenu-header-arrow",
        dropdownButtonGroupClassName: "updatemenu-dropdown-button-group",
        dropdownButtonClassName: "updatemenu-dropdown-button",
        buttonClassName: "updatemenu-button",
        itemRectClassName: "updatemenu-item-rect",
        itemTextClassName: "updatemenu-item-text",
        // DOM attribute name in button group keeping track
        // of active update menu
        menuIndexAttrName: "updatemenu-active-index",
        // id root pass to Plots.autoMargin
        autoMarginIdRoot: "updatemenu-",
        // options when 'active: -1'
        blankHeaderOpts: { label: "  " },
        // min item width / height
        minWidth: 30,
        minHeight: 30,
        // padding around item text
        textPadX: 24,
        arrowPadX: 16,
        // item rect radii
        rx: 2,
        ry: 2,
        // item  text x offset off left edge
        textOffsetX: 12,
        // item  text y offset (w.r.t. middle)
        textOffsetY: 3,
        // arrow offset off right edge
        arrowOffsetX: 4,
        // gap between header and buttons
        gapButtonHeader: 5,
        // gap between between buttons
        gapButton: 2,
        // color given to active buttons
        activeColor: "#F4FAFF",
        // color given to hovered buttons
        hoverColor: "#F4FAFF",
        // symbol for menu open arrow
        arrowSymbol: {
          left: "\u25C4",
          right: "\u25BA",
          up: "\u25B2",
          down: "\u25BC"
        }
      };
    }
  });

  // src/components/updatemenus/attributes.js
  var require_attributes18 = __commonJS({
    "src/components/updatemenus/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var colorAttrs = require_attributes3();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var padAttrs = require_pad_attributes();
      var templatedArray = require_plot_template().templatedArray;
      var buttonsAttrs = templatedArray("button", {
        visible: {
          valType: "boolean"
        },
        method: {
          valType: "enumerated",
          values: ["restyle", "relayout", "animate", "update", "skip"],
          dflt: "restyle"
        },
        args: {
          valType: "info_array",
          freeLength: true,
          items: [
            { valType: "any" },
            { valType: "any" },
            { valType: "any" }
          ]
        },
        args2: {
          valType: "info_array",
          freeLength: true,
          items: [
            { valType: "any" },
            { valType: "any" },
            { valType: "any" }
          ]
        },
        label: {
          valType: "string",
          dflt: ""
        },
        execute: {
          valType: "boolean",
          dflt: true
        }
      });
      module.exports = overrideAll(templatedArray("updatemenu", {
        _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],
        visible: {
          valType: "boolean"
        },
        type: {
          valType: "enumerated",
          values: ["dropdown", "buttons"],
          dflt: "dropdown"
        },
        direction: {
          valType: "enumerated",
          values: ["left", "right", "up", "down"],
          dflt: "down"
        },
        active: {
          valType: "integer",
          min: -1,
          dflt: 0
        },
        showactive: {
          valType: "boolean",
          dflt: true
        },
        buttons: buttonsAttrs,
        x: {
          valType: "number",
          min: -2,
          max: 3,
          dflt: -0.05
        },
        xanchor: {
          valType: "enumerated",
          values: ["auto", "left", "center", "right"],
          dflt: "right"
        },
        y: {
          valType: "number",
          min: -2,
          max: 3,
          dflt: 1
        },
        yanchor: {
          valType: "enumerated",
          values: ["auto", "top", "middle", "bottom"],
          dflt: "top"
        },
        pad: extendFlat(padAttrs({ editType: "arraydraw" }), {}),
        font: fontAttrs({}),
        bgcolor: {
          valType: "color"
        },
        bordercolor: {
          valType: "color",
          dflt: colorAttrs.borderLine
        },
        borderwidth: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "arraydraw"
        }
      }), "arraydraw", "from-root");
    }
  });

  // src/components/updatemenus/defaults.js
  var require_defaults14 = __commonJS({
    "src/components/updatemenus/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes18();
      var constants = require_constants10();
      var name2 = constants.name;
      var buttonAttrs = attributes.buttons;
      module.exports = function updateMenusDefaults(layoutIn, layoutOut) {
        var opts = {
          name: name2,
          handleItemDefaults: menuDefaults
        };
        handleArrayContainerDefaults(layoutIn, layoutOut, opts);
      };
      function menuDefaults(menuIn, menuOut, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(menuIn, menuOut, attributes, attr, dflt);
        }
        var buttons = handleArrayContainerDefaults(menuIn, menuOut, {
          name: "buttons",
          handleItemDefaults: buttonDefaults
        });
        var visible = coerce("visible", buttons.length > 0);
        if (!visible) return;
        coerce("active");
        coerce("direction");
        coerce("type");
        coerce("showactive");
        coerce("x");
        coerce("y");
        Lib.noneOrAll(menuIn, menuOut, ["x", "y"]);
        coerce("xanchor");
        coerce("yanchor");
        coerce("pad.t");
        coerce("pad.r");
        coerce("pad.b");
        coerce("pad.l");
        Lib.coerceFont(coerce, "font", layoutOut.font);
        coerce("bgcolor", layoutOut.paper_bgcolor);
        coerce("bordercolor");
        coerce("borderwidth");
      }
      function buttonDefaults(buttonIn, buttonOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(buttonIn, buttonOut, buttonAttrs, attr, dflt);
        }
        var visible = coerce(
          "visible",
          buttonIn.method === "skip" || Array.isArray(buttonIn.args)
        );
        if (visible) {
          coerce("method");
          coerce("args");
          coerce("args2");
          coerce("label");
          coerce("execute");
        }
      }
    }
  });

  // src/components/updatemenus/scrollbox.js
  var require_scrollbox = __commonJS({
    "src/components/updatemenus/scrollbox.js"(exports, module) {
      "use strict";
      module.exports = ScrollBox;
      var d3 = require_d3();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Lib = require_lib();
      function ScrollBox(gd, container, id) {
        this.gd = gd;
        this.container = container;
        this.id = id;
        this.position = null;
        this.translateX = null;
        this.translateY = null;
        this.hbar = null;
        this.vbar = null;
        this.bg = this.container.selectAll("rect.scrollbox-bg").data([0]);
        this.bg.exit().on(".drag", null).on("wheel", null).remove();
        this.bg.enter().append("rect").classed("scrollbox-bg", true).style("pointer-events", "all").attr({
          opacity: 0,
          x: 0,
          y: 0,
          width: 0,
          height: 0
        });
      }
      ScrollBox.barWidth = 2;
      ScrollBox.barLength = 20;
      ScrollBox.barRadius = 2;
      ScrollBox.barPad = 1;
      ScrollBox.barColor = "#808BA4";
      ScrollBox.prototype.enable = function enable(position, translateX, translateY) {
        var fullLayout = this.gd._fullLayout;
        var fullWidth = fullLayout.width;
        var fullHeight = fullLayout.height;
        this.position = position;
        var l = this.position.l;
        var w = this.position.w;
        var t = this.position.t;
        var h = this.position.h;
        var direction = this.position.direction;
        var isDown = direction === "down";
        var isLeft = direction === "left";
        var isRight = direction === "right";
        var isUp = direction === "up";
        var boxW = w;
        var boxH = h;
        var boxL, boxR;
        var boxT, boxB;
        if (!isDown && !isLeft && !isRight && !isUp) {
          this.position.direction = "down";
          isDown = true;
        }
        var isVertical = isDown || isUp;
        if (isVertical) {
          boxL = l;
          boxR = boxL + boxW;
          if (isDown) {
            boxT = t;
            boxB = Math.min(boxT + boxH, fullHeight);
            boxH = boxB - boxT;
          } else {
            boxB = t + boxH;
            boxT = Math.max(boxB - boxH, 0);
            boxH = boxB - boxT;
          }
        } else {
          boxT = t;
          boxB = boxT + boxH;
          if (isLeft) {
            boxR = l + boxW;
            boxL = Math.max(boxR - boxW, 0);
            boxW = boxR - boxL;
          } else {
            boxL = l;
            boxR = Math.min(boxL + boxW, fullWidth);
            boxW = boxR - boxL;
          }
        }
        this._box = {
          l: boxL,
          t: boxT,
          w: boxW,
          h: boxH
        };
        var needsHorizontalScrollBar = w > boxW;
        var hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad;
        var hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad;
        var hbarL = l;
        var hbarT = t + h;
        if (hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH;
        var hbar = this.container.selectAll("rect.scrollbar-horizontal").data(
          needsHorizontalScrollBar ? [0] : []
        );
        hbar.exit().on(".drag", null).remove();
        hbar.enter().append("rect").classed("scrollbar-horizontal", true).call(Color2.fill, ScrollBox.barColor);
        if (needsHorizontalScrollBar) {
          this.hbar = hbar.attr({
            rx: ScrollBox.barRadius,
            ry: ScrollBox.barRadius,
            x: hbarL,
            y: hbarT,
            width: hbarW,
            height: hbarH
          });
          this._hbarXMin = hbarL + hbarW / 2;
          this._hbarTranslateMax = boxW - hbarW;
        } else {
          delete this.hbar;
          delete this._hbarXMin;
          delete this._hbarTranslateMax;
        }
        var needsVerticalScrollBar = h > boxH;
        var vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad;
        var vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad;
        var vbarL = l + w;
        var vbarT = t;
        if (vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW;
        var vbar = this.container.selectAll("rect.scrollbar-vertical").data(
          needsVerticalScrollBar ? [0] : []
        );
        vbar.exit().on(".drag", null).remove();
        vbar.enter().append("rect").classed("scrollbar-vertical", true).call(Color2.fill, ScrollBox.barColor);
        if (needsVerticalScrollBar) {
          this.vbar = vbar.attr({
            rx: ScrollBox.barRadius,
            ry: ScrollBox.barRadius,
            x: vbarL,
            y: vbarT,
            width: vbarW,
            height: vbarH
          });
          this._vbarYMin = vbarT + vbarH / 2;
          this._vbarTranslateMax = boxH - vbarH;
        } else {
          delete this.vbar;
          delete this._vbarYMin;
          delete this._vbarTranslateMax;
        }
        var clipId = this.id;
        var clipL = boxL - 0.5;
        var clipR = needsVerticalScrollBar ? boxR + vbarW + 0.5 : boxR + 0.5;
        var clipT = boxT - 0.5;
        var clipB = needsHorizontalScrollBar ? boxB + hbarH + 0.5 : boxB + 0.5;
        var clipPath = fullLayout._topdefs.selectAll("#" + clipId).data(needsHorizontalScrollBar || needsVerticalScrollBar ? [0] : []);
        clipPath.exit().remove();
        clipPath.enter().append("clipPath").attr("id", clipId).append("rect");
        if (needsHorizontalScrollBar || needsVerticalScrollBar) {
          this._clipRect = clipPath.select("rect").attr({
            x: Math.floor(clipL),
            y: Math.floor(clipT),
            width: Math.ceil(clipR) - Math.floor(clipL),
            height: Math.ceil(clipB) - Math.floor(clipT)
          });
          this.container.call(Drawing.setClipUrl, clipId, this.gd);
          this.bg.attr({
            x: l,
            y: t,
            width: w,
            height: h
          });
        } else {
          this.bg.attr({
            width: 0,
            height: 0
          });
          this.container.on("wheel", null).on(".drag", null).call(Drawing.setClipUrl, null);
          delete this._clipRect;
        }
        if (needsHorizontalScrollBar || needsVerticalScrollBar) {
          var onBoxDrag = d3.behavior.drag().on("dragstart", function() {
            d3.event.sourceEvent.preventDefault();
          }).on("drag", this._onBoxDrag.bind(this));
          this.container.on("wheel", null).on("wheel", this._onBoxWheel.bind(this)).on(".drag", null).call(onBoxDrag);
          var onBarDrag = d3.behavior.drag().on("dragstart", function() {
            d3.event.sourceEvent.preventDefault();
            d3.event.sourceEvent.stopPropagation();
          }).on("drag", this._onBarDrag.bind(this));
          if (needsHorizontalScrollBar) {
            this.hbar.on(".drag", null).call(onBarDrag);
          }
          if (needsVerticalScrollBar) {
            this.vbar.on(".drag", null).call(onBarDrag);
          }
        }
        this.setTranslate(translateX, translateY);
      };
      ScrollBox.prototype.disable = function disable() {
        if (this.hbar || this.vbar) {
          this.bg.attr({
            width: 0,
            height: 0
          });
          this.container.on("wheel", null).on(".drag", null).call(Drawing.setClipUrl, null);
          delete this._clipRect;
        }
        if (this.hbar) {
          this.hbar.on(".drag", null);
          this.hbar.remove();
          delete this.hbar;
          delete this._hbarXMin;
          delete this._hbarTranslateMax;
        }
        if (this.vbar) {
          this.vbar.on(".drag", null);
          this.vbar.remove();
          delete this.vbar;
          delete this._vbarYMin;
          delete this._vbarTranslateMax;
        }
      };
      ScrollBox.prototype._onBoxDrag = function _onBoxDrag() {
        var translateX = this.translateX;
        var translateY = this.translateY;
        if (this.hbar) {
          translateX -= d3.event.dx;
        }
        if (this.vbar) {
          translateY -= d3.event.dy;
        }
        this.setTranslate(translateX, translateY);
      };
      ScrollBox.prototype._onBoxWheel = function _onBoxWheel() {
        var translateX = this.translateX;
        var translateY = this.translateY;
        if (this.hbar) {
          translateX += d3.event.deltaY;
        }
        if (this.vbar) {
          translateY += d3.event.deltaY;
        }
        this.setTranslate(translateX, translateY);
      };
      ScrollBox.prototype._onBarDrag = function _onBarDrag() {
        var translateX = this.translateX;
        var translateY = this.translateY;
        if (this.hbar) {
          var xMin = translateX + this._hbarXMin;
          var xMax = xMin + this._hbarTranslateMax;
          var x = Lib.constrain(d3.event.x, xMin, xMax);
          var xf = (x - xMin) / (xMax - xMin);
          var translateXMax = this.position.w - this._box.w;
          translateX = xf * translateXMax;
        }
        if (this.vbar) {
          var yMin = translateY + this._vbarYMin;
          var yMax = yMin + this._vbarTranslateMax;
          var y = Lib.constrain(d3.event.y, yMin, yMax);
          var yf = (y - yMin) / (yMax - yMin);
          var translateYMax = this.position.h - this._box.h;
          translateY = yf * translateYMax;
        }
        this.setTranslate(translateX, translateY);
      };
      ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) {
        var translateXMax = this.position.w - this._box.w;
        var translateYMax = this.position.h - this._box.h;
        translateX = Lib.constrain(translateX || 0, 0, translateXMax);
        translateY = Lib.constrain(translateY || 0, 0, translateYMax);
        this.translateX = translateX;
        this.translateY = translateY;
        this.container.call(
          Drawing.setTranslate,
          this._box.l - this.position.l - translateX,
          this._box.t - this.position.t - translateY
        );
        if (this._clipRect) {
          this._clipRect.attr({
            x: Math.floor(this.position.l + translateX - 0.5),
            y: Math.floor(this.position.t + translateY - 0.5)
          });
        }
        if (this.hbar) {
          var xf = translateX / translateXMax;
          this.hbar.call(
            Drawing.setTranslate,
            translateX + xf * this._hbarTranslateMax,
            translateY
          );
        }
        if (this.vbar) {
          var yf = translateY / translateYMax;
          this.vbar.call(
            Drawing.setTranslate,
            translateX,
            translateY + yf * this._vbarTranslateMax
          );
        }
      };
    }
  });

  // src/components/updatemenus/draw.js
  var require_draw7 = __commonJS({
    "src/components/updatemenus/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Plots = require_plots();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var svgTextUtils = require_svg_text_utils();
      var arrayEditor = require_plot_template().arrayEditor;
      var LINE_SPACING = require_alignment().LINE_SPACING;
      var constants = require_constants10();
      var ScrollBox = require_scrollbox();
      module.exports = function draw(gd) {
        var fullLayout = gd._fullLayout;
        var menuData = Lib.filterVisible(fullLayout[constants.name]);
        function clearAutoMargin(menuOpts2) {
          Plots.autoMargin(gd, autoMarginId(menuOpts2));
        }
        var menus = fullLayout._menulayer.selectAll("g." + constants.containerClassName).data(menuData.length > 0 ? [0] : []);
        menus.enter().append("g").classed(constants.containerClassName, true).style("cursor", "pointer");
        menus.exit().each(function() {
          d3.select(this).selectAll("g." + constants.headerGroupClassName).each(clearAutoMargin);
        }).remove();
        if (menuData.length === 0) return;
        var headerGroups = menus.selectAll("g." + constants.headerGroupClassName).data(menuData, keyFunction);
        headerGroups.enter().append("g").classed(constants.headerGroupClassName, true);
        var gButton = Lib.ensureSingle(menus, "g", constants.dropdownButtonGroupClassName, function(s) {
          s.style("pointer-events", "all");
        });
        for (var i = 0; i < menuData.length; i++) {
          var menuOpts = menuData[i];
          findDimensions(gd, menuOpts);
        }
        var scrollBoxId = "updatemenus" + fullLayout._uid;
        var scrollBox = new ScrollBox(gd, gButton, scrollBoxId);
        if (headerGroups.enter().size()) {
          gButton.node().parentNode.appendChild(gButton.node());
          gButton.call(removeAllButtons);
        }
        headerGroups.exit().each(function(menuOpts2) {
          gButton.call(removeAllButtons);
          clearAutoMargin(menuOpts2);
        }).remove();
        headerGroups.each(function(menuOpts2) {
          var gHeader = d3.select(this);
          var _gButton = menuOpts2.type === "dropdown" ? gButton : null;
          Plots.manageCommandObserver(gd, menuOpts2, menuOpts2.buttons, function(data) {
            setActive(gd, menuOpts2, menuOpts2.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true);
          });
          if (menuOpts2.type === "dropdown") {
            drawHeader(gd, gHeader, gButton, scrollBox, menuOpts2);
            if (isActive(gButton, menuOpts2)) {
              drawButtons(gd, gHeader, gButton, scrollBox, menuOpts2);
            }
          } else {
            drawButtons(gd, gHeader, null, null, menuOpts2);
          }
        });
      };
      function keyFunction(menuOpts) {
        return menuOpts._index;
      }
      function isFolded(gButton) {
        return +gButton.attr(constants.menuIndexAttrName) === -1;
      }
      function isActive(gButton, menuOpts) {
        return +gButton.attr(constants.menuIndexAttrName) === menuOpts._index;
      }
      function setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) {
        menuOpts.active = buttonIndex;
        arrayEditor(gd.layout, constants.name, menuOpts).applyUpdate("active", buttonIndex);
        if (menuOpts.type === "buttons") {
          drawButtons(gd, gHeader, null, null, menuOpts);
        } else if (menuOpts.type === "dropdown") {
          gButton.attr(constants.menuIndexAttrName, "-1");
          drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);
          if (!isSilentUpdate) {
            drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
          }
        }
      }
      function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) {
        var header = Lib.ensureSingle(gHeader, "g", constants.headerClassName, function(s) {
          s.style("pointer-events", "all");
        });
        var dims = menuOpts._dims;
        var active = menuOpts.active;
        var headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts;
        var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 };
        var positionOverrides = {
          width: dims.headerWidth,
          height: dims.headerHeight
        };
        header.call(drawItem, menuOpts, headerOpts, gd).call(setItemPosition, menuOpts, posOpts, positionOverrides);
        var arrow = Lib.ensureSingle(gHeader, "text", constants.headerArrowClassName, function(s) {
          s.attr("text-anchor", "end").call(Drawing.font, menuOpts.font).text(constants.arrowSymbol[menuOpts.direction]);
        });
        arrow.attr({
          x: dims.headerWidth - constants.arrowOffsetX + menuOpts.pad.l,
          y: dims.headerHeight / 2 + constants.textOffsetY + menuOpts.pad.t
        });
        header.on("click", function() {
          gButton.call(
            removeAllButtons,
            String(isActive(gButton, menuOpts) ? -1 : menuOpts._index)
          );
          drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
        });
        header.on("mouseover", function() {
          header.call(styleOnMouseOver);
        });
        header.on("mouseout", function() {
          header.call(styleOnMouseOut, menuOpts);
        });
        Drawing.setTranslate(gHeader, dims.lx, dims.ly);
      }
      function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) {
        if (!gButton) {
          gButton = gHeader;
          gButton.attr("pointer-events", "all");
        }
        var buttonData = !isFolded(gButton) || menuOpts.type === "buttons" ? menuOpts.buttons : [];
        var klass = menuOpts.type === "dropdown" ? constants.dropdownButtonClassName : constants.buttonClassName;
        var buttons = gButton.selectAll("g." + klass).data(Lib.filterVisible(buttonData));
        var enter = buttons.enter().append("g").classed(klass, true);
        var exit = buttons.exit();
        if (menuOpts.type === "dropdown") {
          enter.attr("opacity", "0").transition().attr("opacity", "1");
          exit.transition().attr("opacity", "0").remove();
        } else {
          exit.remove();
        }
        var x0 = 0;
        var y0 = 0;
        var dims = menuOpts._dims;
        var isVertical = ["up", "down"].indexOf(menuOpts.direction) !== -1;
        if (menuOpts.type === "dropdown") {
          if (isVertical) {
            y0 = dims.headerHeight + constants.gapButtonHeader;
          } else {
            x0 = dims.headerWidth + constants.gapButtonHeader;
          }
        }
        if (menuOpts.type === "dropdown" && menuOpts.direction === "up") {
          y0 = -constants.gapButtonHeader + constants.gapButton - dims.openHeight;
        }
        if (menuOpts.type === "dropdown" && menuOpts.direction === "left") {
          x0 = -constants.gapButtonHeader + constants.gapButton - dims.openWidth;
        }
        var posOpts = {
          x: dims.lx + x0 + menuOpts.pad.l,
          y: dims.ly + y0 + menuOpts.pad.t,
          yPad: constants.gapButton,
          xPad: constants.gapButton,
          index: 0
        };
        var scrollBoxPosition = {
          l: posOpts.x + menuOpts.borderwidth,
          t: posOpts.y + menuOpts.borderwidth
        };
        buttons.each(function(buttonOpts, buttonIndex) {
          var button = d3.select(this);
          button.call(drawItem, menuOpts, buttonOpts, gd).call(setItemPosition, menuOpts, posOpts);
          button.on("click", function() {
            if (d3.event.defaultPrevented) return;
            if (buttonOpts.execute) {
              if (buttonOpts.args2 && menuOpts.active === buttonIndex) {
                setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, -1);
                Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args2);
              } else {
                setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex);
                Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args);
              }
            }
            gd.emit("plotly_buttonclicked", { menu: menuOpts, button: buttonOpts, active: menuOpts.active });
          });
          button.on("mouseover", function() {
            button.call(styleOnMouseOver);
          });
          button.on("mouseout", function() {
            button.call(styleOnMouseOut, menuOpts);
            buttons.call(styleButtons, menuOpts);
          });
        });
        buttons.call(styleButtons, menuOpts);
        if (isVertical) {
          scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth);
          scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t;
        } else {
          scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l;
          scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight);
        }
        scrollBoxPosition.direction = menuOpts.direction;
        if (scrollBox) {
          if (buttons.size()) {
            drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition);
          } else {
            hideScrollBox(scrollBox);
          }
        }
      }
      function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) {
        var direction = menuOpts.direction;
        var isVertical = direction === "up" || direction === "down";
        var dims = menuOpts._dims;
        var active = menuOpts.active;
        var translateX, translateY;
        var i;
        if (isVertical) {
          translateY = 0;
          for (i = 0; i < active; i++) {
            translateY += dims.heights[i] + constants.gapButton;
          }
        } else {
          translateX = 0;
          for (i = 0; i < active; i++) {
            translateX += dims.widths[i] + constants.gapButton;
          }
        }
        scrollBox.enable(position, translateX, translateY);
        if (scrollBox.hbar) {
          scrollBox.hbar.attr("opacity", "0").transition().attr("opacity", "1");
        }
        if (scrollBox.vbar) {
          scrollBox.vbar.attr("opacity", "0").transition().attr("opacity", "1");
        }
      }
      function hideScrollBox(scrollBox) {
        var hasHBar = !!scrollBox.hbar;
        var hasVBar = !!scrollBox.vbar;
        if (hasHBar) {
          scrollBox.hbar.transition().attr("opacity", "0").each("end", function() {
            hasHBar = false;
            if (!hasVBar) scrollBox.disable();
          });
        }
        if (hasVBar) {
          scrollBox.vbar.transition().attr("opacity", "0").each("end", function() {
            hasVBar = false;
            if (!hasHBar) scrollBox.disable();
          });
        }
      }
      function drawItem(item, menuOpts, itemOpts, gd) {
        item.call(drawItemRect, menuOpts).call(drawItemText, menuOpts, itemOpts, gd);
      }
      function drawItemRect(item, menuOpts) {
        var rect = Lib.ensureSingle(item, "rect", constants.itemRectClassName, function(s) {
          s.attr({
            rx: constants.rx,
            ry: constants.ry,
            "shape-rendering": "crispEdges"
          });
        });
        rect.call(Color2.stroke, menuOpts.bordercolor).call(Color2.fill, menuOpts.bgcolor).style("stroke-width", menuOpts.borderwidth + "px");
      }
      function drawItemText(item, menuOpts, itemOpts, gd) {
        var text = Lib.ensureSingle(item, "text", constants.itemTextClassName, function(s) {
          s.attr({
            "text-anchor": "start",
            "data-notex": 1
          });
        });
        var tx = itemOpts.label;
        var _meta = gd._fullLayout._meta;
        if (_meta) tx = Lib.templateString(tx, _meta);
        text.call(Drawing.font, menuOpts.font).text(tx).call(svgTextUtils.convertToTspans, gd);
      }
      function styleButtons(buttons, menuOpts) {
        var active = menuOpts.active;
        buttons.each(function(buttonOpts, i) {
          var button = d3.select(this);
          if (i === active && menuOpts.showactive) {
            button.select("rect." + constants.itemRectClassName).call(Color2.fill, constants.activeColor);
          }
        });
      }
      function styleOnMouseOver(item) {
        item.select("rect." + constants.itemRectClassName).call(Color2.fill, constants.hoverColor);
      }
      function styleOnMouseOut(item, menuOpts) {
        item.select("rect." + constants.itemRectClassName).call(Color2.fill, menuOpts.bgcolor);
      }
      function findDimensions(gd, menuOpts) {
        var dims = menuOpts._dims = {
          width1: 0,
          height1: 0,
          heights: [],
          widths: [],
          totalWidth: 0,
          totalHeight: 0,
          openWidth: 0,
          openHeight: 0,
          lx: 0,
          ly: 0
        };
        var fakeButtons = Drawing.tester.selectAll("g." + constants.dropdownButtonClassName).data(Lib.filterVisible(menuOpts.buttons));
        fakeButtons.enter().append("g").classed(constants.dropdownButtonClassName, true);
        var isVertical = ["up", "down"].indexOf(menuOpts.direction) !== -1;
        fakeButtons.each(function(buttonOpts, i) {
          var button = d3.select(this);
          button.call(drawItem, menuOpts, buttonOpts, gd);
          var text = button.select("." + constants.itemTextClassName);
          var tWidth = text.node() && Drawing.bBox(text.node()).width;
          var wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);
          var tHeight = menuOpts.font.size * LINE_SPACING;
          var tLines = svgTextUtils.lineCount(text);
          var hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;
          hEff = Math.ceil(hEff);
          wEff = Math.ceil(wEff);
          dims.widths[i] = wEff;
          dims.heights[i] = hEff;
          dims.height1 = Math.max(dims.height1, hEff);
          dims.width1 = Math.max(dims.width1, wEff);
          if (isVertical) {
            dims.totalWidth = Math.max(dims.totalWidth, wEff);
            dims.openWidth = dims.totalWidth;
            dims.totalHeight += hEff + constants.gapButton;
            dims.openHeight += hEff + constants.gapButton;
          } else {
            dims.totalWidth += wEff + constants.gapButton;
            dims.openWidth += wEff + constants.gapButton;
            dims.totalHeight = Math.max(dims.totalHeight, hEff);
            dims.openHeight = dims.totalHeight;
          }
        });
        if (isVertical) {
          dims.totalHeight -= constants.gapButton;
        } else {
          dims.totalWidth -= constants.gapButton;
        }
        dims.headerWidth = dims.width1 + constants.arrowPadX;
        dims.headerHeight = dims.height1;
        if (menuOpts.type === "dropdown") {
          if (isVertical) {
            dims.width1 += constants.arrowPadX;
            dims.totalHeight = dims.height1;
          } else {
            dims.totalWidth = dims.width1;
          }
          dims.totalWidth += constants.arrowPadX;
        }
        fakeButtons.remove();
        var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r;
        var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b;
        var graphSize = gd._fullLayout._size;
        dims.lx = graphSize.l + graphSize.w * menuOpts.x;
        dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);
        var xanchor = "left";
        if (Lib.isRightAnchor(menuOpts)) {
          dims.lx -= paddedWidth;
          xanchor = "right";
        }
        if (Lib.isCenterAnchor(menuOpts)) {
          dims.lx -= paddedWidth / 2;
          xanchor = "center";
        }
        var yanchor = "top";
        if (Lib.isBottomAnchor(menuOpts)) {
          dims.ly -= paddedHeight;
          yanchor = "bottom";
        }
        if (Lib.isMiddleAnchor(menuOpts)) {
          dims.ly -= paddedHeight / 2;
          yanchor = "middle";
        }
        dims.totalWidth = Math.ceil(dims.totalWidth);
        dims.totalHeight = Math.ceil(dims.totalHeight);
        dims.lx = Math.round(dims.lx);
        dims.ly = Math.round(dims.ly);
        Plots.autoMargin(gd, autoMarginId(menuOpts), {
          x: menuOpts.x,
          y: menuOpts.y,
          l: paddedWidth * ({ right: 1, center: 0.5 }[xanchor] || 0),
          r: paddedWidth * ({ left: 1, center: 0.5 }[xanchor] || 0),
          b: paddedHeight * ({ top: 1, middle: 0.5 }[yanchor] || 0),
          t: paddedHeight * ({ bottom: 1, middle: 0.5 }[yanchor] || 0)
        });
      }
      function autoMarginId(menuOpts) {
        return constants.autoMarginIdRoot + menuOpts._index;
      }
      function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
        overrideOpts = overrideOpts || {};
        var rect = item.select("." + constants.itemRectClassName);
        var text = item.select("." + constants.itemTextClassName);
        var borderWidth = menuOpts.borderwidth;
        var index = posOpts.index;
        var dims = menuOpts._dims;
        Drawing.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y);
        var isVertical = ["up", "down"].indexOf(menuOpts.direction) !== -1;
        var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1);
        rect.attr({
          x: 0,
          y: 0,
          width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]),
          height: finalHeight
        });
        var tHeight = menuOpts.font.size * LINE_SPACING;
        var tLines = svgTextUtils.lineCount(text);
        var spanOffset = (tLines - 1) * tHeight / 2;
        svgTextUtils.positionText(
          text,
          constants.textOffsetX,
          finalHeight / 2 - spanOffset + constants.textOffsetY
        );
        if (isVertical) {
          posOpts.y += dims.heights[index] + posOpts.yPad;
        } else {
          posOpts.x += dims.widths[index] + posOpts.xPad;
        }
        posOpts.index++;
      }
      function removeAllButtons(gButton, newMenuIndexAttr) {
        gButton.attr(constants.menuIndexAttrName, newMenuIndexAttr || "-1").selectAll("g." + constants.dropdownButtonClassName).remove();
      }
    }
  });

  // src/components/updatemenus/index.js
  var require_updatemenus = __commonJS({
    "src/components/updatemenus/index.js"(exports, module) {
      "use strict";
      var constants = require_constants10();
      module.exports = {
        moduleType: "component",
        name: constants.name,
        layoutAttributes: require_attributes18(),
        supplyLayoutDefaults: require_defaults14(),
        draw: require_draw7()
      };
    }
  });

  // src/components/sliders/constants.js
  var require_constants11 = __commonJS({
    "src/components/sliders/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // layout attribute name
        name: "sliders",
        // class names
        containerClassName: "slider-container",
        groupClassName: "slider-group",
        inputAreaClass: "slider-input-area",
        railRectClass: "slider-rail-rect",
        railTouchRectClass: "slider-rail-touch-rect",
        gripRectClass: "slider-grip-rect",
        tickRectClass: "slider-tick-rect",
        inputProxyClass: "slider-input-proxy",
        labelsClass: "slider-labels",
        labelGroupClass: "slider-label-group",
        labelClass: "slider-label",
        currentValueClass: "slider-current-value",
        railHeight: 5,
        // DOM attribute name in button group keeping track
        // of active update menu
        menuIndexAttrName: "slider-active-index",
        // id root pass to Plots.autoMargin
        autoMarginIdRoot: "slider-",
        // min item width / height
        minWidth: 30,
        minHeight: 30,
        // padding around item text
        textPadX: 40,
        // arrow offset off right edge
        arrowOffsetX: 4,
        railRadius: 2,
        railWidth: 5,
        railBorder: 4,
        railBorderWidth: 1,
        railBorderColor: "#bec8d9",
        railBgColor: "#f8fafc",
        // The distance of the rail from the edge of the touchable area
        // Slightly less than the step inset because of the curved edges
        // of the rail
        railInset: 8,
        // The distance from the extremal tick marks to the edge of the
        // touchable area. This is basically the same as the grip radius,
        // but for other styles it wouldn't really need to be.
        stepInset: 10,
        gripRadius: 10,
        gripWidth: 20,
        gripHeight: 20,
        gripBorder: 20,
        gripBorderWidth: 1,
        gripBorderColor: "#bec8d9",
        gripBgColor: "#f6f8fa",
        gripBgActiveColor: "#dbdde0",
        labelPadding: 8,
        labelOffset: 0,
        tickWidth: 1,
        tickColor: "#333",
        tickOffset: 25,
        tickLength: 7,
        minorTickOffset: 25,
        minorTickColor: "#333",
        minorTickLength: 4,
        // Extra space below the current value label:
        currentValuePadding: 8,
        currentValueInset: 0
      };
    }
  });

  // src/components/sliders/attributes.js
  var require_attributes19 = __commonJS({
    "src/components/sliders/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var padAttrs = require_pad_attributes();
      var extendDeepAll = require_extend().extendDeepAll;
      var overrideAll = require_edit_types().overrideAll;
      var animationAttrs = require_animation_attributes();
      var templatedArray = require_plot_template().templatedArray;
      var constants = require_constants11();
      var stepsAttrs = templatedArray("step", {
        visible: {
          valType: "boolean",
          dflt: true
        },
        method: {
          valType: "enumerated",
          values: ["restyle", "relayout", "animate", "update", "skip"],
          dflt: "restyle"
        },
        args: {
          valType: "info_array",
          freeLength: true,
          items: [
            { valType: "any" },
            { valType: "any" },
            { valType: "any" }
          ]
        },
        label: {
          valType: "string"
        },
        value: {
          valType: "string"
        },
        execute: {
          valType: "boolean",
          dflt: true
        }
      });
      module.exports = overrideAll(templatedArray("slider", {
        visible: {
          valType: "boolean",
          dflt: true
        },
        active: {
          valType: "number",
          min: 0,
          dflt: 0
        },
        steps: stepsAttrs,
        lenmode: {
          valType: "enumerated",
          values: ["fraction", "pixels"],
          dflt: "fraction"
        },
        len: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        x: {
          valType: "number",
          min: -2,
          max: 3,
          dflt: 0
        },
        pad: extendDeepAll(padAttrs({ editType: "arraydraw" }), {}, { t: { dflt: 20 } }),
        xanchor: {
          valType: "enumerated",
          values: ["auto", "left", "center", "right"],
          dflt: "left"
        },
        y: {
          valType: "number",
          min: -2,
          max: 3,
          dflt: 0
        },
        yanchor: {
          valType: "enumerated",
          values: ["auto", "top", "middle", "bottom"],
          dflt: "top"
        },
        transition: {
          duration: {
            valType: "number",
            min: 0,
            dflt: 150
          },
          easing: {
            valType: "enumerated",
            values: animationAttrs.transition.easing.values,
            dflt: "cubic-in-out"
          }
        },
        currentvalue: {
          visible: {
            valType: "boolean",
            dflt: true
          },
          xanchor: {
            valType: "enumerated",
            values: ["left", "center", "right"],
            dflt: "left"
          },
          offset: {
            valType: "number",
            dflt: 10
          },
          prefix: {
            valType: "string"
          },
          suffix: {
            valType: "string"
          },
          font: fontAttrs({})
        },
        font: fontAttrs({}),
        activebgcolor: {
          valType: "color",
          dflt: constants.gripBgActiveColor
        },
        bgcolor: {
          valType: "color",
          dflt: constants.railBgColor
        },
        bordercolor: {
          valType: "color",
          dflt: constants.railBorderColor
        },
        borderwidth: {
          valType: "number",
          min: 0,
          dflt: constants.railBorderWidth
        },
        ticklen: {
          valType: "number",
          min: 0,
          dflt: constants.tickLength
        },
        tickcolor: {
          valType: "color",
          dflt: constants.tickColor
        },
        tickwidth: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        minorticklen: {
          valType: "number",
          min: 0,
          dflt: constants.minorTickLength
        }
      }), "arraydraw", "from-root");
    }
  });

  // src/components/sliders/defaults.js
  var require_defaults15 = __commonJS({
    "src/components/sliders/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes19();
      var constants = require_constants11();
      var name2 = constants.name;
      var stepAttrs = attributes.steps;
      module.exports = function slidersDefaults(layoutIn, layoutOut) {
        handleArrayContainerDefaults(layoutIn, layoutOut, {
          name: name2,
          handleItemDefaults: sliderDefaults
        });
      };
      function sliderDefaults(sliderIn, sliderOut, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(sliderIn, sliderOut, attributes, attr, dflt);
        }
        var steps = handleArrayContainerDefaults(sliderIn, sliderOut, {
          name: "steps",
          handleItemDefaults: stepDefaults
        });
        var stepCount = 0;
        for (var i = 0; i < steps.length; i++) {
          if (steps[i].visible) stepCount++;
        }
        var visible;
        if (stepCount < 2) visible = sliderOut.visible = false;
        else visible = coerce("visible");
        if (!visible) return;
        sliderOut._stepCount = stepCount;
        var visSteps = sliderOut._visibleSteps = Lib.filterVisible(steps);
        var active = coerce("active");
        if (!(steps[active] || {}).visible) sliderOut.active = visSteps[0]._index;
        coerce("x");
        coerce("y");
        Lib.noneOrAll(sliderIn, sliderOut, ["x", "y"]);
        coerce("xanchor");
        coerce("yanchor");
        coerce("len");
        coerce("lenmode");
        coerce("pad.t");
        coerce("pad.r");
        coerce("pad.b");
        coerce("pad.l");
        Lib.coerceFont(coerce, "font", layoutOut.font);
        var currentValueIsVisible = coerce("currentvalue.visible");
        if (currentValueIsVisible) {
          coerce("currentvalue.xanchor");
          coerce("currentvalue.prefix");
          coerce("currentvalue.suffix");
          coerce("currentvalue.offset");
          Lib.coerceFont(coerce, "currentvalue.font", sliderOut.font);
        }
        coerce("transition.duration");
        coerce("transition.easing");
        coerce("bgcolor");
        coerce("activebgcolor");
        coerce("bordercolor");
        coerce("borderwidth");
        coerce("ticklen");
        coerce("tickwidth");
        coerce("tickcolor");
        coerce("minorticklen");
      }
      function stepDefaults(valueIn, valueOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(valueIn, valueOut, stepAttrs, attr, dflt);
        }
        var visible;
        if (valueIn.method !== "skip" && !Array.isArray(valueIn.args)) {
          visible = valueOut.visible = false;
        } else visible = coerce("visible");
        if (visible) {
          coerce("method");
          coerce("args");
          var label = coerce("label", "step-" + valueOut._index);
          coerce("value", label);
          coerce("execute");
        }
      }
    }
  });

  // src/components/sliders/draw.js
  var require_draw8 = __commonJS({
    "src/components/sliders/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Plots = require_plots();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var arrayEditor = require_plot_template().arrayEditor;
      var constants = require_constants11();
      var alignmentConstants = require_alignment();
      var LINE_SPACING = alignmentConstants.LINE_SPACING;
      var FROM_TL = alignmentConstants.FROM_TL;
      var FROM_BR = alignmentConstants.FROM_BR;
      module.exports = function draw(gd) {
        var staticPlot = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var sliderData = makeSliderData(fullLayout, gd);
        var sliders = fullLayout._infolayer.selectAll("g." + constants.containerClassName).data(sliderData.length > 0 ? [0] : []);
        sliders.enter().append("g").classed(constants.containerClassName, true).style("cursor", staticPlot ? null : "ew-resize");
        function clearSlider(sliderOpts2) {
          if (sliderOpts2._commandObserver) {
            sliderOpts2._commandObserver.remove();
            delete sliderOpts2._commandObserver;
          }
          Plots.autoMargin(gd, autoMarginId(sliderOpts2));
        }
        sliders.exit().each(function() {
          d3.select(this).selectAll("g." + constants.groupClassName).each(clearSlider);
        }).remove();
        if (sliderData.length === 0) return;
        var sliderGroups = sliders.selectAll("g." + constants.groupClassName).data(sliderData, keyFunction);
        sliderGroups.enter().append("g").classed(constants.groupClassName, true);
        sliderGroups.exit().each(clearSlider).remove();
        for (var i = 0; i < sliderData.length; i++) {
          var sliderOpts = sliderData[i];
          findDimensions(gd, sliderOpts);
        }
        sliderGroups.each(function(sliderOpts2) {
          var gSlider = d3.select(this);
          computeLabelSteps(sliderOpts2);
          Plots.manageCommandObserver(gd, sliderOpts2, sliderOpts2._visibleSteps, function(data) {
            var opts = gSlider.data()[0];
            if (opts.active === data.index) return;
            if (opts._dragging) return;
            setActive(gd, gSlider, opts, data.index, false, true);
          });
          drawSlider(gd, d3.select(this), sliderOpts2);
        });
      };
      function autoMarginId(sliderOpts) {
        return constants.autoMarginIdRoot + sliderOpts._index;
      }
      function makeSliderData(fullLayout, gd) {
        var contOpts = fullLayout[constants.name];
        var sliderData = [];
        for (var i = 0; i < contOpts.length; i++) {
          var item = contOpts[i];
          if (!item.visible) continue;
          item._gd = gd;
          sliderData.push(item);
        }
        return sliderData;
      }
      function keyFunction(opts) {
        return opts._index;
      }
      function findDimensions(gd, sliderOpts) {
        var sliderLabels = Drawing.tester.selectAll("g." + constants.labelGroupClass).data(sliderOpts._visibleSteps);
        sliderLabels.enter().append("g").classed(constants.labelGroupClass, true);
        var maxLabelWidth = 0;
        var labelHeight = 0;
        sliderLabels.each(function(stepOpts) {
          var labelGroup = d3.select(this);
          var text = drawLabel(labelGroup, { step: stepOpts }, sliderOpts);
          var textNode = text.node();
          if (textNode) {
            var bBox = Drawing.bBox(textNode);
            labelHeight = Math.max(labelHeight, bBox.height);
            maxLabelWidth = Math.max(maxLabelWidth, bBox.width);
          }
        });
        sliderLabels.remove();
        var dims = sliderOpts._dims = {};
        dims.inputAreaWidth = Math.max(
          constants.railWidth,
          constants.gripHeight
        );
        var graphSize = gd._fullLayout._size;
        dims.lx = graphSize.l + graphSize.w * sliderOpts.x;
        dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y);
        if (sliderOpts.lenmode === "fraction") {
          dims.outerLength = Math.round(graphSize.w * sliderOpts.len);
        } else {
          dims.outerLength = sliderOpts.len;
        }
        dims.inputAreaStart = 0;
        dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r);
        var textableInputLength = dims.inputAreaLength - 2 * constants.stepInset;
        var availableSpacePerLabel = textableInputLength / (sliderOpts._stepCount - 1);
        var computedSpacePerLabel = maxLabelWidth + constants.labelPadding;
        dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel));
        dims.labelHeight = labelHeight;
        dims.currentValueMaxWidth = 0;
        dims.currentValueHeight = 0;
        dims.currentValueTotalHeight = 0;
        dims.currentValueMaxLines = 1;
        if (sliderOpts.currentvalue.visible) {
          var dummyGroup = Drawing.tester.append("g");
          sliderLabels.each(function(stepOpts) {
            var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label);
            var curValSize = curValPrefix.node() && Drawing.bBox(curValPrefix.node()) || { width: 0, height: 0 };
            var lines = svgTextUtils.lineCount(curValPrefix);
            dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width));
            dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height));
            dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines);
          });
          dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset;
          dummyGroup.remove();
        }
        dims.height = dims.currentValueTotalHeight + constants.tickOffset + sliderOpts.ticklen + constants.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b;
        var xanchor = "left";
        if (Lib.isRightAnchor(sliderOpts)) {
          dims.lx -= dims.outerLength;
          xanchor = "right";
        }
        if (Lib.isCenterAnchor(sliderOpts)) {
          dims.lx -= dims.outerLength / 2;
          xanchor = "center";
        }
        var yanchor = "top";
        if (Lib.isBottomAnchor(sliderOpts)) {
          dims.ly -= dims.height;
          yanchor = "bottom";
        }
        if (Lib.isMiddleAnchor(sliderOpts)) {
          dims.ly -= dims.height / 2;
          yanchor = "middle";
        }
        dims.outerLength = Math.ceil(dims.outerLength);
        dims.height = Math.ceil(dims.height);
        dims.lx = Math.round(dims.lx);
        dims.ly = Math.round(dims.ly);
        var marginOpts = {
          y: sliderOpts.y,
          b: dims.height * FROM_BR[yanchor],
          t: dims.height * FROM_TL[yanchor]
        };
        if (sliderOpts.lenmode === "fraction") {
          marginOpts.l = 0;
          marginOpts.xl = sliderOpts.x - sliderOpts.len * FROM_TL[xanchor];
          marginOpts.r = 0;
          marginOpts.xr = sliderOpts.x + sliderOpts.len * FROM_BR[xanchor];
        } else {
          marginOpts.x = sliderOpts.x;
          marginOpts.l = dims.outerLength * FROM_TL[xanchor];
          marginOpts.r = dims.outerLength * FROM_BR[xanchor];
        }
        Plots.autoMargin(gd, autoMarginId(sliderOpts), marginOpts);
      }
      function drawSlider(gd, sliderGroup, sliderOpts) {
        if (!(sliderOpts.steps[sliderOpts.active] || {}).visible) {
          sliderOpts.active = sliderOpts._visibleSteps[0]._index;
        }
        sliderGroup.call(drawCurrentValue, sliderOpts).call(drawRail, sliderOpts).call(drawLabelGroup, sliderOpts).call(drawTicks, sliderOpts).call(drawTouchRect, gd, sliderOpts).call(drawGrip, gd, sliderOpts);
        var dims = sliderOpts._dims;
        Drawing.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t);
        sliderGroup.call(setGripPosition, sliderOpts, false);
        sliderGroup.call(drawCurrentValue, sliderOpts);
      }
      function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) {
        if (!sliderOpts.currentvalue.visible) return;
        var dims = sliderOpts._dims;
        var x0, textAnchor;
        switch (sliderOpts.currentvalue.xanchor) {
          case "right":
            x0 = dims.inputAreaLength - constants.currentValueInset - dims.currentValueMaxWidth;
            textAnchor = "left";
            break;
          case "center":
            x0 = dims.inputAreaLength * 0.5;
            textAnchor = "middle";
            break;
          default:
            x0 = constants.currentValueInset;
            textAnchor = "left";
        }
        var text = Lib.ensureSingle(sliderGroup, "text", constants.labelClass, function(s) {
          s.attr({
            "text-anchor": textAnchor,
            "data-notex": 1
          });
        });
        var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : "";
        if (typeof valueOverride === "string") {
          str += valueOverride;
        } else {
          var curVal = sliderOpts.steps[sliderOpts.active].label;
          var _meta = sliderOpts._gd._fullLayout._meta;
          if (_meta) curVal = Lib.templateString(curVal, _meta);
          str += curVal;
        }
        if (sliderOpts.currentvalue.suffix) {
          str += sliderOpts.currentvalue.suffix;
        }
        text.call(Drawing.font, sliderOpts.currentvalue.font).text(str).call(svgTextUtils.convertToTspans, sliderOpts._gd);
        var lines = svgTextUtils.lineCount(text);
        var y0 = (dims.currentValueMaxLines + 1 - lines) * sliderOpts.currentvalue.font.size * LINE_SPACING;
        svgTextUtils.positionText(text, x0, y0);
        return text;
      }
      function drawGrip(sliderGroup, gd, sliderOpts) {
        var grip = Lib.ensureSingle(sliderGroup, "rect", constants.gripRectClass, function(s) {
          s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style("pointer-events", "all");
        });
        grip.attr({
          width: constants.gripWidth,
          height: constants.gripHeight,
          rx: constants.gripRadius,
          ry: constants.gripRadius
        }).call(Color2.stroke, sliderOpts.bordercolor).call(Color2.fill, sliderOpts.bgcolor).style("stroke-width", sliderOpts.borderwidth + "px");
      }
      function drawLabel(item, data, sliderOpts) {
        var text = Lib.ensureSingle(item, "text", constants.labelClass, function(s) {
          s.attr({
            "text-anchor": "middle",
            "data-notex": 1
          });
        });
        var tx = data.step.label;
        var _meta = sliderOpts._gd._fullLayout._meta;
        if (_meta) tx = Lib.templateString(tx, _meta);
        text.call(Drawing.font, sliderOpts.font).text(tx).call(svgTextUtils.convertToTspans, sliderOpts._gd);
        return text;
      }
      function drawLabelGroup(sliderGroup, sliderOpts) {
        var labels = Lib.ensureSingle(sliderGroup, "g", constants.labelsClass);
        var dims = sliderOpts._dims;
        var labelItems = labels.selectAll("g." + constants.labelGroupClass).data(dims.labelSteps);
        labelItems.enter().append("g").classed(constants.labelGroupClass, true);
        labelItems.exit().remove();
        labelItems.each(function(d) {
          var item = d3.select(this);
          item.call(drawLabel, d, sliderOpts);
          Drawing.setTranslate(
            item,
            normalizedValueToPosition(sliderOpts, d.fraction),
            constants.tickOffset + sliderOpts.ticklen + // position is the baseline of the top line of text only, even
            // if the label spans multiple lines
            sliderOpts.font.size * LINE_SPACING + constants.labelOffset + dims.currentValueTotalHeight
          );
        });
      }
      function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) {
        var quantizedPosition = Math.round(normalizedPosition * (sliderOpts._stepCount - 1));
        var quantizedIndex = sliderOpts._visibleSteps[quantizedPosition]._index;
        if (quantizedIndex !== sliderOpts.active) {
          setActive(gd, sliderGroup, sliderOpts, quantizedIndex, true, doTransition);
        }
      }
      function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) {
        var previousActive = sliderOpts.active;
        sliderOpts.active = index;
        arrayEditor(gd.layout, constants.name, sliderOpts).applyUpdate("active", index);
        var step = sliderOpts.steps[sliderOpts.active];
        sliderGroup.call(setGripPosition, sliderOpts, doTransition);
        sliderGroup.call(drawCurrentValue, sliderOpts);
        gd.emit("plotly_sliderchange", {
          slider: sliderOpts,
          step: sliderOpts.steps[sliderOpts.active],
          interaction: doCallback,
          previousActive
        });
        if (step && step.method && doCallback) {
          if (sliderGroup._nextMethod) {
            sliderGroup._nextMethod.step = step;
            sliderGroup._nextMethod.doCallback = doCallback;
            sliderGroup._nextMethod.doTransition = doTransition;
          } else {
            sliderGroup._nextMethod = { step, doCallback, doTransition };
            sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() {
              var _step = sliderGroup._nextMethod.step;
              if (!_step.method) return;
              if (_step.execute) {
                Plots.executeAPICommand(gd, _step.method, _step.args);
              }
              sliderGroup._nextMethod = null;
              sliderGroup._nextMethodRaf = null;
            });
          }
        }
      }
      function attachGripEvents(item, gd, sliderGroup) {
        if (gd._context.staticPlot) return;
        var node = sliderGroup.node();
        var $gd = d3.select(gd);
        function getSliderOpts() {
          return sliderGroup.data()[0];
        }
        function mouseDownHandler() {
          var sliderOpts = getSliderOpts();
          gd.emit("plotly_sliderstart", { slider: sliderOpts });
          var grip = sliderGroup.select("." + constants.gripRectClass);
          d3.event.stopPropagation();
          d3.event.preventDefault();
          grip.call(Color2.fill, sliderOpts.activebgcolor);
          var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
          handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true);
          sliderOpts._dragging = true;
          function mouseMoveHandler() {
            var sliderOpts2 = getSliderOpts();
            var normalizedPosition2 = positionToNormalizedValue(sliderOpts2, d3.mouse(node)[0]);
            handleInput(gd, sliderGroup, sliderOpts2, normalizedPosition2, false);
          }
          $gd.on("mousemove", mouseMoveHandler);
          $gd.on("touchmove", mouseMoveHandler);
          function mouseUpHandler() {
            var sliderOpts2 = getSliderOpts();
            sliderOpts2._dragging = false;
            grip.call(Color2.fill, sliderOpts2.bgcolor);
            $gd.on("mouseup", null);
            $gd.on("mousemove", null);
            $gd.on("touchend", null);
            $gd.on("touchmove", null);
            gd.emit("plotly_sliderend", {
              slider: sliderOpts2,
              step: sliderOpts2.steps[sliderOpts2.active]
            });
          }
          $gd.on("mouseup", mouseUpHandler);
          $gd.on("touchend", mouseUpHandler);
        }
        item.on("mousedown", mouseDownHandler);
        item.on("touchstart", mouseDownHandler);
      }
      function drawTicks(sliderGroup, sliderOpts) {
        var tick = sliderGroup.selectAll("rect." + constants.tickRectClass).data(sliderOpts._visibleSteps);
        var dims = sliderOpts._dims;
        tick.enter().append("rect").classed(constants.tickRectClass, true);
        tick.exit().remove();
        tick.attr({
          width: sliderOpts.tickwidth + "px",
          "shape-rendering": "crispEdges"
        });
        tick.each(function(d, i) {
          var isMajor = i % dims.labelStride === 0;
          var item = d3.select(this);
          item.attr({ height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen }).call(Color2.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor);
          Drawing.setTranslate(
            item,
            normalizedValueToPosition(sliderOpts, i / (sliderOpts._stepCount - 1)) - 0.5 * sliderOpts.tickwidth,
            (isMajor ? constants.tickOffset : constants.minorTickOffset) + dims.currentValueTotalHeight
          );
        });
      }
      function computeLabelSteps(sliderOpts) {
        var dims = sliderOpts._dims;
        dims.labelSteps = [];
        var nsteps = sliderOpts._stepCount;
        for (var i = 0; i < nsteps; i += dims.labelStride) {
          dims.labelSteps.push({
            fraction: i / (nsteps - 1),
            step: sliderOpts._visibleSteps[i]
          });
        }
      }
      function setGripPosition(sliderGroup, sliderOpts, doTransition) {
        var grip = sliderGroup.select("rect." + constants.gripRectClass);
        var quantizedIndex = 0;
        for (var i = 0; i < sliderOpts._stepCount; i++) {
          if (sliderOpts._visibleSteps[i]._index === sliderOpts.active) {
            quantizedIndex = i;
            break;
          }
        }
        var x = normalizedValueToPosition(sliderOpts, quantizedIndex / (sliderOpts._stepCount - 1));
        if (sliderOpts._invokingCommand) return;
        var el = grip;
        if (doTransition && sliderOpts.transition.duration > 0) {
          el = el.transition().duration(sliderOpts.transition.duration).ease(sliderOpts.transition.easing);
        }
        el.attr("transform", strTranslate(x - constants.gripWidth * 0.5, sliderOpts._dims.currentValueTotalHeight));
      }
      function normalizedValueToPosition(sliderOpts, normalizedPosition) {
        var dims = sliderOpts._dims;
        return dims.inputAreaStart + constants.stepInset + (dims.inputAreaLength - 2 * constants.stepInset) * Math.min(1, Math.max(0, normalizedPosition));
      }
      function positionToNormalizedValue(sliderOpts, position) {
        var dims = sliderOpts._dims;
        return Math.min(1, Math.max(0, (position - constants.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants.stepInset - 2 * dims.inputAreaStart)));
      }
      function drawTouchRect(sliderGroup, gd, sliderOpts) {
        var dims = sliderOpts._dims;
        var rect = Lib.ensureSingle(sliderGroup, "rect", constants.railTouchRectClass, function(s) {
          s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style("pointer-events", "all");
        });
        rect.attr({
          width: dims.inputAreaLength,
          height: Math.max(dims.inputAreaWidth, constants.tickOffset + sliderOpts.ticklen + dims.labelHeight)
        }).call(Color2.fill, sliderOpts.bgcolor).attr("opacity", 0);
        Drawing.setTranslate(rect, 0, dims.currentValueTotalHeight);
      }
      function drawRail(sliderGroup, sliderOpts) {
        var dims = sliderOpts._dims;
        var computedLength = dims.inputAreaLength - constants.railInset * 2;
        var rect = Lib.ensureSingle(sliderGroup, "rect", constants.railRectClass);
        rect.attr({
          width: computedLength,
          height: constants.railWidth,
          rx: constants.railRadius,
          ry: constants.railRadius,
          "shape-rendering": "crispEdges"
        }).call(Color2.stroke, sliderOpts.bordercolor).call(Color2.fill, sliderOpts.bgcolor).style("stroke-width", sliderOpts.borderwidth + "px");
        Drawing.setTranslate(
          rect,
          constants.railInset,
          (dims.inputAreaWidth - constants.railWidth) * 0.5 + dims.currentValueTotalHeight
        );
      }
    }
  });

  // src/components/sliders/index.js
  var require_sliders = __commonJS({
    "src/components/sliders/index.js"(exports, module) {
      "use strict";
      var constants = require_constants11();
      module.exports = {
        moduleType: "component",
        name: constants.name,
        layoutAttributes: require_attributes19(),
        supplyLayoutDefaults: require_defaults15(),
        draw: require_draw8()
      };
    }
  });

  // src/components/rangeslider/attributes.js
  var require_attributes20 = __commonJS({
    "src/components/rangeslider/attributes.js"(exports, module) {
      "use strict";
      var colorAttributes = require_attributes3();
      module.exports = {
        bgcolor: {
          valType: "color",
          dflt: colorAttributes.background,
          editType: "plot"
        },
        bordercolor: {
          valType: "color",
          dflt: colorAttributes.defaultLine,
          editType: "plot"
        },
        borderwidth: {
          valType: "integer",
          dflt: 0,
          min: 0,
          editType: "plot"
        },
        autorange: {
          valType: "boolean",
          dflt: true,
          editType: "calc",
          impliedEdits: { "range[0]": void 0, "range[1]": void 0 }
        },
        range: {
          valType: "info_array",
          items: [
            { valType: "any", editType: "calc", impliedEdits: { "^autorange": false } },
            { valType: "any", editType: "calc", impliedEdits: { "^autorange": false } }
          ],
          editType: "calc",
          impliedEdits: { autorange: false }
        },
        thickness: {
          valType: "number",
          dflt: 0.15,
          min: 0,
          max: 1,
          editType: "plot"
        },
        visible: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        },
        editType: "calc"
      };
    }
  });

  // src/components/rangeslider/oppaxis_attributes.js
  var require_oppaxis_attributes = __commonJS({
    "src/components/rangeslider/oppaxis_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        // not really a 'subplot' attribute container,
        // but this is the flag we use to denote attributes that
        // support yaxis, yaxis2, yaxis3, ... counters
        _isSubplotObj: true,
        rangemode: {
          valType: "enumerated",
          values: ["auto", "fixed", "match"],
          dflt: "match",
          editType: "calc"
        },
        range: {
          valType: "info_array",
          items: [
            { valType: "any", editType: "plot" },
            { valType: "any", editType: "plot" }
          ],
          editType: "plot"
        },
        editType: "calc"
      };
    }
  });

  // src/components/rangeslider/constants.js
  var require_constants12 = __commonJS({
    "src/components/rangeslider/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // attribute container name
        name: "rangeslider",
        // class names
        containerClassName: "rangeslider-container",
        bgClassName: "rangeslider-bg",
        rangePlotClassName: "rangeslider-rangeplot",
        maskMinClassName: "rangeslider-mask-min",
        maskMaxClassName: "rangeslider-mask-max",
        slideBoxClassName: "rangeslider-slidebox",
        grabberMinClassName: "rangeslider-grabber-min",
        grabAreaMinClassName: "rangeslider-grabarea-min",
        handleMinClassName: "rangeslider-handle-min",
        grabberMaxClassName: "rangeslider-grabber-max",
        grabAreaMaxClassName: "rangeslider-grabarea-max",
        handleMaxClassName: "rangeslider-handle-max",
        maskMinOppAxisClassName: "rangeslider-mask-min-opp-axis",
        maskMaxOppAxisClassName: "rangeslider-mask-max-opp-axis",
        // style constants
        maskColor: "rgba(0,0,0,0.4)",
        maskOppAxisColor: "rgba(0,0,0,0.2)",
        slideBoxFill: "transparent",
        slideBoxCursor: "ew-resize",
        grabAreaFill: "transparent",
        grabAreaCursor: "col-resize",
        grabAreaWidth: 10,
        handleWidth: 4,
        handleRadius: 1,
        handleStrokeWidth: 1,
        extraPad: 15
      };
    }
  });

  // src/components/rangeslider/helpers.js
  var require_helpers11 = __commonJS({
    "src/components/rangeslider/helpers.js"(exports) {
      "use strict";
      var axisIDs = require_axis_ids();
      var svgTextUtils = require_svg_text_utils();
      var constants = require_constants12();
      var LINE_SPACING = require_alignment().LINE_SPACING;
      var name2 = constants.name;
      function isVisible(ax) {
        var rangeSlider = ax && ax[name2];
        return rangeSlider && rangeSlider.visible;
      }
      exports.isVisible = isVisible;
      exports.makeData = function(fullLayout) {
        var axes = axisIDs.list({ _fullLayout: fullLayout }, "x", true);
        var margin = fullLayout.margin;
        var rangeSliderData = [];
        for (var i = 0; i < axes.length; i++) {
          var ax = axes[i];
          if (isVisible(ax)) {
            rangeSliderData.push(ax);
            var opts = ax[name2];
            opts._id = name2 + ax._id;
            opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness;
            opts._offsetShift = Math.floor(opts.borderwidth / 2);
          }
        }
        fullLayout._rangeSliderData = rangeSliderData;
      };
      exports.autoMarginOpts = function(gd, ax) {
        var fullLayout = gd._fullLayout;
        var opts = ax[name2];
        var axLetter = ax._id.charAt(0);
        var bottomDepth = 0;
        var titleHeight = 0;
        if (ax.side === "bottom") {
          bottomDepth = ax._depth;
          if (ax.title.text !== fullLayout._dfltTitle[axLetter]) {
            titleHeight = 1.5 * ax.title.font.size + 10 + opts._offsetShift;
            var extraLines = (ax.title.text.match(svgTextUtils.BR_TAG_ALL) || []).length;
            titleHeight += extraLines * ax.title.font.size * LINE_SPACING;
          }
        }
        return {
          x: 0,
          y: ax._counterDomainMin,
          l: 0,
          r: 0,
          t: 0,
          b: opts._height + bottomDepth + Math.max(fullLayout.margin.b, titleHeight),
          pad: constants.extraPad + opts._offsetShift * 2
        };
      };
    }
  });

  // src/components/rangeslider/defaults.js
  var require_defaults16 = __commonJS({
    "src/components/rangeslider/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Template = require_plot_template();
      var axisIds = require_axis_ids();
      var attributes = require_attributes20();
      var oppAxisAttrs = require_oppaxis_attributes();
      module.exports = function handleDefaults(layoutIn, layoutOut, axName) {
        var axIn = layoutIn[axName];
        var axOut = layoutOut[axName];
        if (!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return;
        if (!Lib.isPlainObject(axIn.rangeslider)) {
          axIn.rangeslider = {};
        }
        var containerIn = axIn.rangeslider;
        var containerOut = Template.newContainer(axOut, "rangeslider");
        function coerce(attr, dflt) {
          return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
        }
        var rangeContainerIn, rangeContainerOut;
        function coerceRange(attr, dflt) {
          return Lib.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs, attr, dflt);
        }
        var visible = coerce("visible");
        if (!visible) return;
        coerce("bgcolor", layoutOut.plot_bgcolor);
        coerce("bordercolor");
        coerce("borderwidth");
        coerce("thickness");
        coerce("autorange", !axOut.isValidRange(containerIn.range));
        coerce("range");
        var subplots = layoutOut._subplots;
        if (subplots) {
          var yIds = subplots.cartesian.filter(function(subplotId) {
            return subplotId.slice(0, Math.max(0, subplotId.indexOf("y"))) === axisIds.name2id(axName);
          }).map(function(subplotId) {
            return subplotId.slice(subplotId.indexOf("y"), subplotId.length);
          });
          var yNames = Lib.simpleMap(yIds, axisIds.id2name);
          for (var i = 0; i < yNames.length; i++) {
            var yName = yNames[i];
            rangeContainerIn = containerIn[yName] || {};
            rangeContainerOut = Template.newContainer(containerOut, yName, "yaxis");
            var yAxOut = layoutOut[yName];
            var rangemodeDflt;
            if (rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) {
              rangemodeDflt = "fixed";
            }
            var rangeMode = coerceRange("rangemode", rangemodeDflt);
            if (rangeMode !== "match") {
              coerceRange("range", yAxOut.range.slice());
            }
          }
        }
        containerOut._input = containerIn;
      };
    }
  });

  // src/components/rangeslider/calc_autorange.js
  var require_calc_autorange3 = __commonJS({
    "src/components/rangeslider/calc_autorange.js"(exports, module) {
      "use strict";
      var listAxes = require_axis_ids().list;
      var getAutoRange = require_autorange().getAutoRange;
      var constants = require_constants12();
      module.exports = function calcAutorange(gd) {
        var axes = listAxes(gd, "x", true);
        for (var i = 0; i < axes.length; i++) {
          var ax = axes[i];
          var opts = ax[constants.name];
          if (opts && opts.visible && opts.autorange) {
            opts._input.autorange = true;
            opts._input.range = opts.range = getAutoRange(gd, ax);
          }
        }
      };
    }
  });

  // src/components/rangeslider/draw.js
  var require_draw9 = __commonJS({
    "src/components/rangeslider/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Plots = require_plots();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var Drawing = require_drawing();
      var Color2 = require_color();
      var Titles = require_titles();
      var Cartesian = require_cartesian();
      var axisIDs = require_axis_ids();
      var dragElement = require_dragelement();
      var setCursor = require_setcursor();
      var constants = require_constants12();
      module.exports = function(gd) {
        var fullLayout = gd._fullLayout;
        var rangeSliderData = fullLayout._rangeSliderData;
        for (var i = 0; i < rangeSliderData.length; i++) {
          var opts = rangeSliderData[i][constants.name];
          opts._clipId = opts._id + "-" + fullLayout._uid;
        }
        function keyFunction(axisOpts) {
          return axisOpts._name;
        }
        var rangeSliders = fullLayout._infolayer.selectAll("g." + constants.containerClassName).data(rangeSliderData, keyFunction);
        rangeSliders.exit().each(function(axisOpts) {
          var opts2 = axisOpts[constants.name];
          fullLayout._topdefs.select("#" + opts2._clipId).remove();
        }).remove();
        if (rangeSliderData.length === 0) return;
        rangeSliders.enter().append("g").classed(constants.containerClassName, true).attr("pointer-events", "all");
        rangeSliders.each(function(axisOpts) {
          var rangeSlider = d3.select(this);
          var opts2 = axisOpts[constants.name];
          var oppAxisOpts = fullLayout[axisIDs.id2name(axisOpts.anchor)];
          var oppAxisRangeOpts = opts2[axisIDs.id2name(axisOpts.anchor)];
          if (opts2.range) {
            var rng = Lib.simpleMap(opts2.range, axisOpts.r2l);
            var axRng = Lib.simpleMap(axisOpts.range, axisOpts.r2l);
            var newRng;
            if (axRng[0] < axRng[1]) {
              newRng = [
                Math.min(rng[0], axRng[0]),
                Math.max(rng[1], axRng[1])
              ];
            } else {
              newRng = [
                Math.max(rng[0], axRng[0]),
                Math.min(rng[1], axRng[1])
              ];
            }
            opts2.range = opts2._input.range = Lib.simpleMap(newRng, axisOpts.l2r);
          }
          axisOpts.cleanRange("rangeslider.range");
          var gs = fullLayout._size;
          var domain = axisOpts.domain;
          opts2._width = gs.w * (domain[1] - domain[0]);
          var x = Math.round(gs.l + gs.w * domain[0]);
          var y = Math.round(
            gs.t + gs.h * (1 - axisOpts._counterDomainMin) + (axisOpts.side === "bottom" ? axisOpts._depth : 0) + opts2._offsetShift + constants.extraPad
          );
          rangeSlider.attr("transform", strTranslate(x, y));
          opts2._rl = Lib.simpleMap(opts2.range, axisOpts.r2l);
          var rl0 = opts2._rl[0];
          var rl1 = opts2._rl[1];
          var drl = rl1 - rl0;
          opts2.p2d = function(v) {
            return v / opts2._width * drl + rl0;
          };
          opts2.d2p = function(v) {
            return (v - rl0) / drl * opts2._width;
          };
          if (axisOpts.rangebreaks) {
            var rsBreaks = axisOpts.locateBreaks(rl0, rl1);
            if (rsBreaks.length) {
              var j, brk;
              var lBreaks = 0;
              for (j = 0; j < rsBreaks.length; j++) {
                brk = rsBreaks[j];
                lBreaks += brk.max - brk.min;
              }
              var m2 = opts2._width / (rl1 - rl0 - lBreaks);
              var _B = [-m2 * rl0];
              for (j = 0; j < rsBreaks.length; j++) {
                brk = rsBreaks[j];
                _B.push(_B[_B.length - 1] - m2 * (brk.max - brk.min));
              }
              opts2.d2p = function(v) {
                var b = _B[0];
                for (var j2 = 0; j2 < rsBreaks.length; j2++) {
                  var brk2 = rsBreaks[j2];
                  if (v >= brk2.max) b = _B[j2 + 1];
                  else if (v < brk2.min) break;
                }
                return b + m2 * v;
              };
              for (j = 0; j < rsBreaks.length; j++) {
                brk = rsBreaks[j];
                brk.pmin = opts2.d2p(brk.min);
                brk.pmax = opts2.d2p(brk.max);
              }
              opts2.p2d = function(v) {
                var b = _B[0];
                for (var j2 = 0; j2 < rsBreaks.length; j2++) {
                  var brk2 = rsBreaks[j2];
                  if (v >= brk2.pmax) b = _B[j2 + 1];
                  else if (v < brk2.pmin) break;
                }
                return (v - b) / m2;
              };
            }
          }
          if (oppAxisRangeOpts.rangemode !== "match") {
            var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]);
            var range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]);
            var distOppAxis = range1OppAxis - range0OppAxis;
            opts2.d2pOppAxis = function(v) {
              return (v - range0OppAxis) / distOppAxis * opts2._height;
            };
          }
          rangeSlider.call(drawBg, gd, axisOpts, opts2).call(addClipPath, gd, axisOpts, opts2).call(drawRangePlot, gd, axisOpts, opts2).call(drawMasks, gd, axisOpts, opts2, oppAxisRangeOpts).call(drawSlideBox, gd, axisOpts, opts2).call(drawGrabbers, gd, axisOpts, opts2);
          setupDragElement(rangeSlider, gd, axisOpts, opts2);
          setPixelRange(rangeSlider, gd, axisOpts, opts2, oppAxisOpts, oppAxisRangeOpts);
          if (axisOpts.side === "bottom") {
            Titles.draw(gd, axisOpts._id + "title", {
              propContainer: axisOpts,
              propName: axisOpts._name + ".title.text",
              placeholder: fullLayout._dfltTitle.x,
              attributes: {
                x: axisOpts._offset + axisOpts._length / 2,
                y: y + opts2._height + opts2._offsetShift + 10 + 1.5 * axisOpts.title.font.size,
                "text-anchor": "middle"
              }
            });
          }
        });
      };
      function eventX(event) {
        if (typeof event.clientX === "number") {
          return event.clientX;
        }
        if (event.touches && event.touches.length > 0) {
          return event.touches[0].clientX;
        }
        return 0;
      }
      function setupDragElement(rangeSlider, gd, axisOpts, opts) {
        if (gd._context.staticPlot) return;
        var slideBox = rangeSlider.select("rect." + constants.slideBoxClassName).node();
        var grabAreaMin = rangeSlider.select("rect." + constants.grabAreaMinClassName).node();
        var grabAreaMax = rangeSlider.select("rect." + constants.grabAreaMaxClassName).node();
        function mouseDownHandler() {
          var event = d3.event;
          var target = event.target;
          var startX = eventX(event);
          var offsetX = startX - rangeSlider.node().getBoundingClientRect().left;
          var minVal = opts.d2p(axisOpts._rl[0]);
          var maxVal = opts.d2p(axisOpts._rl[1]);
          var dragCover = dragElement.coverSlip();
          this.addEventListener("touchmove", mouseMove);
          this.addEventListener("touchend", mouseUp);
          dragCover.addEventListener("mousemove", mouseMove);
          dragCover.addEventListener("mouseup", mouseUp);
          function mouseMove(e) {
            var clientX = eventX(e);
            var delta = +clientX - startX;
            var pixelMin, pixelMax, cursor;
            switch (target) {
              case slideBox:
                cursor = "ew-resize";
                if (minVal + delta > axisOpts._length || maxVal + delta < 0) {
                  return;
                }
                pixelMin = minVal + delta;
                pixelMax = maxVal + delta;
                break;
              case grabAreaMin:
                cursor = "col-resize";
                if (minVal + delta > axisOpts._length) {
                  return;
                }
                pixelMin = minVal + delta;
                pixelMax = maxVal;
                break;
              case grabAreaMax:
                cursor = "col-resize";
                if (maxVal + delta < 0) {
                  return;
                }
                pixelMin = minVal;
                pixelMax = maxVal + delta;
                break;
              default:
                cursor = "ew-resize";
                pixelMin = offsetX;
                pixelMax = offsetX + delta;
                break;
            }
            if (pixelMax < pixelMin) {
              var tmp = pixelMax;
              pixelMax = pixelMin;
              pixelMin = tmp;
            }
            opts._pixelMin = pixelMin;
            opts._pixelMax = pixelMax;
            setCursor(d3.select(dragCover), cursor);
            setDataRange(rangeSlider, gd, axisOpts, opts);
          }
          function mouseUp() {
            dragCover.removeEventListener("mousemove", mouseMove);
            dragCover.removeEventListener("mouseup", mouseUp);
            this.removeEventListener("touchmove", mouseMove);
            this.removeEventListener("touchend", mouseUp);
            Lib.removeElement(dragCover);
          }
        }
        rangeSlider.on("mousedown", mouseDownHandler);
        rangeSlider.on("touchstart", mouseDownHandler);
      }
      function setDataRange(rangeSlider, gd, axisOpts, opts) {
        function clamp(v) {
          return axisOpts.l2r(Lib.constrain(v, opts._rl[0], opts._rl[1]));
        }
        var dataMin = clamp(opts.p2d(opts._pixelMin));
        var dataMax = clamp(opts.p2d(opts._pixelMax));
        window.requestAnimationFrame(function() {
          Registry.call("_guiRelayout", gd, axisOpts._name + ".range", [dataMin, dataMax]);
        });
      }
      function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) {
        var hw2 = constants.handleWidth / 2;
        function clamp(v) {
          return Lib.constrain(v, 0, opts._width);
        }
        function clampOppAxis(v) {
          return Lib.constrain(v, 0, opts._height);
        }
        function clampHandle(v) {
          return Lib.constrain(v, -hw2, opts._width + hw2);
        }
        var pixelMin = clamp(opts.d2p(axisOpts._rl[0]));
        var pixelMax = clamp(opts.d2p(axisOpts._rl[1]));
        rangeSlider.select("rect." + constants.slideBoxClassName).attr("x", pixelMin).attr("width", pixelMax - pixelMin);
        rangeSlider.select("rect." + constants.maskMinClassName).attr("width", pixelMin);
        rangeSlider.select("rect." + constants.maskMaxClassName).attr("x", pixelMax).attr("width", opts._width - pixelMax);
        if (oppAxisRangeOpts.rangemode !== "match") {
          var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1]));
          var pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0]));
          rangeSlider.select("rect." + constants.maskMinOppAxisClassName).attr("x", pixelMin).attr("height", pixelMinOppAxis).attr("width", pixelMax - pixelMin);
          rangeSlider.select("rect." + constants.maskMaxOppAxisClassName).attr("x", pixelMin).attr("y", pixelMaxOppAxis).attr("height", opts._height - pixelMaxOppAxis).attr("width", pixelMax - pixelMin);
          rangeSlider.select("rect." + constants.slideBoxClassName).attr("y", pixelMinOppAxis).attr("height", pixelMaxOppAxis - pixelMinOppAxis);
        }
        var offset = 0.5;
        var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset;
        var xMax = Math.round(clampHandle(pixelMax - hw2)) + offset;
        rangeSlider.select("g." + constants.grabberMinClassName).attr("transform", strTranslate(xMin, offset));
        rangeSlider.select("g." + constants.grabberMaxClassName).attr("transform", strTranslate(xMax, offset));
      }
      function drawBg(rangeSlider, gd, axisOpts, opts) {
        var bg = Lib.ensureSingle(rangeSlider, "rect", constants.bgClassName, function(s) {
          s.attr({
            x: 0,
            y: 0,
            "shape-rendering": "crispEdges"
          });
        });
        var borderCorrect = opts.borderwidth % 2 === 0 ? opts.borderwidth : opts.borderwidth - 1;
        var offsetShift = -opts._offsetShift;
        var lw = Drawing.crispRound(gd, opts.borderwidth);
        bg.attr({
          width: opts._width + borderCorrect,
          height: opts._height + borderCorrect,
          transform: strTranslate(offsetShift, offsetShift),
          "stroke-width": lw
        }).call(Color2.stroke, opts.bordercolor).call(Color2.fill, opts.bgcolor);
      }
      function addClipPath(rangeSlider, gd, axisOpts, opts) {
        var fullLayout = gd._fullLayout;
        var clipPath = Lib.ensureSingleById(fullLayout._topdefs, "clipPath", opts._clipId, function(s) {
          s.append("rect").attr({ x: 0, y: 0 });
        });
        clipPath.select("rect").attr({
          width: opts._width,
          height: opts._height
        });
      }
      function drawRangePlot(rangeSlider, gd, axisOpts, opts) {
        var calcData = gd.calcdata;
        var rangePlots = rangeSlider.selectAll("g." + constants.rangePlotClassName).data(axisOpts._subplotsWith, Lib.identity);
        rangePlots.enter().append("g").attr("class", function(id) {
          return constants.rangePlotClassName + " " + id;
        }).call(Drawing.setClipUrl, opts._clipId, gd);
        rangePlots.order();
        rangePlots.exit().remove();
        var mainplotinfo;
        rangePlots.each(function(id, i) {
          var plotgroup = d3.select(this);
          var isMainPlot = i === 0;
          var oppAxisOpts = axisIDs.getFromId(gd, id, "y");
          var oppAxisName = oppAxisOpts._name;
          var oppAxisRangeOpts = opts[oppAxisName];
          var mockFigure = {
            data: [],
            layout: {
              xaxis: {
                type: axisOpts.type,
                domain: [0, 1],
                range: opts.range.slice(),
                calendar: axisOpts.calendar
              },
              width: opts._width,
              height: opts._height,
              margin: { t: 0, b: 0, l: 0, r: 0 }
            },
            _context: gd._context
          };
          if (axisOpts.rangebreaks) {
            mockFigure.layout.xaxis.rangebreaks = axisOpts.rangebreaks;
          }
          mockFigure.layout[oppAxisName] = {
            type: oppAxisOpts.type,
            domain: [0, 1],
            range: oppAxisRangeOpts.rangemode !== "match" ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(),
            calendar: oppAxisOpts.calendar
          };
          if (oppAxisOpts.rangebreaks) {
            mockFigure.layout[oppAxisName].rangebreaks = oppAxisOpts.rangebreaks;
          }
          Plots.supplyDefaults(mockFigure);
          var xa = mockFigure._fullLayout.xaxis;
          var ya = mockFigure._fullLayout[oppAxisName];
          xa.clearCalc();
          xa.setScale();
          ya.clearCalc();
          ya.setScale();
          var plotinfo = {
            id,
            plotgroup,
            xaxis: xa,
            yaxis: ya,
            isRangePlot: true
          };
          if (isMainPlot) mainplotinfo = plotinfo;
          else {
            plotinfo.mainplot = "xy";
            plotinfo.mainplotinfo = mainplotinfo;
          }
          Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id));
        });
      }
      function filterRangePlotCalcData(calcData, subplotId) {
        var out = [];
        for (var i = 0; i < calcData.length; i++) {
          var calcTrace = calcData[i];
          var trace = calcTrace[0].trace;
          if (trace.xaxis + trace.yaxis === subplotId) {
            out.push(calcTrace);
          }
        }
        return out;
      }
      function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) {
        var maskMin = Lib.ensureSingle(rangeSlider, "rect", constants.maskMinClassName, function(s) {
          s.attr({
            x: 0,
            y: 0,
            "shape-rendering": "crispEdges"
          });
        });
        maskMin.attr("height", opts._height).call(Color2.fill, constants.maskColor);
        var maskMax = Lib.ensureSingle(rangeSlider, "rect", constants.maskMaxClassName, function(s) {
          s.attr({
            y: 0,
            "shape-rendering": "crispEdges"
          });
        });
        maskMax.attr("height", opts._height).call(Color2.fill, constants.maskColor);
        if (oppAxisRangeOpts.rangemode !== "match") {
          var maskMinOppAxis = Lib.ensureSingle(rangeSlider, "rect", constants.maskMinOppAxisClassName, function(s) {
            s.attr({
              y: 0,
              "shape-rendering": "crispEdges"
            });
          });
          maskMinOppAxis.attr("width", opts._width).call(Color2.fill, constants.maskOppAxisColor);
          var maskMaxOppAxis = Lib.ensureSingle(rangeSlider, "rect", constants.maskMaxOppAxisClassName, function(s) {
            s.attr({
              y: 0,
              "shape-rendering": "crispEdges"
            });
          });
          maskMaxOppAxis.attr("width", opts._width).style("border-top", constants.maskOppBorder).call(Color2.fill, constants.maskOppAxisColor);
        }
      }
      function drawSlideBox(rangeSlider, gd, axisOpts, opts) {
        if (gd._context.staticPlot) return;
        var slideBox = Lib.ensureSingle(rangeSlider, "rect", constants.slideBoxClassName, function(s) {
          s.attr({
            y: 0,
            cursor: constants.slideBoxCursor,
            "shape-rendering": "crispEdges"
          });
        });
        slideBox.attr({
          height: opts._height,
          fill: constants.slideBoxFill
        });
      }
      function drawGrabbers(rangeSlider, gd, axisOpts, opts) {
        var grabberMin = Lib.ensureSingle(rangeSlider, "g", constants.grabberMinClassName);
        var grabberMax = Lib.ensureSingle(rangeSlider, "g", constants.grabberMaxClassName);
        var handleFixAttrs = {
          x: 0,
          width: constants.handleWidth,
          rx: constants.handleRadius,
          fill: Color2.background,
          stroke: Color2.defaultLine,
          "stroke-width": constants.handleStrokeWidth,
          "shape-rendering": "crispEdges"
        };
        var handleDynamicAttrs = {
          y: Math.round(opts._height / 4),
          height: Math.round(opts._height / 2)
        };
        var handleMin = Lib.ensureSingle(grabberMin, "rect", constants.handleMinClassName, function(s) {
          s.attr(handleFixAttrs);
        });
        handleMin.attr(handleDynamicAttrs);
        var handleMax = Lib.ensureSingle(grabberMax, "rect", constants.handleMaxClassName, function(s) {
          s.attr(handleFixAttrs);
        });
        handleMax.attr(handleDynamicAttrs);
        var grabAreaFixAttrs = {
          width: constants.grabAreaWidth,
          x: 0,
          y: 0,
          fill: constants.grabAreaFill,
          cursor: !gd._context.staticPlot ? constants.grabAreaCursor : void 0
        };
        var grabAreaMin = Lib.ensureSingle(grabberMin, "rect", constants.grabAreaMinClassName, function(s) {
          s.attr(grabAreaFixAttrs);
        });
        grabAreaMin.attr("height", opts._height);
        var grabAreaMax = Lib.ensureSingle(grabberMax, "rect", constants.grabAreaMaxClassName, function(s) {
          s.attr(grabAreaFixAttrs);
        });
        grabAreaMax.attr("height", opts._height);
      }
    }
  });

  // src/components/rangeslider/index.js
  var require_rangeslider = __commonJS({
    "src/components/rangeslider/index.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attrs = require_attributes20();
      var oppAxisAttrs = require_oppaxis_attributes();
      var helpers = require_helpers11();
      module.exports = {
        moduleType: "component",
        name: "rangeslider",
        schema: {
          subplots: {
            xaxis: {
              rangeslider: Lib.extendFlat({}, attrs, {
                yaxis: oppAxisAttrs
              })
            }
          }
        },
        layoutAttributes: require_attributes20(),
        handleDefaults: require_defaults16(),
        calcAutorange: require_calc_autorange3(),
        draw: require_draw9(),
        isVisible: helpers.isVisible,
        makeData: helpers.makeData,
        autoMarginOpts: helpers.autoMarginOpts
      };
    }
  });

  // src/components/rangeselector/attributes.js
  var require_attributes21 = __commonJS({
    "src/components/rangeselector/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var colorAttrs = require_attributes3();
      var templatedArray = require_plot_template().templatedArray;
      var buttonAttrs = templatedArray("button", {
        visible: {
          valType: "boolean",
          dflt: true,
          editType: "plot"
        },
        step: {
          valType: "enumerated",
          values: ["month", "year", "day", "hour", "minute", "second", "all"],
          dflt: "month",
          editType: "plot"
        },
        stepmode: {
          valType: "enumerated",
          values: ["backward", "todate"],
          dflt: "backward",
          editType: "plot"
        },
        count: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "plot"
        },
        label: {
          valType: "string",
          editType: "plot"
        },
        editType: "plot"
      });
      module.exports = {
        visible: {
          valType: "boolean",
          editType: "plot"
        },
        buttons: buttonAttrs,
        x: {
          valType: "number",
          min: -2,
          max: 3,
          editType: "plot"
        },
        xanchor: {
          valType: "enumerated",
          values: ["auto", "left", "center", "right"],
          dflt: "left",
          editType: "plot"
        },
        y: {
          valType: "number",
          min: -2,
          max: 3,
          editType: "plot"
        },
        yanchor: {
          valType: "enumerated",
          values: ["auto", "top", "middle", "bottom"],
          dflt: "bottom",
          editType: "plot"
        },
        font: fontAttrs({
          editType: "plot"
        }),
        bgcolor: {
          valType: "color",
          dflt: colorAttrs.lightLine,
          editType: "plot"
        },
        activecolor: {
          valType: "color",
          editType: "plot"
        },
        bordercolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "plot"
        },
        borderwidth: {
          valType: "number",
          min: 0,
          dflt: 0,
          editType: "plot"
        },
        editType: "plot"
      };
    }
  });

  // src/components/rangeselector/constants.js
  var require_constants13 = __commonJS({
    "src/components/rangeselector/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // 'y' position pad above counter axis domain
        yPad: 0.02,
        // minimum button width (regardless of text size)
        minButtonWidth: 30,
        // buttons rect radii
        rx: 3,
        ry: 3,
        // light fraction used to compute the 'activecolor' default
        lightAmount: 25,
        darkAmount: 10
      };
    }
  });

  // src/components/rangeselector/defaults.js
  var require_defaults17 = __commonJS({
    "src/components/rangeselector/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var Template = require_plot_template();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes21();
      var constants = require_constants13();
      module.exports = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) {
        var selectorIn = containerIn.rangeselector || {};
        var selectorOut = Template.newContainer(containerOut, "rangeselector");
        function coerce(attr, dflt) {
          return Lib.coerce(selectorIn, selectorOut, attributes, attr, dflt);
        }
        var buttons = handleArrayContainerDefaults(selectorIn, selectorOut, {
          name: "buttons",
          handleItemDefaults: buttonDefaults,
          calendar
        });
        var visible = coerce("visible", buttons.length > 0);
        if (visible) {
          var posDflt = getPosDflt(containerOut, layout, counterAxes);
          coerce("x", posDflt[0]);
          coerce("y", posDflt[1]);
          Lib.noneOrAll(containerIn, containerOut, ["x", "y"]);
          coerce("xanchor");
          coerce("yanchor");
          Lib.coerceFont(coerce, "font", layout.font);
          var bgColor = coerce("bgcolor");
          coerce("activecolor", Color2.contrast(bgColor, constants.lightAmount, constants.darkAmount));
          coerce("bordercolor");
          coerce("borderwidth");
        }
      };
      function buttonDefaults(buttonIn, buttonOut, selectorOut, opts) {
        var calendar = opts.calendar;
        function coerce(attr, dflt) {
          return Lib.coerce(buttonIn, buttonOut, attributes.buttons, attr, dflt);
        }
        var visible = coerce("visible");
        if (visible) {
          var step = coerce("step");
          if (step !== "all") {
            if (calendar && calendar !== "gregorian" && (step === "month" || step === "year")) {
              buttonOut.stepmode = "backward";
            } else {
              coerce("stepmode");
            }
            coerce("count");
          }
          coerce("label");
        }
      }
      function getPosDflt(containerOut, layout, counterAxes) {
        var anchoredList = counterAxes.filter(function(ax) {
          return layout[ax].anchor === containerOut._id;
        });
        var posY = 0;
        for (var i = 0; i < anchoredList.length; i++) {
          var domain = layout[anchoredList[i]].domain;
          if (domain) posY = Math.max(domain[1], posY);
        }
        return [containerOut.domain[0], posY + constants.yPad];
      }
    }
  });

  // src/components/rangeselector/get_update_object.js
  var require_get_update_object = __commonJS({
    "src/components/rangeselector/get_update_object.js"(exports, module) {
      "use strict";
      var d3Time = require_d3_time();
      var titleCase = require_lib().titleCase;
      module.exports = function getUpdateObject(axisLayout, buttonLayout) {
        var axName = axisLayout._name;
        var update = {};
        if (buttonLayout.step === "all") {
          update[axName + ".autorange"] = true;
        } else {
          var xrange = getXRange(axisLayout, buttonLayout);
          update[axName + ".range[0]"] = xrange[0];
          update[axName + ".range[1]"] = xrange[1];
        }
        return update;
      };
      function getXRange(axisLayout, buttonLayout) {
        var currentRange = axisLayout.range;
        var base = new Date(axisLayout.r2l(currentRange[1]));
        var step = buttonLayout.step;
        var utcStep = d3Time["utc" + titleCase(step)];
        var count = buttonLayout.count;
        var range0;
        switch (buttonLayout.stepmode) {
          case "backward":
            range0 = axisLayout.l2r(+utcStep.offset(base, -count));
            break;
          case "todate":
            var base2 = utcStep.offset(base, -count);
            range0 = axisLayout.l2r(+utcStep.ceil(base2));
            break;
        }
        var range1 = currentRange[1];
        return [range0, range1];
      }
    }
  });

  // src/components/rangeselector/draw.js
  var require_draw10 = __commonJS({
    "src/components/rangeselector/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var Plots = require_plots();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var axisIds = require_axis_ids();
      var alignmentConstants = require_alignment();
      var LINE_SPACING = alignmentConstants.LINE_SPACING;
      var FROM_TL = alignmentConstants.FROM_TL;
      var FROM_BR = alignmentConstants.FROM_BR;
      var constants = require_constants13();
      var getUpdateObject = require_get_update_object();
      module.exports = function draw(gd) {
        var fullLayout = gd._fullLayout;
        var selectors = fullLayout._infolayer.selectAll(".rangeselector").data(makeSelectorData(gd), selectorKeyFunc);
        selectors.enter().append("g").classed("rangeselector", true);
        selectors.exit().remove();
        selectors.style({
          cursor: "pointer",
          "pointer-events": "all"
        });
        selectors.each(function(d) {
          var selector = d3.select(this);
          var axisLayout = d;
          var selectorLayout = axisLayout.rangeselector;
          var buttons = selector.selectAll("g.button").data(Lib.filterVisible(selectorLayout.buttons));
          buttons.enter().append("g").classed("button", true);
          buttons.exit().remove();
          buttons.each(function(d2) {
            var button = d3.select(this);
            var update = getUpdateObject(axisLayout, d2);
            d2._isActive = isActive(axisLayout, d2, update);
            button.call(drawButtonRect, selectorLayout, d2);
            button.call(drawButtonText, selectorLayout, d2, gd);
            button.on("click", function() {
              if (gd._dragged) return;
              Registry.call("_guiRelayout", gd, update);
            });
            button.on("mouseover", function() {
              d2._isHovered = true;
              button.call(drawButtonRect, selectorLayout, d2);
            });
            button.on("mouseout", function() {
              d2._isHovered = false;
              button.call(drawButtonRect, selectorLayout, d2);
            });
          });
          reposition(gd, buttons, selectorLayout, axisLayout._name, selector);
        });
      };
      function makeSelectorData(gd) {
        var axes = axisIds.list(gd, "x", true);
        var data = [];
        for (var i = 0; i < axes.length; i++) {
          var axis = axes[i];
          if (axis.rangeselector && axis.rangeselector.visible) {
            data.push(axis);
          }
        }
        return data;
      }
      function selectorKeyFunc(d) {
        return d._id;
      }
      function isActive(axisLayout, opts, update) {
        if (opts.step === "all") {
          return axisLayout.autorange === true;
        } else {
          var keys = Object.keys(update);
          return axisLayout.range[0] === update[keys[0]] && axisLayout.range[1] === update[keys[1]];
        }
      }
      function drawButtonRect(button, selectorLayout, d) {
        var rect = Lib.ensureSingle(button, "rect", "selector-rect", function(s) {
          s.attr("shape-rendering", "crispEdges");
        });
        rect.attr({
          rx: constants.rx,
          ry: constants.ry
        });
        rect.call(Color2.stroke, selectorLayout.bordercolor).call(Color2.fill, getFillColor(selectorLayout, d)).style("stroke-width", selectorLayout.borderwidth + "px");
      }
      function getFillColor(selectorLayout, d) {
        return d._isActive || d._isHovered ? selectorLayout.activecolor : selectorLayout.bgcolor;
      }
      function drawButtonText(button, selectorLayout, d, gd) {
        function textLayout(s) {
          svgTextUtils.convertToTspans(s, gd);
        }
        var text = Lib.ensureSingle(button, "text", "selector-text", function(s) {
          s.attr("text-anchor", "middle");
        });
        text.call(Drawing.font, selectorLayout.font).text(getLabel(d, gd._fullLayout._meta)).call(textLayout);
      }
      function getLabel(opts, _meta) {
        if (opts.label) {
          return _meta ? Lib.templateString(opts.label, _meta) : opts.label;
        }
        if (opts.step === "all") return "all";
        return opts.count + opts.step.charAt(0);
      }
      function reposition(gd, buttons, opts, axName, selector) {
        var width = 0;
        var height = 0;
        var borderWidth = opts.borderwidth;
        buttons.each(function() {
          var button = d3.select(this);
          var text = button.select(".selector-text");
          var tHeight = opts.font.size * LINE_SPACING;
          var hEff = Math.max(tHeight * svgTextUtils.lineCount(text), 16) + 3;
          height = Math.max(height, hEff);
        });
        buttons.each(function() {
          var button = d3.select(this);
          var rect = button.select(".selector-rect");
          var text = button.select(".selector-text");
          var tWidth = text.node() && Drawing.bBox(text.node()).width;
          var tHeight = opts.font.size * LINE_SPACING;
          var tLines = svgTextUtils.lineCount(text);
          var wEff = Math.max(tWidth + 10, constants.minButtonWidth);
          button.attr("transform", strTranslate(borderWidth + width, borderWidth));
          rect.attr({
            x: 0,
            y: 0,
            width: wEff,
            height
          });
          svgTextUtils.positionText(
            text,
            wEff / 2,
            height / 2 - (tLines - 1) * tHeight / 2 + 3
          );
          width += wEff + 5;
        });
        var graphSize = gd._fullLayout._size;
        var lx = graphSize.l + graphSize.w * opts.x;
        var ly = graphSize.t + graphSize.h * (1 - opts.y);
        var xanchor = "left";
        if (Lib.isRightAnchor(opts)) {
          lx -= width;
          xanchor = "right";
        }
        if (Lib.isCenterAnchor(opts)) {
          lx -= width / 2;
          xanchor = "center";
        }
        var yanchor = "top";
        if (Lib.isBottomAnchor(opts)) {
          ly -= height;
          yanchor = "bottom";
        }
        if (Lib.isMiddleAnchor(opts)) {
          ly -= height / 2;
          yanchor = "middle";
        }
        width = Math.ceil(width);
        height = Math.ceil(height);
        lx = Math.round(lx);
        ly = Math.round(ly);
        Plots.autoMargin(gd, axName + "-range-selector", {
          x: opts.x,
          y: opts.y,
          l: width * FROM_TL[xanchor],
          r: width * FROM_BR[xanchor],
          b: height * FROM_BR[yanchor],
          t: height * FROM_TL[yanchor]
        });
        selector.attr("transform", strTranslate(lx, ly));
      }
    }
  });

  // src/components/rangeselector/index.js
  var require_rangeselector = __commonJS({
    "src/components/rangeselector/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "component",
        name: "rangeselector",
        schema: {
          subplots: {
            xaxis: { rangeselector: require_attributes21() }
          }
        },
        layoutAttributes: require_attributes21(),
        handleDefaults: require_defaults17(),
        draw: require_draw10()
      };
    }
  });

  // src/plots/domain.js
  var require_domain = __commonJS({
    "src/plots/domain.js"(exports) {
      "use strict";
      var extendFlat = require_extend().extendFlat;
      exports.attributes = function(opts, extra) {
        opts = opts || {};
        extra = extra || {};
        var base = {
          valType: "info_array",
          editType: opts.editType,
          items: [
            { valType: "number", min: 0, max: 1, editType: opts.editType },
            { valType: "number", min: 0, max: 1, editType: opts.editType }
          ],
          dflt: [0, 1]
        };
        var namePart = opts.name ? opts.name + " " : "";
        var contPart = opts.trace ? "trace " : "subplot ";
        var descPart = extra.description ? " " + extra.description : "";
        var out = {
          x: extendFlat({}, base, {}),
          y: extendFlat({}, base, {}),
          editType: opts.editType
        };
        if (!opts.noGridCell) {
          out.row = {
            valType: "integer",
            min: 0,
            dflt: 0,
            editType: opts.editType
          };
          out.column = {
            valType: "integer",
            min: 0,
            dflt: 0,
            editType: opts.editType
          };
        }
        return out;
      };
      exports.defaults = function(containerOut, layout, coerce, dfltDomains) {
        var dfltX = dfltDomains && dfltDomains.x || [0, 1];
        var dfltY = dfltDomains && dfltDomains.y || [0, 1];
        var grid = layout.grid;
        if (grid) {
          var column = coerce("domain.column");
          if (column !== void 0) {
            if (column < grid.columns) dfltX = grid._domains.x[column];
            else delete containerOut.domain.column;
          }
          var row = coerce("domain.row");
          if (row !== void 0) {
            if (row < grid.rows) dfltY = grid._domains.y[row];
            else delete containerOut.domain.row;
          }
        }
        var x = coerce("domain.x", dfltX);
        var y = coerce("domain.y", dfltY);
        if (!(x[0] < x[1])) containerOut.domain.x = dfltX.slice();
        if (!(y[0] < y[1])) containerOut.domain.y = dfltY.slice();
      };
    }
  });

  // src/components/grid/index.js
  var require_grid = __commonJS({
    "src/components/grid/index.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var counterRegex = require_regex().counter;
      var domainAttrs = require_domain().attributes;
      var cartesianIdRegex = require_constants2().idRegex;
      var Template = require_plot_template();
      var gridAttrs = {
        rows: {
          valType: "integer",
          min: 1,
          editType: "plot"
        },
        roworder: {
          valType: "enumerated",
          values: ["top to bottom", "bottom to top"],
          dflt: "top to bottom",
          editType: "plot"
        },
        columns: {
          valType: "integer",
          min: 1,
          editType: "plot"
        },
        subplots: {
          valType: "info_array",
          freeLength: true,
          dimensions: 2,
          items: { valType: "enumerated", values: [counterRegex("xy").toString(), ""], editType: "plot" },
          editType: "plot"
        },
        xaxes: {
          valType: "info_array",
          freeLength: true,
          items: { valType: "enumerated", values: [cartesianIdRegex.x.toString(), ""], editType: "plot" },
          editType: "plot"
        },
        yaxes: {
          valType: "info_array",
          freeLength: true,
          items: { valType: "enumerated", values: [cartesianIdRegex.y.toString(), ""], editType: "plot" },
          editType: "plot"
        },
        pattern: {
          valType: "enumerated",
          values: ["independent", "coupled"],
          dflt: "coupled",
          editType: "plot"
        },
        xgap: {
          valType: "number",
          min: 0,
          max: 1,
          editType: "plot"
        },
        ygap: {
          valType: "number",
          min: 0,
          max: 1,
          editType: "plot"
        },
        domain: domainAttrs({ name: "grid", editType: "plot", noGridCell: true }, {}),
        xside: {
          valType: "enumerated",
          values: ["bottom", "bottom plot", "top plot", "top"],
          dflt: "bottom plot",
          editType: "plot"
        },
        yside: {
          valType: "enumerated",
          values: ["left", "left plot", "right plot", "right"],
          dflt: "left plot",
          editType: "plot"
        },
        editType: "plot"
      };
      function getAxes(layout, grid, axLetter) {
        var gridVal = grid[axLetter + "axes"];
        var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {});
        if (Array.isArray(gridVal)) return gridVal;
        if (splomVal.length) return splomVal;
      }
      function sizeDefaults(layoutIn, layoutOut) {
        var gridIn = layoutIn.grid || {};
        var xAxes = getAxes(layoutOut, gridIn, "x");
        var yAxes = getAxes(layoutOut, gridIn, "y");
        if (!layoutIn.grid && !xAxes && !yAxes) return;
        var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]);
        var hasXaxes = Array.isArray(xAxes);
        var hasYaxes = Array.isArray(yAxes);
        var isSplomGenerated = hasXaxes && xAxes !== gridIn.xaxes && hasYaxes && yAxes !== gridIn.yaxes;
        var dfltRows, dfltColumns;
        if (hasSubplotGrid) {
          dfltRows = gridIn.subplots.length;
          dfltColumns = gridIn.subplots[0].length;
        } else {
          if (hasYaxes) dfltRows = yAxes.length;
          if (hasXaxes) dfltColumns = xAxes.length;
        }
        var gridOut = Template.newContainer(layoutOut, "grid");
        function coerce(attr, dflt) {
          return Lib.coerce(gridIn, gridOut, gridAttrs, attr, dflt);
        }
        var rows = coerce("rows", dfltRows);
        var columns = coerce("columns", dfltColumns);
        if (!(rows * columns > 1)) {
          delete layoutOut.grid;
          return;
        }
        if (!hasSubplotGrid && !hasXaxes && !hasYaxes) {
          var useDefaultSubplots = coerce("pattern") === "independent";
          if (useDefaultSubplots) hasSubplotGrid = true;
        }
        gridOut._hasSubplotGrid = hasSubplotGrid;
        var rowOrder = coerce("roworder");
        var reversed = rowOrder === "top to bottom";
        var dfltGapX = hasSubplotGrid ? 0.2 : 0.1;
        var dfltGapY = hasSubplotGrid ? 0.3 : 0.1;
        var dfltSideX, dfltSideY;
        if (isSplomGenerated && layoutOut._splomGridDflt) {
          dfltSideX = layoutOut._splomGridDflt.xside;
          dfltSideY = layoutOut._splomGridDflt.yside;
        }
        gridOut._domains = {
          x: fillGridPositions("x", coerce, dfltGapX, dfltSideX, columns),
          y: fillGridPositions("y", coerce, dfltGapY, dfltSideY, rows, reversed)
        };
      }
      function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) {
        var dirGap = coerce(axLetter + "gap", dfltGap);
        var domain = coerce("domain." + axLetter);
        coerce(axLetter + "side", dfltSide);
        var out = new Array(len);
        var start = domain[0];
        var step = (domain[1] - start) / (len - dirGap);
        var cellDomain = step * (1 - dirGap);
        for (var i = 0; i < len; i++) {
          var cellStart = start + step * i;
          out[reversed ? len - 1 - i : i] = [cellStart, cellStart + cellDomain];
        }
        return out;
      }
      function contentDefaults(layoutIn, layoutOut) {
        var gridOut = layoutOut.grid;
        if (!gridOut || !gridOut._domains) return;
        var gridIn = layoutIn.grid || {};
        var subplots = layoutOut._subplots;
        var hasSubplotGrid = gridOut._hasSubplotGrid;
        var rows = gridOut.rows;
        var columns = gridOut.columns;
        var useDefaultSubplots = gridOut.pattern === "independent";
        var i, j, xId, yId, subplotId, subplotsOut, yPos;
        var axisMap = gridOut._axisMap = {};
        if (hasSubplotGrid) {
          var subplotsIn = gridIn.subplots || [];
          subplotsOut = gridOut.subplots = new Array(rows);
          var index = 1;
          for (i = 0; i < rows; i++) {
            var rowOut = subplotsOut[i] = new Array(columns);
            var rowIn = subplotsIn[i] || [];
            for (j = 0; j < columns; j++) {
              if (useDefaultSubplots) {
                subplotId = index === 1 ? "xy" : "x" + index + "y" + index;
                index++;
              } else subplotId = rowIn[j];
              rowOut[j] = "";
              if (subplots.cartesian.indexOf(subplotId) !== -1) {
                yPos = subplotId.indexOf("y");
                xId = subplotId.slice(0, yPos);
                yId = subplotId.slice(yPos);
                if (axisMap[xId] !== void 0 && axisMap[xId] !== j || axisMap[yId] !== void 0 && axisMap[yId] !== i) {
                  continue;
                }
                rowOut[j] = subplotId;
                axisMap[xId] = j;
                axisMap[yId] = i;
              }
            }
          }
        } else {
          var xAxes = getAxes(layoutOut, gridIn, "x");
          var yAxes = getAxes(layoutOut, gridIn, "y");
          gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, "x");
          gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, "y");
        }
        var anchors = gridOut._anchors = {};
        var reversed = gridOut.roworder === "top to bottom";
        for (var axisId in axisMap) {
          var axLetter = axisId.charAt(0);
          var side = gridOut[axLetter + "side"];
          var i0, inc, iFinal;
          if (side.length < 8) {
            anchors[axisId] = "free";
          } else if (axLetter === "x") {
            if (side.charAt(0) === "t" === reversed) {
              i0 = 0;
              inc = 1;
              iFinal = rows;
            } else {
              i0 = rows - 1;
              inc = -1;
              iFinal = -1;
            }
            if (hasSubplotGrid) {
              var column = axisMap[axisId];
              for (i = i0; i !== iFinal; i += inc) {
                subplotId = subplotsOut[i][column];
                if (!subplotId) continue;
                yPos = subplotId.indexOf("y");
                if (subplotId.slice(0, yPos) === axisId) {
                  anchors[axisId] = subplotId.slice(yPos);
                  break;
                }
              }
            } else {
              for (i = i0; i !== iFinal; i += inc) {
                yId = gridOut.yaxes[i];
                if (subplots.cartesian.indexOf(axisId + yId) !== -1) {
                  anchors[axisId] = yId;
                  break;
                }
              }
            }
          } else {
            if (side.charAt(0) === "l") {
              i0 = 0;
              inc = 1;
              iFinal = columns;
            } else {
              i0 = columns - 1;
              inc = -1;
              iFinal = -1;
            }
            if (hasSubplotGrid) {
              var row = axisMap[axisId];
              for (i = i0; i !== iFinal; i += inc) {
                subplotId = subplotsOut[row][i];
                if (!subplotId) continue;
                yPos = subplotId.indexOf("y");
                if (subplotId.slice(yPos) === axisId) {
                  anchors[axisId] = subplotId.slice(0, yPos);
                  break;
                }
              }
            } else {
              for (i = i0; i !== iFinal; i += inc) {
                xId = gridOut.xaxes[i];
                if (subplots.cartesian.indexOf(xId + axisId) !== -1) {
                  anchors[axisId] = xId;
                  break;
                }
              }
            }
          }
        }
      }
      function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) {
        var out = new Array(len);
        var i;
        function fillOneAxis(i2, axisId) {
          if (axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === void 0) {
            out[i2] = axisId;
            axisMap[axisId] = i2;
          } else out[i2] = "";
        }
        if (Array.isArray(axesIn)) {
          for (i = 0; i < len; i++) {
            fillOneAxis(i, axesIn[i]);
          }
        } else {
          fillOneAxis(0, axLetter);
          for (i = 1; i < len; i++) {
            fillOneAxis(i, axLetter + (i + 1));
          }
        }
        return out;
      }
      module.exports = {
        moduleType: "component",
        name: "grid",
        schema: {
          layout: { grid: gridAttrs }
        },
        layoutAttributes: gridAttrs,
        sizeDefaults,
        contentDefaults
      };
    }
  });

  // src/components/errorbars/attributes.js
  var require_attributes22 = __commonJS({
    "src/components/errorbars/attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        visible: {
          valType: "boolean",
          editType: "calc"
        },
        type: {
          valType: "enumerated",
          values: ["percent", "constant", "sqrt", "data"],
          editType: "calc"
        },
        symmetric: {
          valType: "boolean",
          editType: "calc"
        },
        array: {
          valType: "data_array",
          editType: "calc"
        },
        arrayminus: {
          valType: "data_array",
          editType: "calc"
        },
        value: {
          valType: "number",
          min: 0,
          dflt: 10,
          editType: "calc"
        },
        valueminus: {
          valType: "number",
          min: 0,
          dflt: 10,
          editType: "calc"
        },
        traceref: {
          valType: "integer",
          min: 0,
          dflt: 0,
          editType: "style"
        },
        tracerefminus: {
          valType: "integer",
          min: 0,
          dflt: 0,
          editType: "style"
        },
        copy_ystyle: {
          valType: "boolean",
          editType: "plot"
        },
        copy_zstyle: {
          valType: "boolean",
          editType: "style"
        },
        color: {
          valType: "color",
          editType: "style"
        },
        thickness: {
          valType: "number",
          min: 0,
          dflt: 2,
          editType: "style"
        },
        width: {
          valType: "number",
          min: 0,
          editType: "plot"
        },
        editType: "calc"
      };
    }
  });

  // src/components/errorbars/defaults.js
  var require_defaults18 = __commonJS({
    "src/components/errorbars/defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Registry = require_registry();
      var Lib = require_lib();
      var Template = require_plot_template();
      var attributes = require_attributes22();
      module.exports = function(traceIn, traceOut, defaultColor, opts) {
        var objName = "error_" + opts.axis;
        var containerOut = Template.newContainer(traceOut, objName);
        var containerIn = traceIn[objName] || {};
        function coerce(attr, dflt) {
          return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
        }
        var hasErrorBars = containerIn.array !== void 0 || containerIn.value !== void 0 || containerIn.type === "sqrt";
        var visible = coerce("visible", hasErrorBars);
        if (visible === false) return;
        var type = coerce("type", "array" in containerIn ? "data" : "percent");
        var symmetric = true;
        if (type !== "sqrt") {
          symmetric = coerce(
            "symmetric",
            !((type === "data" ? "arrayminus" : "valueminus") in containerIn)
          );
        }
        if (type === "data") {
          coerce("array");
          coerce("traceref");
          if (!symmetric) {
            coerce("arrayminus");
            coerce("tracerefminus");
          }
        } else if (type === "percent" || type === "constant") {
          coerce("value");
          if (!symmetric) coerce("valueminus");
        }
        var copyAttr = "copy_" + opts.inherit + "style";
        if (opts.inherit) {
          var inheritObj = traceOut["error_" + opts.inherit];
          if ((inheritObj || {}).visible) {
            coerce(copyAttr, !(containerIn.color || isNumeric(containerIn.thickness) || isNumeric(containerIn.width)));
          }
        }
        if (!opts.inherit || !containerOut[copyAttr]) {
          coerce("color", defaultColor);
          coerce("thickness");
          coerce("width", Registry.traceIs(traceOut, "gl3d") ? 0 : 4);
        }
      };
    }
  });

  // src/components/errorbars/compute_error.js
  var require_compute_error = __commonJS({
    "src/components/errorbars/compute_error.js"(exports, module) {
      "use strict";
      module.exports = function makeComputeError(opts) {
        var type = opts.type;
        var symmetric = opts.symmetric;
        if (type === "data") {
          var array = opts.array || [];
          if (symmetric) {
            return function computeError(dataPt, index) {
              var val = +array[index];
              return [val, val];
            };
          } else {
            var arrayminus = opts.arrayminus || [];
            return function computeError(dataPt, index) {
              var val = +array[index];
              var valMinus = +arrayminus[index];
              if (!isNaN(val) || !isNaN(valMinus)) {
                return [valMinus || 0, val || 0];
              }
              return [NaN, NaN];
            };
          }
        } else {
          var computeErrorValue = makeComputeErrorValue(type, opts.value);
          var computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus);
          if (symmetric || opts.valueminus === void 0) {
            return function computeError(dataPt) {
              var val = computeErrorValue(dataPt);
              return [val, val];
            };
          } else {
            return function computeError(dataPt) {
              return [
                computeErrorValueMinus(dataPt),
                computeErrorValue(dataPt)
              ];
            };
          }
        }
      };
      function makeComputeErrorValue(type, value) {
        if (type === "percent") {
          return function(dataPt) {
            return Math.abs(dataPt * value / 100);
          };
        }
        if (type === "constant") {
          return function() {
            return Math.abs(value);
          };
        }
        if (type === "sqrt") {
          return function(dataPt) {
            return Math.sqrt(Math.abs(dataPt));
          };
        }
      }
    }
  });

  // src/components/errorbars/calc.js
  var require_calc4 = __commonJS({
    "src/components/errorbars/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Registry = require_registry();
      var Axes = require_axes();
      var Lib = require_lib();
      var makeComputeError = require_compute_error();
      module.exports = function calc(gd) {
        var calcdata = gd.calcdata;
        for (var i = 0; i < calcdata.length; i++) {
          var calcTrace = calcdata[i];
          var trace = calcTrace[0].trace;
          if (trace.visible === true && Registry.traceIs(trace, "errorBarsOK")) {
            var xa = Axes.getFromId(gd, trace.xaxis);
            var ya = Axes.getFromId(gd, trace.yaxis);
            calcOneAxis(calcTrace, trace, xa, "x");
            calcOneAxis(calcTrace, trace, ya, "y");
          }
        }
      };
      function calcOneAxis(calcTrace, trace, axis, coord) {
        var opts = trace["error_" + coord] || {};
        var isVisible = opts.visible && ["linear", "log"].indexOf(axis.type) !== -1;
        var vals = [];
        if (!isVisible) return;
        var computeError = makeComputeError(opts);
        for (var i = 0; i < calcTrace.length; i++) {
          var calcPt = calcTrace[i];
          var iIn = calcPt.i;
          if (iIn === void 0) iIn = i;
          else if (iIn === null) continue;
          var calcCoord = calcPt[coord];
          if (!isNumeric(axis.c2l(calcCoord))) continue;
          var errors = computeError(calcCoord, iIn);
          if (isNumeric(errors[0]) && isNumeric(errors[1])) {
            var shoe = calcPt[coord + "s"] = calcCoord - errors[0];
            var hat = calcPt[coord + "h"] = calcCoord + errors[1];
            vals.push(shoe, hat);
          }
        }
        var axId = axis._id;
        var baseExtremes = trace._extremes[axId];
        var extremes = Axes.findExtremes(
          axis,
          vals,
          Lib.extendFlat({ tozero: baseExtremes.opts.tozero }, { padded: true })
        );
        baseExtremes.min = baseExtremes.min.concat(extremes.min);
        baseExtremes.max = baseExtremes.max.concat(extremes.max);
      }
    }
  });

  // src/components/errorbars/plot.js
  var require_plot2 = __commonJS({
    "src/components/errorbars/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var Drawing = require_drawing();
      var subTypes = require_subtypes();
      module.exports = function plot(gd, traces, plotinfo, transitionOpts) {
        var isNew;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var hasAnimation = transitionOpts && transitionOpts.duration > 0;
        var isStatic = gd._context.staticPlot;
        traces.each(function(d) {
          var trace = d[0].trace;
          var xObj = trace.error_x || {};
          var yObj = trace.error_y || {};
          var keyFunc;
          if (trace.ids) {
            keyFunc = function(d2) {
              return d2.id;
            };
          }
          var sparse = subTypes.hasMarkers(trace) && trace.marker.maxdisplayed > 0;
          if (!yObj.visible && !xObj.visible) d = [];
          var errorbars = d3.select(this).selectAll("g.errorbar").data(d, keyFunc);
          errorbars.exit().remove();
          if (!d.length) return;
          if (!xObj.visible) errorbars.selectAll("path.xerror").remove();
          if (!yObj.visible) errorbars.selectAll("path.yerror").remove();
          errorbars.style("opacity", 1);
          var enter = errorbars.enter().append("g").classed("errorbar", true);
          if (hasAnimation) {
            enter.style("opacity", 0).transition().duration(transitionOpts.duration).style("opacity", 1);
          }
          Drawing.setClipUrl(errorbars, plotinfo.layerClipId, gd);
          errorbars.each(function(d2) {
            var errorbar = d3.select(this);
            var coords = errorCoords(d2, xa, ya);
            if (sparse && !d2.vis) return;
            var path;
            var yerror = errorbar.select("path.yerror");
            if (yObj.visible && isNumeric(coords.x) && isNumeric(coords.yh) && isNumeric(coords.ys)) {
              var yw = yObj.width;
              path = "M" + (coords.x - yw) + "," + coords.yh + "h" + 2 * yw + // hat
              "m-" + yw + ",0V" + coords.ys;
              if (!coords.noYS) path += "m-" + yw + ",0h" + 2 * yw;
              isNew = !yerror.size();
              if (isNew) {
                yerror = errorbar.append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").classed("yerror", true);
              } else if (hasAnimation) {
                yerror = yerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing);
              }
              yerror.attr("d", path);
            } else yerror.remove();
            var xerror = errorbar.select("path.xerror");
            if (xObj.visible && isNumeric(coords.y) && isNumeric(coords.xh) && isNumeric(coords.xs)) {
              var xw = (xObj.copy_ystyle ? yObj : xObj).width;
              path = "M" + coords.xh + "," + (coords.y - xw) + "v" + 2 * xw + // hat
              "m0,-" + xw + "H" + coords.xs;
              if (!coords.noXS) path += "m0,-" + xw + "v" + 2 * xw;
              isNew = !xerror.size();
              if (isNew) {
                xerror = errorbar.append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").classed("xerror", true);
              } else if (hasAnimation) {
                xerror = xerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing);
              }
              xerror.attr("d", path);
            } else xerror.remove();
          });
        });
      };
      function errorCoords(d, xa, ya) {
        var out = {
          x: xa.c2p(d.x),
          y: ya.c2p(d.y)
        };
        if (d.yh !== void 0) {
          out.yh = ya.c2p(d.yh);
          out.ys = ya.c2p(d.ys);
          if (!isNumeric(out.ys)) {
            out.noYS = true;
            out.ys = ya.c2p(d.ys, true);
          }
        }
        if (d.xh !== void 0) {
          out.xh = xa.c2p(d.xh);
          out.xs = xa.c2p(d.xs);
          if (!isNumeric(out.xs)) {
            out.noXS = true;
            out.xs = xa.c2p(d.xs, true);
          }
        }
        return out;
      }
    }
  });

  // src/components/errorbars/style.js
  var require_style3 = __commonJS({
    "src/components/errorbars/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      module.exports = function style(traces) {
        traces.each(function(d) {
          var trace = d[0].trace;
          var yObj = trace.error_y || {};
          var xObj = trace.error_x || {};
          var s = d3.select(this);
          s.selectAll("path.yerror").style("stroke-width", yObj.thickness + "px").call(Color2.stroke, yObj.color);
          if (xObj.copy_ystyle) xObj = yObj;
          s.selectAll("path.xerror").style("stroke-width", xObj.thickness + "px").call(Color2.stroke, xObj.color);
        });
      };
    }
  });

  // src/components/errorbars/index.js
  var require_errorbars = __commonJS({
    "src/components/errorbars/index.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var overrideAll = require_edit_types().overrideAll;
      var attributes = require_attributes22();
      var xyAttrs = {
        error_x: Lib.extendFlat({}, attributes),
        error_y: Lib.extendFlat({}, attributes)
      };
      delete xyAttrs.error_x.copy_zstyle;
      delete xyAttrs.error_y.copy_zstyle;
      delete xyAttrs.error_y.copy_ystyle;
      var xyzAttrs = {
        error_x: Lib.extendFlat({}, attributes),
        error_y: Lib.extendFlat({}, attributes),
        error_z: Lib.extendFlat({}, attributes)
      };
      delete xyzAttrs.error_x.copy_ystyle;
      delete xyzAttrs.error_y.copy_ystyle;
      delete xyzAttrs.error_z.copy_ystyle;
      delete xyzAttrs.error_z.copy_zstyle;
      module.exports = {
        moduleType: "component",
        name: "errorbars",
        schema: {
          traces: {
            scatter: xyAttrs,
            bar: xyAttrs,
            histogram: xyAttrs,
            scatter3d: overrideAll(xyzAttrs, "calc", "nested"),
            scattergl: overrideAll(xyAttrs, "calc", "nested")
          }
        },
        supplyDefaults: require_defaults18(),
        calc: require_calc4(),
        makeComputeError: require_compute_error(),
        plot: require_plot2(),
        style: require_style3(),
        hoverInfo
      };
      function hoverInfo(calcPoint, trace, hoverPoint) {
        if ((trace.error_y || {}).visible) {
          hoverPoint.yerr = calcPoint.yh - calcPoint.y;
          if (!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys;
        }
        if ((trace.error_x || {}).visible) {
          hoverPoint.xerr = calcPoint.xh - calcPoint.x;
          if (!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs;
        }
      }
    }
  });

  // src/components/colorbar/constants.js
  var require_constants14 = __commonJS({
    "src/components/colorbar/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        cn: {
          colorbar: "colorbar",
          cbbg: "cbbg",
          cbfill: "cbfill",
          cbfills: "cbfills",
          cbline: "cbline",
          cblines: "cblines",
          cbaxis: "cbaxis",
          cbtitleunshift: "cbtitleunshift",
          cbtitle: "cbtitle",
          cboutline: "cboutline",
          crisp: "crisp",
          jsPlaceholder: "js-placeholder"
        }
      };
    }
  });

  // src/components/colorbar/draw.js
  var require_draw11 = __commonJS({
    "src/components/colorbar/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var tinycolor = require_tinycolor();
      var Plots = require_plots();
      var Registry = require_registry();
      var Axes = require_axes();
      var dragElement = require_dragelement();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var extendFlat = require_extend().extendFlat;
      var setCursor = require_setcursor();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var Titles = require_titles();
      var svgTextUtils = require_svg_text_utils();
      var flipScale = require_helpers().flipScale;
      var handleAxisDefaults = require_axis_defaults();
      var handleAxisPositionDefaults = require_position_defaults();
      var axisLayoutAttrs = require_layout_attributes4();
      var alignmentConstants = require_alignment();
      var LINE_SPACING = alignmentConstants.LINE_SPACING;
      var FROM_TL = alignmentConstants.FROM_TL;
      var FROM_BR = alignmentConstants.FROM_BR;
      var cn = require_constants14().cn;
      function draw(gd) {
        var fullLayout = gd._fullLayout;
        var colorBars = fullLayout._infolayer.selectAll("g." + cn.colorbar).data(makeColorBarData(gd), function(opts) {
          return opts._id;
        });
        colorBars.enter().append("g").attr("class", function(opts) {
          return opts._id;
        }).classed(cn.colorbar, true);
        colorBars.each(function(opts) {
          var g = d3.select(this);
          Lib.ensureSingle(g, "rect", cn.cbbg);
          Lib.ensureSingle(g, "g", cn.cbfills);
          Lib.ensureSingle(g, "g", cn.cblines);
          Lib.ensureSingle(g, "g", cn.cbaxis, function(s) {
            s.classed(cn.crisp, true);
          });
          Lib.ensureSingle(g, "g", cn.cbtitleunshift, function(s) {
            s.append("g").classed(cn.cbtitle, true);
          });
          Lib.ensureSingle(g, "rect", cn.cboutline);
          var done = drawColorBar(g, opts, gd);
          if (done && done.then) (gd._promises || []).push(done);
          if (gd._context.edits.colorbarPosition) {
            makeEditable(g, opts, gd);
          }
        });
        colorBars.exit().each(function(opts) {
          Plots.autoMargin(gd, opts._id);
        }).remove();
        colorBars.order();
      }
      function makeColorBarData(gd) {
        var fullLayout = gd._fullLayout;
        var calcdata = gd.calcdata;
        var out = [];
        var opts;
        var cont;
        var trace;
        var cbOpt;
        function initOpts(opts2) {
          return extendFlat(opts2, {
            // fillcolor can be a d3 scale, domain is z values, range is colors
            // or leave it out for no fill,
            // or set to a string constant for single-color fill
            _fillcolor: null,
            // line.color has the same options as fillcolor
            _line: { color: null, width: null, dash: null },
            // levels of lines to draw.
            // note that this DOES NOT determine the extent of the bar
            // that's given by the domain of fillcolor
            // (or line.color if no fillcolor domain)
            _levels: { start: null, end: null, size: null },
            // separate fill levels (for example, heatmap coloring of a
            // contour map) if this is omitted, fillcolors will be
            // evaluated halfway between levels
            _filllevels: null,
            // for continuous colorscales: fill with a gradient instead of explicit levels
            // value should be the colorscale [[0, c0], [v1, c1], ..., [1, cEnd]]
            _fillgradient: null,
            // when using a gradient, we need the data range specified separately
            _zrange: null
          });
        }
        function calcOpts() {
          if (typeof cbOpt.calc === "function") {
            cbOpt.calc(gd, trace, opts);
          } else {
            opts._fillgradient = cont.reversescale ? flipScale(cont.colorscale) : cont.colorscale;
            opts._zrange = [cont[cbOpt.min], cont[cbOpt.max]];
          }
        }
        for (var i = 0; i < calcdata.length; i++) {
          var cd = calcdata[i];
          trace = cd[0].trace;
          if (!trace._module) continue;
          var moduleOpts = trace._module.colorbar;
          if (trace.visible === true && moduleOpts) {
            var allowsMultiplotCbs = Array.isArray(moduleOpts);
            var cbOpts = allowsMultiplotCbs ? moduleOpts : [moduleOpts];
            for (var j = 0; j < cbOpts.length; j++) {
              cbOpt = cbOpts[j];
              var contName = cbOpt.container;
              cont = contName ? trace[contName] : trace;
              if (cont && cont.showscale) {
                opts = initOpts(cont.colorbar);
                opts._id = "cb" + trace.uid + (allowsMultiplotCbs && contName ? "-" + contName : "");
                opts._traceIndex = trace.index;
                opts._propPrefix = (contName ? contName + "." : "") + "colorbar.";
                opts._meta = trace._meta;
                calcOpts();
                out.push(opts);
              }
            }
          }
        }
        for (var k in fullLayout._colorAxes) {
          cont = fullLayout[k];
          if (cont.showscale) {
            var colorAxOpts = fullLayout._colorAxes[k];
            opts = initOpts(cont.colorbar);
            opts._id = "cb" + k;
            opts._propPrefix = k + ".colorbar.";
            opts._meta = fullLayout._meta;
            cbOpt = { min: "cmin", max: "cmax" };
            if (colorAxOpts[0] !== "heatmap") {
              trace = colorAxOpts[1];
              cbOpt.calc = trace._module.colorbar.calc;
            }
            calcOpts();
            out.push(opts);
          }
        }
        return out;
      }
      function drawColorBar(g, opts, gd) {
        var isVertical = opts.orientation === "v";
        var len = opts.len;
        var lenmode = opts.lenmode;
        var thickness = opts.thickness;
        var thicknessmode = opts.thicknessmode;
        var outlinewidth = opts.outlinewidth;
        var borderwidth = opts.borderwidth;
        var bgcolor = opts.bgcolor;
        var xanchor = opts.xanchor;
        var yanchor = opts.yanchor;
        var xpad = opts.xpad;
        var ypad = opts.ypad;
        var optsX = opts.x;
        var optsY = isVertical ? opts.y : 1 - opts.y;
        var isPaperY = opts.yref === "paper";
        var isPaperX = opts.xref === "paper";
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        var fillColor = opts._fillcolor;
        var line = opts._line;
        var title = opts.title;
        var titleSide = title.side;
        var zrange = opts._zrange || d3.extent((typeof fillColor === "function" ? fillColor : line.color).domain());
        var lineColormap = typeof line.color === "function" ? line.color : function() {
          return line.color;
        };
        var fillColormap = typeof fillColor === "function" ? fillColor : function() {
          return fillColor;
        };
        var levelsIn = opts._levels;
        var levelsOut = calcLevels(gd, opts, zrange);
        var fillLevels = levelsOut.fill;
        var lineLevels = levelsOut.line;
        var thickPx = Math.round(thickness * (thicknessmode === "fraction" ? isVertical ? gs.w : gs.h : 1));
        var thickFrac = thickPx / (isVertical ? gs.w : gs.h);
        var lenPx = Math.round(len * (lenmode === "fraction" ? isVertical ? gs.h : gs.w : 1));
        var lenFrac = lenPx / (isVertical ? gs.h : gs.w);
        var posW = isPaperX ? gs.w : gd._fullLayout.width;
        var posH = isPaperY ? gs.h : gd._fullLayout.height;
        var uPx = Math.round(
          isVertical ? optsX * posW + xpad : optsY * posH + ypad
        );
        var xRatio = { center: 0.5, right: 1 }[xanchor] || 0;
        var yRatio = { top: 1, middle: 0.5 }[yanchor] || 0;
        var uFrac = isVertical ? optsX - xRatio * thickFrac : optsY - yRatio * thickFrac;
        var vFrac = isVertical ? optsY - yRatio * lenFrac : optsX - xRatio * lenFrac;
        var vPx = Math.round(
          isVertical ? posH * (1 - vFrac) : posW * vFrac
        );
        opts._lenFrac = lenFrac;
        opts._thickFrac = thickFrac;
        opts._uFrac = uFrac;
        opts._vFrac = vFrac;
        var ax = opts._axis = mockColorBarAxis(gd, opts, zrange);
        ax.position = thickFrac + (isVertical ? optsX + xpad / gs.w : optsY + ypad / gs.h);
        var topOrBottom = ["top", "bottom"].indexOf(titleSide) !== -1;
        if (isVertical && topOrBottom) {
          ax.title.side = titleSide;
          ax.titlex = optsX + xpad / gs.w;
          ax.titley = vFrac + (title.side === "top" ? lenFrac - ypad / gs.h : ypad / gs.h);
        }
        if (!isVertical && !topOrBottom) {
          ax.title.side = titleSide;
          ax.titley = optsY + ypad / gs.h;
          ax.titlex = vFrac + xpad / gs.w;
        }
        if (line.color && opts.tickmode === "auto") {
          ax.tickmode = "linear";
          ax.tick0 = levelsIn.start;
          var dtick = levelsIn.size;
          var autoNtick = Lib.constrain(lenPx / 50, 4, 15) + 1;
          var dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick);
          if (dtFactor > 1) {
            var dtexp = Math.pow(10, Math.floor(Math.log(dtFactor) / Math.LN10));
            dtick *= dtexp * Lib.roundUp(dtFactor / dtexp, [2, 5, 10]);
            if ((Math.abs(levelsIn.start) / levelsIn.size + 1e-6) % 1 < 2e-6) {
              ax.tick0 = 0;
            }
          }
          ax.dtick = dtick;
        }
        ax.domain = isVertical ? [
          vFrac + ypad / gs.h,
          vFrac + lenFrac - ypad / gs.h
        ] : [
          vFrac + xpad / gs.w,
          vFrac + lenFrac - xpad / gs.w
        ];
        ax.setScale();
        g.attr("transform", strTranslate(Math.round(gs.l), Math.round(gs.t)));
        var titleCont = g.select("." + cn.cbtitleunshift).attr("transform", strTranslate(-Math.round(gs.l), -Math.round(gs.t)));
        var ticklabelposition = ax.ticklabelposition;
        var titleFontSize = ax.title.font.size;
        var axLayer = g.select("." + cn.cbaxis);
        var titleEl;
        var titleHeight = 0;
        var titleWidth = 0;
        function drawTitle(titleClass, titleOpts) {
          var dfltTitleOpts = {
            propContainer: ax,
            propName: opts._propPrefix + "title.text",
            traceIndex: opts._traceIndex,
            _meta: opts._meta,
            placeholder: fullLayout._dfltTitle.colorbar,
            containerGroup: g.select("." + cn.cbtitle)
          };
          var otherClass = titleClass.charAt(0) === "h" ? titleClass.slice(1) : "h" + titleClass;
          g.selectAll("." + otherClass + ",." + otherClass + "-math-group").remove();
          Titles.draw(gd, titleClass, extendFlat(dfltTitleOpts, titleOpts || {}));
        }
        function drawDummyTitle() {
          if (isVertical && topOrBottom || !isVertical && !topOrBottom) {
            var x, y;
            if (titleSide === "top") {
              x = xpad + gs.l + posW * optsX;
              y = ypad + gs.t + posH * (1 - vFrac - lenFrac) + 3 + titleFontSize * 0.75;
            }
            if (titleSide === "bottom") {
              x = xpad + gs.l + posW * optsX;
              y = ypad + gs.t + posH * (1 - vFrac) - 3 - titleFontSize * 0.25;
            }
            if (titleSide === "right") {
              y = ypad + gs.t + posH * optsY + 3 + titleFontSize * 0.75;
              x = xpad + gs.l + posW * vFrac;
            }
            drawTitle(ax._id + "title", {
              attributes: { x, y, "text-anchor": isVertical ? "start" : "middle" }
            });
          }
        }
        function drawCbTitle() {
          if (isVertical && !topOrBottom || !isVertical && topOrBottom) {
            var pos = ax.position || 0;
            var mid = ax._offset + ax._length / 2;
            var x, y;
            if (titleSide === "right") {
              y = mid;
              x = gs.l + posW * pos + 10 + titleFontSize * (ax.showticklabels ? 1 : 0.5);
            } else {
              x = mid;
              if (titleSide === "bottom") {
                y = gs.t + posH * pos + 10 + (ticklabelposition.indexOf("inside") === -1 ? ax.tickfont.size : 0) + (ax.ticks !== "inside" ? opts.ticklen || 0 : 0);
              }
              if (titleSide === "top") {
                var nlines = title.text.split("<br>").length;
                y = gs.t + posH * pos + 10 - thickPx - LINE_SPACING * titleFontSize * nlines;
              }
            }
            drawTitle((isVertical ? (
              // the 'h' + is a hack to get around the fact that
              // convertToTspans rotates any 'y...' class by 90 degrees.
              // TODO: find a better way to control this.
              "h"
            ) : "v") + ax._id + "title", {
              avoid: {
                selection: d3.select(gd).selectAll("g." + ax._id + "tick"),
                side: titleSide,
                offsetTop: isVertical ? 0 : gs.t,
                offsetLeft: isVertical ? gs.l : 0,
                maxShift: isVertical ? fullLayout.width : fullLayout.height
              },
              attributes: { x, y, "text-anchor": "middle" },
              transform: { rotate: isVertical ? -90 : 0, offset: 0 }
            });
          }
        }
        function drawAxis() {
          if (!isVertical && !topOrBottom || isVertical && topOrBottom) {
            var titleGroup = g.select("." + cn.cbtitle);
            var titleText = titleGroup.select("text");
            var titleTrans = [-outlinewidth / 2, outlinewidth / 2];
            var mathJaxNode = titleGroup.select(".h" + ax._id + "title-math-group").node();
            var lineSize = 15.6;
            if (titleText.node()) {
              lineSize = parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING;
            }
            var bb;
            if (mathJaxNode) {
              bb = Drawing.bBox(mathJaxNode);
              titleWidth = bb.width;
              titleHeight = bb.height;
              if (titleHeight > lineSize) {
                titleTrans[1] -= (titleHeight - lineSize) / 2;
              }
            } else if (titleText.node() && !titleText.classed(cn.jsPlaceholder)) {
              bb = Drawing.bBox(titleText.node());
              titleWidth = bb.width;
              titleHeight = bb.height;
            }
            if (isVertical) {
              if (titleHeight) {
                titleHeight += 5;
                if (titleSide === "top") {
                  ax.domain[1] -= titleHeight / gs.h;
                  titleTrans[1] *= -1;
                } else {
                  ax.domain[0] += titleHeight / gs.h;
                  var nlines = svgTextUtils.lineCount(titleText);
                  titleTrans[1] += (1 - nlines) * lineSize;
                }
                titleGroup.attr("transform", strTranslate(titleTrans[0], titleTrans[1]));
                ax.setScale();
              }
            } else {
              if (titleWidth) {
                if (titleSide === "right") {
                  ax.domain[0] += (titleWidth + titleFontSize / 2) / gs.w;
                }
                titleGroup.attr("transform", strTranslate(titleTrans[0], titleTrans[1]));
                ax.setScale();
              }
            }
          }
          g.selectAll("." + cn.cbfills + ",." + cn.cblines).attr(
            "transform",
            isVertical ? strTranslate(0, Math.round(gs.h * (1 - ax.domain[1]))) : strTranslate(Math.round(gs.w * ax.domain[0]), 0)
          );
          axLayer.attr(
            "transform",
            isVertical ? strTranslate(0, Math.round(-gs.t)) : strTranslate(Math.round(-gs.l), 0)
          );
          var fills = g.select("." + cn.cbfills).selectAll("rect." + cn.cbfill).attr("style", "").data(fillLevels);
          fills.enter().append("rect").classed(cn.cbfill, true).attr("style", "");
          fills.exit().remove();
          var zBounds = zrange.map(ax.c2p).map(Math.round).sort(function(a, b) {
            return a - b;
          });
          fills.each(function(d, i) {
            var z = [
              i === 0 ? zrange[0] : (fillLevels[i] + fillLevels[i - 1]) / 2,
              i === fillLevels.length - 1 ? zrange[1] : (fillLevels[i] + fillLevels[i + 1]) / 2
            ].map(ax.c2p).map(Math.round);
            if (isVertical) {
              z[1] = Lib.constrain(z[1] + (z[1] > z[0]) ? 1 : -1, zBounds[0], zBounds[1]);
            }
            var fillEl = d3.select(this).attr(isVertical ? "x" : "y", uPx).attr(isVertical ? "y" : "x", d3.min(z)).attr(isVertical ? "width" : "height", Math.max(thickPx, 2)).attr(isVertical ? "height" : "width", Math.max(d3.max(z) - d3.min(z), 2));
            if (opts._fillgradient) {
              Drawing.gradient(fillEl, gd, opts._id, isVertical ? "vertical" : "horizontalreversed", opts._fillgradient, "fill");
            } else {
              var colorString = fillColormap(d).replace("e-", "");
              fillEl.attr("fill", tinycolor(colorString).toHexString());
            }
          });
          var lines = g.select("." + cn.cblines).selectAll("path." + cn.cbline).data(line.color && line.width ? lineLevels : []);
          lines.enter().append("path").classed(cn.cbline, true);
          lines.exit().remove();
          lines.each(function(d) {
            var a = uPx;
            var b = Math.round(ax.c2p(d)) + line.width / 2 % 1;
            d3.select(this).attr(
              "d",
              "M" + (isVertical ? a + "," + b : b + "," + a) + (isVertical ? "h" : "v") + thickPx
            ).call(Drawing.lineGroupStyle, line.width, lineColormap(d), line.dash);
          });
          axLayer.selectAll("g." + ax._id + "tick,path").remove();
          var shift = uPx + thickPx + (outlinewidth || 0) / 2 - (opts.ticks === "outside" ? 1 : 0);
          var vals = Axes.calcTicks(ax);
          var tickSign = Axes.getTickSigns(ax)[2];
          Axes.drawTicks(gd, ax, {
            vals: ax.ticks === "inside" ? Axes.clipEnds(ax, vals) : vals,
            layer: axLayer,
            path: Axes.makeTickPath(ax, shift, tickSign),
            transFn: Axes.makeTransTickFn(ax)
          });
          return Axes.drawLabels(gd, ax, {
            vals,
            layer: axLayer,
            transFn: Axes.makeTransTickLabelFn(ax),
            labelFns: Axes.makeLabelFns(ax, shift)
          });
        }
        function positionCB() {
          var bb;
          var innerThickness = thickPx + outlinewidth / 2;
          if (ticklabelposition.indexOf("inside") === -1) {
            bb = Drawing.bBox(axLayer.node());
            innerThickness += isVertical ? bb.width : bb.height;
          }
          titleEl = titleCont.select("text");
          var titleWidth2 = 0;
          var topSideVertical = isVertical && titleSide === "top";
          var rightSideHorizontal = !isVertical && titleSide === "right";
          var moveY = 0;
          if (titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) {
            var _titleHeight;
            var mathJaxNode = titleCont.select(".h" + ax._id + "title-math-group").node();
            if (mathJaxNode && (isVertical && topOrBottom || !isVertical && !topOrBottom)) {
              bb = Drawing.bBox(mathJaxNode);
              titleWidth2 = bb.width;
              _titleHeight = bb.height;
            } else {
              bb = Drawing.bBox(titleCont.node());
              titleWidth2 = bb.right - gs.l - (isVertical ? uPx : vPx);
              _titleHeight = bb.bottom - gs.t - (isVertical ? vPx : uPx);
              if (!isVertical && titleSide === "top") {
                innerThickness += bb.height;
                moveY = bb.height;
              }
            }
            if (rightSideHorizontal) {
              titleEl.attr("transform", strTranslate(titleWidth2 / 2 + titleFontSize / 2, 0));
              titleWidth2 *= 2;
            }
            innerThickness = Math.max(
              innerThickness,
              isVertical ? titleWidth2 : _titleHeight
            );
          }
          var outerThickness = (isVertical ? xpad : ypad) * 2 + innerThickness + borderwidth + outlinewidth / 2;
          var hColorbarMoveTitle = 0;
          if (!isVertical && title.text && yanchor === "bottom" && optsY <= 0) {
            hColorbarMoveTitle = outerThickness / 2;
            outerThickness += hColorbarMoveTitle;
            moveY += hColorbarMoveTitle;
          }
          fullLayout._hColorbarMoveTitle = hColorbarMoveTitle;
          fullLayout._hColorbarMoveCBTitle = moveY;
          var extraW = borderwidth + outlinewidth;
          var lx = (isVertical ? uPx : vPx) - extraW / 2 - (isVertical ? xpad : 0);
          var ly = (isVertical ? vPx : uPx) - (isVertical ? lenPx : ypad + moveY - hColorbarMoveTitle);
          g.select("." + cn.cbbg).attr("x", lx).attr("y", ly).attr(isVertical ? "width" : "height", Math.max(outerThickness - hColorbarMoveTitle, 2)).attr(isVertical ? "height" : "width", Math.max(lenPx + extraW, 2)).call(Color2.fill, bgcolor).call(Color2.stroke, opts.bordercolor).style("stroke-width", borderwidth);
          var moveX = rightSideHorizontal ? Math.max(titleWidth2 - 10, 0) : 0;
          g.selectAll("." + cn.cboutline).attr("x", (isVertical ? uPx : vPx + xpad) + moveX).attr("y", (isVertical ? vPx + ypad - lenPx : uPx) + (topSideVertical ? titleHeight : 0)).attr(isVertical ? "width" : "height", Math.max(thickPx, 2)).attr(isVertical ? "height" : "width", Math.max(lenPx - (isVertical ? 2 * ypad + titleHeight : 2 * xpad + moveX), 2)).call(Color2.stroke, opts.outlinecolor).style({
            fill: "none",
            "stroke-width": outlinewidth
          });
          var xShift = isVertical ? xRatio * outerThickness : 0;
          var yShift = isVertical ? 0 : (1 - yRatio) * outerThickness - moveY;
          xShift = isPaperX ? gs.l - xShift : -xShift;
          yShift = isPaperY ? gs.t - yShift : -yShift;
          g.attr("transform", strTranslate(
            xShift,
            yShift
          ));
          if (!isVertical && (borderwidth || tinycolor(bgcolor).getAlpha() && !tinycolor.equals(fullLayout.paper_bgcolor, bgcolor))) {
            var tickLabels = axLayer.selectAll("text");
            var numTicks = tickLabels[0].length;
            var border = g.select("." + cn.cbbg).node();
            var oBb = Drawing.bBox(border);
            var oTr = Drawing.getTranslate(g);
            var TEXTPAD = 2;
            tickLabels.each(function(d, i) {
              var first = 0;
              var last = numTicks - 1;
              if (i === first || i === last) {
                var iBb = Drawing.bBox(this);
                var iTr = Drawing.getTranslate(this);
                var deltaX;
                if (i === last) {
                  var iRight = iBb.right + iTr.x;
                  var oRight = oBb.right + oTr.x + vPx - borderwidth - TEXTPAD + optsX;
                  deltaX = oRight - iRight;
                  if (deltaX > 0) deltaX = 0;
                } else if (i === first) {
                  var iLeft = iBb.left + iTr.x;
                  var oLeft = oBb.left + oTr.x + vPx + borderwidth + TEXTPAD;
                  deltaX = oLeft - iLeft;
                  if (deltaX < 0) deltaX = 0;
                }
                if (deltaX) {
                  if (numTicks < 3) {
                    this.setAttribute(
                      "transform",
                      "translate(" + deltaX + ",0) " + this.getAttribute("transform")
                    );
                  } else {
                    this.setAttribute("visibility", "hidden");
                  }
                }
              }
            });
          }
          var marginOpts = {};
          var lFrac = FROM_TL[xanchor];
          var rFrac = FROM_BR[xanchor];
          var tFrac = FROM_TL[yanchor];
          var bFrac = FROM_BR[yanchor];
          var extraThickness = outerThickness - thickPx;
          if (isVertical) {
            if (lenmode === "pixels") {
              marginOpts.y = optsY;
              marginOpts.t = lenPx * tFrac;
              marginOpts.b = lenPx * bFrac;
            } else {
              marginOpts.t = marginOpts.b = 0;
              marginOpts.yt = optsY + len * tFrac;
              marginOpts.yb = optsY - len * bFrac;
            }
            if (thicknessmode === "pixels") {
              marginOpts.x = optsX;
              marginOpts.l = outerThickness * lFrac;
              marginOpts.r = outerThickness * rFrac;
            } else {
              marginOpts.l = extraThickness * lFrac;
              marginOpts.r = extraThickness * rFrac;
              marginOpts.xl = optsX - thickness * lFrac;
              marginOpts.xr = optsX + thickness * rFrac;
            }
          } else {
            if (lenmode === "pixels") {
              marginOpts.x = optsX;
              marginOpts.l = lenPx * lFrac;
              marginOpts.r = lenPx * rFrac;
            } else {
              marginOpts.l = marginOpts.r = 0;
              marginOpts.xl = optsX + len * lFrac;
              marginOpts.xr = optsX - len * rFrac;
            }
            if (thicknessmode === "pixels") {
              marginOpts.y = 1 - optsY;
              marginOpts.t = outerThickness * tFrac;
              marginOpts.b = outerThickness * bFrac;
            } else {
              marginOpts.t = extraThickness * tFrac;
              marginOpts.b = extraThickness * bFrac;
              marginOpts.yt = optsY - thickness * tFrac;
              marginOpts.yb = optsY + thickness * bFrac;
            }
          }
          var sideY = opts.y < 0.5 ? "b" : "t";
          var sideX = opts.x < 0.5 ? "l" : "r";
          gd._fullLayout._reservedMargin[opts._id] = {};
          var possibleReservedMargins = {
            r: fullLayout.width - lx - xShift,
            l: lx + marginOpts.r,
            b: fullLayout.height - ly - yShift,
            t: ly + marginOpts.b
          };
          if (isPaperX && isPaperY) {
            Plots.autoMargin(gd, opts._id, marginOpts);
          } else if (isPaperX) {
            gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY];
          } else if (isPaperY) {
            gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX];
          } else {
            if (isVertical) {
              gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX];
            } else {
              gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY];
            }
          }
        }
        return Lib.syncOrAsync([
          Plots.previousPromises,
          drawDummyTitle,
          drawAxis,
          drawCbTitle,
          Plots.previousPromises,
          positionCB
        ], gd);
      }
      function makeEditable(g, opts, gd) {
        var isVertical = opts.orientation === "v";
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        var t02, xf, yf;
        dragElement.init({
          element: g.node(),
          gd,
          prepFn: function() {
            t02 = g.attr("transform");
            setCursor(g);
          },
          moveFn: function(dx, dy) {
            g.attr("transform", t02 + strTranslate(dx, dy));
            xf = dragElement.align(
              (isVertical ? opts._uFrac : opts._vFrac) + dx / gs.w,
              isVertical ? opts._thickFrac : opts._lenFrac,
              0,
              1,
              opts.xanchor
            );
            yf = dragElement.align(
              (isVertical ? opts._vFrac : 1 - opts._uFrac) - dy / gs.h,
              isVertical ? opts._lenFrac : opts._thickFrac,
              0,
              1,
              opts.yanchor
            );
            var csr = dragElement.getCursor(xf, yf, opts.xanchor, opts.yanchor);
            setCursor(g, csr);
          },
          doneFn: function() {
            setCursor(g);
            if (xf !== void 0 && yf !== void 0) {
              var update = {};
              update[opts._propPrefix + "x"] = xf;
              update[opts._propPrefix + "y"] = yf;
              if (opts._traceIndex !== void 0) {
                Registry.call("_guiRestyle", gd, update, opts._traceIndex);
              } else {
                Registry.call("_guiRelayout", gd, update);
              }
            }
          }
        });
      }
      function calcLevels(gd, opts, zrange) {
        var levelsIn = opts._levels;
        var lineLevels = [];
        var fillLevels = [];
        var l;
        var i;
        var l0 = levelsIn.end + levelsIn.size / 100;
        var ls = levelsIn.size;
        var zr0 = 1.001 * zrange[0] - 1e-3 * zrange[1];
        var zr1 = 1.001 * zrange[1] - 1e-3 * zrange[0];
        for (i = 0; i < 1e5; i++) {
          l = levelsIn.start + i * ls;
          if (ls > 0 ? l >= l0 : l <= l0) break;
          if (l > zr0 && l < zr1) lineLevels.push(l);
        }
        if (opts._fillgradient) {
          fillLevels = [0];
        } else if (typeof opts._fillcolor === "function") {
          var fillLevelsIn = opts._filllevels;
          if (fillLevelsIn) {
            l0 = fillLevelsIn.end + fillLevelsIn.size / 100;
            ls = fillLevelsIn.size;
            for (i = 0; i < 1e5; i++) {
              l = fillLevelsIn.start + i * ls;
              if (ls > 0 ? l >= l0 : l <= l0) break;
              if (l > zrange[0] && l < zrange[1]) fillLevels.push(l);
            }
          } else {
            fillLevels = lineLevels.map(function(v) {
              return v - levelsIn.size / 2;
            });
            fillLevels.push(fillLevels[fillLevels.length - 1] + levelsIn.size);
          }
        } else if (opts._fillcolor && typeof opts._fillcolor === "string") {
          fillLevels = [0];
        }
        if (levelsIn.size < 0) {
          lineLevels.reverse();
          fillLevels.reverse();
        }
        return { line: lineLevels, fill: fillLevels };
      }
      function mockColorBarAxis(gd, opts, zrange) {
        var fullLayout = gd._fullLayout;
        var isVertical = opts.orientation === "v";
        var cbAxisIn = {
          type: "linear",
          range: zrange,
          tickmode: opts.tickmode,
          nticks: opts.nticks,
          tick0: opts.tick0,
          dtick: opts.dtick,
          tickvals: opts.tickvals,
          ticktext: opts.ticktext,
          ticks: opts.ticks,
          ticklen: opts.ticklen,
          tickwidth: opts.tickwidth,
          tickcolor: opts.tickcolor,
          showticklabels: opts.showticklabels,
          labelalias: opts.labelalias,
          ticklabelposition: opts.ticklabelposition,
          ticklabeloverflow: opts.ticklabeloverflow,
          ticklabelstep: opts.ticklabelstep,
          tickfont: opts.tickfont,
          tickangle: opts.tickangle,
          tickformat: opts.tickformat,
          exponentformat: opts.exponentformat,
          minexponent: opts.minexponent,
          separatethousands: opts.separatethousands,
          showexponent: opts.showexponent,
          showtickprefix: opts.showtickprefix,
          tickprefix: opts.tickprefix,
          showticksuffix: opts.showticksuffix,
          ticksuffix: opts.ticksuffix,
          title: opts.title,
          showline: true,
          anchor: "free",
          side: isVertical ? "right" : "bottom",
          position: 1
        };
        var letter = isVertical ? "y" : "x";
        var cbAxisOut = {
          type: "linear",
          _id: letter + opts._id
        };
        var axisOptions = {
          letter,
          font: fullLayout.font,
          noAutotickangles: letter === "y",
          noHover: true,
          noTickson: true,
          noTicklabelmode: true,
          noInsideRange: true,
          calendar: fullLayout.calendar
          // not really necessary (yet?)
        };
        function coerce(attr, dflt) {
          return Lib.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt);
        }
        handleAxisDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout);
        handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);
        return cbAxisOut;
      }
      module.exports = {
        draw
      };
    }
  });

  // src/components/colorbar/index.js
  var require_colorbar = __commonJS({
    "src/components/colorbar/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "component",
        name: "colorbar",
        attributes: require_attributes7(),
        supplyDefaults: require_defaults(),
        draw: require_draw11().draw,
        hasColorbar: require_has_colorbar()
      };
    }
  });

  // src/components/legend/index.js
  var require_legend = __commonJS({
    "src/components/legend/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "component",
        name: "legend",
        layoutAttributes: require_attributes9(),
        supplyLayoutDefaults: require_defaults3(),
        draw: require_draw(),
        style: require_style()
      };
    }
  });

  // src/locale-en.js
  var require_locale_en = __commonJS({
    "src/locale-en.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "locale",
        name: "en",
        dictionary: {
          "Click to enter Colorscale title": "Click to enter Colourscale title"
        },
        format: {
          days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
          shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
          months: [
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"
          ],
          shortMonths: [
            "Jan",
            "Feb",
            "Mar",
            "Apr",
            "May",
            "Jun",
            "Jul",
            "Aug",
            "Sep",
            "Oct",
            "Nov",
            "Dec"
          ],
          periods: ["AM", "PM"],
          dateTime: "%a %b %e %X %Y",
          date: "%d/%m/%Y",
          time: "%H:%M:%S",
          decimal: ".",
          thousands: ",",
          grouping: [3],
          currency: ["$", ""],
          year: "%Y",
          month: "%b %Y",
          dayMonth: "%b %-d",
          dayMonthYear: "%b %-d, %Y"
        }
      };
    }
  });

  // src/locale-en-us.js
  var require_locale_en_us = __commonJS({
    "src/locale-en-us.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "locale",
        name: "en-US",
        dictionary: {
          "Click to enter Colorscale title": "Click to enter Colorscale title"
        },
        format: {
          date: "%m/%d/%Y"
        }
      };
    }
  });

  // src/snapshot/cloneplot.js
  var require_cloneplot = __commonJS({
    "src/snapshot/cloneplot.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var extendFlat = Lib.extendFlat;
      var extendDeep = Lib.extendDeep;
      function cloneLayoutOverride(tileClass) {
        var override;
        switch (tileClass) {
          case "themes__thumb":
            override = {
              autosize: true,
              width: 150,
              height: 150,
              title: { text: "" },
              showlegend: false,
              margin: { l: 5, r: 5, t: 5, b: 5, pad: 0 },
              annotations: []
            };
            break;
          case "thumbnail":
            override = {
              title: { text: "" },
              hidesources: true,
              showlegend: false,
              borderwidth: 0,
              bordercolor: "",
              margin: { l: 1, r: 1, t: 1, b: 1, pad: 0 },
              annotations: []
            };
            break;
          default:
            override = {};
        }
        return override;
      }
      function keyIsAxis(keyName) {
        var types = ["xaxis", "yaxis", "zaxis"];
        return types.indexOf(keyName.slice(0, 5)) > -1;
      }
      module.exports = function clonePlot(graphObj, options) {
        var i;
        var oldData = graphObj.data;
        var oldLayout = graphObj.layout;
        var newData = extendDeep([], oldData);
        var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
        var context = graphObj._context || {};
        if (options.width) newLayout.width = options.width;
        if (options.height) newLayout.height = options.height;
        if (options.tileClass === "thumbnail" || options.tileClass === "themes__thumb") {
          newLayout.annotations = [];
          var keys = Object.keys(newLayout);
          for (i = 0; i < keys.length; i++) {
            if (keyIsAxis(keys[i])) {
              newLayout[keys[i]].title = { text: "" };
            }
          }
          for (i = 0; i < newData.length; i++) {
            var trace = newData[i];
            trace.showscale = false;
            if (trace.marker) trace.marker.showscale = false;
            if (Registry.traceIs(trace, "pie-like")) trace.textposition = "none";
          }
        }
        if (Array.isArray(options.annotations)) {
          for (i = 0; i < options.annotations.length; i++) {
            newLayout.annotations.push(options.annotations[i]);
          }
        }
        var sceneIds = Object.keys(newLayout).filter(function(key) {
          return key.match(/^scene\d*$/);
        });
        if (sceneIds.length) {
          var axesImageOverride = {};
          if (options.tileClass === "thumbnail") {
            axesImageOverride = {
              title: { text: "" },
              showaxeslabels: false,
              showticklabels: false,
              linetickenable: false
            };
          }
          for (i = 0; i < sceneIds.length; i++) {
            var scene = newLayout[sceneIds[i]];
            if (!scene.xaxis) {
              scene.xaxis = {};
            }
            if (!scene.yaxis) {
              scene.yaxis = {};
            }
            if (!scene.zaxis) {
              scene.zaxis = {};
            }
            extendFlat(scene.xaxis, axesImageOverride);
            extendFlat(scene.yaxis, axesImageOverride);
            extendFlat(scene.zaxis, axesImageOverride);
            scene._scene = null;
          }
        }
        var gd = document.createElement("div");
        if (options.tileClass) gd.className = options.tileClass;
        var plotTile = {
          gd,
          td: gd,
          // for external (image server) compatibility
          layout: newLayout,
          data: newData,
          config: {
            staticPlot: options.staticPlot === void 0 ? true : options.staticPlot,
            plotGlPixelRatio: options.plotGlPixelRatio === void 0 ? 2 : options.plotGlPixelRatio,
            displaylogo: options.displaylogo || false,
            showLink: options.showLink || false,
            showTips: options.showTips || false,
            mapboxAccessToken: context.mapboxAccessToken
          }
        };
        if (options.setBackground !== "transparent") {
          plotTile.config.setBackground = options.setBackground || "opaque";
        }
        plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass);
        return plotTile;
      };
    }
  });

  // src/snapshot/toimage.js
  var require_toimage = __commonJS({
    "src/snapshot/toimage.js"(exports, module) {
      "use strict";
      var EventEmitter = require_events().EventEmitter;
      var Registry = require_registry();
      var Lib = require_lib();
      var helpers = require_helpers10();
      var clonePlot = require_cloneplot();
      var toSVG = require_tosvg();
      var svgToImg = require_svgtoimg();
      function toImage(gd, opts) {
        var ev = new EventEmitter();
        var clone = clonePlot(gd, { format: "png" });
        var clonedGd = clone.gd;
        clonedGd.style.position = "absolute";
        clonedGd.style.left = "-5000px";
        document.body.appendChild(clonedGd);
        function wait() {
          var delay = helpers.getDelay(clonedGd._fullLayout);
          setTimeout(function() {
            var svg = toSVG(clonedGd);
            var canvas = document.createElement("canvas");
            canvas.id = Lib.randstr();
            ev = svgToImg({
              format: opts.format,
              width: clonedGd._fullLayout.width,
              height: clonedGd._fullLayout.height,
              canvas,
              emitter: ev,
              svg
            });
            ev.clean = function() {
              if (clonedGd) document.body.removeChild(clonedGd);
            };
          }, delay);
        }
        var redrawFunc = helpers.getRedrawFunc(clonedGd);
        Registry.call("_doPlot", clonedGd, clone.data, clone.layout, clone.config).then(redrawFunc).then(wait).catch(function(err) {
          ev.emit("error", err);
        });
        return ev;
      }
      module.exports = toImage;
    }
  });

  // src/snapshot/index.js
  var require_snapshot = __commonJS({
    "src/snapshot/index.js"(exports, module) {
      "use strict";
      var helpers = require_helpers10();
      var Snapshot = {
        getDelay: helpers.getDelay,
        getRedrawFunc: helpers.getRedrawFunc,
        clone: require_cloneplot(),
        toSVG: require_tosvg(),
        svgToImg: require_svgtoimg(),
        toImage: require_toimage(),
        downloadImage: require_download()
      };
      module.exports = Snapshot;
    }
  });

  // src/core.js
  var require_core = __commonJS({
    "src/core.js"(exports) {
      "use strict";
      exports.version = require_version().version;
      require_npo_src();
      require_plotcss();
      var Registry = require_registry();
      var register = exports.register = Registry.register;
      var plotApi = require_plot_api2();
      var methodNames = Object.keys(plotApi);
      for (i = 0; i < methodNames.length; i++) {
        name2 = methodNames[i];
        if (name2.charAt(0) !== "_") exports[name2] = plotApi[name2];
        register({
          moduleType: "apiMethod",
          name: name2,
          fn: plotApi[name2]
        });
      }
      var name2;
      var i;
      register(require_scatter());
      register([
        require_annotations(),
        require_annotations3d(),
        require_selections(),
        require_shapes(),
        require_images(),
        require_updatemenus(),
        require_sliders(),
        require_rangeslider(),
        require_rangeselector(),
        require_grid(),
        require_errorbars(),
        require_colorscale(),
        require_colorbar(),
        require_legend(),
        // legend needs to come after shape | legend defaults depends on shapes
        require_fx(),
        // fx needs to come after legend | unified hover defaults depends on legends
        require_modebar2()
      ]);
      register([
        require_locale_en(),
        require_locale_en_us()
      ]);
      if (window.PlotlyLocales && Array.isArray(window.PlotlyLocales)) {
        register(window.PlotlyLocales);
        delete window.PlotlyLocales;
      }
      exports.Icons = require_ploticon();
      var Fx = require_fx();
      var Plots = require_plots();
      exports.Plots = {
        resize: Plots.resize,
        graphJson: Plots.graphJson,
        sendDataToCloud: Plots.sendDataToCloud
      };
      exports.Fx = {
        hover: Fx.hover,
        unhover: Fx.unhover,
        loneHover: Fx.loneHover,
        loneUnhover: Fx.loneUnhover
      };
      exports.Snapshot = require_snapshot();
      exports.PlotSchema = require_plot_schema();
    }
  });

  // lib/core.js
  var require_core2 = __commonJS({
    "lib/core.js"(exports, module) {
      "use strict";
      module.exports = require_core();
    }
  });

  // src/traces/bar/attributes.js
  var require_attributes23 = __commonJS({
    "src/traces/bar/attributes.js"(exports, module) {
      "use strict";
      var scatterAttrs = require_attributes12();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorScaleAttrs = require_attributes8();
      var fontAttrs = require_font_attributes();
      var constants = require_constants9();
      var pattern = require_attributes4().pattern;
      var extendFlat = require_extend().extendFlat;
      var textFontAttrs = fontAttrs({
        editType: "calc",
        arrayOk: true,
        colorEditType: "style"
      });
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      var markerLineWidth = extendFlat({}, scatterMarkerLineAttrs.width, { dflt: 0 });
      var markerLine = extendFlat(
        {
          width: markerLineWidth,
          editType: "calc"
        },
        colorScaleAttrs("marker.line")
      );
      var marker = extendFlat(
        {
          line: markerLine,
          editType: "calc"
        },
        colorScaleAttrs("marker"),
        {
          opacity: {
            valType: "number",
            arrayOk: true,
            dflt: 1,
            min: 0,
            max: 1,
            editType: "style"
          },
          pattern,
          cornerradius: {
            valType: "any",
            editType: "calc"
          }
        }
      );
      module.exports = {
        x: scatterAttrs.x,
        x0: scatterAttrs.x0,
        dx: scatterAttrs.dx,
        y: scatterAttrs.y,
        y0: scatterAttrs.y0,
        dy: scatterAttrs.dy,
        xperiod: scatterAttrs.xperiod,
        yperiod: scatterAttrs.yperiod,
        xperiod0: scatterAttrs.xperiod0,
        yperiod0: scatterAttrs.yperiod0,
        xperiodalignment: scatterAttrs.xperiodalignment,
        yperiodalignment: scatterAttrs.yperiodalignment,
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        text: scatterAttrs.text,
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: constants.eventDataKeys }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: scatterAttrs.hovertext,
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        textposition: {
          valType: "enumerated",
          values: ["inside", "outside", "auto", "none"],
          dflt: "auto",
          arrayOk: true,
          editType: "calc"
        },
        insidetextanchor: {
          valType: "enumerated",
          values: ["end", "middle", "start"],
          dflt: "end",
          editType: "plot"
        },
        textangle: {
          valType: "angle",
          dflt: "auto",
          editType: "plot"
        },
        textfont: extendFlat({}, textFontAttrs, {}),
        insidetextfont: extendFlat({}, textFontAttrs, {}),
        outsidetextfont: extendFlat({}, textFontAttrs, {}),
        constraintext: {
          valType: "enumerated",
          values: ["inside", "outside", "both", "none"],
          dflt: "both",
          editType: "calc"
        },
        cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {}),
        orientation: {
          valType: "enumerated",
          values: ["v", "h"],
          editType: "calc+clearAxisTypes"
        },
        base: {
          valType: "any",
          dflt: null,
          arrayOk: true,
          editType: "calc"
        },
        offset: {
          valType: "number",
          dflt: null,
          arrayOk: true,
          editType: "calc"
        },
        width: {
          valType: "number",
          dflt: null,
          min: 0,
          arrayOk: true,
          editType: "calc"
        },
        marker,
        offsetgroup: scatterAttrs.offsetgroup,
        alignmentgroup: scatterAttrs.alignmentgroup,
        selected: {
          marker: {
            opacity: scatterAttrs.selected.marker.opacity,
            color: scatterAttrs.selected.marker.color,
            editType: "style"
          },
          textfont: scatterAttrs.selected.textfont,
          editType: "style"
        },
        unselected: {
          marker: {
            opacity: scatterAttrs.unselected.marker.opacity,
            color: scatterAttrs.unselected.marker.color,
            editType: "style"
          },
          textfont: scatterAttrs.unselected.textfont,
          editType: "style"
        },
        zorder: scatterAttrs.zorder
      };
    }
  });

  // src/traces/bar/layout_attributes.js
  var require_layout_attributes6 = __commonJS({
    "src/traces/bar/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        barmode: {
          valType: "enumerated",
          values: ["stack", "group", "overlay", "relative"],
          dflt: "group",
          editType: "calc"
        },
        barnorm: {
          valType: "enumerated",
          values: ["", "fraction", "percent"],
          dflt: "",
          editType: "calc"
        },
        bargap: {
          valType: "number",
          min: 0,
          max: 1,
          editType: "calc"
        },
        bargroupgap: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0,
          editType: "calc"
        },
        barcornerradius: {
          valType: "any",
          editType: "calc"
        }
      };
    }
  });

  // src/traces/bar/style_defaults.js
  var require_style_defaults = __commonJS({
    "src/traces/bar/style_defaults.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleDefaults = require_defaults2();
      var coercePattern = require_lib().coercePattern;
      module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) {
        var markerColor = coerce("marker.color", defaultColor);
        var hasMarkerColorscale = hasColorscale(traceIn, "marker");
        if (hasMarkerColorscale) {
          colorscaleDefaults(
            traceIn,
            traceOut,
            layout,
            coerce,
            { prefix: "marker.", cLetter: "c" }
          );
        }
        coerce("marker.line.color", Color2.defaultLine);
        if (hasColorscale(traceIn, "marker.line")) {
          colorscaleDefaults(
            traceIn,
            traceOut,
            layout,
            coerce,
            { prefix: "marker.line.", cLetter: "c" }
          );
        }
        coerce("marker.line.width");
        coerce("marker.opacity");
        coercePattern(coerce, "marker.pattern", markerColor, hasMarkerColorscale);
        coerce("selected.marker.color");
        coerce("unselected.marker.color");
      };
    }
  });

  // src/traces/bar/defaults.js
  var require_defaults19 = __commonJS({
    "src/traces/bar/defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Color2 = require_color();
      var Registry = require_registry();
      var handleXYDefaults = require_xy_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var handleStyleDefaults = require_style_defaults();
      var handleGroupingDefaults = require_grouping_defaults();
      var attributes = require_attributes23();
      var coerceFont = Lib.coerceFont;
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("zorder");
        coerce("orientation", traceOut.x && !traceOut.y ? "h" : "v");
        coerce("base");
        coerce("offset");
        coerce("width");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var textposition = coerce("textposition");
        handleText(traceIn, traceOut, layout, coerce, textposition, {
          moduleHasSelected: true,
          moduleHasUnselected: true,
          moduleHasConstrain: true,
          moduleHasCliponaxis: true,
          moduleHasTextangle: true,
          moduleHasInsideanchor: true
        });
        handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
        var lineColor = (traceOut.marker.line || {}).color;
        var errorBarsSupplyDefaults = Registry.getComponentMethod("errorbars", "supplyDefaults");
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color2.defaultLine, { axis: "y" });
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color2.defaultLine, { axis: "x", inherit: "y" });
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      }
      function crossTraceDefaults(fullData, fullLayout) {
        var traceIn, traceOut;
        function coerce(attr, dflt) {
          return Lib.coerce(traceOut._input, traceOut, attributes, attr, dflt);
        }
        for (var i = 0; i < fullData.length; i++) {
          traceOut = fullData[i];
          if (traceOut.type === "bar") {
            traceIn = traceOut._input;
            var r = coerce("marker.cornerradius", fullLayout.barcornerradius);
            if (traceOut.marker) {
              traceOut.marker.cornerradius = validateCornerradius(r);
            }
            handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce, fullLayout.barmode);
          }
        }
      }
      function validateCornerradius(r) {
        if (isNumeric(r)) {
          r = +r;
          if (r >= 0) return r;
        } else if (typeof r === "string") {
          r = r.trim();
          if (r.slice(-1) === "%" && isNumeric(r.slice(0, -1))) {
            r = +r.slice(0, -1);
            if (r >= 0) return r + "%";
          }
        }
        return void 0;
      }
      function handleText(traceIn, traceOut, layout, coerce, textposition, opts) {
        opts = opts || {};
        var moduleHasSelected = !(opts.moduleHasSelected === false);
        var moduleHasUnselected = !(opts.moduleHasUnselected === false);
        var moduleHasConstrain = !(opts.moduleHasConstrain === false);
        var moduleHasCliponaxis = !(opts.moduleHasCliponaxis === false);
        var moduleHasTextangle = !(opts.moduleHasTextangle === false);
        var moduleHasInsideanchor = !(opts.moduleHasInsideanchor === false);
        var hasPathbar = !!opts.hasPathbar;
        var hasBoth = Array.isArray(textposition) || textposition === "auto";
        var hasInside = hasBoth || textposition === "inside";
        var hasOutside = hasBoth || textposition === "outside";
        if (hasInside || hasOutside) {
          var dfltFont = coerceFont(coerce, "textfont", layout.font);
          var insideTextFontDefault = Lib.extendFlat({}, dfltFont);
          var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
          var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
          if (isColorInheritedFromLayoutFont) {
            delete insideTextFontDefault.color;
          }
          coerceFont(coerce, "insidetextfont", insideTextFontDefault);
          if (hasPathbar) {
            var pathbarTextFontDefault = Lib.extendFlat({}, dfltFont);
            if (isColorInheritedFromLayoutFont) {
              delete pathbarTextFontDefault.color;
            }
            coerceFont(coerce, "pathbar.textfont", pathbarTextFontDefault);
          }
          if (hasOutside) coerceFont(coerce, "outsidetextfont", dfltFont);
          if (moduleHasSelected) coerce("selected.textfont.color");
          if (moduleHasUnselected) coerce("unselected.textfont.color");
          if (moduleHasConstrain) coerce("constraintext");
          if (moduleHasCliponaxis) coerce("cliponaxis");
          if (moduleHasTextangle) coerce("textangle");
          coerce("texttemplate");
          coerce("texttemplatefallback");
        }
        if (hasInside) {
          if (moduleHasInsideanchor) coerce("insidetextanchor");
        }
      }
      module.exports = {
        supplyDefaults,
        crossTraceDefaults,
        handleText,
        validateCornerradius
      };
    }
  });

  // src/traces/bar/layout_defaults.js
  var require_layout_defaults5 = __commonJS({
    "src/traces/bar/layout_defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Axes = require_axes();
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes6();
      var validateCornerradius = require_defaults19().validateCornerradius;
      module.exports = function(layoutIn, layoutOut, fullData) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        var hasBars = false;
        var shouldBeGapless = false;
        var gappedAnyway = false;
        var usedSubplots = {};
        var mode = coerce("barmode");
        var isGroup = mode === "group";
        for (var i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          if (Registry.traceIs(trace, "bar") && trace.visible) hasBars = true;
          else continue;
          var subploti = trace.xaxis + trace.yaxis;
          if (isGroup) {
            if (usedSubplots[subploti]) gappedAnyway = true;
            usedSubplots[subploti] = true;
          } else {
            subploti += trace._input.offsetgroup;
            if (usedSubplots.length > 0 && !usedSubplots[subploti]) gappedAnyway = true;
            usedSubplots[subploti] = true;
          }
          if (trace.visible && trace.type === "histogram") {
            var pa = Axes.getFromId(
              { _fullLayout: layoutOut },
              trace[trace.orientation === "v" ? "xaxis" : "yaxis"]
            );
            if (pa.type !== "category") shouldBeGapless = true;
          }
        }
        if (!hasBars) {
          delete layoutOut.barmode;
          return;
        }
        if (mode !== "overlay") coerce("barnorm");
        coerce("bargap", shouldBeGapless && !gappedAnyway ? 0 : 0.2);
        coerce("bargroupgap");
        var r = coerce("barcornerradius");
        layoutOut.barcornerradius = validateCornerradius(r);
      };
    }
  });

  // src/traces/bar/arrays_to_calcdata.js
  var require_arrays_to_calcdata2 = __commonJS({
    "src/traces/bar/arrays_to_calcdata.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function arraysToCalcdata(cd, trace) {
        for (var i = 0; i < cd.length; i++) cd[i].i = i;
        Lib.mergeArray(trace.text, cd, "tx");
        Lib.mergeArray(trace.hovertext, cd, "htx");
        var marker = trace.marker;
        if (marker) {
          Lib.mergeArray(marker.opacity, cd, "mo", true);
          Lib.mergeArray(marker.color, cd, "mc");
          var markerLine = marker.line;
          if (markerLine) {
            Lib.mergeArray(markerLine.color, cd, "mlc");
            Lib.mergeArrayCastPositive(markerLine.width, cd, "mlw");
          }
        }
      };
    }
  });

  // src/traces/bar/calc.js
  var require_calc5 = __commonJS({
    "src/traces/bar/calc.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleCalc = require_calc();
      var arraysToCalcdata = require_arrays_to_calcdata2();
      var calcSelection = require_calc_selection();
      module.exports = function calc(gd, trace) {
        var xa = Axes.getFromId(gd, trace.xaxis || "x");
        var ya = Axes.getFromId(gd, trace.yaxis || "y");
        var size, pos, origPos, pObj, hasPeriod, pLetter;
        var sizeOpts = {
          msUTC: !!(trace.base || trace.base === 0)
        };
        if (trace.orientation === "h") {
          size = xa.makeCalcdata(trace, "x", sizeOpts);
          origPos = ya.makeCalcdata(trace, "y");
          pObj = alignPeriod(trace, ya, "y", origPos);
          hasPeriod = !!trace.yperiodalignment;
          pLetter = "y";
        } else {
          size = ya.makeCalcdata(trace, "y", sizeOpts);
          origPos = xa.makeCalcdata(trace, "x");
          pObj = alignPeriod(trace, xa, "x", origPos);
          hasPeriod = !!trace.xperiodalignment;
          pLetter = "x";
        }
        pos = pObj.vals;
        var serieslen = Math.min(pos.length, size.length);
        var cd = new Array(serieslen);
        for (var i = 0; i < serieslen; i++) {
          cd[i] = { p: pos[i], s: size[i] };
          if (hasPeriod) {
            cd[i].orig_p = origPos[i];
            cd[i][pLetter + "End"] = pObj.ends[i];
            cd[i][pLetter + "Start"] = pObj.starts[i];
          }
          if (trace.ids) {
            cd[i].id = String(trace.ids[i]);
          }
        }
        if (hasColorscale(trace, "marker")) {
          colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: "marker",
            cLetter: "c"
          });
        }
        if (hasColorscale(trace, "marker.line")) {
          colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: "marker.line",
            cLetter: "c"
          });
        }
        arraysToCalcdata(cd, trace);
        calcSelection(cd, trace);
        return cd;
      };
    }
  });

  // src/traces/bar/uniform_text.js
  var require_uniform_text = __commonJS({
    "src/traces/bar/uniform_text.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      function resizeText(gd, gTrace, traceType) {
        var fullLayout = gd._fullLayout;
        var minSize = fullLayout["_" + traceType + "Text_minsize"];
        if (minSize) {
          var shouldHide = fullLayout.uniformtext.mode === "hide";
          var selector;
          switch (traceType) {
            case "funnelarea":
            case "pie":
            case "sunburst":
              selector = "g.slice";
              break;
            case "treemap":
            case "icicle":
              selector = "g.slice, g.pathbar";
              break;
            default:
              selector = "g.points > g.point";
          }
          gTrace.selectAll(selector).each(function(d) {
            var transform = d.transform;
            if (transform) {
              transform.scale = shouldHide && transform.hide ? 0 : minSize / transform.fontSize;
              var el = d3.select(this).select("text");
              Lib.setTransormAndDisplay(el, transform);
            }
          });
        }
      }
      function recordMinTextSize(traceType, transform, fullLayout) {
        if (fullLayout.uniformtext.mode) {
          var minKey = getMinKey(traceType);
          var minSize = fullLayout.uniformtext.minsize;
          var size = transform.scale * transform.fontSize;
          transform.hide = size < minSize;
          fullLayout[minKey] = fullLayout[minKey] || Infinity;
          if (!transform.hide) {
            fullLayout[minKey] = Math.min(
              fullLayout[minKey],
              Math.max(size, minSize)
            );
          }
        }
      }
      function clearMinTextSize(traceType, fullLayout) {
        var minKey = getMinKey(traceType);
        fullLayout[minKey] = void 0;
      }
      function getMinKey(traceType) {
        return "_" + traceType + "Text_minsize";
      }
      module.exports = {
        recordMinTextSize,
        clearMinTextSize,
        resizeText
      };
    }
  });

  // src/traces/bar/helpers.js
  var require_helpers12 = __commonJS({
    "src/traces/bar/helpers.js"(exports) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var tinycolor = require_tinycolor();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      exports.coerceString = function(attributeDefinition, value, defaultValue) {
        if (typeof value === "string") {
          if (value || !attributeDefinition.noBlank) return value;
        } else if (typeof value === "number" || value === true) {
          if (!attributeDefinition.strict) return String(value);
        }
        return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt;
      };
      exports.coerceNumber = function(attributeDefinition, value, defaultValue) {
        if (isNumeric(value)) {
          value = +value;
          var min = attributeDefinition.min;
          var max = attributeDefinition.max;
          var isOutOfBounds = min !== void 0 && value < min || max !== void 0 && value > max;
          if (!isOutOfBounds) return value;
        }
        return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt;
      };
      exports.coerceColor = function(attributeDefinition, value, defaultValue) {
        if (tinycolor(value).isValid()) return value;
        return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt;
      };
      exports.coerceEnumerated = function(attributeDefinition, value, defaultValue) {
        if (attributeDefinition.coerceNumber) value = +value;
        if (attributeDefinition.values.indexOf(value) !== -1) return value;
        return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt;
      };
      exports.getValue = function(arrayOrScalar, index) {
        var value;
        if (!isArrayOrTypedArray(arrayOrScalar)) value = arrayOrScalar;
        else if (index < arrayOrScalar.length) value = arrayOrScalar[index];
        return value;
      };
      exports.getLineWidth = function(trace, di) {
        var w = 0 < di.mlw ? di.mlw : !isArrayOrTypedArray(trace.marker.line.width) ? trace.marker.line.width : 0;
        return w;
      };
    }
  });

  // src/traces/bar/style.js
  var require_style4 = __commonJS({
    "src/traces/bar/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var Registry = require_registry();
      var resizeText = require_uniform_text().resizeText;
      var attributes = require_attributes23();
      var attributeTextFont = attributes.textfont;
      var attributeInsideTextFont = attributes.insidetextfont;
      var attributeOutsideTextFont = attributes.outsidetextfont;
      var helpers = require_helpers12();
      function style(gd) {
        var s = d3.select(gd).selectAll('g[class^="barlayer"]').selectAll("g.trace");
        resizeText(gd, s, "bar");
        var barcount = s.size();
        var fullLayout = gd._fullLayout;
        s.style("opacity", function(d) {
          return d[0].trace.opacity;
        }).each(function(d) {
          if (fullLayout.barmode === "stack" && barcount > 1 || fullLayout.bargap === 0 && fullLayout.bargroupgap === 0 && !d[0].trace.marker.line.width) {
            d3.select(this).attr("shape-rendering", "crispEdges");
          }
        });
        s.selectAll("g.points").each(function(d) {
          var sel = d3.select(this);
          var trace = d[0].trace;
          stylePoints(sel, trace, gd);
        });
        Registry.getComponentMethod("errorbars", "style")(s);
      }
      function stylePoints(sel, trace, gd) {
        Drawing.pointStyle(sel.selectAll("path"), trace, gd);
        styleTextPoints(sel, trace, gd);
      }
      function styleTextPoints(sel, trace, gd) {
        sel.selectAll("text").each(function(d) {
          var tx = d3.select(this);
          var font = Lib.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd));
          Drawing.font(tx, font);
        });
      }
      function styleOnSelect(gd, cd, sel) {
        var trace = cd[0].trace;
        if (trace.selectedpoints) {
          stylePointsInSelectionMode(sel, trace, gd);
        } else {
          stylePoints(sel, trace, gd);
          Registry.getComponentMethod("errorbars", "style")(sel);
        }
      }
      function stylePointsInSelectionMode(s, trace, gd) {
        Drawing.selectedPointStyle(s.selectAll("path"), trace);
        styleTextInSelectionMode(s.selectAll("text"), trace, gd);
      }
      function styleTextInSelectionMode(txs, trace, gd) {
        txs.each(function(d) {
          var tx = d3.select(this);
          var font;
          if (d.selected) {
            font = Lib.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd));
            var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color;
            if (selectedFontColor) {
              font.color = selectedFontColor;
            }
            Drawing.font(tx, font);
          } else {
            Drawing.selectedTextStyle(tx, trace);
          }
        });
      }
      function determineFont(tx, d, trace, gd) {
        var layoutFont = gd._fullLayout.font;
        var textFont = trace.textfont;
        if (tx.classed("bartext-inside")) {
          var barColor = getBarColor(d, trace);
          textFont = getInsideTextFont(trace, d.i, layoutFont, barColor);
        } else if (tx.classed("bartext-outside")) {
          textFont = getOutsideTextFont(trace, d.i, layoutFont);
        }
        return textFont;
      }
      function getTextFont(trace, index, defaultValue) {
        return getFontValue(
          attributeTextFont,
          trace.textfont,
          index,
          defaultValue
        );
      }
      function getInsideTextFont(trace, index, layoutFont, barColor) {
        var defaultFont = getTextFont(trace, index, layoutFont);
        var wouldFallBackToLayoutFont = trace._input.textfont === void 0 || trace._input.textfont.color === void 0 || Array.isArray(trace.textfont.color) && trace.textfont.color[index] === void 0;
        if (wouldFallBackToLayoutFont) {
          defaultFont = {
            color: Color2.contrast(barColor),
            family: defaultFont.family,
            size: defaultFont.size,
            weight: defaultFont.weight,
            style: defaultFont.style,
            variant: defaultFont.variant,
            textcase: defaultFont.textcase,
            lineposition: defaultFont.lineposition,
            shadow: defaultFont.shadow
          };
        }
        return getFontValue(
          attributeInsideTextFont,
          trace.insidetextfont,
          index,
          defaultFont
        );
      }
      function getOutsideTextFont(trace, index, layoutFont) {
        var defaultFont = getTextFont(trace, index, layoutFont);
        return getFontValue(
          attributeOutsideTextFont,
          trace.outsidetextfont,
          index,
          defaultFont
        );
      }
      function getFontValue(attributeDefinition, attributeValue, index, defaultValue) {
        attributeValue = attributeValue || {};
        var familyValue = helpers.getValue(attributeValue.family, index);
        var sizeValue = helpers.getValue(attributeValue.size, index);
        var colorValue = helpers.getValue(attributeValue.color, index);
        var weightValue = helpers.getValue(attributeValue.weight, index);
        var styleValue = helpers.getValue(attributeValue.style, index);
        var variantValue = helpers.getValue(attributeValue.variant, index);
        var textcaseValue = helpers.getValue(attributeValue.textcase, index);
        var linepositionValue = helpers.getValue(attributeValue.lineposition, index);
        var shadowValue = helpers.getValue(attributeValue.shadow, index);
        return {
          family: helpers.coerceString(
            attributeDefinition.family,
            familyValue,
            defaultValue.family
          ),
          size: helpers.coerceNumber(
            attributeDefinition.size,
            sizeValue,
            defaultValue.size
          ),
          color: helpers.coerceColor(
            attributeDefinition.color,
            colorValue,
            defaultValue.color
          ),
          weight: helpers.coerceString(
            attributeDefinition.weight,
            weightValue,
            defaultValue.weight
          ),
          style: helpers.coerceString(
            attributeDefinition.style,
            styleValue,
            defaultValue.style
          ),
          variant: helpers.coerceString(
            attributeDefinition.variant,
            variantValue,
            defaultValue.variant
          ),
          textcase: helpers.coerceString(
            attributeDefinition.variant,
            textcaseValue,
            defaultValue.textcase
          ),
          lineposition: helpers.coerceString(
            attributeDefinition.variant,
            linepositionValue,
            defaultValue.lineposition
          ),
          shadow: helpers.coerceString(
            attributeDefinition.variant,
            shadowValue,
            defaultValue.shadow
          )
        };
      }
      function getBarColor(cd, trace) {
        if (trace.type === "waterfall") {
          return trace[cd.dir].marker.color;
        }
        return cd.mcc || cd.mc || trace.marker.color;
      }
      module.exports = {
        style,
        styleTextPoints,
        styleOnSelect,
        getInsideTextFont,
        getOutsideTextFont,
        getBarColor,
        resizeText
      };
    }
  });

  // src/traces/bar/plot.js
  var require_plot3 = __commonJS({
    "src/traces/bar/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var svgTextUtils = require_svg_text_utils();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Registry = require_registry();
      var tickText = require_axes().tickText;
      var uniformText = require_uniform_text();
      var recordMinTextSize = uniformText.recordMinTextSize;
      var clearMinTextSize = uniformText.clearMinTextSize;
      var style = require_style4();
      var helpers = require_helpers12();
      var constants = require_constants9();
      var attributes = require_attributes23();
      var attributeText = attributes.text;
      var attributeTextPosition = attributes.textposition;
      var appendArrayPointValue = require_helpers2().appendArrayPointValue;
      var TEXTPAD = constants.TEXTPAD;
      function keyFunc(d) {
        return d.id;
      }
      function getKeyFunc(trace) {
        if (trace.ids) {
          return keyFunc;
        }
      }
      function sign(v) {
        return (v > 0) - (v < 0);
      }
      function dirSign(a, b) {
        return a < b ? 1 : -1;
      }
      function getXY(di, xa, ya, isHorizontal) {
        var s = [];
        var p = [];
        var sAxis = isHorizontal ? xa : ya;
        var pAxis = isHorizontal ? ya : xa;
        s[0] = sAxis.c2p(di.s0, true);
        p[0] = pAxis.c2p(di.p0, true);
        s[1] = sAxis.c2p(di.s1, true);
        p[1] = pAxis.c2p(di.p1, true);
        return isHorizontal ? [s, p] : [p, s];
      }
      function transition(selection, fullLayout, opts, makeOnCompleteCallback) {
        if (!fullLayout.uniformtext.mode && hasTransition(opts)) {
          var onComplete;
          if (makeOnCompleteCallback) {
            onComplete = makeOnCompleteCallback();
          }
          return selection.transition().duration(opts.duration).ease(opts.easing).each("end", function() {
            onComplete && onComplete();
          }).each("interrupt", function() {
            onComplete && onComplete();
          });
        } else {
          return selection;
        }
      }
      function hasTransition(transitionOpts) {
        return transitionOpts && transitionOpts.duration > 0;
      }
      function plot(gd, plotinfo, cdModule, traceLayer, opts, makeOnCompleteCallback) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var fullLayout = gd._fullLayout;
        var isStatic = gd._context.staticPlot;
        if (!opts) {
          opts = {
            mode: fullLayout.barmode,
            norm: fullLayout.barmode,
            gap: fullLayout.bargap,
            groupgap: fullLayout.bargroupgap
          };
          clearMinTextSize("bar", fullLayout);
        }
        var bartraces = Lib.makeTraceGroups(traceLayer, cdModule, "trace bars").each(function(cd) {
          var plotGroup = d3.select(this);
          var trace = cd[0].trace;
          var t = cd[0].t;
          var isWaterfall = trace.type === "waterfall";
          var isFunnel = trace.type === "funnel";
          var isHistogram = trace.type === "histogram";
          var isBar = trace.type === "bar";
          var shouldDisplayZeros = isBar || isFunnel;
          var adjustPixel = 0;
          if (isWaterfall && trace.connector.visible && trace.connector.mode === "between") {
            adjustPixel = trace.connector.line.width / 2;
          }
          var isHorizontal = trace.orientation === "h";
          var withTransition = hasTransition(opts);
          var pointGroup = Lib.ensureSingle(plotGroup, "g", "points");
          var keyFunc2 = getKeyFunc(trace);
          var bars = pointGroup.selectAll("g.point").data(Lib.identity, keyFunc2);
          bars.enter().append("g").classed("point", true);
          bars.exit().remove();
          bars.each(function(di, i) {
            var bar = d3.select(this);
            var xy = getXY(di, xa, ya, isHorizontal);
            var x0 = xy[0][0];
            var x1 = xy[0][1];
            var y0 = xy[1][0];
            var y1 = xy[1][1];
            var isBlank = (isHorizontal ? x1 - x0 : y1 - y0) === 0;
            if (isBlank && shouldDisplayZeros && helpers.getLineWidth(trace, di)) {
              isBlank = false;
            }
            if (!isBlank) {
              isBlank = !isNumeric(x0) || !isNumeric(x1) || !isNumeric(y0) || !isNumeric(y1);
            }
            di.isBlank = isBlank;
            if (isBlank) {
              if (isHorizontal) {
                x1 = x0;
              } else {
                y1 = y0;
              }
            }
            if (adjustPixel && !isBlank) {
              if (isHorizontal) {
                x0 -= dirSign(x0, x1) * adjustPixel;
                x1 += dirSign(x0, x1) * adjustPixel;
              } else {
                y0 -= dirSign(y0, y1) * adjustPixel;
                y1 += dirSign(y0, y1) * adjustPixel;
              }
            }
            var lw;
            var mc;
            if (trace.type === "waterfall") {
              if (!isBlank) {
                var cont = trace[di.dir].marker;
                lw = cont.line.width;
                mc = cont.color;
              }
            } else {
              lw = helpers.getLineWidth(trace, di);
              mc = di.mc || trace.marker.color;
            }
            function roundWithLine(v) {
              var offset = d3.round(lw / 2 % 1, 2);
              return opts.gap === 0 && opts.groupgap === 0 ? d3.round(Math.round(v) - offset, 2) : v;
            }
            function expandToVisible(v, vc, hideZeroSpan) {
              if (hideZeroSpan && v === vc) {
                return v;
              }
              return Math.abs(v - vc) >= 2 ? roundWithLine(v) : (
                // but if it's very thin, expand it so it's
                // necessarily visible, even if it might overlap
                // its neighbor
                v > vc ? Math.ceil(v) : Math.floor(v)
              );
            }
            var op = Color2.opacity(mc);
            var fixpx = op < 1 || lw > 0.01 ? roundWithLine : expandToVisible;
            if (!gd._context.staticPlot) {
              x0 = fixpx(x0, x1, isHorizontal);
              x1 = fixpx(x1, x0, isHorizontal);
              y0 = fixpx(y0, y1, !isHorizontal);
              y1 = fixpx(y1, y0, !isHorizontal);
            }
            var c2p = isHorizontal ? xa.c2p : ya.c2p;
            var outerBound;
            if (di.s0 > 0) {
              outerBound = di._sMax;
            } else if (di.s0 < 0) {
              outerBound = di._sMin;
            } else {
              outerBound = di.s1 > 0 ? di._sMax : di._sMin;
            }
            function calcCornerRadius(crValue, crForm) {
              if (!crValue) return 0;
              var barWidth = isHorizontal ? Math.abs(y1 - y0) : Math.abs(x1 - x0);
              var barLength = isHorizontal ? Math.abs(x1 - x0) : Math.abs(y1 - y0);
              var stackedBarTotalLength = fixpx(Math.abs(c2p(outerBound, true) - c2p(0, true)));
              var maxRadius = di.hasB ? Math.min(barWidth / 2, barLength / 2) : Math.min(barWidth / 2, stackedBarTotalLength);
              var crPx;
              if (crForm === "%") {
                var crPercent = Math.min(50, crValue);
                crPx = barWidth * (crPercent / 100);
              } else {
                crPx = crValue;
              }
              return fixpx(Math.max(Math.min(crPx, maxRadius), 0));
            }
            var r = isBar || isHistogram ? calcCornerRadius(t.cornerradiusvalue, t.cornerradiusform) : 0;
            var path, h;
            var rectanglePath = "M" + x0 + "," + y0 + "V" + y1 + "H" + x1 + "V" + y0 + "Z";
            var overhead = 0;
            if (r && di.s) {
              var refPoint = sign(di.s0) === 0 || sign(di.s) === sign(di.s0) ? di.s1 : di.s0;
              overhead = fixpx(!di.hasB ? Math.abs(c2p(outerBound, true) - c2p(refPoint, true)) : 0);
              if (overhead < r) {
                var xdir = dirSign(x0, x1);
                var ydir = dirSign(y0, y1);
                var cornersweep = xdir === -ydir ? 1 : 0;
                if (isHorizontal) {
                  if (di.hasB) {
                    path = "M" + (x0 + r * xdir) + "," + y0 + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x0 + "," + (y0 + r * ydir) + "V" + (y1 - r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir) + "," + y1 + "H" + (x1 - r * xdir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir) + "V" + (y0 + r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - r * xdir) + "," + y0 + "Z";
                  } else {
                    h = Math.abs(x1 - x0) + overhead;
                    var dy1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0;
                    var dy2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0;
                    var xminfunc = xdir > 0 ? Math.max : Math.min;
                    path = "M" + x0 + "," + y0 + "V" + (y1 - dy1 * ydir) + "H" + xminfunc(x1 - (r - overhead) * xdir, x0) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir - dy2) + "V" + (y0 + r * ydir + dy2) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + xminfunc(x1 - (r - overhead) * xdir, x0) + "," + (y0 + dy1 * ydir) + "Z";
                  }
                } else {
                  if (di.hasB) {
                    path = "M" + (x0 + r * xdir) + "," + y0 + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x0 + "," + (y0 + r * ydir) + "V" + (y1 - r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir) + "," + y1 + "H" + (x1 - r * xdir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir) + "V" + (y0 + r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - r * xdir) + "," + y0 + "Z";
                  } else {
                    h = Math.abs(y1 - y0) + overhead;
                    var dx1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0;
                    var dx2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0;
                    var yminfunc = ydir > 0 ? Math.max : Math.min;
                    path = "M" + (x0 + dx1 * xdir) + "," + y0 + "V" + yminfunc(y1 - (r - overhead) * ydir, y0) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir - dx2) + "," + y1 + "H" + (x1 - r * xdir + dx2) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - dx1 * xdir) + "," + yminfunc(y1 - (r - overhead) * ydir, y0) + "V" + y0 + "Z";
                  }
                }
              } else {
                path = rectanglePath;
              }
            } else {
              path = rectanglePath;
            }
            var sel = transition(Lib.ensureSingle(bar, "path"), fullLayout, opts, makeOnCompleteCallback);
            sel.style("vector-effect", isStatic ? "none" : "non-scaling-stroke").attr("d", isNaN((x1 - x0) * (y1 - y0)) || isBlank && gd._context.staticPlot ? "M0,0Z" : path).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
            if (!fullLayout.uniformtext.mode && withTransition) {
              var styleFns = Drawing.makePointStyleFns(trace);
              Drawing.singlePointStyle(di, sel, trace, styleFns, gd);
            }
            appendBarText(gd, plotinfo, bar, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback);
            if (plotinfo.layerClipId) {
              Drawing.hideOutsideRangePoint(di, bar.select("text"), xa, ya, trace.xcalendar, trace.ycalendar);
            }
          });
          var hasClipOnAxisFalse = trace.cliponaxis === false;
          Drawing.setClipUrl(plotGroup, hasClipOnAxisFalse ? null : plotinfo.layerClipId, gd);
        });
        Registry.getComponentMethod("errorbars", "plot")(gd, bartraces, plotinfo, opts);
      }
      function appendBarText(gd, plotinfo, bar, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var fullLayout = gd._fullLayout;
        var textPosition;
        function appendTextNode(bar2, text2, font2) {
          var textSelection2 = Lib.ensureSingle(bar2, "text").text(text2).attr({
            class: "bartext bartext-" + textPosition,
            "text-anchor": "middle",
            // prohibit tex interpretation until we can handle
            // tex and regular text together
            "data-notex": 1
          }).call(Drawing.font, font2).call(svgTextUtils.convertToTspans, gd);
          return textSelection2;
        }
        var trace = cd[0].trace;
        var isHorizontal = trace.orientation === "h";
        var text = getText(fullLayout, cd, i, xa, ya);
        textPosition = getTextPosition(trace, i);
        var inStackOrRelativeMode = opts.mode === "stack" || opts.mode === "relative";
        var calcBar = cd[i];
        var isOutmostBar = !inStackOrRelativeMode || calcBar._outmost;
        var hasB = calcBar.hasB;
        var barIsRounded = r && r - overhead > TEXTPAD;
        if (!text || textPosition === "none" || (calcBar.isBlank || x0 === x1 || y0 === y1) && (textPosition === "auto" || textPosition === "inside")) {
          bar.select("text").remove();
          return;
        }
        var layoutFont = fullLayout.font;
        var barColor = style.getBarColor(cd[i], trace);
        var insideTextFont = style.getInsideTextFont(trace, i, layoutFont, barColor);
        var outsideTextFont = style.getOutsideTextFont(trace, i, layoutFont);
        var insidetextanchor = trace.insidetextanchor || "end";
        var di = bar.datum();
        if (isHorizontal) {
          if (xa.type === "log" && di.s0 <= 0) {
            if (xa.range[0] < xa.range[1]) {
              x0 = 0;
            } else {
              x0 = xa._length;
            }
          }
        } else {
          if (ya.type === "log" && di.s0 <= 0) {
            if (ya.range[0] < ya.range[1]) {
              y0 = ya._length;
            } else {
              y0 = 0;
            }
          }
        }
        var lx = Math.abs(x1 - x0);
        var ly = Math.abs(y1 - y0);
        var barWidth = lx - 2 * TEXTPAD;
        var barHeight = ly - 2 * TEXTPAD;
        var textSelection;
        var textBB;
        var textWidth;
        var textHeight;
        var font;
        if (textPosition === "outside") {
          if (!isOutmostBar && !calcBar.hasB) textPosition = "inside";
        }
        if (textPosition === "auto") {
          if (isOutmostBar) {
            textPosition = "inside";
            font = Lib.ensureUniformFontSize(gd, insideTextFont);
            textSelection = appendTextNode(bar, text, font);
            textBB = Drawing.bBox(textSelection.node());
            textWidth = textBB.width;
            textHeight = textBB.height;
            var textHasSize = textWidth > 0 && textHeight > 0;
            var fitsInside;
            if (barIsRounded) {
              if (hasB) {
                fitsInside = textfitsInsideBar(barWidth - 2 * r, barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth, barHeight - 2 * r, textWidth, textHeight, isHorizontal);
              } else if (isHorizontal) {
                fitsInside = textfitsInsideBar(barWidth - (r - overhead), barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(
                  barWidth,
                  barHeight - 2 * (r - overhead),
                  textWidth,
                  textHeight,
                  isHorizontal
                );
              } else {
                fitsInside = textfitsInsideBar(barWidth, barHeight - (r - overhead), textWidth, textHeight, isHorizontal) || textfitsInsideBar(
                  barWidth - 2 * (r - overhead),
                  barHeight,
                  textWidth,
                  textHeight,
                  isHorizontal
                );
              }
            } else {
              fitsInside = textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal);
            }
            if (textHasSize && fitsInside) {
              textPosition = "inside";
            } else {
              textPosition = "outside";
              textSelection.remove();
              textSelection = null;
            }
          } else {
            textPosition = "inside";
          }
        }
        if (!textSelection) {
          font = Lib.ensureUniformFontSize(gd, textPosition === "outside" ? outsideTextFont : insideTextFont);
          textSelection = appendTextNode(bar, text, font);
          var currentTransform = textSelection.attr("transform");
          textSelection.attr("transform", "");
          textBB = Drawing.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height;
          textSelection.attr("transform", currentTransform);
          if (textWidth <= 0 || textHeight <= 0) {
            textSelection.remove();
            return;
          }
        }
        var angle = trace.textangle;
        var transform, constrained;
        if (textPosition === "outside") {
          constrained = trace.constraintext === "both" || trace.constraintext === "outside";
          transform = toMoveOutsideBar(x0, x1, y0, y1, textBB, {
            isHorizontal,
            constrained,
            angle
          });
        } else {
          constrained = trace.constraintext === "both" || trace.constraintext === "inside";
          transform = toMoveInsideBar(x0, x1, y0, y1, textBB, {
            isHorizontal,
            constrained,
            angle,
            anchor: insidetextanchor,
            hasB,
            r,
            overhead
          });
        }
        transform.fontSize = font.size;
        recordMinTextSize(trace.type === "histogram" ? "bar" : trace.type, transform, fullLayout);
        calcBar.transform = transform;
        var s = transition(textSelection, fullLayout, opts, makeOnCompleteCallback);
        Lib.setTransormAndDisplay(s, transform);
      }
      function textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal) {
        if (barWidth < 0 || barHeight < 0) return false;
        var fitsInside = textWidth <= barWidth && textHeight <= barHeight;
        var fitsInsideIfRotated = textWidth <= barHeight && textHeight <= barWidth;
        var fitsInsideIfShrunk = isHorizontal ? barWidth >= textWidth * (barHeight / textHeight) : barHeight >= textHeight * (barWidth / textWidth);
        return fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk;
      }
      function getRotateFromAngle(angle) {
        return angle === "auto" ? 0 : angle;
      }
      function getRotatedTextSize(textBB, rotate) {
        var a = Math.PI / 180 * rotate;
        var absSin = Math.abs(Math.sin(a));
        var absCos = Math.abs(Math.cos(a));
        return {
          x: textBB.width * absCos + textBB.height * absSin,
          y: textBB.width * absSin + textBB.height * absCos
        };
      }
      function toMoveInsideBar(x0, x1, y0, y1, textBB, opts) {
        var isHorizontal = !!opts.isHorizontal;
        var constrained = !!opts.constrained;
        var angle = opts.angle || 0;
        var anchor = opts.anchor;
        var isEnd = anchor === "end";
        var isStart = anchor === "start";
        var leftToRight = opts.leftToRight || 0;
        var toRight = (leftToRight + 1) / 2;
        var toLeft = 1 - toRight;
        var hasB = opts.hasB;
        var r = opts.r;
        var overhead = opts.overhead;
        var textWidth = textBB.width;
        var textHeight = textBB.height;
        var lx = Math.abs(x1 - x0);
        var ly = Math.abs(y1 - y0);
        var textpad = lx > 2 * TEXTPAD && ly > 2 * TEXTPAD ? TEXTPAD : 0;
        lx -= 2 * textpad;
        ly -= 2 * textpad;
        var rotate = getRotateFromAngle(angle);
        if (angle === "auto" && !(textWidth <= lx && textHeight <= ly) && (textWidth > lx || textHeight > ly) && (!(textWidth > ly || textHeight > lx) || textWidth < textHeight !== lx < ly)) {
          rotate += 90;
        }
        var t = getRotatedTextSize(textBB, rotate);
        var scale, padForRounding;
        if (r && r - overhead > TEXTPAD) {
          var scaleAndPad = scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB);
          scale = scaleAndPad.scale;
          padForRounding = scaleAndPad.pad;
        } else {
          scale = 1;
          if (constrained) {
            scale = Math.min(1, lx / t.x, ly / t.y);
          }
          padForRounding = 0;
        }
        var textX = textBB.left * toLeft + textBB.right * toRight;
        var textY = (textBB.top + textBB.bottom) / 2;
        var targetX = (x0 + TEXTPAD) * toLeft + (x1 - TEXTPAD) * toRight;
        var targetY = (y0 + y1) / 2;
        var anchorX = 0;
        var anchorY = 0;
        if (isStart || isEnd) {
          var extrapad = (isHorizontal ? t.x : t.y) / 2;
          if (r && (isEnd || hasB)) {
            textpad += padForRounding;
          }
          var dir = isHorizontal ? dirSign(x0, x1) : dirSign(y0, y1);
          if (isHorizontal) {
            if (isStart) {
              targetX = x0 + dir * textpad;
              anchorX = -dir * extrapad;
            } else {
              targetX = x1 - dir * textpad;
              anchorX = dir * extrapad;
            }
          } else {
            if (isStart) {
              targetY = y0 + dir * textpad;
              anchorY = -dir * extrapad;
            } else {
              targetY = y1 - dir * textpad;
              anchorY = dir * extrapad;
            }
          }
        }
        return {
          textX,
          textY,
          targetX,
          targetY,
          anchorX,
          anchorY,
          scale,
          rotate
        };
      }
      function scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB) {
        var barWidth = Math.max(0, Math.abs(x1 - x0) - 2 * TEXTPAD);
        var barHeight = Math.max(0, Math.abs(y1 - y0) - 2 * TEXTPAD);
        var R = r - TEXTPAD;
        var clippedR = overhead ? R - Math.sqrt(R * R - (R - overhead) * (R - overhead)) : R;
        var rX = hasB ? R * 2 : isHorizontal ? R - overhead : 2 * clippedR;
        var rY = hasB ? R * 2 : isHorizontal ? 2 * clippedR : R - overhead;
        var a, b, c;
        var scale, pad;
        if (t.y / t.x >= barHeight / (barWidth - rX)) {
          scale = barHeight / t.y;
        } else if (t.y / t.x <= (barHeight - rY) / barWidth) {
          scale = barWidth / t.x;
        } else if (!hasB && isHorizontal) {
          a = t.x * t.x + t.y * t.y / 4;
          b = -2 * t.x * (barWidth - R) - t.y * (barHeight / 2 - R);
          c = (barWidth - R) * (barWidth - R) + (barHeight / 2 - R) * (barHeight / 2 - R) - R * R;
          scale = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
        } else if (!hasB) {
          a = t.x * t.x / 4 + t.y * t.y;
          b = -t.x * (barWidth / 2 - R) - 2 * t.y * (barHeight - R);
          c = (barWidth / 2 - R) * (barWidth / 2 - R) + (barHeight - R) * (barHeight - R) - R * R;
          scale = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
        } else {
          a = (t.x * t.x + t.y * t.y) / 4;
          b = -t.x * (barWidth / 2 - R) - t.y * (barHeight / 2 - R);
          c = (barWidth / 2 - R) * (barWidth / 2 - R) + (barHeight / 2 - R) * (barHeight / 2 - R) - R * R;
          scale = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
        }
        scale = Math.min(1, scale);
        if (isHorizontal) {
          pad = Math.max(
            0,
            R - Math.sqrt(
              Math.max(0, R * R - (R - (barHeight - t.y * scale) / 2) * (R - (barHeight - t.y * scale) / 2))
            ) - overhead
          );
        } else {
          pad = Math.max(
            0,
            R - Math.sqrt(
              Math.max(0, R * R - (R - (barWidth - t.x * scale) / 2) * (R - (barWidth - t.x * scale) / 2))
            ) - overhead
          );
        }
        return { scale, pad };
      }
      function toMoveOutsideBar(x0, x1, y0, y1, textBB, opts) {
        var isHorizontal = !!opts.isHorizontal;
        var constrained = !!opts.constrained;
        var angle = opts.angle || 0;
        var textWidth = textBB.width;
        var textHeight = textBB.height;
        var lx = Math.abs(x1 - x0);
        var ly = Math.abs(y1 - y0);
        var textpad;
        if (isHorizontal) {
          textpad = ly > 2 * TEXTPAD ? TEXTPAD : 0;
        } else {
          textpad = lx > 2 * TEXTPAD ? TEXTPAD : 0;
        }
        var scale = 1;
        if (constrained) {
          scale = isHorizontal ? Math.min(1, ly / textHeight) : Math.min(1, lx / textWidth);
        }
        var rotate = getRotateFromAngle(angle);
        var t = getRotatedTextSize(textBB, rotate);
        var extrapad = (isHorizontal ? t.x : t.y) / 2;
        var textX = (textBB.left + textBB.right) / 2;
        var textY = (textBB.top + textBB.bottom) / 2;
        var targetX = (x0 + x1) / 2;
        var targetY = (y0 + y1) / 2;
        var anchorX = 0;
        var anchorY = 0;
        var dir = isHorizontal ? dirSign(x1, x0) : dirSign(y0, y1);
        if (isHorizontal) {
          targetX = x1 - dir * textpad;
          anchorX = dir * extrapad;
        } else {
          targetY = y1 + dir * textpad;
          anchorY = -dir * extrapad;
        }
        return {
          textX,
          textY,
          targetX,
          targetY,
          anchorX,
          anchorY,
          scale,
          rotate
        };
      }
      function getText(fullLayout, cd, index, xa, ya) {
        var trace = cd[0].trace;
        var texttemplate = trace.texttemplate;
        var value;
        if (texttemplate) {
          value = calcTexttemplate(fullLayout, cd, index, xa, ya);
        } else if (trace.textinfo) {
          value = calcTextinfo(cd, index, xa, ya);
        } else {
          value = helpers.getValue(trace.text, index);
        }
        return helpers.coerceString(attributeText, value);
      }
      function getTextPosition(trace, index) {
        var value = helpers.getValue(trace.textposition, index);
        return helpers.coerceEnumerated(attributeTextPosition, value);
      }
      function calcTexttemplate(fullLayout, cd, index, xa, ya) {
        var trace = cd[0].trace;
        var texttemplate = Lib.castOption(trace, index, "texttemplate");
        if (!texttemplate) return "";
        var isHistogram = trace.type === "histogram";
        var isWaterfall = trace.type === "waterfall";
        var isFunnel = trace.type === "funnel";
        var isHorizontal = trace.orientation === "h";
        var pLetter, pAxis;
        var vLetter, vAxis;
        if (isHorizontal) {
          pLetter = "y";
          pAxis = ya;
          vLetter = "x";
          vAxis = xa;
        } else {
          pLetter = "x";
          pAxis = xa;
          vLetter = "y";
          vAxis = ya;
        }
        function formatLabel(u) {
          return tickText(pAxis, pAxis.c2l(u), true).text;
        }
        function formatNumber(v) {
          return tickText(vAxis, vAxis.c2l(v), true).text;
        }
        var cdi = cd[index];
        var obj = {};
        obj.label = cdi.p;
        obj.labelLabel = obj[pLetter + "Label"] = formatLabel(cdi.p);
        var tx = Lib.castOption(trace, cdi.i, "text");
        if (tx === 0 || tx) obj.text = tx;
        obj.value = cdi.s;
        obj.valueLabel = obj[vLetter + "Label"] = formatNumber(cdi.s);
        var pt = {};
        appendArrayPointValue(pt, trace, cdi.i);
        if (isHistogram || pt.x === void 0) pt.x = isHorizontal ? obj.value : obj.label;
        if (isHistogram || pt.y === void 0) pt.y = isHorizontal ? obj.label : obj.value;
        if (isHistogram || pt.xLabel === void 0) pt.xLabel = isHorizontal ? obj.valueLabel : obj.labelLabel;
        if (isHistogram || pt.yLabel === void 0) pt.yLabel = isHorizontal ? obj.labelLabel : obj.valueLabel;
        if (isWaterfall) {
          obj.delta = +cdi.rawS || cdi.s;
          obj.deltaLabel = formatNumber(obj.delta);
          obj.final = cdi.v;
          obj.finalLabel = formatNumber(obj.final);
          obj.initial = obj.final - obj.delta;
          obj.initialLabel = formatNumber(obj.initial);
        }
        if (isFunnel) {
          obj.value = cdi.s;
          obj.valueLabel = formatNumber(obj.value);
          obj.percentInitial = cdi.begR;
          obj.percentInitialLabel = Lib.formatPercent(cdi.begR);
          obj.percentPrevious = cdi.difR;
          obj.percentPreviousLabel = Lib.formatPercent(cdi.difR);
          obj.percentTotal = cdi.sumR;
          obj.percenTotalLabel = Lib.formatPercent(cdi.sumR);
        }
        var customdata = Lib.castOption(trace, cdi.i, "customdata");
        if (customdata) obj.customdata = customdata;
        return Lib.texttemplateString({
          data: [pt, obj, trace._meta],
          fallback: trace.texttemplatefallback,
          labels: obj,
          locale: fullLayout._d3locale,
          template: texttemplate
        });
      }
      function calcTextinfo(cd, index, xa, ya) {
        var trace = cd[0].trace;
        var isHorizontal = trace.orientation === "h";
        var isWaterfall = trace.type === "waterfall";
        var isFunnel = trace.type === "funnel";
        function formatLabel(u) {
          var pAxis = isHorizontal ? ya : xa;
          return tickText(pAxis, u, true).text;
        }
        function formatNumber(v) {
          var sAxis = isHorizontal ? xa : ya;
          return tickText(sAxis, +v, true).text;
        }
        var textinfo = trace.textinfo;
        var cdi = cd[index];
        var parts = textinfo.split("+");
        var text = [];
        var tx;
        var hasFlag = function(flag) {
          return parts.indexOf(flag) !== -1;
        };
        if (hasFlag("label")) {
          text.push(formatLabel(cd[index].p));
        }
        if (hasFlag("text")) {
          tx = Lib.castOption(trace, cdi.i, "text");
          if (tx === 0 || tx) text.push(tx);
        }
        if (isWaterfall) {
          var delta = +cdi.rawS || cdi.s;
          var final = cdi.v;
          var initial = final - delta;
          if (hasFlag("initial")) text.push(formatNumber(initial));
          if (hasFlag("delta")) text.push(formatNumber(delta));
          if (hasFlag("final")) text.push(formatNumber(final));
        }
        if (isFunnel) {
          if (hasFlag("value")) text.push(formatNumber(cdi.s));
          var nPercent = 0;
          if (hasFlag("percent initial")) nPercent++;
          if (hasFlag("percent previous")) nPercent++;
          if (hasFlag("percent total")) nPercent++;
          var hasMultiplePercents = nPercent > 1;
          if (hasFlag("percent initial")) {
            tx = Lib.formatPercent(cdi.begR);
            if (hasMultiplePercents) tx += " of initial";
            text.push(tx);
          }
          if (hasFlag("percent previous")) {
            tx = Lib.formatPercent(cdi.difR);
            if (hasMultiplePercents) tx += " of previous";
            text.push(tx);
          }
          if (hasFlag("percent total")) {
            tx = Lib.formatPercent(cdi.sumR);
            if (hasMultiplePercents) tx += " of total";
            text.push(tx);
          }
        }
        return text.join("<br>");
      }
      module.exports = {
        plot,
        toMoveInsideBar
      };
    }
  });

  // src/traces/bar/hover.js
  var require_hover3 = __commonJS({
    "src/traces/bar/hover.js"(exports, module) {
      "use strict";
      var Fx = require_fx();
      var Registry = require_registry();
      var Color2 = require_color();
      var fillText = require_lib().fillText;
      var getLineWidth = require_helpers12().getLineWidth;
      var hoverLabelText = require_axes().hoverLabelText;
      var BADNUM = require_numerical().BADNUM;
      function hoverPoints(pointData, xval, yval, hovermode, opts) {
        var barPointData = hoverOnBars(pointData, xval, yval, hovermode, opts);
        if (barPointData) {
          var cd = barPointData.cd;
          var trace = cd[0].trace;
          var di = cd[barPointData.index];
          barPointData.color = getTraceColor(trace, di);
          Registry.getComponentMethod("errorbars", "hoverInfo")(di, trace, barPointData);
          return [barPointData];
        }
      }
      function hoverOnBars(pointData, xval, yval, hovermode, opts) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var t = cd[0].t;
        var isClosest = hovermode === "closest";
        var isWaterfall = trace.type === "waterfall";
        var maxHoverDistance = pointData.maxHoverDistance;
        var maxSpikeDistance = pointData.maxSpikeDistance;
        var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc;
        if (trace.orientation === "h") {
          posVal = yval;
          sizeVal = xval;
          posLetter = "y";
          sizeLetter = "x";
          dx = sizeFn;
          dy = positionFn;
        } else {
          posVal = xval;
          sizeVal = yval;
          posLetter = "x";
          sizeLetter = "y";
          dy = sizeFn;
          dx = positionFn;
        }
        var period = trace[posLetter + "period"];
        var isClosestOrPeriod = isClosest || period;
        function thisBarMinPos(di2) {
          return thisBarExtPos(di2, -1);
        }
        function thisBarMaxPos(di2) {
          return thisBarExtPos(di2, 1);
        }
        function thisBarExtPos(di2, sgn) {
          var w = di2.w;
          return di2[posLetter] + sgn * w / 2;
        }
        function periodLength(di2) {
          return di2[posLetter + "End"] - di2[posLetter + "Start"];
        }
        var minPos = isClosest ? thisBarMinPos : period ? function(di2) {
          return di2.p - periodLength(di2) / 2;
        } : function(di2) {
          return Math.min(thisBarMinPos(di2), di2.p - t.bardelta / 2);
        };
        var maxPos = isClosest ? thisBarMaxPos : period ? function(di2) {
          return di2.p + periodLength(di2) / 2;
        } : function(di2) {
          return Math.max(thisBarMaxPos(di2), di2.p + t.bardelta / 2);
        };
        function inbox(_minPos, _maxPos, maxDistance) {
          if (opts.finiteRange) maxDistance = 0;
          return Fx.inbox(
            _minPos - posVal,
            _maxPos - posVal,
            maxDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1
          );
        }
        function positionFn(di2) {
          return inbox(minPos(di2), maxPos(di2), maxHoverDistance);
        }
        function thisBarPositionFn(di2) {
          return inbox(thisBarMinPos(di2), thisBarMaxPos(di2), maxSpikeDistance);
        }
        function getSize(di2) {
          var s = di2[sizeLetter];
          if (isWaterfall) {
            var rawS = Math.abs(di2.rawS) || 0;
            if (sizeVal > 0) {
              s += rawS;
            } else if (sizeVal < 0) {
              s -= rawS;
            }
          }
          return s;
        }
        function sizeFn(di2) {
          var v = sizeVal;
          var b = di2.b;
          var s = getSize(di2);
          return Fx.inbox(b - v, s - v, maxHoverDistance + (s - v) / (s - b) - 1);
        }
        function thisBarSizeFn(di2) {
          var v = sizeVal;
          var b = di2.b;
          var s = getSize(di2);
          return Fx.inbox(b - v, s - v, maxSpikeDistance + (s - v) / (s - b) - 1);
        }
        var pa = pointData[posLetter + "a"];
        var sa = pointData[sizeLetter + "a"];
        pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0]));
        function dxy(di2) {
          return (dx(di2) + dy(di2)) / 2;
        }
        var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
        Fx.getClosest(cd, distfn, pointData);
        if (pointData.index === false) return;
        if (cd[pointData.index].p === BADNUM) return;
        if (!isClosestOrPeriod) {
          minPos = function(di2) {
            return Math.min(thisBarMinPos(di2), di2.p - t.bargroupwidth / 2);
          };
          maxPos = function(di2) {
            return Math.max(thisBarMaxPos(di2), di2.p + t.bargroupwidth / 2);
          };
        }
        var index = pointData.index;
        var di = cd[index];
        var size = trace.base ? di.b + di.s : di.s;
        pointData[sizeLetter + "0"] = pointData[sizeLetter + "1"] = sa.c2p(di[sizeLetter], true);
        pointData[sizeLetter + "LabelVal"] = size;
        var extent = t.extents[t.extents.round(di.p)];
        pointData[posLetter + "0"] = pa.c2p(isClosest ? minPos(di) : extent[0], true);
        pointData[posLetter + "1"] = pa.c2p(isClosest ? maxPos(di) : extent[1], true);
        var hasPeriod = di.orig_p !== void 0;
        pointData[posLetter + "LabelVal"] = hasPeriod ? di.orig_p : di.p;
        pointData.labelLabel = hoverLabelText(pa, pointData[posLetter + "LabelVal"], trace[posLetter + "hoverformat"]);
        pointData.valueLabel = hoverLabelText(sa, pointData[sizeLetter + "LabelVal"], trace[sizeLetter + "hoverformat"]);
        pointData.baseLabel = hoverLabelText(sa, di.b, trace[sizeLetter + "hoverformat"]);
        pointData.spikeDistance = (thisBarSizeFn(di) + thisBarPositionFn(di)) / 2;
        pointData[posLetter + "Spike"] = pa.c2p(di.p, true);
        fillText(di, trace, pointData);
        pointData.hovertemplate = trace.hovertemplate;
        return pointData;
      }
      function getTraceColor(trace, di) {
        var mc = di.mcc || trace.marker.color;
        var mlc = di.mlcc || trace.marker.line.color;
        var mlw = getLineWidth(trace, di);
        if (Color2.opacity(mc)) return mc;
        else if (Color2.opacity(mlc) && mlw) return mlc;
      }
      module.exports = {
        hoverPoints,
        hoverOnBars,
        getTraceColor
      };
    }
  });

  // src/traces/bar/event_data.js
  var require_event_data = __commonJS({
    "src/traces/bar/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt, trace) {
        out.x = "xVal" in pt ? pt.xVal : pt.x;
        out.y = "yVal" in pt ? pt.yVal : pt.y;
        if (pt.xa) out.xaxis = pt.xa;
        if (pt.ya) out.yaxis = pt.ya;
        if (trace.orientation === "h") {
          out.label = out.y;
          out.value = out.x;
        } else {
          out.label = out.x;
          out.value = out.y;
        }
        return out;
      };
    }
  });

  // src/traces/bar/select.js
  var require_select3 = __commonJS({
    "src/traces/bar/select.js"(exports, module) {
      "use strict";
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var trace = cd[0].trace;
        var isFunnel = trace.type === "funnel";
        var isHorizontal = trace.orientation === "h";
        var selection = [];
        var i;
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            var di = cd[i];
            var ct = "ct" in di ? di.ct : getCentroid(di, xa, ya, isHorizontal, isFunnel);
            if (selectionTester.contains(ct, false, i, searchInfo)) {
              selection.push({
                pointNumber: i,
                x: xa.c2d(di.x),
                y: ya.c2d(di.y)
              });
              di.selected = 1;
            } else {
              di.selected = 0;
            }
          }
        }
        return selection;
      };
      function getCentroid(d, xa, ya, isHorizontal, isFunnel) {
        var x0 = xa.c2p(isHorizontal ? d.s0 : d.p0, true);
        var x1 = xa.c2p(isHorizontal ? d.s1 : d.p1, true);
        var y0 = ya.c2p(isHorizontal ? d.p0 : d.s0, true);
        var y1 = ya.c2p(isHorizontal ? d.p1 : d.s1, true);
        if (isFunnel) {
          return [(x0 + x1) / 2, (y0 + y1) / 2];
        } else {
          if (isHorizontal) {
            return [x1, (y0 + y1) / 2];
          } else {
            return [(x0 + x1) / 2, y1];
          }
        }
      }
    }
  });

  // src/traces/bar/index.js
  var require_bar = __commonJS({
    "src/traces/bar/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes23(),
        layoutAttributes: require_layout_attributes6(),
        supplyDefaults: require_defaults19().supplyDefaults,
        crossTraceDefaults: require_defaults19().crossTraceDefaults,
        supplyLayoutDefaults: require_layout_defaults5(),
        calc: require_calc5(),
        crossTraceCalc: require_cross_trace_calc().crossTraceCalc,
        colorbar: require_marker_colorbar(),
        arraysToCalcdata: require_arrays_to_calcdata2(),
        plot: require_plot3().plot,
        style: require_style4().style,
        styleOnSelect: require_style4().styleOnSelect,
        hoverPoints: require_hover3().hoverPoints,
        eventData: require_event_data(),
        selectPoints: require_select3(),
        moduleType: "trace",
        name: "bar",
        basePlotModule: require_cartesian(),
        categories: ["bar-like", "cartesian", "svg", "bar", "oriented", "errorBarsOK", "showLegend", "zoomScale"],
        animatable: true,
        meta: {}
      };
    }
  });

  // lib/bar.js
  var require_bar2 = __commonJS({
    "lib/bar.js"(exports, module) {
      "use strict";
      module.exports = require_bar();
    }
  });

  // src/traces/box/attributes.js
  var require_attributes24 = __commonJS({
    "src/traces/box/attributes.js"(exports, module) {
      "use strict";
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterAttrs = require_attributes12();
      var barAttrs = require_attributes23();
      var colorAttrs = require_attributes3();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var extendFlat = require_extend().extendFlat;
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      module.exports = {
        y: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        x: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        x0: {
          valType: "any",
          editType: "calc+clearAxisTypes"
        },
        y0: {
          valType: "any",
          editType: "calc+clearAxisTypes"
        },
        dx: {
          valType: "number",
          editType: "calc"
        },
        dy: {
          valType: "number",
          editType: "calc"
        },
        xperiod: scatterAttrs.xperiod,
        yperiod: scatterAttrs.yperiod,
        xperiod0: scatterAttrs.xperiod0,
        yperiod0: scatterAttrs.yperiod0,
        xperiodalignment: scatterAttrs.xperiodalignment,
        yperiodalignment: scatterAttrs.yperiodalignment,
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        name: {
          valType: "string",
          editType: "calc+clearAxisTypes"
        },
        q1: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        median: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        q3: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        lowerfence: {
          valType: "data_array",
          editType: "calc"
        },
        upperfence: {
          valType: "data_array",
          editType: "calc"
        },
        notched: {
          valType: "boolean",
          editType: "calc"
        },
        notchwidth: {
          valType: "number",
          min: 0,
          max: 0.5,
          dflt: 0.25,
          editType: "calc"
        },
        notchspan: {
          valType: "data_array",
          editType: "calc"
        },
        // TODO
        // maybe add
        // - loweroutlierbound / upperoutlierbound
        // - lowersuspectedoutlierbound / uppersuspectedoutlierbound
        boxpoints: {
          valType: "enumerated",
          values: ["all", "outliers", "suspectedoutliers", false],
          editType: "calc"
        },
        jitter: {
          valType: "number",
          min: 0,
          max: 1,
          editType: "calc"
        },
        pointpos: {
          valType: "number",
          min: -2,
          max: 2,
          editType: "calc"
        },
        sdmultiple: {
          valType: "number",
          min: 0,
          editType: "calc",
          dflt: 1
        },
        sizemode: {
          valType: "enumerated",
          values: ["quartiles", "sd"],
          editType: "calc",
          dflt: "quartiles"
        },
        boxmean: {
          valType: "enumerated",
          values: [true, "sd", false],
          editType: "calc"
        },
        mean: {
          valType: "data_array",
          editType: "calc"
        },
        sd: {
          valType: "data_array",
          editType: "calc"
        },
        orientation: {
          valType: "enumerated",
          values: ["v", "h"],
          editType: "calc+clearAxisTypes"
        },
        quartilemethod: {
          valType: "enumerated",
          values: ["linear", "exclusive", "inclusive"],
          dflt: "linear",
          editType: "calc"
        },
        width: {
          valType: "number",
          min: 0,
          dflt: 0,
          editType: "calc"
        },
        marker: {
          outliercolor: {
            valType: "color",
            dflt: "rgba(0, 0, 0, 0)",
            editType: "style"
          },
          symbol: extendFlat({}, scatterMarkerAttrs.symbol, { arrayOk: false, editType: "plot" }),
          opacity: extendFlat({}, scatterMarkerAttrs.opacity, { arrayOk: false, dflt: 1, editType: "style" }),
          angle: extendFlat({}, scatterMarkerAttrs.angle, { arrayOk: false, editType: "calc" }),
          size: extendFlat({}, scatterMarkerAttrs.size, { arrayOk: false, editType: "calc" }),
          color: extendFlat({}, scatterMarkerAttrs.color, { arrayOk: false, editType: "style" }),
          line: {
            color: extendFlat({}, scatterMarkerLineAttrs.color, {
              arrayOk: false,
              dflt: colorAttrs.defaultLine,
              editType: "style"
            }),
            width: extendFlat({}, scatterMarkerLineAttrs.width, { arrayOk: false, dflt: 0, editType: "style" }),
            outliercolor: {
              valType: "color",
              editType: "style"
            },
            outlierwidth: {
              valType: "number",
              min: 0,
              dflt: 1,
              editType: "style"
            },
            editType: "style"
          },
          editType: "plot"
        },
        line: {
          color: {
            valType: "color",
            editType: "style"
          },
          width: {
            valType: "number",
            min: 0,
            dflt: 2,
            editType: "style"
          },
          editType: "plot"
        },
        fillcolor: makeFillcolorAttr(),
        whiskerwidth: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0.5,
          editType: "calc"
        },
        showwhiskers: {
          valType: "boolean",
          editType: "calc"
        },
        offsetgroup: barAttrs.offsetgroup,
        alignmentgroup: barAttrs.alignmentgroup,
        selected: {
          marker: scatterAttrs.selected.marker,
          editType: "style"
        },
        unselected: {
          marker: scatterAttrs.unselected.marker,
          editType: "style"
        },
        text: extendFlat({}, scatterAttrs.text, {}),
        hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
        hovertemplate: hovertemplateAttrs({}),
        hovertemplatefallback: templatefallbackAttrs(),
        hoveron: {
          valType: "flaglist",
          flags: ["boxes", "points"],
          dflt: "boxes+points",
          editType: "style"
        },
        zorder: scatterAttrs.zorder
      };
    }
  });

  // src/traces/box/layout_attributes.js
  var require_layout_attributes7 = __commonJS({
    "src/traces/box/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        boxmode: {
          valType: "enumerated",
          values: ["group", "overlay"],
          dflt: "overlay",
          editType: "calc"
        },
        boxgap: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0.3,
          editType: "calc"
        },
        boxgroupgap: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0.3,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/box/defaults.js
  var require_defaults20 = __commonJS({
    "src/traces/box/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Registry = require_registry();
      var Color2 = require_color();
      var handlePeriodDefaults = require_period_defaults();
      var handleGroupingDefaults = require_grouping_defaults();
      var autoType = require_axis_autotype();
      var attributes = require_attributes24();
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        handleSampleDefaults(traceIn, traceOut, coerce, layout);
        if (traceOut.visible === false) return;
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        var hasPreCompStats = traceOut._hasPreCompStats;
        if (hasPreCompStats) {
          coerce("lowerfence");
          coerce("upperfence");
        }
        coerce("line.color", (traceIn.marker || {}).color || defaultColor);
        coerce("line.width");
        coerce("fillcolor", Color2.addOpacity(traceOut.line.color, 0.5));
        var boxmeanDflt = false;
        if (hasPreCompStats) {
          var mean = coerce("mean");
          var sd = coerce("sd");
          if (mean && mean.length) {
            boxmeanDflt = true;
            if (sd && sd.length) boxmeanDflt = "sd";
          }
        }
        coerce("whiskerwidth");
        var sizemode = coerce("sizemode");
        var boxmean;
        if (sizemode === "quartiles") {
          boxmean = coerce("boxmean", boxmeanDflt);
        }
        coerce("showwhiskers", sizemode === "quartiles");
        if (sizemode === "sd" || boxmean === "sd") {
          coerce("sdmultiple");
        }
        coerce("width");
        coerce("quartilemethod");
        var notchedDflt = false;
        if (hasPreCompStats) {
          var notchspan = coerce("notchspan");
          if (notchspan && notchspan.length) {
            notchedDflt = true;
          }
        } else if (Lib.validate(traceIn.notchwidth, attributes.notchwidth)) {
          notchedDflt = true;
        }
        var notched = coerce("notched", notchedDflt);
        if (notched) coerce("notchwidth");
        handlePointsDefaults(traceIn, traceOut, coerce, { prefix: "box" });
        coerce("zorder");
      }
      function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
        function getDims(arr) {
          var dims = 0;
          if (arr && arr.length) {
            dims += 1;
            if (Lib.isArrayOrTypedArray(arr[0]) && arr[0].length) {
              dims += 1;
            }
          }
          return dims;
        }
        function valid(astr) {
          return Lib.validate(traceIn[astr], attributes[astr]);
        }
        var y = coerce("y");
        var x = coerce("x");
        var sLen;
        if (traceOut.type === "box") {
          var q1 = coerce("q1");
          var median = coerce("median");
          var q3 = coerce("q3");
          traceOut._hasPreCompStats = q1 && q1.length && median && median.length && q3 && q3.length;
          sLen = Math.min(Lib.minRowLength(q1), Lib.minRowLength(median), Lib.minRowLength(q3));
        }
        var yDims = getDims(y);
        var xDims = getDims(x);
        var yLen = yDims && Lib.minRowLength(y);
        var xLen = xDims && Lib.minRowLength(x);
        var calendar = layout.calendar;
        var opts = {
          autotypenumbers: layout.autotypenumbers
        };
        var defaultOrientation, len;
        if (traceOut._hasPreCompStats) {
          switch (String(xDims) + String(yDims)) {
            // no x / no y
            case "00":
              var setInX = valid("x0") || valid("dx");
              var setInY = valid("y0") || valid("dy");
              if (setInY && !setInX) {
                defaultOrientation = "h";
              } else {
                defaultOrientation = "v";
              }
              len = sLen;
              break;
            // just x
            case "10":
              defaultOrientation = "v";
              len = Math.min(sLen, xLen);
              break;
            case "20":
              defaultOrientation = "h";
              len = Math.min(sLen, x.length);
              break;
            // just y
            case "01":
              defaultOrientation = "h";
              len = Math.min(sLen, yLen);
              break;
            case "02":
              defaultOrientation = "v";
              len = Math.min(sLen, y.length);
              break;
            // both
            case "12":
              defaultOrientation = "v";
              len = Math.min(sLen, xLen, y.length);
              break;
            case "21":
              defaultOrientation = "h";
              len = Math.min(sLen, x.length, yLen);
              break;
            case "11":
              len = 0;
              break;
            case "22":
              var hasCategories = false;
              var i;
              for (i = 0; i < x.length; i++) {
                if (autoType(x[i], calendar, opts) === "category") {
                  hasCategories = true;
                  break;
                }
              }
              if (hasCategories) {
                defaultOrientation = "v";
                len = Math.min(sLen, xLen, y.length);
              } else {
                for (i = 0; i < y.length; i++) {
                  if (autoType(y[i], calendar, opts) === "category") {
                    hasCategories = true;
                    break;
                  }
                }
                if (hasCategories) {
                  defaultOrientation = "h";
                  len = Math.min(sLen, x.length, yLen);
                } else {
                  defaultOrientation = "v";
                  len = Math.min(sLen, xLen, y.length);
                }
              }
              break;
          }
        } else if (yDims > 0) {
          defaultOrientation = "v";
          if (xDims > 0) {
            len = Math.min(xLen, yLen);
          } else {
            len = Math.min(yLen);
          }
        } else if (xDims > 0) {
          defaultOrientation = "h";
          len = Math.min(xLen);
        } else {
          len = 0;
        }
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        var orientation = coerce("orientation", defaultOrientation);
        if (traceOut._hasPreCompStats) {
          if (orientation === "v" && xDims === 0) {
            coerce("x0", 0);
            coerce("dx", 1);
          } else if (orientation === "h" && yDims === 0) {
            coerce("y0", 0);
            coerce("dy", 1);
          }
        } else {
          if (orientation === "v" && xDims === 0) {
            coerce("x0");
          } else if (orientation === "h" && yDims === 0) {
            coerce("y0");
          }
        }
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout);
      }
      function handlePointsDefaults(traceIn, traceOut, coerce, opts) {
        var prefix = opts.prefix;
        var outlierColorDflt = Lib.coerce2(traceIn, traceOut, attributes, "marker.outliercolor");
        var lineoutliercolor = coerce("marker.line.outliercolor");
        var modeDflt = "outliers";
        if (traceOut._hasPreCompStats) {
          modeDflt = "all";
        } else if (outlierColorDflt || lineoutliercolor) {
          modeDflt = "suspectedoutliers";
        }
        var mode = coerce(prefix + "points", modeDflt);
        if (mode) {
          coerce("jitter", mode === "all" ? 0.3 : 0);
          coerce("pointpos", mode === "all" ? -1.5 : 0);
          coerce("marker.symbol");
          coerce("marker.opacity");
          coerce("marker.size");
          coerce("marker.angle");
          coerce("marker.color", traceOut.line.color);
          coerce("marker.line.color");
          coerce("marker.line.width");
          if (mode === "suspectedoutliers") {
            coerce("marker.line.outliercolor", traceOut.marker.color);
            coerce("marker.line.outlierwidth");
          }
          coerce("selected.marker.color");
          coerce("unselected.marker.color");
          coerce("selected.marker.size");
          coerce("unselected.marker.size");
          coerce("text");
          coerce("hovertext");
        } else {
          delete traceOut.marker;
        }
        var hoveron = coerce("hoveron");
        if (hoveron === "all" || hoveron.indexOf("points") !== -1) {
          coerce("hovertemplate");
          coerce("hovertemplatefallback");
        }
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      }
      function crossTraceDefaults(fullData, fullLayout) {
        var traceIn, traceOut;
        function coerce(attr) {
          return Lib.coerce(traceOut._input, traceOut, attributes, attr);
        }
        for (var i = 0; i < fullData.length; i++) {
          traceOut = fullData[i];
          var traceType = traceOut.type;
          if (traceType === "box" || traceType === "violin") {
            traceIn = traceOut._input;
            var mode = fullLayout[traceType + "mode"];
            if (mode === "group") {
              handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce, mode);
            }
          }
        }
      }
      module.exports = {
        supplyDefaults,
        crossTraceDefaults,
        handleSampleDefaults,
        handlePointsDefaults
      };
    }
  });

  // src/traces/box/layout_defaults.js
  var require_layout_defaults6 = __commonJS({
    "src/traces/box/layout_defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes7();
      function _supply(layoutIn, layoutOut, fullData, coerce, traceType) {
        var category = traceType + "Layout";
        var hasTraceType = false;
        for (var i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          if (Registry.traceIs(trace, category)) {
            hasTraceType = true;
            break;
          }
        }
        if (!hasTraceType) return;
        coerce(traceType + "mode");
        coerce(traceType + "gap");
        coerce(traceType + "groupgap");
      }
      function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        _supply(layoutIn, layoutOut, fullData, coerce, "box");
      }
      module.exports = {
        supplyLayoutDefaults,
        _supply
      };
    }
  });

  // src/traces/box/calc.js
  var require_calc6 = __commonJS({
    "src/traces/box/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var Lib = require_lib();
      var BADNUM = require_numerical().BADNUM;
      var _ = Lib._;
      module.exports = function calc(gd, trace) {
        var fullLayout = gd._fullLayout;
        var xa = Axes.getFromId(gd, trace.xaxis || "x");
        var ya = Axes.getFromId(gd, trace.yaxis || "y");
        var cd = [];
        var numKey = trace.type === "violin" ? "_numViolins" : "_numBoxes";
        var i, j;
        var valAxis, valLetter;
        var posAxis, posLetter;
        var hasPeriod;
        if (trace.orientation === "h") {
          valAxis = xa;
          valLetter = "x";
          posAxis = ya;
          posLetter = "y";
          hasPeriod = !!trace.yperiodalignment;
        } else {
          valAxis = ya;
          valLetter = "y";
          posAxis = xa;
          posLetter = "x";
          hasPeriod = !!trace.xperiodalignment;
        }
        var allPosArrays = getPosArrays(trace, posLetter, posAxis, fullLayout[numKey]);
        var posArray = allPosArrays[0];
        var origPos = allPosArrays[1];
        var dv = Lib.distinctVals(posArray, posAxis);
        var posDistinct = dv.vals;
        var dPos = dv.minDiff / 2;
        var cdi;
        var pts;
        var boxVals;
        var N;
        var pt;
        var v;
        var ptFilterFn = (trace.boxpoints || trace.points) === "all" ? Lib.identity : function(pt2) {
          return pt2.v < cdi.lf || pt2.v > cdi.uf;
        };
        if (trace._hasPreCompStats) {
          var valArrayRaw = trace[valLetter];
          var d2c = function(k) {
            return valAxis.d2c((trace[k] || [])[i]);
          };
          var minVal = Infinity;
          var maxVal = -Infinity;
          for (i = 0; i < trace._length; i++) {
            var posi = posArray[i];
            if (!isNumeric(posi)) continue;
            cdi = {};
            cdi.pos = cdi[posLetter] = posi;
            if (hasPeriod && origPos) {
              cdi.orig_p = origPos[i];
            }
            cdi.q1 = d2c("q1");
            cdi.med = d2c("median");
            cdi.q3 = d2c("q3");
            pts = [];
            if (valArrayRaw && Lib.isArrayOrTypedArray(valArrayRaw[i])) {
              for (j = 0; j < valArrayRaw[i].length; j++) {
                v = valAxis.d2c(valArrayRaw[i][j]);
                if (v !== BADNUM) {
                  pt = { v, i: [i, j] };
                  arraysToCalcdata(pt, trace, [i, j]);
                  pts.push(pt);
                }
              }
            }
            cdi.pts = pts.sort(sortByVal);
            boxVals = cdi[valLetter] = pts.map(extractVal);
            N = boxVals.length;
            if (cdi.med !== BADNUM && cdi.q1 !== BADNUM && cdi.q3 !== BADNUM && cdi.med >= cdi.q1 && cdi.q3 >= cdi.med) {
              var lf = d2c("lowerfence");
              cdi.lf = lf !== BADNUM && lf <= cdi.q1 ? lf : computeLowerFence(cdi, boxVals, N);
              var uf = d2c("upperfence");
              cdi.uf = uf !== BADNUM && uf >= cdi.q3 ? uf : computeUpperFence(cdi, boxVals, N);
              var mean = d2c("mean");
              cdi.mean = mean !== BADNUM ? mean : N ? Lib.mean(boxVals, N) : (cdi.q1 + cdi.q3) / 2;
              var sd = d2c("sd");
              cdi.sd = mean !== BADNUM && sd >= 0 ? sd : N ? Lib.stdev(boxVals, N, cdi.mean) : cdi.q3 - cdi.q1;
              cdi.lo = computeLowerOutlierBound(cdi);
              cdi.uo = computeUpperOutlierBound(cdi);
              var ns = d2c("notchspan");
              ns = ns !== BADNUM && ns > 0 ? ns : computeNotchSpan(cdi, N);
              cdi.ln = cdi.med - ns;
              cdi.un = cdi.med + ns;
              var imin = cdi.lf;
              var imax = cdi.uf;
              if (trace.boxpoints && boxVals.length) {
                imin = Math.min(imin, boxVals[0]);
                imax = Math.max(imax, boxVals[N - 1]);
              }
              if (trace.notched) {
                imin = Math.min(imin, cdi.ln);
                imax = Math.max(imax, cdi.un);
              }
              cdi.min = imin;
              cdi.max = imax;
            } else {
              Lib.warn([
                "Invalid input - make sure that q1 <= median <= q3",
                "q1 = " + cdi.q1,
                "median = " + cdi.med,
                "q3 = " + cdi.q3
              ].join("\n"));
              var v0;
              if (cdi.med !== BADNUM) {
                v0 = cdi.med;
              } else if (cdi.q1 !== BADNUM) {
                if (cdi.q3 !== BADNUM) v0 = (cdi.q1 + cdi.q3) / 2;
                else v0 = cdi.q1;
              } else if (cdi.q3 !== BADNUM) {
                v0 = cdi.q3;
              } else {
                v0 = 0;
              }
              cdi.med = v0;
              cdi.q1 = cdi.q3 = v0;
              cdi.lf = cdi.uf = v0;
              cdi.mean = cdi.sd = v0;
              cdi.ln = cdi.un = v0;
              cdi.min = cdi.max = v0;
            }
            minVal = Math.min(minVal, cdi.min);
            maxVal = Math.max(maxVal, cdi.max);
            cdi.pts2 = pts.filter(ptFilterFn);
            cd.push(cdi);
          }
          trace._extremes[valAxis._id] = Axes.findExtremes(
            valAxis,
            [minVal, maxVal],
            { padded: true }
          );
        } else {
          var valArray = valAxis.makeCalcdata(trace, valLetter);
          var posBins = makeBins(posDistinct, dPos);
          var pLen = posDistinct.length;
          var ptsPerBin = initNestedArray(pLen);
          for (i = 0; i < trace._length; i++) {
            v = valArray[i];
            if (!isNumeric(v)) continue;
            var n = Lib.findBin(posArray[i], posBins);
            if (n >= 0 && n < pLen) {
              pt = { v, i };
              arraysToCalcdata(pt, trace, i);
              ptsPerBin[n].push(pt);
            }
          }
          var minLowerNotch = Infinity;
          var maxUpperNotch = -Infinity;
          var quartilemethod = trace.quartilemethod;
          var usesExclusive = quartilemethod === "exclusive";
          var usesInclusive = quartilemethod === "inclusive";
          for (i = 0; i < pLen; i++) {
            if (ptsPerBin[i].length > 0) {
              cdi = {};
              cdi.pos = cdi[posLetter] = posDistinct[i];
              pts = cdi.pts = ptsPerBin[i].sort(sortByVal);
              boxVals = cdi[valLetter] = pts.map(extractVal);
              N = boxVals.length;
              cdi.min = boxVals[0];
              cdi.max = boxVals[N - 1];
              cdi.mean = Lib.mean(boxVals, N);
              cdi.sd = Lib.stdev(boxVals, N, cdi.mean) * trace.sdmultiple;
              cdi.med = Lib.interp(boxVals, 0.5);
              if (N % 2 && (usesExclusive || usesInclusive)) {
                var lower;
                var upper;
                if (usesExclusive) {
                  lower = boxVals.slice(0, N / 2);
                  upper = boxVals.slice(N / 2 + 1);
                } else if (usesInclusive) {
                  lower = boxVals.slice(0, N / 2 + 1);
                  upper = boxVals.slice(N / 2);
                }
                cdi.q1 = Lib.interp(lower, 0.5);
                cdi.q3 = Lib.interp(upper, 0.5);
              } else {
                cdi.q1 = Lib.interp(boxVals, 0.25);
                cdi.q3 = Lib.interp(boxVals, 0.75);
              }
              cdi.lf = computeLowerFence(cdi, boxVals, N);
              cdi.uf = computeUpperFence(cdi, boxVals, N);
              cdi.lo = computeLowerOutlierBound(cdi);
              cdi.uo = computeUpperOutlierBound(cdi);
              var mci = computeNotchSpan(cdi, N);
              cdi.ln = cdi.med - mci;
              cdi.un = cdi.med + mci;
              minLowerNotch = Math.min(minLowerNotch, cdi.ln);
              maxUpperNotch = Math.max(maxUpperNotch, cdi.un);
              cdi.pts2 = pts.filter(ptFilterFn);
              cd.push(cdi);
            }
          }
          if (trace.notched && Lib.isTypedArray(valArray)) valArray = Array.from(valArray);
          trace._extremes[valAxis._id] = Axes.findExtremes(
            valAxis,
            trace.notched ? valArray.concat([minLowerNotch, maxUpperNotch]) : valArray,
            { padded: true }
          );
        }
        calcSelection(cd, trace);
        if (cd.length > 0) {
          cd[0].t = {
            num: fullLayout[numKey],
            dPos,
            posLetter,
            valLetter,
            labels: {
              med: _(gd, "median:"),
              min: _(gd, "min:"),
              q1: _(gd, "q1:"),
              q3: _(gd, "q3:"),
              max: _(gd, "max:"),
              mean: trace.boxmean === "sd" || trace.sizemode === "sd" ? _(gd, "mean \xB1 \u03C3:").replace("\u03C3", trace.sdmultiple === 1 ? "\u03C3" : trace.sdmultiple + "\u03C3") : (
                // displaying mean +- Nσ whilst supporting translations
                _(gd, "mean:")
              ),
              lf: _(gd, "lower fence:"),
              uf: _(gd, "upper fence:")
            }
          };
          fullLayout[numKey]++;
          return cd;
        } else {
          return [{ t: { empty: true } }];
        }
      };
      function getPosArrays(trace, posLetter, posAxis, num) {
        var hasPosArray = posLetter in trace;
        var hasPos0 = posLetter + "0" in trace;
        var hasPosStep = "d" + posLetter in trace;
        if (hasPosArray || hasPos0 && hasPosStep) {
          var origPos = posAxis.makeCalcdata(trace, posLetter);
          var pos = alignPeriod(trace, posAxis, posLetter, origPos).vals;
          return [pos, origPos];
        }
        var pos0;
        if (hasPos0) {
          pos0 = trace[posLetter + "0"];
        } else if ("name" in trace && (posAxis.type === "category" || isNumeric(trace.name) && ["linear", "log"].indexOf(posAxis.type) !== -1 || Lib.isDateTime(trace.name) && posAxis.type === "date")) {
          pos0 = trace.name;
        } else {
          pos0 = num;
        }
        var pos0c = posAxis.type === "multicategory" ? posAxis.r2c_just_indices(pos0) : posAxis.d2c(pos0, 0, trace[posLetter + "calendar"]);
        var len = trace._length;
        var out = new Array(len);
        for (var i = 0; i < len; i++) out[i] = pos0c;
        return [out];
      }
      function makeBins(x, dx) {
        var len = x.length;
        var bins = new Array(len + 1);
        for (var i = 0; i < len; i++) {
          bins[i] = x[i] - dx;
        }
        bins[len] = x[len - 1] + dx;
        return bins;
      }
      function initNestedArray(len) {
        var arr = new Array(len);
        for (var i = 0; i < len; i++) {
          arr[i] = [];
        }
        return arr;
      }
      var TRACE_TO_CALC = {
        text: "tx",
        hovertext: "htx"
      };
      function arraysToCalcdata(pt, trace, ptNumber) {
        for (var k in TRACE_TO_CALC) {
          if (Lib.isArrayOrTypedArray(trace[k])) {
            if (Array.isArray(ptNumber)) {
              if (Lib.isArrayOrTypedArray(trace[k][ptNumber[0]])) {
                pt[TRACE_TO_CALC[k]] = trace[k][ptNumber[0]][ptNumber[1]];
              }
            } else {
              pt[TRACE_TO_CALC[k]] = trace[k][ptNumber];
            }
          }
        }
      }
      function calcSelection(cd, trace) {
        if (Lib.isArrayOrTypedArray(trace.selectedpoints)) {
          for (var i = 0; i < cd.length; i++) {
            var pts = cd[i].pts || [];
            var ptNumber2cdIndex = {};
            for (var j = 0; j < pts.length; j++) {
              ptNumber2cdIndex[pts[j].i] = j;
            }
            Lib.tagSelected(pts, trace, ptNumber2cdIndex);
          }
        }
      }
      function sortByVal(a, b) {
        return a.v - b.v;
      }
      function extractVal(o) {
        return o.v;
      }
      function computeLowerFence(cdi, boxVals, N) {
        if (N === 0) return cdi.q1;
        return Math.min(
          cdi.q1,
          boxVals[Math.min(
            Lib.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1,
            N - 1
          )]
        );
      }
      function computeUpperFence(cdi, boxVals, N) {
        if (N === 0) return cdi.q3;
        return Math.max(
          cdi.q3,
          boxVals[Math.max(
            Lib.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals),
            0
          )]
        );
      }
      function computeLowerOutlierBound(cdi) {
        return 4 * cdi.q1 - 3 * cdi.q3;
      }
      function computeUpperOutlierBound(cdi) {
        return 4 * cdi.q3 - 3 * cdi.q1;
      }
      function computeNotchSpan(cdi, N) {
        if (N === 0) return 0;
        return 1.57 * (cdi.q3 - cdi.q1) / Math.sqrt(N);
      }
    }
  });

  // src/traces/box/cross_trace_calc.js
  var require_cross_trace_calc3 = __commonJS({
    "src/traces/box/cross_trace_calc.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var Lib = require_lib();
      var getAxisGroup = require_constraints().getAxisGroup;
      var orientations = ["v", "h"];
      function crossTraceCalc(gd, plotinfo) {
        var calcdata = gd.calcdata;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        for (var i = 0; i < orientations.length; i++) {
          var orientation = orientations[i];
          var posAxis = orientation === "h" ? ya : xa;
          var boxList = [];
          for (var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var t = cd[0].t;
            var trace = cd[0].trace;
            if (trace.visible === true && (trace.type === "box" || trace.type === "candlestick") && !t.empty && (trace.orientation || "v") === orientation && trace.xaxis === xa._id && trace.yaxis === ya._id) {
              boxList.push(j);
            }
          }
          setPositionOffset("box", gd, boxList, posAxis);
        }
      }
      function setPositionOffset(traceType, gd, boxList, posAxis) {
        var calcdata = gd.calcdata;
        var fullLayout = gd._fullLayout;
        var axId = posAxis._id;
        var axLetter = axId.charAt(0);
        var i, j, calcTrace;
        var pointList = [];
        var shownPts = 0;
        for (i = 0; i < boxList.length; i++) {
          calcTrace = calcdata[boxList[i]];
          for (j = 0; j < calcTrace.length; j++) {
            pointList.push(posAxis.c2l(calcTrace[j].pos, true));
            shownPts += (calcTrace[j].pts2 || []).length;
          }
        }
        if (!pointList.length) return;
        var boxdv = Lib.distinctVals(pointList);
        if (posAxis.type === "category" || posAxis.type === "multicategory") {
          boxdv.minDiff = 1;
        }
        var dPos0 = boxdv.minDiff / 2;
        Axes.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true);
        var numKey = traceType === "violin" ? "_numViolins" : "_numBoxes";
        var numTotal = fullLayout[numKey];
        var group = fullLayout[traceType + "mode"] === "group" && numTotal > 1;
        var groupFraction = 1 - fullLayout[traceType + "gap"];
        var groupGapFraction = 1 - fullLayout[traceType + "groupgap"];
        for (i = 0; i < boxList.length; i++) {
          calcTrace = calcdata[boxList[i]];
          var trace = calcTrace[0].trace;
          var t = calcTrace[0].t;
          var width = trace.width;
          var side = trace.side;
          var dPos;
          var bdPos;
          var bPos;
          var wHover;
          if (width) {
            dPos = bdPos = wHover = width / 2;
            bPos = 0;
          } else {
            dPos = dPos0;
            if (group) {
              var groupId = getAxisGroup(fullLayout, posAxis._id) + trace.orientation;
              var alignmentGroups = fullLayout._alignmentOpts[groupId] || {};
              var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {};
              var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length;
              var num = nOffsetGroups || numTotal;
              var shift = nOffsetGroups ? trace._offsetIndex : t.num;
              bdPos = dPos * groupFraction * groupGapFraction / num;
              bPos = 2 * dPos * (-0.5 + (shift + 0.5) / num) * groupFraction;
              wHover = dPos * groupFraction / num;
            } else {
              bdPos = dPos * groupFraction * groupGapFraction;
              bPos = 0;
              wHover = dPos;
            }
          }
          t.dPos = dPos;
          t.bPos = bPos;
          t.bdPos = bdPos;
          t.wHover = wHover;
          var pushplus;
          var pushminus;
          var edge = bPos + bdPos;
          var edgeplus;
          var edgeminus;
          var vpadplus;
          var vpadminus;
          var ppadplus;
          var ppadminus;
          var padded = Boolean(width);
          var hasPts = (trace.boxpoints || trace.points) && shownPts > 0;
          if (side === "positive") {
            pushplus = dPos * (width ? 1 : 0.5);
            edgeplus = edge;
            pushminus = edgeplus = bPos;
          } else if (side === "negative") {
            pushplus = edgeplus = bPos;
            pushminus = dPos * (width ? 1 : 0.5);
            edgeminus = edge;
          } else {
            pushplus = pushminus = dPos;
            edgeplus = edgeminus = edge;
          }
          if (hasPts) {
            var pointpos = trace.pointpos;
            var jitter = trace.jitter;
            var ms = trace.marker.size / 2;
            var pp = 0;
            if (pointpos + jitter >= 0) {
              pp = edge * (pointpos + jitter);
              if (pp > pushplus) {
                padded = true;
                ppadplus = ms;
                vpadplus = pp;
              } else if (pp > edgeplus) {
                ppadplus = ms;
                vpadplus = pushplus;
              }
            }
            if (pp <= pushplus) {
              vpadplus = pushplus;
            }
            var pm = 0;
            if (pointpos - jitter <= 0) {
              pm = -edge * (pointpos - jitter);
              if (pm > pushminus) {
                padded = true;
                ppadminus = ms;
                vpadminus = pm;
              } else if (pm > edgeminus) {
                ppadminus = ms;
                vpadminus = pushminus;
              }
            }
            if (pm <= pushminus) {
              vpadminus = pushminus;
            }
          } else {
            vpadplus = pushplus;
            vpadminus = pushminus;
          }
          var pos = new Array(calcTrace.length);
          for (j = 0; j < calcTrace.length; j++) {
            pos[j] = calcTrace[j].pos;
          }
          trace._extremes[axId] = Axes.findExtremes(posAxis, pos, {
            padded,
            vpadminus,
            vpadplus,
            vpadLinearized: true,
            // N.B. SVG px-space positive/negative
            ppadminus: { x: ppadminus, y: ppadplus }[axLetter],
            ppadplus: { x: ppadplus, y: ppadminus }[axLetter]
          });
        }
      }
      module.exports = {
        crossTraceCalc,
        setPositionOffset
      };
    }
  });

  // src/traces/box/plot.js
  var require_plot4 = __commonJS({
    "src/traces/box/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var JITTERCOUNT = 5;
      var JITTERSPREAD = 0.01;
      function plot(gd, plotinfo, cdbox, boxLayer) {
        var isStatic = gd._context.staticPlot;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        Lib.makeTraceGroups(boxLayer, cdbox, "trace boxes").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var t = cd0.t;
          var trace = cd0.trace;
          t.wdPos = t.bdPos * trace.whiskerwidth;
          if (trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
          }
          var posAxis, valAxis;
          if (trace.orientation === "h") {
            posAxis = ya;
            valAxis = xa;
          } else {
            posAxis = xa;
            valAxis = ya;
          }
          plotBoxAndWhiskers(plotGroup, { pos: posAxis, val: valAxis }, trace, t, isStatic);
          plotPoints(plotGroup, { x: xa, y: ya }, trace, t);
          plotBoxMean(plotGroup, { pos: posAxis, val: valAxis }, trace, t);
        });
      }
      function plotBoxAndWhiskers(sel, axes, trace, t, isStatic) {
        var isHorizontal = trace.orientation === "h";
        var valAxis = axes.val;
        var posAxis = axes.pos;
        var posHasRangeBreaks = !!posAxis.rangebreaks;
        var bPos = t.bPos;
        var wdPos = t.wdPos || 0;
        var bPosPxOffset = t.bPosPxOffset || 0;
        var whiskerWidth = trace.whiskerwidth || 0;
        var showWhiskers = trace.showwhiskers !== false;
        var notched = trace.notched || false;
        var nw = notched ? 1 - 2 * trace.notchwidth : 1;
        var bdPos0;
        var bdPos1;
        if (Array.isArray(t.bdPos)) {
          bdPos0 = t.bdPos[0];
          bdPos1 = t.bdPos[1];
        } else {
          bdPos0 = t.bdPos;
          bdPos1 = t.bdPos;
        }
        var paths = sel.selectAll("path.box").data(trace.type !== "violin" || trace.box.visible ? Lib.identity : []);
        paths.enter().append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").attr("class", "box");
        paths.exit().remove();
        paths.each(function(d) {
          if (d.empty) return d3.select(this).attr("d", "M0,0Z");
          var lcenter = posAxis.c2l(d.pos + bPos, true);
          var pos0 = posAxis.l2p(lcenter - bdPos0) + bPosPxOffset;
          var pos1 = posAxis.l2p(lcenter + bdPos1) + bPosPxOffset;
          var posc = posHasRangeBreaks ? (pos0 + pos1) / 2 : posAxis.l2p(lcenter) + bPosPxOffset;
          var r = trace.whiskerwidth;
          var posw0 = posHasRangeBreaks ? pos0 * r + (1 - r) * posc : posAxis.l2p(lcenter - wdPos) + bPosPxOffset;
          var posw1 = posHasRangeBreaks ? pos1 * r + (1 - r) * posc : posAxis.l2p(lcenter + wdPos) + bPosPxOffset;
          var posm0 = posAxis.l2p(lcenter - bdPos0 * nw) + bPosPxOffset;
          var posm1 = posAxis.l2p(lcenter + bdPos1 * nw) + bPosPxOffset;
          var sdmode = trace.sizemode === "sd";
          var q1 = valAxis.c2p(sdmode ? d.mean - d.sd : d.q1, true);
          var q3 = sdmode ? valAxis.c2p(d.mean + d.sd, true) : valAxis.c2p(d.q3, true);
          var m = Lib.constrain(
            sdmode ? valAxis.c2p(d.mean, true) : valAxis.c2p(d.med, true),
            Math.min(q1, q3) + 1,
            Math.max(q1, q3) - 1
          );
          var useExtremes = d.lf === void 0 || trace.boxpoints === false || sdmode;
          var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true);
          var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true);
          var ln = valAxis.c2p(d.ln, true);
          var un = valAxis.c2p(d.un, true);
          if (isHorizontal) {
            d3.select(this).attr(
              "d",
              "M" + m + "," + posm0 + "V" + posm1 + // median line
              "M" + q1 + "," + pos0 + "V" + pos1 + // left edge
              (notched ? "H" + ln + "L" + m + "," + posm1 + "L" + un + "," + pos1 : "") + // top notched edge
              "H" + q3 + // end of the top edge
              "V" + pos0 + // right edge
              (notched ? "H" + un + "L" + m + "," + posm0 + "L" + ln + "," + pos0 : "") + // bottom notched edge
              "Z" + // end of the box
              (showWhiskers ? "M" + q1 + "," + posc + "H" + lf + "M" + q3 + "," + posc + "H" + uf + // whiskers
              (whiskerWidth === 0 ? "" : (
                // whisker caps
                "M" + lf + "," + posw0 + "V" + posw1 + "M" + uf + "," + posw0 + "V" + posw1
              )) : "")
            );
          } else {
            d3.select(this).attr(
              "d",
              "M" + posm0 + "," + m + "H" + posm1 + // median line
              "M" + pos0 + "," + q1 + "H" + pos1 + // top of the box
              (notched ? "V" + ln + "L" + posm1 + "," + m + "L" + pos1 + "," + un : "") + // notched right edge
              "V" + q3 + // end of the right edge
              "H" + pos0 + // bottom of the box
              (notched ? "V" + un + "L" + posm0 + "," + m + "L" + pos0 + "," + ln : "") + // notched left edge
              "Z" + // end of the box
              (showWhiskers ? "M" + posc + "," + q1 + "V" + lf + "M" + posc + "," + q3 + "V" + uf + // whiskers
              (whiskerWidth === 0 ? "" : (
                // whisker caps
                "M" + posw0 + "," + lf + "H" + posw1 + "M" + posw0 + "," + uf + "H" + posw1
              )) : "")
            );
          }
        });
      }
      function plotPoints(sel, axes, trace, t) {
        var xa = axes.x;
        var ya = axes.y;
        var bdPos = t.bdPos;
        var bPos = t.bPos;
        var mode = trace.boxpoints || trace.points;
        Lib.seedPseudoRandom();
        var fn = function(d) {
          d.forEach(function(v) {
            v.t = t;
            v.trace = trace;
          });
          return d;
        };
        var gPoints = sel.selectAll("g.points").data(mode ? fn : []);
        gPoints.enter().append("g").attr("class", "points");
        gPoints.exit().remove();
        var paths = gPoints.selectAll("path").data(function(d) {
          var i;
          var pts = d.pts2;
          var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1);
          var minSpread = typicalSpread * 1e-9;
          var spreadLimit = typicalSpread * JITTERSPREAD;
          var jitterFactors = [];
          var maxJitterFactor = 0;
          var newJitter;
          if (trace.jitter) {
            if (typicalSpread === 0) {
              maxJitterFactor = 1;
              jitterFactors = new Array(pts.length);
              for (i = 0; i < pts.length; i++) {
                jitterFactors[i] = 1;
              }
            } else {
              for (i = 0; i < pts.length; i++) {
                var i0 = Math.max(0, i - JITTERCOUNT);
                var pmin = pts[i0].v;
                var i1 = Math.min(pts.length - 1, i + JITTERCOUNT);
                var pmax = pts[i1].v;
                if (mode !== "all") {
                  if (pts[i].v < d.lf) pmax = Math.min(pmax, d.lf);
                  else pmin = Math.max(pmin, d.uf);
                }
                var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0;
                jitterFactor = Lib.constrain(Math.abs(jitterFactor), 0, 1);
                jitterFactors.push(jitterFactor);
                maxJitterFactor = Math.max(jitterFactor, maxJitterFactor);
              }
            }
            newJitter = trace.jitter * 2 / (maxJitterFactor || 1);
          }
          for (i = 0; i < pts.length; i++) {
            var pt = pts[i];
            var v = pt.v;
            var jitterOffset = trace.jitter ? newJitter * jitterFactors[i] * (Lib.pseudoRandom() - 0.5) : 0;
            var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset);
            if (trace.orientation === "h") {
              pt.y = posPx;
              pt.x = v;
            } else {
              pt.x = posPx;
              pt.y = v;
            }
            if (mode === "suspectedoutliers" && v < d.uo && v > d.lo) {
              pt.so = true;
            }
          }
          return pts;
        });
        paths.enter().append("path").classed("point", true);
        paths.exit().remove();
        paths.call(Drawing.translatePoints, xa, ya);
      }
      function plotBoxMean(sel, axes, trace, t) {
        var valAxis = axes.val;
        var posAxis = axes.pos;
        var posHasRangeBreaks = !!posAxis.rangebreaks;
        var bPos = t.bPos;
        var bPosPxOffset = t.bPosPxOffset || 0;
        var mode = trace.boxmean || (trace.meanline || {}).visible;
        var bdPos0;
        var bdPos1;
        if (Array.isArray(t.bdPos)) {
          bdPos0 = t.bdPos[0];
          bdPos1 = t.bdPos[1];
        } else {
          bdPos0 = t.bdPos;
          bdPos1 = t.bdPos;
        }
        var paths = sel.selectAll("path.mean").data(trace.type === "box" && trace.boxmean || trace.type === "violin" && trace.box.visible && trace.meanline.visible ? Lib.identity : []);
        paths.enter().append("path").attr("class", "mean").style({
          fill: "none",
          "vector-effect": "non-scaling-stroke"
        });
        paths.exit().remove();
        paths.each(function(d) {
          var lcenter = posAxis.c2l(d.pos + bPos, true);
          var pos0 = posAxis.l2p(lcenter - bdPos0) + bPosPxOffset;
          var pos1 = posAxis.l2p(lcenter + bdPos1) + bPosPxOffset;
          var posc = posHasRangeBreaks ? (pos0 + pos1) / 2 : posAxis.l2p(lcenter) + bPosPxOffset;
          var m = valAxis.c2p(d.mean, true);
          var sl = valAxis.c2p(d.mean - d.sd, true);
          var sh = valAxis.c2p(d.mean + d.sd, true);
          if (trace.orientation === "h") {
            d3.select(this).attr(
              "d",
              "M" + m + "," + pos0 + "V" + pos1 + (mode === "sd" ? "m0,0L" + sl + "," + posc + "L" + m + "," + pos0 + "L" + sh + "," + posc + "Z" : "")
            );
          } else {
            d3.select(this).attr(
              "d",
              "M" + pos0 + "," + m + "H" + pos1 + (mode === "sd" ? "m0,0L" + posc + "," + sl + "L" + pos0 + "," + m + "L" + posc + "," + sh + "Z" : "")
            );
          }
        });
      }
      module.exports = {
        plot,
        plotBoxAndWhiskers,
        plotPoints,
        plotBoxMean
      };
    }
  });

  // src/traces/box/style.js
  var require_style5 = __commonJS({
    "src/traces/box/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var Drawing = require_drawing();
      function style(gd, cd, sel) {
        var s = sel ? sel : d3.select(gd).selectAll("g.trace.boxes");
        s.style("opacity", function(d) {
          return d[0].trace.opacity;
        });
        s.each(function(d) {
          var el = d3.select(this);
          var trace = d[0].trace;
          var lineWidth = trace.line.width;
          function styleBox(boxSel, lineWidth2, lineColor, fillColor) {
            boxSel.style("stroke-width", lineWidth2 + "px").call(Color2.stroke, lineColor).call(Color2.fill, fillColor);
          }
          var allBoxes = el.selectAll("path.box");
          if (trace.type === "candlestick") {
            allBoxes.each(function(boxData) {
              if (boxData.empty) return;
              var thisBox = d3.select(this);
              var container = trace[boxData.dir];
              styleBox(thisBox, container.line.width, container.line.color, container.fillcolor);
              thisBox.style("opacity", trace.selectedpoints && !boxData.selected ? 0.3 : 1);
            });
          } else {
            styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor);
            el.selectAll("path.mean").style({
              "stroke-width": lineWidth,
              "stroke-dasharray": 2 * lineWidth + "px," + lineWidth + "px"
            }).call(Color2.stroke, trace.line.color);
            var pts = el.selectAll("path.point");
            Drawing.pointStyle(pts, trace, gd);
          }
        });
      }
      function styleOnSelect(gd, cd, sel) {
        var trace = cd[0].trace;
        var pts = sel.selectAll("path.point");
        if (trace.selectedpoints) {
          Drawing.selectedPointStyle(pts, trace);
        } else {
          Drawing.pointStyle(pts, trace, gd);
        }
      }
      module.exports = {
        style,
        styleOnSelect
      };
    }
  });

  // src/traces/box/hover.js
  var require_hover4 = __commonJS({
    "src/traces/box/hover.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var Lib = require_lib();
      var Fx = require_fx();
      var Color2 = require_color();
      var fillText = Lib.fillText;
      function hoverPoints(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var hoveron = trace.hoveron;
        var closeBoxData = [];
        var closePtData;
        if (hoveron.indexOf("boxes") !== -1) {
          closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode));
        }
        if (hoveron.indexOf("points") !== -1) {
          closePtData = hoverOnPoints(pointData, xval, yval);
        }
        if (hovermode === "closest") {
          if (closePtData) return [closePtData];
          return closeBoxData;
        }
        if (closePtData) {
          closeBoxData.push(closePtData);
          return closeBoxData;
        }
        return closeBoxData;
      }
      function hoverOnBoxes(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var trace = cd[0].trace;
        var t = cd[0].t;
        var isViolin = trace.type === "violin";
        var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos, hoverPseudoDistance, spikePseudoDistance;
        var boxDelta = t.bdPos;
        var boxDeltaPos, boxDeltaNeg;
        var posAcceptance = t.wHover;
        var shiftPos = function(di2) {
          return pAxis.c2l(di2.pos) + t.bPos - pAxis.c2l(pVal);
        };
        if (isViolin && trace.side !== "both") {
          if (trace.side === "positive") {
            dPos = function(di2) {
              var pos = shiftPos(di2);
              return Fx.inbox(pos, pos + posAcceptance, hoverPseudoDistance);
            };
            boxDeltaPos = boxDelta;
            boxDeltaNeg = 0;
          }
          if (trace.side === "negative") {
            dPos = function(di2) {
              var pos = shiftPos(di2);
              return Fx.inbox(pos - posAcceptance, pos, hoverPseudoDistance);
            };
            boxDeltaPos = 0;
            boxDeltaNeg = boxDelta;
          }
        } else {
          dPos = function(di2) {
            var pos = shiftPos(di2);
            return Fx.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance);
          };
          boxDeltaPos = boxDeltaNeg = boxDelta;
        }
        var dVal;
        if (isViolin) {
          dVal = function(di2) {
            return Fx.inbox(di2.span[0] - vVal, di2.span[1] - vVal, hoverPseudoDistance);
          };
        } else {
          dVal = function(di2) {
            return Fx.inbox(di2.min - vVal, di2.max - vVal, hoverPseudoDistance);
          };
        }
        if (trace.orientation === "h") {
          vVal = xval;
          pVal = yval;
          dx = dVal;
          dy = dPos;
          pLetter = "y";
          pAxis = ya;
          vLetter = "x";
          vAxis = xa;
        } else {
          vVal = yval;
          pVal = xval;
          dx = dPos;
          dy = dVal;
          pLetter = "x";
          pAxis = xa;
          vLetter = "y";
          vAxis = ya;
        }
        var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0])));
        hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
        spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;
        function dxy(di2) {
          return (dx(di2) + dy(di2)) / 2;
        }
        var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
        Fx.getClosest(cd, distfn, pointData);
        if (pointData.index === false) return [];
        var di = cd[pointData.index];
        var lc = trace.line.color;
        var mc = (trace.marker || {}).color;
        if (Color2.opacity(lc) && trace.line.width) pointData.color = lc;
        else if (Color2.opacity(mc) && trace.boxpoints) pointData.color = mc;
        else pointData.color = trace.fillcolor;
        pointData[pLetter + "0"] = pAxis.c2p(di.pos + t.bPos - boxDeltaNeg, true);
        pointData[pLetter + "1"] = pAxis.c2p(di.pos + t.bPos + boxDeltaPos, true);
        pointData[pLetter + "LabelVal"] = di.orig_p !== void 0 ? di.orig_p : di.pos;
        var spikePosAttr = pLetter + "Spike";
        pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
        pointData[spikePosAttr] = pAxis.c2p(di.pos, true);
        var hasMean = trace.boxmean || trace.sizemode === "sd" || (trace.meanline || {}).visible;
        var hasFences = trace.boxpoints || trace.points;
        var attrs = hasFences && hasMean ? ["max", "uf", "q3", "med", "mean", "q1", "lf", "min"] : hasFences && !hasMean ? ["max", "uf", "q3", "med", "q1", "lf", "min"] : !hasFences && hasMean ? ["max", "q3", "med", "mean", "q1", "min"] : ["max", "q3", "med", "q1", "min"];
        var rev = vAxis.range[1] < vAxis.range[0];
        if (trace.orientation === (rev ? "v" : "h")) {
          attrs.reverse();
        }
        var spikeDistance = pointData.spikeDistance;
        var spikePosition = pointData[spikePosAttr];
        var closeBoxData = [];
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          if (!(attr in di)) continue;
          var val = di[attr];
          var valPx = vAxis.c2p(val, true);
          var pointData2 = Lib.extendFlat({}, pointData);
          pointData2.attr = attr;
          pointData2[vLetter + "0"] = pointData2[vLetter + "1"] = valPx;
          pointData2[vLetter + "LabelVal"] = val;
          pointData2[vLetter + "Label"] = (t.labels ? t.labels[attr] + " " : "") + Axes.hoverLabelText(vAxis, val, trace[vLetter + "hoverformat"]);
          pointData2.hoverOnBox = true;
          if (attr === "mean" && "sd" in di && (trace.boxmean === "sd" || trace.sizemode === "sd")) {
            pointData2[vLetter + "err"] = di.sd;
          }
          pointData2.hovertemplate = false;
          closeBoxData.push(pointData2);
        }
        pointData.name = "";
        pointData.spikeDistance = void 0;
        pointData[spikePosAttr] = void 0;
        for (var k = 0; k < closeBoxData.length; k++) {
          if (closeBoxData[k].attr !== "med") {
            closeBoxData[k].name = "";
            closeBoxData[k].spikeDistance = void 0;
            closeBoxData[k][spikePosAttr] = void 0;
          } else {
            closeBoxData[k].spikeDistance = spikeDistance;
            closeBoxData[k][spikePosAttr] = spikePosition;
          }
        }
        return closeBoxData;
      }
      function hoverOnPoints(pointData, xval, yval) {
        var cd = pointData.cd;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var trace = cd[0].trace;
        var xPx = xa.c2p(xval);
        var yPx = ya.c2p(yval);
        var closePtData;
        var dx = function(di2) {
          var rad2 = Math.max(3, di2.mrc || 0);
          return Math.max(Math.abs(xa.c2p(di2.x) - xPx) - rad2, 1 - 3 / rad2);
        };
        var dy = function(di2) {
          var rad2 = Math.max(3, di2.mrc || 0);
          return Math.max(Math.abs(ya.c2p(di2.y) - yPx) - rad2, 1 - 3 / rad2);
        };
        var distfn = Fx.quadrature(dx, dy);
        var ijClosest = false;
        var di, pt;
        for (var i = 0; i < cd.length; i++) {
          di = cd[i];
          for (var j = 0; j < (di.pts || []).length; j++) {
            pt = di.pts[j];
            var newDistance = distfn(pt);
            if (newDistance <= pointData.distance) {
              pointData.distance = newDistance;
              ijClosest = [i, j];
            }
          }
        }
        if (!ijClosest) return false;
        di = cd[ijClosest[0]];
        pt = di.pts[ijClosest[1]];
        var xc = xa.c2p(pt.x, true);
        var yc = ya.c2p(pt.y, true);
        var rad = pt.mrc || 1;
        closePtData = Lib.extendFlat({}, pointData, {
          // corresponds to index in x/y input data array
          index: pt.i,
          color: (trace.marker || {}).color,
          name: trace.name,
          x0: xc - rad,
          x1: xc + rad,
          y0: yc - rad,
          y1: yc + rad,
          spikeDistance: pointData.distance,
          hovertemplate: trace.hovertemplate
        });
        var origPos = di.orig_p;
        var pos = origPos !== void 0 ? origPos : di.pos;
        var pa;
        if (trace.orientation === "h") {
          pa = ya;
          closePtData.xLabelVal = pt.x;
          closePtData.yLabelVal = pos;
        } else {
          pa = xa;
          closePtData.xLabelVal = pos;
          closePtData.yLabelVal = pt.y;
        }
        var pLetter = pa._id.charAt(0);
        closePtData[pLetter + "Spike"] = pa.c2p(di.pos, true);
        fillText(pt, trace, closePtData);
        return closePtData;
      }
      module.exports = {
        hoverPoints,
        hoverOnBoxes,
        hoverOnPoints
      };
    }
  });

  // src/traces/box/event_data.js
  var require_event_data2 = __commonJS({
    "src/traces/box/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        if (pt.hoverOnBox) out.hoverOnBox = pt.hoverOnBox;
        if ("xVal" in pt) out.x = pt.xVal;
        if ("yVal" in pt) out.y = pt.yVal;
        if (pt.xa) out.xaxis = pt.xa;
        if (pt.ya) out.yaxis = pt.ya;
        return out;
      };
    }
  });

  // src/traces/box/select.js
  var require_select4 = __commonJS({
    "src/traces/box/select.js"(exports, module) {
      "use strict";
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var i, j;
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            for (j = 0; j < (cd[i].pts || []).length; j++) {
              cd[i].pts[j].selected = 0;
            }
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            for (j = 0; j < (cd[i].pts || []).length; j++) {
              var pt = cd[i].pts[j];
              var x = xa.c2p(pt.x);
              var y = ya.c2p(pt.y);
              if (selectionTester.contains([x, y], null, pt.i, searchInfo)) {
                selection.push({
                  pointNumber: pt.i,
                  x: xa.c2d(pt.x),
                  y: ya.c2d(pt.y)
                });
                pt.selected = 1;
              } else {
                pt.selected = 0;
              }
            }
          }
        }
        return selection;
      };
    }
  });

  // src/traces/box/index.js
  var require_box = __commonJS({
    "src/traces/box/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes24(),
        layoutAttributes: require_layout_attributes7(),
        supplyDefaults: require_defaults20().supplyDefaults,
        crossTraceDefaults: require_defaults20().crossTraceDefaults,
        supplyLayoutDefaults: require_layout_defaults6().supplyLayoutDefaults,
        calc: require_calc6(),
        crossTraceCalc: require_cross_trace_calc3().crossTraceCalc,
        plot: require_plot4().plot,
        style: require_style5().style,
        styleOnSelect: require_style5().styleOnSelect,
        hoverPoints: require_hover4().hoverPoints,
        eventData: require_event_data2(),
        selectPoints: require_select4(),
        moduleType: "trace",
        name: "box",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "symbols", "oriented", "box-violin", "showLegend", "boxLayout", "zoomScale"],
        meta: {}
      };
    }
  });

  // lib/box.js
  var require_box2 = __commonJS({
    "lib/box.js"(exports, module) {
      "use strict";
      module.exports = require_box();
    }
  });

  // src/traces/heatmap/attributes.js
  var require_attributes25 = __commonJS({
    "src/traces/heatmap/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var { extendFlat } = require_extend();
      var baseAttrs = require_attributes2();
      var { axisHoverFormat } = require_axis_format_attributes();
      var fontAttrs = require_font_attributes();
      var { hovertemplateAttrs, templatefallbackAttrs, texttemplateAttrs } = require_template_attributes();
      var scatterAttrs = require_attributes12();
      module.exports = extendFlat(
        {
          z: {
            valType: "data_array",
            editType: "calc"
          },
          x: extendFlat({}, scatterAttrs.x, { impliedEdits: { xtype: "array" } }),
          x0: extendFlat({}, scatterAttrs.x0, { impliedEdits: { xtype: "scaled" } }),
          dx: extendFlat({}, scatterAttrs.dx, { impliedEdits: { xtype: "scaled" } }),
          y: extendFlat({}, scatterAttrs.y, { impliedEdits: { ytype: "array" } }),
          y0: extendFlat({}, scatterAttrs.y0, { impliedEdits: { ytype: "scaled" } }),
          dy: extendFlat({}, scatterAttrs.dy, { impliedEdits: { ytype: "scaled" } }),
          xperiod: extendFlat({}, scatterAttrs.xperiod, { impliedEdits: { xtype: "scaled" } }),
          yperiod: extendFlat({}, scatterAttrs.yperiod, { impliedEdits: { ytype: "scaled" } }),
          xperiod0: extendFlat({}, scatterAttrs.xperiod0, { impliedEdits: { xtype: "scaled" } }),
          yperiod0: extendFlat({}, scatterAttrs.yperiod0, { impliedEdits: { ytype: "scaled" } }),
          xperiodalignment: extendFlat({}, scatterAttrs.xperiodalignment, { impliedEdits: { xtype: "scaled" } }),
          yperiodalignment: extendFlat({}, scatterAttrs.yperiodalignment, { impliedEdits: { ytype: "scaled" } }),
          text: {
            valType: "data_array",
            editType: "calc"
          },
          hovertext: {
            valType: "data_array",
            editType: "calc"
          },
          transpose: {
            valType: "boolean",
            dflt: false,
            editType: "calc"
          },
          xtype: {
            valType: "enumerated",
            values: ["array", "scaled"],
            editType: "calc+clearAxisTypes"
          },
          ytype: {
            valType: "enumerated",
            values: ["array", "scaled"],
            editType: "calc+clearAxisTypes"
          },
          zsmooth: {
            valType: "enumerated",
            values: ["fast", "best", false],
            dflt: false,
            editType: "calc"
          },
          hoverongaps: {
            valType: "boolean",
            dflt: true,
            editType: "none"
          },
          connectgaps: {
            valType: "boolean",
            editType: "calc"
          },
          xgap: {
            valType: "number",
            dflt: 0,
            min: 0,
            editType: "plot"
          },
          ygap: {
            valType: "number",
            dflt: 0,
            min: 0,
            editType: "plot"
          },
          xhoverformat: axisHoverFormat("x"),
          yhoverformat: axisHoverFormat("y"),
          zhoverformat: axisHoverFormat("z", 1),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs(),
          texttemplate: texttemplateAttrs({ arrayOk: false, editType: "plot" }, { keys: ["x", "y", "z", "text"] }),
          texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
          textfont: fontAttrs({
            editType: "plot",
            autoSize: true,
            autoColor: true,
            colorEditType: "style"
          }),
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false }),
          zorder: scatterAttrs.zorder
        },
        colorScaleAttrs("", { cLetter: "z", autoColorDflt: false })
      );
    }
  });

  // src/traces/heatmap/xyz_defaults.js
  var require_xyz_defaults = __commonJS({
    "src/traces/heatmap/xyz_defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Registry = require_registry();
      module.exports = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) {
        var z = coerce("z");
        xName = xName || "x";
        yName = yName || "y";
        var x, y;
        if (z === void 0 || !z.length) return 0;
        if (Lib.isArray1D(z)) {
          x = coerce(xName);
          y = coerce(yName);
          var xlen = Lib.minRowLength(x);
          var ylen = Lib.minRowLength(y);
          if (xlen === 0 || ylen === 0) return 0;
          traceOut._length = Math.min(xlen, ylen, z.length);
        } else {
          x = coordDefaults(xName, coerce);
          y = coordDefaults(yName, coerce);
          if (!isValidZ(z)) return 0;
          coerce("transpose");
          traceOut._length = null;
        }
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout);
        return true;
      };
      function coordDefaults(coordStr, coerce) {
        var coord = coerce(coordStr);
        var coordType = coord ? coerce(coordStr + "type", "array") : "scaled";
        if (coordType === "scaled") {
          coerce(coordStr + "0");
          coerce("d" + coordStr);
        }
        return coord;
      }
      function isValidZ(z) {
        var allRowsAreArrays = true;
        var oneRowIsFilled = false;
        var hasOneNumber = false;
        var zi;
        for (var i = 0; i < z.length; i++) {
          zi = z[i];
          if (!Lib.isArrayOrTypedArray(zi)) {
            allRowsAreArrays = false;
            break;
          }
          if (zi.length > 0) oneRowIsFilled = true;
          for (var j = 0; j < zi.length; j++) {
            if (isNumeric(zi[j])) {
              hasOneNumber = true;
              break;
            }
          }
        }
        return allRowsAreArrays && oneRowIsFilled && hasOneNumber;
      }
    }
  });

  // src/traces/heatmap/label_defaults.js
  var require_label_defaults = __commonJS({
    "src/traces/heatmap/label_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function handleHeatmapLabelDefaults(coerce, layout) {
        coerce("texttemplate");
        coerce("texttemplatefallback");
        var fontDflt = Lib.extendFlat({}, layout.font, {
          color: "auto",
          size: "auto"
        });
        Lib.coerceFont(coerce, "textfont", fontDflt);
      };
    }
  });

  // src/traces/heatmap/style_defaults.js
  var require_style_defaults2 = __commonJS({
    "src/traces/heatmap/style_defaults.js"(exports, module) {
      "use strict";
      module.exports = function handleStyleDefaults(traceIn, traceOut, coerce) {
        var zsmooth = coerce("zsmooth");
        if (zsmooth === false) {
          coerce("xgap");
          coerce("ygap");
        }
        coerce("zhoverformat");
      };
    }
  });

  // src/traces/heatmap/defaults.js
  var require_defaults21 = __commonJS({
    "src/traces/heatmap/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleXYZDefaults = require_xyz_defaults();
      var handleHeatmapLabelDefaults = require_label_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var handleStyleDefaults = require_style_defaults2();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes25();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var validData = handleXYZDefaults(traceIn, traceOut, coerce, layout);
        if (!validData) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        handleHeatmapLabelDefaults(coerce, layout);
        handleStyleDefaults(traceIn, traceOut, coerce, layout);
        coerce("hoverongaps");
        coerce("connectgaps", Lib.isArray1D(traceOut.z) && traceOut.zsmooth !== false);
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "z" });
        coerce("zorder");
      };
    }
  });

  // src/traces/histogram/bin_functions.js
  var require_bin_functions = __commonJS({
    "src/traces/histogram/bin_functions.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      module.exports = {
        count: function(n, i, size) {
          size[n]++;
          return 1;
        },
        sum: function(n, i, size, counterData) {
          var v = counterData[i];
          if (isNumeric(v)) {
            v = Number(v);
            size[n] += v;
            return v;
          }
          return 0;
        },
        avg: function(n, i, size, counterData, counts) {
          var v = counterData[i];
          if (isNumeric(v)) {
            v = Number(v);
            size[n] += v;
            counts[n]++;
          }
          return 0;
        },
        min: function(n, i, size, counterData) {
          var v = counterData[i];
          if (isNumeric(v)) {
            v = Number(v);
            if (!isNumeric(size[n])) {
              size[n] = v;
              return v;
            } else if (size[n] > v) {
              var delta = v - size[n];
              size[n] = v;
              return delta;
            }
          }
          return 0;
        },
        max: function(n, i, size, counterData) {
          var v = counterData[i];
          if (isNumeric(v)) {
            v = Number(v);
            if (!isNumeric(size[n])) {
              size[n] = v;
              return v;
            } else if (size[n] < v) {
              var delta = v - size[n];
              size[n] = v;
              return delta;
            }
          }
          return 0;
        }
      };
    }
  });

  // src/traces/histogram/norm_functions.js
  var require_norm_functions = __commonJS({
    "src/traces/histogram/norm_functions.js"(exports, module) {
      "use strict";
      module.exports = {
        percent: function(size, total) {
          var nMax = size.length;
          var norm = 100 / total;
          for (var n = 0; n < nMax; n++) size[n] *= norm;
        },
        probability: function(size, total) {
          var nMax = size.length;
          for (var n = 0; n < nMax; n++) size[n] /= total;
        },
        density: function(size, total, inc, yinc) {
          var nMax = size.length;
          yinc = yinc || 1;
          for (var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc;
        },
        "probability density": function(size, total, inc, yinc) {
          var nMax = size.length;
          if (yinc) total /= yinc;
          for (var n = 0; n < nMax; n++) size[n] *= inc[n] / total;
        }
      };
    }
  });

  // src/traces/histogram/average.js
  var require_average = __commonJS({
    "src/traces/histogram/average.js"(exports, module) {
      "use strict";
      module.exports = function doAvg(size, counts) {
        var nMax = size.length;
        var total = 0;
        for (var i = 0; i < nMax; i++) {
          if (counts[i]) {
            size[i] /= counts[i];
            total += size[i];
          } else size[i] = null;
        }
        return total;
      };
    }
  });

  // src/traces/histogram/bin_label_vals.js
  var require_bin_label_vals = __commonJS({
    "src/traces/histogram/bin_label_vals.js"(exports, module) {
      "use strict";
      var numConstants = require_numerical();
      var oneYear = numConstants.ONEAVGYEAR;
      var oneMonth = numConstants.ONEAVGMONTH;
      var oneDay = numConstants.ONEDAY;
      var oneHour = numConstants.ONEHOUR;
      var oneMin = numConstants.ONEMIN;
      var oneSec = numConstants.ONESEC;
      var tickIncrement = require_axes().tickIncrement;
      module.exports = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) {
        var dv0 = -1.1 * rightGap;
        var dv1 = -0.1 * rightGap;
        var dv2 = leftGap - dv1;
        var edge0 = binEdges[0];
        var edge1 = binEdges[1];
        var leftDigit = Math.min(
          biggestDigitChanged(edge0 + dv1, edge0 + dv2, pa, calendar),
          biggestDigitChanged(edge1 + dv1, edge1 + dv2, pa, calendar)
        );
        var rightDigit = Math.min(
          biggestDigitChanged(edge0 + dv0, edge0 + dv1, pa, calendar),
          biggestDigitChanged(edge1 + dv0, edge1 + dv1, pa, calendar)
        );
        var digit, disambiguateEdges;
        if (leftDigit > rightDigit && rightDigit < Math.abs(edge1 - edge0) / 4e3) {
          digit = leftDigit;
          disambiguateEdges = false;
        } else {
          digit = Math.min(leftDigit, rightDigit);
          disambiguateEdges = true;
        }
        if (pa.type === "date" && digit > oneDay) {
          var dashExclude = digit === oneYear ? 1 : 6;
          var increment = digit === oneYear ? "M12" : "M1";
          return function(v, isRightEdge) {
            var dateStr = pa.c2d(v, oneYear, calendar);
            var dashPos = dateStr.indexOf("-", dashExclude);
            if (dashPos > 0) dateStr = dateStr.slice(0, dashPos);
            var roundedV = pa.d2c(dateStr, 0, calendar);
            if (roundedV < v) {
              var nextV = tickIncrement(roundedV, increment, false, calendar);
              if ((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV;
            }
            if (isRightEdge && disambiguateEdges) {
              return tickIncrement(roundedV, increment, true, calendar);
            }
            return roundedV;
          };
        }
        return function(v, isRightEdge) {
          var roundedV = digit * Math.round(v / digit);
          if (roundedV + digit / 10 < v && roundedV + digit * 0.9 < v + leftGap) {
            roundedV += digit;
          }
          if (isRightEdge && disambiguateEdges) {
            roundedV -= digit;
          }
          return roundedV;
        };
      };
      function biggestDigitChanged(v1, v2, pa, calendar) {
        if (v1 * v2 <= 0) return Infinity;
        var dv = Math.abs(v2 - v1);
        var isDate = pa.type === "date";
        var digit = biggestGuaranteedDigitChanged(dv, isDate);
        for (var i = 0; i < 10; i++) {
          var nextDigit = biggestGuaranteedDigitChanged(digit * 80, isDate);
          if (digit === nextDigit) break;
          if (didDigitChange(nextDigit, v1, v2, isDate, pa, calendar)) digit = nextDigit;
          else break;
        }
        return digit;
      }
      function biggestGuaranteedDigitChanged(dv, isDate) {
        if (isDate && dv > oneSec) {
          if (dv > oneDay) {
            if (dv > oneYear * 1.1) return oneYear;
            if (dv > oneMonth * 1.1) return oneMonth;
            return oneDay;
          }
          if (dv > oneHour) return oneHour;
          if (dv > oneMin) return oneMin;
          return oneSec;
        }
        return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10));
      }
      function didDigitChange(digit, v1, v2, isDate, pa, calendar) {
        if (isDate && digit > oneDay) {
          var dateParts1 = dateParts(v1, pa, calendar);
          var dateParts2 = dateParts(v2, pa, calendar);
          var parti = digit === oneYear ? 0 : 1;
          return dateParts1[parti] !== dateParts2[parti];
        }
        return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1;
      }
      function dateParts(v, pa, calendar) {
        var parts = pa.c2d(v, oneYear, calendar).split("-");
        if (parts[0] === "") {
          parts.unshift();
          parts[0] = "-" + parts[0];
        }
        return parts;
      }
    }
  });

  // src/traces/histogram/calc.js
  var require_calc7 = __commonJS({
    "src/traces/histogram/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Registry = require_registry();
      var Axes = require_axes();
      var { hasColorscale } = require_helpers();
      var colorscaleCalc = require_calc();
      var arraysToCalcdata = require_arrays_to_calcdata2();
      var binFunctions = require_bin_functions();
      var normFunctions = require_norm_functions();
      var doAvg = require_average();
      var getBinSpanLabelRound = require_bin_label_vals();
      function calc(gd, trace) {
        var pos = [];
        var size = [];
        var isHorizontal = trace.orientation === "h";
        var pa = Axes.getFromId(gd, isHorizontal ? trace.yaxis : trace.xaxis);
        var mainData = isHorizontal ? "y" : "x";
        var counterData = { x: "y", y: "x" }[mainData];
        var calendar = trace[mainData + "calendar"];
        var cumulativeSpec = trace.cumulative;
        var i;
        var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData);
        var binSpec = binsAndPos[0];
        var pos0 = binsAndPos[1];
        var nonuniformBins = typeof binSpec.size === "string";
        var binEdges = [];
        var bins = nonuniformBins ? binEdges : binSpec;
        var inc = [];
        var counts = [];
        var inputPoints = [];
        var total = 0;
        var norm = trace.histnorm;
        var func = trace.histfunc;
        var densityNorm = norm.indexOf("density") !== -1;
        var i2, binEnd, n;
        if (cumulativeSpec.enabled && densityNorm) {
          norm = norm.replace(/ ?density$/, "");
          densityNorm = false;
        }
        var extremeFunc = func === "max" || func === "min";
        var sizeInit = extremeFunc ? null : 0;
        var binFunc = binFunctions.count;
        var normFunc = normFunctions[norm];
        var isAvg = false;
        var pr2c = function(v) {
          return pa.r2c(v, 0, calendar);
        };
        var rawCounterData;
        if (Lib.isArrayOrTypedArray(trace[counterData]) && func !== "count") {
          rawCounterData = trace[counterData];
          isAvg = func === "avg";
          binFunc = binFunctions[func];
        }
        i = pr2c(binSpec.start);
        binEnd = pr2c(binSpec.end) + (i - Axes.tickIncrement(i, binSpec.size, false, calendar)) / 1e6;
        while (i < binEnd && pos.length < 1e6) {
          i2 = Axes.tickIncrement(i, binSpec.size, false, calendar);
          pos.push((i + i2) / 2);
          size.push(sizeInit);
          inputPoints.push([]);
          binEdges.push(i);
          if (densityNorm) inc.push(1 / (i2 - i));
          if (isAvg) counts.push(0);
          if (i2 <= i) break;
          i = i2;
        }
        binEdges.push(i);
        if (!nonuniformBins && pa.type === "date") {
          bins = {
            start: pr2c(bins.start),
            end: pr2c(bins.end),
            size: bins.size
          };
        }
        if (!gd._fullLayout._roundFnOpts) gd._fullLayout._roundFnOpts = {};
        var groupName = trace["_" + mainData + "bingroup"];
        var roundFnOpts = { leftGap: Infinity, rightGap: Infinity };
        if (groupName) {
          if (!gd._fullLayout._roundFnOpts[groupName]) gd._fullLayout._roundFnOpts[groupName] = roundFnOpts;
          roundFnOpts = gd._fullLayout._roundFnOpts[groupName];
        }
        var nMax = size.length;
        var uniqueValsPerBin = true;
        var leftGap = roundFnOpts.leftGap;
        var rightGap = roundFnOpts.rightGap;
        var ptNumber2cdIndex = {};
        for (i = 0; i < pos0.length; i++) {
          var posi = pos0[i];
          n = Lib.findBin(posi, bins);
          if (n >= 0 && n < nMax) {
            total += binFunc(n, i, size, rawCounterData, counts);
            if (uniqueValsPerBin && inputPoints[n].length && posi !== pos0[inputPoints[n][0]]) {
              uniqueValsPerBin = false;
            }
            inputPoints[n].push(i);
            ptNumber2cdIndex[i] = n;
            leftGap = Math.min(leftGap, posi - binEdges[n]);
            rightGap = Math.min(rightGap, binEdges[n + 1] - posi);
          }
        }
        roundFnOpts.leftGap = leftGap;
        roundFnOpts.rightGap = rightGap;
        var roundFn;
        if (!uniqueValsPerBin) {
          roundFn = function(v, isRightEdge) {
            return function() {
              var roundFnOpts2 = gd._fullLayout._roundFnOpts[groupName];
              return getBinSpanLabelRound(
                roundFnOpts2.leftGap,
                roundFnOpts2.rightGap,
                binEdges,
                pa,
                calendar
              )(v, isRightEdge);
            };
          };
        }
        if (isAvg) total = doAvg(size, counts);
        if (normFunc) normFunc(size, total, inc);
        if (cumulativeSpec.enabled) cdf(size, cumulativeSpec.direction, cumulativeSpec.currentbin);
        var seriesLen = Math.min(pos.length, size.length);
        var cd = [];
        var firstNonzero = 0;
        var lastNonzero = seriesLen - 1;
        for (i = 0; i < seriesLen; i++) {
          if (size[i]) {
            firstNonzero = i;
            break;
          }
        }
        for (i = seriesLen - 1; i >= firstNonzero; i--) {
          if (size[i]) {
            lastNonzero = i;
            break;
          }
        }
        for (i = firstNonzero; i <= lastNonzero; i++) {
          if (isNumeric(pos[i]) && isNumeric(size[i])) {
            var cdi = {
              p: pos[i],
              s: size[i],
              b: 0
            };
            if (!cumulativeSpec.enabled) {
              cdi.pts = inputPoints[i];
              if (uniqueValsPerBin) {
                cdi.ph0 = cdi.ph1 = inputPoints[i].length ? pos0[inputPoints[i][0]] : pos[i];
              } else {
                trace._computePh = true;
                cdi.ph0 = roundFn(binEdges[i]);
                cdi.ph1 = roundFn(binEdges[i + 1], true);
              }
            }
            cd.push(cdi);
          }
        }
        if (cd.length === 1) {
          cd[0].width1 = Axes.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p;
        }
        if (hasColorscale(trace, "marker")) {
          colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: "marker",
            cLetter: "c"
          });
        }
        if (hasColorscale(trace, "marker.line")) {
          colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: "marker.line",
            cLetter: "c"
          });
        }
        arraysToCalcdata(cd, trace);
        if (Lib.isArrayOrTypedArray(trace.selectedpoints)) {
          Lib.tagSelected(cd, trace, ptNumber2cdIndex);
        }
        return cd;
      }
      function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) {
        var binAttr = mainData + "bins";
        var fullLayout = gd._fullLayout;
        var groupName = trace["_" + mainData + "bingroup"];
        var binOpts = fullLayout._histogramBinOpts[groupName];
        var isOverlay = fullLayout.barmode === "overlay";
        var i, traces, tracei, calendar, pos0, autoVals, cumulativeSpec;
        var r2c = function(v) {
          return pa.r2c(v, 0, calendar);
        };
        var c2r = function(v) {
          return pa.c2r(v, 0, calendar);
        };
        var cleanBound = pa.type === "date" ? function(v) {
          return v || v === 0 ? Lib.cleanDate(v, null, calendar) : null;
        } : function(v) {
          return isNumeric(v) ? Number(v) : null;
        };
        function setBound(attr, bins, newBins) {
          if (bins[attr + "Found"]) {
            bins[attr] = cleanBound(bins[attr]);
            if (bins[attr] === null) bins[attr] = newBins[attr];
          } else {
            autoVals[attr] = bins[attr] = newBins[attr];
            Lib.nestedProperty(traces[0], binAttr + "." + attr).set(newBins[attr]);
          }
        }
        if (trace["_" + mainData + "autoBinFinished"]) {
          delete trace["_" + mainData + "autoBinFinished"];
        } else {
          traces = binOpts.traces;
          var allPos = [];
          var isFirstVisible = true;
          var has2dMap = false;
          var hasHist2dContour = false;
          for (i = 0; i < traces.length; i++) {
            tracei = traces[i];
            if (tracei.visible) {
              var mainDatai = binOpts.dirs[i];
              pos0 = tracei["_" + mainDatai + "pos0"] = pa.makeCalcdata(tracei, mainDatai);
              allPos = Lib.concat(allPos, pos0);
              delete tracei["_" + mainData + "autoBinFinished"];
              if (trace.visible === true) {
                if (isFirstVisible) {
                  isFirstVisible = false;
                } else {
                  delete tracei._autoBin;
                  tracei["_" + mainData + "autoBinFinished"] = 1;
                }
                if (Registry.traceIs(tracei, "2dMap")) {
                  has2dMap = true;
                }
                if (tracei.type === "histogram2dcontour") {
                  hasHist2dContour = true;
                }
              }
            }
          }
          calendar = traces[0][mainData + "calendar"];
          var newBinSpec = Axes.autoBin(allPos, pa, binOpts.nbins, has2dMap, calendar, binOpts.sizeFound && binOpts.size);
          var autoBin = traces[0]._autoBin = {};
          autoVals = autoBin[binOpts.dirs[0]] = {};
          if (hasHist2dContour) {
            if (!binOpts.size) {
              newBinSpec.start = c2r(Axes.tickIncrement(
                r2c(newBinSpec.start),
                newBinSpec.size,
                true,
                calendar
              ));
            }
            if (binOpts.end === void 0) {
              newBinSpec.end = c2r(Axes.tickIncrement(
                r2c(newBinSpec.end),
                newBinSpec.size,
                false,
                calendar
              ));
            }
          }
          if (isOverlay && !Registry.traceIs(trace, "2dMap") && newBinSpec._dataSpan === 0 && pa.type !== "category" && pa.type !== "multicategory" && trace.bingroup === "" && typeof trace.xbins === "undefined") {
            if (_overlayEdgeCase) return [newBinSpec, pos0, true];
            newBinSpec = handleSingleValueOverlays(gd, trace, pa, mainData, binAttr);
          }
          cumulativeSpec = tracei.cumulative || {};
          if (cumulativeSpec.enabled && cumulativeSpec.currentbin !== "include") {
            if (cumulativeSpec.direction === "decreasing") {
              newBinSpec.start = c2r(Axes.tickIncrement(
                r2c(newBinSpec.start),
                newBinSpec.size,
                true,
                calendar
              ));
            } else {
              newBinSpec.end = c2r(Axes.tickIncrement(
                r2c(newBinSpec.end),
                newBinSpec.size,
                false,
                calendar
              ));
            }
          }
          binOpts.size = newBinSpec.size;
          if (!binOpts.sizeFound) {
            autoVals.size = newBinSpec.size;
            Lib.nestedProperty(traces[0], binAttr + ".size").set(newBinSpec.size);
          }
          setBound("start", binOpts, newBinSpec);
          setBound("end", binOpts, newBinSpec);
        }
        pos0 = trace["_" + mainData + "pos0"];
        delete trace["_" + mainData + "pos0"];
        var traceInputBins = trace._input[binAttr] || {};
        var traceBinOptsCalc = Lib.extendFlat({}, binOpts);
        var mainStart = binOpts.start;
        var startIn = pa.r2l(traceInputBins.start);
        var hasStart = startIn !== void 0;
        if ((binOpts.startFound || hasStart) && startIn !== pa.r2l(mainStart)) {
          var traceStart = hasStart ? startIn : Lib.aggNums(Math.min, null, pos0);
          var dummyAx = {
            type: pa.type === "category" || pa.type === "multicategory" ? "linear" : pa.type,
            r2l: pa.r2l,
            dtick: binOpts.size,
            tick0: mainStart,
            calendar,
            range: [traceStart, Axes.tickIncrement(traceStart, binOpts.size, false, calendar)].map(pa.l2r)
          };
          var newStart = Axes.tickFirst(dummyAx);
          if (newStart > pa.r2l(traceStart)) {
            newStart = Axes.tickIncrement(newStart, binOpts.size, true, calendar);
          }
          traceBinOptsCalc.start = pa.l2r(newStart);
          if (!hasStart) Lib.nestedProperty(trace, binAttr + ".start").set(traceBinOptsCalc.start);
        }
        var mainEnd = binOpts.end;
        var endIn = pa.r2l(traceInputBins.end);
        var hasEnd = endIn !== void 0;
        if ((binOpts.endFound || hasEnd) && endIn !== pa.r2l(mainEnd)) {
          var traceEnd = hasEnd ? endIn : Lib.aggNums(Math.max, null, pos0);
          traceBinOptsCalc.end = pa.l2r(traceEnd);
          if (!hasEnd) Lib.nestedProperty(trace, binAttr + ".start").set(traceBinOptsCalc.end);
        }
        var autoBinAttr = "autobin" + mainData;
        if (trace._input[autoBinAttr] === false) {
          trace._input[binAttr] = Lib.extendFlat({}, trace[binAttr] || {});
          delete trace._input[autoBinAttr];
          delete trace[autoBinAttr];
        }
        return [traceBinOptsCalc, pos0];
      }
      function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) {
        var fullLayout = gd._fullLayout;
        var overlaidTraceGroup = getConnectedHistograms(gd, trace);
        var pastThisTrace = false;
        var minSize = Infinity;
        var singleValuedTraces = [trace];
        var i, tracei, binOpts;
        for (i = 0; i < overlaidTraceGroup.length; i++) {
          tracei = overlaidTraceGroup[i];
          if (tracei === trace) {
            pastThisTrace = true;
          } else if (!pastThisTrace) {
            binOpts = fullLayout._histogramBinOpts[tracei["_" + mainData + "bingroup"]];
            minSize = Math.min(minSize, binOpts.size || tracei[binAttr].size);
          } else {
            var resulti = calcAllAutoBins(gd, tracei, pa, mainData, true);
            var binSpeci = resulti[0];
            var isSingleValued = resulti[2];
            tracei["_" + mainData + "autoBinFinished"] = 1;
            tracei["_" + mainData + "pos0"] = resulti[1];
            if (isSingleValued) {
              singleValuedTraces.push(tracei);
            } else {
              minSize = Math.min(minSize, binSpeci.size);
            }
          }
        }
        var dataVals = new Array(singleValuedTraces.length);
        for (i = 0; i < singleValuedTraces.length; i++) {
          var pos0 = singleValuedTraces[i]["_" + mainData + "pos0"];
          for (var j = 0; j < pos0.length; j++) {
            if (pos0[j] !== void 0) {
              dataVals[i] = pos0[j];
              break;
            }
          }
        }
        if (!isFinite(minSize)) {
          minSize = Lib.distinctVals(dataVals).minDiff;
        }
        for (i = 0; i < singleValuedTraces.length; i++) {
          tracei = singleValuedTraces[i];
          var calendar = tracei[mainData + "calendar"];
          var newBins = {
            start: pa.c2r(dataVals[i] - minSize / 2, 0, calendar),
            end: pa.c2r(dataVals[i] + minSize / 2, 0, calendar),
            size: minSize
          };
          tracei._input[binAttr] = tracei[binAttr] = newBins;
          binOpts = fullLayout._histogramBinOpts[tracei["_" + mainData + "bingroup"]];
          if (binOpts) Lib.extendFlat(binOpts, newBins);
        }
        return trace[binAttr];
      }
      function getConnectedHistograms(gd, trace) {
        var xid = trace.xaxis;
        var yid = trace.yaxis;
        var orientation = trace.orientation;
        var out = [];
        var fullData = gd._fullData;
        for (var i = 0; i < fullData.length; i++) {
          var tracei = fullData[i];
          if (tracei.type === "histogram" && tracei.visible === true && tracei.orientation === orientation && tracei.xaxis === xid && tracei.yaxis === yid) {
            out.push(tracei);
          }
        }
        return out;
      }
      function cdf(size, direction, currentBin) {
        var i, vi, prevSum;
        function firstHalfPoint(i2) {
          prevSum = size[i2];
          size[i2] /= 2;
        }
        function nextHalfPoint(i2) {
          vi = size[i2];
          size[i2] = prevSum + vi / 2;
          prevSum += vi;
        }
        if (currentBin === "half") {
          if (direction === "increasing") {
            firstHalfPoint(0);
            for (i = 1; i < size.length; i++) {
              nextHalfPoint(i);
            }
          } else {
            firstHalfPoint(size.length - 1);
            for (i = size.length - 2; i >= 0; i--) {
              nextHalfPoint(i);
            }
          }
        } else if (direction === "increasing") {
          for (i = 1; i < size.length; i++) {
            size[i] += size[i - 1];
          }
          if (currentBin === "exclude") {
            size.unshift(0);
            size.pop();
          }
        } else {
          for (i = size.length - 2; i >= 0; i--) {
            size[i] += size[i + 1];
          }
          if (currentBin === "exclude") {
            size.push(0);
            size.shift();
          }
        }
      }
      module.exports = {
        calc,
        calcAllAutoBins
      };
    }
  });

  // src/traces/histogram2d/calc.js
  var require_calc8 = __commonJS({
    "src/traces/histogram2d/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var binFunctions = require_bin_functions();
      var normFunctions = require_norm_functions();
      var doAvg = require_average();
      var getBinSpanLabelRound = require_bin_label_vals();
      var calcAllAutoBins = require_calc7().calcAllAutoBins;
      module.exports = function calc(gd, trace) {
        var xa = Axes.getFromId(gd, trace.xaxis);
        var ya = Axes.getFromId(gd, trace.yaxis);
        var xcalendar = trace.xcalendar;
        var ycalendar = trace.ycalendar;
        var xr2c = function(v) {
          return xa.r2c(v, 0, xcalendar);
        };
        var yr2c = function(v) {
          return ya.r2c(v, 0, ycalendar);
        };
        var xc2r = function(v) {
          return xa.c2r(v, 0, xcalendar);
        };
        var yc2r = function(v) {
          return ya.c2r(v, 0, ycalendar);
        };
        var i, j, n, m;
        var xBinsAndPos = calcAllAutoBins(gd, trace, xa, "x");
        var xBinSpec = xBinsAndPos[0];
        var xPos0 = xBinsAndPos[1];
        var yBinsAndPos = calcAllAutoBins(gd, trace, ya, "y");
        var yBinSpec = yBinsAndPos[0];
        var yPos0 = yBinsAndPos[1];
        var serieslen = trace._length;
        if (xPos0.length > serieslen) xPos0.splice(serieslen, xPos0.length - serieslen);
        if (yPos0.length > serieslen) yPos0.splice(serieslen, yPos0.length - serieslen);
        var z = [];
        var onecol = [];
        var zerocol = [];
        var nonuniformBinsX = typeof xBinSpec.size === "string";
        var nonuniformBinsY = typeof yBinSpec.size === "string";
        var xEdges = [];
        var yEdges = [];
        var xbins = nonuniformBinsX ? xEdges : xBinSpec;
        var ybins = nonuniformBinsY ? yEdges : yBinSpec;
        var total = 0;
        var counts = [];
        var inputPoints = [];
        var norm = trace.histnorm;
        var func = trace.histfunc;
        var densitynorm = norm.indexOf("density") !== -1;
        var extremefunc = func === "max" || func === "min";
        var sizeinit = extremefunc ? null : 0;
        var binfunc = binFunctions.count;
        var normfunc = normFunctions[norm];
        var doavg = false;
        var xinc = [];
        var yinc = [];
        var rawCounterData = "z" in trace ? trace.z : "marker" in trace && Array.isArray(trace.marker.color) ? trace.marker.color : "";
        if (rawCounterData && func !== "count") {
          doavg = func === "avg";
          binfunc = binFunctions[func];
        }
        var xBinSize = xBinSpec.size;
        var xBinStart = xr2c(xBinSpec.start);
        var xBinEnd = xr2c(xBinSpec.end) + (xBinStart - Axes.tickIncrement(xBinStart, xBinSize, false, xcalendar)) / 1e6;
        for (i = xBinStart; i < xBinEnd; i = Axes.tickIncrement(i, xBinSize, false, xcalendar)) {
          onecol.push(sizeinit);
          xEdges.push(i);
          if (doavg) zerocol.push(0);
        }
        xEdges.push(i);
        var nx = onecol.length;
        var dx = (i - xBinStart) / nx;
        var x0 = xc2r(xBinStart + dx / 2);
        var yBinSize = yBinSpec.size;
        var yBinStart = yr2c(yBinSpec.start);
        var yBinEnd = yr2c(yBinSpec.end) + (yBinStart - Axes.tickIncrement(yBinStart, yBinSize, false, ycalendar)) / 1e6;
        for (i = yBinStart; i < yBinEnd; i = Axes.tickIncrement(i, yBinSize, false, ycalendar)) {
          z.push(onecol.slice());
          yEdges.push(i);
          var ipCol = new Array(nx);
          for (j = 0; j < nx; j++) ipCol[j] = [];
          inputPoints.push(ipCol);
          if (doavg) counts.push(zerocol.slice());
        }
        yEdges.push(i);
        var ny = z.length;
        var dy = (i - yBinStart) / ny;
        var y0 = yc2r(yBinStart + dy / 2);
        if (densitynorm) {
          xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX);
          yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY);
        }
        if (!nonuniformBinsX && xa.type === "date") xbins = binsToCalc(xr2c, xbins);
        if (!nonuniformBinsY && ya.type === "date") ybins = binsToCalc(yr2c, ybins);
        var uniqueValsPerX = true;
        var uniqueValsPerY = true;
        var xVals = new Array(nx);
        var yVals = new Array(ny);
        var xGapLow = Infinity;
        var xGapHigh = Infinity;
        var yGapLow = Infinity;
        var yGapHigh = Infinity;
        for (i = 0; i < serieslen; i++) {
          var xi = xPos0[i];
          var yi = yPos0[i];
          n = Lib.findBin(xi, xbins);
          m = Lib.findBin(yi, ybins);
          if (n >= 0 && n < nx && m >= 0 && m < ny) {
            total += binfunc(n, i, z[m], rawCounterData, counts[m]);
            inputPoints[m][n].push(i);
            if (uniqueValsPerX) {
              if (xVals[n] === void 0) xVals[n] = xi;
              else if (xVals[n] !== xi) uniqueValsPerX = false;
            }
            if (uniqueValsPerY) {
              if (yVals[m] === void 0) yVals[m] = yi;
              else if (yVals[m] !== yi) uniqueValsPerY = false;
            }
            xGapLow = Math.min(xGapLow, xi - xEdges[n]);
            xGapHigh = Math.min(xGapHigh, xEdges[n + 1] - xi);
            yGapLow = Math.min(yGapLow, yi - yEdges[m]);
            yGapHigh = Math.min(yGapHigh, yEdges[m + 1] - yi);
          }
        }
        if (doavg) {
          for (m = 0; m < ny; m++) total += doAvg(z[m], counts[m]);
        }
        if (normfunc) {
          for (m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]);
        }
        return {
          x: xPos0,
          xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar),
          x0,
          dx,
          y: yPos0,
          yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar),
          y0,
          dy,
          z,
          pts: inputPoints
        };
      };
      function makeIncrements(len, bins, dv, nonuniform) {
        var out = new Array(len);
        var i;
        if (nonuniform) {
          for (i = 0; i < len; i++) out[i] = 1 / (bins[i + 1] - bins[i]);
        } else {
          var inc = 1 / dv;
          for (i = 0; i < len; i++) out[i] = inc;
        }
        return out;
      }
      function binsToCalc(r2c, bins) {
        return {
          start: r2c(bins.start),
          end: r2c(bins.end),
          size: bins.size
        };
      }
      function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) {
        var i;
        var len = edges.length - 1;
        var out = new Array(len);
        var roundFn = getBinSpanLabelRound(gapLow, gapHigh, edges, ax, calendar);
        for (i = 0; i < len; i++) {
          var v = (uniqueVals || [])[i];
          out[i] = v === void 0 ? [roundFn(edges[i]), roundFn(edges[i + 1], true)] : [v, v];
        }
        return out;
      }
    }
  });

  // src/traces/heatmap/convert_column_xyz.js
  var require_convert_column_xyz = __commonJS({
    "src/traces/heatmap/convert_column_xyz.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var BADNUM = require_numerical().BADNUM;
      var alignPeriod = require_align_period();
      module.exports = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) {
        var colLen = trace._length;
        var col1 = ax1.makeCalcdata(trace, var1Name);
        var col2 = ax2.makeCalcdata(trace, var2Name);
        col1 = alignPeriod(trace, ax1, var1Name, col1).vals;
        col2 = alignPeriod(trace, ax2, var2Name, col2).vals;
        var textCol = trace.text;
        var hasColumnText = textCol !== void 0 && Lib.isArray1D(textCol);
        var hoverTextCol = trace.hovertext;
        var hasColumnHoverText = hoverTextCol !== void 0 && Lib.isArray1D(hoverTextCol);
        var i, j;
        var col1dv = Lib.distinctVals(col1);
        var col1vals = col1dv.vals;
        var col2dv = Lib.distinctVals(col2);
        var col2vals = col2dv.vals;
        var newArrays = [];
        var text;
        var hovertext;
        var nI = col2vals.length;
        var nJ = col1vals.length;
        for (i = 0; i < arrayVarNames.length; i++) {
          newArrays[i] = Lib.init2dArray(nI, nJ);
        }
        if (hasColumnText) {
          text = Lib.init2dArray(nI, nJ);
        }
        if (hasColumnHoverText) {
          hovertext = Lib.init2dArray(nI, nJ);
        }
        var after2before = Lib.init2dArray(nI, nJ);
        for (i = 0; i < colLen; i++) {
          if (col1[i] !== BADNUM && col2[i] !== BADNUM) {
            var i1 = Lib.findBin(col1[i] + col1dv.minDiff / 2, col1vals);
            var i2 = Lib.findBin(col2[i] + col2dv.minDiff / 2, col2vals);
            for (j = 0; j < arrayVarNames.length; j++) {
              var arrayVarName = arrayVarNames[j];
              var arrayVar = trace[arrayVarName];
              var newArray = newArrays[j];
              newArray[i2][i1] = arrayVar[i];
              after2before[i2][i1] = i;
            }
            if (hasColumnText) text[i2][i1] = textCol[i];
            if (hasColumnHoverText) hovertext[i2][i1] = hoverTextCol[i];
          }
        }
        trace["_" + var1Name] = col1vals;
        trace["_" + var2Name] = col2vals;
        for (j = 0; j < arrayVarNames.length; j++) {
          trace["_" + arrayVarNames[j]] = newArrays[j];
        }
        if (hasColumnText) trace._text = text;
        if (hasColumnHoverText) trace._hovertext = hovertext;
        if (ax1 && ax1.type === "category") {
          trace["_" + var1Name + "CategoryMap"] = col1vals.map(function(v) {
            return ax1._categories[v];
          });
        }
        if (ax2 && ax2.type === "category") {
          trace["_" + var2Name + "CategoryMap"] = col2vals.map(function(v) {
            return ax2._categories[v];
          });
        }
        trace._after2before = after2before;
      };
    }
  });

  // src/traces/heatmap/clean_2d_array.js
  var require_clean_2d_array = __commonJS({
    "src/traces/heatmap/clean_2d_array.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function clean2dArray(zOld, trace, xa, ya) {
        var rowlen, collen, getCollen, old2new, i, j;
        function cleanZvalue(v) {
          if (!isNumeric(v)) return void 0;
          return +v;
        }
        if (trace && trace.transpose) {
          rowlen = 0;
          for (i = 0; i < zOld.length; i++) rowlen = Math.max(rowlen, zOld[i].length);
          if (rowlen === 0) return false;
          getCollen = function(zOld2) {
            return zOld2.length;
          };
          old2new = function(zOld2, i2, j2) {
            return (zOld2[j2] || [])[i2];
          };
        } else {
          rowlen = zOld.length;
          getCollen = function(zOld2, i2) {
            return zOld2[i2].length;
          };
          old2new = function(zOld2, i2, j2) {
            return (zOld2[i2] || [])[j2];
          };
        }
        var padOld2new = function(zOld2, i2, j2) {
          if (i2 === BADNUM || j2 === BADNUM) return BADNUM;
          return old2new(zOld2, i2, j2);
        };
        function axisMapping(ax) {
          if (trace && trace.type !== "carpet" && trace.type !== "contourcarpet" && ax && ax.type === "category" && trace["_" + ax._id.charAt(0)].length) {
            var axLetter = ax._id.charAt(0);
            var axMapping = {};
            var traceCategories = trace["_" + axLetter + "CategoryMap"] || trace[axLetter];
            for (i = 0; i < traceCategories.length; i++) {
              axMapping[traceCategories[i]] = i;
            }
            return function(i2) {
              var ind = axMapping[ax._categories[i2]];
              return ind + 1 ? ind : BADNUM;
            };
          } else {
            return Lib.identity;
          }
        }
        var xMap = axisMapping(xa);
        var yMap = axisMapping(ya);
        if (ya && ya.type === "category") rowlen = ya._categories.length;
        var zNew = new Array(rowlen);
        for (i = 0; i < rowlen; i++) {
          if (xa && xa.type === "category") {
            collen = xa._categories.length;
          } else {
            collen = getCollen(zOld, i);
          }
          zNew[i] = new Array(collen);
          for (j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(padOld2new(zOld, yMap(i), xMap(j)));
        }
        return zNew;
      };
    }
  });

  // src/traces/heatmap/interp2d.js
  var require_interp2d = __commonJS({
    "src/traces/heatmap/interp2d.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var INTERPTHRESHOLD = 0.01;
      var NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]];
      function correctionOvershoot(maxFractionalChange) {
        return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5);
      }
      module.exports = function interp2d(z, emptyPoints) {
        var maxFractionalChange = 1;
        var i;
        iterateInterp2d(z, emptyPoints);
        for (i = 0; i < emptyPoints.length; i++) {
          if (emptyPoints[i][2] < 4) break;
        }
        emptyPoints = emptyPoints.slice(i);
        for (i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) {
          maxFractionalChange = iterateInterp2d(
            z,
            emptyPoints,
            correctionOvershoot(maxFractionalChange)
          );
        }
        if (maxFractionalChange > INTERPTHRESHOLD) {
          Lib.log("interp2d didn't converge quickly", maxFractionalChange);
        }
        return z;
      };
      function iterateInterp2d(z, emptyPoints, overshoot) {
        var maxFractionalChange = 0;
        var thisPt;
        var i;
        var j;
        var p;
        var q;
        var neighborShift;
        var neighborRow;
        var neighborVal;
        var neighborCount;
        var neighborSum;
        var initialVal;
        var minNeighbor;
        var maxNeighbor;
        for (p = 0; p < emptyPoints.length; p++) {
          thisPt = emptyPoints[p];
          i = thisPt[0];
          j = thisPt[1];
          initialVal = z[i][j];
          neighborSum = 0;
          neighborCount = 0;
          for (q = 0; q < 4; q++) {
            neighborShift = NEIGHBORSHIFTS[q];
            neighborRow = z[i + neighborShift[0]];
            if (!neighborRow) continue;
            neighborVal = neighborRow[j + neighborShift[1]];
            if (neighborVal !== void 0) {
              if (neighborSum === 0) {
                minNeighbor = maxNeighbor = neighborVal;
              } else {
                minNeighbor = Math.min(minNeighbor, neighborVal);
                maxNeighbor = Math.max(maxNeighbor, neighborVal);
              }
              neighborCount++;
              neighborSum += neighborVal;
            }
          }
          if (neighborCount === 0) {
            throw "iterateInterp2d order is wrong: no defined neighbors";
          }
          z[i][j] = neighborSum / neighborCount;
          if (initialVal === void 0) {
            if (neighborCount < 4) maxFractionalChange = 1;
          } else {
            z[i][j] = (1 + overshoot) * z[i][j] - overshoot * initialVal;
            if (maxNeighbor > minNeighbor) {
              maxFractionalChange = Math.max(
                maxFractionalChange,
                Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor)
              );
            }
          }
        }
        return maxFractionalChange;
      }
    }
  });

  // src/traces/heatmap/find_empties.js
  var require_find_empties = __commonJS({
    "src/traces/heatmap/find_empties.js"(exports, module) {
      "use strict";
      var maxRowLength = require_lib().maxRowLength;
      module.exports = function findEmpties(z) {
        var empties = [];
        var neighborHash = {};
        var noNeighborList = [];
        var nextRow = z[0];
        var row = [];
        var blank = [0, 0, 0];
        var rowLength = maxRowLength(z);
        var prevRow;
        var i;
        var j;
        var thisPt;
        var p;
        var neighborCount;
        var newNeighborHash;
        var foundNewNeighbors;
        for (i = 0; i < z.length; i++) {
          prevRow = row;
          row = nextRow;
          nextRow = z[i + 1] || [];
          for (j = 0; j < rowLength; j++) {
            if (row[j] === void 0) {
              neighborCount = (row[j - 1] !== void 0 ? 1 : 0) + (row[j + 1] !== void 0 ? 1 : 0) + (prevRow[j] !== void 0 ? 1 : 0) + (nextRow[j] !== void 0 ? 1 : 0);
              if (neighborCount) {
                if (i === 0) neighborCount++;
                if (j === 0) neighborCount++;
                if (i === z.length - 1) neighborCount++;
                if (j === row.length - 1) neighborCount++;
                if (neighborCount < 4) {
                  neighborHash[[i, j]] = [i, j, neighborCount];
                }
                empties.push([i, j, neighborCount]);
              } else noNeighborList.push([i, j]);
            }
          }
        }
        while (noNeighborList.length) {
          newNeighborHash = {};
          foundNewNeighbors = false;
          for (p = noNeighborList.length - 1; p >= 0; p--) {
            thisPt = noNeighborList[p];
            i = thisPt[0];
            j = thisPt[1];
            neighborCount = ((neighborHash[[i - 1, j]] || blank)[2] + (neighborHash[[i + 1, j]] || blank)[2] + (neighborHash[[i, j - 1]] || blank)[2] + (neighborHash[[i, j + 1]] || blank)[2]) / 20;
            if (neighborCount) {
              newNeighborHash[thisPt] = [i, j, neighborCount];
              noNeighborList.splice(p, 1);
              foundNewNeighbors = true;
            }
          }
          if (!foundNewNeighbors) {
            throw "findEmpties iterated with no new neighbors";
          }
          for (thisPt in newNeighborHash) {
            neighborHash[thisPt] = newNeighborHash[thisPt];
            empties.push(newNeighborHash[thisPt]);
          }
        }
        return empties.sort(function(a, b) {
          return b[2] - a[2];
        });
      };
    }
  });

  // src/traces/heatmap/make_bound_array.js
  var require_make_bound_array = __commonJS({
    "src/traces/heatmap/make_bound_array.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      module.exports = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) {
        var arrayOut = [];
        var isContour = Registry.traceIs(trace, "contour");
        var isHist = Registry.traceIs(trace, "histogram");
        var v0;
        var dv;
        var i;
        var isArrayOfTwoItemsOrMore = isArrayOrTypedArray(arrayIn) && arrayIn.length > 1;
        if (isArrayOfTwoItemsOrMore && !isHist && ax.type !== "category") {
          var len = arrayIn.length;
          if (len <= numbricks) {
            if (isContour) arrayOut = Array.from(arrayIn).slice(0, numbricks);
            else if (numbricks === 1) {
              if (ax.type === "log") {
                arrayOut = [0.5 * arrayIn[0], 2 * arrayIn[0]];
              } else {
                arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5];
              }
            } else if (ax.type === "log") {
              arrayOut = [Math.pow(arrayIn[0], 1.5) / Math.pow(arrayIn[1], 0.5)];
              for (i = 1; i < len; i++) {
                arrayOut.push(Math.sqrt(arrayIn[i - 1] * arrayIn[i]));
              }
              arrayOut.push(Math.pow(arrayIn[len - 1], 1.5) / Math.pow(arrayIn[len - 2], 0.5));
            } else {
              arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]];
              for (i = 1; i < len; i++) {
                arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5);
              }
              arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]);
            }
            if (len < numbricks) {
              var lastPt = arrayOut[arrayOut.length - 1];
              var delta;
              if (ax.type === "log") {
                delta = lastPt / arrayOut[arrayOut.length - 2];
                for (i = len; i < numbricks; i++) {
                  lastPt *= delta;
                  arrayOut.push(lastPt);
                }
              } else {
                delta = lastPt - arrayOut[arrayOut.length - 2];
                for (i = len; i < numbricks; i++) {
                  lastPt += delta;
                  arrayOut.push(lastPt);
                }
              }
            }
          } else {
            return isContour ? arrayIn.slice(0, numbricks) : (
              // we must be strict for contours
              arrayIn.slice(0, numbricks + 1)
            );
          }
        } else {
          var calendar = trace[ax._id.charAt(0) + "calendar"];
          if (isHist) {
            v0 = ax.r2c(v0In, 0, calendar);
          } else {
            if (isArrayOrTypedArray(arrayIn) && arrayIn.length === 1) {
              v0 = arrayIn[0];
            } else if (v0In === void 0) {
              v0 = 0;
            } else {
              var fn = ax.type === "log" ? ax.d2c : ax.r2c;
              v0 = fn(v0In, 0, calendar);
            }
          }
          dv = dvIn || 1;
          for (i = isContour ? 0 : -0.5; i < numbricks; i++) {
            arrayOut.push(v0 + dv * i);
          }
        }
        return arrayOut;
      };
    }
  });

  // src/traces/heatmap/calc.js
  var require_calc9 = __commonJS({
    "src/traces/heatmap/calc.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var histogram2dCalc = require_calc8();
      var colorscaleCalc = require_calc();
      var convertColumnData = require_convert_column_xyz();
      var clean2dArray = require_clean_2d_array();
      var interp2d = require_interp2d();
      var findEmpties = require_find_empties();
      var makeBoundArray = require_make_bound_array();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function calc(gd, trace) {
        var xa = Axes.getFromId(gd, trace.xaxis || "x");
        var ya = Axes.getFromId(gd, trace.yaxis || "y");
        var isContour = Registry.traceIs(trace, "contour");
        var isHist = Registry.traceIs(trace, "histogram");
        var zsmooth = isContour ? "best" : trace.zsmooth;
        var x, x0, dx, origX;
        var y, y0, dy, origY;
        var z, i, binned;
        xa._minDtick = 0;
        ya._minDtick = 0;
        if (isHist) {
          binned = histogram2dCalc(gd, trace);
          origX = binned.orig_x;
          x = binned.x;
          x0 = binned.x0;
          dx = binned.dx;
          origY = binned.orig_y;
          y = binned.y;
          y0 = binned.y0;
          dy = binned.dy;
          z = binned.z;
        } else {
          var zIn = trace.z;
          if (Lib.isArray1D(zIn)) {
            convertColumnData(trace, xa, ya, "x", "y", ["z"]);
            x = trace._x;
            y = trace._y;
            zIn = trace._z;
          } else {
            origX = trace.x ? xa.makeCalcdata(trace, "x") : [];
            origY = trace.y ? ya.makeCalcdata(trace, "y") : [];
            x = alignPeriod(trace, xa, "x", origX).vals;
            y = alignPeriod(trace, ya, "y", origY).vals;
            trace._x = x;
            trace._y = y;
          }
          x0 = trace.x0;
          dx = trace.dx;
          y0 = trace.y0;
          dy = trace.dy;
          z = clean2dArray(zIn, trace, xa, ya);
        }
        if (xa.rangebreaks || ya.rangebreaks) {
          z = dropZonBreaks(x, y, z);
          if (!isHist) {
            x = skipBreaks(x);
            y = skipBreaks(y);
            trace._x = x;
            trace._y = y;
          }
        }
        if (!isHist && (isContour || trace.connectgaps)) {
          trace._emptypoints = findEmpties(z);
          interp2d(z, trace._emptypoints);
        }
        function noZsmooth(msg) {
          zsmooth = trace._input.zsmooth = trace.zsmooth = false;
          Lib.warn('cannot use zsmooth: "fast": ' + msg);
        }
        function scaleIsLinear(s) {
          if (s.length > 1) {
            var avgdx = (s[s.length - 1] - s[0]) / (s.length - 1);
            var maxErrX = Math.abs(avgdx / 100);
            for (i = 0; i < s.length - 1; i++) {
              if (Math.abs(s[i + 1] - s[i] - avgdx) > maxErrX) {
                return false;
              }
            }
          }
          return true;
        }
        trace._islinear = false;
        if (xa.type === "log" || ya.type === "log") {
          if (zsmooth === "fast") {
            noZsmooth("log axis found");
          }
        } else if (!scaleIsLinear(x)) {
          if (zsmooth === "fast") noZsmooth("x scale is not linear");
        } else if (!scaleIsLinear(y)) {
          if (zsmooth === "fast") noZsmooth("y scale is not linear");
        } else {
          trace._islinear = true;
        }
        var xlen = Lib.maxRowLength(z);
        var xIn = trace.xtype === "scaled" ? "" : x;
        var xArray = makeBoundArray(trace, xIn, x0, dx, xlen, xa);
        var yIn = trace.ytype === "scaled" ? "" : y;
        var yArray = makeBoundArray(trace, yIn, y0, dy, z.length, ya);
        trace._extremes[xa._id] = Axes.findExtremes(xa, xArray);
        trace._extremes[ya._id] = Axes.findExtremes(ya, yArray);
        var cd0 = {
          x: xArray,
          y: yArray,
          z,
          text: trace._text || trace.text,
          hovertext: trace._hovertext || trace.hovertext
        };
        if (trace.xperiodalignment && origX) {
          cd0.orig_x = origX;
        }
        if (trace.yperiodalignment && origY) {
          cd0.orig_y = origY;
        }
        if (xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn;
        if (yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn;
        if (isHist) {
          cd0.xRanges = binned.xRanges;
          cd0.yRanges = binned.yRanges;
          cd0.pts = binned.pts;
        }
        if (!isContour) {
          colorscaleCalc(gd, trace, { vals: z, cLetter: "z" });
        }
        if (isContour && trace.contours && trace.contours.coloring === "heatmap") {
          var dummyTrace = {
            type: trace.type === "contour" ? "heatmap" : "histogram2d",
            xcalendar: trace.xcalendar,
            ycalendar: trace.ycalendar
          };
          cd0.xfill = makeBoundArray(dummyTrace, xIn, x0, dx, xlen, xa);
          cd0.yfill = makeBoundArray(dummyTrace, yIn, y0, dy, z.length, ya);
        }
        return [cd0];
      };
      function skipBreaks(a) {
        var b = [];
        var len = a.length;
        for (var i = 0; i < len; i++) {
          var v = a[i];
          if (v !== BADNUM) b.push(v);
        }
        return b;
      }
      function dropZonBreaks(x, y, z) {
        var newZ = [];
        var k = -1;
        for (var i = 0; i < z.length; i++) {
          if (y[i] === BADNUM) continue;
          k++;
          newZ[k] = [];
          for (var j = 0; j < z[i].length; j++) {
            if (x[j] === BADNUM) continue;
            newZ[k].push(z[i][j]);
          }
        }
        return newZ;
      }
    }
  });

  // src/constants/pixelated_image.js
  var require_pixelated_image = __commonJS({
    "src/constants/pixelated_image.js"(exports) {
      "use strict";
      exports.CSS_DECLARATIONS = [
        ["image-rendering", "optimizeSpeed"],
        ["image-rendering", "-moz-crisp-edges"],
        ["image-rendering", "-o-crisp-edges"],
        ["image-rendering", "-webkit-optimize-contrast"],
        ["image-rendering", "optimize-contrast"],
        ["image-rendering", "crisp-edges"],
        ["image-rendering", "pixelated"]
      ];
      exports.STYLE = exports.CSS_DECLARATIONS.map(function(d) {
        return d.join(": ") + "; ";
      }).join("");
    }
  });

  // src/lib/supports_pixelated_image.js
  var require_supports_pixelated_image = __commonJS({
    "src/lib/supports_pixelated_image.js"(exports, module) {
      "use strict";
      var constants = require_pixelated_image();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var _supportsPixelated = null;
      function supportsPixelatedImage() {
        if (_supportsPixelated !== null) {
          return _supportsPixelated;
        }
        _supportsPixelated = false;
        var unsupportedBrowser = Lib.isSafari() || Lib.isMacWKWebView() || Lib.isIOS();
        if (window.navigator.userAgent && !unsupportedBrowser) {
          var declarations = Array.from(constants.CSS_DECLARATIONS).reverse();
          var supports = window.CSS && window.CSS.supports || window.supportsCSS;
          if (typeof supports === "function") {
            _supportsPixelated = declarations.some(function(d) {
              return supports.apply(null, d);
            });
          } else {
            var image3 = Drawing.tester.append("image").attr("style", constants.STYLE);
            var cStyles = window.getComputedStyle(image3.node());
            var imageRendering = cStyles.imageRendering;
            _supportsPixelated = declarations.some(function(d) {
              var value = d[1];
              return imageRendering === value || imageRendering === value.toLowerCase();
            });
            image3.remove();
          }
        }
        return _supportsPixelated;
      }
      module.exports = supportsPixelatedImage;
    }
  });

  // src/traces/heatmap/plot.js
  var require_plot5 = __commonJS({
    "src/traces/heatmap/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var tinycolor = require_tinycolor();
      var Registry = require_registry();
      var Drawing = require_drawing();
      var Axes = require_axes();
      var Lib = require_lib();
      var svgTextUtils = require_svg_text_utils();
      var formatLabels = require_format_labels();
      var Color2 = require_color();
      var extractOpts = require_colorscale().extractOpts;
      var makeColorScaleFuncFromTrace = require_colorscale().makeColorScaleFuncFromTrace;
      var xmlnsNamespaces = require_xmlns_namespaces();
      var alignmentConstants = require_alignment();
      var LINE_SPACING = alignmentConstants.LINE_SPACING;
      var supportsPixelatedImage = require_supports_pixelated_image();
      var PIXELATED_IMAGE_STYLE = require_pixelated_image().STYLE;
      var labelClass = "heatmap-label";
      function selectLabels(plotGroup) {
        return plotGroup.selectAll("g." + labelClass);
      }
      function removeLabels(plotGroup) {
        selectLabels(plotGroup).remove();
      }
      module.exports = function(gd, plotinfo, cdheatmaps, heatmapLayer) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        Lib.makeTraceGroups(heatmapLayer, cdheatmaps, "hm").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          var xGap = trace.xgap || 0;
          var yGap = trace.ygap || 0;
          var z = cd0.z;
          var x = cd0.x;
          var y = cd0.y;
          var xc = cd0.xCenter;
          var yc = cd0.yCenter;
          var isContour = Registry.traceIs(trace, "contour");
          var zsmooth = isContour ? "best" : trace.zsmooth;
          var m = z.length;
          var n = Lib.maxRowLength(z);
          var xrev = false;
          var yrev = false;
          var left, right, temp, top, bottom, i, j, k;
          i = 0;
          while (left === void 0 && i < x.length - 1) {
            left = xa.c2p(x[i]);
            i++;
          }
          i = x.length - 1;
          while (right === void 0 && i > 0) {
            right = xa.c2p(x[i]);
            i--;
          }
          if (right < left) {
            temp = right;
            right = left;
            left = temp;
            xrev = true;
          }
          i = 0;
          while (top === void 0 && i < y.length - 1) {
            top = ya.c2p(y[i]);
            i++;
          }
          i = y.length - 1;
          while (bottom === void 0 && i > 0) {
            bottom = ya.c2p(y[i]);
            i--;
          }
          if (bottom < top) {
            temp = top;
            top = bottom;
            bottom = temp;
            yrev = true;
          }
          if (isContour) {
            xc = x;
            yc = y;
            x = cd0.xfill;
            y = cd0.yfill;
          }
          var drawingMethod = "default";
          if (zsmooth) {
            drawingMethod = zsmooth === "best" ? "smooth" : "fast";
          } else if (trace._islinear && xGap === 0 && yGap === 0 && supportsPixelatedImage()) {
            drawingMethod = "fast";
          }
          if (drawingMethod !== "fast") {
            var extra = zsmooth === "best" ? 0 : 0.5;
            left = Math.max(-extra * xa._length, left);
            right = Math.min((1 + extra) * xa._length, right);
            top = Math.max(-extra * ya._length, top);
            bottom = Math.min((1 + extra) * ya._length, bottom);
          }
          var imageWidth = Math.round(right - left);
          var imageHeight = Math.round(bottom - top);
          var isOffScreen = left >= xa._length || right <= 0 || top >= ya._length || bottom <= 0;
          if (isOffScreen) {
            var noImage = plotGroup.selectAll("image").data([]);
            noImage.exit().remove();
            removeLabels(plotGroup);
            return;
          }
          var canvasW, canvasH;
          if (drawingMethod === "fast") {
            canvasW = n;
            canvasH = m;
          } else {
            canvasW = imageWidth;
            canvasH = imageHeight;
          }
          var canvas = document.createElement("canvas");
          canvas.width = canvasW;
          canvas.height = canvasH;
          var context = canvas.getContext("2d", { willReadFrequently: true });
          var sclFunc = makeColorScaleFuncFromTrace(trace, { noNumericCheck: true, returnArray: true });
          var xpx, ypx;
          if (drawingMethod === "fast") {
            xpx = xrev ? function(index) {
              return n - 1 - index;
            } : Lib.identity;
            ypx = yrev ? function(index) {
              return m - 1 - index;
            } : Lib.identity;
          } else {
            xpx = function(index) {
              return Lib.constrain(Math.round(xa.c2p(x[index]) - left), 0, imageWidth);
            };
            ypx = function(index) {
              return Lib.constrain(Math.round(ya.c2p(y[index]) - top), 0, imageHeight);
            };
          }
          var yi = ypx(0);
          var yb = [yi, yi];
          var xbi = xrev ? 0 : 1;
          var ybi = yrev ? 0 : 1;
          var pixcount = 0;
          var rcount = 0;
          var gcount = 0;
          var bcount = 0;
          var xb, xi, v, row, c;
          function setColor(v2, pixsize) {
            if (v2 !== void 0) {
              var c2 = sclFunc(v2);
              c2[0] = Math.round(c2[0]);
              c2[1] = Math.round(c2[1]);
              c2[2] = Math.round(c2[2]);
              pixcount += pixsize;
              rcount += c2[0] * pixsize;
              gcount += c2[1] * pixsize;
              bcount += c2[2] * pixsize;
              return c2;
            }
            return [0, 0, 0, 0];
          }
          function interpColor(r02, r12, xinterp, yinterp2) {
            var z00 = r02[xinterp.bin0];
            if (z00 === void 0) return setColor(void 0, 1);
            var z01 = r02[xinterp.bin1];
            var z10 = r12[xinterp.bin0];
            var z11 = r12[xinterp.bin1];
            var dx2 = z01 - z00 || 0;
            var dy2 = z10 - z00 || 0;
            var dxy;
            if (z01 === void 0) {
              if (z11 === void 0) dxy = 0;
              else if (z10 === void 0) dxy = 2 * (z11 - z00);
              else dxy = (2 * z11 - z10 - z00) * 2 / 3;
            } else if (z11 === void 0) {
              if (z10 === void 0) dxy = 0;
              else dxy = (2 * z00 - z01 - z10) * 2 / 3;
            } else if (z10 === void 0) dxy = (2 * z11 - z01 - z00) * 2 / 3;
            else dxy = z11 + z00 - z01 - z10;
            return setColor(z00 + xinterp.frac * dx2 + yinterp2.frac * (dy2 + xinterp.frac * dxy));
          }
          if (drawingMethod !== "default") {
            var pxIndex = 0;
            var pixels;
            try {
              pixels = new Uint8Array(canvasW * canvasH * 4);
            } catch (e) {
              pixels = new Array(canvasW * canvasH * 4);
            }
            if (drawingMethod === "smooth") {
              var xForPx = xc || x;
              var yForPx = yc || y;
              var xPixArray = new Array(xForPx.length);
              var yPixArray = new Array(yForPx.length);
              var xinterpArray = new Array(imageWidth);
              var findInterpX = xc ? findInterpFromCenters : findInterp;
              var findInterpY = yc ? findInterpFromCenters : findInterp;
              var yinterp, r0, r1;
              for (i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left);
              for (i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top);
              for (i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray);
              for (j = 0; j < imageHeight; j++) {
                yinterp = findInterpY(j, yPixArray);
                r0 = z[yinterp.bin0];
                r1 = z[yinterp.bin1];
                for (i = 0; i < imageWidth; i++, pxIndex += 4) {
                  c = interpColor(r0, r1, xinterpArray[i], yinterp);
                  putColor(pixels, pxIndex, c);
                }
              }
            } else {
              for (j = 0; j < m; j++) {
                row = z[j];
                yb = ypx(j);
                for (i = 0; i < n; i++) {
                  c = setColor(row[i], 1);
                  pxIndex = (yb * n + xpx(i)) * 4;
                  putColor(pixels, pxIndex, c);
                }
              }
            }
            var imageData = context.createImageData(canvasW, canvasH);
            try {
              imageData.data.set(pixels);
            } catch (e) {
              var pxArray = imageData.data;
              var dlen = pxArray.length;
              for (j = 0; j < dlen; j++) {
                pxArray[j] = pixels[j];
              }
            }
            context.putImageData(imageData, 0, 0);
          } else {
            var xGapLeft = Math.floor(xGap / 2);
            var yGapTop = Math.floor(yGap / 2);
            for (j = 0; j < m; j++) {
              row = z[j];
              yb.reverse();
              yb[ybi] = ypx(j + 1);
              if (yb[0] === yb[1] || yb[0] === void 0 || yb[1] === void 0) {
                continue;
              }
              xi = xpx(0);
              xb = [xi, xi];
              for (i = 0; i < n; i++) {
                xb.reverse();
                xb[xbi] = xpx(i + 1);
                if (xb[0] === xb[1] || xb[0] === void 0 || xb[1] === void 0) {
                  continue;
                }
                v = row[i];
                c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0]));
                context.fillStyle = "rgba(" + c.join(",") + ")";
                context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop, xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap);
              }
            }
          }
          rcount = Math.round(rcount / pixcount);
          gcount = Math.round(gcount / pixcount);
          bcount = Math.round(bcount / pixcount);
          var avgColor = tinycolor("rgb(" + rcount + "," + gcount + "," + bcount + ")");
          gd._hmpixcount = (gd._hmpixcount || 0) + pixcount;
          gd._hmlumcount = (gd._hmlumcount || 0) + pixcount * avgColor.getLuminance();
          var image3 = plotGroup.selectAll("image").data(cd);
          image3.enter().append("svg:image").attr({
            xmlns: xmlnsNamespaces.svg,
            preserveAspectRatio: "none"
          });
          image3.attr({
            height: imageHeight,
            width: imageWidth,
            x: left,
            y: top,
            "xlink:href": canvas.toDataURL("image/png")
          });
          if (drawingMethod === "fast" && !zsmooth) {
            image3.attr("style", PIXELATED_IMAGE_STYLE);
          }
          removeLabels(plotGroup);
          var texttemplate = trace.texttemplate;
          if (texttemplate) {
            var cOpts = extractOpts(trace);
            var dummyAx = {
              type: "linear",
              range: [cOpts.min, cOpts.max],
              _separators: xa._separators,
              _numFormat: xa._numFormat
            };
            var aHistogram2dContour = trace.type === "histogram2dcontour";
            var aContour = trace.type === "contour";
            var iStart = aContour ? 1 : 0;
            var iStop = aContour ? m - 1 : m;
            var jStart = aContour ? 1 : 0;
            var jStop = aContour ? n - 1 : n;
            var textData = [];
            for (i = iStart; i < iStop; i++) {
              var yVal;
              if (aContour) {
                yVal = cd0.y[i];
              } else if (aHistogram2dContour) {
                if (i === 0 || i === m - 1) continue;
                yVal = cd0.y[i];
              } else if (cd0.yCenter) {
                yVal = cd0.yCenter[i];
              } else {
                if (i + 1 === m && cd0.y[i + 1] === void 0) continue;
                yVal = (cd0.y[i] + cd0.y[i + 1]) / 2;
              }
              var _y = Math.round(ya.c2p(yVal));
              if (0 > _y || _y > ya._length) continue;
              for (j = jStart; j < jStop; j++) {
                var xVal;
                if (aContour) {
                  xVal = cd0.x[j];
                } else if (aHistogram2dContour) {
                  if (j === 0 || j === n - 1) continue;
                  xVal = cd0.x[j];
                } else if (cd0.xCenter) {
                  xVal = cd0.xCenter[j];
                } else {
                  if (j + 1 === n && cd0.x[j + 1] === void 0) continue;
                  xVal = (cd0.x[j] + cd0.x[j + 1]) / 2;
                }
                var _x = Math.round(xa.c2p(xVal));
                if (0 > _x || _x > xa._length) continue;
                var obj = formatLabels(
                  {
                    x: xVal,
                    y: yVal
                  },
                  trace,
                  gd._fullLayout
                );
                obj.x = xVal;
                obj.y = yVal;
                var zVal = cd0.z[i][j];
                if (zVal === void 0) {
                  obj.z = "";
                  obj.zLabel = "";
                } else {
                  obj.z = zVal;
                  obj.zLabel = Axes.tickText(dummyAx, zVal, "hover").text;
                }
                var theText = cd0.text && cd0.text[i] && cd0.text[i][j];
                if (theText === void 0 || theText === false) theText = "";
                obj.text = theText;
                var _t = Lib.texttemplateString({
                  data: [obj, trace._meta],
                  fallback: trace.texttemplatefallback,
                  labels: obj,
                  locale: gd._fullLayout._d3locale,
                  template: texttemplate
                });
                if (!_t) continue;
                var lines = _t.split("<br>");
                var nL = lines.length;
                var nC = 0;
                for (k = 0; k < nL; k++) {
                  nC = Math.max(nC, lines[k].length);
                }
                textData.push({
                  l: nL,
                  // number of lines
                  c: nC,
                  // maximum number of chars in a line
                  t: _t,
                  // text
                  x: _x,
                  y: _y,
                  z: zVal
                });
              }
            }
            var font = trace.textfont;
            var fontSize = font.size;
            var globalFontSize = gd._fullLayout.font.size;
            if (!fontSize || fontSize === "auto") {
              var minW = Infinity;
              var minH = Infinity;
              var maxL = 0;
              var maxC = 0;
              for (k = 0; k < textData.length; k++) {
                var d = textData[k];
                maxL = Math.max(maxL, d.l);
                maxC = Math.max(maxC, d.c);
                if (k < textData.length - 1) {
                  var nextD = textData[k + 1];
                  var dx = Math.abs(nextD.x - d.x);
                  var dy = Math.abs(nextD.y - d.y);
                  if (dx) minW = Math.min(minW, dx);
                  if (dy) minH = Math.min(minH, dy);
                }
              }
              if (!isFinite(minW) || !isFinite(minH)) {
                fontSize = globalFontSize;
              } else {
                minW -= xGap;
                minH -= yGap;
                minW /= maxC;
                minH /= maxL;
                minW /= LINE_SPACING / 2;
                minH /= LINE_SPACING;
                fontSize = Math.min(Math.floor(minW), Math.floor(minH), globalFontSize);
              }
            }
            if (fontSize <= 0 || !isFinite(fontSize)) return;
            var xFn = function(d2) {
              return d2.x;
            };
            var yFn = function(d2) {
              return d2.y - fontSize * (d2.l * LINE_SPACING / 2 - 1);
            };
            var labels = selectLabels(plotGroup).data(textData);
            labels.enter().append("g").classed(labelClass, 1).append("text").attr("text-anchor", "middle").each(function(d2) {
              var thisLabel = d3.select(this);
              var fontColor = font.color;
              if (!fontColor || fontColor === "auto") {
                fontColor = Color2.contrast(
                  d2.z === void 0 ? gd._fullLayout.plot_bgcolor : "rgba(" + sclFunc(d2.z).join() + ")"
                );
              }
              thisLabel.attr("data-notex", 1).call(svgTextUtils.positionText, xFn(d2), yFn(d2)).call(Drawing.font, {
                family: font.family,
                size: fontSize,
                color: fontColor,
                weight: font.weight,
                style: font.style,
                variant: font.variant,
                textcase: font.textcase,
                lineposition: font.lineposition,
                shadow: font.shadow
              }).text(d2.t).call(svgTextUtils.convertToTspans, gd);
            });
          }
        });
      };
      function findInterp(pixel, pixArray) {
        var maxBin = pixArray.length - 2;
        var bin = Lib.constrain(Lib.findBin(pixel, pixArray), 0, maxBin);
        var pix0 = pixArray[bin];
        var pix1 = pixArray[bin + 1];
        var interp = Lib.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin);
        var bin0 = Math.round(interp);
        var frac = Math.abs(interp - bin0);
        if (!interp || interp === maxBin || !frac) {
          return {
            bin0,
            bin1: bin0,
            frac: 0
          };
        }
        return {
          bin0,
          frac,
          bin1: Math.round(bin0 + frac / (interp - bin0))
        };
      }
      function findInterpFromCenters(pixel, centerPixArray) {
        var maxBin = centerPixArray.length - 1;
        var bin = Lib.constrain(Lib.findBin(pixel, centerPixArray), 0, maxBin);
        var pix0 = centerPixArray[bin];
        var pix1 = centerPixArray[bin + 1];
        var frac = (pixel - pix0) / (pix1 - pix0) || 0;
        if (frac <= 0) {
          return {
            bin0: bin,
            bin1: bin,
            frac: 0
          };
        }
        if (frac < 0.5) {
          return {
            bin0: bin,
            bin1: bin + 1,
            frac
          };
        }
        return {
          bin0: bin + 1,
          bin1: bin,
          frac: 1 - frac
        };
      }
      function putColor(pixels, pxIndex, c) {
        pixels[pxIndex] = c[0];
        pixels[pxIndex + 1] = c[1];
        pixels[pxIndex + 2] = c[2];
        pixels[pxIndex + 3] = Math.round(c[3] * 255);
      }
    }
  });

  // src/traces/heatmap/colorbar.js
  var require_colorbar2 = __commonJS({
    "src/traces/heatmap/colorbar.js"(exports, module) {
      "use strict";
      module.exports = {
        min: "zmin",
        max: "zmax"
      };
    }
  });

  // src/traces/heatmap/style.js
  var require_style6 = __commonJS({
    "src/traces/heatmap/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      module.exports = function style(gd) {
        d3.select(gd).selectAll(".hm image").style("opacity", function(d) {
          return d.trace.opacity;
        });
      };
    }
  });

  // src/traces/heatmap/hover.js
  var require_hover5 = __commonJS({
    "src/traces/heatmap/hover.js"(exports, module) {
      "use strict";
      var Fx = require_fx();
      var Lib = require_lib();
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var Axes = require_axes();
      var extractOpts = require_colorscale().extractOpts;
      module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
        if (!opts) opts = {};
        var isContour = opts.isContour;
        var cd0 = pointData.cd[0];
        var trace = cd0.trace;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var x = cd0.x;
        var y = cd0.y;
        var z = cd0.z;
        var xc = cd0.xCenter;
        var yc = cd0.yCenter;
        var zmask = cd0.zmask;
        var zhoverformat = trace.zhoverformat;
        var x2 = x;
        var y2 = y;
        var xl, yl, nx, ny;
        if (pointData.index !== false) {
          try {
            nx = Math.round(pointData.index[1]);
            ny = Math.round(pointData.index[0]);
          } catch (e) {
            Lib.error("Error hovering on heatmap, pointNumber must be [row,col], found:", pointData.index);
            return;
          }
          if (nx < 0 || nx >= z[0].length || ny < 0 || ny > z.length) {
            return;
          }
        } else if (Fx.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || Fx.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) {
          return;
        } else {
          if (isContour) {
            var i2;
            x2 = [2 * x[0] - x[1]];
            for (i2 = 1; i2 < x.length; i2++) {
              x2.push((x[i2] + x[i2 - 1]) / 2);
            }
            x2.push([2 * x[x.length - 1] - x[x.length - 2]]);
            y2 = [2 * y[0] - y[1]];
            for (i2 = 1; i2 < y.length; i2++) {
              y2.push((y[i2] + y[i2 - 1]) / 2);
            }
            y2.push([2 * y[y.length - 1] - y[y.length - 2]]);
          }
          nx = Math.max(0, Math.min(x2.length - 2, Lib.findBin(xval, x2)));
          ny = Math.max(0, Math.min(y2.length - 2, Lib.findBin(yval, y2)));
        }
        var x0 = xa.c2p(x[nx]);
        var x1 = xa.c2p(x[nx + 1]);
        var y0 = ya.c2p(y[ny]);
        var y1 = ya.c2p(y[ny + 1]);
        var _x, _y;
        if (isContour) {
          _x = cd0.orig_x || x;
          _y = cd0.orig_y || y;
          x1 = x0;
          xl = _x[nx];
          y1 = y0;
          yl = _y[ny];
        } else {
          _x = cd0.orig_x || xc || x;
          _y = cd0.orig_y || yc || y;
          xl = xc ? _x[nx] : (_x[nx] + _x[nx + 1]) / 2;
          yl = yc ? _y[ny] : (_y[ny] + _y[ny + 1]) / 2;
          if (xa && xa.type === "category") xl = x[nx];
          if (ya && ya.type === "category") yl = y[ny];
          if (trace.zsmooth) {
            x0 = x1 = xa.c2p(xl);
            y0 = y1 = ya.c2p(yl);
          }
        }
        var zVal = z[ny][nx];
        if (zmask && !zmask[ny][nx]) zVal = void 0;
        if (zVal === void 0 && !trace.hoverongaps) return;
        var text;
        if (isArrayOrTypedArray(cd0.hovertext) && isArrayOrTypedArray(cd0.hovertext[ny])) {
          text = cd0.hovertext[ny][nx];
        } else if (isArrayOrTypedArray(cd0.text) && isArrayOrTypedArray(cd0.text[ny])) {
          text = cd0.text[ny][nx];
        }
        var cOpts = extractOpts(trace);
        var dummyAx = {
          type: "linear",
          range: [cOpts.min, cOpts.max],
          hoverformat: zhoverformat,
          _separators: xa._separators,
          _numFormat: xa._numFormat
        };
        var zLabel = Axes.tickText(dummyAx, zVal, "hover").text;
        return [Lib.extendFlat(pointData, {
          index: trace._after2before ? trace._after2before[ny][nx] : [ny, nx],
          // never let a 2D override 1D type as closest point
          distance: pointData.maxHoverDistance,
          spikeDistance: pointData.maxSpikeDistance,
          x0,
          x1,
          y0,
          y1,
          xLabelVal: xl,
          yLabelVal: yl,
          zLabelVal: zVal,
          zLabel,
          text
        })];
      };
    }
  });

  // src/traces/heatmap/index.js
  var require_heatmap = __commonJS({
    "src/traces/heatmap/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes25(),
        supplyDefaults: require_defaults21(),
        calc: require_calc9(),
        plot: require_plot5(),
        colorbar: require_colorbar2(),
        style: require_style6(),
        hoverPoints: require_hover5(),
        moduleType: "trace",
        name: "heatmap",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "2dMap", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/heatmap.js
  var require_heatmap2 = __commonJS({
    "lib/heatmap.js"(exports, module) {
      "use strict";
      module.exports = require_heatmap();
    }
  });

  // src/traces/histogram/bin_attributes.js
  var require_bin_attributes = __commonJS({
    "src/traces/histogram/bin_attributes.js"(exports, module) {
      "use strict";
      module.exports = function makeBinAttrs(axLetter, match) {
        return {
          start: {
            valType: "any",
            // for date axes
            editType: "calc"
          },
          end: {
            valType: "any",
            // for date axes
            editType: "calc"
          },
          size: {
            valType: "any",
            // for date axes
            editType: "calc"
          },
          editType: "calc"
        };
      };
    }
  });

  // src/traces/histogram/constants.js
  var require_constants15 = __commonJS({
    "src/traces/histogram/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        eventDataKeys: ["binNumber"]
      };
    }
  });

  // src/traces/histogram/attributes.js
  var require_attributes26 = __commonJS({
    "src/traces/histogram/attributes.js"(exports, module) {
      "use strict";
      var barAttrs = require_attributes23();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var fontAttrs = require_font_attributes();
      var makeBinAttrs = require_bin_attributes();
      var constants = require_constants15();
      var extendFlat = require_extend().extendFlat;
      module.exports = {
        x: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        y: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        text: extendFlat({}, barAttrs.text, {}),
        hovertext: extendFlat({}, barAttrs.hovertext, {}),
        orientation: barAttrs.orientation,
        histfunc: {
          valType: "enumerated",
          values: ["count", "sum", "avg", "min", "max"],
          dflt: "count",
          editType: "calc"
        },
        histnorm: {
          valType: "enumerated",
          values: ["", "percent", "probability", "density", "probability density"],
          dflt: "",
          editType: "calc"
        },
        cumulative: {
          enabled: {
            valType: "boolean",
            dflt: false,
            editType: "calc"
          },
          direction: {
            valType: "enumerated",
            values: ["increasing", "decreasing"],
            dflt: "increasing",
            editType: "calc"
          },
          currentbin: {
            valType: "enumerated",
            values: ["include", "exclude", "half"],
            dflt: "include",
            editType: "calc"
          },
          editType: "calc"
        },
        nbinsx: {
          valType: "integer",
          min: 0,
          dflt: 0,
          editType: "calc"
        },
        xbins: makeBinAttrs("x", true),
        nbinsy: {
          valType: "integer",
          min: 0,
          dflt: 0,
          editType: "calc"
        },
        ybins: makeBinAttrs("y", true),
        autobinx: {
          valType: "boolean",
          dflt: null,
          editType: "calc"
        },
        autobiny: {
          valType: "boolean",
          dflt: null,
          editType: "calc"
        },
        bingroup: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        texttemplate: texttemplateAttrs({ arrayOk: false, editType: "plot" }, { keys: ["label", "value"] }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        textposition: extendFlat({}, barAttrs.textposition, {
          arrayOk: false
        }),
        textfont: fontAttrs({
          arrayOk: false,
          editType: "plot",
          colorEditType: "style"
        }),
        outsidetextfont: fontAttrs({
          arrayOk: false,
          editType: "plot",
          colorEditType: "style"
        }),
        insidetextfont: fontAttrs({
          arrayOk: false,
          editType: "plot",
          colorEditType: "style"
        }),
        insidetextanchor: barAttrs.insidetextanchor,
        textangle: barAttrs.textangle,
        cliponaxis: barAttrs.cliponaxis,
        constraintext: barAttrs.constraintext,
        marker: barAttrs.marker,
        offsetgroup: barAttrs.offsetgroup,
        alignmentgroup: barAttrs.alignmentgroup,
        selected: barAttrs.selected,
        unselected: barAttrs.unselected,
        zorder: barAttrs.zorder
      };
    }
  });

  // src/traces/histogram/defaults.js
  var require_defaults22 = __commonJS({
    "src/traces/histogram/defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var Color2 = require_color();
      var handleText = require_defaults19().handleText;
      var handleStyleDefaults = require_style_defaults();
      var attributes = require_attributes26();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var x = coerce("x");
        var y = coerce("y");
        var cumulative = coerce("cumulative.enabled");
        if (cumulative) {
          coerce("cumulative.direction");
          coerce("cumulative.currentbin");
        }
        coerce("text");
        var textposition = coerce("textposition");
        handleText(traceIn, traceOut, layout, coerce, textposition, {
          moduleHasSelected: true,
          moduleHasUnselected: true,
          moduleHasConstrain: true,
          moduleHasCliponaxis: true,
          moduleHasTextangle: true,
          moduleHasInsideanchor: true
        });
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("xhoverformat");
        coerce("yhoverformat");
        var orientation = coerce("orientation", y && !x ? "h" : "v");
        var sampleLetter = orientation === "v" ? "x" : "y";
        var aggLetter = orientation === "v" ? "y" : "x";
        var len = x && y ? Math.min(Lib.minRowLength(x) && Lib.minRowLength(y)) : Lib.minRowLength(traceOut[sampleLetter] || []);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout);
        var hasAggregationData = traceOut[aggLetter];
        if (hasAggregationData) coerce("histfunc");
        coerce("histnorm");
        coerce("autobin" + sampleLetter);
        handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
        var lineColor = (traceOut.marker.line || {}).color;
        var errorBarsSupplyDefaults = Registry.getComponentMethod("errorbars", "supplyDefaults");
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color2.defaultLine, { axis: "y" });
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color2.defaultLine, { axis: "x", inherit: "y" });
        coerce("zorder");
      };
    }
  });

  // src/traces/histogram/cross_trace_defaults.js
  var require_cross_trace_defaults3 = __commonJS({
    "src/traces/histogram/cross_trace_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var axisIds = require_axis_ids();
      var traceIs = require_registry().traceIs;
      var handleGroupingDefaults = require_grouping_defaults();
      var validateCornerradius = require_defaults19().validateCornerradius;
      var nestedProperty = Lib.nestedProperty;
      var getAxisGroup = require_constraints().getAxisGroup;
      var BINATTRS = [
        { aStr: { x: "xbins.start", y: "ybins.start" }, name: "start" },
        { aStr: { x: "xbins.end", y: "ybins.end" }, name: "end" },
        { aStr: { x: "xbins.size", y: "ybins.size" }, name: "size" },
        { aStr: { x: "nbinsx", y: "nbinsy" }, name: "nbins" }
      ];
      var BINDIRECTIONS = ["x", "y"];
      module.exports = function crossTraceDefaults(fullData, fullLayout) {
        var allBinOpts = fullLayout._histogramBinOpts = {};
        var histTraces = [];
        var mustMatchTracesLookup = {};
        var otherTracesList = [];
        var traceOut, traces, groupName, binDir;
        var i, j, k;
        function coerce(attr2, dflt) {
          return Lib.coerce(traceOut._input, traceOut, traceOut._module.attributes, attr2, dflt);
        }
        function orientation2binDir(traceOut2) {
          return traceOut2.orientation === "v" ? "x" : "y";
        }
        function getAxisType(traceOut2, binDir2) {
          var ax = axisIds.getFromTrace({ _fullLayout: fullLayout }, traceOut2, binDir2);
          return ax.type;
        }
        function fillBinOpts(traceOut2, groupName2, binDir2) {
          var fallbackGroupName = traceOut2.uid + "__" + binDir2;
          if (!groupName2) groupName2 = fallbackGroupName;
          var axType = getAxisType(traceOut2, binDir2);
          var calendar = traceOut2[binDir2 + "calendar"] || "";
          var binOpts2 = allBinOpts[groupName2];
          var needsNewItem = true;
          if (binOpts2) {
            if (axType === binOpts2.axType && calendar === binOpts2.calendar) {
              needsNewItem = false;
              binOpts2.traces.push(traceOut2);
              binOpts2.dirs.push(binDir2);
            } else {
              groupName2 = fallbackGroupName;
              if (axType !== binOpts2.axType) {
                Lib.warn([
                  "Attempted to group the bins of trace",
                  traceOut2.index,
                  "set on a",
                  "type:" + axType,
                  "axis",
                  "with bins on",
                  "type:" + binOpts2.axType,
                  "axis."
                ].join(" "));
              }
              if (calendar !== binOpts2.calendar) {
                Lib.warn([
                  "Attempted to group the bins of trace",
                  traceOut2.index,
                  "set with a",
                  calendar,
                  "calendar",
                  "with bins",
                  binOpts2.calendar ? "on a " + binOpts2.calendar + " calendar" : "w/o a set calendar"
                ].join(" "));
              }
            }
          }
          if (needsNewItem) {
            allBinOpts[groupName2] = {
              traces: [traceOut2],
              dirs: [binDir2],
              axType,
              calendar: traceOut2[binDir2 + "calendar"] || ""
            };
          }
          traceOut2["_" + binDir2 + "bingroup"] = groupName2;
        }
        for (i = 0; i < fullData.length; i++) {
          traceOut = fullData[i];
          if (traceIs(traceOut, "histogram")) {
            histTraces.push(traceOut);
            delete traceOut._xautoBinFinished;
            delete traceOut._yautoBinFinished;
            if (traceOut.type === "histogram") {
              var r = coerce("marker.cornerradius", fullLayout.barcornerradius);
              if (traceOut.marker) {
                traceOut.marker.cornerradius = validateCornerradius(r);
              }
            }
            if (!traceIs(traceOut, "2dMap")) {
              handleGroupingDefaults(traceOut._input, traceOut, fullLayout, coerce, fullLayout.barmode);
            }
          }
        }
        var alignmentOpts = fullLayout._alignmentOpts || {};
        for (i = 0; i < histTraces.length; i++) {
          traceOut = histTraces[i];
          groupName = "";
          if (!traceIs(traceOut, "2dMap")) {
            binDir = orientation2binDir(traceOut);
            if (fullLayout.barmode === "group" && traceOut.alignmentgroup) {
              var pa = traceOut[binDir + "axis"];
              var aGroupId = getAxisGroup(fullLayout, pa) + traceOut.orientation;
              if ((alignmentOpts[aGroupId] || {})[traceOut.alignmentgroup]) {
                groupName = aGroupId;
              }
            }
            if (!groupName && fullLayout.barmode !== "overlay") {
              groupName = getAxisGroup(fullLayout, traceOut.xaxis) + getAxisGroup(fullLayout, traceOut.yaxis) + orientation2binDir(traceOut);
            }
          }
          if (groupName) {
            if (!mustMatchTracesLookup[groupName]) {
              mustMatchTracesLookup[groupName] = [];
            }
            mustMatchTracesLookup[groupName].push(traceOut);
          } else {
            otherTracesList.push(traceOut);
          }
        }
        for (groupName in mustMatchTracesLookup) {
          traces = mustMatchTracesLookup[groupName];
          if (traces.length === 1) {
            otherTracesList.push(traces[0]);
            continue;
          }
          var binGroupFound = false;
          if (traces.length) {
            traceOut = traces[0];
            binGroupFound = coerce("bingroup");
          }
          groupName = binGroupFound || groupName;
          for (i = 0; i < traces.length; i++) {
            traceOut = traces[i];
            var bingroupIn = traceOut._input.bingroup;
            if (bingroupIn && bingroupIn !== groupName) {
              Lib.warn([
                "Trace",
                traceOut.index,
                "must match",
                "within bingroup",
                groupName + ".",
                "Ignoring its bingroup:",
                bingroupIn,
                "setting."
              ].join(" "));
            }
            traceOut.bingroup = groupName;
            fillBinOpts(traceOut, groupName, orientation2binDir(traceOut));
          }
        }
        for (i = 0; i < otherTracesList.length; i++) {
          traceOut = otherTracesList[i];
          var binGroup = coerce("bingroup");
          if (traceIs(traceOut, "2dMap")) {
            for (k = 0; k < 2; k++) {
              binDir = BINDIRECTIONS[k];
              var binGroupInDir = coerce(
                binDir + "bingroup",
                binGroup ? binGroup + "__" + binDir : null
              );
              fillBinOpts(traceOut, binGroupInDir, binDir);
            }
          } else {
            fillBinOpts(traceOut, binGroup, orientation2binDir(traceOut));
          }
        }
        for (groupName in allBinOpts) {
          var binOpts = allBinOpts[groupName];
          traces = binOpts.traces;
          for (j = 0; j < BINATTRS.length; j++) {
            var attrSpec = BINATTRS[j];
            var attr = attrSpec.name;
            var aStr;
            var autoVals;
            if (attr === "nbins" && binOpts.sizeFound) continue;
            for (i = 0; i < traces.length; i++) {
              traceOut = traces[i];
              binDir = binOpts.dirs[i];
              aStr = attrSpec.aStr[binDir];
              if (nestedProperty(traceOut._input, aStr).get() !== void 0) {
                binOpts[attr] = coerce(aStr);
                binOpts[attr + "Found"] = true;
                break;
              }
              autoVals = (traceOut._autoBin || {})[binDir] || {};
              if (autoVals[attr]) {
                nestedProperty(traceOut, aStr).set(autoVals[attr]);
              }
            }
            if (attr === "start" || attr === "end") {
              for (; i < traces.length; i++) {
                traceOut = traces[i];
                if (traceOut["_" + binDir + "bingroup"]) {
                  autoVals = (traceOut._autoBin || {})[binDir] || {};
                  coerce(aStr, autoVals[attr]);
                }
              }
            }
            if (attr === "nbins" && !binOpts.sizeFound && !binOpts.nbinsFound) {
              traceOut = traces[0];
              binOpts[attr] = coerce(aStr);
            }
          }
        }
      };
    }
  });

  // src/traces/histogram/hover.js
  var require_hover6 = __commonJS({
    "src/traces/histogram/hover.js"(exports, module) {
      "use strict";
      var barHover = require_hover3().hoverPoints;
      var hoverLabelText = require_axes().hoverLabelText;
      module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
        var pts = barHover(pointData, xval, yval, hovermode, opts);
        if (!pts) return;
        pointData = pts[0];
        var di = pointData.cd[pointData.index];
        var trace = pointData.cd[0].trace;
        if (!trace.cumulative.enabled) {
          var posLetter = trace.orientation === "h" ? "y" : "x";
          pointData[posLetter + "Label"] = hoverLabelText(pointData[posLetter + "a"], [di.ph0, di.ph1], trace[posLetter + "hoverformat"]);
        }
        return pts;
      };
    }
  });

  // src/traces/histogram/event_data.js
  var require_event_data3 = __commonJS({
    "src/traces/histogram/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt, trace, cd, pointNumber) {
        out.x = "xVal" in pt ? pt.xVal : pt.x;
        out.y = "yVal" in pt ? pt.yVal : pt.y;
        if ("zLabelVal" in pt) out.z = pt.zLabelVal;
        if (pt.xa) out.xaxis = pt.xa;
        if (pt.ya) out.yaxis = pt.ya;
        if (!(trace.cumulative || {}).enabled) {
          var pts = Array.isArray(pointNumber) ? cd[0].pts[pointNumber[0]][pointNumber[1]] : cd[pointNumber].pts;
          out.pointNumbers = pts;
          out.binNumber = out.pointNumber;
          delete out.pointNumber;
          delete out.pointIndex;
          var pointIndices;
          if (trace._indexToPoints) {
            pointIndices = [];
            for (var i = 0; i < pts.length; i++) {
              pointIndices = pointIndices.concat(trace._indexToPoints[pts[i]]);
            }
          } else {
            pointIndices = pts;
          }
          out.pointIndices = pointIndices;
        }
        return out;
      };
    }
  });

  // src/traces/histogram/index.js
  var require_histogram = __commonJS({
    "src/traces/histogram/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes26(),
        layoutAttributes: require_layout_attributes6(),
        supplyDefaults: require_defaults22(),
        crossTraceDefaults: require_cross_trace_defaults3(),
        supplyLayoutDefaults: require_layout_defaults5(),
        calc: require_calc7().calc,
        crossTraceCalc: require_cross_trace_calc().crossTraceCalc,
        plot: require_plot3().plot,
        layerName: "barlayer",
        style: require_style4().style,
        styleOnSelect: require_style4().styleOnSelect,
        colorbar: require_marker_colorbar(),
        hoverPoints: require_hover6(),
        selectPoints: require_select3(),
        eventData: require_event_data3(),
        moduleType: "trace",
        name: "histogram",
        basePlotModule: require_cartesian(),
        categories: ["bar-like", "cartesian", "svg", "bar", "histogram", "oriented", "errorBarsOK", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/histogram.js
  var require_histogram2 = __commonJS({
    "lib/histogram.js"(exports, module) {
      "use strict";
      module.exports = require_histogram();
    }
  });

  // src/traces/histogram2d/attributes.js
  var require_attributes27 = __commonJS({
    "src/traces/histogram2d/attributes.js"(exports, module) {
      "use strict";
      var histogramAttrs = require_attributes26();
      var makeBinAttrs = require_bin_attributes();
      var heatmapAttrs = require_attributes25();
      var baseAttrs = require_attributes2();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorScaleAttrs = require_attributes8();
      var extendFlat = require_extend().extendFlat;
      module.exports = extendFlat(
        {
          x: histogramAttrs.x,
          y: histogramAttrs.y,
          z: {
            valType: "data_array",
            editType: "calc"
          },
          marker: {
            color: {
              valType: "data_array",
              editType: "calc"
            },
            editType: "calc"
          },
          histnorm: histogramAttrs.histnorm,
          histfunc: histogramAttrs.histfunc,
          nbinsx: histogramAttrs.nbinsx,
          xbins: makeBinAttrs("x"),
          nbinsy: histogramAttrs.nbinsy,
          ybins: makeBinAttrs("y"),
          autobinx: histogramAttrs.autobinx,
          autobiny: histogramAttrs.autobiny,
          bingroup: extendFlat({}, histogramAttrs.bingroup, {}),
          xbingroup: extendFlat({}, histogramAttrs.bingroup, {}),
          ybingroup: extendFlat({}, histogramAttrs.bingroup, {}),
          xgap: heatmapAttrs.xgap,
          ygap: heatmapAttrs.ygap,
          zsmooth: heatmapAttrs.zsmooth,
          xhoverformat: axisHoverFormat("x"),
          yhoverformat: axisHoverFormat("y"),
          zhoverformat: axisHoverFormat("z", 1),
          hovertemplate: hovertemplateAttrs({}, { keys: ["z"] }),
          hovertemplatefallback: templatefallbackAttrs(),
          texttemplate: texttemplateAttrs({ arrayOk: false, editType: "plot" }, { keys: ["z"] }),
          texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
          textfont: heatmapAttrs.textfont,
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
        },
        colorScaleAttrs("", { cLetter: "z", autoColorDflt: false })
      );
    }
  });

  // src/traces/histogram2d/sample_defaults.js
  var require_sample_defaults = __commonJS({
    "src/traces/histogram2d/sample_defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      module.exports = function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
        var x = coerce("x");
        var y = coerce("y");
        var xlen = Lib.minRowLength(x);
        var ylen = Lib.minRowLength(y);
        if (!xlen || !ylen) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = Math.min(xlen, ylen);
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout);
        var hasAggregationData = coerce("z") || coerce("marker.color");
        if (hasAggregationData) coerce("histfunc");
        coerce("histnorm");
        coerce("autobinx");
        coerce("autobiny");
      };
    }
  });

  // src/traces/histogram2d/defaults.js
  var require_defaults23 = __commonJS({
    "src/traces/histogram2d/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleSampleDefaults = require_sample_defaults();
      var handleStyleDefaults = require_style_defaults2();
      var colorscaleDefaults = require_defaults2();
      var handleHeatmapLabelDefaults = require_label_defaults();
      var attributes = require_attributes27();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        handleSampleDefaults(traceIn, traceOut, coerce, layout);
        if (traceOut.visible === false) return;
        handleStyleDefaults(traceIn, traceOut, coerce, layout);
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "z" });
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        handleHeatmapLabelDefaults(coerce, layout);
        coerce("xhoverformat");
        coerce("yhoverformat");
      };
    }
  });

  // src/traces/histogram2d/hover.js
  var require_hover7 = __commonJS({
    "src/traces/histogram2d/hover.js"(exports, module) {
      "use strict";
      var heatmapHover = require_hover5();
      var hoverLabelText = require_axes().hoverLabelText;
      module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
        var pts = heatmapHover(pointData, xval, yval, hovermode, opts);
        if (!pts) return;
        pointData = pts[0];
        var indices = pointData.index;
        var ny = indices[0];
        var nx = indices[1];
        var cd0 = pointData.cd[0];
        var trace = cd0.trace;
        var xRange = cd0.xRanges[nx];
        var yRange = cd0.yRanges[ny];
        pointData.xLabel = hoverLabelText(pointData.xa, [xRange[0], xRange[1]], trace.xhoverformat);
        pointData.yLabel = hoverLabelText(pointData.ya, [yRange[0], yRange[1]], trace.yhoverformat);
        return pts;
      };
    }
  });

  // src/traces/histogram2d/index.js
  var require_histogram2d = __commonJS({
    "src/traces/histogram2d/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes27(),
        supplyDefaults: require_defaults23(),
        crossTraceDefaults: require_cross_trace_defaults3(),
        calc: require_calc9(),
        plot: require_plot5(),
        layerName: "heatmaplayer",
        colorbar: require_colorbar2(),
        style: require_style6(),
        hoverPoints: require_hover7(),
        eventData: require_event_data3(),
        moduleType: "trace",
        name: "histogram2d",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "2dMap", "histogram", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/histogram2d.js
  var require_histogram2d2 = __commonJS({
    "lib/histogram2d.js"(exports, module) {
      "use strict";
      module.exports = require_histogram2d();
    }
  });

  // src/constants/filter_ops.js
  var require_filter_ops = __commonJS({
    "src/constants/filter_ops.js"(exports, module) {
      "use strict";
      module.exports = {
        COMPARISON_OPS: ["=", "!=", "<", ">=", ">", "<="],
        COMPARISON_OPS2: ["=", "<", ">=", ">", "<="],
        INTERVAL_OPS: ["[]", "()", "[)", "(]", "][", ")(", "](", ")["],
        SET_OPS: ["{}", "}{"],
        CONSTRAINT_REDUCTION: {
          // for contour constraints, open/closed endpoints are equivalent
          "=": "=",
          "<": "<",
          "<=": "<",
          ">": ">",
          ">=": ">",
          "[]": "[]",
          "()": "[]",
          "[)": "[]",
          "(]": "[]",
          "][": "][",
          ")(": "][",
          "](": "][",
          ")[": "]["
        }
      };
    }
  });

  // src/traces/contour/attributes.js
  var require_attributes28 = __commonJS({
    "src/traces/contour/attributes.js"(exports, module) {
      "use strict";
      var heatmapAttrs = require_attributes25();
      var scatterAttrs = require_attributes12();
      var axisFormat = require_axis_format_attributes();
      var axisHoverFormat = axisFormat.axisHoverFormat;
      var descriptionOnlyNumbers = axisFormat.descriptionOnlyNumbers;
      var colorScaleAttrs = require_attributes8();
      var dash = require_attributes4().dash;
      var fontAttrs = require_font_attributes();
      var extendFlat = require_extend().extendFlat;
      var filterOps = require_filter_ops();
      var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
      var INTERVAL_OPS = filterOps.INTERVAL_OPS;
      var scatterLineAttrs = scatterAttrs.line;
      module.exports = extendFlat(
        {
          z: heatmapAttrs.z,
          x: heatmapAttrs.x,
          x0: heatmapAttrs.x0,
          dx: heatmapAttrs.dx,
          y: heatmapAttrs.y,
          y0: heatmapAttrs.y0,
          dy: heatmapAttrs.dy,
          xperiod: heatmapAttrs.xperiod,
          yperiod: heatmapAttrs.yperiod,
          xperiod0: scatterAttrs.xperiod0,
          yperiod0: scatterAttrs.yperiod0,
          xperiodalignment: heatmapAttrs.xperiodalignment,
          yperiodalignment: heatmapAttrs.yperiodalignment,
          text: heatmapAttrs.text,
          hovertext: heatmapAttrs.hovertext,
          transpose: heatmapAttrs.transpose,
          xtype: heatmapAttrs.xtype,
          ytype: heatmapAttrs.ytype,
          xhoverformat: axisHoverFormat("x"),
          yhoverformat: axisHoverFormat("y"),
          zhoverformat: axisHoverFormat("z", 1),
          hovertemplate: heatmapAttrs.hovertemplate,
          hovertemplatefallback: heatmapAttrs.hovertemplatefallback,
          texttemplate: extendFlat({}, heatmapAttrs.texttemplate, {}),
          texttemplatefallback: heatmapAttrs.texttemplatefallback,
          textfont: extendFlat({}, heatmapAttrs.textfont, {}),
          hoverongaps: heatmapAttrs.hoverongaps,
          connectgaps: extendFlat({}, heatmapAttrs.connectgaps, {}),
          fillcolor: {
            valType: "color",
            editType: "calc"
          },
          autocontour: {
            valType: "boolean",
            dflt: true,
            editType: "calc",
            impliedEdits: {
              "contours.start": void 0,
              "contours.end": void 0,
              "contours.size": void 0
            }
          },
          ncontours: {
            valType: "integer",
            dflt: 15,
            min: 1,
            editType: "calc"
          },
          contours: {
            type: {
              valType: "enumerated",
              values: ["levels", "constraint"],
              dflt: "levels",
              editType: "calc"
            },
            start: {
              valType: "number",
              dflt: null,
              editType: "plot",
              impliedEdits: { "^autocontour": false }
            },
            end: {
              valType: "number",
              dflt: null,
              editType: "plot",
              impliedEdits: { "^autocontour": false }
            },
            size: {
              valType: "number",
              dflt: null,
              min: 0,
              editType: "plot",
              impliedEdits: { "^autocontour": false }
            },
            coloring: {
              valType: "enumerated",
              values: ["fill", "heatmap", "lines", "none"],
              dflt: "fill",
              editType: "calc"
            },
            showlines: {
              valType: "boolean",
              dflt: true,
              editType: "plot"
            },
            showlabels: {
              valType: "boolean",
              dflt: false,
              editType: "plot"
            },
            labelfont: fontAttrs({
              editType: "plot",
              colorEditType: "style"
            }),
            labelformat: {
              valType: "string",
              dflt: "",
              editType: "plot",
              description: descriptionOnlyNumbers("contour label")
            },
            operation: {
              valType: "enumerated",
              values: [].concat(COMPARISON_OPS2).concat(INTERVAL_OPS),
              dflt: "=",
              editType: "calc"
            },
            value: {
              valType: "any",
              dflt: 0,
              editType: "calc"
            },
            editType: "calc",
            impliedEdits: { autocontour: false }
          },
          line: {
            color: extendFlat({}, scatterLineAttrs.color, {
              editType: "style+colorbars"
            }),
            width: {
              valType: "number",
              min: 0,
              editType: "style+colorbars"
            },
            dash,
            smoothing: extendFlat({}, scatterLineAttrs.smoothing, {}),
            editType: "plot"
          },
          zorder: scatterAttrs.zorder
        },
        colorScaleAttrs("", {
          cLetter: "z",
          autoColorDflt: false,
          editTypeOverride: "calc"
        })
      );
    }
  });

  // src/traces/histogram2dcontour/attributes.js
  var require_attributes29 = __commonJS({
    "src/traces/histogram2dcontour/attributes.js"(exports, module) {
      "use strict";
      var histogram2dAttrs = require_attributes27();
      var contourAttrs = require_attributes28();
      var colorScaleAttrs = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var extendFlat = require_extend().extendFlat;
      module.exports = extendFlat(
        {
          x: histogram2dAttrs.x,
          y: histogram2dAttrs.y,
          z: histogram2dAttrs.z,
          marker: histogram2dAttrs.marker,
          histnorm: histogram2dAttrs.histnorm,
          histfunc: histogram2dAttrs.histfunc,
          nbinsx: histogram2dAttrs.nbinsx,
          xbins: histogram2dAttrs.xbins,
          nbinsy: histogram2dAttrs.nbinsy,
          ybins: histogram2dAttrs.ybins,
          autobinx: histogram2dAttrs.autobinx,
          autobiny: histogram2dAttrs.autobiny,
          bingroup: histogram2dAttrs.bingroup,
          xbingroup: histogram2dAttrs.xbingroup,
          ybingroup: histogram2dAttrs.ybingroup,
          autocontour: contourAttrs.autocontour,
          ncontours: contourAttrs.ncontours,
          contours: contourAttrs.contours,
          line: {
            color: contourAttrs.line.color,
            width: extendFlat({}, contourAttrs.line.width, {
              dflt: 0.5
            }),
            dash: contourAttrs.line.dash,
            smoothing: contourAttrs.line.smoothing,
            editType: "plot"
          },
          xhoverformat: axisHoverFormat("x"),
          yhoverformat: axisHoverFormat("y"),
          zhoverformat: axisHoverFormat("z", 1),
          hovertemplate: histogram2dAttrs.hovertemplate,
          hovertemplatefallback: histogram2dAttrs.hovertemplatefallback,
          texttemplate: contourAttrs.texttemplate,
          texttemplatefallback: contourAttrs.texttemplatefallback,
          textfont: contourAttrs.textfont
        },
        colorScaleAttrs("", {
          cLetter: "z",
          editTypeOverride: "calc"
        })
      );
    }
  });

  // src/traces/contour/contours_defaults.js
  var require_contours_defaults = __commonJS({
    "src/traces/contour/contours_defaults.js"(exports, module) {
      "use strict";
      module.exports = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) {
        var contourStart = coerce2("contours.start");
        var contourEnd = coerce2("contours.end");
        var missingEnd = contourStart === false || contourEnd === false;
        var contourSize = coerce("contours.size");
        var autoContour;
        if (missingEnd) autoContour = traceOut.autocontour = true;
        else autoContour = coerce("autocontour", false);
        if (autoContour || !contourSize) coerce("ncontours");
      };
    }
  });

  // src/traces/contour/label_defaults.js
  var require_label_defaults2 = __commonJS({
    "src/traces/contour/label_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function handleLabelDefaults(coerce, layout, lineColor, opts) {
        if (!opts) opts = {};
        var showLabels = coerce("contours.showlabels");
        if (showLabels) {
          var globalFont = layout.font;
          Lib.coerceFont(coerce, "contours.labelfont", globalFont, { overrideDflt: {
            color: lineColor
          } });
          coerce("contours.labelformat");
        }
        if (opts.hasHover !== false) coerce("zhoverformat");
      };
    }
  });

  // src/traces/contour/style_defaults.js
  var require_style_defaults3 = __commonJS({
    "src/traces/contour/style_defaults.js"(exports, module) {
      "use strict";
      var colorscaleDefaults = require_defaults2();
      var handleLabelDefaults = require_label_defaults2();
      module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) {
        var coloring = coerce("contours.coloring");
        var showLines;
        var lineColor = "";
        if (coloring === "fill") showLines = coerce("contours.showlines");
        if (showLines !== false) {
          if (coloring !== "lines") lineColor = coerce("line.color", "#000");
          coerce("line.width", 0.5);
          coerce("line.dash");
        }
        if (coloring !== "none") {
          if (traceIn.showlegend !== true) traceOut.showlegend = false;
          traceOut._dfltShowLegend = false;
          colorscaleDefaults(
            traceIn,
            traceOut,
            layout,
            coerce,
            { prefix: "", cLetter: "z" }
          );
        }
        coerce("line.smoothing");
        handleLabelDefaults(coerce, layout, lineColor, opts);
      };
    }
  });

  // src/traces/histogram2dcontour/defaults.js
  var require_defaults24 = __commonJS({
    "src/traces/histogram2dcontour/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleSampleDefaults = require_sample_defaults();
      var handleContoursDefaults = require_contours_defaults();
      var handleStyleDefaults = require_style_defaults3();
      var handleHeatmapLabelDefaults = require_label_defaults();
      var attributes = require_attributes29();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        function coerce2(attr) {
          return Lib.coerce2(traceIn, traceOut, attributes, attr);
        }
        handleSampleDefaults(traceIn, traceOut, coerce, layout);
        if (traceOut.visible === false) return;
        handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
        handleStyleDefaults(traceIn, traceOut, coerce, layout);
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        if (traceOut.contours && traceOut.contours.coloring === "heatmap") {
          handleHeatmapLabelDefaults(coerce, layout);
        }
      };
    }
  });

  // src/traces/contour/set_contours.js
  var require_set_contours = __commonJS({
    "src/traces/contour/set_contours.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var Lib = require_lib();
      module.exports = function setContours(trace, vals) {
        var contours = trace.contours;
        if (trace.autocontour) {
          var zmin = trace.zmin;
          var zmax = trace.zmax;
          if (trace.zauto || zmin === void 0) {
            zmin = Lib.aggNums(Math.min, null, vals);
          }
          if (trace.zauto || zmax === void 0) {
            zmax = Lib.aggNums(Math.max, null, vals);
          }
          var dummyAx = autoContours(zmin, zmax, trace.ncontours);
          contours.size = dummyAx.dtick;
          contours.start = Axes.tickFirst(dummyAx);
          dummyAx.range.reverse();
          contours.end = Axes.tickFirst(dummyAx);
          if (contours.start === zmin) contours.start += contours.size;
          if (contours.end === zmax) contours.end -= contours.size;
          if (contours.start > contours.end) {
            contours.start = contours.end = (contours.start + contours.end) / 2;
          }
          if (!trace._input.contours) trace._input.contours = {};
          Lib.extendFlat(trace._input.contours, {
            start: contours.start,
            end: contours.end,
            size: contours.size
          });
          trace._input.autocontour = true;
        } else if (contours.type !== "constraint") {
          var start = contours.start;
          var end = contours.end;
          var inputContours = trace._input.contours;
          if (start > end) {
            contours.start = inputContours.start = end;
            end = contours.end = inputContours.end = start;
            start = contours.start;
          }
          if (!(contours.size > 0)) {
            var sizeOut;
            if (start === end) sizeOut = 1;
            else sizeOut = autoContours(start, end, trace.ncontours).dtick;
            inputContours.size = contours.size = sizeOut;
          }
        }
      };
      function autoContours(start, end, ncontours) {
        var dummyAx = {
          type: "linear",
          range: [start, end]
        };
        Axes.autoTicks(
          dummyAx,
          (end - start) / (ncontours || 15)
        );
        return dummyAx;
      }
    }
  });

  // src/traces/contour/end_plus.js
  var require_end_plus = __commonJS({
    "src/traces/contour/end_plus.js"(exports, module) {
      "use strict";
      module.exports = function endPlus(contours) {
        return contours.end + contours.size / 1e6;
      };
    }
  });

  // src/traces/contour/calc.js
  var require_calc10 = __commonJS({
    "src/traces/contour/calc.js"(exports, module) {
      "use strict";
      var Colorscale = require_colorscale();
      var heatmapCalc = require_calc9();
      var setContours = require_set_contours();
      var endPlus = require_end_plus();
      module.exports = function calc(gd, trace) {
        var cd = heatmapCalc(gd, trace);
        var zOut = cd[0].z;
        setContours(trace, zOut);
        var contours = trace.contours;
        var cOpts = Colorscale.extractOpts(trace);
        var cVals;
        if (contours.coloring === "heatmap" && cOpts.auto && trace.autocontour === false) {
          var start = contours.start;
          var end = endPlus(contours);
          var cs = contours.size || 1;
          var nc = Math.floor((end - start) / cs) + 1;
          if (!isFinite(cs)) {
            cs = 1;
            nc = 1;
          }
          var min0 = start - cs / 2;
          var max0 = min0 + nc * cs;
          cVals = [min0, max0];
        } else {
          cVals = zOut;
        }
        Colorscale.calc(gd, trace, { vals: cVals, cLetter: "z" });
        return cd;
      };
    }
  });

  // src/traces/contour/constants.js
  var require_constants16 = __commonJS({
    "src/traces/contour/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // some constants to help with marching squares algorithm
        // where does the path start for each index?
        BOTTOMSTART: [1, 9, 13, 104, 713],
        TOPSTART: [4, 6, 7, 104, 713],
        LEFTSTART: [8, 12, 14, 208, 1114],
        RIGHTSTART: [2, 3, 11, 208, 1114],
        // which way [dx,dy] do we leave a given index?
        // saddles are already disambiguated
        NEWDELTA: [
          null,
          [-1, 0],
          [0, -1],
          [-1, 0],
          [1, 0],
          null,
          [0, -1],
          [-1, 0],
          [0, 1],
          [0, 1],
          null,
          [0, 1],
          [1, 0],
          [1, 0],
          [0, -1]
        ],
        // for each saddle, the first index here is used
        // for dx||dy<0, the second for dx||dy>0
        CHOOSESADDLE: {
          104: [4, 1],
          208: [2, 8],
          713: [7, 13],
          1114: [11, 14]
        },
        // after one index has been used for a saddle, which do we
        // substitute to be used up later?
        SADDLEREMAINDER: { 1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11 },
        // length of a contour, as a multiple of the plot area diagonal, per label
        LABELDISTANCE: 2,
        // number of contour levels after which we start increasing the number of
        // labels we draw. Many contours means they will generally be close
        // together, so it will be harder to follow a long way to find a label
        LABELINCREASE: 10,
        // minimum length of a contour line, as a multiple of the label length,
        // at which we draw *any* labels
        LABELMIN: 3,
        // max number of labels to draw on a single contour path, no matter how long
        LABELMAX: 10,
        // constants for the label position cost function
        LABELOPTIMIZER: {
          // weight given to edge proximity
          EDGECOST: 1,
          // weight given to the angle off horizontal
          ANGLECOST: 1,
          // weight given to distance from already-placed labels
          NEIGHBORCOST: 5,
          // cost multiplier for labels on the same level
          SAMELEVELFACTOR: 10,
          // minimum distance (as a multiple of the label length)
          // for labels on the same level
          SAMELEVELDISTANCE: 5,
          // maximum cost before we won't even place the label
          MAXCOST: 100,
          // number of evenly spaced points to look at in the first
          // iteration of the search
          INITIALSEARCHPOINTS: 10,
          // number of binary search iterations after the initial wide search
          ITERATIONS: 5
        }
      };
    }
  });

  // src/traces/contour/make_crossings.js
  var require_make_crossings = __commonJS({
    "src/traces/contour/make_crossings.js"(exports, module) {
      "use strict";
      var constants = require_constants16();
      module.exports = function makeCrossings(pathinfo) {
        var z = pathinfo[0].z;
        var m = z.length;
        var n = z[0].length;
        var twoWide = m === 2 || n === 2;
        var xi;
        var yi;
        var startIndices;
        var ystartIndices;
        var label;
        var corners;
        var mi;
        var pi;
        var i;
        for (yi = 0; yi < m - 1; yi++) {
          ystartIndices = [];
          if (yi === 0) ystartIndices = ystartIndices.concat(constants.BOTTOMSTART);
          if (yi === m - 2) ystartIndices = ystartIndices.concat(constants.TOPSTART);
          for (xi = 0; xi < n - 1; xi++) {
            startIndices = ystartIndices.slice();
            if (xi === 0) startIndices = startIndices.concat(constants.LEFTSTART);
            if (xi === n - 2) startIndices = startIndices.concat(constants.RIGHTSTART);
            label = xi + "," + yi;
            corners = [
              [z[yi][xi], z[yi][xi + 1]],
              [z[yi + 1][xi], z[yi + 1][xi + 1]]
            ];
            for (i = 0; i < pathinfo.length; i++) {
              pi = pathinfo[i];
              mi = getMarchingIndex(pi.level, corners);
              if (!mi) continue;
              pi.crossings[label] = mi;
              if (startIndices.indexOf(mi) !== -1) {
                pi.starts.push([xi, yi]);
                if (twoWide && startIndices.indexOf(
                  mi,
                  startIndices.indexOf(mi) + 1
                ) !== -1) {
                  pi.starts.push([xi, yi]);
                }
              }
            }
          }
        }
      };
      function getMarchingIndex(val, corners) {
        var mi = (corners[0][0] > val ? 0 : 1) + (corners[0][1] > val ? 0 : 2) + (corners[1][1] > val ? 0 : 4) + (corners[1][0] > val ? 0 : 8);
        if (mi === 5 || mi === 10) {
          var avg = (corners[0][0] + corners[0][1] + corners[1][0] + corners[1][1]) / 4;
          if (val > avg) return mi === 5 ? 713 : 1114;
          return mi === 5 ? 104 : 208;
        }
        return mi === 15 ? 0 : mi;
      }
    }
  });

  // src/traces/contour/find_all_paths.js
  var require_find_all_paths = __commonJS({
    "src/traces/contour/find_all_paths.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var constants = require_constants16();
      module.exports = function findAllPaths(pathinfo, xtol, ytol) {
        var cnt, startLoc, i, pi, j;
        xtol = xtol || 0.01;
        ytol = ytol || 0.01;
        for (i = 0; i < pathinfo.length; i++) {
          pi = pathinfo[i];
          for (j = 0; j < pi.starts.length; j++) {
            startLoc = pi.starts[j];
            makePath(pi, startLoc, "edge", xtol, ytol);
          }
          cnt = 0;
          while (Object.keys(pi.crossings).length && cnt < 1e4) {
            cnt++;
            startLoc = Object.keys(pi.crossings)[0].split(",").map(Number);
            makePath(pi, startLoc, void 0, xtol, ytol);
          }
          if (cnt === 1e4) Lib.log("Infinite loop in contour?");
        }
      };
      function equalPts(pt1, pt2, xtol, ytol) {
        return Math.abs(pt1[0] - pt2[0]) < xtol && Math.abs(pt1[1] - pt2[1]) < ytol;
      }
      function ptDist(pt1, pt2) {
        var dx = pt1[2] - pt2[2];
        var dy = pt1[3] - pt2[3];
        return Math.sqrt(dx * dx + dy * dy);
      }
      function makePath(pi, loc, edgeflag, xtol, ytol) {
        var locStr = loc.join(",");
        var mi = pi.crossings[locStr];
        var marchStep = getStartStep(mi, edgeflag, loc);
        var pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])];
        var m = pi.z.length;
        var n = pi.z[0].length;
        var startLoc = loc.slice();
        var startStep = marchStep.slice();
        var cnt;
        for (cnt = 0; cnt < 1e4; cnt++) {
          if (mi > 20) {
            mi = constants.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1];
            pi.crossings[locStr] = constants.SADDLEREMAINDER[mi];
          } else {
            delete pi.crossings[locStr];
          }
          marchStep = constants.NEWDELTA[mi];
          if (!marchStep) {
            Lib.log("Found bad marching index:", mi, loc, pi.level);
            break;
          }
          pts.push(getInterpPx(pi, loc, marchStep));
          loc[0] += marchStep[0];
          loc[1] += marchStep[1];
          locStr = loc.join(",");
          if (equalPts(pts[pts.length - 1], pts[pts.length - 2], xtol, ytol)) pts.pop();
          var atEdge = marchStep[0] && (loc[0] < 0 || loc[0] > n - 2) || marchStep[1] && (loc[1] < 0 || loc[1] > m - 2);
          var closedLoop = loc[0] === startLoc[0] && loc[1] === startLoc[1] && marchStep[0] === startStep[0] && marchStep[1] === startStep[1];
          if (closedLoop || edgeflag && atEdge) break;
          mi = pi.crossings[locStr];
        }
        if (cnt === 1e4) {
          Lib.log("Infinite loop in contour?");
        }
        var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol);
        var totaldist = 0;
        var distThresholdFactor = 0.2 * pi.smoothing;
        var alldists = [];
        var cropstart = 0;
        var distgroup, cnt2, cnt3, newpt, ptcnt, ptavg, thisdist, i, j, edgepathi, edgepathj;
        for (cnt = 1; cnt < pts.length; cnt++) {
          thisdist = ptDist(pts[cnt], pts[cnt - 1]);
          totaldist += thisdist;
          alldists.push(thisdist);
        }
        var distThreshold = totaldist / alldists.length * distThresholdFactor;
        function getpt(i2) {
          return pts[i2 % pts.length];
        }
        for (cnt = pts.length - 2; cnt >= cropstart; cnt--) {
          distgroup = alldists[cnt];
          if (distgroup < distThreshold) {
            cnt3 = 0;
            for (cnt2 = cnt - 1; cnt2 >= cropstart; cnt2--) {
              if (distgroup + alldists[cnt2] < distThreshold) {
                distgroup += alldists[cnt2];
              } else break;
            }
            if (closedpath && cnt === pts.length - 2) {
              for (cnt3 = 0; cnt3 < cnt2; cnt3++) {
                if (distgroup + alldists[cnt3] < distThreshold) {
                  distgroup += alldists[cnt3];
                } else break;
              }
            }
            ptcnt = cnt - cnt2 + cnt3 + 1;
            ptavg = Math.floor((cnt + cnt2 + cnt3 + 2) / 2);
            if (!closedpath && cnt === pts.length - 2) newpt = pts[pts.length - 1];
            else if (!closedpath && cnt2 === -1) newpt = pts[0];
            else if (ptcnt % 2) newpt = getpt(ptavg);
            else {
              newpt = [
                (getpt(ptavg)[0] + getpt(ptavg + 1)[0]) / 2,
                (getpt(ptavg)[1] + getpt(ptavg + 1)[1]) / 2
              ];
            }
            pts.splice(cnt2 + 1, cnt - cnt2 + 1, newpt);
            cnt = cnt2 + 1;
            if (cnt3) cropstart = cnt3;
            if (closedpath) {
              if (cnt === pts.length - 2) pts[cnt3] = pts[pts.length - 1];
              else if (cnt === 0) pts[pts.length - 1] = pts[0];
            }
          }
        }
        pts.splice(0, cropstart);
        for (cnt = 0; cnt < pts.length; cnt++) pts[cnt].length = 2;
        if (pts.length < 2) return;
        else if (closedpath) {
          pts.pop();
          pi.paths.push(pts);
        } else {
          if (!edgeflag) {
            Lib.log(
              "Unclosed interior contour?",
              pi.level,
              startLoc.join(","),
              pts.join("L")
            );
          }
          var merged = false;
          for (i = 0; i < pi.edgepaths.length; i++) {
            edgepathi = pi.edgepaths[i];
            if (!merged && equalPts(edgepathi[0], pts[pts.length - 1], xtol, ytol)) {
              pts.pop();
              merged = true;
              var doublemerged = false;
              for (j = 0; j < pi.edgepaths.length; j++) {
                edgepathj = pi.edgepaths[j];
                if (equalPts(edgepathj[edgepathj.length - 1], pts[0], xtol, ytol)) {
                  doublemerged = true;
                  pts.shift();
                  pi.edgepaths.splice(i, 1);
                  if (j === i) {
                    pi.paths.push(pts.concat(edgepathj));
                  } else {
                    if (j > i) j--;
                    pi.edgepaths[j] = edgepathj.concat(pts, edgepathi);
                  }
                  break;
                }
              }
              if (!doublemerged) {
                pi.edgepaths[i] = pts.concat(edgepathi);
              }
            }
          }
          for (i = 0; i < pi.edgepaths.length; i++) {
            if (merged) break;
            edgepathi = pi.edgepaths[i];
            if (equalPts(edgepathi[edgepathi.length - 1], pts[0], xtol, ytol)) {
              pts.shift();
              pi.edgepaths[i] = edgepathi.concat(pts);
              merged = true;
            }
          }
          if (!merged) pi.edgepaths.push(pts);
        }
      }
      function getStartStep(mi, edgeflag, loc) {
        var dx = 0;
        var dy = 0;
        if (mi > 20 && edgeflag) {
          if (mi === 208 || mi === 1114) {
            dx = loc[0] === 0 ? 1 : -1;
          } else {
            dy = loc[1] === 0 ? 1 : -1;
          }
        } else if (constants.BOTTOMSTART.indexOf(mi) !== -1) dy = 1;
        else if (constants.LEFTSTART.indexOf(mi) !== -1) dx = 1;
        else if (constants.TOPSTART.indexOf(mi) !== -1) dy = -1;
        else dx = -1;
        return [dx, dy];
      }
      function getInterpPx(pi, loc, step) {
        var locx = loc[0] + Math.max(step[0], 0);
        var locy = loc[1] + Math.max(step[1], 0);
        var zxy = pi.z[locy][locx];
        var xa = pi.xaxis;
        var ya = pi.yaxis;
        if (step[1]) {
          var dx = (pi.level - zxy) / (pi.z[locy][locx + 1] - zxy);
          var dxl = (dx !== 1 ? (1 - dx) * xa.c2l(pi.x[locx]) : 0) + (dx !== 0 ? dx * xa.c2l(pi.x[locx + 1]) : 0);
          return [
            xa.c2p(xa.l2c(dxl), true),
            ya.c2p(pi.y[locy], true),
            locx + dx,
            locy
          ];
        } else {
          var dy = (pi.level - zxy) / (pi.z[locy + 1][locx] - zxy);
          var dyl = (dy !== 1 ? (1 - dy) * ya.c2l(pi.y[locy]) : 0) + (dy !== 0 ? dy * ya.c2l(pi.y[locy + 1]) : 0);
          return [
            xa.c2p(pi.x[locx], true),
            ya.c2p(ya.l2c(dyl), true),
            locx,
            locy + dy
          ];
        }
      }
    }
  });

  // src/traces/contour/constraint_mapping.js
  var require_constraint_mapping = __commonJS({
    "src/traces/contour/constraint_mapping.js"(exports, module) {
      "use strict";
      var filterOps = require_filter_ops();
      var isNumeric = require_fast_isnumeric();
      module.exports = {
        "[]": makeRangeSettings("[]"),
        "][": makeRangeSettings("]["),
        ">": makeInequalitySettings(">"),
        "<": makeInequalitySettings("<"),
        "=": makeInequalitySettings("=")
      };
      function coerceValue(operation, value) {
        var hasArrayValue = Array.isArray(value);
        var coercedValue;
        function coerce(value2) {
          return isNumeric(value2) ? +value2 : null;
        }
        if (filterOps.COMPARISON_OPS2.indexOf(operation) !== -1) {
          coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value);
        } else if (filterOps.INTERVAL_OPS.indexOf(operation) !== -1) {
          coercedValue = hasArrayValue ? [coerce(value[0]), coerce(value[1])] : [coerce(value), coerce(value)];
        } else if (filterOps.SET_OPS.indexOf(operation) !== -1) {
          coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)];
        }
        return coercedValue;
      }
      function makeRangeSettings(operation) {
        return function(value) {
          value = coerceValue(operation, value);
          var min = Math.min(value[0], value[1]);
          var max = Math.max(value[0], value[1]);
          return {
            start: min,
            end: max,
            size: max - min
          };
        };
      }
      function makeInequalitySettings(operation) {
        return function(value) {
          value = coerceValue(operation, value);
          return {
            start: value,
            end: Infinity,
            size: Infinity
          };
        };
      }
    }
  });

  // src/traces/contour/empty_pathinfo.js
  var require_empty_pathinfo = __commonJS({
    "src/traces/contour/empty_pathinfo.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var constraintMapping = require_constraint_mapping();
      var endPlus = require_end_plus();
      module.exports = function emptyPathinfo(contours, plotinfo, cd0) {
        var contoursFinal = contours.type === "constraint" ? constraintMapping[contours._operation](contours.value) : contours;
        var cs = contoursFinal.size;
        var pathinfo = [];
        var end = endPlus(contoursFinal);
        var carpet = cd0.trace._carpetTrace;
        var basePathinfo = carpet ? {
          // store axes so we can convert to px
          xaxis: carpet.aaxis,
          yaxis: carpet.baxis,
          // full data arrays to use for interpolation
          x: cd0.a,
          y: cd0.b
        } : {
          xaxis: plotinfo.xaxis,
          yaxis: plotinfo.yaxis,
          x: cd0.x,
          y: cd0.y
        };
        for (var ci = contoursFinal.start; ci < end; ci += cs) {
          pathinfo.push(Lib.extendFlat({
            level: ci,
            // all the cells with nontrivial marching index
            crossings: {},
            // starting points on the edges of the lattice for each contour
            starts: [],
            // all unclosed paths (may have less items than starts,
            // if a path is closed by rounding)
            edgepaths: [],
            // all closed paths
            paths: [],
            z: cd0.z,
            smoothing: cd0.trace.line.smoothing
          }, basePathinfo));
          if (pathinfo.length > 1e3) {
            Lib.warn("Too many contours, clipping at 1000", contours);
            break;
          }
        }
        return pathinfo;
      };
    }
  });

  // src/traces/contour/convert_to_constraints.js
  var require_convert_to_constraints = __commonJS({
    "src/traces/contour/convert_to_constraints.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function(pathinfo, operation) {
        var i, pi0, pi1;
        var op0 = function(arr) {
          return arr.reverse();
        };
        var op1 = function(arr) {
          return arr;
        };
        switch (operation) {
          case "=":
          case "<":
            return pathinfo;
          case ">":
            if (pathinfo.length !== 1) {
              Lib.warn("Contour data invalid for the specified inequality operation.");
            }
            pi0 = pathinfo[0];
            for (i = 0; i < pi0.edgepaths.length; i++) {
              pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
            }
            for (i = 0; i < pi0.paths.length; i++) {
              pi0.paths[i] = op0(pi0.paths[i]);
            }
            for (i = 0; i < pi0.starts.length; i++) {
              pi0.starts[i] = op0(pi0.starts[i]);
            }
            return pathinfo;
          case "][":
            var tmp = op0;
            op0 = op1;
            op1 = tmp;
          // It's a nice rule, except this definitely *is* what's intended here.
          /* eslint-disable: no-fallthrough */
          case "[]":
            if (pathinfo.length !== 2) {
              Lib.warn("Contour data invalid for the specified inequality range operation.");
            }
            pi0 = copyPathinfo(pathinfo[0]);
            pi1 = copyPathinfo(pathinfo[1]);
            for (i = 0; i < pi0.edgepaths.length; i++) {
              pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
            }
            for (i = 0; i < pi0.paths.length; i++) {
              pi0.paths[i] = op0(pi0.paths[i]);
            }
            for (i = 0; i < pi0.starts.length; i++) {
              pi0.starts[i] = op0(pi0.starts[i]);
            }
            while (pi1.edgepaths.length) {
              pi0.edgepaths.push(op1(pi1.edgepaths.shift()));
            }
            while (pi1.paths.length) {
              pi0.paths.push(op1(pi1.paths.shift()));
            }
            while (pi1.starts.length) {
              pi0.starts.push(op1(pi1.starts.shift()));
            }
            return [pi0];
        }
      };
      function copyPathinfo(pi) {
        return Lib.extendFlat({}, pi, {
          edgepaths: Lib.extendDeep([], pi.edgepaths),
          paths: Lib.extendDeep([], pi.paths),
          starts: Lib.extendDeep([], pi.starts)
        });
      }
    }
  });

  // src/traces/contour/close_boundaries.js
  var require_close_boundaries = __commonJS({
    "src/traces/contour/close_boundaries.js"(exports, module) {
      "use strict";
      module.exports = function(pathinfo, contours) {
        var pi0 = pathinfo[0];
        var z = pi0.z;
        var i;
        switch (contours.type) {
          case "levels":
            var edgeVal2 = Math.min(z[0][0], z[0][1]);
            for (i = 0; i < pathinfo.length; i++) {
              var pi = pathinfo[i];
              pi.prefixBoundary = !pi.edgepaths.length && (edgeVal2 > pi.level || pi.starts.length && edgeVal2 === pi.level);
            }
            break;
          case "constraint":
            pi0.prefixBoundary = false;
            if (pi0.edgepaths.length) return;
            var na = pi0.x.length;
            var nb = pi0.y.length;
            var boundaryMax = -Infinity;
            var boundaryMin = Infinity;
            for (i = 0; i < nb; i++) {
              boundaryMin = Math.min(boundaryMin, z[i][0]);
              boundaryMin = Math.min(boundaryMin, z[i][na - 1]);
              boundaryMax = Math.max(boundaryMax, z[i][0]);
              boundaryMax = Math.max(boundaryMax, z[i][na - 1]);
            }
            for (i = 1; i < na - 1; i++) {
              boundaryMin = Math.min(boundaryMin, z[0][i]);
              boundaryMin = Math.min(boundaryMin, z[nb - 1][i]);
              boundaryMax = Math.max(boundaryMax, z[0][i]);
              boundaryMax = Math.max(boundaryMax, z[nb - 1][i]);
            }
            var contoursValue = contours.value;
            var v1, v2;
            switch (contours._operation) {
              case ">":
                if (contoursValue > boundaryMax) {
                  pi0.prefixBoundary = true;
                }
                break;
              case "<":
                if (contoursValue < boundaryMin || pi0.starts.length && contoursValue === boundaryMin) {
                  pi0.prefixBoundary = true;
                }
                break;
              case "[]":
                v1 = Math.min(contoursValue[0], contoursValue[1]);
                v2 = Math.max(contoursValue[0], contoursValue[1]);
                if (v2 < boundaryMin || v1 > boundaryMax || pi0.starts.length && v2 === boundaryMin) {
                  pi0.prefixBoundary = true;
                }
                break;
              case "][":
                v1 = Math.min(contoursValue[0], contoursValue[1]);
                v2 = Math.max(contoursValue[0], contoursValue[1]);
                if (v1 < boundaryMin && v2 > boundaryMax) {
                  pi0.prefixBoundary = true;
                }
                break;
            }
            break;
        }
      };
    }
  });

  // src/traces/contour/plot.js
  var require_plot6 = __commonJS({
    "src/traces/contour/plot.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var Colorscale = require_colorscale();
      var svgTextUtils = require_svg_text_utils();
      var Axes = require_axes();
      var setConvert = require_set_convert();
      var heatmapPlot = require_plot5();
      var makeCrossings = require_make_crossings();
      var findAllPaths = require_find_all_paths();
      var emptyPathinfo = require_empty_pathinfo();
      var convertToConstraints = require_convert_to_constraints();
      var closeBoundaries = require_close_boundaries();
      var constants = require_constants16();
      var costConstants = constants.LABELOPTIMIZER;
      exports.plot = function plot(gd, plotinfo, cdcontours, contourLayer) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        Lib.makeTraceGroups(contourLayer, cdcontours, "contour").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          var x = cd0.x;
          var y = cd0.y;
          var contours = trace.contours;
          var pathinfo = emptyPathinfo(contours, plotinfo, cd0);
          var heatmapColoringLayer = Lib.ensureSingle(plotGroup, "g", "heatmapcoloring");
          var cdheatmaps = [];
          if (contours.coloring === "heatmap") {
            cdheatmaps = [cd];
          }
          heatmapPlot(gd, plotinfo, cdheatmaps, heatmapColoringLayer);
          makeCrossings(pathinfo);
          findAllPaths(pathinfo);
          var leftedge = xa.c2p(x[0], true);
          var rightedge = xa.c2p(x[x.length - 1], true);
          var bottomedge = ya.c2p(y[0], true);
          var topedge = ya.c2p(y[y.length - 1], true);
          var perimeter = [
            [leftedge, topedge],
            [rightedge, topedge],
            [rightedge, bottomedge],
            [leftedge, bottomedge]
          ];
          var fillPathinfo = pathinfo;
          if (contours.type === "constraint") {
            fillPathinfo = convertToConstraints(pathinfo, contours._operation);
          }
          makeBackground(plotGroup, perimeter, contours);
          makeFills(plotGroup, fillPathinfo, perimeter, contours);
          makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours);
          clipGaps(plotGroup, plotinfo, gd, cd0, perimeter);
        });
      };
      function makeBackground(plotgroup, perimeter, contours) {
        var bggroup = Lib.ensureSingle(plotgroup, "g", "contourbg");
        var bgfill = bggroup.selectAll("path").data(contours.coloring === "fill" ? [0] : []);
        bgfill.enter().append("path");
        bgfill.exit().remove();
        bgfill.attr("d", "M" + perimeter.join("L") + "Z").style("stroke", "none");
      }
      function makeFills(plotgroup, pathinfo, perimeter, contours) {
        var hasFills = contours.coloring === "fill" || contours.type === "constraint" && contours._operation !== "=";
        var boundaryPath = "M" + perimeter.join("L") + "Z";
        if (hasFills) {
          closeBoundaries(pathinfo, contours);
        }
        var fillgroup = Lib.ensureSingle(plotgroup, "g", "contourfill");
        var fillitems = fillgroup.selectAll("path").data(hasFills ? pathinfo : []);
        fillitems.enter().append("path");
        fillitems.exit().remove();
        fillitems.each(function(pi) {
          var fullpath = (pi.prefixBoundary ? boundaryPath : "") + joinAllPaths(pi, perimeter);
          if (!fullpath) {
            d3.select(this).remove();
          } else {
            d3.select(this).attr("d", fullpath).style("stroke", "none");
          }
        });
      }
      function joinAllPaths(pi, perimeter) {
        var fullpath = "";
        var i = 0;
        var startsleft = pi.edgepaths.map(function(v, i2) {
          return i2;
        });
        var newloop = true;
        var endpt;
        var newendpt;
        var cnt;
        var nexti;
        var possiblei;
        var addpath;
        function istop(pt) {
          return Math.abs(pt[1] - perimeter[0][1]) < 0.01;
        }
        function isbottom(pt) {
          return Math.abs(pt[1] - perimeter[2][1]) < 0.01;
        }
        function isleft(pt) {
          return Math.abs(pt[0] - perimeter[0][0]) < 0.01;
        }
        function isright(pt) {
          return Math.abs(pt[0] - perimeter[2][0]) < 0.01;
        }
        while (startsleft.length) {
          addpath = Drawing.smoothopen(pi.edgepaths[i], pi.smoothing);
          fullpath += newloop ? addpath : addpath.replace(/^M/, "L");
          startsleft.splice(startsleft.indexOf(i), 1);
          endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
          nexti = -1;
          for (cnt = 0; cnt < 4; cnt++) {
            if (!endpt) {
              Lib.log("Missing end?", i, pi);
              break;
            }
            if (istop(endpt) && !isright(endpt)) newendpt = perimeter[1];
            else if (isleft(endpt)) newendpt = perimeter[0];
            else if (isbottom(endpt)) newendpt = perimeter[3];
            else if (isright(endpt)) newendpt = perimeter[2];
            for (possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
              var ptNew = pi.edgepaths[possiblei][0];
              if (Math.abs(endpt[0] - newendpt[0]) < 0.01) {
                if (Math.abs(endpt[0] - ptNew[0]) < 0.01 && (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
                  newendpt = ptNew;
                  nexti = possiblei;
                }
              } else if (Math.abs(endpt[1] - newendpt[1]) < 0.01) {
                if (Math.abs(endpt[1] - ptNew[1]) < 0.01 && (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
                  newendpt = ptNew;
                  nexti = possiblei;
                }
              } else {
                Lib.log(
                  "endpt to newendpt is not vert. or horz.",
                  endpt,
                  newendpt,
                  ptNew
                );
              }
            }
            endpt = newendpt;
            if (nexti >= 0) break;
            fullpath += "L" + newendpt;
          }
          if (nexti === pi.edgepaths.length) {
            Lib.log("unclosed perimeter path");
            break;
          }
          i = nexti;
          newloop = startsleft.indexOf(i) === -1;
          if (newloop) {
            i = startsleft[0];
            fullpath += "Z";
          }
        }
        for (i = 0; i < pi.paths.length; i++) {
          fullpath += Drawing.smoothclosed(pi.paths[i], pi.smoothing);
        }
        return fullpath;
      }
      function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours) {
        var isStatic = gd._context.staticPlot;
        var lineContainer = Lib.ensureSingle(plotgroup, "g", "contourlines");
        var showLines = contours.showlines !== false;
        var showLabels = contours.showlabels;
        var clipLinesForLabels = showLines && showLabels;
        var linegroup = exports.createLines(lineContainer, showLines || showLabels, pathinfo, isStatic);
        var lineClip = exports.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);
        var labelGroup = plotgroup.selectAll("g.contourlabels").data(showLabels ? [0] : []);
        labelGroup.exit().remove();
        labelGroup.enter().append("g").classed("contourlabels", true);
        if (showLabels) {
          var labelClipPathData = [];
          var labelData = [];
          Lib.clearLocationCache();
          var contourFormat = exports.labelFormatter(gd, cd0);
          var dummyText = Drawing.tester.append("text").attr("data-notex", 1).call(Drawing.font, contours.labelfont);
          var xa = pathinfo[0].xaxis;
          var ya = pathinfo[0].yaxis;
          var xLen = xa._length;
          var yLen = ya._length;
          var xRng = xa.range;
          var yRng = ya.range;
          var xMin = Lib.aggNums(Math.min, null, cd0.x);
          var xMax = Lib.aggNums(Math.max, null, cd0.x);
          var yMin = Lib.aggNums(Math.min, null, cd0.y);
          var yMax = Lib.aggNums(Math.max, null, cd0.y);
          var x0 = Math.max(xa.c2p(xMin, true), 0);
          var x1 = Math.min(xa.c2p(xMax, true), xLen);
          var y0 = Math.max(ya.c2p(yMax, true), 0);
          var y1 = Math.min(ya.c2p(yMin, true), yLen);
          var bounds = {};
          if (xRng[0] < xRng[1]) {
            bounds.left = x0;
            bounds.right = x1;
          } else {
            bounds.left = x1;
            bounds.right = x0;
          }
          if (yRng[0] < yRng[1]) {
            bounds.top = y0;
            bounds.bottom = y1;
          } else {
            bounds.top = y1;
            bounds.bottom = y0;
          }
          bounds.middle = (bounds.top + bounds.bottom) / 2;
          bounds.center = (bounds.left + bounds.right) / 2;
          labelClipPathData.push([
            [bounds.left, bounds.top],
            [bounds.right, bounds.top],
            [bounds.right, bounds.bottom],
            [bounds.left, bounds.bottom]
          ]);
          var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);
          var normLength = constants.LABELDISTANCE * plotDiagonal / Math.max(1, pathinfo.length / constants.LABELINCREASE);
          linegroup.each(function(d) {
            var textOpts = exports.calcTextOpts(d.level, contourFormat, dummyText, gd);
            d3.select(this).selectAll("path").each(function() {
              var path = this;
              var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
              if (!pathBounds) return;
              if (pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;
              var maxLabels = Math.min(
                Math.ceil(pathBounds.len / normLength),
                constants.LABELMAX
              );
              for (var i = 0; i < maxLabels; i++) {
                var loc = exports.findBestTextLocation(
                  path,
                  pathBounds,
                  textOpts,
                  labelData,
                  bounds
                );
                if (!loc) break;
                exports.addLabelData(loc, textOpts, labelData, labelClipPathData);
              }
            });
          });
          dummyText.remove();
          exports.drawLabels(
            labelGroup,
            labelData,
            gd,
            lineClip,
            clipLinesForLabels ? labelClipPathData : null
          );
        }
        if (showLabels && !showLines) linegroup.remove();
      }
      exports.createLines = function(lineContainer, makeLines, pathinfo, isStatic) {
        var smoothing = pathinfo[0].smoothing;
        var linegroup = lineContainer.selectAll("g.contourlevel").data(makeLines ? pathinfo : []);
        linegroup.exit().remove();
        linegroup.enter().append("g").classed("contourlevel", true);
        if (makeLines) {
          var opencontourlines = linegroup.selectAll("path.openline").data(function(d) {
            return d.pedgepaths || d.edgepaths;
          });
          opencontourlines.exit().remove();
          opencontourlines.enter().append("path").classed("openline", true);
          opencontourlines.attr("d", function(d) {
            return Drawing.smoothopen(d, smoothing);
          }).style("stroke-miterlimit", 1).style("vector-effect", isStatic ? "none" : "non-scaling-stroke");
          var closedcontourlines = linegroup.selectAll("path.closedline").data(function(d) {
            return d.ppaths || d.paths;
          });
          closedcontourlines.exit().remove();
          closedcontourlines.enter().append("path").classed("closedline", true);
          closedcontourlines.attr("d", function(d) {
            return Drawing.smoothclosed(d, smoothing);
          }).style("stroke-miterlimit", 1).style("vector-effect", isStatic ? "none" : "non-scaling-stroke");
        }
        return linegroup;
      };
      exports.createLineClip = function(lineContainer, clipLinesForLabels, gd, uid) {
        var clips = gd._fullLayout._clips;
        var clipId = clipLinesForLabels ? "clipline" + uid : null;
        var lineClip = clips.selectAll("#" + clipId).data(clipLinesForLabels ? [0] : []);
        lineClip.exit().remove();
        lineClip.enter().append("clipPath").classed("contourlineclip", true).attr("id", clipId);
        Drawing.setClipUrl(lineContainer, clipId, gd);
        return lineClip;
      };
      exports.labelFormatter = function(gd, cd0) {
        var fullLayout = gd._fullLayout;
        var trace = cd0.trace;
        var contours = trace.contours;
        var formatAxis = {
          type: "linear",
          _id: "ycontour",
          showexponent: "all",
          exponentformat: "B"
        };
        if (contours.labelformat) {
          formatAxis.tickformat = contours.labelformat;
          setConvert(formatAxis, fullLayout);
        } else {
          var cOpts = Colorscale.extractOpts(trace);
          if (cOpts && cOpts.colorbar && cOpts.colorbar._axis) {
            formatAxis = cOpts.colorbar._axis;
          } else {
            if (contours.type === "constraint") {
              var value = contours.value;
              if (Lib.isArrayOrTypedArray(value)) {
                formatAxis.range = [value[0], value[value.length - 1]];
              } else formatAxis.range = [value, value];
            } else {
              formatAxis.range = [contours.start, contours.end];
              formatAxis.nticks = (contours.end - contours.start) / contours.size;
            }
            if (formatAxis.range[0] === formatAxis.range[1]) {
              formatAxis.range[1] += formatAxis.range[0] || 1;
            }
            if (!formatAxis.nticks) formatAxis.nticks = 1e3;
            setConvert(formatAxis, fullLayout);
            Axes.prepTicks(formatAxis);
            formatAxis._tmin = null;
            formatAxis._tmax = null;
          }
        }
        return function(v) {
          return Axes.tickText(formatAxis, v).text;
        };
      };
      exports.calcTextOpts = function(level, contourFormat, dummyText, gd) {
        var text = contourFormat(level);
        dummyText.text(text).call(svgTextUtils.convertToTspans, gd);
        var el = dummyText.node();
        var bBox = Drawing.bBox(el, true);
        return {
          text,
          width: bBox.width,
          height: bBox.height,
          fontSize: +el.style["font-size"].replace("px", ""),
          level,
          dy: (bBox.top + bBox.bottom) / 2
        };
      };
      exports.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) {
        var textWidth = textOpts.width;
        var p0, dp, pMax, pMin, loc;
        if (pathBounds.isClosed) {
          dp = pathBounds.len / costConstants.INITIALSEARCHPOINTS;
          p0 = pathBounds.min + dp / 2;
          pMax = pathBounds.max;
        } else {
          dp = (pathBounds.len - textWidth) / (costConstants.INITIALSEARCHPOINTS + 1);
          p0 = pathBounds.min + dp + textWidth / 2;
          pMax = pathBounds.max - (dp + textWidth) / 2;
        }
        var cost = Infinity;
        for (var j = 0; j < costConstants.ITERATIONS; j++) {
          for (var p = p0; p < pMax; p += dp) {
            var newLocation = Lib.getTextLocation(path, pathBounds.total, p, textWidth);
            var newCost = locationCost(newLocation, textOpts, labelData, plotBounds);
            if (newCost < cost) {
              cost = newCost;
              loc = newLocation;
              pMin = p;
            }
          }
          if (cost > costConstants.MAXCOST * 2) break;
          if (j) dp /= 2;
          p0 = pMin - dp / 2;
          pMax = p0 + dp * 1.5;
        }
        if (cost <= costConstants.MAXCOST) return loc;
      };
      function locationCost(loc, textOpts, labelData, bounds) {
        var halfWidth = textOpts.width / 2;
        var halfHeight = textOpts.height / 2;
        var x = loc.x;
        var y = loc.y;
        var theta = loc.theta;
        var dx = Math.cos(theta) * halfWidth;
        var dy = Math.sin(theta) * halfWidth;
        var normX = (x > bounds.center ? bounds.right - x : x - bounds.left) / (dx + Math.abs(Math.sin(theta) * halfHeight));
        var normY = (y > bounds.middle ? bounds.bottom - y : y - bounds.top) / (Math.abs(dy) + Math.cos(theta) * halfHeight);
        if (normX < 1 || normY < 1) return Infinity;
        var cost = costConstants.EDGECOST * (1 / (normX - 1) + 1 / (normY - 1));
        cost += costConstants.ANGLECOST * theta * theta;
        var x1 = x - dx;
        var y1 = y - dy;
        var x2 = x + dx;
        var y2 = y + dy;
        for (var i = 0; i < labelData.length; i++) {
          var labeli = labelData[i];
          var dxd = Math.cos(labeli.theta) * labeli.width / 2;
          var dyd = Math.sin(labeli.theta) * labeli.width / 2;
          var dist = Lib.segmentDistance(
            x1,
            y1,
            x2,
            y2,
            labeli.x - dxd,
            labeli.y - dyd,
            labeli.x + dxd,
            labeli.y + dyd
          ) * 2 / (textOpts.height + labeli.height);
          var sameLevel = labeli.level === textOpts.level;
          var distOffset = sameLevel ? costConstants.SAMELEVELDISTANCE : 1;
          if (dist <= distOffset) return Infinity;
          var distFactor = costConstants.NEIGHBORCOST * (sameLevel ? costConstants.SAMELEVELFACTOR : 1);
          cost += distFactor / (dist - distOffset);
        }
        return cost;
      }
      exports.addLabelData = function(loc, textOpts, labelData, labelClipPathData) {
        var fontSize = textOpts.fontSize;
        var w = textOpts.width + fontSize / 3;
        var h = Math.max(0, textOpts.height - fontSize / 3);
        var x = loc.x;
        var y = loc.y;
        var theta = loc.theta;
        var sin = Math.sin(theta);
        var cos = Math.cos(theta);
        var rotateXY = function(dx, dy) {
          return [
            x + dx * cos - dy * sin,
            y + dx * sin + dy * cos
          ];
        };
        var bBoxPts = [
          rotateXY(-w / 2, -h / 2),
          rotateXY(-w / 2, h / 2),
          rotateXY(w / 2, h / 2),
          rotateXY(w / 2, -h / 2)
        ];
        labelData.push({
          text: textOpts.text,
          x,
          y,
          dy: textOpts.dy,
          theta,
          level: textOpts.level,
          width: w,
          height: h
        });
        labelClipPathData.push(bBoxPts);
      };
      exports.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipPathData) {
        var labels = labelGroup.selectAll("text").data(labelData, function(d) {
          return d.text + "," + d.x + "," + d.y + "," + d.theta;
        });
        labels.exit().remove();
        labels.enter().append("text").attr({
          "data-notex": 1,
          "text-anchor": "middle"
        }).each(function(d) {
          var x = d.x + Math.sin(d.theta) * d.dy;
          var y = d.y - Math.cos(d.theta) * d.dy;
          d3.select(this).text(d.text).attr({
            x,
            y,
            transform: "rotate(" + 180 * d.theta / Math.PI + " " + x + " " + y + ")"
          }).call(svgTextUtils.convertToTspans, gd);
        });
        if (labelClipPathData) {
          var clipPath = "";
          for (var i = 0; i < labelClipPathData.length; i++) {
            clipPath += "M" + labelClipPathData[i].join("L") + "Z";
          }
          var lineClipPath = Lib.ensureSingle(lineClip, "path", "");
          lineClipPath.attr("d", clipPath);
        }
      };
      function clipGaps(plotGroup, plotinfo, gd, cd0, perimeter) {
        var trace = cd0.trace;
        var clips = gd._fullLayout._clips;
        var clipId = "clip" + trace.uid;
        var clipPath = clips.selectAll("#" + clipId).data(trace.connectgaps ? [] : [0]);
        clipPath.enter().append("clipPath").classed("contourclip", true).attr("id", clipId);
        clipPath.exit().remove();
        if (trace.connectgaps === false) {
          var clipPathInfo = {
            // fraction of the way from missing to present point
            // to draw the boundary.
            // if you make this 1 (or 1-epsilon) then a point in
            // a sea of missing data will disappear entirely.
            level: 0.9,
            crossings: {},
            starts: [],
            edgepaths: [],
            paths: [],
            xaxis: plotinfo.xaxis,
            yaxis: plotinfo.yaxis,
            x: cd0.x,
            y: cd0.y,
            // 0 = no data, 1 = data
            z: makeClipMask(cd0),
            smoothing: 0
          };
          makeCrossings([clipPathInfo]);
          findAllPaths([clipPathInfo]);
          closeBoundaries([clipPathInfo], { type: "levels" });
          var path = Lib.ensureSingle(clipPath, "path", "");
          path.attr(
            "d",
            (clipPathInfo.prefixBoundary ? "M" + perimeter.join("L") + "Z" : "") + joinAllPaths(clipPathInfo, perimeter)
          );
        } else clipId = null;
        Drawing.setClipUrl(plotGroup, clipId, gd);
      }
      function makeClipMask(cd0) {
        var empties = cd0.trace._emptypoints;
        var z = [];
        var m = cd0.z.length;
        var n = cd0.z[0].length;
        var i;
        var row = [];
        var emptyPoint;
        for (i = 0; i < n; i++) row.push(1);
        for (i = 0; i < m; i++) z.push(row.slice());
        for (i = 0; i < empties.length; i++) {
          emptyPoint = empties[i];
          z[emptyPoint[0]][emptyPoint[1]] = 0;
        }
        cd0.zmask = z;
        return z;
      }
    }
  });

  // src/traces/contour/make_color_map.js
  var require_make_color_map = __commonJS({
    "src/traces/contour/make_color_map.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Colorscale = require_colorscale();
      var endPlus = require_end_plus();
      module.exports = function makeColorMap(trace) {
        var contours = trace.contours;
        var start = contours.start;
        var end = endPlus(contours);
        var cs = contours.size || 1;
        var nc = Math.floor((end - start) / cs) + 1;
        var extra = contours.coloring === "lines" ? 0 : 1;
        var cOpts = Colorscale.extractOpts(trace);
        if (!isFinite(cs)) {
          cs = 1;
          nc = 1;
        }
        var scl = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : cOpts.colorscale;
        var len = scl.length;
        var domain = new Array(len);
        var range = new Array(len);
        var si, i;
        var zmin0 = cOpts.min;
        var zmax0 = cOpts.max;
        if (contours.coloring === "heatmap") {
          for (i = 0; i < len; i++) {
            si = scl[i];
            domain[i] = si[0] * (zmax0 - zmin0) + zmin0;
            range[i] = si[1];
          }
          var zRange = d3.extent([
            zmin0,
            zmax0,
            contours.start,
            contours.start + cs * (nc - 1)
          ]);
          var zmin = zRange[zmin0 < zmax0 ? 0 : 1];
          var zmax = zRange[zmin0 < zmax0 ? 1 : 0];
          if (zmin !== zmin0) {
            domain.splice(0, 0, zmin);
            range.splice(0, 0, range[0]);
          }
          if (zmax !== zmax0) {
            domain.push(zmax);
            range.push(range[range.length - 1]);
          }
        } else {
          var zRangeInput = trace._input && (typeof trace._input.zmin === "number" && typeof trace._input.zmax === "number");
          if (zRangeInput && (start <= zmin0 || end >= zmax0)) {
            if (start <= zmin0) start = zmin0;
            if (end >= zmax0) end = zmax0;
            nc = Math.floor((end - start) / cs) + 1;
            extra = 0;
          }
          for (i = 0; i < len; i++) {
            si = scl[i];
            domain[i] = (si[0] * (nc + extra - 1) - extra / 2) * cs + start;
            range[i] = si[1];
          }
          if (zRangeInput || trace.autocontour) {
            if (domain[0] > zmin0) {
              domain.unshift(zmin0);
              range.unshift(range[0]);
            }
            if (domain[domain.length - 1] < zmax0) {
              domain.push(zmax0);
              range.push(range[range.length - 1]);
            }
          }
        }
        return Colorscale.makeColorScaleFunc(
          { domain, range },
          { noNumericCheck: true }
        );
      };
    }
  });

  // src/traces/contour/style.js
  var require_style7 = __commonJS({
    "src/traces/contour/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var heatmapStyle = require_style6();
      var makeColorMap = require_make_color_map();
      module.exports = function style(gd) {
        var contours = d3.select(gd).selectAll("g.contour");
        contours.style("opacity", function(d) {
          return d[0].trace.opacity;
        });
        contours.each(function(d) {
          var c = d3.select(this);
          var trace = d[0].trace;
          var contours2 = trace.contours;
          var line = trace.line;
          var cs = contours2.size || 1;
          var start = contours2.start;
          var isConstraintType = contours2.type === "constraint";
          var colorLines = !isConstraintType && contours2.coloring === "lines";
          var colorFills = !isConstraintType && contours2.coloring === "fill";
          var colorMap = colorLines || colorFills ? makeColorMap(trace) : null;
          c.selectAll("g.contourlevel").each(function(d2) {
            d3.select(this).selectAll("path").call(
              Drawing.lineGroupStyle,
              line.width,
              colorLines ? colorMap(d2.level) : line.color,
              line.dash
            );
          });
          var labelFont = contours2.labelfont;
          c.selectAll("g.contourlabels text").each(function(d2) {
            Drawing.font(d3.select(this), {
              weight: labelFont.weight,
              style: labelFont.style,
              variant: labelFont.variant,
              textcase: labelFont.textcase,
              lineposition: labelFont.lineposition,
              shadow: labelFont.shadow,
              family: labelFont.family,
              size: labelFont.size,
              color: labelFont.color || (colorLines ? colorMap(d2.level) : line.color)
            });
          });
          if (isConstraintType) {
            c.selectAll("g.contourfill path").style("fill", trace.fillcolor);
          } else if (colorFills) {
            var firstFill;
            c.selectAll("g.contourfill path").style("fill", function(d2) {
              if (firstFill === void 0) firstFill = d2.level;
              return colorMap(d2.level + 0.5 * cs);
            });
            if (firstFill === void 0) firstFill = start;
            c.selectAll("g.contourbg path").style("fill", colorMap(firstFill - 0.5 * cs));
          }
        });
        heatmapStyle(gd);
      };
    }
  });

  // src/traces/contour/colorbar.js
  var require_colorbar3 = __commonJS({
    "src/traces/contour/colorbar.js"(exports, module) {
      "use strict";
      var Colorscale = require_colorscale();
      var makeColorMap = require_make_color_map();
      var endPlus = require_end_plus();
      function calc(gd, trace, opts) {
        var contours = trace.contours;
        var line = trace.line;
        var cs = contours.size || 1;
        var coloring = contours.coloring;
        var colorMap = makeColorMap(trace, { isColorbar: true });
        if (coloring === "heatmap") {
          var cOpts = Colorscale.extractOpts(trace);
          opts._fillgradient = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : cOpts.colorscale;
          opts._zrange = [cOpts.min, cOpts.max];
        } else if (coloring === "fill") {
          opts._fillcolor = colorMap;
        }
        opts._line = {
          color: coloring === "lines" ? colorMap : line.color,
          width: contours.showlines !== false ? line.width : 0,
          dash: line.dash
        };
        opts._levels = {
          start: contours.start,
          end: endPlus(contours),
          size: cs
        };
      }
      module.exports = {
        min: "zmin",
        max: "zmax",
        calc
      };
    }
  });

  // src/traces/contour/hover.js
  var require_hover8 = __commonJS({
    "src/traces/contour/hover.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var heatmapHoverPoints = require_hover5();
      module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
        if (!opts) opts = {};
        opts.isContour = true;
        var hoverData = heatmapHoverPoints(pointData, xval, yval, hovermode, opts);
        if (hoverData) {
          hoverData.forEach(function(hoverPt) {
            var trace = hoverPt.trace;
            if (trace.contours.type === "constraint") {
              if (trace.fillcolor && Color2.opacity(trace.fillcolor)) {
                hoverPt.color = Color2.addOpacity(trace.fillcolor, 1);
              } else if (trace.contours.showlines && Color2.opacity(trace.line.color)) {
                hoverPt.color = Color2.addOpacity(trace.line.color, 1);
              }
            }
          });
        }
        return hoverData;
      };
    }
  });

  // src/traces/histogram2dcontour/index.js
  var require_histogram2dcontour = __commonJS({
    "src/traces/histogram2dcontour/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes29(),
        supplyDefaults: require_defaults24(),
        crossTraceDefaults: require_cross_trace_defaults3(),
        calc: require_calc10(),
        plot: require_plot6().plot,
        layerName: "contourlayer",
        style: require_style7(),
        colorbar: require_colorbar3(),
        hoverPoints: require_hover8(),
        moduleType: "trace",
        name: "histogram2dcontour",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "2dMap", "contour", "histogram", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/histogram2dcontour.js
  var require_histogram2dcontour2 = __commonJS({
    "lib/histogram2dcontour.js"(exports, module) {
      "use strict";
      module.exports = require_histogram2dcontour();
    }
  });

  // src/traces/contour/constraint_defaults.js
  var require_constraint_defaults = __commonJS({
    "src/traces/contour/constraint_defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var handleLabelDefaults = require_label_defaults2();
      var Color2 = require_color();
      var addOpacity = Color2.addOpacity;
      var opacity = Color2.opacity;
      var filterOps = require_filter_ops();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var CONSTRAINT_REDUCTION = filterOps.CONSTRAINT_REDUCTION;
      var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
      module.exports = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) {
        var contours = traceOut.contours;
        var showLines, lineColor, fillColor;
        var operation = coerce("contours.operation");
        contours._operation = CONSTRAINT_REDUCTION[operation];
        handleConstraintValueDefaults(coerce, contours);
        if (operation === "=") {
          showLines = contours.showlines = true;
        } else {
          showLines = coerce("contours.showlines");
          fillColor = coerce("fillcolor", addOpacity(
            (traceIn.line || {}).color || defaultColor,
            0.5
          ));
        }
        if (showLines) {
          var lineDfltColor = fillColor && opacity(fillColor) ? addOpacity(traceOut.fillcolor, 1) : defaultColor;
          lineColor = coerce("line.color", lineDfltColor);
          coerce("line.width", 2);
          coerce("line.dash");
        }
        coerce("line.smoothing");
        handleLabelDefaults(coerce, layout, lineColor, opts);
      };
      function handleConstraintValueDefaults(coerce, contours) {
        var zvalue;
        if (COMPARISON_OPS2.indexOf(contours.operation) === -1) {
          coerce("contours.value", [0, 1]);
          if (!isArrayOrTypedArray(contours.value)) {
            if (isNumeric(contours.value)) {
              zvalue = parseFloat(contours.value);
              contours.value = [zvalue, zvalue + 1];
            }
          } else if (contours.value.length > 2) {
            contours.value = contours.value.slice(2);
          } else if (contours.length === 0) {
            contours.value = [0, 1];
          } else if (contours.length < 2) {
            zvalue = parseFloat(contours.value[0]);
            contours.value = [zvalue, zvalue + 1];
          } else {
            contours.value = [
              parseFloat(contours.value[0]),
              parseFloat(contours.value[1])
            ];
          }
        } else {
          coerce("contours.value", 0);
          if (!isNumeric(contours.value)) {
            if (isArrayOrTypedArray(contours.value)) {
              contours.value = parseFloat(contours.value[0]);
            } else {
              contours.value = 0;
            }
          }
        }
      }
    }
  });

  // src/traces/contour/defaults.js
  var require_defaults25 = __commonJS({
    "src/traces/contour/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleXYZDefaults = require_xyz_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var handleConstraintDefaults = require_constraint_defaults();
      var handleContoursDefaults = require_contours_defaults();
      var handleStyleDefaults = require_style_defaults3();
      var handleHeatmapLabelDefaults = require_label_defaults();
      var attributes = require_attributes28();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        function coerce2(attr) {
          return Lib.coerce2(traceIn, traceOut, attributes, attr);
        }
        var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("text");
        coerce("hovertext");
        coerce("hoverongaps");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var isConstraint = coerce("contours.type") === "constraint";
        coerce("connectgaps", Lib.isArray1D(traceOut.z));
        if (isConstraint) {
          handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor);
        } else {
          handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
          handleStyleDefaults(traceIn, traceOut, coerce, layout);
        }
        if (traceOut.contours && traceOut.contours.coloring === "heatmap") {
          handleHeatmapLabelDefaults(coerce, layout);
        }
        coerce("zorder");
      };
    }
  });

  // src/traces/contour/index.js
  var require_contour = __commonJS({
    "src/traces/contour/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes28(),
        supplyDefaults: require_defaults25(),
        calc: require_calc10(),
        plot: require_plot6().plot,
        style: require_style7(),
        colorbar: require_colorbar3(),
        hoverPoints: require_hover8(),
        moduleType: "trace",
        name: "contour",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "2dMap", "contour", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/contour.js
  var require_contour2 = __commonJS({
    "lib/contour.js"(exports, module) {
      "use strict";
      module.exports = require_contour();
    }
  });

  // src/traces/scatterternary/attributes.js
  var require_attributes30 = __commonJS({
    "src/traces/scatterternary/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterAttrs = require_attributes12();
      var baseAttrs = require_attributes2();
      var colorScaleAttrs = require_attributes8();
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterLineAttrs = scatterAttrs.line;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      module.exports = {
        a: {
          valType: "data_array",
          editType: "calc"
        },
        b: {
          valType: "data_array",
          editType: "calc"
        },
        c: {
          valType: "data_array",
          editType: "calc"
        },
        sum: {
          valType: "number",
          dflt: 0,
          min: 0,
          editType: "calc"
        },
        mode: extendFlat({}, scatterAttrs.mode, { dflt: "markers" }),
        text: extendFlat({}, scatterAttrs.text, {}),
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["a", "b", "c", "text"] }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
        line: {
          color: scatterLineAttrs.color,
          width: scatterLineAttrs.width,
          dash,
          backoff: scatterLineAttrs.backoff,
          shape: extendFlat({}, scatterLineAttrs.shape, { values: ["linear", "spline"] }),
          smoothing: scatterLineAttrs.smoothing,
          editType: "calc"
        },
        connectgaps: scatterAttrs.connectgaps,
        cliponaxis: scatterAttrs.cliponaxis,
        fill: extendFlat({}, scatterAttrs.fill, {
          values: ["none", "toself", "tonext"],
          dflt: "none"
        }),
        fillcolor: makeFillcolorAttr(),
        marker: extendFlat(
          {
            symbol: scatterMarkerAttrs.symbol,
            opacity: scatterMarkerAttrs.opacity,
            angle: scatterMarkerAttrs.angle,
            angleref: scatterMarkerAttrs.angleref,
            standoff: scatterMarkerAttrs.standoff,
            maxdisplayed: scatterMarkerAttrs.maxdisplayed,
            size: scatterMarkerAttrs.size,
            sizeref: scatterMarkerAttrs.sizeref,
            sizemin: scatterMarkerAttrs.sizemin,
            sizemode: scatterMarkerAttrs.sizemode,
            line: extendFlat(
              {
                width: scatterMarkerLineAttrs.width,
                dash: scatterMarkerLineAttrs.dash,
                editType: "calc"
              },
              colorScaleAttrs("marker.line")
            ),
            gradient: scatterMarkerAttrs.gradient,
            editType: "calc"
          },
          colorScaleAttrs("marker")
        ),
        textfont: scatterAttrs.textfont,
        textposition: scatterAttrs.textposition,
        selected: scatterAttrs.selected,
        unselected: scatterAttrs.unselected,
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["a", "b", "c", "text", "name"]
        }),
        hoveron: scatterAttrs.hoveron,
        hovertemplate: hovertemplateAttrs(),
        hovertemplatefallback: templatefallbackAttrs()
      };
    }
  });

  // src/traces/scatterternary/defaults.js
  var require_defaults26 = __commonJS({
    "src/traces/scatterternary/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var constants = require_constants8();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleLineShapeDefaults = require_line_shape_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var attributes = require_attributes30();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var a = coerce("a");
        var b = coerce("b");
        var c = coerce("c");
        var len;
        if (a) {
          len = a.length;
          if (b) {
            len = Math.min(len, b.length);
            if (c) len = Math.min(len, c.length);
          } else if (c) len = Math.min(len, c.length);
          else len = 0;
        } else if (b && c) {
          len = Math.min(b.length, c.length);
        }
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        coerce("sum");
        coerce("text");
        coerce("hovertext");
        if (traceOut.hoveron !== "fills") {
          coerce("hovertemplate");
          coerce("hovertemplatefallback");
        }
        var defaultMode = len < constants.PTS_LINESONLY ? "lines+markers" : "lines";
        coerce("mode", defaultMode);
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { gradient: true });
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, { backoff: true });
          handleLineShapeDefaults(traceIn, traceOut, coerce);
          coerce("connectgaps");
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce);
        }
        var dfltHoverOn = [];
        if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
          coerce("cliponaxis");
          coerce("marker.maxdisplayed");
          dfltHoverOn.push("points");
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
          if (!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
        }
        if (traceOut.fill === "tonext" || traceOut.fill === "toself") {
          dfltHoverOn.push("fills");
        }
        coerce("hoveron", dfltHoverOn.join("+") || "points");
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/scatterternary/format_labels.js
  var require_format_labels2 = __commonJS({
    "src/traces/scatterternary/format_labels.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var labels = {};
        var subplot = fullLayout[trace.subplot]._subplot;
        labels.aLabel = Axes.tickText(subplot.aaxis, cdi.a, true).text;
        labels.bLabel = Axes.tickText(subplot.baxis, cdi.b, true).text;
        labels.cLabel = Axes.tickText(subplot.caxis, cdi.c, true).text;
        return labels;
      };
    }
  });

  // src/traces/scatterternary/calc.js
  var require_calc11 = __commonJS({
    "src/traces/scatterternary/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var calcColorscale = require_colorscale_calc();
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcSelection = require_calc_selection();
      var calcMarkerSize = require_calc3().calcMarkerSize;
      var dataArrays = ["a", "b", "c"];
      var arraysToFill = { a: ["b", "c"], b: ["a", "c"], c: ["a", "b"] };
      module.exports = function calc(gd, trace) {
        var ternary = gd._fullLayout[trace.subplot];
        var displaySum = ternary.sum;
        var normSum = trace.sum || displaySum;
        var arrays = { a: trace.a, b: trace.b, c: trace.c };
        var ids = trace.ids;
        var i, j, dataArray, newArray, fillArray1, fillArray2;
        for (i = 0; i < dataArrays.length; i++) {
          dataArray = dataArrays[i];
          if (arrays[dataArray]) continue;
          fillArray1 = arrays[arraysToFill[dataArray][0]];
          fillArray2 = arrays[arraysToFill[dataArray][1]];
          newArray = new Array(fillArray1.length);
          for (j = 0; j < fillArray1.length; j++) {
            newArray[j] = normSum - fillArray1[j] - fillArray2[j];
          }
          arrays[dataArray] = newArray;
        }
        var serieslen = trace._length;
        var cd = new Array(serieslen);
        var a, b, c, norm, x, y;
        for (i = 0; i < serieslen; i++) {
          a = arrays.a[i];
          b = arrays.b[i];
          c = arrays.c[i];
          if (isNumeric(a) && isNumeric(b) && isNumeric(c)) {
            a = +a;
            b = +b;
            c = +c;
            norm = displaySum / (a + b + c);
            if (norm !== 1) {
              a *= norm;
              b *= norm;
              c *= norm;
            }
            y = a;
            x = c - b;
            cd[i] = { x, y, a, b, c };
            if (ids) {
              cd[i].id = ids[i];
            }
          } else cd[i] = { x: false, y: false };
        }
        calcMarkerSize(trace, serieslen);
        calcColorscale(gd, trace);
        arraysToCalcdata(cd, trace);
        calcSelection(cd, trace);
        return cd;
      };
    }
  });

  // src/traces/scatterternary/plot.js
  var require_plot7 = __commonJS({
    "src/traces/scatterternary/plot.js"(exports, module) {
      "use strict";
      var scatterPlot = require_plot();
      module.exports = function plot(gd, ternary, moduleCalcData) {
        var plotContainer = ternary.plotContainer;
        plotContainer.select(".scatterlayer").selectAll("*").remove();
        var xa = ternary.xaxis;
        var ya = ternary.yaxis;
        var plotinfo = {
          xaxis: xa,
          yaxis: ya,
          plot: plotContainer,
          layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null
        };
        var scatterLayer = ternary.layers.frontplot.select("g.scatterlayer");
        for (var i = 0; i < moduleCalcData.length; i++) {
          var cdi = moduleCalcData[i];
          if (cdi.length) {
            cdi[0].trace._xA = xa;
            cdi[0].trace._yA = ya;
          }
        }
        scatterPlot(gd, plotinfo, moduleCalcData, scatterLayer);
      };
    }
  });

  // src/traces/scatterternary/hover.js
  var require_hover9 = __commonJS({
    "src/traces/scatterternary/hover.js"(exports, module) {
      "use strict";
      var scatterHover = require_hover2();
      module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
        var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
        if (!scatterPointData || scatterPointData[0].index === false) return;
        var newPointData = scatterPointData[0];
        if (newPointData.index === void 0) {
          var yFracUp = 1 - newPointData.y0 / pointData.ya._length;
          var xLen = pointData.xa._length;
          var xMin = xLen * yFracUp / 2;
          var xMax = xLen - xMin;
          newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
          newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
          return scatterPointData;
        }
        var cdi = newPointData.cd[newPointData.index];
        var trace = newPointData.trace;
        var subplot = newPointData.subplot;
        newPointData.a = cdi.a;
        newPointData.b = cdi.b;
        newPointData.c = cdi.c;
        newPointData.xLabelVal = void 0;
        newPointData.yLabelVal = void 0;
        var fullLayout = {};
        fullLayout[trace.subplot] = { _subplot: subplot };
        var labels = trace._module.formatLabels(cdi, trace, fullLayout);
        newPointData.aLabel = labels.aLabel;
        newPointData.bLabel = labels.bLabel;
        newPointData.cLabel = labels.cLabel;
        var hoverinfo = cdi.hi || trace.hoverinfo;
        var text = [];
        function textPart(ax, val) {
          text.push(ax._hovertitle + ": " + val);
        }
        if (!trace.hovertemplate) {
          var parts = hoverinfo.split("+");
          if (parts.indexOf("all") !== -1) parts = ["a", "b", "c"];
          if (parts.indexOf("a") !== -1) textPart(subplot.aaxis, newPointData.aLabel);
          if (parts.indexOf("b") !== -1) textPart(subplot.baxis, newPointData.bLabel);
          if (parts.indexOf("c") !== -1) textPart(subplot.caxis, newPointData.cLabel);
        }
        newPointData.extraText = text.join("<br>");
        newPointData.hovertemplate = trace.hovertemplate;
        return scatterPointData;
      };
    }
  });

  // src/traces/scatterternary/event_data.js
  var require_event_data4 = __commonJS({
    "src/traces/scatterternary/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt, trace, cd, pointNumber) {
        if (pt.xa) out.xaxis = pt.xa;
        if (pt.ya) out.yaxis = pt.ya;
        if (cd[pointNumber]) {
          var cdi = cd[pointNumber];
          out.a = cdi.a;
          out.b = cdi.b;
          out.c = cdi.c;
        } else {
          out.a = pt.a;
          out.b = pt.b;
          out.c = pt.c;
        }
        return out;
      };
    }
  });

  // src/plots/ternary/ternary.js
  var require_ternary = __commonJS({
    "src/plots/ternary/ternary.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var tinycolor = require_tinycolor();
      var Registry = require_registry();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var _ = Lib._;
      var Color2 = require_color();
      var Drawing = require_drawing();
      var setConvert = require_set_convert();
      var extendFlat = require_extend().extendFlat;
      var Plots = require_plots();
      var Axes = require_axes();
      var dragElement = require_dragelement();
      var Fx = require_fx();
      var dragHelpers = require_helpers5();
      var freeMode = dragHelpers.freeMode;
      var rectMode = dragHelpers.rectMode;
      var Titles = require_titles();
      var prepSelect = require_selections().prepSelect;
      var selectOnClick = require_selections().selectOnClick;
      var clearOutline = require_selections().clearOutline;
      var clearSelectionsCache = require_selections().clearSelectionsCache;
      var constants = require_constants2();
      function Ternary(options, fullLayout) {
        this.id = options.id;
        this.graphDiv = options.graphDiv;
        this.init(fullLayout);
        this.makeFramework(fullLayout);
        this.updateFx(fullLayout);
        this.aTickLayout = null;
        this.bTickLayout = null;
        this.cTickLayout = null;
      }
      module.exports = Ternary;
      var proto = Ternary.prototype;
      proto.init = function(fullLayout) {
        this.container = fullLayout._ternarylayer;
        this.defs = fullLayout._defs;
        this.layoutId = fullLayout._uid;
        this.traceHash = {};
        this.layers = {};
      };
      proto.plot = function(ternaryCalcData, fullLayout) {
        var _this = this;
        var ternaryLayout = fullLayout[_this.id];
        var graphSize = fullLayout._size;
        _this._hasClipOnAxisFalse = false;
        for (var i = 0; i < ternaryCalcData.length; i++) {
          var trace = ternaryCalcData[i][0].trace;
          if (trace.cliponaxis === false) {
            _this._hasClipOnAxisFalse = true;
            break;
          }
        }
        _this.updateLayers(ternaryLayout);
        _this.adjustLayout(ternaryLayout, graphSize);
        Plots.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout);
        _this.layers.plotbg.select("path").call(Color2.fill, ternaryLayout.bgcolor);
      };
      proto.makeFramework = function(fullLayout) {
        var _this = this;
        var gd = _this.graphDiv;
        var ternaryLayout = fullLayout[_this.id];
        var clipId = _this.clipId = "clip" + _this.layoutId + _this.id;
        var clipIdRelative = _this.clipIdRelative = "clip-relative" + _this.layoutId + _this.id;
        _this.clipDef = Lib.ensureSingleById(fullLayout._clips, "clipPath", clipId, function(s) {
          s.append("path").attr("d", "M0,0Z");
        });
        _this.clipDefRelative = Lib.ensureSingleById(fullLayout._clips, "clipPath", clipIdRelative, function(s) {
          s.append("path").attr("d", "M0,0Z");
        });
        _this.plotContainer = Lib.ensureSingle(_this.container, "g", _this.id);
        _this.updateLayers(ternaryLayout);
        Drawing.setClipUrl(_this.layers.backplot, clipId, gd);
        Drawing.setClipUrl(_this.layers.grids, clipId, gd);
      };
      proto.updateFx = function(fullLayout) {
        fullLayout._ternarylayer.selectAll("g.toplevel").style("cursor", fullLayout.dragmode === "pan" ? "move" : "crosshair");
      };
      proto.updateLayers = function(ternaryLayout) {
        var _this = this;
        var layers = _this.layers;
        var plotLayers = ["draglayer", "plotbg", "backplot", "grids"];
        if (ternaryLayout.aaxis.layer === "below traces") {
          plotLayers.push("aaxis", "aline");
        }
        if (ternaryLayout.baxis.layer === "below traces") {
          plotLayers.push("baxis", "bline");
        }
        if (ternaryLayout.caxis.layer === "below traces") {
          plotLayers.push("caxis", "cline");
        }
        plotLayers.push("frontplot");
        if (ternaryLayout.aaxis.layer === "above traces") {
          plotLayers.push("aaxis", "aline");
        }
        if (ternaryLayout.baxis.layer === "above traces") {
          plotLayers.push("baxis", "bline");
        }
        if (ternaryLayout.caxis.layer === "above traces") {
          plotLayers.push("caxis", "cline");
        }
        var toplevel = _this.plotContainer.selectAll("g.toplevel").data(plotLayers, String);
        var grids = ["agrid", "bgrid", "cgrid"];
        toplevel.enter().append("g").attr("class", function(d) {
          return "toplevel " + d;
        }).each(function(d) {
          var s = d3.select(this);
          layers[d] = s;
          if (d === "frontplot") {
            s.append("g").classed("scatterlayer", true);
          } else if (d === "backplot") {
            s.append("g").classed("maplayer", true);
          } else if (d === "plotbg") {
            s.append("path").attr("d", "M0,0Z");
          } else if (d === "aline" || d === "bline" || d === "cline") {
            s.append("path");
          } else if (d === "grids") {
            grids.forEach(function(d2) {
              layers[d2] = s.append("g").classed("grid " + d2, true);
            });
          }
        });
        toplevel.order();
      };
      var whRatio = Math.sqrt(4 / 3);
      proto.adjustLayout = function(ternaryLayout, graphSize) {
        var _this = this;
        var domain = ternaryLayout.domain;
        var xDomainCenter = (domain.x[0] + domain.x[1]) / 2;
        var yDomainCenter = (domain.y[0] + domain.y[1]) / 2;
        var xDomain = domain.x[1] - domain.x[0];
        var yDomain = domain.y[1] - domain.y[0];
        var wmax = xDomain * graphSize.w;
        var hmax = yDomain * graphSize.h;
        var sum = ternaryLayout.sum;
        var amin = ternaryLayout.aaxis.min;
        var bmin = ternaryLayout.baxis.min;
        var cmin = ternaryLayout.caxis.min;
        var x0, y0, w, h, xDomainFinal, yDomainFinal;
        if (wmax > whRatio * hmax) {
          h = hmax;
          w = h * whRatio;
        } else {
          w = wmax;
          h = w / whRatio;
        }
        xDomainFinal = xDomain * w / wmax;
        yDomainFinal = yDomain * h / hmax;
        x0 = graphSize.l + graphSize.w * xDomainCenter - w / 2;
        y0 = graphSize.t + graphSize.h * (1 - yDomainCenter) - h / 2;
        _this.x0 = x0;
        _this.y0 = y0;
        _this.w = w;
        _this.h = h;
        _this.sum = sum;
        _this.xaxis = {
          type: "linear",
          range: [amin + 2 * cmin - sum, sum - amin - 2 * bmin],
          domain: [
            xDomainCenter - xDomainFinal / 2,
            xDomainCenter + xDomainFinal / 2
          ],
          _id: "x"
        };
        setConvert(_this.xaxis, _this.graphDiv._fullLayout);
        _this.xaxis.setScale();
        _this.xaxis.isPtWithinRange = function(d) {
          return d.a >= _this.aaxis.range[0] && d.a <= _this.aaxis.range[1] && d.b >= _this.baxis.range[1] && d.b <= _this.baxis.range[0] && d.c >= _this.caxis.range[1] && d.c <= _this.caxis.range[0];
        };
        _this.yaxis = {
          type: "linear",
          range: [amin, sum - bmin - cmin],
          domain: [
            yDomainCenter - yDomainFinal / 2,
            yDomainCenter + yDomainFinal / 2
          ],
          _id: "y"
        };
        setConvert(_this.yaxis, _this.graphDiv._fullLayout);
        _this.yaxis.setScale();
        _this.yaxis.isPtWithinRange = function() {
          return true;
        };
        var yDomain0 = _this.yaxis.domain[0];
        var aaxis = _this.aaxis = extendFlat({}, ternaryLayout.aaxis, {
          range: [amin, sum - bmin - cmin],
          side: "left",
          // tickangle = 'auto' means 0 anyway for a y axis, need to coerce to 0 here
          // so we can shift by 30.
          tickangle: (+ternaryLayout.aaxis.tickangle || 0) - 30,
          domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
          anchor: "free",
          position: 0,
          _id: "y",
          _length: w
        });
        setConvert(aaxis, _this.graphDiv._fullLayout);
        aaxis.setScale();
        var baxis = _this.baxis = extendFlat({}, ternaryLayout.baxis, {
          range: [sum - amin - cmin, bmin],
          side: "bottom",
          domain: _this.xaxis.domain,
          anchor: "free",
          position: 0,
          _id: "x",
          _length: w
        });
        setConvert(baxis, _this.graphDiv._fullLayout);
        baxis.setScale();
        var caxis = _this.caxis = extendFlat({}, ternaryLayout.caxis, {
          range: [sum - amin - bmin, cmin],
          side: "right",
          tickangle: (+ternaryLayout.caxis.tickangle || 0) + 30,
          domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
          anchor: "free",
          position: 0,
          _id: "y",
          _length: w
        });
        setConvert(caxis, _this.graphDiv._fullLayout);
        caxis.setScale();
        var triangleClip = "M" + x0 + "," + (y0 + h) + "h" + w + "l-" + w / 2 + ",-" + h + "Z";
        _this.clipDef.select("path").attr("d", triangleClip);
        _this.layers.plotbg.select("path").attr("d", triangleClip);
        var triangleClipRelative = "M0," + h + "h" + w + "l-" + w / 2 + ",-" + h + "Z";
        _this.clipDefRelative.select("path").attr("d", triangleClipRelative);
        var plotTransform = strTranslate(x0, y0);
        _this.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform", plotTransform);
        _this.clipDefRelative.select("path").attr("transform", null);
        var bTransform = strTranslate(x0 - baxis._offset, y0 + h);
        _this.layers.baxis.attr("transform", bTransform);
        _this.layers.bgrid.attr("transform", bTransform);
        var aTransform = strTranslate(x0 + w / 2, y0) + "rotate(30)" + strTranslate(0, -aaxis._offset);
        _this.layers.aaxis.attr("transform", aTransform);
        _this.layers.agrid.attr("transform", aTransform);
        var cTransform = strTranslate(x0 + w / 2, y0) + "rotate(-30)" + strTranslate(0, -caxis._offset);
        _this.layers.caxis.attr("transform", cTransform);
        _this.layers.cgrid.attr("transform", cTransform);
        _this.drawAxes(true);
        _this.layers.aline.select("path").attr("d", aaxis.showline ? "M" + x0 + "," + (y0 + h) + "l" + w / 2 + ",-" + h : "M0,0").call(Color2.stroke, aaxis.linecolor || "#000").style("stroke-width", (aaxis.linewidth || 0) + "px");
        _this.layers.bline.select("path").attr("d", baxis.showline ? "M" + x0 + "," + (y0 + h) + "h" + w : "M0,0").call(Color2.stroke, baxis.linecolor || "#000").style("stroke-width", (baxis.linewidth || 0) + "px");
        _this.layers.cline.select("path").attr("d", caxis.showline ? "M" + (x0 + w / 2) + "," + y0 + "l" + w / 2 + "," + h : "M0,0").call(Color2.stroke, caxis.linecolor || "#000").style("stroke-width", (caxis.linewidth || 0) + "px");
        if (!_this.graphDiv._context.staticPlot) {
          _this.initInteractions();
        }
        Drawing.setClipUrl(
          _this.layers.frontplot,
          _this._hasClipOnAxisFalse ? null : _this.clipId,
          _this.graphDiv
        );
      };
      proto.drawAxes = function(doTitles) {
        var _this = this;
        var gd = _this.graphDiv;
        var titlesuffix = _this.id.slice(7) + "title";
        var layers = _this.layers;
        var aaxis = _this.aaxis;
        var baxis = _this.baxis;
        var caxis = _this.caxis;
        _this.drawAx(aaxis);
        _this.drawAx(baxis);
        _this.drawAx(caxis);
        if (doTitles) {
          var apad = Math.max(
            aaxis.showticklabels ? aaxis.tickfont.size / 2 : 0,
            (caxis.showticklabels ? caxis.tickfont.size * 0.75 : 0) + (caxis.ticks === "outside" ? caxis.ticklen * 0.87 : 0)
          );
          var bpad = (baxis.showticklabels ? baxis.tickfont.size : 0) + (baxis.ticks === "outside" ? baxis.ticklen : 0) + 3;
          layers["a-title"] = Titles.draw(gd, "a" + titlesuffix, {
            propContainer: aaxis,
            propName: _this.id + ".aaxis.title.text",
            placeholder: _(gd, "Click to enter Component A title"),
            attributes: {
              x: _this.x0 + _this.w / 2,
              y: _this.y0 - aaxis.title.font.size / 3 - apad,
              "text-anchor": "middle"
            }
          });
          layers["b-title"] = Titles.draw(gd, "b" + titlesuffix, {
            propContainer: baxis,
            propName: _this.id + ".baxis.title.text",
            placeholder: _(gd, "Click to enter Component B title"),
            attributes: {
              x: _this.x0 - bpad,
              y: _this.y0 + _this.h + baxis.title.font.size * 0.83 + bpad,
              "text-anchor": "middle"
            }
          });
          layers["c-title"] = Titles.draw(gd, "c" + titlesuffix, {
            propContainer: caxis,
            propName: _this.id + ".caxis.title.text",
            placeholder: _(gd, "Click to enter Component C title"),
            attributes: {
              x: _this.x0 + _this.w + bpad,
              y: _this.y0 + _this.h + caxis.title.font.size * 0.83 + bpad,
              "text-anchor": "middle"
            }
          });
        }
      };
      proto.drawAx = function(ax) {
        var _this = this;
        var gd = _this.graphDiv;
        var axName = ax._name;
        var axLetter = axName.charAt(0);
        var axId = ax._id;
        var axLayer = _this.layers[axName];
        var counterAngle = 30;
        var stashKey = axLetter + "tickLayout";
        var newTickLayout = strTickLayout(ax);
        if (_this[stashKey] !== newTickLayout) {
          axLayer.selectAll("." + axId + "tick").remove();
          _this[stashKey] = newTickLayout;
        }
        ax.setScale();
        var vals = Axes.calcTicks(ax);
        var valsClipped = Axes.clipEnds(ax, vals);
        var transFn = Axes.makeTransTickFn(ax);
        var tickSign = Axes.getTickSigns(ax)[2];
        var caRad = Lib.deg2rad(counterAngle);
        var pad = tickSign * (ax.linewidth || 1) / 2;
        var len = tickSign * ax.ticklen;
        var w = _this.w;
        var h = _this.h;
        var tickPath = axLetter === "b" ? "M0," + pad + "l" + Math.sin(caRad) * len + "," + Math.cos(caRad) * len : "M" + pad + ",0l" + Math.cos(caRad) * len + "," + -Math.sin(caRad) * len;
        var gridPath = {
          a: "M0,0l" + h + ",-" + w / 2,
          b: "M0,0l-" + w / 2 + ",-" + h,
          c: "M0,0l-" + h + "," + w / 2
        }[axLetter];
        Axes.drawTicks(gd, ax, {
          vals: ax.ticks === "inside" ? valsClipped : vals,
          layer: axLayer,
          path: tickPath,
          transFn,
          crisp: false
        });
        Axes.drawGrid(gd, ax, {
          vals: valsClipped,
          layer: _this.layers[axLetter + "grid"],
          path: gridPath,
          transFn,
          crisp: false
        });
        Axes.drawLabels(gd, ax, {
          vals,
          layer: axLayer,
          transFn,
          labelFns: Axes.makeLabelFns(ax, 0, counterAngle)
        });
      };
      function strTickLayout(axLayout) {
        return axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
      }
      var CLEN = constants.MINZOOM / 2 + 0.87;
      var BLPATH = "m-0.87,.5h" + CLEN + "v3h-" + (CLEN + 5.2) + "l" + (CLEN / 2 + 2.6) + ",-" + (CLEN * 0.87 + 4.5) + "l2.6,1.5l-" + CLEN / 2 + "," + CLEN * 0.87 + "Z";
      var BRPATH = "m0.87,.5h-" + CLEN + "v3h" + (CLEN + 5.2) + "l-" + (CLEN / 2 + 2.6) + ",-" + (CLEN * 0.87 + 4.5) + "l-2.6,1.5l" + CLEN / 2 + "," + CLEN * 0.87 + "Z";
      var TOPPATH = "m0,1l" + CLEN / 2 + "," + CLEN * 0.87 + "l2.6,-1.5l-" + (CLEN / 2 + 2.6) + ",-" + (CLEN * 0.87 + 4.5) + "l-" + (CLEN / 2 + 2.6) + "," + (CLEN * 0.87 + 4.5) + "l2.6,1.5l" + CLEN / 2 + ",-" + CLEN * 0.87 + "Z";
      var STARTMARKER = "m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z";
      var SHOWZOOMOUTTIP = true;
      proto.clearOutline = function() {
        clearSelectionsCache(this.dragOptions);
        clearOutline(this.dragOptions.gd);
      };
      proto.initInteractions = function() {
        var _this = this;
        var dragger = _this.layers.plotbg.select("path").node();
        var gd = _this.graphDiv;
        var zoomLayer = gd._fullLayout._zoomlayer;
        var scaleX;
        var scaleY;
        this.dragOptions = {
          element: dragger,
          gd,
          plotinfo: {
            id: _this.id,
            domain: gd._fullLayout[_this.id].domain,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis
          },
          subplot: _this.id,
          prepFn: function(e, startX, startY) {
            _this.dragOptions.xaxes = [_this.xaxis];
            _this.dragOptions.yaxes = [_this.yaxis];
            scaleX = gd._fullLayout._invScaleX;
            scaleY = gd._fullLayout._invScaleY;
            var dragModeNow = _this.dragOptions.dragmode = gd._fullLayout.dragmode;
            if (freeMode(dragModeNow)) _this.dragOptions.minDrag = 1;
            else _this.dragOptions.minDrag = void 0;
            if (dragModeNow === "zoom") {
              _this.dragOptions.moveFn = zoomMove;
              _this.dragOptions.clickFn = clickZoomPan;
              _this.dragOptions.doneFn = zoomDone;
              zoomPrep(e, startX, startY);
            } else if (dragModeNow === "pan") {
              _this.dragOptions.moveFn = plotDrag;
              _this.dragOptions.clickFn = clickZoomPan;
              _this.dragOptions.doneFn = dragDone;
              panPrep();
              _this.clearOutline(gd);
            } else if (rectMode(dragModeNow) || freeMode(dragModeNow)) {
              prepSelect(e, startX, startY, _this.dragOptions, dragModeNow);
            }
          }
        };
        var x0, y0, mins0, span0, mins, lum, path0, dimmed, zb, corners;
        function makeUpdate(_mins) {
          var attrs = {};
          attrs[_this.id + ".aaxis.min"] = _mins.a;
          attrs[_this.id + ".baxis.min"] = _mins.b;
          attrs[_this.id + ".caxis.min"] = _mins.c;
          return attrs;
        }
        function clickZoomPan(numClicks, evt) {
          var clickMode = gd._fullLayout.clickmode;
          removeZoombox(gd);
          if (numClicks === 2) {
            gd.emit("plotly_doubleclick", null);
            Registry.call("_guiRelayout", gd, makeUpdate({ a: 0, b: 0, c: 0 }));
          }
          if (clickMode.indexOf("select") > -1 && numClicks === 1) {
            selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, _this.dragOptions);
          }
          if (clickMode.indexOf("event") > -1) {
            Fx.click(gd, evt, _this.id);
          }
        }
        function zoomPrep(e, startX, startY) {
          var dragBBox = dragger.getBoundingClientRect();
          x0 = startX - dragBBox.left;
          y0 = startY - dragBBox.top;
          gd._fullLayout._calcInverseTransform(gd);
          var inverse = gd._fullLayout._invTransform;
          var transformedCoords = Lib.apply3DTransform(inverse)(x0, y0);
          x0 = transformedCoords[0];
          y0 = transformedCoords[1];
          mins0 = {
            a: _this.aaxis.range[0],
            b: _this.baxis.range[1],
            c: _this.caxis.range[1]
          };
          mins = mins0;
          span0 = _this.aaxis.range[1] - mins0.a;
          lum = tinycolor(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance();
          path0 = "M0," + _this.h + "L" + _this.w / 2 + ", 0L" + _this.w + "," + _this.h + "Z";
          dimmed = false;
          zb = zoomLayer.append("path").attr("class", "zoombox").attr("transform", strTranslate(_this.x0, _this.y0)).style({
            fill: lum > 0.2 ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)",
            "stroke-width": 0
          }).attr("d", path0);
          corners = zoomLayer.append("path").attr("class", "zoombox-corners").attr("transform", strTranslate(_this.x0, _this.y0)).style({
            fill: Color2.background,
            stroke: Color2.defaultLine,
            "stroke-width": 1,
            opacity: 0
          }).attr("d", "M0,0Z");
          _this.clearOutline(gd);
        }
        function getAFrac(x, y) {
          return 1 - y / _this.h;
        }
        function getBFrac(x, y) {
          return 1 - (x + (_this.h - y) / Math.sqrt(3)) / _this.w;
        }
        function getCFrac(x, y) {
          return (x - (_this.h - y) / Math.sqrt(3)) / _this.w;
        }
        function zoomMove(dx0, dy0) {
          var x1 = x0 + dx0 * scaleX;
          var y1 = y0 + dy0 * scaleY;
          var afrac = Math.max(0, Math.min(1, getAFrac(x0, y0), getAFrac(x1, y1)));
          var bfrac = Math.max(0, Math.min(1, getBFrac(x0, y0), getBFrac(x1, y1)));
          var cfrac = Math.max(0, Math.min(1, getCFrac(x0, y0), getCFrac(x1, y1)));
          var xLeft = (afrac / 2 + cfrac) * _this.w;
          var xRight = (1 - afrac / 2 - bfrac) * _this.w;
          var xCenter = (xLeft + xRight) / 2;
          var xSpan = xRight - xLeft;
          var yBottom = (1 - afrac) * _this.h;
          var yTop = yBottom - xSpan / whRatio;
          if (xSpan < constants.MINZOOM) {
            mins = mins0;
            zb.attr("d", path0);
            corners.attr("d", "M0,0Z");
          } else {
            mins = {
              a: mins0.a + afrac * span0,
              b: mins0.b + bfrac * span0,
              c: mins0.c + cfrac * span0
            };
            zb.attr("d", path0 + "M" + xLeft + "," + yBottom + "H" + xRight + "L" + xCenter + "," + yTop + "L" + xLeft + "," + yBottom + "Z");
            corners.attr("d", "M" + x0 + "," + y0 + STARTMARKER + "M" + xLeft + "," + yBottom + BLPATH + "M" + xRight + "," + yBottom + BRPATH + "M" + xCenter + "," + yTop + TOPPATH);
          }
          if (!dimmed) {
            zb.transition().style("fill", lum > 0.2 ? "rgba(0,0,0,0.4)" : "rgba(255,255,255,0.3)").duration(200);
            corners.transition().style("opacity", 1).duration(200);
            dimmed = true;
          }
          gd.emit("plotly_relayouting", makeUpdate(mins));
        }
        function zoomDone() {
          removeZoombox(gd);
          if (mins === mins0) return;
          Registry.call("_guiRelayout", gd, makeUpdate(mins));
          if (SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
            Lib.notifier(_(gd, "Double-click to zoom back out"), "long");
            SHOWZOOMOUTTIP = false;
          }
        }
        function panPrep() {
          mins0 = {
            a: _this.aaxis.range[0],
            b: _this.baxis.range[1],
            c: _this.caxis.range[1]
          };
          mins = mins0;
        }
        function plotDrag(dx, dy) {
          var dxScaled = dx / _this.xaxis._m;
          var dyScaled = dy / _this.yaxis._m;
          mins = {
            a: mins0.a - dyScaled,
            b: mins0.b + (dxScaled + dyScaled) / 2,
            c: mins0.c - (dxScaled - dyScaled) / 2
          };
          var minsorted = [mins.a, mins.b, mins.c].sort(Lib.sorterAsc);
          var minindices = {
            a: minsorted.indexOf(mins.a),
            b: minsorted.indexOf(mins.b),
            c: minsorted.indexOf(mins.c)
          };
          if (minsorted[0] < 0) {
            if (minsorted[1] + minsorted[0] / 2 < 0) {
              minsorted[2] += minsorted[0] + minsorted[1];
              minsorted[0] = minsorted[1] = 0;
            } else {
              minsorted[2] += minsorted[0] / 2;
              minsorted[1] += minsorted[0] / 2;
              minsorted[0] = 0;
            }
            mins = {
              a: minsorted[minindices.a],
              b: minsorted[minindices.b],
              c: minsorted[minindices.c]
            };
            dy = (mins0.a - mins.a) * _this.yaxis._m;
            dx = (mins0.c - mins.c - mins0.b + mins.b) * _this.xaxis._m;
          }
          var plotTransform = strTranslate(_this.x0 + dx, _this.y0 + dy);
          _this.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform", plotTransform);
          var plotTransform2 = strTranslate(-dx, -dy);
          _this.clipDefRelative.select("path").attr("transform", plotTransform2);
          _this.aaxis.range = [mins.a, _this.sum - mins.b - mins.c];
          _this.baxis.range = [_this.sum - mins.a - mins.c, mins.b];
          _this.caxis.range = [_this.sum - mins.a - mins.b, mins.c];
          _this.drawAxes(false);
          if (_this._hasClipOnAxisFalse) {
            _this.plotContainer.select(".scatterlayer").selectAll(".trace").call(Drawing.hideOutsideRangePoints, _this);
          }
          gd.emit("plotly_relayouting", makeUpdate(mins));
        }
        function dragDone() {
          Registry.call("_guiRelayout", gd, makeUpdate(mins));
        }
        dragger.onmousemove = function(evt) {
          Fx.hover(gd, evt, _this.id);
          gd._fullLayout._lasthover = dragger;
          gd._fullLayout._hoversubplot = _this.id;
        };
        dragger.onmouseout = function(evt) {
          if (gd._dragging) return;
          dragElement.unhover(gd, evt);
        };
        dragElement.init(this.dragOptions);
      };
      function removeZoombox(gd) {
        d3.select(gd).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove();
      }
    }
  });

  // src/plots/ternary/layout_attributes.js
  var require_layout_attributes8 = __commonJS({
    "src/plots/ternary/layout_attributes.js"(exports, module) {
      "use strict";
      var colorAttrs = require_attributes3();
      var domainAttrs = require_domain().attributes;
      var axesAttrs = require_layout_attributes4();
      var overrideAll = require_edit_types().overrideAll;
      var extendFlat = require_extend().extendFlat;
      var ternaryAxesAttrs = {
        title: {
          text: axesAttrs.title.text,
          font: axesAttrs.title.font
          // TODO does standoff here make sense?
        },
        color: axesAttrs.color,
        // ticks
        tickmode: axesAttrs.minor.tickmode,
        nticks: extendFlat({}, axesAttrs.nticks, { dflt: 6, min: 1 }),
        tick0: axesAttrs.tick0,
        dtick: axesAttrs.dtick,
        tickvals: axesAttrs.tickvals,
        ticktext: axesAttrs.ticktext,
        ticks: axesAttrs.ticks,
        ticklen: axesAttrs.ticklen,
        tickwidth: axesAttrs.tickwidth,
        tickcolor: axesAttrs.tickcolor,
        ticklabelstep: axesAttrs.ticklabelstep,
        showticklabels: axesAttrs.showticklabels,
        labelalias: axesAttrs.labelalias,
        showtickprefix: axesAttrs.showtickprefix,
        tickprefix: axesAttrs.tickprefix,
        showticksuffix: axesAttrs.showticksuffix,
        ticksuffix: axesAttrs.ticksuffix,
        showexponent: axesAttrs.showexponent,
        exponentformat: axesAttrs.exponentformat,
        minexponent: axesAttrs.minexponent,
        separatethousands: axesAttrs.separatethousands,
        tickfont: axesAttrs.tickfont,
        tickangle: axesAttrs.tickangle,
        tickformat: axesAttrs.tickformat,
        tickformatstops: axesAttrs.tickformatstops,
        hoverformat: axesAttrs.hoverformat,
        // lines and grids
        showline: extendFlat({}, axesAttrs.showline, { dflt: true }),
        linecolor: axesAttrs.linecolor,
        linewidth: axesAttrs.linewidth,
        showgrid: extendFlat({}, axesAttrs.showgrid, { dflt: true }),
        gridcolor: axesAttrs.gridcolor,
        gridwidth: axesAttrs.gridwidth,
        griddash: axesAttrs.griddash,
        layer: axesAttrs.layer,
        // range
        min: {
          valType: "number",
          dflt: 0,
          min: 0
        }
      };
      var attrs = module.exports = overrideAll({
        domain: domainAttrs({ name: "ternary" }),
        bgcolor: {
          valType: "color",
          dflt: colorAttrs.background
        },
        sum: {
          valType: "number",
          dflt: 1,
          min: 0
        },
        aaxis: ternaryAxesAttrs,
        baxis: ternaryAxesAttrs,
        caxis: ternaryAxesAttrs
      }, "plot", "from-root");
      attrs.uirevision = {
        valType: "any",
        editType: "none"
      };
      attrs.aaxis.uirevision = attrs.baxis.uirevision = attrs.caxis.uirevision = {
        valType: "any",
        editType: "none"
      };
    }
  });

  // src/plots/subplot_defaults.js
  var require_subplot_defaults = __commonJS({
    "src/plots/subplot_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Template = require_plot_template();
      var handleDomainDefaults = require_domain().defaults;
      module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) {
        var subplotType = opts.type;
        var subplotAttributes = opts.attributes;
        var handleDefaults = opts.handleDefaults;
        var partition = opts.partition || "x";
        var ids = layoutOut._subplots[subplotType];
        var idsLength = ids.length;
        var baseId = idsLength && ids[0].replace(/\d+$/, "");
        var subplotLayoutIn, subplotLayoutOut;
        function coerce(attr, dflt) {
          return Lib.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt);
        }
        for (var i = 0; i < idsLength; i++) {
          var id = ids[i];
          if (layoutIn[id]) subplotLayoutIn = layoutIn[id];
          else subplotLayoutIn = layoutIn[id] = {};
          subplotLayoutOut = Template.newContainer(layoutOut, id, baseId);
          if (!opts.noUirevision) coerce("uirevision", layoutOut.uirevision);
          var dfltDomains = {};
          dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength];
          handleDomainDefaults(subplotLayoutOut, layoutOut, coerce, dfltDomains);
          opts.id = id;
          handleDefaults(subplotLayoutIn, subplotLayoutOut, coerce, opts);
        }
      };
    }
  });

  // src/plots/ternary/layout_defaults.js
  var require_layout_defaults7 = __commonJS({
    "src/plots/ternary/layout_defaults.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var Template = require_plot_template();
      var Lib = require_lib();
      var handleSubplotDefaults = require_subplot_defaults();
      var handleTickLabelDefaults = require_tick_label_defaults();
      var handlePrefixSuffixDefaults = require_prefix_suffix_defaults();
      var handleTickMarkDefaults = require_tick_mark_defaults();
      var handleTickValueDefaults = require_tick_value_defaults();
      var handleLineGridDefaults = require_line_grid_defaults();
      var layoutAttributes = require_layout_attributes8();
      var axesNames = ["aaxis", "baxis", "caxis"];
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        handleSubplotDefaults(layoutIn, layoutOut, fullData, {
          type: "ternary",
          attributes: layoutAttributes,
          handleDefaults: handleTernaryDefaults,
          font: layoutOut.font,
          paper_bgcolor: layoutOut.paper_bgcolor
        });
      };
      function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, options) {
        var bgColor = coerce("bgcolor");
        var sum = coerce("sum");
        options.bgColor = Color2.combine(bgColor, options.paper_bgcolor);
        var axName, containerIn, containerOut;
        for (var j = 0; j < axesNames.length; j++) {
          axName = axesNames[j];
          containerIn = ternaryLayoutIn[axName] || {};
          containerOut = Template.newContainer(ternaryLayoutOut, axName);
          containerOut._name = axName;
          handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut);
        }
        var aaxis = ternaryLayoutOut.aaxis;
        var baxis = ternaryLayoutOut.baxis;
        var caxis = ternaryLayoutOut.caxis;
        if (aaxis.min + baxis.min + caxis.min >= sum) {
          aaxis.min = 0;
          baxis.min = 0;
          caxis.min = 0;
          if (ternaryLayoutIn.aaxis) delete ternaryLayoutIn.aaxis.min;
          if (ternaryLayoutIn.baxis) delete ternaryLayoutIn.baxis.min;
          if (ternaryLayoutIn.caxis) delete ternaryLayoutIn.caxis.min;
        }
      }
      function handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut) {
        var axAttrs = layoutAttributes[containerOut._name];
        function coerce(attr, dflt) {
          return Lib.coerce(containerIn, containerOut, axAttrs, attr, dflt);
        }
        coerce("uirevision", ternaryLayoutOut.uirevision);
        containerOut.type = "linear";
        var dfltColor = coerce("color");
        var dfltFontColor = dfltColor !== axAttrs.color.dflt ? dfltColor : options.font.color;
        var axName = containerOut._name;
        var letterUpper = axName.charAt(0).toUpperCase();
        var dfltTitle = "Component " + letterUpper;
        var title = coerce("title.text", dfltTitle);
        containerOut._hovertitle = title === dfltTitle ? title : letterUpper;
        Lib.coerceFont(coerce, "title.font", options.font, { overrideDflt: {
          size: Lib.bigFont(options.font.size),
          color: dfltFontColor
        } });
        coerce("min");
        handleTickValueDefaults(containerIn, containerOut, coerce, "linear");
        handlePrefixSuffixDefaults(containerIn, containerOut, coerce, "linear");
        handleTickLabelDefaults(containerIn, containerOut, coerce, "linear", {
          noAutotickangles: true,
          noTicklabelshift: true,
          noTicklabelstandoff: true
        });
        handleTickMarkDefaults(
          containerIn,
          containerOut,
          coerce,
          { outerTicks: true }
        );
        var showTickLabels = coerce("showticklabels");
        if (showTickLabels) {
          Lib.coerceFont(coerce, "tickfont", options.font, { overrideDflt: {
            color: dfltFontColor
          } });
          coerce("tickangle");
          coerce("tickformat");
        }
        handleLineGridDefaults(containerIn, containerOut, coerce, {
          dfltColor,
          bgColor: options.bgColor,
          // default grid color is darker here (60%, vs cartesian default ~91%)
          // because the grid is not square so the eye needs heavier cues to follow
          blend: 60,
          showLine: true,
          showGrid: true,
          noZeroLine: true,
          attributes: axAttrs
        });
        coerce("hoverformat");
        coerce("layer");
      }
    }
  });

  // src/plots/ternary/index.js
  var require_ternary2 = __commonJS({
    "src/plots/ternary/index.js"(exports) {
      "use strict";
      var Ternary = require_ternary();
      var getSubplotCalcData = require_get_data().getSubplotCalcData;
      var counterRegex = require_lib().counterRegex;
      var TERNARY = "ternary";
      exports.name = TERNARY;
      var attr = exports.attr = "subplot";
      exports.idRoot = TERNARY;
      exports.idRegex = exports.attrRegex = counterRegex(TERNARY);
      var attributes = exports.attributes = {};
      attributes[attr] = {
        valType: "subplotid",
        dflt: "ternary",
        editType: "calc"
      };
      exports.layoutAttributes = require_layout_attributes8();
      exports.supplyLayoutDefaults = require_layout_defaults7();
      exports.plot = function plot(gd) {
        var fullLayout = gd._fullLayout;
        var calcData = gd.calcdata;
        var ternaryIds = fullLayout._subplots[TERNARY];
        for (var i = 0; i < ternaryIds.length; i++) {
          var ternaryId = ternaryIds[i];
          var ternaryCalcData = getSubplotCalcData(calcData, TERNARY, ternaryId);
          var ternary = fullLayout[ternaryId]._subplot;
          if (!ternary) {
            ternary = new Ternary(
              {
                id: ternaryId,
                graphDiv: gd,
                container: fullLayout._ternarylayer.node()
              },
              fullLayout
            );
            fullLayout[ternaryId]._subplot = ternary;
          }
          ternary.plot(ternaryCalcData, fullLayout, gd._promises);
        }
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || [];
        for (var i = 0; i < oldTernaryKeys.length; i++) {
          var oldTernaryKey = oldTernaryKeys[i];
          var oldTernary = oldFullLayout[oldTernaryKey]._subplot;
          if (!newFullLayout[oldTernaryKey] && !!oldTernary) {
            oldTernary.plotContainer.remove();
            oldTernary.clipDef.remove();
            oldTernary.clipDefRelative.remove();
            oldTernary.layers["a-title"].remove();
            oldTernary.layers["b-title"].remove();
            oldTernary.layers["c-title"].remove();
          }
        }
      };
      exports.updateFx = function(gd) {
        var fullLayout = gd._fullLayout;
        fullLayout._ternarylayer.selectAll("g.toplevel").style("cursor", fullLayout.dragmode === "pan" ? "move" : "crosshair");
      };
    }
  });

  // src/traces/scatterternary/index.js
  var require_scatterternary = __commonJS({
    "src/traces/scatterternary/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes30(),
        supplyDefaults: require_defaults26(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels2(),
        calc: require_calc11(),
        plot: require_plot7(),
        style: require_style2().style,
        styleOnSelect: require_style2().styleOnSelect,
        hoverPoints: require_hover9(),
        selectPoints: require_select2(),
        eventData: require_event_data4(),
        moduleType: "trace",
        name: "scatterternary",
        basePlotModule: require_ternary2(),
        categories: ["ternary", "symbols", "showLegend", "scatter-like"],
        meta: {}
      };
    }
  });

  // lib/scatterternary.js
  var require_scatterternary2 = __commonJS({
    "lib/scatterternary.js"(exports, module) {
      "use strict";
      module.exports = require_scatterternary();
    }
  });

  // src/traces/violin/attributes.js
  var require_attributes31 = __commonJS({
    "src/traces/violin/attributes.js"(exports, module) {
      "use strict";
      var boxAttrs = require_attributes24();
      var extendFlat = require_extend().extendFlat;
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      module.exports = {
        y: boxAttrs.y,
        x: boxAttrs.x,
        x0: boxAttrs.x0,
        y0: boxAttrs.y0,
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        name: extendFlat({}, boxAttrs.name, {}),
        orientation: extendFlat({}, boxAttrs.orientation, {}),
        bandwidth: {
          valType: "number",
          min: 0,
          editType: "calc"
        },
        scalegroup: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        scalemode: {
          valType: "enumerated",
          values: ["width", "count"],
          dflt: "width",
          editType: "calc"
        },
        spanmode: {
          valType: "enumerated",
          values: ["soft", "hard", "manual"],
          dflt: "soft",
          editType: "calc"
        },
        span: {
          valType: "info_array",
          items: [
            { valType: "any", editType: "calc" },
            { valType: "any", editType: "calc" }
          ],
          editType: "calc"
        },
        line: {
          color: {
            valType: "color",
            editType: "style"
          },
          width: {
            valType: "number",
            min: 0,
            dflt: 2,
            editType: "style"
          },
          editType: "plot"
        },
        fillcolor: boxAttrs.fillcolor,
        points: extendFlat({}, boxAttrs.boxpoints, {}),
        jitter: extendFlat({}, boxAttrs.jitter, {}),
        pointpos: extendFlat({}, boxAttrs.pointpos, {}),
        width: extendFlat({}, boxAttrs.width, {}),
        marker: boxAttrs.marker,
        text: boxAttrs.text,
        hovertext: boxAttrs.hovertext,
        hovertemplate: boxAttrs.hovertemplate,
        hovertemplatefallback: boxAttrs.hovertemplatefallback,
        quartilemethod: boxAttrs.quartilemethod,
        box: {
          visible: {
            valType: "boolean",
            dflt: false,
            editType: "plot"
          },
          width: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 0.25,
            editType: "plot"
          },
          fillcolor: {
            valType: "color",
            editType: "style"
          },
          line: {
            color: {
              valType: "color",
              editType: "style"
            },
            width: {
              valType: "number",
              min: 0,
              editType: "style"
            },
            editType: "style"
          },
          editType: "plot"
        },
        meanline: {
          visible: {
            valType: "boolean",
            dflt: false,
            editType: "plot"
          },
          color: {
            valType: "color",
            editType: "style"
          },
          width: {
            valType: "number",
            min: 0,
            editType: "style"
          },
          editType: "plot"
        },
        side: {
          valType: "enumerated",
          values: ["both", "positive", "negative"],
          dflt: "both",
          editType: "calc"
        },
        offsetgroup: boxAttrs.offsetgroup,
        alignmentgroup: boxAttrs.alignmentgroup,
        selected: boxAttrs.selected,
        unselected: boxAttrs.unselected,
        hoveron: {
          valType: "flaglist",
          flags: ["violins", "points", "kde"],
          dflt: "violins+points+kde",
          extras: ["all"],
          editType: "style"
        },
        zorder: boxAttrs.zorder
      };
    }
  });

  // src/traces/violin/layout_attributes.js
  var require_layout_attributes9 = __commonJS({
    "src/traces/violin/layout_attributes.js"(exports, module) {
      "use strict";
      var boxLayoutAttrs = require_layout_attributes7();
      var extendFlat = require_lib().extendFlat;
      module.exports = {
        violinmode: extendFlat({}, boxLayoutAttrs.boxmode, {}),
        violingap: extendFlat({}, boxLayoutAttrs.boxgap, {}),
        violingroupgap: extendFlat({}, boxLayoutAttrs.boxgroupgap, {})
      };
    }
  });

  // src/traces/violin/defaults.js
  var require_defaults27 = __commonJS({
    "src/traces/violin/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var boxDefaults = require_defaults20();
      var attributes = require_attributes31();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        function coerce2(attr, dflt) {
          return Lib.coerce2(traceIn, traceOut, attributes, attr, dflt);
        }
        boxDefaults.handleSampleDefaults(traceIn, traceOut, coerce, layout);
        if (traceOut.visible === false) return;
        coerce("bandwidth");
        coerce("side");
        var width = coerce("width");
        if (!width) {
          coerce("scalegroup", traceOut.name);
          coerce("scalemode");
        }
        var span = coerce("span");
        var spanmodeDflt;
        if (Array.isArray(span)) spanmodeDflt = "manual";
        coerce("spanmode", spanmodeDflt);
        var lineColor = coerce("line.color", (traceIn.marker || {}).color || defaultColor);
        var lineWidth = coerce("line.width");
        var fillColor = coerce("fillcolor", Color2.addOpacity(traceOut.line.color, 0.5));
        boxDefaults.handlePointsDefaults(traceIn, traceOut, coerce, { prefix: "" });
        var boxWidth = coerce2("box.width");
        var boxFillColor = coerce2("box.fillcolor", fillColor);
        var boxLineColor = coerce2("box.line.color", lineColor);
        var boxLineWidth = coerce2("box.line.width", lineWidth);
        var boxVisible = coerce("box.visible", Boolean(boxWidth || boxFillColor || boxLineColor || boxLineWidth));
        if (!boxVisible) traceOut.box = { visible: false };
        var meanLineColor = coerce2("meanline.color", lineColor);
        var meanLineWidth = coerce2("meanline.width", lineWidth);
        var meanLineVisible = coerce("meanline.visible", Boolean(meanLineColor || meanLineWidth));
        if (!meanLineVisible) traceOut.meanline = { visible: false };
        coerce("quartilemethod");
        coerce("zorder");
      };
    }
  });

  // src/traces/violin/layout_defaults.js
  var require_layout_defaults8 = __commonJS({
    "src/traces/violin/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes9();
      var boxLayoutDefaults = require_layout_defaults6();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        boxLayoutDefaults._supply(layoutIn, layoutOut, fullData, coerce, "violin");
      };
    }
  });

  // src/traces/violin/helpers.js
  var require_helpers13 = __commonJS({
    "src/traces/violin/helpers.js"(exports) {
      "use strict";
      var Lib = require_lib();
      var kernels = {
        gaussian: function(v) {
          return 1 / Math.sqrt(2 * Math.PI) * Math.exp(-0.5 * v * v);
        }
      };
      exports.makeKDE = function(calcItem, trace, vals) {
        var len = vals.length;
        var kernel = kernels.gaussian;
        var bandwidth = calcItem.bandwidth;
        var factor = 1 / (len * bandwidth);
        return function(x) {
          var sum = 0;
          for (var i = 0; i < len; i++) {
            sum += kernel((x - vals[i]) / bandwidth);
          }
          return factor * sum;
        };
      };
      exports.getPositionOnKdePath = function(calcItem, trace, valuePx) {
        var posLetter, valLetter;
        if (trace.orientation === "h") {
          posLetter = "y";
          valLetter = "x";
        } else {
          posLetter = "x";
          valLetter = "y";
        }
        var pointOnPath = Lib.findPointOnPath(
          calcItem.path,
          valuePx,
          valLetter,
          { pathLength: calcItem.pathLength }
        );
        var posCenterPx = calcItem.posCenterPx;
        var posOnPath0 = pointOnPath[posLetter];
        var posOnPath1 = trace.side === "both" ? 2 * posCenterPx - posOnPath0 : posCenterPx;
        return [posOnPath0, posOnPath1];
      };
      exports.getKdeValue = function(calcItem, trace, valueDist) {
        var vals = calcItem.pts.map(exports.extractVal);
        var kde = exports.makeKDE(calcItem, trace, vals);
        return kde(valueDist) / calcItem.posDensityScale;
      };
      exports.extractVal = function(o) {
        return o.v;
      };
    }
  });

  // src/traces/violin/calc.js
  var require_calc12 = __commonJS({
    "src/traces/violin/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var boxCalc = require_calc6();
      var helpers = require_helpers13();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function calc(gd, trace) {
        var cd = boxCalc(gd, trace);
        if (cd[0].t.empty) return cd;
        var fullLayout = gd._fullLayout;
        var valAxis = Axes.getFromId(
          gd,
          trace[trace.orientation === "h" ? "xaxis" : "yaxis"]
        );
        var spanMin = Infinity;
        var spanMax = -Infinity;
        var maxKDE = 0;
        var maxCount = 0;
        for (var i = 0; i < cd.length; i++) {
          var cdi = cd[i];
          var vals = cdi.pts.map(helpers.extractVal);
          var bandwidth = cdi.bandwidth = calcBandwidth(trace, cdi, vals);
          var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth);
          if (cdi.min === cdi.max && bandwidth === 0) {
            span = cdi.span = [cdi.min, cdi.max];
            cdi.density = [{ v: 1, t: span[0] }];
            cdi.bandwidth = bandwidth;
            maxKDE = Math.max(maxKDE, 1);
          } else {
            var dist = span[1] - span[0];
            var n = Math.ceil(dist / (bandwidth / 3));
            var step = dist / n;
            if (!isFinite(step) || !isFinite(n)) {
              Lib.error("Something went wrong with computing the violin span");
              cd[0].t.empty = true;
              return cd;
            }
            var kde = helpers.makeKDE(cdi, trace, vals);
            cdi.density = new Array(n + 1);
            for (var k = 0; k < cdi.density.length; k++) {
              var t = span[0] + k * step;
              var v = kde(t);
              cdi.density[k] = { v, t };
              maxKDE = Math.max(maxKDE, v);
            }
          }
          maxCount = Math.max(maxCount, vals.length);
          spanMin = Math.min(spanMin, span[0]);
          spanMax = Math.max(spanMax, span[1]);
        }
        var extremes = Axes.findExtremes(valAxis, [spanMin, spanMax], { padded: true });
        trace._extremes[valAxis._id] = extremes;
        if (trace.width) {
          cd[0].t.maxKDE = maxKDE;
        } else {
          var violinScaleGroupStats = fullLayout._violinScaleGroupStats;
          var scaleGroup = trace.scalegroup;
          var groupStats = violinScaleGroupStats[scaleGroup];
          if (groupStats) {
            groupStats.maxKDE = Math.max(groupStats.maxKDE, maxKDE);
            groupStats.maxCount = Math.max(groupStats.maxCount, maxCount);
          } else {
            violinScaleGroupStats[scaleGroup] = {
              maxKDE,
              maxCount
            };
          }
        }
        cd[0].t.labels.kde = Lib._(gd, "kde:");
        return cd;
      };
      function silvermanRule(len, ssd, iqr) {
        var a = Math.min(ssd, iqr / 1.349);
        return 1.059 * a * Math.pow(len, -0.2);
      }
      function calcBandwidth(trace, cdi, vals) {
        var span = cdi.max - cdi.min;
        if (!span) {
          if (trace.bandwidth) {
            return trace.bandwidth;
          } else {
            return 0;
          }
        }
        if (trace.bandwidth) {
          return Math.max(trace.bandwidth, span / 1e4);
        } else {
          var len = vals.length;
          var ssd = Lib.stdev(vals, len - 1, cdi.mean);
          return Math.max(
            silvermanRule(len, ssd, cdi.q3 - cdi.q1),
            span / 100
          );
        }
      }
      function calcSpan(trace, cdi, valAxis, bandwidth) {
        var spanmode = trace.spanmode;
        var spanIn = trace.span || [];
        var spanTight = [cdi.min, cdi.max];
        var spanLoose = [cdi.min - 2 * bandwidth, cdi.max + 2 * bandwidth];
        var spanOut;
        function calcSpanItem(index) {
          var s = spanIn[index];
          var sc = valAxis.type === "multicategory" ? valAxis.r2c(s) : valAxis.d2c(s, 0, trace[cdi.valLetter + "calendar"]);
          return sc === BADNUM ? spanLoose[index] : sc;
        }
        if (spanmode === "soft") {
          spanOut = spanLoose;
        } else if (spanmode === "hard") {
          spanOut = spanTight;
        } else {
          spanOut = [calcSpanItem(0), calcSpanItem(1)];
        }
        var dummyAx = {
          type: "linear",
          range: spanOut
        };
        Axes.setConvert(dummyAx);
        dummyAx.cleanRange();
        return spanOut;
      }
    }
  });

  // src/traces/violin/cross_trace_calc.js
  var require_cross_trace_calc4 = __commonJS({
    "src/traces/violin/cross_trace_calc.js"(exports, module) {
      "use strict";
      var setPositionOffset = require_cross_trace_calc3().setPositionOffset;
      var orientations = ["v", "h"];
      module.exports = function crossTraceCalc(gd, plotinfo) {
        var calcdata = gd.calcdata;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        for (var i = 0; i < orientations.length; i++) {
          var orientation = orientations[i];
          var posAxis = orientation === "h" ? ya : xa;
          var violinList = [];
          for (var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var t = cd[0].t;
            var trace = cd[0].trace;
            if (trace.visible === true && trace.type === "violin" && !t.empty && trace.orientation === orientation && trace.xaxis === xa._id && trace.yaxis === ya._id) {
              violinList.push(j);
            }
          }
          setPositionOffset("violin", gd, violinList, posAxis);
        }
      };
    }
  });

  // src/traces/violin/plot.js
  var require_plot8 = __commonJS({
    "src/traces/violin/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var boxPlot = require_plot4();
      var linePoints = require_line_points();
      var helpers = require_helpers13();
      module.exports = function plot(gd, plotinfo, cdViolins, violinLayer) {
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        function makePath(pts, trace) {
          var segments = linePoints(pts, {
            xaxis: xa,
            yaxis: ya,
            trace,
            connectGaps: true,
            baseTolerance: 0.75,
            shape: "spline",
            simplify: true,
            linearized: true
          });
          return Drawing.smoothopen(segments[0], 1);
        }
        Lib.makeTraceGroups(violinLayer, cdViolins, "trace violins").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var t = cd0.t;
          var trace = cd0.trace;
          if (trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
          }
          var bPos = t.bPos;
          var bdPos = t.bdPos;
          var valAxis = plotinfo[t.valLetter + "axis"];
          var posAxis = plotinfo[t.posLetter + "axis"];
          var hasBothSides = trace.side === "both";
          var hasPositiveSide = hasBothSides || trace.side === "positive";
          var hasNegativeSide = hasBothSides || trace.side === "negative";
          var violins = plotGroup.selectAll("path.violin").data(Lib.identity);
          violins.enter().append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").attr("class", "violin");
          violins.exit().remove();
          violins.each(function(d) {
            var pathSel = d3.select(this);
            var density = d.density;
            var len = density.length;
            var posCenter = posAxis.c2l(d.pos + bPos, true);
            var posCenterPx = posAxis.l2p(posCenter);
            var scale;
            if (trace.width) {
              scale = t.maxKDE / bdPos;
            } else {
              var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup];
              scale = trace.scalemode === "count" ? groupStats.maxKDE / bdPos * (groupStats.maxCount / d.pts.length) : groupStats.maxKDE / bdPos;
            }
            var pathPos, pathNeg, path;
            var i, k, pts, pt;
            if (hasPositiveSide) {
              pts = new Array(len);
              for (i = 0; i < len; i++) {
                pt = pts[i] = {};
                pt[t.posLetter] = posCenter + density[i].v / scale;
                pt[t.valLetter] = valAxis.c2l(density[i].t, true);
              }
              pathPos = makePath(pts, trace);
            }
            if (hasNegativeSide) {
              pts = new Array(len);
              for (k = 0, i = len - 1; k < len; k++, i--) {
                pt = pts[k] = {};
                pt[t.posLetter] = posCenter - density[i].v / scale;
                pt[t.valLetter] = valAxis.c2l(density[i].t, true);
              }
              pathNeg = makePath(pts, trace);
            }
            if (hasBothSides) {
              path = pathPos + "L" + pathNeg.slice(1) + "Z";
            } else {
              var startPt = [posCenterPx, valAxis.c2p(density[0].t)];
              var endPt = [posCenterPx, valAxis.c2p(density[len - 1].t)];
              if (trace.orientation === "h") {
                startPt.reverse();
                endPt.reverse();
              }
              if (hasPositiveSide) {
                path = "M" + startPt + "L" + pathPos.slice(1) + "L" + endPt;
              } else {
                path = "M" + endPt + "L" + pathNeg.slice(1) + "L" + startPt;
              }
            }
            pathSel.attr("d", path);
            d.posCenterPx = posCenterPx;
            d.posDensityScale = scale * bdPos;
            d.path = pathSel.node();
            d.pathLength = d.path.getTotalLength() / (hasBothSides ? 2 : 1);
          });
          var boxAttrs = trace.box;
          var boxWidth = boxAttrs.width;
          var boxLineWidth = (boxAttrs.line || {}).width;
          var bdPosScaled;
          var bPosPxOffset;
          if (hasBothSides) {
            bdPosScaled = bdPos * boxWidth;
            bPosPxOffset = 0;
          } else if (hasPositiveSide) {
            bdPosScaled = [0, bdPos * boxWidth / 2];
            bPosPxOffset = boxLineWidth * { x: 1, y: -1 }[t.posLetter];
          } else {
            bdPosScaled = [bdPos * boxWidth / 2, 0];
            bPosPxOffset = boxLineWidth * { x: -1, y: 1 }[t.posLetter];
          }
          boxPlot.plotBoxAndWhiskers(plotGroup, { pos: posAxis, val: valAxis }, trace, {
            bPos,
            bdPos: bdPosScaled,
            bPosPxOffset
          });
          boxPlot.plotBoxMean(plotGroup, { pos: posAxis, val: valAxis }, trace, {
            bPos,
            bdPos: bdPosScaled,
            bPosPxOffset
          });
          var fn;
          if (!trace.box.visible && trace.meanline.visible) {
            fn = Lib.identity;
          }
          var meanPaths = plotGroup.selectAll("path.meanline").data(fn || []);
          meanPaths.enter().append("path").attr("class", "meanline").style("fill", "none").style("vector-effect", isStatic ? "none" : "non-scaling-stroke");
          meanPaths.exit().remove();
          meanPaths.each(function(d) {
            var v = valAxis.c2p(d.mean, true);
            var p = helpers.getPositionOnKdePath(d, trace, v);
            d3.select(this).attr(
              "d",
              trace.orientation === "h" ? "M" + v + "," + p[0] + "V" + p[1] : "M" + p[0] + "," + v + "H" + p[1]
            );
          });
          boxPlot.plotPoints(plotGroup, { x: xa, y: ya }, trace, t);
        });
      };
    }
  });

  // src/traces/violin/style.js
  var require_style8 = __commonJS({
    "src/traces/violin/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var stylePoints = require_style2().stylePoints;
      module.exports = function style(gd) {
        var s = d3.select(gd).selectAll("g.trace.violins");
        s.style("opacity", function(d) {
          return d[0].trace.opacity;
        });
        s.each(function(d) {
          var trace = d[0].trace;
          var sel = d3.select(this);
          var box = trace.box || {};
          var boxLine = box.line || {};
          var meanline = trace.meanline || {};
          var meanLineWidth = meanline.width;
          sel.selectAll("path.violin").style("stroke-width", trace.line.width + "px").call(Color2.stroke, trace.line.color).call(Color2.fill, trace.fillcolor);
          sel.selectAll("path.box").style("stroke-width", boxLine.width + "px").call(Color2.stroke, boxLine.color).call(Color2.fill, box.fillcolor);
          var meanLineStyle = {
            "stroke-width": meanLineWidth + "px",
            "stroke-dasharray": 2 * meanLineWidth + "px," + meanLineWidth + "px"
          };
          sel.selectAll("path.mean").style(meanLineStyle).call(Color2.stroke, meanline.color);
          sel.selectAll("path.meanline").style(meanLineStyle).call(Color2.stroke, meanline.color);
          stylePoints(sel, trace, gd);
        });
      };
    }
  });

  // src/traces/violin/hover.js
  var require_hover10 = __commonJS({
    "src/traces/violin/hover.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var Lib = require_lib();
      var Axes = require_axes();
      var boxHoverPoints = require_hover4();
      var helpers = require_helpers13();
      module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
        if (!opts) opts = {};
        var hoverLayer = opts.hoverLayer;
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var hoveron = trace.hoveron;
        var hasHoveronViolins = hoveron.indexOf("violins") !== -1;
        var hasHoveronKDE = hoveron.indexOf("kde") !== -1;
        var closeData = [];
        var closePtData;
        var violinLineAttrs;
        if (hasHoveronViolins || hasHoveronKDE) {
          var closeBoxData = boxHoverPoints.hoverOnBoxes(pointData, xval, yval, hovermode);
          if (hasHoveronKDE && closeBoxData.length > 0) {
            var xa = pointData.xa;
            var ya = pointData.ya;
            var pLetter, vLetter, pAxis, vAxis, vVal;
            if (trace.orientation === "h") {
              vVal = xval;
              pLetter = "y";
              pAxis = ya;
              vLetter = "x";
              vAxis = xa;
            } else {
              vVal = yval;
              pLetter = "x";
              pAxis = xa;
              vLetter = "y";
              vAxis = ya;
            }
            var di = cd[pointData.index];
            if (vVal >= di.span[0] && vVal <= di.span[1]) {
              var kdePointData = Lib.extendFlat({}, pointData);
              var vValPx = vAxis.c2p(vVal, true);
              var kdeVal = helpers.getKdeValue(di, trace, vVal);
              var pOnPath = helpers.getPositionOnKdePath(di, trace, vValPx);
              var paOffset = pAxis._offset;
              var paLength = pAxis._length;
              kdePointData[pLetter + "0"] = pOnPath[0];
              kdePointData[pLetter + "1"] = pOnPath[1];
              kdePointData[vLetter + "0"] = kdePointData[vLetter + "1"] = vValPx;
              kdePointData[vLetter + "Label"] = vLetter + ": " + Axes.hoverLabelText(vAxis, vVal, trace[vLetter + "hoverformat"]) + ", " + cd[0].t.labels.kde + " " + kdeVal.toFixed(3);
              var medId = 0;
              for (var k = 0; k < closeBoxData.length; k++) {
                if (closeBoxData[k].attr === "med") {
                  medId = k;
                  break;
                }
              }
              kdePointData.spikeDistance = closeBoxData[medId].spikeDistance;
              var spikePosAttr = pLetter + "Spike";
              kdePointData[spikePosAttr] = closeBoxData[medId][spikePosAttr];
              closeBoxData[medId].spikeDistance = void 0;
              closeBoxData[medId][spikePosAttr] = void 0;
              kdePointData.hovertemplate = false;
              closeData.push(kdePointData);
              violinLineAttrs = {};
              violinLineAttrs[pLetter + "1"] = Lib.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength);
              violinLineAttrs[pLetter + "2"] = Lib.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength);
              violinLineAttrs[vLetter + "1"] = violinLineAttrs[vLetter + "2"] = vAxis._offset + vValPx;
            }
          }
          if (hasHoveronViolins) {
            closeData = closeData.concat(closeBoxData);
          }
        }
        if (hoveron.indexOf("points") !== -1) {
          closePtData = boxHoverPoints.hoverOnPoints(pointData, xval, yval);
        }
        var violinLine = hoverLayer.selectAll(".violinline-" + trace.uid).data(violinLineAttrs ? [0] : []);
        violinLine.enter().append("line").classed("violinline-" + trace.uid, true).attr("stroke-width", 1.5);
        violinLine.exit().remove();
        violinLine.attr(violinLineAttrs).call(Color2.stroke, pointData.color);
        if (hovermode === "closest") {
          if (closePtData) return [closePtData];
          return closeData;
        }
        if (closePtData) {
          closeData.push(closePtData);
          return closeData;
        }
        return closeData;
      };
    }
  });

  // src/traces/violin/index.js
  var require_violin = __commonJS({
    "src/traces/violin/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes31(),
        layoutAttributes: require_layout_attributes9(),
        supplyDefaults: require_defaults27(),
        crossTraceDefaults: require_defaults20().crossTraceDefaults,
        supplyLayoutDefaults: require_layout_defaults8(),
        calc: require_calc12(),
        crossTraceCalc: require_cross_trace_calc4(),
        plot: require_plot8(),
        style: require_style8(),
        styleOnSelect: require_style2().styleOnSelect,
        hoverPoints: require_hover10(),
        selectPoints: require_select4(),
        moduleType: "trace",
        name: "violin",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "symbols", "oriented", "box-violin", "showLegend", "violinLayout", "zoomScale"],
        meta: {}
      };
    }
  });

  // lib/violin.js
  var require_violin2 = __commonJS({
    "lib/violin.js"(exports, module) {
      "use strict";
      module.exports = require_violin();
    }
  });

  // src/traces/funnel/constants.js
  var require_constants17 = __commonJS({
    "src/traces/funnel/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        eventDataKeys: [
          "percentInitial",
          "percentPrevious",
          "percentTotal"
        ]
      };
    }
  });

  // src/traces/funnel/attributes.js
  var require_attributes32 = __commonJS({
    "src/traces/funnel/attributes.js"(exports, module) {
      "use strict";
      var barAttrs = require_attributes23();
      var lineAttrs = require_attributes12().line;
      var baseAttrs = require_attributes2();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var constants = require_constants17();
      var extendFlat = require_extend().extendFlat;
      var Color2 = require_color();
      module.exports = {
        x: barAttrs.x,
        x0: barAttrs.x0,
        dx: barAttrs.dx,
        y: barAttrs.y,
        y0: barAttrs.y0,
        dy: barAttrs.dy,
        xperiod: barAttrs.xperiod,
        yperiod: barAttrs.yperiod,
        xperiod0: barAttrs.xperiod0,
        yperiod0: barAttrs.yperiod0,
        xperiodalignment: barAttrs.xperiodalignment,
        yperiodalignment: barAttrs.yperiodalignment,
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        hovertext: barAttrs.hovertext,
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["name", "x", "y", "text", "percent initial", "percent previous", "percent total"]
        }),
        textinfo: {
          valType: "flaglist",
          flags: ["label", "text", "percent initial", "percent previous", "percent total", "value"],
          extras: ["none"],
          editType: "plot",
          arrayOk: false
        },
        // TODO: incorporate `label` and `value` in the eventData
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: constants.eventDataKeys.concat(["label", "value"]) }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        text: barAttrs.text,
        textposition: barAttrs.textposition,
        insidetextanchor: extendFlat({}, barAttrs.insidetextanchor, { dflt: "middle" }),
        textangle: extendFlat({}, barAttrs.textangle, { dflt: 0 }),
        textfont: barAttrs.textfont,
        insidetextfont: barAttrs.insidetextfont,
        outsidetextfont: barAttrs.outsidetextfont,
        constraintext: barAttrs.constraintext,
        cliponaxis: barAttrs.cliponaxis,
        orientation: extendFlat({}, barAttrs.orientation, {}),
        offset: extendFlat({}, barAttrs.offset, { arrayOk: false }),
        width: extendFlat({}, barAttrs.width, { arrayOk: false }),
        marker: funnelMarker(),
        connector: {
          fillcolor: {
            valType: "color",
            editType: "style"
          },
          line: {
            color: extendFlat({}, lineAttrs.color, { dflt: Color2.defaultLine }),
            width: extendFlat({}, lineAttrs.width, {
              dflt: 0,
              editType: "plot"
            }),
            dash: lineAttrs.dash,
            editType: "style"
          },
          visible: {
            valType: "boolean",
            dflt: true,
            editType: "plot"
          },
          editType: "plot"
        },
        offsetgroup: barAttrs.offsetgroup,
        alignmentgroup: barAttrs.alignmentgroup,
        zorder: barAttrs.zorder
      };
      function funnelMarker() {
        var marker = extendFlat({}, barAttrs.marker);
        delete marker.pattern;
        delete marker.cornerradius;
        return marker;
      }
    }
  });

  // src/traces/funnel/layout_attributes.js
  var require_layout_attributes10 = __commonJS({
    "src/traces/funnel/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        funnelmode: {
          valType: "enumerated",
          values: ["stack", "group", "overlay"],
          dflt: "stack",
          editType: "calc"
        },
        funnelgap: {
          valType: "number",
          min: 0,
          max: 1,
          editType: "calc"
        },
        funnelgroupgap: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/funnel/defaults.js
  var require_defaults28 = __commonJS({
    "src/traces/funnel/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleGroupingDefaults = require_grouping_defaults();
      var handleText = require_defaults19().handleText;
      var handleXYDefaults = require_xy_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var attributes = require_attributes32();
      var Color2 = require_color();
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("orientation", traceOut.y && !traceOut.x ? "v" : "h");
        coerce("offset");
        coerce("width");
        var text = coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var textposition = coerce("textposition");
        handleText(traceIn, traceOut, layout, coerce, textposition, {
          moduleHasSelected: false,
          moduleHasUnselected: false,
          moduleHasConstrain: true,
          moduleHasCliponaxis: true,
          moduleHasTextangle: true,
          moduleHasInsideanchor: true
        });
        if (traceOut.textposition !== "none" && !traceOut.texttemplate) {
          coerce("textinfo", Lib.isArrayOrTypedArray(text) ? "text+value" : "value");
        }
        var markerColor = coerce("marker.color", defaultColor);
        coerce("marker.line.color", Color2.defaultLine);
        coerce("marker.line.width");
        var connectorVisible = coerce("connector.visible");
        if (connectorVisible) {
          coerce("connector.fillcolor", defaultFillColor(markerColor));
          var connectorLineWidth = coerce("connector.line.width");
          if (connectorLineWidth) {
            coerce("connector.line.color");
            coerce("connector.line.dash");
          }
        }
        coerce("zorder");
      }
      function defaultFillColor(markerColor) {
        var cBase = Lib.isArrayOrTypedArray(markerColor) ? "#000" : markerColor;
        return Color2.addOpacity(cBase, 0.5 * Color2.opacity(cBase));
      }
      function crossTraceDefaults(fullData, fullLayout) {
        var traceIn, traceOut;
        function coerce(attr) {
          return Lib.coerce(traceOut._input, traceOut, attributes, attr);
        }
        for (var i = 0; i < fullData.length; i++) {
          traceOut = fullData[i];
          if (traceOut.type === "funnel") {
            traceIn = traceOut._input;
            handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce, fullLayout.funnelmode);
          }
        }
      }
      module.exports = {
        supplyDefaults,
        crossTraceDefaults
      };
    }
  });

  // src/traces/funnel/layout_defaults.js
  var require_layout_defaults9 = __commonJS({
    "src/traces/funnel/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes10();
      module.exports = function(layoutIn, layoutOut, fullData) {
        var hasTraceType = false;
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        for (var i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          if (trace.visible && trace.type === "funnel") {
            hasTraceType = true;
            break;
          }
        }
        if (hasTraceType) {
          coerce("funnelmode");
          coerce("funnelgap", 0.2);
          coerce("funnelgroupgap");
        }
      };
    }
  });

  // src/traces/funnel/arrays_to_calcdata.js
  var require_arrays_to_calcdata3 = __commonJS({
    "src/traces/funnel/arrays_to_calcdata.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function arraysToCalcdata(cd, trace) {
        for (var i = 0; i < cd.length; i++) cd[i].i = i;
        Lib.mergeArray(trace.text, cd, "tx");
        Lib.mergeArray(trace.hovertext, cd, "htx");
        var marker = trace.marker;
        if (marker) {
          Lib.mergeArray(marker.opacity, cd, "mo");
          Lib.mergeArray(marker.color, cd, "mc");
          var markerLine = marker.line;
          if (markerLine) {
            Lib.mergeArray(markerLine.color, cd, "mlc");
            Lib.mergeArrayCastPositive(markerLine.width, cd, "mlw");
          }
        }
      };
    }
  });

  // src/traces/funnel/calc.js
  var require_calc13 = __commonJS({
    "src/traces/funnel/calc.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var arraysToCalcdata = require_arrays_to_calcdata3();
      var calcSelection = require_calc_selection();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function calc(gd, trace) {
        var xa = Axes.getFromId(gd, trace.xaxis || "x");
        var ya = Axes.getFromId(gd, trace.yaxis || "y");
        var size, pos, origPos, pObj, hasPeriod, pLetter, i, cdi;
        if (trace.orientation === "h") {
          size = xa.makeCalcdata(trace, "x");
          origPos = ya.makeCalcdata(trace, "y");
          pObj = alignPeriod(trace, ya, "y", origPos);
          hasPeriod = !!trace.yperiodalignment;
          pLetter = "y";
        } else {
          size = ya.makeCalcdata(trace, "y");
          origPos = xa.makeCalcdata(trace, "x");
          pObj = alignPeriod(trace, xa, "x", origPos);
          hasPeriod = !!trace.xperiodalignment;
          pLetter = "x";
        }
        pos = pObj.vals;
        var serieslen = Math.min(pos.length, size.length);
        var cd = new Array(serieslen);
        trace._base = [];
        for (i = 0; i < serieslen; i++) {
          if (size[i] < 0) size[i] = BADNUM;
          var connectToNext = false;
          if (size[i] !== BADNUM) {
            if (i + 1 < serieslen && size[i + 1] !== BADNUM) {
              connectToNext = true;
            }
          }
          cdi = cd[i] = {
            p: pos[i],
            s: size[i],
            cNext: connectToNext
          };
          trace._base[i] = -0.5 * cdi.s;
          if (hasPeriod) {
            cd[i].orig_p = origPos[i];
            cd[i][pLetter + "End"] = pObj.ends[i];
            cd[i][pLetter + "Start"] = pObj.starts[i];
          }
          if (trace.ids) {
            cdi.id = String(trace.ids[i]);
          }
          if (i === 0) cd[0].vTotal = 0;
          cd[0].vTotal += fixNum(cdi.s);
          cdi.begR = fixNum(cdi.s) / fixNum(cd[0].s);
        }
        var prevGoodNum;
        for (i = 0; i < serieslen; i++) {
          cdi = cd[i];
          if (cdi.s === BADNUM) continue;
          cdi.sumR = cdi.s / cd[0].vTotal;
          cdi.difR = prevGoodNum !== void 0 ? cdi.s / prevGoodNum : 1;
          prevGoodNum = cdi.s;
        }
        arraysToCalcdata(cd, trace);
        calcSelection(cd, trace);
        return cd;
      };
      function fixNum(a) {
        return a === BADNUM ? 0 : a;
      }
    }
  });

  // src/traces/funnel/cross_trace_calc.js
  var require_cross_trace_calc5 = __commonJS({
    "src/traces/funnel/cross_trace_calc.js"(exports, module) {
      "use strict";
      var setGroupPositions = require_cross_trace_calc().setGroupPositions;
      module.exports = function crossTraceCalc(gd, plotinfo) {
        var fullLayout = gd._fullLayout;
        var fullData = gd._fullData;
        var calcdata = gd.calcdata;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var funnels = [];
        var funnelsVert = [];
        var funnelsHorz = [];
        var cd, i;
        for (i = 0; i < fullData.length; i++) {
          var fullTrace = fullData[i];
          var isHorizontal = fullTrace.orientation === "h";
          if (fullTrace.visible === true && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id && fullTrace.type === "funnel") {
            cd = calcdata[i];
            if (isHorizontal) {
              funnelsHorz.push(cd);
            } else {
              funnelsVert.push(cd);
            }
            funnels.push(cd);
          }
        }
        var opts = {
          mode: fullLayout.funnelmode,
          norm: fullLayout.funnelnorm,
          gap: fullLayout.funnelgap,
          groupgap: fullLayout.funnelgroupgap
        };
        setGroupPositions(gd, xa, ya, funnelsVert, opts);
        setGroupPositions(gd, ya, xa, funnelsHorz, opts);
        for (i = 0; i < funnels.length; i++) {
          cd = funnels[i];
          for (var j = 0; j < cd.length; j++) {
            if (j + 1 < cd.length) {
              cd[j].nextP0 = cd[j + 1].p0;
              cd[j].nextS0 = cd[j + 1].s0;
              cd[j].nextP1 = cd[j + 1].p1;
              cd[j].nextS1 = cd[j + 1].s1;
            }
          }
        }
      };
    }
  });

  // src/traces/funnel/plot.js
  var require_plot9 = __commonJS({
    "src/traces/funnel/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var BADNUM = require_numerical().BADNUM;
      var barPlot = require_plot3();
      var clearMinTextSize = require_uniform_text().clearMinTextSize;
      module.exports = function plot(gd, plotinfo, cdModule, traceLayer) {
        var fullLayout = gd._fullLayout;
        clearMinTextSize("funnel", fullLayout);
        plotConnectorRegions(gd, plotinfo, cdModule, traceLayer);
        plotConnectorLines(gd, plotinfo, cdModule, traceLayer);
        barPlot.plot(gd, plotinfo, cdModule, traceLayer, {
          mode: fullLayout.funnelmode,
          norm: fullLayout.funnelmode,
          gap: fullLayout.funnelgap,
          groupgap: fullLayout.funnelgroupgap
        });
      };
      function plotConnectorRegions(gd, plotinfo, cdModule, traceLayer) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        Lib.makeTraceGroups(traceLayer, cdModule, "trace bars").each(function(cd) {
          var plotGroup = d3.select(this);
          var trace = cd[0].trace;
          var group = Lib.ensureSingle(plotGroup, "g", "regions");
          if (!trace.connector || !trace.connector.visible) {
            group.remove();
            return;
          }
          var isHorizontal = trace.orientation === "h";
          var connectors = group.selectAll("g.region").data(Lib.identity);
          connectors.enter().append("g").classed("region", true);
          connectors.exit().remove();
          var len = connectors.size();
          connectors.each(function(di, i) {
            if (i !== len - 1 && !di.cNext) return;
            var xy = getXY(di, xa, ya, isHorizontal);
            var x = xy[0];
            var y = xy[1];
            var shape = "";
            if (x[0] !== BADNUM && y[0] !== BADNUM && x[1] !== BADNUM && y[1] !== BADNUM && x[2] !== BADNUM && y[2] !== BADNUM && x[3] !== BADNUM && y[3] !== BADNUM) {
              if (isHorizontal) {
                shape += "M" + x[0] + "," + y[1] + "L" + x[2] + "," + y[2] + "H" + x[3] + "L" + x[1] + "," + y[1] + "Z";
              } else {
                shape += "M" + x[1] + "," + y[1] + "L" + x[2] + "," + y[3] + "V" + y[2] + "L" + x[1] + "," + y[0] + "Z";
              }
            }
            if (shape === "") shape = "M0,0Z";
            Lib.ensureSingle(d3.select(this), "path").attr("d", shape).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
          });
        });
      }
      function plotConnectorLines(gd, plotinfo, cdModule, traceLayer) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        Lib.makeTraceGroups(traceLayer, cdModule, "trace bars").each(function(cd) {
          var plotGroup = d3.select(this);
          var trace = cd[0].trace;
          var group = Lib.ensureSingle(plotGroup, "g", "lines");
          if (!trace.connector || !trace.connector.visible || !trace.connector.line.width) {
            group.remove();
            return;
          }
          var isHorizontal = trace.orientation === "h";
          var connectors = group.selectAll("g.line").data(Lib.identity);
          connectors.enter().append("g").classed("line", true);
          connectors.exit().remove();
          var len = connectors.size();
          connectors.each(function(di, i) {
            if (i !== len - 1 && !di.cNext) return;
            var xy = getXY(di, xa, ya, isHorizontal);
            var x = xy[0];
            var y = xy[1];
            var shape = "";
            if (x[3] !== void 0 && y[3] !== void 0) {
              if (isHorizontal) {
                shape += "M" + x[0] + "," + y[1] + "L" + x[2] + "," + y[2];
                shape += "M" + x[1] + "," + y[1] + "L" + x[3] + "," + y[2];
              } else {
                shape += "M" + x[1] + "," + y[1] + "L" + x[2] + "," + y[3];
                shape += "M" + x[1] + "," + y[0] + "L" + x[2] + "," + y[2];
              }
            }
            if (shape === "") shape = "M0,0Z";
            Lib.ensureSingle(d3.select(this), "path").attr("d", shape).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
          });
        });
      }
      function getXY(di, xa, ya, isHorizontal) {
        var s = [];
        var p = [];
        var sAxis = isHorizontal ? xa : ya;
        var pAxis = isHorizontal ? ya : xa;
        s[0] = sAxis.c2p(di.s0, true);
        p[0] = pAxis.c2p(di.p0, true);
        s[1] = sAxis.c2p(di.s1, true);
        p[1] = pAxis.c2p(di.p1, true);
        s[2] = sAxis.c2p(di.nextS0, true);
        p[2] = pAxis.c2p(di.nextP0, true);
        s[3] = sAxis.c2p(di.nextS1, true);
        p[3] = pAxis.c2p(di.nextP1, true);
        return isHorizontal ? [s, p] : [p, s];
      }
    }
  });

  // src/traces/funnel/style.js
  var require_style9 = __commonJS({
    "src/traces/funnel/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var DESELECTDIM = require_interactions().DESELECTDIM;
      var barStyle = require_style4();
      var resizeText = require_uniform_text().resizeText;
      var styleTextPoints = barStyle.styleTextPoints;
      function style(gd, cd, sel) {
        var s = sel ? sel : d3.select(gd).selectAll('g[class^="funnellayer"]').selectAll("g.trace");
        resizeText(gd, s, "funnel");
        s.style("opacity", function(d) {
          return d[0].trace.opacity;
        });
        s.each(function(d) {
          var gTrace = d3.select(this);
          var trace = d[0].trace;
          gTrace.selectAll(".point > path").each(function(di) {
            if (!di.isBlank) {
              var cont = trace.marker;
              d3.select(this).call(Color2.fill, di.mc || cont.color).call(Color2.stroke, di.mlc || cont.line.color).call(Drawing.dashLine, cont.line.dash, di.mlw || cont.line.width).style("opacity", trace.selectedpoints && !di.selected ? DESELECTDIM : 1);
            }
          });
          styleTextPoints(gTrace, trace, gd);
          gTrace.selectAll(".regions").each(function() {
            d3.select(this).selectAll("path").style("stroke-width", 0).call(Color2.fill, trace.connector.fillcolor);
          });
          gTrace.selectAll(".lines").each(function() {
            var cont = trace.connector.line;
            Drawing.lineGroupStyle(
              d3.select(this).selectAll("path"),
              cont.width,
              cont.color,
              cont.dash
            );
          });
        });
      }
      module.exports = {
        style
      };
    }
  });

  // src/traces/funnel/hover.js
  var require_hover11 = __commonJS({
    "src/traces/funnel/hover.js"(exports, module) {
      "use strict";
      var opacity = require_color().opacity;
      var hoverOnBars = require_hover3().hoverOnBars;
      var formatPercent = require_lib().formatPercent;
      module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
        var point = hoverOnBars(pointData, xval, yval, hovermode, opts);
        if (!point) return;
        var cd = point.cd;
        var trace = cd[0].trace;
        var isHorizontal = trace.orientation === "h";
        var index = point.index;
        var di = cd[index];
        var sizeLetter = isHorizontal ? "x" : "y";
        point[sizeLetter + "LabelVal"] = di.s;
        point.percentInitial = di.begR;
        point.percentInitialLabel = formatPercent(di.begR, 1);
        point.percentPrevious = di.difR;
        point.percentPreviousLabel = formatPercent(di.difR, 1);
        point.percentTotal = di.sumR;
        point.percentTotalLabel = formatPercent(di.sumR, 1);
        var hoverinfo = di.hi || trace.hoverinfo;
        var text = [];
        if (hoverinfo && hoverinfo !== "none" && hoverinfo !== "skip") {
          var isAll = hoverinfo === "all";
          var parts = hoverinfo.split("+");
          var hasFlag = function(flag) {
            return isAll || parts.indexOf(flag) !== -1;
          };
          if (hasFlag("percent initial")) {
            text.push(point.percentInitialLabel + " of initial");
          }
          if (hasFlag("percent previous")) {
            text.push(point.percentPreviousLabel + " of previous");
          }
          if (hasFlag("percent total")) {
            text.push(point.percentTotalLabel + " of total");
          }
        }
        point.extraText = text.join("<br>");
        point.color = getTraceColor(trace, di);
        return [point];
      };
      function getTraceColor(trace, di) {
        var cont = trace.marker;
        var mc = di.mc || cont.color;
        var mlc = di.mlc || cont.line.color;
        var mlw = di.mlw || cont.line.width;
        if (opacity(mc)) return mc;
        else if (opacity(mlc) && mlw) return mlc;
      }
    }
  });

  // src/traces/funnel/event_data.js
  var require_event_data5 = __commonJS({
    "src/traces/funnel/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        out.x = "xVal" in pt ? pt.xVal : pt.x;
        out.y = "yVal" in pt ? pt.yVal : pt.y;
        if ("percentInitial" in pt) out.percentInitial = pt.percentInitial;
        if ("percentPrevious" in pt) out.percentPrevious = pt.percentPrevious;
        if ("percentTotal" in pt) out.percentTotal = pt.percentTotal;
        if (pt.xa) out.xaxis = pt.xa;
        if (pt.ya) out.yaxis = pt.ya;
        return out;
      };
    }
  });

  // src/traces/funnel/index.js
  var require_funnel = __commonJS({
    "src/traces/funnel/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes32(),
        layoutAttributes: require_layout_attributes10(),
        supplyDefaults: require_defaults28().supplyDefaults,
        crossTraceDefaults: require_defaults28().crossTraceDefaults,
        supplyLayoutDefaults: require_layout_defaults9(),
        calc: require_calc13(),
        crossTraceCalc: require_cross_trace_calc5(),
        plot: require_plot9(),
        style: require_style9().style,
        hoverPoints: require_hover11(),
        eventData: require_event_data5(),
        selectPoints: require_select3(),
        moduleType: "trace",
        name: "funnel",
        basePlotModule: require_cartesian(),
        categories: ["bar-like", "cartesian", "svg", "oriented", "showLegend", "zoomScale"],
        meta: {}
      };
    }
  });

  // lib/funnel.js
  var require_funnel2 = __commonJS({
    "lib/funnel.js"(exports, module) {
      "use strict";
      module.exports = require_funnel();
    }
  });

  // src/traces/waterfall/constants.js
  var require_constants18 = __commonJS({
    "src/traces/waterfall/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        eventDataKeys: [
          "initial",
          "delta",
          "final"
        ]
      };
    }
  });

  // src/traces/waterfall/attributes.js
  var require_attributes33 = __commonJS({
    "src/traces/waterfall/attributes.js"(exports, module) {
      "use strict";
      var barAttrs = require_attributes23();
      var lineAttrs = require_attributes12().line;
      var baseAttrs = require_attributes2();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var constants = require_constants18();
      var extendFlat = require_extend().extendFlat;
      var Color2 = require_color();
      function directionAttrs(dirTxt) {
        return {
          marker: {
            color: extendFlat({}, barAttrs.marker.color, {
              arrayOk: false,
              editType: "style"
            }),
            line: {
              color: extendFlat({}, barAttrs.marker.line.color, {
                arrayOk: false,
                editType: "style"
              }),
              width: extendFlat({}, barAttrs.marker.line.width, {
                arrayOk: false,
                editType: "style"
              }),
              editType: "style"
            },
            editType: "style"
          },
          editType: "style"
        };
      }
      module.exports = {
        measure: {
          valType: "data_array",
          dflt: [],
          editType: "calc"
        },
        base: {
          valType: "number",
          dflt: null,
          arrayOk: false,
          editType: "calc"
        },
        x: barAttrs.x,
        x0: barAttrs.x0,
        dx: barAttrs.dx,
        y: barAttrs.y,
        y0: barAttrs.y0,
        dy: barAttrs.dy,
        xperiod: barAttrs.xperiod,
        yperiod: barAttrs.yperiod,
        xperiod0: barAttrs.xperiod0,
        yperiod0: barAttrs.yperiod0,
        xperiodalignment: barAttrs.xperiodalignment,
        yperiodalignment: barAttrs.yperiodalignment,
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        hovertext: barAttrs.hovertext,
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["name", "x", "y", "text", "initial", "delta", "final"]
        }),
        textinfo: {
          valType: "flaglist",
          flags: ["label", "text", "initial", "delta", "final"],
          extras: ["none"],
          editType: "plot",
          arrayOk: false
        },
        // TODO: incorporate `label` and `value` in the eventData
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: constants.eventDataKeys.concat(["label"]) }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        text: barAttrs.text,
        textposition: barAttrs.textposition,
        insidetextanchor: barAttrs.insidetextanchor,
        textangle: barAttrs.textangle,
        textfont: barAttrs.textfont,
        insidetextfont: barAttrs.insidetextfont,
        outsidetextfont: barAttrs.outsidetextfont,
        constraintext: barAttrs.constraintext,
        cliponaxis: barAttrs.cliponaxis,
        orientation: barAttrs.orientation,
        offset: barAttrs.offset,
        width: barAttrs.width,
        increasing: directionAttrs("increasing"),
        decreasing: directionAttrs("decreasing"),
        totals: directionAttrs("intermediate sums and total"),
        connector: {
          line: {
            color: extendFlat({}, lineAttrs.color, { dflt: Color2.defaultLine }),
            width: extendFlat({}, lineAttrs.width, {
              editType: "plot"
              // i.e. to adjust bars is mode: 'between'. See https://github.com/plotly/plotly.js/issues/3787
            }),
            dash: lineAttrs.dash,
            editType: "plot"
          },
          mode: {
            valType: "enumerated",
            values: ["spanning", "between"],
            dflt: "between",
            editType: "plot"
          },
          visible: {
            valType: "boolean",
            dflt: true,
            editType: "plot"
          },
          editType: "plot"
        },
        offsetgroup: barAttrs.offsetgroup,
        alignmentgroup: barAttrs.alignmentgroup,
        zorder: barAttrs.zorder
      };
    }
  });

  // src/traces/waterfall/layout_attributes.js
  var require_layout_attributes11 = __commonJS({
    "src/traces/waterfall/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        waterfallmode: {
          valType: "enumerated",
          values: ["group", "overlay"],
          dflt: "group",
          editType: "calc"
        },
        waterfallgap: {
          valType: "number",
          min: 0,
          max: 1,
          editType: "calc"
        },
        waterfallgroupgap: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0,
          editType: "calc"
        }
      };
    }
  });

  // src/constants/delta.js
  var require_delta = __commonJS({
    "src/constants/delta.js"(exports, module) {
      "use strict";
      module.exports = {
        INCREASING: {
          COLOR: "#3D9970",
          SYMBOL: "\u25B2"
        },
        DECREASING: {
          COLOR: "#FF4136",
          SYMBOL: "\u25BC"
        }
      };
    }
  });

  // src/traces/waterfall/defaults.js
  var require_defaults29 = __commonJS({
    "src/traces/waterfall/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleGroupingDefaults = require_grouping_defaults();
      var handleText = require_defaults19().handleText;
      var handleXYDefaults = require_xy_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var attributes = require_attributes33();
      var Color2 = require_color();
      var delta = require_delta();
      var INCREASING_COLOR = delta.INCREASING.COLOR;
      var DECREASING_COLOR = delta.DECREASING.COLOR;
      var TOTALS_COLOR = "#4499FF";
      function handleDirection(coerce, direction, defaultColor) {
        coerce(direction + ".marker.color", defaultColor);
        coerce(direction + ".marker.line.color", Color2.defaultLine);
        coerce(direction + ".marker.line.width");
      }
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("measure");
        coerce("orientation", traceOut.x && !traceOut.y ? "h" : "v");
        coerce("base");
        coerce("offset");
        coerce("width");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var textposition = coerce("textposition");
        handleText(traceIn, traceOut, layout, coerce, textposition, {
          moduleHasSelected: false,
          moduleHasUnselected: false,
          moduleHasConstrain: true,
          moduleHasCliponaxis: true,
          moduleHasTextangle: true,
          moduleHasInsideanchor: true
        });
        if (traceOut.textposition !== "none") {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          if (!traceOut.texttemplate) coerce("textinfo");
        }
        handleDirection(coerce, "increasing", INCREASING_COLOR);
        handleDirection(coerce, "decreasing", DECREASING_COLOR);
        handleDirection(coerce, "totals", TOTALS_COLOR);
        var connectorVisible = coerce("connector.visible");
        if (connectorVisible) {
          coerce("connector.mode");
          var connectorLineWidth = coerce("connector.line.width");
          if (connectorLineWidth) {
            coerce("connector.line.color");
            coerce("connector.line.dash");
          }
        }
        coerce("zorder");
      }
      function crossTraceDefaults(fullData, fullLayout) {
        var traceIn, traceOut;
        function coerce(attr) {
          return Lib.coerce(traceOut._input, traceOut, attributes, attr);
        }
        if (fullLayout.waterfallmode === "group") {
          for (var i = 0; i < fullData.length; i++) {
            traceOut = fullData[i];
            traceIn = traceOut._input;
            handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce, fullLayout.waterfallmode);
          }
        }
      }
      module.exports = {
        supplyDefaults,
        crossTraceDefaults
      };
    }
  });

  // src/traces/waterfall/layout_defaults.js
  var require_layout_defaults10 = __commonJS({
    "src/traces/waterfall/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes11();
      module.exports = function(layoutIn, layoutOut, fullData) {
        var hasTraceType = false;
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        for (var i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          if (trace.visible && trace.type === "waterfall") {
            hasTraceType = true;
            break;
          }
        }
        if (hasTraceType) {
          coerce("waterfallmode");
          coerce("waterfallgap", 0.2);
          coerce("waterfallgroupgap");
        }
      };
    }
  });

  // src/traces/waterfall/calc.js
  var require_calc14 = __commonJS({
    "src/traces/waterfall/calc.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var mergeArray = require_lib().mergeArray;
      var calcSelection = require_calc_selection();
      var BADNUM = require_numerical().BADNUM;
      function isAbsolute(a) {
        return a === "a" || a === "absolute";
      }
      function isTotal(a) {
        return a === "t" || a === "total";
      }
      module.exports = function calc(gd, trace) {
        var xa = Axes.getFromId(gd, trace.xaxis || "x");
        var ya = Axes.getFromId(gd, trace.yaxis || "y");
        var size, pos, origPos, pObj, hasPeriod, pLetter;
        if (trace.orientation === "h") {
          size = xa.makeCalcdata(trace, "x");
          origPos = ya.makeCalcdata(trace, "y");
          pObj = alignPeriod(trace, ya, "y", origPos);
          hasPeriod = !!trace.yperiodalignment;
          pLetter = "y";
        } else {
          size = ya.makeCalcdata(trace, "y");
          origPos = xa.makeCalcdata(trace, "x");
          pObj = alignPeriod(trace, xa, "x", origPos);
          hasPeriod = !!trace.xperiodalignment;
          pLetter = "x";
        }
        pos = pObj.vals;
        var serieslen = Math.min(pos.length, size.length);
        var cd = new Array(serieslen);
        var previousSum = 0;
        var newSize;
        var hasTotals = false;
        for (var i = 0; i < serieslen; i++) {
          var amount = size[i] || 0;
          var connectToNext = false;
          if (size[i] !== BADNUM || isTotal(trace.measure[i]) || isAbsolute(trace.measure[i])) {
            if (i + 1 < serieslen && (size[i + 1] !== BADNUM || isTotal(trace.measure[i + 1]) || isAbsolute(trace.measure[i + 1]))) {
              connectToNext = true;
            }
          }
          var cdi = cd[i] = {
            i,
            p: pos[i],
            s: amount,
            rawS: amount,
            cNext: connectToNext
          };
          if (isAbsolute(trace.measure[i])) {
            previousSum = cdi.s;
            cdi.isSum = true;
            cdi.dir = "totals";
            cdi.s = previousSum;
          } else if (isTotal(trace.measure[i])) {
            cdi.isSum = true;
            cdi.dir = "totals";
            cdi.s = previousSum;
          } else {
            cdi.isSum = false;
            cdi.dir = cdi.rawS < 0 ? "decreasing" : "increasing";
            newSize = cdi.s;
            cdi.s = previousSum + newSize;
            previousSum += newSize;
          }
          if (cdi.dir === "totals") {
            hasTotals = true;
          }
          if (hasPeriod) {
            cd[i].orig_p = origPos[i];
            cd[i][pLetter + "End"] = pObj.ends[i];
            cd[i][pLetter + "Start"] = pObj.starts[i];
          }
          if (trace.ids) {
            cdi.id = String(trace.ids[i]);
          }
          cdi.v = (trace.base || 0) + previousSum;
        }
        if (cd.length) cd[0].hasTotals = hasTotals;
        mergeArray(trace.text, cd, "tx");
        mergeArray(trace.hovertext, cd, "htx");
        calcSelection(cd, trace);
        return cd;
      };
    }
  });

  // src/traces/waterfall/cross_trace_calc.js
  var require_cross_trace_calc6 = __commonJS({
    "src/traces/waterfall/cross_trace_calc.js"(exports, module) {
      "use strict";
      var setGroupPositions = require_cross_trace_calc().setGroupPositions;
      module.exports = function crossTraceCalc(gd, plotinfo) {
        var fullLayout = gd._fullLayout;
        var fullData = gd._fullData;
        var calcdata = gd.calcdata;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var waterfalls = [];
        var waterfallsVert = [];
        var waterfallsHorz = [];
        var cd, i;
        for (i = 0; i < fullData.length; i++) {
          var fullTrace = fullData[i];
          if (fullTrace.visible === true && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id && fullTrace.type === "waterfall") {
            cd = calcdata[i];
            if (fullTrace.orientation === "h") {
              waterfallsHorz.push(cd);
            } else {
              waterfallsVert.push(cd);
            }
            waterfalls.push(cd);
          }
        }
        var opts = {
          mode: fullLayout.waterfallmode,
          norm: fullLayout.waterfallnorm,
          gap: fullLayout.waterfallgap,
          groupgap: fullLayout.waterfallgroupgap
        };
        setGroupPositions(gd, xa, ya, waterfallsVert, opts);
        setGroupPositions(gd, ya, xa, waterfallsHorz, opts);
        for (i = 0; i < waterfalls.length; i++) {
          cd = waterfalls[i];
          for (var j = 0; j < cd.length; j++) {
            var di = cd[j];
            if (di.isSum === false) {
              di.s0 += j === 0 ? 0 : cd[j - 1].s;
            }
            if (j + 1 < cd.length) {
              cd[j].nextP0 = cd[j + 1].p0;
              cd[j].nextS0 = cd[j + 1].s0;
            }
          }
        }
      };
    }
  });

  // src/traces/waterfall/plot.js
  var require_plot10 = __commonJS({
    "src/traces/waterfall/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var BADNUM = require_numerical().BADNUM;
      var barPlot = require_plot3();
      var clearMinTextSize = require_uniform_text().clearMinTextSize;
      module.exports = function plot(gd, plotinfo, cdModule, traceLayer) {
        var fullLayout = gd._fullLayout;
        clearMinTextSize("waterfall", fullLayout);
        barPlot.plot(gd, plotinfo, cdModule, traceLayer, {
          mode: fullLayout.waterfallmode,
          norm: fullLayout.waterfallmode,
          gap: fullLayout.waterfallgap,
          groupgap: fullLayout.waterfallgroupgap
        });
        plotConnectors(gd, plotinfo, cdModule, traceLayer);
      };
      function plotConnectors(gd, plotinfo, cdModule, traceLayer) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        Lib.makeTraceGroups(traceLayer, cdModule, "trace bars").each(function(cd) {
          var plotGroup = d3.select(this);
          var trace = cd[0].trace;
          var group = Lib.ensureSingle(plotGroup, "g", "lines");
          if (!trace.connector || !trace.connector.visible) {
            group.remove();
            return;
          }
          var isHorizontal = trace.orientation === "h";
          var mode = trace.connector.mode;
          var connectors = group.selectAll("g.line").data(Lib.identity);
          connectors.enter().append("g").classed("line", true);
          connectors.exit().remove();
          var len = connectors.size();
          connectors.each(function(di, i) {
            if (i !== len - 1 && !di.cNext) return;
            var xy = getXY(di, xa, ya, isHorizontal);
            var x = xy[0];
            var y = xy[1];
            var shape = "";
            if (x[0] !== BADNUM && y[0] !== BADNUM && x[1] !== BADNUM && y[1] !== BADNUM) {
              if (mode === "spanning") {
                if (!di.isSum && i > 0) {
                  if (isHorizontal) {
                    shape += "M" + x[0] + "," + y[1] + "V" + y[0];
                  } else {
                    shape += "M" + x[1] + "," + y[0] + "H" + x[0];
                  }
                }
              }
              if (mode !== "between") {
                if (di.isSum || i < len - 1) {
                  if (isHorizontal) {
                    shape += "M" + x[1] + "," + y[0] + "V" + y[1];
                  } else {
                    shape += "M" + x[0] + "," + y[1] + "H" + x[1];
                  }
                }
              }
              if (x[2] !== BADNUM && y[2] !== BADNUM) {
                if (isHorizontal) {
                  shape += "M" + x[1] + "," + y[1] + "V" + y[2];
                } else {
                  shape += "M" + x[1] + "," + y[1] + "H" + x[2];
                }
              }
            }
            if (shape === "") shape = "M0,0Z";
            Lib.ensureSingle(d3.select(this), "path").attr("d", shape).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
          });
        });
      }
      function getXY(di, xa, ya, isHorizontal) {
        var s = [];
        var p = [];
        var sAxis = isHorizontal ? xa : ya;
        var pAxis = isHorizontal ? ya : xa;
        s[0] = sAxis.c2p(di.s0, true);
        p[0] = pAxis.c2p(di.p0, true);
        s[1] = sAxis.c2p(di.s1, true);
        p[1] = pAxis.c2p(di.p1, true);
        s[2] = sAxis.c2p(di.nextS0, true);
        p[2] = pAxis.c2p(di.nextP0, true);
        return isHorizontal ? [s, p] : [p, s];
      }
    }
  });

  // src/traces/waterfall/style.js
  var require_style10 = __commonJS({
    "src/traces/waterfall/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var DESELECTDIM = require_interactions().DESELECTDIM;
      var barStyle = require_style4();
      var resizeText = require_uniform_text().resizeText;
      var styleTextPoints = barStyle.styleTextPoints;
      function style(gd, cd, sel) {
        var s = sel ? sel : d3.select(gd).selectAll('g[class^="waterfalllayer"]').selectAll("g.trace");
        resizeText(gd, s, "waterfall");
        s.style("opacity", function(d) {
          return d[0].trace.opacity;
        });
        s.each(function(d) {
          var gTrace = d3.select(this);
          var trace = d[0].trace;
          gTrace.selectAll(".point > path").each(function(di) {
            if (!di.isBlank) {
              var cont = trace[di.dir].marker;
              d3.select(this).call(Color2.fill, cont.color).call(Color2.stroke, cont.line.color).call(Drawing.dashLine, cont.line.dash, cont.line.width).style("opacity", trace.selectedpoints && !di.selected ? DESELECTDIM : 1);
            }
          });
          styleTextPoints(gTrace, trace, gd);
          gTrace.selectAll(".lines").each(function() {
            var cont = trace.connector.line;
            Drawing.lineGroupStyle(
              d3.select(this).selectAll("path"),
              cont.width,
              cont.color,
              cont.dash
            );
          });
        });
      }
      module.exports = {
        style
      };
    }
  });

  // src/traces/waterfall/hover.js
  var require_hover12 = __commonJS({
    "src/traces/waterfall/hover.js"(exports, module) {
      "use strict";
      var hoverLabelText = require_axes().hoverLabelText;
      var opacity = require_color().opacity;
      var hoverOnBars = require_hover3().hoverOnBars;
      var delta = require_delta();
      var DIRSYMBOL = {
        increasing: delta.INCREASING.SYMBOL,
        decreasing: delta.DECREASING.SYMBOL
      };
      module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
        var point = hoverOnBars(pointData, xval, yval, hovermode, opts);
        if (!point) return;
        var cd = point.cd;
        var trace = cd[0].trace;
        var isHorizontal = trace.orientation === "h";
        var vLetter = isHorizontal ? "x" : "y";
        var vAxis = isHorizontal ? pointData.xa : pointData.ya;
        function formatNumber(a) {
          return hoverLabelText(vAxis, a, trace[vLetter + "hoverformat"]);
        }
        var index = point.index;
        var di = cd[index];
        var size = di.isSum ? di.b + di.s : di.rawS;
        point.initial = di.b + di.s - size;
        point.delta = size;
        point.final = point.initial + point.delta;
        var v = formatNumber(Math.abs(point.delta));
        point.deltaLabel = size < 0 ? "(" + v + ")" : v;
        point.finalLabel = formatNumber(point.final);
        point.initialLabel = formatNumber(point.initial);
        var hoverinfo = di.hi || trace.hoverinfo;
        var text = [];
        if (hoverinfo && hoverinfo !== "none" && hoverinfo !== "skip") {
          var isAll = hoverinfo === "all";
          var parts = hoverinfo.split("+");
          var hasFlag = function(flag) {
            return isAll || parts.indexOf(flag) !== -1;
          };
          if (!di.isSum) {
            if (hasFlag("final") && (isHorizontal ? !hasFlag("x") : !hasFlag("y"))) {
              text.push(point.finalLabel);
            }
            if (hasFlag("delta")) {
              if (size < 0) {
                text.push(point.deltaLabel + " " + DIRSYMBOL.decreasing);
              } else {
                text.push(point.deltaLabel + " " + DIRSYMBOL.increasing);
              }
            }
            if (hasFlag("initial")) {
              text.push("Initial: " + point.initialLabel);
            }
          }
        }
        if (text.length) point.extraText = text.join("<br>");
        point.color = getTraceColor(trace, di);
        return [point];
      };
      function getTraceColor(trace, di) {
        var cont = trace[di.dir].marker;
        var mc = cont.color;
        var mlc = cont.line.color;
        var mlw = cont.line.width;
        if (opacity(mc)) return mc;
        else if (opacity(mlc) && mlw) return mlc;
      }
    }
  });

  // src/traces/waterfall/event_data.js
  var require_event_data6 = __commonJS({
    "src/traces/waterfall/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        out.x = "xVal" in pt ? pt.xVal : pt.x;
        out.y = "yVal" in pt ? pt.yVal : pt.y;
        if ("initial" in pt) out.initial = pt.initial;
        if ("delta" in pt) out.delta = pt.delta;
        if ("final" in pt) out.final = pt.final;
        if (pt.xa) out.xaxis = pt.xa;
        if (pt.ya) out.yaxis = pt.ya;
        return out;
      };
    }
  });

  // src/traces/waterfall/index.js
  var require_waterfall = __commonJS({
    "src/traces/waterfall/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes33(),
        layoutAttributes: require_layout_attributes11(),
        supplyDefaults: require_defaults29().supplyDefaults,
        crossTraceDefaults: require_defaults29().crossTraceDefaults,
        supplyLayoutDefaults: require_layout_defaults10(),
        calc: require_calc14(),
        crossTraceCalc: require_cross_trace_calc6(),
        plot: require_plot10(),
        style: require_style10().style,
        hoverPoints: require_hover12(),
        eventData: require_event_data6(),
        selectPoints: require_select3(),
        moduleType: "trace",
        name: "waterfall",
        basePlotModule: require_cartesian(),
        categories: ["bar-like", "cartesian", "svg", "oriented", "showLegend", "zoomScale"],
        meta: {}
      };
    }
  });

  // lib/waterfall.js
  var require_waterfall2 = __commonJS({
    "lib/waterfall.js"(exports, module) {
      "use strict";
      module.exports = require_waterfall();
    }
  });

  // src/traces/image/constants.js
  var require_constants19 = __commonJS({
    "src/traces/image/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        colormodel: {
          // min and max define the numerical range accepted in CSS
          // If z(min|max)Dflt are not defined, z(min|max) will default to min/max
          rgb: {
            min: [0, 0, 0],
            max: [255, 255, 255],
            fmt: function(c) {
              return c.slice(0, 3);
            },
            suffix: ["", "", ""]
          },
          rgba: {
            min: [0, 0, 0, 0],
            max: [255, 255, 255, 1],
            fmt: function(c) {
              return c.slice(0, 4);
            },
            suffix: ["", "", "", ""]
          },
          rgba256: {
            colormodel: "rgba",
            // because rgba256 is not an accept colormodel in CSS
            zminDflt: [0, 0, 0, 0],
            zmaxDflt: [255, 255, 255, 255],
            min: [0, 0, 0, 0],
            max: [255, 255, 255, 1],
            fmt: function(c) {
              return c.slice(0, 4);
            },
            suffix: ["", "", "", ""]
          },
          hsl: {
            min: [0, 0, 0],
            max: [360, 100, 100],
            fmt: function(c) {
              var p = c.slice(0, 3);
              p[1] = p[1] + "%";
              p[2] = p[2] + "%";
              return p;
            },
            suffix: ["\xB0", "%", "%"]
          },
          hsla: {
            min: [0, 0, 0, 0],
            max: [360, 100, 100, 1],
            fmt: function(c) {
              var p = c.slice(0, 4);
              p[1] = p[1] + "%";
              p[2] = p[2] + "%";
              return p;
            },
            suffix: ["\xB0", "%", "%", ""]
          }
        }
      };
    }
  });

  // src/traces/image/attributes.js
  var require_attributes34 = __commonJS({
    "src/traces/image/attributes.js"(exports, module) {
      "use strict";
      var baseAttrs = require_attributes2();
      var zorder = require_attributes12().zorder;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var extendFlat = require_extend().extendFlat;
      var colormodel = require_constants19().colormodel;
      var cm = ["rgb", "rgba", "rgba256", "hsl", "hsla"];
      var zminDesc = [];
      var zmaxDesc = [];
      for (i = 0; i < cm.length; i++) {
        cr = colormodel[cm[i]];
        zminDesc.push("For the `" + cm[i] + "` colormodel, it is [" + (cr.zminDflt || cr.min).join(", ") + "].");
        zmaxDesc.push("For the `" + cm[i] + "` colormodel, it is [" + (cr.zmaxDflt || cr.max).join(", ") + "].");
      }
      var cr;
      var i;
      module.exports = extendFlat({
        source: {
          valType: "string",
          editType: "calc"
        },
        z: {
          valType: "data_array",
          editType: "calc"
        },
        colormodel: {
          valType: "enumerated",
          values: cm,
          editType: "calc"
        },
        zsmooth: {
          valType: "enumerated",
          values: ["fast", false],
          dflt: false,
          editType: "plot"
        },
        zmin: {
          valType: "info_array",
          items: [
            { valType: "number", editType: "calc" },
            { valType: "number", editType: "calc" },
            { valType: "number", editType: "calc" },
            { valType: "number", editType: "calc" }
          ],
          editType: "calc"
        },
        zmax: {
          valType: "info_array",
          items: [
            { valType: "number", editType: "calc" },
            { valType: "number", editType: "calc" },
            { valType: "number", editType: "calc" },
            { valType: "number", editType: "calc" }
          ],
          editType: "calc"
        },
        x0: {
          valType: "any",
          dflt: 0,
          editType: "calc+clearAxisTypes"
        },
        y0: {
          valType: "any",
          dflt: 0,
          editType: "calc+clearAxisTypes"
        },
        dx: {
          valType: "number",
          dflt: 1,
          editType: "calc",
          description: "Set the pixel's horizontal size."
        },
        dy: {
          valType: "number",
          dflt: 1,
          editType: "calc",
          description: "Set the pixel's vertical size"
        },
        text: {
          valType: "data_array",
          editType: "plot"
        },
        hovertext: {
          valType: "data_array",
          editType: "plot"
        },
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["x", "y", "z", "color", "name", "text"],
          dflt: "x+y+z+text+name"
        }),
        hovertemplate: hovertemplateAttrs({}, { keys: ["z", "color", "colormodel"] }),
        hovertemplatefallback: templatefallbackAttrs(),
        zorder
      });
    }
  });

  // src/traces/image/defaults.js
  var require_defaults30 = __commonJS({
    "src/traces/image/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes34();
      var constants = require_constants19();
      var dataUri = require_helpers10().IMAGE_URL_PREFIX;
      module.exports = function supplyDefaults(traceIn, traceOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        coerce("source");
        if (traceOut.source && !traceOut.source.match(dataUri)) delete traceOut.source;
        traceOut._hasSource = !!traceOut.source;
        var z = coerce("z");
        traceOut._hasZ = !(z === void 0 || !z.length || !z[0] || !z[0].length);
        if (!traceOut._hasZ && !traceOut._hasSource) {
          traceOut.visible = false;
          return;
        }
        coerce("x0");
        coerce("y0");
        coerce("dx");
        coerce("dy");
        var cm;
        if (traceOut._hasZ) {
          coerce("colormodel", "rgb");
          cm = constants.colormodel[traceOut.colormodel];
          coerce("zmin", cm.zminDflt || cm.min);
          coerce("zmax", cm.zmaxDflt || cm.max);
        } else if (traceOut._hasSource) {
          traceOut.colormodel = "rgba256";
          cm = constants.colormodel[traceOut.colormodel];
          traceOut.zmin = cm.zminDflt;
          traceOut.zmax = cm.zmaxDflt;
        }
        coerce("zsmooth");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        traceOut._length = null;
        coerce("zorder");
      };
    }
  });

  // node_modules/inherits/inherits_browser.js
  var require_inherits_browser = __commonJS({
    "node_modules/inherits/inherits_browser.js"(exports, module) {
      if (typeof Object.create === "function") {
        module.exports = function inherits(ctor, superCtor) {
          if (superCtor) {
            ctor.super_ = superCtor;
            ctor.prototype = Object.create(superCtor.prototype, {
              constructor: {
                value: ctor,
                enumerable: false,
                writable: true,
                configurable: true
              }
            });
          }
        };
      } else {
        module.exports = function inherits(ctor, superCtor) {
          if (superCtor) {
            ctor.super_ = superCtor;
            var TempCtor = function() {
            };
            TempCtor.prototype = superCtor.prototype;
            ctor.prototype = new TempCtor();
            ctor.prototype.constructor = ctor;
          }
        };
      }
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream-browser.js
  var require_stream_browser = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream-browser.js"(exports, module) {
      module.exports = require_events().EventEmitter;
    }
  });

  // node_modules/base64-js/index.js
  var require_base64_js = __commonJS({
    "node_modules/base64-js/index.js"(exports) {
      "use strict";
      exports.byteLength = byteLength;
      exports.toByteArray = toByteArray;
      exports.fromByteArray = fromByteArray;
      var lookup = [];
      var revLookup = [];
      var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
      var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      for (i = 0, len = code.length; i < len; ++i) {
        lookup[i] = code[i];
        revLookup[code.charCodeAt(i)] = i;
      }
      var i;
      var len;
      revLookup["-".charCodeAt(0)] = 62;
      revLookup["_".charCodeAt(0)] = 63;
      function getLens(b64) {
        var len2 = b64.length;
        if (len2 % 4 > 0) {
          throw new Error("Invalid string. Length must be a multiple of 4");
        }
        var validLen = b64.indexOf("=");
        if (validLen === -1) validLen = len2;
        var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
        return [validLen, placeHoldersLen];
      }
      function byteLength(b64) {
        var lens = getLens(b64);
        var validLen = lens[0];
        var placeHoldersLen = lens[1];
        return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
      }
      function _byteLength(b64, validLen, placeHoldersLen) {
        return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
      }
      function toByteArray(b64) {
        var tmp;
        var lens = getLens(b64);
        var validLen = lens[0];
        var placeHoldersLen = lens[1];
        var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
        var curByte = 0;
        var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
        var i2;
        for (i2 = 0; i2 < len2; i2 += 4) {
          tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
          arr[curByte++] = tmp >> 16 & 255;
          arr[curByte++] = tmp >> 8 & 255;
          arr[curByte++] = tmp & 255;
        }
        if (placeHoldersLen === 2) {
          tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
          arr[curByte++] = tmp & 255;
        }
        if (placeHoldersLen === 1) {
          tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
          arr[curByte++] = tmp >> 8 & 255;
          arr[curByte++] = tmp & 255;
        }
        return arr;
      }
      function tripletToBase64(num) {
        return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
      }
      function encodeChunk(uint8, start, end) {
        var tmp;
        var output = [];
        for (var i2 = start; i2 < end; i2 += 3) {
          tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
          output.push(tripletToBase64(tmp));
        }
        return output.join("");
      }
      function fromByteArray(uint8) {
        var tmp;
        var len2 = uint8.length;
        var extraBytes = len2 % 3;
        var parts = [];
        var maxChunkLength = 16383;
        for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
          parts.push(encodeChunk(
            uint8,
            i2,
            i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength
          ));
        }
        if (extraBytes === 1) {
          tmp = uint8[len2 - 1];
          parts.push(
            lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
          );
        } else if (extraBytes === 2) {
          tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
          parts.push(
            lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
          );
        }
        return parts.join("");
      }
    }
  });

  // node_modules/ieee754/index.js
  var require_ieee754 = __commonJS({
    "node_modules/ieee754/index.js"(exports) {
      exports.read = function(buffer, offset, isLE, mLen, nBytes) {
        var e, m;
        var eLen = nBytes * 8 - mLen - 1;
        var eMax = (1 << eLen) - 1;
        var eBias = eMax >> 1;
        var nBits = -7;
        var i = isLE ? nBytes - 1 : 0;
        var d = isLE ? -1 : 1;
        var s = buffer[offset + i];
        i += d;
        e = s & (1 << -nBits) - 1;
        s >>= -nBits;
        nBits += eLen;
        for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
        }
        m = e & (1 << -nBits) - 1;
        e >>= -nBits;
        nBits += mLen;
        for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
        }
        if (e === 0) {
          e = 1 - eBias;
        } else if (e === eMax) {
          return m ? NaN : (s ? -1 : 1) * Infinity;
        } else {
          m = m + Math.pow(2, mLen);
          e = e - eBias;
        }
        return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
      };
      exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
        var e, m, c;
        var eLen = nBytes * 8 - mLen - 1;
        var eMax = (1 << eLen) - 1;
        var eBias = eMax >> 1;
        var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
        var i = isLE ? 0 : nBytes - 1;
        var d = isLE ? 1 : -1;
        var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
        value = Math.abs(value);
        if (isNaN(value) || value === Infinity) {
          m = isNaN(value) ? 1 : 0;
          e = eMax;
        } else {
          e = Math.floor(Math.log(value) / Math.LN2);
          if (value * (c = Math.pow(2, -e)) < 1) {
            e--;
            c *= 2;
          }
          if (e + eBias >= 1) {
            value += rt / c;
          } else {
            value += rt * Math.pow(2, 1 - eBias);
          }
          if (value * c >= 2) {
            e++;
            c /= 2;
          }
          if (e + eBias >= eMax) {
            m = 0;
            e = eMax;
          } else if (e + eBias >= 1) {
            m = (value * c - 1) * Math.pow(2, mLen);
            e = e + eBias;
          } else {
            m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
            e = 0;
          }
        }
        for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
        }
        e = e << mLen | m;
        eLen += mLen;
        for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
        }
        buffer[offset + i - d] |= s * 128;
      };
    }
  });

  // node_modules/buffer/index.js
  var require_buffer = __commonJS({
    "node_modules/buffer/index.js"(exports) {
      "use strict";
      var base64 = require_base64_js();
      var ieee754 = require_ieee754();
      var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
      exports.Buffer = Buffer2;
      exports.SlowBuffer = SlowBuffer;
      exports.INSPECT_MAX_BYTES = 50;
      var K_MAX_LENGTH = 2147483647;
      exports.kMaxLength = K_MAX_LENGTH;
      Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
      if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
        console.error(
          "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
        );
      }
      function typedArraySupport() {
        try {
          const arr = new Uint8Array(1);
          const proto = { foo: function() {
            return 42;
          } };
          Object.setPrototypeOf(proto, Uint8Array.prototype);
          Object.setPrototypeOf(arr, proto);
          return arr.foo() === 42;
        } catch (e) {
          return false;
        }
      }
      Object.defineProperty(Buffer2.prototype, "parent", {
        enumerable: true,
        get: function() {
          if (!Buffer2.isBuffer(this)) return void 0;
          return this.buffer;
        }
      });
      Object.defineProperty(Buffer2.prototype, "offset", {
        enumerable: true,
        get: function() {
          if (!Buffer2.isBuffer(this)) return void 0;
          return this.byteOffset;
        }
      });
      function createBuffer(length) {
        if (length > K_MAX_LENGTH) {
          throw new RangeError('The value "' + length + '" is invalid for option "size"');
        }
        const buf = new Uint8Array(length);
        Object.setPrototypeOf(buf, Buffer2.prototype);
        return buf;
      }
      function Buffer2(arg, encodingOrOffset, length) {
        if (typeof arg === "number") {
          if (typeof encodingOrOffset === "string") {
            throw new TypeError(
              'The "string" argument must be of type string. Received type number'
            );
          }
          return allocUnsafe(arg);
        }
        return from(arg, encodingOrOffset, length);
      }
      Buffer2.poolSize = 8192;
      function from(value, encodingOrOffset, length) {
        if (typeof value === "string") {
          return fromString(value, encodingOrOffset);
        }
        if (ArrayBuffer.isView(value)) {
          return fromArrayView(value);
        }
        if (value == null) {
          throw new TypeError(
            "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
          );
        }
        if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
          return fromArrayBuffer(value, encodingOrOffset, length);
        }
        if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
          return fromArrayBuffer(value, encodingOrOffset, length);
        }
        if (typeof value === "number") {
          throw new TypeError(
            'The "value" argument must not be of type number. Received type number'
          );
        }
        const valueOf = value.valueOf && value.valueOf();
        if (valueOf != null && valueOf !== value) {
          return Buffer2.from(valueOf, encodingOrOffset, length);
        }
        const b = fromObject(value);
        if (b) return b;
        if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
          return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
        }
        throw new TypeError(
          "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
        );
      }
      Buffer2.from = function(value, encodingOrOffset, length) {
        return from(value, encodingOrOffset, length);
      };
      Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
      Object.setPrototypeOf(Buffer2, Uint8Array);
      function assertSize(size) {
        if (typeof size !== "number") {
          throw new TypeError('"size" argument must be of type number');
        } else if (size < 0) {
          throw new RangeError('The value "' + size + '" is invalid for option "size"');
        }
      }
      function alloc(size, fill, encoding) {
        assertSize(size);
        if (size <= 0) {
          return createBuffer(size);
        }
        if (fill !== void 0) {
          return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
        }
        return createBuffer(size);
      }
      Buffer2.alloc = function(size, fill, encoding) {
        return alloc(size, fill, encoding);
      };
      function allocUnsafe(size) {
        assertSize(size);
        return createBuffer(size < 0 ? 0 : checked(size) | 0);
      }
      Buffer2.allocUnsafe = function(size) {
        return allocUnsafe(size);
      };
      Buffer2.allocUnsafeSlow = function(size) {
        return allocUnsafe(size);
      };
      function fromString(string, encoding) {
        if (typeof encoding !== "string" || encoding === "") {
          encoding = "utf8";
        }
        if (!Buffer2.isEncoding(encoding)) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
        const length = byteLength(string, encoding) | 0;
        let buf = createBuffer(length);
        const actual = buf.write(string, encoding);
        if (actual !== length) {
          buf = buf.slice(0, actual);
        }
        return buf;
      }
      function fromArrayLike(array) {
        const length = array.length < 0 ? 0 : checked(array.length) | 0;
        const buf = createBuffer(length);
        for (let i = 0; i < length; i += 1) {
          buf[i] = array[i] & 255;
        }
        return buf;
      }
      function fromArrayView(arrayView) {
        if (isInstance(arrayView, Uint8Array)) {
          const copy = new Uint8Array(arrayView);
          return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
        }
        return fromArrayLike(arrayView);
      }
      function fromArrayBuffer(array, byteOffset, length) {
        if (byteOffset < 0 || array.byteLength < byteOffset) {
          throw new RangeError('"offset" is outside of buffer bounds');
        }
        if (array.byteLength < byteOffset + (length || 0)) {
          throw new RangeError('"length" is outside of buffer bounds');
        }
        let buf;
        if (byteOffset === void 0 && length === void 0) {
          buf = new Uint8Array(array);
        } else if (length === void 0) {
          buf = new Uint8Array(array, byteOffset);
        } else {
          buf = new Uint8Array(array, byteOffset, length);
        }
        Object.setPrototypeOf(buf, Buffer2.prototype);
        return buf;
      }
      function fromObject(obj) {
        if (Buffer2.isBuffer(obj)) {
          const len = checked(obj.length) | 0;
          const buf = createBuffer(len);
          if (buf.length === 0) {
            return buf;
          }
          obj.copy(buf, 0, 0, len);
          return buf;
        }
        if (obj.length !== void 0) {
          if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
            return createBuffer(0);
          }
          return fromArrayLike(obj);
        }
        if (obj.type === "Buffer" && Array.isArray(obj.data)) {
          return fromArrayLike(obj.data);
        }
      }
      function checked(length) {
        if (length >= K_MAX_LENGTH) {
          throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
        }
        return length | 0;
      }
      function SlowBuffer(length) {
        if (+length != length) {
          length = 0;
        }
        return Buffer2.alloc(+length);
      }
      Buffer2.isBuffer = function isBuffer(b) {
        return b != null && b._isBuffer === true && b !== Buffer2.prototype;
      };
      Buffer2.compare = function compare(a, b) {
        if (isInstance(a, Uint8Array)) a = Buffer2.from(a, a.offset, a.byteLength);
        if (isInstance(b, Uint8Array)) b = Buffer2.from(b, b.offset, b.byteLength);
        if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) {
          throw new TypeError(
            'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
          );
        }
        if (a === b) return 0;
        let x = a.length;
        let y = b.length;
        for (let i = 0, len = Math.min(x, y); i < len; ++i) {
          if (a[i] !== b[i]) {
            x = a[i];
            y = b[i];
            break;
          }
        }
        if (x < y) return -1;
        if (y < x) return 1;
        return 0;
      };
      Buffer2.isEncoding = function isEncoding(encoding) {
        switch (String(encoding).toLowerCase()) {
          case "hex":
          case "utf8":
          case "utf-8":
          case "ascii":
          case "latin1":
          case "binary":
          case "base64":
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return true;
          default:
            return false;
        }
      };
      Buffer2.concat = function concat(list, length) {
        if (!Array.isArray(list)) {
          throw new TypeError('"list" argument must be an Array of Buffers');
        }
        if (list.length === 0) {
          return Buffer2.alloc(0);
        }
        let i;
        if (length === void 0) {
          length = 0;
          for (i = 0; i < list.length; ++i) {
            length += list[i].length;
          }
        }
        const buffer = Buffer2.allocUnsafe(length);
        let pos = 0;
        for (i = 0; i < list.length; ++i) {
          let buf = list[i];
          if (isInstance(buf, Uint8Array)) {
            if (pos + buf.length > buffer.length) {
              if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf);
              buf.copy(buffer, pos);
            } else {
              Uint8Array.prototype.set.call(
                buffer,
                buf,
                pos
              );
            }
          } else if (!Buffer2.isBuffer(buf)) {
            throw new TypeError('"list" argument must be an Array of Buffers');
          } else {
            buf.copy(buffer, pos);
          }
          pos += buf.length;
        }
        return buffer;
      };
      function byteLength(string, encoding) {
        if (Buffer2.isBuffer(string)) {
          return string.length;
        }
        if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
          return string.byteLength;
        }
        if (typeof string !== "string") {
          throw new TypeError(
            'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
          );
        }
        const len = string.length;
        const mustMatch = arguments.length > 2 && arguments[2] === true;
        if (!mustMatch && len === 0) return 0;
        let loweredCase = false;
        for (; ; ) {
          switch (encoding) {
            case "ascii":
            case "latin1":
            case "binary":
              return len;
            case "utf8":
            case "utf-8":
              return utf8ToBytes(string).length;
            case "ucs2":
            case "ucs-2":
            case "utf16le":
            case "utf-16le":
              return len * 2;
            case "hex":
              return len >>> 1;
            case "base64":
              return base64ToBytes(string).length;
            default:
              if (loweredCase) {
                return mustMatch ? -1 : utf8ToBytes(string).length;
              }
              encoding = ("" + encoding).toLowerCase();
              loweredCase = true;
          }
        }
      }
      Buffer2.byteLength = byteLength;
      function slowToString(encoding, start, end) {
        let loweredCase = false;
        if (start === void 0 || start < 0) {
          start = 0;
        }
        if (start > this.length) {
          return "";
        }
        if (end === void 0 || end > this.length) {
          end = this.length;
        }
        if (end <= 0) {
          return "";
        }
        end >>>= 0;
        start >>>= 0;
        if (end <= start) {
          return "";
        }
        if (!encoding) encoding = "utf8";
        while (true) {
          switch (encoding) {
            case "hex":
              return hexSlice(this, start, end);
            case "utf8":
            case "utf-8":
              return utf8Slice(this, start, end);
            case "ascii":
              return asciiSlice(this, start, end);
            case "latin1":
            case "binary":
              return latin1Slice(this, start, end);
            case "base64":
              return base64Slice(this, start, end);
            case "ucs2":
            case "ucs-2":
            case "utf16le":
            case "utf-16le":
              return utf16leSlice(this, start, end);
            default:
              if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
              encoding = (encoding + "").toLowerCase();
              loweredCase = true;
          }
        }
      }
      Buffer2.prototype._isBuffer = true;
      function swap(b, n, m) {
        const i = b[n];
        b[n] = b[m];
        b[m] = i;
      }
      Buffer2.prototype.swap16 = function swap16() {
        const len = this.length;
        if (len % 2 !== 0) {
          throw new RangeError("Buffer size must be a multiple of 16-bits");
        }
        for (let i = 0; i < len; i += 2) {
          swap(this, i, i + 1);
        }
        return this;
      };
      Buffer2.prototype.swap32 = function swap32() {
        const len = this.length;
        if (len % 4 !== 0) {
          throw new RangeError("Buffer size must be a multiple of 32-bits");
        }
        for (let i = 0; i < len; i += 4) {
          swap(this, i, i + 3);
          swap(this, i + 1, i + 2);
        }
        return this;
      };
      Buffer2.prototype.swap64 = function swap64() {
        const len = this.length;
        if (len % 8 !== 0) {
          throw new RangeError("Buffer size must be a multiple of 64-bits");
        }
        for (let i = 0; i < len; i += 8) {
          swap(this, i, i + 7);
          swap(this, i + 1, i + 6);
          swap(this, i + 2, i + 5);
          swap(this, i + 3, i + 4);
        }
        return this;
      };
      Buffer2.prototype.toString = function toString() {
        const length = this.length;
        if (length === 0) return "";
        if (arguments.length === 0) return utf8Slice(this, 0, length);
        return slowToString.apply(this, arguments);
      };
      Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
      Buffer2.prototype.equals = function equals(b) {
        if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
        if (this === b) return true;
        return Buffer2.compare(this, b) === 0;
      };
      Buffer2.prototype.inspect = function inspect() {
        let str = "";
        const max = exports.INSPECT_MAX_BYTES;
        str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
        if (this.length > max) str += " ... ";
        return "<Buffer " + str + ">";
      };
      if (customInspectSymbol) {
        Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
      }
      Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
        if (isInstance(target, Uint8Array)) {
          target = Buffer2.from(target, target.offset, target.byteLength);
        }
        if (!Buffer2.isBuffer(target)) {
          throw new TypeError(
            'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
          );
        }
        if (start === void 0) {
          start = 0;
        }
        if (end === void 0) {
          end = target ? target.length : 0;
        }
        if (thisStart === void 0) {
          thisStart = 0;
        }
        if (thisEnd === void 0) {
          thisEnd = this.length;
        }
        if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
          throw new RangeError("out of range index");
        }
        if (thisStart >= thisEnd && start >= end) {
          return 0;
        }
        if (thisStart >= thisEnd) {
          return -1;
        }
        if (start >= end) {
          return 1;
        }
        start >>>= 0;
        end >>>= 0;
        thisStart >>>= 0;
        thisEnd >>>= 0;
        if (this === target) return 0;
        let x = thisEnd - thisStart;
        let y = end - start;
        const len = Math.min(x, y);
        const thisCopy = this.slice(thisStart, thisEnd);
        const targetCopy = target.slice(start, end);
        for (let i = 0; i < len; ++i) {
          if (thisCopy[i] !== targetCopy[i]) {
            x = thisCopy[i];
            y = targetCopy[i];
            break;
          }
        }
        if (x < y) return -1;
        if (y < x) return 1;
        return 0;
      };
      function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
        if (buffer.length === 0) return -1;
        if (typeof byteOffset === "string") {
          encoding = byteOffset;
          byteOffset = 0;
        } else if (byteOffset > 2147483647) {
          byteOffset = 2147483647;
        } else if (byteOffset < -2147483648) {
          byteOffset = -2147483648;
        }
        byteOffset = +byteOffset;
        if (numberIsNaN(byteOffset)) {
          byteOffset = dir ? 0 : buffer.length - 1;
        }
        if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
        if (byteOffset >= buffer.length) {
          if (dir) return -1;
          else byteOffset = buffer.length - 1;
        } else if (byteOffset < 0) {
          if (dir) byteOffset = 0;
          else return -1;
        }
        if (typeof val === "string") {
          val = Buffer2.from(val, encoding);
        }
        if (Buffer2.isBuffer(val)) {
          if (val.length === 0) {
            return -1;
          }
          return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
        } else if (typeof val === "number") {
          val = val & 255;
          if (typeof Uint8Array.prototype.indexOf === "function") {
            if (dir) {
              return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
            } else {
              return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
            }
          }
          return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
        }
        throw new TypeError("val must be string, number or Buffer");
      }
      function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
        let indexSize = 1;
        let arrLength = arr.length;
        let valLength = val.length;
        if (encoding !== void 0) {
          encoding = String(encoding).toLowerCase();
          if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
            if (arr.length < 2 || val.length < 2) {
              return -1;
            }
            indexSize = 2;
            arrLength /= 2;
            valLength /= 2;
            byteOffset /= 2;
          }
        }
        function read(buf, i2) {
          if (indexSize === 1) {
            return buf[i2];
          } else {
            return buf.readUInt16BE(i2 * indexSize);
          }
        }
        let i;
        if (dir) {
          let foundIndex = -1;
          for (i = byteOffset; i < arrLength; i++) {
            if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
              if (foundIndex === -1) foundIndex = i;
              if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
            } else {
              if (foundIndex !== -1) i -= i - foundIndex;
              foundIndex = -1;
            }
          }
        } else {
          if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
          for (i = byteOffset; i >= 0; i--) {
            let found = true;
            for (let j = 0; j < valLength; j++) {
              if (read(arr, i + j) !== read(val, j)) {
                found = false;
                break;
              }
            }
            if (found) return i;
          }
        }
        return -1;
      }
      Buffer2.prototype.includes = function includes(val, byteOffset, encoding) {
        return this.indexOf(val, byteOffset, encoding) !== -1;
      };
      Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
        return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
      };
      Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
        return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
      };
      function hexWrite(buf, string, offset, length) {
        offset = Number(offset) || 0;
        const remaining = buf.length - offset;
        if (!length) {
          length = remaining;
        } else {
          length = Number(length);
          if (length > remaining) {
            length = remaining;
          }
        }
        const strLen = string.length;
        if (length > strLen / 2) {
          length = strLen / 2;
        }
        let i;
        for (i = 0; i < length; ++i) {
          const parsed = parseInt(string.substr(i * 2, 2), 16);
          if (numberIsNaN(parsed)) return i;
          buf[offset + i] = parsed;
        }
        return i;
      }
      function utf8Write(buf, string, offset, length) {
        return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
      }
      function asciiWrite(buf, string, offset, length) {
        return blitBuffer(asciiToBytes(string), buf, offset, length);
      }
      function base64Write(buf, string, offset, length) {
        return blitBuffer(base64ToBytes(string), buf, offset, length);
      }
      function ucs2Write(buf, string, offset, length) {
        return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
      }
      Buffer2.prototype.write = function write(string, offset, length, encoding) {
        if (offset === void 0) {
          encoding = "utf8";
          length = this.length;
          offset = 0;
        } else if (length === void 0 && typeof offset === "string") {
          encoding = offset;
          length = this.length;
          offset = 0;
        } else if (isFinite(offset)) {
          offset = offset >>> 0;
          if (isFinite(length)) {
            length = length >>> 0;
            if (encoding === void 0) encoding = "utf8";
          } else {
            encoding = length;
            length = void 0;
          }
        } else {
          throw new Error(
            "Buffer.write(string, encoding, offset[, length]) is no longer supported"
          );
        }
        const remaining = this.length - offset;
        if (length === void 0 || length > remaining) length = remaining;
        if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
          throw new RangeError("Attempt to write outside buffer bounds");
        }
        if (!encoding) encoding = "utf8";
        let loweredCase = false;
        for (; ; ) {
          switch (encoding) {
            case "hex":
              return hexWrite(this, string, offset, length);
            case "utf8":
            case "utf-8":
              return utf8Write(this, string, offset, length);
            case "ascii":
            case "latin1":
            case "binary":
              return asciiWrite(this, string, offset, length);
            case "base64":
              return base64Write(this, string, offset, length);
            case "ucs2":
            case "ucs-2":
            case "utf16le":
            case "utf-16le":
              return ucs2Write(this, string, offset, length);
            default:
              if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
              encoding = ("" + encoding).toLowerCase();
              loweredCase = true;
          }
        }
      };
      Buffer2.prototype.toJSON = function toJSON() {
        return {
          type: "Buffer",
          data: Array.prototype.slice.call(this._arr || this, 0)
        };
      };
      function base64Slice(buf, start, end) {
        if (start === 0 && end === buf.length) {
          return base64.fromByteArray(buf);
        } else {
          return base64.fromByteArray(buf.slice(start, end));
        }
      }
      function utf8Slice(buf, start, end) {
        end = Math.min(buf.length, end);
        const res = [];
        let i = start;
        while (i < end) {
          const firstByte = buf[i];
          let codePoint = null;
          let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
          if (i + bytesPerSequence <= end) {
            let secondByte, thirdByte, fourthByte, tempCodePoint;
            switch (bytesPerSequence) {
              case 1:
                if (firstByte < 128) {
                  codePoint = firstByte;
                }
                break;
              case 2:
                secondByte = buf[i + 1];
                if ((secondByte & 192) === 128) {
                  tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
                  if (tempCodePoint > 127) {
                    codePoint = tempCodePoint;
                  }
                }
                break;
              case 3:
                secondByte = buf[i + 1];
                thirdByte = buf[i + 2];
                if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
                  tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
                  if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
                    codePoint = tempCodePoint;
                  }
                }
                break;
              case 4:
                secondByte = buf[i + 1];
                thirdByte = buf[i + 2];
                fourthByte = buf[i + 3];
                if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
                  tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
                  if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
                    codePoint = tempCodePoint;
                  }
                }
            }
          }
          if (codePoint === null) {
            codePoint = 65533;
            bytesPerSequence = 1;
          } else if (codePoint > 65535) {
            codePoint -= 65536;
            res.push(codePoint >>> 10 & 1023 | 55296);
            codePoint = 56320 | codePoint & 1023;
          }
          res.push(codePoint);
          i += bytesPerSequence;
        }
        return decodeCodePointsArray(res);
      }
      var MAX_ARGUMENTS_LENGTH = 4096;
      function decodeCodePointsArray(codePoints) {
        const len = codePoints.length;
        if (len <= MAX_ARGUMENTS_LENGTH) {
          return String.fromCharCode.apply(String, codePoints);
        }
        let res = "";
        let i = 0;
        while (i < len) {
          res += String.fromCharCode.apply(
            String,
            codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
          );
        }
        return res;
      }
      function asciiSlice(buf, start, end) {
        let ret = "";
        end = Math.min(buf.length, end);
        for (let i = start; i < end; ++i) {
          ret += String.fromCharCode(buf[i] & 127);
        }
        return ret;
      }
      function latin1Slice(buf, start, end) {
        let ret = "";
        end = Math.min(buf.length, end);
        for (let i = start; i < end; ++i) {
          ret += String.fromCharCode(buf[i]);
        }
        return ret;
      }
      function hexSlice(buf, start, end) {
        const len = buf.length;
        if (!start || start < 0) start = 0;
        if (!end || end < 0 || end > len) end = len;
        let out = "";
        for (let i = start; i < end; ++i) {
          out += hexSliceLookupTable[buf[i]];
        }
        return out;
      }
      function utf16leSlice(buf, start, end) {
        const bytes = buf.slice(start, end);
        let res = "";
        for (let i = 0; i < bytes.length - 1; i += 2) {
          res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
        }
        return res;
      }
      Buffer2.prototype.slice = function slice(start, end) {
        const len = this.length;
        start = ~~start;
        end = end === void 0 ? len : ~~end;
        if (start < 0) {
          start += len;
          if (start < 0) start = 0;
        } else if (start > len) {
          start = len;
        }
        if (end < 0) {
          end += len;
          if (end < 0) end = 0;
        } else if (end > len) {
          end = len;
        }
        if (end < start) end = start;
        const newBuf = this.subarray(start, end);
        Object.setPrototypeOf(newBuf, Buffer2.prototype);
        return newBuf;
      };
      function checkOffset(offset, ext, length) {
        if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
        if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
      }
      Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
        offset = offset >>> 0;
        byteLength2 = byteLength2 >>> 0;
        if (!noAssert) checkOffset(offset, byteLength2, this.length);
        let val = this[offset];
        let mul = 1;
        let i = 0;
        while (++i < byteLength2 && (mul *= 256)) {
          val += this[offset + i] * mul;
        }
        return val;
      };
      Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
        offset = offset >>> 0;
        byteLength2 = byteLength2 >>> 0;
        if (!noAssert) {
          checkOffset(offset, byteLength2, this.length);
        }
        let val = this[offset + --byteLength2];
        let mul = 1;
        while (byteLength2 > 0 && (mul *= 256)) {
          val += this[offset + --byteLength2] * mul;
        }
        return val;
      };
      Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 1, this.length);
        return this[offset];
      };
      Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 2, this.length);
        return this[offset] | this[offset + 1] << 8;
      };
      Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 2, this.length);
        return this[offset] << 8 | this[offset + 1];
      };
      Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 4, this.length);
        return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
      };
      Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 4, this.length);
        return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
      };
      Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
        offset = offset >>> 0;
        validateNumber(offset, "offset");
        const first = this[offset];
        const last = this[offset + 7];
        if (first === void 0 || last === void 0) {
          boundsError(offset, this.length - 8);
        }
        const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
        const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
        return BigInt(lo) + (BigInt(hi) << BigInt(32));
      });
      Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
        offset = offset >>> 0;
        validateNumber(offset, "offset");
        const first = this[offset];
        const last = this[offset + 7];
        if (first === void 0 || last === void 0) {
          boundsError(offset, this.length - 8);
        }
        const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
        const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
        return (BigInt(hi) << BigInt(32)) + BigInt(lo);
      });
      Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
        offset = offset >>> 0;
        byteLength2 = byteLength2 >>> 0;
        if (!noAssert) checkOffset(offset, byteLength2, this.length);
        let val = this[offset];
        let mul = 1;
        let i = 0;
        while (++i < byteLength2 && (mul *= 256)) {
          val += this[offset + i] * mul;
        }
        mul *= 128;
        if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
        return val;
      };
      Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
        offset = offset >>> 0;
        byteLength2 = byteLength2 >>> 0;
        if (!noAssert) checkOffset(offset, byteLength2, this.length);
        let i = byteLength2;
        let mul = 1;
        let val = this[offset + --i];
        while (i > 0 && (mul *= 256)) {
          val += this[offset + --i] * mul;
        }
        mul *= 128;
        if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
        return val;
      };
      Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 1, this.length);
        if (!(this[offset] & 128)) return this[offset];
        return (255 - this[offset] + 1) * -1;
      };
      Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 2, this.length);
        const val = this[offset] | this[offset + 1] << 8;
        return val & 32768 ? val | 4294901760 : val;
      };
      Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 2, this.length);
        const val = this[offset + 1] | this[offset] << 8;
        return val & 32768 ? val | 4294901760 : val;
      };
      Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 4, this.length);
        return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
      };
      Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 4, this.length);
        return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
      };
      Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
        offset = offset >>> 0;
        validateNumber(offset, "offset");
        const first = this[offset];
        const last = this[offset + 7];
        if (first === void 0 || last === void 0) {
          boundsError(offset, this.length - 8);
        }
        const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
        return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
      });
      Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
        offset = offset >>> 0;
        validateNumber(offset, "offset");
        const first = this[offset];
        const last = this[offset + 7];
        if (first === void 0 || last === void 0) {
          boundsError(offset, this.length - 8);
        }
        const val = (first << 24) + // Overflow
        this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
        return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
      });
      Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 4, this.length);
        return ieee754.read(this, offset, true, 23, 4);
      };
      Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 4, this.length);
        return ieee754.read(this, offset, false, 23, 4);
      };
      Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 8, this.length);
        return ieee754.read(this, offset, true, 52, 8);
      };
      Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
        offset = offset >>> 0;
        if (!noAssert) checkOffset(offset, 8, this.length);
        return ieee754.read(this, offset, false, 52, 8);
      };
      function checkInt(buf, value, offset, ext, max, min) {
        if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
        if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
        if (offset + ext > buf.length) throw new RangeError("Index out of range");
      }
      Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
        value = +value;
        offset = offset >>> 0;
        byteLength2 = byteLength2 >>> 0;
        if (!noAssert) {
          const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
          checkInt(this, value, offset, byteLength2, maxBytes, 0);
        }
        let mul = 1;
        let i = 0;
        this[offset] = value & 255;
        while (++i < byteLength2 && (mul *= 256)) {
          this[offset + i] = value / mul & 255;
        }
        return offset + byteLength2;
      };
      Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
        value = +value;
        offset = offset >>> 0;
        byteLength2 = byteLength2 >>> 0;
        if (!noAssert) {
          const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
          checkInt(this, value, offset, byteLength2, maxBytes, 0);
        }
        let i = byteLength2 - 1;
        let mul = 1;
        this[offset + i] = value & 255;
        while (--i >= 0 && (mul *= 256)) {
          this[offset + i] = value / mul & 255;
        }
        return offset + byteLength2;
      };
      Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
        this[offset] = value & 255;
        return offset + 1;
      };
      Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
        this[offset] = value & 255;
        this[offset + 1] = value >>> 8;
        return offset + 2;
      };
      Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
        this[offset] = value >>> 8;
        this[offset + 1] = value & 255;
        return offset + 2;
      };
      Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
        this[offset + 3] = value >>> 24;
        this[offset + 2] = value >>> 16;
        this[offset + 1] = value >>> 8;
        this[offset] = value & 255;
        return offset + 4;
      };
      Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
        this[offset] = value >>> 24;
        this[offset + 1] = value >>> 16;
        this[offset + 2] = value >>> 8;
        this[offset + 3] = value & 255;
        return offset + 4;
      };
      function wrtBigUInt64LE(buf, value, offset, min, max) {
        checkIntBI(value, min, max, buf, offset, 7);
        let lo = Number(value & BigInt(4294967295));
        buf[offset++] = lo;
        lo = lo >> 8;
        buf[offset++] = lo;
        lo = lo >> 8;
        buf[offset++] = lo;
        lo = lo >> 8;
        buf[offset++] = lo;
        let hi = Number(value >> BigInt(32) & BigInt(4294967295));
        buf[offset++] = hi;
        hi = hi >> 8;
        buf[offset++] = hi;
        hi = hi >> 8;
        buf[offset++] = hi;
        hi = hi >> 8;
        buf[offset++] = hi;
        return offset;
      }
      function wrtBigUInt64BE(buf, value, offset, min, max) {
        checkIntBI(value, min, max, buf, offset, 7);
        let lo = Number(value & BigInt(4294967295));
        buf[offset + 7] = lo;
        lo = lo >> 8;
        buf[offset + 6] = lo;
        lo = lo >> 8;
        buf[offset + 5] = lo;
        lo = lo >> 8;
        buf[offset + 4] = lo;
        let hi = Number(value >> BigInt(32) & BigInt(4294967295));
        buf[offset + 3] = hi;
        hi = hi >> 8;
        buf[offset + 2] = hi;
        hi = hi >> 8;
        buf[offset + 1] = hi;
        hi = hi >> 8;
        buf[offset] = hi;
        return offset + 8;
      }
      Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
        return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
      });
      Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
        return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
      });
      Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) {
          const limit = Math.pow(2, 8 * byteLength2 - 1);
          checkInt(this, value, offset, byteLength2, limit - 1, -limit);
        }
        let i = 0;
        let mul = 1;
        let sub = 0;
        this[offset] = value & 255;
        while (++i < byteLength2 && (mul *= 256)) {
          if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
            sub = 1;
          }
          this[offset + i] = (value / mul >> 0) - sub & 255;
        }
        return offset + byteLength2;
      };
      Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) {
          const limit = Math.pow(2, 8 * byteLength2 - 1);
          checkInt(this, value, offset, byteLength2, limit - 1, -limit);
        }
        let i = byteLength2 - 1;
        let mul = 1;
        let sub = 0;
        this[offset + i] = value & 255;
        while (--i >= 0 && (mul *= 256)) {
          if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
            sub = 1;
          }
          this[offset + i] = (value / mul >> 0) - sub & 255;
        }
        return offset + byteLength2;
      };
      Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
        if (value < 0) value = 255 + value + 1;
        this[offset] = value & 255;
        return offset + 1;
      };
      Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
        this[offset] = value & 255;
        this[offset + 1] = value >>> 8;
        return offset + 2;
      };
      Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
        this[offset] = value >>> 8;
        this[offset + 1] = value & 255;
        return offset + 2;
      };
      Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
        this[offset] = value & 255;
        this[offset + 1] = value >>> 8;
        this[offset + 2] = value >>> 16;
        this[offset + 3] = value >>> 24;
        return offset + 4;
      };
      Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
        if (value < 0) value = 4294967295 + value + 1;
        this[offset] = value >>> 24;
        this[offset + 1] = value >>> 16;
        this[offset + 2] = value >>> 8;
        this[offset + 3] = value & 255;
        return offset + 4;
      };
      Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
        return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
      });
      Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
        return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
      });
      function checkIEEE754(buf, value, offset, ext, max, min) {
        if (offset + ext > buf.length) throw new RangeError("Index out of range");
        if (offset < 0) throw new RangeError("Index out of range");
      }
      function writeFloat(buf, value, offset, littleEndian, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) {
          checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22);
        }
        ieee754.write(buf, value, offset, littleEndian, 23, 4);
        return offset + 4;
      }
      Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
        return writeFloat(this, value, offset, true, noAssert);
      };
      Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
        return writeFloat(this, value, offset, false, noAssert);
      };
      function writeDouble(buf, value, offset, littleEndian, noAssert) {
        value = +value;
        offset = offset >>> 0;
        if (!noAssert) {
          checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292);
        }
        ieee754.write(buf, value, offset, littleEndian, 52, 8);
        return offset + 8;
      }
      Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
        return writeDouble(this, value, offset, true, noAssert);
      };
      Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
        return writeDouble(this, value, offset, false, noAssert);
      };
      Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
        if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer");
        if (!start) start = 0;
        if (!end && end !== 0) end = this.length;
        if (targetStart >= target.length) targetStart = target.length;
        if (!targetStart) targetStart = 0;
        if (end > 0 && end < start) end = start;
        if (end === start) return 0;
        if (target.length === 0 || this.length === 0) return 0;
        if (targetStart < 0) {
          throw new RangeError("targetStart out of bounds");
        }
        if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
        if (end < 0) throw new RangeError("sourceEnd out of bounds");
        if (end > this.length) end = this.length;
        if (target.length - targetStart < end - start) {
          end = target.length - targetStart + start;
        }
        const len = end - start;
        if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
          this.copyWithin(targetStart, start, end);
        } else {
          Uint8Array.prototype.set.call(
            target,
            this.subarray(start, end),
            targetStart
          );
        }
        return len;
      };
      Buffer2.prototype.fill = function fill(val, start, end, encoding) {
        if (typeof val === "string") {
          if (typeof start === "string") {
            encoding = start;
            start = 0;
            end = this.length;
          } else if (typeof end === "string") {
            encoding = end;
            end = this.length;
          }
          if (encoding !== void 0 && typeof encoding !== "string") {
            throw new TypeError("encoding must be a string");
          }
          if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
            throw new TypeError("Unknown encoding: " + encoding);
          }
          if (val.length === 1) {
            const code = val.charCodeAt(0);
            if (encoding === "utf8" && code < 128 || encoding === "latin1") {
              val = code;
            }
          }
        } else if (typeof val === "number") {
          val = val & 255;
        } else if (typeof val === "boolean") {
          val = Number(val);
        }
        if (start < 0 || this.length < start || this.length < end) {
          throw new RangeError("Out of range index");
        }
        if (end <= start) {
          return this;
        }
        start = start >>> 0;
        end = end === void 0 ? this.length : end >>> 0;
        if (!val) val = 0;
        let i;
        if (typeof val === "number") {
          for (i = start; i < end; ++i) {
            this[i] = val;
          }
        } else {
          const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding);
          const len = bytes.length;
          if (len === 0) {
            throw new TypeError('The value "' + val + '" is invalid for argument "value"');
          }
          for (i = 0; i < end - start; ++i) {
            this[i + start] = bytes[i % len];
          }
        }
        return this;
      };
      var errors = {};
      function E2(sym, getMessage, Base) {
        errors[sym] = class NodeError extends Base {
          constructor() {
            super();
            Object.defineProperty(this, "message", {
              value: getMessage.apply(this, arguments),
              writable: true,
              configurable: true
            });
            this.name = `${this.name} [${sym}]`;
            this.stack;
            delete this.name;
          }
          get code() {
            return sym;
          }
          set code(value) {
            Object.defineProperty(this, "code", {
              configurable: true,
              enumerable: true,
              value,
              writable: true
            });
          }
          toString() {
            return `${this.name} [${sym}]: ${this.message}`;
          }
        };
      }
      E2(
        "ERR_BUFFER_OUT_OF_BOUNDS",
        function(name2) {
          if (name2) {
            return `${name2} is outside of buffer bounds`;
          }
          return "Attempt to access memory outside buffer bounds";
        },
        RangeError
      );
      E2(
        "ERR_INVALID_ARG_TYPE",
        function(name2, actual) {
          return `The "${name2}" argument must be of type number. Received type ${typeof actual}`;
        },
        TypeError
      );
      E2(
        "ERR_OUT_OF_RANGE",
        function(str, range, input) {
          let msg = `The value of "${str}" is out of range.`;
          let received = input;
          if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
            received = addNumericalSeparator(String(input));
          } else if (typeof input === "bigint") {
            received = String(input);
            if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
              received = addNumericalSeparator(received);
            }
            received += "n";
          }
          msg += ` It must be ${range}. Received ${received}`;
          return msg;
        },
        RangeError
      );
      function addNumericalSeparator(val) {
        let res = "";
        let i = val.length;
        const start = val[0] === "-" ? 1 : 0;
        for (; i >= start + 4; i -= 3) {
          res = `_${val.slice(i - 3, i)}${res}`;
        }
        return `${val.slice(0, i)}${res}`;
      }
      function checkBounds(buf, offset, byteLength2) {
        validateNumber(offset, "offset");
        if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
          boundsError(offset, buf.length - (byteLength2 + 1));
        }
      }
      function checkIntBI(value, min, max, buf, offset, byteLength2) {
        if (value > max || value < min) {
          const n = typeof min === "bigint" ? "n" : "";
          let range;
          if (byteLength2 > 3) {
            if (min === 0 || min === BigInt(0)) {
              range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
            } else {
              range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
            }
          } else {
            range = `>= ${min}${n} and <= ${max}${n}`;
          }
          throw new errors.ERR_OUT_OF_RANGE("value", range, value);
        }
        checkBounds(buf, offset, byteLength2);
      }
      function validateNumber(value, name2) {
        if (typeof value !== "number") {
          throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value);
        }
      }
      function boundsError(value, length, type) {
        if (Math.floor(value) !== value) {
          validateNumber(value, type);
          throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value);
        }
        if (length < 0) {
          throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
        }
        throw new errors.ERR_OUT_OF_RANGE(
          type || "offset",
          `>= ${type ? 1 : 0} and <= ${length}`,
          value
        );
      }
      var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
      function base64clean(str) {
        str = str.split("=")[0];
        str = str.trim().replace(INVALID_BASE64_RE, "");
        if (str.length < 2) return "";
        while (str.length % 4 !== 0) {
          str = str + "=";
        }
        return str;
      }
      function utf8ToBytes(string, units) {
        units = units || Infinity;
        let codePoint;
        const length = string.length;
        let leadSurrogate = null;
        const bytes = [];
        for (let i = 0; i < length; ++i) {
          codePoint = string.charCodeAt(i);
          if (codePoint > 55295 && codePoint < 57344) {
            if (!leadSurrogate) {
              if (codePoint > 56319) {
                if ((units -= 3) > -1) bytes.push(239, 191, 189);
                continue;
              } else if (i + 1 === length) {
                if ((units -= 3) > -1) bytes.push(239, 191, 189);
                continue;
              }
              leadSurrogate = codePoint;
              continue;
            }
            if (codePoint < 56320) {
              if ((units -= 3) > -1) bytes.push(239, 191, 189);
              leadSurrogate = codePoint;
              continue;
            }
            codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
          } else if (leadSurrogate) {
            if ((units -= 3) > -1) bytes.push(239, 191, 189);
          }
          leadSurrogate = null;
          if (codePoint < 128) {
            if ((units -= 1) < 0) break;
            bytes.push(codePoint);
          } else if (codePoint < 2048) {
            if ((units -= 2) < 0) break;
            bytes.push(
              codePoint >> 6 | 192,
              codePoint & 63 | 128
            );
          } else if (codePoint < 65536) {
            if ((units -= 3) < 0) break;
            bytes.push(
              codePoint >> 12 | 224,
              codePoint >> 6 & 63 | 128,
              codePoint & 63 | 128
            );
          } else if (codePoint < 1114112) {
            if ((units -= 4) < 0) break;
            bytes.push(
              codePoint >> 18 | 240,
              codePoint >> 12 & 63 | 128,
              codePoint >> 6 & 63 | 128,
              codePoint & 63 | 128
            );
          } else {
            throw new Error("Invalid code point");
          }
        }
        return bytes;
      }
      function asciiToBytes(str) {
        const byteArray = [];
        for (let i = 0; i < str.length; ++i) {
          byteArray.push(str.charCodeAt(i) & 255);
        }
        return byteArray;
      }
      function utf16leToBytes(str, units) {
        let c, hi, lo;
        const byteArray = [];
        for (let i = 0; i < str.length; ++i) {
          if ((units -= 2) < 0) break;
          c = str.charCodeAt(i);
          hi = c >> 8;
          lo = c % 256;
          byteArray.push(lo);
          byteArray.push(hi);
        }
        return byteArray;
      }
      function base64ToBytes(str) {
        return base64.toByteArray(base64clean(str));
      }
      function blitBuffer(src, dst, offset, length) {
        let i;
        for (i = 0; i < length; ++i) {
          if (i + offset >= dst.length || i >= src.length) break;
          dst[i + offset] = src[i];
        }
        return i;
      }
      function isInstance(obj, type) {
        return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
      }
      function numberIsNaN(obj) {
        return obj !== obj;
      }
      var hexSliceLookupTable = function() {
        const alphabet = "0123456789abcdef";
        const table = new Array(256);
        for (let i = 0; i < 16; ++i) {
          const i16 = i * 16;
          for (let j = 0; j < 16; ++j) {
            table[i16 + j] = alphabet[i] + alphabet[j];
          }
        }
        return table;
      }();
      function defineBigIntMethod(fn) {
        return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
      }
      function BufferBigIntNotDefined() {
        throw new Error("BigInt not supported");
      }
    }
  });

  // node_modules/has-symbols/shams.js
  var require_shams = __commonJS({
    "node_modules/has-symbols/shams.js"(exports, module) {
      "use strict";
      module.exports = function hasSymbols() {
        if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
          return false;
        }
        if (typeof Symbol.iterator === "symbol") {
          return true;
        }
        var obj = {};
        var sym = Symbol("test");
        var symObj = Object(sym);
        if (typeof sym === "string") {
          return false;
        }
        if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
          return false;
        }
        if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
          return false;
        }
        var symVal = 42;
        obj[sym] = symVal;
        for (var _ in obj) {
          return false;
        }
        if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
          return false;
        }
        if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
          return false;
        }
        var syms = Object.getOwnPropertySymbols(obj);
        if (syms.length !== 1 || syms[0] !== sym) {
          return false;
        }
        if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
          return false;
        }
        if (typeof Object.getOwnPropertyDescriptor === "function") {
          var descriptor = (
            /** @type {PropertyDescriptor} */
            Object.getOwnPropertyDescriptor(obj, sym)
          );
          if (descriptor.value !== symVal || descriptor.enumerable !== true) {
            return false;
          }
        }
        return true;
      };
    }
  });

  // node_modules/has-tostringtag/shams.js
  var require_shams2 = __commonJS({
    "node_modules/has-tostringtag/shams.js"(exports, module) {
      "use strict";
      var hasSymbols = require_shams();
      module.exports = function hasToStringTagShams() {
        return hasSymbols() && !!Symbol.toStringTag;
      };
    }
  });

  // node_modules/es-object-atoms/index.js
  var require_es_object_atoms = __commonJS({
    "node_modules/es-object-atoms/index.js"(exports, module) {
      "use strict";
      module.exports = Object;
    }
  });

  // node_modules/es-errors/index.js
  var require_es_errors = __commonJS({
    "node_modules/es-errors/index.js"(exports, module) {
      "use strict";
      module.exports = Error;
    }
  });

  // node_modules/es-errors/eval.js
  var require_eval = __commonJS({
    "node_modules/es-errors/eval.js"(exports, module) {
      "use strict";
      module.exports = EvalError;
    }
  });

  // node_modules/es-errors/range.js
  var require_range = __commonJS({
    "node_modules/es-errors/range.js"(exports, module) {
      "use strict";
      module.exports = RangeError;
    }
  });

  // node_modules/es-errors/ref.js
  var require_ref = __commonJS({
    "node_modules/es-errors/ref.js"(exports, module) {
      "use strict";
      module.exports = ReferenceError;
    }
  });

  // node_modules/es-errors/syntax.js
  var require_syntax = __commonJS({
    "node_modules/es-errors/syntax.js"(exports, module) {
      "use strict";
      module.exports = SyntaxError;
    }
  });

  // node_modules/es-errors/type.js
  var require_type = __commonJS({
    "node_modules/es-errors/type.js"(exports, module) {
      "use strict";
      module.exports = TypeError;
    }
  });

  // node_modules/es-errors/uri.js
  var require_uri = __commonJS({
    "node_modules/es-errors/uri.js"(exports, module) {
      "use strict";
      module.exports = URIError;
    }
  });

  // node_modules/math-intrinsics/abs.js
  var require_abs = __commonJS({
    "node_modules/math-intrinsics/abs.js"(exports, module) {
      "use strict";
      module.exports = Math.abs;
    }
  });

  // node_modules/math-intrinsics/floor.js
  var require_floor = __commonJS({
    "node_modules/math-intrinsics/floor.js"(exports, module) {
      "use strict";
      module.exports = Math.floor;
    }
  });

  // node_modules/math-intrinsics/max.js
  var require_max = __commonJS({
    "node_modules/math-intrinsics/max.js"(exports, module) {
      "use strict";
      module.exports = Math.max;
    }
  });

  // node_modules/math-intrinsics/min.js
  var require_min = __commonJS({
    "node_modules/math-intrinsics/min.js"(exports, module) {
      "use strict";
      module.exports = Math.min;
    }
  });

  // node_modules/math-intrinsics/pow.js
  var require_pow = __commonJS({
    "node_modules/math-intrinsics/pow.js"(exports, module) {
      "use strict";
      module.exports = Math.pow;
    }
  });

  // node_modules/math-intrinsics/round.js
  var require_round = __commonJS({
    "node_modules/math-intrinsics/round.js"(exports, module) {
      "use strict";
      module.exports = Math.round;
    }
  });

  // node_modules/math-intrinsics/isNaN.js
  var require_isNaN = __commonJS({
    "node_modules/math-intrinsics/isNaN.js"(exports, module) {
      "use strict";
      module.exports = Number.isNaN || function isNaN2(a) {
        return a !== a;
      };
    }
  });

  // node_modules/math-intrinsics/sign.js
  var require_sign = __commonJS({
    "node_modules/math-intrinsics/sign.js"(exports, module) {
      "use strict";
      var $isNaN = require_isNaN();
      module.exports = function sign(number) {
        if ($isNaN(number) || number === 0) {
          return number;
        }
        return number < 0 ? -1 : 1;
      };
    }
  });

  // node_modules/gopd/gOPD.js
  var require_gOPD = __commonJS({
    "node_modules/gopd/gOPD.js"(exports, module) {
      "use strict";
      module.exports = Object.getOwnPropertyDescriptor;
    }
  });

  // node_modules/gopd/index.js
  var require_gopd = __commonJS({
    "node_modules/gopd/index.js"(exports, module) {
      "use strict";
      var $gOPD = require_gOPD();
      if ($gOPD) {
        try {
          $gOPD([], "length");
        } catch (e) {
          $gOPD = null;
        }
      }
      module.exports = $gOPD;
    }
  });

  // node_modules/es-define-property/index.js
  var require_es_define_property = __commonJS({
    "node_modules/es-define-property/index.js"(exports, module) {
      "use strict";
      var $defineProperty = Object.defineProperty || false;
      if ($defineProperty) {
        try {
          $defineProperty({}, "a", { value: 1 });
        } catch (e) {
          $defineProperty = false;
        }
      }
      module.exports = $defineProperty;
    }
  });

  // node_modules/has-symbols/index.js
  var require_has_symbols = __commonJS({
    "node_modules/has-symbols/index.js"(exports, module) {
      "use strict";
      var origSymbol = typeof Symbol !== "undefined" && Symbol;
      var hasSymbolSham = require_shams();
      module.exports = function hasNativeSymbols() {
        if (typeof origSymbol !== "function") {
          return false;
        }
        if (typeof Symbol !== "function") {
          return false;
        }
        if (typeof origSymbol("foo") !== "symbol") {
          return false;
        }
        if (typeof Symbol("bar") !== "symbol") {
          return false;
        }
        return hasSymbolSham();
      };
    }
  });

  // node_modules/get-proto/Reflect.getPrototypeOf.js
  var require_Reflect_getPrototypeOf = __commonJS({
    "node_modules/get-proto/Reflect.getPrototypeOf.js"(exports, module) {
      "use strict";
      module.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
    }
  });

  // node_modules/get-proto/Object.getPrototypeOf.js
  var require_Object_getPrototypeOf = __commonJS({
    "node_modules/get-proto/Object.getPrototypeOf.js"(exports, module) {
      "use strict";
      var $Object = require_es_object_atoms();
      module.exports = $Object.getPrototypeOf || null;
    }
  });

  // node_modules/function-bind/implementation.js
  var require_implementation = __commonJS({
    "node_modules/function-bind/implementation.js"(exports, module) {
      "use strict";
      var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
      var toStr = Object.prototype.toString;
      var max = Math.max;
      var funcType = "[object Function]";
      var concatty = function concatty2(a, b) {
        var arr = [];
        for (var i = 0; i < a.length; i += 1) {
          arr[i] = a[i];
        }
        for (var j = 0; j < b.length; j += 1) {
          arr[j + a.length] = b[j];
        }
        return arr;
      };
      var slicy = function slicy2(arrLike, offset) {
        var arr = [];
        for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
          arr[j] = arrLike[i];
        }
        return arr;
      };
      var joiny = function(arr, joiner) {
        var str = "";
        for (var i = 0; i < arr.length; i += 1) {
          str += arr[i];
          if (i + 1 < arr.length) {
            str += joiner;
          }
        }
        return str;
      };
      module.exports = function bind(that) {
        var target = this;
        if (typeof target !== "function" || toStr.apply(target) !== funcType) {
          throw new TypeError(ERROR_MESSAGE + target);
        }
        var args = slicy(arguments, 1);
        var bound;
        var binder = function() {
          if (this instanceof bound) {
            var result = target.apply(
              this,
              concatty(args, arguments)
            );
            if (Object(result) === result) {
              return result;
            }
            return this;
          }
          return target.apply(
            that,
            concatty(args, arguments)
          );
        };
        var boundLength = max(0, target.length - args.length);
        var boundArgs = [];
        for (var i = 0; i < boundLength; i++) {
          boundArgs[i] = "$" + i;
        }
        bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
        if (target.prototype) {
          var Empty = function Empty2() {
          };
          Empty.prototype = target.prototype;
          bound.prototype = new Empty();
          Empty.prototype = null;
        }
        return bound;
      };
    }
  });

  // node_modules/function-bind/index.js
  var require_function_bind = __commonJS({
    "node_modules/function-bind/index.js"(exports, module) {
      "use strict";
      var implementation = require_implementation();
      module.exports = Function.prototype.bind || implementation;
    }
  });

  // node_modules/call-bind-apply-helpers/functionCall.js
  var require_functionCall = __commonJS({
    "node_modules/call-bind-apply-helpers/functionCall.js"(exports, module) {
      "use strict";
      module.exports = Function.prototype.call;
    }
  });

  // node_modules/call-bind-apply-helpers/functionApply.js
  var require_functionApply = __commonJS({
    "node_modules/call-bind-apply-helpers/functionApply.js"(exports, module) {
      "use strict";
      module.exports = Function.prototype.apply;
    }
  });

  // node_modules/call-bind-apply-helpers/reflectApply.js
  var require_reflectApply = __commonJS({
    "node_modules/call-bind-apply-helpers/reflectApply.js"(exports, module) {
      "use strict";
      module.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
    }
  });

  // node_modules/call-bind-apply-helpers/actualApply.js
  var require_actualApply = __commonJS({
    "node_modules/call-bind-apply-helpers/actualApply.js"(exports, module) {
      "use strict";
      var bind = require_function_bind();
      var $apply = require_functionApply();
      var $call = require_functionCall();
      var $reflectApply = require_reflectApply();
      module.exports = $reflectApply || bind.call($call, $apply);
    }
  });

  // node_modules/call-bind-apply-helpers/index.js
  var require_call_bind_apply_helpers = __commonJS({
    "node_modules/call-bind-apply-helpers/index.js"(exports, module) {
      "use strict";
      var bind = require_function_bind();
      var $TypeError = require_type();
      var $call = require_functionCall();
      var $actualApply = require_actualApply();
      module.exports = function callBindBasic(args) {
        if (args.length < 1 || typeof args[0] !== "function") {
          throw new $TypeError("a function is required");
        }
        return $actualApply(bind, $call, args);
      };
    }
  });

  // node_modules/dunder-proto/get.js
  var require_get = __commonJS({
    "node_modules/dunder-proto/get.js"(exports, module) {
      "use strict";
      var callBind = require_call_bind_apply_helpers();
      var gOPD = require_gopd();
      var hasProtoAccessor;
      try {
        hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
        [].__proto__ === Array.prototype;
      } catch (e) {
        if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") {
          throw e;
        }
      }
      var desc = !!hasProtoAccessor && gOPD && gOPD(
        Object.prototype,
        /** @type {keyof typeof Object.prototype} */
        "__proto__"
      );
      var $Object = Object;
      var $getPrototypeOf = $Object.getPrototypeOf;
      module.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? (
        /** @type {import('./get')} */
        function getDunder(value) {
          return $getPrototypeOf(value == null ? value : $Object(value));
        }
      ) : false;
    }
  });

  // node_modules/get-proto/index.js
  var require_get_proto = __commonJS({
    "node_modules/get-proto/index.js"(exports, module) {
      "use strict";
      var reflectGetProto = require_Reflect_getPrototypeOf();
      var originalGetProto = require_Object_getPrototypeOf();
      var getDunderProto = require_get();
      module.exports = reflectGetProto ? function getProto(O) {
        return reflectGetProto(O);
      } : originalGetProto ? function getProto(O) {
        if (!O || typeof O !== "object" && typeof O !== "function") {
          throw new TypeError("getProto: not an object");
        }
        return originalGetProto(O);
      } : getDunderProto ? function getProto(O) {
        return getDunderProto(O);
      } : null;
    }
  });

  // node_modules/hasown/index.js
  var require_hasown = __commonJS({
    "node_modules/hasown/index.js"(exports, module) {
      "use strict";
      var call = Function.prototype.call;
      var $hasOwn = Object.prototype.hasOwnProperty;
      var bind = require_function_bind();
      module.exports = bind.call(call, $hasOwn);
    }
  });

  // node_modules/get-intrinsic/index.js
  var require_get_intrinsic = __commonJS({
    "node_modules/get-intrinsic/index.js"(exports, module) {
      "use strict";
      var undefined2;
      var $Object = require_es_object_atoms();
      var $Error = require_es_errors();
      var $EvalError = require_eval();
      var $RangeError = require_range();
      var $ReferenceError = require_ref();
      var $SyntaxError = require_syntax();
      var $TypeError = require_type();
      var $URIError = require_uri();
      var abs = require_abs();
      var floor = require_floor();
      var max = require_max();
      var min = require_min();
      var pow = require_pow();
      var round = require_round();
      var sign = require_sign();
      var $Function = Function;
      var getEvalledConstructor = function(expressionSyntax) {
        try {
          return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
        } catch (e) {
        }
      };
      var $gOPD = require_gopd();
      var $defineProperty = require_es_define_property();
      var throwTypeError = function() {
        throw new $TypeError();
      };
      var ThrowTypeError = $gOPD ? function() {
        try {
          arguments.callee;
          return throwTypeError;
        } catch (calleeThrows) {
          try {
            return $gOPD(arguments, "callee").get;
          } catch (gOPDthrows) {
            return throwTypeError;
          }
        }
      }() : throwTypeError;
      var hasSymbols = require_has_symbols()();
      var getProto = require_get_proto();
      var $ObjectGPO = require_Object_getPrototypeOf();
      var $ReflectGPO = require_Reflect_getPrototypeOf();
      var $apply = require_functionApply();
      var $call = require_functionCall();
      var needsEval = {};
      var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array);
      var INTRINSICS = {
        __proto__: null,
        "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError,
        "%Array%": Array,
        "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer,
        "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2,
        "%AsyncFromSyncIteratorPrototype%": undefined2,
        "%AsyncFunction%": needsEval,
        "%AsyncGenerator%": needsEval,
        "%AsyncGeneratorFunction%": needsEval,
        "%AsyncIteratorPrototype%": needsEval,
        "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics,
        "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt,
        "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array,
        "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array,
        "%Boolean%": Boolean,
        "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView,
        "%Date%": Date,
        "%decodeURI%": decodeURI,
        "%decodeURIComponent%": decodeURIComponent,
        "%encodeURI%": encodeURI,
        "%encodeURIComponent%": encodeURIComponent,
        "%Error%": $Error,
        "%eval%": eval,
        // eslint-disable-line no-eval
        "%EvalError%": $EvalError,
        "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array,
        "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array,
        "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array,
        "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry,
        "%Function%": $Function,
        "%GeneratorFunction%": needsEval,
        "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array,
        "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array,
        "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array,
        "%isFinite%": isFinite,
        "%isNaN%": isNaN,
        "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2,
        "%JSON%": typeof JSON === "object" ? JSON : undefined2,
        "%Map%": typeof Map === "undefined" ? undefined2 : Map,
        "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()),
        "%Math%": Math,
        "%Number%": Number,
        "%Object%": $Object,
        "%Object.getOwnPropertyDescriptor%": $gOPD,
        "%parseFloat%": parseFloat,
        "%parseInt%": parseInt,
        "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise,
        "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy,
        "%RangeError%": $RangeError,
        "%ReferenceError%": $ReferenceError,
        "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect,
        "%RegExp%": RegExp,
        "%Set%": typeof Set === "undefined" ? undefined2 : Set,
        "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()),
        "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer,
        "%String%": String,
        "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2,
        "%Symbol%": hasSymbols ? Symbol : undefined2,
        "%SyntaxError%": $SyntaxError,
        "%ThrowTypeError%": ThrowTypeError,
        "%TypedArray%": TypedArray,
        "%TypeError%": $TypeError,
        "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array,
        "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray,
        "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array,
        "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array,
        "%URIError%": $URIError,
        "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap,
        "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef,
        "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet,
        "%Function.prototype.call%": $call,
        "%Function.prototype.apply%": $apply,
        "%Object.defineProperty%": $defineProperty,
        "%Object.getPrototypeOf%": $ObjectGPO,
        "%Math.abs%": abs,
        "%Math.floor%": floor,
        "%Math.max%": max,
        "%Math.min%": min,
        "%Math.pow%": pow,
        "%Math.round%": round,
        "%Math.sign%": sign,
        "%Reflect.getPrototypeOf%": $ReflectGPO
      };
      if (getProto) {
        try {
          null.error;
        } catch (e) {
          errorProto = getProto(getProto(e));
          INTRINSICS["%Error.prototype%"] = errorProto;
        }
      }
      var errorProto;
      var doEval = function doEval2(name2) {
        var value;
        if (name2 === "%AsyncFunction%") {
          value = getEvalledConstructor("async function () {}");
        } else if (name2 === "%GeneratorFunction%") {
          value = getEvalledConstructor("function* () {}");
        } else if (name2 === "%AsyncGeneratorFunction%") {
          value = getEvalledConstructor("async function* () {}");
        } else if (name2 === "%AsyncGenerator%") {
          var fn = doEval2("%AsyncGeneratorFunction%");
          if (fn) {
            value = fn.prototype;
          }
        } else if (name2 === "%AsyncIteratorPrototype%") {
          var gen = doEval2("%AsyncGenerator%");
          if (gen && getProto) {
            value = getProto(gen.prototype);
          }
        }
        INTRINSICS[name2] = value;
        return value;
      };
      var LEGACY_ALIASES = {
        __proto__: null,
        "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
        "%ArrayPrototype%": ["Array", "prototype"],
        "%ArrayProto_entries%": ["Array", "prototype", "entries"],
        "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
        "%ArrayProto_keys%": ["Array", "prototype", "keys"],
        "%ArrayProto_values%": ["Array", "prototype", "values"],
        "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
        "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
        "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
        "%BooleanPrototype%": ["Boolean", "prototype"],
        "%DataViewPrototype%": ["DataView", "prototype"],
        "%DatePrototype%": ["Date", "prototype"],
        "%ErrorPrototype%": ["Error", "prototype"],
        "%EvalErrorPrototype%": ["EvalError", "prototype"],
        "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
        "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
        "%FunctionPrototype%": ["Function", "prototype"],
        "%Generator%": ["GeneratorFunction", "prototype"],
        "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
        "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
        "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
        "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
        "%JSONParse%": ["JSON", "parse"],
        "%JSONStringify%": ["JSON", "stringify"],
        "%MapPrototype%": ["Map", "prototype"],
        "%NumberPrototype%": ["Number", "prototype"],
        "%ObjectPrototype%": ["Object", "prototype"],
        "%ObjProto_toString%": ["Object", "prototype", "toString"],
        "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
        "%PromisePrototype%": ["Promise", "prototype"],
        "%PromiseProto_then%": ["Promise", "prototype", "then"],
        "%Promise_all%": ["Promise", "all"],
        "%Promise_reject%": ["Promise", "reject"],
        "%Promise_resolve%": ["Promise", "resolve"],
        "%RangeErrorPrototype%": ["RangeError", "prototype"],
        "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
        "%RegExpPrototype%": ["RegExp", "prototype"],
        "%SetPrototype%": ["Set", "prototype"],
        "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
        "%StringPrototype%": ["String", "prototype"],
        "%SymbolPrototype%": ["Symbol", "prototype"],
        "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
        "%TypedArrayPrototype%": ["TypedArray", "prototype"],
        "%TypeErrorPrototype%": ["TypeError", "prototype"],
        "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
        "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
        "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
        "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
        "%URIErrorPrototype%": ["URIError", "prototype"],
        "%WeakMapPrototype%": ["WeakMap", "prototype"],
        "%WeakSetPrototype%": ["WeakSet", "prototype"]
      };
      var bind = require_function_bind();
      var hasOwn = require_hasown();
      var $concat = bind.call($call, Array.prototype.concat);
      var $spliceApply = bind.call($apply, Array.prototype.splice);
      var $replace = bind.call($call, String.prototype.replace);
      var $strSlice = bind.call($call, String.prototype.slice);
      var $exec = bind.call($call, RegExp.prototype.exec);
      var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
      var reEscapeChar = /\\(\\)?/g;
      var stringToPath = function stringToPath2(string) {
        var first = $strSlice(string, 0, 1);
        var last = $strSlice(string, -1);
        if (first === "%" && last !== "%") {
          throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
        } else if (last === "%" && first !== "%") {
          throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
        }
        var result = [];
        $replace(string, rePropName, function(match, number, quote, subString) {
          result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match;
        });
        return result;
      };
      var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) {
        var intrinsicName = name2;
        var alias;
        if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
          alias = LEGACY_ALIASES[intrinsicName];
          intrinsicName = "%" + alias[0] + "%";
        }
        if (hasOwn(INTRINSICS, intrinsicName)) {
          var value = INTRINSICS[intrinsicName];
          if (value === needsEval) {
            value = doEval(intrinsicName);
          }
          if (typeof value === "undefined" && !allowMissing) {
            throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!");
          }
          return {
            alias,
            name: intrinsicName,
            value
          };
        }
        throw new $SyntaxError("intrinsic " + name2 + " does not exist!");
      };
      module.exports = function GetIntrinsic(name2, allowMissing) {
        if (typeof name2 !== "string" || name2.length === 0) {
          throw new $TypeError("intrinsic name must be a non-empty string");
        }
        if (arguments.length > 1 && typeof allowMissing !== "boolean") {
          throw new $TypeError('"allowMissing" argument must be a boolean');
        }
        if ($exec(/^%?[^%]*%?$/, name2) === null) {
          throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
        }
        var parts = stringToPath(name2);
        var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
        var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
        var intrinsicRealName = intrinsic.name;
        var value = intrinsic.value;
        var skipFurtherCaching = false;
        var alias = intrinsic.alias;
        if (alias) {
          intrinsicBaseName = alias[0];
          $spliceApply(parts, $concat([0, 1], alias));
        }
        for (var i = 1, isOwn = true; i < parts.length; i += 1) {
          var part = parts[i];
          var first = $strSlice(part, 0, 1);
          var last = $strSlice(part, -1);
          if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
            throw new $SyntaxError("property names with quotes must have matching quotes");
          }
          if (part === "constructor" || !isOwn) {
            skipFurtherCaching = true;
          }
          intrinsicBaseName += "." + part;
          intrinsicRealName = "%" + intrinsicBaseName + "%";
          if (hasOwn(INTRINSICS, intrinsicRealName)) {
            value = INTRINSICS[intrinsicRealName];
          } else if (value != null) {
            if (!(part in value)) {
              if (!allowMissing) {
                throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available.");
              }
              return void undefined2;
            }
            if ($gOPD && i + 1 >= parts.length) {
              var desc = $gOPD(value, part);
              isOwn = !!desc;
              if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
                value = desc.get;
              } else {
                value = value[part];
              }
            } else {
              isOwn = hasOwn(value, part);
              value = value[part];
            }
            if (isOwn && !skipFurtherCaching) {
              INTRINSICS[intrinsicRealName] = value;
            }
          }
        }
        return value;
      };
    }
  });

  // node_modules/define-data-property/index.js
  var require_define_data_property = __commonJS({
    "node_modules/define-data-property/index.js"(exports, module) {
      "use strict";
      var $defineProperty = require_es_define_property();
      var $SyntaxError = require_syntax();
      var $TypeError = require_type();
      var gopd = require_gopd();
      module.exports = function defineDataProperty(obj, property, value) {
        if (!obj || typeof obj !== "object" && typeof obj !== "function") {
          throw new $TypeError("`obj` must be an object or a function`");
        }
        if (typeof property !== "string" && typeof property !== "symbol") {
          throw new $TypeError("`property` must be a string or a symbol`");
        }
        if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) {
          throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null");
        }
        if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) {
          throw new $TypeError("`nonWritable`, if provided, must be a boolean or null");
        }
        if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) {
          throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null");
        }
        if (arguments.length > 6 && typeof arguments[6] !== "boolean") {
          throw new $TypeError("`loose`, if provided, must be a boolean");
        }
        var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
        var nonWritable = arguments.length > 4 ? arguments[4] : null;
        var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
        var loose = arguments.length > 6 ? arguments[6] : false;
        var desc = !!gopd && gopd(obj, property);
        if ($defineProperty) {
          $defineProperty(obj, property, {
            configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
            enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
            value,
            writable: nonWritable === null && desc ? desc.writable : !nonWritable
          });
        } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) {
          obj[property] = value;
        } else {
          throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
        }
      };
    }
  });

  // node_modules/has-property-descriptors/index.js
  var require_has_property_descriptors = __commonJS({
    "node_modules/has-property-descriptors/index.js"(exports, module) {
      "use strict";
      var $defineProperty = require_es_define_property();
      var hasPropertyDescriptors = function hasPropertyDescriptors2() {
        return !!$defineProperty;
      };
      hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
        if (!$defineProperty) {
          return null;
        }
        try {
          return $defineProperty([], "length", { value: 1 }).length !== 1;
        } catch (e) {
          return true;
        }
      };
      module.exports = hasPropertyDescriptors;
    }
  });

  // node_modules/set-function-length/index.js
  var require_set_function_length = __commonJS({
    "node_modules/set-function-length/index.js"(exports, module) {
      "use strict";
      var GetIntrinsic = require_get_intrinsic();
      var define2 = require_define_data_property();
      var hasDescriptors = require_has_property_descriptors()();
      var gOPD = require_gopd();
      var $TypeError = require_type();
      var $floor = GetIntrinsic("%Math.floor%");
      module.exports = function setFunctionLength(fn, length) {
        if (typeof fn !== "function") {
          throw new $TypeError("`fn` is not a function");
        }
        if (typeof length !== "number" || length < 0 || length > 4294967295 || $floor(length) !== length) {
          throw new $TypeError("`length` must be a positive 32-bit integer");
        }
        var loose = arguments.length > 2 && !!arguments[2];
        var functionLengthIsConfigurable = true;
        var functionLengthIsWritable = true;
        if ("length" in fn && gOPD) {
          var desc = gOPD(fn, "length");
          if (desc && !desc.configurable) {
            functionLengthIsConfigurable = false;
          }
          if (desc && !desc.writable) {
            functionLengthIsWritable = false;
          }
        }
        if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
          if (hasDescriptors) {
            define2(
              /** @type {Parameters<define>[0]} */
              fn,
              "length",
              length,
              true,
              true
            );
          } else {
            define2(
              /** @type {Parameters<define>[0]} */
              fn,
              "length",
              length
            );
          }
        }
        return fn;
      };
    }
  });

  // node_modules/call-bind/index.js
  var require_call_bind = __commonJS({
    "node_modules/call-bind/index.js"(exports, module) {
      "use strict";
      var bind = require_function_bind();
      var GetIntrinsic = require_get_intrinsic();
      var setFunctionLength = require_set_function_length();
      var $TypeError = require_type();
      var $apply = GetIntrinsic("%Function.prototype.apply%");
      var $call = GetIntrinsic("%Function.prototype.call%");
      var $reflectApply = GetIntrinsic("%Reflect.apply%", true) || bind.call($call, $apply);
      var $defineProperty = require_es_define_property();
      var $max = GetIntrinsic("%Math.max%");
      module.exports = function callBind(originalFunction) {
        if (typeof originalFunction !== "function") {
          throw new $TypeError("a function is required");
        }
        var func = $reflectApply(bind, $call, arguments);
        return setFunctionLength(
          func,
          1 + $max(0, originalFunction.length - (arguments.length - 1)),
          true
        );
      };
      var applyBind = function applyBind2() {
        return $reflectApply(bind, $apply, arguments);
      };
      if ($defineProperty) {
        $defineProperty(module.exports, "apply", { value: applyBind });
      } else {
        module.exports.apply = applyBind;
      }
    }
  });

  // node_modules/call-bind/callBound.js
  var require_callBound = __commonJS({
    "node_modules/call-bind/callBound.js"(exports, module) {
      "use strict";
      var GetIntrinsic = require_get_intrinsic();
      var callBind = require_call_bind();
      var $indexOf = callBind(GetIntrinsic("String.prototype.indexOf"));
      module.exports = function callBoundIntrinsic(name2, allowMissing) {
        var intrinsic = GetIntrinsic(name2, !!allowMissing);
        if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) {
          return callBind(intrinsic);
        }
        return intrinsic;
      };
    }
  });

  // node_modules/is-arguments/index.js
  var require_is_arguments = __commonJS({
    "node_modules/is-arguments/index.js"(exports, module) {
      "use strict";
      var hasToStringTag = require_shams2()();
      var callBound = require_callBound();
      var $toString = callBound("Object.prototype.toString");
      var isStandardArguments = function isArguments(value) {
        if (hasToStringTag && value && typeof value === "object" && Symbol.toStringTag in value) {
          return false;
        }
        return $toString(value) === "[object Arguments]";
      };
      var isLegacyArguments = function isArguments(value) {
        if (isStandardArguments(value)) {
          return true;
        }
        return value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && $toString(value) !== "[object Array]" && $toString(value.callee) === "[object Function]";
      };
      var supportsStandardArguments = function() {
        return isStandardArguments(arguments);
      }();
      isStandardArguments.isLegacyArguments = isLegacyArguments;
      module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
    }
  });

  // node_modules/is-generator-function/index.js
  var require_is_generator_function = __commonJS({
    "node_modules/is-generator-function/index.js"(exports, module) {
      "use strict";
      var toStr = Object.prototype.toString;
      var fnToStr = Function.prototype.toString;
      var isFnRegex = /^\s*(?:function)?\*/;
      var hasToStringTag = require_shams2()();
      var getProto = Object.getPrototypeOf;
      var getGeneratorFunc = function() {
        if (!hasToStringTag) {
          return false;
        }
        try {
          return Function("return function*() {}")();
        } catch (e) {
        }
      };
      var GeneratorFunction;
      module.exports = function isGeneratorFunction(fn) {
        if (typeof fn !== "function") {
          return false;
        }
        if (isFnRegex.test(fnToStr.call(fn))) {
          return true;
        }
        if (!hasToStringTag) {
          var str = toStr.call(fn);
          return str === "[object GeneratorFunction]";
        }
        if (!getProto) {
          return false;
        }
        if (typeof GeneratorFunction === "undefined") {
          var generatorFunc = getGeneratorFunc();
          GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;
        }
        return getProto(fn) === GeneratorFunction;
      };
    }
  });

  // node_modules/is-callable/index.js
  var require_is_callable = __commonJS({
    "node_modules/is-callable/index.js"(exports, module) {
      "use strict";
      var fnToStr = Function.prototype.toString;
      var reflectApply = typeof Reflect === "object" && Reflect !== null && Reflect.apply;
      var badArrayLike;
      var isCallableMarker;
      if (typeof reflectApply === "function" && typeof Object.defineProperty === "function") {
        try {
          badArrayLike = Object.defineProperty({}, "length", {
            get: function() {
              throw isCallableMarker;
            }
          });
          isCallableMarker = {};
          reflectApply(function() {
            throw 42;
          }, null, badArrayLike);
        } catch (_) {
          if (_ !== isCallableMarker) {
            reflectApply = null;
          }
        }
      } else {
        reflectApply = null;
      }
      var constructorRegex = /^\s*class\b/;
      var isES6ClassFn = function isES6ClassFunction(value) {
        try {
          var fnStr = fnToStr.call(value);
          return constructorRegex.test(fnStr);
        } catch (e) {
          return false;
        }
      };
      var tryFunctionObject = function tryFunctionToStr(value) {
        try {
          if (isES6ClassFn(value)) {
            return false;
          }
          fnToStr.call(value);
          return true;
        } catch (e) {
          return false;
        }
      };
      var toStr = Object.prototype.toString;
      var objectClass = "[object Object]";
      var fnClass = "[object Function]";
      var genClass = "[object GeneratorFunction]";
      var ddaClass = "[object HTMLAllCollection]";
      var ddaClass2 = "[object HTML document.all class]";
      var ddaClass3 = "[object HTMLCollection]";
      var hasToStringTag = typeof Symbol === "function" && !!Symbol.toStringTag;
      var isIE68 = !(0 in [,]);
      var isDDA = function isDocumentDotAll() {
        return false;
      };
      if (typeof document === "object") {
        all = document.all;
        if (toStr.call(all) === toStr.call(document.all)) {
          isDDA = function isDocumentDotAll(value) {
            if ((isIE68 || !value) && (typeof value === "undefined" || typeof value === "object")) {
              try {
                var str = toStr.call(value);
                return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null;
              } catch (e) {
              }
            }
            return false;
          };
        }
      }
      var all;
      module.exports = reflectApply ? function isCallable(value) {
        if (isDDA(value)) {
          return true;
        }
        if (!value) {
          return false;
        }
        if (typeof value !== "function" && typeof value !== "object") {
          return false;
        }
        try {
          reflectApply(value, null, badArrayLike);
        } catch (e) {
          if (e !== isCallableMarker) {
            return false;
          }
        }
        return !isES6ClassFn(value) && tryFunctionObject(value);
      } : function isCallable(value) {
        if (isDDA(value)) {
          return true;
        }
        if (!value) {
          return false;
        }
        if (typeof value !== "function" && typeof value !== "object") {
          return false;
        }
        if (hasToStringTag) {
          return tryFunctionObject(value);
        }
        if (isES6ClassFn(value)) {
          return false;
        }
        var strClass = toStr.call(value);
        if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass)) {
          return false;
        }
        return tryFunctionObject(value);
      };
    }
  });

  // node_modules/for-each/index.js
  var require_for_each = __commonJS({
    "node_modules/for-each/index.js"(exports, module) {
      "use strict";
      var isCallable = require_is_callable();
      var toStr = Object.prototype.toString;
      var hasOwnProperty2 = Object.prototype.hasOwnProperty;
      var forEachArray = function forEachArray2(array, iterator, receiver) {
        for (var i = 0, len = array.length; i < len; i++) {
          if (hasOwnProperty2.call(array, i)) {
            if (receiver == null) {
              iterator(array[i], i, array);
            } else {
              iterator.call(receiver, array[i], i, array);
            }
          }
        }
      };
      var forEachString = function forEachString2(string, iterator, receiver) {
        for (var i = 0, len = string.length; i < len; i++) {
          if (receiver == null) {
            iterator(string.charAt(i), i, string);
          } else {
            iterator.call(receiver, string.charAt(i), i, string);
          }
        }
      };
      var forEachObject = function forEachObject2(object, iterator, receiver) {
        for (var k in object) {
          if (hasOwnProperty2.call(object, k)) {
            if (receiver == null) {
              iterator(object[k], k, object);
            } else {
              iterator.call(receiver, object[k], k, object);
            }
          }
        }
      };
      var forEach = function forEach2(list, iterator, thisArg) {
        if (!isCallable(iterator)) {
          throw new TypeError("iterator must be a function");
        }
        var receiver;
        if (arguments.length >= 3) {
          receiver = thisArg;
        }
        if (toStr.call(list) === "[object Array]") {
          forEachArray(list, iterator, receiver);
        } else if (typeof list === "string") {
          forEachString(list, iterator, receiver);
        } else {
          forEachObject(list, iterator, receiver);
        }
      };
      module.exports = forEach;
    }
  });

  // node_modules/available-typed-arrays/index.js
  var require_available_typed_arrays = __commonJS({
    "node_modules/available-typed-arrays/index.js"(exports, module) {
      "use strict";
      var possibleNames = [
        "BigInt64Array",
        "BigUint64Array",
        "Float32Array",
        "Float64Array",
        "Int16Array",
        "Int32Array",
        "Int8Array",
        "Uint16Array",
        "Uint32Array",
        "Uint8Array",
        "Uint8ClampedArray"
      ];
      var g = typeof globalThis === "undefined" ? window : globalThis;
      module.exports = function availableTypedArrays() {
        var out = [];
        for (var i = 0; i < possibleNames.length; i++) {
          if (typeof g[possibleNames[i]] === "function") {
            out[out.length] = possibleNames[i];
          }
        }
        return out;
      };
    }
  });

  // node_modules/which-typed-array/index.js
  var require_which_typed_array = __commonJS({
    "node_modules/which-typed-array/index.js"(exports, module) {
      "use strict";
      var forEach = require_for_each();
      var availableTypedArrays = require_available_typed_arrays();
      var callBind = require_call_bind();
      var callBound = require_callBound();
      var gOPD = require_gopd();
      var $toString = callBound("Object.prototype.toString");
      var hasToStringTag = require_shams2()();
      var g = typeof globalThis === "undefined" ? window : globalThis;
      var typedArrays = availableTypedArrays();
      var $slice = callBound("String.prototype.slice");
      var getPrototypeOf = Object.getPrototypeOf;
      var $indexOf = callBound("Array.prototype.indexOf", true) || /** @type {(array: readonly unknown[], value: unknown) => keyof array} */
      function indexOf(array, value) {
        for (var i = 0; i < array.length; i += 1) {
          if (array[i] === value) {
            return i;
          }
        }
        return -1;
      };
      var cache = { __proto__: null };
      if (hasToStringTag && gOPD && getPrototypeOf) {
        forEach(typedArrays, function(typedArray) {
          var arr = new g[typedArray]();
          if (Symbol.toStringTag in arr) {
            var proto = getPrototypeOf(arr);
            var descriptor = gOPD(proto, Symbol.toStringTag);
            if (!descriptor) {
              var superProto = getPrototypeOf(proto);
              descriptor = gOPD(superProto, Symbol.toStringTag);
            }
            cache["$" + typedArray] = callBind(descriptor.get);
          }
        });
      } else {
        forEach(typedArrays, function(typedArray) {
          var arr = new g[typedArray]();
          var fn = arr.slice || arr.set;
          if (fn) {
            cache["$" + typedArray] = callBind(fn);
          }
        });
      }
      var tryTypedArrays = function tryAllTypedArrays(value) {
        var found = false;
        forEach(
          // eslint-disable-next-line no-extra-parens
          /** @type {Record<`\$${TypedArrayName}`, typeof cache>} */
          /** @type {any} */
          cache,
          /** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */
          function(getter, typedArray) {
            if (!found) {
              try {
                if ("$" + getter(value) === typedArray) {
                  found = $slice(typedArray, 1);
                }
              } catch (e) {
              }
            }
          }
        );
        return found;
      };
      var trySlices = function tryAllSlices(value) {
        var found = false;
        forEach(
          // eslint-disable-next-line no-extra-parens
          /** @type {any} */
          cache,
          /** @type {(getter: typeof cache, name: `\$${TypedArrayName}`) => void} */
          function(getter, name2) {
            if (!found) {
              try {
                getter(value);
                found = $slice(name2, 1);
              } catch (e) {
              }
            }
          }
        );
        return found;
      };
      module.exports = function whichTypedArray(value) {
        if (!value || typeof value !== "object") {
          return false;
        }
        if (!hasToStringTag) {
          var tag = $slice($toString(value), 8, -1);
          if ($indexOf(typedArrays, tag) > -1) {
            return tag;
          }
          if (tag !== "Object") {
            return false;
          }
          return trySlices(value);
        }
        if (!gOPD) {
          return null;
        }
        return tryTypedArrays(value);
      };
    }
  });

  // node_modules/is-typed-array/index.js
  var require_is_typed_array = __commonJS({
    "node_modules/is-typed-array/index.js"(exports, module) {
      "use strict";
      var forEach = require_for_each();
      var availableTypedArrays = require_available_typed_arrays();
      var callBound = require_callBound();
      var $toString = callBound("Object.prototype.toString");
      var hasToStringTag = require_shams2()();
      var gOPD = require_gopd();
      var g = typeof globalThis === "undefined" ? window : globalThis;
      var typedArrays = availableTypedArrays();
      var $indexOf = callBound("Array.prototype.indexOf", true) || function indexOf(array, value) {
        for (var i = 0; i < array.length; i += 1) {
          if (array[i] === value) {
            return i;
          }
        }
        return -1;
      };
      var $slice = callBound("String.prototype.slice");
      var toStrTags = {};
      var getPrototypeOf = Object.getPrototypeOf;
      if (hasToStringTag && gOPD && getPrototypeOf) {
        forEach(typedArrays, function(typedArray) {
          var arr = new g[typedArray]();
          if (Symbol.toStringTag in arr) {
            var proto = getPrototypeOf(arr);
            var descriptor = gOPD(proto, Symbol.toStringTag);
            if (!descriptor) {
              var superProto = getPrototypeOf(proto);
              descriptor = gOPD(superProto, Symbol.toStringTag);
            }
            toStrTags[typedArray] = descriptor.get;
          }
        });
      }
      var tryTypedArrays = function tryAllTypedArrays(value) {
        var anyTrue = false;
        forEach(toStrTags, function(getter, typedArray) {
          if (!anyTrue) {
            try {
              anyTrue = getter.call(value) === typedArray;
            } catch (e) {
            }
          }
        });
        return anyTrue;
      };
      module.exports = function isTypedArray(value) {
        if (!value || typeof value !== "object") {
          return false;
        }
        if (!hasToStringTag || !(Symbol.toStringTag in value)) {
          var tag = $slice($toString(value), 8, -1);
          return $indexOf(typedArrays, tag) > -1;
        }
        if (!gOPD) {
          return false;
        }
        return tryTypedArrays(value);
      };
    }
  });

  // node_modules/util/support/types.js
  var require_types = __commonJS({
    "node_modules/util/support/types.js"(exports) {
      "use strict";
      var isArgumentsObject = require_is_arguments();
      var isGeneratorFunction = require_is_generator_function();
      var whichTypedArray = require_which_typed_array();
      var isTypedArray = require_is_typed_array();
      function uncurryThis(f) {
        return f.call.bind(f);
      }
      var BigIntSupported = typeof BigInt !== "undefined";
      var SymbolSupported = typeof Symbol !== "undefined";
      var ObjectToString = uncurryThis(Object.prototype.toString);
      var numberValue = uncurryThis(Number.prototype.valueOf);
      var stringValue = uncurryThis(String.prototype.valueOf);
      var booleanValue = uncurryThis(Boolean.prototype.valueOf);
      if (BigIntSupported) {
        bigIntValue = uncurryThis(BigInt.prototype.valueOf);
      }
      var bigIntValue;
      if (SymbolSupported) {
        symbolValue = uncurryThis(Symbol.prototype.valueOf);
      }
      var symbolValue;
      function checkBoxedPrimitive(value, prototypeValueOf) {
        if (typeof value !== "object") {
          return false;
        }
        try {
          prototypeValueOf(value);
          return true;
        } catch (e) {
          return false;
        }
      }
      exports.isArgumentsObject = isArgumentsObject;
      exports.isGeneratorFunction = isGeneratorFunction;
      exports.isTypedArray = isTypedArray;
      function isPromise(input) {
        return typeof Promise !== "undefined" && input instanceof Promise || input !== null && typeof input === "object" && typeof input.then === "function" && typeof input.catch === "function";
      }
      exports.isPromise = isPromise;
      function isArrayBufferView(value) {
        if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
          return ArrayBuffer.isView(value);
        }
        return isTypedArray(value) || isDataView(value);
      }
      exports.isArrayBufferView = isArrayBufferView;
      function isUint8Array(value) {
        return whichTypedArray(value) === "Uint8Array";
      }
      exports.isUint8Array = isUint8Array;
      function isUint8ClampedArray(value) {
        return whichTypedArray(value) === "Uint8ClampedArray";
      }
      exports.isUint8ClampedArray = isUint8ClampedArray;
      function isUint16Array(value) {
        return whichTypedArray(value) === "Uint16Array";
      }
      exports.isUint16Array = isUint16Array;
      function isUint32Array(value) {
        return whichTypedArray(value) === "Uint32Array";
      }
      exports.isUint32Array = isUint32Array;
      function isInt8Array(value) {
        return whichTypedArray(value) === "Int8Array";
      }
      exports.isInt8Array = isInt8Array;
      function isInt16Array(value) {
        return whichTypedArray(value) === "Int16Array";
      }
      exports.isInt16Array = isInt16Array;
      function isInt32Array(value) {
        return whichTypedArray(value) === "Int32Array";
      }
      exports.isInt32Array = isInt32Array;
      function isFloat32Array(value) {
        return whichTypedArray(value) === "Float32Array";
      }
      exports.isFloat32Array = isFloat32Array;
      function isFloat64Array(value) {
        return whichTypedArray(value) === "Float64Array";
      }
      exports.isFloat64Array = isFloat64Array;
      function isBigInt64Array(value) {
        return whichTypedArray(value) === "BigInt64Array";
      }
      exports.isBigInt64Array = isBigInt64Array;
      function isBigUint64Array(value) {
        return whichTypedArray(value) === "BigUint64Array";
      }
      exports.isBigUint64Array = isBigUint64Array;
      function isMapToString(value) {
        return ObjectToString(value) === "[object Map]";
      }
      isMapToString.working = typeof Map !== "undefined" && isMapToString(/* @__PURE__ */ new Map());
      function isMap(value) {
        if (typeof Map === "undefined") {
          return false;
        }
        return isMapToString.working ? isMapToString(value) : value instanceof Map;
      }
      exports.isMap = isMap;
      function isSetToString(value) {
        return ObjectToString(value) === "[object Set]";
      }
      isSetToString.working = typeof Set !== "undefined" && isSetToString(/* @__PURE__ */ new Set());
      function isSet(value) {
        if (typeof Set === "undefined") {
          return false;
        }
        return isSetToString.working ? isSetToString(value) : value instanceof Set;
      }
      exports.isSet = isSet;
      function isWeakMapToString(value) {
        return ObjectToString(value) === "[object WeakMap]";
      }
      isWeakMapToString.working = typeof WeakMap !== "undefined" && isWeakMapToString(/* @__PURE__ */ new WeakMap());
      function isWeakMap(value) {
        if (typeof WeakMap === "undefined") {
          return false;
        }
        return isWeakMapToString.working ? isWeakMapToString(value) : value instanceof WeakMap;
      }
      exports.isWeakMap = isWeakMap;
      function isWeakSetToString(value) {
        return ObjectToString(value) === "[object WeakSet]";
      }
      isWeakSetToString.working = typeof WeakSet !== "undefined" && isWeakSetToString(/* @__PURE__ */ new WeakSet());
      function isWeakSet(value) {
        return isWeakSetToString(value);
      }
      exports.isWeakSet = isWeakSet;
      function isArrayBufferToString(value) {
        return ObjectToString(value) === "[object ArrayBuffer]";
      }
      isArrayBufferToString.working = typeof ArrayBuffer !== "undefined" && isArrayBufferToString(new ArrayBuffer());
      function isArrayBuffer(value) {
        if (typeof ArrayBuffer === "undefined") {
          return false;
        }
        return isArrayBufferToString.working ? isArrayBufferToString(value) : value instanceof ArrayBuffer;
      }
      exports.isArrayBuffer = isArrayBuffer;
      function isDataViewToString(value) {
        return ObjectToString(value) === "[object DataView]";
      }
      isDataViewToString.working = typeof ArrayBuffer !== "undefined" && typeof DataView !== "undefined" && isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1));
      function isDataView(value) {
        if (typeof DataView === "undefined") {
          return false;
        }
        return isDataViewToString.working ? isDataViewToString(value) : value instanceof DataView;
      }
      exports.isDataView = isDataView;
      var SharedArrayBufferCopy = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : void 0;
      function isSharedArrayBufferToString(value) {
        return ObjectToString(value) === "[object SharedArrayBuffer]";
      }
      function isSharedArrayBuffer(value) {
        if (typeof SharedArrayBufferCopy === "undefined") {
          return false;
        }
        if (typeof isSharedArrayBufferToString.working === "undefined") {
          isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());
        }
        return isSharedArrayBufferToString.working ? isSharedArrayBufferToString(value) : value instanceof SharedArrayBufferCopy;
      }
      exports.isSharedArrayBuffer = isSharedArrayBuffer;
      function isAsyncFunction(value) {
        return ObjectToString(value) === "[object AsyncFunction]";
      }
      exports.isAsyncFunction = isAsyncFunction;
      function isMapIterator(value) {
        return ObjectToString(value) === "[object Map Iterator]";
      }
      exports.isMapIterator = isMapIterator;
      function isSetIterator(value) {
        return ObjectToString(value) === "[object Set Iterator]";
      }
      exports.isSetIterator = isSetIterator;
      function isGeneratorObject(value) {
        return ObjectToString(value) === "[object Generator]";
      }
      exports.isGeneratorObject = isGeneratorObject;
      function isWebAssemblyCompiledModule(value) {
        return ObjectToString(value) === "[object WebAssembly.Module]";
      }
      exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
      function isNumberObject(value) {
        return checkBoxedPrimitive(value, numberValue);
      }
      exports.isNumberObject = isNumberObject;
      function isStringObject(value) {
        return checkBoxedPrimitive(value, stringValue);
      }
      exports.isStringObject = isStringObject;
      function isBooleanObject(value) {
        return checkBoxedPrimitive(value, booleanValue);
      }
      exports.isBooleanObject = isBooleanObject;
      function isBigIntObject(value) {
        return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
      }
      exports.isBigIntObject = isBigIntObject;
      function isSymbolObject(value) {
        return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
      }
      exports.isSymbolObject = isSymbolObject;
      function isBoxedPrimitive(value) {
        return isNumberObject(value) || isStringObject(value) || isBooleanObject(value) || isBigIntObject(value) || isSymbolObject(value);
      }
      exports.isBoxedPrimitive = isBoxedPrimitive;
      function isAnyArrayBuffer(value) {
        return typeof Uint8Array !== "undefined" && (isArrayBuffer(value) || isSharedArrayBuffer(value));
      }
      exports.isAnyArrayBuffer = isAnyArrayBuffer;
      ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(method) {
        Object.defineProperty(exports, method, {
          enumerable: false,
          value: function() {
            throw new Error(method + " is not supported in userland");
          }
        });
      });
    }
  });

  // node_modules/util/support/isBufferBrowser.js
  var require_isBufferBrowser = __commonJS({
    "node_modules/util/support/isBufferBrowser.js"(exports, module) {
      module.exports = function isBuffer(arg) {
        return arg && typeof arg === "object" && typeof arg.copy === "function" && typeof arg.fill === "function" && typeof arg.readUInt8 === "function";
      };
    }
  });

  // (disabled):node_modules/util/util.js
  var require_util = __commonJS({
    "(disabled):node_modules/util/util.js"(exports) {
      var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors2(obj) {
        var keys = Object.keys(obj);
        var descriptors = {};
        for (var i = 0; i < keys.length; i++) {
          descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
        }
        return descriptors;
      };
      var formatRegExp = /%[sdj%]/g;
      exports.format = function(f) {
        if (!isString(f)) {
          var objects = [];
          for (var i = 0; i < arguments.length; i++) {
            objects.push(inspect(arguments[i]));
          }
          return objects.join(" ");
        }
        var i = 1;
        var args = arguments;
        var len = args.length;
        var str = String(f).replace(formatRegExp, function(x2) {
          if (x2 === "%%") return "%";
          if (i >= len) return x2;
          switch (x2) {
            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 x2;
          }
        });
        for (var x = args[i]; i < len; x = args[++i]) {
          if (isNull(x) || !isObject(x)) {
            str += " " + x;
          } else {
            str += " " + inspect(x);
          }
        }
        return str;
      };
      exports.deprecate = function(fn, msg) {
        if (typeof process !== "undefined" && process.noDeprecation === true) {
          return fn;
        }
        if (typeof process === "undefined") {
          return function() {
            return exports.deprecate(fn, msg).apply(this, arguments);
          };
        }
        var warned = false;
        function deprecated() {
          if (!warned) {
            if (process.throwDeprecation) {
              throw new Error(msg);
            } else if (process.traceDeprecation) {
              console.trace(msg);
            } else {
              console.error(msg);
            }
            warned = true;
          }
          return fn.apply(this, arguments);
        }
        return deprecated;
      };
      var debugs = {};
      var debugEnvRegex = /^$/;
      if ("false") {
        debugEnv = "false";
        debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase();
        debugEnvRegex = new RegExp("^" + debugEnv + "$", "i");
      }
      var debugEnv;
      exports.debuglog = function(set) {
        set = set.toUpperCase();
        if (!debugs[set]) {
          if (debugEnvRegex.test(set)) {
            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];
      };
      function inspect(obj, opts) {
        var ctx = {
          seen: [],
          stylize: stylizeNoColor
        };
        if (arguments.length >= 3) ctx.depth = arguments[2];
        if (arguments.length >= 4) ctx.colors = arguments[3];
        if (isBoolean(opts)) {
          ctx.showHidden = opts;
        } else if (opts) {
          exports._extend(ctx, opts);
        }
        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;
      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]
      };
      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 "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + 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) {
        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;
        }
        var primitive = formatPrimitive(ctx, value);
        if (primitive) {
          return primitive;
        }
        var keys = Object.keys(value);
        var visibleKeys = arrayToHash(keys);
        if (ctx.showHidden) {
          keys = Object.getOwnPropertyNames(value);
        }
        if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
          return formatError(value);
        }
        if (keys.length === 0) {
          if (isFunction(value)) {
            var name2 = value.name ? ": " + value.name : "";
            return ctx.stylize("[Function" + name2 + "]", "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 = ["{", "}"];
        if (isArray(value)) {
          array = true;
          braces = ["[", "]"];
        }
        if (isFunction(value)) {
          var n = value.name ? ": " + value.name : "";
          base = " [Function" + n + "]";
        }
        if (isRegExp(value)) {
          base = " " + RegExp.prototype.toString.call(value);
        }
        if (isDate(value)) {
          base = " " + Date.prototype.toUTCString.call(value);
        }
        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");
        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 (hasOwnProperty2(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 name2, 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 (!hasOwnProperty2(visibleKeys, key)) {
          name2 = "[" + 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").slice(2);
              } else {
                str = "\n" + str.split("\n").map(function(line) {
                  return "   " + line;
                }).join("\n");
              }
            }
          } else {
            str = ctx.stylize("[Circular]", "special");
          }
        }
        if (isUndefined(name2)) {
          if (array && key.match(/^\d+$/)) {
            return str;
          }
          name2 = JSON.stringify("" + key);
          if (name2.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
            name2 = name2.slice(1, -1);
            name2 = ctx.stylize(name2, "name");
          } else {
            name2 = name2.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
            name2 = ctx.stylize(name2, "string");
          }
        }
        return name2 + ": " + 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];
      }
      exports.types = require_types();
      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;
      exports.types.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;
      exports.types.isDate = isDate;
      function isError(e) {
        return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
      }
      exports.isError = isError;
      exports.types.isNativeError = 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_isBufferBrowser();
      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"
      ];
      function timestamp() {
        var d = /* @__PURE__ */ new Date();
        var time = [
          pad(d.getHours()),
          pad(d.getMinutes()),
          pad(d.getSeconds())
        ].join(":");
        return [d.getDate(), months[d.getMonth()], time].join(" ");
      }
      exports.log = function() {
        console.log("%s - %s", timestamp(), exports.format.apply(exports, arguments));
      };
      exports.inherits = require_inherits_browser();
      exports._extend = function(origin, add) {
        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 hasOwnProperty2(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
      }
      var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : void 0;
      exports.promisify = function promisify(original) {
        if (typeof original !== "function")
          throw new TypeError('The "original" argument must be of type Function');
        if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
          var fn = original[kCustomPromisifiedSymbol];
          if (typeof fn !== "function") {
            throw new TypeError('The "util.promisify.custom" argument must be of type Function');
          }
          Object.defineProperty(fn, kCustomPromisifiedSymbol, {
            value: fn,
            enumerable: false,
            writable: false,
            configurable: true
          });
          return fn;
        }
        function fn() {
          var promiseResolve, promiseReject;
          var promise = new Promise(function(resolve, reject) {
            promiseResolve = resolve;
            promiseReject = reject;
          });
          var args = [];
          for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
          }
          args.push(function(err, value) {
            if (err) {
              promiseReject(err);
            } else {
              promiseResolve(value);
            }
          });
          try {
            original.apply(this, args);
          } catch (err) {
            promiseReject(err);
          }
          return promise;
        }
        Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
        if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
          value: fn,
          enumerable: false,
          writable: false,
          configurable: true
        });
        return Object.defineProperties(
          fn,
          getOwnPropertyDescriptors(original)
        );
      };
      exports.promisify.custom = kCustomPromisifiedSymbol;
      function callbackifyOnRejected(reason, cb) {
        if (!reason) {
          var newReason = new Error("Promise was rejected with a falsy value");
          newReason.reason = reason;
          reason = newReason;
        }
        return cb(reason);
      }
      function callbackify(original) {
        if (typeof original !== "function") {
          throw new TypeError('The "original" argument must be of type Function');
        }
        function callbackified() {
          var args = [];
          for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
          }
          var maybeCb = args.pop();
          if (typeof maybeCb !== "function") {
            throw new TypeError("The last argument must be of type Function");
          }
          var self2 = this;
          var cb = function() {
            return maybeCb.apply(self2, arguments);
          };
          original.apply(this, args).then(
            function(ret) {
              process.nextTick(cb.bind(null, null, ret));
            },
            function(rej) {
              process.nextTick(callbackifyOnRejected.bind(null, rej, cb));
            }
          );
        }
        Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
        Object.defineProperties(
          callbackified,
          getOwnPropertyDescriptors(original)
        );
        return callbackified;
      }
      exports.callbackify = callbackify;
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/buffer_list.js
  var require_buffer_list = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports, module) {
      "use strict";
      function ownKeys(object, enumerableOnly) {
        var keys = Object.keys(object);
        if (Object.getOwnPropertySymbols) {
          var symbols = Object.getOwnPropertySymbols(object);
          if (enumerableOnly) symbols = symbols.filter(function(sym) {
            return Object.getOwnPropertyDescriptor(object, sym).enumerable;
          });
          keys.push.apply(keys, symbols);
        }
        return keys;
      }
      function _objectSpread(target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i] != null ? arguments[i] : {};
          if (i % 2) {
            ownKeys(Object(source), true).forEach(function(key) {
              _defineProperty(target, key, source[key]);
            });
          } else if (Object.getOwnPropertyDescriptors) {
            Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
          } else {
            ownKeys(Object(source)).forEach(function(key) {
              Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
            });
          }
        }
        return target;
      }
      function _defineProperty(obj, key, value) {
        if (key in obj) {
          Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
        } else {
          obj[key] = value;
        }
        return obj;
      }
      function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
          throw new TypeError("Cannot call a class as a function");
        }
      }
      function _defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, descriptor.key, descriptor);
        }
      }
      function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        return Constructor;
      }
      var _require = require_buffer();
      var Buffer2 = _require.Buffer;
      var _require2 = require_util();
      var inspect = _require2.inspect;
      var custom = inspect && inspect.custom || "inspect";
      function copyBuffer(src, target, offset) {
        Buffer2.prototype.copy.call(src, target, offset);
      }
      module.exports = /* @__PURE__ */ function() {
        function BufferList() {
          _classCallCheck(this, BufferList);
          this.head = null;
          this.tail = null;
          this.length = 0;
        }
        _createClass(BufferList, [{
          key: "push",
          value: function push(v) {
            var entry = {
              data: v,
              next: null
            };
            if (this.length > 0) this.tail.next = entry;
            else this.head = entry;
            this.tail = entry;
            ++this.length;
          }
        }, {
          key: "unshift",
          value: function unshift(v) {
            var entry = {
              data: v,
              next: this.head
            };
            if (this.length === 0) this.tail = entry;
            this.head = entry;
            ++this.length;
          }
        }, {
          key: "shift",
          value: function shift() {
            if (this.length === 0) return;
            var ret = this.head.data;
            if (this.length === 1) this.head = this.tail = null;
            else this.head = this.head.next;
            --this.length;
            return ret;
          }
        }, {
          key: "clear",
          value: function clear() {
            this.head = this.tail = null;
            this.length = 0;
          }
        }, {
          key: "join",
          value: function join(s) {
            if (this.length === 0) return "";
            var p = this.head;
            var ret = "" + p.data;
            while (p = p.next) {
              ret += s + p.data;
            }
            return ret;
          }
        }, {
          key: "concat",
          value: function concat(n) {
            if (this.length === 0) return Buffer2.alloc(0);
            var ret = Buffer2.allocUnsafe(n >>> 0);
            var p = this.head;
            var i = 0;
            while (p) {
              copyBuffer(p.data, ret, i);
              i += p.data.length;
              p = p.next;
            }
            return ret;
          }
          // Consumes a specified amount of bytes or characters from the buffered data.
        }, {
          key: "consume",
          value: function consume(n, hasStrings) {
            var ret;
            if (n < this.head.data.length) {
              ret = this.head.data.slice(0, n);
              this.head.data = this.head.data.slice(n);
            } else if (n === this.head.data.length) {
              ret = this.shift();
            } else {
              ret = hasStrings ? this._getString(n) : this._getBuffer(n);
            }
            return ret;
          }
        }, {
          key: "first",
          value: function first() {
            return this.head.data;
          }
          // Consumes a specified amount of characters from the buffered data.
        }, {
          key: "_getString",
          value: function _getString(n) {
            var p = this.head;
            var c = 1;
            var ret = p.data;
            n -= ret.length;
            while (p = p.next) {
              var str = p.data;
              var nb = n > str.length ? str.length : n;
              if (nb === str.length) ret += str;
              else ret += str.slice(0, n);
              n -= nb;
              if (n === 0) {
                if (nb === str.length) {
                  ++c;
                  if (p.next) this.head = p.next;
                  else this.head = this.tail = null;
                } else {
                  this.head = p;
                  p.data = str.slice(nb);
                }
                break;
              }
              ++c;
            }
            this.length -= c;
            return ret;
          }
          // Consumes a specified amount of bytes from the buffered data.
        }, {
          key: "_getBuffer",
          value: function _getBuffer(n) {
            var ret = Buffer2.allocUnsafe(n);
            var p = this.head;
            var c = 1;
            p.data.copy(ret);
            n -= p.data.length;
            while (p = p.next) {
              var buf = p.data;
              var nb = n > buf.length ? buf.length : n;
              buf.copy(ret, ret.length - n, 0, nb);
              n -= nb;
              if (n === 0) {
                if (nb === buf.length) {
                  ++c;
                  if (p.next) this.head = p.next;
                  else this.head = this.tail = null;
                } else {
                  this.head = p;
                  p.data = buf.slice(nb);
                }
                break;
              }
              ++c;
            }
            this.length -= c;
            return ret;
          }
          // Make sure the linked list only shows the minimal necessary information.
        }, {
          key: custom,
          value: function value(_, options) {
            return inspect(this, _objectSpread({}, options, {
              // Only inspect one level.
              depth: 0,
              // It should not recurse.
              customInspect: false
            }));
          }
        }]);
        return BufferList;
      }();
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/destroy.js
  var require_destroy = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/destroy.js"(exports, module) {
      "use strict";
      function destroy(err, cb) {
        var _this = this;
        var readableDestroyed = this._readableState && this._readableState.destroyed;
        var writableDestroyed = this._writableState && this._writableState.destroyed;
        if (readableDestroyed || writableDestroyed) {
          if (cb) {
            cb(err);
          } else if (err) {
            if (!this._writableState) {
              process.nextTick(emitErrorNT, this, err);
            } else if (!this._writableState.errorEmitted) {
              this._writableState.errorEmitted = true;
              process.nextTick(emitErrorNT, this, err);
            }
          }
          return this;
        }
        if (this._readableState) {
          this._readableState.destroyed = true;
        }
        if (this._writableState) {
          this._writableState.destroyed = true;
        }
        this._destroy(err || null, function(err2) {
          if (!cb && err2) {
            if (!_this._writableState) {
              process.nextTick(emitErrorAndCloseNT, _this, err2);
            } else if (!_this._writableState.errorEmitted) {
              _this._writableState.errorEmitted = true;
              process.nextTick(emitErrorAndCloseNT, _this, err2);
            } else {
              process.nextTick(emitCloseNT, _this);
            }
          } else if (cb) {
            process.nextTick(emitCloseNT, _this);
            cb(err2);
          } else {
            process.nextTick(emitCloseNT, _this);
          }
        });
        return this;
      }
      function emitErrorAndCloseNT(self2, err) {
        emitErrorNT(self2, err);
        emitCloseNT(self2);
      }
      function emitCloseNT(self2) {
        if (self2._writableState && !self2._writableState.emitClose) return;
        if (self2._readableState && !self2._readableState.emitClose) return;
        self2.emit("close");
      }
      function undestroy() {
        if (this._readableState) {
          this._readableState.destroyed = false;
          this._readableState.reading = false;
          this._readableState.ended = false;
          this._readableState.endEmitted = false;
        }
        if (this._writableState) {
          this._writableState.destroyed = false;
          this._writableState.ended = false;
          this._writableState.ending = false;
          this._writableState.finalCalled = false;
          this._writableState.prefinished = false;
          this._writableState.finished = false;
          this._writableState.errorEmitted = false;
        }
      }
      function emitErrorNT(self2, err) {
        self2.emit("error", err);
      }
      function errorOrDestroy(stream, err) {
        var rState = stream._readableState;
        var wState = stream._writableState;
        if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);
        else stream.emit("error", err);
      }
      module.exports = {
        destroy,
        undestroy,
        errorOrDestroy
      };
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/errors-browser.js
  var require_errors_browser = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/errors-browser.js"(exports, module) {
      "use strict";
      function _inheritsLoose(subClass, superClass) {
        subClass.prototype = Object.create(superClass.prototype);
        subClass.prototype.constructor = subClass;
        subClass.__proto__ = superClass;
      }
      var codes = {};
      function createErrorType(code, message, Base) {
        if (!Base) {
          Base = Error;
        }
        function getMessage(arg1, arg2, arg3) {
          if (typeof message === "string") {
            return message;
          } else {
            return message(arg1, arg2, arg3);
          }
        }
        var NodeError = /* @__PURE__ */ function(_Base) {
          _inheritsLoose(NodeError2, _Base);
          function NodeError2(arg1, arg2, arg3) {
            return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
          }
          return NodeError2;
        }(Base);
        NodeError.prototype.name = Base.name;
        NodeError.prototype.code = code;
        codes[code] = NodeError;
      }
      function oneOf(expected, thing) {
        if (Array.isArray(expected)) {
          var len = expected.length;
          expected = expected.map(function(i) {
            return String(i);
          });
          if (len > 2) {
            return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1];
          } else if (len === 2) {
            return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
          } else {
            return "of ".concat(thing, " ").concat(expected[0]);
          }
        } else {
          return "of ".concat(thing, " ").concat(String(expected));
        }
      }
      function startsWith(str, search, pos) {
        return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
      }
      function endsWith(str, search, this_len) {
        if (this_len === void 0 || this_len > str.length) {
          this_len = str.length;
        }
        return str.substring(this_len - search.length, this_len) === search;
      }
      function includes(str, search, start) {
        if (typeof start !== "number") {
          start = 0;
        }
        if (start + search.length > str.length) {
          return false;
        } else {
          return str.indexOf(search, start) !== -1;
        }
      }
      createErrorType("ERR_INVALID_OPT_VALUE", function(name2, value) {
        return 'The value "' + value + '" is invalid for option "' + name2 + '"';
      }, TypeError);
      createErrorType("ERR_INVALID_ARG_TYPE", function(name2, expected, actual) {
        var determiner;
        if (typeof expected === "string" && startsWith(expected, "not ")) {
          determiner = "must not be";
          expected = expected.replace(/^not /, "");
        } else {
          determiner = "must be";
        }
        var msg;
        if (endsWith(name2, " argument")) {
          msg = "The ".concat(name2, " ").concat(determiner, " ").concat(oneOf(expected, "type"));
        } else {
          var type = includes(name2, ".") ? "property" : "argument";
          msg = 'The "'.concat(name2, '" ').concat(type, " ").concat(determiner, " ").concat(oneOf(expected, "type"));
        }
        msg += ". Received type ".concat(typeof actual);
        return msg;
      }, TypeError);
      createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF");
      createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name2) {
        return "The " + name2 + " method is not implemented";
      });
      createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close");
      createErrorType("ERR_STREAM_DESTROYED", function(name2) {
        return "Cannot call " + name2 + " after a stream was destroyed";
      });
      createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times");
      createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable");
      createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end");
      createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError);
      createErrorType("ERR_UNKNOWN_ENCODING", function(arg) {
        return "Unknown encoding: " + arg;
      }, TypeError);
      createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event");
      module.exports.codes = codes;
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/state.js
  var require_state = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/state.js"(exports, module) {
      "use strict";
      var ERR_INVALID_OPT_VALUE = require_errors_browser().codes.ERR_INVALID_OPT_VALUE;
      function highWaterMarkFrom(options, isDuplex, duplexKey) {
        return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
      }
      function getHighWaterMark(state, options, duplexKey, isDuplex) {
        var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
        if (hwm != null) {
          if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
            var name2 = isDuplex ? duplexKey : "highWaterMark";
            throw new ERR_INVALID_OPT_VALUE(name2, hwm);
          }
          return Math.floor(hwm);
        }
        return state.objectMode ? 16 : 16 * 1024;
      }
      module.exports = {
        getHighWaterMark
      };
    }
  });

  // node_modules/util-deprecate/browser.js
  var require_browser = __commonJS({
    "node_modules/util-deprecate/browser.js"(exports, module) {
      module.exports = deprecate;
      function deprecate(fn, msg) {
        if (config("noDeprecation")) {
          return fn;
        }
        var warned = false;
        function deprecated() {
          if (!warned) {
            if (config("throwDeprecation")) {
              throw new Error(msg);
            } else if (config("traceDeprecation")) {
              console.trace(msg);
            } else {
              console.warn(msg);
            }
            warned = true;
          }
          return fn.apply(this, arguments);
        }
        return deprecated;
      }
      function config(name2) {
        try {
          if (!window.localStorage) return false;
        } catch (_) {
          return false;
        }
        var val = window.localStorage[name2];
        if (null == val) return false;
        return String(val).toLowerCase() === "true";
      }
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_writable.js
  var require_stream_writable = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_writable.js"(exports, module) {
      "use strict";
      module.exports = Writable;
      function CorkedRequest(state) {
        var _this = this;
        this.next = null;
        this.entry = null;
        this.finish = function() {
          onCorkedFinish(_this, state);
        };
      }
      var Duplex;
      Writable.WritableState = WritableState;
      var internalUtil = {
        deprecate: require_browser()
      };
      var Stream = require_stream_browser();
      var Buffer2 = require_buffer().Buffer;
      var OurUint8Array = window.Uint8Array || function() {
      };
      function _uint8ArrayToBuffer(chunk) {
        return Buffer2.from(chunk);
      }
      function _isUint8Array(obj) {
        return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array;
      }
      var destroyImpl = require_destroy();
      var _require = require_state();
      var getHighWaterMark = _require.getHighWaterMark;
      var _require$codes = require_errors_browser().codes;
      var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE;
      var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED;
      var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK;
      var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE;
      var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
      var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES;
      var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END;
      var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
      var errorOrDestroy = destroyImpl.errorOrDestroy;
      require_inherits_browser()(Writable, Stream);
      function nop() {
      }
      function WritableState(options, stream, isDuplex) {
        Duplex = Duplex || require_stream_duplex();
        options = options || {};
        if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex;
        this.objectMode = !!options.objectMode;
        if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
        this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex);
        this.finalCalled = false;
        this.needDrain = false;
        this.ending = false;
        this.ended = false;
        this.finished = false;
        this.destroyed = false;
        var noDecode = options.decodeStrings === false;
        this.decodeStrings = !noDecode;
        this.defaultEncoding = options.defaultEncoding || "utf8";
        this.length = 0;
        this.writing = false;
        this.corked = 0;
        this.sync = true;
        this.bufferProcessing = false;
        this.onwrite = function(er) {
          onwrite(stream, er);
        };
        this.writecb = null;
        this.writelen = 0;
        this.bufferedRequest = null;
        this.lastBufferedRequest = null;
        this.pendingcb = 0;
        this.prefinished = false;
        this.errorEmitted = false;
        this.emitClose = options.emitClose !== false;
        this.autoDestroy = !!options.autoDestroy;
        this.bufferedRequestCount = 0;
        this.corkedRequestsFree = new CorkedRequest(this);
      }
      WritableState.prototype.getBuffer = function getBuffer() {
        var current = this.bufferedRequest;
        var out = [];
        while (current) {
          out.push(current);
          current = current.next;
        }
        return out;
      };
      (function() {
        try {
          Object.defineProperty(WritableState.prototype, "buffer", {
            get: internalUtil.deprecate(function writableStateBufferGetter() {
              return this.getBuffer();
            }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003")
          });
        } catch (_) {
        }
      })();
      var realHasInstance;
      if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") {
        realHasInstance = Function.prototype[Symbol.hasInstance];
        Object.defineProperty(Writable, Symbol.hasInstance, {
          value: function value(object) {
            if (realHasInstance.call(this, object)) return true;
            if (this !== Writable) return false;
            return object && object._writableState instanceof WritableState;
          }
        });
      } else {
        realHasInstance = function realHasInstance2(object) {
          return object instanceof this;
        };
      }
      function Writable(options) {
        Duplex = Duplex || require_stream_duplex();
        var isDuplex = this instanceof Duplex;
        if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
        this._writableState = new WritableState(options, this, isDuplex);
        this.writable = true;
        if (options) {
          if (typeof options.write === "function") this._write = options.write;
          if (typeof options.writev === "function") this._writev = options.writev;
          if (typeof options.destroy === "function") this._destroy = options.destroy;
          if (typeof options.final === "function") this._final = options.final;
        }
        Stream.call(this);
      }
      Writable.prototype.pipe = function() {
        errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
      };
      function writeAfterEnd(stream, cb) {
        var er = new ERR_STREAM_WRITE_AFTER_END();
        errorOrDestroy(stream, er);
        process.nextTick(cb, er);
      }
      function validChunk(stream, state, chunk, cb) {
        var er;
        if (chunk === null) {
          er = new ERR_STREAM_NULL_VALUES();
        } else if (typeof chunk !== "string" && !state.objectMode) {
          er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk);
        }
        if (er) {
          errorOrDestroy(stream, er);
          process.nextTick(cb, er);
          return false;
        }
        return true;
      }
      Writable.prototype.write = function(chunk, encoding, cb) {
        var state = this._writableState;
        var ret = false;
        var isBuf = !state.objectMode && _isUint8Array(chunk);
        if (isBuf && !Buffer2.isBuffer(chunk)) {
          chunk = _uint8ArrayToBuffer(chunk);
        }
        if (typeof encoding === "function") {
          cb = encoding;
          encoding = null;
        }
        if (isBuf) encoding = "buffer";
        else if (!encoding) encoding = state.defaultEncoding;
        if (typeof cb !== "function") cb = nop;
        if (state.ending) writeAfterEnd(this, cb);
        else if (isBuf || validChunk(this, state, chunk, cb)) {
          state.pendingcb++;
          ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
        }
        return ret;
      };
      Writable.prototype.cork = function() {
        this._writableState.corked++;
      };
      Writable.prototype.uncork = function() {
        var state = this._writableState;
        if (state.corked) {
          state.corked--;
          if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
        }
      };
      Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
        if (typeof encoding === "string") encoding = encoding.toLowerCase();
        if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
        this._writableState.defaultEncoding = encoding;
        return this;
      };
      Object.defineProperty(Writable.prototype, "writableBuffer", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._writableState && this._writableState.getBuffer();
        }
      });
      function decodeChunk(state, chunk, encoding) {
        if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") {
          chunk = Buffer2.from(chunk, encoding);
        }
        return chunk;
      }
      Object.defineProperty(Writable.prototype, "writableHighWaterMark", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._writableState.highWaterMark;
        }
      });
      function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
        if (!isBuf) {
          var newChunk = decodeChunk(state, chunk, encoding);
          if (chunk !== newChunk) {
            isBuf = true;
            encoding = "buffer";
            chunk = newChunk;
          }
        }
        var len = state.objectMode ? 1 : chunk.length;
        state.length += len;
        var ret = state.length < state.highWaterMark;
        if (!ret) state.needDrain = true;
        if (state.writing || state.corked) {
          var last = state.lastBufferedRequest;
          state.lastBufferedRequest = {
            chunk,
            encoding,
            isBuf,
            callback: cb,
            next: null
          };
          if (last) {
            last.next = state.lastBufferedRequest;
          } else {
            state.bufferedRequest = state.lastBufferedRequest;
          }
          state.bufferedRequestCount += 1;
        } else {
          doWrite(stream, state, false, len, chunk, encoding, cb);
        }
        return ret;
      }
      function doWrite(stream, state, writev, len, chunk, encoding, cb) {
        state.writelen = len;
        state.writecb = cb;
        state.writing = true;
        state.sync = true;
        if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write"));
        else if (writev) stream._writev(chunk, state.onwrite);
        else stream._write(chunk, encoding, state.onwrite);
        state.sync = false;
      }
      function onwriteError(stream, state, sync, er, cb) {
        --state.pendingcb;
        if (sync) {
          process.nextTick(cb, er);
          process.nextTick(finishMaybe, stream, state);
          stream._writableState.errorEmitted = true;
          errorOrDestroy(stream, er);
        } else {
          cb(er);
          stream._writableState.errorEmitted = true;
          errorOrDestroy(stream, er);
          finishMaybe(stream, state);
        }
      }
      function onwriteStateUpdate(state) {
        state.writing = false;
        state.writecb = null;
        state.length -= state.writelen;
        state.writelen = 0;
      }
      function onwrite(stream, er) {
        var state = stream._writableState;
        var sync = state.sync;
        var cb = state.writecb;
        if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK();
        onwriteStateUpdate(state);
        if (er) onwriteError(stream, state, sync, er, cb);
        else {
          var finished = needFinish(state) || stream.destroyed;
          if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
            clearBuffer(stream, state);
          }
          if (sync) {
            process.nextTick(afterWrite, stream, state, finished, cb);
          } else {
            afterWrite(stream, state, finished, cb);
          }
        }
      }
      function afterWrite(stream, state, finished, cb) {
        if (!finished) onwriteDrain(stream, state);
        state.pendingcb--;
        cb();
        finishMaybe(stream, state);
      }
      function onwriteDrain(stream, state) {
        if (state.length === 0 && state.needDrain) {
          state.needDrain = false;
          stream.emit("drain");
        }
      }
      function clearBuffer(stream, state) {
        state.bufferProcessing = true;
        var entry = state.bufferedRequest;
        if (stream._writev && entry && entry.next) {
          var l = state.bufferedRequestCount;
          var buffer = new Array(l);
          var holder = state.corkedRequestsFree;
          holder.entry = entry;
          var count = 0;
          var allBuffers = true;
          while (entry) {
            buffer[count] = entry;
            if (!entry.isBuf) allBuffers = false;
            entry = entry.next;
            count += 1;
          }
          buffer.allBuffers = allBuffers;
          doWrite(stream, state, true, state.length, buffer, "", holder.finish);
          state.pendingcb++;
          state.lastBufferedRequest = null;
          if (holder.next) {
            state.corkedRequestsFree = holder.next;
            holder.next = null;
          } else {
            state.corkedRequestsFree = new CorkedRequest(state);
          }
          state.bufferedRequestCount = 0;
        } else {
          while (entry) {
            var chunk = entry.chunk;
            var encoding = entry.encoding;
            var cb = entry.callback;
            var len = state.objectMode ? 1 : chunk.length;
            doWrite(stream, state, false, len, chunk, encoding, cb);
            entry = entry.next;
            state.bufferedRequestCount--;
            if (state.writing) {
              break;
            }
          }
          if (entry === null) state.lastBufferedRequest = null;
        }
        state.bufferedRequest = entry;
        state.bufferProcessing = false;
      }
      Writable.prototype._write = function(chunk, encoding, cb) {
        cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"));
      };
      Writable.prototype._writev = null;
      Writable.prototype.end = function(chunk, encoding, cb) {
        var state = this._writableState;
        if (typeof chunk === "function") {
          cb = chunk;
          chunk = null;
          encoding = null;
        } else if (typeof encoding === "function") {
          cb = encoding;
          encoding = null;
        }
        if (chunk !== null && chunk !== void 0) this.write(chunk, encoding);
        if (state.corked) {
          state.corked = 1;
          this.uncork();
        }
        if (!state.ending) endWritable(this, state, cb);
        return this;
      };
      Object.defineProperty(Writable.prototype, "writableLength", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._writableState.length;
        }
      });
      function needFinish(state) {
        return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
      }
      function callFinal(stream, state) {
        stream._final(function(err) {
          state.pendingcb--;
          if (err) {
            errorOrDestroy(stream, err);
          }
          state.prefinished = true;
          stream.emit("prefinish");
          finishMaybe(stream, state);
        });
      }
      function prefinish(stream, state) {
        if (!state.prefinished && !state.finalCalled) {
          if (typeof stream._final === "function" && !state.destroyed) {
            state.pendingcb++;
            state.finalCalled = true;
            process.nextTick(callFinal, stream, state);
          } else {
            state.prefinished = true;
            stream.emit("prefinish");
          }
        }
      }
      function finishMaybe(stream, state) {
        var need = needFinish(state);
        if (need) {
          prefinish(stream, state);
          if (state.pendingcb === 0) {
            state.finished = true;
            stream.emit("finish");
            if (state.autoDestroy) {
              var rState = stream._readableState;
              if (!rState || rState.autoDestroy && rState.endEmitted) {
                stream.destroy();
              }
            }
          }
        }
        return need;
      }
      function endWritable(stream, state, cb) {
        state.ending = true;
        finishMaybe(stream, state);
        if (cb) {
          if (state.finished) process.nextTick(cb);
          else stream.once("finish", cb);
        }
        state.ended = true;
        stream.writable = false;
      }
      function onCorkedFinish(corkReq, state, err) {
        var entry = corkReq.entry;
        corkReq.entry = null;
        while (entry) {
          var cb = entry.callback;
          state.pendingcb--;
          cb(err);
          entry = entry.next;
        }
        state.corkedRequestsFree.next = corkReq;
      }
      Object.defineProperty(Writable.prototype, "destroyed", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          if (this._writableState === void 0) {
            return false;
          }
          return this._writableState.destroyed;
        },
        set: function set(value) {
          if (!this._writableState) {
            return;
          }
          this._writableState.destroyed = value;
        }
      });
      Writable.prototype.destroy = destroyImpl.destroy;
      Writable.prototype._undestroy = destroyImpl.undestroy;
      Writable.prototype._destroy = function(err, cb) {
        cb(err);
      };
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_duplex.js
  var require_stream_duplex = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_duplex.js"(exports, module) {
      "use strict";
      var objectKeys = Object.keys || function(obj) {
        var keys2 = [];
        for (var key in obj) {
          keys2.push(key);
        }
        return keys2;
      };
      module.exports = Duplex;
      var Readable = require_stream_readable();
      var Writable = require_stream_writable();
      require_inherits_browser()(Duplex, Readable);
      {
        keys = objectKeys(Writable.prototype);
        for (v = 0; v < keys.length; v++) {
          method = keys[v];
          if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
        }
      }
      var keys;
      var method;
      var v;
      function Duplex(options) {
        if (!(this instanceof Duplex)) return new Duplex(options);
        Readable.call(this, options);
        Writable.call(this, options);
        this.allowHalfOpen = true;
        if (options) {
          if (options.readable === false) this.readable = false;
          if (options.writable === false) this.writable = false;
          if (options.allowHalfOpen === false) {
            this.allowHalfOpen = false;
            this.once("end", onend);
          }
        }
      }
      Object.defineProperty(Duplex.prototype, "writableHighWaterMark", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._writableState.highWaterMark;
        }
      });
      Object.defineProperty(Duplex.prototype, "writableBuffer", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._writableState && this._writableState.getBuffer();
        }
      });
      Object.defineProperty(Duplex.prototype, "writableLength", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._writableState.length;
        }
      });
      function onend() {
        if (this._writableState.ended) return;
        process.nextTick(onEndNT, this);
      }
      function onEndNT(self2) {
        self2.end();
      }
      Object.defineProperty(Duplex.prototype, "destroyed", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          if (this._readableState === void 0 || this._writableState === void 0) {
            return false;
          }
          return this._readableState.destroyed && this._writableState.destroyed;
        },
        set: function set(value) {
          if (this._readableState === void 0 || this._writableState === void 0) {
            return;
          }
          this._readableState.destroyed = value;
          this._writableState.destroyed = value;
        }
      });
    }
  });

  // node_modules/safe-buffer/index.js
  var require_safe_buffer = __commonJS({
    "node_modules/safe-buffer/index.js"(exports, module) {
      var buffer = require_buffer();
      var Buffer2 = buffer.Buffer;
      function copyProps(src, dst) {
        for (var key in src) {
          dst[key] = src[key];
        }
      }
      if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) {
        module.exports = buffer;
      } else {
        copyProps(buffer, exports);
        exports.Buffer = SafeBuffer;
      }
      function SafeBuffer(arg, encodingOrOffset, length) {
        return Buffer2(arg, encodingOrOffset, length);
      }
      SafeBuffer.prototype = Object.create(Buffer2.prototype);
      copyProps(Buffer2, SafeBuffer);
      SafeBuffer.from = function(arg, encodingOrOffset, length) {
        if (typeof arg === "number") {
          throw new TypeError("Argument must not be a number");
        }
        return Buffer2(arg, encodingOrOffset, length);
      };
      SafeBuffer.alloc = function(size, fill, encoding) {
        if (typeof size !== "number") {
          throw new TypeError("Argument must be a number");
        }
        var buf = Buffer2(size);
        if (fill !== void 0) {
          if (typeof encoding === "string") {
            buf.fill(fill, encoding);
          } else {
            buf.fill(fill);
          }
        } else {
          buf.fill(0);
        }
        return buf;
      };
      SafeBuffer.allocUnsafe = function(size) {
        if (typeof size !== "number") {
          throw new TypeError("Argument must be a number");
        }
        return Buffer2(size);
      };
      SafeBuffer.allocUnsafeSlow = function(size) {
        if (typeof size !== "number") {
          throw new TypeError("Argument must be a number");
        }
        return buffer.SlowBuffer(size);
      };
    }
  });

  // node_modules/stream-browserify/node_modules/string_decoder/lib/string_decoder.js
  var require_string_decoder = __commonJS({
    "node_modules/stream-browserify/node_modules/string_decoder/lib/string_decoder.js"(exports) {
      "use strict";
      var Buffer2 = require_safe_buffer().Buffer;
      var isEncoding = Buffer2.isEncoding || function(encoding) {
        encoding = "" + encoding;
        switch (encoding && encoding.toLowerCase()) {
          case "hex":
          case "utf8":
          case "utf-8":
          case "ascii":
          case "binary":
          case "base64":
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
          case "raw":
            return true;
          default:
            return false;
        }
      };
      function _normalizeEncoding(enc) {
        if (!enc) return "utf8";
        var retried;
        while (true) {
          switch (enc) {
            case "utf8":
            case "utf-8":
              return "utf8";
            case "ucs2":
            case "ucs-2":
            case "utf16le":
            case "utf-16le":
              return "utf16le";
            case "latin1":
            case "binary":
              return "latin1";
            case "base64":
            case "ascii":
            case "hex":
              return enc;
            default:
              if (retried) return;
              enc = ("" + enc).toLowerCase();
              retried = true;
          }
        }
      }
      function normalizeEncoding(enc) {
        var nenc = _normalizeEncoding(enc);
        if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc);
        return nenc || enc;
      }
      exports.StringDecoder = StringDecoder;
      function StringDecoder(encoding) {
        this.encoding = normalizeEncoding(encoding);
        var nb;
        switch (this.encoding) {
          case "utf16le":
            this.text = utf16Text;
            this.end = utf16End;
            nb = 4;
            break;
          case "utf8":
            this.fillLast = utf8FillLast;
            nb = 4;
            break;
          case "base64":
            this.text = base64Text;
            this.end = base64End;
            nb = 3;
            break;
          default:
            this.write = simpleWrite;
            this.end = simpleEnd;
            return;
        }
        this.lastNeed = 0;
        this.lastTotal = 0;
        this.lastChar = Buffer2.allocUnsafe(nb);
      }
      StringDecoder.prototype.write = function(buf) {
        if (buf.length === 0) return "";
        var r;
        var i;
        if (this.lastNeed) {
          r = this.fillLast(buf);
          if (r === void 0) return "";
          i = this.lastNeed;
          this.lastNeed = 0;
        } else {
          i = 0;
        }
        if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
        return r || "";
      };
      StringDecoder.prototype.end = utf8End;
      StringDecoder.prototype.text = utf8Text;
      StringDecoder.prototype.fillLast = function(buf) {
        if (this.lastNeed <= buf.length) {
          buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
          return this.lastChar.toString(this.encoding, 0, this.lastTotal);
        }
        buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
        this.lastNeed -= buf.length;
      };
      function utf8CheckByte(byte) {
        if (byte <= 127) return 0;
        else if (byte >> 5 === 6) return 2;
        else if (byte >> 4 === 14) return 3;
        else if (byte >> 3 === 30) return 4;
        return byte >> 6 === 2 ? -1 : -2;
      }
      function utf8CheckIncomplete(self2, buf, i) {
        var j = buf.length - 1;
        if (j < i) return 0;
        var nb = utf8CheckByte(buf[j]);
        if (nb >= 0) {
          if (nb > 0) self2.lastNeed = nb - 1;
          return nb;
        }
        if (--j < i || nb === -2) return 0;
        nb = utf8CheckByte(buf[j]);
        if (nb >= 0) {
          if (nb > 0) self2.lastNeed = nb - 2;
          return nb;
        }
        if (--j < i || nb === -2) return 0;
        nb = utf8CheckByte(buf[j]);
        if (nb >= 0) {
          if (nb > 0) {
            if (nb === 2) nb = 0;
            else self2.lastNeed = nb - 3;
          }
          return nb;
        }
        return 0;
      }
      function utf8CheckExtraBytes(self2, buf, p) {
        if ((buf[0] & 192) !== 128) {
          self2.lastNeed = 0;
          return "\uFFFD";
        }
        if (self2.lastNeed > 1 && buf.length > 1) {
          if ((buf[1] & 192) !== 128) {
            self2.lastNeed = 1;
            return "\uFFFD";
          }
          if (self2.lastNeed > 2 && buf.length > 2) {
            if ((buf[2] & 192) !== 128) {
              self2.lastNeed = 2;
              return "\uFFFD";
            }
          }
        }
      }
      function utf8FillLast(buf) {
        var p = this.lastTotal - this.lastNeed;
        var r = utf8CheckExtraBytes(this, buf, p);
        if (r !== void 0) return r;
        if (this.lastNeed <= buf.length) {
          buf.copy(this.lastChar, p, 0, this.lastNeed);
          return this.lastChar.toString(this.encoding, 0, this.lastTotal);
        }
        buf.copy(this.lastChar, p, 0, buf.length);
        this.lastNeed -= buf.length;
      }
      function utf8Text(buf, i) {
        var total = utf8CheckIncomplete(this, buf, i);
        if (!this.lastNeed) return buf.toString("utf8", i);
        this.lastTotal = total;
        var end = buf.length - (total - this.lastNeed);
        buf.copy(this.lastChar, 0, end);
        return buf.toString("utf8", i, end);
      }
      function utf8End(buf) {
        var r = buf && buf.length ? this.write(buf) : "";
        if (this.lastNeed) return r + "\uFFFD";
        return r;
      }
      function utf16Text(buf, i) {
        if ((buf.length - i) % 2 === 0) {
          var r = buf.toString("utf16le", i);
          if (r) {
            var c = r.charCodeAt(r.length - 1);
            if (c >= 55296 && c <= 56319) {
              this.lastNeed = 2;
              this.lastTotal = 4;
              this.lastChar[0] = buf[buf.length - 2];
              this.lastChar[1] = buf[buf.length - 1];
              return r.slice(0, -1);
            }
          }
          return r;
        }
        this.lastNeed = 1;
        this.lastTotal = 2;
        this.lastChar[0] = buf[buf.length - 1];
        return buf.toString("utf16le", i, buf.length - 1);
      }
      function utf16End(buf) {
        var r = buf && buf.length ? this.write(buf) : "";
        if (this.lastNeed) {
          var end = this.lastTotal - this.lastNeed;
          return r + this.lastChar.toString("utf16le", 0, end);
        }
        return r;
      }
      function base64Text(buf, i) {
        var n = (buf.length - i) % 3;
        if (n === 0) return buf.toString("base64", i);
        this.lastNeed = 3 - n;
        this.lastTotal = 3;
        if (n === 1) {
          this.lastChar[0] = buf[buf.length - 1];
        } else {
          this.lastChar[0] = buf[buf.length - 2];
          this.lastChar[1] = buf[buf.length - 1];
        }
        return buf.toString("base64", i, buf.length - n);
      }
      function base64End(buf) {
        var r = buf && buf.length ? this.write(buf) : "";
        if (this.lastNeed) return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
        return r;
      }
      function simpleWrite(buf) {
        return buf.toString(this.encoding);
      }
      function simpleEnd(buf) {
        return buf && buf.length ? this.write(buf) : "";
      }
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/end-of-stream.js
  var require_end_of_stream = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports, module) {
      "use strict";
      var ERR_STREAM_PREMATURE_CLOSE = require_errors_browser().codes.ERR_STREAM_PREMATURE_CLOSE;
      function once(callback) {
        var called = false;
        return function() {
          if (called) return;
          called = true;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          callback.apply(this, args);
        };
      }
      function noop() {
      }
      function isRequest(stream) {
        return stream.setHeader && typeof stream.abort === "function";
      }
      function eos(stream, opts, callback) {
        if (typeof opts === "function") return eos(stream, null, opts);
        if (!opts) opts = {};
        callback = once(callback || noop);
        var readable = opts.readable || opts.readable !== false && stream.readable;
        var writable = opts.writable || opts.writable !== false && stream.writable;
        var onlegacyfinish = function onlegacyfinish2() {
          if (!stream.writable) onfinish();
        };
        var writableEnded = stream._writableState && stream._writableState.finished;
        var onfinish = function onfinish2() {
          writable = false;
          writableEnded = true;
          if (!readable) callback.call(stream);
        };
        var readableEnded = stream._readableState && stream._readableState.endEmitted;
        var onend = function onend2() {
          readable = false;
          readableEnded = true;
          if (!writable) callback.call(stream);
        };
        var onerror = function onerror2(err) {
          callback.call(stream, err);
        };
        var onclose = function onclose2() {
          var err;
          if (readable && !readableEnded) {
            if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
            return callback.call(stream, err);
          }
          if (writable && !writableEnded) {
            if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
            return callback.call(stream, err);
          }
        };
        var onrequest = function onrequest2() {
          stream.req.on("finish", onfinish);
        };
        if (isRequest(stream)) {
          stream.on("complete", onfinish);
          stream.on("abort", onclose);
          if (stream.req) onrequest();
          else stream.on("request", onrequest);
        } else if (writable && !stream._writableState) {
          stream.on("end", onlegacyfinish);
          stream.on("close", onlegacyfinish);
        }
        stream.on("end", onend);
        stream.on("finish", onfinish);
        if (opts.error !== false) stream.on("error", onerror);
        stream.on("close", onclose);
        return function() {
          stream.removeListener("complete", onfinish);
          stream.removeListener("abort", onclose);
          stream.removeListener("request", onrequest);
          if (stream.req) stream.req.removeListener("finish", onfinish);
          stream.removeListener("end", onlegacyfinish);
          stream.removeListener("close", onlegacyfinish);
          stream.removeListener("finish", onfinish);
          stream.removeListener("end", onend);
          stream.removeListener("error", onerror);
          stream.removeListener("close", onclose);
        };
      }
      module.exports = eos;
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/async_iterator.js
  var require_async_iterator = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports, module) {
      "use strict";
      var _Object$setPrototypeO;
      function _defineProperty(obj, key, value) {
        if (key in obj) {
          Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
        } else {
          obj[key] = value;
        }
        return obj;
      }
      var finished = require_end_of_stream();
      var kLastResolve = Symbol("lastResolve");
      var kLastReject = Symbol("lastReject");
      var kError = Symbol("error");
      var kEnded = Symbol("ended");
      var kLastPromise = Symbol("lastPromise");
      var kHandlePromise = Symbol("handlePromise");
      var kStream = Symbol("stream");
      function createIterResult(value, done) {
        return {
          value,
          done
        };
      }
      function readAndResolve(iter) {
        var resolve = iter[kLastResolve];
        if (resolve !== null) {
          var data = iter[kStream].read();
          if (data !== null) {
            iter[kLastPromise] = null;
            iter[kLastResolve] = null;
            iter[kLastReject] = null;
            resolve(createIterResult(data, false));
          }
        }
      }
      function onReadable(iter) {
        process.nextTick(readAndResolve, iter);
      }
      function wrapForNext(lastPromise, iter) {
        return function(resolve, reject) {
          lastPromise.then(function() {
            if (iter[kEnded]) {
              resolve(createIterResult(void 0, true));
              return;
            }
            iter[kHandlePromise](resolve, reject);
          }, reject);
        };
      }
      var AsyncIteratorPrototype = Object.getPrototypeOf(function() {
      });
      var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
        get stream() {
          return this[kStream];
        },
        next: function next() {
          var _this = this;
          var error = this[kError];
          if (error !== null) {
            return Promise.reject(error);
          }
          if (this[kEnded]) {
            return Promise.resolve(createIterResult(void 0, true));
          }
          if (this[kStream].destroyed) {
            return new Promise(function(resolve, reject) {
              process.nextTick(function() {
                if (_this[kError]) {
                  reject(_this[kError]);
                } else {
                  resolve(createIterResult(void 0, true));
                }
              });
            });
          }
          var lastPromise = this[kLastPromise];
          var promise;
          if (lastPromise) {
            promise = new Promise(wrapForNext(lastPromise, this));
          } else {
            var data = this[kStream].read();
            if (data !== null) {
              return Promise.resolve(createIterResult(data, false));
            }
            promise = new Promise(this[kHandlePromise]);
          }
          this[kLastPromise] = promise;
          return promise;
        }
      }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() {
        return this;
      }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
        var _this2 = this;
        return new Promise(function(resolve, reject) {
          _this2[kStream].destroy(null, function(err) {
            if (err) {
              reject(err);
              return;
            }
            resolve(createIterResult(void 0, true));
          });
        });
      }), _Object$setPrototypeO), AsyncIteratorPrototype);
      var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) {
        var _Object$create;
        var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
          value: stream,
          writable: true
        }), _defineProperty(_Object$create, kLastResolve, {
          value: null,
          writable: true
        }), _defineProperty(_Object$create, kLastReject, {
          value: null,
          writable: true
        }), _defineProperty(_Object$create, kError, {
          value: null,
          writable: true
        }), _defineProperty(_Object$create, kEnded, {
          value: stream._readableState.endEmitted,
          writable: true
        }), _defineProperty(_Object$create, kHandlePromise, {
          value: function value(resolve, reject) {
            var data = iterator[kStream].read();
            if (data) {
              iterator[kLastPromise] = null;
              iterator[kLastResolve] = null;
              iterator[kLastReject] = null;
              resolve(createIterResult(data, false));
            } else {
              iterator[kLastResolve] = resolve;
              iterator[kLastReject] = reject;
            }
          },
          writable: true
        }), _Object$create));
        iterator[kLastPromise] = null;
        finished(stream, function(err) {
          if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") {
            var reject = iterator[kLastReject];
            if (reject !== null) {
              iterator[kLastPromise] = null;
              iterator[kLastResolve] = null;
              iterator[kLastReject] = null;
              reject(err);
            }
            iterator[kError] = err;
            return;
          }
          var resolve = iterator[kLastResolve];
          if (resolve !== null) {
            iterator[kLastPromise] = null;
            iterator[kLastResolve] = null;
            iterator[kLastReject] = null;
            resolve(createIterResult(void 0, true));
          }
          iterator[kEnded] = true;
        });
        stream.on("readable", onReadable.bind(null, iterator));
        return iterator;
      };
      module.exports = createReadableStreamAsyncIterator;
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from-browser.js
  var require_from_browser = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from-browser.js"(exports, module) {
      module.exports = function() {
        throw new Error("Readable.from is not available in the browser");
      };
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_readable.js
  var require_stream_readable = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_readable.js"(exports, module) {
      "use strict";
      module.exports = Readable;
      var Duplex;
      Readable.ReadableState = ReadableState;
      var EE = require_events().EventEmitter;
      var EElistenerCount = function EElistenerCount2(emitter, type) {
        return emitter.listeners(type).length;
      };
      var Stream = require_stream_browser();
      var Buffer2 = require_buffer().Buffer;
      var OurUint8Array = window.Uint8Array || function() {
      };
      function _uint8ArrayToBuffer(chunk) {
        return Buffer2.from(chunk);
      }
      function _isUint8Array(obj) {
        return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array;
      }
      var debugUtil = require_util();
      var debug;
      if (debugUtil && debugUtil.debuglog) {
        debug = debugUtil.debuglog("stream");
      } else {
        debug = function debug2() {
        };
      }
      var BufferList = require_buffer_list();
      var destroyImpl = require_destroy();
      var _require = require_state();
      var getHighWaterMark = _require.getHighWaterMark;
      var _require$codes = require_errors_browser().codes;
      var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE;
      var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF;
      var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED;
      var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
      var StringDecoder;
      var createReadableStreamAsyncIterator;
      var from;
      require_inherits_browser()(Readable, Stream);
      var errorOrDestroy = destroyImpl.errorOrDestroy;
      var kProxyEvents = ["error", "close", "destroy", "pause", "resume"];
      function prependListener(emitter, event, fn) {
        if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn);
        if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);
        else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);
        else emitter._events[event] = [fn, emitter._events[event]];
      }
      function ReadableState(options, stream, isDuplex) {
        Duplex = Duplex || require_stream_duplex();
        options = options || {};
        if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex;
        this.objectMode = !!options.objectMode;
        if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
        this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex);
        this.buffer = new BufferList();
        this.length = 0;
        this.pipes = null;
        this.pipesCount = 0;
        this.flowing = null;
        this.ended = false;
        this.endEmitted = false;
        this.reading = false;
        this.sync = true;
        this.needReadable = false;
        this.emittedReadable = false;
        this.readableListening = false;
        this.resumeScheduled = false;
        this.paused = true;
        this.emitClose = options.emitClose !== false;
        this.autoDestroy = !!options.autoDestroy;
        this.destroyed = false;
        this.defaultEncoding = options.defaultEncoding || "utf8";
        this.awaitDrain = 0;
        this.readingMore = false;
        this.decoder = null;
        this.encoding = null;
        if (options.encoding) {
          if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder;
          this.decoder = new StringDecoder(options.encoding);
          this.encoding = options.encoding;
        }
      }
      function Readable(options) {
        Duplex = Duplex || require_stream_duplex();
        if (!(this instanceof Readable)) return new Readable(options);
        var isDuplex = this instanceof Duplex;
        this._readableState = new ReadableState(options, this, isDuplex);
        this.readable = true;
        if (options) {
          if (typeof options.read === "function") this._read = options.read;
          if (typeof options.destroy === "function") this._destroy = options.destroy;
        }
        Stream.call(this);
      }
      Object.defineProperty(Readable.prototype, "destroyed", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          if (this._readableState === void 0) {
            return false;
          }
          return this._readableState.destroyed;
        },
        set: function set(value) {
          if (!this._readableState) {
            return;
          }
          this._readableState.destroyed = value;
        }
      });
      Readable.prototype.destroy = destroyImpl.destroy;
      Readable.prototype._undestroy = destroyImpl.undestroy;
      Readable.prototype._destroy = function(err, cb) {
        cb(err);
      };
      Readable.prototype.push = function(chunk, encoding) {
        var state = this._readableState;
        var skipChunkCheck;
        if (!state.objectMode) {
          if (typeof chunk === "string") {
            encoding = encoding || state.defaultEncoding;
            if (encoding !== state.encoding) {
              chunk = Buffer2.from(chunk, encoding);
              encoding = "";
            }
            skipChunkCheck = true;
          }
        } else {
          skipChunkCheck = true;
        }
        return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
      };
      Readable.prototype.unshift = function(chunk) {
        return readableAddChunk(this, chunk, null, true, false);
      };
      function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
        debug("readableAddChunk", chunk);
        var state = stream._readableState;
        if (chunk === null) {
          state.reading = false;
          onEofChunk(stream, state);
        } else {
          var er;
          if (!skipChunkCheck) er = chunkInvalid(state, chunk);
          if (er) {
            errorOrDestroy(stream, er);
          } else if (state.objectMode || chunk && chunk.length > 0) {
            if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) {
              chunk = _uint8ArrayToBuffer(chunk);
            }
            if (addToFront) {
              if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
              else addChunk(stream, state, chunk, true);
            } else if (state.ended) {
              errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
            } else if (state.destroyed) {
              return false;
            } else {
              state.reading = false;
              if (state.decoder && !encoding) {
                chunk = state.decoder.write(chunk);
                if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);
                else maybeReadMore(stream, state);
              } else {
                addChunk(stream, state, chunk, false);
              }
            }
          } else if (!addToFront) {
            state.reading = false;
            maybeReadMore(stream, state);
          }
        }
        return !state.ended && (state.length < state.highWaterMark || state.length === 0);
      }
      function addChunk(stream, state, chunk, addToFront) {
        if (state.flowing && state.length === 0 && !state.sync) {
          state.awaitDrain = 0;
          stream.emit("data", chunk);
        } else {
          state.length += state.objectMode ? 1 : chunk.length;
          if (addToFront) state.buffer.unshift(chunk);
          else state.buffer.push(chunk);
          if (state.needReadable) emitReadable(stream);
        }
        maybeReadMore(stream, state);
      }
      function chunkInvalid(state, chunk) {
        var er;
        if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) {
          er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk);
        }
        return er;
      }
      Readable.prototype.isPaused = function() {
        return this._readableState.flowing === false;
      };
      Readable.prototype.setEncoding = function(enc) {
        if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder;
        var decoder = new StringDecoder(enc);
        this._readableState.decoder = decoder;
        this._readableState.encoding = this._readableState.decoder.encoding;
        var p = this._readableState.buffer.head;
        var content = "";
        while (p !== null) {
          content += decoder.write(p.data);
          p = p.next;
        }
        this._readableState.buffer.clear();
        if (content !== "") this._readableState.buffer.push(content);
        this._readableState.length = content.length;
        return this;
      };
      var MAX_HWM = 1073741824;
      function computeNewHighWaterMark(n) {
        if (n >= MAX_HWM) {
          n = MAX_HWM;
        } else {
          n--;
          n |= n >>> 1;
          n |= n >>> 2;
          n |= n >>> 4;
          n |= n >>> 8;
          n |= n >>> 16;
          n++;
        }
        return n;
      }
      function howMuchToRead(n, state) {
        if (n <= 0 || state.length === 0 && state.ended) return 0;
        if (state.objectMode) return 1;
        if (n !== n) {
          if (state.flowing && state.length) return state.buffer.head.data.length;
          else return state.length;
        }
        if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
        if (n <= state.length) return n;
        if (!state.ended) {
          state.needReadable = true;
          return 0;
        }
        return state.length;
      }
      Readable.prototype.read = function(n) {
        debug("read", n);
        n = parseInt(n, 10);
        var state = this._readableState;
        var nOrig = n;
        if (n !== 0) state.emittedReadable = false;
        if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
          debug("read: emitReadable", state.length, state.ended);
          if (state.length === 0 && state.ended) endReadable(this);
          else emitReadable(this);
          return null;
        }
        n = howMuchToRead(n, state);
        if (n === 0 && state.ended) {
          if (state.length === 0) endReadable(this);
          return null;
        }
        var doRead = state.needReadable;
        debug("need readable", doRead);
        if (state.length === 0 || state.length - n < state.highWaterMark) {
          doRead = true;
          debug("length less than watermark", doRead);
        }
        if (state.ended || state.reading) {
          doRead = false;
          debug("reading or ended", doRead);
        } else if (doRead) {
          debug("do read");
          state.reading = true;
          state.sync = true;
          if (state.length === 0) state.needReadable = true;
          this._read(state.highWaterMark);
          state.sync = false;
          if (!state.reading) n = howMuchToRead(nOrig, state);
        }
        var ret;
        if (n > 0) ret = fromList(n, state);
        else ret = null;
        if (ret === null) {
          state.needReadable = state.length <= state.highWaterMark;
          n = 0;
        } else {
          state.length -= n;
          state.awaitDrain = 0;
        }
        if (state.length === 0) {
          if (!state.ended) state.needReadable = true;
          if (nOrig !== n && state.ended) endReadable(this);
        }
        if (ret !== null) this.emit("data", ret);
        return ret;
      };
      function onEofChunk(stream, state) {
        debug("onEofChunk");
        if (state.ended) return;
        if (state.decoder) {
          var chunk = state.decoder.end();
          if (chunk && chunk.length) {
            state.buffer.push(chunk);
            state.length += state.objectMode ? 1 : chunk.length;
          }
        }
        state.ended = true;
        if (state.sync) {
          emitReadable(stream);
        } else {
          state.needReadable = false;
          if (!state.emittedReadable) {
            state.emittedReadable = true;
            emitReadable_(stream);
          }
        }
      }
      function emitReadable(stream) {
        var state = stream._readableState;
        debug("emitReadable", state.needReadable, state.emittedReadable);
        state.needReadable = false;
        if (!state.emittedReadable) {
          debug("emitReadable", state.flowing);
          state.emittedReadable = true;
          process.nextTick(emitReadable_, stream);
        }
      }
      function emitReadable_(stream) {
        var state = stream._readableState;
        debug("emitReadable_", state.destroyed, state.length, state.ended);
        if (!state.destroyed && (state.length || state.ended)) {
          stream.emit("readable");
          state.emittedReadable = false;
        }
        state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
        flow(stream);
      }
      function maybeReadMore(stream, state) {
        if (!state.readingMore) {
          state.readingMore = true;
          process.nextTick(maybeReadMore_, stream, state);
        }
      }
      function maybeReadMore_(stream, state) {
        while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
          var len = state.length;
          debug("maybeReadMore read 0");
          stream.read(0);
          if (len === state.length)
            break;
        }
        state.readingMore = false;
      }
      Readable.prototype._read = function(n) {
        errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()"));
      };
      Readable.prototype.pipe = function(dest, pipeOpts) {
        var src = this;
        var state = this._readableState;
        switch (state.pipesCount) {
          case 0:
            state.pipes = dest;
            break;
          case 1:
            state.pipes = [state.pipes, dest];
            break;
          default:
            state.pipes.push(dest);
            break;
        }
        state.pipesCount += 1;
        debug("pipe count=%d opts=%j", state.pipesCount, pipeOpts);
        var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
        var endFn = doEnd ? onend : unpipe;
        if (state.endEmitted) process.nextTick(endFn);
        else src.once("end", endFn);
        dest.on("unpipe", onunpipe);
        function onunpipe(readable, unpipeInfo) {
          debug("onunpipe");
          if (readable === src) {
            if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
              unpipeInfo.hasUnpiped = true;
              cleanup();
            }
          }
        }
        function onend() {
          debug("onend");
          dest.end();
        }
        var ondrain = pipeOnDrain(src);
        dest.on("drain", ondrain);
        var cleanedUp = false;
        function cleanup() {
          debug("cleanup");
          dest.removeListener("close", onclose);
          dest.removeListener("finish", onfinish);
          dest.removeListener("drain", ondrain);
          dest.removeListener("error", onerror);
          dest.removeListener("unpipe", onunpipe);
          src.removeListener("end", onend);
          src.removeListener("end", unpipe);
          src.removeListener("data", ondata);
          cleanedUp = true;
          if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
        }
        src.on("data", ondata);
        function ondata(chunk) {
          debug("ondata");
          var ret = dest.write(chunk);
          debug("dest.write", ret);
          if (ret === false) {
            if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
              debug("false write response, pause", state.awaitDrain);
              state.awaitDrain++;
            }
            src.pause();
          }
        }
        function onerror(er) {
          debug("onerror", er);
          unpipe();
          dest.removeListener("error", onerror);
          if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er);
        }
        prependListener(dest, "error", onerror);
        function onclose() {
          dest.removeListener("finish", onfinish);
          unpipe();
        }
        dest.once("close", onclose);
        function onfinish() {
          debug("onfinish");
          dest.removeListener("close", onclose);
          unpipe();
        }
        dest.once("finish", onfinish);
        function unpipe() {
          debug("unpipe");
          src.unpipe(dest);
        }
        dest.emit("pipe", src);
        if (!state.flowing) {
          debug("pipe resume");
          src.resume();
        }
        return dest;
      };
      function pipeOnDrain(src) {
        return function pipeOnDrainFunctionResult() {
          var state = src._readableState;
          debug("pipeOnDrain", state.awaitDrain);
          if (state.awaitDrain) state.awaitDrain--;
          if (state.awaitDrain === 0 && EElistenerCount(src, "data")) {
            state.flowing = true;
            flow(src);
          }
        };
      }
      Readable.prototype.unpipe = function(dest) {
        var state = this._readableState;
        var unpipeInfo = {
          hasUnpiped: false
        };
        if (state.pipesCount === 0) return this;
        if (state.pipesCount === 1) {
          if (dest && dest !== state.pipes) return this;
          if (!dest) dest = state.pipes;
          state.pipes = null;
          state.pipesCount = 0;
          state.flowing = false;
          if (dest) dest.emit("unpipe", this, unpipeInfo);
          return this;
        }
        if (!dest) {
          var dests = state.pipes;
          var len = state.pipesCount;
          state.pipes = null;
          state.pipesCount = 0;
          state.flowing = false;
          for (var i = 0; i < len; i++) {
            dests[i].emit("unpipe", this, {
              hasUnpiped: false
            });
          }
          return this;
        }
        var index = indexOf(state.pipes, dest);
        if (index === -1) return this;
        state.pipes.splice(index, 1);
        state.pipesCount -= 1;
        if (state.pipesCount === 1) state.pipes = state.pipes[0];
        dest.emit("unpipe", this, unpipeInfo);
        return this;
      };
      Readable.prototype.on = function(ev, fn) {
        var res = Stream.prototype.on.call(this, ev, fn);
        var state = this._readableState;
        if (ev === "data") {
          state.readableListening = this.listenerCount("readable") > 0;
          if (state.flowing !== false) this.resume();
        } else if (ev === "readable") {
          if (!state.endEmitted && !state.readableListening) {
            state.readableListening = state.needReadable = true;
            state.flowing = false;
            state.emittedReadable = false;
            debug("on readable", state.length, state.reading);
            if (state.length) {
              emitReadable(this);
            } else if (!state.reading) {
              process.nextTick(nReadingNextTick, this);
            }
          }
        }
        return res;
      };
      Readable.prototype.addListener = Readable.prototype.on;
      Readable.prototype.removeListener = function(ev, fn) {
        var res = Stream.prototype.removeListener.call(this, ev, fn);
        if (ev === "readable") {
          process.nextTick(updateReadableListening, this);
        }
        return res;
      };
      Readable.prototype.removeAllListeners = function(ev) {
        var res = Stream.prototype.removeAllListeners.apply(this, arguments);
        if (ev === "readable" || ev === void 0) {
          process.nextTick(updateReadableListening, this);
        }
        return res;
      };
      function updateReadableListening(self2) {
        var state = self2._readableState;
        state.readableListening = self2.listenerCount("readable") > 0;
        if (state.resumeScheduled && !state.paused) {
          state.flowing = true;
        } else if (self2.listenerCount("data") > 0) {
          self2.resume();
        }
      }
      function nReadingNextTick(self2) {
        debug("readable nexttick read 0");
        self2.read(0);
      }
      Readable.prototype.resume = function() {
        var state = this._readableState;
        if (!state.flowing) {
          debug("resume");
          state.flowing = !state.readableListening;
          resume(this, state);
        }
        state.paused = false;
        return this;
      };
      function resume(stream, state) {
        if (!state.resumeScheduled) {
          state.resumeScheduled = true;
          process.nextTick(resume_, stream, state);
        }
      }
      function resume_(stream, state) {
        debug("resume", state.reading);
        if (!state.reading) {
          stream.read(0);
        }
        state.resumeScheduled = false;
        stream.emit("resume");
        flow(stream);
        if (state.flowing && !state.reading) stream.read(0);
      }
      Readable.prototype.pause = function() {
        debug("call pause flowing=%j", this._readableState.flowing);
        if (this._readableState.flowing !== false) {
          debug("pause");
          this._readableState.flowing = false;
          this.emit("pause");
        }
        this._readableState.paused = true;
        return this;
      };
      function flow(stream) {
        var state = stream._readableState;
        debug("flow", state.flowing);
        while (state.flowing && stream.read() !== null) {
          ;
        }
      }
      Readable.prototype.wrap = function(stream) {
        var _this = this;
        var state = this._readableState;
        var paused = false;
        stream.on("end", function() {
          debug("wrapped end");
          if (state.decoder && !state.ended) {
            var chunk = state.decoder.end();
            if (chunk && chunk.length) _this.push(chunk);
          }
          _this.push(null);
        });
        stream.on("data", function(chunk) {
          debug("wrapped data");
          if (state.decoder) chunk = state.decoder.write(chunk);
          if (state.objectMode && (chunk === null || chunk === void 0)) return;
          else if (!state.objectMode && (!chunk || !chunk.length)) return;
          var ret = _this.push(chunk);
          if (!ret) {
            paused = true;
            stream.pause();
          }
        });
        for (var i in stream) {
          if (this[i] === void 0 && typeof stream[i] === "function") {
            this[i] = /* @__PURE__ */ function methodWrap(method) {
              return function methodWrapReturnFunction() {
                return stream[method].apply(stream, arguments);
              };
            }(i);
          }
        }
        for (var n = 0; n < kProxyEvents.length; n++) {
          stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
        }
        this._read = function(n2) {
          debug("wrapped _read", n2);
          if (paused) {
            paused = false;
            stream.resume();
          }
        };
        return this;
      };
      if (typeof Symbol === "function") {
        Readable.prototype[Symbol.asyncIterator] = function() {
          if (createReadableStreamAsyncIterator === void 0) {
            createReadableStreamAsyncIterator = require_async_iterator();
          }
          return createReadableStreamAsyncIterator(this);
        };
      }
      Object.defineProperty(Readable.prototype, "readableHighWaterMark", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._readableState.highWaterMark;
        }
      });
      Object.defineProperty(Readable.prototype, "readableBuffer", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._readableState && this._readableState.buffer;
        }
      });
      Object.defineProperty(Readable.prototype, "readableFlowing", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._readableState.flowing;
        },
        set: function set(state) {
          if (this._readableState) {
            this._readableState.flowing = state;
          }
        }
      });
      Readable._fromList = fromList;
      Object.defineProperty(Readable.prototype, "readableLength", {
        // making it explicit this property is not enumerable
        // because otherwise some prototype manipulation in
        // userland will fail
        enumerable: false,
        get: function get() {
          return this._readableState.length;
        }
      });
      function fromList(n, state) {
        if (state.length === 0) return null;
        var ret;
        if (state.objectMode) ret = state.buffer.shift();
        else if (!n || n >= state.length) {
          if (state.decoder) ret = state.buffer.join("");
          else if (state.buffer.length === 1) ret = state.buffer.first();
          else ret = state.buffer.concat(state.length);
          state.buffer.clear();
        } else {
          ret = state.buffer.consume(n, state.decoder);
        }
        return ret;
      }
      function endReadable(stream) {
        var state = stream._readableState;
        debug("endReadable", state.endEmitted);
        if (!state.endEmitted) {
          state.ended = true;
          process.nextTick(endReadableNT, state, stream);
        }
      }
      function endReadableNT(state, stream) {
        debug("endReadableNT", state.endEmitted, state.length);
        if (!state.endEmitted && state.length === 0) {
          state.endEmitted = true;
          stream.readable = false;
          stream.emit("end");
          if (state.autoDestroy) {
            var wState = stream._writableState;
            if (!wState || wState.autoDestroy && wState.finished) {
              stream.destroy();
            }
          }
        }
      }
      if (typeof Symbol === "function") {
        Readable.from = function(iterable, opts) {
          if (from === void 0) {
            from = require_from_browser();
          }
          return from(Readable, iterable, opts);
        };
      }
      function indexOf(xs, x) {
        for (var i = 0, l = xs.length; i < l; i++) {
          if (xs[i] === x) return i;
        }
        return -1;
      }
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_transform.js
  var require_stream_transform = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_transform.js"(exports, module) {
      "use strict";
      module.exports = Transform;
      var _require$codes = require_errors_browser().codes;
      var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED;
      var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK;
      var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING;
      var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
      var Duplex = require_stream_duplex();
      require_inherits_browser()(Transform, Duplex);
      function afterTransform(er, data) {
        var ts = this._transformState;
        ts.transforming = false;
        var cb = ts.writecb;
        if (cb === null) {
          return this.emit("error", new ERR_MULTIPLE_CALLBACK());
        }
        ts.writechunk = null;
        ts.writecb = null;
        if (data != null)
          this.push(data);
        cb(er);
        var rs = this._readableState;
        rs.reading = false;
        if (rs.needReadable || rs.length < rs.highWaterMark) {
          this._read(rs.highWaterMark);
        }
      }
      function Transform(options) {
        if (!(this instanceof Transform)) return new Transform(options);
        Duplex.call(this, options);
        this._transformState = {
          afterTransform: afterTransform.bind(this),
          needTransform: false,
          transforming: false,
          writecb: null,
          writechunk: null,
          writeencoding: null
        };
        this._readableState.needReadable = true;
        this._readableState.sync = false;
        if (options) {
          if (typeof options.transform === "function") this._transform = options.transform;
          if (typeof options.flush === "function") this._flush = options.flush;
        }
        this.on("prefinish", prefinish);
      }
      function prefinish() {
        var _this = this;
        if (typeof this._flush === "function" && !this._readableState.destroyed) {
          this._flush(function(er, data) {
            done(_this, er, data);
          });
        } else {
          done(this, null, null);
        }
      }
      Transform.prototype.push = function(chunk, encoding) {
        this._transformState.needTransform = false;
        return Duplex.prototype.push.call(this, chunk, encoding);
      };
      Transform.prototype._transform = function(chunk, encoding, cb) {
        cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"));
      };
      Transform.prototype._write = function(chunk, encoding, cb) {
        var ts = this._transformState;
        ts.writecb = cb;
        ts.writechunk = chunk;
        ts.writeencoding = encoding;
        if (!ts.transforming) {
          var rs = this._readableState;
          if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
        }
      };
      Transform.prototype._read = function(n) {
        var ts = this._transformState;
        if (ts.writechunk !== null && !ts.transforming) {
          ts.transforming = true;
          this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
        } else {
          ts.needTransform = true;
        }
      };
      Transform.prototype._destroy = function(err, cb) {
        Duplex.prototype._destroy.call(this, err, function(err2) {
          cb(err2);
        });
      };
      function done(stream, er, data) {
        if (er) return stream.emit("error", er);
        if (data != null)
          stream.push(data);
        if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
        if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
        return stream.push(null);
      }
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_passthrough.js
  var require_stream_passthrough = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_passthrough.js"(exports, module) {
      "use strict";
      module.exports = PassThrough;
      var Transform = require_stream_transform();
      require_inherits_browser()(PassThrough, Transform);
      function PassThrough(options) {
        if (!(this instanceof PassThrough)) return new PassThrough(options);
        Transform.call(this, options);
      }
      PassThrough.prototype._transform = function(chunk, encoding, cb) {
        cb(null, chunk);
      };
    }
  });

  // node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/pipeline.js
  var require_pipeline = __commonJS({
    "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports, module) {
      "use strict";
      var eos;
      function once(callback) {
        var called = false;
        return function() {
          if (called) return;
          called = true;
          callback.apply(void 0, arguments);
        };
      }
      var _require$codes = require_errors_browser().codes;
      var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS;
      var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
      function noop(err) {
        if (err) throw err;
      }
      function isRequest(stream) {
        return stream.setHeader && typeof stream.abort === "function";
      }
      function destroyer(stream, reading, writing, callback) {
        callback = once(callback);
        var closed = false;
        stream.on("close", function() {
          closed = true;
        });
        if (eos === void 0) eos = require_end_of_stream();
        eos(stream, {
          readable: reading,
          writable: writing
        }, function(err) {
          if (err) return callback(err);
          closed = true;
          callback();
        });
        var destroyed = false;
        return function(err) {
          if (closed) return;
          if (destroyed) return;
          destroyed = true;
          if (isRequest(stream)) return stream.abort();
          if (typeof stream.destroy === "function") return stream.destroy();
          callback(err || new ERR_STREAM_DESTROYED("pipe"));
        };
      }
      function call(fn) {
        fn();
      }
      function pipe(from, to) {
        return from.pipe(to);
      }
      function popCallback(streams) {
        if (!streams.length) return noop;
        if (typeof streams[streams.length - 1] !== "function") return noop;
        return streams.pop();
      }
      function pipeline() {
        for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
          streams[_key] = arguments[_key];
        }
        var callback = popCallback(streams);
        if (Array.isArray(streams[0])) streams = streams[0];
        if (streams.length < 2) {
          throw new ERR_MISSING_ARGS("streams");
        }
        var error;
        var destroys = streams.map(function(stream, i) {
          var reading = i < streams.length - 1;
          var writing = i > 0;
          return destroyer(stream, reading, writing, function(err) {
            if (!error) error = err;
            if (err) destroys.forEach(call);
            if (reading) return;
            destroys.forEach(call);
            callback(error);
          });
        });
        return streams.reduce(pipe);
      }
      module.exports = pipeline;
    }
  });

  // node_modules/stream-browserify/index.js
  var require_stream_browserify = __commonJS({
    "node_modules/stream-browserify/index.js"(exports, module) {
      module.exports = Stream;
      var EE = require_events().EventEmitter;
      var inherits = require_inherits_browser();
      inherits(Stream, EE);
      Stream.Readable = require_stream_readable();
      Stream.Writable = require_stream_writable();
      Stream.Duplex = require_stream_duplex();
      Stream.Transform = require_stream_transform();
      Stream.PassThrough = require_stream_passthrough();
      Stream.finished = require_end_of_stream();
      Stream.pipeline = require_pipeline();
      Stream.Stream = Stream;
      function Stream() {
        EE.call(this);
      }
      Stream.prototype.pipe = function(dest, options) {
        var source = this;
        function ondata(chunk) {
          if (dest.writable) {
            if (false === dest.write(chunk) && source.pause) {
              source.pause();
            }
          }
        }
        source.on("data", ondata);
        function ondrain() {
          if (source.readable && source.resume) {
            source.resume();
          }
        }
        dest.on("drain", ondrain);
        if (!dest._isStdio && (!options || options.end !== false)) {
          source.on("end", onend);
          source.on("close", onclose);
        }
        var didOnEnd = false;
        function onend() {
          if (didOnEnd) return;
          didOnEnd = true;
          dest.end();
        }
        function onclose() {
          if (didOnEnd) return;
          didOnEnd = true;
          if (typeof dest.destroy === "function") dest.destroy();
        }
        function onerror(er) {
          cleanup();
          if (EE.listenerCount(this, "error") === 0) {
            throw er;
          }
        }
        source.on("error", onerror);
        dest.on("error", onerror);
        function cleanup() {
          source.removeListener("data", ondata);
          dest.removeListener("drain", ondrain);
          source.removeListener("end", onend);
          source.removeListener("close", onclose);
          source.removeListener("error", onerror);
          dest.removeListener("error", onerror);
          source.removeListener("end", cleanup);
          source.removeListener("close", cleanup);
          dest.removeListener("close", cleanup);
        }
        source.on("end", cleanup);
        source.on("close", cleanup);
        dest.on("close", cleanup);
        dest.emit("pipe", source);
        return dest;
      };
    }
  });

  // node_modules/util/util.js
  var require_util2 = __commonJS({
    "node_modules/util/util.js"(exports) {
      var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors2(obj) {
        var keys = Object.keys(obj);
        var descriptors = {};
        for (var i = 0; i < keys.length; i++) {
          descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
        }
        return descriptors;
      };
      var formatRegExp = /%[sdj%]/g;
      exports.format = function(f) {
        if (!isString(f)) {
          var objects = [];
          for (var i = 0; i < arguments.length; i++) {
            objects.push(inspect(arguments[i]));
          }
          return objects.join(" ");
        }
        var i = 1;
        var args = arguments;
        var len = args.length;
        var str = String(f).replace(formatRegExp, function(x2) {
          if (x2 === "%%") return "%";
          if (i >= len) return x2;
          switch (x2) {
            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 x2;
          }
        });
        for (var x = args[i]; i < len; x = args[++i]) {
          if (isNull(x) || !isObject(x)) {
            str += " " + x;
          } else {
            str += " " + inspect(x);
          }
        }
        return str;
      };
      exports.deprecate = function(fn, msg) {
        if (typeof process !== "undefined" && process.noDeprecation === true) {
          return fn;
        }
        if (typeof process === "undefined") {
          return function() {
            return exports.deprecate(fn, msg).apply(this, arguments);
          };
        }
        var warned = false;
        function deprecated() {
          if (!warned) {
            if (process.throwDeprecation) {
              throw new Error(msg);
            } else if (process.traceDeprecation) {
              console.trace(msg);
            } else {
              console.error(msg);
            }
            warned = true;
          }
          return fn.apply(this, arguments);
        }
        return deprecated;
      };
      var debugs = {};
      var debugEnvRegex = /^$/;
      if ("false") {
        debugEnv = "false";
        debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase();
        debugEnvRegex = new RegExp("^" + debugEnv + "$", "i");
      }
      var debugEnv;
      exports.debuglog = function(set) {
        set = set.toUpperCase();
        if (!debugs[set]) {
          if (debugEnvRegex.test(set)) {
            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];
      };
      function inspect(obj, opts) {
        var ctx = {
          seen: [],
          stylize: stylizeNoColor
        };
        if (arguments.length >= 3) ctx.depth = arguments[2];
        if (arguments.length >= 4) ctx.colors = arguments[3];
        if (isBoolean(opts)) {
          ctx.showHidden = opts;
        } else if (opts) {
          exports._extend(ctx, opts);
        }
        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;
      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]
      };
      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 "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + 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) {
        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;
        }
        var primitive = formatPrimitive(ctx, value);
        if (primitive) {
          return primitive;
        }
        var keys = Object.keys(value);
        var visibleKeys = arrayToHash(keys);
        if (ctx.showHidden) {
          keys = Object.getOwnPropertyNames(value);
        }
        if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
          return formatError(value);
        }
        if (keys.length === 0) {
          if (isFunction(value)) {
            var name2 = value.name ? ": " + value.name : "";
            return ctx.stylize("[Function" + name2 + "]", "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 = ["{", "}"];
        if (isArray(value)) {
          array = true;
          braces = ["[", "]"];
        }
        if (isFunction(value)) {
          var n = value.name ? ": " + value.name : "";
          base = " [Function" + n + "]";
        }
        if (isRegExp(value)) {
          base = " " + RegExp.prototype.toString.call(value);
        }
        if (isDate(value)) {
          base = " " + Date.prototype.toUTCString.call(value);
        }
        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");
        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 (hasOwnProperty2(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 name2, 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 (!hasOwnProperty2(visibleKeys, key)) {
          name2 = "[" + 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").slice(2);
              } else {
                str = "\n" + str.split("\n").map(function(line) {
                  return "   " + line;
                }).join("\n");
              }
            }
          } else {
            str = ctx.stylize("[Circular]", "special");
          }
        }
        if (isUndefined(name2)) {
          if (array && key.match(/^\d+$/)) {
            return str;
          }
          name2 = JSON.stringify("" + key);
          if (name2.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
            name2 = name2.slice(1, -1);
            name2 = ctx.stylize(name2, "name");
          } else {
            name2 = name2.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
            name2 = ctx.stylize(name2, "string");
          }
        }
        return name2 + ": " + 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];
      }
      exports.types = require_types();
      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;
      exports.types.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;
      exports.types.isDate = isDate;
      function isError(e) {
        return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
      }
      exports.isError = isError;
      exports.types.isNativeError = 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_isBufferBrowser();
      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"
      ];
      function timestamp() {
        var d = /* @__PURE__ */ new Date();
        var time = [
          pad(d.getHours()),
          pad(d.getMinutes()),
          pad(d.getSeconds())
        ].join(":");
        return [d.getDate(), months[d.getMonth()], time].join(" ");
      }
      exports.log = function() {
        console.log("%s - %s", timestamp(), exports.format.apply(exports, arguments));
      };
      exports.inherits = require_inherits_browser();
      exports._extend = function(origin, add) {
        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 hasOwnProperty2(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
      }
      var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : void 0;
      exports.promisify = function promisify(original) {
        if (typeof original !== "function")
          throw new TypeError('The "original" argument must be of type Function');
        if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
          var fn = original[kCustomPromisifiedSymbol];
          if (typeof fn !== "function") {
            throw new TypeError('The "util.promisify.custom" argument must be of type Function');
          }
          Object.defineProperty(fn, kCustomPromisifiedSymbol, {
            value: fn,
            enumerable: false,
            writable: false,
            configurable: true
          });
          return fn;
        }
        function fn() {
          var promiseResolve, promiseReject;
          var promise = new Promise(function(resolve, reject) {
            promiseResolve = resolve;
            promiseReject = reject;
          });
          var args = [];
          for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
          }
          args.push(function(err, value) {
            if (err) {
              promiseReject(err);
            } else {
              promiseResolve(value);
            }
          });
          try {
            original.apply(this, args);
          } catch (err) {
            promiseReject(err);
          }
          return promise;
        }
        Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
        if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
          value: fn,
          enumerable: false,
          writable: false,
          configurable: true
        });
        return Object.defineProperties(
          fn,
          getOwnPropertyDescriptors(original)
        );
      };
      exports.promisify.custom = kCustomPromisifiedSymbol;
      function callbackifyOnRejected(reason, cb) {
        if (!reason) {
          var newReason = new Error("Promise was rejected with a falsy value");
          newReason.reason = reason;
          reason = newReason;
        }
        return cb(reason);
      }
      function callbackify(original) {
        if (typeof original !== "function") {
          throw new TypeError('The "original" argument must be of type Function');
        }
        function callbackified() {
          var args = [];
          for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
          }
          var maybeCb = args.pop();
          if (typeof maybeCb !== "function") {
            throw new TypeError("The last argument must be of type Function");
          }
          var self2 = this;
          var cb = function() {
            return maybeCb.apply(self2, arguments);
          };
          original.apply(this, args).then(
            function(ret) {
              process.nextTick(cb.bind(null, null, ret));
            },
            function(rej) {
              process.nextTick(callbackifyOnRejected.bind(null, rej, cb));
            }
          );
        }
        Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
        Object.defineProperties(
          callbackified,
          getOwnPropertyDescriptors(original)
        );
        return callbackified;
      }
      exports.callbackify = callbackify;
    }
  });

  // node_modules/assert/build/internal/errors.js
  var require_errors = __commonJS({
    "node_modules/assert/build/internal/errors.js"(exports, module) {
      "use strict";
      function _typeof(o) {
        "@babel/helpers - typeof";
        return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
          return typeof o2;
        } : function(o2) {
          return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
        }, _typeof(o);
      }
      function _defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
        }
      }
      function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        Object.defineProperty(Constructor, "prototype", { writable: false });
        return Constructor;
      }
      function _toPropertyKey(arg) {
        var key = _toPrimitive(arg, "string");
        return _typeof(key) === "symbol" ? key : String(key);
      }
      function _toPrimitive(input, hint) {
        if (_typeof(input) !== "object" || input === null) return input;
        var prim = input[Symbol.toPrimitive];
        if (prim !== void 0) {
          var res = prim.call(input, hint || "default");
          if (_typeof(res) !== "object") return res;
          throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return (hint === "string" ? String : Number)(input);
      }
      function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
          throw new TypeError("Cannot call a class as a function");
        }
      }
      function _inherits(subClass, superClass) {
        if (typeof superClass !== "function" && superClass !== null) {
          throw new TypeError("Super expression must either be null or a function");
        }
        subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
        Object.defineProperty(subClass, "prototype", { writable: false });
        if (superClass) _setPrototypeOf(subClass, superClass);
      }
      function _setPrototypeOf(o, p) {
        _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
          o2.__proto__ = p2;
          return o2;
        };
        return _setPrototypeOf(o, p);
      }
      function _createSuper(Derived) {
        var hasNativeReflectConstruct = _isNativeReflectConstruct();
        return function _createSuperInternal() {
          var Super = _getPrototypeOf(Derived), result;
          if (hasNativeReflectConstruct) {
            var NewTarget = _getPrototypeOf(this).constructor;
            result = Reflect.construct(Super, arguments, NewTarget);
          } else {
            result = Super.apply(this, arguments);
          }
          return _possibleConstructorReturn(this, result);
        };
      }
      function _possibleConstructorReturn(self2, call) {
        if (call && (_typeof(call) === "object" || typeof call === "function")) {
          return call;
        } else if (call !== void 0) {
          throw new TypeError("Derived constructors may only return object or undefined");
        }
        return _assertThisInitialized(self2);
      }
      function _assertThisInitialized(self2) {
        if (self2 === void 0) {
          throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
        }
        return self2;
      }
      function _isNativeReflectConstruct() {
        if (typeof Reflect === "undefined" || !Reflect.construct) return false;
        if (Reflect.construct.sham) return false;
        if (typeof Proxy === "function") return true;
        try {
          Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
          }));
          return true;
        } catch (e) {
          return false;
        }
      }
      function _getPrototypeOf(o) {
        _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
          return o2.__proto__ || Object.getPrototypeOf(o2);
        };
        return _getPrototypeOf(o);
      }
      var codes = {};
      var assert;
      var util;
      function createErrorType(code, message, Base) {
        if (!Base) {
          Base = Error;
        }
        function getMessage(arg1, arg2, arg3) {
          if (typeof message === "string") {
            return message;
          } else {
            return message(arg1, arg2, arg3);
          }
        }
        var NodeError = /* @__PURE__ */ function(_Base) {
          _inherits(NodeError2, _Base);
          var _super = _createSuper(NodeError2);
          function NodeError2(arg1, arg2, arg3) {
            var _this;
            _classCallCheck(this, NodeError2);
            _this = _super.call(this, getMessage(arg1, arg2, arg3));
            _this.code = code;
            return _this;
          }
          return _createClass(NodeError2);
        }(Base);
        codes[code] = NodeError;
      }
      function oneOf(expected, thing) {
        if (Array.isArray(expected)) {
          var len = expected.length;
          expected = expected.map(function(i) {
            return String(i);
          });
          if (len > 2) {
            return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(", "), ", or ") + expected[len - 1];
          } else if (len === 2) {
            return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
          } else {
            return "of ".concat(thing, " ").concat(expected[0]);
          }
        } else {
          return "of ".concat(thing, " ").concat(String(expected));
        }
      }
      function startsWith(str, search, pos) {
        return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
      }
      function endsWith(str, search, this_len) {
        if (this_len === void 0 || this_len > str.length) {
          this_len = str.length;
        }
        return str.substring(this_len - search.length, this_len) === search;
      }
      function includes(str, search, start) {
        if (typeof start !== "number") {
          start = 0;
        }
        if (start + search.length > str.length) {
          return false;
        } else {
          return str.indexOf(search, start) !== -1;
        }
      }
      createErrorType("ERR_AMBIGUOUS_ARGUMENT", 'The "%s" argument is ambiguous. %s', TypeError);
      createErrorType("ERR_INVALID_ARG_TYPE", function(name2, expected, actual) {
        if (assert === void 0) assert = require_assert();
        assert(typeof name2 === "string", "'name' must be a string");
        var determiner;
        if (typeof expected === "string" && startsWith(expected, "not ")) {
          determiner = "must not be";
          expected = expected.replace(/^not /, "");
        } else {
          determiner = "must be";
        }
        var msg;
        if (endsWith(name2, " argument")) {
          msg = "The ".concat(name2, " ").concat(determiner, " ").concat(oneOf(expected, "type"));
        } else {
          var type = includes(name2, ".") ? "property" : "argument";
          msg = 'The "'.concat(name2, '" ').concat(type, " ").concat(determiner, " ").concat(oneOf(expected, "type"));
        }
        msg += ". Received type ".concat(_typeof(actual));
        return msg;
      }, TypeError);
      createErrorType("ERR_INVALID_ARG_VALUE", function(name2, value) {
        var reason = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "is invalid";
        if (util === void 0) util = require_util2();
        var inspected = util.inspect(value);
        if (inspected.length > 128) {
          inspected = "".concat(inspected.slice(0, 128), "...");
        }
        return "The argument '".concat(name2, "' ").concat(reason, ". Received ").concat(inspected);
      }, TypeError, RangeError);
      createErrorType("ERR_INVALID_RETURN_VALUE", function(input, name2, value) {
        var type;
        if (value && value.constructor && value.constructor.name) {
          type = "instance of ".concat(value.constructor.name);
        } else {
          type = "type ".concat(_typeof(value));
        }
        return "Expected ".concat(input, ' to be returned from the "').concat(name2, '"') + " function but got ".concat(type, ".");
      }, TypeError);
      createErrorType("ERR_MISSING_ARGS", function() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        if (assert === void 0) assert = require_assert();
        assert(args.length > 0, "At least one arg needs to be specified");
        var msg = "The ";
        var len = args.length;
        args = args.map(function(a) {
          return '"'.concat(a, '"');
        });
        switch (len) {
          case 1:
            msg += "".concat(args[0], " argument");
            break;
          case 2:
            msg += "".concat(args[0], " and ").concat(args[1], " arguments");
            break;
          default:
            msg += args.slice(0, len - 1).join(", ");
            msg += ", and ".concat(args[len - 1], " arguments");
            break;
        }
        return "".concat(msg, " must be specified");
      }, TypeError);
      module.exports.codes = codes;
    }
  });

  // node_modules/assert/build/internal/assert/assertion_error.js
  var require_assertion_error = __commonJS({
    "node_modules/assert/build/internal/assert/assertion_error.js"(exports, module) {
      "use strict";
      function ownKeys(e, r) {
        var t = Object.keys(e);
        if (Object.getOwnPropertySymbols) {
          var o = Object.getOwnPropertySymbols(e);
          r && (o = o.filter(function(r2) {
            return Object.getOwnPropertyDescriptor(e, r2).enumerable;
          })), t.push.apply(t, o);
        }
        return t;
      }
      function _objectSpread(e) {
        for (var r = 1; r < arguments.length; r++) {
          var t = null != arguments[r] ? arguments[r] : {};
          r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
            _defineProperty(e, r2, t[r2]);
          }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
            Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
          });
        }
        return e;
      }
      function _defineProperty(obj, key, value) {
        key = _toPropertyKey(key);
        if (key in obj) {
          Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
        } else {
          obj[key] = value;
        }
        return obj;
      }
      function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
          throw new TypeError("Cannot call a class as a function");
        }
      }
      function _defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
        }
      }
      function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        Object.defineProperty(Constructor, "prototype", { writable: false });
        return Constructor;
      }
      function _toPropertyKey(arg) {
        var key = _toPrimitive(arg, "string");
        return _typeof(key) === "symbol" ? key : String(key);
      }
      function _toPrimitive(input, hint) {
        if (_typeof(input) !== "object" || input === null) return input;
        var prim = input[Symbol.toPrimitive];
        if (prim !== void 0) {
          var res = prim.call(input, hint || "default");
          if (_typeof(res) !== "object") return res;
          throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return (hint === "string" ? String : Number)(input);
      }
      function _inherits(subClass, superClass) {
        if (typeof superClass !== "function" && superClass !== null) {
          throw new TypeError("Super expression must either be null or a function");
        }
        subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
        Object.defineProperty(subClass, "prototype", { writable: false });
        if (superClass) _setPrototypeOf(subClass, superClass);
      }
      function _createSuper(Derived) {
        var hasNativeReflectConstruct = _isNativeReflectConstruct();
        return function _createSuperInternal() {
          var Super = _getPrototypeOf(Derived), result;
          if (hasNativeReflectConstruct) {
            var NewTarget = _getPrototypeOf(this).constructor;
            result = Reflect.construct(Super, arguments, NewTarget);
          } else {
            result = Super.apply(this, arguments);
          }
          return _possibleConstructorReturn(this, result);
        };
      }
      function _possibleConstructorReturn(self2, call) {
        if (call && (_typeof(call) === "object" || typeof call === "function")) {
          return call;
        } else if (call !== void 0) {
          throw new TypeError("Derived constructors may only return object or undefined");
        }
        return _assertThisInitialized(self2);
      }
      function _assertThisInitialized(self2) {
        if (self2 === void 0) {
          throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
        }
        return self2;
      }
      function _wrapNativeSuper(Class) {
        var _cache = typeof Map === "function" ? /* @__PURE__ */ new Map() : void 0;
        _wrapNativeSuper = function _wrapNativeSuper2(Class2) {
          if (Class2 === null || !_isNativeFunction(Class2)) return Class2;
          if (typeof Class2 !== "function") {
            throw new TypeError("Super expression must either be null or a function");
          }
          if (typeof _cache !== "undefined") {
            if (_cache.has(Class2)) return _cache.get(Class2);
            _cache.set(Class2, Wrapper);
          }
          function Wrapper() {
            return _construct(Class2, arguments, _getPrototypeOf(this).constructor);
          }
          Wrapper.prototype = Object.create(Class2.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } });
          return _setPrototypeOf(Wrapper, Class2);
        };
        return _wrapNativeSuper(Class);
      }
      function _construct(Parent, args, Class) {
        if (_isNativeReflectConstruct()) {
          _construct = Reflect.construct.bind();
        } else {
          _construct = function _construct2(Parent2, args2, Class2) {
            var a = [null];
            a.push.apply(a, args2);
            var Constructor = Function.bind.apply(Parent2, a);
            var instance = new Constructor();
            if (Class2) _setPrototypeOf(instance, Class2.prototype);
            return instance;
          };
        }
        return _construct.apply(null, arguments);
      }
      function _isNativeReflectConstruct() {
        if (typeof Reflect === "undefined" || !Reflect.construct) return false;
        if (Reflect.construct.sham) return false;
        if (typeof Proxy === "function") return true;
        try {
          Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
          }));
          return true;
        } catch (e) {
          return false;
        }
      }
      function _isNativeFunction(fn) {
        return Function.toString.call(fn).indexOf("[native code]") !== -1;
      }
      function _setPrototypeOf(o, p) {
        _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) {
          o2.__proto__ = p2;
          return o2;
        };
        return _setPrototypeOf(o, p);
      }
      function _getPrototypeOf(o) {
        _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) {
          return o2.__proto__ || Object.getPrototypeOf(o2);
        };
        return _getPrototypeOf(o);
      }
      function _typeof(o) {
        "@babel/helpers - typeof";
        return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
          return typeof o2;
        } : function(o2) {
          return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
        }, _typeof(o);
      }
      var _require = require_util2();
      var inspect = _require.inspect;
      var _require2 = require_errors();
      var ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE;
      function endsWith(str, search, this_len) {
        if (this_len === void 0 || this_len > str.length) {
          this_len = str.length;
        }
        return str.substring(this_len - search.length, this_len) === search;
      }
      function repeat(str, count) {
        count = Math.floor(count);
        if (str.length == 0 || count == 0) return "";
        var maxCount = str.length * count;
        count = Math.floor(Math.log(count) / Math.log(2));
        while (count) {
          str += str;
          count--;
        }
        str += str.substring(0, maxCount - str.length);
        return str;
      }
      var blue = "";
      var green = "";
      var red = "";
      var white = "";
      var kReadableOperator = {
        deepStrictEqual: "Expected values to be strictly deep-equal:",
        strictEqual: "Expected values to be strictly equal:",
        strictEqualObject: 'Expected "actual" to be reference-equal to "expected":',
        deepEqual: "Expected values to be loosely deep-equal:",
        equal: "Expected values to be loosely equal:",
        notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:',
        notStrictEqual: 'Expected "actual" to be strictly unequal to:',
        notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":',
        notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:',
        notEqual: 'Expected "actual" to be loosely unequal to:',
        notIdentical: "Values identical but not reference-equal:"
      };
      var kMaxShortLength = 10;
      function copyError(source) {
        var keys = Object.keys(source);
        var target = Object.create(Object.getPrototypeOf(source));
        keys.forEach(function(key) {
          target[key] = source[key];
        });
        Object.defineProperty(target, "message", {
          value: source.message
        });
        return target;
      }
      function inspectValue(val) {
        return inspect(val, {
          compact: false,
          customInspect: false,
          depth: 1e3,
          maxArrayLength: Infinity,
          // Assert compares only enumerable properties (with a few exceptions).
          showHidden: false,
          // Having a long line as error is better than wrapping the line for
          // comparison for now.
          // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we
          // have meta information about the inspected properties (i.e., know where
          // in what line the property starts and ends).
          breakLength: Infinity,
          // Assert does not detect proxies currently.
          showProxy: false,
          sorted: true,
          // Inspect getters as we also check them when comparing entries.
          getters: true
        });
      }
      function createErrDiff(actual, expected, operator) {
        var other = "";
        var res = "";
        var lastPos = 0;
        var end = "";
        var skipped = false;
        var actualInspected = inspectValue(actual);
        var actualLines = actualInspected.split("\n");
        var expectedLines = inspectValue(expected).split("\n");
        var i = 0;
        var indicator = "";
        if (operator === "strictEqual" && _typeof(actual) === "object" && _typeof(expected) === "object" && actual !== null && expected !== null) {
          operator = "strictEqualObject";
        }
        if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) {
          var inputLength = actualLines[0].length + expectedLines[0].length;
          if (inputLength <= kMaxShortLength) {
            if ((_typeof(actual) !== "object" || actual === null) && (_typeof(expected) !== "object" || expected === null) && (actual !== 0 || expected !== 0)) {
              return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n");
            }
          } else if (operator !== "strictEqualObject") {
            var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80;
            if (inputLength < maxLength) {
              while (actualLines[0][i] === expectedLines[0][i]) {
                i++;
              }
              if (i > 2) {
                indicator = "\n  ".concat(repeat(" ", i), "^");
                i = 0;
              }
            }
          }
        }
        var a = actualLines[actualLines.length - 1];
        var b = expectedLines[expectedLines.length - 1];
        while (a === b) {
          if (i++ < 2) {
            end = "\n  ".concat(a).concat(end);
          } else {
            other = a;
          }
          actualLines.pop();
          expectedLines.pop();
          if (actualLines.length === 0 || expectedLines.length === 0) break;
          a = actualLines[actualLines.length - 1];
          b = expectedLines[expectedLines.length - 1];
        }
        var maxLines = Math.max(actualLines.length, expectedLines.length);
        if (maxLines === 0) {
          var _actualLines = actualInspected.split("\n");
          if (_actualLines.length > 30) {
            _actualLines[26] = "".concat(blue, "...").concat(white);
            while (_actualLines.length > 27) {
              _actualLines.pop();
            }
          }
          return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join("\n"), "\n");
        }
        if (i > 3) {
          end = "\n".concat(blue, "...").concat(white).concat(end);
          skipped = true;
        }
        if (other !== "") {
          end = "\n  ".concat(other).concat(end);
          other = "";
        }
        var printedLines = 0;
        var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white);
        var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped");
        for (i = 0; i < maxLines; i++) {
          var cur = i - lastPos;
          if (actualLines.length < i + 1) {
            if (cur > 1 && i > 2) {
              if (cur > 4) {
                res += "\n".concat(blue, "...").concat(white);
                skipped = true;
              } else if (cur > 3) {
                res += "\n  ".concat(expectedLines[i - 2]);
                printedLines++;
              }
              res += "\n  ".concat(expectedLines[i - 1]);
              printedLines++;
            }
            lastPos = i;
            other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]);
            printedLines++;
          } else if (expectedLines.length < i + 1) {
            if (cur > 1 && i > 2) {
              if (cur > 4) {
                res += "\n".concat(blue, "...").concat(white);
                skipped = true;
              } else if (cur > 3) {
                res += "\n  ".concat(actualLines[i - 2]);
                printedLines++;
              }
              res += "\n  ".concat(actualLines[i - 1]);
              printedLines++;
            }
            lastPos = i;
            res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]);
            printedLines++;
          } else {
            var expectedLine = expectedLines[i];
            var actualLine = actualLines[i];
            var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ",") || actualLine.slice(0, -1) !== expectedLine);
            if (divergingLines && endsWith(expectedLine, ",") && expectedLine.slice(0, -1) === actualLine) {
              divergingLines = false;
              actualLine += ",";
            }
            if (divergingLines) {
              if (cur > 1 && i > 2) {
                if (cur > 4) {
                  res += "\n".concat(blue, "...").concat(white);
                  skipped = true;
                } else if (cur > 3) {
                  res += "\n  ".concat(actualLines[i - 2]);
                  printedLines++;
                }
                res += "\n  ".concat(actualLines[i - 1]);
                printedLines++;
              }
              lastPos = i;
              res += "\n".concat(green, "+").concat(white, " ").concat(actualLine);
              other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine);
              printedLines += 2;
            } else {
              res += other;
              other = "";
              if (cur === 1 || i === 0) {
                res += "\n  ".concat(actualLine);
                printedLines++;
              }
            }
          }
          if (printedLines > 20 && i < maxLines - 2) {
            return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white);
          }
        }
        return "".concat(msg).concat(skipped ? skippedMsg : "", "\n").concat(res).concat(other).concat(end).concat(indicator);
      }
      var AssertionError = /* @__PURE__ */ function(_Error, _inspect$custom) {
        _inherits(AssertionError2, _Error);
        var _super = _createSuper(AssertionError2);
        function AssertionError2(options) {
          var _this;
          _classCallCheck(this, AssertionError2);
          if (_typeof(options) !== "object" || options === null) {
            throw new ERR_INVALID_ARG_TYPE("options", "Object", options);
          }
          var message = options.message, operator = options.operator, stackStartFn = options.stackStartFn;
          var actual = options.actual, expected = options.expected;
          var limit = Error.stackTraceLimit;
          Error.stackTraceLimit = 0;
          if (message != null) {
            _this = _super.call(this, String(message));
          } else {
            if (process.stderr && process.stderr.isTTY) {
              if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) {
                blue = "\x1B[34m";
                green = "\x1B[32m";
                white = "\x1B[39m";
                red = "\x1B[31m";
              } else {
                blue = "";
                green = "";
                white = "";
                red = "";
              }
            }
            if (_typeof(actual) === "object" && actual !== null && _typeof(expected) === "object" && expected !== null && "stack" in actual && actual instanceof Error && "stack" in expected && expected instanceof Error) {
              actual = copyError(actual);
              expected = copyError(expected);
            }
            if (operator === "deepStrictEqual" || operator === "strictEqual") {
              _this = _super.call(this, createErrDiff(actual, expected, operator));
            } else if (operator === "notDeepStrictEqual" || operator === "notStrictEqual") {
              var base = kReadableOperator[operator];
              var res = inspectValue(actual).split("\n");
              if (operator === "notStrictEqual" && _typeof(actual) === "object" && actual !== null) {
                base = kReadableOperator.notStrictEqualObject;
              }
              if (res.length > 30) {
                res[26] = "".concat(blue, "...").concat(white);
                while (res.length > 27) {
                  res.pop();
                }
              }
              if (res.length === 1) {
                _this = _super.call(this, "".concat(base, " ").concat(res[0]));
              } else {
                _this = _super.call(this, "".concat(base, "\n\n").concat(res.join("\n"), "\n"));
              }
            } else {
              var _res = inspectValue(actual);
              var other = "";
              var knownOperators = kReadableOperator[operator];
              if (operator === "notDeepEqual" || operator === "notEqual") {
                _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res);
                if (_res.length > 1024) {
                  _res = "".concat(_res.slice(0, 1021), "...");
                }
              } else {
                other = "".concat(inspectValue(expected));
                if (_res.length > 512) {
                  _res = "".concat(_res.slice(0, 509), "...");
                }
                if (other.length > 512) {
                  other = "".concat(other.slice(0, 509), "...");
                }
                if (operator === "deepEqual" || operator === "equal") {
                  _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n");
                } else {
                  other = " ".concat(operator, " ").concat(other);
                }
              }
              _this = _super.call(this, "".concat(_res).concat(other));
            }
          }
          Error.stackTraceLimit = limit;
          _this.generatedMessage = !message;
          Object.defineProperty(_assertThisInitialized(_this), "name", {
            value: "AssertionError [ERR_ASSERTION]",
            enumerable: false,
            writable: true,
            configurable: true
          });
          _this.code = "ERR_ASSERTION";
          _this.actual = actual;
          _this.expected = expected;
          _this.operator = operator;
          if (Error.captureStackTrace) {
            Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn);
          }
          _this.stack;
          _this.name = "AssertionError";
          return _possibleConstructorReturn(_this);
        }
        _createClass(AssertionError2, [{
          key: "toString",
          value: function toString() {
            return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message);
          }
        }, {
          key: _inspect$custom,
          value: function value(recurseTimes, ctx) {
            return inspect(this, _objectSpread(_objectSpread({}, ctx), {}, {
              customInspect: false,
              depth: 0
            }));
          }
        }]);
        return AssertionError2;
      }(/* @__PURE__ */ _wrapNativeSuper(Error), inspect.custom);
      module.exports = AssertionError;
    }
  });

  // node_modules/object-keys/isArguments.js
  var require_isArguments = __commonJS({
    "node_modules/object-keys/isArguments.js"(exports, module) {
      "use strict";
      var toStr = Object.prototype.toString;
      module.exports = function isArguments(value) {
        var str = toStr.call(value);
        var isArgs = str === "[object Arguments]";
        if (!isArgs) {
          isArgs = str !== "[object Array]" && value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && toStr.call(value.callee) === "[object Function]";
        }
        return isArgs;
      };
    }
  });

  // node_modules/object-keys/implementation.js
  var require_implementation2 = __commonJS({
    "node_modules/object-keys/implementation.js"(exports, module) {
      "use strict";
      var keysShim;
      if (!Object.keys) {
        has = Object.prototype.hasOwnProperty;
        toStr = Object.prototype.toString;
        isArgs = require_isArguments();
        isEnumerable = Object.prototype.propertyIsEnumerable;
        hasDontEnumBug = !isEnumerable.call({ toString: null }, "toString");
        hasProtoEnumBug = isEnumerable.call(function() {
        }, "prototype");
        dontEnums = [
          "toString",
          "toLocaleString",
          "valueOf",
          "hasOwnProperty",
          "isPrototypeOf",
          "propertyIsEnumerable",
          "constructor"
        ];
        equalsConstructorPrototype = function(o) {
          var ctor = o.constructor;
          return ctor && ctor.prototype === o;
        };
        excludedKeys = {
          $applicationCache: true,
          $console: true,
          $external: true,
          $frame: true,
          $frameElement: true,
          $frames: true,
          $innerHeight: true,
          $innerWidth: true,
          $onmozfullscreenchange: true,
          $onmozfullscreenerror: true,
          $outerHeight: true,
          $outerWidth: true,
          $pageXOffset: true,
          $pageYOffset: true,
          $parent: true,
          $scrollLeft: true,
          $scrollTop: true,
          $scrollX: true,
          $scrollY: true,
          $self: true,
          $webkitIndexedDB: true,
          $webkitStorageInfo: true,
          $window: true
        };
        hasAutomationEqualityBug = function() {
          if (typeof window === "undefined") {
            return false;
          }
          for (var k in window) {
            try {
              if (!excludedKeys["$" + k] && has.call(window, k) && window[k] !== null && typeof window[k] === "object") {
                try {
                  equalsConstructorPrototype(window[k]);
                } catch (e) {
                  return true;
                }
              }
            } catch (e) {
              return true;
            }
          }
          return false;
        }();
        equalsConstructorPrototypeIfNotBuggy = function(o) {
          if (typeof window === "undefined" || !hasAutomationEqualityBug) {
            return equalsConstructorPrototype(o);
          }
          try {
            return equalsConstructorPrototype(o);
          } catch (e) {
            return false;
          }
        };
        keysShim = function keys(object) {
          var isObject = object !== null && typeof object === "object";
          var isFunction = toStr.call(object) === "[object Function]";
          var isArguments = isArgs(object);
          var isString = isObject && toStr.call(object) === "[object String]";
          var theKeys = [];
          if (!isObject && !isFunction && !isArguments) {
            throw new TypeError("Object.keys called on a non-object");
          }
          var skipProto = hasProtoEnumBug && isFunction;
          if (isString && object.length > 0 && !has.call(object, 0)) {
            for (var i = 0; i < object.length; ++i) {
              theKeys.push(String(i));
            }
          }
          if (isArguments && object.length > 0) {
            for (var j = 0; j < object.length; ++j) {
              theKeys.push(String(j));
            }
          } else {
            for (var name2 in object) {
              if (!(skipProto && name2 === "prototype") && has.call(object, name2)) {
                theKeys.push(String(name2));
              }
            }
          }
          if (hasDontEnumBug) {
            var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
            for (var k = 0; k < dontEnums.length; ++k) {
              if (!(skipConstructor && dontEnums[k] === "constructor") && has.call(object, dontEnums[k])) {
                theKeys.push(dontEnums[k]);
              }
            }
          }
          return theKeys;
        };
      }
      var has;
      var toStr;
      var isArgs;
      var isEnumerable;
      var hasDontEnumBug;
      var hasProtoEnumBug;
      var dontEnums;
      var equalsConstructorPrototype;
      var excludedKeys;
      var hasAutomationEqualityBug;
      var equalsConstructorPrototypeIfNotBuggy;
      module.exports = keysShim;
    }
  });

  // node_modules/object-keys/index.js
  var require_object_keys = __commonJS({
    "node_modules/object-keys/index.js"(exports, module) {
      "use strict";
      var slice = Array.prototype.slice;
      var isArgs = require_isArguments();
      var origKeys = Object.keys;
      var keysShim = origKeys ? function keys(o) {
        return origKeys(o);
      } : require_implementation2();
      var originalKeys = Object.keys;
      keysShim.shim = function shimObjectKeys() {
        if (Object.keys) {
          var keysWorksWithArguments = function() {
            var args = Object.keys(arguments);
            return args && args.length === arguments.length;
          }(1, 2);
          if (!keysWorksWithArguments) {
            Object.keys = function keys(object) {
              if (isArgs(object)) {
                return originalKeys(slice.call(object));
              }
              return originalKeys(object);
            };
          }
        } else {
          Object.keys = keysShim;
        }
        return Object.keys || keysShim;
      };
      module.exports = keysShim;
    }
  });

  // node_modules/object.assign/implementation.js
  var require_implementation3 = __commonJS({
    "node_modules/object.assign/implementation.js"(exports, module) {
      "use strict";
      var objectKeys = require_object_keys();
      var hasSymbols = require_shams()();
      var callBound = require_callBound();
      var toObject = Object;
      var $push = callBound("Array.prototype.push");
      var $propIsEnumerable = callBound("Object.prototype.propertyIsEnumerable");
      var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null;
      module.exports = function assign(target, source1) {
        if (target == null) {
          throw new TypeError("target must be an object");
        }
        var to = toObject(target);
        if (arguments.length === 1) {
          return to;
        }
        for (var s = 1; s < arguments.length; ++s) {
          var from = toObject(arguments[s]);
          var keys = objectKeys(from);
          var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols);
          if (getSymbols) {
            var syms = getSymbols(from);
            for (var j = 0; j < syms.length; ++j) {
              var key = syms[j];
              if ($propIsEnumerable(from, key)) {
                $push(keys, key);
              }
            }
          }
          for (var i = 0; i < keys.length; ++i) {
            var nextKey = keys[i];
            if ($propIsEnumerable(from, nextKey)) {
              var propValue = from[nextKey];
              to[nextKey] = propValue;
            }
          }
        }
        return to;
      };
    }
  });

  // node_modules/object.assign/polyfill.js
  var require_polyfill = __commonJS({
    "node_modules/object.assign/polyfill.js"(exports, module) {
      "use strict";
      var implementation = require_implementation3();
      var lacksProperEnumerationOrder = function() {
        if (!Object.assign) {
          return false;
        }
        var str = "abcdefghijklmnopqrst";
        var letters = str.split("");
        var map = {};
        for (var i = 0; i < letters.length; ++i) {
          map[letters[i]] = letters[i];
        }
        var obj = Object.assign({}, map);
        var actual = "";
        for (var k in obj) {
          actual += k;
        }
        return str !== actual;
      };
      var assignHasPendingExceptions = function() {
        if (!Object.assign || !Object.preventExtensions) {
          return false;
        }
        var thrower = Object.preventExtensions({ 1: 2 });
        try {
          Object.assign(thrower, "xy");
        } catch (e) {
          return thrower[1] === "y";
        }
        return false;
      };
      module.exports = function getPolyfill() {
        if (!Object.assign) {
          return implementation;
        }
        if (lacksProperEnumerationOrder()) {
          return implementation;
        }
        if (assignHasPendingExceptions()) {
          return implementation;
        }
        return Object.assign;
      };
    }
  });

  // node_modules/object-is/implementation.js
  var require_implementation4 = __commonJS({
    "node_modules/object-is/implementation.js"(exports, module) {
      "use strict";
      var numberIsNaN = function(value) {
        return value !== value;
      };
      module.exports = function is(a, b) {
        if (a === 0 && b === 0) {
          return 1 / a === 1 / b;
        }
        if (a === b) {
          return true;
        }
        if (numberIsNaN(a) && numberIsNaN(b)) {
          return true;
        }
        return false;
      };
    }
  });

  // node_modules/object-is/polyfill.js
  var require_polyfill2 = __commonJS({
    "node_modules/object-is/polyfill.js"(exports, module) {
      "use strict";
      var implementation = require_implementation4();
      module.exports = function getPolyfill() {
        return typeof Object.is === "function" ? Object.is : implementation;
      };
    }
  });

  // node_modules/define-properties/index.js
  var require_define_properties = __commonJS({
    "node_modules/define-properties/index.js"(exports, module) {
      "use strict";
      var keys = require_object_keys();
      var hasSymbols = typeof Symbol === "function" && typeof Symbol("foo") === "symbol";
      var toStr = Object.prototype.toString;
      var concat = Array.prototype.concat;
      var origDefineProperty = Object.defineProperty;
      var isFunction = function(fn) {
        return typeof fn === "function" && toStr.call(fn) === "[object Function]";
      };
      var hasPropertyDescriptors = require_has_property_descriptors()();
      var supportsDescriptors = origDefineProperty && hasPropertyDescriptors;
      var defineProperty = function(object, name2, value, predicate) {
        if (name2 in object) {
          if (predicate === true) {
            if (object[name2] === value) {
              return;
            }
          } else if (!isFunction(predicate) || !predicate()) {
            return;
          }
        }
        if (supportsDescriptors) {
          origDefineProperty(object, name2, {
            configurable: true,
            enumerable: false,
            value,
            writable: true
          });
        } else {
          object[name2] = value;
        }
      };
      var defineProperties = function(object, map) {
        var predicates = arguments.length > 2 ? arguments[2] : {};
        var props = keys(map);
        if (hasSymbols) {
          props = concat.call(props, Object.getOwnPropertySymbols(map));
        }
        for (var i = 0; i < props.length; i += 1) {
          defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
        }
      };
      defineProperties.supportsDescriptors = !!supportsDescriptors;
      module.exports = defineProperties;
    }
  });

  // node_modules/object-is/shim.js
  var require_shim = __commonJS({
    "node_modules/object-is/shim.js"(exports, module) {
      "use strict";
      var getPolyfill = require_polyfill2();
      var define2 = require_define_properties();
      module.exports = function shimObjectIs() {
        var polyfill = getPolyfill();
        define2(Object, { is: polyfill }, {
          is: function testObjectIs() {
            return Object.is !== polyfill;
          }
        });
        return polyfill;
      };
    }
  });

  // node_modules/object-is/index.js
  var require_object_is = __commonJS({
    "node_modules/object-is/index.js"(exports, module) {
      "use strict";
      var define2 = require_define_properties();
      var callBind = require_call_bind();
      var implementation = require_implementation4();
      var getPolyfill = require_polyfill2();
      var shim = require_shim();
      var polyfill = callBind(getPolyfill(), Object);
      define2(polyfill, {
        getPolyfill,
        implementation,
        shim
      });
      module.exports = polyfill;
    }
  });

  // node_modules/is-nan/implementation.js
  var require_implementation5 = __commonJS({
    "node_modules/is-nan/implementation.js"(exports, module) {
      "use strict";
      module.exports = function isNaN2(value) {
        return value !== value;
      };
    }
  });

  // node_modules/is-nan/polyfill.js
  var require_polyfill3 = __commonJS({
    "node_modules/is-nan/polyfill.js"(exports, module) {
      "use strict";
      var implementation = require_implementation5();
      module.exports = function getPolyfill() {
        if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN("a")) {
          return Number.isNaN;
        }
        return implementation;
      };
    }
  });

  // node_modules/is-nan/shim.js
  var require_shim2 = __commonJS({
    "node_modules/is-nan/shim.js"(exports, module) {
      "use strict";
      var define2 = require_define_properties();
      var getPolyfill = require_polyfill3();
      module.exports = function shimNumberIsNaN() {
        var polyfill = getPolyfill();
        define2(Number, { isNaN: polyfill }, {
          isNaN: function testIsNaN() {
            return Number.isNaN !== polyfill;
          }
        });
        return polyfill;
      };
    }
  });

  // node_modules/is-nan/index.js
  var require_is_nan = __commonJS({
    "node_modules/is-nan/index.js"(exports, module) {
      "use strict";
      var callBind = require_call_bind();
      var define2 = require_define_properties();
      var implementation = require_implementation5();
      var getPolyfill = require_polyfill3();
      var shim = require_shim2();
      var polyfill = callBind(getPolyfill(), Number);
      define2(polyfill, {
        getPolyfill,
        implementation,
        shim
      });
      module.exports = polyfill;
    }
  });

  // node_modules/assert/build/internal/util/comparisons.js
  var require_comparisons = __commonJS({
    "node_modules/assert/build/internal/util/comparisons.js"(exports, module) {
      "use strict";
      function _slicedToArray(arr, i) {
        return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
      }
      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 _unsupportedIterableToArray(o, minLen) {
        if (!o) return;
        if (typeof o === "string") return _arrayLikeToArray(o, minLen);
        var n = Object.prototype.toString.call(o).slice(8, -1);
        if (n === "Object" && o.constructor) n = o.constructor.name;
        if (n === "Map" || n === "Set") return Array.from(o);
        if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
      }
      function _arrayLikeToArray(arr, len) {
        if (len == null || len > arr.length) len = arr.length;
        for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
        return arr2;
      }
      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 = false;
            } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = true) ;
          } catch (r2) {
            o = true, n = r2;
          } finally {
            try {
              if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
            } finally {
              if (o) throw n;
            }
          }
          return a;
        }
      }
      function _arrayWithHoles(arr) {
        if (Array.isArray(arr)) return arr;
      }
      function _typeof(o) {
        "@babel/helpers - typeof";
        return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
          return typeof o2;
        } : function(o2) {
          return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
        }, _typeof(o);
      }
      var regexFlagsSupported = /a/g.flags !== void 0;
      var arrayFromSet = function arrayFromSet2(set) {
        var array = [];
        set.forEach(function(value) {
          return array.push(value);
        });
        return array;
      };
      var arrayFromMap = function arrayFromMap2(map) {
        var array = [];
        map.forEach(function(value, key) {
          return array.push([key, value]);
        });
        return array;
      };
      var objectIs = Object.is ? Object.is : require_object_is();
      var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function() {
        return [];
      };
      var numberIsNaN = Number.isNaN ? Number.isNaN : require_is_nan();
      function uncurryThis(f) {
        return f.call.bind(f);
      }
      var hasOwnProperty2 = uncurryThis(Object.prototype.hasOwnProperty);
      var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable);
      var objectToString = uncurryThis(Object.prototype.toString);
      var _require$types = require_util2().types;
      var isAnyArrayBuffer = _require$types.isAnyArrayBuffer;
      var isArrayBufferView = _require$types.isArrayBufferView;
      var isDate = _require$types.isDate;
      var isMap = _require$types.isMap;
      var isRegExp = _require$types.isRegExp;
      var isSet = _require$types.isSet;
      var isNativeError = _require$types.isNativeError;
      var isBoxedPrimitive = _require$types.isBoxedPrimitive;
      var isNumberObject = _require$types.isNumberObject;
      var isStringObject = _require$types.isStringObject;
      var isBooleanObject = _require$types.isBooleanObject;
      var isBigIntObject = _require$types.isBigIntObject;
      var isSymbolObject = _require$types.isSymbolObject;
      var isFloat32Array = _require$types.isFloat32Array;
      var isFloat64Array = _require$types.isFloat64Array;
      function isNonIndex(key) {
        if (key.length === 0 || key.length > 10) return true;
        for (var i = 0; i < key.length; i++) {
          var code = key.charCodeAt(i);
          if (code < 48 || code > 57) return true;
        }
        return key.length === 10 && key >= Math.pow(2, 32);
      }
      function getOwnNonIndexProperties(value) {
        return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value)));
      }
      function compare(a, b) {
        if (a === b) {
          return 0;
        }
        var x = a.length;
        var y = b.length;
        for (var i = 0, len = Math.min(x, y); i < len; ++i) {
          if (a[i] !== b[i]) {
            x = a[i];
            y = b[i];
            break;
          }
        }
        if (x < y) {
          return -1;
        }
        if (y < x) {
          return 1;
        }
        return 0;
      }
      var ONLY_ENUMERABLE = void 0;
      var kStrict = true;
      var kLoose = false;
      var kNoIterator = 0;
      var kIsArray = 1;
      var kIsSet = 2;
      var kIsMap = 3;
      function areSimilarRegExps(a, b) {
        return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b);
      }
      function areSimilarFloatArrays(a, b) {
        if (a.byteLength !== b.byteLength) {
          return false;
        }
        for (var offset = 0; offset < a.byteLength; offset++) {
          if (a[offset] !== b[offset]) {
            return false;
          }
        }
        return true;
      }
      function areSimilarTypedArrays(a, b) {
        if (a.byteLength !== b.byteLength) {
          return false;
        }
        return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0;
      }
      function areEqualArrayBuffers(buf1, buf2) {
        return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0;
      }
      function isEqualBoxedPrimitive(val1, val2) {
        if (isNumberObject(val1)) {
          return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2));
        }
        if (isStringObject(val1)) {
          return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2);
        }
        if (isBooleanObject(val1)) {
          return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2);
        }
        if (isBigIntObject(val1)) {
          return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2);
        }
        return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2);
      }
      function innerDeepEqual(val1, val2, strict, memos) {
        if (val1 === val2) {
          if (val1 !== 0) return true;
          return strict ? objectIs(val1, val2) : true;
        }
        if (strict) {
          if (_typeof(val1) !== "object") {
            return typeof val1 === "number" && numberIsNaN(val1) && numberIsNaN(val2);
          }
          if (_typeof(val2) !== "object" || val1 === null || val2 === null) {
            return false;
          }
          if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) {
            return false;
          }
        } else {
          if (val1 === null || _typeof(val1) !== "object") {
            if (val2 === null || _typeof(val2) !== "object") {
              return val1 == val2;
            }
            return false;
          }
          if (val2 === null || _typeof(val2) !== "object") {
            return false;
          }
        }
        var val1Tag = objectToString(val1);
        var val2Tag = objectToString(val2);
        if (val1Tag !== val2Tag) {
          return false;
        }
        if (Array.isArray(val1)) {
          if (val1.length !== val2.length) {
            return false;
          }
          var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);
          var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);
          if (keys1.length !== keys2.length) {
            return false;
          }
          return keyCheck(val1, val2, strict, memos, kIsArray, keys1);
        }
        if (val1Tag === "[object Object]") {
          if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) {
            return false;
          }
        }
        if (isDate(val1)) {
          if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) {
            return false;
          }
        } else if (isRegExp(val1)) {
          if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) {
            return false;
          }
        } else if (isNativeError(val1) || val1 instanceof Error) {
          if (val1.message !== val2.message || val1.name !== val2.name) {
            return false;
          }
        } else if (isArrayBufferView(val1)) {
          if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) {
            if (!areSimilarFloatArrays(val1, val2)) {
              return false;
            }
          } else if (!areSimilarTypedArrays(val1, val2)) {
            return false;
          }
          var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);
          var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);
          if (_keys.length !== _keys2.length) {
            return false;
          }
          return keyCheck(val1, val2, strict, memos, kNoIterator, _keys);
        } else if (isSet(val1)) {
          if (!isSet(val2) || val1.size !== val2.size) {
            return false;
          }
          return keyCheck(val1, val2, strict, memos, kIsSet);
        } else if (isMap(val1)) {
          if (!isMap(val2) || val1.size !== val2.size) {
            return false;
          }
          return keyCheck(val1, val2, strict, memos, kIsMap);
        } else if (isAnyArrayBuffer(val1)) {
          if (!areEqualArrayBuffers(val1, val2)) {
            return false;
          }
        } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) {
          return false;
        }
        return keyCheck(val1, val2, strict, memos, kNoIterator);
      }
      function getEnumerables(val, keys) {
        return keys.filter(function(k) {
          return propertyIsEnumerable(val, k);
        });
      }
      function keyCheck(val1, val2, strict, memos, iterationType, aKeys) {
        if (arguments.length === 5) {
          aKeys = Object.keys(val1);
          var bKeys = Object.keys(val2);
          if (aKeys.length !== bKeys.length) {
            return false;
          }
        }
        var i = 0;
        for (; i < aKeys.length; i++) {
          if (!hasOwnProperty2(val2, aKeys[i])) {
            return false;
          }
        }
        if (strict && arguments.length === 5) {
          var symbolKeysA = objectGetOwnPropertySymbols(val1);
          if (symbolKeysA.length !== 0) {
            var count = 0;
            for (i = 0; i < symbolKeysA.length; i++) {
              var key = symbolKeysA[i];
              if (propertyIsEnumerable(val1, key)) {
                if (!propertyIsEnumerable(val2, key)) {
                  return false;
                }
                aKeys.push(key);
                count++;
              } else if (propertyIsEnumerable(val2, key)) {
                return false;
              }
            }
            var symbolKeysB = objectGetOwnPropertySymbols(val2);
            if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) {
              return false;
            }
          } else {
            var _symbolKeysB = objectGetOwnPropertySymbols(val2);
            if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) {
              return false;
            }
          }
        }
        if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) {
          return true;
        }
        if (memos === void 0) {
          memos = {
            val1: /* @__PURE__ */ new Map(),
            val2: /* @__PURE__ */ new Map(),
            position: 0
          };
        } else {
          var val2MemoA = memos.val1.get(val1);
          if (val2MemoA !== void 0) {
            var val2MemoB = memos.val2.get(val2);
            if (val2MemoB !== void 0) {
              return val2MemoA === val2MemoB;
            }
          }
          memos.position++;
        }
        memos.val1.set(val1, memos.position);
        memos.val2.set(val2, memos.position);
        var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType);
        memos.val1.delete(val1);
        memos.val2.delete(val2);
        return areEq;
      }
      function setHasEqualElement(set, val1, strict, memo) {
        var setValues = arrayFromSet(set);
        for (var i = 0; i < setValues.length; i++) {
          var val2 = setValues[i];
          if (innerDeepEqual(val1, val2, strict, memo)) {
            set.delete(val2);
            return true;
          }
        }
        return false;
      }
      function findLooseMatchingPrimitives(prim) {
        switch (_typeof(prim)) {
          case "undefined":
            return null;
          case "object":
            return void 0;
          case "symbol":
            return false;
          case "string":
            prim = +prim;
          // Loose equal entries exist only if the string is possible to convert to
          // a regular number and not NaN.
          // Fall through
          case "number":
            if (numberIsNaN(prim)) {
              return false;
            }
        }
        return true;
      }
      function setMightHaveLoosePrim(a, b, prim) {
        var altValue = findLooseMatchingPrimitives(prim);
        if (altValue != null) return altValue;
        return b.has(altValue) && !a.has(altValue);
      }
      function mapMightHaveLoosePrim(a, b, prim, item, memo) {
        var altValue = findLooseMatchingPrimitives(prim);
        if (altValue != null) {
          return altValue;
        }
        var curB = b.get(altValue);
        if (curB === void 0 && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) {
          return false;
        }
        return !a.has(altValue) && innerDeepEqual(item, curB, false, memo);
      }
      function setEquiv(a, b, strict, memo) {
        var set = null;
        var aValues = arrayFromSet(a);
        for (var i = 0; i < aValues.length; i++) {
          var val = aValues[i];
          if (_typeof(val) === "object" && val !== null) {
            if (set === null) {
              set = /* @__PURE__ */ new Set();
            }
            set.add(val);
          } else if (!b.has(val)) {
            if (strict) return false;
            if (!setMightHaveLoosePrim(a, b, val)) {
              return false;
            }
            if (set === null) {
              set = /* @__PURE__ */ new Set();
            }
            set.add(val);
          }
        }
        if (set !== null) {
          var bValues = arrayFromSet(b);
          for (var _i = 0; _i < bValues.length; _i++) {
            var _val = bValues[_i];
            if (_typeof(_val) === "object" && _val !== null) {
              if (!setHasEqualElement(set, _val, strict, memo)) return false;
            } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) {
              return false;
            }
          }
          return set.size === 0;
        }
        return true;
      }
      function mapHasEqualEntry(set, map, key1, item1, strict, memo) {
        var setValues = arrayFromSet(set);
        for (var i = 0; i < setValues.length; i++) {
          var key2 = setValues[i];
          if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) {
            set.delete(key2);
            return true;
          }
        }
        return false;
      }
      function mapEquiv(a, b, strict, memo) {
        var set = null;
        var aEntries = arrayFromMap(a);
        for (var i = 0; i < aEntries.length; i++) {
          var _aEntries$i = _slicedToArray(aEntries[i], 2), key = _aEntries$i[0], item1 = _aEntries$i[1];
          if (_typeof(key) === "object" && key !== null) {
            if (set === null) {
              set = /* @__PURE__ */ new Set();
            }
            set.add(key);
          } else {
            var item2 = b.get(key);
            if (item2 === void 0 && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) {
              if (strict) return false;
              if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false;
              if (set === null) {
                set = /* @__PURE__ */ new Set();
              }
              set.add(key);
            }
          }
        }
        if (set !== null) {
          var bEntries = arrayFromMap(b);
          for (var _i2 = 0; _i2 < bEntries.length; _i2++) {
            var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), _key = _bEntries$_i[0], item = _bEntries$_i[1];
            if (_typeof(_key) === "object" && _key !== null) {
              if (!mapHasEqualEntry(set, a, _key, item, strict, memo)) return false;
            } else if (!strict && (!a.has(_key) || !innerDeepEqual(a.get(_key), item, false, memo)) && !mapHasEqualEntry(set, a, _key, item, false, memo)) {
              return false;
            }
          }
          return set.size === 0;
        }
        return true;
      }
      function objEquiv(a, b, strict, keys, memos, iterationType) {
        var i = 0;
        if (iterationType === kIsSet) {
          if (!setEquiv(a, b, strict, memos)) {
            return false;
          }
        } else if (iterationType === kIsMap) {
          if (!mapEquiv(a, b, strict, memos)) {
            return false;
          }
        } else if (iterationType === kIsArray) {
          for (; i < a.length; i++) {
            if (hasOwnProperty2(a, i)) {
              if (!hasOwnProperty2(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) {
                return false;
              }
            } else if (hasOwnProperty2(b, i)) {
              return false;
            } else {
              var keysA = Object.keys(a);
              for (; i < keysA.length; i++) {
                var key = keysA[i];
                if (!hasOwnProperty2(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) {
                  return false;
                }
              }
              if (keysA.length !== Object.keys(b).length) {
                return false;
              }
              return true;
            }
          }
        }
        for (i = 0; i < keys.length; i++) {
          var _key2 = keys[i];
          if (!innerDeepEqual(a[_key2], b[_key2], strict, memos)) {
            return false;
          }
        }
        return true;
      }
      function isDeepEqual(val1, val2) {
        return innerDeepEqual(val1, val2, kLoose);
      }
      function isDeepStrictEqual(val1, val2) {
        return innerDeepEqual(val1, val2, kStrict);
      }
      module.exports = {
        isDeepEqual,
        isDeepStrictEqual
      };
    }
  });

  // node_modules/assert/build/assert.js
  var require_assert = __commonJS({
    "node_modules/assert/build/assert.js"(exports, module) {
      "use strict";
      function _typeof(o) {
        "@babel/helpers - typeof";
        return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
          return typeof o2;
        } : function(o2) {
          return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
        }, _typeof(o);
      }
      function _defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
        }
      }
      function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        Object.defineProperty(Constructor, "prototype", { writable: false });
        return Constructor;
      }
      function _toPropertyKey(arg) {
        var key = _toPrimitive(arg, "string");
        return _typeof(key) === "symbol" ? key : String(key);
      }
      function _toPrimitive(input, hint) {
        if (_typeof(input) !== "object" || input === null) return input;
        var prim = input[Symbol.toPrimitive];
        if (prim !== void 0) {
          var res = prim.call(input, hint || "default");
          if (_typeof(res) !== "object") return res;
          throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return (hint === "string" ? String : Number)(input);
      }
      function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
          throw new TypeError("Cannot call a class as a function");
        }
      }
      var _require = require_errors();
      var _require$codes = _require.codes;
      var ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT;
      var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE;
      var ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE;
      var ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE;
      var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS;
      var AssertionError = require_assertion_error();
      var _require2 = require_util2();
      var inspect = _require2.inspect;
      var _require$types = require_util2().types;
      var isPromise = _require$types.isPromise;
      var isRegExp = _require$types.isRegExp;
      var objectAssign = require_polyfill()();
      var objectIs = require_polyfill2()();
      var RegExpPrototypeTest = require_callBound()("RegExp.prototype.test");
      var isDeepEqual;
      var isDeepStrictEqual;
      function lazyLoadComparison() {
        var comparison = require_comparisons();
        isDeepEqual = comparison.isDeepEqual;
        isDeepStrictEqual = comparison.isDeepStrictEqual;
      }
      var warned = false;
      var assert = module.exports = ok;
      var NO_EXCEPTION_SENTINEL = {};
      function innerFail(obj) {
        if (obj.message instanceof Error) throw obj.message;
        throw new AssertionError(obj);
      }
      function fail(actual, expected, message, operator, stackStartFn) {
        var argsLen = arguments.length;
        var internalMessage;
        if (argsLen === 0) {
          internalMessage = "Failed";
        } else if (argsLen === 1) {
          message = actual;
          actual = void 0;
        } else {
          if (warned === false) {
            warned = true;
            var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console);
            warn("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.", "DeprecationWarning", "DEP0094");
          }
          if (argsLen === 2) operator = "!=";
        }
        if (message instanceof Error) throw message;
        var errArgs = {
          actual,
          expected,
          operator: operator === void 0 ? "fail" : operator,
          stackStartFn: stackStartFn || fail
        };
        if (message !== void 0) {
          errArgs.message = message;
        }
        var err = new AssertionError(errArgs);
        if (internalMessage) {
          err.message = internalMessage;
          err.generatedMessage = true;
        }
        throw err;
      }
      assert.fail = fail;
      assert.AssertionError = AssertionError;
      function innerOk(fn, argLen, value, message) {
        if (!value) {
          var generatedMessage = false;
          if (argLen === 0) {
            generatedMessage = true;
            message = "No value argument passed to `assert.ok()`";
          } else if (message instanceof Error) {
            throw message;
          }
          var err = new AssertionError({
            actual: value,
            expected: true,
            message,
            operator: "==",
            stackStartFn: fn
          });
          err.generatedMessage = generatedMessage;
          throw err;
        }
      }
      function ok() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        innerOk.apply(void 0, [ok, args.length].concat(args));
      }
      assert.ok = ok;
      assert.equal = function equal(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (actual != expected) {
          innerFail({
            actual,
            expected,
            message,
            operator: "==",
            stackStartFn: equal
          });
        }
      };
      assert.notEqual = function notEqual(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (actual == expected) {
          innerFail({
            actual,
            expected,
            message,
            operator: "!=",
            stackStartFn: notEqual
          });
        }
      };
      assert.deepEqual = function deepEqual(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (isDeepEqual === void 0) lazyLoadComparison();
        if (!isDeepEqual(actual, expected)) {
          innerFail({
            actual,
            expected,
            message,
            operator: "deepEqual",
            stackStartFn: deepEqual
          });
        }
      };
      assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (isDeepEqual === void 0) lazyLoadComparison();
        if (isDeepEqual(actual, expected)) {
          innerFail({
            actual,
            expected,
            message,
            operator: "notDeepEqual",
            stackStartFn: notDeepEqual
          });
        }
      };
      assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (isDeepEqual === void 0) lazyLoadComparison();
        if (!isDeepStrictEqual(actual, expected)) {
          innerFail({
            actual,
            expected,
            message,
            operator: "deepStrictEqual",
            stackStartFn: deepStrictEqual
          });
        }
      };
      assert.notDeepStrictEqual = notDeepStrictEqual;
      function notDeepStrictEqual(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (isDeepEqual === void 0) lazyLoadComparison();
        if (isDeepStrictEqual(actual, expected)) {
          innerFail({
            actual,
            expected,
            message,
            operator: "notDeepStrictEqual",
            stackStartFn: notDeepStrictEqual
          });
        }
      }
      assert.strictEqual = function strictEqual(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (!objectIs(actual, expected)) {
          innerFail({
            actual,
            expected,
            message,
            operator: "strictEqual",
            stackStartFn: strictEqual
          });
        }
      };
      assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
        if (arguments.length < 2) {
          throw new ERR_MISSING_ARGS("actual", "expected");
        }
        if (objectIs(actual, expected)) {
          innerFail({
            actual,
            expected,
            message,
            operator: "notStrictEqual",
            stackStartFn: notStrictEqual
          });
        }
      };
      var Comparison = /* @__PURE__ */ _createClass(function Comparison2(obj, keys, actual) {
        var _this = this;
        _classCallCheck(this, Comparison2);
        keys.forEach(function(key) {
          if (key in obj) {
            if (actual !== void 0 && typeof actual[key] === "string" && isRegExp(obj[key]) && RegExpPrototypeTest(obj[key], actual[key])) {
              _this[key] = actual[key];
            } else {
              _this[key] = obj[key];
            }
          }
        });
      });
      function compareExceptionKey(actual, expected, key, message, keys, fn) {
        if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) {
          if (!message) {
            var a = new Comparison(actual, keys);
            var b = new Comparison(expected, keys, actual);
            var err = new AssertionError({
              actual: a,
              expected: b,
              operator: "deepStrictEqual",
              stackStartFn: fn
            });
            err.actual = actual;
            err.expected = expected;
            err.operator = fn.name;
            throw err;
          }
          innerFail({
            actual,
            expected,
            message,
            operator: fn.name,
            stackStartFn: fn
          });
        }
      }
      function expectedException(actual, expected, msg, fn) {
        if (typeof expected !== "function") {
          if (isRegExp(expected)) return RegExpPrototypeTest(expected, actual);
          if (arguments.length === 2) {
            throw new ERR_INVALID_ARG_TYPE("expected", ["Function", "RegExp"], expected);
          }
          if (_typeof(actual) !== "object" || actual === null) {
            var err = new AssertionError({
              actual,
              expected,
              message: msg,
              operator: "deepStrictEqual",
              stackStartFn: fn
            });
            err.operator = fn.name;
            throw err;
          }
          var keys = Object.keys(expected);
          if (expected instanceof Error) {
            keys.push("name", "message");
          } else if (keys.length === 0) {
            throw new ERR_INVALID_ARG_VALUE("error", expected, "may not be an empty object");
          }
          if (isDeepEqual === void 0) lazyLoadComparison();
          keys.forEach(function(key) {
            if (typeof actual[key] === "string" && isRegExp(expected[key]) && RegExpPrototypeTest(expected[key], actual[key])) {
              return;
            }
            compareExceptionKey(actual, expected, key, msg, keys, fn);
          });
          return true;
        }
        if (expected.prototype !== void 0 && actual instanceof expected) {
          return true;
        }
        if (Error.isPrototypeOf(expected)) {
          return false;
        }
        return expected.call({}, actual) === true;
      }
      function getActual(fn) {
        if (typeof fn !== "function") {
          throw new ERR_INVALID_ARG_TYPE("fn", "Function", fn);
        }
        try {
          fn();
        } catch (e) {
          return e;
        }
        return NO_EXCEPTION_SENTINEL;
      }
      function checkIsPromise(obj) {
        return isPromise(obj) || obj !== null && _typeof(obj) === "object" && typeof obj.then === "function" && typeof obj.catch === "function";
      }
      function waitForActual(promiseFn) {
        return Promise.resolve().then(function() {
          var resultPromise;
          if (typeof promiseFn === "function") {
            resultPromise = promiseFn();
            if (!checkIsPromise(resultPromise)) {
              throw new ERR_INVALID_RETURN_VALUE("instance of Promise", "promiseFn", resultPromise);
            }
          } else if (checkIsPromise(promiseFn)) {
            resultPromise = promiseFn;
          } else {
            throw new ERR_INVALID_ARG_TYPE("promiseFn", ["Function", "Promise"], promiseFn);
          }
          return Promise.resolve().then(function() {
            return resultPromise;
          }).then(function() {
            return NO_EXCEPTION_SENTINEL;
          }).catch(function(e) {
            return e;
          });
        });
      }
      function expectsError(stackStartFn, actual, error, message) {
        if (typeof error === "string") {
          if (arguments.length === 4) {
            throw new ERR_INVALID_ARG_TYPE("error", ["Object", "Error", "Function", "RegExp"], error);
          }
          if (_typeof(actual) === "object" && actual !== null) {
            if (actual.message === error) {
              throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error message "'.concat(actual.message, '" is identical to the message.'));
            }
          } else if (actual === error) {
            throw new ERR_AMBIGUOUS_ARGUMENT("error/message", 'The error "'.concat(actual, '" is identical to the message.'));
          }
          message = error;
          error = void 0;
        } else if (error != null && _typeof(error) !== "object" && typeof error !== "function") {
          throw new ERR_INVALID_ARG_TYPE("error", ["Object", "Error", "Function", "RegExp"], error);
        }
        if (actual === NO_EXCEPTION_SENTINEL) {
          var details = "";
          if (error && error.name) {
            details += " (".concat(error.name, ")");
          }
          details += message ? ": ".concat(message) : ".";
          var fnType = stackStartFn.name === "rejects" ? "rejection" : "exception";
          innerFail({
            actual: void 0,
            expected: error,
            operator: stackStartFn.name,
            message: "Missing expected ".concat(fnType).concat(details),
            stackStartFn
          });
        }
        if (error && !expectedException(actual, error, message, stackStartFn)) {
          throw actual;
        }
      }
      function expectsNoError(stackStartFn, actual, error, message) {
        if (actual === NO_EXCEPTION_SENTINEL) return;
        if (typeof error === "string") {
          message = error;
          error = void 0;
        }
        if (!error || expectedException(actual, error)) {
          var details = message ? ": ".concat(message) : ".";
          var fnType = stackStartFn.name === "doesNotReject" ? "rejection" : "exception";
          innerFail({
            actual,
            expected: error,
            operator: stackStartFn.name,
            message: "Got unwanted ".concat(fnType).concat(details, "\n") + 'Actual message: "'.concat(actual && actual.message, '"'),
            stackStartFn
          });
        }
        throw actual;
      }
      assert.throws = function throws(promiseFn) {
        for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          args[_key2 - 1] = arguments[_key2];
        }
        expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args));
      };
      assert.rejects = function rejects(promiseFn) {
        for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
          args[_key3 - 1] = arguments[_key3];
        }
        return waitForActual(promiseFn).then(function(result) {
          return expectsError.apply(void 0, [rejects, result].concat(args));
        });
      };
      assert.doesNotThrow = function doesNotThrow(fn) {
        for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
          args[_key4 - 1] = arguments[_key4];
        }
        expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args));
      };
      assert.doesNotReject = function doesNotReject(fn) {
        for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
          args[_key5 - 1] = arguments[_key5];
        }
        return waitForActual(fn).then(function(result) {
          return expectsNoError.apply(void 0, [doesNotReject, result].concat(args));
        });
      };
      assert.ifError = function ifError(err) {
        if (err !== null && err !== void 0) {
          var message = "ifError got unwanted exception: ";
          if (_typeof(err) === "object" && typeof err.message === "string") {
            if (err.message.length === 0 && err.constructor) {
              message += err.constructor.name;
            } else {
              message += err.message;
            }
          } else {
            message += inspect(err);
          }
          var newErr = new AssertionError({
            actual: err,
            expected: null,
            operator: "ifError",
            message,
            stackStartFn: ifError
          });
          var origStack = err.stack;
          if (typeof origStack === "string") {
            var tmp2 = origStack.split("\n");
            tmp2.shift();
            var tmp1 = newErr.stack.split("\n");
            for (var i = 0; i < tmp2.length; i++) {
              var pos = tmp1.indexOf(tmp2[i]);
              if (pos !== -1) {
                tmp1 = tmp1.slice(0, pos);
                break;
              }
            }
            newErr.stack = "".concat(tmp1.join("\n"), "\n").concat(tmp2.join("\n"));
          }
          throw newErr;
        }
      };
      function internalMatch(string, regexp, message, fn, fnName) {
        if (!isRegExp(regexp)) {
          throw new ERR_INVALID_ARG_TYPE("regexp", "RegExp", regexp);
        }
        var match = fnName === "match";
        if (typeof string !== "string" || RegExpPrototypeTest(regexp, string) !== match) {
          if (message instanceof Error) {
            throw message;
          }
          var generatedMessage = !message;
          message = message || (typeof string !== "string" ? 'The "string" argument must be of type string. Received type ' + "".concat(_typeof(string), " (").concat(inspect(string), ")") : (match ? "The input did not match the regular expression " : "The input was expected to not match the regular expression ") + "".concat(inspect(regexp), ". Input:\n\n").concat(inspect(string), "\n"));
          var err = new AssertionError({
            actual: string,
            expected: regexp,
            message,
            operator: fnName,
            stackStartFn: fn
          });
          err.generatedMessage = generatedMessage;
          throw err;
        }
      }
      assert.match = function match(string, regexp, message) {
        internalMatch(string, regexp, message, match, "match");
      };
      assert.doesNotMatch = function doesNotMatch(string, regexp, message) {
        internalMatch(string, regexp, message, doesNotMatch, "doesNotMatch");
      };
      function strict() {
        for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
          args[_key6] = arguments[_key6];
        }
        innerOk.apply(void 0, [strict, args.length].concat(args));
      }
      assert.strict = objectAssign(strict, assert, {
        equal: assert.strictEqual,
        deepEqual: assert.deepStrictEqual,
        notEqual: assert.notStrictEqual,
        notDeepEqual: assert.notDeepStrictEqual
      });
      assert.strict.strict = assert.strict;
    }
  });

  // node_modules/stream-parser/node_modules/ms/index.js
  var require_ms = __commonJS({
    "node_modules/stream-parser/node_modules/ms/index.js"(exports, module) {
      var s = 1e3;
      var m = s * 60;
      var h = m * 60;
      var d = h * 24;
      var y = d * 365.25;
      module.exports = function(val, options) {
        options = options || {};
        var type = typeof val;
        if (type === "string" && val.length > 0) {
          return parse2(val);
        } else if (type === "number" && isNaN(val) === false) {
          return options.long ? fmtLong(val) : fmtShort(val);
        }
        throw new Error(
          "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
        );
      };
      function parse2(str) {
        str = String(str);
        if (str.length > 100) {
          return;
        }
        var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
          str
        );
        if (!match) {
          return;
        }
        var n = parseFloat(match[1]);
        var type = (match[2] || "ms").toLowerCase();
        switch (type) {
          case "years":
          case "year":
          case "yrs":
          case "yr":
          case "y":
            return n * y;
          case "days":
          case "day":
          case "d":
            return n * d;
          case "hours":
          case "hour":
          case "hrs":
          case "hr":
          case "h":
            return n * h;
          case "minutes":
          case "minute":
          case "mins":
          case "min":
          case "m":
            return n * m;
          case "seconds":
          case "second":
          case "secs":
          case "sec":
          case "s":
            return n * s;
          case "milliseconds":
          case "millisecond":
          case "msecs":
          case "msec":
          case "ms":
            return n;
          default:
            return void 0;
        }
      }
      function fmtShort(ms) {
        if (ms >= d) {
          return Math.round(ms / d) + "d";
        }
        if (ms >= h) {
          return Math.round(ms / h) + "h";
        }
        if (ms >= m) {
          return Math.round(ms / m) + "m";
        }
        if (ms >= s) {
          return Math.round(ms / s) + "s";
        }
        return ms + "ms";
      }
      function fmtLong(ms) {
        return plural(ms, d, "day") || plural(ms, h, "hour") || plural(ms, m, "minute") || plural(ms, s, "second") || ms + " ms";
      }
      function plural(ms, n, name2) {
        if (ms < n) {
          return;
        }
        if (ms < n * 1.5) {
          return Math.floor(ms / n) + " " + name2;
        }
        return Math.ceil(ms / n) + " " + name2 + "s";
      }
    }
  });

  // node_modules/stream-parser/node_modules/debug/src/debug.js
  var require_debug = __commonJS({
    "node_modules/stream-parser/node_modules/debug/src/debug.js"(exports, module) {
      exports = module.exports = createDebug.debug = createDebug["default"] = createDebug;
      exports.coerce = coerce;
      exports.disable = disable;
      exports.enable = enable;
      exports.enabled = enabled;
      exports.humanize = require_ms();
      exports.names = [];
      exports.skips = [];
      exports.formatters = {};
      var prevTime;
      function selectColor(namespace) {
        var hash = 0, i;
        for (i in namespace) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i);
          hash |= 0;
        }
        return exports.colors[Math.abs(hash) % exports.colors.length];
      }
      function createDebug(namespace) {
        function debug() {
          if (!debug.enabled) return;
          var self2 = debug;
          var curr = +/* @__PURE__ */ new Date();
          var ms = curr - (prevTime || curr);
          self2.diff = ms;
          self2.prev = prevTime;
          self2.curr = curr;
          prevTime = curr;
          var args = new Array(arguments.length);
          for (var i = 0; i < args.length; i++) {
            args[i] = arguments[i];
          }
          args[0] = exports.coerce(args[0]);
          if ("string" !== typeof args[0]) {
            args.unshift("%O");
          }
          var index = 0;
          args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
            if (match === "%%") return match;
            index++;
            var formatter = exports.formatters[format];
            if ("function" === typeof formatter) {
              var val = args[index];
              match = formatter.call(self2, val);
              args.splice(index, 1);
              index--;
            }
            return match;
          });
          exports.formatArgs.call(self2, args);
          var logFn = debug.log || exports.log || console.log.bind(console);
          logFn.apply(self2, args);
        }
        debug.namespace = namespace;
        debug.enabled = exports.enabled(namespace);
        debug.useColors = exports.useColors();
        debug.color = selectColor(namespace);
        if ("function" === typeof exports.init) {
          exports.init(debug);
        }
        return debug;
      }
      function enable(namespaces) {
        exports.save(namespaces);
        exports.names = [];
        exports.skips = [];
        var split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
        var len = split.length;
        for (var i = 0; i < len; i++) {
          if (!split[i]) continue;
          namespaces = split[i].replace(/\*/g, ".*?");
          if (namespaces[0] === "-") {
            exports.skips.push(new RegExp("^" + namespaces.substr(1) + "$"));
          } else {
            exports.names.push(new RegExp("^" + namespaces + "$"));
          }
        }
      }
      function disable() {
        exports.enable("");
      }
      function enabled(name2) {
        var i, len;
        for (i = 0, len = exports.skips.length; i < len; i++) {
          if (exports.skips[i].test(name2)) {
            return false;
          }
        }
        for (i = 0, len = exports.names.length; i < len; i++) {
          if (exports.names[i].test(name2)) {
            return true;
          }
        }
        return false;
      }
      function coerce(val) {
        if (val instanceof Error) return val.stack || val.message;
        return val;
      }
    }
  });

  // node_modules/stream-parser/node_modules/debug/src/browser.js
  var require_browser2 = __commonJS({
    "node_modules/stream-parser/node_modules/debug/src/browser.js"(exports, module) {
      exports = module.exports = require_debug();
      exports.log = log;
      exports.formatArgs = formatArgs;
      exports.save = save;
      exports.load = load;
      exports.useColors = useColors;
      exports.storage = "undefined" != typeof chrome && "undefined" != typeof chrome.storage ? chrome.storage.local : localstorage();
      exports.colors = [
        "lightseagreen",
        "forestgreen",
        "goldenrod",
        "dodgerblue",
        "darkorchid",
        "crimson"
      ];
      function useColors() {
        if (typeof window !== "undefined" && window.process && window.process.type === "renderer") {
          return true;
        }
        return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // is firebug? http://stackoverflow.com/a/398120/376773
        typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // is firefox >= v31?
        // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
        typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // double check webkit in userAgent just in case we are in a worker
        typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
      }
      exports.formatters.j = function(v) {
        try {
          return JSON.stringify(v);
        } catch (err) {
          return "[UnexpectedJSONParseError]: " + err.message;
        }
      };
      function formatArgs(args) {
        var useColors2 = this.useColors;
        args[0] = (useColors2 ? "%c" : "") + this.namespace + (useColors2 ? " %c" : " ") + args[0] + (useColors2 ? "%c " : " ") + "+" + exports.humanize(this.diff);
        if (!useColors2) return;
        var c = "color: " + this.color;
        args.splice(1, 0, c, "color: inherit");
        var index = 0;
        var lastC = 0;
        args[0].replace(/%[a-zA-Z%]/g, function(match) {
          if ("%%" === match) return;
          index++;
          if ("%c" === match) {
            lastC = index;
          }
        });
        args.splice(lastC, 0, c);
      }
      function log() {
        return "object" === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments);
      }
      function save(namespaces) {
        try {
          if (null == namespaces) {
            exports.storage.removeItem("debug");
          } else {
            exports.storage.debug = namespaces;
          }
        } catch (e) {
        }
      }
      function load() {
        var r;
        try {
          r = exports.storage.debug;
        } catch (e) {
        }
        if (!r && typeof process !== "undefined" && "env" in process) {
          r = process.env.DEBUG;
        }
        return r;
      }
      exports.enable(load());
      function localstorage() {
        try {
          return window.localStorage;
        } catch (e) {
        }
      }
    }
  });

  // node_modules/stream-parser/index.js
  var require_stream_parser = __commonJS({
    "node_modules/stream-parser/index.js"(exports, module) {
      var assert = require_assert();
      var debug = require_browser2()("stream-parser");
      module.exports = Parser;
      var INIT = -1;
      var BUFFERING = 0;
      var SKIPPING = 1;
      var PASSTHROUGH = 2;
      function Parser(stream) {
        var isTransform = stream && "function" == typeof stream._transform;
        var isWritable = stream && "function" == typeof stream._write;
        if (!isTransform && !isWritable) throw new Error("must pass a Writable or Transform stream in");
        debug("extending Parser into stream");
        stream._bytes = _bytes;
        stream._skipBytes = _skipBytes;
        if (isTransform) stream._passthrough = _passthrough;
        if (isTransform) {
          stream._transform = transform;
        } else {
          stream._write = write;
        }
      }
      function init(stream) {
        debug("initializing parser stream");
        stream._parserBytesLeft = 0;
        stream._parserBuffers = [];
        stream._parserBuffered = 0;
        stream._parserState = INIT;
        stream._parserCallback = null;
        if ("function" == typeof stream.push) {
          stream._parserOutput = stream.push.bind(stream);
        }
        stream._parserInit = true;
      }
      function _bytes(n, fn) {
        assert(!this._parserCallback, 'there is already a "callback" set!');
        assert(isFinite(n) && n > 0, 'can only buffer a finite number of bytes > 0, got "' + n + '"');
        if (!this._parserInit) init(this);
        debug("buffering %o bytes", n);
        this._parserBytesLeft = n;
        this._parserCallback = fn;
        this._parserState = BUFFERING;
      }
      function _skipBytes(n, fn) {
        assert(!this._parserCallback, 'there is already a "callback" set!');
        assert(n > 0, 'can only skip > 0 bytes, got "' + n + '"');
        if (!this._parserInit) init(this);
        debug("skipping %o bytes", n);
        this._parserBytesLeft = n;
        this._parserCallback = fn;
        this._parserState = SKIPPING;
      }
      function _passthrough(n, fn) {
        assert(!this._parserCallback, 'There is already a "callback" set!');
        assert(n > 0, 'can only pass through > 0 bytes, got "' + n + '"');
        if (!this._parserInit) init(this);
        debug("passing through %o bytes", n);
        this._parserBytesLeft = n;
        this._parserCallback = fn;
        this._parserState = PASSTHROUGH;
      }
      function write(chunk, encoding, fn) {
        if (!this._parserInit) init(this);
        debug("write(%o bytes)", chunk.length);
        if ("function" == typeof encoding) fn = encoding;
        data(this, chunk, null, fn);
      }
      function transform(chunk, output, fn) {
        if (!this._parserInit) init(this);
        debug("transform(%o bytes)", chunk.length);
        if ("function" != typeof output) {
          output = this._parserOutput;
        }
        data(this, chunk, output, fn);
      }
      function _data(stream, chunk, output, fn) {
        if (stream._parserBytesLeft <= 0) {
          return fn(new Error("got data but not currently parsing anything"));
        }
        if (chunk.length <= stream._parserBytesLeft) {
          return function() {
            return process2(stream, chunk, output, fn);
          };
        } else {
          return function() {
            var b = chunk.slice(0, stream._parserBytesLeft);
            return process2(stream, b, output, function(err) {
              if (err) return fn(err);
              if (chunk.length > b.length) {
                return function() {
                  return _data(stream, chunk.slice(b.length), output, fn);
                };
              }
            });
          };
        }
      }
      function process2(stream, chunk, output, fn) {
        stream._parserBytesLeft -= chunk.length;
        debug("%o bytes left for stream piece", stream._parserBytesLeft);
        if (stream._parserState === BUFFERING) {
          stream._parserBuffers.push(chunk);
          stream._parserBuffered += chunk.length;
        } else if (stream._parserState === PASSTHROUGH) {
          output(chunk);
        }
        if (0 === stream._parserBytesLeft) {
          var cb = stream._parserCallback;
          if (cb && stream._parserState === BUFFERING && stream._parserBuffers.length > 1) {
            chunk = Buffer.concat(stream._parserBuffers, stream._parserBuffered);
          }
          if (stream._parserState !== BUFFERING) {
            chunk = null;
          }
          stream._parserCallback = null;
          stream._parserBuffered = 0;
          stream._parserState = INIT;
          stream._parserBuffers.splice(0);
          if (cb) {
            var args = [];
            if (chunk) {
              args.push(chunk);
            } else {
            }
            if (output) {
              args.push(output);
            }
            var async = cb.length > args.length;
            if (async) {
              args.push(trampoline(fn));
            }
            var rtn = cb.apply(stream, args);
            if (!async || fn === rtn) return fn;
          }
        } else {
          return fn;
        }
      }
      var data = trampoline(_data);
      function trampoline(fn) {
        return function() {
          var result = fn.apply(this, arguments);
          while ("function" == typeof result) {
            result = result();
          }
          return result;
        };
      }
    }
  });

  // node_modules/probe-image-size/lib/common.js
  var require_common = __commonJS({
    "node_modules/probe-image-size/lib/common.js"(exports) {
      "use strict";
      var Transform = require_stream_browserify().Transform;
      var streamParser = require_stream_parser();
      function ParserStream() {
        Transform.call(this, { readableObjectMode: true });
      }
      ParserStream.prototype = Object.create(Transform.prototype);
      ParserStream.prototype.constructor = ParserStream;
      streamParser(ParserStream.prototype);
      exports.ParserStream = ParserStream;
      exports.sliceEq = function(src, start, dest) {
        for (var i = start, j = 0; j < dest.length; ) {
          if (src[i++] !== dest[j++]) return false;
        }
        return true;
      };
      exports.str2arr = function(str, format) {
        var arr = [], i = 0;
        if (format && format === "hex") {
          while (i < str.length) {
            arr.push(parseInt(str.slice(i, i + 2), 16));
            i += 2;
          }
        } else {
          for (; i < str.length; i++) {
            arr.push(str.charCodeAt(i) & 255);
          }
        }
        return arr;
      };
      exports.readUInt16LE = function(data, offset) {
        return data[offset] | data[offset + 1] << 8;
      };
      exports.readUInt16BE = function(data, offset) {
        return data[offset + 1] | data[offset] << 8;
      };
      exports.readUInt32LE = function(data, offset) {
        return data[offset] | data[offset + 1] << 8 | data[offset + 2] << 16 | data[offset + 3] * 16777216;
      };
      exports.readUInt32BE = function(data, offset) {
        return data[offset + 3] | data[offset + 2] << 8 | data[offset + 1] << 16 | data[offset] * 16777216;
      };
      function ProbeError(message, code, statusCode) {
        Error.call(this);
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, this.constructor);
        } else {
          this.stack = new Error().stack || "";
        }
        this.name = this.constructor.name;
        this.message = message;
        if (code) this.code = code;
        if (statusCode) this.statusCode = statusCode;
      }
      ProbeError.prototype = Object.create(Error.prototype);
      ProbeError.prototype.constructor = ProbeError;
      exports.ProbeError = ProbeError;
    }
  });

  // node_modules/probe-image-size/lib/miaf_utils.js
  var require_miaf_utils = __commonJS({
    "node_modules/probe-image-size/lib/miaf_utils.js"(exports, module) {
      "use strict";
      var readUInt16BE = require_common().readUInt16BE;
      var readUInt32BE = require_common().readUInt32BE;
      function unbox(data, offset) {
        if (data.length < 4 + offset) return null;
        var size = readUInt32BE(data, offset);
        if (data.length < size + offset || size < 8) return null;
        return {
          boxtype: String.fromCharCode.apply(null, data.slice(offset + 4, offset + 8)),
          data: data.slice(offset + 8, offset + size),
          end: offset + size
        };
      }
      module.exports.unbox = unbox;
      function scan_ipco(data, sandbox) {
        var offset = 0;
        for (; ; ) {
          var box = unbox(data, offset);
          if (!box) break;
          switch (box.boxtype) {
            case "ispe":
              sandbox.sizes.push({
                width: readUInt32BE(box.data, 4),
                height: readUInt32BE(box.data, 8)
              });
              break;
            case "irot":
              sandbox.transforms.push({
                type: "irot",
                value: box.data[0] & 3
              });
              break;
            case "imir":
              sandbox.transforms.push({
                type: "imir",
                value: box.data[0] & 1
              });
              break;
          }
          offset = box.end;
        }
      }
      function readUIntBE(data, offset, size) {
        var result = 0;
        for (var i = 0; i < size; i++) {
          result = result * 256 + (data[offset + i] || 0);
        }
        return result;
      }
      function scan_iloc(data, sandbox) {
        var offset_size = data[4] >> 4 & 15;
        var length_size = data[4] & 15;
        var base_offset_size = data[5] >> 4 & 15;
        var item_count = readUInt16BE(data, 6);
        var offset = 8;
        for (var i = 0; i < item_count; i++) {
          var item_ID = readUInt16BE(data, offset);
          offset += 2;
          var data_reference_index = readUInt16BE(data, offset);
          offset += 2;
          var base_offset = readUIntBE(data, offset, base_offset_size);
          offset += base_offset_size;
          var extent_count = readUInt16BE(data, offset);
          offset += 2;
          if (data_reference_index === 0 && extent_count === 1) {
            var first_extent_offset = readUIntBE(data, offset, offset_size);
            var first_extent_length = readUIntBE(data, offset + offset_size, length_size);
            sandbox.item_loc[item_ID] = { length: first_extent_length, offset: first_extent_offset + base_offset };
          }
          offset += extent_count * (offset_size + length_size);
        }
      }
      function scan_iinf(data, sandbox) {
        var item_count = readUInt16BE(data, 4);
        var offset = 6;
        for (var i = 0; i < item_count; i++) {
          var box = unbox(data, offset);
          if (!box) break;
          if (box.boxtype === "infe") {
            var item_id = readUInt16BE(box.data, 4);
            var item_name = "";
            for (var pos = 8; pos < box.data.length && box.data[pos]; pos++) {
              item_name += String.fromCharCode(box.data[pos]);
            }
            sandbox.item_inf[item_name] = item_id;
          }
          offset = box.end;
        }
      }
      function scan_iprp(data, sandbox) {
        var offset = 0;
        for (; ; ) {
          var box = unbox(data, offset);
          if (!box) break;
          if (box.boxtype === "ipco") scan_ipco(box.data, sandbox);
          offset = box.end;
        }
      }
      function scan_meta(data, sandbox) {
        var offset = 4;
        for (; ; ) {
          var box = unbox(data, offset);
          if (!box) break;
          if (box.boxtype === "iprp") scan_iprp(box.data, sandbox);
          if (box.boxtype === "iloc") scan_iloc(box.data, sandbox);
          if (box.boxtype === "iinf") scan_iinf(box.data, sandbox);
          offset = box.end;
        }
      }
      function getMaxSize(sizes) {
        var maxWidthSize = sizes.reduce(function(a, b) {
          return a.width > b.width || a.width === b.width && a.height > b.height ? a : b;
        });
        var maxHeightSize = sizes.reduce(function(a, b) {
          return a.height > b.height || a.height === b.height && a.width > b.width ? a : b;
        });
        var maxSize;
        if (maxWidthSize.width > maxHeightSize.height || maxWidthSize.width === maxHeightSize.height && maxWidthSize.height > maxHeightSize.width) {
          maxSize = maxWidthSize;
        } else {
          maxSize = maxHeightSize;
        }
        return maxSize;
      }
      module.exports.readSizeFromMeta = function(data) {
        var sandbox = {
          sizes: [],
          transforms: [],
          item_inf: {},
          item_loc: {}
        };
        scan_meta(data, sandbox);
        if (!sandbox.sizes.length) return;
        var maxSize = getMaxSize(sandbox.sizes);
        var orientation = 1;
        sandbox.transforms.forEach(function(transform) {
          var rotate_ccw = { 1: 6, 2: 5, 3: 8, 4: 7, 5: 4, 6: 3, 7: 2, 8: 1 };
          var mirror_vert = { 1: 4, 2: 3, 3: 2, 4: 1, 5: 6, 6: 5, 7: 8, 8: 7 };
          if (transform.type === "imir") {
            if (transform.value === 0) {
              orientation = mirror_vert[orientation];
            } else {
              orientation = mirror_vert[orientation];
              orientation = rotate_ccw[orientation];
              orientation = rotate_ccw[orientation];
            }
          }
          if (transform.type === "irot") {
            for (var i = 0; i < transform.value; i++) {
              orientation = rotate_ccw[orientation];
            }
          }
        });
        var exif_location = null;
        if (sandbox.item_inf.Exif) {
          exif_location = sandbox.item_loc[sandbox.item_inf.Exif];
        }
        return {
          width: maxSize.width,
          height: maxSize.height,
          orientation: sandbox.transforms.length ? orientation : null,
          variants: sandbox.sizes,
          exif_location
        };
      };
      module.exports.getMimeType = function(data) {
        var brand = String.fromCharCode.apply(null, data.slice(0, 4));
        var compat = {};
        compat[brand] = true;
        for (var i = 8; i < data.length; i += 4) {
          compat[String.fromCharCode.apply(null, data.slice(i, i + 4))] = true;
        }
        if (!compat.mif1 && !compat.msf1 && !compat.miaf) return;
        if (brand === "avif" || brand === "avis" || brand === "avio") {
          return { type: "avif", mime: "image/avif" };
        }
        if (brand === "heic" || brand === "heix") {
          return { type: "heic", mime: "image/heic" };
        }
        if (brand === "hevc" || brand === "hevx") {
          return { type: "heic", mime: "image/heic-sequence" };
        }
        if (compat.avif || compat.avis) {
          return { type: "avif", mime: "image/avif" };
        }
        if (compat.heic || compat.heix || compat.hevc || compat.hevx || compat.heis) {
          if (compat.msf1) {
            return { type: "heif", mime: "image/heif-sequence" };
          }
          return { type: "heif", mime: "image/heif" };
        }
        return { type: "avif", mime: "image/avif" };
      };
    }
  });

  // node_modules/probe-image-size/lib/exif_utils.js
  var require_exif_utils = __commonJS({
    "node_modules/probe-image-size/lib/exif_utils.js"(exports, module) {
      "use strict";
      function error(message, code) {
        var err = new Error(message);
        err.code = code;
        return err;
      }
      function utf8_decode(str) {
        try {
          return decodeURIComponent(escape(str));
        } catch (_) {
          return str;
        }
      }
      function ExifParser(jpeg_bin, exif_start, exif_end) {
        this.input = jpeg_bin.subarray(exif_start, exif_end);
        this.start = exif_start;
        var sig = String.fromCharCode.apply(null, this.input.subarray(0, 4));
        if (sig !== "II*\0" && sig !== "MM\0*") {
          throw error("invalid TIFF signature", "EBADDATA");
        }
        this.big_endian = sig[0] === "M";
      }
      ExifParser.prototype.each = function(on_entry) {
        this.aborted = false;
        var offset = this.read_uint32(4);
        this.ifds_to_read = [{
          id: 0,
          offset
        }];
        while (this.ifds_to_read.length > 0 && !this.aborted) {
          var i = this.ifds_to_read.shift();
          if (!i.offset) continue;
          this.scan_ifd(i.id, i.offset, on_entry);
        }
      };
      ExifParser.prototype.read_uint16 = function(offset) {
        var d = this.input;
        if (offset + 2 > d.length) throw error("unexpected EOF", "EBADDATA");
        return this.big_endian ? d[offset] * 256 + d[offset + 1] : d[offset] + d[offset + 1] * 256;
      };
      ExifParser.prototype.read_uint32 = function(offset) {
        var d = this.input;
        if (offset + 4 > d.length) throw error("unexpected EOF", "EBADDATA");
        return this.big_endian ? d[offset] * 16777216 + d[offset + 1] * 65536 + d[offset + 2] * 256 + d[offset + 3] : d[offset] + d[offset + 1] * 256 + d[offset + 2] * 65536 + d[offset + 3] * 16777216;
      };
      ExifParser.prototype.is_subifd_link = function(ifd, tag) {
        return ifd === 0 && tag === 34665 || // SubIFD
        ifd === 0 && tag === 34853 || // GPS Info
        ifd === 34665 && tag === 40965;
      };
      ExifParser.prototype.exif_format_length = function(format) {
        switch (format) {
          case 1:
          // byte
          case 2:
          // ascii
          case 6:
          // sbyte
          case 7:
            return 1;
          case 3:
          // short
          case 8:
            return 2;
          case 4:
          // long
          case 9:
          // slong
          case 11:
            return 4;
          case 5:
          // rational
          case 10:
          // srational
          case 12:
            return 8;
          default:
            return 0;
        }
      };
      ExifParser.prototype.exif_format_read = function(format, offset) {
        var v;
        switch (format) {
          case 1:
          // byte
          case 2:
            v = this.input[offset];
            return v;
          case 6:
            v = this.input[offset];
            return v | (v & 128) * 33554430;
          case 3:
            v = this.read_uint16(offset);
            return v;
          case 8:
            v = this.read_uint16(offset);
            return v | (v & 32768) * 131070;
          case 4:
            v = this.read_uint32(offset);
            return v;
          case 9:
            v = this.read_uint32(offset);
            return v | 0;
          case 5:
          // rational
          case 10:
          // srational
          case 11:
          // float
          case 12:
            return null;
          // not implemented
          case 7:
            return null;
          // blob
          default:
            return null;
        }
      };
      ExifParser.prototype.scan_ifd = function(ifd_no, offset, on_entry) {
        var entry_count = this.read_uint16(offset);
        offset += 2;
        for (var i = 0; i < entry_count; i++) {
          var tag = this.read_uint16(offset);
          var format = this.read_uint16(offset + 2);
          var count = this.read_uint32(offset + 4);
          var comp_length = this.exif_format_length(format);
          var data_length = count * comp_length;
          var data_offset = data_length <= 4 ? offset + 8 : this.read_uint32(offset + 8);
          var is_subifd_link = false;
          if (data_offset + data_length > this.input.length) {
            throw error("unexpected EOF", "EBADDATA");
          }
          var value = [];
          var comp_offset = data_offset;
          for (var j = 0; j < count; j++, comp_offset += comp_length) {
            var item = this.exif_format_read(format, comp_offset);
            if (item === null) {
              value = null;
              break;
            }
            value.push(item);
          }
          if (Array.isArray(value) && format === 2) {
            value = utf8_decode(String.fromCharCode.apply(null, value));
            if (value && value[value.length - 1] === "\0") value = value.slice(0, -1);
          }
          if (this.is_subifd_link(ifd_no, tag)) {
            if (Array.isArray(value) && Number.isInteger(value[0]) && value[0] > 0) {
              this.ifds_to_read.push({
                id: tag,
                offset: value[0]
              });
              is_subifd_link = true;
            }
          }
          var entry = {
            is_big_endian: this.big_endian,
            ifd: ifd_no,
            tag,
            format,
            count,
            entry_offset: offset + this.start,
            data_length,
            data_offset: data_offset + this.start,
            value,
            is_subifd_link
          };
          if (on_entry(entry) === false) {
            this.aborted = true;
            return;
          }
          offset += 12;
        }
        if (ifd_no === 0) {
          this.ifds_to_read.push({
            id: 1,
            offset: this.read_uint32(offset)
          });
        }
      };
      module.exports.ExifParser = ExifParser;
      module.exports.get_orientation = function(data) {
        var orientation = 0;
        try {
          new ExifParser(data, 0, data.length).each(function(entry) {
            if (entry.ifd === 0 && entry.tag === 274 && Array.isArray(entry.value)) {
              orientation = entry.value[0];
              return false;
            }
          });
          return orientation;
        } catch (err) {
          return -1;
        }
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/avif.js
  var require_avif = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/avif.js"(exports, module) {
      "use strict";
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var readUInt32BE = require_common().readUInt32BE;
      var miaf = require_miaf_utils();
      var exif = require_exif_utils();
      var SIG_FTYP = str2arr("ftyp");
      module.exports = function(data) {
        if (!sliceEq(data, 4, SIG_FTYP)) return;
        var firstBox = miaf.unbox(data, 0);
        if (!firstBox) return;
        var fileType = miaf.getMimeType(firstBox.data);
        if (!fileType) return;
        var meta, offset = firstBox.end;
        for (; ; ) {
          var box = miaf.unbox(data, offset);
          if (!box) break;
          offset = box.end;
          if (box.boxtype === "mdat") return;
          if (box.boxtype === "meta") {
            meta = box.data;
            break;
          }
        }
        if (!meta) return;
        var imgSize = miaf.readSizeFromMeta(meta);
        if (!imgSize) return;
        var result = {
          width: imgSize.width,
          height: imgSize.height,
          type: fileType.type,
          mime: fileType.mime,
          wUnits: "px",
          hUnits: "px"
        };
        if (imgSize.variants.length > 1) {
          result.variants = imgSize.variants;
        }
        if (imgSize.orientation) {
          result.orientation = imgSize.orientation;
        }
        if (imgSize.exif_location && imgSize.exif_location.offset + imgSize.exif_location.length <= data.length) {
          var sig_offset = readUInt32BE(data, imgSize.exif_location.offset);
          var exif_data = data.slice(
            imgSize.exif_location.offset + sig_offset + 4,
            imgSize.exif_location.offset + imgSize.exif_location.length
          );
          var orientation = exif.get_orientation(exif_data);
          if (orientation > 0) result.orientation = orientation;
        }
        return result;
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/bmp.js
  var require_bmp = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/bmp.js"(exports, module) {
      "use strict";
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var readUInt16LE = require_common().readUInt16LE;
      var SIG_BM = str2arr("BM");
      module.exports = function(data) {
        if (data.length < 26) return;
        if (!sliceEq(data, 0, SIG_BM)) return;
        return {
          width: readUInt16LE(data, 18),
          height: readUInt16LE(data, 22),
          type: "bmp",
          mime: "image/bmp",
          wUnits: "px",
          hUnits: "px"
        };
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/gif.js
  var require_gif = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/gif.js"(exports, module) {
      "use strict";
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var readUInt16LE = require_common().readUInt16LE;
      var SIG_GIF87a = str2arr("GIF87a");
      var SIG_GIF89a = str2arr("GIF89a");
      module.exports = function(data) {
        if (data.length < 10) return;
        if (!sliceEq(data, 0, SIG_GIF87a) && !sliceEq(data, 0, SIG_GIF89a)) return;
        return {
          width: readUInt16LE(data, 6),
          height: readUInt16LE(data, 8),
          type: "gif",
          mime: "image/gif",
          wUnits: "px",
          hUnits: "px"
        };
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/ico.js
  var require_ico = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/ico.js"(exports, module) {
      "use strict";
      var readUInt16LE = require_common().readUInt16LE;
      var HEADER = 0;
      var TYPE_ICO = 1;
      var INDEX_SIZE = 16;
      module.exports = function(data) {
        var header = readUInt16LE(data, 0);
        var type = readUInt16LE(data, 2);
        var numImages = readUInt16LE(data, 4);
        if (header !== HEADER || type !== TYPE_ICO || !numImages) {
          return;
        }
        var variants = [];
        var maxSize = { width: 0, height: 0 };
        for (var i = 0; i < numImages; i++) {
          var width = data[6 + INDEX_SIZE * i] || 256;
          var height = data[6 + INDEX_SIZE * i + 1] || 256;
          var size = { width, height };
          variants.push(size);
          if (width > maxSize.width || height > maxSize.height) {
            maxSize = size;
          }
        }
        return {
          width: maxSize.width,
          height: maxSize.height,
          variants,
          type: "ico",
          mime: "image/x-icon",
          wUnits: "px",
          hUnits: "px"
        };
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/jpeg.js
  var require_jpeg = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/jpeg.js"(exports, module) {
      "use strict";
      var readUInt16BE = require_common().readUInt16BE;
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var exif = require_exif_utils();
      var SIG_EXIF = str2arr("Exif\0\0");
      module.exports = function(data) {
        if (data.length < 2) return;
        if (data[0] !== 255 || data[1] !== 216 || data[2] !== 255) return;
        var offset = 2;
        for (; ; ) {
          for (; ; ) {
            if (data.length - offset < 2) return;
            if (data[offset++] === 255) break;
          }
          var code = data[offset++];
          var length;
          while (code === 255) code = data[offset++];
          if (208 <= code && code <= 217 || code === 1) {
            length = 0;
          } else if (192 <= code && code <= 254) {
            if (data.length - offset < 2) return;
            length = readUInt16BE(data, offset) - 2;
            offset += 2;
          } else {
            return;
          }
          if (code === 217 || code === 218) {
            return;
          }
          var orientation;
          if (code === 225 && length >= 10 && sliceEq(data, offset, SIG_EXIF)) {
            orientation = exif.get_orientation(data.slice(offset + 6, offset + length));
          }
          if (length >= 5 && (192 <= code && code <= 207) && code !== 196 && code !== 200 && code !== 204) {
            if (data.length - offset < length) return;
            var result = {
              width: readUInt16BE(data, offset + 3),
              height: readUInt16BE(data, offset + 1),
              type: "jpg",
              mime: "image/jpeg",
              wUnits: "px",
              hUnits: "px"
            };
            if (orientation > 0) {
              result.orientation = orientation;
            }
            return result;
          }
          offset += length;
        }
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/png.js
  var require_png = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/png.js"(exports, module) {
      "use strict";
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var readUInt32BE = require_common().readUInt32BE;
      var SIG_PNG = str2arr("\x89PNG\r\n\n");
      var SIG_IHDR = str2arr("IHDR");
      module.exports = function(data) {
        if (data.length < 24) return;
        if (!sliceEq(data, 0, SIG_PNG)) return;
        if (!sliceEq(data, 12, SIG_IHDR)) return;
        return {
          width: readUInt32BE(data, 16),
          height: readUInt32BE(data, 20),
          type: "png",
          mime: "image/png",
          wUnits: "px",
          hUnits: "px"
        };
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/psd.js
  var require_psd = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/psd.js"(exports, module) {
      "use strict";
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var readUInt32BE = require_common().readUInt32BE;
      var SIG_8BPS = str2arr("8BPS\0");
      module.exports = function(data) {
        if (data.length < 6 + 16) return;
        if (!sliceEq(data, 0, SIG_8BPS)) return;
        return {
          width: readUInt32BE(data, 6 + 12),
          height: readUInt32BE(data, 6 + 8),
          type: "psd",
          mime: "image/vnd.adobe.photoshop",
          wUnits: "px",
          hUnits: "px"
        };
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/svg.js
  var require_svg = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/svg.js"(exports, module) {
      "use strict";
      function isWhiteSpace(chr) {
        return chr === 32 || chr === 9 || chr === 13 || chr === 10;
      }
      function isFinitePositive(val) {
        return typeof val === "number" && isFinite(val) && val > 0;
      }
      function canBeSvg(buf) {
        var i = 0, max = buf.length;
        if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
        while (i < max && isWhiteSpace(buf[i])) i++;
        if (i === max) return false;
        return buf[i] === 60;
      }
      var SVG_HEADER_RE = /<[-_.:a-zA-Z0-9][^>]*>/;
      var SVG_TAG_RE = /^<([-_.:a-zA-Z0-9]+:)?svg\s/;
      var SVG_WIDTH_RE = /[^-]\bwidth="([^%]+?)"|[^-]\bwidth='([^%]+?)'/;
      var SVG_HEIGHT_RE = /\bheight="([^%]+?)"|\bheight='([^%]+?)'/;
      var SVG_VIEWBOX_RE = /\bview[bB]ox="(.+?)"|\bview[bB]ox='(.+?)'/;
      var SVG_UNITS_RE = /in$|mm$|cm$|pt$|pc$|px$|em$|ex$/;
      function svgAttrs(str) {
        var width = str.match(SVG_WIDTH_RE);
        var height = str.match(SVG_HEIGHT_RE);
        var viewbox = str.match(SVG_VIEWBOX_RE);
        return {
          width: width && (width[1] || width[2]),
          height: height && (height[1] || height[2]),
          viewbox: viewbox && (viewbox[1] || viewbox[2])
        };
      }
      function units(str) {
        if (!SVG_UNITS_RE.test(str)) return "px";
        return str.match(SVG_UNITS_RE)[0];
      }
      module.exports = function(data) {
        if (!canBeSvg(data)) return;
        var str = "";
        for (var i = 0; i < data.length; i++) {
          str += String.fromCharCode(data[i]);
        }
        var svgTag = (str.match(SVG_HEADER_RE) || [""])[0];
        if (!SVG_TAG_RE.test(svgTag)) return;
        var attrs = svgAttrs(svgTag);
        var width = parseFloat(attrs.width);
        var height = parseFloat(attrs.height);
        if (attrs.width && attrs.height) {
          if (!isFinitePositive(width) || !isFinitePositive(height)) return;
          return {
            width,
            height,
            type: "svg",
            mime: "image/svg+xml",
            wUnits: units(attrs.width),
            hUnits: units(attrs.height)
          };
        }
        var parts = (attrs.viewbox || "").split(" ");
        var viewbox = {
          width: parts[2],
          height: parts[3]
        };
        var vbWidth = parseFloat(viewbox.width);
        var vbHeight = parseFloat(viewbox.height);
        if (!isFinitePositive(vbWidth) || !isFinitePositive(vbHeight)) return;
        if (units(viewbox.width) !== units(viewbox.height)) return;
        var ratio = vbWidth / vbHeight;
        if (attrs.width) {
          if (!isFinitePositive(width)) return;
          return {
            width,
            height: width / ratio,
            type: "svg",
            mime: "image/svg+xml",
            wUnits: units(attrs.width),
            hUnits: units(attrs.width)
          };
        }
        if (attrs.height) {
          if (!isFinitePositive(height)) return;
          return {
            width: height * ratio,
            height,
            type: "svg",
            mime: "image/svg+xml",
            wUnits: units(attrs.height),
            hUnits: units(attrs.height)
          };
        }
        return {
          width: vbWidth,
          height: vbHeight,
          type: "svg",
          mime: "image/svg+xml",
          wUnits: units(viewbox.width),
          hUnits: units(viewbox.height)
        };
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/tiff.js
  var require_tiff = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/tiff.js"(exports, module) {
      "use strict";
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var readUInt16LE = require_common().readUInt16LE;
      var readUInt16BE = require_common().readUInt16BE;
      var readUInt32LE = require_common().readUInt32LE;
      var readUInt32BE = require_common().readUInt32BE;
      var SIG_1 = str2arr("II*\0");
      var SIG_2 = str2arr("MM\0*");
      function readUInt16(buffer, offset, is_big_endian) {
        return is_big_endian ? readUInt16BE(buffer, offset) : readUInt16LE(buffer, offset);
      }
      function readUInt32(buffer, offset, is_big_endian) {
        return is_big_endian ? readUInt32BE(buffer, offset) : readUInt32LE(buffer, offset);
      }
      function readIFDValue(data, data_offset, is_big_endian) {
        var type = readUInt16(data, data_offset + 2, is_big_endian);
        var values = readUInt32(data, data_offset + 4, is_big_endian);
        if (values !== 1 || type !== 3 && type !== 4) return null;
        if (type === 3) {
          return readUInt16(data, data_offset + 8, is_big_endian);
        }
        return readUInt32(data, data_offset + 8, is_big_endian);
      }
      module.exports = function(data) {
        if (data.length < 8) return;
        if (!sliceEq(data, 0, SIG_1) && !sliceEq(data, 0, SIG_2)) return;
        var is_big_endian = data[0] === 77;
        var count = readUInt32(data, 4, is_big_endian) - 8;
        if (count < 0) return;
        var offset = count + 8;
        if (data.length - offset < 2) return;
        var ifd_size = readUInt16(data, offset + 0, is_big_endian) * 12;
        if (ifd_size <= 0) return;
        offset += 2;
        if (data.length - offset < ifd_size) return;
        var i, width, height, tag;
        for (i = 0; i < ifd_size; i += 12) {
          tag = readUInt16(data, offset + i, is_big_endian);
          if (tag === 256) {
            width = readIFDValue(data, offset + i, is_big_endian);
          } else if (tag === 257) {
            height = readIFDValue(data, offset + i, is_big_endian);
          }
        }
        if (width && height) {
          return {
            width,
            height,
            type: "tiff",
            mime: "image/tiff",
            wUnits: "px",
            hUnits: "px"
          };
        }
      };
    }
  });

  // node_modules/probe-image-size/lib/parse_sync/webp.js
  var require_webp = __commonJS({
    "node_modules/probe-image-size/lib/parse_sync/webp.js"(exports, module) {
      "use strict";
      var str2arr = require_common().str2arr;
      var sliceEq = require_common().sliceEq;
      var readUInt16LE = require_common().readUInt16LE;
      var readUInt32LE = require_common().readUInt32LE;
      var exif = require_exif_utils();
      var SIG_RIFF = str2arr("RIFF");
      var SIG_WEBP = str2arr("WEBP");
      function parseVP8(data, offset) {
        if (data[offset + 3] !== 157 || data[offset + 4] !== 1 || data[offset + 5] !== 42) {
          return;
        }
        return {
          width: readUInt16LE(data, offset + 6) & 16383,
          height: readUInt16LE(data, offset + 8) & 16383,
          type: "webp",
          mime: "image/webp",
          wUnits: "px",
          hUnits: "px"
        };
      }
      function parseVP8L(data, offset) {
        if (data[offset] !== 47) return;
        var bits = readUInt32LE(data, offset + 1);
        return {
          width: (bits & 16383) + 1,
          height: (bits >> 14 & 16383) + 1,
          type: "webp",
          mime: "image/webp",
          wUnits: "px",
          hUnits: "px"
        };
      }
      function parseVP8X(data, offset) {
        return {
          // TODO: replace with `data.readUIntLE(8, 3) + 1`
          //       when 0.10 support is dropped
          width: (data[offset + 6] << 16 | data[offset + 5] << 8 | data[offset + 4]) + 1,
          height: (data[offset + 9] << offset | data[offset + 8] << 8 | data[offset + 7]) + 1,
          type: "webp",
          mime: "image/webp",
          wUnits: "px",
          hUnits: "px"
        };
      }
      module.exports = function(data) {
        if (data.length < 16) return;
        if (!sliceEq(data, 0, SIG_RIFF) && !sliceEq(data, 8, SIG_WEBP)) return;
        var offset = 12;
        var result = null;
        var exif_orientation = 0;
        var fileLength = readUInt32LE(data, 4) + 8;
        if (fileLength > data.length) return;
        while (offset + 8 < fileLength) {
          if (data[offset] === 0) {
            offset++;
            continue;
          }
          var header = String.fromCharCode.apply(null, data.slice(offset, offset + 4));
          var length = readUInt32LE(data, offset + 4);
          if (header === "VP8 " && length >= 10) {
            result = result || parseVP8(data, offset + 8);
          } else if (header === "VP8L" && length >= 9) {
            result = result || parseVP8L(data, offset + 8);
          } else if (header === "VP8X" && length >= 10) {
            result = result || parseVP8X(data, offset + 8);
          } else if (header === "EXIF") {
            exif_orientation = exif.get_orientation(data.slice(offset + 8, offset + 8 + length));
            offset = Infinity;
          }
          offset += 8 + length;
        }
        if (!result) return;
        if (exif_orientation > 0) {
          result.orientation = exif_orientation;
        }
        return result;
      };
    }
  });

  // node_modules/probe-image-size/lib/parsers_sync.js
  var require_parsers_sync = __commonJS({
    "node_modules/probe-image-size/lib/parsers_sync.js"(exports, module) {
      "use strict";
      module.exports = {
        avif: require_avif(),
        bmp: require_bmp(),
        gif: require_gif(),
        ico: require_ico(),
        jpeg: require_jpeg(),
        png: require_png(),
        psd: require_psd(),
        svg: require_svg(),
        tiff: require_tiff(),
        webp: require_webp()
      };
    }
  });

  // node_modules/probe-image-size/sync.js
  var require_sync = __commonJS({
    "node_modules/probe-image-size/sync.js"(exports, module) {
      "use strict";
      var parsers = require_parsers_sync();
      function probeBuffer(buffer) {
        var parser_names = Object.keys(parsers);
        for (var i = 0; i < parser_names.length; i++) {
          var result = parsers[parser_names[i]](buffer);
          if (result) return result;
        }
        return null;
      }
      module.exports = function get_image_size(src) {
        return probeBuffer(src);
      };
      module.exports.parsers = parsers;
    }
  });

  // src/traces/image/helpers.js
  var require_helpers14 = __commonJS({
    "src/traces/image/helpers.js"(exports) {
      "use strict";
      var probeSync = require_sync();
      var dataUri = require_helpers10().IMAGE_URL_PREFIX;
      var Buffer2 = require_buffer().Buffer;
      exports.getImageSize = function(src) {
        var data = src.replace(dataUri, "");
        var buff = new Buffer2(data, "base64");
        return probeSync(buff);
      };
    }
  });

  // src/traces/image/calc.js
  var require_calc15 = __commonJS({
    "src/traces/image/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var constants = require_constants19();
      var isNumeric = require_fast_isnumeric();
      var Axes = require_axes();
      var maxRowLength = require_lib().maxRowLength;
      var getImageSize = require_helpers14().getImageSize;
      module.exports = function calc(gd, trace) {
        var h;
        var w;
        if (trace._hasZ) {
          h = trace.z.length;
          w = maxRowLength(trace.z);
        } else if (trace._hasSource) {
          var size = getImageSize(trace.source);
          h = size.height;
          w = size.width;
        }
        var xa = Axes.getFromId(gd, trace.xaxis || "x");
        var ya = Axes.getFromId(gd, trace.yaxis || "y");
        var x0 = xa.d2c(trace.x0) - trace.dx / 2;
        var y0 = ya.d2c(trace.y0) - trace.dy / 2;
        var i;
        var xrange = [x0, x0 + w * trace.dx];
        var yrange = [y0, y0 + h * trace.dy];
        if (xa && xa.type === "log") for (i = 0; i < w; i++) xrange.push(x0 + i * trace.dx);
        if (ya && ya.type === "log") for (i = 0; i < h; i++) yrange.push(y0 + i * trace.dy);
        trace._extremes[xa._id] = Axes.findExtremes(xa, xrange);
        trace._extremes[ya._id] = Axes.findExtremes(ya, yrange);
        trace._scaler = makeScaler(trace);
        var cd0 = {
          x0,
          y0,
          z: trace.z,
          w,
          h
        };
        return [cd0];
      };
      function scale(zero2, ratio, min, max) {
        return function(c) {
          return Lib.constrain((c - zero2) * ratio, min, max);
        };
      }
      function constrain(min, max) {
        return function(c) {
          return Lib.constrain(c, min, max);
        };
      }
      function makeScaler(trace) {
        var cr = constants.colormodel[trace.colormodel];
        var colormodel = cr.colormodel || trace.colormodel;
        var n = colormodel.length;
        trace._sArray = [];
        for (var k = 0; k < n; k++) {
          if (cr.min[k] !== trace.zmin[k] || cr.max[k] !== trace.zmax[k]) {
            trace._sArray.push(scale(
              trace.zmin[k],
              (cr.max[k] - cr.min[k]) / (trace.zmax[k] - trace.zmin[k]),
              cr.min[k],
              cr.max[k]
            ));
          } else {
            trace._sArray.push(constrain(cr.min[k], cr.max[k]));
          }
        }
        return function(pixel) {
          var c = pixel.slice(0, n);
          for (var k2 = 0; k2 < n; k2++) {
            var ck = c[k2];
            if (!isNumeric(ck)) return false;
            c[k2] = trace._sArray[k2](ck);
          }
          return c;
        };
      }
    }
  });

  // src/traces/image/plot.js
  var require_plot11 = __commonJS({
    "src/traces/image/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var xmlnsNamespaces = require_xmlns_namespaces();
      var constants = require_constants19();
      var supportsPixelatedImage = require_supports_pixelated_image();
      var PIXELATED_IMAGE_STYLE = require_pixelated_image().STYLE;
      module.exports = function plot(gd, plotinfo, cdimage, imageLayer) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var supportsPixelated = !gd._context._exportedPlot && supportsPixelatedImage();
        Lib.makeTraceGroups(imageLayer, cdimage, "im").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          var realImage = (trace.zsmooth === "fast" || trace.zsmooth === false && supportsPixelated) && !trace._hasZ && trace._hasSource && xa.type === "linear" && ya.type === "linear";
          trace._realImage = realImage;
          var z = cd0.z;
          var x0 = cd0.x0;
          var y0 = cd0.y0;
          var w = cd0.w;
          var h = cd0.h;
          var dx = trace.dx;
          var dy = trace.dy;
          var left, right, temp, top, bottom, i;
          i = 0;
          while (left === void 0 && i < w) {
            left = xa.c2p(x0 + i * dx);
            i++;
          }
          i = w;
          while (right === void 0 && i > 0) {
            right = xa.c2p(x0 + i * dx);
            i--;
          }
          i = 0;
          while (top === void 0 && i < h) {
            top = ya.c2p(y0 + i * dy);
            i++;
          }
          i = h;
          while (bottom === void 0 && i > 0) {
            bottom = ya.c2p(y0 + i * dy);
            i--;
          }
          if (right < left) {
            temp = right;
            right = left;
            left = temp;
          }
          if (bottom < top) {
            temp = top;
            top = bottom;
            bottom = temp;
          }
          if (!realImage) {
            var extra = 0.5;
            left = Math.max(-extra * xa._length, left);
            right = Math.min((1 + extra) * xa._length, right);
            top = Math.max(-extra * ya._length, top);
            bottom = Math.min((1 + extra) * ya._length, bottom);
          }
          var imageWidth = Math.round(right - left);
          var imageHeight = Math.round(bottom - top);
          var isOffScreen = imageWidth <= 0 || imageHeight <= 0;
          if (isOffScreen) {
            var noImage = plotGroup.selectAll("image").data([]);
            noImage.exit().remove();
            return;
          }
          function drawMagnifiedPixelsOnCanvas(readPixel) {
            var canvas = document.createElement("canvas");
            canvas.width = imageWidth;
            canvas.height = imageHeight;
            var context = canvas.getContext("2d", { willReadFrequently: true });
            var ipx = function(i2) {
              return Lib.constrain(Math.round(xa.c2p(x0 + i2 * dx) - left), 0, imageWidth);
            };
            var jpx = function(j2) {
              return Lib.constrain(Math.round(ya.c2p(y0 + j2 * dy) - top), 0, imageHeight);
            };
            var cr = constants.colormodel[trace.colormodel];
            var colormodel = cr.colormodel || trace.colormodel;
            var fmt = cr.fmt;
            var c;
            for (i = 0; i < cd0.w; i++) {
              var ipx0 = ipx(i);
              var ipx1 = ipx(i + 1);
              if (ipx1 === ipx0 || isNaN(ipx1) || isNaN(ipx0)) continue;
              for (var j = 0; j < cd0.h; j++) {
                var jpx0 = jpx(j);
                var jpx1 = jpx(j + 1);
                if (jpx1 === jpx0 || isNaN(jpx1) || isNaN(jpx0) || !readPixel(i, j)) continue;
                c = trace._scaler(readPixel(i, j));
                if (c) {
                  context.fillStyle = colormodel + "(" + fmt(c).join(",") + ")";
                } else {
                  context.fillStyle = "rgba(0,0,0,0)";
                }
                context.fillRect(ipx0, jpx0, ipx1 - ipx0, jpx1 - jpx0);
              }
            }
            return canvas;
          }
          var image3 = plotGroup.selectAll("image").data([cd]);
          image3.enter().append("svg:image").attr({
            xmlns: xmlnsNamespaces.svg,
            preserveAspectRatio: "none"
          });
          image3.exit().remove();
          var style = trace.zsmooth === false ? PIXELATED_IMAGE_STYLE : "";
          if (realImage) {
            var xRange = Lib.simpleMap(xa.range, xa.r2l);
            var yRange = Lib.simpleMap(ya.range, ya.r2l);
            var flipX = xRange[1] < xRange[0];
            var flipY = yRange[1] > yRange[0];
            if (flipX || flipY) {
              var tx = left + imageWidth / 2;
              var ty = top + imageHeight / 2;
              style += "transform:" + strTranslate(tx + "px", ty + "px") + "scale(" + (flipX ? -1 : 1) + "," + (flipY ? -1 : 1) + ")" + strTranslate(-tx + "px", -ty + "px") + ";";
            }
          }
          image3.attr("style", style);
          var p = new Promise(function(resolve) {
            if (trace._hasZ) {
              resolve();
            } else if (trace._hasSource) {
              if (trace._canvas && trace._canvas.el.width === w && trace._canvas.el.height === h && trace._canvas.source === trace.source) {
                resolve();
              } else {
                var canvas = document.createElement("canvas");
                canvas.width = w;
                canvas.height = h;
                var context = canvas.getContext("2d", { willReadFrequently: true });
                trace._image = trace._image || new Image();
                var image = trace._image;
                image.onload = function() {
                  context.drawImage(image, 0, 0);
                  trace._canvas = {
                    el: canvas,
                    source: trace.source
                  };
                  resolve();
                };
                image.setAttribute("src", trace.source);
              }
            }
          }).then(function() {
            var href, canvas;
            if (trace._hasZ) {
              canvas = drawMagnifiedPixelsOnCanvas(function(i2, j) {
                var _z = z[j][i2];
                if (Lib.isTypedArray(_z)) _z = Array.from(_z);
                return _z;
              });
              href = canvas.toDataURL("image/png");
            } else if (trace._hasSource) {
              if (realImage) {
                href = trace.source;
              } else {
                var context = trace._canvas.el.getContext("2d", { willReadFrequently: true });
                var data = context.getImageData(0, 0, w, h).data;
                canvas = drawMagnifiedPixelsOnCanvas(function(i2, j) {
                  var index = 4 * (j * w + i2);
                  return [
                    data[index],
                    data[index + 1],
                    data[index + 2],
                    data[index + 3]
                  ];
                });
                href = canvas.toDataURL("image/png");
              }
            }
            image3.attr({
              "xlink:href": href,
              height: imageHeight,
              width: imageWidth,
              x: left,
              y: top
            });
          });
          gd._promises.push(p);
        });
      };
    }
  });

  // src/traces/image/style.js
  var require_style11 = __commonJS({
    "src/traces/image/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      module.exports = function style(gd) {
        d3.select(gd).selectAll(".im image").style("opacity", function(d) {
          return d[0].trace.opacity;
        });
      };
    }
  });

  // src/traces/image/hover.js
  var require_hover13 = __commonJS({
    "src/traces/image/hover.js"(exports, module) {
      "use strict";
      var Fx = require_fx();
      var Lib = require_lib();
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var constants = require_constants19();
      module.exports = function hoverPoints(pointData, xval, yval) {
        var cd0 = pointData.cd[0];
        var trace = cd0.trace;
        var xa = pointData.xa;
        var ya = pointData.ya;
        if (Fx.inbox(xval - cd0.x0, xval - (cd0.x0 + cd0.w * trace.dx), 0) > 0 || Fx.inbox(yval - cd0.y0, yval - (cd0.y0 + cd0.h * trace.dy), 0) > 0) {
          return;
        }
        var nx = Math.floor((xval - cd0.x0) / trace.dx);
        var ny = Math.floor(Math.abs(yval - cd0.y0) / trace.dy);
        var pixel;
        if (trace._hasZ) {
          pixel = cd0.z[ny][nx];
        } else if (trace._hasSource) {
          pixel = trace._canvas.el.getContext("2d", { willReadFrequently: true }).getImageData(nx, ny, 1, 1).data;
        }
        if (!pixel) return;
        var hoverinfo = cd0.hi || trace.hoverinfo;
        var fmtColor;
        if (hoverinfo) {
          var parts = hoverinfo.split("+");
          if (parts.indexOf("all") !== -1) parts = ["color"];
          if (parts.indexOf("color") !== -1) fmtColor = true;
        }
        var cr = constants.colormodel[trace.colormodel];
        var colormodel = cr.colormodel || trace.colormodel;
        var dims = colormodel.length;
        var c = trace._scaler(pixel);
        var s = cr.suffix;
        var colorstring = [];
        if (trace.hovertemplate || fmtColor) {
          colorstring.push("[" + [c[0] + s[0], c[1] + s[1], c[2] + s[2]].join(", "));
          if (dims === 4) colorstring.push(", " + c[3] + s[3]);
          colorstring.push("]");
          colorstring = colorstring.join("");
          pointData.extraText = colormodel.toUpperCase() + ": " + colorstring;
        }
        var text;
        if (isArrayOrTypedArray(trace.hovertext) && isArrayOrTypedArray(trace.hovertext[ny])) {
          text = trace.hovertext[ny][nx];
        } else if (isArrayOrTypedArray(trace.text) && isArrayOrTypedArray(trace.text[ny])) {
          text = trace.text[ny][nx];
        }
        var py = ya.c2p(cd0.y0 + (ny + 0.5) * trace.dy);
        var xVal = cd0.x0 + (nx + 0.5) * trace.dx;
        var yVal = cd0.y0 + (ny + 0.5) * trace.dy;
        var zLabel = "[" + pixel.slice(0, trace.colormodel.length).join(", ") + "]";
        return [Lib.extendFlat(pointData, {
          index: [ny, nx],
          x0: xa.c2p(cd0.x0 + nx * trace.dx),
          x1: xa.c2p(cd0.x0 + (nx + 1) * trace.dx),
          y0: py,
          y1: py,
          color: c,
          xVal,
          xLabelVal: xVal,
          yVal,
          yLabelVal: yVal,
          zLabelVal: zLabel,
          text,
          hovertemplateLabels: {
            zLabel,
            colorLabel: colorstring,
            "color[0]Label": c[0] + s[0],
            "color[1]Label": c[1] + s[1],
            "color[2]Label": c[2] + s[2],
            "color[3]Label": c[3] + s[3]
          }
        })];
      };
    }
  });

  // src/traces/image/event_data.js
  var require_event_data7 = __commonJS({
    "src/traces/image/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        if ("xVal" in pt) out.x = pt.xVal;
        if ("yVal" in pt) out.y = pt.yVal;
        if (pt.xa) out.xaxis = pt.xa;
        if (pt.ya) out.yaxis = pt.ya;
        out.color = pt.color;
        out.colormodel = pt.trace.colormodel;
        if (!out.z) out.z = pt.color;
        return out;
      };
    }
  });

  // src/traces/image/index.js
  var require_image = __commonJS({
    "src/traces/image/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes34(),
        supplyDefaults: require_defaults30(),
        calc: require_calc15(),
        plot: require_plot11(),
        style: require_style11(),
        hoverPoints: require_hover13(),
        eventData: require_event_data7(),
        moduleType: "trace",
        name: "image",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "2dMap", "noSortingByValue"],
        animatable: false,
        meta: {}
      };
    }
  });

  // lib/image.js
  var require_image2 = __commonJS({
    "lib/image.js"(exports, module) {
      "use strict";
      module.exports = require_image();
    }
  });

  // src/traces/pie/attributes.js
  var require_attributes35 = __commonJS({
    "src/traces/pie/attributes.js"(exports, module) {
      "use strict";
      var baseAttrs = require_attributes2();
      var domainAttrs = require_domain().attributes;
      var fontAttrs = require_font_attributes();
      var colorAttrs = require_attributes3();
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var extendFlat = require_extend().extendFlat;
      var pattern = require_attributes4().pattern;
      var textFontAttrs = fontAttrs({
        editType: "plot",
        arrayOk: true,
        colorEditType: "plot"
      });
      module.exports = {
        labels: {
          valType: "data_array",
          editType: "calc"
        },
        // equivalent of x0 and dx, if label is missing
        label0: {
          valType: "number",
          dflt: 0,
          editType: "calc"
        },
        dlabel: {
          valType: "number",
          dflt: 1,
          editType: "calc"
        },
        values: {
          valType: "data_array",
          editType: "calc"
        },
        marker: {
          colors: {
            valType: "data_array",
            // TODO 'color_array' ?
            editType: "calc"
          },
          line: {
            color: {
              valType: "color",
              dflt: colorAttrs.defaultLine,
              arrayOk: true,
              editType: "style"
            },
            width: {
              valType: "number",
              min: 0,
              dflt: 0,
              arrayOk: true,
              editType: "style"
            },
            editType: "calc"
          },
          pattern,
          editType: "calc"
        },
        text: {
          valType: "data_array",
          editType: "plot"
        },
        hovertext: {
          valType: "string",
          dflt: "",
          arrayOk: true,
          editType: "style"
        },
        // 'see eg:'
        // 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif',
        // '(this example involves a map too - may someday be a whole trace type',
        // 'of its own. but the point is the size of the whole pie is important.)'
        scalegroup: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        // labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels)
        textinfo: {
          valType: "flaglist",
          flags: ["label", "text", "value", "percent"],
          extras: ["none"],
          editType: "calc"
        },
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["label", "text", "value", "percent", "name"]
        }),
        hovertemplate: hovertemplateAttrs({}, { keys: ["label", "color", "value", "percent", "text"] }),
        hovertemplatefallback: templatefallbackAttrs(),
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["label", "color", "value", "percent", "text"] }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        textposition: {
          valType: "enumerated",
          values: ["inside", "outside", "auto", "none"],
          dflt: "auto",
          arrayOk: true,
          editType: "plot"
        },
        textfont: extendFlat({}, textFontAttrs, {}),
        insidetextorientation: {
          valType: "enumerated",
          values: ["horizontal", "radial", "tangential", "auto"],
          dflt: "auto",
          editType: "plot"
        },
        insidetextfont: extendFlat({}, textFontAttrs, {}),
        outsidetextfont: extendFlat({}, textFontAttrs, {}),
        automargin: {
          valType: "boolean",
          dflt: false,
          editType: "plot"
        },
        showlegend: extendFlat({}, baseAttrs.showlegend, {
          arrayOk: true
        }),
        legend: extendFlat({}, baseAttrs.legend, {
          arrayOk: true
        }),
        title: {
          text: {
            valType: "string",
            dflt: "",
            editType: "plot"
          },
          font: extendFlat({}, textFontAttrs, {}),
          position: {
            valType: "enumerated",
            values: [
              "top left",
              "top center",
              "top right",
              "middle center",
              "bottom left",
              "bottom center",
              "bottom right"
            ],
            editType: "plot"
          },
          editType: "plot"
        },
        // position and shape
        domain: domainAttrs({ name: "pie", trace: true, editType: "calc" }),
        hole: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0,
          editType: "calc"
        },
        // ordering and direction
        sort: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        },
        direction: {
          /**
           * there are two common conventions, both of which place the first
           * (largest, if sorted) slice with its left edge at 12 o'clock but
           * succeeding slices follow either cw or ccw from there.
           *
           * see http://visage.co/data-visualization-101-pie-charts/
           */
          valType: "enumerated",
          values: ["clockwise", "counterclockwise"],
          dflt: "counterclockwise",
          editType: "calc"
        },
        rotation: {
          valType: "angle",
          dflt: 0,
          editType: "calc"
        },
        pull: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0,
          arrayOk: true,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/pie/defaults.js
  var require_defaults31 = __commonJS({
    "src/traces/pie/defaults.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var attributes = require_attributes35();
      var handleDomainDefaults = require_domain().defaults;
      var handleText = require_defaults19().handleText;
      var coercePattern = require_lib().coercePattern;
      function handleLabelsAndValues(labels, values) {
        var hasLabels = Lib.isArrayOrTypedArray(labels);
        var hasValues = Lib.isArrayOrTypedArray(values);
        var len = Math.min(hasLabels ? labels.length : Infinity, hasValues ? values.length : Infinity);
        if (!isFinite(len)) len = 0;
        if (len && hasValues) {
          var hasPositive;
          for (var i = 0; i < len; i++) {
            var v = values[i];
            if (isNumeric(v) && v > 0) {
              hasPositive = true;
              break;
            }
          }
          if (!hasPositive) len = 0;
        }
        return {
          hasLabels,
          hasValues,
          len
        };
      }
      function handleMarkerDefaults(traceIn, traceOut, layout, coerce, isPie) {
        var lineWidth = coerce("marker.line.width");
        if (lineWidth) {
          coerce(
            "marker.line.color",
            isPie ? void 0 : layout.paper_bgcolor
            // case of funnelarea, sunburst, icicle, treemap
          );
        }
        var markerColors = coerce("marker.colors");
        coercePattern(coerce, "marker.pattern", markerColors);
        if (traceIn.marker && !traceOut.marker.pattern.fgcolor) traceOut.marker.pattern.fgcolor = traceIn.marker.colors;
        if (!traceOut.marker.pattern.bgcolor) traceOut.marker.pattern.bgcolor = layout.paper_bgcolor;
      }
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var labels = coerce("labels");
        var values = coerce("values");
        var res = handleLabelsAndValues(labels, values);
        var len = res.len;
        traceOut._hasLabels = res.hasLabels;
        traceOut._hasValues = res.hasValues;
        if (!traceOut._hasLabels && traceOut._hasValues) {
          coerce("label0");
          coerce("dlabel");
        }
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        handleMarkerDefaults(traceIn, traceOut, layout, coerce, true);
        coerce("scalegroup");
        var textData = coerce("text");
        var textTemplate = coerce("texttemplate");
        coerce("texttemplatefallback");
        var textInfo;
        if (!textTemplate) textInfo = coerce("textinfo", Lib.isArrayOrTypedArray(textData) ? "text+percent" : "percent");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        if (textTemplate || textInfo && textInfo !== "none") {
          var textposition = coerce("textposition");
          handleText(traceIn, traceOut, layout, coerce, textposition, {
            moduleHasSelected: false,
            moduleHasUnselected: false,
            moduleHasConstrain: false,
            moduleHasCliponaxis: false,
            moduleHasTextangle: false,
            moduleHasInsideanchor: false
          });
          var hasBoth = Array.isArray(textposition) || textposition === "auto";
          var hasOutside = hasBoth || textposition === "outside";
          if (hasOutside) {
            coerce("automargin");
          }
          if (textposition === "inside" || textposition === "auto" || Array.isArray(textposition)) {
            coerce("insidetextorientation");
          }
        } else if (textInfo === "none") {
          coerce("textposition", "none");
        }
        handleDomainDefaults(traceOut, layout, coerce);
        var hole = coerce("hole");
        var title = coerce("title.text");
        if (title) {
          var titlePosition = coerce("title.position", hole ? "middle center" : "top center");
          if (!hole && titlePosition === "middle center") traceOut.title.position = "top center";
          Lib.coerceFont(coerce, "title.font", layout.font);
        }
        coerce("sort");
        coerce("direction");
        coerce("rotation");
        coerce("pull");
      }
      module.exports = {
        handleLabelsAndValues,
        handleMarkerDefaults,
        supplyDefaults
      };
    }
  });

  // src/traces/pie/layout_attributes.js
  var require_layout_attributes12 = __commonJS({
    "src/traces/pie/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        hiddenlabels: {
          valType: "data_array",
          editType: "calc"
        },
        piecolorway: {
          valType: "colorlist",
          editType: "calc"
        },
        extendpiecolors: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/pie/layout_defaults.js
  var require_layout_defaults11 = __commonJS({
    "src/traces/pie/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes12();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        coerce("hiddenlabels");
        coerce("piecolorway", layoutOut.colorway);
        coerce("extendpiecolors");
      };
    }
  });

  // src/traces/pie/calc.js
  var require_calc16 = __commonJS({
    "src/traces/pie/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var tinycolor = require_tinycolor();
      var Color2 = require_color();
      var extendedColorWayList = {};
      function calc(gd, trace) {
        var cd = [];
        var fullLayout = gd._fullLayout;
        var hiddenLabels = fullLayout.hiddenlabels || [];
        var labels = trace.labels;
        var colors = trace.marker.colors || [];
        var vals = trace.values;
        var len = trace._length;
        var hasValues = trace._hasValues && len;
        var i, pt;
        if (trace.dlabel) {
          labels = new Array(len);
          for (i = 0; i < len; i++) {
            labels[i] = String(trace.label0 + i * trace.dlabel);
          }
        }
        var allThisTraceLabels = {};
        var pullColor = makePullColorFn(fullLayout["_" + trace.type + "colormap"]);
        var vTotal = 0;
        var isAggregated = false;
        for (i = 0; i < len; i++) {
          var v, label, hidden;
          if (hasValues) {
            v = vals[i];
            if (!isNumeric(v)) continue;
            v = +v;
          } else v = 1;
          label = labels[i];
          if (label === void 0 || label === "") label = i;
          label = String(label);
          var thisLabelIndex = allThisTraceLabels[label];
          if (thisLabelIndex === void 0) {
            allThisTraceLabels[label] = cd.length;
            hidden = hiddenLabels.indexOf(label) !== -1;
            if (!hidden) vTotal += v;
            cd.push({
              v,
              label,
              color: pullColor(colors[i], label),
              i,
              pts: [i],
              hidden
            });
          } else {
            isAggregated = true;
            pt = cd[thisLabelIndex];
            pt.v += v;
            pt.pts.push(i);
            if (!pt.hidden) vTotal += v;
            if (pt.color === false && colors[i]) {
              pt.color = pullColor(colors[i], label);
            }
          }
        }
        cd = cd.filter(function(elem) {
          return elem.v >= 0;
        });
        var shouldSort = trace.type === "funnelarea" ? isAggregated : trace.sort;
        if (shouldSort) cd.sort(function(a, b) {
          return b.v - a.v;
        });
        if (cd[0]) cd[0].vTotal = vTotal;
        return cd;
      }
      function makePullColorFn(colorMap) {
        return function pullColor(color2, id) {
          if (!color2) return false;
          color2 = tinycolor(color2);
          if (!color2.isValid()) return false;
          color2 = Color2.addOpacity(color2, color2.getAlpha());
          if (!colorMap[id]) colorMap[id] = color2;
          return color2;
        };
      }
      function crossTraceCalc(gd, plotinfo) {
        var desiredType = (plotinfo || {}).type;
        if (!desiredType) desiredType = "pie";
        var fullLayout = gd._fullLayout;
        var calcdata = gd.calcdata;
        var colorWay = fullLayout[desiredType + "colorway"];
        var colorMap = fullLayout["_" + desiredType + "colormap"];
        if (fullLayout["extend" + desiredType + "colors"]) {
          colorWay = generateExtendedColors(colorWay, extendedColorWayList);
        }
        var dfltColorCount = 0;
        for (var i = 0; i < calcdata.length; i++) {
          var cd = calcdata[i];
          var traceType = cd[0].trace.type;
          if (traceType !== desiredType) continue;
          for (var j = 0; j < cd.length; j++) {
            var pt = cd[j];
            if (pt.color === false) {
              if (colorMap[pt.label]) {
                pt.color = colorMap[pt.label];
              } else {
                colorMap[pt.label] = pt.color = colorWay[dfltColorCount % colorWay.length];
                dfltColorCount++;
              }
            }
          }
        }
      }
      function generateExtendedColors(colorList, extendedColorWays) {
        var i;
        var colorString = JSON.stringify(colorList);
        var colors = extendedColorWays[colorString];
        if (!colors) {
          colors = colorList.slice();
          for (i = 0; i < colorList.length; i++) {
            colors.push(tinycolor(colorList[i]).lighten(20).toHexString());
          }
          for (i = 0; i < colorList.length; i++) {
            colors.push(tinycolor(colorList[i]).darken(20).toHexString());
          }
          extendedColorWays[colorString] = colors;
        }
        return colors;
      }
      module.exports = {
        calc,
        crossTraceCalc,
        makePullColorFn,
        generateExtendedColors
      };
    }
  });

  // src/traces/pie/event_data.js
  var require_event_data8 = __commonJS({
    "src/traces/pie/event_data.js"(exports, module) {
      "use strict";
      var appendArrayMultiPointValues = require_helpers2().appendArrayMultiPointValues;
      module.exports = function eventData(pt, trace) {
        var out = {
          curveNumber: trace.index,
          pointNumbers: pt.pts,
          data: trace._input,
          fullData: trace,
          label: pt.label,
          color: pt.color,
          value: pt.v,
          percent: pt.percent,
          text: pt.text,
          bbox: pt.bbox,
          // pt.v (and pt.i below) for backward compatibility
          v: pt.v
        };
        if (pt.pts.length === 1) out.pointNumber = out.i = pt.pts[0];
        appendArrayMultiPointValues(out, trace, pt.pts);
        if (trace.type === "funnelarea") {
          delete out.v;
          delete out.i;
        }
        return out;
      };
    }
  });

  // src/traces/pie/plot.js
  var require_plot12 = __commonJS({
    "src/traces/pie/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Plots = require_plots();
      var Fx = require_fx();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var strScale = Lib.strScale;
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var uniformText = require_uniform_text();
      var recordMinTextSize = uniformText.recordMinTextSize;
      var clearMinTextSize = uniformText.clearMinTextSize;
      var TEXTPAD = require_constants9().TEXTPAD;
      var helpers = require_helpers4();
      var eventData = require_event_data8();
      var isValidTextValue = require_lib().isValidTextValue;
      function plot(gd, cdModule) {
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        clearMinTextSize("pie", fullLayout);
        prerenderTitles(cdModule, gd);
        layoutAreas(cdModule, gs);
        var plotGroups = Lib.makeTraceGroups(fullLayout._pielayer, cdModule, "trace").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          setCoords(cd);
          plotGroup.attr("stroke-linejoin", "round");
          plotGroup.each(function() {
            var slices = d3.select(this).selectAll("g.slice").data(cd);
            slices.enter().append("g").classed("slice", true);
            slices.exit().remove();
            var quadrants = [
              [[], []],
              // y<0: x<0, x>=0
              [[], []]
              // y>=0: x<0, x>=0
            ];
            var hasOutsideText = false;
            slices.each(function(pt, i) {
              if (pt.hidden) {
                d3.select(this).selectAll("path,g").remove();
                return;
              }
              pt.pointNumber = pt.i;
              pt.curveNumber = trace.index;
              quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt);
              var cx = cd0.cx;
              var cy = cd0.cy;
              var sliceTop = d3.select(this);
              var slicePath = sliceTop.selectAll("path.surface").data([pt]);
              slicePath.enter().append("path").classed("surface", true).style({ "pointer-events": isStatic ? "none" : "all" });
              sliceTop.call(attachFxHandlers, gd, cd);
              if (trace.pull) {
                var pull = +helpers.castOption(trace.pull, pt.pts) || 0;
                if (pull > 0) {
                  cx += pull * pt.pxmid[0];
                  cy += pull * pt.pxmid[1];
                }
              }
              pt.cxFinal = cx;
              pt.cyFinal = cy;
              function arc(start, finish, cw, scale) {
                var dx = scale * (finish[0] - start[0]);
                var dy = scale * (finish[1] - start[1]);
                return "a" + scale * cd0.r + "," + scale * cd0.r + " 0 " + pt.largeArc + (cw ? " 1 " : " 0 ") + dx + "," + dy;
              }
              var hole = trace.hole;
              if (pt.v === cd0.vTotal) {
                var outerCircle = "M" + (cx + pt.px0[0]) + "," + (cy + pt.px0[1]) + arc(pt.px0, pt.pxmid, true, 1) + arc(pt.pxmid, pt.px0, true, 1) + "Z";
                if (hole) {
                  slicePath.attr(
                    "d",
                    "M" + (cx + hole * pt.px0[0]) + "," + (cy + hole * pt.px0[1]) + arc(pt.px0, pt.pxmid, false, hole) + arc(pt.pxmid, pt.px0, false, hole) + "Z" + outerCircle
                  );
                } else slicePath.attr("d", outerCircle);
              } else {
                var outerArc = arc(pt.px0, pt.px1, true, 1);
                if (hole) {
                  var rim = 1 - hole;
                  slicePath.attr(
                    "d",
                    "M" + (cx + hole * pt.px1[0]) + "," + (cy + hole * pt.px1[1]) + arc(pt.px1, pt.px0, false, hole) + "l" + rim * pt.px0[0] + "," + rim * pt.px0[1] + outerArc + "Z"
                  );
                } else {
                  slicePath.attr("d", "M" + cx + "," + cy + "l" + pt.px0[0] + "," + pt.px0[1] + outerArc + "Z");
                }
              }
              formatSliceLabel(gd, pt, cd0);
              var textPosition = helpers.castOption(trace.textposition, pt.pts);
              var sliceTextGroup = sliceTop.selectAll("g.slicetext").data(pt.text && textPosition !== "none" ? [0] : []);
              sliceTextGroup.enter().append("g").classed("slicetext", true);
              sliceTextGroup.exit().remove();
              sliceTextGroup.each(function() {
                var sliceText = Lib.ensureSingle(d3.select(this), "text", "", function(s) {
                  s.attr("data-notex", 1);
                });
                var font = Lib.ensureUniformFontSize(
                  gd,
                  textPosition === "outside" ? determineOutsideTextFont(trace, pt, fullLayout.font) : determineInsideTextFont(trace, pt, fullLayout.font)
                );
                sliceText.text(pt.text).attr({
                  class: "slicetext",
                  transform: "",
                  "text-anchor": "middle"
                }).call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
                var textBB = Drawing.bBox(sliceText.node());
                var transform;
                if (textPosition === "outside") {
                  transform = transformOutsideText(textBB, pt);
                } else {
                  transform = transformInsideText(textBB, pt, cd0);
                  if (textPosition === "auto" && transform.scale < 1) {
                    var newFont = Lib.ensureUniformFontSize(gd, trace.outsidetextfont);
                    sliceText.call(Drawing.font, newFont);
                    textBB = Drawing.bBox(sliceText.node());
                    transform = transformOutsideText(textBB, pt);
                  }
                }
                var textPosAngle = transform.textPosAngle;
                var textXY = textPosAngle === void 0 ? pt.pxmid : getCoords(cd0.r, textPosAngle);
                transform.targetX = cx + textXY[0] * transform.rCenter + (transform.x || 0);
                transform.targetY = cy + textXY[1] * transform.rCenter + (transform.y || 0);
                computeTransform(transform, textBB);
                if (transform.outside) {
                  var targetY = transform.targetY;
                  pt.yLabelMin = targetY - textBB.height / 2;
                  pt.yLabelMid = targetY;
                  pt.yLabelMax = targetY + textBB.height / 2;
                  pt.labelExtraX = 0;
                  pt.labelExtraY = 0;
                  hasOutsideText = true;
                }
                transform.fontSize = font.size;
                recordMinTextSize(trace.type, transform, fullLayout);
                cd[i].transform = transform;
                Lib.setTransormAndDisplay(sliceText, transform);
              });
            });
            var titleTextGroup = d3.select(this).selectAll("g.titletext").data(trace.title.text ? [0] : []);
            titleTextGroup.enter().append("g").classed("titletext", true);
            titleTextGroup.exit().remove();
            titleTextGroup.each(function() {
              var titleText = Lib.ensureSingle(d3.select(this), "text", "", function(s) {
                s.attr("data-notex", 1);
              });
              var txt = trace.title.text;
              if (trace._meta) {
                txt = Lib.templateString(txt, trace._meta);
              }
              titleText.text(txt).attr({
                class: "titletext",
                transform: "",
                "text-anchor": "middle"
              }).call(Drawing.font, trace.title.font).call(svgTextUtils.convertToTspans, gd);
              var transform;
              if (trace.title.position === "middle center") {
                transform = positionTitleInside(cd0);
              } else {
                transform = positionTitleOutside(cd0, gs);
              }
              titleText.attr(
                "transform",
                strTranslate(transform.x, transform.y) + strScale(Math.min(1, transform.scale)) + strTranslate(transform.tx, transform.ty)
              );
            });
            if (hasOutsideText) scootLabels(quadrants, trace);
            plotTextLines(slices, trace);
            if (hasOutsideText && trace.automargin) {
              var traceBbox = Drawing.bBox(plotGroup.node());
              var domain = trace.domain;
              var vpw = gs.w * (domain.x[1] - domain.x[0]);
              var vph = gs.h * (domain.y[1] - domain.y[0]);
              var xgap = (0.5 * vpw - cd0.r) / gs.w;
              var ygap = (0.5 * vph - cd0.r) / gs.h;
              Plots.autoMargin(gd, "pie." + trace.uid + ".automargin", {
                xl: domain.x[0] - xgap,
                xr: domain.x[1] + xgap,
                yb: domain.y[0] - ygap,
                yt: domain.y[1] + ygap,
                l: Math.max(cd0.cx - cd0.r - traceBbox.left, 0),
                r: Math.max(traceBbox.right - (cd0.cx + cd0.r), 0),
                b: Math.max(traceBbox.bottom - (cd0.cy + cd0.r), 0),
                t: Math.max(cd0.cy - cd0.r - traceBbox.top, 0),
                pad: 5
              });
            }
          });
        });
        setTimeout(function() {
          plotGroups.selectAll("tspan").each(function() {
            var s = d3.select(this);
            if (s.attr("dy")) s.attr("dy", s.attr("dy"));
          });
        }, 0);
      }
      function plotTextLines(slices, trace) {
        slices.each(function(pt) {
          var sliceTop = d3.select(this);
          if (!pt.labelExtraX && !pt.labelExtraY) {
            sliceTop.select("path.textline").remove();
            return;
          }
          var sliceText = sliceTop.select("g.slicetext text");
          pt.transform.targetX += pt.labelExtraX;
          pt.transform.targetY += pt.labelExtraY;
          Lib.setTransormAndDisplay(sliceText, pt.transform);
          var lineStartX = pt.cxFinal + pt.pxmid[0];
          var lineStartY = pt.cyFinal + pt.pxmid[1];
          var textLinePath = "M" + lineStartX + "," + lineStartY;
          var finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4;
          if (pt.labelExtraX) {
            var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0];
            var yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]);
            if (Math.abs(yFromX) > Math.abs(yNet)) {
              textLinePath += "l" + yNet * pt.pxmid[0] / pt.pxmid[1] + "," + yNet + "H" + (lineStartX + pt.labelExtraX + finalX);
            } else {
              textLinePath += "l" + pt.labelExtraX + "," + yFromX + "v" + (yNet - yFromX) + "h" + finalX;
            }
          } else {
            textLinePath += "V" + (pt.yLabelMid + pt.labelExtraY) + "h" + finalX;
          }
          Lib.ensureSingle(sliceTop, "path", "textline").call(Color2.stroke, trace.outsidetextfont.color).attr({
            "stroke-width": Math.min(2, trace.outsidetextfont.size / 8),
            d: textLinePath,
            fill: "none"
          });
        });
      }
      function attachFxHandlers(sliceTop, gd, cd) {
        var cd0 = cd[0];
        var cx = cd0.cx;
        var cy = cd0.cy;
        var trace = cd0.trace;
        var isFunnelArea = trace.type === "funnelarea";
        if (!("_hasHoverLabel" in trace)) trace._hasHoverLabel = false;
        if (!("_hasHoverEvent" in trace)) trace._hasHoverEvent = false;
        sliceTop.on("mouseover", function(pt) {
          var fullLayout2 = gd._fullLayout;
          var trace2 = gd._fullData[trace.index];
          if (gd._dragging || fullLayout2.hovermode === false) return;
          var hoverinfo = trace2.hoverinfo;
          if (Array.isArray(hoverinfo)) {
            hoverinfo = Fx.castHoverinfo(
              {
                hoverinfo: [helpers.castOption(hoverinfo, pt.pts)],
                _module: trace._module
              },
              fullLayout2,
              0
            );
          }
          if (hoverinfo === "all") hoverinfo = "label+text+value+percent+name";
          if (trace2.hovertemplate || hoverinfo !== "none" && hoverinfo !== "skip" && hoverinfo) {
            var rInscribed = pt.rInscribed || 0;
            var hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed);
            var hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed);
            var separators = fullLayout2.separators;
            var text = [];
            if (hoverinfo && hoverinfo.indexOf("label") !== -1) text.push(pt.label);
            pt.text = helpers.castOption(trace2.hovertext || trace2.text, pt.pts);
            if (hoverinfo && hoverinfo.indexOf("text") !== -1) {
              var tx = pt.text;
              if (Lib.isValidTextValue(tx)) text.push(tx);
            }
            pt.value = pt.v;
            pt.valueLabel = helpers.formatPieValue(pt.v, separators);
            if (hoverinfo && hoverinfo.indexOf("value") !== -1) text.push(pt.valueLabel);
            pt.percent = pt.v / cd0.vTotal;
            pt.percentLabel = helpers.formatPiePercent(pt.percent, separators);
            if (hoverinfo && hoverinfo.indexOf("percent") !== -1) text.push(pt.percentLabel);
            var hoverLabel = trace2.hoverlabel;
            var hoverFont = hoverLabel.font;
            var bbox = [];
            Fx.loneHover(
              {
                trace,
                x0: hoverCenterX - rInscribed * cd0.r,
                x1: hoverCenterX + rInscribed * cd0.r,
                y: hoverCenterY,
                _x0: isFunnelArea ? cx + pt.TL[0] : hoverCenterX - rInscribed * cd0.r,
                _x1: isFunnelArea ? cx + pt.TR[0] : hoverCenterX + rInscribed * cd0.r,
                _y0: isFunnelArea ? cy + pt.TL[1] : hoverCenterY - rInscribed * cd0.r,
                _y1: isFunnelArea ? cy + pt.BL[1] : hoverCenterY + rInscribed * cd0.r,
                text: text.join("<br>"),
                name: trace2.hovertemplate || hoverinfo.indexOf("name") !== -1 ? trace2.name : void 0,
                idealAlign: pt.pxmid[0] < 0 ? "left" : "right",
                color: helpers.castOption(hoverLabel.bgcolor, pt.pts) || pt.color,
                borderColor: helpers.castOption(hoverLabel.bordercolor, pt.pts),
                fontFamily: helpers.castOption(hoverFont.family, pt.pts),
                fontSize: helpers.castOption(hoverFont.size, pt.pts),
                fontColor: helpers.castOption(hoverFont.color, pt.pts),
                nameLength: helpers.castOption(hoverLabel.namelength, pt.pts),
                textAlign: helpers.castOption(hoverLabel.align, pt.pts),
                hovertemplate: helpers.castOption(trace2.hovertemplate, pt.pts),
                hovertemplateLabels: pt,
                eventData: [eventData(pt, trace2)]
              },
              {
                container: fullLayout2._hoverlayer.node(),
                outerContainer: fullLayout2._paper.node(),
                gd,
                inOut_bbox: bbox
              }
            );
            pt.bbox = bbox[0];
            trace._hasHoverLabel = true;
          }
          trace._hasHoverEvent = true;
          gd.emit("plotly_hover", {
            points: [eventData(pt, trace2)],
            event: d3.event
          });
        });
        sliceTop.on("mouseout", function(evt) {
          var fullLayout2 = gd._fullLayout;
          var trace2 = gd._fullData[trace.index];
          var pt = d3.select(this).datum();
          if (trace._hasHoverEvent) {
            evt.originalEvent = d3.event;
            gd.emit("plotly_unhover", {
              points: [eventData(pt, trace2)],
              event: d3.event
            });
            trace._hasHoverEvent = false;
          }
          if (trace._hasHoverLabel) {
            Fx.loneUnhover(fullLayout2._hoverlayer.node());
            trace._hasHoverLabel = false;
          }
        });
        sliceTop.on("click", function(pt) {
          var fullLayout2 = gd._fullLayout;
          var trace2 = gd._fullData[trace.index];
          if (gd._dragging || fullLayout2.hovermode === false) return;
          gd._hoverdata = [eventData(pt, trace2)];
          Fx.click(gd, d3.event);
        });
      }
      function determineOutsideTextFont(trace, pt, layoutFont) {
        var color2 = helpers.castOption(trace.outsidetextfont.color, pt.pts) || helpers.castOption(trace.textfont.color, pt.pts) || layoutFont.color;
        var family = helpers.castOption(trace.outsidetextfont.family, pt.pts) || helpers.castOption(trace.textfont.family, pt.pts) || layoutFont.family;
        var size = helpers.castOption(trace.outsidetextfont.size, pt.pts) || helpers.castOption(trace.textfont.size, pt.pts) || layoutFont.size;
        var weight = helpers.castOption(trace.outsidetextfont.weight, pt.pts) || helpers.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight;
        var style = helpers.castOption(trace.outsidetextfont.style, pt.pts) || helpers.castOption(trace.textfont.style, pt.pts) || layoutFont.style;
        var variant = helpers.castOption(trace.outsidetextfont.variant, pt.pts) || helpers.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant;
        var textcase = helpers.castOption(trace.outsidetextfont.textcase, pt.pts) || helpers.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase;
        var lineposition = helpers.castOption(trace.outsidetextfont.lineposition, pt.pts) || helpers.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition;
        var shadow = helpers.castOption(trace.outsidetextfont.shadow, pt.pts) || helpers.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow;
        return {
          color: color2,
          family,
          size,
          weight,
          style,
          variant,
          textcase,
          lineposition,
          shadow
        };
      }
      function determineInsideTextFont(trace, pt, layoutFont) {
        var customColor = helpers.castOption(trace.insidetextfont.color, pt.pts);
        if (!customColor && trace._input.textfont) {
          customColor = helpers.castOption(trace._input.textfont.color, pt.pts);
        }
        var family = helpers.castOption(trace.insidetextfont.family, pt.pts) || helpers.castOption(trace.textfont.family, pt.pts) || layoutFont.family;
        var size = helpers.castOption(trace.insidetextfont.size, pt.pts) || helpers.castOption(trace.textfont.size, pt.pts) || layoutFont.size;
        var weight = helpers.castOption(trace.insidetextfont.weight, pt.pts) || helpers.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight;
        var style = helpers.castOption(trace.insidetextfont.style, pt.pts) || helpers.castOption(trace.textfont.style, pt.pts) || layoutFont.style;
        var variant = helpers.castOption(trace.insidetextfont.variant, pt.pts) || helpers.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant;
        var textcase = helpers.castOption(trace.insidetextfont.textcase, pt.pts) || helpers.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase;
        var lineposition = helpers.castOption(trace.insidetextfont.lineposition, pt.pts) || helpers.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition;
        var shadow = helpers.castOption(trace.insidetextfont.shadow, pt.pts) || helpers.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow;
        return {
          color: customColor || Color2.contrast(pt.color),
          family,
          size,
          weight,
          style,
          variant,
          textcase,
          lineposition,
          shadow
        };
      }
      function prerenderTitles(cdModule, gd) {
        var cd0, trace;
        for (var i = 0; i < cdModule.length; i++) {
          cd0 = cdModule[i][0];
          trace = cd0.trace;
          if (trace.title.text) {
            var txt = trace.title.text;
            if (trace._meta) {
              txt = Lib.templateString(txt, trace._meta);
            }
            var dummyTitle = Drawing.tester.append("text").attr("data-notex", 1).text(txt).call(Drawing.font, trace.title.font).call(svgTextUtils.convertToTspans, gd);
            var bBox = Drawing.bBox(dummyTitle.node(), true);
            cd0.titleBox = {
              width: bBox.width,
              height: bBox.height
            };
            dummyTitle.remove();
          }
        }
      }
      function transformInsideText(textBB, pt, cd0) {
        var r = cd0.r || pt.rpx1;
        var rInscribed = pt.rInscribed;
        var isEmpty = pt.startangle === pt.stopangle;
        if (isEmpty) {
          return {
            rCenter: 1 - rInscribed,
            scale: 0,
            rotate: 0,
            textPosAngle: 0
          };
        }
        var ring = pt.ring;
        var isCircle = ring === 1 && Math.abs(pt.startangle - pt.stopangle) === Math.PI * 2;
        var halfAngle = pt.halfangle;
        var midAngle = pt.midangle;
        var orientation = cd0.trace.insidetextorientation;
        var isHorizontal = orientation === "horizontal";
        var isTangential = orientation === "tangential";
        var isRadial = orientation === "radial";
        var isAuto = orientation === "auto";
        var allTransforms = [];
        var newT;
        if (!isAuto) {
          var considerCrossing = function(angle, key) {
            if (isCrossing(pt, angle)) {
              var dStart = Math.abs(angle - pt.startangle);
              var dStop = Math.abs(angle - pt.stopangle);
              var closestEdge = dStart < dStop ? dStart : dStop;
              if (key === "tan") {
                newT = calcTanTransform(textBB, r, ring, closestEdge, 0);
              } else {
                newT = calcRadTransform(textBB, r, ring, closestEdge, Math.PI / 2);
              }
              newT.textPosAngle = angle;
              allTransforms.push(newT);
            }
          };
          var i;
          if (isHorizontal || isTangential) {
            for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * i, "tan");
            for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1), "tan");
          }
          if (isHorizontal || isRadial) {
            for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1.5), "rad");
            for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 0.5), "rad");
          }
        }
        if (isCircle || isAuto || isHorizontal) {
          var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height);
          newT = {
            scale: rInscribed * r * 2 / textDiameter,
            // and the center position and rotation in this case
            rCenter: 1 - rInscribed,
            rotate: 0
          };
          newT.textPosAngle = (pt.startangle + pt.stopangle) / 2;
          if (newT.scale >= 1) return newT;
          allTransforms.push(newT);
        }
        if (isAuto || isRadial) {
          newT = calcRadTransform(textBB, r, ring, halfAngle, midAngle);
          newT.textPosAngle = (pt.startangle + pt.stopangle) / 2;
          allTransforms.push(newT);
        }
        if (isAuto || isTangential) {
          newT = calcTanTransform(textBB, r, ring, halfAngle, midAngle);
          newT.textPosAngle = (pt.startangle + pt.stopangle) / 2;
          allTransforms.push(newT);
        }
        var id = 0;
        var maxScale = 0;
        for (var k = 0; k < allTransforms.length; k++) {
          var s = allTransforms[k].scale;
          if (maxScale < s) {
            maxScale = s;
            id = k;
          }
          if (!isAuto && maxScale >= 1) {
            break;
          }
        }
        return allTransforms[id];
      }
      function isCrossing(pt, angle) {
        var start = pt.startangle;
        var stop = pt.stopangle;
        return start > angle && angle > stop || start < angle && angle < stop;
      }
      function calcRadTransform(textBB, r, ring, halfAngle, midAngle) {
        r = Math.max(0, r - 2 * TEXTPAD);
        var a = textBB.width / textBB.height;
        var s = calcMaxHalfSize(a, halfAngle, r, ring);
        return {
          scale: s * 2 / textBB.height,
          rCenter: calcRCenter(a, s / r),
          rotate: calcRotate(midAngle)
        };
      }
      function calcTanTransform(textBB, r, ring, halfAngle, midAngle) {
        r = Math.max(0, r - 2 * TEXTPAD);
        var a = textBB.height / textBB.width;
        var s = calcMaxHalfSize(a, halfAngle, r, ring);
        return {
          scale: s * 2 / textBB.width,
          rCenter: calcRCenter(a, s / r),
          rotate: calcRotate(midAngle + Math.PI / 2)
        };
      }
      function calcRCenter(a, b) {
        return Math.cos(b) - a * b;
      }
      function calcRotate(t) {
        return (180 / Math.PI * t + 720) % 180 - 90;
      }
      function calcMaxHalfSize(a, halfAngle, r, ring) {
        var q = a + 1 / (2 * Math.tan(halfAngle));
        return r * Math.min(1 / (Math.sqrt(q * q + 0.5) + q), ring / (Math.sqrt(a * a + ring / 2) + a));
      }
      function getInscribedRadiusFraction(pt, cd0) {
        if (pt.v === cd0.vTotal && !cd0.trace.hole) return 1;
        return Math.min(1 / (1 + 1 / Math.sin(pt.halfangle)), pt.ring / 2);
      }
      function transformOutsideText(textBB, pt) {
        var x = pt.pxmid[0];
        var y = pt.pxmid[1];
        var dx = textBB.width / 2;
        var dy = textBB.height / 2;
        if (x < 0) dx *= -1;
        if (y < 0) dy *= -1;
        return {
          scale: 1,
          rCenter: 1,
          rotate: 0,
          x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2,
          y: dy / (1 + x * x / (y * y)),
          outside: true
        };
      }
      function positionTitleInside(cd0) {
        var textDiameter = Math.sqrt(cd0.titleBox.width * cd0.titleBox.width + cd0.titleBox.height * cd0.titleBox.height);
        return {
          x: cd0.cx,
          y: cd0.cy,
          scale: cd0.trace.hole * cd0.r * 2 / textDiameter,
          tx: 0,
          ty: -cd0.titleBox.height / 2 + cd0.trace.title.font.size
        };
      }
      function positionTitleOutside(cd0, plotSize) {
        var scaleX = 1;
        var scaleY = 1;
        var maxPull;
        var trace = cd0.trace;
        var topMiddle = {
          x: cd0.cx,
          y: cd0.cy
        };
        var translate = {
          tx: 0,
          ty: 0
        };
        translate.ty += trace.title.font.size;
        maxPull = getMaxPull(trace);
        if (trace.title.position.indexOf("top") !== -1) {
          topMiddle.y -= (1 + maxPull) * cd0.r;
          translate.ty -= cd0.titleBox.height;
        } else if (trace.title.position.indexOf("bottom") !== -1) {
          topMiddle.y += (1 + maxPull) * cd0.r;
        }
        var rx = applyAspectRatio(cd0.r, cd0.trace.aspectratio);
        var maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2;
        if (trace.title.position.indexOf("left") !== -1) {
          maxWidth = maxWidth + rx;
          topMiddle.x -= (1 + maxPull) * rx;
          translate.tx += cd0.titleBox.width / 2;
        } else if (trace.title.position.indexOf("center") !== -1) {
          maxWidth *= 2;
        } else if (trace.title.position.indexOf("right") !== -1) {
          maxWidth = maxWidth + rx;
          topMiddle.x += (1 + maxPull) * rx;
          translate.tx -= cd0.titleBox.width / 2;
        }
        scaleX = maxWidth / cd0.titleBox.width;
        scaleY = getTitleSpace(cd0, plotSize) / cd0.titleBox.height;
        return {
          x: topMiddle.x,
          y: topMiddle.y,
          scale: Math.min(scaleX, scaleY),
          tx: translate.tx,
          ty: translate.ty
        };
      }
      function applyAspectRatio(x, aspectratio) {
        return x / (aspectratio === void 0 ? 1 : aspectratio);
      }
      function getTitleSpace(cd0, plotSize) {
        var trace = cd0.trace;
        var pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
        return Math.min(cd0.titleBox.height, pieBoxHeight / 2);
      }
      function getMaxPull(trace) {
        var maxPull = trace.pull;
        if (!maxPull) return 0;
        var j;
        if (Lib.isArrayOrTypedArray(maxPull)) {
          maxPull = 0;
          for (j = 0; j < trace.pull.length; j++) {
            if (trace.pull[j] > maxPull) maxPull = trace.pull[j];
          }
        }
        return maxPull;
      }
      function scootLabels(quadrants, trace) {
        var xHalf, yHalf, equatorFirst, farthestX, farthestY, xDiffSign, yDiffSign, thisQuad, oppositeQuad, wholeSide, i, thisQuadOutside, firstOppositeOutsidePt;
        function topFirst(a, b) {
          return a.pxmid[1] - b.pxmid[1];
        }
        function bottomFirst(a, b) {
          return b.pxmid[1] - a.pxmid[1];
        }
        function scootOneLabel(thisPt, prevPt2) {
          if (!prevPt2) prevPt2 = {};
          var prevOuterY = prevPt2.labelExtraY + (yHalf ? prevPt2.yLabelMax : prevPt2.yLabelMin);
          var thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax;
          var thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin;
          var thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]);
          var newExtraY = prevOuterY - thisInnerY;
          var xBuffer, i2, otherPt, otherOuterY, otherOuterX, newExtraX;
          if (newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY;
          if (!Lib.isArrayOrTypedArray(trace.pull)) return;
          for (i2 = 0; i2 < wholeSide.length; i2++) {
            otherPt = wholeSide[i2];
            if (otherPt === thisPt || (helpers.castOption(trace.pull, thisPt.pts) || 0) >= (helpers.castOption(trace.pull, otherPt.pts) || 0)) {
              continue;
            }
            if ((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) {
              otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]);
              newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY;
              if (newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY;
            } else if ((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) {
              xBuffer = 3 * xDiffSign * Math.abs(i2 - wholeSide.indexOf(thisPt));
              otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]);
              newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX;
              if (newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX;
            }
          }
        }
        for (yHalf = 0; yHalf < 2; yHalf++) {
          equatorFirst = yHalf ? topFirst : bottomFirst;
          farthestY = yHalf ? Math.max : Math.min;
          yDiffSign = yHalf ? 1 : -1;
          for (xHalf = 0; xHalf < 2; xHalf++) {
            farthestX = xHalf ? Math.max : Math.min;
            xDiffSign = xHalf ? 1 : -1;
            thisQuad = quadrants[yHalf][xHalf];
            thisQuad.sort(equatorFirst);
            oppositeQuad = quadrants[1 - yHalf][xHalf];
            wholeSide = oppositeQuad.concat(thisQuad);
            thisQuadOutside = [];
            for (i = 0; i < thisQuad.length; i++) {
              if (thisQuad[i].yLabelMid !== void 0) thisQuadOutside.push(thisQuad[i]);
            }
            firstOppositeOutsidePt = false;
            for (i = 0; yHalf && i < oppositeQuad.length; i++) {
              if (oppositeQuad[i].yLabelMid !== void 0) {
                firstOppositeOutsidePt = oppositeQuad[i];
                break;
              }
            }
            for (i = 0; i < thisQuadOutside.length; i++) {
              var prevPt = i && thisQuadOutside[i - 1];
              if (firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt;
              scootOneLabel(thisQuadOutside[i], prevPt);
            }
          }
        }
      }
      function layoutAreas(cdModule, plotSize) {
        var scaleGroups = [];
        for (var i = 0; i < cdModule.length; i++) {
          var cd0 = cdModule[i][0];
          var trace = cd0.trace;
          var domain = trace.domain;
          var width = plotSize.w * (domain.x[1] - domain.x[0]);
          var height = plotSize.h * (domain.y[1] - domain.y[0]);
          if (trace.title.text && trace.title.position !== "middle center") {
            height -= getTitleSpace(cd0, plotSize);
          }
          var rx = width / 2;
          var ry = height / 2;
          if (trace.type === "funnelarea" && !trace.scalegroup) {
            ry /= trace.aspectratio;
          }
          cd0.r = Math.min(rx, ry) / (1 + getMaxPull(trace));
          cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0]) / 2;
          cd0.cy = plotSize.t + plotSize.h * (1 - trace.domain.y[0]) - height / 2;
          if (trace.title.text && trace.title.position.indexOf("bottom") !== -1) {
            cd0.cy -= getTitleSpace(cd0, plotSize);
          }
          if (trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) {
            scaleGroups.push(trace.scalegroup);
          }
        }
        groupScale(cdModule, scaleGroups);
      }
      function groupScale(cdModule, scaleGroups) {
        var cd0, i, trace;
        for (var k = 0; k < scaleGroups.length; k++) {
          var min = Infinity;
          var g = scaleGroups[k];
          for (i = 0; i < cdModule.length; i++) {
            cd0 = cdModule[i][0];
            trace = cd0.trace;
            if (trace.scalegroup === g) {
              var area;
              if (trace.type === "pie") {
                area = cd0.r * cd0.r;
              } else if (trace.type === "funnelarea") {
                var rx, ry;
                if (trace.aspectratio > 1) {
                  rx = cd0.r;
                  ry = rx / trace.aspectratio;
                } else {
                  ry = cd0.r;
                  rx = ry * trace.aspectratio;
                }
                rx *= (1 + trace.baseratio) / 2;
                area = rx * ry;
              }
              min = Math.min(min, area / cd0.vTotal);
            }
          }
          for (i = 0; i < cdModule.length; i++) {
            cd0 = cdModule[i][0];
            trace = cd0.trace;
            if (trace.scalegroup === g) {
              var v = min * cd0.vTotal;
              if (trace.type === "funnelarea") {
                v /= (1 + trace.baseratio) / 2;
                v /= trace.aspectratio;
              }
              cd0.r = Math.sqrt(v);
            }
          }
        }
      }
      function setCoords(cd) {
        var cd0 = cd[0];
        var r = cd0.r;
        var trace = cd0.trace;
        var currentAngle = helpers.getRotationAngle(trace.rotation);
        var angleFactor = 2 * Math.PI / cd0.vTotal;
        var firstPt = "px0";
        var lastPt = "px1";
        var i, cdi, currentCoords;
        if (trace.direction === "counterclockwise") {
          for (i = 0; i < cd.length; i++) {
            if (!cd[i].hidden) break;
          }
          if (i === cd.length) return;
          currentAngle += angleFactor * cd[i].v;
          angleFactor *= -1;
          firstPt = "px1";
          lastPt = "px0";
        }
        currentCoords = getCoords(r, currentAngle);
        for (i = 0; i < cd.length; i++) {
          cdi = cd[i];
          if (cdi.hidden) continue;
          cdi[firstPt] = currentCoords;
          cdi.startangle = currentAngle;
          currentAngle += angleFactor * cdi.v / 2;
          cdi.pxmid = getCoords(r, currentAngle);
          cdi.midangle = currentAngle;
          currentAngle += angleFactor * cdi.v / 2;
          currentCoords = getCoords(r, currentAngle);
          cdi.stopangle = currentAngle;
          cdi[lastPt] = currentCoords;
          cdi.largeArc = cdi.v > cd0.vTotal / 2 ? 1 : 0;
          cdi.halfangle = Math.PI * Math.min(cdi.v / cd0.vTotal, 0.5);
          cdi.ring = 1 - trace.hole;
          cdi.rInscribed = getInscribedRadiusFraction(cdi, cd0);
        }
      }
      function getCoords(r, angle) {
        return [r * Math.sin(angle), -r * Math.cos(angle)];
      }
      function formatSliceLabel(gd, pt, cd0) {
        var fullLayout = gd._fullLayout;
        var trace = cd0.trace;
        var texttemplate = trace.texttemplate;
        var textinfo = trace.textinfo;
        if (!texttemplate && textinfo && textinfo !== "none") {
          var parts = textinfo.split("+");
          var hasFlag = function(flag) {
            return parts.indexOf(flag) !== -1;
          };
          var hasLabel = hasFlag("label");
          var hasText = hasFlag("text");
          var hasValue = hasFlag("value");
          var hasPercent = hasFlag("percent");
          var separators = fullLayout.separators;
          var text;
          text = hasLabel ? [pt.label] : [];
          if (hasText) {
            var tx = helpers.getFirstFilled(trace.text, pt.pts);
            if (isValidTextValue(tx)) text.push(tx);
          }
          if (hasValue) text.push(helpers.formatPieValue(pt.v, separators));
          if (hasPercent) text.push(helpers.formatPiePercent(pt.v / cd0.vTotal, separators));
          pt.text = text.join("<br>");
        }
        function makeTemplateVariables(pt2) {
          return {
            label: pt2.label,
            value: pt2.v,
            valueLabel: helpers.formatPieValue(pt2.v, fullLayout.separators),
            percent: pt2.v / cd0.vTotal,
            percentLabel: helpers.formatPiePercent(pt2.v / cd0.vTotal, fullLayout.separators),
            color: pt2.color,
            text: pt2.text,
            customdata: Lib.castOption(trace, pt2.i, "customdata")
          };
        }
        if (texttemplate) {
          var txt = Lib.castOption(trace, pt.i, "texttemplate");
          if (!txt) {
            pt.text = "";
          } else {
            var obj = makeTemplateVariables(pt);
            var ptTx = helpers.getFirstFilled(trace.text, pt.pts);
            if (isValidTextValue(ptTx) || ptTx === "") obj.text = ptTx;
            pt.text = Lib.texttemplateString({
              data: [obj, trace._meta],
              fallback: trace.texttemplatefallback,
              labels: obj,
              locale: gd._fullLayout._d3locale,
              template: txt
            });
          }
        }
      }
      function computeTransform(transform, textBB) {
        var a = transform.rotate * Math.PI / 180;
        var cosA = Math.cos(a);
        var sinA = Math.sin(a);
        var midX = (textBB.left + textBB.right) / 2;
        var midY = (textBB.top + textBB.bottom) / 2;
        transform.textX = midX * cosA - midY * sinA;
        transform.textY = midX * sinA + midY * cosA;
        transform.noCenter = true;
      }
      module.exports = {
        plot,
        formatSliceLabel,
        transformInsideText,
        determineInsideTextFont,
        positionTitleOutside,
        prerenderTitles,
        layoutAreas,
        attachFxHandlers,
        computeTransform
      };
    }
  });

  // src/traces/pie/style.js
  var require_style12 = __commonJS({
    "src/traces/pie/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var styleOne = require_style_one();
      var resizeText = require_uniform_text().resizeText;
      module.exports = function style(gd) {
        var s = gd._fullLayout._pielayer.selectAll(".trace");
        resizeText(gd, s, "pie");
        s.each(function(cd) {
          var cd0 = cd[0];
          var trace = cd0.trace;
          var traceSelection = d3.select(this);
          traceSelection.style({ opacity: trace.opacity });
          traceSelection.selectAll("path.surface").each(function(pt) {
            d3.select(this).call(styleOne, pt, trace, gd);
          });
        });
      };
    }
  });

  // src/traces/pie/base_plot.js
  var require_base_plot = __commonJS({
    "src/traces/pie/base_plot.js"(exports) {
      "use strict";
      var plots = require_plots();
      exports.name = "pie";
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        plots.plotBasePlot(exports.name, gd, traces, transitionOpts, makeOnCompleteCallback);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        plots.cleanBasePlot(exports.name, newFullData, newFullLayout, oldFullData, oldFullLayout);
      };
    }
  });

  // src/traces/pie/index.js
  var require_pie = __commonJS({
    "src/traces/pie/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes35(),
        supplyDefaults: require_defaults31().supplyDefaults,
        supplyLayoutDefaults: require_layout_defaults11(),
        layoutAttributes: require_layout_attributes12(),
        calc: require_calc16().calc,
        crossTraceCalc: require_calc16().crossTraceCalc,
        plot: require_plot12().plot,
        style: require_style12(),
        styleOne: require_style_one(),
        moduleType: "trace",
        name: "pie",
        basePlotModule: require_base_plot(),
        categories: ["pie-like", "pie", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/pie.js
  var require_pie2 = __commonJS({
    "lib/pie.js"(exports, module) {
      "use strict";
      module.exports = require_pie();
    }
  });

  // src/traces/sunburst/base_plot.js
  var require_base_plot2 = __commonJS({
    "src/traces/sunburst/base_plot.js"(exports) {
      "use strict";
      var plots = require_plots();
      exports.name = "sunburst";
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        plots.plotBasePlot(exports.name, gd, traces, transitionOpts, makeOnCompleteCallback);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        plots.cleanBasePlot(exports.name, newFullData, newFullLayout, oldFullData, oldFullLayout);
      };
    }
  });

  // src/traces/sunburst/constants.js
  var require_constants20 = __commonJS({
    "src/traces/sunburst/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        CLICK_TRANSITION_TIME: 750,
        CLICK_TRANSITION_EASING: "linear",
        eventDataKeys: [
          // string
          "currentPath",
          "root",
          "entry",
          // no need to add 'parent' here
          // percentages i.e. ratios
          "percentRoot",
          "percentEntry",
          "percentParent"
        ]
      };
    }
  });

  // src/traces/sunburst/attributes.js
  var require_attributes36 = __commonJS({
    "src/traces/sunburst/attributes.js"(exports, module) {
      "use strict";
      var baseAttrs = require_attributes2();
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorScaleAttrs = require_attributes8();
      var domainAttrs = require_domain().attributes;
      var pieAttrs = require_attributes35();
      var constants = require_constants20();
      var extendFlat = require_extend().extendFlat;
      var pattern = require_attributes4().pattern;
      module.exports = {
        labels: {
          valType: "data_array",
          editType: "calc"
        },
        parents: {
          valType: "data_array",
          editType: "calc"
        },
        values: {
          valType: "data_array",
          editType: "calc"
        },
        branchvalues: {
          valType: "enumerated",
          values: ["remainder", "total"],
          dflt: "remainder",
          editType: "calc"
        },
        count: {
          valType: "flaglist",
          flags: ["branches", "leaves"],
          dflt: "leaves",
          editType: "calc"
        },
        level: {
          valType: "any",
          editType: "plot",
          anim: true
        },
        maxdepth: {
          valType: "integer",
          editType: "plot",
          dflt: -1
        },
        marker: extendFlat(
          {
            colors: {
              valType: "data_array",
              editType: "calc"
            },
            // colorinheritance: {
            //     valType: 'enumerated',
            //     values: ['per-branch', 'per-label', false]
            // },
            line: {
              color: extendFlat({}, pieAttrs.marker.line.color, {
                dflt: null
              }),
              width: extendFlat({}, pieAttrs.marker.line.width, { dflt: 1 }),
              editType: "calc"
            },
            pattern,
            editType: "calc"
          },
          colorScaleAttrs("marker", {
            colorAttr: "colors",
            anim: false
            // TODO: set to anim: true?
          })
        ),
        leaf: {
          opacity: {
            valType: "number",
            editType: "style",
            min: 0,
            max: 1
          },
          editType: "plot"
        },
        text: pieAttrs.text,
        textinfo: {
          valType: "flaglist",
          flags: ["label", "text", "value", "current path", "percent root", "percent entry", "percent parent"],
          extras: ["none"],
          editType: "plot"
        },
        // TODO: incorporate `label` and `value` in the eventData
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: constants.eventDataKeys.concat(["label", "value"]) }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: pieAttrs.hovertext,
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["label", "text", "value", "name", "current path", "percent root", "percent entry", "percent parent"],
          dflt: "label+text+value+name"
        }),
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        textfont: pieAttrs.textfont,
        insidetextorientation: pieAttrs.insidetextorientation,
        insidetextfont: pieAttrs.insidetextfont,
        outsidetextfont: extendFlat({}, pieAttrs.outsidetextfont, {}),
        rotation: {
          valType: "angle",
          dflt: 0,
          editType: "plot"
        },
        sort: pieAttrs.sort,
        root: {
          color: {
            valType: "color",
            editType: "calc",
            dflt: "rgba(0,0,0,0)"
          },
          editType: "calc"
        },
        domain: domainAttrs({ name: "sunburst", trace: true, editType: "calc" })
      };
    }
  });

  // src/traces/sunburst/layout_attributes.js
  var require_layout_attributes13 = __commonJS({
    "src/traces/sunburst/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        sunburstcolorway: {
          valType: "colorlist",
          editType: "calc"
        },
        extendsunburstcolors: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/sunburst/defaults.js
  var require_defaults32 = __commonJS({
    "src/traces/sunburst/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes36();
      var handleDomainDefaults = require_domain().defaults;
      var handleText = require_defaults19().handleText;
      var handleMarkerDefaults = require_defaults31().handleMarkerDefaults;
      var Colorscale = require_colorscale();
      var hasColorscale = Colorscale.hasColorscale;
      var colorscaleDefaults = Colorscale.handleDefaults;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var labels = coerce("labels");
        var parents = coerce("parents");
        if (!labels || !labels.length || !parents || !parents.length) {
          traceOut.visible = false;
          return;
        }
        var vals = coerce("values");
        if (vals && vals.length) {
          coerce("branchvalues");
        } else {
          coerce("count");
        }
        coerce("level");
        coerce("maxdepth");
        handleMarkerDefaults(traceIn, traceOut, layout, coerce);
        var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, "marker", "colors") || (traceIn.marker || {}).coloraxis;
        if (withColorscale) {
          colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "marker.", cLetter: "c" });
        }
        coerce("leaf.opacity", withColorscale ? 1 : 0.7);
        var text = coerce("text");
        coerce("texttemplate");
        coerce("texttemplatefallback");
        if (!traceOut.texttemplate) coerce("textinfo", Lib.isArrayOrTypedArray(text) ? "text+label" : "label");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var textposition = "auto";
        handleText(traceIn, traceOut, layout, coerce, textposition, {
          moduleHasSelected: false,
          moduleHasUnselected: false,
          moduleHasConstrain: false,
          moduleHasCliponaxis: false,
          moduleHasTextangle: false,
          moduleHasInsideanchor: false
        });
        coerce("insidetextorientation");
        coerce("sort");
        coerce("rotation");
        coerce("root.color");
        handleDomainDefaults(traceOut, layout, coerce);
        traceOut._length = null;
      };
    }
  });

  // src/traces/sunburst/layout_defaults.js
  var require_layout_defaults12 = __commonJS({
    "src/traces/sunburst/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes13();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        coerce("sunburstcolorway", layoutOut.colorway);
        coerce("extendsunburstcolors");
      };
    }
  });

  // node_modules/d3-hierarchy/dist/d3-hierarchy.js
  var require_d3_hierarchy = __commonJS({
    "node_modules/d3-hierarchy/dist/d3-hierarchy.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}));
      })(exports, function(exports2) {
        "use strict";
        function defaultSeparation(a, b) {
          return a.parent === b.parent ? 1 : 2;
        }
        function meanX(children) {
          return children.reduce(meanXReduce, 0) / children.length;
        }
        function meanXReduce(x, c) {
          return x + c.x;
        }
        function maxY(children) {
          return 1 + children.reduce(maxYReduce, 0);
        }
        function maxYReduce(y, c) {
          return Math.max(y, c.y);
        }
        function leafLeft(node) {
          var children;
          while (children = node.children) node = children[0];
          return node;
        }
        function leafRight(node) {
          var children;
          while (children = node.children) node = children[children.length - 1];
          return node;
        }
        function cluster() {
          var separation = defaultSeparation, dx = 1, dy = 1, nodeSize = false;
          function cluster2(root) {
            var previousNode, x = 0;
            root.eachAfter(function(node) {
              var children = node.children;
              if (children) {
                node.x = meanX(children);
                node.y = maxY(children);
              } else {
                node.x = previousNode ? x += separation(node, previousNode) : 0;
                node.y = 0;
                previousNode = node;
              }
            });
            var left = leafLeft(root), right = leafRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
            return root.eachAfter(nodeSize ? function(node) {
              node.x = (node.x - root.x) * dx;
              node.y = (root.y - node.y) * dy;
            } : function(node) {
              node.x = (node.x - x0) / (x1 - x0) * dx;
              node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;
            });
          }
          cluster2.separation = function(x) {
            return arguments.length ? (separation = x, cluster2) : separation;
          };
          cluster2.size = function(x) {
            return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster2) : nodeSize ? null : [dx, dy];
          };
          cluster2.nodeSize = function(x) {
            return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster2) : nodeSize ? [dx, dy] : null;
          };
          return cluster2;
        }
        function count(node) {
          var sum = 0, children = node.children, i = children && children.length;
          if (!i) sum = 1;
          else while (--i >= 0) sum += children[i].value;
          node.value = sum;
        }
        function node_count() {
          return this.eachAfter(count);
        }
        function node_each(callback) {
          var node = this, current, next = [node], children, i, n;
          do {
            current = next.reverse(), next = [];
            while (node = current.pop()) {
              callback(node), children = node.children;
              if (children) for (i = 0, n = children.length; i < n; ++i) {
                next.push(children[i]);
              }
            }
          } while (next.length);
          return this;
        }
        function node_eachBefore(callback) {
          var node = this, nodes = [node], children, i;
          while (node = nodes.pop()) {
            callback(node), children = node.children;
            if (children) for (i = children.length - 1; i >= 0; --i) {
              nodes.push(children[i]);
            }
          }
          return this;
        }
        function node_eachAfter(callback) {
          var node = this, nodes = [node], next = [], children, i, n;
          while (node = nodes.pop()) {
            next.push(node), children = node.children;
            if (children) for (i = 0, n = children.length; i < n; ++i) {
              nodes.push(children[i]);
            }
          }
          while (node = next.pop()) {
            callback(node);
          }
          return this;
        }
        function node_sum(value) {
          return this.eachAfter(function(node) {
            var sum = +value(node.data) || 0, children = node.children, i = children && children.length;
            while (--i >= 0) sum += children[i].value;
            node.value = sum;
          });
        }
        function node_sort(compare) {
          return this.eachBefore(function(node) {
            if (node.children) {
              node.children.sort(compare);
            }
          });
        }
        function node_path(end) {
          var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
          while (start !== ancestor) {
            start = start.parent;
            nodes.push(start);
          }
          var k = nodes.length;
          while (end !== ancestor) {
            nodes.splice(k, 0, end);
            end = end.parent;
          }
          return nodes;
        }
        function leastCommonAncestor(a, b) {
          if (a === b) return a;
          var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
          a = aNodes.pop();
          b = bNodes.pop();
          while (a === b) {
            c = a;
            a = aNodes.pop();
            b = bNodes.pop();
          }
          return c;
        }
        function node_ancestors() {
          var node = this, nodes = [node];
          while (node = node.parent) {
            nodes.push(node);
          }
          return nodes;
        }
        function node_descendants() {
          var nodes = [];
          this.each(function(node) {
            nodes.push(node);
          });
          return nodes;
        }
        function node_leaves() {
          var leaves = [];
          this.eachBefore(function(node) {
            if (!node.children) {
              leaves.push(node);
            }
          });
          return leaves;
        }
        function node_links() {
          var root = this, links = [];
          root.each(function(node) {
            if (node !== root) {
              links.push({ source: node.parent, target: node });
            }
          });
          return links;
        }
        function hierarchy(data, children) {
          var root = new Node(data), valued = +data.value && (root.value = data.value), node, nodes = [root], child, childs, i, n;
          if (children == null) children = defaultChildren;
          while (node = nodes.pop()) {
            if (valued) node.value = +node.data.value;
            if ((childs = children(node.data)) && (n = childs.length)) {
              node.children = new Array(n);
              for (i = n - 1; i >= 0; --i) {
                nodes.push(child = node.children[i] = new Node(childs[i]));
                child.parent = node;
                child.depth = node.depth + 1;
              }
            }
          }
          return root.eachBefore(computeHeight);
        }
        function node_copy() {
          return hierarchy(this).eachBefore(copyData);
        }
        function defaultChildren(d) {
          return d.children;
        }
        function copyData(node) {
          node.data = node.data.data;
        }
        function computeHeight(node) {
          var height = 0;
          do
            node.height = height;
          while ((node = node.parent) && node.height < ++height);
        }
        function Node(data) {
          this.data = data;
          this.depth = this.height = 0;
          this.parent = null;
        }
        Node.prototype = hierarchy.prototype = {
          constructor: Node,
          count: node_count,
          each: node_each,
          eachAfter: node_eachAfter,
          eachBefore: node_eachBefore,
          sum: node_sum,
          sort: node_sort,
          path: node_path,
          ancestors: node_ancestors,
          descendants: node_descendants,
          leaves: node_leaves,
          links: node_links,
          copy: node_copy
        };
        var slice = Array.prototype.slice;
        function shuffle(array) {
          var m = array.length, t, i;
          while (m) {
            i = Math.random() * m-- | 0;
            t = array[m];
            array[m] = array[i];
            array[i] = t;
          }
          return array;
        }
        function enclose(circles) {
          var i = 0, n = (circles = shuffle(slice.call(circles))).length, B2 = [], p, e;
          while (i < n) {
            p = circles[i];
            if (e && enclosesWeak(e, p)) ++i;
            else e = encloseBasis(B2 = extendBasis(B2, p)), i = 0;
          }
          return e;
        }
        function extendBasis(B2, p) {
          var i, j;
          if (enclosesWeakAll(p, B2)) return [p];
          for (i = 0; i < B2.length; ++i) {
            if (enclosesNot(p, B2[i]) && enclosesWeakAll(encloseBasis2(B2[i], p), B2)) {
              return [B2[i], p];
            }
          }
          for (i = 0; i < B2.length - 1; ++i) {
            for (j = i + 1; j < B2.length; ++j) {
              if (enclosesNot(encloseBasis2(B2[i], B2[j]), p) && enclosesNot(encloseBasis2(B2[i], p), B2[j]) && enclosesNot(encloseBasis2(B2[j], p), B2[i]) && enclosesWeakAll(encloseBasis3(B2[i], B2[j], p), B2)) {
                return [B2[i], B2[j], p];
              }
            }
          }
          throw new Error();
        }
        function enclosesNot(a, b) {
          var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y;
          return dr < 0 || dr * dr < dx * dx + dy * dy;
        }
        function enclosesWeak(a, b) {
          var dr = a.r - b.r + 1e-6, dx = b.x - a.x, dy = b.y - a.y;
          return dr > 0 && dr * dr > dx * dx + dy * dy;
        }
        function enclosesWeakAll(a, B2) {
          for (var i = 0; i < B2.length; ++i) {
            if (!enclosesWeak(a, B2[i])) {
              return false;
            }
          }
          return true;
        }
        function encloseBasis(B2) {
          switch (B2.length) {
            case 1:
              return encloseBasis1(B2[0]);
            case 2:
              return encloseBasis2(B2[0], B2[1]);
            case 3:
              return encloseBasis3(B2[0], B2[1], B2[2]);
          }
        }
        function encloseBasis1(a) {
          return {
            x: a.x,
            y: a.y,
            r: a.r
          };
        }
        function encloseBasis2(a, b) {
          var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1, l = Math.sqrt(x21 * x21 + y21 * y21);
          return {
            x: (x1 + x2 + x21 / l * r21) / 2,
            y: (y1 + y2 + y21 / l * r21) / 2,
            r: (l + r1 + r2) / 2
          };
        }
        function encloseBasis3(a, b, c) {
          var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x3 = c.x, y3 = c.y, r3 = c.r, a2 = x1 - x2, a3 = x1 - x3, b2 = y1 - y2, b3 = y1 - y3, c2 = r2 - r1, c3 = r3 - r1, d1 = x1 * x1 + y1 * y1 - r1 * r1, d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2, d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3, ab = a3 * b2 - a2 * b3, xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1, xb = (b3 * c2 - b2 * c3) / ab, ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1, yb = (a2 * c3 - a3 * c2) / ab, A2 = xb * xb + yb * yb - 1, B2 = 2 * (r1 + xa * xb + ya * yb), C2 = xa * xa + ya * ya - r1 * r1, r = -(A2 ? (B2 + Math.sqrt(B2 * B2 - 4 * A2 * C2)) / (2 * A2) : C2 / B2);
          return {
            x: x1 + xa + xb * r,
            y: y1 + ya + yb * r,
            r
          };
        }
        function place(b, a, c) {
          var dx = b.x - a.x, x, a2, dy = b.y - a.y, y, b2, d2 = dx * dx + dy * dy;
          if (d2) {
            a2 = a.r + c.r, a2 *= a2;
            b2 = b.r + c.r, b2 *= b2;
            if (a2 > b2) {
              x = (d2 + b2 - a2) / (2 * d2);
              y = Math.sqrt(Math.max(0, b2 / d2 - x * x));
              c.x = b.x - x * dx - y * dy;
              c.y = b.y - x * dy + y * dx;
            } else {
              x = (d2 + a2 - b2) / (2 * d2);
              y = Math.sqrt(Math.max(0, a2 / d2 - x * x));
              c.x = a.x + x * dx - y * dy;
              c.y = a.y + x * dy + y * dx;
            }
          } else {
            c.x = a.x + c.r;
            c.y = a.y;
          }
        }
        function intersects(a, b) {
          var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y;
          return dr > 0 && dr * dr > dx * dx + dy * dy;
        }
        function score(node) {
          var a = node._, b = node.next._, ab = a.r + b.r, dx = (a.x * b.r + b.x * a.r) / ab, dy = (a.y * b.r + b.y * a.r) / ab;
          return dx * dx + dy * dy;
        }
        function Node$1(circle) {
          this._ = circle;
          this.next = null;
          this.previous = null;
        }
        function packEnclose(circles) {
          if (!(n = circles.length)) return 0;
          var a, b, c, n, aa, ca, i, j, k, sj, sk;
          a = circles[0], a.x = 0, a.y = 0;
          if (!(n > 1)) return a.r;
          b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0;
          if (!(n > 2)) return a.r + b.r;
          place(b, a, c = circles[2]);
          a = new Node$1(a), b = new Node$1(b), c = new Node$1(c);
          a.next = c.previous = b;
          b.next = a.previous = c;
          c.next = b.previous = a;
          pack: for (i = 3; i < n; ++i) {
            place(a._, b._, c = circles[i]), c = new Node$1(c);
            j = b.next, k = a.previous, sj = b._.r, sk = a._.r;
            do {
              if (sj <= sk) {
                if (intersects(j._, c._)) {
                  b = j, a.next = b, b.previous = a, --i;
                  continue pack;
                }
                sj += j._.r, j = j.next;
              } else {
                if (intersects(k._, c._)) {
                  a = k, a.next = b, b.previous = a, --i;
                  continue pack;
                }
                sk += k._.r, k = k.previous;
              }
            } while (j !== k.next);
            c.previous = a, c.next = b, a.next = b.previous = b = c;
            aa = score(a);
            while ((c = c.next) !== b) {
              if ((ca = score(c)) < aa) {
                a = c, aa = ca;
              }
            }
            b = a.next;
          }
          a = [b._], c = b;
          while ((c = c.next) !== b) a.push(c._);
          c = enclose(a);
          for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y;
          return c.r;
        }
        function siblings(circles) {
          packEnclose(circles);
          return circles;
        }
        function optional(f) {
          return f == null ? null : required(f);
        }
        function required(f) {
          if (typeof f !== "function") throw new Error();
          return f;
        }
        function constantZero() {
          return 0;
        }
        function constant(x) {
          return function() {
            return x;
          };
        }
        function defaultRadius(d) {
          return Math.sqrt(d.value);
        }
        function index() {
          var radius = null, dx = 1, dy = 1, padding = constantZero;
          function pack(root) {
            root.x = dx / 2, root.y = dy / 2;
            if (radius) {
              root.eachBefore(radiusLeaf(radius)).eachAfter(packChildren(padding, 0.5)).eachBefore(translateChild(1));
            } else {
              root.eachBefore(radiusLeaf(defaultRadius)).eachAfter(packChildren(constantZero, 1)).eachAfter(packChildren(padding, root.r / Math.min(dx, dy))).eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r)));
            }
            return root;
          }
          pack.radius = function(x) {
            return arguments.length ? (radius = optional(x), pack) : radius;
          };
          pack.size = function(x) {
            return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy];
          };
          pack.padding = function(x) {
            return arguments.length ? (padding = typeof x === "function" ? x : constant(+x), pack) : padding;
          };
          return pack;
        }
        function radiusLeaf(radius) {
          return function(node) {
            if (!node.children) {
              node.r = Math.max(0, +radius(node) || 0);
            }
          };
        }
        function packChildren(padding, k) {
          return function(node) {
            if (children = node.children) {
              var children, i, n = children.length, r = padding(node) * k || 0, e;
              if (r) for (i = 0; i < n; ++i) children[i].r += r;
              e = packEnclose(children);
              if (r) for (i = 0; i < n; ++i) children[i].r -= r;
              node.r = e + r;
            }
          };
        }
        function translateChild(k) {
          return function(node) {
            var parent = node.parent;
            node.r *= k;
            if (parent) {
              node.x = parent.x + k * node.x;
              node.y = parent.y + k * node.y;
            }
          };
        }
        function roundNode(node) {
          node.x0 = Math.round(node.x0);
          node.y0 = Math.round(node.y0);
          node.x1 = Math.round(node.x1);
          node.y1 = Math.round(node.y1);
        }
        function treemapDice(parent, x0, y0, x1, y1) {
          var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value;
          while (++i < n) {
            node = nodes[i], node.y0 = y0, node.y1 = y1;
            node.x0 = x0, node.x1 = x0 += node.value * k;
          }
        }
        function partition() {
          var dx = 1, dy = 1, padding = 0, round = false;
          function partition2(root) {
            var n = root.height + 1;
            root.x0 = root.y0 = padding;
            root.x1 = dx;
            root.y1 = dy / n;
            root.eachBefore(positionNode(dy, n));
            if (round) root.eachBefore(roundNode);
            return root;
          }
          function positionNode(dy2, n) {
            return function(node) {
              if (node.children) {
                treemapDice(node, node.x0, dy2 * (node.depth + 1) / n, node.x1, dy2 * (node.depth + 2) / n);
              }
              var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding;
              if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
              if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
              node.x0 = x0;
              node.y0 = y0;
              node.x1 = x1;
              node.y1 = y1;
            };
          }
          partition2.round = function(x) {
            return arguments.length ? (round = !!x, partition2) : round;
          };
          partition2.size = function(x) {
            return arguments.length ? (dx = +x[0], dy = +x[1], partition2) : [dx, dy];
          };
          partition2.padding = function(x) {
            return arguments.length ? (padding = +x, partition2) : padding;
          };
          return partition2;
        }
        var keyPrefix = "$", preroot = { depth: -1 }, ambiguous = {};
        function defaultId(d) {
          return d.id;
        }
        function defaultParentId(d) {
          return d.parentId;
        }
        function stratify() {
          var id = defaultId, parentId = defaultParentId;
          function stratify2(data) {
            var d, i, n = data.length, root, parent, node, nodes = new Array(n), nodeId, nodeKey, nodeByKey = {};
            for (i = 0; i < n; ++i) {
              d = data[i], node = nodes[i] = new Node(d);
              if ((nodeId = id(d, i, data)) != null && (nodeId += "")) {
                nodeKey = keyPrefix + (node.id = nodeId);
                nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node;
              }
            }
            for (i = 0; i < n; ++i) {
              node = nodes[i], nodeId = parentId(data[i], i, data);
              if (nodeId == null || !(nodeId += "")) {
                if (root) throw new Error("multiple roots");
                root = node;
              } else {
                parent = nodeByKey[keyPrefix + nodeId];
                if (!parent) throw new Error("missing: " + nodeId);
                if (parent === ambiguous) throw new Error("ambiguous: " + nodeId);
                if (parent.children) parent.children.push(node);
                else parent.children = [node];
                node.parent = parent;
              }
            }
            if (!root) throw new Error("no root");
            root.parent = preroot;
            root.eachBefore(function(node2) {
              node2.depth = node2.parent.depth + 1;
              --n;
            }).eachBefore(computeHeight);
            root.parent = null;
            if (n > 0) throw new Error("cycle");
            return root;
          }
          stratify2.id = function(x) {
            return arguments.length ? (id = required(x), stratify2) : id;
          };
          stratify2.parentId = function(x) {
            return arguments.length ? (parentId = required(x), stratify2) : parentId;
          };
          return stratify2;
        }
        function defaultSeparation$1(a, b) {
          return a.parent === b.parent ? 1 : 2;
        }
        function nextLeft(v) {
          var children = v.children;
          return children ? children[0] : v.t;
        }
        function nextRight(v) {
          var children = v.children;
          return children ? children[children.length - 1] : v.t;
        }
        function moveSubtree(wm, wp, shift) {
          var change = shift / (wp.i - wm.i);
          wp.c -= change;
          wp.s += shift;
          wm.c += change;
          wp.z += shift;
          wp.m += shift;
        }
        function executeShifts(v) {
          var shift = 0, change = 0, children = v.children, i = children.length, w;
          while (--i >= 0) {
            w = children[i];
            w.z += shift;
            w.m += shift;
            shift += w.s + (change += w.c);
          }
        }
        function nextAncestor(vim, v, ancestor) {
          return vim.a.parent === v.parent ? vim.a : ancestor;
        }
        function TreeNode(node, i) {
          this._ = node;
          this.parent = null;
          this.children = null;
          this.A = null;
          this.a = this;
          this.z = 0;
          this.m = 0;
          this.c = 0;
          this.s = 0;
          this.t = null;
          this.i = i;
        }
        TreeNode.prototype = Object.create(Node.prototype);
        function treeRoot(root) {
          var tree2 = new TreeNode(root, 0), node, nodes = [tree2], child, children, i, n;
          while (node = nodes.pop()) {
            if (children = node._.children) {
              node.children = new Array(n = children.length);
              for (i = n - 1; i >= 0; --i) {
                nodes.push(child = node.children[i] = new TreeNode(children[i], i));
                child.parent = node;
              }
            }
          }
          (tree2.parent = new TreeNode(null, 0)).children = [tree2];
          return tree2;
        }
        function tree() {
          var separation = defaultSeparation$1, dx = 1, dy = 1, nodeSize = null;
          function tree2(root) {
            var t = treeRoot(root);
            t.eachAfter(firstWalk), t.parent.m = -t.z;
            t.eachBefore(secondWalk);
            if (nodeSize) root.eachBefore(sizeNode);
            else {
              var left = root, right = root, bottom = root;
              root.eachBefore(function(node) {
                if (node.x < left.x) left = node;
                if (node.x > right.x) right = node;
                if (node.depth > bottom.depth) bottom = node;
              });
              var s = left === right ? 1 : separation(left, right) / 2, tx = s - left.x, kx = dx / (right.x + s + tx), ky = dy / (bottom.depth || 1);
              root.eachBefore(function(node) {
                node.x = (node.x + tx) * kx;
                node.y = node.depth * ky;
              });
            }
            return root;
          }
          function firstWalk(v) {
            var children = v.children, siblings2 = v.parent.children, w = v.i ? siblings2[v.i - 1] : null;
            if (children) {
              executeShifts(v);
              var midpoint = (children[0].z + children[children.length - 1].z) / 2;
              if (w) {
                v.z = w.z + separation(v._, w._);
                v.m = v.z - midpoint;
              } else {
                v.z = midpoint;
              }
            } else if (w) {
              v.z = w.z + separation(v._, w._);
            }
            v.parent.A = apportion(v, w, v.parent.A || siblings2[0]);
          }
          function secondWalk(v) {
            v._.x = v.z + v.parent.m;
            v.m += v.parent.m;
          }
          function apportion(v, w, ancestor) {
            if (w) {
              var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
              while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {
                vom = nextLeft(vom);
                vop = nextRight(vop);
                vop.a = v;
                shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
                if (shift > 0) {
                  moveSubtree(nextAncestor(vim, v, ancestor), v, shift);
                  sip += shift;
                  sop += shift;
                }
                sim += vim.m;
                sip += vip.m;
                som += vom.m;
                sop += vop.m;
              }
              if (vim && !nextRight(vop)) {
                vop.t = vim;
                vop.m += sim - sop;
              }
              if (vip && !nextLeft(vom)) {
                vom.t = vip;
                vom.m += sip - som;
                ancestor = v;
              }
            }
            return ancestor;
          }
          function sizeNode(node) {
            node.x *= dx;
            node.y = node.depth * dy;
          }
          tree2.separation = function(x) {
            return arguments.length ? (separation = x, tree2) : separation;
          };
          tree2.size = function(x) {
            return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree2) : nodeSize ? null : [dx, dy];
          };
          tree2.nodeSize = function(x) {
            return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree2) : nodeSize ? [dx, dy] : null;
          };
          return tree2;
        }
        function treemapSlice(parent, x0, y0, x1, y1) {
          var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value;
          while (++i < n) {
            node = nodes[i], node.x0 = x0, node.x1 = x1;
            node.y0 = y0, node.y1 = y0 += node.value * k;
          }
        }
        var phi = (1 + Math.sqrt(5)) / 2;
        function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
          var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
          while (i0 < n) {
            dx = x1 - x0, dy = y1 - y0;
            do
              sumValue = nodes[i1++].value;
            while (!sumValue && i1 < n);
            minValue = maxValue = sumValue;
            alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
            beta = sumValue * sumValue * alpha;
            minRatio = Math.max(maxValue / beta, beta / minValue);
            for (; i1 < n; ++i1) {
              sumValue += nodeValue = nodes[i1].value;
              if (nodeValue < minValue) minValue = nodeValue;
              if (nodeValue > maxValue) maxValue = nodeValue;
              beta = sumValue * sumValue * alpha;
              newRatio = Math.max(maxValue / beta, beta / minValue);
              if (newRatio > minRatio) {
                sumValue -= nodeValue;
                break;
              }
              minRatio = newRatio;
            }
            rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
            if (row.dice) treemapDice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
            else treemapSlice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
            value -= sumValue, i0 = i1;
          }
          return rows;
        }
        var squarify = function custom(ratio) {
          function squarify2(parent, x0, y0, x1, y1) {
            squarifyRatio(ratio, parent, x0, y0, x1, y1);
          }
          squarify2.ratio = function(x) {
            return custom((x = +x) > 1 ? x : 1);
          };
          return squarify2;
        }(phi);
        function index$1() {
          var tile = squarify, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
          function treemap(root) {
            root.x0 = root.y0 = 0;
            root.x1 = dx;
            root.y1 = dy;
            root.eachBefore(positionNode);
            paddingStack = [0];
            if (round) root.eachBefore(roundNode);
            return root;
          }
          function positionNode(node) {
            var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;
            if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
            if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
            node.x0 = x0;
            node.y0 = y0;
            node.x1 = x1;
            node.y1 = y1;
            if (node.children) {
              p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
              x0 += paddingLeft(node) - p;
              y0 += paddingTop(node) - p;
              x1 -= paddingRight(node) - p;
              y1 -= paddingBottom(node) - p;
              if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
              if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
              tile(node, x0, y0, x1, y1);
            }
          }
          treemap.round = function(x) {
            return arguments.length ? (round = !!x, treemap) : round;
          };
          treemap.size = function(x) {
            return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
          };
          treemap.tile = function(x) {
            return arguments.length ? (tile = required(x), treemap) : tile;
          };
          treemap.padding = function(x) {
            return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
          };
          treemap.paddingInner = function(x) {
            return arguments.length ? (paddingInner = typeof x === "function" ? x : constant(+x), treemap) : paddingInner;
          };
          treemap.paddingOuter = function(x) {
            return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
          };
          treemap.paddingTop = function(x) {
            return arguments.length ? (paddingTop = typeof x === "function" ? x : constant(+x), treemap) : paddingTop;
          };
          treemap.paddingRight = function(x) {
            return arguments.length ? (paddingRight = typeof x === "function" ? x : constant(+x), treemap) : paddingRight;
          };
          treemap.paddingBottom = function(x) {
            return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant(+x), treemap) : paddingBottom;
          };
          treemap.paddingLeft = function(x) {
            return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant(+x), treemap) : paddingLeft;
          };
          return treemap;
        }
        function binary(parent, x0, y0, x1, y1) {
          var nodes = parent.children, i, n = nodes.length, sum, sums = new Array(n + 1);
          for (sums[0] = sum = i = 0; i < n; ++i) {
            sums[i + 1] = sum += nodes[i].value;
          }
          partition2(0, n, parent.value, x0, y0, x1, y1);
          function partition2(i2, j, value, x02, y02, x12, y12) {
            if (i2 >= j - 1) {
              var node = nodes[i2];
              node.x0 = x02, node.y0 = y02;
              node.x1 = x12, node.y1 = y12;
              return;
            }
            var valueOffset = sums[i2], valueTarget = value / 2 + valueOffset, k = i2 + 1, hi = j - 1;
            while (k < hi) {
              var mid = k + hi >>> 1;
              if (sums[mid] < valueTarget) k = mid + 1;
              else hi = mid;
            }
            if (valueTarget - sums[k - 1] < sums[k] - valueTarget && i2 + 1 < k) --k;
            var valueLeft = sums[k] - valueOffset, valueRight = value - valueLeft;
            if (x12 - x02 > y12 - y02) {
              var xk = (x02 * valueRight + x12 * valueLeft) / value;
              partition2(i2, k, valueLeft, x02, y02, xk, y12);
              partition2(k, j, valueRight, xk, y02, x12, y12);
            } else {
              var yk = (y02 * valueRight + y12 * valueLeft) / value;
              partition2(i2, k, valueLeft, x02, y02, x12, yk);
              partition2(k, j, valueRight, x02, yk, x12, y12);
            }
          }
        }
        function sliceDice(parent, x0, y0, x1, y1) {
          (parent.depth & 1 ? treemapSlice : treemapDice)(parent, x0, y0, x1, y1);
        }
        var resquarify = function custom(ratio) {
          function resquarify2(parent, x0, y0, x1, y1) {
            if ((rows = parent._squarify) && rows.ratio === ratio) {
              var rows, row, nodes, i, j = -1, n, m = rows.length, value = parent.value;
              while (++j < m) {
                row = rows[j], nodes = row.children;
                for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value;
                if (row.dice) treemapDice(row, x0, y0, x1, y0 += (y1 - y0) * row.value / value);
                else treemapSlice(row, x0, y0, x0 += (x1 - x0) * row.value / value, y1);
                value -= row.value;
              }
            } else {
              parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1);
              rows.ratio = ratio;
            }
          }
          resquarify2.ratio = function(x) {
            return custom((x = +x) > 1 ? x : 1);
          };
          return resquarify2;
        }(phi);
        exports2.cluster = cluster;
        exports2.hierarchy = hierarchy;
        exports2.pack = index;
        exports2.packEnclose = enclose;
        exports2.packSiblings = siblings;
        exports2.partition = partition;
        exports2.stratify = stratify;
        exports2.tree = tree;
        exports2.treemap = index$1;
        exports2.treemapBinary = binary;
        exports2.treemapDice = treemapDice;
        exports2.treemapResquarify = resquarify;
        exports2.treemapSlice = treemapSlice;
        exports2.treemapSliceDice = sliceDice;
        exports2.treemapSquarify = squarify;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // src/traces/sunburst/calc.js
  var require_calc17 = __commonJS({
    "src/traces/sunburst/calc.js"(exports) {
      "use strict";
      var d3Hierarchy = require_d3_hierarchy();
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var makeColorScaleFn = require_colorscale().makeColorScaleFuncFromTrace;
      var makePullColorFn = require_calc16().makePullColorFn;
      var generateExtendedColors = require_calc16().generateExtendedColors;
      var colorscaleCalc = require_colorscale().calc;
      var ALMOST_EQUAL = require_numerical().ALMOST_EQUAL;
      var sunburstExtendedColorWays = {};
      var treemapExtendedColorWays = {};
      var icicleExtendedColorWays = {};
      exports.calc = function(gd, trace) {
        var fullLayout = gd._fullLayout;
        var ids = trace.ids;
        var hasIds = Lib.isArrayOrTypedArray(ids);
        var labels = trace.labels;
        var parents = trace.parents;
        var values = trace.values;
        var hasValues = Lib.isArrayOrTypedArray(values);
        var cd = [];
        var parent2children = {};
        var refs = {};
        var addToLookup = function(parent, v) {
          if (parent2children[parent]) parent2children[parent].push(v);
          else parent2children[parent] = [v];
          refs[v] = 1;
        };
        var isValidKey = function(k2) {
          return k2 || typeof k2 === "number";
        };
        var isValidVal = function(i2) {
          return !hasValues || isNumeric(values[i2]) && values[i2] >= 0;
        };
        var len;
        var isValid;
        var getId;
        if (hasIds) {
          len = Math.min(ids.length, parents.length);
          isValid = function(i2) {
            return isValidKey(ids[i2]) && isValidVal(i2);
          };
          getId = function(i2) {
            return String(ids[i2]);
          };
        } else {
          len = Math.min(labels.length, parents.length);
          isValid = function(i2) {
            return isValidKey(labels[i2]) && isValidVal(i2);
          };
          getId = function(i2) {
            return String(labels[i2]);
          };
        }
        if (hasValues) len = Math.min(len, values.length);
        for (var i = 0; i < len; i++) {
          if (isValid(i)) {
            var id = getId(i);
            var pid = isValidKey(parents[i]) ? String(parents[i]) : "";
            var cdi = {
              i,
              id,
              pid,
              label: isValidKey(labels[i]) ? String(labels[i]) : ""
            };
            if (hasValues) cdi.v = +values[i];
            cd.push(cdi);
            addToLookup(pid, id);
          }
        }
        if (!parent2children[""]) {
          var impliedRoots = [];
          var k;
          for (k in parent2children) {
            if (!refs[k]) {
              impliedRoots.push(k);
            }
          }
          if (impliedRoots.length === 1) {
            k = impliedRoots[0];
            cd.unshift({
              hasImpliedRoot: true,
              id: k,
              pid: "",
              label: k
            });
          } else {
            return Lib.warn([
              "Multiple implied roots, cannot build",
              trace.type,
              "hierarchy of",
              trace.name + ".",
              "These roots include:",
              impliedRoots.join(", ")
            ].join(" "));
          }
        } else if (parent2children[""].length > 1) {
          var dummyId = Lib.randstr();
          for (var j = 0; j < cd.length; j++) {
            if (cd[j].pid === "") {
              cd[j].pid = dummyId;
            }
          }
          cd.unshift({
            hasMultipleRoots: true,
            id: dummyId,
            pid: "",
            label: ""
          });
        }
        var root;
        try {
          root = d3Hierarchy.stratify().id(function(d) {
            return d.id;
          }).parentId(function(d) {
            return d.pid;
          })(cd);
        } catch (e) {
          return Lib.warn([
            "Failed to build",
            trace.type,
            "hierarchy of",
            trace.name + ".",
            "Error:",
            e.message
          ].join(" "));
        }
        var hierarchy = d3Hierarchy.hierarchy(root);
        var failed = false;
        if (hasValues) {
          switch (trace.branchvalues) {
            case "remainder":
              hierarchy.sum(function(d) {
                return d.data.v;
              });
              break;
            case "total":
              hierarchy.each(function(d) {
                var cdi2 = d.data.data;
                var v = cdi2.v;
                if (d.children) {
                  var partialSum = d.children.reduce(function(a, c) {
                    return a + c.data.data.v;
                  }, 0);
                  if (cdi2.hasImpliedRoot || cdi2.hasMultipleRoots) {
                    v = partialSum;
                  }
                  if (v < partialSum * ALMOST_EQUAL) {
                    failed = true;
                    return Lib.warn([
                      "Total value for node",
                      d.data.data.id,
                      "of",
                      trace.name,
                      "is smaller than the sum of its children.",
                      "\nparent value =",
                      v,
                      "\nchildren sum =",
                      partialSum
                    ].join(" "));
                  }
                }
                d.value = v;
              });
              break;
          }
        } else {
          countDescendants(hierarchy, trace, {
            branches: trace.count.indexOf("branches") !== -1,
            leaves: trace.count.indexOf("leaves") !== -1
          });
        }
        if (failed) return;
        if (trace.sort) {
          hierarchy.sort(function(a, b) {
            return b.value - a.value;
          });
        }
        var pullColor;
        var scaleColor;
        var colors = trace.marker.colors || [];
        var hasColors = !!colors.length;
        if (trace._hasColorscale) {
          if (!hasColors) {
            colors = hasValues ? trace.values : trace._values;
          }
          colorscaleCalc(gd, trace, {
            vals: colors,
            containerStr: "marker",
            cLetter: "c"
          });
          scaleColor = makeColorScaleFn(trace.marker);
        } else {
          pullColor = makePullColorFn(fullLayout["_" + trace.type + "colormap"]);
        }
        hierarchy.each(function(d) {
          var cdi2 = d.data.data;
          cdi2.color = trace._hasColorscale ? scaleColor(colors[cdi2.i]) : pullColor(colors[cdi2.i], cdi2.id);
        });
        cd[0].hierarchy = hierarchy;
        return cd;
      };
      exports._runCrossTraceCalc = function(desiredType, gd) {
        var fullLayout = gd._fullLayout;
        var calcdata = gd.calcdata;
        var colorWay = fullLayout[desiredType + "colorway"];
        var colorMap = fullLayout["_" + desiredType + "colormap"];
        if (fullLayout["extend" + desiredType + "colors"]) {
          colorWay = generateExtendedColors(
            colorWay,
            desiredType === "icicle" ? icicleExtendedColorWays : desiredType === "treemap" ? treemapExtendedColorWays : sunburstExtendedColorWays
          );
        }
        var dfltColorCount = 0;
        var rootColor;
        function pickColor(d) {
          var cdi = d.data.data;
          var id = cdi.id;
          if (cdi.color === false) {
            if (colorMap[id]) {
              cdi.color = colorMap[id];
            } else if (d.parent) {
              if (d.parent.parent) {
                cdi.color = d.parent.data.data.color;
              } else {
                colorMap[id] = cdi.color = colorWay[dfltColorCount % colorWay.length];
                dfltColorCount++;
              }
            } else {
              cdi.color = rootColor;
            }
          }
        }
        for (var i = 0; i < calcdata.length; i++) {
          var cd = calcdata[i];
          var cd0 = cd[0];
          if (cd0.trace.type === desiredType && cd0.hierarchy) {
            rootColor = cd0.trace.root.color;
            cd0.hierarchy.each(pickColor);
          }
        }
      };
      exports.crossTraceCalc = function(gd) {
        return exports._runCrossTraceCalc("sunburst", gd);
      };
      function countDescendants(node, trace, opts) {
        var nChild = 0;
        var children = node.children;
        if (children) {
          var len = children.length;
          for (var i = 0; i < len; i++) {
            nChild += countDescendants(children[i], trace, opts);
          }
          if (opts.branches) nChild++;
        } else {
          if (opts.leaves) nChild++;
        }
        node.value = node.data.data.value = nChild;
        if (!trace._values) trace._values = [];
        trace._values[node.data.data.i] = nChild;
        return nChild;
      }
    }
  });

  // node_modules/d3-color/src/define.js
  function define_default(constructor, factory, prototype) {
    constructor.prototype = factory.prototype = prototype;
    prototype.constructor = constructor;
  }
  function extend(parent, definition) {
    var prototype = Object.create(parent.prototype);
    for (var key in definition) prototype[key] = definition[key];
    return prototype;
  }
  var init_define = __esm({
    "node_modules/d3-color/src/define.js"() {
    }
  });

  // node_modules/d3-color/src/color.js
  function Color() {
  }
  function color_formatHex() {
    return this.rgb().formatHex();
  }
  function color_formatHex8() {
    return this.rgb().formatHex8();
  }
  function color_formatHsl() {
    return hslConvert(this).formatHsl();
  }
  function color_formatRgb() {
    return this.rgb().formatRgb();
  }
  function color(format) {
    var m, l;
    format = (format + "").trim().toLowerCase();
    return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format) ? rgbn(named[format]) : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
  }
  function rgbn(n) {
    return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
  }
  function rgba(r, g, b, a) {
    if (a <= 0) r = g = b = NaN;
    return new Rgb(r, g, b, a);
  }
  function rgbConvert(o) {
    if (!(o instanceof Color)) o = color(o);
    if (!o) return new Rgb();
    o = o.rgb();
    return new Rgb(o.r, o.g, o.b, o.opacity);
  }
  function rgb(r, g, b, opacity) {
    return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
  }
  function Rgb(r, g, b, opacity) {
    this.r = +r;
    this.g = +g;
    this.b = +b;
    this.opacity = +opacity;
  }
  function rgb_formatHex() {
    return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
  }
  function rgb_formatHex8() {
    return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
  }
  function rgb_formatRgb() {
    const a = clampa(this.opacity);
    return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
  }
  function clampa(opacity) {
    return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
  }
  function clampi(value) {
    return Math.max(0, Math.min(255, Math.round(value) || 0));
  }
  function hex(value) {
    value = clampi(value);
    return (value < 16 ? "0" : "") + value.toString(16);
  }
  function hsla(h, s, l, a) {
    if (a <= 0) h = s = l = NaN;
    else if (l <= 0 || l >= 1) h = s = NaN;
    else if (s <= 0) h = NaN;
    return new Hsl(h, s, l, a);
  }
  function hslConvert(o) {
    if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
    if (!(o instanceof Color)) o = color(o);
    if (!o) return new Hsl();
    if (o instanceof Hsl) return o;
    o = o.rgb();
    var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2;
    if (s) {
      if (r === max) h = (g - b) / s + (g < b) * 6;
      else if (g === max) h = (b - r) / s + 2;
      else h = (r - g) / s + 4;
      s /= l < 0.5 ? max + min : 2 - max - min;
      h *= 60;
    } else {
      s = l > 0 && l < 1 ? 0 : h;
    }
    return new Hsl(h, s, l, o.opacity);
  }
  function hsl(h, s, l, opacity) {
    return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
  }
  function Hsl(h, s, l, opacity) {
    this.h = +h;
    this.s = +s;
    this.l = +l;
    this.opacity = +opacity;
  }
  function clamph(value) {
    value = (value || 0) % 360;
    return value < 0 ? value + 360 : value;
  }
  function clampt(value) {
    return Math.max(0, Math.min(1, value || 0));
  }
  function hsl2rgb(h, m1, m2) {
    return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
  }
  var darker, brighter, reI, reN, reP, reHex, reRgbInteger, reRgbPercent, reRgbaInteger, reRgbaPercent, reHslPercent, reHslaPercent, named;
  var init_color = __esm({
    "node_modules/d3-color/src/color.js"() {
      init_define();
      darker = 0.7;
      brighter = 1 / darker;
      reI = "\\s*([+-]?\\d+)\\s*";
      reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*";
      reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
      reHex = /^#([0-9a-f]{3,8})$/;
      reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`);
      reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`);
      reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`);
      reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`);
      reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`);
      reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
      named = {
        aliceblue: 15792383,
        antiquewhite: 16444375,
        aqua: 65535,
        aquamarine: 8388564,
        azure: 15794175,
        beige: 16119260,
        bisque: 16770244,
        black: 0,
        blanchedalmond: 16772045,
        blue: 255,
        blueviolet: 9055202,
        brown: 10824234,
        burlywood: 14596231,
        cadetblue: 6266528,
        chartreuse: 8388352,
        chocolate: 13789470,
        coral: 16744272,
        cornflowerblue: 6591981,
        cornsilk: 16775388,
        crimson: 14423100,
        cyan: 65535,
        darkblue: 139,
        darkcyan: 35723,
        darkgoldenrod: 12092939,
        darkgray: 11119017,
        darkgreen: 25600,
        darkgrey: 11119017,
        darkkhaki: 12433259,
        darkmagenta: 9109643,
        darkolivegreen: 5597999,
        darkorange: 16747520,
        darkorchid: 10040012,
        darkred: 9109504,
        darksalmon: 15308410,
        darkseagreen: 9419919,
        darkslateblue: 4734347,
        darkslategray: 3100495,
        darkslategrey: 3100495,
        darkturquoise: 52945,
        darkviolet: 9699539,
        deeppink: 16716947,
        deepskyblue: 49151,
        dimgray: 6908265,
        dimgrey: 6908265,
        dodgerblue: 2003199,
        firebrick: 11674146,
        floralwhite: 16775920,
        forestgreen: 2263842,
        fuchsia: 16711935,
        gainsboro: 14474460,
        ghostwhite: 16316671,
        gold: 16766720,
        goldenrod: 14329120,
        gray: 8421504,
        green: 32768,
        greenyellow: 11403055,
        grey: 8421504,
        honeydew: 15794160,
        hotpink: 16738740,
        indianred: 13458524,
        indigo: 4915330,
        ivory: 16777200,
        khaki: 15787660,
        lavender: 15132410,
        lavenderblush: 16773365,
        lawngreen: 8190976,
        lemonchiffon: 16775885,
        lightblue: 11393254,
        lightcoral: 15761536,
        lightcyan: 14745599,
        lightgoldenrodyellow: 16448210,
        lightgray: 13882323,
        lightgreen: 9498256,
        lightgrey: 13882323,
        lightpink: 16758465,
        lightsalmon: 16752762,
        lightseagreen: 2142890,
        lightskyblue: 8900346,
        lightslategray: 7833753,
        lightslategrey: 7833753,
        lightsteelblue: 11584734,
        lightyellow: 16777184,
        lime: 65280,
        limegreen: 3329330,
        linen: 16445670,
        magenta: 16711935,
        maroon: 8388608,
        mediumaquamarine: 6737322,
        mediumblue: 205,
        mediumorchid: 12211667,
        mediumpurple: 9662683,
        mediumseagreen: 3978097,
        mediumslateblue: 8087790,
        mediumspringgreen: 64154,
        mediumturquoise: 4772300,
        mediumvioletred: 13047173,
        midnightblue: 1644912,
        mintcream: 16121850,
        mistyrose: 16770273,
        moccasin: 16770229,
        navajowhite: 16768685,
        navy: 128,
        oldlace: 16643558,
        olive: 8421376,
        olivedrab: 7048739,
        orange: 16753920,
        orangered: 16729344,
        orchid: 14315734,
        palegoldenrod: 15657130,
        palegreen: 10025880,
        paleturquoise: 11529966,
        palevioletred: 14381203,
        papayawhip: 16773077,
        peachpuff: 16767673,
        peru: 13468991,
        pink: 16761035,
        plum: 14524637,
        powderblue: 11591910,
        purple: 8388736,
        rebeccapurple: 6697881,
        red: 16711680,
        rosybrown: 12357519,
        royalblue: 4286945,
        saddlebrown: 9127187,
        salmon: 16416882,
        sandybrown: 16032864,
        seagreen: 3050327,
        seashell: 16774638,
        sienna: 10506797,
        silver: 12632256,
        skyblue: 8900331,
        slateblue: 6970061,
        slategray: 7372944,
        slategrey: 7372944,
        snow: 16775930,
        springgreen: 65407,
        steelblue: 4620980,
        tan: 13808780,
        teal: 32896,
        thistle: 14204888,
        tomato: 16737095,
        turquoise: 4251856,
        violet: 15631086,
        wheat: 16113331,
        white: 16777215,
        whitesmoke: 16119285,
        yellow: 16776960,
        yellowgreen: 10145074
      };
      define_default(Color, color, {
        copy(channels) {
          return Object.assign(new this.constructor(), this, channels);
        },
        displayable() {
          return this.rgb().displayable();
        },
        hex: color_formatHex,
        // Deprecated! Use color.formatHex.
        formatHex: color_formatHex,
        formatHex8: color_formatHex8,
        formatHsl: color_formatHsl,
        formatRgb: color_formatRgb,
        toString: color_formatRgb
      });
      define_default(Rgb, rgb, extend(Color, {
        brighter(k) {
          k = k == null ? brighter : Math.pow(brighter, k);
          return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
        },
        darker(k) {
          k = k == null ? darker : Math.pow(darker, k);
          return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
        },
        rgb() {
          return this;
        },
        clamp() {
          return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
        },
        displayable() {
          return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
        },
        hex: rgb_formatHex,
        // Deprecated! Use color.formatHex.
        formatHex: rgb_formatHex,
        formatHex8: rgb_formatHex8,
        formatRgb: rgb_formatRgb,
        toString: rgb_formatRgb
      }));
      define_default(Hsl, hsl, extend(Color, {
        brighter(k) {
          k = k == null ? brighter : Math.pow(brighter, k);
          return new Hsl(this.h, this.s, this.l * k, this.opacity);
        },
        darker(k) {
          k = k == null ? darker : Math.pow(darker, k);
          return new Hsl(this.h, this.s, this.l * k, this.opacity);
        },
        rgb() {
          var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
          return new Rgb(
            hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
            hsl2rgb(h, m1, m2),
            hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
            this.opacity
          );
        },
        clamp() {
          return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
        },
        displayable() {
          return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
        },
        formatHsl() {
          const a = clampa(this.opacity);
          return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
        }
      }));
    }
  });

  // node_modules/d3-color/src/math.js
  var radians, degrees;
  var init_math = __esm({
    "node_modules/d3-color/src/math.js"() {
      radians = Math.PI / 180;
      degrees = 180 / Math.PI;
    }
  });

  // node_modules/d3-color/src/lab.js
  function labConvert(o) {
    if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
    if (o instanceof Hcl) return hcl2lab(o);
    if (!(o instanceof Rgb)) o = rgbConvert(o);
    var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
    if (r === g && g === b) x = z = y;
    else {
      x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
      z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
    }
    return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
  }
  function lab(l, a, b, opacity) {
    return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
  }
  function Lab(l, a, b, opacity) {
    this.l = +l;
    this.a = +a;
    this.b = +b;
    this.opacity = +opacity;
  }
  function xyz2lab(t) {
    return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
  }
  function lab2xyz(t) {
    return t > t1 ? t * t * t : t2 * (t - t0);
  }
  function lrgb2rgb(x) {
    return 255 * (x <= 31308e-7 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
  }
  function rgb2lrgb(x) {
    return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
  }
  function hclConvert(o) {
    if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
    if (!(o instanceof Lab)) o = labConvert(o);
    if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
    var h = Math.atan2(o.b, o.a) * degrees;
    return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
  }
  function hcl(h, c, l, opacity) {
    return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
  }
  function Hcl(h, c, l, opacity) {
    this.h = +h;
    this.c = +c;
    this.l = +l;
    this.opacity = +opacity;
  }
  function hcl2lab(o) {
    if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
    var h = o.h * radians;
    return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
  }
  var K, Xn, Yn, Zn, t0, t1, t2, t3;
  var init_lab = __esm({
    "node_modules/d3-color/src/lab.js"() {
      init_define();
      init_color();
      init_math();
      K = 18;
      Xn = 0.96422;
      Yn = 1;
      Zn = 0.82521;
      t0 = 4 / 29;
      t1 = 6 / 29;
      t2 = 3 * t1 * t1;
      t3 = t1 * t1 * t1;
      define_default(Lab, lab, extend(Color, {
        brighter(k) {
          return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
        },
        darker(k) {
          return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
        },
        rgb() {
          var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200;
          x = Xn * lab2xyz(x);
          y = Yn * lab2xyz(y);
          z = Zn * lab2xyz(z);
          return new Rgb(
            lrgb2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
            lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.033454 * z),
            lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
            this.opacity
          );
        }
      }));
      define_default(Hcl, hcl, extend(Color, {
        brighter(k) {
          return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
        },
        darker(k) {
          return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
        },
        rgb() {
          return hcl2lab(this).rgb();
        }
      }));
    }
  });

  // node_modules/d3-color/src/cubehelix.js
  function cubehelixConvert(o) {
    if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
    if (!(o instanceof Rgb)) o = rgbConvert(o);
    var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), h = s ? Math.atan2(k, bl) * degrees - 120 : NaN;
    return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
  }
  function cubehelix(h, s, l, opacity) {
    return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
  }
  function Cubehelix(h, s, l, opacity) {
    this.h = +h;
    this.s = +s;
    this.l = +l;
    this.opacity = +opacity;
  }
  var A, B, C, D, E, ED, EB, BC_DA;
  var init_cubehelix = __esm({
    "node_modules/d3-color/src/cubehelix.js"() {
      init_define();
      init_color();
      init_math();
      A = -0.14861;
      B = 1.78277;
      C = -0.29227;
      D = -0.90649;
      E = 1.97294;
      ED = E * D;
      EB = E * B;
      BC_DA = B * C - D * A;
      define_default(Cubehelix, cubehelix, extend(Color, {
        brighter(k) {
          k = k == null ? brighter : Math.pow(brighter, k);
          return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
        },
        darker(k) {
          k = k == null ? darker : Math.pow(darker, k);
          return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
        },
        rgb() {
          var h = isNaN(this.h) ? 0 : (this.h + 120) * radians, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh2 = Math.cos(h), sinh2 = Math.sin(h);
          return new Rgb(
            255 * (l + a * (A * cosh2 + B * sinh2)),
            255 * (l + a * (C * cosh2 + D * sinh2)),
            255 * (l + a * (E * cosh2)),
            this.opacity
          );
        }
      }));
    }
  });

  // node_modules/d3-color/src/index.js
  var init_src = __esm({
    "node_modules/d3-color/src/index.js"() {
      init_color();
      init_lab();
      init_cubehelix();
    }
  });

  // node_modules/d3-interpolate/src/basis.js
  function basis(t12, v0, v1, v2, v3) {
    var t22 = t12 * t12, t32 = t22 * t12;
    return ((1 - 3 * t12 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t12 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6;
  }
  function basis_default(values) {
    var n = values.length - 1;
    return function(t) {
      var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
      return basis((t - i / n) * n, v0, v1, v2, v3);
    };
  }
  var init_basis = __esm({
    "node_modules/d3-interpolate/src/basis.js"() {
    }
  });

  // node_modules/d3-interpolate/src/basisClosed.js
  function basisClosed_default(values) {
    var n = values.length;
    return function(t) {
      var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n];
      return basis((t - i / n) * n, v0, v1, v2, v3);
    };
  }
  var init_basisClosed = __esm({
    "node_modules/d3-interpolate/src/basisClosed.js"() {
      init_basis();
    }
  });

  // node_modules/d3-interpolate/src/constant.js
  var constant_default;
  var init_constant = __esm({
    "node_modules/d3-interpolate/src/constant.js"() {
      constant_default = (x) => () => x;
    }
  });

  // node_modules/d3-interpolate/src/color.js
  function linear(a, d) {
    return function(t) {
      return a + t * d;
    };
  }
  function exponential(a, b, y) {
    return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
      return Math.pow(a + t * b, y);
    };
  }
  function hue(a, b) {
    var d = b - a;
    return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant_default(isNaN(a) ? b : a);
  }
  function gamma(y) {
    return (y = +y) === 1 ? nogamma : function(a, b) {
      return b - a ? exponential(a, b, y) : constant_default(isNaN(a) ? b : a);
    };
  }
  function nogamma(a, b) {
    var d = b - a;
    return d ? linear(a, d) : constant_default(isNaN(a) ? b : a);
  }
  var init_color2 = __esm({
    "node_modules/d3-interpolate/src/color.js"() {
      init_constant();
    }
  });

  // node_modules/d3-interpolate/src/rgb.js
  function rgbSpline(spline) {
    return function(colors) {
      var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2;
      for (i = 0; i < n; ++i) {
        color2 = rgb(colors[i]);
        r[i] = color2.r || 0;
        g[i] = color2.g || 0;
        b[i] = color2.b || 0;
      }
      r = spline(r);
      g = spline(g);
      b = spline(b);
      color2.opacity = 1;
      return function(t) {
        color2.r = r(t);
        color2.g = g(t);
        color2.b = b(t);
        return color2 + "";
      };
    };
  }
  var rgb_default, rgbBasis, rgbBasisClosed;
  var init_rgb = __esm({
    "node_modules/d3-interpolate/src/rgb.js"() {
      init_src();
      init_basis();
      init_basisClosed();
      init_color2();
      rgb_default = function rgbGamma(y) {
        var color2 = gamma(y);
        function rgb2(start, end) {
          var r = color2((start = rgb(start)).r, (end = rgb(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
          return function(t) {
            start.r = r(t);
            start.g = g(t);
            start.b = b(t);
            start.opacity = opacity(t);
            return start + "";
          };
        }
        rgb2.gamma = rgbGamma;
        return rgb2;
      }(1);
      rgbBasis = rgbSpline(basis_default);
      rgbBasisClosed = rgbSpline(basisClosed_default);
    }
  });

  // node_modules/d3-interpolate/src/numberArray.js
  function numberArray_default(a, b) {
    if (!b) b = [];
    var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i;
    return function(t) {
      for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
      return c;
    };
  }
  function isNumberArray(x) {
    return ArrayBuffer.isView(x) && !(x instanceof DataView);
  }
  var init_numberArray = __esm({
    "node_modules/d3-interpolate/src/numberArray.js"() {
    }
  });

  // node_modules/d3-interpolate/src/array.js
  function array_default(a, b) {
    return (isNumberArray(b) ? numberArray_default : genericArray)(a, b);
  }
  function genericArray(a, b) {
    var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(na), c = new Array(nb), i;
    for (i = 0; i < na; ++i) x[i] = value_default(a[i], b[i]);
    for (; i < nb; ++i) c[i] = b[i];
    return function(t) {
      for (i = 0; i < na; ++i) c[i] = x[i](t);
      return c;
    };
  }
  var init_array = __esm({
    "node_modules/d3-interpolate/src/array.js"() {
      init_value();
      init_numberArray();
    }
  });

  // node_modules/d3-interpolate/src/date.js
  function date_default(a, b) {
    var d = /* @__PURE__ */ new Date();
    return a = +a, b = +b, function(t) {
      return d.setTime(a * (1 - t) + b * t), d;
    };
  }
  var init_date = __esm({
    "node_modules/d3-interpolate/src/date.js"() {
    }
  });

  // node_modules/d3-interpolate/src/number.js
  function number_default(a, b) {
    return a = +a, b = +b, function(t) {
      return a * (1 - t) + b * t;
    };
  }
  var init_number = __esm({
    "node_modules/d3-interpolate/src/number.js"() {
    }
  });

  // node_modules/d3-interpolate/src/object.js
  function object_default(a, b) {
    var i = {}, c = {}, k;
    if (a === null || typeof a !== "object") a = {};
    if (b === null || typeof b !== "object") b = {};
    for (k in b) {
      if (k in a) {
        i[k] = value_default(a[k], b[k]);
      } else {
        c[k] = b[k];
      }
    }
    return function(t) {
      for (k in i) c[k] = i[k](t);
      return c;
    };
  }
  var init_object = __esm({
    "node_modules/d3-interpolate/src/object.js"() {
      init_value();
    }
  });

  // node_modules/d3-interpolate/src/string.js
  function zero(b) {
    return function() {
      return b;
    };
  }
  function one(b) {
    return function(t) {
      return b(t) + "";
    };
  }
  function string_default(a, b) {
    var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
    a = a + "", b = b + "";
    while ((am = reA.exec(a)) && (bm = reB.exec(b))) {
      if ((bs = bm.index) > bi) {
        bs = b.slice(bi, bs);
        if (s[i]) s[i] += bs;
        else s[++i] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) {
        if (s[i]) s[i] += bm;
        else s[++i] = bm;
      } else {
        s[++i] = null;
        q.push({ i, x: number_default(am, bm) });
      }
      bi = reB.lastIndex;
    }
    if (bi < b.length) {
      bs = b.slice(bi);
      if (s[i]) s[i] += bs;
      else s[++i] = bs;
    }
    return s.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function(t) {
      for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t);
      return s.join("");
    });
  }
  var reA, reB;
  var init_string = __esm({
    "node_modules/d3-interpolate/src/string.js"() {
      init_number();
      reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
      reB = new RegExp(reA.source, "g");
    }
  });

  // node_modules/d3-interpolate/src/value.js
  function value_default(a, b) {
    var t = typeof b, c;
    return b == null || t === "boolean" ? constant_default(b) : (t === "number" ? number_default : t === "string" ? (c = color(b)) ? (b = c, rgb_default) : string_default : b instanceof color ? rgb_default : b instanceof Date ? date_default : isNumberArray(b) ? numberArray_default : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object_default : number_default)(a, b);
  }
  var init_value = __esm({
    "node_modules/d3-interpolate/src/value.js"() {
      init_src();
      init_rgb();
      init_array();
      init_date();
      init_number();
      init_object();
      init_string();
      init_constant();
      init_numberArray();
    }
  });

  // node_modules/d3-interpolate/src/discrete.js
  function discrete_default(range) {
    var n = range.length;
    return function(t) {
      return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
    };
  }
  var init_discrete = __esm({
    "node_modules/d3-interpolate/src/discrete.js"() {
    }
  });

  // node_modules/d3-interpolate/src/hue.js
  function hue_default(a, b) {
    var i = hue(+a, +b);
    return function(t) {
      var x = i(t);
      return x - 360 * Math.floor(x / 360);
    };
  }
  var init_hue = __esm({
    "node_modules/d3-interpolate/src/hue.js"() {
      init_color2();
    }
  });

  // node_modules/d3-interpolate/src/round.js
  function round_default(a, b) {
    return a = +a, b = +b, function(t) {
      return Math.round(a * (1 - t) + b * t);
    };
  }
  var init_round = __esm({
    "node_modules/d3-interpolate/src/round.js"() {
    }
  });

  // node_modules/d3-interpolate/src/transform/decompose.js
  function decompose_default(a, b, c, d, e, f) {
    var scaleX, scaleY, skewX;
    if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
    if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
    if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
    if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
    return {
      translateX: e,
      translateY: f,
      rotate: Math.atan2(b, a) * degrees2,
      skewX: Math.atan(skewX) * degrees2,
      scaleX,
      scaleY
    };
  }
  var degrees2, identity;
  var init_decompose = __esm({
    "node_modules/d3-interpolate/src/transform/decompose.js"() {
      degrees2 = 180 / Math.PI;
      identity = {
        translateX: 0,
        translateY: 0,
        rotate: 0,
        skewX: 0,
        scaleX: 1,
        scaleY: 1
      };
    }
  });

  // node_modules/d3-interpolate/src/transform/parse.js
  function parseCss(value) {
    const m = new (typeof DOMMatrix === "function" ? DOMMatrix : WebKitCSSMatrix)(value + "");
    return m.isIdentity ? identity : decompose_default(m.a, m.b, m.c, m.d, m.e, m.f);
  }
  function parseSvg(value) {
    if (value == null) return identity;
    if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
    svgNode.setAttribute("transform", value);
    if (!(value = svgNode.transform.baseVal.consolidate())) return identity;
    value = value.matrix;
    return decompose_default(value.a, value.b, value.c, value.d, value.e, value.f);
  }
  var svgNode;
  var init_parse = __esm({
    "node_modules/d3-interpolate/src/transform/parse.js"() {
      init_decompose();
    }
  });

  // node_modules/d3-interpolate/src/transform/index.js
  function interpolateTransform(parse2, pxComma, pxParen, degParen) {
    function pop(s) {
      return s.length ? s.pop() + " " : "";
    }
    function translate(xa, ya, xb, yb, s, q) {
      if (xa !== xb || ya !== yb) {
        var i = s.push("translate(", null, pxComma, null, pxParen);
        q.push({ i: i - 4, x: number_default(xa, xb) }, { i: i - 2, x: number_default(ya, yb) });
      } else if (xb || yb) {
        s.push("translate(" + xb + pxComma + yb + pxParen);
      }
    }
    function rotate(a, b, s, q) {
      if (a !== b) {
        if (a - b > 180) b += 360;
        else if (b - a > 180) a += 360;
        q.push({ i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number_default(a, b) });
      } else if (b) {
        s.push(pop(s) + "rotate(" + b + degParen);
      }
    }
    function skewX(a, b, s, q) {
      if (a !== b) {
        q.push({ i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number_default(a, b) });
      } else if (b) {
        s.push(pop(s) + "skewX(" + b + degParen);
      }
    }
    function scale(xa, ya, xb, yb, s, q) {
      if (xa !== xb || ya !== yb) {
        var i = s.push(pop(s) + "scale(", null, ",", null, ")");
        q.push({ i: i - 4, x: number_default(xa, xb) }, { i: i - 2, x: number_default(ya, yb) });
      } else if (xb !== 1 || yb !== 1) {
        s.push(pop(s) + "scale(" + xb + "," + yb + ")");
      }
    }
    return function(a, b) {
      var s = [], q = [];
      a = parse2(a), b = parse2(b);
      translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
      rotate(a.rotate, b.rotate, s, q);
      skewX(a.skewX, b.skewX, s, q);
      scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
      a = b = null;
      return function(t) {
        var i = -1, n = q.length, o;
        while (++i < n) s[(o = q[i]).i] = o.x(t);
        return s.join("");
      };
    };
  }
  var interpolateTransformCss, interpolateTransformSvg;
  var init_transform = __esm({
    "node_modules/d3-interpolate/src/transform/index.js"() {
      init_number();
      init_parse();
      interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
      interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");
    }
  });

  // node_modules/d3-interpolate/src/zoom.js
  function cosh(x) {
    return ((x = Math.exp(x)) + 1 / x) / 2;
  }
  function sinh(x) {
    return ((x = Math.exp(x)) - 1 / x) / 2;
  }
  function tanh(x) {
    return ((x = Math.exp(2 * x)) - 1) / (x + 1);
  }
  var epsilon2, zoom_default;
  var init_zoom = __esm({
    "node_modules/d3-interpolate/src/zoom.js"() {
      epsilon2 = 1e-12;
      zoom_default = function zoomRho(rho, rho2, rho4) {
        function zoom(p0, p1) {
          var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
          if (d2 < epsilon2) {
            S = Math.log(w1 / w0) / rho;
            i = function(t) {
              return [
                ux0 + t * dx,
                uy0 + t * dy,
                w0 * Math.exp(rho * t * S)
              ];
            };
          } else {
            var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
            S = (r1 - r0) / rho;
            i = function(t) {
              var s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));
              return [
                ux0 + u * dx,
                uy0 + u * dy,
                w0 * coshr0 / cosh(rho * s + r0)
              ];
            };
          }
          i.duration = S * 1e3 * rho / Math.SQRT2;
          return i;
        }
        zoom.rho = function(_) {
          var _1 = Math.max(1e-3, +_), _2 = _1 * _1, _4 = _2 * _2;
          return zoomRho(_1, _2, _4);
        };
        return zoom;
      }(Math.SQRT2, 2, 4);
    }
  });

  // node_modules/d3-interpolate/src/hsl.js
  function hsl2(hue2) {
    return function(start, end) {
      var h = hue2((start = hsl(start)).h, (end = hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.h = h(t);
        start.s = s(t);
        start.l = l(t);
        start.opacity = opacity(t);
        return start + "";
      };
    };
  }
  var hsl_default, hslLong;
  var init_hsl = __esm({
    "node_modules/d3-interpolate/src/hsl.js"() {
      init_src();
      init_color2();
      hsl_default = hsl2(hue);
      hslLong = hsl2(nogamma);
    }
  });

  // node_modules/d3-interpolate/src/lab.js
  function lab2(start, end) {
    var l = nogamma((start = lab(start)).l, (end = lab(end)).l), a = nogamma(start.a, end.a), b = nogamma(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.l = l(t);
      start.a = a(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
  var init_lab2 = __esm({
    "node_modules/d3-interpolate/src/lab.js"() {
      init_src();
      init_color2();
    }
  });

  // node_modules/d3-interpolate/src/hcl.js
  function hcl2(hue2) {
    return function(start, end) {
      var h = hue2((start = hcl(start)).h, (end = hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.h = h(t);
        start.c = c(t);
        start.l = l(t);
        start.opacity = opacity(t);
        return start + "";
      };
    };
  }
  var hcl_default, hclLong;
  var init_hcl = __esm({
    "node_modules/d3-interpolate/src/hcl.js"() {
      init_src();
      init_color2();
      hcl_default = hcl2(hue);
      hclLong = hcl2(nogamma);
    }
  });

  // node_modules/d3-interpolate/src/cubehelix.js
  function cubehelix2(hue2) {
    return function cubehelixGamma(y) {
      y = +y;
      function cubehelix3(start, end) {
        var h = hue2((start = cubehelix(start)).h, (end = cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity);
        return function(t) {
          start.h = h(t);
          start.s = s(t);
          start.l = l(Math.pow(t, y));
          start.opacity = opacity(t);
          return start + "";
        };
      }
      cubehelix3.gamma = cubehelixGamma;
      return cubehelix3;
    }(1);
  }
  var cubehelix_default, cubehelixLong;
  var init_cubehelix2 = __esm({
    "node_modules/d3-interpolate/src/cubehelix.js"() {
      init_src();
      init_color2();
      cubehelix_default = cubehelix2(hue);
      cubehelixLong = cubehelix2(nogamma);
    }
  });

  // node_modules/d3-interpolate/src/piecewise.js
  function piecewise(interpolate, values) {
    if (values === void 0) values = interpolate, interpolate = value_default;
    var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);
    while (i < n) I[i] = interpolate(v, v = values[++i]);
    return function(t) {
      var i2 = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
      return I[i2](t - i2);
    };
  }
  var init_piecewise = __esm({
    "node_modules/d3-interpolate/src/piecewise.js"() {
      init_value();
    }
  });

  // node_modules/d3-interpolate/src/quantize.js
  function quantize_default(interpolator, n) {
    var samples = new Array(n);
    for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));
    return samples;
  }
  var init_quantize = __esm({
    "node_modules/d3-interpolate/src/quantize.js"() {
    }
  });

  // node_modules/d3-interpolate/src/index.js
  var src_exports = {};
  __export(src_exports, {
    interpolate: () => value_default,
    interpolateArray: () => array_default,
    interpolateBasis: () => basis_default,
    interpolateBasisClosed: () => basisClosed_default,
    interpolateCubehelix: () => cubehelix_default,
    interpolateCubehelixLong: () => cubehelixLong,
    interpolateDate: () => date_default,
    interpolateDiscrete: () => discrete_default,
    interpolateHcl: () => hcl_default,
    interpolateHclLong: () => hclLong,
    interpolateHsl: () => hsl_default,
    interpolateHslLong: () => hslLong,
    interpolateHue: () => hue_default,
    interpolateLab: () => lab2,
    interpolateNumber: () => number_default,
    interpolateNumberArray: () => numberArray_default,
    interpolateObject: () => object_default,
    interpolateRgb: () => rgb_default,
    interpolateRgbBasis: () => rgbBasis,
    interpolateRgbBasisClosed: () => rgbBasisClosed,
    interpolateRound: () => round_default,
    interpolateString: () => string_default,
    interpolateTransformCss: () => interpolateTransformCss,
    interpolateTransformSvg: () => interpolateTransformSvg,
    interpolateZoom: () => zoom_default,
    piecewise: () => piecewise,
    quantize: () => quantize_default
  });
  var init_src2 = __esm({
    "node_modules/d3-interpolate/src/index.js"() {
      init_value();
      init_array();
      init_basis();
      init_basisClosed();
      init_date();
      init_discrete();
      init_hue();
      init_number();
      init_numberArray();
      init_object();
      init_round();
      init_string();
      init_transform();
      init_zoom();
      init_rgb();
      init_hsl();
      init_lab2();
      init_hcl();
      init_cubehelix2();
      init_piecewise();
      init_quantize();
    }
  });

  // src/traces/sunburst/fill_one.js
  var require_fill_one2 = __commonJS({
    "src/traces/sunburst/fill_one.js"(exports, module) {
      "use strict";
      var Drawing = require_drawing();
      var Color2 = require_color();
      module.exports = function fillOne(s, pt, trace, gd, fadedColor) {
        var cdi = pt.data.data;
        var ptNumber = cdi.i;
        var color2 = fadedColor || cdi.color;
        if (ptNumber >= 0) {
          pt.i = cdi.i;
          var marker = trace.marker;
          if (marker.pattern) {
            if (!marker.colors || !marker.pattern.shape) {
              marker.color = color2;
              pt.color = color2;
            }
          } else {
            marker.color = color2;
            pt.color = color2;
          }
          Drawing.pointStyle(s, trace, gd, pt);
        } else {
          Color2.fill(s, color2);
        }
      };
    }
  });

  // src/traces/sunburst/style.js
  var require_style13 = __commonJS({
    "src/traces/sunburst/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var Lib = require_lib();
      var resizeText = require_uniform_text().resizeText;
      var fillOne = require_fill_one2();
      function style(gd) {
        var s = gd._fullLayout._sunburstlayer.selectAll(".trace");
        resizeText(gd, s, "sunburst");
        s.each(function(cd) {
          var gTrace = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          gTrace.style("opacity", trace.opacity);
          gTrace.selectAll("path.surface").each(function(pt) {
            d3.select(this).call(styleOne, pt, trace, gd);
          });
        });
      }
      function styleOne(s, pt, trace, gd) {
        var cdi = pt.data.data;
        var isLeaf = !pt.children;
        var ptNumber = cdi.i;
        var lineColor = Lib.castOption(trace, ptNumber, "marker.line.color") || Color2.defaultLine;
        var lineWidth = Lib.castOption(trace, ptNumber, "marker.line.width") || 0;
        s.call(fillOne, pt, trace, gd).style("stroke-width", lineWidth).call(Color2.stroke, lineColor).style("opacity", isLeaf ? trace.leaf.opacity : null);
      }
      module.exports = {
        style,
        styleOne
      };
    }
  });

  // src/traces/sunburst/helpers.js
  var require_helpers15 = __commonJS({
    "src/traces/sunburst/helpers.js"(exports) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var setCursor = require_setcursor();
      var pieHelpers = require_helpers4();
      exports.findEntryWithLevel = function(hierarchy, level) {
        var out;
        if (level) {
          hierarchy.eachAfter(function(pt) {
            if (exports.getPtId(pt) === level) {
              return out = pt.copy();
            }
          });
        }
        return out || hierarchy;
      };
      exports.findEntryWithChild = function(hierarchy, childId) {
        var out;
        hierarchy.eachAfter(function(pt) {
          var children = pt.children || [];
          for (var i = 0; i < children.length; i++) {
            var child = children[i];
            if (exports.getPtId(child) === childId) {
              return out = pt.copy();
            }
          }
        });
        return out || hierarchy;
      };
      exports.isEntry = function(pt) {
        return !pt.parent;
      };
      exports.isLeaf = function(pt) {
        return !pt.children;
      };
      exports.getPtId = function(pt) {
        return pt.data.data.id;
      };
      exports.getPtLabel = function(pt) {
        return pt.data.data.label;
      };
      exports.getValue = function(d) {
        return d.value;
      };
      exports.isHierarchyRoot = function(pt) {
        return getParentId(pt) === "";
      };
      exports.setSliceCursor = function(sliceTop, gd, opts) {
        var hide = opts.isTransitioning;
        if (!hide) {
          var pt = sliceTop.datum();
          hide = opts.hideOnRoot && exports.isHierarchyRoot(pt) || opts.hideOnLeaves && exports.isLeaf(pt);
        }
        setCursor(sliceTop, hide ? null : "pointer");
      };
      function determineOutsideTextFont(trace, pt, layoutFont) {
        return {
          color: exports.getOutsideTextFontKey("color", trace, pt, layoutFont),
          family: exports.getOutsideTextFontKey("family", trace, pt, layoutFont),
          size: exports.getOutsideTextFontKey("size", trace, pt, layoutFont),
          weight: exports.getOutsideTextFontKey("weight", trace, pt, layoutFont),
          style: exports.getOutsideTextFontKey("style", trace, pt, layoutFont),
          variant: exports.getOutsideTextFontKey("variant", trace, pt, layoutFont),
          textcase: exports.getOutsideTextFontKey("textcase", trace, pt, layoutFont),
          lineposition: exports.getOutsideTextFontKey("lineposition", trace, pt, layoutFont),
          shadow: exports.getOutsideTextFontKey("shadow", trace, pt, layoutFont)
        };
      }
      function determineInsideTextFont(trace, pt, layoutFont, opts) {
        var onPathbar = (opts || {}).onPathbar;
        var cdi = pt.data.data;
        var ptNumber = cdi.i;
        var customColor = Lib.castOption(
          trace,
          ptNumber,
          (onPathbar ? "pathbar.textfont" : "insidetextfont") + ".color"
        );
        if (!customColor && trace._input.textfont) {
          customColor = Lib.castOption(trace._input, ptNumber, "textfont.color");
        }
        return {
          color: customColor || Color2.contrast(cdi.color),
          family: exports.getInsideTextFontKey("family", trace, pt, layoutFont, opts),
          size: exports.getInsideTextFontKey("size", trace, pt, layoutFont, opts),
          weight: exports.getInsideTextFontKey("weight", trace, pt, layoutFont, opts),
          style: exports.getInsideTextFontKey("style", trace, pt, layoutFont, opts),
          variant: exports.getInsideTextFontKey("variant", trace, pt, layoutFont, opts),
          textcase: exports.getInsideTextFontKey("textcase", trace, pt, layoutFont, opts),
          lineposition: exports.getInsideTextFontKey("lineposition", trace, pt, layoutFont, opts),
          shadow: exports.getInsideTextFontKey("shadow", trace, pt, layoutFont, opts)
        };
      }
      exports.getInsideTextFontKey = function(keyStr, trace, pt, layoutFont, opts) {
        var onPathbar = (opts || {}).onPathbar;
        var cont = onPathbar ? "pathbar.textfont" : "insidetextfont";
        var ptNumber = pt.data.data.i;
        return Lib.castOption(trace, ptNumber, cont + "." + keyStr) || Lib.castOption(trace, ptNumber, "textfont." + keyStr) || layoutFont.size;
      };
      exports.getOutsideTextFontKey = function(keyStr, trace, pt, layoutFont) {
        var ptNumber = pt.data.data.i;
        return Lib.castOption(trace, ptNumber, "outsidetextfont." + keyStr) || Lib.castOption(trace, ptNumber, "textfont." + keyStr) || layoutFont.size;
      };
      exports.isOutsideText = function(trace, pt) {
        return !trace._hasColorscale && exports.isHierarchyRoot(pt);
      };
      exports.determineTextFont = function(trace, pt, layoutFont, opts) {
        return exports.isOutsideText(trace, pt) ? determineOutsideTextFont(trace, pt, layoutFont) : determineInsideTextFont(trace, pt, layoutFont, opts);
      };
      exports.hasTransition = function(transitionOpts) {
        return !!(transitionOpts && transitionOpts.duration > 0);
      };
      exports.getMaxDepth = function(trace) {
        return trace.maxdepth >= 0 ? trace.maxdepth : Infinity;
      };
      exports.isHeader = function(pt, trace) {
        return !(exports.isLeaf(pt) || pt.depth === trace._maxDepth - 1);
      };
      function getParentId(pt) {
        return pt.data.data.pid;
      }
      exports.getParent = function(hierarchy, pt) {
        return exports.findEntryWithLevel(hierarchy, getParentId(pt));
      };
      exports.listPath = function(d, keyStr) {
        var parent = d.parent;
        if (!parent) return [];
        var list = keyStr ? [parent.data[keyStr]] : [parent];
        return exports.listPath(parent, keyStr).concat(list);
      };
      exports.getPath = function(d) {
        return exports.listPath(d, "label").join("/") + "/";
      };
      exports.formatValue = pieHelpers.formatPieValue;
      exports.formatPercent = function(v, separators) {
        var tx = Lib.formatPercent(v, 0);
        if (tx === "0%") tx = pieHelpers.formatPiePercent(v, separators);
        return tx;
      };
    }
  });

  // src/traces/sunburst/fx.js
  var require_fx2 = __commonJS({
    "src/traces/sunburst/fx.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Registry = require_registry();
      var appendArrayPointValue = require_helpers2().appendArrayPointValue;
      var Fx = require_fx();
      var Lib = require_lib();
      var Events = require_events2();
      var helpers = require_helpers15();
      var pieHelpers = require_helpers4();
      var formatValue = pieHelpers.formatPieValue;
      module.exports = function attachFxHandlers(sliceTop, entry, gd, cd, opts) {
        var cd0 = cd[0];
        var trace = cd0.trace;
        var hierarchy = cd0.hierarchy;
        var isSunburst = trace.type === "sunburst";
        var isTreemapOrIcicle = trace.type === "treemap" || trace.type === "icicle";
        if (!("_hasHoverLabel" in trace)) trace._hasHoverLabel = false;
        if (!("_hasHoverEvent" in trace)) trace._hasHoverEvent = false;
        var onMouseOver = function(pt) {
          var fullLayoutNow = gd._fullLayout;
          if (gd._dragging || fullLayoutNow.hovermode === false) return;
          var traceNow = gd._fullData[trace.index];
          var cdi = pt.data.data;
          var ptNumber = cdi.i;
          var isRoot = helpers.isHierarchyRoot(pt);
          var parent = helpers.getParent(hierarchy, pt);
          var val = helpers.getValue(pt);
          var _cast = function(astr) {
            return Lib.castOption(traceNow, ptNumber, astr);
          };
          var hovertemplate = _cast("hovertemplate");
          var hoverinfo = Fx.castHoverinfo(traceNow, fullLayoutNow, ptNumber);
          var separators = fullLayoutNow.separators;
          var eventData;
          if (hovertemplate || hoverinfo && hoverinfo !== "none" && hoverinfo !== "skip") {
            var hoverCenterX;
            var hoverCenterY;
            if (isSunburst) {
              hoverCenterX = cd0.cx + pt.pxmid[0] * (1 - pt.rInscribed);
              hoverCenterY = cd0.cy + pt.pxmid[1] * (1 - pt.rInscribed);
            }
            if (isTreemapOrIcicle) {
              hoverCenterX = pt._hoverX;
              hoverCenterY = pt._hoverY;
            }
            var hoverPt = {};
            var parts = [];
            var thisText = [];
            var hasFlag = function(flag) {
              return parts.indexOf(flag) !== -1;
            };
            if (hoverinfo) {
              parts = hoverinfo === "all" ? traceNow._module.attributes.hoverinfo.flags : hoverinfo.split("+");
            }
            hoverPt.label = cdi.label;
            if (hasFlag("label") && hoverPt.label) thisText.push(hoverPt.label);
            if (cdi.hasOwnProperty("v")) {
              hoverPt.value = cdi.v;
              hoverPt.valueLabel = formatValue(hoverPt.value, separators);
              if (hasFlag("value")) thisText.push(hoverPt.valueLabel);
            }
            hoverPt.currentPath = pt.currentPath = helpers.getPath(pt.data);
            if (hasFlag("current path") && !isRoot) {
              thisText.push(hoverPt.currentPath);
            }
            var tx;
            var allPercents = [];
            var insertPercent = function() {
              if (allPercents.indexOf(tx) === -1) {
                thisText.push(tx);
                allPercents.push(tx);
              }
            };
            hoverPt.percentParent = pt.percentParent = val / helpers.getValue(parent);
            hoverPt.parent = pt.parentString = helpers.getPtLabel(parent);
            if (hasFlag("percent parent")) {
              tx = helpers.formatPercent(hoverPt.percentParent, separators) + " of " + hoverPt.parent;
              insertPercent();
            }
            hoverPt.percentEntry = pt.percentEntry = val / helpers.getValue(entry);
            hoverPt.entry = pt.entry = helpers.getPtLabel(entry);
            if (hasFlag("percent entry") && !isRoot && !pt.onPathbar) {
              tx = helpers.formatPercent(hoverPt.percentEntry, separators) + " of " + hoverPt.entry;
              insertPercent();
            }
            hoverPt.percentRoot = pt.percentRoot = val / helpers.getValue(hierarchy);
            hoverPt.root = pt.root = helpers.getPtLabel(hierarchy);
            if (hasFlag("percent root") && !isRoot) {
              tx = helpers.formatPercent(hoverPt.percentRoot, separators) + " of " + hoverPt.root;
              insertPercent();
            }
            hoverPt.text = _cast("hovertext") || _cast("text");
            if (hasFlag("text")) {
              tx = hoverPt.text;
              if (Lib.isValidTextValue(tx)) thisText.push(tx);
            }
            eventData = [makeEventData(pt, traceNow, opts.eventDataKeys)];
            var hoverItems = {
              trace: traceNow,
              y: hoverCenterY,
              _x0: pt._x0,
              _x1: pt._x1,
              _y0: pt._y0,
              _y1: pt._y1,
              text: thisText.join("<br>"),
              name: hovertemplate || hasFlag("name") ? traceNow.name : void 0,
              color: _cast("hoverlabel.bgcolor") || cdi.color,
              borderColor: _cast("hoverlabel.bordercolor"),
              fontFamily: _cast("hoverlabel.font.family"),
              fontSize: _cast("hoverlabel.font.size"),
              fontColor: _cast("hoverlabel.font.color"),
              fontWeight: _cast("hoverlabel.font.weight"),
              fontStyle: _cast("hoverlabel.font.style"),
              fontVariant: _cast("hoverlabel.font.variant"),
              nameLength: _cast("hoverlabel.namelength"),
              textAlign: _cast("hoverlabel.align"),
              hovertemplate,
              hovertemplateLabels: hoverPt,
              eventData
            };
            if (isSunburst) {
              hoverItems.x0 = hoverCenterX - pt.rInscribed * pt.rpx1;
              hoverItems.x1 = hoverCenterX + pt.rInscribed * pt.rpx1;
              hoverItems.idealAlign = pt.pxmid[0] < 0 ? "left" : "right";
            }
            if (isTreemapOrIcicle) {
              hoverItems.x = hoverCenterX;
              hoverItems.idealAlign = hoverCenterX < 0 ? "left" : "right";
            }
            var bbox = [];
            Fx.loneHover(hoverItems, {
              container: fullLayoutNow._hoverlayer.node(),
              outerContainer: fullLayoutNow._paper.node(),
              gd,
              inOut_bbox: bbox
            });
            eventData[0].bbox = bbox[0];
            trace._hasHoverLabel = true;
          }
          if (isTreemapOrIcicle) {
            var slice = sliceTop.select("path.surface");
            opts.styleOne(slice, pt, traceNow, gd, {
              hovered: true
            });
          }
          trace._hasHoverEvent = true;
          gd.emit("plotly_hover", {
            points: eventData || [makeEventData(pt, traceNow, opts.eventDataKeys)],
            event: d3.event
          });
        };
        var onMouseOut = function(evt) {
          var fullLayoutNow = gd._fullLayout;
          var traceNow = gd._fullData[trace.index];
          var pt = d3.select(this).datum();
          if (trace._hasHoverEvent) {
            evt.originalEvent = d3.event;
            gd.emit("plotly_unhover", {
              points: [makeEventData(pt, traceNow, opts.eventDataKeys)],
              event: d3.event
            });
            trace._hasHoverEvent = false;
          }
          if (trace._hasHoverLabel) {
            Fx.loneUnhover(fullLayoutNow._hoverlayer.node());
            trace._hasHoverLabel = false;
          }
          if (isTreemapOrIcicle) {
            var slice = sliceTop.select("path.surface");
            opts.styleOne(slice, pt, traceNow, gd, {
              hovered: false
            });
          }
        };
        var onClick = function(pt) {
          var fullLayoutNow = gd._fullLayout;
          var traceNow = gd._fullData[trace.index];
          var noTransition = isSunburst && (helpers.isHierarchyRoot(pt) || helpers.isLeaf(pt));
          var id = helpers.getPtId(pt);
          var nextEntry = helpers.isEntry(pt) ? helpers.findEntryWithChild(hierarchy, id) : helpers.findEntryWithLevel(hierarchy, id);
          var nextLevel = helpers.getPtId(nextEntry);
          var typeClickEvtData = {
            points: [makeEventData(pt, traceNow, opts.eventDataKeys)],
            event: d3.event
          };
          if (!noTransition) typeClickEvtData.nextLevel = nextLevel;
          var clickVal = Events.triggerHandler(gd, "plotly_" + trace.type + "click", typeClickEvtData);
          if (clickVal !== false && fullLayoutNow.hovermode) {
            gd._hoverdata = [makeEventData(pt, traceNow, opts.eventDataKeys)];
            Fx.click(gd, d3.event);
          }
          if (noTransition) return;
          if (clickVal === false) return;
          if (gd._dragging) return;
          if (gd._transitioning) return;
          Registry.call("_storeDirectGUIEdit", traceNow, fullLayoutNow._tracePreGUI[traceNow.uid], {
            level: traceNow.level
          });
          var frame = {
            data: [{ level: nextLevel }],
            traces: [trace.index]
          };
          var animOpts = {
            frame: {
              redraw: false,
              duration: opts.transitionTime
            },
            transition: {
              duration: opts.transitionTime,
              easing: opts.transitionEasing
            },
            mode: "immediate",
            fromcurrent: true
          };
          Fx.loneUnhover(fullLayoutNow._hoverlayer.node());
          Registry.call("animate", gd, frame, animOpts);
        };
        sliceTop.on("mouseover", onMouseOver);
        sliceTop.on("mouseout", onMouseOut);
        sliceTop.on("click", onClick);
      };
      function makeEventData(pt, trace, keys) {
        var cdi = pt.data.data;
        var out = {
          curveNumber: trace.index,
          pointNumber: cdi.i,
          data: trace._input,
          fullData: trace
          // TODO more things like 'children', 'siblings', 'hierarchy?
        };
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          if (key in pt) out[key] = pt[key];
        }
        if ("parentString" in pt && !helpers.isHierarchyRoot(pt)) out.parent = pt.parentString;
        appendArrayPointValue(out, trace, cdi.i);
        return out;
      }
    }
  });

  // src/traces/sunburst/plot.js
  var require_plot13 = __commonJS({
    "src/traces/sunburst/plot.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var d3Hierarchy = require_d3_hierarchy();
      var interpolate = (init_src2(), __toCommonJS(src_exports)).interpolate;
      var Drawing = require_drawing();
      var Lib = require_lib();
      var svgTextUtils = require_svg_text_utils();
      var uniformText = require_uniform_text();
      var recordMinTextSize = uniformText.recordMinTextSize;
      var clearMinTextSize = uniformText.clearMinTextSize;
      var piePlot = require_plot12();
      var getRotationAngle = require_helpers4().getRotationAngle;
      var computeTransform = piePlot.computeTransform;
      var transformInsideText = piePlot.transformInsideText;
      var styleOne = require_style13().styleOne;
      var resizeText = require_style4().resizeText;
      var attachFxHandlers = require_fx2();
      var constants = require_constants20();
      var helpers = require_helpers15();
      exports.plot = function(gd, cdmodule, transitionOpts, makeOnCompleteCallback) {
        var fullLayout = gd._fullLayout;
        var layer = fullLayout._sunburstlayer;
        var join, onComplete;
        var isFullReplot = !transitionOpts;
        var hasTransition = !fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts);
        clearMinTextSize("sunburst", fullLayout);
        join = layer.selectAll("g.trace.sunburst").data(cdmodule, function(cd) {
          return cd[0].trace.uid;
        });
        join.enter().append("g").classed("trace", true).classed("sunburst", true).attr("stroke-linejoin", "round");
        join.order();
        if (hasTransition) {
          if (makeOnCompleteCallback) {
            onComplete = makeOnCompleteCallback();
          }
          var transition = d3.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() {
            onComplete && onComplete();
          }).each("interrupt", function() {
            onComplete && onComplete();
          });
          transition.each(function() {
            layer.selectAll("g.trace").each(function(cd) {
              plotOne(gd, cd, this, transitionOpts);
            });
          });
        } else {
          join.each(function(cd) {
            plotOne(gd, cd, this, transitionOpts);
          });
          if (fullLayout.uniformtext.mode) {
            resizeText(gd, fullLayout._sunburstlayer.selectAll(".trace"), "sunburst");
          }
        }
        if (isFullReplot) {
          join.exit().remove();
        }
      };
      function plotOne(gd, cd, element, transitionOpts) {
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var hasTransition = !fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts);
        var gTrace = d3.select(element);
        var slices = gTrace.selectAll("g.slice");
        var cd0 = cd[0];
        var trace = cd0.trace;
        var hierarchy = cd0.hierarchy;
        var entry = helpers.findEntryWithLevel(hierarchy, trace.level);
        var maxDepth = helpers.getMaxDepth(trace);
        var gs = fullLayout._size;
        var domain = trace.domain;
        var vpw = gs.w * (domain.x[1] - domain.x[0]);
        var vph = gs.h * (domain.y[1] - domain.y[0]);
        var rMax = 0.5 * Math.min(vpw, vph);
        var cx = cd0.cx = gs.l + gs.w * (domain.x[1] + domain.x[0]) / 2;
        var cy = cd0.cy = gs.t + gs.h * (1 - domain.y[0]) - vph / 2;
        if (!entry) {
          return slices.remove();
        }
        var prevEntry = null;
        var prevLookup = {};
        if (hasTransition) {
          slices.each(function(pt) {
            prevLookup[helpers.getPtId(pt)] = {
              rpx0: pt.rpx0,
              rpx1: pt.rpx1,
              x0: pt.x0,
              x1: pt.x1,
              transform: pt.transform
            };
            if (!prevEntry && helpers.isEntry(pt)) {
              prevEntry = pt;
            }
          });
        }
        var sliceData = partition(entry).descendants();
        var maxHeight = entry.height + 1;
        var yOffset = 0;
        var cutoff = maxDepth;
        if (cd0.hasMultipleRoots && helpers.isHierarchyRoot(entry)) {
          sliceData = sliceData.slice(1);
          maxHeight -= 1;
          yOffset = 1;
          cutoff += 1;
        }
        sliceData = sliceData.filter(function(pt) {
          return pt.y1 <= cutoff;
        });
        var baseX = getRotationAngle(trace.rotation);
        if (baseX) {
          sliceData.forEach(function(pt) {
            pt.x0 += baseX;
            pt.x1 += baseX;
          });
        }
        var maxY = Math.min(maxHeight, maxDepth);
        var y2rpx = function(y) {
          return (y - yOffset) / maxY * rMax;
        };
        var rx2px = function(r, x) {
          return [r * Math.cos(x), -r * Math.sin(x)];
        };
        var pathSlice = function(d) {
          return Lib.pathAnnulus(d.rpx0, d.rpx1, d.x0, d.x1, cx, cy);
        };
        var getTargetX = function(d) {
          return cx + getTextXY(d)[0] * (d.transform.rCenter || 0) + (d.transform.x || 0);
        };
        var getTargetY = function(d) {
          return cy + getTextXY(d)[1] * (d.transform.rCenter || 0) + (d.transform.y || 0);
        };
        slices = slices.data(sliceData, helpers.getPtId);
        slices.enter().append("g").classed("slice", true);
        if (hasTransition) {
          slices.exit().transition().each(function() {
            var sliceTop = d3.select(this);
            var slicePath = sliceTop.select("path.surface");
            slicePath.transition().attrTween("d", function(pt2) {
              var interp = makeExitSliceInterpolator(pt2);
              return function(t) {
                return pathSlice(interp(t));
              };
            });
            var sliceTextGroup = sliceTop.select("g.slicetext");
            sliceTextGroup.attr("opacity", 0);
          }).remove();
        } else {
          slices.exit().remove();
        }
        slices.order();
        var nextX1ofPrevEntry = null;
        if (hasTransition && prevEntry) {
          var prevEntryId = helpers.getPtId(prevEntry);
          slices.each(function(pt) {
            if (nextX1ofPrevEntry === null && helpers.getPtId(pt) === prevEntryId) {
              nextX1ofPrevEntry = pt.x1;
            }
          });
        }
        var updateSlices = slices;
        if (hasTransition) {
          updateSlices = updateSlices.transition().each("end", function() {
            var sliceTop = d3.select(this);
            helpers.setSliceCursor(sliceTop, gd, {
              hideOnRoot: true,
              hideOnLeaves: true,
              isTransitioning: false
            });
          });
        }
        updateSlices.each(function(pt) {
          var sliceTop = d3.select(this);
          var slicePath = Lib.ensureSingle(sliceTop, "path", "surface", function(s) {
            s.style("pointer-events", isStatic ? "none" : "all");
          });
          pt.rpx0 = y2rpx(pt.y0);
          pt.rpx1 = y2rpx(pt.y1);
          pt.xmid = (pt.x0 + pt.x1) / 2;
          pt.pxmid = rx2px(pt.rpx1, pt.xmid);
          pt.midangle = -(pt.xmid - Math.PI / 2);
          pt.startangle = -(pt.x0 - Math.PI / 2);
          pt.stopangle = -(pt.x1 - Math.PI / 2);
          pt.halfangle = 0.5 * Math.min(Lib.angleDelta(pt.x0, pt.x1) || Math.PI, Math.PI);
          pt.ring = 1 - pt.rpx0 / pt.rpx1;
          pt.rInscribed = getInscribedRadiusFraction(pt, trace);
          if (hasTransition) {
            slicePath.transition().attrTween("d", function(pt2) {
              var interp = makeUpdateSliceInterpolator(pt2);
              return function(t) {
                return pathSlice(interp(t));
              };
            });
          } else {
            slicePath.attr("d", pathSlice);
          }
          sliceTop.call(attachFxHandlers, entry, gd, cd, {
            eventDataKeys: constants.eventDataKeys,
            transitionTime: constants.CLICK_TRANSITION_TIME,
            transitionEasing: constants.CLICK_TRANSITION_EASING
          }).call(helpers.setSliceCursor, gd, {
            hideOnRoot: true,
            hideOnLeaves: true,
            isTransitioning: gd._transitioning
          });
          slicePath.call(styleOne, pt, trace, gd);
          var sliceTextGroup = Lib.ensureSingle(sliceTop, "g", "slicetext");
          var sliceText = Lib.ensureSingle(sliceTextGroup, "text", "", function(s) {
            s.attr("data-notex", 1);
          });
          var font = Lib.ensureUniformFontSize(gd, helpers.determineTextFont(trace, pt, fullLayout.font));
          sliceText.text(exports.formatSliceLabel(pt, entry, trace, cd, fullLayout)).classed("slicetext", true).attr("text-anchor", "middle").call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
          var textBB = Drawing.bBox(sliceText.node());
          pt.transform = transformInsideText(textBB, pt, cd0);
          pt.transform.targetX = getTargetX(pt);
          pt.transform.targetY = getTargetY(pt);
          var strTransform = function(d, textBB2) {
            var transform = d.transform;
            computeTransform(transform, textBB2);
            transform.fontSize = font.size;
            recordMinTextSize(trace.type, transform, fullLayout);
            return Lib.getTextTransform(transform);
          };
          if (hasTransition) {
            sliceText.transition().attrTween("transform", function(pt2) {
              var interp = makeUpdateTextInterpolator(pt2);
              return function(t) {
                return strTransform(interp(t), textBB);
              };
            });
          } else {
            sliceText.attr("transform", strTransform(pt, textBB));
          }
        });
        function makeExitSliceInterpolator(pt) {
          var id = helpers.getPtId(pt);
          var prev = prevLookup[id];
          var entryPrev = prevLookup[helpers.getPtId(entry)];
          var next;
          if (entryPrev) {
            var a = (pt.x1 > entryPrev.x1 ? 2 * Math.PI : 0) + baseX;
            next = pt.rpx1 < entryPrev.rpx1 ? { x0: pt.x0, x1: pt.x1, rpx0: 0, rpx1: 0 } : { x0: a, x1: a, rpx0: pt.rpx0, rpx1: pt.rpx1 };
          } else {
            var parent;
            var parentId = helpers.getPtId(pt.parent);
            slices.each(function(pt2) {
              if (helpers.getPtId(pt2) === parentId) {
                return parent = pt2;
              }
            });
            var parentChildren = parent.children;
            var ci;
            parentChildren.forEach(function(pt2, i) {
              if (helpers.getPtId(pt2) === id) {
                return ci = i;
              }
            });
            var n = parentChildren.length;
            var interp = interpolate(parent.x0, parent.x1);
            next = {
              rpx0: rMax,
              rpx1: rMax,
              x0: interp(ci / n),
              x1: interp((ci + 1) / n)
            };
          }
          return interpolate(prev, next);
        }
        function makeUpdateSliceInterpolator(pt) {
          var prev0 = prevLookup[helpers.getPtId(pt)];
          var prev;
          var next = { x0: pt.x0, x1: pt.x1, rpx0: pt.rpx0, rpx1: pt.rpx1 };
          if (prev0) {
            prev = prev0;
          } else {
            if (prevEntry) {
              if (pt.parent) {
                if (nextX1ofPrevEntry) {
                  var a = (pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0) + baseX;
                  prev = { x0: a, x1: a };
                } else {
                  prev = { rpx0: rMax, rpx1: rMax };
                  Lib.extendFlat(prev, interpX0X1FromParent(pt));
                }
              } else {
                prev = { rpx0: 0, rpx1: 0 };
              }
            } else {
              prev = { x0: baseX, x1: baseX };
            }
          }
          return interpolate(prev, next);
        }
        function makeUpdateTextInterpolator(pt) {
          var prev0 = prevLookup[helpers.getPtId(pt)];
          var prev;
          var transform = pt.transform;
          if (prev0) {
            prev = prev0;
          } else {
            prev = {
              rpx1: pt.rpx1,
              transform: {
                textPosAngle: transform.textPosAngle,
                scale: 0,
                rotate: transform.rotate,
                rCenter: transform.rCenter,
                x: transform.x,
                y: transform.y
              }
            };
            if (prevEntry) {
              if (pt.parent) {
                if (nextX1ofPrevEntry) {
                  var a = pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0;
                  prev.x0 = prev.x1 = a;
                } else {
                  Lib.extendFlat(prev, interpX0X1FromParent(pt));
                }
              } else {
                prev.x0 = prev.x1 = baseX;
              }
            } else {
              prev.x0 = prev.x1 = baseX;
            }
          }
          var textPosAngleFn = interpolate(prev.transform.textPosAngle, pt.transform.textPosAngle);
          var rpx1Fn = interpolate(prev.rpx1, pt.rpx1);
          var x0Fn = interpolate(prev.x0, pt.x0);
          var x1Fn = interpolate(prev.x1, pt.x1);
          var scaleFn = interpolate(prev.transform.scale, transform.scale);
          var rotateFn = interpolate(prev.transform.rotate, transform.rotate);
          var pow = transform.rCenter === 0 ? 3 : prev.transform.rCenter === 0 ? 1 / 3 : 1;
          var _rCenterFn = interpolate(prev.transform.rCenter, transform.rCenter);
          var rCenterFn = function(t) {
            return _rCenterFn(Math.pow(t, pow));
          };
          return function(t) {
            var rpx1 = rpx1Fn(t);
            var x0 = x0Fn(t);
            var x1 = x1Fn(t);
            var rCenter = rCenterFn(t);
            var pxmid = rx2px(rpx1, (x0 + x1) / 2);
            var textPosAngle = textPosAngleFn(t);
            var d = {
              pxmid,
              rpx1,
              transform: {
                textPosAngle,
                rCenter,
                x: transform.x,
                y: transform.y
              }
            };
            recordMinTextSize(trace.type, transform, fullLayout);
            return {
              transform: {
                targetX: getTargetX(d),
                targetY: getTargetY(d),
                scale: scaleFn(t),
                rotate: rotateFn(t),
                rCenter
              }
            };
          };
        }
        function interpX0X1FromParent(pt) {
          var parent = pt.parent;
          var parentPrev = prevLookup[helpers.getPtId(parent)];
          var out = {};
          if (parentPrev) {
            var parentChildren = parent.children;
            var ci = parentChildren.indexOf(pt);
            var n = parentChildren.length;
            var interp = interpolate(parentPrev.x0, parentPrev.x1);
            out.x0 = interp(ci / n);
            out.x1 = interp(ci / n);
          } else {
            out.x0 = out.x1 = 0;
          }
          return out;
        }
      }
      function partition(entry) {
        return d3Hierarchy.partition().size([2 * Math.PI, entry.height + 1])(entry);
      }
      exports.formatSliceLabel = function(pt, entry, trace, cd, fullLayout) {
        var texttemplate = trace.texttemplate;
        var textinfo = trace.textinfo;
        if (!texttemplate && (!textinfo || textinfo === "none")) {
          return "";
        }
        var separators = fullLayout.separators;
        var cd0 = cd[0];
        var cdi = pt.data.data;
        var hierarchy = cd0.hierarchy;
        var isRoot = helpers.isHierarchyRoot(pt);
        var parent = helpers.getParent(hierarchy, pt);
        var val = helpers.getValue(pt);
        if (!texttemplate) {
          var parts = textinfo.split("+");
          var hasFlag = function(flag) {
            return parts.indexOf(flag) !== -1;
          };
          var thisText = [];
          var tx;
          if (hasFlag("label") && cdi.label) {
            thisText.push(cdi.label);
          }
          if (cdi.hasOwnProperty("v") && hasFlag("value")) {
            thisText.push(helpers.formatValue(cdi.v, separators));
          }
          if (!isRoot) {
            if (hasFlag("current path")) {
              thisText.push(helpers.getPath(pt.data));
            }
            var nPercent = 0;
            if (hasFlag("percent parent")) nPercent++;
            if (hasFlag("percent entry")) nPercent++;
            if (hasFlag("percent root")) nPercent++;
            var hasMultiplePercents = nPercent > 1;
            if (nPercent) {
              var percent;
              var addPercent = function(key) {
                tx = helpers.formatPercent(percent, separators);
                if (hasMultiplePercents) tx += " of " + key;
                thisText.push(tx);
              };
              if (hasFlag("percent parent") && !isRoot) {
                percent = val / helpers.getValue(parent);
                addPercent("parent");
              }
              if (hasFlag("percent entry")) {
                percent = val / helpers.getValue(entry);
                addPercent("entry");
              }
              if (hasFlag("percent root")) {
                percent = val / helpers.getValue(hierarchy);
                addPercent("root");
              }
            }
          }
          if (hasFlag("text")) {
            tx = Lib.castOption(trace, cdi.i, "text");
            if (Lib.isValidTextValue(tx)) thisText.push(tx);
          }
          return thisText.join("<br>");
        }
        var txt = Lib.castOption(trace, cdi.i, "texttemplate");
        if (!txt) return "";
        var obj = {};
        if (cdi.label) obj.label = cdi.label;
        if (cdi.hasOwnProperty("v")) {
          obj.value = cdi.v;
          obj.valueLabel = helpers.formatValue(cdi.v, separators);
        }
        obj.currentPath = helpers.getPath(pt.data);
        if (!isRoot) {
          obj.percentParent = val / helpers.getValue(parent);
          obj.percentParentLabel = helpers.formatPercent(obj.percentParent, separators);
          obj.parent = helpers.getPtLabel(parent);
        }
        obj.percentEntry = val / helpers.getValue(entry);
        obj.percentEntryLabel = helpers.formatPercent(obj.percentEntry, separators);
        obj.entry = helpers.getPtLabel(entry);
        obj.percentRoot = val / helpers.getValue(hierarchy);
        obj.percentRootLabel = helpers.formatPercent(obj.percentRoot, separators);
        obj.root = helpers.getPtLabel(hierarchy);
        if (cdi.hasOwnProperty("color")) {
          obj.color = cdi.color;
        }
        var ptTx = Lib.castOption(trace, cdi.i, "text");
        if (Lib.isValidTextValue(ptTx) || ptTx === "") obj.text = ptTx;
        obj.customdata = Lib.castOption(trace, cdi.i, "customdata");
        return Lib.texttemplateString({
          data: [obj, trace._meta],
          fallback: trace.texttemplatefallback,
          labels: obj,
          locale: fullLayout._d3locale,
          template: txt
        });
      };
      function getInscribedRadiusFraction(pt) {
        if (pt.rpx0 === 0 && Lib.isFullCircle([pt.x0, pt.x1])) {
          return 1;
        } else {
          return Math.max(0, Math.min(1 / (1 + 1 / Math.sin(pt.halfangle)), pt.ring / 2));
        }
      }
      function getTextXY(d) {
        return getCoords(d.rpx1, d.transform.textPosAngle);
      }
      function getCoords(r, angle) {
        return [r * Math.sin(angle), -r * Math.cos(angle)];
      }
    }
  });

  // src/traces/sunburst/index.js
  var require_sunburst = __commonJS({
    "src/traces/sunburst/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "sunburst",
        basePlotModule: require_base_plot2(),
        categories: [],
        animatable: true,
        attributes: require_attributes36(),
        layoutAttributes: require_layout_attributes13(),
        supplyDefaults: require_defaults32(),
        supplyLayoutDefaults: require_layout_defaults12(),
        calc: require_calc17().calc,
        crossTraceCalc: require_calc17().crossTraceCalc,
        plot: require_plot13().plot,
        style: require_style13().style,
        colorbar: require_marker_colorbar(),
        meta: {}
      };
    }
  });

  // lib/sunburst.js
  var require_sunburst2 = __commonJS({
    "lib/sunburst.js"(exports, module) {
      "use strict";
      module.exports = require_sunburst();
    }
  });

  // src/traces/treemap/base_plot.js
  var require_base_plot3 = __commonJS({
    "src/traces/treemap/base_plot.js"(exports) {
      "use strict";
      var plots = require_plots();
      exports.name = "treemap";
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        plots.plotBasePlot(exports.name, gd, traces, transitionOpts, makeOnCompleteCallback);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        plots.cleanBasePlot(exports.name, newFullData, newFullLayout, oldFullData, oldFullLayout);
      };
    }
  });

  // src/traces/treemap/constants.js
  var require_constants21 = __commonJS({
    "src/traces/treemap/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        CLICK_TRANSITION_TIME: 750,
        CLICK_TRANSITION_EASING: "poly",
        eventDataKeys: [
          // string
          "currentPath",
          "root",
          "entry",
          // no need to add 'parent' here
          // percentages i.e. ratios
          "percentRoot",
          "percentEntry",
          "percentParent"
        ],
        gapWithPathbar: 1
        // i.e. one pixel
      };
    }
  });

  // src/traces/treemap/attributes.js
  var require_attributes37 = __commonJS({
    "src/traces/treemap/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorScaleAttrs = require_attributes8();
      var domainAttrs = require_domain().attributes;
      var pieAttrs = require_attributes35();
      var sunburstAttrs = require_attributes36();
      var constants = require_constants21();
      var extendFlat = require_extend().extendFlat;
      var pattern = require_attributes4().pattern;
      module.exports = {
        labels: sunburstAttrs.labels,
        parents: sunburstAttrs.parents,
        values: sunburstAttrs.values,
        branchvalues: sunburstAttrs.branchvalues,
        count: sunburstAttrs.count,
        level: sunburstAttrs.level,
        maxdepth: sunburstAttrs.maxdepth,
        tiling: {
          packing: {
            valType: "enumerated",
            values: ["squarify", "binary", "dice", "slice", "slice-dice", "dice-slice"],
            dflt: "squarify",
            editType: "plot"
          },
          squarifyratio: {
            valType: "number",
            min: 1,
            dflt: 1,
            editType: "plot"
          },
          flip: {
            valType: "flaglist",
            flags: ["x", "y"],
            dflt: "",
            editType: "plot"
          },
          pad: {
            valType: "number",
            min: 0,
            dflt: 3,
            editType: "plot"
          },
          editType: "calc"
        },
        marker: extendFlat(
          {
            pad: {
              t: {
                valType: "number",
                min: 0,
                editType: "plot"
              },
              l: {
                valType: "number",
                min: 0,
                editType: "plot"
              },
              r: {
                valType: "number",
                min: 0,
                editType: "plot"
              },
              b: {
                valType: "number",
                min: 0,
                editType: "plot"
              },
              editType: "calc"
            },
            colors: sunburstAttrs.marker.colors,
            pattern,
            depthfade: {
              valType: "enumerated",
              values: [true, false, "reversed"],
              editType: "style"
            },
            line: sunburstAttrs.marker.line,
            cornerradius: {
              valType: "number",
              min: 0,
              dflt: 0,
              editType: "plot"
            },
            editType: "calc"
          },
          colorScaleAttrs("marker", {
            colorAttr: "colors",
            anim: false
            // TODO: set to anim: true?
          })
        ),
        pathbar: {
          visible: {
            valType: "boolean",
            dflt: true,
            editType: "plot"
          },
          side: {
            valType: "enumerated",
            values: ["top", "bottom"],
            dflt: "top",
            editType: "plot"
          },
          edgeshape: {
            valType: "enumerated",
            values: [">", "<", "|", "/", "\\"],
            dflt: ">",
            editType: "plot"
          },
          thickness: {
            valType: "number",
            min: 12,
            editType: "plot"
          },
          textfont: extendFlat({}, pieAttrs.textfont, {}),
          editType: "calc"
        },
        text: pieAttrs.text,
        textinfo: sunburstAttrs.textinfo,
        // TODO: incorporate `label` and `value` in the eventData
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: constants.eventDataKeys.concat(["label", "value"]) }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: pieAttrs.hovertext,
        hoverinfo: sunburstAttrs.hoverinfo,
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        textfont: pieAttrs.textfont,
        insidetextfont: pieAttrs.insidetextfont,
        outsidetextfont: extendFlat({}, pieAttrs.outsidetextfont, {}),
        textposition: {
          valType: "enumerated",
          values: [
            "top left",
            "top center",
            "top right",
            "middle left",
            "middle center",
            "middle right",
            "bottom left",
            "bottom center",
            "bottom right"
          ],
          dflt: "top left",
          editType: "plot"
        },
        sort: pieAttrs.sort,
        root: sunburstAttrs.root,
        domain: domainAttrs({ name: "treemap", trace: true, editType: "calc" })
      };
    }
  });

  // src/traces/treemap/layout_attributes.js
  var require_layout_attributes14 = __commonJS({
    "src/traces/treemap/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        treemapcolorway: {
          valType: "colorlist",
          editType: "calc"
        },
        extendtreemapcolors: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/treemap/defaults.js
  var require_defaults33 = __commonJS({
    "src/traces/treemap/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes37();
      var Color2 = require_color();
      var handleDomainDefaults = require_domain().defaults;
      var handleText = require_defaults19().handleText;
      var TEXTPAD = require_constants9().TEXTPAD;
      var handleMarkerDefaults = require_defaults31().handleMarkerDefaults;
      var Colorscale = require_colorscale();
      var hasColorscale = Colorscale.hasColorscale;
      var colorscaleDefaults = Colorscale.handleDefaults;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var labels = coerce("labels");
        var parents = coerce("parents");
        if (!labels || !labels.length || !parents || !parents.length) {
          traceOut.visible = false;
          return;
        }
        var vals = coerce("values");
        if (vals && vals.length) {
          coerce("branchvalues");
        } else {
          coerce("count");
        }
        coerce("level");
        coerce("maxdepth");
        var packing = coerce("tiling.packing");
        if (packing === "squarify") {
          coerce("tiling.squarifyratio");
        }
        coerce("tiling.flip");
        coerce("tiling.pad");
        var text = coerce("text");
        coerce("texttemplate");
        coerce("texttemplatefallback");
        if (!traceOut.texttemplate) coerce("textinfo", Lib.isArrayOrTypedArray(text) ? "text+label" : "label");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var hasPathbar = coerce("pathbar.visible");
        var textposition = "auto";
        handleText(traceIn, traceOut, layout, coerce, textposition, {
          hasPathbar,
          moduleHasSelected: false,
          moduleHasUnselected: false,
          moduleHasConstrain: false,
          moduleHasCliponaxis: false,
          moduleHasTextangle: false,
          moduleHasInsideanchor: false
        });
        coerce("textposition");
        var bottomText = traceOut.textposition.indexOf("bottom") !== -1;
        handleMarkerDefaults(traceIn, traceOut, layout, coerce);
        var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, "marker", "colors") || (traceIn.marker || {}).coloraxis;
        if (withColorscale) {
          colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "marker.", cLetter: "c" });
        } else {
          coerce("marker.depthfade", !(traceOut.marker.colors || []).length);
        }
        var headerSize = traceOut.textfont.size * 2;
        coerce("marker.pad.t", bottomText ? headerSize / 4 : headerSize);
        coerce("marker.pad.l", headerSize / 4);
        coerce("marker.pad.r", headerSize / 4);
        coerce("marker.pad.b", bottomText ? headerSize : headerSize / 4);
        coerce("marker.cornerradius");
        traceOut._hovered = {
          marker: {
            line: {
              width: 2,
              color: Color2.contrast(layout.paper_bgcolor)
            }
          }
        };
        if (hasPathbar) {
          coerce("pathbar.thickness", traceOut.pathbar.textfont.size + 2 * TEXTPAD);
          coerce("pathbar.side");
          coerce("pathbar.edgeshape");
        }
        coerce("sort");
        coerce("root.color");
        handleDomainDefaults(traceOut, layout, coerce);
        traceOut._length = null;
      };
    }
  });

  // src/traces/treemap/layout_defaults.js
  var require_layout_defaults13 = __commonJS({
    "src/traces/treemap/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes14();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        coerce("treemapcolorway", layoutOut.colorway);
        coerce("extendtreemapcolors");
      };
    }
  });

  // src/traces/treemap/calc.js
  var require_calc18 = __commonJS({
    "src/traces/treemap/calc.js"(exports) {
      "use strict";
      var calc = require_calc17();
      exports.calc = function(gd, trace) {
        return calc.calc(gd, trace);
      };
      exports.crossTraceCalc = function(gd) {
        return calc._runCrossTraceCalc("treemap", gd);
      };
    }
  });

  // src/traces/treemap/flip_tree.js
  var require_flip_tree = __commonJS({
    "src/traces/treemap/flip_tree.js"(exports, module) {
      "use strict";
      module.exports = function flipTree(node, size, opts) {
        var tmp;
        if (opts.swapXY) {
          tmp = node.x0;
          node.x0 = node.y0;
          node.y0 = tmp;
          tmp = node.x1;
          node.x1 = node.y1;
          node.y1 = tmp;
        }
        if (opts.flipX) {
          tmp = node.x0;
          node.x0 = size[0] - node.x1;
          node.x1 = size[0] - tmp;
        }
        if (opts.flipY) {
          tmp = node.y0;
          node.y0 = size[1] - node.y1;
          node.y1 = size[1] - tmp;
        }
        var children = node.children;
        if (children) {
          for (var i = 0; i < children.length; i++) {
            flipTree(children[i], size, opts);
          }
        }
      };
    }
  });

  // src/traces/treemap/partition.js
  var require_partition = __commonJS({
    "src/traces/treemap/partition.js"(exports, module) {
      "use strict";
      var d3Hierarchy = require_d3_hierarchy();
      var flipTree = require_flip_tree();
      module.exports = function partition(entry, size, opts) {
        var flipX = opts.flipX;
        var flipY = opts.flipY;
        var swapXY = opts.packing === "dice-slice";
        var top = opts.pad[flipY ? "bottom" : "top"];
        var left = opts.pad[flipX ? "right" : "left"];
        var right = opts.pad[flipX ? "left" : "right"];
        var bottom = opts.pad[flipY ? "top" : "bottom"];
        var tmp;
        if (swapXY) {
          tmp = left;
          left = top;
          top = tmp;
          tmp = right;
          right = bottom;
          bottom = tmp;
        }
        var result = d3Hierarchy.treemap().tile(getTilingMethod(opts.packing, opts.squarifyratio)).paddingInner(opts.pad.inner).paddingLeft(left).paddingRight(right).paddingTop(top).paddingBottom(bottom).size(
          swapXY ? [size[1], size[0]] : size
        )(entry);
        if (swapXY || flipX || flipY) {
          flipTree(result, size, {
            swapXY,
            flipX,
            flipY
          });
        }
        return result;
      };
      function getTilingMethod(key, squarifyratio) {
        switch (key) {
          case "squarify":
            return d3Hierarchy.treemapSquarify.ratio(squarifyratio);
          case "binary":
            return d3Hierarchy.treemapBinary;
          case "dice":
            return d3Hierarchy.treemapDice;
          case "slice":
            return d3Hierarchy.treemapSlice;
          default:
            return d3Hierarchy.treemapSliceDice;
        }
      }
    }
  });

  // src/traces/treemap/style.js
  var require_style14 = __commonJS({
    "src/traces/treemap/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var Lib = require_lib();
      var helpers = require_helpers15();
      var resizeText = require_uniform_text().resizeText;
      var fillOne = require_fill_one2();
      function style(gd) {
        var s = gd._fullLayout._treemaplayer.selectAll(".trace");
        resizeText(gd, s, "treemap");
        s.each(function(cd) {
          var gTrace = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          gTrace.style("opacity", trace.opacity);
          gTrace.selectAll("path.surface").each(function(pt) {
            d3.select(this).call(styleOne, pt, trace, gd, {
              hovered: false
            });
          });
        });
      }
      function styleOne(s, pt, trace, gd, opts) {
        var hovered = (opts || {}).hovered;
        var cdi = pt.data.data;
        var ptNumber = cdi.i;
        var lineColor;
        var lineWidth;
        var fillColor = cdi.color;
        var isRoot = helpers.isHierarchyRoot(pt);
        var opacity = 1;
        if (hovered) {
          lineColor = trace._hovered.marker.line.color;
          lineWidth = trace._hovered.marker.line.width;
        } else {
          if (isRoot && fillColor === trace.root.color) {
            opacity = 100;
            lineColor = "rgba(0,0,0,0)";
            lineWidth = 0;
          } else {
            lineColor = Lib.castOption(trace, ptNumber, "marker.line.color") || Color2.defaultLine;
            lineWidth = Lib.castOption(trace, ptNumber, "marker.line.width") || 0;
            if (!trace._hasColorscale && !pt.onPathbar) {
              var depthfade = trace.marker.depthfade;
              if (depthfade) {
                var fadedColor = Color2.combine(Color2.addOpacity(trace._backgroundColor, 0.75), fillColor);
                var n;
                if (depthfade === true) {
                  var maxDepth = helpers.getMaxDepth(trace);
                  if (isFinite(maxDepth)) {
                    if (helpers.isLeaf(pt)) {
                      n = 0;
                    } else {
                      n = trace._maxVisibleLayers - (pt.data.depth - trace._entryDepth);
                    }
                  } else {
                    n = pt.data.height + 1;
                  }
                } else {
                  n = pt.data.depth - trace._entryDepth;
                  if (!trace._atRootLevel) n++;
                }
                if (n > 0) {
                  for (var i = 0; i < n; i++) {
                    var ratio = 0.5 * i / n;
                    fillColor = Color2.combine(Color2.addOpacity(fadedColor, ratio), fillColor);
                  }
                }
              }
            }
          }
        }
        s.call(fillOne, pt, trace, gd, fillColor).style("stroke-width", lineWidth).call(Color2.stroke, lineColor).style("opacity", opacity);
      }
      module.exports = {
        style,
        styleOne
      };
    }
  });

  // src/traces/treemap/draw_ancestors.js
  var require_draw_ancestors = __commonJS({
    "src/traces/treemap/draw_ancestors.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var svgTextUtils = require_svg_text_utils();
      var partition = require_partition();
      var styleOne = require_style14().styleOne;
      var constants = require_constants21();
      var helpers = require_helpers15();
      var attachFxHandlers = require_fx2();
      var onPathbar = true;
      module.exports = function drawAncestors(gd, cd, entry, slices, opts) {
        var barDifY = opts.barDifY;
        var width = opts.width;
        var height = opts.height;
        var viewX = opts.viewX;
        var viewY = opts.viewY;
        var pathSlice = opts.pathSlice;
        var toMoveInsideSlice = opts.toMoveInsideSlice;
        var strTransform = opts.strTransform;
        var hasTransition = opts.hasTransition;
        var handleSlicesExit = opts.handleSlicesExit;
        var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator;
        var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator;
        var refRect = {};
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var cd0 = cd[0];
        var trace = cd0.trace;
        var hierarchy = cd0.hierarchy;
        var eachWidth = width / trace._entryDepth;
        var pathIds = helpers.listPath(entry.data, "id");
        var sliceData = partition(hierarchy.copy(), [width, height], {
          packing: "dice",
          pad: {
            inner: 0,
            top: 0,
            left: 0,
            right: 0,
            bottom: 0
          }
        }).descendants();
        sliceData = sliceData.filter(function(pt) {
          var level = pathIds.indexOf(pt.data.id);
          if (level === -1) return false;
          pt.x0 = eachWidth * level;
          pt.x1 = eachWidth * (level + 1);
          pt.y0 = barDifY;
          pt.y1 = barDifY + height;
          pt.onPathbar = true;
          return true;
        });
        sliceData.reverse();
        slices = slices.data(sliceData, helpers.getPtId);
        slices.enter().append("g").classed("pathbar", true);
        handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice);
        slices.order();
        var updateSlices = slices;
        if (hasTransition) {
          updateSlices = updateSlices.transition().each("end", function() {
            var sliceTop = d3.select(this);
            helpers.setSliceCursor(sliceTop, gd, {
              hideOnRoot: false,
              hideOnLeaves: false,
              isTransitioning: false
            });
          });
        }
        updateSlices.each(function(pt) {
          pt._x0 = viewX(pt.x0);
          pt._x1 = viewX(pt.x1);
          pt._y0 = viewY(pt.y0);
          pt._y1 = viewY(pt.y1);
          pt._hoverX = viewX(pt.x1 - Math.min(width, height) / 2);
          pt._hoverY = viewY(pt.y1 - height / 2);
          var sliceTop = d3.select(this);
          var slicePath = Lib.ensureSingle(sliceTop, "path", "surface", function(s) {
            s.style("pointer-events", isStatic ? "none" : "all");
          });
          if (hasTransition) {
            slicePath.transition().attrTween("d", function(pt2) {
              var interp = makeUpdateSliceInterpolator(pt2, onPathbar, refRect, [width, height]);
              return function(t) {
                return pathSlice(interp(t));
              };
            });
          } else {
            slicePath.attr("d", pathSlice);
          }
          sliceTop.call(attachFxHandlers, entry, gd, cd, {
            styleOne,
            eventDataKeys: constants.eventDataKeys,
            transitionTime: constants.CLICK_TRANSITION_TIME,
            transitionEasing: constants.CLICK_TRANSITION_EASING
          }).call(helpers.setSliceCursor, gd, {
            hideOnRoot: false,
            hideOnLeaves: false,
            isTransitioning: gd._transitioning
          });
          slicePath.call(styleOne, pt, trace, gd, {
            hovered: false
          });
          pt._text = (helpers.getPtLabel(pt) || "").split("<br>").join(" ") || "";
          var sliceTextGroup = Lib.ensureSingle(sliceTop, "g", "slicetext");
          var sliceText = Lib.ensureSingle(sliceTextGroup, "text", "", function(s) {
            s.attr("data-notex", 1);
          });
          var font = Lib.ensureUniformFontSize(gd, helpers.determineTextFont(trace, pt, fullLayout.font, {
            onPathbar: true
          }));
          sliceText.text(pt._text || " ").classed("slicetext", true).attr("text-anchor", "start").call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
          pt.textBB = Drawing.bBox(sliceText.node());
          pt.transform = toMoveInsideSlice(pt, {
            fontSize: font.size,
            onPathbar: true
          });
          pt.transform.fontSize = font.size;
          if (hasTransition) {
            sliceText.transition().attrTween("transform", function(pt2) {
              var interp = makeUpdateTextInterpolator(pt2, onPathbar, refRect, [width, height]);
              return function(t) {
                return strTransform(interp(t));
              };
            });
          } else {
            sliceText.attr("transform", strTransform(pt));
          }
        });
      };
    }
  });

  // src/traces/treemap/plot_one.js
  var require_plot_one = __commonJS({
    "src/traces/treemap/plot_one.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var interpolate = (init_src2(), __toCommonJS(src_exports)).interpolate;
      var helpers = require_helpers15();
      var Lib = require_lib();
      var TEXTPAD = require_constants9().TEXTPAD;
      var barPlot = require_plot3();
      var toMoveInsideBar = barPlot.toMoveInsideBar;
      var uniformText = require_uniform_text();
      var recordMinTextSize = uniformText.recordMinTextSize;
      var constants = require_constants21();
      var drawAncestors = require_draw_ancestors();
      function getKey(pt) {
        return helpers.isHierarchyRoot(pt) ? "" : (
          // don't use the dummyId
          helpers.getPtId(pt)
        );
      }
      module.exports = function plotOne(gd, cd, element, transitionOpts, drawDescendants) {
        var fullLayout = gd._fullLayout;
        var cd0 = cd[0];
        var trace = cd0.trace;
        var type = trace.type;
        var isIcicle = type === "icicle";
        var hierarchy = cd0.hierarchy;
        var entry = helpers.findEntryWithLevel(hierarchy, trace.level);
        var gTrace = d3.select(element);
        var selAncestors = gTrace.selectAll("g.pathbar");
        var selDescendants = gTrace.selectAll("g.slice");
        if (!entry) {
          selAncestors.remove();
          selDescendants.remove();
          return;
        }
        var isRoot = helpers.isHierarchyRoot(entry);
        var hasTransition = !fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts);
        var maxDepth = helpers.getMaxDepth(trace);
        var hasVisibleDepth = function(pt) {
          return pt.data.depth - entry.data.depth < maxDepth;
        };
        var gs = fullLayout._size;
        var domain = trace.domain;
        var vpw = gs.w * (domain.x[1] - domain.x[0]);
        var vph = gs.h * (domain.y[1] - domain.y[0]);
        var barW = vpw;
        var barH = trace.pathbar.thickness;
        var barPad = trace.marker.line.width + constants.gapWithPathbar;
        var barDifY = !trace.pathbar.visible ? 0 : trace.pathbar.side.indexOf("bottom") > -1 ? vph + barPad : -(barH + barPad);
        var pathbarOrigin = {
          x0: barW,
          // slide to the right
          x1: barW,
          y0: barDifY,
          y1: barDifY + barH
        };
        var findClosestEdge = function(pt, ref, size) {
          var e = trace.tiling.pad;
          var isLeftOfRect = function(x) {
            return x - e <= ref.x0;
          };
          var isRightOfRect = function(x) {
            return x + e >= ref.x1;
          };
          var isBottomOfRect = function(y) {
            return y - e <= ref.y0;
          };
          var isTopOfRect = function(y) {
            return y + e >= ref.y1;
          };
          if (pt.x0 === ref.x0 && pt.x1 === ref.x1 && pt.y0 === ref.y0 && pt.y1 === ref.y1) {
            return {
              x0: pt.x0,
              x1: pt.x1,
              y0: pt.y0,
              y1: pt.y1
            };
          }
          return {
            x0: isLeftOfRect(pt.x0 - e) ? 0 : isRightOfRect(pt.x0 - e) ? size[0] : pt.x0,
            x1: isLeftOfRect(pt.x1 + e) ? 0 : isRightOfRect(pt.x1 + e) ? size[0] : pt.x1,
            y0: isBottomOfRect(pt.y0 - e) ? 0 : isTopOfRect(pt.y0 - e) ? size[1] : pt.y0,
            y1: isBottomOfRect(pt.y1 + e) ? 0 : isTopOfRect(pt.y1 + e) ? size[1] : pt.y1
          };
        };
        var prevEntry = null;
        var prevLookupPathbar = {};
        var prevLookupSlices = {};
        var nextOfPrevEntry = null;
        var getPrev = function(pt, onPathbar) {
          return onPathbar ? prevLookupPathbar[getKey(pt)] : prevLookupSlices[getKey(pt)];
        };
        var getOrigin = function(pt, onPathbar, refRect, size) {
          if (onPathbar) {
            return prevLookupPathbar[getKey(hierarchy)] || pathbarOrigin;
          } else {
            var ref = prevLookupSlices[trace.level] || refRect;
            if (hasVisibleDepth(pt)) {
              return findClosestEdge(pt, ref, size);
            }
          }
          return {};
        };
        if (cd0.hasMultipleRoots && isRoot) {
          maxDepth++;
        }
        trace._maxDepth = maxDepth;
        trace._backgroundColor = fullLayout.paper_bgcolor;
        trace._entryDepth = entry.data.depth;
        trace._atRootLevel = isRoot;
        var cenX = -vpw / 2 + gs.l + gs.w * (domain.x[1] + domain.x[0]) / 2;
        var cenY = -vph / 2 + gs.t + gs.h * (1 - (domain.y[1] + domain.y[0]) / 2);
        var viewMapX = function(x) {
          return cenX + x;
        };
        var viewMapY = function(y) {
          return cenY + y;
        };
        var barY0 = viewMapY(0);
        var barX0 = viewMapX(0);
        var viewBarX = function(x) {
          return barX0 + x;
        };
        var viewBarY = function(y) {
          return barY0 + y;
        };
        function pos(x, y) {
          return x + "," + y;
        }
        var xStart = viewBarX(0);
        var limitX0 = function(p) {
          p.x = Math.max(xStart, p.x);
        };
        var edgeshape = trace.pathbar.edgeshape;
        var pathAncestor = function(d) {
          var _x0 = viewBarX(Math.max(Math.min(d.x0, d.x0), 0));
          var _x1 = viewBarX(Math.min(Math.max(d.x1, d.x1), barW));
          var _y0 = viewBarY(d.y0);
          var _y1 = viewBarY(d.y1);
          var halfH = barH / 2;
          var pL = {};
          var pR = {};
          pL.x = _x0;
          pR.x = _x1;
          pL.y = pR.y = (_y0 + _y1) / 2;
          var pA = { x: _x0, y: _y0 };
          var pB = { x: _x1, y: _y0 };
          var pC = { x: _x1, y: _y1 };
          var pD = { x: _x0, y: _y1 };
          if (edgeshape === ">") {
            pA.x -= halfH;
            pB.x -= halfH;
            pC.x -= halfH;
            pD.x -= halfH;
          } else if (edgeshape === "/") {
            pC.x -= halfH;
            pD.x -= halfH;
            pL.x -= halfH / 2;
            pR.x -= halfH / 2;
          } else if (edgeshape === "\\") {
            pA.x -= halfH;
            pB.x -= halfH;
            pL.x -= halfH / 2;
            pR.x -= halfH / 2;
          } else if (edgeshape === "<") {
            pL.x -= halfH;
            pR.x -= halfH;
          }
          limitX0(pA);
          limitX0(pD);
          limitX0(pL);
          limitX0(pB);
          limitX0(pC);
          limitX0(pR);
          return "M" + pos(pA.x, pA.y) + "L" + pos(pB.x, pB.y) + "L" + pos(pR.x, pR.y) + "L" + pos(pC.x, pC.y) + "L" + pos(pD.x, pD.y) + "L" + pos(pL.x, pL.y) + "Z";
        };
        var pad = trace[isIcicle ? "tiling" : "marker"].pad;
        var hasFlag = function(f) {
          return trace.textposition.indexOf(f) !== -1;
        };
        var hasTop = hasFlag("top");
        var hasLeft = hasFlag("left");
        var hasRight = hasFlag("right");
        var hasBottom = hasFlag("bottom");
        var pathDescendant = function(d) {
          var _x0 = viewMapX(d.x0);
          var _x1 = viewMapX(d.x1);
          var _y0 = viewMapY(d.y0);
          var _y1 = viewMapY(d.y1);
          var dx = _x1 - _x0;
          var dy = _y1 - _y0;
          if (!dx || !dy) return "";
          var cornerradius = trace.marker.cornerradius || 0;
          var r = Math.min(cornerradius, dx / 2, dy / 2);
          if (r && d.data && d.data.data && d.data.data.label) {
            if (hasTop) r = Math.min(r, pad.t);
            if (hasLeft) r = Math.min(r, pad.l);
            if (hasRight) r = Math.min(r, pad.r);
            if (hasBottom) r = Math.min(r, pad.b);
          }
          var arc = function(rx, ry) {
            return r ? "a" + pos(r, r) + " 0 0 1 " + pos(rx, ry) : "";
          };
          return "M" + pos(_x0, _y0 + r) + arc(r, -r) + "L" + pos(_x1 - r, _y0) + arc(r, r) + "L" + pos(_x1, _y1 - r) + arc(-r, r) + "L" + pos(_x0 + r, _y1) + arc(-r, -r) + "Z";
        };
        var toMoveInsideSlice = function(pt, opts) {
          var x0 = pt.x0;
          var x1 = pt.x1;
          var y0 = pt.y0;
          var y1 = pt.y1;
          var textBB = pt.textBB;
          var _hasTop = hasTop || opts.isHeader && !hasBottom;
          var anchor = _hasTop ? "start" : hasBottom ? "end" : "middle";
          var _hasRight = hasFlag("right");
          var _hasLeft = hasFlag("left") || opts.onPathbar;
          var leftToRight = _hasLeft ? -1 : _hasRight ? 1 : 0;
          if (opts.isHeader) {
            x0 += (isIcicle ? pad : pad.l) - TEXTPAD;
            x1 -= (isIcicle ? pad : pad.r) - TEXTPAD;
            if (x0 >= x1) {
              var mid = (x0 + x1) / 2;
              x0 = mid;
              x1 = mid;
            }
            var limY;
            if (hasBottom) {
              limY = y1 - (isIcicle ? pad : pad.b);
              if (y0 < limY && limY < y1) y0 = limY;
            } else {
              limY = y0 + (isIcicle ? pad : pad.t);
              if (y0 < limY && limY < y1) y1 = limY;
            }
          }
          var transform = toMoveInsideBar(x0, x1, y0, y1, textBB, {
            isHorizontal: false,
            constrained: true,
            angle: 0,
            anchor,
            leftToRight
          });
          transform.fontSize = opts.fontSize;
          transform.targetX = viewMapX(transform.targetX);
          transform.targetY = viewMapY(transform.targetY);
          if (isNaN(transform.targetX) || isNaN(transform.targetY)) {
            return {};
          }
          if (x0 !== x1 && y0 !== y1) {
            recordMinTextSize(trace.type, transform, fullLayout);
          }
          return {
            scale: transform.scale,
            rotate: transform.rotate,
            textX: transform.textX,
            textY: transform.textY,
            anchorX: transform.anchorX,
            anchorY: transform.anchorY,
            targetX: transform.targetX,
            targetY: transform.targetY
          };
        };
        var interpFromParent = function(pt, onPathbar) {
          var parentPrev;
          var i = 0;
          var Q = pt;
          while (!parentPrev && i < maxDepth) {
            i++;
            Q = Q.parent;
            if (Q) {
              parentPrev = getPrev(Q, onPathbar);
            } else i = maxDepth;
          }
          return parentPrev || {};
        };
        var makeExitSliceInterpolator = function(pt, onPathbar, refRect, size) {
          var prev = getPrev(pt, onPathbar);
          var next;
          if (onPathbar) {
            next = pathbarOrigin;
          } else {
            var entryPrev = getPrev(entry, onPathbar);
            if (entryPrev) {
              next = findClosestEdge(pt, entryPrev, size);
            } else {
              next = {};
            }
          }
          return interpolate(prev, next);
        };
        var makeUpdateSliceInterpolator = function(pt, onPathbar, refRect, size, opts) {
          var prev0 = getPrev(pt, onPathbar);
          var prev;
          if (prev0) {
            prev = prev0;
          } else {
            if (onPathbar) {
              prev = pathbarOrigin;
            } else {
              if (prevEntry) {
                if (pt.parent) {
                  var ref = nextOfPrevEntry || refRect;
                  if (ref && !onPathbar) {
                    prev = findClosestEdge(pt, ref, size);
                  } else {
                    prev = {};
                    Lib.extendFlat(prev, interpFromParent(pt, onPathbar));
                  }
                } else {
                  prev = Lib.extendFlat({}, pt);
                  if (isIcicle) {
                    if (opts.orientation === "h") {
                      if (opts.flipX) prev.x0 = pt.x1;
                      else prev.x1 = 0;
                    } else {
                      if (opts.flipY) prev.y0 = pt.y1;
                      else prev.y1 = 0;
                    }
                  }
                }
              } else {
                prev = {};
              }
            }
          }
          return interpolate(prev, {
            x0: pt.x0,
            x1: pt.x1,
            y0: pt.y0,
            y1: pt.y1
          });
        };
        var makeUpdateTextInterpolator = function(pt, onPathbar, refRect, size) {
          var prev0 = getPrev(pt, onPathbar);
          var prev = {};
          var origin = getOrigin(pt, onPathbar, refRect, size);
          Lib.extendFlat(prev, {
            transform: toMoveInsideSlice({
              x0: origin.x0,
              x1: origin.x1,
              y0: origin.y0,
              y1: origin.y1,
              textBB: pt.textBB,
              _text: pt._text
            }, {
              isHeader: helpers.isHeader(pt, trace)
            })
          });
          if (prev0) {
            prev = prev0;
          } else {
            if (pt.parent) {
              Lib.extendFlat(prev, interpFromParent(pt, onPathbar));
            }
          }
          var transform = pt.transform;
          if (pt.x0 !== pt.x1 && pt.y0 !== pt.y1) {
            recordMinTextSize(trace.type, transform, fullLayout);
          }
          return interpolate(prev, {
            transform: {
              scale: transform.scale,
              rotate: transform.rotate,
              textX: transform.textX,
              textY: transform.textY,
              anchorX: transform.anchorX,
              anchorY: transform.anchorY,
              targetX: transform.targetX,
              targetY: transform.targetY
            }
          });
        };
        var handleSlicesExit = function(slices, onPathbar, refRect, size, pathSlice) {
          var width = size[0];
          var height = size[1];
          if (hasTransition) {
            slices.exit().transition().each(function() {
              var sliceTop = d3.select(this);
              var slicePath = sliceTop.select("path.surface");
              slicePath.transition().attrTween("d", function(pt2) {
                var interp = makeExitSliceInterpolator(pt2, onPathbar, refRect, [width, height]);
                return function(t) {
                  return pathSlice(interp(t));
                };
              });
              var sliceTextGroup = sliceTop.select("g.slicetext");
              sliceTextGroup.attr("opacity", 0);
            }).remove();
          } else {
            slices.exit().remove();
          }
        };
        var strTransform = function(d) {
          var transform = d.transform;
          if (d.x0 !== d.x1 && d.y0 !== d.y1) {
            recordMinTextSize(trace.type, transform, fullLayout);
          }
          return Lib.getTextTransform({
            textX: transform.textX,
            textY: transform.textY,
            anchorX: transform.anchorX,
            anchorY: transform.anchorY,
            targetX: transform.targetX,
            targetY: transform.targetY,
            scale: transform.scale,
            rotate: transform.rotate
          });
        };
        if (hasTransition) {
          selAncestors.each(function(pt) {
            prevLookupPathbar[getKey(pt)] = {
              x0: pt.x0,
              x1: pt.x1,
              y0: pt.y0,
              y1: pt.y1
            };
            if (pt.transform) {
              prevLookupPathbar[getKey(pt)].transform = {
                textX: pt.transform.textX,
                textY: pt.transform.textY,
                anchorX: pt.transform.anchorX,
                anchorY: pt.transform.anchorY,
                targetX: pt.transform.targetX,
                targetY: pt.transform.targetY,
                scale: pt.transform.scale,
                rotate: pt.transform.rotate
              };
            }
          });
          selDescendants.each(function(pt) {
            prevLookupSlices[getKey(pt)] = {
              x0: pt.x0,
              x1: pt.x1,
              y0: pt.y0,
              y1: pt.y1
            };
            if (pt.transform) {
              prevLookupSlices[getKey(pt)].transform = {
                textX: pt.transform.textX,
                textY: pt.transform.textY,
                anchorX: pt.transform.anchorX,
                anchorY: pt.transform.anchorY,
                targetX: pt.transform.targetX,
                targetY: pt.transform.targetY,
                scale: pt.transform.scale,
                rotate: pt.transform.rotate
              };
            }
            if (!prevEntry && helpers.isEntry(pt)) {
              prevEntry = pt;
            }
          });
        }
        nextOfPrevEntry = drawDescendants(gd, cd, entry, selDescendants, {
          width: vpw,
          height: vph,
          viewX: viewMapX,
          viewY: viewMapY,
          pathSlice: pathDescendant,
          toMoveInsideSlice,
          prevEntry,
          makeUpdateSliceInterpolator,
          makeUpdateTextInterpolator,
          handleSlicesExit,
          hasTransition,
          strTransform
        });
        if (trace.pathbar.visible) {
          drawAncestors(gd, cd, entry, selAncestors, {
            barDifY,
            width: barW,
            height: barH,
            viewX: viewBarX,
            viewY: viewBarY,
            pathSlice: pathAncestor,
            toMoveInsideSlice,
            makeUpdateSliceInterpolator,
            makeUpdateTextInterpolator,
            handleSlicesExit,
            hasTransition,
            strTransform
          });
        } else {
          selAncestors.remove();
        }
      };
    }
  });

  // src/traces/treemap/draw.js
  var require_draw12 = __commonJS({
    "src/traces/treemap/draw.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var helpers = require_helpers15();
      var uniformText = require_uniform_text();
      var clearMinTextSize = uniformText.clearMinTextSize;
      var resizeText = require_style4().resizeText;
      var plotOne = require_plot_one();
      module.exports = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback, opts) {
        var type = opts.type;
        var drawDescendants = opts.drawDescendants;
        var fullLayout = gd._fullLayout;
        var layer = fullLayout["_" + type + "layer"];
        var join, onComplete;
        var isFullReplot = !transitionOpts;
        clearMinTextSize(type, fullLayout);
        join = layer.selectAll("g.trace." + type).data(cdmodule, function(cd) {
          return cd[0].trace.uid;
        });
        join.enter().append("g").classed("trace", true).classed(type, true);
        join.order();
        if (!fullLayout.uniformtext.mode && helpers.hasTransition(transitionOpts)) {
          if (makeOnCompleteCallback) {
            onComplete = makeOnCompleteCallback();
          }
          var transition = d3.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() {
            onComplete && onComplete();
          }).each("interrupt", function() {
            onComplete && onComplete();
          });
          transition.each(function() {
            layer.selectAll("g.trace").each(function(cd) {
              plotOne(gd, cd, this, transitionOpts, drawDescendants);
            });
          });
        } else {
          join.each(function(cd) {
            plotOne(gd, cd, this, transitionOpts, drawDescendants);
          });
          if (fullLayout.uniformtext.mode) {
            resizeText(gd, layer.selectAll(".trace"), type);
          }
        }
        if (isFullReplot) {
          join.exit().remove();
        }
      };
    }
  });

  // src/traces/treemap/draw_descendants.js
  var require_draw_descendants = __commonJS({
    "src/traces/treemap/draw_descendants.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var svgTextUtils = require_svg_text_utils();
      var partition = require_partition();
      var styleOne = require_style14().styleOne;
      var constants = require_constants21();
      var helpers = require_helpers15();
      var attachFxHandlers = require_fx2();
      var formatSliceLabel = require_plot13().formatSliceLabel;
      var onPathbar = false;
      module.exports = function drawDescendants(gd, cd, entry, slices, opts) {
        var width = opts.width;
        var height = opts.height;
        var viewX = opts.viewX;
        var viewY = opts.viewY;
        var pathSlice = opts.pathSlice;
        var toMoveInsideSlice = opts.toMoveInsideSlice;
        var strTransform = opts.strTransform;
        var hasTransition = opts.hasTransition;
        var handleSlicesExit = opts.handleSlicesExit;
        var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator;
        var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator;
        var prevEntry = opts.prevEntry;
        var refRect = {};
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var cd0 = cd[0];
        var trace = cd0.trace;
        var hasLeft = trace.textposition.indexOf("left") !== -1;
        var hasRight = trace.textposition.indexOf("right") !== -1;
        var hasBottom = trace.textposition.indexOf("bottom") !== -1;
        var noRoomForHeader = !hasBottom && !trace.marker.pad.t || hasBottom && !trace.marker.pad.b;
        var allData = partition(entry, [width, height], {
          packing: trace.tiling.packing,
          squarifyratio: trace.tiling.squarifyratio,
          flipX: trace.tiling.flip.indexOf("x") > -1,
          flipY: trace.tiling.flip.indexOf("y") > -1,
          pad: {
            inner: trace.tiling.pad,
            top: trace.marker.pad.t,
            left: trace.marker.pad.l,
            right: trace.marker.pad.r,
            bottom: trace.marker.pad.b
          }
        });
        var sliceData = allData.descendants();
        var minVisibleDepth = Infinity;
        var maxVisibleDepth = -Infinity;
        sliceData.forEach(function(pt) {
          var depth = pt.depth;
          if (depth >= trace._maxDepth) {
            pt.x0 = pt.x1 = (pt.x0 + pt.x1) / 2;
            pt.y0 = pt.y1 = (pt.y0 + pt.y1) / 2;
          } else {
            minVisibleDepth = Math.min(minVisibleDepth, depth);
            maxVisibleDepth = Math.max(maxVisibleDepth, depth);
          }
        });
        slices = slices.data(sliceData, helpers.getPtId);
        trace._maxVisibleLayers = isFinite(maxVisibleDepth) ? maxVisibleDepth - minVisibleDepth + 1 : 0;
        slices.enter().append("g").classed("slice", true);
        handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice);
        slices.order();
        var nextOfPrevEntry = null;
        if (hasTransition && prevEntry) {
          var prevEntryId = helpers.getPtId(prevEntry);
          slices.each(function(pt) {
            if (nextOfPrevEntry === null && helpers.getPtId(pt) === prevEntryId) {
              nextOfPrevEntry = {
                x0: pt.x0,
                x1: pt.x1,
                y0: pt.y0,
                y1: pt.y1
              };
            }
          });
        }
        var getRefRect = function() {
          return nextOfPrevEntry || {
            x0: 0,
            x1: width,
            y0: 0,
            y1: height
          };
        };
        var updateSlices = slices;
        if (hasTransition) {
          updateSlices = updateSlices.transition().each("end", function() {
            var sliceTop = d3.select(this);
            helpers.setSliceCursor(sliceTop, gd, {
              hideOnRoot: true,
              hideOnLeaves: false,
              isTransitioning: false
            });
          });
        }
        updateSlices.each(function(pt) {
          var isHeader = helpers.isHeader(pt, trace);
          pt._x0 = viewX(pt.x0);
          pt._x1 = viewX(pt.x1);
          pt._y0 = viewY(pt.y0);
          pt._y1 = viewY(pt.y1);
          pt._hoverX = viewX(pt.x1 - trace.marker.pad.r), pt._hoverY = hasBottom ? viewY(pt.y1 - trace.marker.pad.b / 2) : viewY(pt.y0 + trace.marker.pad.t / 2);
          var sliceTop = d3.select(this);
          var slicePath = Lib.ensureSingle(sliceTop, "path", "surface", function(s) {
            s.style("pointer-events", isStatic ? "none" : "all");
          });
          if (hasTransition) {
            slicePath.transition().attrTween("d", function(pt2) {
              var interp = makeUpdateSliceInterpolator(pt2, onPathbar, getRefRect(), [width, height]);
              return function(t) {
                return pathSlice(interp(t));
              };
            });
          } else {
            slicePath.attr("d", pathSlice);
          }
          sliceTop.call(attachFxHandlers, entry, gd, cd, {
            styleOne,
            eventDataKeys: constants.eventDataKeys,
            transitionTime: constants.CLICK_TRANSITION_TIME,
            transitionEasing: constants.CLICK_TRANSITION_EASING
          }).call(helpers.setSliceCursor, gd, { isTransitioning: gd._transitioning });
          slicePath.call(styleOne, pt, trace, gd, {
            hovered: false
          });
          if (pt.x0 === pt.x1 || pt.y0 === pt.y1) {
            pt._text = "";
          } else {
            if (isHeader) {
              pt._text = noRoomForHeader ? "" : helpers.getPtLabel(pt) || "";
            } else {
              pt._text = formatSliceLabel(pt, entry, trace, cd, fullLayout) || "";
            }
          }
          var sliceTextGroup = Lib.ensureSingle(sliceTop, "g", "slicetext");
          var sliceText = Lib.ensureSingle(sliceTextGroup, "text", "", function(s) {
            s.attr("data-notex", 1);
          });
          var font = Lib.ensureUniformFontSize(gd, helpers.determineTextFont(trace, pt, fullLayout.font));
          var text = pt._text || " ";
          var singleLineHeader = isHeader && text.indexOf("<br>") === -1;
          sliceText.text(text).classed("slicetext", true).attr("text-anchor", hasRight ? "end" : hasLeft || singleLineHeader ? "start" : "middle").call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
          pt.textBB = Drawing.bBox(sliceText.node());
          pt.transform = toMoveInsideSlice(pt, {
            fontSize: font.size,
            isHeader
          });
          pt.transform.fontSize = font.size;
          if (hasTransition) {
            sliceText.transition().attrTween("transform", function(pt2) {
              var interp = makeUpdateTextInterpolator(pt2, onPathbar, getRefRect(), [width, height]);
              return function(t) {
                return strTransform(interp(t));
              };
            });
          } else {
            sliceText.attr("transform", strTransform(pt));
          }
        });
        return nextOfPrevEntry;
      };
    }
  });

  // src/traces/treemap/plot.js
  var require_plot14 = __commonJS({
    "src/traces/treemap/plot.js"(exports, module) {
      "use strict";
      var draw = require_draw12();
      var drawDescendants = require_draw_descendants();
      module.exports = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback) {
        return draw(gd, cdmodule, transitionOpts, makeOnCompleteCallback, {
          type: "treemap",
          drawDescendants
        });
      };
    }
  });

  // src/traces/treemap/index.js
  var require_treemap = __commonJS({
    "src/traces/treemap/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "treemap",
        basePlotModule: require_base_plot3(),
        categories: [],
        animatable: true,
        attributes: require_attributes37(),
        layoutAttributes: require_layout_attributes14(),
        supplyDefaults: require_defaults33(),
        supplyLayoutDefaults: require_layout_defaults13(),
        calc: require_calc18().calc,
        crossTraceCalc: require_calc18().crossTraceCalc,
        plot: require_plot14(),
        style: require_style14().style,
        colorbar: require_marker_colorbar(),
        meta: {}
      };
    }
  });

  // lib/treemap.js
  var require_treemap2 = __commonJS({
    "lib/treemap.js"(exports, module) {
      "use strict";
      module.exports = require_treemap();
    }
  });

  // src/traces/icicle/base_plot.js
  var require_base_plot4 = __commonJS({
    "src/traces/icicle/base_plot.js"(exports) {
      "use strict";
      var plots = require_plots();
      exports.name = "icicle";
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        plots.plotBasePlot(exports.name, gd, traces, transitionOpts, makeOnCompleteCallback);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        plots.cleanBasePlot(exports.name, newFullData, newFullLayout, oldFullData, oldFullLayout);
      };
    }
  });

  // src/traces/icicle/attributes.js
  var require_attributes38 = __commonJS({
    "src/traces/icicle/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorScaleAttrs = require_attributes8();
      var domainAttrs = require_domain().attributes;
      var pieAttrs = require_attributes35();
      var sunburstAttrs = require_attributes36();
      var treemapAttrs = require_attributes37();
      var constants = require_constants21();
      var extendFlat = require_extend().extendFlat;
      var pattern = require_attributes4().pattern;
      module.exports = {
        labels: sunburstAttrs.labels,
        parents: sunburstAttrs.parents,
        values: sunburstAttrs.values,
        branchvalues: sunburstAttrs.branchvalues,
        count: sunburstAttrs.count,
        level: sunburstAttrs.level,
        maxdepth: sunburstAttrs.maxdepth,
        tiling: {
          orientation: {
            valType: "enumerated",
            values: ["v", "h"],
            dflt: "h",
            editType: "plot"
          },
          flip: treemapAttrs.tiling.flip,
          pad: {
            valType: "number",
            min: 0,
            dflt: 0,
            editType: "plot"
          },
          editType: "calc"
        },
        marker: extendFlat(
          {
            colors: sunburstAttrs.marker.colors,
            line: sunburstAttrs.marker.line,
            pattern,
            editType: "calc"
          },
          colorScaleAttrs("marker", {
            colorAttr: "colors",
            anim: false
            // TODO: set to anim: true?
          })
        ),
        leaf: sunburstAttrs.leaf,
        pathbar: treemapAttrs.pathbar,
        text: pieAttrs.text,
        textinfo: sunburstAttrs.textinfo,
        // TODO: incorporate `label` and `value` in the eventData
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: constants.eventDataKeys.concat(["label", "value"]) }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: pieAttrs.hovertext,
        hoverinfo: sunburstAttrs.hoverinfo,
        hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }),
        hovertemplatefallback: templatefallbackAttrs(),
        textfont: pieAttrs.textfont,
        insidetextfont: pieAttrs.insidetextfont,
        outsidetextfont: treemapAttrs.outsidetextfont,
        textposition: treemapAttrs.textposition,
        sort: pieAttrs.sort,
        root: sunburstAttrs.root,
        domain: domainAttrs({ name: "icicle", trace: true, editType: "calc" })
      };
    }
  });

  // src/traces/icicle/layout_attributes.js
  var require_layout_attributes15 = __commonJS({
    "src/traces/icicle/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        iciclecolorway: {
          valType: "colorlist",
          editType: "calc"
        },
        extendiciclecolors: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/icicle/defaults.js
  var require_defaults34 = __commonJS({
    "src/traces/icicle/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes38();
      var Color2 = require_color();
      var handleDomainDefaults = require_domain().defaults;
      var handleText = require_defaults19().handleText;
      var TEXTPAD = require_constants9().TEXTPAD;
      var handleMarkerDefaults = require_defaults31().handleMarkerDefaults;
      var Colorscale = require_colorscale();
      var hasColorscale = Colorscale.hasColorscale;
      var colorscaleDefaults = Colorscale.handleDefaults;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var labels = coerce("labels");
        var parents = coerce("parents");
        if (!labels || !labels.length || !parents || !parents.length) {
          traceOut.visible = false;
          return;
        }
        var vals = coerce("values");
        if (vals && vals.length) {
          coerce("branchvalues");
        } else {
          coerce("count");
        }
        coerce("level");
        coerce("maxdepth");
        coerce("tiling.orientation");
        coerce("tiling.flip");
        coerce("tiling.pad");
        var text = coerce("text");
        coerce("texttemplate");
        coerce("texttemplatefallback");
        if (!traceOut.texttemplate) coerce("textinfo", Lib.isArrayOrTypedArray(text) ? "text+label" : "label");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var hasPathbar = coerce("pathbar.visible");
        var textposition = "auto";
        handleText(traceIn, traceOut, layout, coerce, textposition, {
          hasPathbar,
          moduleHasSelected: false,
          moduleHasUnselected: false,
          moduleHasConstrain: false,
          moduleHasCliponaxis: false,
          moduleHasTextangle: false,
          moduleHasInsideanchor: false
        });
        coerce("textposition");
        handleMarkerDefaults(traceIn, traceOut, layout, coerce);
        var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, "marker", "colors") || (traceIn.marker || {}).coloraxis;
        if (withColorscale) {
          colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "marker.", cLetter: "c" });
        }
        coerce("leaf.opacity", withColorscale ? 1 : 0.7);
        traceOut._hovered = {
          marker: {
            line: {
              width: 2,
              color: Color2.contrast(layout.paper_bgcolor)
            }
          }
        };
        if (hasPathbar) {
          coerce("pathbar.thickness", traceOut.pathbar.textfont.size + 2 * TEXTPAD);
          coerce("pathbar.side");
          coerce("pathbar.edgeshape");
        }
        coerce("sort");
        coerce("root.color");
        handleDomainDefaults(traceOut, layout, coerce);
        traceOut._length = null;
      };
    }
  });

  // src/traces/icicle/layout_defaults.js
  var require_layout_defaults14 = __commonJS({
    "src/traces/icicle/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes15();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        coerce("iciclecolorway", layoutOut.colorway);
        coerce("extendiciclecolors");
      };
    }
  });

  // src/traces/icicle/calc.js
  var require_calc19 = __commonJS({
    "src/traces/icicle/calc.js"(exports) {
      "use strict";
      var calc = require_calc17();
      exports.calc = function(gd, trace) {
        return calc.calc(gd, trace);
      };
      exports.crossTraceCalc = function(gd) {
        return calc._runCrossTraceCalc("icicle", gd);
      };
    }
  });

  // src/traces/icicle/partition.js
  var require_partition2 = __commonJS({
    "src/traces/icicle/partition.js"(exports, module) {
      "use strict";
      var d3Hierarchy = require_d3_hierarchy();
      var flipTree = require_flip_tree();
      module.exports = function partition(entry, size, opts) {
        var flipX = opts.flipX;
        var flipY = opts.flipY;
        var swapXY = opts.orientation === "h";
        var maxDepth = opts.maxDepth;
        var newWidth = size[0];
        var newHeight = size[1];
        if (maxDepth) {
          newWidth = (entry.height + 1) * size[0] / Math.min(entry.height + 1, maxDepth);
          newHeight = (entry.height + 1) * size[1] / Math.min(entry.height + 1, maxDepth);
        }
        var result = d3Hierarchy.partition().padding(opts.pad.inner).size(
          swapXY ? [size[1], newWidth] : [size[0], newHeight]
        )(entry);
        if (swapXY || flipX || flipY) {
          flipTree(result, size, {
            swapXY,
            flipX,
            flipY
          });
        }
        return result;
      };
    }
  });

  // src/traces/icicle/style.js
  var require_style15 = __commonJS({
    "src/traces/icicle/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var Lib = require_lib();
      var resizeText = require_uniform_text().resizeText;
      var fillOne = require_fill_one2();
      function style(gd) {
        var s = gd._fullLayout._iciclelayer.selectAll(".trace");
        resizeText(gd, s, "icicle");
        s.each(function(cd) {
          var gTrace = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          gTrace.style("opacity", trace.opacity);
          gTrace.selectAll("path.surface").each(function(pt) {
            d3.select(this).call(styleOne, pt, trace, gd);
          });
        });
      }
      function styleOne(s, pt, trace, gd) {
        var cdi = pt.data.data;
        var isLeaf = !pt.children;
        var ptNumber = cdi.i;
        var lineColor = Lib.castOption(trace, ptNumber, "marker.line.color") || Color2.defaultLine;
        var lineWidth = Lib.castOption(trace, ptNumber, "marker.line.width") || 0;
        s.call(fillOne, pt, trace, gd).style("stroke-width", lineWidth).call(Color2.stroke, lineColor).style("opacity", isLeaf ? trace.leaf.opacity : null);
      }
      module.exports = {
        style,
        styleOne
      };
    }
  });

  // src/traces/icicle/draw_descendants.js
  var require_draw_descendants2 = __commonJS({
    "src/traces/icicle/draw_descendants.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var svgTextUtils = require_svg_text_utils();
      var partition = require_partition2();
      var styleOne = require_style15().styleOne;
      var constants = require_constants21();
      var helpers = require_helpers15();
      var attachFxHandlers = require_fx2();
      var formatSliceLabel = require_plot13().formatSliceLabel;
      var onPathbar = false;
      module.exports = function drawDescendants(gd, cd, entry, slices, opts) {
        var width = opts.width;
        var height = opts.height;
        var viewX = opts.viewX;
        var viewY = opts.viewY;
        var pathSlice = opts.pathSlice;
        var toMoveInsideSlice = opts.toMoveInsideSlice;
        var strTransform = opts.strTransform;
        var hasTransition = opts.hasTransition;
        var handleSlicesExit = opts.handleSlicesExit;
        var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator;
        var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator;
        var prevEntry = opts.prevEntry;
        var refRect = {};
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var cd0 = cd[0];
        var trace = cd0.trace;
        var hasLeft = trace.textposition.indexOf("left") !== -1;
        var hasRight = trace.textposition.indexOf("right") !== -1;
        var hasBottom = trace.textposition.indexOf("bottom") !== -1;
        var allData = partition(entry, [width, height], {
          flipX: trace.tiling.flip.indexOf("x") > -1,
          flipY: trace.tiling.flip.indexOf("y") > -1,
          orientation: trace.tiling.orientation,
          pad: {
            inner: trace.tiling.pad
          },
          maxDepth: trace._maxDepth
        });
        var sliceData = allData.descendants();
        var minVisibleDepth = Infinity;
        var maxVisibleDepth = -Infinity;
        sliceData.forEach(function(pt) {
          var depth = pt.depth;
          if (depth >= trace._maxDepth) {
            pt.x0 = pt.x1 = (pt.x0 + pt.x1) / 2;
            pt.y0 = pt.y1 = (pt.y0 + pt.y1) / 2;
          } else {
            minVisibleDepth = Math.min(minVisibleDepth, depth);
            maxVisibleDepth = Math.max(maxVisibleDepth, depth);
          }
        });
        slices = slices.data(sliceData, helpers.getPtId);
        trace._maxVisibleLayers = isFinite(maxVisibleDepth) ? maxVisibleDepth - minVisibleDepth + 1 : 0;
        slices.enter().append("g").classed("slice", true);
        handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice);
        slices.order();
        var nextOfPrevEntry = null;
        if (hasTransition && prevEntry) {
          var prevEntryId = helpers.getPtId(prevEntry);
          slices.each(function(pt) {
            if (nextOfPrevEntry === null && helpers.getPtId(pt) === prevEntryId) {
              nextOfPrevEntry = {
                x0: pt.x0,
                x1: pt.x1,
                y0: pt.y0,
                y1: pt.y1
              };
            }
          });
        }
        var getRefRect = function() {
          return nextOfPrevEntry || {
            x0: 0,
            x1: width,
            y0: 0,
            y1: height
          };
        };
        var updateSlices = slices;
        if (hasTransition) {
          updateSlices = updateSlices.transition().each("end", function() {
            var sliceTop = d3.select(this);
            helpers.setSliceCursor(sliceTop, gd, {
              hideOnRoot: true,
              hideOnLeaves: false,
              isTransitioning: false
            });
          });
        }
        updateSlices.each(function(pt) {
          pt._x0 = viewX(pt.x0);
          pt._x1 = viewX(pt.x1);
          pt._y0 = viewY(pt.y0);
          pt._y1 = viewY(pt.y1);
          pt._hoverX = viewX(pt.x1 - trace.tiling.pad), pt._hoverY = hasBottom ? viewY(pt.y1 - trace.tiling.pad / 2) : viewY(pt.y0 + trace.tiling.pad / 2);
          var sliceTop = d3.select(this);
          var slicePath = Lib.ensureSingle(sliceTop, "path", "surface", function(s) {
            s.style("pointer-events", isStatic ? "none" : "all");
          });
          if (hasTransition) {
            slicePath.transition().attrTween("d", function(pt2) {
              var interp = makeUpdateSliceInterpolator(
                pt2,
                onPathbar,
                getRefRect(),
                [width, height],
                {
                  orientation: trace.tiling.orientation,
                  flipX: trace.tiling.flip.indexOf("x") > -1,
                  flipY: trace.tiling.flip.indexOf("y") > -1
                }
              );
              return function(t) {
                return pathSlice(interp(t));
              };
            });
          } else {
            slicePath.attr("d", pathSlice);
          }
          sliceTop.call(attachFxHandlers, entry, gd, cd, {
            styleOne,
            eventDataKeys: constants.eventDataKeys,
            transitionTime: constants.CLICK_TRANSITION_TIME,
            transitionEasing: constants.CLICK_TRANSITION_EASING
          }).call(helpers.setSliceCursor, gd, { isTransitioning: gd._transitioning });
          slicePath.call(styleOne, pt, trace, gd, {
            hovered: false
          });
          if (pt.x0 === pt.x1 || pt.y0 === pt.y1) {
            pt._text = "";
          } else {
            pt._text = formatSliceLabel(pt, entry, trace, cd, fullLayout) || "";
          }
          var sliceTextGroup = Lib.ensureSingle(sliceTop, "g", "slicetext");
          var sliceText = Lib.ensureSingle(sliceTextGroup, "text", "", function(s) {
            s.attr("data-notex", 1);
          });
          var font = Lib.ensureUniformFontSize(gd, helpers.determineTextFont(trace, pt, fullLayout.font));
          sliceText.text(pt._text || " ").classed("slicetext", true).attr("text-anchor", hasRight ? "end" : hasLeft ? "start" : "middle").call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
          pt.textBB = Drawing.bBox(sliceText.node());
          pt.transform = toMoveInsideSlice(pt, {
            fontSize: font.size
          });
          pt.transform.fontSize = font.size;
          if (hasTransition) {
            sliceText.transition().attrTween("transform", function(pt2) {
              var interp = makeUpdateTextInterpolator(pt2, onPathbar, getRefRect(), [width, height]);
              return function(t) {
                return strTransform(interp(t));
              };
            });
          } else {
            sliceText.attr("transform", strTransform(pt));
          }
        });
        return nextOfPrevEntry;
      };
    }
  });

  // src/traces/icicle/plot.js
  var require_plot15 = __commonJS({
    "src/traces/icicle/plot.js"(exports, module) {
      "use strict";
      var draw = require_draw12();
      var drawDescendants = require_draw_descendants2();
      module.exports = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback) {
        return draw(gd, cdmodule, transitionOpts, makeOnCompleteCallback, {
          type: "icicle",
          drawDescendants
        });
      };
    }
  });

  // src/traces/icicle/index.js
  var require_icicle = __commonJS({
    "src/traces/icicle/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "icicle",
        basePlotModule: require_base_plot4(),
        categories: [],
        animatable: true,
        attributes: require_attributes38(),
        layoutAttributes: require_layout_attributes15(),
        supplyDefaults: require_defaults34(),
        supplyLayoutDefaults: require_layout_defaults14(),
        calc: require_calc19().calc,
        crossTraceCalc: require_calc19().crossTraceCalc,
        plot: require_plot15(),
        style: require_style15().style,
        colorbar: require_marker_colorbar(),
        meta: {}
      };
    }
  });

  // lib/icicle.js
  var require_icicle2 = __commonJS({
    "lib/icicle.js"(exports, module) {
      "use strict";
      module.exports = require_icicle();
    }
  });

  // src/traces/funnelarea/base_plot.js
  var require_base_plot5 = __commonJS({
    "src/traces/funnelarea/base_plot.js"(exports) {
      "use strict";
      var plots = require_plots();
      exports.name = "funnelarea";
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        plots.plotBasePlot(exports.name, gd, traces, transitionOpts, makeOnCompleteCallback);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        plots.cleanBasePlot(exports.name, newFullData, newFullLayout, oldFullData, oldFullLayout);
      };
    }
  });

  // src/traces/funnelarea/attributes.js
  var require_attributes39 = __commonJS({
    "src/traces/funnelarea/attributes.js"(exports, module) {
      "use strict";
      var pieAttrs = require_attributes35();
      var baseAttrs = require_attributes2();
      var domainAttrs = require_domain().attributes;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var extendFlat = require_extend().extendFlat;
      module.exports = {
        labels: pieAttrs.labels,
        // equivalent of x0 and dx, if label is missing
        label0: pieAttrs.label0,
        dlabel: pieAttrs.dlabel,
        values: pieAttrs.values,
        marker: {
          colors: pieAttrs.marker.colors,
          line: {
            color: extendFlat({}, pieAttrs.marker.line.color, {
              dflt: null
            }),
            width: extendFlat({}, pieAttrs.marker.line.width, { dflt: 1 }),
            editType: "calc"
          },
          pattern: pieAttrs.marker.pattern,
          editType: "calc"
        },
        text: pieAttrs.text,
        hovertext: pieAttrs.hovertext,
        scalegroup: extendFlat({}, pieAttrs.scalegroup, {}),
        textinfo: extendFlat({}, pieAttrs.textinfo, {
          flags: ["label", "text", "value", "percent"]
        }),
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["label", "color", "value", "text", "percent"] }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["label", "text", "value", "percent", "name"]
        }),
        hovertemplate: hovertemplateAttrs({}, { keys: ["label", "color", "value", "text", "percent"] }),
        hovertemplatefallback: templatefallbackAttrs(),
        textposition: extendFlat({}, pieAttrs.textposition, {
          values: ["inside", "none"],
          dflt: "inside"
        }),
        textfont: pieAttrs.textfont,
        insidetextfont: pieAttrs.insidetextfont,
        title: {
          text: pieAttrs.title.text,
          font: pieAttrs.title.font,
          position: extendFlat({}, pieAttrs.title.position, {
            values: ["top left", "top center", "top right"],
            dflt: "top center"
          }),
          editType: "plot"
        },
        domain: domainAttrs({ name: "funnelarea", trace: true, editType: "calc" }),
        aspectratio: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "plot"
        },
        baseratio: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0.333,
          editType: "plot"
        }
      };
    }
  });

  // src/traces/funnelarea/layout_attributes.js
  var require_layout_attributes16 = __commonJS({
    "src/traces/funnelarea/layout_attributes.js"(exports, module) {
      "use strict";
      var hiddenlabels = require_layout_attributes12().hiddenlabels;
      module.exports = {
        hiddenlabels,
        funnelareacolorway: {
          valType: "colorlist",
          editType: "calc"
        },
        extendfunnelareacolors: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/funnelarea/defaults.js
  var require_defaults35 = __commonJS({
    "src/traces/funnelarea/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes39();
      var handleDomainDefaults = require_domain().defaults;
      var handleText = require_defaults19().handleText;
      var handleLabelsAndValues = require_defaults31().handleLabelsAndValues;
      var handleMarkerDefaults = require_defaults31().handleMarkerDefaults;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var labels = coerce("labels");
        var values = coerce("values");
        var res = handleLabelsAndValues(labels, values);
        var len = res.len;
        traceOut._hasLabels = res.hasLabels;
        traceOut._hasValues = res.hasValues;
        if (!traceOut._hasLabels && traceOut._hasValues) {
          coerce("label0");
          coerce("dlabel");
        }
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        handleMarkerDefaults(traceIn, traceOut, layout, coerce);
        coerce("scalegroup");
        var textData = coerce("text");
        var textTemplate = coerce("texttemplate");
        coerce("texttemplatefallback");
        var textInfo;
        if (!textTemplate) textInfo = coerce("textinfo", Array.isArray(textData) ? "text+percent" : "percent");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        if (textTemplate || textInfo && textInfo !== "none") {
          var textposition = coerce("textposition");
          handleText(traceIn, traceOut, layout, coerce, textposition, {
            moduleHasSelected: false,
            moduleHasUnselected: false,
            moduleHasConstrain: false,
            moduleHasCliponaxis: false,
            moduleHasTextangle: false,
            moduleHasInsideanchor: false
          });
        } else if (textInfo === "none") {
          coerce("textposition", "none");
        }
        handleDomainDefaults(traceOut, layout, coerce);
        var title = coerce("title.text");
        if (title) {
          coerce("title.position");
          Lib.coerceFont(coerce, "title.font", layout.font);
        }
        coerce("aspectratio");
        coerce("baseratio");
      };
    }
  });

  // src/traces/funnelarea/layout_defaults.js
  var require_layout_defaults15 = __commonJS({
    "src/traces/funnelarea/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var layoutAttributes = require_layout_attributes16();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
        }
        coerce("hiddenlabels");
        coerce("funnelareacolorway", layoutOut.colorway);
        coerce("extendfunnelareacolors");
      };
    }
  });

  // src/traces/funnelarea/calc.js
  var require_calc20 = __commonJS({
    "src/traces/funnelarea/calc.js"(exports, module) {
      "use strict";
      var pieCalc = require_calc16();
      function calc(gd, trace) {
        return pieCalc.calc(gd, trace);
      }
      function crossTraceCalc(gd) {
        pieCalc.crossTraceCalc(gd, { type: "funnelarea" });
      }
      module.exports = {
        calc,
        crossTraceCalc
      };
    }
  });

  // src/traces/funnelarea/plot.js
  var require_plot16 = __commonJS({
    "src/traces/funnelarea/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var strScale = Lib.strScale;
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var barPlot = require_plot3();
      var toMoveInsideBar = barPlot.toMoveInsideBar;
      var uniformText = require_uniform_text();
      var recordMinTextSize = uniformText.recordMinTextSize;
      var clearMinTextSize = uniformText.clearMinTextSize;
      var pieHelpers = require_helpers4();
      var piePlot = require_plot12();
      var attachFxHandlers = piePlot.attachFxHandlers;
      var determineInsideTextFont = piePlot.determineInsideTextFont;
      var layoutAreas = piePlot.layoutAreas;
      var prerenderTitles = piePlot.prerenderTitles;
      var positionTitleOutside = piePlot.positionTitleOutside;
      var formatSliceLabel = piePlot.formatSliceLabel;
      module.exports = function plot(gd, cdModule) {
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        clearMinTextSize("funnelarea", fullLayout);
        prerenderTitles(cdModule, gd);
        layoutAreas(cdModule, fullLayout._size);
        Lib.makeTraceGroups(fullLayout._funnelarealayer, cdModule, "trace").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          setCoords(cd);
          plotGroup.each(function() {
            var slices = d3.select(this).selectAll("g.slice").data(cd);
            slices.enter().append("g").classed("slice", true);
            slices.exit().remove();
            slices.each(function(pt, i) {
              if (pt.hidden) {
                d3.select(this).selectAll("path,g").remove();
                return;
              }
              pt.pointNumber = pt.i;
              pt.curveNumber = trace.index;
              var cx = cd0.cx;
              var cy = cd0.cy;
              var sliceTop = d3.select(this);
              var slicePath = sliceTop.selectAll("path.surface").data([pt]);
              slicePath.enter().append("path").classed("surface", true).style({ "pointer-events": isStatic ? "none" : "all" });
              sliceTop.call(attachFxHandlers, gd, cd);
              var shape = "M" + (cx + pt.TR[0]) + "," + (cy + pt.TR[1]) + line(pt.TR, pt.BR) + line(pt.BR, pt.BL) + line(pt.BL, pt.TL) + "Z";
              slicePath.attr("d", shape);
              formatSliceLabel(gd, pt, cd0);
              var textPosition = pieHelpers.castOption(trace.textposition, pt.pts);
              var sliceTextGroup = sliceTop.selectAll("g.slicetext").data(pt.text && textPosition !== "none" ? [0] : []);
              sliceTextGroup.enter().append("g").classed("slicetext", true);
              sliceTextGroup.exit().remove();
              sliceTextGroup.each(function() {
                var sliceText = Lib.ensureSingle(d3.select(this), "text", "", function(s) {
                  s.attr("data-notex", 1);
                });
                var font = Lib.ensureUniformFontSize(gd, determineInsideTextFont(trace, pt, fullLayout.font));
                sliceText.text(pt.text).attr({
                  class: "slicetext",
                  transform: "",
                  "text-anchor": "middle"
                }).call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
                var textBB = Drawing.bBox(sliceText.node());
                var transform;
                var x0, x1;
                var y0 = Math.min(pt.BL[1], pt.BR[1]) + cy;
                var y1 = Math.max(pt.TL[1], pt.TR[1]) + cy;
                x0 = Math.max(pt.TL[0], pt.BL[0]) + cx;
                x1 = Math.min(pt.TR[0], pt.BR[0]) + cx;
                transform = toMoveInsideBar(x0, x1, y0, y1, textBB, {
                  isHorizontal: true,
                  constrained: true,
                  angle: 0,
                  anchor: "middle"
                });
                transform.fontSize = font.size;
                recordMinTextSize(trace.type, transform, fullLayout);
                cd[i].transform = transform;
                Lib.setTransormAndDisplay(sliceText, transform);
              });
            });
            var titleTextGroup = d3.select(this).selectAll("g.titletext").data(trace.title.text ? [0] : []);
            titleTextGroup.enter().append("g").classed("titletext", true);
            titleTextGroup.exit().remove();
            titleTextGroup.each(function() {
              var titleText = Lib.ensureSingle(d3.select(this), "text", "", function(s) {
                s.attr("data-notex", 1);
              });
              var txt = trace.title.text;
              if (trace._meta) {
                txt = Lib.templateString(txt, trace._meta);
              }
              titleText.text(txt).attr({
                class: "titletext",
                transform: "",
                "text-anchor": "middle"
              }).call(Drawing.font, trace.title.font).call(svgTextUtils.convertToTspans, gd);
              var transform = positionTitleOutside(cd0, fullLayout._size);
              titleText.attr(
                "transform",
                strTranslate(transform.x, transform.y) + strScale(Math.min(1, transform.scale)) + strTranslate(transform.tx, transform.ty)
              );
            });
          });
        });
      };
      function line(a, b) {
        var dx = b[0] - a[0];
        var dy = b[1] - a[1];
        return "l" + dx + "," + dy;
      }
      function getBetween(a, b) {
        return [
          0.5 * (a[0] + b[0]),
          0.5 * (a[1] + b[1])
        ];
      }
      function setCoords(cd) {
        if (!cd.length) return;
        var cd0 = cd[0];
        var trace = cd0.trace;
        var aspectratio = trace.aspectratio;
        var h = trace.baseratio;
        if (h > 0.999) h = 0.999;
        var h2 = Math.pow(h, 2);
        var v1 = cd0.vTotal;
        var v0 = v1 * h2 / (1 - h2);
        var totalValues = v1;
        var sumSteps = v0 / v1;
        function calcPos() {
          var q = Math.sqrt(sumSteps);
          return {
            x: q,
            y: -q
          };
        }
        function getPoint() {
          var pos = calcPos();
          return [pos.x, pos.y];
        }
        var p;
        var allPoints = [];
        allPoints.push(getPoint());
        var i, cdi;
        for (i = cd.length - 1; i > -1; i--) {
          cdi = cd[i];
          if (cdi.hidden) continue;
          var step = cdi.v / totalValues;
          sumSteps += step;
          allPoints.push(getPoint());
        }
        var minY = Infinity;
        var maxY = -Infinity;
        for (i = 0; i < allPoints.length; i++) {
          p = allPoints[i];
          minY = Math.min(minY, p[1]);
          maxY = Math.max(maxY, p[1]);
        }
        for (i = 0; i < allPoints.length; i++) {
          allPoints[i][1] -= (maxY + minY) / 2;
        }
        var lastX = allPoints[allPoints.length - 1][0];
        var r = cd0.r;
        var rY = (maxY - minY) / 2;
        var scaleX = r / lastX;
        var scaleY = r / rY * aspectratio;
        cd0.r = scaleY * rY;
        for (i = 0; i < allPoints.length; i++) {
          allPoints[i][0] *= scaleX;
          allPoints[i][1] *= scaleY;
        }
        p = allPoints[0];
        var prevLeft = [-p[0], p[1]];
        var prevRight = [p[0], p[1]];
        var n = 0;
        for (i = cd.length - 1; i > -1; i--) {
          cdi = cd[i];
          if (cdi.hidden) continue;
          n += 1;
          var x = allPoints[n][0];
          var y = allPoints[n][1];
          cdi.TL = [-x, y];
          cdi.TR = [x, y];
          cdi.BL = prevLeft;
          cdi.BR = prevRight;
          cdi.pxmid = getBetween(cdi.TR, cdi.BR);
          prevLeft = cdi.TL;
          prevRight = cdi.TR;
        }
      }
    }
  });

  // src/traces/funnelarea/style.js
  var require_style16 = __commonJS({
    "src/traces/funnelarea/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var styleOne = require_style_one();
      var resizeText = require_uniform_text().resizeText;
      module.exports = function style(gd) {
        var s = gd._fullLayout._funnelarealayer.selectAll(".trace");
        resizeText(gd, s, "funnelarea");
        s.each(function(cd) {
          var cd0 = cd[0];
          var trace = cd0.trace;
          var traceSelection = d3.select(this);
          traceSelection.style({ opacity: trace.opacity });
          traceSelection.selectAll("path.surface").each(function(pt) {
            d3.select(this).call(styleOne, pt, trace, gd);
          });
        });
      };
    }
  });

  // src/traces/funnelarea/index.js
  var require_funnelarea = __commonJS({
    "src/traces/funnelarea/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "funnelarea",
        basePlotModule: require_base_plot5(),
        categories: ["pie-like", "funnelarea", "showLegend"],
        attributes: require_attributes39(),
        layoutAttributes: require_layout_attributes16(),
        supplyDefaults: require_defaults35(),
        supplyLayoutDefaults: require_layout_defaults15(),
        calc: require_calc20().calc,
        crossTraceCalc: require_calc20().crossTraceCalc,
        plot: require_plot16(),
        style: require_style16(),
        styleOne: require_style_one(),
        meta: {}
      };
    }
  });

  // lib/funnelarea.js
  var require_funnelarea2 = __commonJS({
    "lib/funnelarea.js"(exports, module) {
      "use strict";
      module.exports = require_funnelarea();
    }
  });

  // stackgl_modules/index.js
  var require_stackgl_modules = __commonJS({
    "stackgl_modules/index.js"(exports, module) {
      (function() {
        var __webpack_modules__ = {
          /***/
          24: (
            /***/
            function(module2) {
              var rootPosition = { left: 0, top: 0 };
              module2.exports = mouseEventOffset;
              function mouseEventOffset(ev, target, out) {
                target = target || ev.currentTarget || ev.srcElement;
                if (!Array.isArray(out)) {
                  out = [0, 0];
                }
                var cx = ev.clientX || 0;
                var cy = ev.clientY || 0;
                var rect = getBoundingClientOffset(target);
                out[0] = cx - rect.left;
                out[1] = cy - rect.top;
                return out;
              }
              function getBoundingClientOffset(element) {
                if (element === window || element === document || element === document.body) {
                  return rootPosition;
                } else {
                  return element.getBoundingClientRect();
                }
              }
            }
          ),
          /***/
          109: (
            /***/
            function(module2) {
              module2.exports = rotateY;
              function rotateY(out, a, b, c) {
                var bx = b[0];
                var bz = b[2];
                var px = a[0] - bx;
                var pz = a[2] - bz;
                var sc = Math.sin(c);
                var cc = Math.cos(c);
                out[0] = bx + pz * sc + px * cc;
                out[1] = a[1];
                out[2] = bz + pz * cc - px * sc;
                return out;
              }
            }
          ),
          /***/
          160: (
            /***/
            function(module2) {
              module2.exports = max;
              function max(out, a, b) {
                out[0] = Math.max(a[0], b[0]);
                out[1] = Math.max(a[1], b[1]);
                out[2] = Math.max(a[2], b[2]);
                out[3] = Math.max(a[3], b[3]);
                return out;
              }
            }
          ),
          /***/
          216: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = makeReflectTypes;
              function makeReflectTypes(uniforms, useIndex) {
                var obj = {};
                for (var i = 0; i < uniforms.length; ++i) {
                  var n = uniforms[i].name;
                  var parts = n.split(".");
                  var o = obj;
                  for (var j = 0; j < parts.length; ++j) {
                    var x = parts[j].split("[");
                    if (x.length > 1) {
                      if (!(x[0] in o)) {
                        o[x[0]] = [];
                      }
                      o = o[x[0]];
                      for (var k = 1; k < x.length; ++k) {
                        var y = parseInt(x[k]);
                        if (k < x.length - 1 || j < parts.length - 1) {
                          if (!(y in o)) {
                            if (k < x.length - 1) {
                              o[y] = [];
                            } else {
                              o[y] = {};
                            }
                          }
                          o = o[y];
                        } else {
                          if (useIndex) {
                            o[y] = i;
                          } else {
                            o[y] = uniforms[i].type;
                          }
                        }
                      }
                    } else if (j < parts.length - 1) {
                      if (!(x[0] in o)) {
                        o[x[0]] = {};
                      }
                      o = o[x[0]];
                    } else {
                      if (useIndex) {
                        o[x[0]] = i;
                      } else {
                        o[x[0]] = uniforms[i].type;
                      }
                    }
                  }
                }
                return obj;
              }
            }
          ),
          /***/
          236: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var hiddenStore = __webpack_require__2(8284);
              module2.exports = createStore;
              function createStore() {
                var key = {};
                return function(obj) {
                  if ((typeof obj !== "object" || obj === null) && typeof obj !== "function") {
                    throw new Error("Weakmap-shim: Key must be object");
                  }
                  var store = obj.valueOf(key);
                  return store && store.identity === key ? store : hiddenStore(obj, key);
                };
              }
            }
          ),
          /***/
          244: (
            /***/
            function(module2) {
              module2.exports = dot;
              function dot(a, b) {
                return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
              }
            }
          ),
          /***/
          264: (
            /***/
            function(module2) {
              module2.exports = transformQuat;
              function transformQuat(out, a, q) {
                var x = a[0], y = a[1], z = a[2], qx = q[0], qy = q[1], qz = q[2], qw = q[3], ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
                out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
                out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
                out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
                return out;
              }
            }
          ),
          /***/
          332: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = cleanPSLG;
              var UnionFind = __webpack_require__2(1755);
              var boxIntersect = __webpack_require__2(6867);
              var segseg = __webpack_require__2(1125);
              var rat = __webpack_require__2(7842);
              var ratCmp = __webpack_require__2(1318);
              var ratToFloat = __webpack_require__2(946);
              var ratVec = __webpack_require__2(5838);
              var nextafter = __webpack_require__2(1278);
              var solveIntersection = __webpack_require__2(3637);
              function boundRat(r) {
                var f = ratToFloat(r);
                return [
                  nextafter(f, -Infinity),
                  nextafter(f, Infinity)
                ];
              }
              function boundEdges(points, edges) {
                var bounds = new Array(edges.length);
                for (var i = 0; i < edges.length; ++i) {
                  var e = edges[i];
                  var a = points[e[0]];
                  var b = points[e[1]];
                  bounds[i] = [
                    nextafter(Math.min(a[0], b[0]), -Infinity),
                    nextafter(Math.min(a[1], b[1]), -Infinity),
                    nextafter(Math.max(a[0], b[0]), Infinity),
                    nextafter(Math.max(a[1], b[1]), Infinity)
                  ];
                }
                return bounds;
              }
              function boundPoints(points) {
                var bounds = new Array(points.length);
                for (var i = 0; i < points.length; ++i) {
                  var p = points[i];
                  bounds[i] = [
                    nextafter(p[0], -Infinity),
                    nextafter(p[1], -Infinity),
                    nextafter(p[0], Infinity),
                    nextafter(p[1], Infinity)
                  ];
                }
                return bounds;
              }
              function getCrossings(points, edges, edgeBounds) {
                var result = [];
                boxIntersect(edgeBounds, function(i, j) {
                  var e = edges[i];
                  var f = edges[j];
                  if (e[0] === f[0] || e[0] === f[1] || e[1] === f[0] || e[1] === f[1]) {
                    return;
                  }
                  var a = points[e[0]];
                  var b = points[e[1]];
                  var c = points[f[0]];
                  var d = points[f[1]];
                  if (segseg(a, b, c, d)) {
                    result.push([i, j]);
                  }
                });
                return result;
              }
              function getTJunctions(points, edges, edgeBounds, vertBounds) {
                var result = [];
                boxIntersect(edgeBounds, vertBounds, function(i, v) {
                  var e = edges[i];
                  if (e[0] === v || e[1] === v) {
                    return;
                  }
                  var p = points[v];
                  var a = points[e[0]];
                  var b = points[e[1]];
                  if (segseg(a, b, p, p)) {
                    result.push([i, v]);
                  }
                });
                return result;
              }
              function cutEdges(floatPoints, edges, crossings, junctions, useColor) {
                var i, e;
                var ratPoints = floatPoints.map(function(p) {
                  return [
                    rat(p[0]),
                    rat(p[1])
                  ];
                });
                for (i = 0; i < crossings.length; ++i) {
                  var crossing = crossings[i];
                  e = crossing[0];
                  var f = crossing[1];
                  var ee = edges[e];
                  var ef = edges[f];
                  var x = solveIntersection(
                    ratVec(floatPoints[ee[0]]),
                    ratVec(floatPoints[ee[1]]),
                    ratVec(floatPoints[ef[0]]),
                    ratVec(floatPoints[ef[1]])
                  );
                  if (!x) {
                    continue;
                  }
                  var idx = floatPoints.length;
                  floatPoints.push([ratToFloat(x[0]), ratToFloat(x[1])]);
                  ratPoints.push(x);
                  junctions.push([e, idx], [f, idx]);
                }
                junctions.sort(function(a2, b2) {
                  if (a2[0] !== b2[0]) {
                    return a2[0] - b2[0];
                  }
                  var u = ratPoints[a2[1]];
                  var v = ratPoints[b2[1]];
                  return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1]);
                });
                for (i = junctions.length - 1; i >= 0; --i) {
                  var junction = junctions[i];
                  e = junction[0];
                  var edge = edges[e];
                  var s = edge[0];
                  var t = edge[1];
                  var a = floatPoints[s];
                  var b = floatPoints[t];
                  if ((a[0] - b[0] || a[1] - b[1]) < 0) {
                    var tmp = s;
                    s = t;
                    t = tmp;
                  }
                  edge[0] = s;
                  var last = edge[1] = junction[1];
                  var color2;
                  if (useColor) {
                    color2 = edge[2];
                  }
                  while (i > 0 && junctions[i - 1][0] === e) {
                    var junction = junctions[--i];
                    var next = junction[1];
                    if (useColor) {
                      edges.push([last, next, color2]);
                    } else {
                      edges.push([last, next]);
                    }
                    last = next;
                  }
                  if (useColor) {
                    edges.push([last, t, color2]);
                  } else {
                    edges.push([last, t]);
                  }
                }
                return ratPoints;
              }
              function dedupPoints(floatPoints, ratPoints, floatBounds) {
                var numPoints = ratPoints.length;
                var uf = new UnionFind(numPoints);
                var bounds = [];
                for (var i = 0; i < ratPoints.length; ++i) {
                  var p = ratPoints[i];
                  var xb = boundRat(p[0]);
                  var yb = boundRat(p[1]);
                  bounds.push([
                    nextafter(xb[0], -Infinity),
                    nextafter(yb[0], -Infinity),
                    nextafter(xb[1], Infinity),
                    nextafter(yb[1], Infinity)
                  ]);
                }
                boxIntersect(bounds, function(i2, j2) {
                  uf.link(i2, j2);
                });
                var noDupes = true;
                var labels = new Array(numPoints);
                for (var i = 0; i < numPoints; ++i) {
                  var j = uf.find(i);
                  if (j !== i) {
                    noDupes = false;
                    floatPoints[j] = [
                      Math.min(floatPoints[i][0], floatPoints[j][0]),
                      Math.min(floatPoints[i][1], floatPoints[j][1])
                    ];
                  }
                }
                if (noDupes) {
                  return null;
                }
                var ptr = 0;
                for (var i = 0; i < numPoints; ++i) {
                  var j = uf.find(i);
                  if (j === i) {
                    labels[i] = ptr;
                    floatPoints[ptr++] = floatPoints[i];
                  } else {
                    labels[i] = -1;
                  }
                }
                floatPoints.length = ptr;
                for (var i = 0; i < numPoints; ++i) {
                  if (labels[i] < 0) {
                    labels[i] = labels[uf.find(i)];
                  }
                }
                return labels;
              }
              function compareLex2(a, b) {
                return a[0] - b[0] || a[1] - b[1];
              }
              function compareLex3(a, b) {
                var d = a[0] - b[0] || a[1] - b[1];
                if (d) {
                  return d;
                }
                if (a[2] < b[2]) {
                  return -1;
                } else if (a[2] > b[2]) {
                  return 1;
                }
                return 0;
              }
              function dedupEdges(edges, labels, useColor) {
                if (edges.length === 0) {
                  return;
                }
                if (labels) {
                  for (var i = 0; i < edges.length; ++i) {
                    var e = edges[i];
                    var a = labels[e[0]];
                    var b = labels[e[1]];
                    e[0] = Math.min(a, b);
                    e[1] = Math.max(a, b);
                  }
                } else {
                  for (var i = 0; i < edges.length; ++i) {
                    var e = edges[i];
                    var a = e[0];
                    var b = e[1];
                    e[0] = Math.min(a, b);
                    e[1] = Math.max(a, b);
                  }
                }
                if (useColor) {
                  edges.sort(compareLex3);
                } else {
                  edges.sort(compareLex2);
                }
                var ptr = 1;
                for (var i = 1; i < edges.length; ++i) {
                  var prev = edges[i - 1];
                  var next = edges[i];
                  if (next[0] === prev[0] && next[1] === prev[1] && (!useColor || next[2] === prev[2])) {
                    continue;
                  }
                  edges[ptr++] = next;
                }
                edges.length = ptr;
              }
              function preRound(points, edges, useColor) {
                var labels = dedupPoints(points, [], boundPoints(points));
                dedupEdges(edges, labels, useColor);
                return !!labels;
              }
              function snapRound(points, edges, useColor) {
                var edgeBounds = boundEdges(points, edges);
                var crossings = getCrossings(points, edges, edgeBounds);
                var vertBounds = boundPoints(points);
                var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds);
                var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor);
                var labels = dedupPoints(points, ratPoints, vertBounds);
                dedupEdges(edges, labels, useColor);
                if (!labels) {
                  return crossings.length > 0 || tjunctions.length > 0;
                }
                return true;
              }
              function cleanPSLG(points, edges, colors) {
                var prevEdges;
                if (colors) {
                  prevEdges = edges;
                  var augEdges = new Array(edges.length);
                  for (var i = 0; i < edges.length; ++i) {
                    var e = edges[i];
                    augEdges[i] = [e[0], e[1], colors[i]];
                  }
                  edges = augEdges;
                }
                var modified = preRound(points, edges, !!colors);
                while (snapRound(points, edges, !!colors)) {
                  modified = true;
                }
                if (!!colors && modified) {
                  prevEdges.length = 0;
                  colors.length = 0;
                  for (var i = 0; i < edges.length; ++i) {
                    var e = edges[i];
                    prevEdges.push([e[0], e[1]]);
                    colors.push(e[2]);
                  }
                }
                return modified;
              }
            }
          ),
          /***/
          351: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = mouseListen;
              var mouse = __webpack_require__2(4687);
              function mouseListen(element, callback) {
                if (!callback) {
                  callback = element;
                  element = window;
                }
                var buttonState = 0;
                var x = 0;
                var y = 0;
                var mods = {
                  shift: false,
                  alt: false,
                  control: false,
                  meta: false
                };
                var attached = false;
                function updateMods(ev) {
                  var changed = false;
                  if ("altKey" in ev) {
                    changed = changed || ev.altKey !== mods.alt;
                    mods.alt = !!ev.altKey;
                  }
                  if ("shiftKey" in ev) {
                    changed = changed || ev.shiftKey !== mods.shift;
                    mods.shift = !!ev.shiftKey;
                  }
                  if ("ctrlKey" in ev) {
                    changed = changed || ev.ctrlKey !== mods.control;
                    mods.control = !!ev.ctrlKey;
                  }
                  if ("metaKey" in ev) {
                    changed = changed || ev.metaKey !== mods.meta;
                    mods.meta = !!ev.metaKey;
                  }
                  return changed;
                }
                function handleEvent(nextButtons, ev) {
                  var nextX = mouse.x(ev);
                  var nextY = mouse.y(ev);
                  if ("buttons" in ev) {
                    nextButtons = ev.buttons | 0;
                  }
                  if (nextButtons !== buttonState || nextX !== x || nextY !== y || updateMods(ev)) {
                    buttonState = nextButtons | 0;
                    x = nextX || 0;
                    y = nextY || 0;
                    callback && callback(buttonState, x, y, mods);
                  }
                }
                function clearState(ev) {
                  handleEvent(0, ev);
                }
                function handleBlur() {
                  if (buttonState || x || y || mods.shift || mods.alt || mods.meta || mods.control) {
                    x = y = 0;
                    buttonState = 0;
                    mods.shift = mods.alt = mods.control = mods.meta = false;
                    callback && callback(0, 0, 0, mods);
                  }
                }
                function handleMods(ev) {
                  if (updateMods(ev)) {
                    callback && callback(buttonState, x, y, mods);
                  }
                }
                function handleMouseMove(ev) {
                  if (mouse.buttons(ev) === 0) {
                    handleEvent(0, ev);
                  } else {
                    handleEvent(buttonState, ev);
                  }
                }
                function handleMouseDown(ev) {
                  handleEvent(buttonState | mouse.buttons(ev), ev);
                }
                function handleMouseUp(ev) {
                  handleEvent(buttonState & ~mouse.buttons(ev), ev);
                }
                function attachListeners() {
                  if (attached) {
                    return;
                  }
                  attached = true;
                  element.addEventListener("mousemove", handleMouseMove);
                  element.addEventListener("mousedown", handleMouseDown);
                  element.addEventListener("mouseup", handleMouseUp);
                  element.addEventListener("mouseleave", clearState);
                  element.addEventListener("mouseenter", clearState);
                  element.addEventListener("mouseout", clearState);
                  element.addEventListener("mouseover", clearState);
                  element.addEventListener("blur", handleBlur);
                  element.addEventListener("keyup", handleMods);
                  element.addEventListener("keydown", handleMods);
                  element.addEventListener("keypress", handleMods);
                  if (element !== window) {
                    window.addEventListener("blur", handleBlur);
                    window.addEventListener("keyup", handleMods);
                    window.addEventListener("keydown", handleMods);
                    window.addEventListener("keypress", handleMods);
                  }
                }
                function detachListeners() {
                  if (!attached) {
                    return;
                  }
                  attached = false;
                  element.removeEventListener("mousemove", handleMouseMove);
                  element.removeEventListener("mousedown", handleMouseDown);
                  element.removeEventListener("mouseup", handleMouseUp);
                  element.removeEventListener("mouseleave", clearState);
                  element.removeEventListener("mouseenter", clearState);
                  element.removeEventListener("mouseout", clearState);
                  element.removeEventListener("mouseover", clearState);
                  element.removeEventListener("blur", handleBlur);
                  element.removeEventListener("keyup", handleMods);
                  element.removeEventListener("keydown", handleMods);
                  element.removeEventListener("keypress", handleMods);
                  if (element !== window) {
                    window.removeEventListener("blur", handleBlur);
                    window.removeEventListener("keyup", handleMods);
                    window.removeEventListener("keydown", handleMods);
                    window.removeEventListener("keypress", handleMods);
                  }
                }
                attachListeners();
                var result = {
                  element
                };
                Object.defineProperties(result, {
                  enabled: {
                    get: function() {
                      return attached;
                    },
                    set: function(f) {
                      if (f) {
                        attachListeners();
                      } else {
                        detachListeners();
                      }
                    },
                    enumerable: true
                  },
                  buttons: {
                    get: function() {
                      return buttonState;
                    },
                    enumerable: true
                  },
                  x: {
                    get: function() {
                      return x;
                    },
                    enumerable: true
                  },
                  y: {
                    get: function() {
                      return y;
                    },
                    enumerable: true
                  },
                  mods: {
                    get: function() {
                      return mods;
                    },
                    enumerable: true
                  }
                });
                return result;
              }
            }
          ),
          /***/
          395: (
            /***/
            function(module2) {
              function lerp(v0, v1, t) {
                return v0 * (1 - t) + v1 * t;
              }
              module2.exports = lerp;
            }
          ),
          /***/
          446: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var compile = __webpack_require__2(7640);
              var CACHE = {};
              function sort(array) {
                var order = array.order;
                var dtype = array.dtype;
                var typeSig = [order, dtype];
                var typeName = typeSig.join(":");
                var compiled = CACHE[typeName];
                if (!compiled) {
                  CACHE[typeName] = compiled = compile(order, dtype);
                }
                compiled(array);
                return array;
              }
              module2.exports = sort;
            }
          ),
          /***/
          483: (
            /***/
            function(module2) {
              module2.exports = squaredLength;
              function squaredLength(a) {
                var x = a[0], y = a[1], z = a[2], w = a[3];
                return x * x + y * y + z * z + w * w;
              }
            }
          ),
          /***/
          492: (
            /***/
            function(module2) {
              module2.exports = transformMat3;
              function transformMat3(out, a, m) {
                var x = a[0], y = a[1], z = a[2];
                out[0] = x * m[0] + y * m[3] + z * m[6];
                out[1] = x * m[1] + y * m[4] + z * m[7];
                out[2] = x * m[2] + y * m[5] + z * m[8];
                return out;
              }
            }
          ),
          /***/
          501: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createLines;
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createShader = __webpack_require__2(1879).n;
              var MAJOR_AXIS = [0, 0, 0];
              var MINOR_AXIS = [0, 0, 0];
              var SCREEN_AXIS = [0, 0, 0];
              var OFFSET_VEC = [0, 0, 0];
              var SHAPE = [1, 1];
              function zeroVec(a) {
                a[0] = a[1] = a[2] = 0;
                return a;
              }
              function copyVec(a, b) {
                a[0] = b[0];
                a[1] = b[1];
                a[2] = b[2];
                return a;
              }
              function Lines(gl2, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) {
                this.gl = gl2;
                this.vertBuffer = vertBuffer;
                this.vao = vao;
                this.shader = shader;
                this.tickCount = tickCount;
                this.tickOffset = tickOffset;
                this.gridCount = gridCount;
                this.gridOffset = gridOffset;
              }
              var proto = Lines.prototype;
              proto.bind = function(model, view, projection) {
                this.shader.bind();
                this.shader.uniforms.model = model;
                this.shader.uniforms.view = view;
                this.shader.uniforms.projection = projection;
                SHAPE[0] = this.gl.drawingBufferWidth;
                SHAPE[1] = this.gl.drawingBufferHeight;
                this.shader.uniforms.screenShape = SHAPE;
                this.vao.bind();
              };
              proto.unbind = function() {
                this.vao.unbind();
              };
              proto.drawAxisLine = function(j, bounds, offset, color2, lineWidth) {
                var minorAxis = zeroVec(MINOR_AXIS);
                this.shader.uniforms.majorAxis = MINOR_AXIS;
                minorAxis[j] = bounds[1][j] - bounds[0][j];
                this.shader.uniforms.minorAxis = minorAxis;
                var noffset = copyVec(OFFSET_VEC, offset);
                noffset[j] += bounds[0][j];
                this.shader.uniforms.offset = noffset;
                this.shader.uniforms.lineWidth = lineWidth;
                this.shader.uniforms.color = color2;
                var screenAxis = zeroVec(SCREEN_AXIS);
                screenAxis[(j + 2) % 3] = 1;
                this.shader.uniforms.screenAxis = screenAxis;
                this.vao.draw(this.gl.TRIANGLES, 6);
                var screenAxis = zeroVec(SCREEN_AXIS);
                screenAxis[(j + 1) % 3] = 1;
                this.shader.uniforms.screenAxis = screenAxis;
                this.vao.draw(this.gl.TRIANGLES, 6);
              };
              proto.drawAxisTicks = function(j, offset, minorAxis, color2, lineWidth) {
                if (!this.tickCount[j]) {
                  return;
                }
                var majorAxis = zeroVec(MAJOR_AXIS);
                majorAxis[j] = 1;
                this.shader.uniforms.majorAxis = majorAxis;
                this.shader.uniforms.offset = offset;
                this.shader.uniforms.minorAxis = minorAxis;
                this.shader.uniforms.color = color2;
                this.shader.uniforms.lineWidth = lineWidth;
                var screenAxis = zeroVec(SCREEN_AXIS);
                screenAxis[j] = 1;
                this.shader.uniforms.screenAxis = screenAxis;
                this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j]);
              };
              proto.drawGrid = function(i, j, bounds, offset, color2, lineWidth) {
                if (!this.gridCount[i]) {
                  return;
                }
                var minorAxis = zeroVec(MINOR_AXIS);
                minorAxis[j] = bounds[1][j] - bounds[0][j];
                this.shader.uniforms.minorAxis = minorAxis;
                var noffset = copyVec(OFFSET_VEC, offset);
                noffset[j] += bounds[0][j];
                this.shader.uniforms.offset = noffset;
                var majorAxis = zeroVec(MAJOR_AXIS);
                majorAxis[i] = 1;
                this.shader.uniforms.majorAxis = majorAxis;
                var screenAxis = zeroVec(SCREEN_AXIS);
                screenAxis[i] = 1;
                this.shader.uniforms.screenAxis = screenAxis;
                this.shader.uniforms.lineWidth = lineWidth;
                this.shader.uniforms.color = color2;
                this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i]);
              };
              proto.drawZero = function(j, i, bounds, offset, color2, lineWidth) {
                var minorAxis = zeroVec(MINOR_AXIS);
                this.shader.uniforms.majorAxis = minorAxis;
                minorAxis[j] = bounds[1][j] - bounds[0][j];
                this.shader.uniforms.minorAxis = minorAxis;
                var noffset = copyVec(OFFSET_VEC, offset);
                noffset[j] += bounds[0][j];
                this.shader.uniforms.offset = noffset;
                var screenAxis = zeroVec(SCREEN_AXIS);
                screenAxis[i] = 1;
                this.shader.uniforms.screenAxis = screenAxis;
                this.shader.uniforms.lineWidth = lineWidth;
                this.shader.uniforms.color = color2;
                this.vao.draw(this.gl.TRIANGLES, 6);
              };
              proto.dispose = function() {
                this.vao.dispose();
                this.vertBuffer.dispose();
                this.shader.dispose();
              };
              function createLines(gl2, bounds, ticks) {
                var vertices = [];
                var tickOffset = [0, 0, 0];
                var tickCount = [0, 0, 0];
                var gridOffset = [0, 0, 0];
                var gridCount = [0, 0, 0];
                vertices.push(
                  0,
                  0,
                  1,
                  0,
                  1,
                  1,
                  0,
                  0,
                  -1,
                  0,
                  0,
                  -1,
                  0,
                  1,
                  1,
                  0,
                  1,
                  -1
                );
                for (var i = 0; i < 3; ++i) {
                  var start = vertices.length / 3 | 0;
                  for (var j = 0; j < ticks[i].length; ++j) {
                    var x = +ticks[i][j].x;
                    vertices.push(
                      x,
                      0,
                      1,
                      x,
                      1,
                      1,
                      x,
                      0,
                      -1,
                      x,
                      0,
                      -1,
                      x,
                      1,
                      1,
                      x,
                      1,
                      -1
                    );
                  }
                  var end = vertices.length / 3 | 0;
                  tickOffset[i] = start;
                  tickCount[i] = end - start;
                  var start = vertices.length / 3 | 0;
                  for (var k = 0; k < ticks[i].length; ++k) {
                    var x = +ticks[i][k].x;
                    vertices.push(
                      x,
                      0,
                      1,
                      x,
                      1,
                      1,
                      x,
                      0,
                      -1,
                      x,
                      0,
                      -1,
                      x,
                      1,
                      1,
                      x,
                      1,
                      -1
                    );
                  }
                  var end = vertices.length / 3 | 0;
                  gridOffset[i] = start;
                  gridCount[i] = end - start;
                }
                var vertBuf = createBuffer(gl2, new Float32Array(vertices));
                var vao = createVAO(gl2, [
                  {
                    "buffer": vertBuf,
                    "type": gl2.FLOAT,
                    "size": 3,
                    "stride": 0,
                    "offset": 0
                  }
                ]);
                var shader = createShader(gl2);
                shader.attributes.position.location = 0;
                return new Lines(gl2, vertBuf, vao, shader, tickCount, tickOffset, gridCount, gridOffset);
              }
            }
          ),
          /***/
          544: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bnsub = __webpack_require__2(5572);
              module2.exports = sub;
              function sub(a, b) {
                var n = a.length;
                var r = new Array(n);
                for (var i = 0; i < n; ++i) {
                  r[i] = bnsub(a[i], b[i]);
                }
                return r;
              }
            }
          ),
          /***/
          606: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var createStore = __webpack_require__2(236);
              module2.exports = weakMap;
              function weakMap() {
                var privates = createStore();
                return {
                  "get": function(key, fallback) {
                    var store = privates(key);
                    return store.hasOwnProperty("value") ? store.value : fallback;
                  },
                  "set": function(key, value) {
                    privates(key).value = value;
                    return this;
                  },
                  "has": function(key) {
                    return "value" in privates(key);
                  },
                  "delete": function(key) {
                    return delete privates(key).value;
                  }
                };
              }
            }
          ),
          /***/
          614: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              var glslify = __webpack_require__2(3236);
              var triVertSrc = glslify(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  float index = rawIndex - floor(rawIndex /\n    (segmentCount * 6.0)) *\n    (segmentCount * 6.0);\n\n  float segment = floor(0.001 + index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  float nextAngle = (\n    (segmentIndex > 0.99 &&  segmentIndex < 1.01) ||\n    (segmentIndex > 4.99 &&  segmentIndex < 5.01)\n  ) ? 1.0 : 0.0;\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex < 3.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec3 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\n\nuniform float vectorScale, coneScale, coneOffset;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 eyePosition, lightPosition;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * conePosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal = normalize((vec4(normal, 0.0) * inverseModel).xyz);\n\n  // vec4 m_position  = model * vec4(conePosition, 1.0);\n  vec4 t_position  = view * conePosition;\n  gl_Position      = projection * t_position;\n\n  f_color          = color;\n  f_data           = conePosition.xyz;\n  f_position       = position.xyz;\n  f_uv             = uv;\n}\n"]);
              var triFragSrc = glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision highp float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"]);
              var pickVertSrc = glslify(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the cone vertex and normal at the given index.\n//\n// The returned vertex is for a cone with its top at origin and height of 1.0,\n// pointing in the direction of the vector attribute.\n//\n// Each cone is made up of a top vertex, a center base vertex and base perimeter vertices.\n// These vertices are used to make up the triangles of the cone by the following:\n//   segment + 0 top vertex\n//   segment + 1 perimeter vertex a+1\n//   segment + 2 perimeter vertex a\n//   segment + 3 center base vertex\n//   segment + 4 perimeter vertex a\n//   segment + 5 perimeter vertex a+1\n// Where segment is the number of the radial segment * 6 and a is the angle at that radial segment.\n// To go from index to segment, floor(index / 6)\n// To go from segment to angle, 2*pi * (segment/segmentCount)\n// To go from index to segment index, index - (segment*6)\n//\nvec3 getConePosition(vec3 d, float rawIndex, float coneOffset, out vec3 normal) {\n\n  const float segmentCount = 8.0;\n\n  float index = rawIndex - floor(rawIndex /\n    (segmentCount * 6.0)) *\n    (segmentCount * 6.0);\n\n  float segment = floor(0.001 + index/6.0);\n  float segmentIndex = index - (segment*6.0);\n\n  normal = -normalize(d);\n\n  if (segmentIndex > 2.99 && segmentIndex < 3.01) {\n    return mix(vec3(0.0), -d, coneOffset);\n  }\n\n  float nextAngle = (\n    (segmentIndex > 0.99 &&  segmentIndex < 1.01) ||\n    (segmentIndex > 4.99 &&  segmentIndex < 5.01)\n  ) ? 1.0 : 0.0;\n  float angle = 2.0 * 3.14159 * ((segment + nextAngle) / segmentCount);\n\n  vec3 v1 = mix(d, vec3(0.0), coneOffset);\n  vec3 v2 = v1 - d;\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d)*0.25;\n  vec3 y = v * sin(angle) * length(d)*0.25;\n  vec3 v3 = v2 + x + y;\n  if (segmentIndex < 3.0) {\n    vec3 tx = u * sin(angle);\n    vec3 ty = v * -cos(angle);\n    vec3 tangent = tx + ty;\n    normal = normalize(cross(v3 - v1, tangent));\n  }\n\n  if (segmentIndex == 0.0) {\n    return mix(d, vec3(0.0), coneOffset);\n  }\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform float vectorScale, coneScale, coneOffset;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getConePosition(mat3(model) * ((vectorScale * coneScale) * vector.xyz), position.w, coneOffset, normal);\n  vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n  gl_Position = projection * (view * conePosition);\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"]);
              var pickFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);
              exports2.meshShader = {
                vertex: triVertSrc,
                fragment: triFragSrc,
                attributes: [
                  { name: "position", type: "vec4" },
                  { name: "color", type: "vec4" },
                  { name: "uv", type: "vec2" },
                  { name: "vector", type: "vec3" }
                ]
              };
              exports2.pickShader = {
                vertex: pickVertSrc,
                fragment: pickFragSrc,
                attributes: [
                  { name: "position", type: "vec4" },
                  { name: "id", type: "vec4" },
                  { name: "vector", type: "vec3" }
                ]
              };
            }
          ),
          /***/
          620: (
            /***/
            function(module2) {
              module2.exports = [
                // current
                "precision",
                "highp",
                "mediump",
                "lowp",
                "attribute",
                "const",
                "uniform",
                "varying",
                "break",
                "continue",
                "do",
                "for",
                "while",
                "if",
                "else",
                "in",
                "out",
                "inout",
                "float",
                "int",
                "uint",
                "void",
                "bool",
                "true",
                "false",
                "discard",
                "return",
                "mat2",
                "mat3",
                "mat4",
                "vec2",
                "vec3",
                "vec4",
                "ivec2",
                "ivec3",
                "ivec4",
                "bvec2",
                "bvec3",
                "bvec4",
                "sampler1D",
                "sampler2D",
                "sampler3D",
                "samplerCube",
                "sampler1DShadow",
                "sampler2DShadow",
                "struct",
                "asm",
                "class",
                "union",
                "enum",
                "typedef",
                "template",
                "this",
                "packed",
                "goto",
                "switch",
                "default",
                "inline",
                "noinline",
                "volatile",
                "public",
                "static",
                "extern",
                "external",
                "interface",
                "long",
                "short",
                "double",
                "half",
                "fixed",
                "unsigned",
                "input",
                "output",
                "hvec2",
                "hvec3",
                "hvec4",
                "dvec2",
                "dvec3",
                "dvec4",
                "fvec2",
                "fvec3",
                "fvec4",
                "sampler2DRect",
                "sampler3DRect",
                "sampler2DRectShadow",
                "sizeof",
                "cast",
                "namespace",
                "using"
              ];
            }
          ),
          /***/
          665: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var parseUnit = __webpack_require__2(3202);
              module2.exports = toPX;
              var PIXELS_PER_INCH = 96;
              function getPropertyInPX(element, prop) {
                var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop));
                return parts[0] * toPX(parts[1], element);
              }
              function getSizeBrutal(unit, element) {
                var testDIV = document.createElement("div");
                testDIV.style["font-size"] = "128" + unit;
                element.appendChild(testDIV);
                var size = getPropertyInPX(testDIV, "font-size") / 128;
                element.removeChild(testDIV);
                return size;
              }
              function toPX(str, element) {
                element = element || document.body;
                str = (str || "px").trim().toLowerCase();
                if (element === window || element === document) {
                  element = document.body;
                }
                switch (str) {
                  case "%":
                    return element.clientHeight / 100;
                  case "ch":
                  case "ex":
                    return getSizeBrutal(str, element);
                  case "em":
                    return getPropertyInPX(element, "font-size");
                  case "rem":
                    return getPropertyInPX(document.body, "font-size");
                  case "vw":
                    return window.innerWidth / 100;
                  case "vh":
                    return window.innerHeight / 100;
                  case "vmin":
                    return Math.min(window.innerWidth, window.innerHeight) / 100;
                  case "vmax":
                    return Math.max(window.innerWidth, window.innerHeight) / 100;
                  case "in":
                    return PIXELS_PER_INCH;
                  case "cm":
                    return PIXELS_PER_INCH / 2.54;
                  case "mm":
                    return PIXELS_PER_INCH / 25.4;
                  case "pt":
                    return PIXELS_PER_INCH / 72;
                  case "pc":
                    return PIXELS_PER_INCH / 6;
                }
                return 1;
              }
            }
          ),
          /***/
          727: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var determinant = __webpack_require__2(2962);
              var NUM_EXPAND = 6;
              function generateSolver(n) {
                var fn = n === 2 ? solve2d : n === 3 ? solve3d : n === 4 ? solve4d : n === 5 ? solve5d : solve6d;
                if (n < 6) {
                  return fn(determinant[n]);
                }
                return fn(determinant);
              }
              function robustLinearSolve0d() {
                return [[0]];
              }
              function robustLinearSolve1d(A2, b) {
                return [[b[0]], [A2[0][0]]];
              }
              function solve2d(det) {
                return function robustLinearSolve2d(A2, b) {
                  return [det([[+b[0], +A2[0][1]], [+b[1], +A2[1][1]]]), det([[+A2[0][0], +b[0]], [+A2[1][0], +b[1]]]), det(A2)];
                };
              }
              function solve3d(det) {
                return function robustLinearSolve3d(A2, b) {
                  return [det([[+b[0], +A2[0][1], +A2[0][2]], [+b[1], +A2[1][1], +A2[1][2]], [+b[2], +A2[2][1], +A2[2][2]]]), det([[+A2[0][0], +b[0], +A2[0][2]], [+A2[1][0], +b[1], +A2[1][2]], [+A2[2][0], +b[2], +A2[2][2]]]), det([[+A2[0][0], +A2[0][1], +b[0]], [+A2[1][0], +A2[1][1], +b[1]], [+A2[2][0], +A2[2][1], +b[2]]]), det(A2)];
                };
              }
              function solve4d(det) {
                return function robustLinearSolve4d(A2, b) {
                  return [det([[+b[0], +A2[0][1], +A2[0][2], +A2[0][3]], [+b[1], +A2[1][1], +A2[1][2], +A2[1][3]], [+b[2], +A2[2][1], +A2[2][2], +A2[2][3]], [+b[3], +A2[3][1], +A2[3][2], +A2[3][3]]]), det([[+A2[0][0], +b[0], +A2[0][2], +A2[0][3]], [+A2[1][0], +b[1], +A2[1][2], +A2[1][3]], [+A2[2][0], +b[2], +A2[2][2], +A2[2][3]], [+A2[3][0], +b[3], +A2[3][2], +A2[3][3]]]), det([[+A2[0][0], +A2[0][1], +b[0], +A2[0][3]], [+A2[1][0], +A2[1][1], +b[1], +A2[1][3]], [+A2[2][0], +A2[2][1], +b[2], +A2[2][3]], [+A2[3][0], +A2[3][1], +b[3], +A2[3][3]]]), det([[+A2[0][0], +A2[0][1], +A2[0][2], +b[0]], [+A2[1][0], +A2[1][1], +A2[1][2], +b[1]], [+A2[2][0], +A2[2][1], +A2[2][2], +b[2]], [+A2[3][0], +A2[3][1], +A2[3][2], +b[3]]]), det(A2)];
                };
              }
              function solve5d(det) {
                return function robustLinearSolve5d(A2, b) {
                  return [det([[+b[0], +A2[0][1], +A2[0][2], +A2[0][3], +A2[0][4]], [+b[1], +A2[1][1], +A2[1][2], +A2[1][3], +A2[1][4]], [+b[2], +A2[2][1], +A2[2][2], +A2[2][3], +A2[2][4]], [+b[3], +A2[3][1], +A2[3][2], +A2[3][3], +A2[3][4]], [+b[4], +A2[4][1], +A2[4][2], +A2[4][3], +A2[4][4]]]), det([[+A2[0][0], +b[0], +A2[0][2], +A2[0][3], +A2[0][4]], [+A2[1][0], +b[1], +A2[1][2], +A2[1][3], +A2[1][4]], [+A2[2][0], +b[2], +A2[2][2], +A2[2][3], +A2[2][4]], [+A2[3][0], +b[3], +A2[3][2], +A2[3][3], +A2[3][4]], [+A2[4][0], +b[4], +A2[4][2], +A2[4][3], +A2[4][4]]]), det([[+A2[0][0], +A2[0][1], +b[0], +A2[0][3], +A2[0][4]], [+A2[1][0], +A2[1][1], +b[1], +A2[1][3], +A2[1][4]], [+A2[2][0], +A2[2][1], +b[2], +A2[2][3], +A2[2][4]], [+A2[3][0], +A2[3][1], +b[3], +A2[3][3], +A2[3][4]], [+A2[4][0], +A2[4][1], +b[4], +A2[4][3], +A2[4][4]]]), det([[+A2[0][0], +A2[0][1], +A2[0][2], +b[0], +A2[0][4]], [+A2[1][0], +A2[1][1], +A2[1][2], +b[1], +A2[1][4]], [+A2[2][0], +A2[2][1], +A2[2][2], +b[2], +A2[2][4]], [+A2[3][0], +A2[3][1], +A2[3][2], +b[3], +A2[3][4]], [+A2[4][0], +A2[4][1], +A2[4][2], +b[4], +A2[4][4]]]), det([[+A2[0][0], +A2[0][1], +A2[0][2], +A2[0][3], +b[0]], [+A2[1][0], +A2[1][1], +A2[1][2], +A2[1][3], +b[1]], [+A2[2][0], +A2[2][1], +A2[2][2], +A2[2][3], +b[2]], [+A2[3][0], +A2[3][1], +A2[3][2], +A2[3][3], +b[3]], [+A2[4][0], +A2[4][1], +A2[4][2], +A2[4][3], +b[4]]]), det(A2)];
                };
              }
              function solve6d(det) {
                return function robustLinearSolve6d(A2, b) {
                  return [det([[+b[0], +A2[0][1], +A2[0][2], +A2[0][3], +A2[0][4], +A2[0][5]], [+b[1], +A2[1][1], +A2[1][2], +A2[1][3], +A2[1][4], +A2[1][5]], [+b[2], +A2[2][1], +A2[2][2], +A2[2][3], +A2[2][4], +A2[2][5]], [+b[3], +A2[3][1], +A2[3][2], +A2[3][3], +A2[3][4], +A2[3][5]], [+b[4], +A2[4][1], +A2[4][2], +A2[4][3], +A2[4][4], +A2[4][5]], [+b[5], +A2[5][1], +A2[5][2], +A2[5][3], +A2[5][4], +A2[5][5]]]), det([[+A2[0][0], +b[0], +A2[0][2], +A2[0][3], +A2[0][4], +A2[0][5]], [+A2[1][0], +b[1], +A2[1][2], +A2[1][3], +A2[1][4], +A2[1][5]], [+A2[2][0], +b[2], +A2[2][2], +A2[2][3], +A2[2][4], +A2[2][5]], [+A2[3][0], +b[3], +A2[3][2], +A2[3][3], +A2[3][4], +A2[3][5]], [+A2[4][0], +b[4], +A2[4][2], +A2[4][3], +A2[4][4], +A2[4][5]], [+A2[5][0], +b[5], +A2[5][2], +A2[5][3], +A2[5][4], +A2[5][5]]]), det([[+A2[0][0], +A2[0][1], +b[0], +A2[0][3], +A2[0][4], +A2[0][5]], [+A2[1][0], +A2[1][1], +b[1], +A2[1][3], +A2[1][4], +A2[1][5]], [+A2[2][0], +A2[2][1], +b[2], +A2[2][3], +A2[2][4], +A2[2][5]], [+A2[3][0], +A2[3][1], +b[3], +A2[3][3], +A2[3][4], +A2[3][5]], [+A2[4][0], +A2[4][1], +b[4], +A2[4][3], +A2[4][4], +A2[4][5]], [+A2[5][0], +A2[5][1], +b[5], +A2[5][3], +A2[5][4], +A2[5][5]]]), det([[+A2[0][0], +A2[0][1], +A2[0][2], +b[0], +A2[0][4], +A2[0][5]], [+A2[1][0], +A2[1][1], +A2[1][2], +b[1], +A2[1][4], +A2[1][5]], [+A2[2][0], +A2[2][1], +A2[2][2], +b[2], +A2[2][4], +A2[2][5]], [+A2[3][0], +A2[3][1], +A2[3][2], +b[3], +A2[3][4], +A2[3][5]], [+A2[4][0], +A2[4][1], +A2[4][2], +b[4], +A2[4][4], +A2[4][5]], [+A2[5][0], +A2[5][1], +A2[5][2], +b[5], +A2[5][4], +A2[5][5]]]), det([[+A2[0][0], +A2[0][1], +A2[0][2], +A2[0][3], +b[0], +A2[0][5]], [+A2[1][0], +A2[1][1], +A2[1][2], +A2[1][3], +b[1], +A2[1][5]], [+A2[2][0], +A2[2][1], +A2[2][2], +A2[2][3], +b[2], +A2[2][5]], [+A2[3][0], +A2[3][1], +A2[3][2], +A2[3][3], +b[3], +A2[3][5]], [+A2[4][0], +A2[4][1], +A2[4][2], +A2[4][3], +b[4], +A2[4][5]], [+A2[5][0], +A2[5][1], +A2[5][2], +A2[5][3], +b[5], +A2[5][5]]]), det([[+A2[0][0], +A2[0][1], +A2[0][2], +A2[0][3], +A2[0][4], +b[0]], [+A2[1][0], +A2[1][1], +A2[1][2], +A2[1][3], +A2[1][4], +b[1]], [+A2[2][0], +A2[2][1], +A2[2][2], +A2[2][3], +A2[2][4], +b[2]], [+A2[3][0], +A2[3][1], +A2[3][2], +A2[3][3], +A2[3][4], +b[3]], [+A2[4][0], +A2[4][1], +A2[4][2], +A2[4][3], +A2[4][4], +b[4]], [+A2[5][0], +A2[5][1], +A2[5][2], +A2[5][3], +A2[5][4], +b[5]]]), det(A2)];
                };
              }
              var CACHE = [
                robustLinearSolve0d,
                robustLinearSolve1d
              ];
              function proc(s0, s1, s2, s3, s4, s5, CACHE2, g) {
                return function dispatchLinearSolve(A2, b) {
                  switch (A2.length) {
                    case 0:
                      return s0(A2, b);
                    case 1:
                      return s1(A2, b);
                    case 2:
                      return s2(A2, b);
                    case 3:
                      return s3(A2, b);
                    case 4:
                      return s4(A2, b);
                    case 5:
                      return s5(A2, b);
                  }
                  var s = CACHE2[A2.length];
                  if (!s) s = CACHE2[A2.length] = g(A2.length);
                  return s(A2, b);
                };
              }
              function generateDispatch() {
                while (CACHE.length < NUM_EXPAND) {
                  CACHE.push(generateSolver(CACHE.length));
                }
                module2.exports = proc.apply(void 0, CACHE.concat([CACHE, generateSolver]));
                for (var i = 0; i < NUM_EXPAND; ++i) {
                  module2.exports[i] = CACHE[i];
                }
              }
              generateDispatch();
            }
          ),
          /***/
          737: (
            /***/
            function(module2) {
              module2.exports = {
                0: "NONE",
                1: "ONE",
                2: "LINE_LOOP",
                3: "LINE_STRIP",
                4: "TRIANGLES",
                5: "TRIANGLE_STRIP",
                6: "TRIANGLE_FAN",
                256: "DEPTH_BUFFER_BIT",
                512: "NEVER",
                513: "LESS",
                514: "EQUAL",
                515: "LEQUAL",
                516: "GREATER",
                517: "NOTEQUAL",
                518: "GEQUAL",
                519: "ALWAYS",
                768: "SRC_COLOR",
                769: "ONE_MINUS_SRC_COLOR",
                770: "SRC_ALPHA",
                771: "ONE_MINUS_SRC_ALPHA",
                772: "DST_ALPHA",
                773: "ONE_MINUS_DST_ALPHA",
                774: "DST_COLOR",
                775: "ONE_MINUS_DST_COLOR",
                776: "SRC_ALPHA_SATURATE",
                1024: "STENCIL_BUFFER_BIT",
                1028: "FRONT",
                1029: "BACK",
                1032: "FRONT_AND_BACK",
                1280: "INVALID_ENUM",
                1281: "INVALID_VALUE",
                1282: "INVALID_OPERATION",
                1285: "OUT_OF_MEMORY",
                1286: "INVALID_FRAMEBUFFER_OPERATION",
                2304: "CW",
                2305: "CCW",
                2849: "LINE_WIDTH",
                2884: "CULL_FACE",
                2885: "CULL_FACE_MODE",
                2886: "FRONT_FACE",
                2928: "DEPTH_RANGE",
                2929: "DEPTH_TEST",
                2930: "DEPTH_WRITEMASK",
                2931: "DEPTH_CLEAR_VALUE",
                2932: "DEPTH_FUNC",
                2960: "STENCIL_TEST",
                2961: "STENCIL_CLEAR_VALUE",
                2962: "STENCIL_FUNC",
                2963: "STENCIL_VALUE_MASK",
                2964: "STENCIL_FAIL",
                2965: "STENCIL_PASS_DEPTH_FAIL",
                2966: "STENCIL_PASS_DEPTH_PASS",
                2967: "STENCIL_REF",
                2968: "STENCIL_WRITEMASK",
                2978: "VIEWPORT",
                3024: "DITHER",
                3042: "BLEND",
                3088: "SCISSOR_BOX",
                3089: "SCISSOR_TEST",
                3106: "COLOR_CLEAR_VALUE",
                3107: "COLOR_WRITEMASK",
                3317: "UNPACK_ALIGNMENT",
                3333: "PACK_ALIGNMENT",
                3379: "MAX_TEXTURE_SIZE",
                3386: "MAX_VIEWPORT_DIMS",
                3408: "SUBPIXEL_BITS",
                3410: "RED_BITS",
                3411: "GREEN_BITS",
                3412: "BLUE_BITS",
                3413: "ALPHA_BITS",
                3414: "DEPTH_BITS",
                3415: "STENCIL_BITS",
                3553: "TEXTURE_2D",
                4352: "DONT_CARE",
                4353: "FASTEST",
                4354: "NICEST",
                5120: "BYTE",
                5121: "UNSIGNED_BYTE",
                5122: "SHORT",
                5123: "UNSIGNED_SHORT",
                5124: "INT",
                5125: "UNSIGNED_INT",
                5126: "FLOAT",
                5386: "INVERT",
                5890: "TEXTURE",
                6401: "STENCIL_INDEX",
                6402: "DEPTH_COMPONENT",
                6406: "ALPHA",
                6407: "RGB",
                6408: "RGBA",
                6409: "LUMINANCE",
                6410: "LUMINANCE_ALPHA",
                7680: "KEEP",
                7681: "REPLACE",
                7682: "INCR",
                7683: "DECR",
                7936: "VENDOR",
                7937: "RENDERER",
                7938: "VERSION",
                9728: "NEAREST",
                9729: "LINEAR",
                9984: "NEAREST_MIPMAP_NEAREST",
                9985: "LINEAR_MIPMAP_NEAREST",
                9986: "NEAREST_MIPMAP_LINEAR",
                9987: "LINEAR_MIPMAP_LINEAR",
                10240: "TEXTURE_MAG_FILTER",
                10241: "TEXTURE_MIN_FILTER",
                10242: "TEXTURE_WRAP_S",
                10243: "TEXTURE_WRAP_T",
                10497: "REPEAT",
                10752: "POLYGON_OFFSET_UNITS",
                16384: "COLOR_BUFFER_BIT",
                32769: "CONSTANT_COLOR",
                32770: "ONE_MINUS_CONSTANT_COLOR",
                32771: "CONSTANT_ALPHA",
                32772: "ONE_MINUS_CONSTANT_ALPHA",
                32773: "BLEND_COLOR",
                32774: "FUNC_ADD",
                32777: "BLEND_EQUATION_RGB",
                32778: "FUNC_SUBTRACT",
                32779: "FUNC_REVERSE_SUBTRACT",
                32819: "UNSIGNED_SHORT_4_4_4_4",
                32820: "UNSIGNED_SHORT_5_5_5_1",
                32823: "POLYGON_OFFSET_FILL",
                32824: "POLYGON_OFFSET_FACTOR",
                32854: "RGBA4",
                32855: "RGB5_A1",
                32873: "TEXTURE_BINDING_2D",
                32926: "SAMPLE_ALPHA_TO_COVERAGE",
                32928: "SAMPLE_COVERAGE",
                32936: "SAMPLE_BUFFERS",
                32937: "SAMPLES",
                32938: "SAMPLE_COVERAGE_VALUE",
                32939: "SAMPLE_COVERAGE_INVERT",
                32968: "BLEND_DST_RGB",
                32969: "BLEND_SRC_RGB",
                32970: "BLEND_DST_ALPHA",
                32971: "BLEND_SRC_ALPHA",
                33071: "CLAMP_TO_EDGE",
                33170: "GENERATE_MIPMAP_HINT",
                33189: "DEPTH_COMPONENT16",
                33306: "DEPTH_STENCIL_ATTACHMENT",
                33635: "UNSIGNED_SHORT_5_6_5",
                33648: "MIRRORED_REPEAT",
                33901: "ALIASED_POINT_SIZE_RANGE",
                33902: "ALIASED_LINE_WIDTH_RANGE",
                33984: "TEXTURE0",
                33985: "TEXTURE1",
                33986: "TEXTURE2",
                33987: "TEXTURE3",
                33988: "TEXTURE4",
                33989: "TEXTURE5",
                33990: "TEXTURE6",
                33991: "TEXTURE7",
                33992: "TEXTURE8",
                33993: "TEXTURE9",
                33994: "TEXTURE10",
                33995: "TEXTURE11",
                33996: "TEXTURE12",
                33997: "TEXTURE13",
                33998: "TEXTURE14",
                33999: "TEXTURE15",
                34e3: "TEXTURE16",
                34001: "TEXTURE17",
                34002: "TEXTURE18",
                34003: "TEXTURE19",
                34004: "TEXTURE20",
                34005: "TEXTURE21",
                34006: "TEXTURE22",
                34007: "TEXTURE23",
                34008: "TEXTURE24",
                34009: "TEXTURE25",
                34010: "TEXTURE26",
                34011: "TEXTURE27",
                34012: "TEXTURE28",
                34013: "TEXTURE29",
                34014: "TEXTURE30",
                34015: "TEXTURE31",
                34016: "ACTIVE_TEXTURE",
                34024: "MAX_RENDERBUFFER_SIZE",
                34041: "DEPTH_STENCIL",
                34055: "INCR_WRAP",
                34056: "DECR_WRAP",
                34067: "TEXTURE_CUBE_MAP",
                34068: "TEXTURE_BINDING_CUBE_MAP",
                34069: "TEXTURE_CUBE_MAP_POSITIVE_X",
                34070: "TEXTURE_CUBE_MAP_NEGATIVE_X",
                34071: "TEXTURE_CUBE_MAP_POSITIVE_Y",
                34072: "TEXTURE_CUBE_MAP_NEGATIVE_Y",
                34073: "TEXTURE_CUBE_MAP_POSITIVE_Z",
                34074: "TEXTURE_CUBE_MAP_NEGATIVE_Z",
                34076: "MAX_CUBE_MAP_TEXTURE_SIZE",
                34338: "VERTEX_ATTRIB_ARRAY_ENABLED",
                34339: "VERTEX_ATTRIB_ARRAY_SIZE",
                34340: "VERTEX_ATTRIB_ARRAY_STRIDE",
                34341: "VERTEX_ATTRIB_ARRAY_TYPE",
                34342: "CURRENT_VERTEX_ATTRIB",
                34373: "VERTEX_ATTRIB_ARRAY_POINTER",
                34466: "NUM_COMPRESSED_TEXTURE_FORMATS",
                34467: "COMPRESSED_TEXTURE_FORMATS",
                34660: "BUFFER_SIZE",
                34661: "BUFFER_USAGE",
                34816: "STENCIL_BACK_FUNC",
                34817: "STENCIL_BACK_FAIL",
                34818: "STENCIL_BACK_PASS_DEPTH_FAIL",
                34819: "STENCIL_BACK_PASS_DEPTH_PASS",
                34877: "BLEND_EQUATION_ALPHA",
                34921: "MAX_VERTEX_ATTRIBS",
                34922: "VERTEX_ATTRIB_ARRAY_NORMALIZED",
                34930: "MAX_TEXTURE_IMAGE_UNITS",
                34962: "ARRAY_BUFFER",
                34963: "ELEMENT_ARRAY_BUFFER",
                34964: "ARRAY_BUFFER_BINDING",
                34965: "ELEMENT_ARRAY_BUFFER_BINDING",
                34975: "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",
                35040: "STREAM_DRAW",
                35044: "STATIC_DRAW",
                35048: "DYNAMIC_DRAW",
                35632: "FRAGMENT_SHADER",
                35633: "VERTEX_SHADER",
                35660: "MAX_VERTEX_TEXTURE_IMAGE_UNITS",
                35661: "MAX_COMBINED_TEXTURE_IMAGE_UNITS",
                35663: "SHADER_TYPE",
                35664: "FLOAT_VEC2",
                35665: "FLOAT_VEC3",
                35666: "FLOAT_VEC4",
                35667: "INT_VEC2",
                35668: "INT_VEC3",
                35669: "INT_VEC4",
                35670: "BOOL",
                35671: "BOOL_VEC2",
                35672: "BOOL_VEC3",
                35673: "BOOL_VEC4",
                35674: "FLOAT_MAT2",
                35675: "FLOAT_MAT3",
                35676: "FLOAT_MAT4",
                35678: "SAMPLER_2D",
                35680: "SAMPLER_CUBE",
                35712: "DELETE_STATUS",
                35713: "COMPILE_STATUS",
                35714: "LINK_STATUS",
                35715: "VALIDATE_STATUS",
                35716: "INFO_LOG_LENGTH",
                35717: "ATTACHED_SHADERS",
                35718: "ACTIVE_UNIFORMS",
                35719: "ACTIVE_UNIFORM_MAX_LENGTH",
                35720: "SHADER_SOURCE_LENGTH",
                35721: "ACTIVE_ATTRIBUTES",
                35722: "ACTIVE_ATTRIBUTE_MAX_LENGTH",
                35724: "SHADING_LANGUAGE_VERSION",
                35725: "CURRENT_PROGRAM",
                36003: "STENCIL_BACK_REF",
                36004: "STENCIL_BACK_VALUE_MASK",
                36005: "STENCIL_BACK_WRITEMASK",
                36006: "FRAMEBUFFER_BINDING",
                36007: "RENDERBUFFER_BINDING",
                36048: "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",
                36049: "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",
                36050: "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",
                36051: "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",
                36053: "FRAMEBUFFER_COMPLETE",
                36054: "FRAMEBUFFER_INCOMPLETE_ATTACHMENT",
                36055: "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",
                36057: "FRAMEBUFFER_INCOMPLETE_DIMENSIONS",
                36061: "FRAMEBUFFER_UNSUPPORTED",
                36064: "COLOR_ATTACHMENT0",
                36096: "DEPTH_ATTACHMENT",
                36128: "STENCIL_ATTACHMENT",
                36160: "FRAMEBUFFER",
                36161: "RENDERBUFFER",
                36162: "RENDERBUFFER_WIDTH",
                36163: "RENDERBUFFER_HEIGHT",
                36164: "RENDERBUFFER_INTERNAL_FORMAT",
                36168: "STENCIL_INDEX8",
                36176: "RENDERBUFFER_RED_SIZE",
                36177: "RENDERBUFFER_GREEN_SIZE",
                36178: "RENDERBUFFER_BLUE_SIZE",
                36179: "RENDERBUFFER_ALPHA_SIZE",
                36180: "RENDERBUFFER_DEPTH_SIZE",
                36181: "RENDERBUFFER_STENCIL_SIZE",
                36194: "RGB565",
                36336: "LOW_FLOAT",
                36337: "MEDIUM_FLOAT",
                36338: "HIGH_FLOAT",
                36339: "LOW_INT",
                36340: "MEDIUM_INT",
                36341: "HIGH_INT",
                36346: "SHADER_COMPILER",
                36347: "MAX_VERTEX_UNIFORM_VECTORS",
                36348: "MAX_VARYING_VECTORS",
                36349: "MAX_FRAGMENT_UNIFORM_VECTORS",
                37440: "UNPACK_FLIP_Y_WEBGL",
                37441: "UNPACK_PREMULTIPLY_ALPHA_WEBGL",
                37442: "CONTEXT_LOST_WEBGL",
                37443: "UNPACK_COLORSPACE_CONVERSION_WEBGL",
                37444: "BROWSER_DEFAULT_WEBGL"
              };
            }
          ),
          /***/
          781: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = findZeroCrossings;
              var core = __webpack_require__2(3349);
              function findZeroCrossings(array, level) {
                var cross = [];
                level = +level || 0;
                core(array.hi(array.shape[0] - 1), cross, level);
                return cross;
              }
            }
          ),
          /***/
          783: (
            /***/
            function(module2) {
              module2.exports = slerp;
              function slerp(out, a, b, t) {
                var ax = a[0], ay = a[1], az = a[2], aw = a[3], bx = b[0], by = b[1], bz = b[2], bw = b[3];
                var omega, cosom, sinom, scale0, scale1;
                cosom = ax * bx + ay * by + az * bz + aw * bw;
                if (cosom < 0) {
                  cosom = -cosom;
                  bx = -bx;
                  by = -by;
                  bz = -bz;
                  bw = -bw;
                }
                if (1 - cosom > 1e-6) {
                  omega = Math.acos(cosom);
                  sinom = Math.sin(omega);
                  scale0 = Math.sin((1 - t) * omega) / sinom;
                  scale1 = Math.sin(t * omega) / sinom;
                } else {
                  scale0 = 1 - t;
                  scale1 = t;
                }
                out[0] = scale0 * ax + scale1 * bx;
                out[1] = scale0 * ay + scale1 * by;
                out[2] = scale0 * az + scale1 * bz;
                out[3] = scale0 * aw + scale1 * bw;
                return out;
              }
            }
          ),
          /***/
          799: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var glslify = __webpack_require__2(3236);
              var createShader = __webpack_require__2(9405);
              var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n  uv = position;\n  gl_Position = vec4(position, 0, 1);\n}"]);
              var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D accumBuffer;\nvarying vec2 uv;\n\nvoid main() {\n  vec4 accum = texture2D(accumBuffer, 0.5 * (uv + 1.0));\n  gl_FragColor = min(vec4(1,1,1,1), accum);\n}"]);
              module2.exports = function(gl2) {
                return createShader(gl2, vertSrc, fragSrc, null, [{ name: "position", type: "vec2" }]);
              };
            }
          ),
          /***/
          811: (
            /***/
            function(module2) {
              module2.exports = inverse;
              function inverse(out, a) {
                out[0] = 1 / a[0];
                out[1] = 1 / a[1];
                out[2] = 1 / a[2];
                return out;
              }
            }
          ),
          /***/
          840: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              var glslify = __webpack_require__2(3236);
              var triVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n           , view\n           , projection\n           , inverseModel;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvec4 project(vec3 p) {\n  return projection * (view * (model * vec4(p, 1.0)));\n}\n\nvoid main() {\n  gl_Position      = project(position);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * vec4(position , 1.0);\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal  = normalize((vec4(normal, 0.0) * inverseModel).xyz);\n\n  f_color          = color;\n  f_data           = position;\n  f_uv             = uv;\n}\n"]);
              var triFragSrc = glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision highp float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n//#pragma glslify: beckmann = require(glsl-specular-beckmann) // used in gl-surface3d\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (f_color.a == 0.0 ||\n    outOfRange(clipBounds[0], clipBounds[1], f_data)\n  ) discard;\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  //float specular = max(0.0, beckmann(L, V, N, roughness)); // used in gl-surface3d\n\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = vec4(f_color.rgb, 1.0) * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * f_color.a;\n}\n"]);
              var edgeVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  gl_Position = projection * (view * (model * vec4(position, 1.0)));\n  f_color = color;\n  f_data  = position;\n  f_uv    = uv;\n}"]);
              var edgeFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_data)) discard;\n\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]);
              var pointVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0.0, 0.0 ,0.0 ,0.0);\n  } else {\n    gl_Position = projection * (view * (model * vec4(position, 1.0)));\n  }\n  gl_PointSize = pointSize;\n  f_color = color;\n  f_uv = uv;\n}"]);
              var pointFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec2 pointR = gl_PointCoord.xy - vec2(0.5, 0.5);\n  if(dot(pointR, pointR) > 0.25) {\n    discard;\n  }\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]);
              var pickVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  gl_Position = projection * (view * (model * vec4(position, 1.0)));\n  f_id        = id;\n  f_position  = position;\n}"]);
              var pickFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);
              var pickPointVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3  position;\nattribute float pointSize;\nattribute vec4  id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0.0, 0.0, 0.0, 0.0);\n  } else {\n    gl_Position  = projection * (view * (model * vec4(position, 1.0)));\n    gl_PointSize = pointSize;\n  }\n  f_id         = id;\n  f_position   = position;\n}"]);
              var contourVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n  gl_Position = projection * (view * (model * vec4(position, 1.0)));\n}"]);
              var contourFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n  gl_FragColor = vec4(contourColor, 1.0);\n}\n"]);
              exports2.meshShader = {
                vertex: triVertSrc,
                fragment: triFragSrc,
                attributes: [
                  { name: "position", type: "vec3" },
                  { name: "normal", type: "vec3" },
                  { name: "color", type: "vec4" },
                  { name: "uv", type: "vec2" }
                ]
              };
              exports2.wireShader = {
                vertex: edgeVertSrc,
                fragment: edgeFragSrc,
                attributes: [
                  { name: "position", type: "vec3" },
                  { name: "color", type: "vec4" },
                  { name: "uv", type: "vec2" }
                ]
              };
              exports2.pointShader = {
                vertex: pointVertSrc,
                fragment: pointFragSrc,
                attributes: [
                  { name: "position", type: "vec3" },
                  { name: "color", type: "vec4" },
                  { name: "uv", type: "vec2" },
                  { name: "pointSize", type: "float" }
                ]
              };
              exports2.pickShader = {
                vertex: pickVertSrc,
                fragment: pickFragSrc,
                attributes: [
                  { name: "position", type: "vec3" },
                  { name: "id", type: "vec4" }
                ]
              };
              exports2.pointPickShader = {
                vertex: pickPointVertSrc,
                fragment: pickFragSrc,
                attributes: [
                  { name: "position", type: "vec3" },
                  { name: "pointSize", type: "float" },
                  { name: "id", type: "vec4" }
                ]
              };
              exports2.contourShader = {
                vertex: contourVertSrc,
                fragment: contourFragSrc,
                attributes: [
                  { name: "position", type: "vec3" }
                ]
              };
            }
          ),
          /***/
          855: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = {
                init: sqInit,
                sweepBipartite,
                sweepComplete,
                scanBipartite,
                scanComplete
              };
              var pool = __webpack_require__2(1888);
              var bits = __webpack_require__2(8828);
              var isort = __webpack_require__2(4192);
              var BLUE_FLAG = 1 << 28;
              var INIT_CAPACITY = 1024;
              var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY);
              var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY);
              var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY);
              var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY);
              var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY);
              var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY);
              var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8);
              function sqInit(count) {
                var rcount = bits.nextPow2(count);
                if (RED_SWEEP_QUEUE.length < rcount) {
                  pool.free(RED_SWEEP_QUEUE);
                  RED_SWEEP_QUEUE = pool.mallocInt32(rcount);
                }
                if (RED_SWEEP_INDEX.length < rcount) {
                  pool.free(RED_SWEEP_INDEX);
                  RED_SWEEP_INDEX = pool.mallocInt32(rcount);
                }
                if (BLUE_SWEEP_QUEUE.length < rcount) {
                  pool.free(BLUE_SWEEP_QUEUE);
                  BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount);
                }
                if (BLUE_SWEEP_INDEX.length < rcount) {
                  pool.free(BLUE_SWEEP_INDEX);
                  BLUE_SWEEP_INDEX = pool.mallocInt32(rcount);
                }
                if (COMMON_SWEEP_QUEUE.length < rcount) {
                  pool.free(COMMON_SWEEP_QUEUE);
                  COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount);
                }
                if (COMMON_SWEEP_INDEX.length < rcount) {
                  pool.free(COMMON_SWEEP_INDEX);
                  COMMON_SWEEP_INDEX = pool.mallocInt32(rcount);
                }
                var eventLength = 8 * rcount;
                if (SWEEP_EVENTS.length < eventLength) {
                  pool.free(SWEEP_EVENTS);
                  SWEEP_EVENTS = pool.mallocDouble(eventLength);
                }
              }
              function sqPop(queue, index, count, item) {
                var idx = index[item];
                var top = queue[count - 1];
                queue[idx] = top;
                index[top] = idx;
              }
              function sqPush(queue, index, count, item) {
                queue[count] = item;
                index[item] = count;
              }
              function sweepBipartite(d, visit, redStart, redEnd, red, redIndex, blueStart, blueEnd, blue, blueIndex) {
                var ptr = 0;
                var elemSize = 2 * d;
                var istart = d - 1;
                var iend = elemSize - 1;
                for (var i = redStart; i < redEnd; ++i) {
                  var idx = redIndex[i];
                  var redOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = red[redOffset + istart];
                  SWEEP_EVENTS[ptr++] = -(idx + 1);
                  SWEEP_EVENTS[ptr++] = red[redOffset + iend];
                  SWEEP_EVENTS[ptr++] = idx;
                }
                for (var i = blueStart; i < blueEnd; ++i) {
                  var idx = blueIndex[i] + BLUE_FLAG;
                  var blueOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = blue[blueOffset + istart];
                  SWEEP_EVENTS[ptr++] = -idx;
                  SWEEP_EVENTS[ptr++] = blue[blueOffset + iend];
                  SWEEP_EVENTS[ptr++] = idx;
                }
                var n = ptr >>> 1;
                isort(SWEEP_EVENTS, n);
                var redActive = 0;
                var blueActive = 0;
                for (var i = 0; i < n; ++i) {
                  var e = SWEEP_EVENTS[2 * i + 1] | 0;
                  if (e >= BLUE_FLAG) {
                    e = e - BLUE_FLAG | 0;
                    sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e);
                  } else if (e >= 0) {
                    sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e);
                  } else if (e <= -BLUE_FLAG) {
                    e = -e - BLUE_FLAG | 0;
                    for (var j = 0; j < redActive; ++j) {
                      var retval = visit(RED_SWEEP_QUEUE[j], e);
                      if (retval !== void 0) {
                        return retval;
                      }
                    }
                    sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, e);
                  } else {
                    e = -e - 1 | 0;
                    for (var j = 0; j < blueActive; ++j) {
                      var retval = visit(e, BLUE_SWEEP_QUEUE[j]);
                      if (retval !== void 0) {
                        return retval;
                      }
                    }
                    sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, e);
                  }
                }
              }
              function sweepComplete(d, visit, redStart, redEnd, red, redIndex, blueStart, blueEnd, blue, blueIndex) {
                var ptr = 0;
                var elemSize = 2 * d;
                var istart = d - 1;
                var iend = elemSize - 1;
                for (var i = redStart; i < redEnd; ++i) {
                  var idx = redIndex[i] + 1 << 1;
                  var redOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = red[redOffset + istart];
                  SWEEP_EVENTS[ptr++] = -idx;
                  SWEEP_EVENTS[ptr++] = red[redOffset + iend];
                  SWEEP_EVENTS[ptr++] = idx;
                }
                for (var i = blueStart; i < blueEnd; ++i) {
                  var idx = blueIndex[i] + 1 << 1;
                  var blueOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = blue[blueOffset + istart];
                  SWEEP_EVENTS[ptr++] = -idx | 1;
                  SWEEP_EVENTS[ptr++] = blue[blueOffset + iend];
                  SWEEP_EVENTS[ptr++] = idx | 1;
                }
                var n = ptr >>> 1;
                isort(SWEEP_EVENTS, n);
                var redActive = 0;
                var blueActive = 0;
                var commonActive = 0;
                for (var i = 0; i < n; ++i) {
                  var e = SWEEP_EVENTS[2 * i + 1] | 0;
                  var color2 = e & 1;
                  if (i < n - 1 && e >> 1 === SWEEP_EVENTS[2 * i + 3] >> 1) {
                    color2 = 2;
                    i += 1;
                  }
                  if (e < 0) {
                    var id = -(e >> 1) - 1;
                    for (var j = 0; j < commonActive; ++j) {
                      var retval = visit(COMMON_SWEEP_QUEUE[j], id);
                      if (retval !== void 0) {
                        return retval;
                      }
                    }
                    if (color2 !== 0) {
                      for (var j = 0; j < redActive; ++j) {
                        var retval = visit(RED_SWEEP_QUEUE[j], id);
                        if (retval !== void 0) {
                          return retval;
                        }
                      }
                    }
                    if (color2 !== 1) {
                      for (var j = 0; j < blueActive; ++j) {
                        var retval = visit(BLUE_SWEEP_QUEUE[j], id);
                        if (retval !== void 0) {
                          return retval;
                        }
                      }
                    }
                    if (color2 === 0) {
                      sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id);
                    } else if (color2 === 1) {
                      sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id);
                    } else if (color2 === 2) {
                      sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id);
                    }
                  } else {
                    var id = (e >> 1) - 1;
                    if (color2 === 0) {
                      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id);
                    } else if (color2 === 1) {
                      sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id);
                    } else if (color2 === 2) {
                      sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id);
                    }
                  }
                }
              }
              function scanBipartite(d, axis, visit, flip, redStart, redEnd, red, redIndex, blueStart, blueEnd, blue, blueIndex) {
                var ptr = 0;
                var elemSize = 2 * d;
                var istart = axis;
                var iend = axis + d;
                var redShift = 1;
                var blueShift = 1;
                if (flip) {
                  blueShift = BLUE_FLAG;
                } else {
                  redShift = BLUE_FLAG;
                }
                for (var i = redStart; i < redEnd; ++i) {
                  var idx = i + redShift;
                  var redOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = red[redOffset + istart];
                  SWEEP_EVENTS[ptr++] = -idx;
                  SWEEP_EVENTS[ptr++] = red[redOffset + iend];
                  SWEEP_EVENTS[ptr++] = idx;
                }
                for (var i = blueStart; i < blueEnd; ++i) {
                  var idx = i + blueShift;
                  var blueOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = blue[blueOffset + istart];
                  SWEEP_EVENTS[ptr++] = -idx;
                }
                var n = ptr >>> 1;
                isort(SWEEP_EVENTS, n);
                var redActive = 0;
                for (var i = 0; i < n; ++i) {
                  var e = SWEEP_EVENTS[2 * i + 1] | 0;
                  if (e < 0) {
                    var idx = -e;
                    var isRed = false;
                    if (idx >= BLUE_FLAG) {
                      isRed = !flip;
                      idx -= BLUE_FLAG;
                    } else {
                      isRed = !!flip;
                      idx -= 1;
                    }
                    if (isRed) {
                      sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx);
                    } else {
                      var blueId = blueIndex[idx];
                      var bluePtr = elemSize * idx;
                      var b0 = blue[bluePtr + axis + 1];
                      var b1 = blue[bluePtr + axis + 1 + d];
                      red_loop:
                        for (var j = 0; j < redActive; ++j) {
                          var oidx = RED_SWEEP_QUEUE[j];
                          var redPtr = elemSize * oidx;
                          if (b1 < red[redPtr + axis + 1] || red[redPtr + axis + 1 + d] < b0) {
                            continue;
                          }
                          for (var k = axis + 2; k < d; ++k) {
                            if (blue[bluePtr + k + d] < red[redPtr + k] || red[redPtr + k + d] < blue[bluePtr + k]) {
                              continue red_loop;
                            }
                          }
                          var redId = redIndex[oidx];
                          var retval;
                          if (flip) {
                            retval = visit(blueId, redId);
                          } else {
                            retval = visit(redId, blueId);
                          }
                          if (retval !== void 0) {
                            return retval;
                          }
                        }
                    }
                  } else {
                    sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift);
                  }
                }
              }
              function scanComplete(d, axis, visit, redStart, redEnd, red, redIndex, blueStart, blueEnd, blue, blueIndex) {
                var ptr = 0;
                var elemSize = 2 * d;
                var istart = axis;
                var iend = axis + d;
                for (var i = redStart; i < redEnd; ++i) {
                  var idx = i + BLUE_FLAG;
                  var redOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = red[redOffset + istart];
                  SWEEP_EVENTS[ptr++] = -idx;
                  SWEEP_EVENTS[ptr++] = red[redOffset + iend];
                  SWEEP_EVENTS[ptr++] = idx;
                }
                for (var i = blueStart; i < blueEnd; ++i) {
                  var idx = i + 1;
                  var blueOffset = elemSize * i;
                  SWEEP_EVENTS[ptr++] = blue[blueOffset + istart];
                  SWEEP_EVENTS[ptr++] = -idx;
                }
                var n = ptr >>> 1;
                isort(SWEEP_EVENTS, n);
                var redActive = 0;
                for (var i = 0; i < n; ++i) {
                  var e = SWEEP_EVENTS[2 * i + 1] | 0;
                  if (e < 0) {
                    var idx = -e;
                    if (idx >= BLUE_FLAG) {
                      RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG;
                    } else {
                      idx -= 1;
                      var blueId = blueIndex[idx];
                      var bluePtr = elemSize * idx;
                      var b0 = blue[bluePtr + axis + 1];
                      var b1 = blue[bluePtr + axis + 1 + d];
                      red_loop:
                        for (var j = 0; j < redActive; ++j) {
                          var oidx = RED_SWEEP_QUEUE[j];
                          var redId = redIndex[oidx];
                          if (redId === blueId) {
                            break;
                          }
                          var redPtr = elemSize * oidx;
                          if (b1 < red[redPtr + axis + 1] || red[redPtr + axis + 1 + d] < b0) {
                            continue;
                          }
                          for (var k = axis + 2; k < d; ++k) {
                            if (blue[bluePtr + k + d] < red[redPtr + k] || red[redPtr + k + d] < blue[bluePtr + k]) {
                              continue red_loop;
                            }
                          }
                          var retval = visit(redId, blueId);
                          if (retval !== void 0) {
                            return retval;
                          }
                        }
                    }
                  } else {
                    var idx = e - BLUE_FLAG;
                    for (var j = redActive - 1; j >= 0; --j) {
                      if (RED_SWEEP_QUEUE[j] === idx) {
                        for (var k = j + 1; k < redActive; ++k) {
                          RED_SWEEP_QUEUE[k - 1] = RED_SWEEP_QUEUE[k];
                        }
                        break;
                      }
                    }
                    --redActive;
                  }
                }
              }
            }
          ),
          /***/
          868: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(1387);
            }
          ),
          /***/
          869: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var num2bn = __webpack_require__2(2651);
              var sign = __webpack_require__2(5716);
              module2.exports = rationalize;
              function rationalize(numer, denom) {
                var snumer = sign(numer);
                var sdenom = sign(denom);
                if (snumer === 0) {
                  return [num2bn(0), num2bn(1)];
                }
                if (sdenom === 0) {
                  return [num2bn(0), num2bn(0)];
                }
                if (sdenom < 0) {
                  numer = numer.neg();
                  denom = denom.neg();
                }
                var d = numer.gcd(denom);
                if (d.cmpn(1)) {
                  return [numer.div(d), denom.div(d)];
                }
                return [numer, denom];
              }
            }
          ),
          /***/
          870: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bindAttribs = __webpack_require__2(1433);
              function VAOEmulated(gl2) {
                this.gl = gl2;
                this._elements = null;
                this._attributes = null;
                this._elementsType = gl2.UNSIGNED_SHORT;
              }
              VAOEmulated.prototype.bind = function() {
                bindAttribs(this.gl, this._elements, this._attributes);
              };
              VAOEmulated.prototype.update = function(attributes, elements, elementsType) {
                this._elements = elements;
                this._attributes = attributes;
                this._elementsType = elementsType || this.gl.UNSIGNED_SHORT;
              };
              VAOEmulated.prototype.dispose = function() {
              };
              VAOEmulated.prototype.unbind = function() {
              };
              VAOEmulated.prototype.draw = function(mode, count, offset) {
                offset = offset || 0;
                var gl2 = this.gl;
                if (this._elements) {
                  gl2.drawElements(mode, count, this._elementsType, offset);
                } else {
                  gl2.drawArrays(mode, offset, count);
                }
              };
              function createVAOEmulated(gl2) {
                return new VAOEmulated(gl2);
              }
              module2.exports = createVAOEmulated;
            }
          ),
          /***/
          946: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bn2num = __webpack_require__2(1369);
              var ctz = __webpack_require__2(4025);
              module2.exports = roundRat;
              function roundRat(f) {
                var a = f[0];
                var b = f[1];
                if (a.cmpn(0) === 0) {
                  return 0;
                }
                var h = a.abs().divmod(b.abs());
                var iv = h.div;
                var x = bn2num(iv);
                var ir = h.mod;
                var sgn = a.negative !== b.negative ? -1 : 1;
                if (ir.cmpn(0) === 0) {
                  return sgn * x;
                }
                if (x) {
                  var s = ctz(x) + 4;
                  var y = bn2num(ir.ushln(s).divRound(b));
                  return sgn * (x + y * Math.pow(2, -s));
                } else {
                  var ybits = b.bitLength() - ir.bitLength() + 53;
                  var y = bn2num(ir.ushln(ybits).divRound(b));
                  if (ybits < 1023) {
                    return sgn * y * Math.pow(2, -ybits);
                  }
                  y *= Math.pow(2, -1023);
                  return sgn * y * Math.pow(2, 1023 - ybits);
                }
              }
            }
          ),
          /***/
          990: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              var createShader = __webpack_require__2(9405);
              var glslify = __webpack_require__2(3236);
              var vertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform vec3 objectOffset;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 localCoordinate = vec3(uv.zw, f.x);\n  worldCoordinate = objectOffset + localCoordinate;\n  mat4 objectOffsetTranslation = mat4(1.0) + mat4(vec4(0), vec4(0), vec4(0), vec4(objectOffset, 0));\n  vec4 worldPosition = (model * objectOffsetTranslation) * vec4(localCoordinate, 1.0);\n  vec4 clipPosition = projection * (view * worldPosition);\n  gl_Position = clipPosition;\n  kill = f.y;\n  value = f.z;\n  planeCoordinate = uv.xy;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * worldPosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  lightDirection = lightPosition - cameraCoordinate.xyz;\n  eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  surfaceNormal  = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n"]);
              var fragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat beckmannSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness) {\n  return beckmannDistribution(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform float vertexColor;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  if (\n    kill > 0.0 ||\n    vColor.a == 0.0 ||\n    outOfRange(clipBounds[0], clipBounds[1], worldCoordinate)\n  ) discard;\n\n  vec3 N = normalize(surfaceNormal);\n  vec3 V = normalize(eyeDirection);\n  vec3 L = normalize(lightDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = max(beckmannSpecular(L, V, N, roughness), 0.);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  //decide how to interpolate color \u2014 in vertex or in fragment\n  vec4 surfaceColor =\n    step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) +\n    step(.5, vertexColor) * vColor;\n\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n"]);
              var contourVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform vec3 objectOffset;\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\nuniform sampler2D colormap;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\nvarying vec4 vColor;\n\nvoid main() {\n  vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n  worldCoordinate = objectOffset + dataCoordinate;\n  mat4 objectOffsetTranslation = mat4(1.0) + mat4(vec4(0), vec4(0), vec4(0), vec4(objectOffset, 0));\n  vec4 worldPosition = (model * objectOffsetTranslation) * vec4(dataCoordinate, 1.0);\n\n  vec4 clipPosition = projection * (view * worldPosition);\n  clipPosition.z += zOffset;\n\n  gl_Position = clipPosition;\n  value = f + objectOffset.z;\n  kill = -1.0;\n  planeCoordinate = uv.zw;\n\n  vColor = texture2D(colormap, vec2(value, value));\n\n  //Don't do lighting for contours\n  surfaceNormal   = vec3(1,0,0);\n  eyeDirection    = vec3(0,1,0);\n  lightDirection  = vec3(0,0,1);\n}\n"]);
              var pickSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n  float vh = 255.0 * v;\n  float upper = floor(vh);\n  float lower = fract(vh);\n  return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n  if ((kill > 0.0) ||\n      (outOfRange(clipBounds[0], clipBounds[1], worldCoordinate))) discard;\n\n  vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n  vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n  gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n"]);
              exports2.createShader = function(gl2) {
                var shader = createShader(gl2, vertSrc, fragSrc, null, [
                  { name: "uv", type: "vec4" },
                  { name: "f", type: "vec3" },
                  { name: "normal", type: "vec3" }
                ]);
                shader.attributes.uv.location = 0;
                shader.attributes.f.location = 1;
                shader.attributes.normal.location = 2;
                return shader;
              };
              exports2.createPickShader = function(gl2) {
                var shader = createShader(gl2, vertSrc, pickSrc, null, [
                  { name: "uv", type: "vec4" },
                  { name: "f", type: "vec3" },
                  { name: "normal", type: "vec3" }
                ]);
                shader.attributes.uv.location = 0;
                shader.attributes.f.location = 1;
                shader.attributes.normal.location = 2;
                return shader;
              };
              exports2.createContourShader = function(gl2) {
                var shader = createShader(gl2, contourVertSrc, fragSrc, null, [
                  { name: "uv", type: "vec4" },
                  { name: "f", type: "float" }
                ]);
                shader.attributes.uv.location = 0;
                shader.attributes.f.location = 1;
                return shader;
              };
              exports2.createPickContourShader = function(gl2) {
                var shader = createShader(gl2, contourVertSrc, pickSrc, null, [
                  { name: "uv", type: "vec4" },
                  { name: "f", type: "float" }
                ]);
                shader.attributes.uv.location = 0;
                shader.attributes.f.location = 1;
                return shader;
              };
            }
          ),
          /***/
          1085: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var padLeft = __webpack_require__2(1371);
              module2.exports = addLineNumbers;
              function addLineNumbers(string, start, delim) {
                start = typeof start === "number" ? start : 1;
                delim = delim || ": ";
                var lines = string.split(/\r?\n/);
                var totalDigits = String(lines.length + start - 1).length;
                return lines.map(function(line, i) {
                  var c = i + start;
                  var digits = String(c).length;
                  var prefix = padLeft(c, totalDigits - digits);
                  return prefix + delim + line;
                }).join("\n");
              }
            }
          ),
          /***/
          1091: (
            /***/
            function(module2) {
              module2.exports = create;
              function create() {
                var out = new Float32Array(3);
                out[0] = 0;
                out[1] = 0;
                out[2] = 0;
                return out;
              }
            }
          ),
          /***/
          1125: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = segmentsIntersect;
              var orient = __webpack_require__2(3250)[3];
              function checkCollinear(a0, a1, b0, b1) {
                for (var d = 0; d < 2; ++d) {
                  var x0 = a0[d];
                  var y0 = a1[d];
                  var l0 = Math.min(x0, y0);
                  var h0 = Math.max(x0, y0);
                  var x1 = b0[d];
                  var y1 = b1[d];
                  var l1 = Math.min(x1, y1);
                  var h1 = Math.max(x1, y1);
                  if (h1 < l0 || h0 < l1) {
                    return false;
                  }
                }
                return true;
              }
              function segmentsIntersect(a0, a1, b0, b1) {
                var x0 = orient(a0, b0, b1);
                var y0 = orient(a1, b0, b1);
                if (x0 > 0 && y0 > 0 || x0 < 0 && y0 < 0) {
                  return false;
                }
                var x1 = orient(b0, a0, a1);
                var y1 = orient(b1, a0, a1);
                if (x1 > 0 && y1 > 0 || x1 < 0 && y1 < 0) {
                  return false;
                }
                if (x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) {
                  return checkCollinear(a0, a1, b0, b1);
                }
                return true;
              }
            }
          ),
          /***/
          1278: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var doubleBits = __webpack_require__2(2361);
              var SMALLEST_DENORM = Math.pow(2, -1074);
              var UINT_MAX = -1 >>> 0;
              module2.exports = nextafter;
              function nextafter(x, y) {
                if (isNaN(x) || isNaN(y)) {
                  return NaN;
                }
                if (x === y) {
                  return x;
                }
                if (x === 0) {
                  if (y < 0) {
                    return -SMALLEST_DENORM;
                  } else {
                    return SMALLEST_DENORM;
                  }
                }
                var hi = doubleBits.hi(x);
                var lo = doubleBits.lo(x);
                if (y > x === x > 0) {
                  if (lo === UINT_MAX) {
                    hi += 1;
                    lo = 0;
                  } else {
                    lo += 1;
                  }
                } else {
                  if (lo === 0) {
                    lo = UINT_MAX;
                    hi -= 1;
                  } else {
                    lo -= 1;
                  }
                }
                return doubleBits.pack(lo, hi);
              }
            }
          ),
          /***/
          1283: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              var createShaderWrapper = __webpack_require__2(9405);
              var glslify = __webpack_require__2(3236);
              var perspectiveVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = 1.0;\n    if(distance(highlightId, id) < 0.0001) {\n      scale = highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1);\n    vec4 viewPosition = view * worldPosition;\n    viewPosition = viewPosition / viewPosition.w;\n    vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"]);
              var orthographicVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = pixelRatio;\n    if(distance(highlightId.bgr, id.bgr) < 0.001) {\n      scale *= highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1.0);\n    vec4 viewPosition = view * worldPosition;\n    vec4 clipPosition = projection * viewPosition;\n    clipPosition /= clipPosition.w;\n\n    gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"]);
              var projectionVertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], position)) {\n\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float lscale = pixelRatio * scale;\n    if(distance(highlightId, id) < 0.0001) {\n      lscale *= highlightScale;\n    }\n\n    vec4 clipCenter   = projection * (view * (model * vec4(position, 1)));\n    vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n    vec4 clipPosition = projection * (view * (model * vec4(dataPosition, 1)));\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = dataPosition;\n  }\n}\n"]);
              var drawFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (\n    outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate) ||\n    interpColor.a * opacity == 0.\n  ) discard;\n  gl_FragColor = interpColor * opacity;\n}\n"]);
              var pickFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if (outOfRange(fragClipBounds[0], fragClipBounds[1], dataCoordinate)) discard;\n\n  gl_FragColor = vec4(pickGroup, pickId.bgr);\n}"]);
              var ATTRIBUTES = [
                { name: "position", type: "vec3" },
                { name: "color", type: "vec4" },
                { name: "glyph", type: "vec2" },
                { name: "id", type: "vec4" }
              ];
              var perspective = {
                vertex: perspectiveVertSrc,
                fragment: drawFragSrc,
                attributes: ATTRIBUTES
              }, ortho = {
                vertex: orthographicVertSrc,
                fragment: drawFragSrc,
                attributes: ATTRIBUTES
              }, project = {
                vertex: projectionVertSrc,
                fragment: drawFragSrc,
                attributes: ATTRIBUTES
              }, pickPerspective = {
                vertex: perspectiveVertSrc,
                fragment: pickFragSrc,
                attributes: ATTRIBUTES
              }, pickOrtho = {
                vertex: orthographicVertSrc,
                fragment: pickFragSrc,
                attributes: ATTRIBUTES
              }, pickProject = {
                vertex: projectionVertSrc,
                fragment: pickFragSrc,
                attributes: ATTRIBUTES
              };
              function createShader(gl2, src) {
                var shader = createShaderWrapper(gl2, src);
                var attr = shader.attributes;
                attr.position.location = 0;
                attr.color.location = 1;
                attr.glyph.location = 2;
                attr.id.location = 3;
                return shader;
              }
              exports2.createPerspective = function(gl2) {
                return createShader(gl2, perspective);
              };
              exports2.createOrtho = function(gl2) {
                return createShader(gl2, ortho);
              };
              exports2.createProject = function(gl2) {
                return createShader(gl2, project);
              };
              exports2.createPickPerspective = function(gl2) {
                return createShader(gl2, pickPerspective);
              };
              exports2.createPickOrtho = function(gl2) {
                return createShader(gl2, pickOrtho);
              };
              exports2.createPickProject = function(gl2) {
                return createShader(gl2, pickProject);
              };
            }
          ),
          /***/
          1303: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = orderSegments;
              var orient = __webpack_require__2(3250);
              function horizontalOrder(a, b) {
                var bl, br;
                if (b[0][0] < b[1][0]) {
                  bl = b[0];
                  br = b[1];
                } else if (b[0][0] > b[1][0]) {
                  bl = b[1];
                  br = b[0];
                } else {
                  var alo = Math.min(a[0][1], a[1][1]);
                  var ahi = Math.max(a[0][1], a[1][1]);
                  var blo = Math.min(b[0][1], b[1][1]);
                  var bhi = Math.max(b[0][1], b[1][1]);
                  if (ahi < blo) {
                    return ahi - blo;
                  }
                  if (alo > bhi) {
                    return alo - bhi;
                  }
                  return ahi - bhi;
                }
                var al, ar;
                if (a[0][1] < a[1][1]) {
                  al = a[0];
                  ar = a[1];
                } else {
                  al = a[1];
                  ar = a[0];
                }
                var d = orient(br, bl, al);
                if (d) {
                  return d;
                }
                d = orient(br, bl, ar);
                if (d) {
                  return d;
                }
                return ar - br;
              }
              function orderSegments(b, a) {
                var al, ar;
                if (a[0][0] < a[1][0]) {
                  al = a[0];
                  ar = a[1];
                } else if (a[0][0] > a[1][0]) {
                  al = a[1];
                  ar = a[0];
                } else {
                  return horizontalOrder(a, b);
                }
                var bl, br;
                if (b[0][0] < b[1][0]) {
                  bl = b[0];
                  br = b[1];
                } else if (b[0][0] > b[1][0]) {
                  bl = b[1];
                  br = b[0];
                } else {
                  return -horizontalOrder(b, a);
                }
                var d1 = orient(al, ar, br);
                var d2 = orient(al, ar, bl);
                if (d1 < 0) {
                  if (d2 <= 0) {
                    return d1;
                  }
                } else if (d1 > 0) {
                  if (d2 >= 0) {
                    return d1;
                  }
                } else if (d2) {
                  return d2;
                }
                d1 = orient(br, bl, ar);
                d2 = orient(br, bl, al);
                if (d1 < 0) {
                  if (d2 <= 0) {
                    return d1;
                  }
                } else if (d1 > 0) {
                  if (d2 >= 0) {
                    return d1;
                  }
                } else if (d2) {
                  return d2;
                }
                return ar[0] - br[0];
              }
            }
          ),
          /***/
          1318: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = cmp;
              function cmp(a, b) {
                return a[0].mul(b[1]).cmp(b[0].mul(a[1]));
              }
            }
          ),
          /***/
          1338: (
            /***/
            function(module2) {
              "use strict";
              function dupe_array(count, value, i) {
                var c = count[i] | 0;
                if (c <= 0) {
                  return [];
                }
                var result = new Array(c), j;
                if (i === count.length - 1) {
                  for (j = 0; j < c; ++j) {
                    result[j] = value;
                  }
                } else {
                  for (j = 0; j < c; ++j) {
                    result[j] = dupe_array(count, value, i + 1);
                  }
                }
                return result;
              }
              function dupe_number(count, value) {
                var result, i;
                result = new Array(count);
                for (i = 0; i < count; ++i) {
                  result[i] = value;
                }
                return result;
              }
              function dupe(count, value) {
                if (typeof value === "undefined") {
                  value = 0;
                }
                switch (typeof count) {
                  case "number":
                    if (count > 0) {
                      return dupe_number(count | 0, value);
                    }
                    break;
                  case "object":
                    if (typeof count.length === "number") {
                      return dupe_array(count, value, 0);
                    }
                    break;
                }
                return [];
              }
              module2.exports = dupe;
            }
          ),
          /***/
          1369: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var sign = __webpack_require__2(5716);
              module2.exports = bn2num;
              function bn2num(b) {
                var l = b.length;
                var words = b.words;
                var out = 0;
                if (l === 1) {
                  out = words[0];
                } else if (l === 2) {
                  out = words[0] + words[1] * 67108864;
                } else {
                  for (var i = 0; i < l; i++) {
                    var w = words[i];
                    out += w * Math.pow(67108864, i);
                  }
                }
                return sign(b) * out;
              }
            }
          ),
          /***/
          1371: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var repeat = __webpack_require__2(3233);
              module2.exports = function padLeft(str, num, ch) {
                ch = typeof ch !== "undefined" ? ch + "" : " ";
                return repeat(ch, num) + str;
              };
            }
          ),
          /***/
          1373: (
            /***/
            function(module2) {
              module2.exports = divide;
              function divide(out, a, b) {
                out[0] = a[0] / b[0];
                out[1] = a[1] / b[1];
                out[2] = a[2] / b[2];
                out[3] = a[3] / b[3];
                return out;
              }
            }
          ),
          /***/
          1387: (
            /***/
            function(module2) {
              module2.exports = length;
              function length(a) {
                var x = a[0], y = a[1], z = a[2];
                return Math.sqrt(x * x + y * y + z * z);
              }
            }
          ),
          /***/
          1433: (
            /***/
            function(module2) {
              "use strict";
              function doBind(gl2, elements, attributes) {
                if (elements) {
                  elements.bind();
                } else {
                  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, null);
                }
                var nattribs = gl2.getParameter(gl2.MAX_VERTEX_ATTRIBS) | 0;
                if (attributes) {
                  if (attributes.length > nattribs) {
                    throw new Error("gl-vao: Too many vertex attributes");
                  }
                  for (var i = 0; i < attributes.length; ++i) {
                    var attrib = attributes[i];
                    if (attrib.buffer) {
                      var buffer = attrib.buffer;
                      var size = attrib.size || 4;
                      var type = attrib.type || gl2.FLOAT;
                      var normalized = !!attrib.normalized;
                      var stride = attrib.stride || 0;
                      var offset = attrib.offset || 0;
                      buffer.bind();
                      gl2.enableVertexAttribArray(i);
                      gl2.vertexAttribPointer(i, size, type, normalized, stride, offset);
                    } else {
                      if (typeof attrib === "number") {
                        gl2.vertexAttrib1f(i, attrib);
                      } else if (attrib.length === 1) {
                        gl2.vertexAttrib1f(i, attrib[0]);
                      } else if (attrib.length === 2) {
                        gl2.vertexAttrib2f(i, attrib[0], attrib[1]);
                      } else if (attrib.length === 3) {
                        gl2.vertexAttrib3f(i, attrib[0], attrib[1], attrib[2]);
                      } else if (attrib.length === 4) {
                        gl2.vertexAttrib4f(i, attrib[0], attrib[1], attrib[2], attrib[3]);
                      } else {
                        throw new Error("gl-vao: Invalid vertex attribute");
                      }
                      gl2.disableVertexAttribArray(i);
                    }
                  }
                  for (; i < nattribs; ++i) {
                    gl2.disableVertexAttribArray(i);
                  }
                } else {
                  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);
                  for (var i = 0; i < nattribs; ++i) {
                    gl2.disableVertexAttribArray(i);
                  }
                }
              }
              module2.exports = doBind;
            }
          ),
          /***/
          1463: (
            /***/
            function(module2) {
              module2.exports = set;
              function set(out, x, y, z) {
                out[0] = x;
                out[1] = y;
                out[2] = z;
                return out;
              }
            }
          ),
          /***/
          1493: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var glslify = __webpack_require__2(3236);
              var createShader = __webpack_require__2(9405);
              var vertSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vertexPosition = mix(coordinates[0],\n    mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n  vec4 clipPos = projection * (view * (model * vec4(vertexPosition, 1.0)));\n  vec2 clipOffset = (projection * (view * (model * vec4(color, 0.0)))).xy;\n  vec2 delta = weight * clipOffset * screenShape;\n  vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n  gl_Position   = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n  fragColor     = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n"]);
              var fragSrc = glslify(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n  gl_FragColor = fragColor;\n}"]);
              module2.exports = function(gl2) {
                return createShader(gl2, vertSrc, fragSrc, null, [
                  { name: "position", type: "vec3" },
                  { name: "color", type: "vec3" },
                  { name: "weight", type: "float" }
                ]);
              };
            }
          ),
          /***/
          1498: (
            /***/
            function(module2) {
              module2.exports = negate;
              function negate(out, a) {
                out[0] = -a[0];
                out[1] = -a[1];
                out[2] = -a[2];
                out[3] = -a[3];
                return out;
              }
            }
          ),
          /***/
          1533: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var BN = __webpack_require__2(6859);
              module2.exports = isBN;
              function isBN(x) {
                return x && typeof x === "object" && Boolean(x.words);
              }
            }
          ),
          /***/
          1538: (
            /***/
            function(module2) {
              (function WeakMapModule() {
                "use strict";
                if (typeof ses !== "undefined" && ses.ok && !ses.ok()) {
                  return;
                }
                function weakMapPermitHostObjects(map) {
                  if (map.permitHostObjects___) {
                    map.permitHostObjects___(weakMapPermitHostObjects);
                  }
                }
                if (typeof ses !== "undefined") {
                  ses.weakMapPermitHostObjects = weakMapPermitHostObjects;
                }
                var doubleWeakMapCheckSilentFailure = false;
                if (typeof WeakMap === "function") {
                  var HostWeakMap = WeakMap;
                  if (typeof navigator !== "undefined" && /Firefox/.test(navigator.userAgent)) {
                  } else {
                    var testMap = new HostWeakMap();
                    var testObject = Object.freeze({});
                    testMap.set(testObject, 1);
                    if (testMap.get(testObject) !== 1) {
                      doubleWeakMapCheckSilentFailure = true;
                    } else {
                      module2.exports = WeakMap;
                      return;
                    }
                  }
                }
                var hop = Object.prototype.hasOwnProperty;
                var gopn = Object.getOwnPropertyNames;
                var defProp = Object.defineProperty;
                var isExtensible = Object.isExtensible;
                var HIDDEN_NAME_PREFIX = "weakmap:";
                var HIDDEN_NAME = HIDDEN_NAME_PREFIX + "ident:" + Math.random() + "___";
                if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function" && typeof ArrayBuffer === "function" && typeof Uint8Array === "function") {
                  var ab = new ArrayBuffer(25);
                  var u8s = new Uint8Array(ab);
                  crypto.getRandomValues(u8s);
                  HIDDEN_NAME = HIDDEN_NAME_PREFIX + "rand:" + Array.prototype.map.call(u8s, function(u8) {
                    return (u8 % 36).toString(36);
                  }).join("") + "___";
                }
                function isNotHiddenName(name2) {
                  return !(name2.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && name2.substr(name2.length - 3) === "___");
                }
                defProp(Object, "getOwnPropertyNames", {
                  value: function fakeGetOwnPropertyNames(obj) {
                    return gopn(obj).filter(isNotHiddenName);
                  }
                });
                if ("getPropertyNames" in Object) {
                  var originalGetPropertyNames = Object.getPropertyNames;
                  defProp(Object, "getPropertyNames", {
                    value: function fakeGetPropertyNames(obj) {
                      return originalGetPropertyNames(obj).filter(isNotHiddenName);
                    }
                  });
                }
                function getHiddenRecord(key) {
                  if (key !== Object(key)) {
                    throw new TypeError("Not an object: " + key);
                  }
                  var hiddenRecord = key[HIDDEN_NAME];
                  if (hiddenRecord && hiddenRecord.key === key) {
                    return hiddenRecord;
                  }
                  if (!isExtensible(key)) {
                    return void 0;
                  }
                  hiddenRecord = { key };
                  try {
                    defProp(key, HIDDEN_NAME, {
                      value: hiddenRecord,
                      writable: false,
                      enumerable: false,
                      configurable: false
                    });
                    return hiddenRecord;
                  } catch (error) {
                    return void 0;
                  }
                }
                (function() {
                  var oldFreeze = Object.freeze;
                  defProp(Object, "freeze", {
                    value: function identifyingFreeze(obj) {
                      getHiddenRecord(obj);
                      return oldFreeze(obj);
                    }
                  });
                  var oldSeal = Object.seal;
                  defProp(Object, "seal", {
                    value: function identifyingSeal(obj) {
                      getHiddenRecord(obj);
                      return oldSeal(obj);
                    }
                  });
                  var oldPreventExtensions = Object.preventExtensions;
                  defProp(Object, "preventExtensions", {
                    value: function identifyingPreventExtensions(obj) {
                      getHiddenRecord(obj);
                      return oldPreventExtensions(obj);
                    }
                  });
                })();
                function constFunc(func) {
                  func.prototype = null;
                  return Object.freeze(func);
                }
                var calledAsFunctionWarningDone = false;
                function calledAsFunctionWarning() {
                  if (!calledAsFunctionWarningDone && typeof console !== "undefined") {
                    calledAsFunctionWarningDone = true;
                    console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future.");
                  }
                }
                var nextId = 0;
                var OurWeakMap = function() {
                  if (!(this instanceof OurWeakMap)) {
                    calledAsFunctionWarning();
                  }
                  var keys = [];
                  var values = [];
                  var id = nextId++;
                  function get___(key, opt_default) {
                    var index;
                    var hiddenRecord = getHiddenRecord(key);
                    if (hiddenRecord) {
                      return id in hiddenRecord ? hiddenRecord[id] : opt_default;
                    } else {
                      index = keys.indexOf(key);
                      return index >= 0 ? values[index] : opt_default;
                    }
                  }
                  function has___(key) {
                    var hiddenRecord = getHiddenRecord(key);
                    if (hiddenRecord) {
                      return id in hiddenRecord;
                    } else {
                      return keys.indexOf(key) >= 0;
                    }
                  }
                  function set___(key, value) {
                    var index;
                    var hiddenRecord = getHiddenRecord(key);
                    if (hiddenRecord) {
                      hiddenRecord[id] = value;
                    } else {
                      index = keys.indexOf(key);
                      if (index >= 0) {
                        values[index] = value;
                      } else {
                        index = keys.length;
                        values[index] = value;
                        keys[index] = key;
                      }
                    }
                    return this;
                  }
                  function delete___(key) {
                    var hiddenRecord = getHiddenRecord(key);
                    var index, lastIndex;
                    if (hiddenRecord) {
                      return id in hiddenRecord && delete hiddenRecord[id];
                    } else {
                      index = keys.indexOf(key);
                      if (index < 0) {
                        return false;
                      }
                      lastIndex = keys.length - 1;
                      keys[index] = void 0;
                      values[index] = values[lastIndex];
                      keys[index] = keys[lastIndex];
                      keys.length = lastIndex;
                      values.length = lastIndex;
                      return true;
                    }
                  }
                  return Object.create(OurWeakMap.prototype, {
                    get___: { value: constFunc(get___) },
                    has___: { value: constFunc(has___) },
                    set___: { value: constFunc(set___) },
                    delete___: { value: constFunc(delete___) }
                  });
                };
                OurWeakMap.prototype = Object.create(Object.prototype, {
                  get: {
                    /**
                     * Return the value most recently associated with key, or
                     * opt_default if none.
                     */
                    value: function get(key, opt_default) {
                      return this.get___(key, opt_default);
                    },
                    writable: true,
                    configurable: true
                  },
                  has: {
                    /**
                     * Is there a value associated with key in this WeakMap?
                     */
                    value: function has(key) {
                      return this.has___(key);
                    },
                    writable: true,
                    configurable: true
                  },
                  set: {
                    /**
                     * Associate value with key in this WeakMap, overwriting any
                     * previous association if present.
                     */
                    value: function set(key, value) {
                      return this.set___(key, value);
                    },
                    writable: true,
                    configurable: true
                  },
                  "delete": {
                    /**
                     * Remove any association for key in this WeakMap, returning
                     * whether there was one.
                     *
                     * <p>Note that the boolean return here does not work like the
                     * {@code delete} operator. The {@code delete} operator returns
                     * whether the deletion succeeds at bringing about a state in
                     * which the deleted property is absent. The {@code delete}
                     * operator therefore returns true if the property was already
                     * absent, whereas this {@code delete} method returns false if
                     * the association was already absent.
                     */
                    value: function remove(key) {
                      return this.delete___(key);
                    },
                    writable: true,
                    configurable: true
                  }
                });
                if (typeof HostWeakMap === "function") {
                  (function() {
                    if (doubleWeakMapCheckSilentFailure && typeof Proxy !== "undefined") {
                      Proxy = void 0;
                    }
                    function DoubleWeakMap() {
                      if (!(this instanceof OurWeakMap)) {
                        calledAsFunctionWarning();
                      }
                      var hmap = new HostWeakMap();
                      var omap = void 0;
                      var enableSwitching = false;
                      function dget(key, opt_default) {
                        if (omap) {
                          return hmap.has(key) ? hmap.get(key) : omap.get___(key, opt_default);
                        } else {
                          return hmap.get(key, opt_default);
                        }
                      }
                      function dhas(key) {
                        return hmap.has(key) || (omap ? omap.has___(key) : false);
                      }
                      var dset;
                      if (doubleWeakMapCheckSilentFailure) {
                        dset = function(key, value) {
                          hmap.set(key, value);
                          if (!hmap.has(key)) {
                            if (!omap) {
                              omap = new OurWeakMap();
                            }
                            omap.set(key, value);
                          }
                          return this;
                        };
                      } else {
                        dset = function(key, value) {
                          if (enableSwitching) {
                            try {
                              hmap.set(key, value);
                            } catch (e) {
                              if (!omap) {
                                omap = new OurWeakMap();
                              }
                              omap.set___(key, value);
                            }
                          } else {
                            hmap.set(key, value);
                          }
                          return this;
                        };
                      }
                      function ddelete(key) {
                        var result = !!hmap["delete"](key);
                        if (omap) {
                          return omap.delete___(key) || result;
                        }
                        return result;
                      }
                      return Object.create(OurWeakMap.prototype, {
                        get___: { value: constFunc(dget) },
                        has___: { value: constFunc(dhas) },
                        set___: { value: constFunc(dset) },
                        delete___: { value: constFunc(ddelete) },
                        permitHostObjects___: { value: constFunc(function(token) {
                          if (token === weakMapPermitHostObjects) {
                            enableSwitching = true;
                          } else {
                            throw new Error("bogus call to permitHostObjects___");
                          }
                        }) }
                      });
                    }
                    DoubleWeakMap.prototype = OurWeakMap.prototype;
                    module2.exports = DoubleWeakMap;
                    Object.defineProperty(WeakMap.prototype, "constructor", {
                      value: WeakMap,
                      enumerable: false,
                      // as default .constructor is
                      configurable: true,
                      writable: true
                    });
                  })();
                } else {
                  if (typeof Proxy !== "undefined") {
                    Proxy = void 0;
                  }
                  module2.exports = OurWeakMap;
                }
              })();
            }
          ),
          /***/
          1570: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = getPolygonizer;
              var allFns = [
                function cellPolygonizer_0() {
                  function B2(C2, E2, i, j) {
                    var a = Math.min(i, j) | 0, b = Math.max(i, j) | 0, l = C2[2 * a], h = C2[2 * a + 1];
                    while (l < h) {
                      var m = l + h >> 1, v = E2[2 * m + 1];
                      if (v === b) {
                        return m;
                      }
                      if (b < v) {
                        h = m;
                      } else {
                        l = m + 1;
                      }
                    }
                    return l;
                  }
                  function getContour0d(F, E2, C2, S) {
                    var n = F.length, R = [];
                    for (var i = 0; i < n; ++i) {
                      var c = F[i], l = c.length;
                    }
                    return R;
                  }
                  return getContour0d;
                },
                function cellPolygonizer_1() {
                  function B2(C2, E2, i, j) {
                    var a = Math.min(i, j) | 0, b = Math.max(i, j) | 0, l = C2[2 * a], h = C2[2 * a + 1];
                    while (l < h) {
                      var m = l + h >> 1, v = E2[2 * m + 1];
                      if (v === b) {
                        return m;
                      }
                      if (b < v) {
                        h = m;
                      } else {
                        l = m + 1;
                      }
                    }
                    return l;
                  }
                  function getContour1d(F, E2, C2, S) {
                    var n = F.length, R = [];
                    for (var i = 0; i < n; ++i) {
                      var c = F[i], l = c.length;
                      if (l === 2) {
                        var M = (S[c[0]] << 0) + (S[c[1]] << 1);
                        if (M === 0 || M === 3) {
                          continue;
                        }
                        switch (M) {
                          case 0:
                            break;
                          case 1:
                            R.push([B2(C2, E2, c[0], c[1])]);
                            break;
                          case 2:
                            R.push([B2(C2, E2, c[1], c[0])]);
                            break;
                          case 3:
                            break;
                        }
                      }
                    }
                    return R;
                  }
                  return getContour1d;
                },
                function cellPolygonizer_2() {
                  function B2(C2, E2, i, j) {
                    var a = Math.min(i, j) | 0, b = Math.max(i, j) | 0, l = C2[2 * a], h = C2[2 * a + 1];
                    while (l < h) {
                      var m = l + h >> 1, v = E2[2 * m + 1];
                      if (v === b) {
                        return m;
                      }
                      if (b < v) {
                        h = m;
                      } else {
                        l = m + 1;
                      }
                    }
                    return l;
                  }
                  function getContour2d(F, E2, C2, S) {
                    var n = F.length, R = [];
                    for (var i = 0; i < n; ++i) {
                      var c = F[i], l = c.length;
                      if (l === 3) {
                        var M = (S[c[0]] << 0) + (S[c[1]] << 1) + (S[c[2]] << 2);
                        if (M === 0 || M === 7) {
                          continue;
                        }
                        switch (M) {
                          case 0:
                            break;
                          case 1:
                            R.push([B2(C2, E2, c[0], c[2]), B2(C2, E2, c[0], c[1])]);
                            break;
                          case 2:
                            R.push([B2(C2, E2, c[1], c[0]), B2(C2, E2, c[1], c[2])]);
                            break;
                          case 3:
                            R.push([B2(C2, E2, c[0], c[2]), B2(C2, E2, c[1], c[2])]);
                            break;
                          case 4:
                            R.push([B2(C2, E2, c[2], c[1]), B2(C2, E2, c[2], c[0])]);
                            break;
                          case 5:
                            R.push([B2(C2, E2, c[2], c[1]), B2(C2, E2, c[0], c[1])]);
                            break;
                          case 6:
                            R.push([B2(C2, E2, c[1], c[0]), B2(C2, E2, c[2], c[0])]);
                            break;
                          case 7:
                            break;
                        }
                      } else if (l === 2) {
                        var M = (S[c[0]] << 0) + (S[c[1]] << 1);
                        if (M === 0 || M === 3) {
                          continue;
                        }
                        switch (M) {
                          case 0:
                            break;
                          case 1:
                            R.push([B2(C2, E2, c[0], c[1])]);
                            break;
                          case 2:
                            R.push([B2(C2, E2, c[1], c[0])]);
                            break;
                          case 3:
                            break;
                        }
                      }
                    }
                    return R;
                  }
                  return getContour2d;
                },
                function cellPolygonizer_3() {
                  function B2(C2, E2, i, j) {
                    var a = Math.min(i, j) | 0, b = Math.max(i, j) | 0, l = C2[2 * a], h = C2[2 * a + 1];
                    while (l < h) {
                      var m = l + h >> 1, v = E2[2 * m + 1];
                      if (v === b) {
                        return m;
                      }
                      if (b < v) {
                        h = m;
                      } else {
                        l = m + 1;
                      }
                    }
                    return l;
                  }
                  function getContour3d(F, E2, C2, S) {
                    var n = F.length, R = [];
                    for (var i = 0; i < n; ++i) {
                      var c = F[i], l = c.length;
                      if (l === 4) {
                        var M = (S[c[0]] << 0) + (S[c[1]] << 1) + (S[c[2]] << 2) + (S[c[3]] << 3);
                        if (M === 0 || M === 15) {
                          continue;
                        }
                        switch (M) {
                          case 0:
                            break;
                          case 1:
                            R.push([B2(C2, E2, c[0], c[1]), B2(C2, E2, c[0], c[2]), B2(C2, E2, c[0], c[3])]);
                            break;
                          case 2:
                            R.push([B2(C2, E2, c[1], c[2]), B2(C2, E2, c[1], c[0]), B2(C2, E2, c[1], c[3])]);
                            break;
                          case 3:
                            R.push([B2(C2, E2, c[1], c[2]), B2(C2, E2, c[0], c[2]), B2(C2, E2, c[0], c[3])], [B2(C2, E2, c[1], c[3]), B2(C2, E2, c[1], c[2]), B2(C2, E2, c[0], c[3])]);
                            break;
                          case 4:
                            R.push([B2(C2, E2, c[2], c[0]), B2(C2, E2, c[2], c[1]), B2(C2, E2, c[2], c[3])]);
                            break;
                          case 5:
                            R.push([B2(C2, E2, c[0], c[1]), B2(C2, E2, c[2], c[1]), B2(C2, E2, c[0], c[3])], [B2(C2, E2, c[2], c[1]), B2(C2, E2, c[2], c[3]), B2(C2, E2, c[0], c[3])]);
                            break;
                          case 6:
                            R.push([B2(C2, E2, c[2], c[0]), B2(C2, E2, c[1], c[0]), B2(C2, E2, c[1], c[3])], [B2(C2, E2, c[2], c[3]), B2(C2, E2, c[2], c[0]), B2(C2, E2, c[1], c[3])]);
                            break;
                          case 7:
                            R.push([B2(C2, E2, c[0], c[3]), B2(C2, E2, c[1], c[3]), B2(C2, E2, c[2], c[3])]);
                            break;
                          case 8:
                            R.push([B2(C2, E2, c[3], c[1]), B2(C2, E2, c[3], c[0]), B2(C2, E2, c[3], c[2])]);
                            break;
                          case 9:
                            R.push([B2(C2, E2, c[3], c[1]), B2(C2, E2, c[0], c[1]), B2(C2, E2, c[0], c[2])], [B2(C2, E2, c[3], c[2]), B2(C2, E2, c[3], c[1]), B2(C2, E2, c[0], c[2])]);
                            break;
                          case 10:
                            R.push([B2(C2, E2, c[1], c[0]), B2(C2, E2, c[3], c[0]), B2(C2, E2, c[1], c[2])], [B2(C2, E2, c[3], c[0]), B2(C2, E2, c[3], c[2]), B2(C2, E2, c[1], c[2])]);
                            break;
                          case 11:
                            R.push([B2(C2, E2, c[1], c[2]), B2(C2, E2, c[0], c[2]), B2(C2, E2, c[3], c[2])]);
                            break;
                          case 12:
                            R.push([B2(C2, E2, c[3], c[0]), B2(C2, E2, c[2], c[0]), B2(C2, E2, c[2], c[1])], [B2(C2, E2, c[3], c[1]), B2(C2, E2, c[3], c[0]), B2(C2, E2, c[2], c[1])]);
                            break;
                          case 13:
                            R.push([B2(C2, E2, c[0], c[1]), B2(C2, E2, c[2], c[1]), B2(C2, E2, c[3], c[1])]);
                            break;
                          case 14:
                            R.push([B2(C2, E2, c[2], c[0]), B2(C2, E2, c[1], c[0]), B2(C2, E2, c[3], c[0])]);
                            break;
                          case 15:
                            break;
                        }
                      } else if (l === 3) {
                        var M = (S[c[0]] << 0) + (S[c[1]] << 1) + (S[c[2]] << 2);
                        if (M === 0 || M === 7) {
                          continue;
                        }
                        switch (M) {
                          case 0:
                            break;
                          case 1:
                            R.push([B2(C2, E2, c[0], c[2]), B2(C2, E2, c[0], c[1])]);
                            break;
                          case 2:
                            R.push([B2(C2, E2, c[1], c[0]), B2(C2, E2, c[1], c[2])]);
                            break;
                          case 3:
                            R.push([B2(C2, E2, c[0], c[2]), B2(C2, E2, c[1], c[2])]);
                            break;
                          case 4:
                            R.push([B2(C2, E2, c[2], c[1]), B2(C2, E2, c[2], c[0])]);
                            break;
                          case 5:
                            R.push([B2(C2, E2, c[2], c[1]), B2(C2, E2, c[0], c[1])]);
                            break;
                          case 6:
                            R.push([B2(C2, E2, c[1], c[0]), B2(C2, E2, c[2], c[0])]);
                            break;
                          case 7:
                            break;
                        }
                      } else if (l === 2) {
                        var M = (S[c[0]] << 0) + (S[c[1]] << 1);
                        if (M === 0 || M === 3) {
                          continue;
                        }
                        switch (M) {
                          case 0:
                            break;
                          case 1:
                            R.push([B2(C2, E2, c[0], c[1])]);
                            break;
                          case 2:
                            R.push([B2(C2, E2, c[1], c[0])]);
                            break;
                          case 3:
                            break;
                        }
                      }
                    }
                    return R;
                  }
                  return getContour3d;
                }
              ];
              function getPolygonizer(d) {
                return allFns[d]();
              }
            }
          ),
          /***/
          1682: (
            /***/
            function(module2) {
              "use strict";
              function unique_pred(list, compare) {
                var ptr = 1, len = list.length, a = list[0], b = list[0];
                for (var i = 1; i < len; ++i) {
                  b = a;
                  a = list[i];
                  if (compare(a, b)) {
                    if (i === ptr) {
                      ptr++;
                      continue;
                    }
                    list[ptr++] = a;
                  }
                }
                list.length = ptr;
                return list;
              }
              function unique_eq(list) {
                var ptr = 1, len = list.length, a = list[0], b = list[0];
                for (var i = 1; i < len; ++i, b = a) {
                  b = a;
                  a = list[i];
                  if (a !== b) {
                    if (i === ptr) {
                      ptr++;
                      continue;
                    }
                    list[ptr++] = a;
                  }
                }
                list.length = ptr;
                return list;
              }
              function unique(list, compare, sorted) {
                if (list.length === 0) {
                  return list;
                }
                if (compare) {
                  if (!sorted) {
                    list.sort(compare);
                  }
                  return unique_pred(list, compare);
                }
                if (!sorted) {
                  list.sort();
                }
                return unique_eq(list);
              }
              module2.exports = unique;
            }
          ),
          /***/
          1755: (
            /***/
            function(module2) {
              "use strict";
              "use restrict";
              module2.exports = UnionFind;
              function UnionFind(count) {
                this.roots = new Array(count);
                this.ranks = new Array(count);
                for (var i = 0; i < count; ++i) {
                  this.roots[i] = i;
                  this.ranks[i] = 0;
                }
              }
              var proto = UnionFind.prototype;
              Object.defineProperty(proto, "length", {
                "get": function() {
                  return this.roots.length;
                }
              });
              proto.makeSet = function() {
                var n = this.roots.length;
                this.roots.push(n);
                this.ranks.push(0);
                return n;
              };
              proto.find = function(x) {
                var x0 = x;
                var roots = this.roots;
                while (roots[x] !== x) {
                  x = roots[x];
                }
                while (roots[x0] !== x) {
                  var y = roots[x0];
                  roots[x0] = x;
                  x0 = y;
                }
                return x;
              };
              proto.link = function(x, y) {
                var xr = this.find(x), yr = this.find(y);
                if (xr === yr) {
                  return;
                }
                var ranks = this.ranks, roots = this.roots, xd = ranks[xr], yd = ranks[yr];
                if (xd < yd) {
                  roots[xr] = yr;
                } else if (yd < xd) {
                  roots[yr] = xr;
                } else {
                  roots[yr] = xr;
                  ++ranks[xr];
                }
              };
            }
          ),
          /***/
          1811: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bsearch = __webpack_require__2(2478);
              var m4interp = __webpack_require__2(7442);
              var invert44 = __webpack_require__2(7608);
              var rotateX = __webpack_require__2(5567);
              var rotateY = __webpack_require__2(2408);
              var rotateZ = __webpack_require__2(7089);
              var lookAt = __webpack_require__2(6582);
              var translate = __webpack_require__2(7656);
              var scale = __webpack_require__2(2504);
              var normalize = __webpack_require__2(3536);
              var DEFAULT_CENTER = [0, 0, 0];
              module2.exports = createMatrixCameraController;
              function MatrixCameraController(initialMatrix) {
                this._components = initialMatrix.slice();
                this._time = [0];
                this.prevMatrix = initialMatrix.slice();
                this.nextMatrix = initialMatrix.slice();
                this.computedMatrix = initialMatrix.slice();
                this.computedInverse = initialMatrix.slice();
                this.computedEye = [0, 0, 0];
                this.computedUp = [0, 0, 0];
                this.computedCenter = [0, 0, 0];
                this.computedRadius = [0];
                this._limits = [-Infinity, Infinity];
              }
              var proto = MatrixCameraController.prototype;
              proto.recalcMatrix = function(t) {
                var time = this._time;
                var tidx = bsearch.le(time, t);
                var mat = this.computedMatrix;
                if (tidx < 0) {
                  return;
                }
                var comps = this._components;
                if (tidx === time.length - 1) {
                  var ptr = 16 * tidx;
                  for (var i = 0; i < 16; ++i) {
                    mat[i] = comps[ptr++];
                  }
                } else {
                  var dt = time[tidx + 1] - time[tidx];
                  var ptr = 16 * tidx;
                  var prev = this.prevMatrix;
                  var allEqual = true;
                  for (var i = 0; i < 16; ++i) {
                    prev[i] = comps[ptr++];
                  }
                  var next = this.nextMatrix;
                  for (var i = 0; i < 16; ++i) {
                    next[i] = comps[ptr++];
                    allEqual = allEqual && prev[i] === next[i];
                  }
                  if (dt < 1e-6 || allEqual) {
                    for (var i = 0; i < 16; ++i) {
                      mat[i] = prev[i];
                    }
                  } else {
                    m4interp(mat, prev, next, (t - time[tidx]) / dt);
                  }
                }
                var up = this.computedUp;
                up[0] = mat[1];
                up[1] = mat[5];
                up[2] = mat[9];
                normalize(up, up);
                var imat = this.computedInverse;
                invert44(imat, mat);
                var eye = this.computedEye;
                var w = imat[15];
                eye[0] = imat[12] / w;
                eye[1] = imat[13] / w;
                eye[2] = imat[14] / w;
                var center = this.computedCenter;
                var radius = Math.exp(this.computedRadius[0]);
                for (var i = 0; i < 3; ++i) {
                  center[i] = eye[i] - mat[2 + 4 * i] * radius;
                }
              };
              proto.idle = function(t) {
                if (t < this.lastT()) {
                  return;
                }
                var mc = this._components;
                var ptr = mc.length - 16;
                for (var i = 0; i < 16; ++i) {
                  mc.push(mc[ptr++]);
                }
                this._time.push(t);
              };
              proto.flush = function(t) {
                var idx = bsearch.gt(this._time, t) - 2;
                if (idx < 0) {
                  return;
                }
                this._time.splice(0, idx);
                this._components.splice(0, 16 * idx);
              };
              proto.lastT = function() {
                return this._time[this._time.length - 1];
              };
              proto.lookAt = function(t, eye, center, up) {
                this.recalcMatrix(t);
                eye = eye || this.computedEye;
                center = center || DEFAULT_CENTER;
                up = up || this.computedUp;
                this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up));
                var d2 = 0;
                for (var i = 0; i < 3; ++i) {
                  d2 += Math.pow(center[i] - eye[i], 2);
                }
                d2 = Math.log(Math.sqrt(d2));
                this.computedRadius[0] = d2;
              };
              proto.rotate = function(t, yaw, pitch, roll) {
                this.recalcMatrix(t);
                var mat = this.computedInverse;
                if (yaw) rotateY(mat, mat, yaw);
                if (pitch) rotateX(mat, mat, pitch);
                if (roll) rotateZ(mat, mat, roll);
                this.setMatrix(t, invert44(this.computedMatrix, mat));
              };
              var tvec = [0, 0, 0];
              proto.pan = function(t, dx, dy, dz) {
                tvec[0] = -(dx || 0);
                tvec[1] = -(dy || 0);
                tvec[2] = -(dz || 0);
                this.recalcMatrix(t);
                var mat = this.computedInverse;
                translate(mat, mat, tvec);
                this.setMatrix(t, invert44(mat, mat));
              };
              proto.translate = function(t, dx, dy, dz) {
                tvec[0] = dx || 0;
                tvec[1] = dy || 0;
                tvec[2] = dz || 0;
                this.recalcMatrix(t);
                var mat = this.computedMatrix;
                translate(mat, mat, tvec);
                this.setMatrix(t, mat);
              };
              proto.setMatrix = function(t, mat) {
                if (t < this.lastT()) {
                  return;
                }
                this._time.push(t);
                for (var i = 0; i < 16; ++i) {
                  this._components.push(mat[i]);
                }
              };
              proto.setDistance = function(t, d) {
                this.computedRadius[0] = d;
              };
              proto.setDistanceLimits = function(a, b) {
                var lim = this._limits;
                lim[0] = a;
                lim[1] = b;
              };
              proto.getDistanceLimits = function(out) {
                var lim = this._limits;
                if (out) {
                  out[0] = lim[0];
                  out[1] = lim[1];
                  return out;
                }
                return lim;
              };
              function createMatrixCameraController(options) {
                options = options || {};
                var matrix = options.matrix || [
                  1,
                  0,
                  0,
                  0,
                  0,
                  1,
                  0,
                  0,
                  0,
                  0,
                  1,
                  0,
                  0,
                  0,
                  0,
                  1
                ];
                return new MatrixCameraController(matrix);
              }
            }
          ),
          /***/
          1848: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var tokenize = __webpack_require__2(4905);
              var atob2 = __webpack_require__2(6468);
              module2.exports = getName;
              function getName(src) {
                var tokens = Array.isArray(src) ? src : tokenize(src);
                for (var i = 0; i < tokens.length; i++) {
                  var token = tokens[i];
                  if (token.type !== "preprocessor") continue;
                  var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/);
                  if (!match) continue;
                  if (!match[2]) continue;
                  var b64 = match[1];
                  var name2 = match[2];
                  return (b64 ? atob2(name2) : name2).trim();
                }
              }
            }
          ),
          /***/
          1879: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              "use strict";
              var glslify = __webpack_require__2(3236);
              var createShader = __webpack_require__2(9405);
              var lineVert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * (view * (model * vec4(p, 1.0)));\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n  vec3 major = position.x * majorAxis;\n  vec3 minor = position.y * minorAxis;\n\n  vec3 vPosition = major + minor + offset;\n  vec3 pPosition = project(vPosition);\n  vec3 offset = project(vPosition + screenAxis * position.z);\n\n  vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n  gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]);
              var lineFrag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"]);
              exports2.n = function(gl2) {
                return createShader(gl2, lineVert, lineFrag, null, [
                  { name: "position", type: "vec3" }
                ]);
              };
              var textVert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis, alignDir, alignOpt;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * (view * (model * vec4(p, 1.0)));\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nfloat computeViewAngle(vec3 a, vec3 b) {\n  vec3 A = project(a);\n  vec3 B = project(b);\n\n  return atan(\n    (B.y - A.y) * resolution.y,\n    (B.x - A.x) * resolution.x\n  );\n}\n\nconst float PI = 3.141592;\nconst float TWO_PI = 2.0 * PI;\nconst float HALF_PI = 0.5 * PI;\nconst float ONE_AND_HALF_PI = 1.5 * PI;\n\nint option = int(floor(alignOpt.x + 0.001));\nfloat hv_ratio =       alignOpt.y;\nbool enableAlign =    (alignOpt.z != 0.0);\n\nfloat mod_angle(float a) {\n  return mod(a, PI);\n}\n\nfloat positive_angle(float a) {\n  return mod_angle((a < 0.0) ?\n    a + TWO_PI :\n    a\n  );\n}\n\nfloat look_upwards(float a) {\n  float b = positive_angle(a);\n  return ((b > HALF_PI) && (b <= ONE_AND_HALF_PI)) ?\n    b - PI :\n    b;\n}\n\nfloat look_horizontal_or_vertical(float a, float ratio) {\n  // ratio controls the ratio between being horizontal to (vertical + horizontal)\n  // if ratio is set to 0.5 then it is 50%, 50%.\n  // when using a higher ratio e.g. 0.75 the result would\n  // likely be more horizontal than vertical.\n\n  float b = positive_angle(a);\n\n  return\n    (b < (      ratio) * HALF_PI) ? 0.0 :\n    (b < (2.0 - ratio) * HALF_PI) ? -HALF_PI :\n    (b < (2.0 + ratio) * HALF_PI) ? 0.0 :\n    (b < (4.0 - ratio) * HALF_PI) ? HALF_PI :\n                                    0.0;\n}\n\nfloat roundTo(float a, float b) {\n  return float(b * floor((a + 0.5 * b) / b));\n}\n\nfloat look_round_n_directions(float a, int n) {\n  float b = positive_angle(a);\n  float div = TWO_PI / float(n);\n  float c = roundTo(b, div);\n  return look_upwards(c);\n}\n\nfloat applyAlignOption(float rawAngle, float delta) {\n  return\n    (option >  2) ? look_round_n_directions(rawAngle + delta, option) :       // option 3-n: round to n directions\n    (option == 2) ? look_horizontal_or_vertical(rawAngle + delta, hv_ratio) : // horizontal or vertical\n    (option == 1) ? rawAngle + delta :       // use free angle, and flip to align with one direction of the axis\n    (option == 0) ? look_upwards(rawAngle) : // use free angle, and stay upwards\n    (option ==-1) ? 0.0 :                    // useful for backward compatibility, all texts remains horizontal\n                    rawAngle;                // otherwise return back raw input angle\n}\n\nbool isAxisTitle = (axis.x == 0.0) &&\n                   (axis.y == 0.0) &&\n                   (axis.z == 0.0);\n\nvoid main() {\n  //Compute world offset\n  float axisDistance = position.z;\n  vec3 dataPosition = axisDistance * axis + offset;\n\n  float beta = angle; // i.e. user defined attributes for each tick\n\n  float axisAngle;\n  float clipAngle;\n  float flip;\n\n  if (enableAlign) {\n    axisAngle = (isAxisTitle) ? HALF_PI :\n                      computeViewAngle(dataPosition, dataPosition + axis);\n    clipAngle = computeViewAngle(dataPosition, dataPosition + alignDir);\n\n    axisAngle += (sin(axisAngle) < 0.0) ? PI : 0.0;\n    clipAngle += (sin(clipAngle) < 0.0) ? PI : 0.0;\n\n    flip = (dot(vec2(cos(axisAngle), sin(axisAngle)),\n                vec2(sin(clipAngle),-cos(clipAngle))) > 0.0) ? 1.0 : 0.0;\n\n    beta += applyAlignOption(clipAngle, flip * PI);\n  }\n\n  //Compute plane offset\n  vec2 planeCoord = position.xy * pixelScale;\n\n  mat2 planeXform = scale * mat2(\n     cos(beta), sin(beta),\n    -sin(beta), cos(beta)\n  );\n\n  vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n  //Compute clip position\n  vec3 clipPosition = project(dataPosition);\n\n  //Apply text offset in clip coordinates\n  clipPosition += vec3(viewOffset, 0.0);\n\n  //Done\n  gl_Position = vec4(clipPosition, 1.0);\n}\n"]);
              var textFrag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"]);
              exports2.Q = function(gl2) {
                return createShader(gl2, textVert, textFrag, null, [
                  { name: "position", type: "vec3" }
                ]);
              };
              var bgVert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n\n  vec3 signAxis = sign(bounds[1] - bounds[0]);\n\n  vec3 realNormal = signAxis * normal;\n\n  if(dot(realNormal, enable) > 0.0) {\n    vec3 minRange = min(bounds[0], bounds[1]);\n    vec3 maxRange = max(bounds[0], bounds[1]);\n    vec3 nPosition = mix(minRange, maxRange, 0.5 * (position + 1.0));\n    gl_Position = projection * (view * (model * vec4(nPosition, 1.0)));\n  } else {\n    gl_Position = vec4(0,0,0,0);\n  }\n\n  colorChannel = abs(realNormal);\n}\n"]);
              var bgFrag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  gl_FragColor = colorChannel.x * colors[0] +\n                 colorChannel.y * colors[1] +\n                 colorChannel.z * colors[2];\n}"]);
              exports2.bg = function(gl2) {
                return createShader(gl2, bgVert, bgFrag, null, [
                  { name: "position", type: "vec3" },
                  { name: "normal", type: "vec3" }
                ]);
              };
            }
          ),
          /***/
          1888: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              "use strict";
              var bits = __webpack_require__2(8828);
              var dup = __webpack_require__2(1338);
              var Buffer2 = __webpack_require__2(4793).hp;
              if (!__webpack_require__2.g.__TYPEDARRAY_POOL) {
                __webpack_require__2.g.__TYPEDARRAY_POOL = {
                  UINT8: dup([32, 0]),
                  UINT16: dup([32, 0]),
                  UINT32: dup([32, 0]),
                  BIGUINT64: dup([32, 0]),
                  INT8: dup([32, 0]),
                  INT16: dup([32, 0]),
                  INT32: dup([32, 0]),
                  BIGINT64: dup([32, 0]),
                  FLOAT: dup([32, 0]),
                  DOUBLE: dup([32, 0]),
                  DATA: dup([32, 0]),
                  UINT8C: dup([32, 0]),
                  BUFFER: dup([32, 0])
                };
              }
              var hasUint8C = typeof Uint8ClampedArray !== "undefined";
              var hasBigUint64 = typeof BigUint64Array !== "undefined";
              var hasBigInt64 = typeof BigInt64Array !== "undefined";
              var POOL = __webpack_require__2.g.__TYPEDARRAY_POOL;
              if (!POOL.UINT8C) {
                POOL.UINT8C = dup([32, 0]);
              }
              if (!POOL.BIGUINT64) {
                POOL.BIGUINT64 = dup([32, 0]);
              }
              if (!POOL.BIGINT64) {
                POOL.BIGINT64 = dup([32, 0]);
              }
              if (!POOL.BUFFER) {
                POOL.BUFFER = dup([32, 0]);
              }
              var DATA = POOL.DATA, BUFFER = POOL.BUFFER;
              exports2.free = function free(array) {
                if (Buffer2.isBuffer(array)) {
                  BUFFER[bits.log2(array.length)].push(array);
                } else {
                  if (Object.prototype.toString.call(array) !== "[object ArrayBuffer]") {
                    array = array.buffer;
                  }
                  if (!array) {
                    return;
                  }
                  var n = array.length || array.byteLength;
                  var log_n = bits.log2(n) | 0;
                  DATA[log_n].push(array);
                }
              };
              function freeArrayBuffer(buffer) {
                if (!buffer) {
                  return;
                }
                var n = buffer.length || buffer.byteLength;
                var log_n = bits.log2(n);
                DATA[log_n].push(buffer);
              }
              function freeTypedArray(array) {
                freeArrayBuffer(array.buffer);
              }
              exports2.freeUint8 = exports2.freeUint16 = exports2.freeUint32 = exports2.freeBigUint64 = exports2.freeInt8 = exports2.freeInt16 = exports2.freeInt32 = exports2.freeBigInt64 = exports2.freeFloat32 = exports2.freeFloat = exports2.freeFloat64 = exports2.freeDouble = exports2.freeUint8Clamped = exports2.freeDataView = freeTypedArray;
              exports2.freeArrayBuffer = freeArrayBuffer;
              exports2.freeBuffer = function freeBuffer(array) {
                BUFFER[bits.log2(array.length)].push(array);
              };
              exports2.malloc = function malloc(n, dtype) {
                if (dtype === void 0 || dtype === "arraybuffer") {
                  return mallocArrayBuffer(n);
                } else {
                  switch (dtype) {
                    case "uint8":
                      return mallocUint8(n);
                    case "uint16":
                      return mallocUint16(n);
                    case "uint32":
                      return mallocUint32(n);
                    case "int8":
                      return mallocInt8(n);
                    case "int16":
                      return mallocInt16(n);
                    case "int32":
                      return mallocInt32(n);
                    case "float":
                    case "float32":
                      return mallocFloat(n);
                    case "double":
                    case "float64":
                      return mallocDouble(n);
                    case "uint8_clamped":
                      return mallocUint8Clamped(n);
                    case "bigint64":
                      return mallocBigInt64(n);
                    case "biguint64":
                      return mallocBigUint64(n);
                    case "buffer":
                      return mallocBuffer(n);
                    case "data":
                    case "dataview":
                      return mallocDataView(n);
                    default:
                      return null;
                  }
                }
                return null;
              };
              function mallocArrayBuffer(n) {
                var n = bits.nextPow2(n);
                var log_n = bits.log2(n);
                var d = DATA[log_n];
                if (d.length > 0) {
                  return d.pop();
                }
                return new ArrayBuffer(n);
              }
              exports2.mallocArrayBuffer = mallocArrayBuffer;
              function mallocUint8(n) {
                return new Uint8Array(mallocArrayBuffer(n), 0, n);
              }
              exports2.mallocUint8 = mallocUint8;
              function mallocUint16(n) {
                return new Uint16Array(mallocArrayBuffer(2 * n), 0, n);
              }
              exports2.mallocUint16 = mallocUint16;
              function mallocUint32(n) {
                return new Uint32Array(mallocArrayBuffer(4 * n), 0, n);
              }
              exports2.mallocUint32 = mallocUint32;
              function mallocInt8(n) {
                return new Int8Array(mallocArrayBuffer(n), 0, n);
              }
              exports2.mallocInt8 = mallocInt8;
              function mallocInt16(n) {
                return new Int16Array(mallocArrayBuffer(2 * n), 0, n);
              }
              exports2.mallocInt16 = mallocInt16;
              function mallocInt32(n) {
                return new Int32Array(mallocArrayBuffer(4 * n), 0, n);
              }
              exports2.mallocInt32 = mallocInt32;
              function mallocFloat(n) {
                return new Float32Array(mallocArrayBuffer(4 * n), 0, n);
              }
              exports2.mallocFloat32 = exports2.mallocFloat = mallocFloat;
              function mallocDouble(n) {
                return new Float64Array(mallocArrayBuffer(8 * n), 0, n);
              }
              exports2.mallocFloat64 = exports2.mallocDouble = mallocDouble;
              function mallocUint8Clamped(n) {
                if (hasUint8C) {
                  return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n);
                } else {
                  return mallocUint8(n);
                }
              }
              exports2.mallocUint8Clamped = mallocUint8Clamped;
              function mallocBigUint64(n) {
                if (hasBigUint64) {
                  return new BigUint64Array(mallocArrayBuffer(8 * n), 0, n);
                } else {
                  return null;
                }
              }
              exports2.mallocBigUint64 = mallocBigUint64;
              function mallocBigInt64(n) {
                if (hasBigInt64) {
                  return new BigInt64Array(mallocArrayBuffer(8 * n), 0, n);
                } else {
                  return null;
                }
              }
              exports2.mallocBigInt64 = mallocBigInt64;
              function mallocDataView(n) {
                return new DataView(mallocArrayBuffer(n), 0, n);
              }
              exports2.mallocDataView = mallocDataView;
              function mallocBuffer(n) {
                n = bits.nextPow2(n);
                var log_n = bits.log2(n);
                var cache = BUFFER[log_n];
                if (cache.length > 0) {
                  return cache.pop();
                }
                return new Buffer2(n);
              }
              exports2.mallocBuffer = mallocBuffer;
              exports2.clearCache = function clearCache() {
                for (var i = 0; i < 32; ++i) {
                  POOL.UINT8[i].length = 0;
                  POOL.UINT16[i].length = 0;
                  POOL.UINT32[i].length = 0;
                  POOL.INT8[i].length = 0;
                  POOL.INT16[i].length = 0;
                  POOL.INT32[i].length = 0;
                  POOL.FLOAT[i].length = 0;
                  POOL.DOUBLE[i].length = 0;
                  POOL.BIGUINT64[i].length = 0;
                  POOL.BIGINT64[i].length = 0;
                  POOL.UINT8C[i].length = 0;
                  DATA[i].length = 0;
                  BUFFER[i].length = 0;
                }
              };
            }
          ),
          /***/
          1903: (
            /***/
            function(module2) {
              module2.exports = clone;
              function clone(a) {
                var out = new Float32Array(16);
                out[0] = a[0];
                out[1] = a[1];
                out[2] = a[2];
                out[3] = a[3];
                out[4] = a[4];
                out[5] = a[5];
                out[6] = a[6];
                out[7] = a[7];
                out[8] = a[8];
                out[9] = a[9];
                out[10] = a[10];
                out[11] = a[11];
                out[12] = a[12];
                out[13] = a[13];
                out[14] = a[14];
                out[15] = a[15];
                return out;
              }
              ;
            }
          ),
          /***/
          1944: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var twoProduct = __webpack_require__2(5250);
              var robustSum = __webpack_require__2(8210);
              module2.exports = robustDotProduct;
              function robustDotProduct(a, b) {
                var r = twoProduct(a[0], b[0]);
                for (var i = 1; i < a.length; ++i) {
                  r = robustSum(r, twoProduct(a[i], b[i]));
                }
                return r;
              }
            }
          ),
          /***/
          1964: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = {
                alpha_shape: __webpack_require__2(3502),
                convex_hull: __webpack_require__2(7352),
                delaunay_triangulate: __webpack_require__2(7642),
                gl_cone3d: __webpack_require__2(6405),
                gl_error3d: __webpack_require__2(9165),
                gl_line3d: __webpack_require__2(5714),
                gl_mesh3d: __webpack_require__2(7201),
                gl_plot3d: __webpack_require__2(4100),
                gl_scatter3d: __webpack_require__2(8418),
                gl_streamtube3d: __webpack_require__2(7815),
                gl_surface3d: __webpack_require__2(9499),
                ndarray: __webpack_require__2(9618),
                ndarray_linear_interpolate: __webpack_require__2(4317)
              };
            }
          ),
          /***/
          2014: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              "use strict";
              "use restrict";
              var bits = __webpack_require__2(3105), UnionFind = __webpack_require__2(4623);
              function dimension(cells) {
                var d = 0, max = Math.max;
                for (var i = 0, il = cells.length; i < il; ++i) {
                  d = max(d, cells[i].length);
                }
                return d - 1;
              }
              exports2.dimension = dimension;
              function countVertices(cells) {
                var vc = -1, max = Math.max;
                for (var i = 0, il = cells.length; i < il; ++i) {
                  var c = cells[i];
                  for (var j = 0, jl = c.length; j < jl; ++j) {
                    vc = max(vc, c[j]);
                  }
                }
                return vc + 1;
              }
              exports2.countVertices = countVertices;
              function cloneCells(cells) {
                var ncells = new Array(cells.length);
                for (var i = 0, il = cells.length; i < il; ++i) {
                  ncells[i] = cells[i].slice(0);
                }
                return ncells;
              }
              exports2.cloneCells = cloneCells;
              function compareCells(a, b) {
                var n = a.length, t = a.length - b.length, min = Math.min;
                if (t) {
                  return t;
                }
                switch (n) {
                  case 0:
                    return 0;
                  case 1:
                    return a[0] - b[0];
                  case 2:
                    var d = a[0] + a[1] - b[0] - b[1];
                    if (d) {
                      return d;
                    }
                    return min(a[0], a[1]) - min(b[0], b[1]);
                  case 3:
                    var l1 = a[0] + a[1], m1 = b[0] + b[1];
                    d = l1 + a[2] - (m1 + b[2]);
                    if (d) {
                      return d;
                    }
                    var l0 = min(a[0], a[1]), m0 = min(b[0], b[1]), d = min(l0, a[2]) - min(m0, b[2]);
                    if (d) {
                      return d;
                    }
                    return min(l0 + a[2], l1) - min(m0 + b[2], m1);
                  //TODO: Maybe optimize n=4 as well?
                  default:
                    var as = a.slice(0);
                    as.sort();
                    var bs = b.slice(0);
                    bs.sort();
                    for (var i = 0; i < n; ++i) {
                      t = as[i] - bs[i];
                      if (t) {
                        return t;
                      }
                    }
                    return 0;
                }
              }
              exports2.compareCells = compareCells;
              function compareZipped(a, b) {
                return compareCells(a[0], b[0]);
              }
              function normalize(cells, attr) {
                if (attr) {
                  var len = cells.length;
                  var zipped = new Array(len);
                  for (var i = 0; i < len; ++i) {
                    zipped[i] = [cells[i], attr[i]];
                  }
                  zipped.sort(compareZipped);
                  for (var i = 0; i < len; ++i) {
                    cells[i] = zipped[i][0];
                    attr[i] = zipped[i][1];
                  }
                  return cells;
                } else {
                  cells.sort(compareCells);
                  return cells;
                }
              }
              exports2.normalize = normalize;
              function unique(cells) {
                if (cells.length === 0) {
                  return [];
                }
                var ptr = 1, len = cells.length;
                for (var i = 1; i < len; ++i) {
                  var a = cells[i];
                  if (compareCells(a, cells[i - 1])) {
                    if (i === ptr) {
                      ptr++;
                      continue;
                    }
                    cells[ptr++] = a;
                  }
                }
                cells.length = ptr;
                return cells;
              }
              exports2.unique = unique;
              function findCell(cells, c) {
                var lo = 0, hi = cells.length - 1, r = -1;
                while (lo <= hi) {
                  var mid = lo + hi >> 1, s = compareCells(cells[mid], c);
                  if (s <= 0) {
                    if (s === 0) {
                      r = mid;
                    }
                    lo = mid + 1;
                  } else if (s > 0) {
                    hi = mid - 1;
                  }
                }
                return r;
              }
              exports2.findCell = findCell;
              function incidence(from_cells, to_cells) {
                var index = new Array(from_cells.length);
                for (var i = 0, il = index.length; i < il; ++i) {
                  index[i] = [];
                }
                var b = [];
                for (var i = 0, n = to_cells.length; i < n; ++i) {
                  var c = to_cells[i];
                  var cl = c.length;
                  for (var k = 1, kn = 1 << cl; k < kn; ++k) {
                    b.length = bits.popCount(k);
                    var l = 0;
                    for (var j = 0; j < cl; ++j) {
                      if (k & 1 << j) {
                        b[l++] = c[j];
                      }
                    }
                    var idx = findCell(from_cells, b);
                    if (idx < 0) {
                      continue;
                    }
                    while (true) {
                      index[idx++].push(i);
                      if (idx >= from_cells.length || compareCells(from_cells[idx], b) !== 0) {
                        break;
                      }
                    }
                  }
                }
                return index;
              }
              exports2.incidence = incidence;
              function dual(cells, vertex_count) {
                if (!vertex_count) {
                  return incidence(unique(skeleton(cells, 0)), cells, 0);
                }
                var res = new Array(vertex_count);
                for (var i = 0; i < vertex_count; ++i) {
                  res[i] = [];
                }
                for (var i = 0, len = cells.length; i < len; ++i) {
                  var c = cells[i];
                  for (var j = 0, cl = c.length; j < cl; ++j) {
                    res[c[j]].push(i);
                  }
                }
                return res;
              }
              exports2.dual = dual;
              function explode(cells) {
                var result = [];
                for (var i = 0, il = cells.length; i < il; ++i) {
                  var c = cells[i], cl = c.length | 0;
                  for (var j = 1, jl = 1 << cl; j < jl; ++j) {
                    var b = [];
                    for (var k = 0; k < cl; ++k) {
                      if (j >>> k & 1) {
                        b.push(c[k]);
                      }
                    }
                    result.push(b);
                  }
                }
                return normalize(result);
              }
              exports2.explode = explode;
              function skeleton(cells, n) {
                if (n < 0) {
                  return [];
                }
                var result = [], k0 = (1 << n + 1) - 1;
                for (var i = 0; i < cells.length; ++i) {
                  var c = cells[i];
                  for (var k = k0; k < 1 << c.length; k = bits.nextCombination(k)) {
                    var b = new Array(n + 1), l = 0;
                    for (var j = 0; j < c.length; ++j) {
                      if (k & 1 << j) {
                        b[l++] = c[j];
                      }
                    }
                    result.push(b);
                  }
                }
                return normalize(result);
              }
              exports2.skeleton = skeleton;
              function boundary(cells) {
                var res = [];
                for (var i = 0, il = cells.length; i < il; ++i) {
                  var c = cells[i];
                  for (var j = 0, cl = c.length; j < cl; ++j) {
                    var b = new Array(c.length - 1);
                    for (var k = 0, l = 0; k < cl; ++k) {
                      if (k !== j) {
                        b[l++] = c[k];
                      }
                    }
                    res.push(b);
                  }
                }
                return normalize(res);
              }
              exports2.boundary = boundary;
              function connectedComponents_dense(cells, vertex_count) {
                var labels = new UnionFind(vertex_count);
                for (var i = 0; i < cells.length; ++i) {
                  var c = cells[i];
                  for (var j = 0; j < c.length; ++j) {
                    for (var k = j + 1; k < c.length; ++k) {
                      labels.link(c[j], c[k]);
                    }
                  }
                }
                var components = [], component_labels = labels.ranks;
                for (var i = 0; i < component_labels.length; ++i) {
                  component_labels[i] = -1;
                }
                for (var i = 0; i < cells.length; ++i) {
                  var l = labels.find(cells[i][0]);
                  if (component_labels[l] < 0) {
                    component_labels[l] = components.length;
                    components.push([cells[i].slice(0)]);
                  } else {
                    components[component_labels[l]].push(cells[i].slice(0));
                  }
                }
                return components;
              }
              function connectedComponents_sparse(cells) {
                var vertices = unique(normalize(skeleton(cells, 0))), labels = new UnionFind(vertices.length);
                for (var i = 0; i < cells.length; ++i) {
                  var c = cells[i];
                  for (var j = 0; j < c.length; ++j) {
                    var vj = findCell(vertices, [c[j]]);
                    for (var k = j + 1; k < c.length; ++k) {
                      labels.link(vj, findCell(vertices, [c[k]]));
                    }
                  }
                }
                var components = [], component_labels = labels.ranks;
                for (var i = 0; i < component_labels.length; ++i) {
                  component_labels[i] = -1;
                }
                for (var i = 0; i < cells.length; ++i) {
                  var l = labels.find(findCell(vertices, [cells[i][0]]));
                  if (component_labels[l] < 0) {
                    component_labels[l] = components.length;
                    components.push([cells[i].slice(0)]);
                  } else {
                    components[component_labels[l]].push(cells[i].slice(0));
                  }
                }
                return components;
              }
              function connectedComponents(cells, vertex_count) {
                if (vertex_count) {
                  return connectedComponents_dense(cells, vertex_count);
                }
                return connectedComponents_sparse(cells);
              }
              exports2.connectedComponents = connectedComponents;
            }
          ),
          /***/
          2095: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = planarGraphToPolyline;
              var e2a = __webpack_require__2(3134);
              var planarDual = __webpack_require__2(3088);
              var preprocessPolygon = __webpack_require__2(5085);
              var twoProduct = __webpack_require__2(5250);
              var robustSum = __webpack_require__2(8210);
              var uniq = __webpack_require__2(1682);
              var trimLeaves = __webpack_require__2(5609);
              function makeArray(length, fill) {
                var result = new Array(length);
                for (var i = 0; i < length; ++i) {
                  result[i] = fill;
                }
                return result;
              }
              function makeArrayOfArrays(length) {
                var result = new Array(length);
                for (var i = 0; i < length; ++i) {
                  result[i] = [];
                }
                return result;
              }
              function planarGraphToPolyline(edges, positions) {
                var result = trimLeaves(edges, positions);
                edges = result[0];
                positions = result[1];
                var numVertices = positions.length;
                var numEdges = edges.length;
                var adj = e2a(edges, positions.length);
                for (var i = 0; i < numVertices; ++i) {
                  if (adj[i].length % 2 === 1) {
                    throw new Error("planar-graph-to-polyline: graph must be manifold");
                  }
                }
                var faces = planarDual(edges, positions);
                function ccw(c2) {
                  var n2 = c2.length;
                  var area = [0];
                  for (var j2 = 0; j2 < n2; ++j2) {
                    var a2 = positions[c2[j2]];
                    var b2 = positions[c2[(j2 + 1) % n2]];
                    var t00 = twoProduct(-a2[0], a2[1]);
                    var t01 = twoProduct(-a2[0], b2[1]);
                    var t10 = twoProduct(b2[0], a2[1]);
                    var t11 = twoProduct(b2[0], b2[1]);
                    area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11)));
                  }
                  return area[area.length - 1] > 0;
                }
                faces = faces.filter(ccw);
                var numFaces = faces.length;
                var parent = new Array(numFaces);
                var containment = new Array(numFaces);
                for (var i = 0; i < numFaces; ++i) {
                  parent[i] = i;
                  var row = new Array(numFaces);
                  var loopVertices = faces[i].map(function(v) {
                    return positions[v];
                  });
                  var pmc = preprocessPolygon([loopVertices]);
                  var count = 0;
                  outer:
                    for (var j = 0; j < numFaces; ++j) {
                      row[j] = 0;
                      if (i === j) {
                        continue;
                      }
                      var c = faces[j];
                      var n = c.length;
                      for (var k = 0; k < n; ++k) {
                        var d = pmc(positions[c[k]]);
                        if (d !== 0) {
                          if (d < 0) {
                            row[j] = 1;
                            count += 1;
                          }
                          continue outer;
                        }
                      }
                      row[j] = 1;
                      count += 1;
                    }
                  containment[i] = [count, i, row];
                }
                containment.sort(function(a2, b2) {
                  return b2[0] - a2[0];
                });
                for (var i = 0; i < numFaces; ++i) {
                  var row = containment[i];
                  var idx = row[1];
                  var children = row[2];
                  for (var j = 0; j < numFaces; ++j) {
                    if (children[j]) {
                      parent[j] = idx;
                    }
                  }
                }
                var fadj = makeArrayOfArrays(numFaces);
                for (var i = 0; i < numFaces; ++i) {
                  fadj[i].push(parent[i]);
                  fadj[parent[i]].push(i);
                }
                var edgeAdjacency = {};
                var internalVertices = makeArray(numVertices, false);
                for (var i = 0; i < numFaces; ++i) {
                  var c = faces[i];
                  var n = c.length;
                  for (var j = 0; j < n; ++j) {
                    var a = c[j];
                    var b = c[(j + 1) % n];
                    var key = Math.min(a, b) + ":" + Math.max(a, b);
                    if (key in edgeAdjacency) {
                      var neighbor = edgeAdjacency[key];
                      fadj[neighbor].push(i);
                      fadj[i].push(neighbor);
                      internalVertices[a] = internalVertices[b] = true;
                    } else {
                      edgeAdjacency[key] = i;
                    }
                  }
                }
                function sharedBoundary(c2) {
                  var n2 = c2.length;
                  for (var i2 = 0; i2 < n2; ++i2) {
                    if (!internalVertices[c2[i2]]) {
                      return false;
                    }
                  }
                  return true;
                }
                var toVisit = [];
                var parity = makeArray(numFaces, -1);
                for (var i = 0; i < numFaces; ++i) {
                  if (parent[i] === i && !sharedBoundary(faces[i])) {
                    toVisit.push(i);
                    parity[i] = 0;
                  } else {
                    parity[i] = -1;
                  }
                }
                var result = [];
                while (toVisit.length > 0) {
                  var top = toVisit.pop();
                  var nbhd = fadj[top];
                  uniq(nbhd, function(a2, b2) {
                    return a2 - b2;
                  });
                  var nnbhr = nbhd.length;
                  var p = parity[top];
                  var polyline;
                  if (p === 0) {
                    var c = faces[top];
                    polyline = [c];
                  }
                  for (var i = 0; i < nnbhr; ++i) {
                    var f = nbhd[i];
                    if (parity[f] >= 0) {
                      continue;
                    }
                    parity[f] = p ^ 1;
                    toVisit.push(f);
                    if (p === 0) {
                      var c = faces[f];
                      if (!sharedBoundary(c)) {
                        c.reverse();
                        polyline.push(c);
                      }
                    }
                  }
                  if (p === 0) {
                    result.push(polyline);
                  }
                }
                return result;
              }
            }
          ),
          /***/
          2145: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              exports2.uniforms = runtimeUniforms;
              exports2.attributes = runtimeAttributes;
              var GL_TO_GLSL_TYPES = {
                "FLOAT": "float",
                "FLOAT_VEC2": "vec2",
                "FLOAT_VEC3": "vec3",
                "FLOAT_VEC4": "vec4",
                "INT": "int",
                "INT_VEC2": "ivec2",
                "INT_VEC3": "ivec3",
                "INT_VEC4": "ivec4",
                "BOOL": "bool",
                "BOOL_VEC2": "bvec2",
                "BOOL_VEC3": "bvec3",
                "BOOL_VEC4": "bvec4",
                "FLOAT_MAT2": "mat2",
                "FLOAT_MAT3": "mat3",
                "FLOAT_MAT4": "mat4",
                "SAMPLER_2D": "sampler2D",
                "SAMPLER_CUBE": "samplerCube"
              };
              var GL_TABLE = null;
              function getType(gl2, type) {
                if (!GL_TABLE) {
                  var typeNames = Object.keys(GL_TO_GLSL_TYPES);
                  GL_TABLE = {};
                  for (var i = 0; i < typeNames.length; ++i) {
                    var tn = typeNames[i];
                    GL_TABLE[gl2[tn]] = GL_TO_GLSL_TYPES[tn];
                  }
                }
                return GL_TABLE[type];
              }
              function runtimeUniforms(gl2, program) {
                var numUniforms = gl2.getProgramParameter(program, gl2.ACTIVE_UNIFORMS);
                var result = [];
                for (var i = 0; i < numUniforms; ++i) {
                  var info = gl2.getActiveUniform(program, i);
                  if (info) {
                    var type = getType(gl2, info.type);
                    if (info.size > 1) {
                      for (var j = 0; j < info.size; ++j) {
                        result.push({
                          name: info.name.replace("[0]", "[" + j + "]"),
                          type
                        });
                      }
                    } else {
                      result.push({
                        name: info.name,
                        type
                      });
                    }
                  }
                }
                return result;
              }
              function runtimeAttributes(gl2, program) {
                var numAttributes = gl2.getProgramParameter(program, gl2.ACTIVE_ATTRIBUTES);
                var result = [];
                for (var i = 0; i < numAttributes; ++i) {
                  var info = gl2.getActiveAttrib(program, i);
                  if (info) {
                    result.push({
                      name: info.name,
                      type: getType(gl2, info.type)
                    });
                  }
                }
                return result;
              }
            }
          ),
          /***/
          2229: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(6843);
            }
          ),
          /***/
          2260: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var createTexture = __webpack_require__2(7766);
              module2.exports = createFBO;
              var colorAttachmentArrays = null;
              var FRAMEBUFFER_UNSUPPORTED;
              var FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
              var FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
              var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
              function saveFBOState(gl2) {
                var fbo = gl2.getParameter(gl2.FRAMEBUFFER_BINDING);
                var rbo = gl2.getParameter(gl2.RENDERBUFFER_BINDING);
                var tex = gl2.getParameter(gl2.TEXTURE_BINDING_2D);
                return [fbo, rbo, tex];
              }
              function restoreFBOState(gl2, data) {
                gl2.bindFramebuffer(gl2.FRAMEBUFFER, data[0]);
                gl2.bindRenderbuffer(gl2.RENDERBUFFER, data[1]);
                gl2.bindTexture(gl2.TEXTURE_2D, data[2]);
              }
              function lazyInitColorAttachments(gl2, ext) {
                var maxColorAttachments = gl2.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL);
                colorAttachmentArrays = new Array(maxColorAttachments + 1);
                for (var i = 0; i <= maxColorAttachments; ++i) {
                  var x = new Array(maxColorAttachments);
                  for (var j = 0; j < i; ++j) {
                    x[j] = gl2.COLOR_ATTACHMENT0 + j;
                  }
                  for (var j = i; j < maxColorAttachments; ++j) {
                    x[j] = gl2.NONE;
                  }
                  colorAttachmentArrays[i] = x;
                }
              }
              function throwFBOError(status) {
                switch (status) {
                  case FRAMEBUFFER_UNSUPPORTED:
                    throw new Error("gl-fbo: Framebuffer unsupported");
                  case FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                    throw new Error("gl-fbo: Framebuffer incomplete attachment");
                  case FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                    throw new Error("gl-fbo: Framebuffer incomplete dimensions");
                  case FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                    throw new Error("gl-fbo: Framebuffer incomplete missing attachment");
                  default:
                    throw new Error("gl-fbo: Framebuffer failed for unspecified reason");
                }
              }
              function initTexture(gl2, width, height, type, format, attachment) {
                if (!type) {
                  return null;
                }
                var result = createTexture(gl2, width, height, format, type);
                result.magFilter = gl2.NEAREST;
                result.minFilter = gl2.NEAREST;
                result.mipSamples = 1;
                result.bind();
                gl2.framebufferTexture2D(gl2.FRAMEBUFFER, attachment, gl2.TEXTURE_2D, result.handle, 0);
                return result;
              }
              function initRenderBuffer(gl2, width, height, component, attachment) {
                var result = gl2.createRenderbuffer();
                gl2.bindRenderbuffer(gl2.RENDERBUFFER, result);
                gl2.renderbufferStorage(gl2.RENDERBUFFER, component, width, height);
                gl2.framebufferRenderbuffer(gl2.FRAMEBUFFER, attachment, gl2.RENDERBUFFER, result);
                return result;
              }
              function rebuildFBO(fbo) {
                var state = saveFBOState(fbo.gl);
                var gl2 = fbo.gl;
                var handle = fbo.handle = gl2.createFramebuffer();
                var width = fbo._shape[0];
                var height = fbo._shape[1];
                var numColors = fbo.color.length;
                var ext = fbo._ext;
                var useStencil = fbo._useStencil;
                var useDepth = fbo._useDepth;
                var colorType = fbo._colorType;
                gl2.bindFramebuffer(gl2.FRAMEBUFFER, handle);
                for (var i = 0; i < numColors; ++i) {
                  fbo.color[i] = initTexture(gl2, width, height, colorType, gl2.RGBA, gl2.COLOR_ATTACHMENT0 + i);
                }
                if (numColors === 0) {
                  fbo._color_rb = initRenderBuffer(gl2, width, height, gl2.RGBA4, gl2.COLOR_ATTACHMENT0);
                  if (ext) {
                    ext.drawBuffersWEBGL(colorAttachmentArrays[0]);
                  }
                } else if (numColors > 1) {
                  ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]);
                }
                var WEBGL_depth_texture = gl2.getExtension("WEBGL_depth_texture");
                if (WEBGL_depth_texture) {
                  if (useStencil) {
                    fbo.depth = initTexture(
                      gl2,
                      width,
                      height,
                      WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL,
                      gl2.DEPTH_STENCIL,
                      gl2.DEPTH_STENCIL_ATTACHMENT
                    );
                  } else if (useDepth) {
                    fbo.depth = initTexture(
                      gl2,
                      width,
                      height,
                      gl2.UNSIGNED_SHORT,
                      gl2.DEPTH_COMPONENT,
                      gl2.DEPTH_ATTACHMENT
                    );
                  }
                } else {
                  if (useDepth && useStencil) {
                    fbo._depth_rb = initRenderBuffer(gl2, width, height, gl2.DEPTH_STENCIL, gl2.DEPTH_STENCIL_ATTACHMENT);
                  } else if (useDepth) {
                    fbo._depth_rb = initRenderBuffer(gl2, width, height, gl2.DEPTH_COMPONENT16, gl2.DEPTH_ATTACHMENT);
                  } else if (useStencil) {
                    fbo._depth_rb = initRenderBuffer(gl2, width, height, gl2.STENCIL_INDEX, gl2.STENCIL_ATTACHMENT);
                  }
                }
                var status = gl2.checkFramebufferStatus(gl2.FRAMEBUFFER);
                if (status !== gl2.FRAMEBUFFER_COMPLETE) {
                  fbo._destroyed = true;
                  gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
                  gl2.deleteFramebuffer(fbo.handle);
                  fbo.handle = null;
                  if (fbo.depth) {
                    fbo.depth.dispose();
                    fbo.depth = null;
                  }
                  if (fbo._depth_rb) {
                    gl2.deleteRenderbuffer(fbo._depth_rb);
                    fbo._depth_rb = null;
                  }
                  for (var i = 0; i < fbo.color.length; ++i) {
                    fbo.color[i].dispose();
                    fbo.color[i] = null;
                  }
                  if (fbo._color_rb) {
                    gl2.deleteRenderbuffer(fbo._color_rb);
                    fbo._color_rb = null;
                  }
                  restoreFBOState(gl2, state);
                  throwFBOError(status);
                }
                restoreFBOState(gl2, state);
              }
              function Framebuffer(gl2, width, height, colorType, numColors, useDepth, useStencil, ext) {
                this.gl = gl2;
                this._shape = [width | 0, height | 0];
                this._destroyed = false;
                this._ext = ext;
                this.color = new Array(numColors);
                for (var i = 0; i < numColors; ++i) {
                  this.color[i] = null;
                }
                this._color_rb = null;
                this.depth = null;
                this._depth_rb = null;
                this._colorType = colorType;
                this._useDepth = useDepth;
                this._useStencil = useStencil;
                var parent = this;
                var shapeVector = [width | 0, height | 0];
                Object.defineProperties(shapeVector, {
                  0: {
                    get: function() {
                      return parent._shape[0];
                    },
                    set: function(w) {
                      return parent.width = w;
                    }
                  },
                  1: {
                    get: function() {
                      return parent._shape[1];
                    },
                    set: function(h) {
                      return parent.height = h;
                    }
                  }
                });
                this._shapeVector = shapeVector;
                rebuildFBO(this);
              }
              var proto = Framebuffer.prototype;
              function reshapeFBO(fbo, w, h) {
                if (fbo._destroyed) {
                  throw new Error("gl-fbo: Can't resize destroyed FBO");
                }
                if (fbo._shape[0] === w && fbo._shape[1] === h) {
                  return;
                }
                var gl2 = fbo.gl;
                var maxFBOSize = gl2.getParameter(gl2.MAX_RENDERBUFFER_SIZE);
                if (w < 0 || w > maxFBOSize || h < 0 || h > maxFBOSize) {
                  throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");
                }
                fbo._shape[0] = w;
                fbo._shape[1] = h;
                var state = saveFBOState(gl2);
                for (var i = 0; i < fbo.color.length; ++i) {
                  fbo.color[i].shape = fbo._shape;
                }
                if (fbo._color_rb) {
                  gl2.bindRenderbuffer(gl2.RENDERBUFFER, fbo._color_rb);
                  gl2.renderbufferStorage(gl2.RENDERBUFFER, gl2.RGBA4, fbo._shape[0], fbo._shape[1]);
                }
                if (fbo.depth) {
                  fbo.depth.shape = fbo._shape;
                }
                if (fbo._depth_rb) {
                  gl2.bindRenderbuffer(gl2.RENDERBUFFER, fbo._depth_rb);
                  if (fbo._useDepth && fbo._useStencil) {
                    gl2.renderbufferStorage(gl2.RENDERBUFFER, gl2.DEPTH_STENCIL, fbo._shape[0], fbo._shape[1]);
                  } else if (fbo._useDepth) {
                    gl2.renderbufferStorage(gl2.RENDERBUFFER, gl2.DEPTH_COMPONENT16, fbo._shape[0], fbo._shape[1]);
                  } else if (fbo._useStencil) {
                    gl2.renderbufferStorage(gl2.RENDERBUFFER, gl2.STENCIL_INDEX, fbo._shape[0], fbo._shape[1]);
                  }
                }
                gl2.bindFramebuffer(gl2.FRAMEBUFFER, fbo.handle);
                var status = gl2.checkFramebufferStatus(gl2.FRAMEBUFFER);
                if (status !== gl2.FRAMEBUFFER_COMPLETE) {
                  fbo.dispose();
                  restoreFBOState(gl2, state);
                  throwFBOError(status);
                }
                restoreFBOState(gl2, state);
              }
              Object.defineProperties(proto, {
                "shape": {
                  get: function() {
                    if (this._destroyed) {
                      return [0, 0];
                    }
                    return this._shapeVector;
                  },
                  set: function(x) {
                    if (!Array.isArray(x)) {
                      x = [x | 0, x | 0];
                    }
                    if (x.length !== 2) {
                      throw new Error("gl-fbo: Shape vector must be length 2");
                    }
                    var w = x[0] | 0;
                    var h = x[1] | 0;
                    reshapeFBO(this, w, h);
                    return [w, h];
                  },
                  enumerable: false
                },
                "width": {
                  get: function() {
                    if (this._destroyed) {
                      return 0;
                    }
                    return this._shape[0];
                  },
                  set: function(w) {
                    w = w | 0;
                    reshapeFBO(this, w, this._shape[1]);
                    return w;
                  },
                  enumerable: false
                },
                "height": {
                  get: function() {
                    if (this._destroyed) {
                      return 0;
                    }
                    return this._shape[1];
                  },
                  set: function(h) {
                    h = h | 0;
                    reshapeFBO(this, this._shape[0], h);
                    return h;
                  },
                  enumerable: false
                }
              });
              proto.bind = function() {
                if (this._destroyed) {
                  return;
                }
                var gl2 = this.gl;
                gl2.bindFramebuffer(gl2.FRAMEBUFFER, this.handle);
                gl2.viewport(0, 0, this._shape[0], this._shape[1]);
              };
              proto.dispose = function() {
                if (this._destroyed) {
                  return;
                }
                this._destroyed = true;
                var gl2 = this.gl;
                gl2.deleteFramebuffer(this.handle);
                this.handle = null;
                if (this.depth) {
                  this.depth.dispose();
                  this.depth = null;
                }
                if (this._depth_rb) {
                  gl2.deleteRenderbuffer(this._depth_rb);
                  this._depth_rb = null;
                }
                for (var i = 0; i < this.color.length; ++i) {
                  this.color[i].dispose();
                  this.color[i] = null;
                }
                if (this._color_rb) {
                  gl2.deleteRenderbuffer(this._color_rb);
                  this._color_rb = null;
                }
              };
              function createFBO(gl2, width, height, options) {
                if (!FRAMEBUFFER_UNSUPPORTED) {
                  FRAMEBUFFER_UNSUPPORTED = gl2.FRAMEBUFFER_UNSUPPORTED;
                  FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl2.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
                  FRAMEBUFFER_INCOMPLETE_DIMENSIONS = gl2.FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
                  FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl2.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
                }
                var WEBGL_draw_buffers = gl2.getExtension("WEBGL_draw_buffers");
                if (!colorAttachmentArrays && WEBGL_draw_buffers) {
                  lazyInitColorAttachments(gl2, WEBGL_draw_buffers);
                }
                if (Array.isArray(width)) {
                  options = height;
                  height = width[1] | 0;
                  width = width[0] | 0;
                }
                if (typeof width !== "number") {
                  throw new Error("gl-fbo: Missing shape parameter");
                }
                var maxFBOSize = gl2.getParameter(gl2.MAX_RENDERBUFFER_SIZE);
                if (width < 0 || width > maxFBOSize || height < 0 || height > maxFBOSize) {
                  throw new Error("gl-fbo: Parameters are too large for FBO");
                }
                options = options || {};
                var numColors = 1;
                if ("color" in options) {
                  numColors = Math.max(options.color | 0, 0);
                  if (numColors < 0) {
                    throw new Error("gl-fbo: Must specify a nonnegative number of colors");
                  }
                  if (numColors > 1) {
                    if (!WEBGL_draw_buffers) {
                      throw new Error("gl-fbo: Multiple draw buffer extension not supported");
                    } else if (numColors > gl2.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) {
                      throw new Error("gl-fbo: Context does not support " + numColors + " draw buffers");
                    }
                  }
                }
                var colorType = gl2.UNSIGNED_BYTE;
                var OES_texture_float = gl2.getExtension("OES_texture_float");
                if (options.float && numColors > 0) {
                  if (!OES_texture_float) {
                    throw new Error("gl-fbo: Context does not support floating point textures");
                  }
                  colorType = gl2.FLOAT;
                } else if (options.preferFloat && numColors > 0) {
                  if (OES_texture_float) {
                    colorType = gl2.FLOAT;
                  }
                }
                var useDepth = true;
                if ("depth" in options) {
                  useDepth = !!options.depth;
                }
                var useStencil = false;
                if ("stencil" in options) {
                  useStencil = !!options.stencil;
                }
                return new Framebuffer(
                  gl2,
                  width,
                  height,
                  colorType,
                  numColors,
                  useDepth,
                  useStencil,
                  WEBGL_draw_buffers
                );
              }
            }
          ),
          /***/
          2272: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var inCircle = __webpack_require__2(2646)[4];
              var bsearch = __webpack_require__2(2478);
              module2.exports = delaunayRefine;
              function testFlip(points, triangulation, stack, a, b, x) {
                var y = triangulation.opposite(a, b);
                if (y < 0) {
                  return;
                }
                if (b < a) {
                  var tmp = a;
                  a = b;
                  b = tmp;
                  tmp = x;
                  x = y;
                  y = tmp;
                }
                if (triangulation.isConstraint(a, b)) {
                  return;
                }
                if (inCircle(points[a], points[b], points[x], points[y]) < 0) {
                  stack.push(a, b);
                }
              }
              function delaunayRefine(points, triangulation) {
                var stack = [];
                var numPoints = points.length;
                var stars = triangulation.stars;
                for (var a = 0; a < numPoints; ++a) {
                  var star = stars[a];
                  for (var j = 1; j < star.length; j += 2) {
                    var b = star[j];
                    if (b < a) {
                      continue;
                    }
                    if (triangulation.isConstraint(a, b)) {
                      continue;
                    }
                    var x = star[j - 1], y = -1;
                    for (var k = 1; k < star.length; k += 2) {
                      if (star[k - 1] === b) {
                        y = star[k];
                        break;
                      }
                    }
                    if (y < 0) {
                      continue;
                    }
                    if (inCircle(points[a], points[b], points[x], points[y]) < 0) {
                      stack.push(a, b);
                    }
                  }
                }
                while (stack.length > 0) {
                  var b = stack.pop();
                  var a = stack.pop();
                  var x = -1, y = -1;
                  var star = stars[a];
                  for (var i = 1; i < star.length; i += 2) {
                    var s = star[i - 1];
                    var t = star[i];
                    if (s === b) {
                      y = t;
                    } else if (t === b) {
                      x = s;
                    }
                  }
                  if (x < 0 || y < 0) {
                    continue;
                  }
                  if (inCircle(points[a], points[b], points[x], points[y]) >= 0) {
                    continue;
                  }
                  triangulation.flip(a, b);
                  testFlip(points, triangulation, stack, x, a, y);
                  testFlip(points, triangulation, stack, a, y, x);
                  testFlip(points, triangulation, stack, y, b, x);
                  testFlip(points, triangulation, stack, b, x, y);
                }
              }
            }
          ),
          /***/
          2334: (
            /***/
            function(module2) {
              module2.exports = min;
              function min(out, a, b) {
                out[0] = Math.min(a[0], b[0]);
                out[1] = Math.min(a[1], b[1]);
                out[2] = Math.min(a[2], b[2]);
                out[3] = Math.min(a[3], b[3]);
                return out;
              }
            }
          ),
          /***/
          2335: (
            /***/
            function(module2) {
              module2.exports = clone;
              function clone(a) {
                var out = new Float32Array(4);
                out[0] = a[0];
                out[1] = a[1];
                out[2] = a[2];
                out[3] = a[3];
                return out;
              }
            }
          ),
          /***/
          2361: (
            /***/
            function(module2) {
              var hasTypedArrays = false;
              if (typeof Float64Array !== "undefined") {
                var DOUBLE_VIEW = new Float64Array(1), UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer);
                DOUBLE_VIEW[0] = 1;
                hasTypedArrays = true;
                if (UINT_VIEW[1] === 1072693248) {
                  let toDoubleLE2 = function(lo, hi) {
                    UINT_VIEW[0] = lo;
                    UINT_VIEW[1] = hi;
                    return DOUBLE_VIEW[0];
                  }, lowUintLE2 = function(n) {
                    DOUBLE_VIEW[0] = n;
                    return UINT_VIEW[0];
                  }, highUintLE2 = function(n) {
                    DOUBLE_VIEW[0] = n;
                    return UINT_VIEW[1];
                  };
                  var toDoubleLE = toDoubleLE2, lowUintLE = lowUintLE2, highUintLE = highUintLE2;
                  module2.exports = function doubleBitsLE(n) {
                    DOUBLE_VIEW[0] = n;
                    return [UINT_VIEW[0], UINT_VIEW[1]];
                  };
                  module2.exports.pack = toDoubleLE2;
                  module2.exports.lo = lowUintLE2;
                  module2.exports.hi = highUintLE2;
                } else if (UINT_VIEW[0] === 1072693248) {
                  let toDoubleBE2 = function(lo, hi) {
                    UINT_VIEW[1] = lo;
                    UINT_VIEW[0] = hi;
                    return DOUBLE_VIEW[0];
                  }, lowUintBE2 = function(n) {
                    DOUBLE_VIEW[0] = n;
                    return UINT_VIEW[1];
                  }, highUintBE2 = function(n) {
                    DOUBLE_VIEW[0] = n;
                    return UINT_VIEW[0];
                  };
                  var toDoubleBE = toDoubleBE2, lowUintBE = lowUintBE2, highUintBE = highUintBE2;
                  module2.exports = function doubleBitsBE(n) {
                    DOUBLE_VIEW[0] = n;
                    return [UINT_VIEW[1], UINT_VIEW[0]];
                  };
                  module2.exports.pack = toDoubleBE2;
                  module2.exports.lo = lowUintBE2;
                  module2.exports.hi = highUintBE2;
                } else {
                  hasTypedArrays = false;
                }
              }
              if (!hasTypedArrays) {
                let toDouble2 = function(lo, hi) {
                  buffer.writeUInt32LE(lo, 0, true);
                  buffer.writeUInt32LE(hi, 4, true);
                  return buffer.readDoubleLE(0, true);
                }, lowUint2 = function(n) {
                  buffer.writeDoubleLE(n, 0, true);
                  return buffer.readUInt32LE(0, true);
                }, highUint2 = function(n) {
                  buffer.writeDoubleLE(n, 0, true);
                  return buffer.readUInt32LE(4, true);
                };
                var toDouble = toDouble2, lowUint = lowUint2, highUint = highUint2;
                var buffer = new Buffer(8);
                module2.exports = function doubleBits(n) {
                  buffer.writeDoubleLE(n, 0, true);
                  return [buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true)];
                };
                module2.exports.pack = toDouble2;
                module2.exports.lo = lowUint2;
                module2.exports.hi = highUint2;
              }
              module2.exports.sign = function(n) {
                return module2.exports.hi(n) >>> 31;
              };
              module2.exports.exponent = function(n) {
                var b = module2.exports.hi(n);
                return (b << 1 >>> 21) - 1023;
              };
              module2.exports.fraction = function(n) {
                var lo = module2.exports.lo(n);
                var hi = module2.exports.hi(n);
                var b = hi & (1 << 20) - 1;
                if (hi & 2146435072) {
                  b += 1 << 20;
                }
                return [lo, b];
              };
              module2.exports.denormalized = function(n) {
                var hi = module2.exports.hi(n);
                return !(hi & 2146435072);
              };
            }
          ),
          /***/
          2408: (
            /***/
            function(module2) {
              module2.exports = rotateY;
              function rotateY(out, a, rad) {
                var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
                if (a !== out) {
                  out[4] = a[4];
                  out[5] = a[5];
                  out[6] = a[6];
                  out[7] = a[7];
                  out[12] = a[12];
                  out[13] = a[13];
                  out[14] = a[14];
                  out[15] = a[15];
                }
                out[0] = a00 * c - a20 * s;
                out[1] = a01 * c - a21 * s;
                out[2] = a02 * c - a22 * s;
                out[3] = a03 * c - a23 * s;
                out[8] = a00 * s + a20 * c;
                out[9] = a01 * s + a21 * c;
                out[10] = a02 * s + a22 * c;
                out[11] = a03 * s + a23 * c;
                return out;
              }
              ;
            }
          ),
          /***/
          2419: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = orientation;
              function orientation(s) {
                var p = 1;
                for (var i = 1; i < s.length; ++i) {
                  for (var j = 0; j < i; ++j) {
                    if (s[i] < s[j]) {
                      p = -p;
                    } else if (s[j] === s[i]) {
                      return 0;
                    }
                  }
                }
                return p;
              }
            }
          ),
          /***/
          2447: (
            /***/
            function(module2) {
              module2.exports = round;
              function round(out, a) {
                out[0] = Math.round(a[0]);
                out[1] = Math.round(a[1]);
                out[2] = Math.round(a[2]);
                return out;
              }
            }
          ),
          /***/
          2455: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              function full() {
                function bruteForceRedFull(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi) {
                  var es = 2 * d;
                  for (var i = rs, rp = es * rs; i < re; ++i, rp += es) {
                    var x0 = rb[ax + rp], x1 = rb[ax + rp + d], xi = ri[i];
                    Q: for (var j = bs, bp = es * bs; j < be; ++j, bp += es) {
                      var y0 = bb[ax + bp], y1 = bb[ax + bp + d], yi = bi[j];
                      if (y1 < x0 || x1 < y0) continue;
                      for (var k = ax + 1; k < d; ++k) {
                        var r0 = rb[k + rp], r1 = rb[k + d + rp], b0 = bb[k + bp], b1 = bb[k + d + bp];
                        if (r1 < b0 || b1 < r0) continue Q;
                      }
                      var rv = vv(xi, yi);
                      if (rv !== void 0) return rv;
                    }
                  }
                }
                function bruteForceBlueFull(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi) {
                  var es = 2 * d;
                  for (var j = bs, bp = es * bs; j < be; ++j, bp += es) {
                    var y0 = bb[ax + bp], y1 = bb[ax + bp + d], yi = bi[j];
                    Q: for (var i = rs, rp = es * rs; i < re; ++i, rp += es) {
                      var x0 = rb[ax + rp], x1 = rb[ax + rp + d], xi = ri[i];
                      if (y1 < x0 || x1 < y0) continue;
                      for (var k = ax + 1; k < d; ++k) {
                        var r0 = rb[k + rp], r1 = rb[k + d + rp], b0 = bb[k + bp], b1 = bb[k + d + bp];
                        if (r1 < b0 || b1 < r0) continue Q;
                      }
                      var rv = vv(xi, yi);
                      if (rv !== void 0) return rv;
                    }
                  }
                }
                function bruteForceFull(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi) {
                  if (re - rs > be - bs) {
                    return bruteForceRedFull(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi);
                  } else {
                    return bruteForceBlueFull(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi);
                  }
                }
                return bruteForceFull;
              }
              function partial() {
                function bruteForceRedFlip(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi) {
                  var es = 2 * d;
                  for (var i = rs, rp = es * rs; i < re; ++i, rp += es) {
                    var x0 = rb[ax + rp], x1 = rb[ax + rp + d], xi = ri[i];
                    Q: for (var j = bs, bp = es * bs; j < be; ++j, bp += es) {
                      var y0 = bb[ax + bp], yi = bi[j];
                      if (y0 <= x0 || x1 < y0) continue;
                      for (var k = ax + 1; k < d; ++k) {
                        var r0 = rb[k + rp], r1 = rb[k + d + rp], b0 = bb[k + bp], b1 = bb[k + d + bp];
                        if (r1 < b0 || b1 < r0) continue Q;
                      }
                      var rv = vv(yi, xi);
                      if (rv !== void 0) return rv;
                    }
                  }
                }
                function bruteForceRed(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi) {
                  var es = 2 * d;
                  for (var i = rs, rp = es * rs; i < re; ++i, rp += es) {
                    var x0 = rb[ax + rp], x1 = rb[ax + rp + d], xi = ri[i];
                    Q: for (var j = bs, bp = es * bs; j < be; ++j, bp += es) {
                      var y0 = bb[ax + bp], yi = bi[j];
                      if (y0 < x0 || x1 < y0) continue;
                      for (var k = ax + 1; k < d; ++k) {
                        var r0 = rb[k + rp], r1 = rb[k + d + rp], b0 = bb[k + bp], b1 = bb[k + d + bp];
                        if (r1 < b0 || b1 < r0) continue Q;
                      }
                      var rv = vv(xi, yi);
                      if (rv !== void 0) return rv;
                    }
                  }
                }
                function bruteForceBlueFlip(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi) {
                  var es = 2 * d;
                  for (var j = bs, bp = es * bs; j < be; ++j, bp += es) {
                    var y0 = bb[ax + bp], yi = bi[j];
                    Q: for (var i = rs, rp = es * rs; i < re; ++i, rp += es) {
                      var x0 = rb[ax + rp], x1 = rb[ax + rp + d], xi = ri[i];
                      if (y0 <= x0 || x1 < y0) continue;
                      for (var k = ax + 1; k < d; ++k) {
                        var r0 = rb[k + rp], r1 = rb[k + d + rp], b0 = bb[k + bp], b1 = bb[k + d + bp];
                        if (r1 < b0 || b1 < r0) continue Q;
                      }
                      var rv = vv(yi, xi);
                      if (rv !== void 0) return rv;
                    }
                  }
                }
                function bruteForceBlue(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi) {
                  var es = 2 * d;
                  for (var j = bs, bp = es * bs; j < be; ++j, bp += es) {
                    var y0 = bb[ax + bp], yi = bi[j];
                    Q: for (var i = rs, rp = es * rs; i < re; ++i, rp += es) {
                      var x0 = rb[ax + rp], x1 = rb[ax + rp + d], xi = ri[i];
                      if (y0 < x0 || x1 < y0) continue;
                      for (var k = ax + 1; k < d; ++k) {
                        var r0 = rb[k + rp], r1 = rb[k + d + rp], b0 = bb[k + bp], b1 = bb[k + d + bp];
                        if (r1 < b0 || b1 < r0) continue Q;
                      }
                      var rv = vv(xi, yi);
                      if (rv !== void 0) return rv;
                    }
                  }
                }
                function bruteForcePartial(d, ax, vv, fp, rs, re, rb, ri, bs, be, bb, bi) {
                  if (re - rs > be - bs) {
                    if (fp) {
                      return bruteForceRedFlip(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi);
                    } else {
                      return bruteForceRed(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi);
                    }
                  } else {
                    if (fp) {
                      return bruteForceBlueFlip(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi);
                    } else {
                      return bruteForceBlue(d, ax, vv, rs, re, rb, ri, bs, be, bb, bi);
                    }
                  }
                }
                return bruteForcePartial;
              }
              function bruteForcePlanner(isFull) {
                return isFull ? full() : partial();
              }
              exports2.partial = bruteForcePlanner(false);
              exports2.full = bruteForcePlanner(true);
            }
          ),
          /***/
          2478: (
            /***/
            function(module2) {
              "use strict";
              function ge(a, y, c, l, h) {
                var i = h + 1;
                while (l <= h) {
                  var m = l + h >>> 1, x = a[m];
                  var p = c !== void 0 ? c(x, y) : x - y;
                  if (p >= 0) {
                    i = m;
                    h = m - 1;
                  } else {
                    l = m + 1;
                  }
                }
                return i;
              }
              ;
              function gt(a, y, c, l, h) {
                var i = h + 1;
                while (l <= h) {
                  var m = l + h >>> 1, x = a[m];
                  var p = c !== void 0 ? c(x, y) : x - y;
                  if (p > 0) {
                    i = m;
                    h = m - 1;
                  } else {
                    l = m + 1;
                  }
                }
                return i;
              }
              ;
              function lt(a, y, c, l, h) {
                var i = l - 1;
                while (l <= h) {
                  var m = l + h >>> 1, x = a[m];
                  var p = c !== void 0 ? c(x, y) : x - y;
                  if (p < 0) {
                    i = m;
                    l = m + 1;
                  } else {
                    h = m - 1;
                  }
                }
                return i;
              }
              ;
              function le(a, y, c, l, h) {
                var i = l - 1;
                while (l <= h) {
                  var m = l + h >>> 1, x = a[m];
                  var p = c !== void 0 ? c(x, y) : x - y;
                  if (p <= 0) {
                    i = m;
                    l = m + 1;
                  } else {
                    h = m - 1;
                  }
                }
                return i;
              }
              ;
              function eq(a, y, c, l, h) {
                while (l <= h) {
                  var m = l + h >>> 1, x = a[m];
                  var p = c !== void 0 ? c(x, y) : x - y;
                  if (p === 0) {
                    return m;
                  }
                  if (p <= 0) {
                    l = m + 1;
                  } else {
                    h = m - 1;
                  }
                }
                return -1;
              }
              ;
              function norm(a, y, c, l, h, f) {
                if (typeof c === "function") {
                  return f(a, y, c, l === void 0 ? 0 : l | 0, h === void 0 ? a.length - 1 : h | 0);
                }
                return f(a, y, void 0, c === void 0 ? 0 : c | 0, l === void 0 ? a.length - 1 : l | 0);
              }
              module2.exports = {
                ge: function(a, y, c, l, h) {
                  return norm(a, y, c, l, h, ge);
                },
                gt: function(a, y, c, l, h) {
                  return norm(a, y, c, l, h, gt);
                },
                lt: function(a, y, c, l, h) {
                  return norm(a, y, c, l, h, lt);
                },
                le: function(a, y, c, l, h) {
                  return norm(a, y, c, l, h, le);
                },
                eq: function(a, y, c, l, h) {
                  return norm(a, y, c, l, h, eq);
                }
              };
            }
          ),
          /***/
          2504: (
            /***/
            function(module2) {
              module2.exports = scale;
              function scale(out, a, v) {
                var x = v[0], y = v[1], z = v[2];
                out[0] = a[0] * x;
                out[1] = a[1] * x;
                out[2] = a[2] * x;
                out[3] = a[3] * x;
                out[4] = a[4] * y;
                out[5] = a[5] * y;
                out[6] = a[6] * y;
                out[7] = a[7] * y;
                out[8] = a[8] * z;
                out[9] = a[9] * z;
                out[10] = a[10] * z;
                out[11] = a[11] * z;
                out[12] = a[12];
                out[13] = a[13];
                out[14] = a[14];
                out[15] = a[15];
                return out;
              }
              ;
            }
          ),
          /***/
          2538: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var monotoneTriangulate = __webpack_require__2(8902);
              var makeIndex = __webpack_require__2(5542);
              var delaunayFlip = __webpack_require__2(2272);
              var filterTriangulation = __webpack_require__2(5023);
              module2.exports = cdt2d;
              function canonicalizeEdge(e) {
                return [Math.min(e[0], e[1]), Math.max(e[0], e[1])];
              }
              function compareEdge(a, b) {
                return a[0] - b[0] || a[1] - b[1];
              }
              function canonicalizeEdges(edges) {
                return edges.map(canonicalizeEdge).sort(compareEdge);
              }
              function getDefault(options, property, dflt) {
                if (property in options) {
                  return options[property];
                }
                return dflt;
              }
              function cdt2d(points, edges, options) {
                if (!Array.isArray(edges)) {
                  options = edges || {};
                  edges = [];
                } else {
                  options = options || {};
                  edges = edges || [];
                }
                var delaunay = !!getDefault(options, "delaunay", true);
                var interior = !!getDefault(options, "interior", true);
                var exterior = !!getDefault(options, "exterior", true);
                var infinity = !!getDefault(options, "infinity", false);
                if (!interior && !exterior || points.length === 0) {
                  return [];
                }
                var cells = monotoneTriangulate(points, edges);
                if (delaunay || interior !== exterior || infinity) {
                  var triangulation = makeIndex(points.length, canonicalizeEdges(edges));
                  for (var i = 0; i < cells.length; ++i) {
                    var f = cells[i];
                    triangulation.addTriangle(f[0], f[1], f[2]);
                  }
                  if (delaunay) {
                    delaunayFlip(points, triangulation);
                  }
                  if (!exterior) {
                    return filterTriangulation(triangulation, -1);
                  } else if (!interior) {
                    return filterTriangulation(triangulation, 1, infinity);
                  } else if (infinity) {
                    return filterTriangulation(triangulation, 0, infinity);
                  } else {
                    return triangulation.cells();
                  }
                } else {
                  return cells;
                }
              }
            }
          ),
          /***/
          2573: (
            /***/
            function(module2) {
              module2.exports = lerp;
              function lerp(out, a, b, t) {
                var ax = a[0], ay = a[1], az = a[2], aw = a[3];
                out[0] = ax + t * (b[0] - ax);
                out[1] = ay + t * (b[1] - ay);
                out[2] = az + t * (b[2] - az);
                out[3] = aw + t * (b[3] - aw);
                return out;
              }
            }
          ),
          /***/
          2613: (
            /***/
            function(module2) {
              module2.exports = 1e-6;
            }
          ),
          /***/
          2640: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var pool = __webpack_require__2(1888);
              module2.exports = createSurfaceExtractor;
              var allFns = {
                "false,0,1": function surfaceProcedure(vertex, face, phase, mallocUint32, freeUint32) {
                  return function extractContour0_1(a0, x0, x1, x2) {
                    var s0 = a0.shape[0] | 0, s1 = a0.shape[1] | 0, d0 = a0.data, o0 = a0.offset | 0, t0_0 = a0.stride[0] | 0, t0_1 = a0.stride[1] | 0, p0 = o0, c0_0, d0_1 = -t0_0 | 0, c0_1 = 0, d0_2 = -t0_1 | 0, c0_2 = 0, d0_3 = -t0_0 - t0_1 | 0, c0_3 = 0, u0_0 = t0_0 | 0, u0_1 = t0_1 - t0_0 * s0 | 0, i0 = 0, i1 = 0, N = 0, Q = 2 * s0 | 0, P = mallocUint32(Q), V = mallocUint32(Q), X = 0, b0 = 0, e1 = -1 | 0, y1 = -1 | 0, b1 = 0, e2 = -s0 | 0, y2 = s0 | 0, b2 = 0, e3 = -s0 - 1 | 0, y3 = s0 - 1 | 0, b3 = 0, v0 = 0, T = 0;
                    for (i0 = 0; i0 < s0; ++i0) {
                      P[X++] = phase(d0[p0], x0, x1, x2);
                      p0 += u0_0;
                    }
                    p0 += u0_1;
                    if (s1 > 0) {
                      i1 = 1;
                      P[X++] = phase(d0[p0], x0, x1, x2);
                      p0 += u0_0;
                      if (s0 > 0) {
                        i0 = 1;
                        c0_0 = d0[p0];
                        b0 = P[X] = phase(c0_0, x0, x1, x2);
                        b1 = P[X + e1];
                        b2 = P[X + e2];
                        b3 = P[X + e3];
                        if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                          c0_1 = d0[p0 + d0_1];
                          c0_2 = d0[p0 + d0_2];
                          c0_3 = d0[p0 + d0_3];
                          vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                          v0 = V[X] = N++;
                        }
                        X += 1;
                        p0 += u0_0;
                        for (i0 = 2; i0 < s0; ++i0) {
                          c0_0 = d0[p0];
                          b0 = P[X] = phase(c0_0, x0, x1, x2);
                          b1 = P[X + e1];
                          b2 = P[X + e2];
                          b3 = P[X + e3];
                          if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                            c0_1 = d0[p0 + d0_1];
                            c0_2 = d0[p0 + d0_2];
                            c0_3 = d0[p0 + d0_3];
                            vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                            v0 = V[X] = N++;
                            if (b3 !== b1) {
                              face(V[X + e1], v0, c0_3, c0_1, b3, b1, x0, x1, x2);
                            }
                          }
                          X += 1;
                          p0 += u0_0;
                        }
                      }
                      p0 += u0_1;
                      X = 0;
                      T = e1;
                      e1 = y1;
                      y1 = T;
                      T = e2;
                      e2 = y2;
                      y2 = T;
                      T = e3;
                      e3 = y3;
                      y3 = T;
                      for (i1 = 2; i1 < s1; ++i1) {
                        P[X++] = phase(d0[p0], x0, x1, x2);
                        p0 += u0_0;
                        if (s0 > 0) {
                          i0 = 1;
                          c0_0 = d0[p0];
                          b0 = P[X] = phase(c0_0, x0, x1, x2);
                          b1 = P[X + e1];
                          b2 = P[X + e2];
                          b3 = P[X + e3];
                          if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                            c0_1 = d0[p0 + d0_1];
                            c0_2 = d0[p0 + d0_2];
                            c0_3 = d0[p0 + d0_3];
                            vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                            v0 = V[X] = N++;
                            if (b3 !== b2) {
                              face(V[X + e2], v0, c0_2, c0_3, b2, b3, x0, x1, x2);
                            }
                          }
                          X += 1;
                          p0 += u0_0;
                          for (i0 = 2; i0 < s0; ++i0) {
                            c0_0 = d0[p0];
                            b0 = P[X] = phase(c0_0, x0, x1, x2);
                            b1 = P[X + e1];
                            b2 = P[X + e2];
                            b3 = P[X + e3];
                            if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                              c0_1 = d0[p0 + d0_1];
                              c0_2 = d0[p0 + d0_2];
                              c0_3 = d0[p0 + d0_3];
                              vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                              v0 = V[X] = N++;
                              if (b3 !== b2) {
                                face(V[X + e2], v0, c0_2, c0_3, b2, b3, x0, x1, x2);
                              }
                              if (b3 !== b1) {
                                face(V[X + e1], v0, c0_3, c0_1, b3, b1, x0, x1, x2);
                              }
                            }
                            X += 1;
                            p0 += u0_0;
                          }
                        }
                        if (i1 & 1) {
                          X = 0;
                        }
                        T = e1;
                        e1 = y1;
                        y1 = T;
                        T = e2;
                        e2 = y2;
                        y2 = T;
                        T = e3;
                        e3 = y3;
                        y3 = T;
                        p0 += u0_1;
                      }
                    }
                    freeUint32(V);
                    freeUint32(P);
                  };
                },
                "false,1,0": function anonymous(vertex, face, phase, mallocUint32, freeUint32) {
                  return function extractContour1_0(a0, x0, x1, x2) {
                    var s0 = a0.shape[0] | 0, s1 = a0.shape[1] | 0, d0 = a0.data, o0 = a0.offset | 0, t0_0 = a0.stride[0] | 0, t0_1 = a0.stride[1] | 0, p0 = o0, c0_0, d0_1 = -t0_0 | 0, c0_1 = 0, d0_2 = -t0_1 | 0, c0_2 = 0, d0_3 = -t0_0 - t0_1 | 0, c0_3 = 0, u0_1 = t0_1 | 0, u0_0 = t0_0 - t0_1 * s1 | 0, i0 = 0, i1 = 0, N = 0, Q = 2 * s1 | 0, P = mallocUint32(Q), V = mallocUint32(Q), X = 0, b0 = 0, e2 = -1 | 0, y2 = -1 | 0, b2 = 0, e1 = -s1 | 0, y1 = s1 | 0, b1 = 0, e3 = -s1 - 1 | 0, y3 = s1 - 1 | 0, b3 = 0, v0 = 0, T = 0;
                    for (i1 = 0; i1 < s1; ++i1) {
                      P[X++] = phase(d0[p0], x0, x1, x2);
                      p0 += u0_1;
                    }
                    p0 += u0_0;
                    if (s0 > 0) {
                      i0 = 1;
                      P[X++] = phase(d0[p0], x0, x1, x2);
                      p0 += u0_1;
                      if (s1 > 0) {
                        i1 = 1;
                        c0_0 = d0[p0];
                        b0 = P[X] = phase(c0_0, x0, x1, x2);
                        b1 = P[X + e1];
                        b2 = P[X + e2];
                        b3 = P[X + e3];
                        if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                          c0_1 = d0[p0 + d0_1];
                          c0_2 = d0[p0 + d0_2];
                          c0_3 = d0[p0 + d0_3];
                          vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                          v0 = V[X] = N++;
                        }
                        X += 1;
                        p0 += u0_1;
                        for (i1 = 2; i1 < s1; ++i1) {
                          c0_0 = d0[p0];
                          b0 = P[X] = phase(c0_0, x0, x1, x2);
                          b1 = P[X + e1];
                          b2 = P[X + e2];
                          b3 = P[X + e3];
                          if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                            c0_1 = d0[p0 + d0_1];
                            c0_2 = d0[p0 + d0_2];
                            c0_3 = d0[p0 + d0_3];
                            vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                            v0 = V[X] = N++;
                            if (b3 !== b2) {
                              face(V[X + e2], v0, c0_2, c0_3, b2, b3, x0, x1, x2);
                            }
                          }
                          X += 1;
                          p0 += u0_1;
                        }
                      }
                      p0 += u0_0;
                      X = 0;
                      T = e1;
                      e1 = y1;
                      y1 = T;
                      T = e2;
                      e2 = y2;
                      y2 = T;
                      T = e3;
                      e3 = y3;
                      y3 = T;
                      for (i0 = 2; i0 < s0; ++i0) {
                        P[X++] = phase(d0[p0], x0, x1, x2);
                        p0 += u0_1;
                        if (s1 > 0) {
                          i1 = 1;
                          c0_0 = d0[p0];
                          b0 = P[X] = phase(c0_0, x0, x1, x2);
                          b1 = P[X + e1];
                          b2 = P[X + e2];
                          b3 = P[X + e3];
                          if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                            c0_1 = d0[p0 + d0_1];
                            c0_2 = d0[p0 + d0_2];
                            c0_3 = d0[p0 + d0_3];
                            vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                            v0 = V[X] = N++;
                            if (b3 !== b1) {
                              face(V[X + e1], v0, c0_3, c0_1, b3, b1, x0, x1, x2);
                            }
                          }
                          X += 1;
                          p0 += u0_1;
                          for (i1 = 2; i1 < s1; ++i1) {
                            c0_0 = d0[p0];
                            b0 = P[X] = phase(c0_0, x0, x1, x2);
                            b1 = P[X + e1];
                            b2 = P[X + e2];
                            b3 = P[X + e3];
                            if (b0 !== b1 || b0 !== b2 || b0 !== b3) {
                              c0_1 = d0[p0 + d0_1];
                              c0_2 = d0[p0 + d0_2];
                              c0_3 = d0[p0 + d0_3];
                              vertex(i0, i1, c0_0, c0_1, c0_2, c0_3, b0, b1, b2, b3, x0, x1, x2);
                              v0 = V[X] = N++;
                              if (b3 !== b2) {
                                face(V[X + e2], v0, c0_2, c0_3, b2, b3, x0, x1, x2);
                              }
                              if (b3 !== b1) {
                                face(V[X + e1], v0, c0_3, c0_1, b3, b1, x0, x1, x2);
                              }
                            }
                            X += 1;
                            p0 += u0_1;
                          }
                        }
                        if (i0 & 1) {
                          X = 0;
                        }
                        T = e1;
                        e1 = y1;
                        y1 = T;
                        T = e2;
                        e2 = y2;
                        y2 = T;
                        T = e3;
                        e3 = y3;
                        y3 = T;
                        p0 += u0_0;
                      }
                    }
                    freeUint32(V);
                    freeUint32(P);
                  };
                }
              };
              function compileSurfaceProcedure(vertexFunc, faceFunc, phaseFunc, scalarArgs, order, typesig) {
                var key = [typesig, order].join(",");
                var proc = allFns[key];
                return proc(
                  vertexFunc,
                  faceFunc,
                  phaseFunc,
                  pool.mallocUint32,
                  pool.freeUint32
                );
              }
              function createSurfaceExtractor(args) {
                function error(msg) {
                  throw new Error("ndarray-extract-contour: " + msg);
                }
                if (typeof args !== "object") {
                  error("Must specify arguments");
                }
                var order = args.order;
                if (!Array.isArray(order)) {
                  error("Must specify order");
                }
                var arrays = args.arrayArguments || 1;
                if (arrays < 1) {
                  error("Must have at least one array argument");
                }
                var scalars = args.scalarArguments || 0;
                if (scalars < 0) {
                  error("Scalar arg count must be > 0");
                }
                if (typeof args.vertex !== "function") {
                  error("Must specify vertex creation function");
                }
                if (typeof args.cell !== "function") {
                  error("Must specify cell creation function");
                }
                if (typeof args.phase !== "function") {
                  error("Must specify phase function");
                }
                var getters = args.getters || [];
                var typesig = new Array(arrays);
                for (var i = 0; i < arrays; ++i) {
                  if (getters.indexOf(i) >= 0) {
                    typesig[i] = true;
                  } else {
                    typesig[i] = false;
                  }
                }
                return compileSurfaceProcedure(
                  args.vertex,
                  args.cell,
                  args.phase,
                  scalars,
                  order,
                  typesig
                );
              }
            }
          ),
          /***/
          2642: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = barycentric;
              var solve = __webpack_require__2(727);
              function reduce(x) {
                var r = 0;
                for (var i = 0; i < x.length; ++i) {
                  r += x[i];
                }
                return r;
              }
              function barycentric(simplex, point) {
                var d = point.length;
                var A2 = new Array(d + 1);
                for (var i = 0; i < d; ++i) {
                  var row = new Array(d + 1);
                  for (var j = 0; j <= d; ++j) {
                    row[j] = simplex[j][i];
                  }
                  A2[i] = row;
                }
                A2[d] = new Array(d + 1);
                for (var i = 0; i <= d; ++i) {
                  A2[d][i] = 1;
                }
                var b = new Array(d + 1);
                for (var i = 0; i < d; ++i) {
                  b[i] = point[i];
                }
                b[d] = 1;
                var x = solve(A2, b);
                var w = reduce(x[d + 1]);
                if (w === 0) {
                  w = 1;
                }
                var y = new Array(d + 1);
                for (var i = 0; i <= d; ++i) {
                  y[i] = reduce(x[i]) / w;
                }
                return y;
              }
            }
          ),
          /***/
          2646: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var twoProduct = __webpack_require__2(5250);
              var robustSum = __webpack_require__2(8210);
              var robustDiff = __webpack_require__2(8545);
              var robustScale = __webpack_require__2(3012);
              var NUM_EXPAND = 6;
              function orientation(n) {
                var fn = n === 3 ? inSphere3 : n === 4 ? inSphere4 : n === 5 ? inSphere5 : inSphere6;
                return fn(robustSum, robustDiff, twoProduct, robustScale);
              }
              function inSphere0() {
                return 0;
              }
              function inSphere1() {
                return 0;
              }
              function inSphere2() {
                return 0;
              }
              function inSphere3(sum, diff, prod, scale) {
                function exactInSphere3(m0, m1, m2) {
                  var w0 = prod(m0[0], m0[0]);
                  var w0m1 = scale(w0, m1[0]);
                  var w0m2 = scale(w0, m2[0]);
                  var w1 = prod(m1[0], m1[0]);
                  var w1m0 = scale(w1, m0[0]);
                  var w1m2 = scale(w1, m2[0]);
                  var w2 = prod(m2[0], m2[0]);
                  var w2m0 = scale(w2, m0[0]);
                  var w2m1 = scale(w2, m1[0]);
                  var p = sum(diff(w2m1, w1m2), diff(w1m0, w0m1));
                  var n = diff(w2m0, w0m2);
                  var d = diff(p, n);
                  return d[d.length - 1];
                }
                return exactInSphere3;
              }
              function inSphere4(sum, diff, prod, scale) {
                function exactInSphere4(m0, m1, m2, m3) {
                  var w0 = sum(prod(m0[0], m0[0]), prod(m0[1], m0[1]));
                  var w0m1 = scale(w0, m1[0]);
                  var w0m2 = scale(w0, m2[0]);
                  var w0m3 = scale(w0, m3[0]);
                  var w1 = sum(prod(m1[0], m1[0]), prod(m1[1], m1[1]));
                  var w1m0 = scale(w1, m0[0]);
                  var w1m2 = scale(w1, m2[0]);
                  var w1m3 = scale(w1, m3[0]);
                  var w2 = sum(prod(m2[0], m2[0]), prod(m2[1], m2[1]));
                  var w2m0 = scale(w2, m0[0]);
                  var w2m1 = scale(w2, m1[0]);
                  var w2m3 = scale(w2, m3[0]);
                  var w3 = sum(prod(m3[0], m3[0]), prod(m3[1], m3[1]));
                  var w3m0 = scale(w3, m0[0]);
                  var w3m1 = scale(w3, m1[0]);
                  var w3m2 = scale(w3, m2[0]);
                  var p = sum(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))));
                  var n = sum(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))));
                  var d = diff(p, n);
                  return d[d.length - 1];
                }
                return exactInSphere4;
              }
              function inSphere5(sum, diff, prod, scale) {
                function exactInSphere5(m0, m1, m2, m3, m4) {
                  var w0 = sum(prod(m0[0], m0[0]), sum(prod(m0[1], m0[1]), prod(m0[2], m0[2])));
                  var w0m1 = scale(w0, m1[0]);
                  var w0m2 = scale(w0, m2[0]);
                  var w0m3 = scale(w0, m3[0]);
                  var w0m4 = scale(w0, m4[0]);
                  var w1 = sum(prod(m1[0], m1[0]), sum(prod(m1[1], m1[1]), prod(m1[2], m1[2])));
                  var w1m0 = scale(w1, m0[0]);
                  var w1m2 = scale(w1, m2[0]);
                  var w1m3 = scale(w1, m3[0]);
                  var w1m4 = scale(w1, m4[0]);
                  var w2 = sum(prod(m2[0], m2[0]), sum(prod(m2[1], m2[1]), prod(m2[2], m2[2])));
                  var w2m0 = scale(w2, m0[0]);
                  var w2m1 = scale(w2, m1[0]);
                  var w2m3 = scale(w2, m3[0]);
                  var w2m4 = scale(w2, m4[0]);
                  var w3 = sum(prod(m3[0], m3[0]), sum(prod(m3[1], m3[1]), prod(m3[2], m3[2])));
                  var w3m0 = scale(w3, m0[0]);
                  var w3m1 = scale(w3, m1[0]);
                  var w3m2 = scale(w3, m2[0]);
                  var w3m4 = scale(w3, m4[0]);
                  var w4 = sum(prod(m4[0], m4[0]), sum(prod(m4[1], m4[1]), prod(m4[2], m4[2])));
                  var w4m0 = scale(w4, m0[0]);
                  var w4m1 = scale(w4, m1[0]);
                  var w4m2 = scale(w4, m2[0]);
                  var w4m3 = scale(w4, m3[0]);
                  var p = sum(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), m1[2]), sum(scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), -m2[2]), scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), m3[2]))), sum(scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), -m4[2]), sum(scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), m0[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m1[2])))), sum(sum(scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), m3[2]), sum(scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), -m4[2]), scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), m0[2]))), sum(scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m1[2]), sum(scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m3[2])))));
                  var n = sum(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), m0[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m2[2])), sum(scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m4[2]))), sum(sum(scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), m0[2]), scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), -m1[2])), sum(scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m4[2]))));
                  var d = diff(p, n);
                  return d[d.length - 1];
                }
                return exactInSphere5;
              }
              function inSphere6(sum, diff, prod, scale) {
                function exactInSphere6(m0, m1, m2, m3, m4, m5) {
                  var w0 = sum(sum(prod(m0[0], m0[0]), prod(m0[1], m0[1])), sum(prod(m0[2], m0[2]), prod(m0[3], m0[3])));
                  var w0m1 = scale(w0, m1[0]);
                  var w0m2 = scale(w0, m2[0]);
                  var w0m3 = scale(w0, m3[0]);
                  var w0m4 = scale(w0, m4[0]);
                  var w0m5 = scale(w0, m5[0]);
                  var w1 = sum(sum(prod(m1[0], m1[0]), prod(m1[1], m1[1])), sum(prod(m1[2], m1[2]), prod(m1[3], m1[3])));
                  var w1m0 = scale(w1, m0[0]);
                  var w1m2 = scale(w1, m2[0]);
                  var w1m3 = scale(w1, m3[0]);
                  var w1m4 = scale(w1, m4[0]);
                  var w1m5 = scale(w1, m5[0]);
                  var w2 = sum(sum(prod(m2[0], m2[0]), prod(m2[1], m2[1])), sum(prod(m2[2], m2[2]), prod(m2[3], m2[3])));
                  var w2m0 = scale(w2, m0[0]);
                  var w2m1 = scale(w2, m1[0]);
                  var w2m3 = scale(w2, m3[0]);
                  var w2m4 = scale(w2, m4[0]);
                  var w2m5 = scale(w2, m5[0]);
                  var w3 = sum(sum(prod(m3[0], m3[0]), prod(m3[1], m3[1])), sum(prod(m3[2], m3[2]), prod(m3[3], m3[3])));
                  var w3m0 = scale(w3, m0[0]);
                  var w3m1 = scale(w3, m1[0]);
                  var w3m2 = scale(w3, m2[0]);
                  var w3m4 = scale(w3, m4[0]);
                  var w3m5 = scale(w3, m5[0]);
                  var w4 = sum(sum(prod(m4[0], m4[0]), prod(m4[1], m4[1])), sum(prod(m4[2], m4[2]), prod(m4[3], m4[3])));
                  var w4m0 = scale(w4, m0[0]);
                  var w4m1 = scale(w4, m1[0]);
                  var w4m2 = scale(w4, m2[0]);
                  var w4m3 = scale(w4, m3[0]);
                  var w4m5 = scale(w4, m5[0]);
                  var w5 = sum(sum(prod(m5[0], m5[0]), prod(m5[1], m5[1])), sum(prod(m5[2], m5[2]), prod(m5[3], m5[3])));
                  var w5m0 = scale(w5, m0[0]);
                  var w5m1 = scale(w5, m1[0]);
                  var w5m2 = scale(w5, m2[0]);
                  var w5m3 = scale(w5, m3[0]);
                  var w5m4 = scale(w5, m4[0]);
                  var p = sum(sum(sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m3[1]), sum(scale(diff(w5m3, w3m5), -m4[1]), scale(diff(w4m3, w3m4), m5[1]))), m2[2]), scale(sum(scale(diff(w5m4, w4m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m4[1]), scale(diff(w4m2, w2m4), m5[1]))), -m3[2])), sum(scale(sum(scale(diff(w5m3, w3m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m3[1]), scale(diff(w3m2, w2m3), m5[1]))), m4[2]), scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), -m5[2]))), m1[3]), sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m3[1]), sum(scale(diff(w5m3, w3m5), -m4[1]), scale(diff(w4m3, w3m4), m5[1]))), m1[2]), scale(sum(scale(diff(w5m4, w4m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m4[1]), scale(diff(w4m1, w1m4), m5[1]))), -m3[2])), sum(scale(sum(scale(diff(w5m3, w3m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m3[1]), scale(diff(w3m1, w1m3), m5[1]))), m4[2]), scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), -m5[2]))), -m2[3]), scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m4[1]), scale(diff(w4m2, w2m4), m5[1]))), m1[2]), scale(sum(scale(diff(w5m4, w4m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m4[1]), scale(diff(w4m1, w1m4), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m2[1]), scale(diff(w2m1, w1m2), m5[1]))), m4[2]), scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), -m5[2]))), m3[3]))), sum(sum(scale(sum(sum(scale(sum(scale(diff(w5m3, w3m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m3[1]), scale(diff(w3m2, w2m3), m5[1]))), m1[2]), scale(sum(scale(diff(w5m3, w3m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m3[1]), scale(diff(w3m1, w1m3), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m2[1]), scale(diff(w2m1, w1m2), m5[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), -m5[2]))), -m4[3]), scale(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), m1[2]), scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), -m2[2])), sum(scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), -m4[2]))), m5[3])), sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m3[1]), sum(scale(diff(w5m3, w3m5), -m4[1]), scale(diff(w4m3, w3m4), m5[1]))), m1[2]), scale(sum(scale(diff(w5m4, w4m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m4[1]), scale(diff(w4m1, w1m4), m5[1]))), -m3[2])), sum(scale(sum(scale(diff(w5m3, w3m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m3[1]), scale(diff(w3m1, w1m3), m5[1]))), m4[2]), scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), -m5[2]))), m0[3]), scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m3[1]), sum(scale(diff(w5m3, w3m5), -m4[1]), scale(diff(w4m3, w3m4), m5[1]))), m0[2]), scale(sum(scale(diff(w5m4, w4m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m4[1]), scale(diff(w4m0, w0m4), m5[1]))), -m3[2])), sum(scale(sum(scale(diff(w5m3, w3m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m3[1]), scale(diff(w3m0, w0m3), m5[1]))), m4[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m5[2]))), -m1[3])))), sum(sum(sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m4[1]), scale(diff(w4m1, w1m4), m5[1]))), m0[2]), scale(sum(scale(diff(w5m4, w4m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m4[1]), scale(diff(w4m0, w0m4), m5[1]))), -m1[2])), sum(scale(sum(scale(diff(w5m1, w1m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m1[1]), scale(diff(w1m0, w0m1), m5[1]))), m4[2]), scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), -m5[2]))), m3[3]), scale(sum(sum(scale(sum(scale(diff(w5m3, w3m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m3[1]), scale(diff(w3m1, w1m3), m5[1]))), m0[2]), scale(sum(scale(diff(w5m3, w3m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m3[1]), scale(diff(w3m0, w0m3), m5[1]))), -m1[2])), sum(scale(sum(scale(diff(w5m1, w1m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m1[1]), scale(diff(w1m0, w0m1), m5[1]))), m3[2]), scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), -m5[2]))), -m4[3])), sum(scale(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), m0[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m1[2])), sum(scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), m3[2]), scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), -m4[2]))), m5[3]), scale(sum(sum(scale(sum(scale(diff(w5m3, w3m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m3[1]), scale(diff(w3m2, w2m3), m5[1]))), m1[2]), scale(sum(scale(diff(w5m3, w3m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m3[1]), scale(diff(w3m1, w1m3), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m2[1]), scale(diff(w2m1, w1m2), m5[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), -m5[2]))), m0[3]))), sum(sum(scale(sum(sum(scale(sum(scale(diff(w5m3, w3m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m3[1]), scale(diff(w3m2, w2m3), m5[1]))), m0[2]), scale(sum(scale(diff(w5m3, w3m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m3[1]), scale(diff(w3m0, w0m3), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m2[1]), scale(diff(w2m0, w0m2), m5[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m5[2]))), -m1[3]), scale(sum(sum(scale(sum(scale(diff(w5m3, w3m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m3[1]), scale(diff(w3m1, w1m3), m5[1]))), m0[2]), scale(sum(scale(diff(w5m3, w3m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m3[1]), scale(diff(w3m0, w0m3), m5[1]))), -m1[2])), sum(scale(sum(scale(diff(w5m1, w1m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m1[1]), scale(diff(w1m0, w0m1), m5[1]))), m3[2]), scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), -m5[2]))), m2[3])), sum(scale(sum(sum(scale(sum(scale(diff(w5m2, w2m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m2[1]), scale(diff(w2m1, w1m2), m5[1]))), m0[2]), scale(sum(scale(diff(w5m2, w2m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m2[1]), scale(diff(w2m0, w0m2), m5[1]))), -m1[2])), sum(scale(sum(scale(diff(w5m1, w1m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m1[1]), scale(diff(w1m0, w0m1), m5[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m5[2]))), -m3[3]), scale(sum(sum(scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), m0[2]), scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m1[2])), sum(scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m3[2]))), m5[3])))));
                  var n = sum(sum(sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m3[1]), sum(scale(diff(w5m3, w3m5), -m4[1]), scale(diff(w4m3, w3m4), m5[1]))), m2[2]), scale(sum(scale(diff(w5m4, w4m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m4[1]), scale(diff(w4m2, w2m4), m5[1]))), -m3[2])), sum(scale(sum(scale(diff(w5m3, w3m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m3[1]), scale(diff(w3m2, w2m3), m5[1]))), m4[2]), scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), -m5[2]))), m0[3]), sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m3[1]), sum(scale(diff(w5m3, w3m5), -m4[1]), scale(diff(w4m3, w3m4), m5[1]))), m0[2]), scale(sum(scale(diff(w5m4, w4m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m4[1]), scale(diff(w4m0, w0m4), m5[1]))), -m3[2])), sum(scale(sum(scale(diff(w5m3, w3m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m3[1]), scale(diff(w3m0, w0m3), m5[1]))), m4[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m5[2]))), -m2[3]), scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m4[1]), scale(diff(w4m2, w2m4), m5[1]))), m0[2]), scale(sum(scale(diff(w5m4, w4m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m4[1]), scale(diff(w4m0, w0m4), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m2[1]), scale(diff(w2m0, w0m2), m5[1]))), m4[2]), scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), -m5[2]))), m3[3]))), sum(sum(scale(sum(sum(scale(sum(scale(diff(w5m3, w3m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m3[1]), scale(diff(w3m2, w2m3), m5[1]))), m0[2]), scale(sum(scale(diff(w5m3, w3m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m3[1]), scale(diff(w3m0, w0m3), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m2[1]), scale(diff(w2m0, w0m2), m5[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m5[2]))), -m4[3]), scale(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), m0[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m2[2])), sum(scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m4[2]))), m5[3])), sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m4[1]), scale(diff(w4m2, w2m4), m5[1]))), m1[2]), scale(sum(scale(diff(w5m4, w4m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m4[1]), scale(diff(w4m1, w1m4), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m2[1]), scale(diff(w2m1, w1m2), m5[1]))), m4[2]), scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), -m5[2]))), m0[3]), scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m2[1]), sum(scale(diff(w5m2, w2m5), -m4[1]), scale(diff(w4m2, w2m4), m5[1]))), m0[2]), scale(sum(scale(diff(w5m4, w4m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m4[1]), scale(diff(w4m0, w0m4), m5[1]))), -m2[2])), sum(scale(sum(scale(diff(w5m2, w2m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m2[1]), scale(diff(w2m0, w0m2), m5[1]))), m4[2]), scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), -m5[2]))), -m1[3])))), sum(sum(sum(scale(sum(sum(scale(sum(scale(diff(w5m4, w4m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m4[1]), scale(diff(w4m1, w1m4), m5[1]))), m0[2]), scale(sum(scale(diff(w5m4, w4m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m4[1]), scale(diff(w4m0, w0m4), m5[1]))), -m1[2])), sum(scale(sum(scale(diff(w5m1, w1m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m1[1]), scale(diff(w1m0, w0m1), m5[1]))), m4[2]), scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), -m5[2]))), m2[3]), scale(sum(sum(scale(sum(scale(diff(w5m2, w2m5), m1[1]), sum(scale(diff(w5m1, w1m5), -m2[1]), scale(diff(w2m1, w1m2), m5[1]))), m0[2]), scale(sum(scale(diff(w5m2, w2m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m2[1]), scale(diff(w2m0, w0m2), m5[1]))), -m1[2])), sum(scale(sum(scale(diff(w5m1, w1m5), m0[1]), sum(scale(diff(w5m0, w0m5), -m1[1]), scale(diff(w1m0, w0m1), m5[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m5[2]))), -m4[3])), sum(scale(sum(sum(scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), m0[2]), scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), -m1[2])), sum(scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m4[2]))), m5[3]), scale(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), m1[2]), scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), -m2[2])), sum(scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), -m4[2]))), m0[3]))), sum(sum(scale(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m2[1]), sum(scale(diff(w4m2, w2m4), -m3[1]), scale(diff(w3m2, w2m3), m4[1]))), m0[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m2[2])), sum(scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), m3[2]), scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m4[2]))), -m1[3]), scale(sum(sum(scale(sum(scale(diff(w4m3, w3m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m3[1]), scale(diff(w3m1, w1m3), m4[1]))), m0[2]), scale(sum(scale(diff(w4m3, w3m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m3[1]), scale(diff(w3m0, w0m3), m4[1]))), -m1[2])), sum(scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), m3[2]), scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), -m4[2]))), m2[3])), sum(scale(sum(sum(scale(sum(scale(diff(w4m2, w2m4), m1[1]), sum(scale(diff(w4m1, w1m4), -m2[1]), scale(diff(w2m1, w1m2), m4[1]))), m0[2]), scale(sum(scale(diff(w4m2, w2m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m2[1]), scale(diff(w2m0, w0m2), m4[1]))), -m1[2])), sum(scale(sum(scale(diff(w4m1, w1m4), m0[1]), sum(scale(diff(w4m0, w0m4), -m1[1]), scale(diff(w1m0, w0m1), m4[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m4[2]))), -m3[3]), scale(sum(sum(scale(sum(scale(diff(w3m2, w2m3), m1[1]), sum(scale(diff(w3m1, w1m3), -m2[1]), scale(diff(w2m1, w1m2), m3[1]))), m0[2]), scale(sum(scale(diff(w3m2, w2m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m2[1]), scale(diff(w2m0, w0m2), m3[1]))), -m1[2])), sum(scale(sum(scale(diff(w3m1, w1m3), m0[1]), sum(scale(diff(w3m0, w0m3), -m1[1]), scale(diff(w1m0, w0m1), m3[1]))), m2[2]), scale(sum(scale(diff(w2m1, w1m2), m0[1]), sum(scale(diff(w2m0, w0m2), -m1[1]), scale(diff(w1m0, w0m1), m2[1]))), -m3[2]))), m4[3])))));
                  var d = diff(p, n);
                  return d[d.length - 1];
                }
                return exactInSphere6;
              }
              var CACHED = [
                inSphere0,
                inSphere1,
                inSphere2
              ];
              function slowInSphere(args) {
                var proc2 = CACHED[args.length];
                if (!proc2) {
                  proc2 = CACHED[args.length] = orientation(args.length);
                }
                return proc2.apply(void 0, args);
              }
              function proc(slow, o0, o1, o2, o3, o4, o5, o6) {
                function testInSphere(a0, a1, a2, a3, a4, a5) {
                  switch (arguments.length) {
                    case 0:
                    case 1:
                      return 0;
                    case 2:
                      return o2(a0, a1);
                    case 3:
                      return o3(a0, a1, a2);
                    case 4:
                      return o4(a0, a1, a2, a3);
                    case 5:
                      return o5(a0, a1, a2, a3, a4);
                    case 6:
                      return o6(a0, a1, a2, a3, a4, a5);
                  }
                  var s = new Array(arguments.length);
                  for (var i = 0; i < arguments.length; ++i) {
                    s[i] = arguments[i];
                  }
                  return slow(s);
                }
                return testInSphere;
              }
              function generateInSphereTest() {
                while (CACHED.length <= NUM_EXPAND) {
                  CACHED.push(orientation(CACHED.length));
                }
                module2.exports = proc.apply(void 0, [slowInSphere].concat(CACHED));
                for (var i = 0; i <= NUM_EXPAND; ++i) {
                  module2.exports[i] = CACHED[i];
                }
              }
              generateInSphereTest();
            }
          ),
          /***/
          2651: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var BN = __webpack_require__2(6859);
              var db = __webpack_require__2(2361);
              module2.exports = num2bn;
              function num2bn(x) {
                var e = db.exponent(x);
                if (e < 52) {
                  return new BN(x);
                } else {
                  return new BN(x * Math.pow(2, 52 - e)).ushln(e - 52);
                }
              }
            }
          ),
          /***/
          2652: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var normalize = __webpack_require__2(4335);
              var create = __webpack_require__2(6864);
              var clone = __webpack_require__2(1903);
              var determinant = __webpack_require__2(9921);
              var invert = __webpack_require__2(7608);
              var transpose = __webpack_require__2(5665);
              var vec3 = {
                length: __webpack_require__2(1387),
                normalize: __webpack_require__2(3536),
                dot: __webpack_require__2(244),
                cross: __webpack_require__2(5911)
              };
              var tmp = create();
              var perspectiveMatrix = create();
              var tmpVec4 = [0, 0, 0, 0];
              var row = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
              var pdum3 = [0, 0, 0];
              module2.exports = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
                if (!translation) translation = [0, 0, 0];
                if (!scale) scale = [0, 0, 0];
                if (!skew) skew = [0, 0, 0];
                if (!perspective) perspective = [0, 0, 0, 1];
                if (!quaternion) quaternion = [0, 0, 0, 1];
                if (!normalize(tmp, matrix))
                  return false;
                clone(perspectiveMatrix, tmp);
                perspectiveMatrix[3] = 0;
                perspectiveMatrix[7] = 0;
                perspectiveMatrix[11] = 0;
                perspectiveMatrix[15] = 1;
                if (Math.abs(determinant(perspectiveMatrix) < 1e-8))
                  return false;
                var a03 = tmp[3], a13 = tmp[7], a23 = tmp[11], a30 = tmp[12], a31 = tmp[13], a32 = tmp[14], a33 = tmp[15];
                if (a03 !== 0 || a13 !== 0 || a23 !== 0) {
                  tmpVec4[0] = a03;
                  tmpVec4[1] = a13;
                  tmpVec4[2] = a23;
                  tmpVec4[3] = a33;
                  var ret = invert(perspectiveMatrix, perspectiveMatrix);
                  if (!ret) return false;
                  transpose(perspectiveMatrix, perspectiveMatrix);
                  vec4multMat4(perspective, tmpVec4, perspectiveMatrix);
                } else {
                  perspective[0] = perspective[1] = perspective[2] = 0;
                  perspective[3] = 1;
                }
                translation[0] = a30;
                translation[1] = a31;
                translation[2] = a32;
                mat3from4(row, tmp);
                scale[0] = vec3.length(row[0]);
                vec3.normalize(row[0], row[0]);
                skew[0] = vec3.dot(row[0], row[1]);
                combine(row[1], row[1], row[0], 1, -skew[0]);
                scale[1] = vec3.length(row[1]);
                vec3.normalize(row[1], row[1]);
                skew[0] /= scale[1];
                skew[1] = vec3.dot(row[0], row[2]);
                combine(row[2], row[2], row[0], 1, -skew[1]);
                skew[2] = vec3.dot(row[1], row[2]);
                combine(row[2], row[2], row[1], 1, -skew[2]);
                scale[2] = vec3.length(row[2]);
                vec3.normalize(row[2], row[2]);
                skew[1] /= scale[2];
                skew[2] /= scale[2];
                vec3.cross(pdum3, row[1], row[2]);
                if (vec3.dot(row[0], pdum3) < 0) {
                  for (var i = 0; i < 3; i++) {
                    scale[i] *= -1;
                    row[i][0] *= -1;
                    row[i][1] *= -1;
                    row[i][2] *= -1;
                  }
                }
                quaternion[0] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0));
                quaternion[1] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0));
                quaternion[2] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0));
                quaternion[3] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0));
                if (row[2][1] > row[1][2])
                  quaternion[0] = -quaternion[0];
                if (row[0][2] > row[2][0])
                  quaternion[1] = -quaternion[1];
                if (row[1][0] > row[0][1])
                  quaternion[2] = -quaternion[2];
                return true;
              };
              function vec4multMat4(out, a, m) {
                var x = a[0], y = a[1], z = a[2], w = a[3];
                out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
                out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
                out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
                out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
                return out;
              }
              function mat3from4(out, mat4x4) {
                out[0][0] = mat4x4[0];
                out[0][1] = mat4x4[1];
                out[0][2] = mat4x4[2];
                out[1][0] = mat4x4[4];
                out[1][1] = mat4x4[5];
                out[1][2] = mat4x4[6];
                out[2][0] = mat4x4[8];
                out[2][1] = mat4x4[9];
                out[2][2] = mat4x4[10];
              }
              function combine(out, a, b, scale1, scale2) {
                out[0] = a[0] * scale1 + b[0] * scale2;
                out[1] = a[1] * scale1 + b[1] * scale2;
                out[2] = a[2] * scale1 + b[2] * scale2;
              }
            }
          ),
          /***/
          2653: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bnadd = __webpack_require__2(3865);
              module2.exports = add;
              function add(a, b) {
                var n = a.length;
                var r = new Array(n);
                for (var i = 0; i < n; ++i) {
                  r[i] = bnadd(a[i], b[i]);
                }
                return r;
              }
            }
          ),
          /***/
          2681: (
            /***/
            function(module2) {
              module2.exports = floor;
              function floor(out, a) {
                out[0] = Math.floor(a[0]);
                out[1] = Math.floor(a[1]);
                out[2] = Math.floor(a[2]);
                return out;
              }
            }
          ),
          /***/
          2690: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = convexHullnD;
              var ich = __webpack_require__2(8954);
              var aff = __webpack_require__2(3952);
              function permute(points, front) {
                var n = points.length;
                var npoints = new Array(n);
                for (var i = 0; i < front.length; ++i) {
                  npoints[i] = points[front[i]];
                }
                var ptr = front.length;
                for (var i = 0; i < n; ++i) {
                  if (front.indexOf(i) < 0) {
                    npoints[ptr++] = points[i];
                  }
                }
                return npoints;
              }
              function invPermute(cells, front) {
                var nc = cells.length;
                var nf = front.length;
                for (var i = 0; i < nc; ++i) {
                  var c = cells[i];
                  for (var j = 0; j < c.length; ++j) {
                    var x = c[j];
                    if (x < nf) {
                      c[j] = front[x];
                    } else {
                      x = x - nf;
                      for (var k = 0; k < nf; ++k) {
                        if (x >= front[k]) {
                          x += 1;
                        }
                      }
                      c[j] = x;
                    }
                  }
                }
                return cells;
              }
              function convexHullnD(points, d) {
                try {
                  return ich(points, true);
                } catch (e) {
                  var ah = aff(points);
                  if (ah.length <= d) {
                    return [];
                  }
                  var npoints = permute(points, ah);
                  var nhull = ich(npoints, true);
                  return invPermute(nhull, ah);
                }
              }
            }
          ),
          /***/
          2762: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var pool = __webpack_require__2(1888);
              var ops = __webpack_require__2(5298);
              var ndarray = __webpack_require__2(9618);
              var SUPPORTED_TYPES = [
                "uint8",
                "uint8_clamped",
                "uint16",
                "uint32",
                "int8",
                "int16",
                "int32",
                "float32"
              ];
              function GLBuffer(gl2, type, handle, length, usage) {
                this.gl = gl2;
                this.type = type;
                this.handle = handle;
                this.length = length;
                this.usage = usage;
              }
              var proto = GLBuffer.prototype;
              proto.bind = function() {
                this.gl.bindBuffer(this.type, this.handle);
              };
              proto.unbind = function() {
                this.gl.bindBuffer(this.type, null);
              };
              proto.dispose = function() {
                this.gl.deleteBuffer(this.handle);
              };
              function updateTypeArray(gl2, type, len, usage, data, offset) {
                var dataLen = data.length * data.BYTES_PER_ELEMENT;
                if (offset < 0) {
                  gl2.bufferData(type, data, usage);
                  return dataLen;
                }
                if (dataLen + offset > len) {
                  throw new Error("gl-buffer: If resizing buffer, must not specify offset");
                }
                gl2.bufferSubData(type, offset, data);
                return len;
              }
              function makeScratchTypeArray(array, dtype) {
                var res = pool.malloc(array.length, dtype);
                var n = array.length;
                for (var i = 0; i < n; ++i) {
                  res[i] = array[i];
                }
                return res;
              }
              function isPacked(shape, stride) {
                var n = 1;
                for (var i = stride.length - 1; i >= 0; --i) {
                  if (stride[i] !== n) {
                    return false;
                  }
                  n *= shape[i];
                }
                return true;
              }
              proto.update = function(array, offset) {
                if (typeof offset !== "number") {
                  offset = -1;
                }
                this.bind();
                if (typeof array === "object" && typeof array.shape !== "undefined") {
                  var dtype = array.dtype;
                  if (SUPPORTED_TYPES.indexOf(dtype) < 0) {
                    dtype = "float32";
                  }
                  if (this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
                    var ext = gl.getExtension("OES_element_index_uint");
                    if (ext && dtype !== "uint16") {
                      dtype = "uint32";
                    } else {
                      dtype = "uint16";
                    }
                  }
                  if (dtype === array.dtype && isPacked(array.shape, array.stride)) {
                    if (array.offset === 0 && array.data.length === array.shape[0]) {
                      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset);
                    } else {
                      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset);
                    }
                  } else {
                    var tmp = pool.malloc(array.size, dtype);
                    var ndt = ndarray(tmp, array.shape);
                    ops.assign(ndt, array);
                    if (offset < 0) {
                      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset);
                    } else {
                      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset);
                    }
                    pool.free(tmp);
                  }
                } else if (Array.isArray(array)) {
                  var t;
                  if (this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
                    t = makeScratchTypeArray(array, "uint16");
                  } else {
                    t = makeScratchTypeArray(array, "float32");
                  }
                  if (offset < 0) {
                    this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset);
                  } else {
                    this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset);
                  }
                  pool.free(t);
                } else if (typeof array === "object" && typeof array.length === "number") {
                  this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset);
                } else if (typeof array === "number" || array === void 0) {
                  if (offset >= 0) {
                    throw new Error("gl-buffer: Cannot specify offset when resizing buffer");
                  }
                  array = array | 0;
                  if (array <= 0) {
                    array = 1;
                  }
                  this.gl.bufferData(this.type, array | 0, this.usage);
                  this.length = array;
                } else {
                  throw new Error("gl-buffer: Invalid data type");
                }
              };
              function createBuffer(gl2, data, type, usage) {
                type = type || gl2.ARRAY_BUFFER;
                usage = usage || gl2.DYNAMIC_DRAW;
                if (type !== gl2.ARRAY_BUFFER && type !== gl2.ELEMENT_ARRAY_BUFFER) {
                  throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");
                }
                if (usage !== gl2.DYNAMIC_DRAW && usage !== gl2.STATIC_DRAW && usage !== gl2.STREAM_DRAW) {
                  throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");
                }
                var handle = gl2.createBuffer();
                var result = new GLBuffer(gl2, type, handle, 0, usage);
                result.update(data);
                return result;
              }
              module2.exports = createBuffer;
            }
          ),
          /***/
          2825: (
            /***/
            function(module2) {
              module2.exports = fromValues;
              function fromValues(x, y, z) {
                var out = new Float32Array(3);
                out[0] = x;
                out[1] = y;
                out[2] = z;
                return out;
              }
            }
          ),
          /***/
          2931: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = {
                EPSILON: __webpack_require__2(2613),
                create: __webpack_require__2(1091),
                clone: __webpack_require__2(3126),
                angle: __webpack_require__2(8192),
                fromValues: __webpack_require__2(2825),
                copy: __webpack_require__2(3990),
                set: __webpack_require__2(1463),
                equals: __webpack_require__2(9922),
                exactEquals: __webpack_require__2(9265),
                add: __webpack_require__2(5632),
                subtract: __webpack_require__2(6843),
                sub: __webpack_require__2(2229),
                multiply: __webpack_require__2(5847),
                mul: __webpack_require__2(4505),
                divide: __webpack_require__2(6690),
                div: __webpack_require__2(4008),
                min: __webpack_require__2(8107),
                max: __webpack_require__2(7417),
                floor: __webpack_require__2(2681),
                ceil: __webpack_require__2(9226),
                round: __webpack_require__2(2447),
                scale: __webpack_require__2(6621),
                scaleAndAdd: __webpack_require__2(8489),
                distance: __webpack_require__2(7056),
                dist: __webpack_require__2(5455),
                squaredDistance: __webpack_require__2(2953),
                sqrDist: __webpack_require__2(6141),
                length: __webpack_require__2(1387),
                len: __webpack_require__2(868),
                squaredLength: __webpack_require__2(3066),
                sqrLen: __webpack_require__2(5486),
                negate: __webpack_require__2(5093),
                inverse: __webpack_require__2(811),
                normalize: __webpack_require__2(3536),
                dot: __webpack_require__2(244),
                cross: __webpack_require__2(5911),
                lerp: __webpack_require__2(6658),
                random: __webpack_require__2(7636),
                transformMat4: __webpack_require__2(5673),
                transformMat3: __webpack_require__2(492),
                transformQuat: __webpack_require__2(264),
                rotateX: __webpack_require__2(6894),
                rotateY: __webpack_require__2(109),
                rotateZ: __webpack_require__2(8692),
                forEach: __webpack_require__2(5137)
              };
            }
          ),
          /***/
          2933: (
            /***/
            function(module2) {
              module2.exports = copy;
              function copy(out, a) {
                out[0] = a[0];
                out[1] = a[1];
                out[2] = a[2];
                out[3] = a[3];
                return out;
              }
            }
          ),
          /***/
          2953: (
            /***/
            function(module2) {
              module2.exports = squaredDistance;
              function squaredDistance(a, b) {
                var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2];
                return x * x + y * y + z * z;
              }
            }
          ),
          /***/
          2962: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var twoProduct = __webpack_require__2(5250);
              var robustSum = __webpack_require__2(8210);
              var robustScale = __webpack_require__2(3012);
              var compress = __webpack_require__2(7004);
              var NUM_EXPANDED = 6;
              function determinant_2(sum, scale, prod, compress2) {
                return function robustDeterminant2(m) {
                  return compress2(sum(prod(m[0][0], m[1][1]), prod(-m[0][1], m[1][0])));
                };
              }
              function determinant_3(sum, scale, prod, compress2) {
                return function robustDeterminant3(m) {
                  return compress2(sum(scale(sum(prod(m[1][1], m[2][2]), prod(-m[1][2], m[2][1])), m[0][0]), sum(scale(sum(prod(m[1][0], m[2][2]), prod(-m[1][2], m[2][0])), -m[0][1]), scale(sum(prod(m[1][0], m[2][1]), prod(-m[1][1], m[2][0])), m[0][2]))));
                };
              }
              function determinant_4(sum, scale, prod, compress2) {
                return function robustDeterminant4(m) {
                  return compress2(sum(sum(scale(sum(scale(sum(prod(m[2][2], m[3][3]), prod(-m[2][3], m[3][2])), m[1][1]), sum(scale(sum(prod(m[2][1], m[3][3]), prod(-m[2][3], m[3][1])), -m[1][2]), scale(sum(prod(m[2][1], m[3][2]), prod(-m[2][2], m[3][1])), m[1][3]))), m[0][0]), scale(sum(scale(sum(prod(m[2][2], m[3][3]), prod(-m[2][3], m[3][2])), m[1][0]), sum(scale(sum(prod(m[2][0], m[3][3]), prod(-m[2][3], m[3][0])), -m[1][2]), scale(sum(prod(m[2][0], m[3][2]), prod(-m[2][2], m[3][0])), m[1][3]))), -m[0][1])), sum(scale(sum(scale(sum(prod(m[2][1], m[3][3]), prod(-m[2][3], m[3][1])), m[1][0]), sum(scale(sum(prod(m[2][0], m[3][3]), prod(-m[2][3], m[3][0])), -m[1][1]), scale(sum(prod(m[2][0], m[3][1]), prod(-m[2][1], m[3][0])), m[1][3]))), m[0][2]), scale(sum(scale(sum(prod(m[2][1], m[3][2]), prod(-m[2][2], m[3][1])), m[1][0]), sum(scale(sum(prod(m[2][0], m[3][2]), prod(-m[2][2], m[3][0])), -m[1][1]), scale(sum(prod(m[2][0], m[3][1]), prod(-m[2][1], m[3][0])), m[1][2]))), -m[0][3]))));
                };
              }
              function determinant_5(sum, scale, prod, compress2) {
                return function robustDeterminant5(m) {
                  return compress2(sum(sum(scale(sum(sum(scale(sum(scale(sum(prod(m[3][3], m[4][4]), prod(-m[3][4], m[4][3])), m[2][2]), sum(scale(sum(prod(m[3][2], m[4][4]), prod(-m[3][4], m[4][2])), -m[2][3]), scale(sum(prod(m[3][2], m[4][3]), prod(-m[3][3], m[4][2])), m[2][4]))), m[1][1]), scale(sum(scale(sum(prod(m[3][3], m[4][4]), prod(-m[3][4], m[4][3])), m[2][1]), sum(scale(sum(prod(m[3][1], m[4][4]), prod(-m[3][4], m[4][1])), -m[2][3]), scale(sum(prod(m[3][1], m[4][3]), prod(-m[3][3], m[4][1])), m[2][4]))), -m[1][2])), sum(scale(sum(scale(sum(prod(m[3][2], m[4][4]), prod(-m[3][4], m[4][2])), m[2][1]), sum(scale(sum(prod(m[3][1], m[4][4]), prod(-m[3][4], m[4][1])), -m[2][2]), scale(sum(prod(m[3][1], m[4][2]), prod(-m[3][2], m[4][1])), m[2][4]))), m[1][3]), scale(sum(scale(sum(prod(m[3][2], m[4][3]), prod(-m[3][3], m[4][2])), m[2][1]), sum(scale(sum(prod(m[3][1], m[4][3]), prod(-m[3][3], m[4][1])), -m[2][2]), scale(sum(prod(m[3][1], m[4][2]), prod(-m[3][2], m[4][1])), m[2][3]))), -m[1][4]))), m[0][0]), scale(sum(sum(scale(sum(scale(sum(prod(m[3][3], m[4][4]), prod(-m[3][4], m[4][3])), m[2][2]), sum(scale(sum(prod(m[3][2], m[4][4]), prod(-m[3][4], m[4][2])), -m[2][3]), scale(sum(prod(m[3][2], m[4][3]), prod(-m[3][3], m[4][2])), m[2][4]))), m[1][0]), scale(sum(scale(sum(prod(m[3][3], m[4][4]), prod(-m[3][4], m[4][3])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][4]), prod(-m[3][4], m[4][0])), -m[2][3]), scale(sum(prod(m[3][0], m[4][3]), prod(-m[3][3], m[4][0])), m[2][4]))), -m[1][2])), sum(scale(sum(scale(sum(prod(m[3][2], m[4][4]), prod(-m[3][4], m[4][2])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][4]), prod(-m[3][4], m[4][0])), -m[2][2]), scale(sum(prod(m[3][0], m[4][2]), prod(-m[3][2], m[4][0])), m[2][4]))), m[1][3]), scale(sum(scale(sum(prod(m[3][2], m[4][3]), prod(-m[3][3], m[4][2])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][3]), prod(-m[3][3], m[4][0])), -m[2][2]), scale(sum(prod(m[3][0], m[4][2]), prod(-m[3][2], m[4][0])), m[2][3]))), -m[1][4]))), -m[0][1])), sum(scale(sum(sum(scale(sum(scale(sum(prod(m[3][3], m[4][4]), prod(-m[3][4], m[4][3])), m[2][1]), sum(scale(sum(prod(m[3][1], m[4][4]), prod(-m[3][4], m[4][1])), -m[2][3]), scale(sum(prod(m[3][1], m[4][3]), prod(-m[3][3], m[4][1])), m[2][4]))), m[1][0]), scale(sum(scale(sum(prod(m[3][3], m[4][4]), prod(-m[3][4], m[4][3])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][4]), prod(-m[3][4], m[4][0])), -m[2][3]), scale(sum(prod(m[3][0], m[4][3]), prod(-m[3][3], m[4][0])), m[2][4]))), -m[1][1])), sum(scale(sum(scale(sum(prod(m[3][1], m[4][4]), prod(-m[3][4], m[4][1])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][4]), prod(-m[3][4], m[4][0])), -m[2][1]), scale(sum(prod(m[3][0], m[4][1]), prod(-m[3][1], m[4][0])), m[2][4]))), m[1][3]), scale(sum(scale(sum(prod(m[3][1], m[4][3]), prod(-m[3][3], m[4][1])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][3]), prod(-m[3][3], m[4][0])), -m[2][1]), scale(sum(prod(m[3][0], m[4][1]), prod(-m[3][1], m[4][0])), m[2][3]))), -m[1][4]))), m[0][2]), sum(scale(sum(sum(scale(sum(scale(sum(prod(m[3][2], m[4][4]), prod(-m[3][4], m[4][2])), m[2][1]), sum(scale(sum(prod(m[3][1], m[4][4]), prod(-m[3][4], m[4][1])), -m[2][2]), scale(sum(prod(m[3][1], m[4][2]), prod(-m[3][2], m[4][1])), m[2][4]))), m[1][0]), scale(sum(scale(sum(prod(m[3][2], m[4][4]), prod(-m[3][4], m[4][2])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][4]), prod(-m[3][4], m[4][0])), -m[2][2]), scale(sum(prod(m[3][0], m[4][2]), prod(-m[3][2], m[4][0])), m[2][4]))), -m[1][1])), sum(scale(sum(scale(sum(prod(m[3][1], m[4][4]), prod(-m[3][4], m[4][1])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][4]), prod(-m[3][4], m[4][0])), -m[2][1]), scale(sum(prod(m[3][0], m[4][1]), prod(-m[3][1], m[4][0])), m[2][4]))), m[1][2]), scale(sum(scale(sum(prod(m[3][1], m[4][2]), prod(-m[3][2], m[4][1])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][2]), prod(-m[3][2], m[4][0])), -m[2][1]), scale(sum(prod(m[3][0], m[4][1]), prod(-m[3][1], m[4][0])), m[2][2]))), -m[1][4]))), -m[0][3]), scale(sum(sum(scale(sum(scale(sum(prod(m[3][2], m[4][3]), prod(-m[3][3], m[4][2])), m[2][1]), sum(scale(sum(prod(m[3][1], m[4][3]), prod(-m[3][3], m[4][1])), -m[2][2]), scale(sum(prod(m[3][1], m[4][2]), prod(-m[3][2], m[4][1])), m[2][3]))), m[1][0]), scale(sum(scale(sum(prod(m[3][2], m[4][3]), prod(-m[3][3], m[4][2])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][3]), prod(-m[3][3], m[4][0])), -m[2][2]), scale(sum(prod(m[3][0], m[4][2]), prod(-m[3][2], m[4][0])), m[2][3]))), -m[1][1])), sum(scale(sum(scale(sum(prod(m[3][1], m[4][3]), prod(-m[3][3], m[4][1])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][3]), prod(-m[3][3], m[4][0])), -m[2][1]), scale(sum(prod(m[3][0], m[4][1]), prod(-m[3][1], m[4][0])), m[2][3]))), m[1][2]), scale(sum(scale(sum(prod(m[3][1], m[4][2]), prod(-m[3][2], m[4][1])), m[2][0]), sum(scale(sum(prod(m[3][0], m[4][2]), prod(-m[3][2], m[4][0])), -m[2][1]), scale(sum(prod(m[3][0], m[4][1]), prod(-m[3][1], m[4][0])), m[2][2]))), -m[1][3]))), m[0][4])))));
                };
              }
              function compileDeterminant(n) {
                var fn = n === 2 ? determinant_2 : n === 3 ? determinant_3 : n === 4 ? determinant_4 : n === 5 ? determinant_5 : void 0;
                return fn(robustSum, robustScale, twoProduct, compress);
              }
              var CACHE = [
                function robustDeterminant0() {
                  return [0];
                },
                function robustDeterminant1(m) {
                  return [m[0][0]];
                }
              ];
              function proc(det0, det1, det2, det3, det4, det5, CACHE2, gen) {
                return function robustDeterminant(m) {
                  switch (m.length) {
                    case 0:
                      return det0(m);
                    case 1:
                      return det1(m);
                    case 2:
                      return det2(m);
                    case 3:
                      return det3(m);
                    case 4:
                      return det4(m);
                    case 5:
                      return det5(m);
                  }
                  var det = CACHE2[m.length];
                  if (!det) det = CACHE2[m.length] = gen(m.length);
                  return det(m);
                };
              }
              function generateDispatch() {
                while (CACHE.length < NUM_EXPANDED) {
                  CACHE.push(compileDeterminant(CACHE.length));
                }
                module2.exports = proc.apply(void 0, CACHE.concat([CACHE, compileDeterminant]));
                for (var i = 0; i < CACHE.length; ++i) {
                  module2.exports[i] = CACHE[i];
                }
              }
              generateDispatch();
            }
          ),
          /***/
          2992: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var sprintf = __webpack_require__2(3387).sprintf;
              var glConstants = __webpack_require__2(5171);
              var shaderName = __webpack_require__2(1848);
              var addLineNumbers = __webpack_require__2(1085);
              module2.exports = formatCompilerError;
              function formatCompilerError(errLog, src, type) {
                "use strict";
                var name2 = shaderName(src) || "of unknown name (see npm glsl-shader-name)";
                var typeName = "unknown type";
                if (type !== void 0) {
                  typeName = type === glConstants.FRAGMENT_SHADER ? "fragment" : "vertex";
                }
                var longForm = sprintf("Error compiling %s shader %s:\n", typeName, name2);
                var shortForm = sprintf("%s%s", longForm, errLog);
                var errorStrings = errLog.split("\n");
                var errors = {};
                for (var i = 0; i < errorStrings.length; i++) {
                  var errorString = errorStrings[i];
                  if (errorString === "" || errorString === "\0") continue;
                  var lineNo = parseInt(errorString.split(":")[2]);
                  if (isNaN(lineNo)) {
                    throw new Error(sprintf("Could not parse error: %s", errorString));
                  }
                  errors[lineNo] = errorString;
                }
                var lines = addLineNumbers(src).split("\n");
                for (var i = 0; i < lines.length; i++) {
                  if (!errors[i + 3] && !errors[i + 2] && !errors[i + 1]) continue;
                  var line = lines[i];
                  longForm += line + "\n";
                  if (errors[i + 1]) {
                    var e = errors[i + 1];
                    e = e.substr(e.split(":", 3).join(":").length + 1).trim();
                    longForm += sprintf("^^^ %s\n\n", e);
                  }
                }
                return {
                  long: longForm.trim(),
                  short: shortForm.trim()
                };
              }
            }
          ),
          /***/
          3012: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var twoProduct = __webpack_require__2(5250);
              var twoSum = __webpack_require__2(9362);
              module2.exports = scaleLinearExpansion;
              function scaleLinearExpansion(e, scale) {
                var n = e.length;
                if (n === 1) {
                  var ts = twoProduct(e[0], scale);
                  if (ts[0]) {
                    return ts;
                  }
                  return [ts[1]];
                }
                var g = new Array(2 * n);
                var q = [0.1, 0.1];
                var t = [0.1, 0.1];
                var count = 0;
                twoProduct(e[0], scale, q);
                if (q[0]) {
                  g[count++] = q[0];
                }
                for (var i = 1; i < n; ++i) {
                  twoProduct(e[i], scale, t);
                  var pq = q[1];
                  twoSum(pq, t[0], q);
                  if (q[0]) {
                    g[count++] = q[0];
                  }
                  var a = t[1];
                  var b = q[1];
                  var x = a + b;
                  var bv = x - a;
                  var y = b - bv;
                  q[1] = x;
                  if (y) {
                    g[count++] = y;
                  }
                }
                if (q[1]) {
                  g[count++] = q[1];
                }
                if (count === 0) {
                  g[count++] = 0;
                }
                g.length = count;
                return g;
              }
            }
          ),
          /***/
          3025: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2.g.performance && __webpack_require__2.g.performance.now ? function now() {
                return performance.now();
              } : Date.now || function now() {
                return +/* @__PURE__ */ new Date();
              };
            }
          ),
          /***/
          3066: (
            /***/
            function(module2) {
              module2.exports = squaredLength;
              function squaredLength(a) {
                var x = a[0], y = a[1], z = a[2];
                return x * x + y * y + z * z;
              }
            }
          ),
          /***/
          3088: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = planarDual;
              var compareAngle = __webpack_require__2(3140);
              function planarDual(cells, positions) {
                var numVertices = positions.length | 0;
                var numEdges = cells.length;
                var adj = [new Array(numVertices), new Array(numVertices)];
                for (var i = 0; i < numVertices; ++i) {
                  adj[0][i] = [];
                  adj[1][i] = [];
                }
                for (var i = 0; i < numEdges; ++i) {
                  var c = cells[i];
                  adj[0][c[0]].push(c);
                  adj[1][c[1]].push(c);
                }
                var cycles = [];
                for (var i = 0; i < numVertices; ++i) {
                  if (adj[0][i].length + adj[1][i].length === 0) {
                    cycles.push([i]);
                  }
                }
                function cut(c2, i2) {
                  var a = adj[i2][c2[i2]];
                  a.splice(a.indexOf(c2), 1);
                }
                function next(a, b, noCut) {
                  var nextCell, nextVertex, nextDir;
                  for (var i2 = 0; i2 < 2; ++i2) {
                    if (adj[i2][b].length > 0) {
                      nextCell = adj[i2][b][0];
                      nextDir = i2;
                      break;
                    }
                  }
                  nextVertex = nextCell[nextDir ^ 1];
                  for (var dir = 0; dir < 2; ++dir) {
                    var nbhd = adj[dir][b];
                    for (var k = 0; k < nbhd.length; ++k) {
                      var e = nbhd[k];
                      var p = e[dir ^ 1];
                      var cmp = compareAngle(
                        positions[a],
                        positions[b],
                        positions[nextVertex],
                        positions[p]
                      );
                      if (cmp > 0) {
                        nextCell = e;
                        nextVertex = p;
                        nextDir = dir;
                      }
                    }
                  }
                  if (noCut) {
                    return nextVertex;
                  }
                  if (nextCell) {
                    cut(nextCell, nextDir);
                  }
                  return nextVertex;
                }
                function extractCycle(v, dir) {
                  var e0 = adj[dir][v][0];
                  var cycle = [v];
                  cut(e0, dir);
                  var u = e0[dir ^ 1];
                  var d0 = dir;
                  while (true) {
                    while (u !== v) {
                      cycle.push(u);
                      u = next(cycle[cycle.length - 2], u, false);
                    }
                    if (adj[0][v].length + adj[1][v].length === 0) {
                      break;
                    }
                    var a = cycle[cycle.length - 1];
                    var b = v;
                    var c2 = cycle[1];
                    var d = next(a, b, true);
                    if (compareAngle(positions[a], positions[b], positions[c2], positions[d]) < 0) {
                      break;
                    }
                    cycle.push(v);
                    u = next(a, b);
                  }
                  return cycle;
                }
                function shouldGlue(pcycle2, ncycle2) {
                  return ncycle2[1] === ncycle2[ncycle2.length - 1];
                }
                for (var i = 0; i < numVertices; ++i) {
                  for (var j = 0; j < 2; ++j) {
                    var pcycle = [];
                    while (adj[j][i].length > 0) {
                      var ni = adj[0][i].length;
                      var ncycle = extractCycle(i, j);
                      if (shouldGlue(pcycle, ncycle)) {
                        pcycle.push.apply(pcycle, ncycle);
                      } else {
                        if (pcycle.length > 0) {
                          cycles.push(pcycle);
                        }
                        pcycle = ncycle;
                      }
                    }
                    if (pcycle.length > 0) {
                      cycles.push(pcycle);
                    }
                  }
                }
                return cycles;
              }
            }
          ),
          /***/
          3090: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = monotoneConvexHull2D;
              var orient = __webpack_require__2(3250)[3];
              function monotoneConvexHull2D(points) {
                var n = points.length;
                if (n < 3) {
                  var result = new Array(n);
                  for (var i = 0; i < n; ++i) {
                    result[i] = i;
                  }
                  if (n === 2 && points[0][0] === points[1][0] && points[0][1] === points[1][1]) {
                    return [0];
                  }
                  return result;
                }
                var sorted = new Array(n);
                for (var i = 0; i < n; ++i) {
                  sorted[i] = i;
                }
                sorted.sort(function(a, b) {
                  var d = points[a][0] - points[b][0];
                  if (d) {
                    return d;
                  }
                  return points[a][1] - points[b][1];
                });
                var lower = [sorted[0], sorted[1]];
                var upper = [sorted[0], sorted[1]];
                for (var i = 2; i < n; ++i) {
                  var idx = sorted[i];
                  var p = points[idx];
                  var m = lower.length;
                  while (m > 1 && orient(
                    points[lower[m - 2]],
                    points[lower[m - 1]],
                    p
                  ) <= 0) {
                    m -= 1;
                    lower.pop();
                  }
                  lower.push(idx);
                  m = upper.length;
                  while (m > 1 && orient(
                    points[upper[m - 2]],
                    points[upper[m - 1]],
                    p
                  ) >= 0) {
                    m -= 1;
                    upper.pop();
                  }
                  upper.push(idx);
                }
                var result = new Array(upper.length + lower.length - 2);
                var ptr = 0;
                for (var i = 0, nl = lower.length; i < nl; ++i) {
                  result[ptr++] = lower[i];
                }
                for (var j = upper.length - 2; j > 0; --j) {
                  result[ptr++] = upper[j];
                }
                return result;
              }
            }
          ),
          /***/
          3105: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              "use restrict";
              var INT_BITS = 32;
              exports2.INT_BITS = INT_BITS;
              exports2.INT_MAX = 2147483647;
              exports2.INT_MIN = -1 << INT_BITS - 1;
              exports2.sign = function(v) {
                return (v > 0) - (v < 0);
              };
              exports2.abs = function(v) {
                var mask = v >> INT_BITS - 1;
                return (v ^ mask) - mask;
              };
              exports2.min = function(x, y) {
                return y ^ (x ^ y) & -(x < y);
              };
              exports2.max = function(x, y) {
                return x ^ (x ^ y) & -(x < y);
              };
              exports2.isPow2 = function(v) {
                return !(v & v - 1) && !!v;
              };
              exports2.log2 = function(v) {
                var r, shift;
                r = (v > 65535) << 4;
                v >>>= r;
                shift = (v > 255) << 3;
                v >>>= shift;
                r |= shift;
                shift = (v > 15) << 2;
                v >>>= shift;
                r |= shift;
                shift = (v > 3) << 1;
                v >>>= shift;
                r |= shift;
                return r | v >> 1;
              };
              exports2.log10 = function(v) {
                return v >= 1e9 ? 9 : v >= 1e8 ? 8 : v >= 1e7 ? 7 : v >= 1e6 ? 6 : v >= 1e5 ? 5 : v >= 1e4 ? 4 : v >= 1e3 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0;
              };
              exports2.popCount = function(v) {
                v = v - (v >>> 1 & 1431655765);
                v = (v & 858993459) + (v >>> 2 & 858993459);
                return (v + (v >>> 4) & 252645135) * 16843009 >>> 24;
              };
              function countTrailingZeros(v) {
                var c = 32;
                v &= -v;
                if (v) c--;
                if (v & 65535) c -= 16;
                if (v & 16711935) c -= 8;
                if (v & 252645135) c -= 4;
                if (v & 858993459) c -= 2;
                if (v & 1431655765) c -= 1;
                return c;
              }
              exports2.countTrailingZeros = countTrailingZeros;
              exports2.nextPow2 = function(v) {
                v += v === 0;
                --v;
                v |= v >>> 1;
                v |= v >>> 2;
                v |= v >>> 4;
                v |= v >>> 8;
                v |= v >>> 16;
                return v + 1;
              };
              exports2.prevPow2 = function(v) {
                v |= v >>> 1;
                v |= v >>> 2;
                v |= v >>> 4;
                v |= v >>> 8;
                v |= v >>> 16;
                return v - (v >>> 1);
              };
              exports2.parity = function(v) {
                v ^= v >>> 16;
                v ^= v >>> 8;
                v ^= v >>> 4;
                v &= 15;
                return 27030 >>> v & 1;
              };
              var REVERSE_TABLE = new Array(256);
              (function(tab) {
                for (var i = 0; i < 256; ++i) {
                  var v = i, r = i, s = 7;
                  for (v >>>= 1; v; v >>>= 1) {
                    r <<= 1;
                    r |= v & 1;
                    --s;
                  }
                  tab[i] = r << s & 255;
                }
              })(REVERSE_TABLE);
              exports2.reverse = function(v) {
                return REVERSE_TABLE[v & 255] << 24 | REVERSE_TABLE[v >>> 8 & 255] << 16 | REVERSE_TABLE[v >>> 16 & 255] << 8 | REVERSE_TABLE[v >>> 24 & 255];
              };
              exports2.interleave2 = function(x, y) {
                x &= 65535;
                x = (x | x << 8) & 16711935;
                x = (x | x << 4) & 252645135;
                x = (x | x << 2) & 858993459;
                x = (x | x << 1) & 1431655765;
                y &= 65535;
                y = (y | y << 8) & 16711935;
                y = (y | y << 4) & 252645135;
                y = (y | y << 2) & 858993459;
                y = (y | y << 1) & 1431655765;
                return x | y << 1;
              };
              exports2.deinterleave2 = function(v, n) {
                v = v >>> n & 1431655765;
                v = (v | v >>> 1) & 858993459;
                v = (v | v >>> 2) & 252645135;
                v = (v | v >>> 4) & 16711935;
                v = (v | v >>> 16) & 65535;
                return v << 16 >> 16;
              };
              exports2.interleave3 = function(x, y, z) {
                x &= 1023;
                x = (x | x << 16) & 4278190335;
                x = (x | x << 8) & 251719695;
                x = (x | x << 4) & 3272356035;
                x = (x | x << 2) & 1227133513;
                y &= 1023;
                y = (y | y << 16) & 4278190335;
                y = (y | y << 8) & 251719695;
                y = (y | y << 4) & 3272356035;
                y = (y | y << 2) & 1227133513;
                x |= y << 1;
                z &= 1023;
                z = (z | z << 16) & 4278190335;
                z = (z | z << 8) & 251719695;
                z = (z | z << 4) & 3272356035;
                z = (z | z << 2) & 1227133513;
                return x | z << 2;
              };
              exports2.deinterleave3 = function(v, n) {
                v = v >>> n & 1227133513;
                v = (v | v >>> 2) & 3272356035;
                v = (v | v >>> 4) & 251719695;
                v = (v | v >>> 8) & 4278190335;
                v = (v | v >>> 16) & 1023;
                return v << 22 >> 22;
              };
              exports2.nextCombination = function(v) {
                var t = v | v - 1;
                return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1;
              };
            }
          ),
          /***/
          3126: (
            /***/
            function(module2) {
              module2.exports = clone;
              function clone(a) {
                var out = new Float32Array(3);
                out[0] = a[0];
                out[1] = a[1];
                out[2] = a[2];
                return out;
              }
            }
          ),
          /***/
          3134: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = edgeToAdjacency;
              var uniq = __webpack_require__2(1682);
              function edgeToAdjacency(edges, numVertices) {
                var numEdges = edges.length;
                if (typeof numVertices !== "number") {
                  numVertices = 0;
                  for (var i = 0; i < numEdges; ++i) {
                    var e = edges[i];
                    numVertices = Math.max(numVertices, e[0], e[1]);
                  }
                  numVertices = (numVertices | 0) + 1;
                }
                numVertices = numVertices | 0;
                var adj = new Array(numVertices);
                for (var i = 0; i < numVertices; ++i) {
                  adj[i] = [];
                }
                for (var i = 0; i < numEdges; ++i) {
                  var e = edges[i];
                  adj[e[0]].push(e[1]);
                  adj[e[1]].push(e[0]);
                }
                for (var j = 0; j < numVertices; ++j) {
                  uniq(adj[j], function(a, b) {
                    return a - b;
                  });
                }
                return adj;
              }
            }
          ),
          /***/
          3140: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = compareAngle;
              var orient = __webpack_require__2(3250);
              var sgn = __webpack_require__2(8572);
              var twoSum = __webpack_require__2(9362);
              var robustProduct = __webpack_require__2(5382);
              var robustSum = __webpack_require__2(8210);
              function testInterior(a, b, c) {
                var x0 = twoSum(a[0], -b[0]);
                var y0 = twoSum(a[1], -b[1]);
                var x1 = twoSum(c[0], -b[0]);
                var y1 = twoSum(c[1], -b[1]);
                var d = robustSum(
                  robustProduct(x0, x1),
                  robustProduct(y0, y1)
                );
                return d[d.length - 1] >= 0;
              }
              function compareAngle(a, b, c, d) {
                var bcd = orient(b, c, d);
                if (bcd === 0) {
                  var sabc = sgn(orient(a, b, c));
                  var sabd = sgn(orient(a, b, d));
                  if (sabc === sabd) {
                    if (sabc === 0) {
                      var ic = testInterior(a, b, c);
                      var id = testInterior(a, b, d);
                      if (ic === id) {
                        return 0;
                      } else if (ic) {
                        return 1;
                      } else {
                        return -1;
                      }
                    }
                    return 0;
                  } else if (sabd === 0) {
                    if (sabc > 0) {
                      return -1;
                    } else if (testInterior(a, b, d)) {
                      return -1;
                    } else {
                      return 1;
                    }
                  } else if (sabc === 0) {
                    if (sabd > 0) {
                      return 1;
                    } else if (testInterior(a, b, c)) {
                      return 1;
                    } else {
                      return -1;
                    }
                  }
                  return sgn(sabd - sabc);
                }
                var abc = orient(a, b, c);
                if (abc > 0) {
                  if (bcd > 0 && orient(a, b, d) > 0) {
                    return 1;
                  }
                  return -1;
                } else if (abc < 0) {
                  if (bcd > 0 || orient(a, b, d) > 0) {
                    return 1;
                  }
                  return -1;
                } else {
                  var abd = orient(a, b, d);
                  if (abd > 0) {
                    return 1;
                  } else {
                    if (testInterior(a, b, c)) {
                      return 1;
                    } else {
                      return -1;
                    }
                  }
                }
              }
            }
          ),
          /***/
          3202: (
            /***/
            function(module2) {
              module2.exports = function parseUnit(str, out) {
                if (!out)
                  out = [0, ""];
                str = String(str);
                var num = parseFloat(str, 10);
                out[0] = num;
                out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || "";
                return out;
              };
            }
          ),
          /***/
          3233: (
            /***/
            function(module2) {
              "use strict";
              var res = "";
              var cache;
              module2.exports = repeat;
              function repeat(str, num) {
                if (typeof str !== "string") {
                  throw new TypeError("expected a string");
                }
                if (num === 1) return str;
                if (num === 2) return str + str;
                var max = str.length * num;
                if (cache !== str || typeof cache === "undefined") {
                  cache = str;
                  res = "";
                } else if (res.length >= max) {
                  return res.substr(0, max);
                }
                while (max > res.length && num > 1) {
                  if (num & 1) {
                    res += str;
                  }
                  num >>= 1;
                  str += str;
                }
                res += str;
                res = res.substr(0, max);
                return res;
              }
            }
          ),
          /***/
          3236: (
            /***/
            function(module2) {
              module2.exports = function(strings) {
                if (typeof strings === "string") strings = [strings];
                var exprs = [].slice.call(arguments, 1);
                var parts = [];
                for (var i = 0; i < strings.length - 1; i++) {
                  parts.push(strings[i], exprs[i] || "");
                }
                parts.push(strings[i]);
                return parts.join("");
              };
            }
          ),
          /***/
          3250: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var twoProduct = __webpack_require__2(5250);
              var robustSum = __webpack_require__2(8210);
              var robustScale = __webpack_require__2(3012);
              var robustSubtract = __webpack_require__2(8545);
              var NUM_EXPAND = 5;
              var EPSILON = 11102230246251565e-32;
              var ERRBOUND3 = (3 + 16 * EPSILON) * EPSILON;
              var ERRBOUND4 = (7 + 56 * EPSILON) * EPSILON;
              function orientation_3(sum, prod, scale, sub) {
                return function orientation3Exact2(m0, m1, m2) {
                  var p = sum(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])));
                  var n = sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0]));
                  var d = sub(p, n);
                  return d[d.length - 1];
                };
              }
              function orientation_4(sum, prod, scale, sub) {
                return function orientation4Exact2(m0, m1, m2, m3) {
                  var p = sum(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))));
                  var n = sum(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))));
                  var d = sub(p, n);
                  return d[d.length - 1];
                };
              }
              function orientation_5(sum, prod, scale, sub) {
                return function orientation5Exact(m0, m1, m2, m3, m4) {
                  var p = sum(sum(sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m2[2]), sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), -m3[2]), scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m4[2]))), m1[3]), sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m3[2]), scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m4[2]))), -m2[3]), scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m4[2]))), m3[3]))), sum(scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), -m4[3]), sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m3[2]), scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m3[2]), scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), m4[2]))), -m1[3])))), sum(sum(scale(sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m4[2]))), m3[3]), sum(scale(sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))), -m4[3]), scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), m0[3]))), sum(scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), -m1[3]), sum(scale(sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))), m2[3]), scale(sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))), -m3[3])))));
                  var n = sum(sum(sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m2[2]), sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), -m3[2]), scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m3[2]), scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), m4[2]))), -m2[3])), sum(scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m4[2]))), m3[3]), scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), -m4[3]))), sum(sum(scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m4[2]))), -m1[3])), sum(scale(sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m4[2]))), m2[3]), scale(sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))), -m4[3]))));
                  var d = sub(p, n);
                  return d[d.length - 1];
                };
              }
              function orientation(n) {
                var fn = n === 3 ? orientation_3 : n === 4 ? orientation_4 : orientation_5;
                return fn(robustSum, twoProduct, robustScale, robustSubtract);
              }
              var orientation3Exact = orientation(3);
              var orientation4Exact = orientation(4);
              var CACHED = [
                function orientation0() {
                  return 0;
                },
                function orientation1() {
                  return 0;
                },
                function orientation2(a, b) {
                  return b[0] - a[0];
                },
                function orientation3(a, b, c) {
                  var l = (a[1] - c[1]) * (b[0] - c[0]);
                  var r = (a[0] - c[0]) * (b[1] - c[1]);
                  var det = l - r;
                  var s;
                  if (l > 0) {
                    if (r <= 0) {
                      return det;
                    } else {
                      s = l + r;
                    }
                  } else if (l < 0) {
                    if (r >= 0) {
                      return det;
                    } else {
                      s = -(l + r);
                    }
                  } else {
                    return det;
                  }
                  var tol = ERRBOUND3 * s;
                  if (det >= tol || det <= -tol) {
                    return det;
                  }
                  return orientation3Exact(a, b, c);
                },
                function orientation4(a, b, c, d) {
                  var adx = a[0] - d[0];
                  var bdx = b[0] - d[0];
                  var cdx = c[0] - d[0];
                  var ady = a[1] - d[1];
                  var bdy = b[1] - d[1];
                  var cdy = c[1] - d[1];
                  var adz = a[2] - d[2];
                  var bdz = b[2] - d[2];
                  var cdz = c[2] - d[2];
                  var bdxcdy = bdx * cdy;
                  var cdxbdy = cdx * bdy;
                  var cdxady = cdx * ady;
                  var adxcdy = adx * cdy;
                  var adxbdy = adx * bdy;
                  var bdxady = bdx * ady;
                  var det = adz * (bdxcdy - cdxbdy) + bdz * (cdxady - adxcdy) + cdz * (adxbdy - bdxady);
                  var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz);
                  var tol = ERRBOUND4 * permanent;
                  if (det > tol || -det > tol) {
                    return det;
                  }
                  return orientation4Exact(a, b, c, d);
                }
              ];
              function slowOrient(args) {
                var proc2 = CACHED[args.length];
                if (!proc2) {
                  proc2 = CACHED[args.length] = orientation(args.length);
                }
                return proc2.apply(void 0, args);
              }
              function proc(slow, o0, o1, o2, o3, o4, o5) {
                return function getOrientation(a0, a1, a2, a3, a4) {
                  switch (arguments.length) {
                    case 0:
                    case 1:
                      return 0;
                    case 2:
                      return o2(a0, a1);
                    case 3:
                      return o3(a0, a1, a2);
                    case 4:
                      return o4(a0, a1, a2, a3);
                    case 5:
                      return o5(a0, a1, a2, a3, a4);
                  }
                  var s = new Array(arguments.length);
                  for (var i = 0; i < arguments.length; ++i) {
                    s[i] = arguments[i];
                  }
                  return slow(s);
                };
              }
              function generateOrientationProc() {
                while (CACHED.length <= NUM_EXPAND) {
                  CACHED.push(orientation(CACHED.length));
                }
                module2.exports = proc.apply(void 0, [slowOrient].concat(CACHED));
                for (var i = 0; i <= NUM_EXPAND; ++i) {
                  module2.exports[i] = CACHED[i];
                }
              }
              generateOrientationProc();
            }
          ),
          /***/
          3327: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var coallesceUniforms = __webpack_require__2(216);
              var GLError = __webpack_require__2(8866);
              module2.exports = createUniformWrapper;
              function identity2(x) {
                return function() {
                  return x;
                };
              }
              function makeVector(length, fill) {
                var result = new Array(length);
                for (var i = 0; i < length; ++i) {
                  result[i] = fill;
                }
                return result;
              }
              function createUniformWrapper(gl2, wrapper, uniforms, locations) {
                function makeGetter(idx) {
                  return function(gl3, wrapper2, locations2) {
                    return gl3.getUniform(wrapper2.program, locations2[idx]);
                  };
                }
                function makeSetter(type) {
                  return function updateProperty(obj) {
                    var indices = enumerateIndices("", type);
                    for (var i = 0; i < indices.length; ++i) {
                      var item = indices[i];
                      var path = item[0];
                      var idx = item[1];
                      if (locations[idx]) {
                        var objPath = obj;
                        if (typeof path === "string" && (path.indexOf(".") === 0 || path.indexOf("[") === 0)) {
                          var key = path;
                          if (path.indexOf(".") === 0) {
                            key = path.slice(1);
                          }
                          if (key.indexOf("]") === key.length - 1) {
                            var j = key.indexOf("[");
                            var k1 = key.slice(0, j);
                            var k2 = key.slice(j + 1, key.length - 1);
                            objPath = k1 ? obj[k1][k2] : obj[k2];
                          } else {
                            objPath = obj[key];
                          }
                        }
                        var t = uniforms[idx].type;
                        var d;
                        switch (t) {
                          case "bool":
                          case "int":
                          case "sampler2D":
                          case "samplerCube":
                            gl2.uniform1i(locations[idx], objPath);
                            break;
                          case "float":
                            gl2.uniform1f(locations[idx], objPath);
                            break;
                          default:
                            var vidx = t.indexOf("vec");
                            if (0 <= vidx && vidx <= 1 && t.length === 4 + vidx) {
                              d = t.charCodeAt(t.length - 1) - 48;
                              if (d < 2 || d > 4) {
                                throw new GLError("", "Invalid data type");
                              }
                              switch (t.charAt(0)) {
                                case "b":
                                case "i":
                                  gl2["uniform" + d + "iv"](locations[idx], objPath);
                                  break;
                                case "v":
                                  gl2["uniform" + d + "fv"](locations[idx], objPath);
                                  break;
                                default:
                                  throw new GLError("", "Unrecognized data type for vector " + name + ": " + t);
                              }
                            } else if (t.indexOf("mat") === 0 && t.length === 4) {
                              d = t.charCodeAt(t.length - 1) - 48;
                              if (d < 2 || d > 4) {
                                throw new GLError("", "Invalid uniform dimension type for matrix " + name + ": " + t);
                              }
                              gl2["uniformMatrix" + d + "fv"](locations[idx], false, objPath);
                              break;
                            } else {
                              throw new GLError("", "Unknown uniform data type for " + name + ": " + t);
                            }
                        }
                      }
                    }
                  };
                }
                function enumerateIndices(prefix, type) {
                  if (typeof type !== "object") {
                    return [[prefix, type]];
                  }
                  var indices = [];
                  for (var id in type) {
                    var prop = type[id];
                    var tprefix = prefix;
                    if (parseInt(id) + "" === id) {
                      tprefix += "[" + id + "]";
                    } else {
                      tprefix += "." + id;
                    }
                    if (typeof prop === "object") {
                      indices.push.apply(indices, enumerateIndices(tprefix, prop));
                    } else {
                      indices.push([tprefix, prop]);
                    }
                  }
                  return indices;
                }
                function defaultValue(type) {
                  switch (type) {
                    case "bool":
                      return false;
                    case "int":
                    case "sampler2D":
                    case "samplerCube":
                      return 0;
                    case "float":
                      return 0;
                    default:
                      var vidx = type.indexOf("vec");
                      if (0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
                        var d = type.charCodeAt(type.length - 1) - 48;
                        if (d < 2 || d > 4) {
                          throw new GLError("", "Invalid data type");
                        }
                        if (type.charAt(0) === "b") {
                          return makeVector(d, false);
                        }
                        return makeVector(d, 0);
                      } else if (type.indexOf("mat") === 0 && type.length === 4) {
                        var d = type.charCodeAt(type.length - 1) - 48;
                        if (d < 2 || d > 4) {
                          throw new GLError("", "Invalid uniform dimension type for matrix " + name + ": " + type);
                        }
                        return makeVector(d * d, 0);
                      } else {
                        throw new GLError("", "Unknown uniform data type for " + name + ": " + type);
                      }
                  }
                }
                function storeProperty(obj, prop, type) {
                  if (typeof type === "object") {
                    var child = processObject(type);
                    Object.defineProperty(obj, prop, {
                      get: identity2(child),
                      set: makeSetter(type),
                      enumerable: true,
                      configurable: false
                    });
                  } else {
                    if (locations[type]) {
                      Object.defineProperty(obj, prop, {
                        get: makeGetter(type),
                        set: makeSetter(type),
                        enumerable: true,
                        configurable: false
                      });
                    } else {
                      obj[prop] = defaultValue(uniforms[type].type);
                    }
                  }
                }
                function processObject(obj) {
                  var result;
                  if (Array.isArray(obj)) {
                    result = new Array(obj.length);
                    for (var i = 0; i < obj.length; ++i) {
                      storeProperty(result, i, obj[i]);
                    }
                  } else {
                    result = {};
                    for (var id in obj) {
                      storeProperty(result, id, obj[id]);
                    }
                  }
                  return result;
                }
                var coallesced = coallesceUniforms(uniforms, true);
                return {
                  get: identity2(processObject(coallesced)),
                  set: makeSetter(coallesced),
                  enumerable: true,
                  configurable: true
                };
              }
            }
          ),
          /***/
          3349: (
            /***/
            function(module2) {
              "use strict";
              function CWiseOp() {
                return function(SS, a0, t02, p0, Y0, Y1) {
                  var s0 = SS[0], t0p0 = t02[0], index = [0], q0 = t0p0;
                  p0 |= 0;
                  var i0 = 0, d0s0 = t0p0;
                  for (i0 = 0; i0 < s0; ++i0) {
                    {
                      var da = a0[p0] - Y1;
                      var db = a0[p0 + q0] - Y1;
                      if (da >= 0 !== db >= 0) {
                        Y0.push(index[0] + 0.5 + 0.5 * (da + db) / (da - db));
                      }
                    }
                    p0 += d0s0;
                    ++index[0];
                  }
                };
              }
              function generateCWiseOp() {
                return CWiseOp();
              }
              var compile = generateCWiseOp;
              function thunk(compile2) {
                var CACHED = {};
                return function zeroCrossings_cwise_thunk(array0, scalar2, scalar3) {
                  var t02 = array0.dtype, r0 = array0.order, type = [t02, r0.join()].join(), proc = CACHED[type];
                  if (!proc) {
                    CACHED[type] = proc = compile2([t02, r0]);
                  }
                  return proc(array0.shape.slice(0), array0.data, array0.stride, array0.offset | 0, scalar2, scalar3);
                };
              }
              function createThunk(proc) {
                return thunk(compile.bind(void 0, proc));
              }
              function compileCwise(user_args) {
                return createThunk({
                  funcName: user_args.funcName
                });
              }
              module2.exports = compileCwise({
                funcName: "zeroCrossings"
              });
            }
          ),
          /***/
          3352: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bounds = __webpack_require__2(2478);
              var NOT_FOUND = 0;
              var SUCCESS = 1;
              var EMPTY = 2;
              module2.exports = createWrapper;
              function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) {
                this.mid = mid;
                this.left = left;
                this.right = right;
                this.leftPoints = leftPoints;
                this.rightPoints = rightPoints;
                this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length;
              }
              var proto = IntervalTreeNode.prototype;
              function copy(a, b) {
                a.mid = b.mid;
                a.left = b.left;
                a.right = b.right;
                a.leftPoints = b.leftPoints;
                a.rightPoints = b.rightPoints;
                a.count = b.count;
              }
              function rebuild(node, intervals) {
                var ntree = createIntervalTree(intervals);
                node.mid = ntree.mid;
                node.left = ntree.left;
                node.right = ntree.right;
                node.leftPoints = ntree.leftPoints;
                node.rightPoints = ntree.rightPoints;
                node.count = ntree.count;
              }
              function rebuildWithInterval(node, interval) {
                var intervals = node.intervals([]);
                intervals.push(interval);
                rebuild(node, intervals);
              }
              function rebuildWithoutInterval(node, interval) {
                var intervals = node.intervals([]);
                var idx = intervals.indexOf(interval);
                if (idx < 0) {
                  return NOT_FOUND;
                }
                intervals.splice(idx, 1);
                rebuild(node, intervals);
                return SUCCESS;
              }
              proto.intervals = function(result) {
                result.push.apply(result, this.leftPoints);
                if (this.left) {
                  this.left.intervals(result);
                }
                if (this.right) {
                  this.right.intervals(result);
                }
                return result;
              };
              proto.insert = function(interval) {
                var weight = this.count - this.leftPoints.length;
                this.count += 1;
                if (interval[1] < this.mid) {
                  if (this.left) {
                    if (4 * (this.left.count + 1) > 3 * (weight + 1)) {
                      rebuildWithInterval(this, interval);
                    } else {
                      this.left.insert(interval);
                    }
                  } else {
                    this.left = createIntervalTree([interval]);
                  }
                } else if (interval[0] > this.mid) {
                  if (this.right) {
                    if (4 * (this.right.count + 1) > 3 * (weight + 1)) {
                      rebuildWithInterval(this, interval);
                    } else {
                      this.right.insert(interval);
                    }
                  } else {
                    this.right = createIntervalTree([interval]);
                  }
                } else {
                  var l = bounds.ge(this.leftPoints, interval, compareBegin);
                  var r = bounds.ge(this.rightPoints, interval, compareEnd);
                  this.leftPoints.splice(l, 0, interval);
                  this.rightPoints.splice(r, 0, interval);
                }
              };
              proto.remove = function(interval) {
                var weight = this.count - this.leftPoints;
                if (interval[1] < this.mid) {
                  if (!this.left) {
                    return NOT_FOUND;
                  }
                  var rw = this.right ? this.right.count : 0;
                  if (4 * rw > 3 * (weight - 1)) {
                    return rebuildWithoutInterval(this, interval);
                  }
                  var r = this.left.remove(interval);
                  if (r === EMPTY) {
                    this.left = null;
                    this.count -= 1;
                    return SUCCESS;
                  } else if (r === SUCCESS) {
                    this.count -= 1;
                  }
                  return r;
                } else if (interval[0] > this.mid) {
                  if (!this.right) {
                    return NOT_FOUND;
                  }
                  var lw = this.left ? this.left.count : 0;
                  if (4 * lw > 3 * (weight - 1)) {
                    return rebuildWithoutInterval(this, interval);
                  }
                  var r = this.right.remove(interval);
                  if (r === EMPTY) {
                    this.right = null;
                    this.count -= 1;
                    return SUCCESS;
                  } else if (r === SUCCESS) {
                    this.count -= 1;
                  }
                  return r;
                } else {
                  if (this.count === 1) {
                    if (this.leftPoints[0] === interval) {
                      return EMPTY;
                    } else {
                      return NOT_FOUND;
                    }
                  }
                  if (this.leftPoints.length === 1 && this.leftPoints[0] === interval) {
                    if (this.left && this.right) {
                      var p = this;
                      var n = this.left;
                      while (n.right) {
                        p = n;
                        n = n.right;
                      }
                      if (p === this) {
                        n.right = this.right;
                      } else {
                        var l = this.left;
                        var r = this.right;
                        p.count -= n.count;
                        p.right = n.left;
                        n.left = l;
                        n.right = r;
                      }
                      copy(this, n);
                      this.count = (this.left ? this.left.count : 0) + (this.right ? this.right.count : 0) + this.leftPoints.length;
                    } else if (this.left) {
                      copy(this, this.left);
                    } else {
                      copy(this, this.right);
                    }
                    return SUCCESS;
                  }
                  for (var l = bounds.ge(this.leftPoints, interval, compareBegin); l < this.leftPoints.length; ++l) {
                    if (this.leftPoints[l][0] !== interval[0]) {
                      break;
                    }
                    if (this.leftPoints[l] === interval) {
                      this.count -= 1;
                      this.leftPoints.splice(l, 1);
                      for (var r = bounds.ge(this.rightPoints, interval, compareEnd); r < this.rightPoints.length; ++r) {
                        if (this.rightPoints[r][1] !== interval[1]) {
                          break;
                        } else if (this.rightPoints[r] === interval) {
                          this.rightPoints.splice(r, 1);
                          return SUCCESS;
                        }
                      }
                    }
                  }
                  return NOT_FOUND;
                }
              };
              function reportLeftRange(arr, hi, cb) {
                for (var i = 0; i < arr.length && arr[i][0] <= hi; ++i) {
                  var r = cb(arr[i]);
                  if (r) {
                    return r;
                  }
                }
              }
              function reportRightRange(arr, lo, cb) {
                for (var i = arr.length - 1; i >= 0 && arr[i][1] >= lo; --i) {
                  var r = cb(arr[i]);
                  if (r) {
                    return r;
                  }
                }
              }
              function reportRange(arr, cb) {
                for (var i = 0; i < arr.length; ++i) {
                  var r = cb(arr[i]);
                  if (r) {
                    return r;
                  }
                }
              }
              proto.queryPoint = function(x, cb) {
                if (x < this.mid) {
                  if (this.left) {
                    var r = this.left.queryPoint(x, cb);
                    if (r) {
                      return r;
                    }
                  }
                  return reportLeftRange(this.leftPoints, x, cb);
                } else if (x > this.mid) {
                  if (this.right) {
                    var r = this.right.queryPoint(x, cb);
                    if (r) {
                      return r;
                    }
                  }
                  return reportRightRange(this.rightPoints, x, cb);
                } else {
                  return reportRange(this.leftPoints, cb);
                }
              };
              proto.queryInterval = function(lo, hi, cb) {
                if (lo < this.mid && this.left) {
                  var r = this.left.queryInterval(lo, hi, cb);
                  if (r) {
                    return r;
                  }
                }
                if (hi > this.mid && this.right) {
                  var r = this.right.queryInterval(lo, hi, cb);
                  if (r) {
                    return r;
                  }
                }
                if (hi < this.mid) {
                  return reportLeftRange(this.leftPoints, hi, cb);
                } else if (lo > this.mid) {
                  return reportRightRange(this.rightPoints, lo, cb);
                } else {
                  return reportRange(this.leftPoints, cb);
                }
              };
              function compareNumbers(a, b) {
                return a - b;
              }
              function compareBegin(a, b) {
                var d = a[0] - b[0];
                if (d) {
                  return d;
                }
                return a[1] - b[1];
              }
              function compareEnd(a, b) {
                var d = a[1] - b[1];
                if (d) {
                  return d;
                }
                return a[0] - b[0];
              }
              function createIntervalTree(intervals) {
                if (intervals.length === 0) {
                  return null;
                }
                var pts = [];
                for (var i = 0; i < intervals.length; ++i) {
                  pts.push(intervals[i][0], intervals[i][1]);
                }
                pts.sort(compareNumbers);
                var mid = pts[pts.length >> 1];
                var leftIntervals = [];
                var rightIntervals = [];
                var centerIntervals = [];
                for (var i = 0; i < intervals.length; ++i) {
                  var s = intervals[i];
                  if (s[1] < mid) {
                    leftIntervals.push(s);
                  } else if (mid < s[0]) {
                    rightIntervals.push(s);
                  } else {
                    centerIntervals.push(s);
                  }
                }
                var leftPoints = centerIntervals;
                var rightPoints = centerIntervals.slice();
                leftPoints.sort(compareBegin);
                rightPoints.sort(compareEnd);
                return new IntervalTreeNode(
                  mid,
                  createIntervalTree(leftIntervals),
                  createIntervalTree(rightIntervals),
                  leftPoints,
                  rightPoints
                );
              }
              function IntervalTree(root) {
                this.root = root;
              }
              var tproto = IntervalTree.prototype;
              tproto.insert = function(interval) {
                if (this.root) {
                  this.root.insert(interval);
                } else {
                  this.root = new IntervalTreeNode(interval[0], null, null, [interval], [interval]);
                }
              };
              tproto.remove = function(interval) {
                if (this.root) {
                  var r = this.root.remove(interval);
                  if (r === EMPTY) {
                    this.root = null;
                  }
                  return r !== NOT_FOUND;
                }
                return false;
              };
              tproto.queryPoint = function(p, cb) {
                if (this.root) {
                  return this.root.queryPoint(p, cb);
                }
              };
              tproto.queryInterval = function(lo, hi, cb) {
                if (lo <= hi && this.root) {
                  return this.root.queryInterval(lo, hi, cb);
                }
              };
              Object.defineProperty(tproto, "count", {
                get: function() {
                  if (this.root) {
                    return this.root.count;
                  }
                  return 0;
                }
              });
              Object.defineProperty(tproto, "intervals", {
                get: function() {
                  if (this.root) {
                    return this.root.intervals([]);
                  }
                  return [];
                }
              });
              function createWrapper(intervals) {
                if (!intervals || intervals.length === 0) {
                  return new IntervalTree(null);
                }
                return new IntervalTree(createIntervalTree(intervals));
              }
            }
          ),
          /***/
          3387: (
            /***/
            function(module2, exports2, __webpack_require__2) {
              var __WEBPACK_AMD_DEFINE_RESULT__;
              !function() {
                "use strict";
                var re = {
                  not_string: /[^s]/,
                  not_bool: /[^t]/,
                  not_type: /[^T]/,
                  not_primitive: /[^v]/,
                  number: /[diefg]/,
                  numeric_arg: /[bcdiefguxX]/,
                  json: /[j]/,
                  not_json: /[^j]/,
                  text: /^[^\x25]+/,
                  modulo: /^\x25{2}/,
                  placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
                  key: /^([a-z_][a-z_\d]*)/i,
                  key_access: /^\.([a-z_][a-z_\d]*)/i,
                  index_access: /^\[(\d+)\]/,
                  sign: /^[+-]/
                };
                function sprintf(key) {
                  return sprintf_format(sprintf_parse(key), arguments);
                }
                function vsprintf(fmt, argv) {
                  return sprintf.apply(null, [fmt].concat(argv || []));
                }
                function sprintf_format(parse_tree, argv) {
                  var cursor = 1, tree_length = parse_tree.length, arg, output = "", i, k, ph, pad, pad_character, pad_length, is_positive, sign;
                  for (i = 0; i < tree_length; i++) {
                    if (typeof parse_tree[i] === "string") {
                      output += parse_tree[i];
                    } else if (typeof parse_tree[i] === "object") {
                      ph = parse_tree[i];
                      if (ph.keys) {
                        arg = argv[cursor];
                        for (k = 0; k < ph.keys.length; k++) {
                          if (arg == void 0) {
                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
                          }
                          arg = arg[ph.keys[k]];
                        }
                      } else if (ph.param_no) {
                        arg = argv[ph.param_no];
                      } else {
                        arg = argv[cursor++];
                      }
                      if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                        arg = arg();
                      }
                      if (re.numeric_arg.test(ph.type) && (typeof arg !== "number" && isNaN(arg))) {
                        throw new TypeError(sprintf("[sprintf] expecting number but found %T", arg));
                      }
                      if (re.number.test(ph.type)) {
                        is_positive = arg >= 0;
                      }
                      switch (ph.type) {
                        case "b":
                          arg = parseInt(arg, 10).toString(2);
                          break;
                        case "c":
                          arg = String.fromCharCode(parseInt(arg, 10));
                          break;
                        case "d":
                        case "i":
                          arg = parseInt(arg, 10);
                          break;
                        case "j":
                          arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
                          break;
                        case "e":
                          arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
                          break;
                        case "f":
                          arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
                          break;
                        case "g":
                          arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
                          break;
                        case "o":
                          arg = (parseInt(arg, 10) >>> 0).toString(8);
                          break;
                        case "s":
                          arg = String(arg);
                          arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                          break;
                        case "t":
                          arg = String(!!arg);
                          arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                          break;
                        case "T":
                          arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
                          arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                          break;
                        case "u":
                          arg = parseInt(arg, 10) >>> 0;
                          break;
                        case "v":
                          arg = arg.valueOf();
                          arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                          break;
                        case "x":
                          arg = (parseInt(arg, 10) >>> 0).toString(16);
                          break;
                        case "X":
                          arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
                          break;
                      }
                      if (re.json.test(ph.type)) {
                        output += arg;
                      } else {
                        if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                          sign = is_positive ? "+" : "-";
                          arg = arg.toString().replace(re.sign, "");
                        } else {
                          sign = "";
                        }
                        pad_character = ph.pad_char ? ph.pad_char === "0" ? "0" : ph.pad_char.charAt(1) : " ";
                        pad_length = ph.width - (sign + arg).length;
                        pad = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : "" : "";
                        output += ph.align ? sign + arg + pad : pad_character === "0" ? sign + pad + arg : pad + sign + arg;
                      }
                    }
                  }
                  return output;
                }
                var sprintf_cache = /* @__PURE__ */ Object.create(null);
                function sprintf_parse(fmt) {
                  if (sprintf_cache[fmt]) {
                    return sprintf_cache[fmt];
                  }
                  var _fmt = fmt, match, parse_tree = [], arg_names = 0;
                  while (_fmt) {
                    if ((match = re.text.exec(_fmt)) !== null) {
                      parse_tree.push(match[0]);
                    } else if ((match = re.modulo.exec(_fmt)) !== null) {
                      parse_tree.push("%");
                    } else if ((match = re.placeholder.exec(_fmt)) !== null) {
                      if (match[2]) {
                        arg_names |= 1;
                        var field_list = [], replacement_field = match[2], field_match = [];
                        if ((field_match = re.key.exec(replacement_field)) !== null) {
                          field_list.push(field_match[1]);
                          while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") {
                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                              field_list.push(field_match[1]);
                            } else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                              field_list.push(field_match[1]);
                            } else {
                              throw new SyntaxError("[sprintf] failed to parse named argument key");
                            }
                          }
                        } else {
                          throw new SyntaxError("[sprintf] failed to parse named argument key");
                        }
                        match[2] = field_list;
                      } else {
                        arg_names |= 2;
                      }
                      if (arg_names === 3) {
                        throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");
                      }
                      parse_tree.push(
                        {
                          placeholder: match[0],
                          param_no: match[1],
                          keys: match[2],
                          sign: match[3],
                          pad_char: match[4],
                          align: match[5],
                          width: match[6],
                          precision: match[7],
                          type: match[8]
                        }
                      );
                    } else {
                      throw new SyntaxError("[sprintf] unexpected placeholder");
                    }
                    _fmt = _fmt.substring(match[0].length);
                  }
                  return sprintf_cache[fmt] = parse_tree;
                }
                if (true) {
                  exports2.sprintf = sprintf;
                  exports2.vsprintf = vsprintf;
                }
                if (typeof window !== "undefined") {
                  window["sprintf"] = sprintf;
                  window["vsprintf"] = vsprintf;
                  if (true) {
                    !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
                      return {
                        "sprintf": sprintf,
                        "vsprintf": vsprintf
                      };
                    }.call(exports2, __webpack_require__2, exports2, module2), __WEBPACK_AMD_DEFINE_RESULT__ !== void 0 && (module2.exports = __WEBPACK_AMD_DEFINE_RESULT__));
                  }
                }
              }();
            }
          ),
          /***/
          3390: (
            /***/
            function(module2) {
              module2.exports = fromValues;
              function fromValues(x, y, z, w) {
                var out = new Float32Array(4);
                out[0] = x;
                out[1] = y;
                out[2] = z;
                out[3] = w;
                return out;
              }
            }
          ),
          /***/
          3436: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var glslify = __webpack_require__2(3236);
              var createShader = __webpack_require__2(9405);
              var vertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n  vec4 worldPosition  = model * vec4(position, 1.0);\n  worldPosition       = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n  gl_Position         = projection * (view * worldPosition);\n  fragColor           = color;\n  fragPosition        = position;\n}"]);
              var fragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], fragPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  gl_FragColor = opacity * fragColor;\n}"]);
              module2.exports = function(gl2) {
                return createShader(gl2, vertSrc, fragSrc, null, [
                  { name: "position", type: "vec3" },
                  { name: "color", type: "vec4" },
                  { name: "offset", type: "vec3" }
                ]);
              };
            }
          ),
          /***/
          3502: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = alphaShape;
              var ac = __webpack_require__2(5995);
              var bnd = __webpack_require__2(9127);
              function alphaShape(alpha, points) {
                return bnd(ac(alpha, points));
              }
            }
          ),
          /***/
          3508: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var v100 = __webpack_require__2(6852);
              v100 = v100.slice().filter(function(b) {
                return !/^(gl\_|texture)/.test(b);
              });
              module2.exports = v100.concat([
                // the updated gl_ constants
                "gl_VertexID",
                "gl_InstanceID",
                "gl_Position",
                "gl_PointSize",
                "gl_FragCoord",
                "gl_FrontFacing",
                "gl_FragDepth",
                "gl_PointCoord",
                "gl_MaxVertexAttribs",
                "gl_MaxVertexUniformVectors",
                "gl_MaxVertexOutputVectors",
                "gl_MaxFragmentInputVectors",
                "gl_MaxVertexTextureImageUnits",
                "gl_MaxCombinedTextureImageUnits",
                "gl_MaxTextureImageUnits",
                "gl_MaxFragmentUniformVectors",
                "gl_MaxDrawBuffers",
                "gl_MinProgramTexelOffset",
                "gl_MaxProgramTexelOffset",
                "gl_DepthRangeParameters",
                "gl_DepthRange",
                "trunc",
                "round",
                "roundEven",
                "isnan",
                "isinf",
                "floatBitsToInt",
                "floatBitsToUint",
                "intBitsToFloat",
                "uintBitsToFloat",
                "packSnorm2x16",
                "unpackSnorm2x16",
                "packUnorm2x16",
                "unpackUnorm2x16",
                "packHalf2x16",
                "unpackHalf2x16",
                "outerProduct",
                "transpose",
                "determinant",
                "inverse",
                "texture",
                "textureSize",
                "textureProj",
                "textureLod",
                "textureOffset",
                "texelFetch",
                "texelFetchOffset",
                "textureProjOffset",
                "textureLodOffset",
                "textureProjLod",
                "textureProjLodOffset",
                "textureGrad",
                "textureGradOffset",
                "textureProjGrad",
                "textureProjGradOffset"
              ]);
            }
          ),
          /***/
          3536: (
            /***/
            function(module2) {
              module2.exports = normalize;
              function normalize(out, a) {
                var x = a[0], y = a[1], z = a[2];
                var len = x * x + y * y + z * z;
                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  out[0] = a[0] * len;
                  out[1] = a[1] * len;
                  out[2] = a[2] * len;
                }
                return out;
              }
            }
          ),
          /***/
          3545: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = findMedian;
              var genPartition = __webpack_require__2(8105);
              var partitionStartLessThan = genPartition("lo<p0");
              var PARTITION_THRESHOLD = 8;
              function insertionSort(d, axis, start, end, boxes, ids) {
                var elemSize = 2 * d;
                var boxPtr = elemSize * (start + 1) + axis;
                for (var i = start + 1; i < end; ++i, boxPtr += elemSize) {
                  var x = boxes[boxPtr];
                  for (var j = i, ptr = elemSize * (i - 1); j > start && boxes[ptr + axis] > x; --j, ptr -= elemSize) {
                    var aPtr = ptr;
                    var bPtr = ptr + elemSize;
                    for (var k = 0; k < elemSize; ++k, ++aPtr, ++bPtr) {
                      var y = boxes[aPtr];
                      boxes[aPtr] = boxes[bPtr];
                      boxes[bPtr] = y;
                    }
                    var tmp = ids[j];
                    ids[j] = ids[j - 1];
                    ids[j - 1] = tmp;
                  }
                }
              }
              function findMedian(d, axis, start, end, boxes, ids) {
                if (end <= start + 1) {
                  return start;
                }
                var lo = start;
                var hi = end;
                var mid = end + start >>> 1;
                var elemSize = 2 * d;
                var pivot = mid;
                var value = boxes[elemSize * mid + axis];
                while (lo < hi) {
                  if (hi - lo < PARTITION_THRESHOLD) {
                    insertionSort(d, axis, lo, hi, boxes, ids);
                    value = boxes[elemSize * mid + axis];
                    break;
                  }
                  var count = hi - lo;
                  var pivot0 = Math.random() * count + lo | 0;
                  var value0 = boxes[elemSize * pivot0 + axis];
                  var pivot1 = Math.random() * count + lo | 0;
                  var value1 = boxes[elemSize * pivot1 + axis];
                  var pivot2 = Math.random() * count + lo | 0;
                  var value2 = boxes[elemSize * pivot2 + axis];
                  if (value0 <= value1) {
                    if (value2 >= value1) {
                      pivot = pivot1;
                      value = value1;
                    } else if (value0 >= value2) {
                      pivot = pivot0;
                      value = value0;
                    } else {
                      pivot = pivot2;
                      value = value2;
                    }
                  } else {
                    if (value1 >= value2) {
                      pivot = pivot1;
                      value = value1;
                    } else if (value2 >= value0) {
                      pivot = pivot0;
                      value = value0;
                    } else {
                      pivot = pivot2;
                      value = value2;
                    }
                  }
                  var aPtr = elemSize * (hi - 1);
                  var bPtr = elemSize * pivot;
                  for (var i = 0; i < elemSize; ++i, ++aPtr, ++bPtr) {
                    var x = boxes[aPtr];
                    boxes[aPtr] = boxes[bPtr];
                    boxes[bPtr] = x;
                  }
                  var y = ids[hi - 1];
                  ids[hi - 1] = ids[pivot];
                  ids[pivot] = y;
                  pivot = partitionStartLessThan(
                    d,
                    axis,
                    lo,
                    hi - 1,
                    boxes,
                    ids,
                    value
                  );
                  var aPtr = elemSize * (hi - 1);
                  var bPtr = elemSize * pivot;
                  for (var i = 0; i < elemSize; ++i, ++aPtr, ++bPtr) {
                    var x = boxes[aPtr];
                    boxes[aPtr] = boxes[bPtr];
                    boxes[bPtr] = x;
                  }
                  var y = ids[hi - 1];
                  ids[hi - 1] = ids[pivot];
                  ids[pivot] = y;
                  if (mid < pivot) {
                    hi = pivot - 1;
                    while (lo < hi && boxes[elemSize * (hi - 1) + axis] === value) {
                      hi -= 1;
                    }
                    hi += 1;
                  } else if (pivot < mid) {
                    lo = pivot + 1;
                    while (lo < hi && boxes[elemSize * lo + axis] === value) {
                      lo += 1;
                    }
                  } else {
                    break;
                  }
                }
                return partitionStartLessThan(
                  d,
                  axis,
                  start,
                  mid,
                  boxes,
                  ids,
                  boxes[elemSize * mid + axis]
                );
              }
            }
          ),
          /***/
          3576: (
            /***/
            function(module2) {
              module2.exports = multiply;
              function multiply(out, a, b) {
                out[0] = a[0] * b[0];
                out[1] = a[1] * b[1];
                out[2] = a[2] * b[2];
                out[3] = a[3] * b[3];
                return out;
              }
            }
          ),
          /***/
          3589: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createSelectBuffer;
              var createFBO = __webpack_require__2(2260);
              var pool = __webpack_require__2(1888);
              var ndarray = __webpack_require__2(9618);
              var nextPow2 = __webpack_require__2(8828).nextPow2;
              var selectRange = function(arr, x, y) {
                var closestD2 = 1e8;
                var closestX = -1;
                var closestY = -1;
                var ni = arr.shape[0];
                var nj = arr.shape[1];
                for (var i = 0; i < ni; i++) {
                  for (var j = 0; j < nj; j++) {
                    var r = arr.get(i, j, 0);
                    var g = arr.get(i, j, 1);
                    var b = arr.get(i, j, 2);
                    var a = arr.get(i, j, 3);
                    if (r < 255 || g < 255 || b < 255 || a < 255) {
                      var dx = x - i;
                      var dy = y - j;
                      var d2 = dx * dx + dy * dy;
                      if (d2 < closestD2) {
                        closestD2 = d2;
                        closestX = i;
                        closestY = j;
                      }
                    }
                  }
                }
                return [closestX, closestY, closestD2];
              };
              function SelectResult(x, y, id, value, distance) {
                this.coord = [x, y];
                this.id = id;
                this.value = value;
                this.distance = distance;
              }
              function SelectBuffer(gl2, fbo, buffer) {
                this.gl = gl2;
                this.fbo = fbo;
                this.buffer = buffer;
                this._readTimeout = null;
                var self2 = this;
                this._readCallback = function() {
                  if (!self2.gl) {
                    return;
                  }
                  fbo.bind();
                  gl2.readPixels(0, 0, fbo.shape[0], fbo.shape[1], gl2.RGBA, gl2.UNSIGNED_BYTE, self2.buffer);
                  self2._readTimeout = null;
                };
              }
              var proto = SelectBuffer.prototype;
              Object.defineProperty(proto, "shape", {
                get: function() {
                  if (!this.gl) {
                    return [0, 0];
                  }
                  return this.fbo.shape.slice();
                },
                set: function(v) {
                  if (!this.gl) {
                    return;
                  }
                  this.fbo.shape = v;
                  var c = this.fbo.shape[0];
                  var r = this.fbo.shape[1];
                  if (r * c * 4 > this.buffer.length) {
                    pool.free(this.buffer);
                    var buffer = this.buffer = pool.mallocUint8(nextPow2(r * c * 4));
                    for (var i = 0; i < r * c * 4; ++i) {
                      buffer[i] = 255;
                    }
                  }
                  return v;
                }
              });
              proto.begin = function() {
                var gl2 = this.gl;
                var shape = this.shape;
                if (!gl2) {
                  return;
                }
                this.fbo.bind();
                gl2.clearColor(1, 1, 1, 1);
                gl2.clear(gl2.COLOR_BUFFER_BIT | gl2.DEPTH_BUFFER_BIT);
              };
              proto.end = function() {
                var gl2 = this.gl;
                if (!gl2) {
                  return;
                }
                gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
                if (!this._readTimeout) {
                  clearTimeout(this._readTimeout);
                }
                this._readTimeout = setTimeout(this._readCallback, 1);
              };
              proto.query = function(x, y, radius) {
                if (!this.gl) {
                  return null;
                }
                var shape = this.fbo.shape.slice();
                x = x | 0;
                y = y | 0;
                if (typeof radius !== "number") {
                  radius = 1;
                }
                var x0 = Math.min(Math.max(x - radius, 0), shape[0]) | 0;
                var x1 = Math.min(Math.max(x + radius, 0), shape[0]) | 0;
                var y0 = Math.min(Math.max(y - radius, 0), shape[1]) | 0;
                var y1 = Math.min(Math.max(y + radius, 0), shape[1]) | 0;
                if (x1 <= x0 || y1 <= y0) {
                  return null;
                }
                var dims = [x1 - x0, y1 - y0];
                var region = ndarray(
                  this.buffer,
                  [dims[0], dims[1], 4],
                  [4, shape[0] * 4, 1],
                  4 * (x0 + shape[0] * y0)
                );
                var closest = selectRange(region.hi(dims[0], dims[1], 1), radius, radius);
                var dx = closest[0];
                var dy = closest[1];
                if (dx < 0 || Math.pow(this.radius, 2) < closest[2]) {
                  return null;
                }
                var c0 = region.get(dx, dy, 0);
                var c1 = region.get(dx, dy, 1);
                var c2 = region.get(dx, dy, 2);
                var c3 = region.get(dx, dy, 3);
                return new SelectResult(
                  dx + x0 | 0,
                  dy + y0 | 0,
                  c0,
                  [c1, c2, c3],
                  Math.sqrt(closest[2])
                );
              };
              proto.dispose = function() {
                if (!this.gl) {
                  return;
                }
                this.fbo.dispose();
                pool.free(this.buffer);
                this.gl = null;
                if (this._readTimeout) {
                  clearTimeout(this._readTimeout);
                }
              };
              function createSelectBuffer(gl2, shape) {
                var width = shape[0];
                var height = shape[1];
                var options = {};
                var fbo = createFBO(gl2, width, height, options);
                var buffer = pool.mallocUint8(width * height * 4);
                return new SelectBuffer(gl2, fbo, buffer);
              }
            }
          ),
          /***/
          3628: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var dup = __webpack_require__2(1338);
              var solve = __webpack_require__2(727);
              function dot(a, b) {
                var s = 0;
                var d = a.length;
                for (var i = 0; i < d; ++i) {
                  s += a[i] * b[i];
                }
                return s;
              }
              function barycentricCircumcenter(points) {
                var N = points.length;
                if (N === 0) {
                  return [];
                }
                var D2 = points[0].length;
                var A2 = dup([points.length + 1, points.length + 1], 1);
                var b = dup([points.length + 1], 1);
                A2[N][N] = 0;
                for (var i = 0; i < N; ++i) {
                  for (var j = 0; j <= i; ++j) {
                    A2[j][i] = A2[i][j] = 2 * dot(points[i], points[j]);
                  }
                  b[i] = dot(points[i], points[i]);
                }
                var x = solve(A2, b);
                var denom = 0;
                var h = x[N + 1];
                for (var i = 0; i < h.length; ++i) {
                  denom += h[i];
                }
                var y = new Array(N);
                for (var i = 0; i < N; ++i) {
                  var h = x[i];
                  var numer = 0;
                  for (var j = 0; j < h.length; ++j) {
                    numer += h[j];
                  }
                  y[i] = numer / denom;
                }
                return y;
              }
              function circumcenter(points) {
                if (points.length === 0) {
                  return [];
                }
                var D2 = points[0].length;
                var result = dup([D2]);
                var weights = barycentricCircumcenter(points);
                for (var i = 0; i < points.length; ++i) {
                  for (var j = 0; j < D2; ++j) {
                    result[j] += points[i][j] * weights[i];
                  }
                }
                return result;
              }
              circumcenter.barycenetric = barycentricCircumcenter;
              module2.exports = circumcenter;
            }
          ),
          /***/
          3637: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = solveIntersection;
              var ratMul = __webpack_require__2(6504);
              var ratDiv = __webpack_require__2(8697);
              var ratSub = __webpack_require__2(5572);
              var ratSign = __webpack_require__2(7721);
              var rvSub = __webpack_require__2(544);
              var rvAdd = __webpack_require__2(2653);
              var rvMuls = __webpack_require__2(8987);
              function ratPerp(a, b) {
                return ratSub(ratMul(a[0], b[1]), ratMul(a[1], b[0]));
              }
              function solveIntersection(a, b, c, d) {
                var ba = rvSub(b, a);
                var dc = rvSub(d, c);
                var baXdc = ratPerp(ba, dc);
                if (ratSign(baXdc) === 0) {
                  return null;
                }
                var ac = rvSub(a, c);
                var dcXac = ratPerp(dc, ac);
                var t = ratDiv(dcXac, baXdc);
                var s = rvMuls(ba, t);
                var r = rvAdd(a, s);
                return r;
              }
            }
          ),
          /***/
          3642: (
            /***/
            function(module2) {
              module2.exports = {
                "jet": [{ "index": 0, "rgb": [0, 0, 131] }, { "index": 0.125, "rgb": [0, 60, 170] }, { "index": 0.375, "rgb": [5, 255, 255] }, { "index": 0.625, "rgb": [255, 255, 0] }, { "index": 0.875, "rgb": [250, 0, 0] }, { "index": 1, "rgb": [128, 0, 0] }],
                "hsv": [{ "index": 0, "rgb": [255, 0, 0] }, { "index": 0.169, "rgb": [253, 255, 2] }, { "index": 0.173, "rgb": [247, 255, 2] }, { "index": 0.337, "rgb": [0, 252, 4] }, { "index": 0.341, "rgb": [0, 252, 10] }, { "index": 0.506, "rgb": [1, 249, 255] }, { "index": 0.671, "rgb": [2, 0, 253] }, { "index": 0.675, "rgb": [8, 0, 253] }, { "index": 0.839, "rgb": [255, 0, 251] }, { "index": 0.843, "rgb": [255, 0, 245] }, { "index": 1, "rgb": [255, 0, 6] }],
                "hot": [{ "index": 0, "rgb": [0, 0, 0] }, { "index": 0.3, "rgb": [230, 0, 0] }, { "index": 0.6, "rgb": [255, 210, 0] }, { "index": 1, "rgb": [255, 255, 255] }],
                "spring": [{ "index": 0, "rgb": [255, 0, 255] }, { "index": 1, "rgb": [255, 255, 0] }],
                "summer": [{ "index": 0, "rgb": [0, 128, 102] }, { "index": 1, "rgb": [255, 255, 102] }],
                "autumn": [{ "index": 0, "rgb": [255, 0, 0] }, { "index": 1, "rgb": [255, 255, 0] }],
                "winter": [{ "index": 0, "rgb": [0, 0, 255] }, { "index": 1, "rgb": [0, 255, 128] }],
                "bone": [{ "index": 0, "rgb": [0, 0, 0] }, { "index": 0.376, "rgb": [84, 84, 116] }, { "index": 0.753, "rgb": [169, 200, 200] }, { "index": 1, "rgb": [255, 255, 255] }],
                "copper": [{ "index": 0, "rgb": [0, 0, 0] }, { "index": 0.804, "rgb": [255, 160, 102] }, { "index": 1, "rgb": [255, 199, 127] }],
                "greys": [{ "index": 0, "rgb": [0, 0, 0] }, { "index": 1, "rgb": [255, 255, 255] }],
                "yignbu": [{ "index": 0, "rgb": [8, 29, 88] }, { "index": 0.125, "rgb": [37, 52, 148] }, { "index": 0.25, "rgb": [34, 94, 168] }, { "index": 0.375, "rgb": [29, 145, 192] }, { "index": 0.5, "rgb": [65, 182, 196] }, { "index": 0.625, "rgb": [127, 205, 187] }, { "index": 0.75, "rgb": [199, 233, 180] }, { "index": 0.875, "rgb": [237, 248, 217] }, { "index": 1, "rgb": [255, 255, 217] }],
                "greens": [{ "index": 0, "rgb": [0, 68, 27] }, { "index": 0.125, "rgb": [0, 109, 44] }, { "index": 0.25, "rgb": [35, 139, 69] }, { "index": 0.375, "rgb": [65, 171, 93] }, { "index": 0.5, "rgb": [116, 196, 118] }, { "index": 0.625, "rgb": [161, 217, 155] }, { "index": 0.75, "rgb": [199, 233, 192] }, { "index": 0.875, "rgb": [229, 245, 224] }, { "index": 1, "rgb": [247, 252, 245] }],
                "yiorrd": [{ "index": 0, "rgb": [128, 0, 38] }, { "index": 0.125, "rgb": [189, 0, 38] }, { "index": 0.25, "rgb": [227, 26, 28] }, { "index": 0.375, "rgb": [252, 78, 42] }, { "index": 0.5, "rgb": [253, 141, 60] }, { "index": 0.625, "rgb": [254, 178, 76] }, { "index": 0.75, "rgb": [254, 217, 118] }, { "index": 0.875, "rgb": [255, 237, 160] }, { "index": 1, "rgb": [255, 255, 204] }],
                "bluered": [{ "index": 0, "rgb": [0, 0, 255] }, { "index": 1, "rgb": [255, 0, 0] }],
                "rdbu": [{ "index": 0, "rgb": [5, 10, 172] }, { "index": 0.35, "rgb": [106, 137, 247] }, { "index": 0.5, "rgb": [190, 190, 190] }, { "index": 0.6, "rgb": [220, 170, 132] }, { "index": 0.7, "rgb": [230, 145, 90] }, { "index": 1, "rgb": [178, 10, 28] }],
                "picnic": [{ "index": 0, "rgb": [0, 0, 255] }, { "index": 0.1, "rgb": [51, 153, 255] }, { "index": 0.2, "rgb": [102, 204, 255] }, { "index": 0.3, "rgb": [153, 204, 255] }, { "index": 0.4, "rgb": [204, 204, 255] }, { "index": 0.5, "rgb": [255, 255, 255] }, { "index": 0.6, "rgb": [255, 204, 255] }, { "index": 0.7, "rgb": [255, 153, 255] }, { "index": 0.8, "rgb": [255, 102, 204] }, { "index": 0.9, "rgb": [255, 102, 102] }, { "index": 1, "rgb": [255, 0, 0] }],
                "rainbow": [{ "index": 0, "rgb": [150, 0, 90] }, { "index": 0.125, "rgb": [0, 0, 200] }, { "index": 0.25, "rgb": [0, 25, 255] }, { "index": 0.375, "rgb": [0, 152, 255] }, { "index": 0.5, "rgb": [44, 255, 150] }, { "index": 0.625, "rgb": [151, 255, 0] }, { "index": 0.75, "rgb": [255, 234, 0] }, { "index": 0.875, "rgb": [255, 111, 0] }, { "index": 1, "rgb": [255, 0, 0] }],
                "portland": [{ "index": 0, "rgb": [12, 51, 131] }, { "index": 0.25, "rgb": [10, 136, 186] }, { "index": 0.5, "rgb": [242, 211, 56] }, { "index": 0.75, "rgb": [242, 143, 56] }, { "index": 1, "rgb": [217, 30, 30] }],
                "blackbody": [{ "index": 0, "rgb": [0, 0, 0] }, { "index": 0.2, "rgb": [230, 0, 0] }, { "index": 0.4, "rgb": [230, 210, 0] }, { "index": 0.7, "rgb": [255, 255, 255] }, { "index": 1, "rgb": [160, 200, 255] }],
                "earth": [{ "index": 0, "rgb": [0, 0, 130] }, { "index": 0.1, "rgb": [0, 180, 180] }, { "index": 0.2, "rgb": [40, 210, 40] }, { "index": 0.4, "rgb": [230, 230, 50] }, { "index": 0.6, "rgb": [120, 70, 20] }, { "index": 1, "rgb": [255, 255, 255] }],
                "electric": [{ "index": 0, "rgb": [0, 0, 0] }, { "index": 0.15, "rgb": [30, 0, 100] }, { "index": 0.4, "rgb": [120, 0, 100] }, { "index": 0.6, "rgb": [160, 90, 0] }, { "index": 0.8, "rgb": [230, 200, 0] }, { "index": 1, "rgb": [255, 250, 220] }],
                "alpha": [{ "index": 0, "rgb": [255, 255, 255, 0] }, { "index": 1, "rgb": [255, 255, 255, 1] }],
                "viridis": [{ "index": 0, "rgb": [68, 1, 84] }, { "index": 0.13, "rgb": [71, 44, 122] }, { "index": 0.25, "rgb": [59, 81, 139] }, { "index": 0.38, "rgb": [44, 113, 142] }, { "index": 0.5, "rgb": [33, 144, 141] }, { "index": 0.63, "rgb": [39, 173, 129] }, { "index": 0.75, "rgb": [92, 200, 99] }, { "index": 0.88, "rgb": [170, 220, 50] }, { "index": 1, "rgb": [253, 231, 37] }],
                "inferno": [{ "index": 0, "rgb": [0, 0, 4] }, { "index": 0.13, "rgb": [31, 12, 72] }, { "index": 0.25, "rgb": [85, 15, 109] }, { "index": 0.38, "rgb": [136, 34, 106] }, { "index": 0.5, "rgb": [186, 54, 85] }, { "index": 0.63, "rgb": [227, 89, 51] }, { "index": 0.75, "rgb": [249, 140, 10] }, { "index": 0.88, "rgb": [249, 201, 50] }, { "index": 1, "rgb": [252, 255, 164] }],
                "magma": [{ "index": 0, "rgb": [0, 0, 4] }, { "index": 0.13, "rgb": [28, 16, 68] }, { "index": 0.25, "rgb": [79, 18, 123] }, { "index": 0.38, "rgb": [129, 37, 129] }, { "index": 0.5, "rgb": [181, 54, 122] }, { "index": 0.63, "rgb": [229, 80, 100] }, { "index": 0.75, "rgb": [251, 135, 97] }, { "index": 0.88, "rgb": [254, 194, 135] }, { "index": 1, "rgb": [252, 253, 191] }],
                "plasma": [{ "index": 0, "rgb": [13, 8, 135] }, { "index": 0.13, "rgb": [75, 3, 161] }, { "index": 0.25, "rgb": [125, 3, 168] }, { "index": 0.38, "rgb": [168, 34, 150] }, { "index": 0.5, "rgb": [203, 70, 121] }, { "index": 0.63, "rgb": [229, 107, 93] }, { "index": 0.75, "rgb": [248, 148, 65] }, { "index": 0.88, "rgb": [253, 195, 40] }, { "index": 1, "rgb": [240, 249, 33] }],
                "warm": [{ "index": 0, "rgb": [125, 0, 179] }, { "index": 0.13, "rgb": [172, 0, 187] }, { "index": 0.25, "rgb": [219, 0, 170] }, { "index": 0.38, "rgb": [255, 0, 130] }, { "index": 0.5, "rgb": [255, 63, 74] }, { "index": 0.63, "rgb": [255, 123, 0] }, { "index": 0.75, "rgb": [234, 176, 0] }, { "index": 0.88, "rgb": [190, 228, 0] }, { "index": 1, "rgb": [147, 255, 0] }],
                "cool": [{ "index": 0, "rgb": [125, 0, 179] }, { "index": 0.13, "rgb": [116, 0, 218] }, { "index": 0.25, "rgb": [98, 74, 237] }, { "index": 0.38, "rgb": [68, 146, 231] }, { "index": 0.5, "rgb": [0, 204, 197] }, { "index": 0.63, "rgb": [0, 247, 146] }, { "index": 0.75, "rgb": [0, 255, 88] }, { "index": 0.88, "rgb": [40, 255, 8] }, { "index": 1, "rgb": [147, 255, 0] }],
                "rainbow-soft": [{ "index": 0, "rgb": [125, 0, 179] }, { "index": 0.1, "rgb": [199, 0, 180] }, { "index": 0.2, "rgb": [255, 0, 121] }, { "index": 0.3, "rgb": [255, 108, 0] }, { "index": 0.4, "rgb": [222, 194, 0] }, { "index": 0.5, "rgb": [150, 255, 0] }, { "index": 0.6, "rgb": [0, 255, 55] }, { "index": 0.7, "rgb": [0, 246, 150] }, { "index": 0.8, "rgb": [50, 167, 222] }, { "index": 0.9, "rgb": [103, 51, 235] }, { "index": 1, "rgb": [124, 0, 186] }],
                "bathymetry": [{ "index": 0, "rgb": [40, 26, 44] }, { "index": 0.13, "rgb": [59, 49, 90] }, { "index": 0.25, "rgb": [64, 76, 139] }, { "index": 0.38, "rgb": [63, 110, 151] }, { "index": 0.5, "rgb": [72, 142, 158] }, { "index": 0.63, "rgb": [85, 174, 163] }, { "index": 0.75, "rgb": [120, 206, 163] }, { "index": 0.88, "rgb": [187, 230, 172] }, { "index": 1, "rgb": [253, 254, 204] }],
                "cdom": [{ "index": 0, "rgb": [47, 15, 62] }, { "index": 0.13, "rgb": [87, 23, 86] }, { "index": 0.25, "rgb": [130, 28, 99] }, { "index": 0.38, "rgb": [171, 41, 96] }, { "index": 0.5, "rgb": [206, 67, 86] }, { "index": 0.63, "rgb": [230, 106, 84] }, { "index": 0.75, "rgb": [242, 149, 103] }, { "index": 0.88, "rgb": [249, 193, 135] }, { "index": 1, "rgb": [254, 237, 176] }],
                "chlorophyll": [{ "index": 0, "rgb": [18, 36, 20] }, { "index": 0.13, "rgb": [25, 63, 41] }, { "index": 0.25, "rgb": [24, 91, 59] }, { "index": 0.38, "rgb": [13, 119, 72] }, { "index": 0.5, "rgb": [18, 148, 80] }, { "index": 0.63, "rgb": [80, 173, 89] }, { "index": 0.75, "rgb": [132, 196, 122] }, { "index": 0.88, "rgb": [175, 221, 162] }, { "index": 1, "rgb": [215, 249, 208] }],
                "density": [{ "index": 0, "rgb": [54, 14, 36] }, { "index": 0.13, "rgb": [89, 23, 80] }, { "index": 0.25, "rgb": [110, 45, 132] }, { "index": 0.38, "rgb": [120, 77, 178] }, { "index": 0.5, "rgb": [120, 113, 213] }, { "index": 0.63, "rgb": [115, 151, 228] }, { "index": 0.75, "rgb": [134, 185, 227] }, { "index": 0.88, "rgb": [177, 214, 227] }, { "index": 1, "rgb": [230, 241, 241] }],
                "freesurface-blue": [{ "index": 0, "rgb": [30, 4, 110] }, { "index": 0.13, "rgb": [47, 14, 176] }, { "index": 0.25, "rgb": [41, 45, 236] }, { "index": 0.38, "rgb": [25, 99, 212] }, { "index": 0.5, "rgb": [68, 131, 200] }, { "index": 0.63, "rgb": [114, 156, 197] }, { "index": 0.75, "rgb": [157, 181, 203] }, { "index": 0.88, "rgb": [200, 208, 216] }, { "index": 1, "rgb": [241, 237, 236] }],
                "freesurface-red": [{ "index": 0, "rgb": [60, 9, 18] }, { "index": 0.13, "rgb": [100, 17, 27] }, { "index": 0.25, "rgb": [142, 20, 29] }, { "index": 0.38, "rgb": [177, 43, 27] }, { "index": 0.5, "rgb": [192, 87, 63] }, { "index": 0.63, "rgb": [205, 125, 105] }, { "index": 0.75, "rgb": [216, 162, 148] }, { "index": 0.88, "rgb": [227, 199, 193] }, { "index": 1, "rgb": [241, 237, 236] }],
                "oxygen": [{ "index": 0, "rgb": [64, 5, 5] }, { "index": 0.13, "rgb": [106, 6, 15] }, { "index": 0.25, "rgb": [144, 26, 7] }, { "index": 0.38, "rgb": [168, 64, 3] }, { "index": 0.5, "rgb": [188, 100, 4] }, { "index": 0.63, "rgb": [206, 136, 11] }, { "index": 0.75, "rgb": [220, 174, 25] }, { "index": 0.88, "rgb": [231, 215, 44] }, { "index": 1, "rgb": [248, 254, 105] }],
                "par": [{ "index": 0, "rgb": [51, 20, 24] }, { "index": 0.13, "rgb": [90, 32, 35] }, { "index": 0.25, "rgb": [129, 44, 34] }, { "index": 0.38, "rgb": [159, 68, 25] }, { "index": 0.5, "rgb": [182, 99, 19] }, { "index": 0.63, "rgb": [199, 134, 22] }, { "index": 0.75, "rgb": [212, 171, 35] }, { "index": 0.88, "rgb": [221, 210, 54] }, { "index": 1, "rgb": [225, 253, 75] }],
                "phase": [{ "index": 0, "rgb": [145, 105, 18] }, { "index": 0.13, "rgb": [184, 71, 38] }, { "index": 0.25, "rgb": [186, 58, 115] }, { "index": 0.38, "rgb": [160, 71, 185] }, { "index": 0.5, "rgb": [110, 97, 218] }, { "index": 0.63, "rgb": [50, 123, 164] }, { "index": 0.75, "rgb": [31, 131, 110] }, { "index": 0.88, "rgb": [77, 129, 34] }, { "index": 1, "rgb": [145, 105, 18] }],
                "salinity": [{ "index": 0, "rgb": [42, 24, 108] }, { "index": 0.13, "rgb": [33, 50, 162] }, { "index": 0.25, "rgb": [15, 90, 145] }, { "index": 0.38, "rgb": [40, 118, 137] }, { "index": 0.5, "rgb": [59, 146, 135] }, { "index": 0.63, "rgb": [79, 175, 126] }, { "index": 0.75, "rgb": [120, 203, 104] }, { "index": 0.88, "rgb": [193, 221, 100] }, { "index": 1, "rgb": [253, 239, 154] }],
                "temperature": [{ "index": 0, "rgb": [4, 35, 51] }, { "index": 0.13, "rgb": [23, 51, 122] }, { "index": 0.25, "rgb": [85, 59, 157] }, { "index": 0.38, "rgb": [129, 79, 143] }, { "index": 0.5, "rgb": [175, 95, 130] }, { "index": 0.63, "rgb": [222, 112, 101] }, { "index": 0.75, "rgb": [249, 146, 66] }, { "index": 0.88, "rgb": [249, 196, 65] }, { "index": 1, "rgb": [232, 250, 91] }],
                "turbidity": [{ "index": 0, "rgb": [34, 31, 27] }, { "index": 0.13, "rgb": [65, 50, 41] }, { "index": 0.25, "rgb": [98, 69, 52] }, { "index": 0.38, "rgb": [131, 89, 57] }, { "index": 0.5, "rgb": [161, 112, 59] }, { "index": 0.63, "rgb": [185, 140, 66] }, { "index": 0.75, "rgb": [202, 174, 88] }, { "index": 0.88, "rgb": [216, 209, 126] }, { "index": 1, "rgb": [233, 246, 171] }],
                "velocity-blue": [{ "index": 0, "rgb": [17, 32, 64] }, { "index": 0.13, "rgb": [35, 52, 116] }, { "index": 0.25, "rgb": [29, 81, 156] }, { "index": 0.38, "rgb": [31, 113, 162] }, { "index": 0.5, "rgb": [50, 144, 169] }, { "index": 0.63, "rgb": [87, 173, 176] }, { "index": 0.75, "rgb": [149, 196, 189] }, { "index": 0.88, "rgb": [203, 221, 211] }, { "index": 1, "rgb": [254, 251, 230] }],
                "velocity-green": [{ "index": 0, "rgb": [23, 35, 19] }, { "index": 0.13, "rgb": [24, 64, 38] }, { "index": 0.25, "rgb": [11, 95, 45] }, { "index": 0.38, "rgb": [39, 123, 35] }, { "index": 0.5, "rgb": [95, 146, 12] }, { "index": 0.63, "rgb": [152, 165, 18] }, { "index": 0.75, "rgb": [201, 186, 69] }, { "index": 0.88, "rgb": [233, 216, 137] }, { "index": 1, "rgb": [255, 253, 205] }],
                "cubehelix": [{ "index": 0, "rgb": [0, 0, 0] }, { "index": 0.07, "rgb": [22, 5, 59] }, { "index": 0.13, "rgb": [60, 4, 105] }, { "index": 0.2, "rgb": [109, 1, 135] }, { "index": 0.27, "rgb": [161, 0, 147] }, { "index": 0.33, "rgb": [210, 2, 142] }, { "index": 0.4, "rgb": [251, 11, 123] }, { "index": 0.47, "rgb": [255, 29, 97] }, { "index": 0.53, "rgb": [255, 54, 69] }, { "index": 0.6, "rgb": [255, 85, 46] }, { "index": 0.67, "rgb": [255, 120, 34] }, { "index": 0.73, "rgb": [255, 157, 37] }, { "index": 0.8, "rgb": [241, 191, 57] }, { "index": 0.87, "rgb": [224, 220, 93] }, { "index": 0.93, "rgb": [218, 241, 142] }, { "index": 1, "rgb": [227, 253, 198] }]
              };
            }
          ),
          /***/
          3711: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = surfaceNets;
              var generateContourExtractor = __webpack_require__2(2640);
              var zeroCrossings = __webpack_require__2(781);
              var allFns = {
                "2d": function(genContour, order, dtype) {
                  var contour = genContour({
                    order,
                    scalarArguments: 3,
                    getters: dtype === "generic" ? [0] : void 0,
                    phase: function phaseFunc(p, a, b, c) {
                      return p > c | 0;
                    },
                    vertex: function vertexFunc(d0, d1, v0, v1, v2, v3, p0, p1, p2, p3, a, b, c) {
                      var m = (p0 << 0) + (p1 << 1) + (p2 << 2) + (p3 << 3) | 0;
                      if (m === 0 || m === 15) {
                        return;
                      }
                      switch (m) {
                        case 0:
                          a.push([d0 - 0.5, d1 - 0.5]);
                          break;
                        case 1:
                          a.push([d0 - 0.25 - 0.25 * (v1 + v0 - 2 * c) / (v0 - v1), d1 - 0.25 - 0.25 * (v2 + v0 - 2 * c) / (v0 - v2)]);
                          break;
                        case 2:
                          a.push([d0 - 0.75 - 0.25 * (-v1 - v0 + 2 * c) / (v1 - v0), d1 - 0.25 - 0.25 * (v3 + v1 - 2 * c) / (v1 - v3)]);
                          break;
                        case 3:
                          a.push([d0 - 0.5, d1 - 0.5 - 0.5 * (v2 + v0 + v3 + v1 - 4 * c) / (v0 - v2 + v1 - v3)]);
                          break;
                        case 4:
                          a.push([d0 - 0.25 - 0.25 * (v3 + v2 - 2 * c) / (v2 - v3), d1 - 0.75 - 0.25 * (-v2 - v0 + 2 * c) / (v2 - v0)]);
                          break;
                        case 5:
                          a.push([d0 - 0.5 - 0.5 * (v1 + v0 + v3 + v2 - 4 * c) / (v0 - v1 + v2 - v3), d1 - 0.5]);
                          break;
                        case 6:
                          a.push([d0 - 0.5 - 0.25 * (-v1 - v0 + v3 + v2) / (v1 - v0 + v2 - v3), d1 - 0.5 - 0.25 * (-v2 - v0 + v3 + v1) / (v2 - v0 + v1 - v3)]);
                          break;
                        case 7:
                          a.push([d0 - 0.75 - 0.25 * (v3 + v2 - 2 * c) / (v2 - v3), d1 - 0.75 - 0.25 * (v3 + v1 - 2 * c) / (v1 - v3)]);
                          break;
                        case 8:
                          a.push([d0 - 0.75 - 0.25 * (-v3 - v2 + 2 * c) / (v3 - v2), d1 - 0.75 - 0.25 * (-v3 - v1 + 2 * c) / (v3 - v1)]);
                          break;
                        case 9:
                          a.push([d0 - 0.5 - 0.25 * (v1 + v0 + -v3 - v2) / (v0 - v1 + v3 - v2), d1 - 0.5 - 0.25 * (v2 + v0 + -v3 - v1) / (v0 - v2 + v3 - v1)]);
                          break;
                        case 10:
                          a.push([d0 - 0.5 - 0.5 * (-v1 - v0 + -v3 - v2 + 4 * c) / (v1 - v0 + v3 - v2), d1 - 0.5]);
                          break;
                        case 11:
                          a.push([d0 - 0.25 - 0.25 * (-v3 - v2 + 2 * c) / (v3 - v2), d1 - 0.75 - 0.25 * (v2 + v0 - 2 * c) / (v0 - v2)]);
                          break;
                        case 12:
                          a.push([d0 - 0.5, d1 - 0.5 - 0.5 * (-v2 - v0 + -v3 - v1 + 4 * c) / (v2 - v0 + v3 - v1)]);
                          break;
                        case 13:
                          a.push([d0 - 0.75 - 0.25 * (v1 + v0 - 2 * c) / (v0 - v1), d1 - 0.25 - 0.25 * (-v3 - v1 + 2 * c) / (v3 - v1)]);
                          break;
                        case 14:
                          a.push([d0 - 0.25 - 0.25 * (-v1 - v0 + 2 * c) / (v1 - v0), d1 - 0.25 - 0.25 * (-v2 - v0 + 2 * c) / (v2 - v0)]);
                          break;
                        case 15:
                          a.push([d0 - 0.5, d1 - 0.5]);
                          break;
                      }
                    },
                    cell: function cellFunc(v0, v1, c0, c1, p0, p1, a, b, c) {
                      if (p0) {
                        b.push([v0, v1]);
                      } else {
                        b.push([v1, v0]);
                      }
                    }
                  });
                  return function(array, level) {
                    var verts = [], cells = [];
                    contour(array, verts, cells, level);
                    return { positions: verts, cells };
                  };
                }
              };
              function buildSurfaceNets(order, dtype) {
                var inKey = order.length + "d";
                var fn = allFns[inKey];
                if (fn) return fn(generateContourExtractor, order, dtype);
              }
              function mesh1D(array, level) {
                var zc = zeroCrossings(array, level);
                var n = zc.length;
                var npos = new Array(n);
                var ncel = new Array(n);
                for (var i = 0; i < n; ++i) {
                  npos[i] = [zc[i]];
                  ncel[i] = [i];
                }
                return {
                  positions: npos,
                  cells: ncel
                };
              }
              var CACHE = {};
              function surfaceNets(array, level) {
                if (array.dimension <= 0) {
                  return { positions: [], cells: [] };
                } else if (array.dimension === 1) {
                  return mesh1D(array, level);
                }
                var typesig = array.order.join() + "-" + array.dtype;
                var proc = CACHE[typesig];
                var level = +level || 0;
                if (!proc) {
                  proc = CACHE[typesig] = buildSurfaceNets(array.order, array.dtype);
                }
                return proc(array, level);
              }
            }
          ),
          /***/
          3750: (
            /***/
            function(module2) {
              module2.exports = dot;
              function dot(a, b) {
                return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
              }
            }
          ),
          /***/
          3778: (
            /***/
            function(__unused_webpack_module, exports2) {
              exports2.read = function(buffer, offset, isLE, mLen, nBytes) {
                var e, m;
                var eLen = nBytes * 8 - mLen - 1;
                var eMax = (1 << eLen) - 1;
                var eBias = eMax >> 1;
                var nBits = -7;
                var i = isLE ? nBytes - 1 : 0;
                var d = isLE ? -1 : 1;
                var s = buffer[offset + i];
                i += d;
                e = s & (1 << -nBits) - 1;
                s >>= -nBits;
                nBits += eLen;
                for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
                }
                m = e & (1 << -nBits) - 1;
                e >>= -nBits;
                nBits += mLen;
                for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
                }
                if (e === 0) {
                  e = 1 - eBias;
                } else if (e === eMax) {
                  return m ? NaN : (s ? -1 : 1) * Infinity;
                } else {
                  m = m + Math.pow(2, mLen);
                  e = e - eBias;
                }
                return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
              };
              exports2.write = function(buffer, value, offset, isLE, mLen, nBytes) {
                var e, m, c;
                var eLen = nBytes * 8 - mLen - 1;
                var eMax = (1 << eLen) - 1;
                var eBias = eMax >> 1;
                var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
                var i = isLE ? 0 : nBytes - 1;
                var d = isLE ? 1 : -1;
                var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
                value = Math.abs(value);
                if (isNaN(value) || value === Infinity) {
                  m = isNaN(value) ? 1 : 0;
                  e = eMax;
                } else {
                  e = Math.floor(Math.log(value) / Math.LN2);
                  if (value * (c = Math.pow(2, -e)) < 1) {
                    e--;
                    c *= 2;
                  }
                  if (e + eBias >= 1) {
                    value += rt / c;
                  } else {
                    value += rt * Math.pow(2, 1 - eBias);
                  }
                  if (value * c >= 2) {
                    e++;
                    c /= 2;
                  }
                  if (e + eBias >= eMax) {
                    m = 0;
                    e = eMax;
                  } else if (e + eBias >= 1) {
                    m = (value * c - 1) * Math.pow(2, mLen);
                    e = e + eBias;
                  } else {
                    m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
                    e = 0;
                  }
                }
                for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
                }
                e = e << mLen | m;
                eLen += mLen;
                for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
                }
                buffer[offset + i - d] |= s * 128;
              };
            }
          ),
          /***/
          3788: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var compareCells = __webpack_require__2(8507);
              var parity = __webpack_require__2(2419);
              module2.exports = compareOrientedCells;
              function compareOrientedCells(a, b) {
                return compareCells(a, b) || parity(a) - parity(b);
              }
            }
          ),
          /***/
          3837: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createAxes;
              var createText = __webpack_require__2(4935);
              var createLines = __webpack_require__2(501);
              var createBackground = __webpack_require__2(5304);
              var getCubeProperties = __webpack_require__2(6429);
              var Ticks = __webpack_require__2(6444);
              var identity2 = new Float32Array([
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ]);
              var ab = ArrayBuffer;
              var dv = DataView;
              function isTypedArray(a) {
                return ab.isView(a) && !(a instanceof dv);
              }
              function isArrayOrTypedArray(a) {
                return Array.isArray(a) || isTypedArray(a);
              }
              function copyVec3(a, b) {
                a[0] = b[0];
                a[1] = b[1];
                a[2] = b[2];
                return a;
              }
              function Axes(gl2) {
                this.gl = gl2;
                this.pixelRatio = 1;
                this.bounds = [
                  [-10, -10, -10],
                  [10, 10, 10]
                ];
                this.ticks = [[], [], []];
                this.autoTicks = true;
                this.tickSpacing = [1, 1, 1];
                this.tickEnable = [true, true, true];
                this.tickFont = ["sans-serif", "sans-serif", "sans-serif"];
                this.tickFontStyle = ["normal", "normal", "normal"];
                this.tickFontWeight = ["normal", "normal", "normal"];
                this.tickFontVariant = ["normal", "normal", "normal"];
                this.tickSize = [12, 12, 12];
                this.tickAngle = [0, 0, 0];
                this.tickAlign = ["auto", "auto", "auto"];
                this.tickColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.tickPad = [10, 10, 10];
                this.lastCubeProps = {
                  cubeEdges: [0, 0, 0],
                  axis: [0, 0, 0]
                };
                this.labels = ["x", "y", "z"];
                this.labelEnable = [true, true, true];
                this.labelFont = ["sans-serif", "sans-serif", "sans-serif"];
                this.labelFontStyle = ["normal", "normal", "normal"];
                this.labelFontWeight = ["normal", "normal", "normal"];
                this.labelFontVariant = ["normal", "normal", "normal"];
                this.labelSize = [20, 20, 20];
                this.labelAngle = [0, 0, 0];
                this.labelAlign = ["auto", "auto", "auto"];
                this.labelColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.labelPad = [10, 10, 10];
                this.lineEnable = [true, true, true];
                this.lineMirror = [false, false, false];
                this.lineWidth = [1, 1, 1];
                this.lineColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.lineTickEnable = [true, true, true];
                this.lineTickMirror = [false, false, false];
                this.lineTickLength = [0, 0, 0];
                this.lineTickWidth = [1, 1, 1];
                this.lineTickColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.gridEnable = [true, true, true];
                this.gridWidth = [1, 1, 1];
                this.gridColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.zeroEnable = [true, true, true];
                this.zeroLineColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.zeroLineWidth = [2, 2, 2];
                this.backgroundEnable = [false, false, false];
                this.backgroundColor = [
                  [0.8, 0.8, 0.8, 0.5],
                  [0.8, 0.8, 0.8, 0.5],
                  [0.8, 0.8, 0.8, 0.5]
                ];
                this._firstInit = true;
                this._text = null;
                this._lines = null;
                this._background = createBackground(gl2);
              }
              var proto = Axes.prototype;
              proto.update = function(options) {
                options = options || {};
                function parseOption(nest, cons, name2) {
                  if (name2 in options) {
                    var opt = options[name2];
                    var prev = this[name2];
                    var next;
                    if (nest ? isArrayOrTypedArray(opt) && isArrayOrTypedArray(opt[0]) : isArrayOrTypedArray(opt)) {
                      this[name2] = next = [cons(opt[0]), cons(opt[1]), cons(opt[2])];
                    } else {
                      this[name2] = next = [cons(opt), cons(opt), cons(opt)];
                    }
                    for (var i2 = 0; i2 < 3; ++i2) {
                      if (next[i2] !== prev[i2]) {
                        return true;
                      }
                    }
                  }
                  return false;
                }
                var NUMBER = parseOption.bind(this, false, Number);
                var BOOLEAN = parseOption.bind(this, false, Boolean);
                var STRING = parseOption.bind(this, false, String);
                var COLOR = parseOption.bind(this, true, function(v) {
                  if (isArrayOrTypedArray(v)) {
                    if (v.length === 3) {
                      return [+v[0], +v[1], +v[2], 1];
                    } else if (v.length === 4) {
                      return [+v[0], +v[1], +v[2], +v[3]];
                    }
                  }
                  return [0, 0, 0, 1];
                });
                var nextTicks;
                var ticksUpdate = false;
                var boundsChanged = false;
                if ("bounds" in options) {
                  var bounds = options.bounds;
                  i_loop:
                    for (var i = 0; i < 2; ++i) {
                      for (var j = 0; j < 3; ++j) {
                        if (bounds[i][j] !== this.bounds[i][j]) {
                          boundsChanged = true;
                        }
                        this.bounds[i][j] = bounds[i][j];
                      }
                    }
                }
                if ("ticks" in options) {
                  nextTicks = options.ticks;
                  ticksUpdate = true;
                  this.autoTicks = false;
                  for (var i = 0; i < 3; ++i) {
                    this.tickSpacing[i] = 0;
                  }
                } else if (NUMBER("tickSpacing")) {
                  this.autoTicks = true;
                  boundsChanged = true;
                }
                if (this._firstInit) {
                  if (!("ticks" in options || "tickSpacing" in options)) {
                    this.autoTicks = true;
                  }
                  boundsChanged = true;
                  ticksUpdate = true;
                  this._firstInit = false;
                }
                if (boundsChanged && this.autoTicks) {
                  nextTicks = Ticks.create(this.bounds, this.tickSpacing);
                  ticksUpdate = true;
                }
                if (ticksUpdate) {
                  for (var i = 0; i < 3; ++i) {
                    nextTicks[i].sort(function(a, b) {
                      return a.x - b.x;
                    });
                  }
                  if (Ticks.equal(nextTicks, this.ticks)) {
                    ticksUpdate = false;
                  } else {
                    this.ticks = nextTicks;
                  }
                }
                BOOLEAN("tickEnable");
                if (STRING("tickFont")) ticksUpdate = true;
                if (STRING("tickFontStyle")) ticksUpdate = true;
                if (STRING("tickFontWeight")) ticksUpdate = true;
                if (STRING("tickFontVariant")) ticksUpdate = true;
                NUMBER("tickSize");
                NUMBER("tickAngle");
                NUMBER("tickPad");
                COLOR("tickColor");
                var labelUpdate = STRING("labels");
                if (STRING("labelFont")) labelUpdate = true;
                if (STRING("labelFontStyle")) labelUpdate = true;
                if (STRING("labelFontWeight")) labelUpdate = true;
                if (STRING("labelFontVariant")) labelUpdate = true;
                BOOLEAN("labelEnable");
                NUMBER("labelSize");
                NUMBER("labelPad");
                COLOR("labelColor");
                BOOLEAN("lineEnable");
                BOOLEAN("lineMirror");
                NUMBER("lineWidth");
                COLOR("lineColor");
                BOOLEAN("lineTickEnable");
                BOOLEAN("lineTickMirror");
                NUMBER("lineTickLength");
                NUMBER("lineTickWidth");
                COLOR("lineTickColor");
                BOOLEAN("gridEnable");
                NUMBER("gridWidth");
                COLOR("gridColor");
                BOOLEAN("zeroEnable");
                COLOR("zeroLineColor");
                NUMBER("zeroLineWidth");
                BOOLEAN("backgroundEnable");
                COLOR("backgroundColor");
                var labelFontOpts = [
                  {
                    family: this.labelFont[0],
                    style: this.labelFontStyle[0],
                    weight: this.labelFontWeight[0],
                    variant: this.labelFontVariant[0]
                  },
                  {
                    family: this.labelFont[1],
                    style: this.labelFontStyle[1],
                    weight: this.labelFontWeight[1],
                    variant: this.labelFontVariant[1]
                  },
                  {
                    family: this.labelFont[2],
                    style: this.labelFontStyle[2],
                    weight: this.labelFontWeight[2],
                    variant: this.labelFontVariant[2]
                  }
                ];
                var tickFontOpts = [
                  {
                    family: this.tickFont[0],
                    style: this.tickFontStyle[0],
                    weight: this.tickFontWeight[0],
                    variant: this.tickFontVariant[0]
                  },
                  {
                    family: this.tickFont[1],
                    style: this.tickFontStyle[1],
                    weight: this.tickFontWeight[1],
                    variant: this.tickFontVariant[1]
                  },
                  {
                    family: this.tickFont[2],
                    style: this.tickFontStyle[2],
                    weight: this.tickFontWeight[2],
                    variant: this.tickFontVariant[2]
                  }
                ];
                if (!this._text) {
                  this._text = createText(
                    this.gl,
                    this.bounds,
                    this.labels,
                    labelFontOpts,
                    this.ticks,
                    tickFontOpts
                  );
                } else if (this._text && (labelUpdate || ticksUpdate)) {
                  this._text.update(
                    this.bounds,
                    this.labels,
                    labelFontOpts,
                    this.ticks,
                    tickFontOpts
                  );
                }
                if (this._lines && ticksUpdate) {
                  this._lines.dispose();
                  this._lines = null;
                }
                if (!this._lines) {
                  this._lines = createLines(this.gl, this.bounds, this.ticks);
                }
              };
              function OffsetInfo() {
                this.primalOffset = [0, 0, 0];
                this.primalMinor = [0, 0, 0];
                this.mirrorOffset = [0, 0, 0];
                this.mirrorMinor = [0, 0, 0];
              }
              var LINE_OFFSET = [new OffsetInfo(), new OffsetInfo(), new OffsetInfo()];
              function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) {
                var primalOffset = result.primalOffset;
                var primalMinor = result.primalMinor;
                var dualOffset = result.mirrorOffset;
                var dualMinor = result.mirrorMinor;
                var e = cubeEdges[i];
                for (var j = 0; j < 3; ++j) {
                  if (i === j) {
                    continue;
                  }
                  var a = primalOffset, b = dualOffset, c = primalMinor, d = dualMinor;
                  if (e & 1 << j) {
                    a = dualOffset;
                    b = primalOffset;
                    c = dualMinor;
                    d = primalMinor;
                  }
                  a[j] = bounds[0][j];
                  b[j] = bounds[1][j];
                  if (cubeAxis[j] > 0) {
                    c[j] = -1;
                    d[j] = 0;
                  } else {
                    c[j] = 0;
                    d[j] = 1;
                  }
                }
              }
              var CUBE_ENABLE = [0, 0, 0];
              var DEFAULT_PARAMS = {
                model: identity2,
                view: identity2,
                projection: identity2,
                _ortho: false
              };
              proto.isOpaque = function() {
                return true;
              };
              proto.isTransparent = function() {
                return false;
              };
              proto.drawTransparent = function(params) {
              };
              var ALIGN_OPTION_AUTO = 0;
              var PRIMAL_MINOR = [0, 0, 0];
              var MIRROR_MINOR = [0, 0, 0];
              var PRIMAL_OFFSET = [0, 0, 0];
              proto.draw = function(params) {
                params = params || DEFAULT_PARAMS;
                var gl2 = this.gl;
                var model = params.model || identity2;
                var view = params.view || identity2;
                var projection = params.projection || identity2;
                var bounds = this.bounds;
                var isOrtho = params._ortho || false;
                var cubeParams = getCubeProperties(model, view, projection, bounds, isOrtho);
                var cubeEdges = cubeParams.cubeEdges;
                var cubeAxis = cubeParams.axis;
                var cx = view[12];
                var cy = view[13];
                var cz = view[14];
                var cw = view[15];
                var orthoFix = isOrtho ? 2 : 1;
                var pixelScaleF = orthoFix * this.pixelRatio * (projection[3] * cx + projection[7] * cy + projection[11] * cz + projection[15] * cw) / gl2.drawingBufferHeight;
                for (var i = 0; i < 3; ++i) {
                  this.lastCubeProps.cubeEdges[i] = cubeEdges[i];
                  this.lastCubeProps.axis[i] = cubeAxis[i];
                }
                var lineOffset = LINE_OFFSET;
                for (var i = 0; i < 3; ++i) {
                  computeLineOffset(
                    LINE_OFFSET[i],
                    i,
                    this.bounds,
                    cubeEdges,
                    cubeAxis
                  );
                }
                var gl2 = this.gl;
                var cubeEnable = CUBE_ENABLE;
                for (var i = 0; i < 3; ++i) {
                  if (this.backgroundEnable[i]) {
                    cubeEnable[i] = cubeAxis[i];
                  } else {
                    cubeEnable[i] = 0;
                  }
                }
                this._background.draw(
                  model,
                  view,
                  projection,
                  bounds,
                  cubeEnable,
                  this.backgroundColor
                );
                this._lines.bind(
                  model,
                  view,
                  projection,
                  this
                );
                for (var i = 0; i < 3; ++i) {
                  var x = [0, 0, 0];
                  if (cubeAxis[i] > 0) {
                    x[i] = bounds[1][i];
                  } else {
                    x[i] = bounds[0][i];
                  }
                  for (var j = 0; j < 2; ++j) {
                    var u = (i + 1 + j) % 3;
                    var v = (i + 1 + (j ^ 1)) % 3;
                    if (this.gridEnable[u]) {
                      this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u] * this.pixelRatio);
                    }
                  }
                  for (var j = 0; j < 2; ++j) {
                    var u = (i + 1 + j) % 3;
                    var v = (i + 1 + (j ^ 1)) % 3;
                    if (this.zeroEnable[v]) {
                      if (Math.min(bounds[0][v], bounds[1][v]) <= 0 && Math.max(bounds[0][v], bounds[1][v]) >= 0) {
                        this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v] * this.pixelRatio);
                      }
                    }
                  }
                }
                for (var i = 0; i < 3; ++i) {
                  if (this.lineEnable[i]) {
                    this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i] * this.pixelRatio);
                  }
                  if (this.lineMirror[i]) {
                    this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i] * this.pixelRatio);
                  }
                  var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor);
                  var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor);
                  var tickLength = this.lineTickLength;
                  for (var j = 0; j < 3; ++j) {
                    var scaleFactor = pixelScaleF / model[5 * j];
                    primalMinor[j] *= tickLength[j] * scaleFactor;
                    mirrorMinor[j] *= tickLength[j] * scaleFactor;
                  }
                  if (this.lineTickEnable[i]) {
                    this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i] * this.pixelRatio);
                  }
                  if (this.lineTickMirror[i]) {
                    this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i] * this.pixelRatio);
                  }
                }
                this._lines.unbind();
                this._text.bind(
                  model,
                  view,
                  projection,
                  this.pixelRatio
                );
                var alignOpt;
                var hv_ratio = 0.5;
                var enableAlign;
                var alignDir;
                function alignTo(i2) {
                  alignDir = [0, 0, 0];
                  alignDir[i2] = 1;
                }
                function solveTickAlignments(i2, minor2, major2) {
                  var i1 = (i2 + 1) % 3;
                  var i22 = (i2 + 2) % 3;
                  var A2 = minor2[i1];
                  var B2 = minor2[i22];
                  var C2 = major2[i1];
                  var D2 = major2[i22];
                  if (A2 > 0 && D2 > 0) {
                    alignTo(i1);
                    return;
                  } else if (A2 > 0 && D2 < 0) {
                    alignTo(i1);
                    return;
                  } else if (A2 < 0 && D2 > 0) {
                    alignTo(i1);
                    return;
                  } else if (A2 < 0 && D2 < 0) {
                    alignTo(i1);
                    return;
                  } else if (B2 > 0 && C2 > 0) {
                    alignTo(i22);
                    return;
                  } else if (B2 > 0 && C2 < 0) {
                    alignTo(i22);
                    return;
                  } else if (B2 < 0 && C2 > 0) {
                    alignTo(i22);
                    return;
                  } else if (B2 < 0 && C2 < 0) {
                    alignTo(i22);
                    return;
                  }
                }
                for (var i = 0; i < 3; ++i) {
                  var minor = lineOffset[i].primalMinor;
                  var major = lineOffset[i].mirrorMinor;
                  var offset = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset);
                  for (var j = 0; j < 3; ++j) {
                    if (this.lineTickEnable[i]) {
                      offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0) / model[5 * j];
                    }
                  }
                  var axis = [0, 0, 0];
                  axis[i] = 1;
                  if (this.tickEnable[i]) {
                    if (this.tickAngle[i] === -3600) {
                      this.tickAngle[i] = 0;
                      this.tickAlign[i] = "auto";
                    } else {
                      this.tickAlign[i] = -1;
                    }
                    enableAlign = 1;
                    alignOpt = [this.tickAlign[i], hv_ratio, enableAlign];
                    if (alignOpt[0] === "auto") alignOpt[0] = ALIGN_OPTION_AUTO;
                    else alignOpt[0] = parseInt("" + alignOpt[0]);
                    alignDir = [0, 0, 0];
                    solveTickAlignments(i, minor, major);
                    for (var j = 0; j < 3; ++j) {
                      offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5 * j];
                    }
                    this._text.drawTicks(
                      i,
                      this.tickSize[i],
                      this.tickAngle[i],
                      offset,
                      this.tickColor[i],
                      axis,
                      alignDir,
                      alignOpt
                    );
                  }
                  if (this.labelEnable[i]) {
                    enableAlign = 0;
                    alignDir = [0, 0, 0];
                    if (this.labels[i].length > 4) {
                      alignTo(i);
                      enableAlign = 1;
                    }
                    alignOpt = [this.labelAlign[i], hv_ratio, enableAlign];
                    if (alignOpt[0] === "auto") alignOpt[0] = ALIGN_OPTION_AUTO;
                    else alignOpt[0] = parseInt("" + alignOpt[0]);
                    for (var j = 0; j < 3; ++j) {
                      offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5 * j];
                    }
                    offset[i] += 0.5 * (bounds[0][i] + bounds[1][i]);
                    this._text.drawLabel(
                      i,
                      this.labelSize[i],
                      this.labelAngle[i],
                      offset,
                      this.labelColor[i],
                      [0, 0, 0],
                      alignDir,
                      alignOpt
                    );
                  }
                }
                this._text.unbind();
              };
              proto.dispose = function() {
                this._text.dispose();
                this._lines.dispose();
                this._background.dispose();
                this._lines = null;
                this._text = null;
                this._background = null;
                this.gl = null;
              };
              function createAxes(gl2, options) {
                var axes = new Axes(gl2);
                axes.update(options);
                return axes;
              }
            }
          ),
          /***/
          3840: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = createRBTree;
              var RED = 0;
              var BLACK = 1;
              function RBNode(color2, key, value, left, right, count) {
                this._color = color2;
                this.key = key;
                this.value = value;
                this.left = left;
                this.right = right;
                this._count = count;
              }
              function cloneNode(node) {
                return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count);
              }
              function repaint(color2, node) {
                return new RBNode(color2, node.key, node.value, node.left, node.right, node._count);
              }
              function recount(node) {
                node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0);
              }
              function RedBlackTree(compare, root) {
                this._compare = compare;
                this.root = root;
              }
              var proto = RedBlackTree.prototype;
              Object.defineProperty(proto, "keys", {
                get: function() {
                  var result = [];
                  this.forEach(function(k, v) {
                    result.push(k);
                  });
                  return result;
                }
              });
              Object.defineProperty(proto, "values", {
                get: function() {
                  var result = [];
                  this.forEach(function(k, v) {
                    result.push(v);
                  });
                  return result;
                }
              });
              Object.defineProperty(proto, "length", {
                get: function() {
                  if (this.root) {
                    return this.root._count;
                  }
                  return 0;
                }
              });
              proto.insert = function(key, value) {
                var cmp = this._compare;
                var n = this.root;
                var n_stack = [];
                var d_stack = [];
                while (n) {
                  var d = cmp(key, n.key);
                  n_stack.push(n);
                  d_stack.push(d);
                  if (d <= 0) {
                    n = n.left;
                  } else {
                    n = n.right;
                  }
                }
                n_stack.push(new RBNode(RED, key, value, null, null, 1));
                for (var s = n_stack.length - 2; s >= 0; --s) {
                  var n = n_stack[s];
                  if (d_stack[s] <= 0) {
                    n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s + 1], n.right, n._count + 1);
                  } else {
                    n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s + 1], n._count + 1);
                  }
                }
                for (var s = n_stack.length - 1; s > 1; --s) {
                  var p = n_stack[s - 1];
                  var n = n_stack[s];
                  if (p._color === BLACK || n._color === BLACK) {
                    break;
                  }
                  var pp = n_stack[s - 2];
                  if (pp.left === p) {
                    if (p.left === n) {
                      var y = pp.right;
                      if (y && y._color === RED) {
                        p._color = BLACK;
                        pp.right = repaint(BLACK, y);
                        pp._color = RED;
                        s -= 1;
                      } else {
                        pp._color = RED;
                        pp.left = p.right;
                        p._color = BLACK;
                        p.right = pp;
                        n_stack[s - 2] = p;
                        n_stack[s - 1] = n;
                        recount(pp);
                        recount(p);
                        if (s >= 3) {
                          var ppp = n_stack[s - 3];
                          if (ppp.left === pp) {
                            ppp.left = p;
                          } else {
                            ppp.right = p;
                          }
                        }
                        break;
                      }
                    } else {
                      var y = pp.right;
                      if (y && y._color === RED) {
                        p._color = BLACK;
                        pp.right = repaint(BLACK, y);
                        pp._color = RED;
                        s -= 1;
                      } else {
                        p.right = n.left;
                        pp._color = RED;
                        pp.left = n.right;
                        n._color = BLACK;
                        n.left = p;
                        n.right = pp;
                        n_stack[s - 2] = n;
                        n_stack[s - 1] = p;
                        recount(pp);
                        recount(p);
                        recount(n);
                        if (s >= 3) {
                          var ppp = n_stack[s - 3];
                          if (ppp.left === pp) {
                            ppp.left = n;
                          } else {
                            ppp.right = n;
                          }
                        }
                        break;
                      }
                    }
                  } else {
                    if (p.right === n) {
                      var y = pp.left;
                      if (y && y._color === RED) {
                        p._color = BLACK;
                        pp.left = repaint(BLACK, y);
                        pp._color = RED;
                        s -= 1;
                      } else {
                        pp._color = RED;
                        pp.right = p.left;
                        p._color = BLACK;
                        p.left = pp;
                        n_stack[s - 2] = p;
                        n_stack[s - 1] = n;
                        recount(pp);
                        recount(p);
                        if (s >= 3) {
                          var ppp = n_stack[s - 3];
                          if (ppp.right === pp) {
                            ppp.right = p;
                          } else {
                            ppp.left = p;
                          }
                        }
                        break;
                      }
                    } else {
                      var y = pp.left;
                      if (y && y._color === RED) {
                        p._color = BLACK;
                        pp.left = repaint(BLACK, y);
                        pp._color = RED;
                        s -= 1;
                      } else {
                        p.left = n.right;
                        pp._color = RED;
                        pp.right = n.left;
                        n._color = BLACK;
                        n.right = p;
                        n.left = pp;
                        n_stack[s - 2] = n;
                        n_stack[s - 1] = p;
                        recount(pp);
                        recount(p);
                        recount(n);
                        if (s >= 3) {
                          var ppp = n_stack[s - 3];
                          if (ppp.right === pp) {
                            ppp.right = n;
                          } else {
                            ppp.left = n;
                          }
                        }
                        break;
                      }
                    }
                  }
                }
                n_stack[0]._color = BLACK;
                return new RedBlackTree(cmp, n_stack[0]);
              };
              function doVisitFull(visit, node) {
                if (node.left) {
                  var v = doVisitFull(visit, node.left);
                  if (v) {
                    return v;
                  }
                }
                var v = visit(node.key, node.value);
                if (v) {
                  return v;
                }
                if (node.right) {
                  return doVisitFull(visit, node.right);
                }
              }
              function doVisitHalf(lo, compare, visit, node) {
                var l = compare(lo, node.key);
                if (l <= 0) {
                  if (node.left) {
                    var v = doVisitHalf(lo, compare, visit, node.left);
                    if (v) {
                      return v;
                    }
                  }
                  var v = visit(node.key, node.value);
                  if (v) {
                    return v;
                  }
                }
                if (node.right) {
                  return doVisitHalf(lo, compare, visit, node.right);
                }
              }
              function doVisit(lo, hi, compare, visit, node) {
                var l = compare(lo, node.key);
                var h = compare(hi, node.key);
                var v;
                if (l <= 0) {
                  if (node.left) {
                    v = doVisit(lo, hi, compare, visit, node.left);
                    if (v) {
                      return v;
                    }
                  }
                  if (h > 0) {
                    v = visit(node.key, node.value);
                    if (v) {
                      return v;
                    }
                  }
                }
                if (h > 0 && node.right) {
                  return doVisit(lo, hi, compare, visit, node.right);
                }
              }
              proto.forEach = function rbTreeForEach(visit, lo, hi) {
                if (!this.root) {
                  return;
                }
                switch (arguments.length) {
                  case 1:
                    return doVisitFull(visit, this.root);
                  // removed by dead control flow
                  case 2:
                    return doVisitHalf(lo, this._compare, visit, this.root);
                  // removed by dead control flow
                  case 3:
                    if (this._compare(lo, hi) >= 0) {
                      return;
                    }
                    return doVisit(lo, hi, this._compare, visit, this.root);
                }
              };
              Object.defineProperty(proto, "begin", {
                get: function() {
                  var stack = [];
                  var n = this.root;
                  while (n) {
                    stack.push(n);
                    n = n.left;
                  }
                  return new RedBlackTreeIterator(this, stack);
                }
              });
              Object.defineProperty(proto, "end", {
                get: function() {
                  var stack = [];
                  var n = this.root;
                  while (n) {
                    stack.push(n);
                    n = n.right;
                  }
                  return new RedBlackTreeIterator(this, stack);
                }
              });
              proto.at = function(idx) {
                if (idx < 0) {
                  return new RedBlackTreeIterator(this, []);
                }
                var n = this.root;
                var stack = [];
                while (true) {
                  stack.push(n);
                  if (n.left) {
                    if (idx < n.left._count) {
                      n = n.left;
                      continue;
                    }
                    idx -= n.left._count;
                  }
                  if (!idx) {
                    return new RedBlackTreeIterator(this, stack);
                  }
                  idx -= 1;
                  if (n.right) {
                    if (idx >= n.right._count) {
                      break;
                    }
                    n = n.right;
                  } else {
                    break;
                  }
                }
                return new RedBlackTreeIterator(this, []);
              };
              proto.ge = function(key) {
                var cmp = this._compare;
                var n = this.root;
                var stack = [];
                var last_ptr = 0;
                while (n) {
                  var d = cmp(key, n.key);
                  stack.push(n);
                  if (d <= 0) {
                    last_ptr = stack.length;
                  }
                  if (d <= 0) {
                    n = n.left;
                  } else {
                    n = n.right;
                  }
                }
                stack.length = last_ptr;
                return new RedBlackTreeIterator(this, stack);
              };
              proto.gt = function(key) {
                var cmp = this._compare;
                var n = this.root;
                var stack = [];
                var last_ptr = 0;
                while (n) {
                  var d = cmp(key, n.key);
                  stack.push(n);
                  if (d < 0) {
                    last_ptr = stack.length;
                  }
                  if (d < 0) {
                    n = n.left;
                  } else {
                    n = n.right;
                  }
                }
                stack.length = last_ptr;
                return new RedBlackTreeIterator(this, stack);
              };
              proto.lt = function(key) {
                var cmp = this._compare;
                var n = this.root;
                var stack = [];
                var last_ptr = 0;
                while (n) {
                  var d = cmp(key, n.key);
                  stack.push(n);
                  if (d > 0) {
                    last_ptr = stack.length;
                  }
                  if (d <= 0) {
                    n = n.left;
                  } else {
                    n = n.right;
                  }
                }
                stack.length = last_ptr;
                return new RedBlackTreeIterator(this, stack);
              };
              proto.le = function(key) {
                var cmp = this._compare;
                var n = this.root;
                var stack = [];
                var last_ptr = 0;
                while (n) {
                  var d = cmp(key, n.key);
                  stack.push(n);
                  if (d >= 0) {
                    last_ptr = stack.length;
                  }
                  if (d < 0) {
                    n = n.left;
                  } else {
                    n = n.right;
                  }
                }
                stack.length = last_ptr;
                return new RedBlackTreeIterator(this, stack);
              };
              proto.find = function(key) {
                var cmp = this._compare;
                var n = this.root;
                var stack = [];
                while (n) {
                  var d = cmp(key, n.key);
                  stack.push(n);
                  if (d === 0) {
                    return new RedBlackTreeIterator(this, stack);
                  }
                  if (d <= 0) {
                    n = n.left;
                  } else {
                    n = n.right;
                  }
                }
                return new RedBlackTreeIterator(this, []);
              };
              proto.remove = function(key) {
                var iter = this.find(key);
                if (iter) {
                  return iter.remove();
                }
                return this;
              };
              proto.get = function(key) {
                var cmp = this._compare;
                var n = this.root;
                while (n) {
                  var d = cmp(key, n.key);
                  if (d === 0) {
                    return n.value;
                  }
                  if (d <= 0) {
                    n = n.left;
                  } else {
                    n = n.right;
                  }
                }
                return;
              };
              function RedBlackTreeIterator(tree, stack) {
                this.tree = tree;
                this._stack = stack;
              }
              var iproto = RedBlackTreeIterator.prototype;
              Object.defineProperty(iproto, "valid", {
                get: function() {
                  return this._stack.length > 0;
                }
              });
              Object.defineProperty(iproto, "node", {
                get: function() {
                  if (this._stack.length > 0) {
                    return this._stack[this._stack.length - 1];
                  }
                  return null;
                },
                enumerable: true
              });
              iproto.clone = function() {
                return new RedBlackTreeIterator(this.tree, this._stack.slice());
              };
              function swapNode(n, v) {
                n.key = v.key;
                n.value = v.value;
                n.left = v.left;
                n.right = v.right;
                n._color = v._color;
                n._count = v._count;
              }
              function fixDoubleBlack(stack) {
                var n, p, s, z;
                for (var i = stack.length - 1; i >= 0; --i) {
                  n = stack[i];
                  if (i === 0) {
                    n._color = BLACK;
                    return;
                  }
                  p = stack[i - 1];
                  if (p.left === n) {
                    s = p.right;
                    if (s.right && s.right._color === RED) {
                      s = p.right = cloneNode(s);
                      z = s.right = cloneNode(s.right);
                      p.right = s.left;
                      s.left = p;
                      s.right = z;
                      s._color = p._color;
                      n._color = BLACK;
                      p._color = BLACK;
                      z._color = BLACK;
                      recount(p);
                      recount(s);
                      if (i > 1) {
                        var pp = stack[i - 2];
                        if (pp.left === p) {
                          pp.left = s;
                        } else {
                          pp.right = s;
                        }
                      }
                      stack[i - 1] = s;
                      return;
                    } else if (s.left && s.left._color === RED) {
                      s = p.right = cloneNode(s);
                      z = s.left = cloneNode(s.left);
                      p.right = z.left;
                      s.left = z.right;
                      z.left = p;
                      z.right = s;
                      z._color = p._color;
                      p._color = BLACK;
                      s._color = BLACK;
                      n._color = BLACK;
                      recount(p);
                      recount(s);
                      recount(z);
                      if (i > 1) {
                        var pp = stack[i - 2];
                        if (pp.left === p) {
                          pp.left = z;
                        } else {
                          pp.right = z;
                        }
                      }
                      stack[i - 1] = z;
                      return;
                    }
                    if (s._color === BLACK) {
                      if (p._color === RED) {
                        p._color = BLACK;
                        p.right = repaint(RED, s);
                        return;
                      } else {
                        p.right = repaint(RED, s);
                        continue;
                      }
                    } else {
                      s = cloneNode(s);
                      p.right = s.left;
                      s.left = p;
                      s._color = p._color;
                      p._color = RED;
                      recount(p);
                      recount(s);
                      if (i > 1) {
                        var pp = stack[i - 2];
                        if (pp.left === p) {
                          pp.left = s;
                        } else {
                          pp.right = s;
                        }
                      }
                      stack[i - 1] = s;
                      stack[i] = p;
                      if (i + 1 < stack.length) {
                        stack[i + 1] = n;
                      } else {
                        stack.push(n);
                      }
                      i = i + 2;
                    }
                  } else {
                    s = p.left;
                    if (s.left && s.left._color === RED) {
                      s = p.left = cloneNode(s);
                      z = s.left = cloneNode(s.left);
                      p.left = s.right;
                      s.right = p;
                      s.left = z;
                      s._color = p._color;
                      n._color = BLACK;
                      p._color = BLACK;
                      z._color = BLACK;
                      recount(p);
                      recount(s);
                      if (i > 1) {
                        var pp = stack[i - 2];
                        if (pp.right === p) {
                          pp.right = s;
                        } else {
                          pp.left = s;
                        }
                      }
                      stack[i - 1] = s;
                      return;
                    } else if (s.right && s.right._color === RED) {
                      s = p.left = cloneNode(s);
                      z = s.right = cloneNode(s.right);
                      p.left = z.right;
                      s.right = z.left;
                      z.right = p;
                      z.left = s;
                      z._color = p._color;
                      p._color = BLACK;
                      s._color = BLACK;
                      n._color = BLACK;
                      recount(p);
                      recount(s);
                      recount(z);
                      if (i > 1) {
                        var pp = stack[i - 2];
                        if (pp.right === p) {
                          pp.right = z;
                        } else {
                          pp.left = z;
                        }
                      }
                      stack[i - 1] = z;
                      return;
                    }
                    if (s._color === BLACK) {
                      if (p._color === RED) {
                        p._color = BLACK;
                        p.left = repaint(RED, s);
                        return;
                      } else {
                        p.left = repaint(RED, s);
                        continue;
                      }
                    } else {
                      s = cloneNode(s);
                      p.left = s.right;
                      s.right = p;
                      s._color = p._color;
                      p._color = RED;
                      recount(p);
                      recount(s);
                      if (i > 1) {
                        var pp = stack[i - 2];
                        if (pp.right === p) {
                          pp.right = s;
                        } else {
                          pp.left = s;
                        }
                      }
                      stack[i - 1] = s;
                      stack[i] = p;
                      if (i + 1 < stack.length) {
                        stack[i + 1] = n;
                      } else {
                        stack.push(n);
                      }
                      i = i + 2;
                    }
                  }
                }
              }
              iproto.remove = function() {
                var stack = this._stack;
                if (stack.length === 0) {
                  return this.tree;
                }
                var cstack = new Array(stack.length);
                var n = stack[stack.length - 1];
                cstack[cstack.length - 1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count);
                for (var i = stack.length - 2; i >= 0; --i) {
                  var n = stack[i];
                  if (n.left === stack[i + 1]) {
                    cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i + 1], n.right, n._count);
                  } else {
                    cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count);
                  }
                }
                n = cstack[cstack.length - 1];
                if (n.left && n.right) {
                  var split = cstack.length;
                  n = n.left;
                  while (n.right) {
                    cstack.push(n);
                    n = n.right;
                  }
                  var v = cstack[split - 1];
                  cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count));
                  cstack[split - 1].key = n.key;
                  cstack[split - 1].value = n.value;
                  for (var i = cstack.length - 2; i >= split; --i) {
                    n = cstack[i];
                    cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count);
                  }
                  cstack[split - 1].left = cstack[split];
                }
                n = cstack[cstack.length - 1];
                if (n._color === RED) {
                  var p = cstack[cstack.length - 2];
                  if (p.left === n) {
                    p.left = null;
                  } else if (p.right === n) {
                    p.right = null;
                  }
                  cstack.pop();
                  for (var i = 0; i < cstack.length; ++i) {
                    cstack[i]._count--;
                  }
                  return new RedBlackTree(this.tree._compare, cstack[0]);
                } else {
                  if (n.left || n.right) {
                    if (n.left) {
                      swapNode(n, n.left);
                    } else if (n.right) {
                      swapNode(n, n.right);
                    }
                    n._color = BLACK;
                    for (var i = 0; i < cstack.length - 1; ++i) {
                      cstack[i]._count--;
                    }
                    return new RedBlackTree(this.tree._compare, cstack[0]);
                  } else if (cstack.length === 1) {
                    return new RedBlackTree(this.tree._compare, null);
                  } else {
                    for (var i = 0; i < cstack.length; ++i) {
                      cstack[i]._count--;
                    }
                    var parent = cstack[cstack.length - 2];
                    fixDoubleBlack(cstack);
                    if (parent.left === n) {
                      parent.left = null;
                    } else {
                      parent.right = null;
                    }
                  }
                }
                return new RedBlackTree(this.tree._compare, cstack[0]);
              };
              Object.defineProperty(iproto, "key", {
                get: function() {
                  if (this._stack.length > 0) {
                    return this._stack[this._stack.length - 1].key;
                  }
                  return;
                },
                enumerable: true
              });
              Object.defineProperty(iproto, "value", {
                get: function() {
                  if (this._stack.length > 0) {
                    return this._stack[this._stack.length - 1].value;
                  }
                  return;
                },
                enumerable: true
              });
              Object.defineProperty(iproto, "index", {
                get: function() {
                  var idx = 0;
                  var stack = this._stack;
                  if (stack.length === 0) {
                    var r = this.tree.root;
                    if (r) {
                      return r._count;
                    }
                    return 0;
                  } else if (stack[stack.length - 1].left) {
                    idx = stack[stack.length - 1].left._count;
                  }
                  for (var s = stack.length - 2; s >= 0; --s) {
                    if (stack[s + 1] === stack[s].right) {
                      ++idx;
                      if (stack[s].left) {
                        idx += stack[s].left._count;
                      }
                    }
                  }
                  return idx;
                },
                enumerable: true
              });
              iproto.next = function() {
                var stack = this._stack;
                if (stack.length === 0) {
                  return;
                }
                var n = stack[stack.length - 1];
                if (n.right) {
                  n = n.right;
                  while (n) {
                    stack.push(n);
                    n = n.left;
                  }
                } else {
                  stack.pop();
                  while (stack.length > 0 && stack[stack.length - 1].right === n) {
                    n = stack[stack.length - 1];
                    stack.pop();
                  }
                }
              };
              Object.defineProperty(iproto, "hasNext", {
                get: function() {
                  var stack = this._stack;
                  if (stack.length === 0) {
                    return false;
                  }
                  if (stack[stack.length - 1].right) {
                    return true;
                  }
                  for (var s = stack.length - 1; s > 0; --s) {
                    if (stack[s - 1].left === stack[s]) {
                      return true;
                    }
                  }
                  return false;
                }
              });
              iproto.update = function(value) {
                var stack = this._stack;
                if (stack.length === 0) {
                  throw new Error("Can't update empty node!");
                }
                var cstack = new Array(stack.length);
                var n = stack[stack.length - 1];
                cstack[cstack.length - 1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count);
                for (var i = stack.length - 2; i >= 0; --i) {
                  n = stack[i];
                  if (n.left === stack[i + 1]) {
                    cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i + 1], n.right, n._count);
                  } else {
                    cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i + 1], n._count);
                  }
                }
                return new RedBlackTree(this.tree._compare, cstack[0]);
              };
              iproto.prev = function() {
                var stack = this._stack;
                if (stack.length === 0) {
                  return;
                }
                var n = stack[stack.length - 1];
                if (n.left) {
                  n = n.left;
                  while (n) {
                    stack.push(n);
                    n = n.right;
                  }
                } else {
                  stack.pop();
                  while (stack.length > 0 && stack[stack.length - 1].left === n) {
                    n = stack[stack.length - 1];
                    stack.pop();
                  }
                }
              };
              Object.defineProperty(iproto, "hasPrev", {
                get: function() {
                  var stack = this._stack;
                  if (stack.length === 0) {
                    return false;
                  }
                  if (stack[stack.length - 1].left) {
                    return true;
                  }
                  for (var s = stack.length - 1; s > 0; --s) {
                    if (stack[s - 1].right === stack[s]) {
                      return true;
                    }
                  }
                  return false;
                }
              });
              function defaultCompare(a, b) {
                if (a < b) {
                  return -1;
                }
                if (a > b) {
                  return 1;
                }
                return 0;
              }
              function createRBTree(compare) {
                return new RedBlackTree(compare || defaultCompare, null);
              }
            }
          ),
          /***/
          3865: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var rationalize = __webpack_require__2(869);
              module2.exports = add;
              function add(a, b) {
                return rationalize(
                  a[0].mul(b[1]).add(b[0].mul(a[1])),
                  a[1].mul(b[1])
                );
              }
            }
          ),
          /***/
          3952: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = affineHull;
              var orient = __webpack_require__2(3250);
              function linearlyIndependent(points, d) {
                var nhull = new Array(d + 1);
                for (var i = 0; i < points.length; ++i) {
                  nhull[i] = points[i];
                }
                for (var i = 0; i <= points.length; ++i) {
                  for (var j = points.length; j <= d; ++j) {
                    var x = new Array(d);
                    for (var k = 0; k < d; ++k) {
                      x[k] = Math.pow(j + 1 - i, k);
                    }
                    nhull[j] = x;
                  }
                  var o = orient.apply(void 0, nhull);
                  if (o) {
                    return true;
                  }
                }
                return false;
              }
              function affineHull(points) {
                var n = points.length;
                if (n === 0) {
                  return [];
                }
                if (n === 1) {
                  return [0];
                }
                var d = points[0].length;
                var frame = [points[0]];
                var index = [0];
                for (var i = 1; i < n; ++i) {
                  frame.push(points[i]);
                  if (!linearlyIndependent(frame, d)) {
                    frame.pop();
                    continue;
                  }
                  index.push(i);
                  if (index.length === d + 1) {
                    return index;
                  }
                }
                return index;
              }
            }
          ),
          /***/
          3990: (
            /***/
            function(module2) {
              module2.exports = copy;
              function copy(out, a) {
                out[0] = a[0];
                out[1] = a[1];
                out[2] = a[2];
                return out;
              }
            }
          ),
          /***/
          4008: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(6690);
            }
          ),
          /***/
          4025: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var db = __webpack_require__2(2361);
              var ctz = __webpack_require__2(8828).countTrailingZeros;
              module2.exports = ctzNumber;
              function ctzNumber(x) {
                var l = ctz(db.lo(x));
                if (l < 32) {
                  return l;
                }
                var h = ctz(db.hi(x));
                if (h > 20) {
                  return 52;
                }
                return h + 32;
              }
            }
          ),
          /***/
          4040: (
            /***/
            function(module2) {
              module2.exports = ortho;
              function ortho(out, left, right, bottom, top, near, far) {
                var lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far);
                out[0] = -2 * lr;
                out[1] = 0;
                out[2] = 0;
                out[3] = 0;
                out[4] = 0;
                out[5] = -2 * bt;
                out[6] = 0;
                out[7] = 0;
                out[8] = 0;
                out[9] = 0;
                out[10] = 2 * nf;
                out[11] = 0;
                out[12] = (left + right) * lr;
                out[13] = (top + bottom) * bt;
                out[14] = (far + near) * nf;
                out[15] = 1;
                return out;
              }
              ;
            }
          ),
          /***/
          4041: (
            /***/
            function(module2) {
              module2.exports = transformQuat;
              function transformQuat(out, a, q) {
                var x = a[0], y = a[1], z = a[2], qx = q[0], qy = q[1], qz = q[2], qw = q[3], ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
                out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
                out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
                out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
                out[3] = a[3];
                return out;
              }
            }
          ),
          /***/
          4081: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = quatFromFrame;
              function quatFromFrame(out, rx, ry, rz, ux, uy, uz, fx, fy, fz) {
                var tr = rx + uy + fz;
                if (l > 0) {
                  var l = Math.sqrt(tr + 1);
                  out[0] = 0.5 * (uz - fy) / l;
                  out[1] = 0.5 * (fx - rz) / l;
                  out[2] = 0.5 * (ry - uy) / l;
                  out[3] = 0.5 * l;
                } else {
                  var tf = Math.max(rx, uy, fz);
                  var l = Math.sqrt(2 * tf - tr + 1);
                  if (rx >= tf) {
                    out[0] = 0.5 * l;
                    out[1] = 0.5 * (ux + ry) / l;
                    out[2] = 0.5 * (fx + rz) / l;
                    out[3] = 0.5 * (uz - fy) / l;
                  } else if (uy >= tf) {
                    out[0] = 0.5 * (ry + ux) / l;
                    out[1] = 0.5 * l;
                    out[2] = 0.5 * (fy + uz) / l;
                    out[3] = 0.5 * (fx - rz) / l;
                  } else {
                    out[0] = 0.5 * (rz + fx) / l;
                    out[1] = 0.5 * (uz + fy) / l;
                    out[2] = 0.5 * l;
                    out[3] = 0.5 * (ry - ux) / l;
                  }
                }
                return out;
              }
            }
          ),
          /***/
          4100: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var createCamera = __webpack_require__2(4437);
              var createAxes = __webpack_require__2(3837);
              var axesRanges = __webpack_require__2(5445);
              var createSpikes = __webpack_require__2(4449);
              var createSelect = __webpack_require__2(3589);
              var createFBO = __webpack_require__2(2260);
              var drawTriangle = __webpack_require__2(7169);
              var mouseChange = __webpack_require__2(351);
              var perspective = __webpack_require__2(4772);
              var ortho = __webpack_require__2(4040);
              var createShader = __webpack_require__2(799);
              var isMobile = __webpack_require__2(9216)({ tablet: true, featureDetect: true });
              module2.exports = {
                createScene,
                createCamera
              };
              function MouseSelect() {
                this.mouse = [-1, -1];
                this.screen = null;
                this.distance = Infinity;
                this.index = null;
                this.dataCoordinate = null;
                this.dataPosition = null;
                this.object = null;
                this.data = null;
              }
              function getContext(canvas, options) {
                var gl2 = null;
                try {
                  gl2 = canvas.getContext("webgl", options);
                  if (!gl2) {
                    gl2 = canvas.getContext("experimental-webgl", options);
                  }
                } catch (e) {
                  return null;
                }
                return gl2;
              }
              function roundUpPow10(x) {
                var y = Math.round(Math.log(Math.abs(x)) / Math.log(10));
                if (y < 0) {
                  var base = Math.round(Math.pow(10, -y));
                  return Math.ceil(x * base) / base;
                } else if (y > 0) {
                  var base = Math.round(Math.pow(10, y));
                  return Math.ceil(x / base) * base;
                }
                return Math.ceil(x);
              }
              function defaultBool(x) {
                if (typeof x === "boolean") {
                  return x;
                }
                return true;
              }
              function createScene(options) {
                options = options || {};
                options.camera = options.camera || {};
                var canvas = options.canvas;
                if (!canvas) {
                  canvas = document.createElement("canvas");
                  if (options.container) {
                    var container = options.container;
                    container.appendChild(canvas);
                  } else {
                    document.body.appendChild(canvas);
                  }
                }
                var gl2 = options.gl;
                if (!gl2) {
                  if (options.glOptions) {
                    isMobile = !!options.glOptions.preserveDrawingBuffer;
                  }
                  gl2 = getContext(
                    canvas,
                    options.glOptions || {
                      premultipliedAlpha: true,
                      antialias: true,
                      preserveDrawingBuffer: isMobile
                    }
                  );
                }
                if (!gl2) {
                  throw new Error("webgl not supported");
                }
                var bounds = options.bounds || [[-10, -10, -10], [10, 10, 10]];
                var selection = new MouseSelect();
                var accumBuffer = createFBO(
                  gl2,
                  gl2.drawingBufferWidth,
                  gl2.drawingBufferHeight,
                  {
                    preferFloat: !isMobile
                  }
                );
                var accumShader = createShader(gl2);
                var isOrtho = options.cameraObject && options.cameraObject._ortho === true || options.camera.projection && options.camera.projection.type === "orthographic" || false;
                var cameraOptions = {
                  eye: options.camera.eye || [2, 0, 0],
                  center: options.camera.center || [0, 0, 0],
                  up: options.camera.up || [0, 1, 0],
                  zoomMin: options.camera.zoomMax || 0.1,
                  zoomMax: options.camera.zoomMin || 100,
                  mode: options.camera.mode || "turntable",
                  _ortho: isOrtho
                };
                var axesOptions = options.axes || {};
                var axes = createAxes(gl2, axesOptions);
                axes.enable = !axesOptions.disable;
                var spikeOptions = options.spikes || {};
                var spikes = createSpikes(gl2, spikeOptions);
                var objects = [];
                var pickBufferIds = [];
                var pickBufferCount = [];
                var pickBuffers = [];
                var dirty = true;
                var pickDirty = true;
                var projection = new Array(16);
                var model = new Array(16);
                var cameraParams = {
                  view: null,
                  projection,
                  model,
                  _ortho: false
                };
                var pickDirty = true;
                var viewShape = [gl2.drawingBufferWidth, gl2.drawingBufferHeight];
                var camera = options.cameraObject || createCamera(canvas, cameraOptions);
                var scene = {
                  gl: gl2,
                  contextLost: false,
                  pixelRatio: options.pixelRatio || 1,
                  canvas,
                  selection,
                  camera,
                  axes,
                  axesPixels: null,
                  spikes,
                  bounds,
                  objects,
                  shape: viewShape,
                  aspect: options.aspectRatio || [1, 1, 1],
                  pickRadius: options.pickRadius || 10,
                  zNear: options.zNear || 0.01,
                  zFar: options.zFar || 1e3,
                  fovy: options.fovy || Math.PI / 4,
                  clearColor: options.clearColor || [0, 0, 0, 0],
                  autoResize: defaultBool(options.autoResize),
                  autoBounds: defaultBool(options.autoBounds),
                  autoScale: !!options.autoScale,
                  autoCenter: defaultBool(options.autoCenter),
                  clipToBounds: defaultBool(options.clipToBounds),
                  snapToData: !!options.snapToData,
                  onselect: options.onselect || null,
                  onrender: options.onrender || null,
                  onclick: options.onclick || null,
                  cameraParams,
                  oncontextloss: null,
                  mouseListener: null,
                  _stopped: false,
                  getAspectratio: function() {
                    return {
                      x: this.aspect[0],
                      y: this.aspect[1],
                      z: this.aspect[2]
                    };
                  },
                  setAspectratio: function(aspectratio) {
                    this.aspect[0] = aspectratio.x;
                    this.aspect[1] = aspectratio.y;
                    this.aspect[2] = aspectratio.z;
                    pickDirty = true;
                  },
                  setBounds: function(axisIndex, range) {
                    this.bounds[0][axisIndex] = range.min;
                    this.bounds[1][axisIndex] = range.max;
                  },
                  setClearColor: function(clearColor) {
                    this.clearColor = clearColor;
                  },
                  clearRGBA: function() {
                    this.gl.clearColor(
                      this.clearColor[0],
                      this.clearColor[1],
                      this.clearColor[2],
                      this.clearColor[3]
                    );
                    this.gl.clear(
                      this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT
                    );
                  }
                };
                var pickShape = [gl2.drawingBufferWidth / scene.pixelRatio | 0, gl2.drawingBufferHeight / scene.pixelRatio | 0];
                function resizeListener() {
                  if (scene._stopped) {
                    return;
                  }
                  if (!scene.autoResize) {
                    return;
                  }
                  var parent = canvas.parentNode;
                  var width = 1;
                  var height = 1;
                  if (parent && parent !== document.body) {
                    width = parent.clientWidth;
                    height = parent.clientHeight;
                  } else {
                    width = window.innerWidth;
                    height = window.innerHeight;
                  }
                  var nextWidth = Math.ceil(width * scene.pixelRatio) | 0;
                  var nextHeight = Math.ceil(height * scene.pixelRatio) | 0;
                  if (nextWidth !== canvas.width || nextHeight !== canvas.height) {
                    canvas.width = nextWidth;
                    canvas.height = nextHeight;
                    var style = canvas.style;
                    style.position = style.position || "absolute";
                    style.left = "0px";
                    style.top = "0px";
                    style.width = width + "px";
                    style.height = height + "px";
                    dirty = true;
                  }
                }
                if (scene.autoResize) {
                  resizeListener();
                }
                window.addEventListener("resize", resizeListener);
                function reallocPickIds() {
                  var numObjs = objects.length;
                  var numPick = pickBuffers.length;
                  for (var i = 0; i < numPick; ++i) {
                    pickBufferCount[i] = 0;
                  }
                  obj_loop:
                    for (var i = 0; i < numObjs; ++i) {
                      var obj = objects[i];
                      var pickCount = obj.pickSlots;
                      if (!pickCount) {
                        pickBufferIds[i] = -1;
                        continue;
                      }
                      for (var j = 0; j < numPick; ++j) {
                        if (pickBufferCount[j] + pickCount < 255) {
                          pickBufferIds[i] = j;
                          obj.setPickBase(pickBufferCount[j] + 1);
                          pickBufferCount[j] += pickCount;
                          continue obj_loop;
                        }
                      }
                      var nbuffer = createSelect(gl2, viewShape);
                      pickBufferIds[i] = numPick;
                      pickBuffers.push(nbuffer);
                      pickBufferCount.push(pickCount);
                      obj.setPickBase(1);
                      numPick += 1;
                    }
                  while (numPick > 0 && pickBufferCount[numPick - 1] === 0) {
                    pickBufferCount.pop();
                    pickBuffers.pop().dispose();
                  }
                }
                scene.update = function(options2) {
                  if (scene._stopped) {
                    return;
                  }
                  options2 = options2 || {};
                  dirty = true;
                  pickDirty = true;
                };
                scene.add = function(obj) {
                  if (scene._stopped) {
                    return;
                  }
                  obj.axes = axes;
                  objects.push(obj);
                  pickBufferIds.push(-1);
                  dirty = true;
                  pickDirty = true;
                  reallocPickIds();
                };
                scene.remove = function(obj) {
                  if (scene._stopped) {
                    return;
                  }
                  var idx = objects.indexOf(obj);
                  if (idx < 0) {
                    return;
                  }
                  objects.splice(idx, 1);
                  pickBufferIds.pop();
                  dirty = true;
                  pickDirty = true;
                  reallocPickIds();
                };
                scene.dispose = function() {
                  if (scene._stopped) {
                    return;
                  }
                  scene._stopped = true;
                  window.removeEventListener("resize", resizeListener);
                  canvas.removeEventListener("webglcontextlost", checkContextLoss);
                  scene.mouseListener.enabled = false;
                  if (scene.contextLost) {
                    return;
                  }
                  axes.dispose();
                  spikes.dispose();
                  for (var i = 0; i < objects.length; ++i) {
                    objects[i].dispose();
                  }
                  accumBuffer.dispose();
                  for (var i = 0; i < pickBuffers.length; ++i) {
                    pickBuffers[i].dispose();
                  }
                  accumShader.dispose();
                  gl2 = null;
                  axes = null;
                  spikes = null;
                  objects = [];
                };
                scene._mouseRotating = false;
                scene._prevButtons = 0;
                scene.enableMouseListeners = function() {
                  scene.mouseListener = mouseChange(canvas, function(buttons, x, y) {
                    if (scene._stopped) {
                      return;
                    }
                    var numPick = pickBuffers.length;
                    var numObjs = objects.length;
                    var prevObj = selection.object;
                    selection.distance = Infinity;
                    selection.mouse[0] = x;
                    selection.mouse[1] = y;
                    selection.object = null;
                    selection.screen = null;
                    selection.dataCoordinate = selection.dataPosition = null;
                    var change = false;
                    if (buttons && scene._prevButtons) {
                      scene._mouseRotating = true;
                    } else {
                      if (scene._mouseRotating) {
                        pickDirty = true;
                      }
                      scene._mouseRotating = false;
                      for (var i = 0; i < numPick; ++i) {
                        var result = pickBuffers[i].query(x, pickShape[1] - y - 1, scene.pickRadius);
                        if (result) {
                          if (result.distance > selection.distance) {
                            continue;
                          }
                          for (var j = 0; j < numObjs; ++j) {
                            var obj = objects[j];
                            if (pickBufferIds[j] !== i) {
                              continue;
                            }
                            var objPick = obj.pick(result);
                            if (objPick) {
                              selection.buttons = buttons;
                              selection.screen = result.coord;
                              selection.distance = result.distance;
                              selection.object = obj;
                              selection.index = objPick.distance;
                              selection.dataPosition = objPick.position;
                              selection.dataCoordinate = objPick.dataCoordinate;
                              selection.data = objPick;
                              change = true;
                            }
                          }
                        }
                      }
                    }
                    if (prevObj && prevObj !== selection.object) {
                      if (prevObj.highlight) {
                        prevObj.highlight(null);
                      }
                      dirty = true;
                    }
                    if (selection.object) {
                      if (selection.object.highlight) {
                        selection.object.highlight(selection.data);
                      }
                      dirty = true;
                    }
                    change = change || selection.object !== prevObj;
                    if (change && scene.onselect) {
                      scene.onselect(selection);
                    }
                    if (buttons & 1 && !(scene._prevButtons & 1) && scene.onclick) {
                      scene.onclick(selection);
                    }
                    scene._prevButtons = buttons;
                  });
                };
                function checkContextLoss() {
                  if (scene.contextLost) {
                    return true;
                  }
                  if (gl2.isContextLost()) {
                    scene.contextLost = true;
                    scene.mouseListener.enabled = false;
                    scene.selection.object = null;
                    if (scene.oncontextloss) {
                      scene.oncontextloss();
                    }
                  }
                }
                canvas.addEventListener("webglcontextlost", checkContextLoss);
                function renderPick() {
                  if (checkContextLoss()) {
                    return;
                  }
                  gl2.colorMask(true, true, true, true);
                  gl2.depthMask(true);
                  gl2.disable(gl2.BLEND);
                  gl2.enable(gl2.DEPTH_TEST);
                  gl2.depthFunc(gl2.LEQUAL);
                  var numObjs = objects.length;
                  var numPick = pickBuffers.length;
                  for (var j = 0; j < numPick; ++j) {
                    var buf = pickBuffers[j];
                    buf.shape = pickShape;
                    buf.begin();
                    for (var i = 0; i < numObjs; ++i) {
                      if (pickBufferIds[i] !== j) {
                        continue;
                      }
                      var obj = objects[i];
                      if (obj.drawPick) {
                        obj.pixelRatio = 1;
                        obj.drawPick(cameraParams);
                      }
                    }
                    buf.end();
                  }
                }
                var nBounds = [
                  [Infinity, Infinity, Infinity],
                  [-Infinity, -Infinity, -Infinity]
                ];
                var prevBounds = [nBounds[0].slice(), nBounds[1].slice()];
                function redraw() {
                  if (checkContextLoss()) {
                    return;
                  }
                  resizeListener();
                  var cameraMoved = scene.camera.tick();
                  cameraParams.view = scene.camera.matrix;
                  dirty = dirty || cameraMoved;
                  pickDirty = pickDirty || cameraMoved;
                  axes.pixelRatio = scene.pixelRatio;
                  spikes.pixelRatio = scene.pixelRatio;
                  var numObjs = objects.length;
                  var lo = nBounds[0];
                  var hi = nBounds[1];
                  lo[0] = lo[1] = lo[2] = Infinity;
                  hi[0] = hi[1] = hi[2] = -Infinity;
                  for (var i = 0; i < numObjs; ++i) {
                    var obj = objects[i];
                    obj.pixelRatio = scene.pixelRatio;
                    obj.axes = scene.axes;
                    dirty = dirty || !!obj.dirty;
                    pickDirty = pickDirty || !!obj.dirty;
                    var obb = obj.bounds;
                    if (obb) {
                      var olo = obb[0];
                      var ohi = obb[1];
                      for (var j = 0; j < 3; ++j) {
                        lo[j] = Math.min(lo[j], olo[j]);
                        hi[j] = Math.max(hi[j], ohi[j]);
                      }
                    }
                  }
                  var bounds2 = scene.bounds;
                  if (scene.autoBounds) {
                    for (var j = 0; j < 3; ++j) {
                      if (hi[j] < lo[j]) {
                        lo[j] = -1;
                        hi[j] = 1;
                      } else {
                        if (lo[j] === hi[j]) {
                          lo[j] -= 1;
                          hi[j] += 1;
                        }
                        var padding = 0.05 * (hi[j] - lo[j]);
                        lo[j] = lo[j] - padding;
                        hi[j] = hi[j] + padding;
                      }
                      bounds2[0][j] = lo[j];
                      bounds2[1][j] = hi[j];
                    }
                  }
                  var boundsChanged = false;
                  for (var j = 0; j < 3; ++j) {
                    boundsChanged = boundsChanged || prevBounds[0][j] !== bounds2[0][j] || prevBounds[1][j] !== bounds2[1][j];
                    prevBounds[0][j] = bounds2[0][j];
                    prevBounds[1][j] = bounds2[1][j];
                  }
                  pickDirty = pickDirty || boundsChanged;
                  dirty = dirty || boundsChanged;
                  if (!dirty) {
                    return;
                  }
                  if (boundsChanged) {
                    var tickSpacing = [0, 0, 0];
                    for (var i = 0; i < 3; ++i) {
                      tickSpacing[i] = roundUpPow10((bounds2[1][i] - bounds2[0][i]) / 10);
                    }
                    if (axes.autoTicks) {
                      axes.update({
                        bounds: bounds2,
                        tickSpacing
                      });
                    } else {
                      axes.update({
                        bounds: bounds2
                      });
                    }
                  }
                  var width = gl2.drawingBufferWidth;
                  var height = gl2.drawingBufferHeight;
                  viewShape[0] = width;
                  viewShape[1] = height;
                  pickShape[0] = Math.max(width / scene.pixelRatio, 1) | 0;
                  pickShape[1] = Math.max(height / scene.pixelRatio, 1) | 0;
                  calcCameraParams(scene, isOrtho);
                  for (var i = 0; i < numObjs; ++i) {
                    var obj = objects[i];
                    obj.axesBounds = bounds2;
                    if (scene.clipToBounds) {
                      obj.clipBounds = bounds2;
                    }
                  }
                  if (selection.object) {
                    if (scene.snapToData) {
                      spikes.position = selection.dataCoordinate;
                    } else {
                      spikes.position = selection.dataPosition;
                    }
                    spikes.bounds = bounds2;
                  }
                  if (pickDirty) {
                    pickDirty = false;
                    renderPick();
                  }
                  scene.axesPixels = axesRanges(scene.axes, cameraParams, width, height);
                  if (scene.onrender) {
                    scene.onrender();
                  }
                  gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
                  gl2.viewport(0, 0, width, height);
                  scene.clearRGBA();
                  gl2.depthMask(true);
                  gl2.colorMask(true, true, true, true);
                  gl2.enable(gl2.DEPTH_TEST);
                  gl2.depthFunc(gl2.LEQUAL);
                  gl2.disable(gl2.BLEND);
                  gl2.disable(gl2.CULL_FACE);
                  var hasTransparent = false;
                  if (axes.enable) {
                    hasTransparent = hasTransparent || axes.isTransparent();
                    axes.draw(cameraParams);
                  }
                  spikes.axes = axes;
                  if (selection.object) {
                    spikes.draw(cameraParams);
                  }
                  gl2.disable(gl2.CULL_FACE);
                  for (var i = 0; i < numObjs; ++i) {
                    var obj = objects[i];
                    obj.axes = axes;
                    obj.pixelRatio = scene.pixelRatio;
                    if (obj.isOpaque && obj.isOpaque()) {
                      obj.draw(cameraParams);
                    }
                    if (obj.isTransparent && obj.isTransparent()) {
                      hasTransparent = true;
                    }
                  }
                  if (hasTransparent) {
                    accumBuffer.shape = viewShape;
                    accumBuffer.bind();
                    gl2.clear(gl2.DEPTH_BUFFER_BIT);
                    gl2.colorMask(false, false, false, false);
                    gl2.depthMask(true);
                    gl2.depthFunc(gl2.LESS);
                    if (axes.enable && axes.isTransparent()) {
                      axes.drawTransparent(cameraParams);
                    }
                    for (var i = 0; i < numObjs; ++i) {
                      var obj = objects[i];
                      if (obj.isOpaque && obj.isOpaque()) {
                        obj.draw(cameraParams);
                      }
                    }
                    gl2.enable(gl2.BLEND);
                    gl2.blendEquation(gl2.FUNC_ADD);
                    gl2.blendFunc(gl2.ONE, gl2.ONE_MINUS_SRC_ALPHA);
                    gl2.colorMask(true, true, true, true);
                    gl2.depthMask(false);
                    gl2.clearColor(0, 0, 0, 0);
                    gl2.clear(gl2.COLOR_BUFFER_BIT);
                    if (axes.isTransparent()) {
                      axes.drawTransparent(cameraParams);
                    }
                    for (var i = 0; i < numObjs; ++i) {
                      var obj = objects[i];
                      if (obj.isTransparent && obj.isTransparent()) {
                        obj.drawTransparent(cameraParams);
                      }
                    }
                    gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
                    gl2.blendFunc(gl2.ONE, gl2.ONE_MINUS_SRC_ALPHA);
                    gl2.disable(gl2.DEPTH_TEST);
                    accumShader.bind();
                    accumBuffer.color[0].bind(0);
                    accumShader.uniforms.accumBuffer = 0;
                    drawTriangle(gl2);
                    gl2.disable(gl2.BLEND);
                  }
                  dirty = false;
                  for (var i = 0; i < numObjs; ++i) {
                    objects[i].dirty = false;
                  }
                }
                function render() {
                  if (scene._stopped || scene.contextLost) {
                    return;
                  }
                  redraw();
                  requestAnimationFrame(render);
                }
                scene.enableMouseListeners();
                render();
                scene.redraw = function() {
                  if (scene._stopped) {
                    return;
                  }
                  dirty = true;
                  redraw();
                };
                return scene;
              }
              function calcCameraParams(scene, isOrtho) {
                var bounds = scene.bounds;
                var cameraParams = scene.cameraParams;
                var projection = cameraParams.projection;
                var model = cameraParams.model;
                var width = scene.gl.drawingBufferWidth;
                var height = scene.gl.drawingBufferHeight;
                var zNear = scene.zNear;
                var zFar = scene.zFar;
                var fovy = scene.fovy;
                var r = width / height;
                if (isOrtho) {
                  ortho(
                    projection,
                    -r,
                    r,
                    -1,
                    1,
                    zNear,
                    zFar
                  );
                  cameraParams._ortho = true;
                } else {
                  perspective(
                    projection,
                    fovy,
                    r,
                    zNear,
                    zFar
                  );
                  cameraParams._ortho = false;
                }
                for (var i = 0; i < 16; ++i) {
                  model[i] = 0;
                }
                model[15] = 1;
                var maxS = 0;
                for (var i = 0; i < 3; ++i) {
                  maxS = Math.max(maxS, bounds[1][i] - bounds[0][i]);
                }
                for (var i = 0; i < 3; ++i) {
                  if (scene.autoScale) {
                    model[5 * i] = scene.aspect[i] / (bounds[1][i] - bounds[0][i]);
                  } else {
                    model[5 * i] = 1 / maxS;
                  }
                  if (scene.autoCenter) {
                    model[12 + i] = -model[5 * i] * 0.5 * (bounds[0][i] + bounds[1][i]);
                  }
                }
              }
            }
          ),
          /***/
          4192: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = wrapper;
              var INSERT_SORT_CUTOFF = 32;
              function wrapper(data, n0) {
                if (n0 <= 4 * INSERT_SORT_CUTOFF) {
                  insertionSort(0, n0 - 1, data);
                } else {
                  quickSort(0, n0 - 1, data);
                }
              }
              function insertionSort(left, right, data) {
                var ptr = 2 * (left + 1);
                for (var i = left + 1; i <= right; ++i) {
                  var a = data[ptr++];
                  var b = data[ptr++];
                  var j = i;
                  var jptr = ptr - 2;
                  while (j-- > left) {
                    var x = data[jptr - 2];
                    var y = data[jptr - 1];
                    if (x < a) {
                      break;
                    } else if (x === a && y < b) {
                      break;
                    }
                    data[jptr] = x;
                    data[jptr + 1] = y;
                    jptr -= 2;
                  }
                  data[jptr] = a;
                  data[jptr + 1] = b;
                }
              }
              function swap(i, j, data) {
                i *= 2;
                j *= 2;
                var x = data[i];
                var y = data[i + 1];
                data[i] = data[j];
                data[i + 1] = data[j + 1];
                data[j] = x;
                data[j + 1] = y;
              }
              function move(i, j, data) {
                i *= 2;
                j *= 2;
                data[i] = data[j];
                data[i + 1] = data[j + 1];
              }
              function rotate(i, j, k, data) {
                i *= 2;
                j *= 2;
                k *= 2;
                var x = data[i];
                var y = data[i + 1];
                data[i] = data[j];
                data[i + 1] = data[j + 1];
                data[j] = data[k];
                data[j + 1] = data[k + 1];
                data[k] = x;
                data[k + 1] = y;
              }
              function shufflePivot(i, j, px, py, data) {
                i *= 2;
                j *= 2;
                data[i] = data[j];
                data[j] = px;
                data[i + 1] = data[j + 1];
                data[j + 1] = py;
              }
              function compare(i, j, data) {
                i *= 2;
                j *= 2;
                var x = data[i], y = data[j];
                if (x < y) {
                  return false;
                } else if (x === y) {
                  return data[i + 1] > data[j + 1];
                }
                return true;
              }
              function comparePivot(i, y, b, data) {
                i *= 2;
                var x = data[i];
                if (x < y) {
                  return true;
                } else if (x === y) {
                  return data[i + 1] < b;
                }
                return false;
              }
              function quickSort(left, right, data) {
                var sixth = (right - left + 1) / 6 | 0, index1 = left + sixth, index5 = right - sixth, index3 = left + right >> 1, index2 = index3 - sixth, index4 = index3 + sixth, el1 = index1, el2 = index2, el3 = index3, el4 = index4, el5 = index5, less = left + 1, great = right - 1, tmp = 0;
                if (compare(el1, el2, data)) {
                  tmp = el1;
                  el1 = el2;
                  el2 = tmp;
                }
                if (compare(el4, el5, data)) {
                  tmp = el4;
                  el4 = el5;
                  el5 = tmp;
                }
                if (compare(el1, el3, data)) {
                  tmp = el1;
                  el1 = el3;
                  el3 = tmp;
                }
                if (compare(el2, el3, data)) {
                  tmp = el2;
                  el2 = el3;
                  el3 = tmp;
                }
                if (compare(el1, el4, data)) {
                  tmp = el1;
                  el1 = el4;
                  el4 = tmp;
                }
                if (compare(el3, el4, data)) {
                  tmp = el3;
                  el3 = el4;
                  el4 = tmp;
                }
                if (compare(el2, el5, data)) {
                  tmp = el2;
                  el2 = el5;
                  el5 = tmp;
                }
                if (compare(el2, el3, data)) {
                  tmp = el2;
                  el2 = el3;
                  el3 = tmp;
                }
                if (compare(el4, el5, data)) {
                  tmp = el4;
                  el4 = el5;
                  el5 = tmp;
                }
                var pivot1X = data[2 * el2];
                var pivot1Y = data[2 * el2 + 1];
                var pivot2X = data[2 * el4];
                var pivot2Y = data[2 * el4 + 1];
                var ptr0 = 2 * el1;
                var ptr2 = 2 * el3;
                var ptr4 = 2 * el5;
                var ptr5 = 2 * index1;
                var ptr6 = 2 * index3;
                var ptr7 = 2 * index5;
                for (var i1 = 0; i1 < 2; ++i1) {
                  var x = data[ptr0 + i1];
                  var y = data[ptr2 + i1];
                  var z = data[ptr4 + i1];
                  data[ptr5 + i1] = x;
                  data[ptr6 + i1] = y;
                  data[ptr7 + i1] = z;
                }
                move(index2, left, data);
                move(index4, right, data);
                for (var k = less; k <= great; ++k) {
                  if (comparePivot(k, pivot1X, pivot1Y, data)) {
                    if (k !== less) {
                      swap(k, less, data);
                    }
                    ++less;
                  } else {
                    if (!comparePivot(k, pivot2X, pivot2Y, data)) {
                      while (true) {
                        if (!comparePivot(great, pivot2X, pivot2Y, data)) {
                          if (--great < k) {
                            break;
                          }
                          continue;
                        } else {
                          if (comparePivot(great, pivot1X, pivot1Y, data)) {
                            rotate(k, less, great, data);
                            ++less;
                            --great;
                          } else {
                            swap(k, great, data);
                            --great;
                          }
                          break;
                        }
                      }
                    }
                  }
                }
                shufflePivot(left, less - 1, pivot1X, pivot1Y, data);
                shufflePivot(right, great + 1, pivot2X, pivot2Y, data);
                if (less - 2 - left <= INSERT_SORT_CUTOFF) {
                  insertionSort(left, less - 2, data);
                } else {
                  quickSort(left, less - 2, data);
                }
                if (right - (great + 2) <= INSERT_SORT_CUTOFF) {
                  insertionSort(great + 2, right, data);
                } else {
                  quickSort(great + 2, right, data);
                }
                if (great - less <= INSERT_SORT_CUTOFF) {
                  insertionSort(less, great, data);
                } else {
                  quickSort(less, great, data);
                }
              }
            }
          ),
          /***/
          4209: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createSlabDecomposition;
              var bounds = __webpack_require__2(2478);
              var createRBTree = __webpack_require__2(3840);
              var orient = __webpack_require__2(3250);
              var orderSegments = __webpack_require__2(1303);
              function SlabDecomposition(slabs, coordinates, horizontal) {
                this.slabs = slabs;
                this.coordinates = coordinates;
                this.horizontal = horizontal;
              }
              var proto = SlabDecomposition.prototype;
              function compareHorizontal(e, y) {
                return e.y - y;
              }
              function searchBucket(root, p) {
                var lastNode = null;
                while (root) {
                  var seg = root.key;
                  var l, r;
                  if (seg[0][0] < seg[1][0]) {
                    l = seg[0];
                    r = seg[1];
                  } else {
                    l = seg[1];
                    r = seg[0];
                  }
                  var o = orient(l, r, p);
                  if (o < 0) {
                    root = root.left;
                  } else if (o > 0) {
                    if (p[0] !== seg[1][0]) {
                      lastNode = root;
                      root = root.right;
                    } else {
                      var val = searchBucket(root.right, p);
                      if (val) {
                        return val;
                      }
                      root = root.left;
                    }
                  } else {
                    if (p[0] !== seg[1][0]) {
                      return root;
                    } else {
                      var val = searchBucket(root.right, p);
                      if (val) {
                        return val;
                      }
                      root = root.left;
                    }
                  }
                }
                return lastNode;
              }
              proto.castUp = function(p) {
                var bucket = bounds.le(this.coordinates, p[0]);
                if (bucket < 0) {
                  return -1;
                }
                var root = this.slabs[bucket];
                var hitNode = searchBucket(this.slabs[bucket], p);
                var lastHit = -1;
                if (hitNode) {
                  lastHit = hitNode.value;
                }
                if (this.coordinates[bucket] === p[0]) {
                  var lastSegment = null;
                  if (hitNode) {
                    lastSegment = hitNode.key;
                  }
                  if (bucket > 0) {
                    var otherHitNode = searchBucket(this.slabs[bucket - 1], p);
                    if (otherHitNode) {
                      if (lastSegment) {
                        if (orderSegments(otherHitNode.key, lastSegment) > 0) {
                          lastSegment = otherHitNode.key;
                          lastHit = otherHitNode.value;
                        }
                      } else {
                        lastHit = otherHitNode.value;
                        lastSegment = otherHitNode.key;
                      }
                    }
                  }
                  var horiz = this.horizontal[bucket];
                  if (horiz.length > 0) {
                    var hbucket = bounds.ge(horiz, p[1], compareHorizontal);
                    if (hbucket < horiz.length) {
                      var e = horiz[hbucket];
                      if (p[1] === e.y) {
                        if (e.closed) {
                          return e.index;
                        } else {
                          while (hbucket < horiz.length - 1 && horiz[hbucket + 1].y === p[1]) {
                            hbucket = hbucket + 1;
                            e = horiz[hbucket];
                            if (e.closed) {
                              return e.index;
                            }
                          }
                          if (e.y === p[1] && !e.start) {
                            hbucket = hbucket + 1;
                            if (hbucket >= horiz.length) {
                              return lastHit;
                            }
                            e = horiz[hbucket];
                          }
                        }
                      }
                      if (e.start) {
                        if (lastSegment) {
                          var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]);
                          if (lastSegment[0][0] > lastSegment[1][0]) {
                            o = -o;
                          }
                          if (o > 0) {
                            lastHit = e.index;
                          }
                        } else {
                          lastHit = e.index;
                        }
                      } else if (e.y !== p[1]) {
                        lastHit = e.index;
                      }
                    }
                  }
                }
                return lastHit;
              };
              function IntervalSegment(y, index, start, closed) {
                this.y = y;
                this.index = index;
                this.start = start;
                this.closed = closed;
              }
              function Event(x, segment, create, index) {
                this.x = x;
                this.segment = segment;
                this.create = create;
                this.index = index;
              }
              function createSlabDecomposition(segments) {
                var numSegments = segments.length;
                var numEvents = 2 * numSegments;
                var events = new Array(numEvents);
                for (var i = 0; i < numSegments; ++i) {
                  var s = segments[i];
                  var f = s[0][0] < s[1][0];
                  events[2 * i] = new Event(s[0][0], s, f, i);
                  events[2 * i + 1] = new Event(s[1][0], s, !f, i);
                }
                events.sort(function(a, b) {
                  var d = a.x - b.x;
                  if (d) {
                    return d;
                  }
                  d = a.create - b.create;
                  if (d) {
                    return d;
                  }
                  return Math.min(a.segment[0][1], a.segment[1][1]) - Math.min(b.segment[0][1], b.segment[1][1]);
                });
                var tree = createRBTree(orderSegments);
                var slabs = [];
                var lines = [];
                var horizontal = [];
                var lastX = -Infinity;
                for (var i = 0; i < numEvents; ) {
                  var x = events[i].x;
                  var horiz = [];
                  while (i < numEvents) {
                    var e = events[i];
                    if (e.x !== x) {
                      break;
                    }
                    i += 1;
                    if (e.segment[0][0] === e.x && e.segment[1][0] === e.x) {
                      if (e.create) {
                        if (e.segment[0][1] < e.segment[1][1]) {
                          horiz.push(new IntervalSegment(
                            e.segment[0][1],
                            e.index,
                            true,
                            true
                          ));
                          horiz.push(new IntervalSegment(
                            e.segment[1][1],
                            e.index,
                            false,
                            false
                          ));
                        } else {
                          horiz.push(new IntervalSegment(
                            e.segment[1][1],
                            e.index,
                            true,
                            false
                          ));
                          horiz.push(new IntervalSegment(
                            e.segment[0][1],
                            e.index,
                            false,
                            true
                          ));
                        }
                      }
                    } else {
                      if (e.create) {
                        tree = tree.insert(e.segment, e.index);
                      } else {
                        tree = tree.remove(e.segment);
                      }
                    }
                  }
                  slabs.push(tree.root);
                  lines.push(x);
                  horizontal.push(horiz);
                }
                return new SlabDecomposition(slabs, lines, horizontal);
              }
            }
          ),
          /***/
          4317: (
            /***/
            function(module2) {
              "use strict";
              function interp1d(arr, x) {
                var ix = Math.floor(x), fx = x - ix, s0 = 0 <= ix && ix < arr.shape[0], s1 = 0 <= ix + 1 && ix + 1 < arr.shape[0], w0 = s0 ? +arr.get(ix) : 0, w1 = s1 ? +arr.get(ix + 1) : 0;
                return (1 - fx) * w0 + fx * w1;
              }
              function interp2d(arr, x, y) {
                var ix = Math.floor(x), fx = x - ix, s0 = 0 <= ix && ix < arr.shape[0], s1 = 0 <= ix + 1 && ix + 1 < arr.shape[0], iy = Math.floor(y), fy = y - iy, t02 = 0 <= iy && iy < arr.shape[1], t12 = 0 <= iy + 1 && iy + 1 < arr.shape[1], w00 = s0 && t02 ? arr.get(ix, iy) : 0, w01 = s0 && t12 ? arr.get(ix, iy + 1) : 0, w10 = s1 && t02 ? arr.get(ix + 1, iy) : 0, w11 = s1 && t12 ? arr.get(ix + 1, iy + 1) : 0;
                return (1 - fy) * ((1 - fx) * w00 + fx * w10) + fy * ((1 - fx) * w01 + fx * w11);
              }
              function interp3d(arr, x, y, z) {
                var ix = Math.floor(x), fx = x - ix, s0 = 0 <= ix && ix < arr.shape[0], s1 = 0 <= ix + 1 && ix + 1 < arr.shape[0], iy = Math.floor(y), fy = y - iy, t02 = 0 <= iy && iy < arr.shape[1], t12 = 0 <= iy + 1 && iy + 1 < arr.shape[1], iz = Math.floor(z), fz = z - iz, u0 = 0 <= iz && iz < arr.shape[2], u1 = 0 <= iz + 1 && iz + 1 < arr.shape[2], w000 = s0 && t02 && u0 ? arr.get(ix, iy, iz) : 0, w010 = s0 && t12 && u0 ? arr.get(ix, iy + 1, iz) : 0, w100 = s1 && t02 && u0 ? arr.get(ix + 1, iy, iz) : 0, w110 = s1 && t12 && u0 ? arr.get(ix + 1, iy + 1, iz) : 0, w001 = s0 && t02 && u1 ? arr.get(ix, iy, iz + 1) : 0, w011 = s0 && t12 && u1 ? arr.get(ix, iy + 1, iz + 1) : 0, w101 = s1 && t02 && u1 ? arr.get(ix + 1, iy, iz + 1) : 0, w111 = s1 && t12 && u1 ? arr.get(ix + 1, iy + 1, iz + 1) : 0;
                return (1 - fz) * ((1 - fy) * ((1 - fx) * w000 + fx * w100) + fy * ((1 - fx) * w010 + fx * w110)) + fz * ((1 - fy) * ((1 - fx) * w001 + fx * w101) + fy * ((1 - fx) * w011 + fx * w111));
              }
              function interpNd(arr) {
                var d = arr.shape.length | 0, ix = new Array(d), fx = new Array(d), s0 = new Array(d), s1 = new Array(d), i, t;
                for (i = 0; i < d; ++i) {
                  t = +arguments[i + 1];
                  ix[i] = Math.floor(t);
                  fx[i] = t - ix[i];
                  s0[i] = 0 <= ix[i] && ix[i] < arr.shape[i];
                  s1[i] = 0 <= ix[i] + 1 && ix[i] + 1 < arr.shape[i];
                }
                var r = 0, j, w, idx;
                i_loop:
                  for (i = 0; i < 1 << d; ++i) {
                    w = 1;
                    idx = arr.offset;
                    for (j = 0; j < d; ++j) {
                      if (i & 1 << j) {
                        if (!s1[j]) {
                          continue i_loop;
                        }
                        w *= fx[j];
                        idx += arr.stride[j] * (ix[j] + 1);
                      } else {
                        if (!s0[j]) {
                          continue i_loop;
                        }
                        w *= 1 - fx[j];
                        idx += arr.stride[j] * ix[j];
                      }
                    }
                    r += w * arr.data[idx];
                  }
                return r;
              }
              function interpolate(arr, x, y, z) {
                switch (arr.shape.length) {
                  case 0:
                    return 0;
                  case 1:
                    return interp1d(arr, x);
                  case 2:
                    return interp2d(arr, x, y);
                  case 3:
                    return interp3d(arr, x, y, z);
                  default:
                    return interpNd.apply(void 0, arguments);
                }
              }
              module2.exports = interpolate;
              module2.exports.d1 = interp1d;
              module2.exports.d2 = interp2d;
              module2.exports.d3 = interp3d;
            }
          ),
          /***/
          4335: (
            /***/
            function(module2) {
              module2.exports = function normalize(out, mat) {
                var m44 = mat[15];
                if (m44 === 0)
                  return false;
                var scale = 1 / m44;
                for (var i = 0; i < 16; i++)
                  out[i] = mat[i] * scale;
                return true;
              };
            }
          ),
          /***/
          4359: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createText;
              var vectorizeText = __webpack_require__2(7718);
              var defaultCanvas = null;
              var defaultContext = null;
              if (typeof document !== "undefined") {
                defaultCanvas = document.createElement("canvas");
                defaultCanvas.width = 8192;
                defaultCanvas.height = 1024;
                defaultContext = defaultCanvas.getContext("2d");
              }
              function createText(str, options) {
                if (typeof options !== "object" || options === null) {
                  options = {};
                }
                return vectorizeText(
                  str,
                  options.canvas || defaultCanvas,
                  options.context || defaultContext,
                  options
                );
              }
            }
          ),
          /***/
          4361: (
            /***/
            function(module2) {
              module2.exports = add;
              function add(out, a, b) {
                out[0] = a[0] + b[0];
                out[1] = a[1] + b[1];
                out[2] = a[2] + b[2];
                out[3] = a[3] + b[3];
                return out;
              }
            }
          ),
          /***/
          4437: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createCamera;
              var now = __webpack_require__2(3025);
              var createView = __webpack_require__2(6296);
              var mouseChange = __webpack_require__2(351);
              var mouseWheel = __webpack_require__2(8512);
              var mouseOffset = __webpack_require__2(24);
              var hasPassive = __webpack_require__2(7520);
              function createCamera(element, options) {
                element = element || document.body;
                options = options || {};
                var limits = [0.01, Infinity];
                if ("distanceLimits" in options) {
                  limits[0] = options.distanceLimits[0];
                  limits[1] = options.distanceLimits[1];
                }
                if ("zoomMin" in options) {
                  limits[0] = options.zoomMin;
                }
                if ("zoomMax" in options) {
                  limits[1] = options.zoomMax;
                }
                var view = createView({
                  center: options.center || [0, 0, 0],
                  up: options.up || [0, 1, 0],
                  eye: options.eye || [0, 0, 10],
                  mode: options.mode || "orbit",
                  distanceLimits: limits
                });
                var pmatrix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                var distance = 0;
                var width = element.clientWidth;
                var height = element.clientHeight;
                var camera = {
                  keyBindingMode: "rotate",
                  enableWheel: true,
                  view,
                  element,
                  delay: options.delay || 16,
                  rotateSpeed: options.rotateSpeed || 1,
                  zoomSpeed: options.zoomSpeed || 1,
                  translateSpeed: options.translateSpeed || 1,
                  flipX: !!options.flipX,
                  flipY: !!options.flipY,
                  modes: view.modes,
                  _ortho: options._ortho || options.projection && options.projection.type === "orthographic" || false,
                  tick: function() {
                    var t = now();
                    var delay = this.delay;
                    var ctime = t - 2 * delay;
                    view.idle(t - delay);
                    view.recalcMatrix(ctime);
                    view.flush(t - (100 + delay * 2));
                    var allEqual = true;
                    var matrix = view.computedMatrix;
                    for (var i = 0; i < 16; ++i) {
                      allEqual = allEqual && pmatrix[i] === matrix[i];
                      pmatrix[i] = matrix[i];
                    }
                    var sizeChanged = element.clientWidth === width && element.clientHeight === height;
                    width = element.clientWidth;
                    height = element.clientHeight;
                    if (allEqual) {
                      return !sizeChanged;
                    }
                    distance = Math.exp(view.computedRadius[0]);
                    return true;
                  },
                  lookAt: function(eye, center, up) {
                    view.lookAt(view.lastT(), eye, center, up);
                  },
                  rotate: function(pitch, yaw, roll) {
                    view.rotate(view.lastT(), pitch, yaw, roll);
                  },
                  pan: function(dx, dy, dz) {
                    view.pan(view.lastT(), dx, dy, dz);
                  },
                  translate: function(dx, dy, dz) {
                    view.translate(view.lastT(), dx, dy, dz);
                  }
                };
                Object.defineProperties(camera, {
                  matrix: {
                    get: function() {
                      return view.computedMatrix;
                    },
                    set: function(mat) {
                      view.setMatrix(view.lastT(), mat);
                      return view.computedMatrix;
                    },
                    enumerable: true
                  },
                  mode: {
                    get: function() {
                      return view.getMode();
                    },
                    set: function(mode) {
                      var curUp = view.computedUp.slice();
                      var curEye = view.computedEye.slice();
                      var curCenter = view.computedCenter.slice();
                      view.setMode(mode);
                      if (mode === "turntable") {
                        var t02 = now();
                        view._active.lookAt(t02, curEye, curCenter, curUp);
                        view._active.lookAt(t02 + 500, curEye, curCenter, [0, 0, 1]);
                        view._active.flush(t02);
                      }
                      return view.getMode();
                    },
                    enumerable: true
                  },
                  center: {
                    get: function() {
                      return view.computedCenter;
                    },
                    set: function(ncenter) {
                      view.lookAt(view.lastT(), null, ncenter);
                      return view.computedCenter;
                    },
                    enumerable: true
                  },
                  eye: {
                    get: function() {
                      return view.computedEye;
                    },
                    set: function(neye) {
                      view.lookAt(view.lastT(), neye);
                      return view.computedEye;
                    },
                    enumerable: true
                  },
                  up: {
                    get: function() {
                      return view.computedUp;
                    },
                    set: function(nup) {
                      view.lookAt(view.lastT(), null, null, nup);
                      return view.computedUp;
                    },
                    enumerable: true
                  },
                  distance: {
                    get: function() {
                      return distance;
                    },
                    set: function(d) {
                      view.setDistance(view.lastT(), d);
                      return d;
                    },
                    enumerable: true
                  },
                  distanceLimits: {
                    get: function() {
                      return view.getDistanceLimits(limits);
                    },
                    set: function(v) {
                      view.setDistanceLimits(v);
                      return v;
                    },
                    enumerable: true
                  }
                });
                element.addEventListener("contextmenu", function(ev) {
                  ev.preventDefault();
                  return false;
                });
                camera._lastX = -1;
                camera._lastY = -1;
                camera._lastMods = { shift: false, control: false, alt: false, meta: false };
                camera.enableMouseListeners = function() {
                  camera.mouseListener = mouseChange(element, handleInteraction);
                  element.addEventListener("touchstart", function(ev) {
                    var xy = mouseOffset(ev.changedTouches[0], element);
                    handleInteraction(0, xy[0], xy[1], camera._lastMods);
                    handleInteraction(1, xy[0], xy[1], camera._lastMods);
                  }, hasPassive ? { passive: true } : false);
                  element.addEventListener("touchmove", function(ev) {
                    var xy = mouseOffset(ev.changedTouches[0], element);
                    handleInteraction(1, xy[0], xy[1], camera._lastMods);
                    ev.preventDefault();
                  }, hasPassive ? { passive: false } : false);
                  element.addEventListener("touchend", function(ev) {
                    handleInteraction(0, camera._lastX, camera._lastY, camera._lastMods);
                  }, hasPassive ? { passive: true } : false);
                  function handleInteraction(buttons, x, y, mods) {
                    var keyBindingMode = camera.keyBindingMode;
                    if (keyBindingMode === false) return;
                    var rotate = keyBindingMode === "rotate";
                    var pan = keyBindingMode === "pan";
                    var zoom = keyBindingMode === "zoom";
                    var ctrl = !!mods.control;
                    var alt = !!mods.alt;
                    var shift = !!mods.shift;
                    var left = !!(buttons & 1);
                    var right = !!(buttons & 2);
                    var middle = !!(buttons & 4);
                    var scale = 1 / element.clientHeight;
                    var dx = scale * (x - camera._lastX);
                    var dy = scale * (y - camera._lastY);
                    var flipX = camera.flipX ? 1 : -1;
                    var flipY = camera.flipY ? 1 : -1;
                    var drot = Math.PI * camera.rotateSpeed;
                    var t = now();
                    if (camera._lastX !== -1 && camera._lastY !== -1) {
                      if (rotate && left && !ctrl && !alt && !shift || left && !ctrl && !alt && shift) {
                        view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0);
                      }
                      if (pan && left && !ctrl && !alt && !shift || right || left && ctrl && !alt && !shift) {
                        view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0);
                      }
                      if (zoom && left && !ctrl && !alt && !shift || middle || left && !ctrl && alt && !shift) {
                        var kzoom = -camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 100;
                        view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1));
                      }
                    }
                    camera._lastX = x;
                    camera._lastY = y;
                    camera._lastMods = mods;
                    return true;
                  }
                  camera.wheelListener = mouseWheel(element, function(dx, dy) {
                    if (camera.keyBindingMode === false) return;
                    if (!camera.enableWheel) return;
                    var flipX = camera.flipX ? 1 : -1;
                    var flipY = camera.flipY ? 1 : -1;
                    var t = now();
                    if (Math.abs(dx) > Math.abs(dy)) {
                      view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth);
                    } else {
                      if (!camera._ortho) {
                        var kzoom = -camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 20;
                        view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1));
                      }
                    }
                  }, true);
                };
                camera.enableMouseListeners();
                return camera;
              }
            }
          ),
          /***/
          4449: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createShader = __webpack_require__2(1493);
              module2.exports = createSpikes;
              var identity2 = [
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ];
              function AxisSpikes(gl2, buffer, vao, shader) {
                this.gl = gl2;
                this.buffer = buffer;
                this.vao = vao;
                this.shader = shader;
                this.pixelRatio = 1;
                this.bounds = [[-1e3, -1e3, -1e3], [1e3, 1e3, 1e3]];
                this.position = [0, 0, 0];
                this.lineWidth = [2, 2, 2];
                this.colors = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.enabled = [true, true, true];
                this.drawSides = [true, true, true];
                this.axes = null;
              }
              var proto = AxisSpikes.prototype;
              var OUTER_FACE = [0, 0, 0];
              var INNER_FACE = [0, 0, 0];
              var SHAPE = [0, 0];
              proto.isTransparent = function() {
                return false;
              };
              proto.drawTransparent = function(camera) {
              };
              proto.draw = function(camera) {
                var gl2 = this.gl;
                var vao = this.vao;
                var shader = this.shader;
                vao.bind();
                shader.bind();
                var model = camera.model || identity2;
                var view = camera.view || identity2;
                var projection = camera.projection || identity2;
                var axis;
                if (this.axes) {
                  axis = this.axes.lastCubeProps.axis;
                }
                var outerFace = OUTER_FACE;
                var innerFace = INNER_FACE;
                for (var i = 0; i < 3; ++i) {
                  if (axis && axis[i] < 0) {
                    outerFace[i] = this.bounds[0][i];
                    innerFace[i] = this.bounds[1][i];
                  } else {
                    outerFace[i] = this.bounds[1][i];
                    innerFace[i] = this.bounds[0][i];
                  }
                }
                SHAPE[0] = gl2.drawingBufferWidth;
                SHAPE[1] = gl2.drawingBufferHeight;
                shader.uniforms.model = model;
                shader.uniforms.view = view;
                shader.uniforms.projection = projection;
                shader.uniforms.coordinates = [this.position, outerFace, innerFace];
                shader.uniforms.colors = this.colors;
                shader.uniforms.screenShape = SHAPE;
                for (var i = 0; i < 3; ++i) {
                  shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio;
                  if (this.enabled[i]) {
                    vao.draw(gl2.TRIANGLES, 6, 6 * i);
                    if (this.drawSides[i]) {
                      vao.draw(gl2.TRIANGLES, 12, 18 + 12 * i);
                    }
                  }
                }
                vao.unbind();
              };
              proto.update = function(options) {
                if (!options) {
                  return;
                }
                if ("bounds" in options) {
                  this.bounds = options.bounds;
                }
                if ("position" in options) {
                  this.position = options.position;
                }
                if ("lineWidth" in options) {
                  this.lineWidth = options.lineWidth;
                }
                if ("colors" in options) {
                  this.colors = options.colors;
                }
                if ("enabled" in options) {
                  this.enabled = options.enabled;
                }
                if ("drawSides" in options) {
                  this.drawSides = options.drawSides;
                }
              };
              proto.dispose = function() {
                this.vao.dispose();
                this.buffer.dispose();
                this.shader.dispose();
              };
              function createSpikes(gl2, options) {
                var data = [];
                function line(x, y, z, i, l, h) {
                  var row = [x, y, z, 0, 0, 0, 1];
                  row[i + 3] = 1;
                  row[i] = l;
                  data.push.apply(data, row);
                  row[6] = -1;
                  data.push.apply(data, row);
                  row[i] = h;
                  data.push.apply(data, row);
                  data.push.apply(data, row);
                  row[6] = 1;
                  data.push.apply(data, row);
                  row[i] = l;
                  data.push.apply(data, row);
                }
                line(0, 0, 0, 0, 0, 1);
                line(0, 0, 0, 1, 0, 1);
                line(0, 0, 0, 2, 0, 1);
                line(1, 0, 0, 1, -1, 1);
                line(1, 0, 0, 2, -1, 1);
                line(0, 1, 0, 0, -1, 1);
                line(0, 1, 0, 2, -1, 1);
                line(0, 0, 1, 0, -1, 1);
                line(0, 0, 1, 1, -1, 1);
                var buffer = createBuffer(gl2, data);
                var vao = createVAO(gl2, [{
                  type: gl2.FLOAT,
                  buffer,
                  size: 3,
                  offset: 0,
                  stride: 28
                }, {
                  type: gl2.FLOAT,
                  buffer,
                  size: 3,
                  offset: 12,
                  stride: 28
                }, {
                  type: gl2.FLOAT,
                  buffer,
                  size: 1,
                  offset: 24,
                  stride: 28
                }]);
                var shader = createShader(gl2);
                shader.attributes.position.location = 0;
                shader.attributes.color.location = 1;
                shader.attributes.weight.location = 2;
                var spikes = new AxisSpikes(gl2, buffer, vao, shader);
                spikes.update(options);
                return spikes;
              }
            }
          ),
          /***/
          4494: (
            /***/
            function(module2) {
              module2.exports = inverse;
              function inverse(out, a) {
                out[0] = 1 / a[0];
                out[1] = 1 / a[1];
                out[2] = 1 / a[2];
                out[3] = 1 / a[3];
                return out;
              }
            }
          ),
          /***/
          4505: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(5847);
            }
          ),
          /***/
          4578: (
            /***/
            function(module2) {
              module2.exports = set;
              function set(out, x, y, z, w) {
                out[0] = x;
                out[1] = y;
                out[2] = z;
                out[3] = w;
                return out;
              }
            }
          ),
          /***/
          4623: (
            /***/
            function(module2) {
              "use strict";
              "use restrict";
              module2.exports = UnionFind;
              function UnionFind(count) {
                this.roots = new Array(count);
                this.ranks = new Array(count);
                for (var i = 0; i < count; ++i) {
                  this.roots[i] = i;
                  this.ranks[i] = 0;
                }
              }
              UnionFind.prototype.length = function() {
                return this.roots.length;
              };
              UnionFind.prototype.makeSet = function() {
                var n = this.roots.length;
                this.roots.push(n);
                this.ranks.push(0);
                return n;
              };
              UnionFind.prototype.find = function(x) {
                var roots = this.roots;
                while (roots[x] !== x) {
                  var y = roots[x];
                  roots[x] = roots[y];
                  x = y;
                }
                return x;
              };
              UnionFind.prototype.link = function(x, y) {
                var xr = this.find(x), yr = this.find(y);
                if (xr === yr) {
                  return;
                }
                var ranks = this.ranks, roots = this.roots, xd = ranks[xr], yd = ranks[yr];
                if (xd < yd) {
                  roots[xr] = yr;
                } else if (yd < xd) {
                  roots[yr] = xr;
                } else {
                  roots[yr] = xr;
                  ++ranks[xr];
                }
              };
            }
          ),
          /***/
          4687: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              function mouseButtons(ev) {
                if (typeof ev === "object") {
                  if ("buttons" in ev) {
                    return ev.buttons;
                  } else if ("which" in ev) {
                    var b = ev.which;
                    if (b === 2) {
                      return 4;
                    } else if (b === 3) {
                      return 2;
                    } else if (b > 0) {
                      return 1 << b - 1;
                    }
                  } else if ("button" in ev) {
                    var b = ev.button;
                    if (b === 1) {
                      return 4;
                    } else if (b === 2) {
                      return 2;
                    } else if (b >= 0) {
                      return 1 << b;
                    }
                  }
                }
                return 0;
              }
              exports2.buttons = mouseButtons;
              function mouseElement(ev) {
                return ev.target || ev.srcElement || window;
              }
              exports2.element = mouseElement;
              function mouseRelativeX(ev) {
                if (typeof ev === "object") {
                  if ("offsetX" in ev) {
                    return ev.offsetX;
                  }
                  var target = mouseElement(ev);
                  var bounds = target.getBoundingClientRect();
                  return ev.clientX - bounds.left;
                }
                return 0;
              }
              exports2.x = mouseRelativeX;
              function mouseRelativeY(ev) {
                if (typeof ev === "object") {
                  if ("offsetY" in ev) {
                    return ev.offsetY;
                  }
                  var target = mouseElement(ev);
                  var bounds = target.getBoundingClientRect();
                  return ev.clientY - bounds.top;
                }
                return 0;
              }
              exports2.y = mouseRelativeY;
            }
          ),
          /***/
          4691: (
            /***/
            function(module2) {
              module2.exports = distance;
              function distance(a, b) {
                var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2], w = b[3] - a[3];
                return Math.sqrt(x * x + y * y + z * z + w * w);
              }
            }
          ),
          /***/
          4750: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = convexHull2D;
              var monotoneHull = __webpack_require__2(3090);
              function convexHull2D(points) {
                var hull = monotoneHull(points);
                var h = hull.length;
                if (h <= 2) {
                  return [];
                }
                var edges = new Array(h);
                var a = hull[h - 1];
                for (var i = 0; i < h; ++i) {
                  var b = hull[i];
                  edges[i] = [a, b];
                  a = b;
                }
                return edges;
              }
            }
          ),
          /***/
          4769: (
            /***/
            function(module2) {
              "use strict";
              function dcubicHermite(p0, v0, p1, v1, t, f) {
                var dh00 = 6 * t * t - 6 * t, dh10 = 3 * t * t - 4 * t + 1, dh01 = -6 * t * t + 6 * t, dh11 = 3 * t * t - 2 * t;
                if (p0.length) {
                  if (!f) {
                    f = new Array(p0.length);
                  }
                  for (var i = p0.length - 1; i >= 0; --i) {
                    f[i] = dh00 * p0[i] + dh10 * v0[i] + dh01 * p1[i] + dh11 * v1[i];
                  }
                  return f;
                }
                return dh00 * p0 + dh10 * v0 + dh01 * p1[i] + dh11 * v1;
              }
              function cubicHermite(p0, v0, p1, v1, t, f) {
                var ti = t - 1, t22 = t * t, ti2 = ti * ti, h00 = (1 + 2 * t) * ti2, h10 = t * ti2, h01 = t22 * (3 - 2 * t), h11 = t22 * ti;
                if (p0.length) {
                  if (!f) {
                    f = new Array(p0.length);
                  }
                  for (var i = p0.length - 1; i >= 0; --i) {
                    f[i] = h00 * p0[i] + h10 * v0[i] + h01 * p1[i] + h11 * v1[i];
                  }
                  return f;
                }
                return h00 * p0 + h10 * v0 + h01 * p1 + h11 * v1;
              }
              module2.exports = cubicHermite;
              module2.exports.derivative = dcubicHermite;
            }
          ),
          /***/
          4772: (
            /***/
            function(module2) {
              module2.exports = perspective;
              function perspective(out, fovy, aspect, near, far) {
                var f = 1 / Math.tan(fovy / 2), nf = 1 / (near - far);
                out[0] = f / aspect;
                out[1] = 0;
                out[2] = 0;
                out[3] = 0;
                out[4] = 0;
                out[5] = f;
                out[6] = 0;
                out[7] = 0;
                out[8] = 0;
                out[9] = 0;
                out[10] = (far + near) * nf;
                out[11] = -1;
                out[12] = 0;
                out[13] = 0;
                out[14] = 2 * far * near * nf;
                out[15] = 0;
                return out;
              }
              ;
            }
          ),
          /***/
          4793: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              "use strict";
              var __webpack_unused_export__;
              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), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: false }), e;
              }
              function _toPropertyKey(t) {
                var i = _toPrimitive(t, "string");
                return "symbol" == _typeof(i) ? i : i + "";
              }
              function _toPrimitive(t, r) {
                if ("object" != _typeof(t) || !t) return t;
                var e = t[Symbol.toPrimitive];
                if (void 0 !== e) {
                  var i = e.call(t, r || "default");
                  if ("object" != _typeof(i)) return i;
                  throw new TypeError("@@toPrimitive must return a primitive value.");
                }
                return ("string" === r ? String : Number)(t);
              }
              function _callSuper(t, o, e) {
                return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
              }
              function _possibleConstructorReturn(t, e) {
                if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
                if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
                return _assertThisInitialized(t);
              }
              function _assertThisInitialized(e) {
                if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
                return e;
              }
              function _isNativeReflectConstruct() {
                try {
                  var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
                  }));
                } catch (t4) {
                }
                return (_isNativeReflectConstruct = function _isNativeReflectConstruct2() {
                  return !!t;
                })();
              }
              function _getPrototypeOf(t) {
                return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t4) {
                  return t4.__proto__ || Object.getPrototypeOf(t4);
                }, _getPrototypeOf(t);
              }
              function _inherits(t, e) {
                if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
                t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e);
              }
              function _setPrototypeOf(t, e) {
                return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t4, e2) {
                  return t4.__proto__ = e2, t4;
                }, _setPrototypeOf(t, e);
              }
              function _typeof(o) {
                "@babel/helpers - typeof";
                return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
                  return typeof o2;
                } : function(o2) {
                  return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
                }, _typeof(o);
              }
              var base64 = __webpack_require__2(7507);
              var ieee754 = __webpack_require__2(3778);
              var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
              exports2.hp = Buffer2;
              __webpack_unused_export__ = SlowBuffer;
              exports2.IS = 50;
              var K_MAX_LENGTH = 2147483647;
              __webpack_unused_export__ = K_MAX_LENGTH;
              Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
              if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
                console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");
              }
              function typedArraySupport() {
                try {
                  var arr = new Uint8Array(1);
                  var proto = {
                    foo: function foo() {
                      return 42;
                    }
                  };
                  Object.setPrototypeOf(proto, Uint8Array.prototype);
                  Object.setPrototypeOf(arr, proto);
                  return arr.foo() === 42;
                } catch (e) {
                  return false;
                }
              }
              Object.defineProperty(Buffer2.prototype, "parent", {
                enumerable: true,
                get: function get() {
                  if (!Buffer2.isBuffer(this)) return void 0;
                  return this.buffer;
                }
              });
              Object.defineProperty(Buffer2.prototype, "offset", {
                enumerable: true,
                get: function get() {
                  if (!Buffer2.isBuffer(this)) return void 0;
                  return this.byteOffset;
                }
              });
              function createBuffer(length) {
                if (length > K_MAX_LENGTH) {
                  throw new RangeError('The value "' + length + '" is invalid for option "size"');
                }
                var buf = new Uint8Array(length);
                Object.setPrototypeOf(buf, Buffer2.prototype);
                return buf;
              }
              function Buffer2(arg, encodingOrOffset, length) {
                if (typeof arg === "number") {
                  if (typeof encodingOrOffset === "string") {
                    throw new TypeError('The "string" argument must be of type string. Received type number');
                  }
                  return allocUnsafe(arg);
                }
                return from(arg, encodingOrOffset, length);
              }
              Buffer2.poolSize = 8192;
              function from(value, encodingOrOffset, length) {
                if (typeof value === "string") {
                  return fromString(value, encodingOrOffset);
                }
                if (ArrayBuffer.isView(value)) {
                  return fromArrayView(value);
                }
                if (value == null) {
                  throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + _typeof(value));
                }
                if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
                  return fromArrayBuffer(value, encodingOrOffset, length);
                }
                if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
                  return fromArrayBuffer(value, encodingOrOffset, length);
                }
                if (typeof value === "number") {
                  throw new TypeError('The "value" argument must not be of type number. Received type number');
                }
                var valueOf = value.valueOf && value.valueOf();
                if (valueOf != null && valueOf !== value) {
                  return Buffer2.from(valueOf, encodingOrOffset, length);
                }
                var b = fromObject(value);
                if (b) return b;
                if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
                  return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
                }
                throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + _typeof(value));
              }
              Buffer2.from = function(value, encodingOrOffset, length) {
                return from(value, encodingOrOffset, length);
              };
              Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
              Object.setPrototypeOf(Buffer2, Uint8Array);
              function assertSize(size) {
                if (typeof size !== "number") {
                  throw new TypeError('"size" argument must be of type number');
                } else if (size < 0) {
                  throw new RangeError('The value "' + size + '" is invalid for option "size"');
                }
              }
              function alloc(size, fill, encoding) {
                assertSize(size);
                if (size <= 0) {
                  return createBuffer(size);
                }
                if (fill !== void 0) {
                  return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
                }
                return createBuffer(size);
              }
              Buffer2.alloc = function(size, fill, encoding) {
                return alloc(size, fill, encoding);
              };
              function allocUnsafe(size) {
                assertSize(size);
                return createBuffer(size < 0 ? 0 : checked(size) | 0);
              }
              Buffer2.allocUnsafe = function(size) {
                return allocUnsafe(size);
              };
              Buffer2.allocUnsafeSlow = function(size) {
                return allocUnsafe(size);
              };
              function fromString(string, encoding) {
                if (typeof encoding !== "string" || encoding === "") {
                  encoding = "utf8";
                }
                if (!Buffer2.isEncoding(encoding)) {
                  throw new TypeError("Unknown encoding: " + encoding);
                }
                var length = byteLength(string, encoding) | 0;
                var buf = createBuffer(length);
                var actual = buf.write(string, encoding);
                if (actual !== length) {
                  buf = buf.slice(0, actual);
                }
                return buf;
              }
              function fromArrayLike(array) {
                var length = array.length < 0 ? 0 : checked(array.length) | 0;
                var buf = createBuffer(length);
                for (var i = 0; i < length; i += 1) {
                  buf[i] = array[i] & 255;
                }
                return buf;
              }
              function fromArrayView(arrayView) {
                if (isInstance(arrayView, Uint8Array)) {
                  var copy = new Uint8Array(arrayView);
                  return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
                }
                return fromArrayLike(arrayView);
              }
              function fromArrayBuffer(array, byteOffset, length) {
                if (byteOffset < 0 || array.byteLength < byteOffset) {
                  throw new RangeError('"offset" is outside of buffer bounds');
                }
                if (array.byteLength < byteOffset + (length || 0)) {
                  throw new RangeError('"length" is outside of buffer bounds');
                }
                var buf;
                if (byteOffset === void 0 && length === void 0) {
                  buf = new Uint8Array(array);
                } else if (length === void 0) {
                  buf = new Uint8Array(array, byteOffset);
                } else {
                  buf = new Uint8Array(array, byteOffset, length);
                }
                Object.setPrototypeOf(buf, Buffer2.prototype);
                return buf;
              }
              function fromObject(obj) {
                if (Buffer2.isBuffer(obj)) {
                  var len = checked(obj.length) | 0;
                  var buf = createBuffer(len);
                  if (buf.length === 0) {
                    return buf;
                  }
                  obj.copy(buf, 0, 0, len);
                  return buf;
                }
                if (obj.length !== void 0) {
                  if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
                    return createBuffer(0);
                  }
                  return fromArrayLike(obj);
                }
                if (obj.type === "Buffer" && Array.isArray(obj.data)) {
                  return fromArrayLike(obj.data);
                }
              }
              function checked(length) {
                if (length >= K_MAX_LENGTH) {
                  throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
                }
                return length | 0;
              }
              function SlowBuffer(length) {
                if (+length != length) {
                  length = 0;
                }
                return Buffer2.alloc(+length);
              }
              Buffer2.isBuffer = function isBuffer(b) {
                return b != null && b._isBuffer === true && b !== Buffer2.prototype;
              };
              Buffer2.compare = function compare(a, b) {
                if (isInstance(a, Uint8Array)) a = Buffer2.from(a, a.offset, a.byteLength);
                if (isInstance(b, Uint8Array)) b = Buffer2.from(b, b.offset, b.byteLength);
                if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) {
                  throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
                }
                if (a === b) return 0;
                var x = a.length;
                var y = b.length;
                for (var i = 0, len = Math.min(x, y); i < len; ++i) {
                  if (a[i] !== b[i]) {
                    x = a[i];
                    y = b[i];
                    break;
                  }
                }
                if (x < y) return -1;
                if (y < x) return 1;
                return 0;
              };
              Buffer2.isEncoding = function isEncoding(encoding) {
                switch (String(encoding).toLowerCase()) {
                  case "hex":
                  case "utf8":
                  case "utf-8":
                  case "ascii":
                  case "latin1":
                  case "binary":
                  case "base64":
                  case "ucs2":
                  case "ucs-2":
                  case "utf16le":
                  case "utf-16le":
                    return true;
                  default:
                    return false;
                }
              };
              Buffer2.concat = function concat(list, length) {
                if (!Array.isArray(list)) {
                  throw new TypeError('"list" argument must be an Array of Buffers');
                }
                if (list.length === 0) {
                  return Buffer2.alloc(0);
                }
                var i;
                if (length === void 0) {
                  length = 0;
                  for (i = 0; i < list.length; ++i) {
                    length += list[i].length;
                  }
                }
                var buffer = Buffer2.allocUnsafe(length);
                var pos = 0;
                for (i = 0; i < list.length; ++i) {
                  var buf = list[i];
                  if (isInstance(buf, Uint8Array)) {
                    if (pos + buf.length > buffer.length) {
                      if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf);
                      buf.copy(buffer, pos);
                    } else {
                      Uint8Array.prototype.set.call(buffer, buf, pos);
                    }
                  } else if (!Buffer2.isBuffer(buf)) {
                    throw new TypeError('"list" argument must be an Array of Buffers');
                  } else {
                    buf.copy(buffer, pos);
                  }
                  pos += buf.length;
                }
                return buffer;
              };
              function byteLength(string, encoding) {
                if (Buffer2.isBuffer(string)) {
                  return string.length;
                }
                if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
                  return string.byteLength;
                }
                if (typeof string !== "string") {
                  throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + _typeof(string));
                }
                var len = string.length;
                var mustMatch = arguments.length > 2 && arguments[2] === true;
                if (!mustMatch && len === 0) return 0;
                var loweredCase = false;
                for (; ; ) {
                  switch (encoding) {
                    case "ascii":
                    case "latin1":
                    case "binary":
                      return len;
                    case "utf8":
                    case "utf-8":
                      return utf8ToBytes(string).length;
                    case "ucs2":
                    case "ucs-2":
                    case "utf16le":
                    case "utf-16le":
                      return len * 2;
                    case "hex":
                      return len >>> 1;
                    case "base64":
                      return base64ToBytes(string).length;
                    default:
                      if (loweredCase) {
                        return mustMatch ? -1 : utf8ToBytes(string).length;
                      }
                      encoding = ("" + encoding).toLowerCase();
                      loweredCase = true;
                  }
                }
              }
              Buffer2.byteLength = byteLength;
              function slowToString(encoding, start, end) {
                var loweredCase = false;
                if (start === void 0 || start < 0) {
                  start = 0;
                }
                if (start > this.length) {
                  return "";
                }
                if (end === void 0 || end > this.length) {
                  end = this.length;
                }
                if (end <= 0) {
                  return "";
                }
                end >>>= 0;
                start >>>= 0;
                if (end <= start) {
                  return "";
                }
                if (!encoding) encoding = "utf8";
                while (true) {
                  switch (encoding) {
                    case "hex":
                      return hexSlice(this, start, end);
                    case "utf8":
                    case "utf-8":
                      return utf8Slice(this, start, end);
                    case "ascii":
                      return asciiSlice(this, start, end);
                    case "latin1":
                    case "binary":
                      return latin1Slice(this, start, end);
                    case "base64":
                      return base64Slice(this, start, end);
                    case "ucs2":
                    case "ucs-2":
                    case "utf16le":
                    case "utf-16le":
                      return utf16leSlice(this, start, end);
                    default:
                      if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
                      encoding = (encoding + "").toLowerCase();
                      loweredCase = true;
                  }
                }
              }
              Buffer2.prototype._isBuffer = true;
              function swap(b, n, m) {
                var i = b[n];
                b[n] = b[m];
                b[m] = i;
              }
              Buffer2.prototype.swap16 = function swap16() {
                var len = this.length;
                if (len % 2 !== 0) {
                  throw new RangeError("Buffer size must be a multiple of 16-bits");
                }
                for (var i = 0; i < len; i += 2) {
                  swap(this, i, i + 1);
                }
                return this;
              };
              Buffer2.prototype.swap32 = function swap32() {
                var len = this.length;
                if (len % 4 !== 0) {
                  throw new RangeError("Buffer size must be a multiple of 32-bits");
                }
                for (var i = 0; i < len; i += 4) {
                  swap(this, i, i + 3);
                  swap(this, i + 1, i + 2);
                }
                return this;
              };
              Buffer2.prototype.swap64 = function swap64() {
                var len = this.length;
                if (len % 8 !== 0) {
                  throw new RangeError("Buffer size must be a multiple of 64-bits");
                }
                for (var i = 0; i < len; i += 8) {
                  swap(this, i, i + 7);
                  swap(this, i + 1, i + 6);
                  swap(this, i + 2, i + 5);
                  swap(this, i + 3, i + 4);
                }
                return this;
              };
              Buffer2.prototype.toString = function toString() {
                var length = this.length;
                if (length === 0) return "";
                if (arguments.length === 0) return utf8Slice(this, 0, length);
                return slowToString.apply(this, arguments);
              };
              Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
              Buffer2.prototype.equals = function equals(b) {
                if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
                if (this === b) return true;
                return Buffer2.compare(this, b) === 0;
              };
              Buffer2.prototype.inspect = function inspect() {
                var str = "";
                var max = exports2.IS;
                str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
                if (this.length > max) str += " ... ";
                return "<Buffer " + str + ">";
              };
              if (customInspectSymbol) {
                Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
              }
              Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
                if (isInstance(target, Uint8Array)) {
                  target = Buffer2.from(target, target.offset, target.byteLength);
                }
                if (!Buffer2.isBuffer(target)) {
                  throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + _typeof(target));
                }
                if (start === void 0) {
                  start = 0;
                }
                if (end === void 0) {
                  end = target ? target.length : 0;
                }
                if (thisStart === void 0) {
                  thisStart = 0;
                }
                if (thisEnd === void 0) {
                  thisEnd = this.length;
                }
                if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
                  throw new RangeError("out of range index");
                }
                if (thisStart >= thisEnd && start >= end) {
                  return 0;
                }
                if (thisStart >= thisEnd) {
                  return -1;
                }
                if (start >= end) {
                  return 1;
                }
                start >>>= 0;
                end >>>= 0;
                thisStart >>>= 0;
                thisEnd >>>= 0;
                if (this === target) return 0;
                var x = thisEnd - thisStart;
                var y = end - start;
                var len = Math.min(x, y);
                var thisCopy = this.slice(thisStart, thisEnd);
                var targetCopy = target.slice(start, end);
                for (var i = 0; i < len; ++i) {
                  if (thisCopy[i] !== targetCopy[i]) {
                    x = thisCopy[i];
                    y = targetCopy[i];
                    break;
                  }
                }
                if (x < y) return -1;
                if (y < x) return 1;
                return 0;
              };
              function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
                if (buffer.length === 0) return -1;
                if (typeof byteOffset === "string") {
                  encoding = byteOffset;
                  byteOffset = 0;
                } else if (byteOffset > 2147483647) {
                  byteOffset = 2147483647;
                } else if (byteOffset < -2147483648) {
                  byteOffset = -2147483648;
                }
                byteOffset = +byteOffset;
                if (numberIsNaN(byteOffset)) {
                  byteOffset = dir ? 0 : buffer.length - 1;
                }
                if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
                if (byteOffset >= buffer.length) {
                  if (dir) return -1;
                  else byteOffset = buffer.length - 1;
                } else if (byteOffset < 0) {
                  if (dir) byteOffset = 0;
                  else return -1;
                }
                if (typeof val === "string") {
                  val = Buffer2.from(val, encoding);
                }
                if (Buffer2.isBuffer(val)) {
                  if (val.length === 0) {
                    return -1;
                  }
                  return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
                } else if (typeof val === "number") {
                  val = val & 255;
                  if (typeof Uint8Array.prototype.indexOf === "function") {
                    if (dir) {
                      return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
                    } else {
                      return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
                    }
                  }
                  return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
                }
                throw new TypeError("val must be string, number or Buffer");
              }
              function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
                var indexSize = 1;
                var arrLength = arr.length;
                var valLength = val.length;
                if (encoding !== void 0) {
                  encoding = String(encoding).toLowerCase();
                  if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
                    if (arr.length < 2 || val.length < 2) {
                      return -1;
                    }
                    indexSize = 2;
                    arrLength /= 2;
                    valLength /= 2;
                    byteOffset /= 2;
                  }
                }
                function read(buf, i2) {
                  if (indexSize === 1) {
                    return buf[i2];
                  } else {
                    return buf.readUInt16BE(i2 * indexSize);
                  }
                }
                var i;
                if (dir) {
                  var foundIndex = -1;
                  for (i = byteOffset; i < arrLength; i++) {
                    if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
                      if (foundIndex === -1) foundIndex = i;
                      if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
                    } else {
                      if (foundIndex !== -1) i -= i - foundIndex;
                      foundIndex = -1;
                    }
                  }
                } else {
                  if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
                  for (i = byteOffset; i >= 0; i--) {
                    var found = true;
                    for (var j = 0; j < valLength; j++) {
                      if (read(arr, i + j) !== read(val, j)) {
                        found = false;
                        break;
                      }
                    }
                    if (found) return i;
                  }
                }
                return -1;
              }
              Buffer2.prototype.includes = function includes(val, byteOffset, encoding) {
                return this.indexOf(val, byteOffset, encoding) !== -1;
              };
              Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
                return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
              };
              Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
                return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
              };
              function hexWrite(buf, string, offset, length) {
                offset = Number(offset) || 0;
                var remaining = buf.length - offset;
                if (!length) {
                  length = remaining;
                } else {
                  length = Number(length);
                  if (length > remaining) {
                    length = remaining;
                  }
                }
                var strLen = string.length;
                if (length > strLen / 2) {
                  length = strLen / 2;
                }
                var i;
                for (i = 0; i < length; ++i) {
                  var parsed = parseInt(string.substr(i * 2, 2), 16);
                  if (numberIsNaN(parsed)) return i;
                  buf[offset + i] = parsed;
                }
                return i;
              }
              function utf8Write(buf, string, offset, length) {
                return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
              }
              function asciiWrite(buf, string, offset, length) {
                return blitBuffer(asciiToBytes(string), buf, offset, length);
              }
              function base64Write(buf, string, offset, length) {
                return blitBuffer(base64ToBytes(string), buf, offset, length);
              }
              function ucs2Write(buf, string, offset, length) {
                return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
              }
              Buffer2.prototype.write = function write(string, offset, length, encoding) {
                if (offset === void 0) {
                  encoding = "utf8";
                  length = this.length;
                  offset = 0;
                } else if (length === void 0 && typeof offset === "string") {
                  encoding = offset;
                  length = this.length;
                  offset = 0;
                } else if (isFinite(offset)) {
                  offset = offset >>> 0;
                  if (isFinite(length)) {
                    length = length >>> 0;
                    if (encoding === void 0) encoding = "utf8";
                  } else {
                    encoding = length;
                    length = void 0;
                  }
                } else {
                  throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
                }
                var remaining = this.length - offset;
                if (length === void 0 || length > remaining) length = remaining;
                if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
                  throw new RangeError("Attempt to write outside buffer bounds");
                }
                if (!encoding) encoding = "utf8";
                var loweredCase = false;
                for (; ; ) {
                  switch (encoding) {
                    case "hex":
                      return hexWrite(this, string, offset, length);
                    case "utf8":
                    case "utf-8":
                      return utf8Write(this, string, offset, length);
                    case "ascii":
                    case "latin1":
                    case "binary":
                      return asciiWrite(this, string, offset, length);
                    case "base64":
                      return base64Write(this, string, offset, length);
                    case "ucs2":
                    case "ucs-2":
                    case "utf16le":
                    case "utf-16le":
                      return ucs2Write(this, string, offset, length);
                    default:
                      if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
                      encoding = ("" + encoding).toLowerCase();
                      loweredCase = true;
                  }
                }
              };
              Buffer2.prototype.toJSON = function toJSON() {
                return {
                  type: "Buffer",
                  data: Array.prototype.slice.call(this._arr || this, 0)
                };
              };
              function base64Slice(buf, start, end) {
                if (start === 0 && end === buf.length) {
                  return base64.fromByteArray(buf);
                } else {
                  return base64.fromByteArray(buf.slice(start, end));
                }
              }
              function utf8Slice(buf, start, end) {
                end = Math.min(buf.length, end);
                var res = [];
                var i = start;
                while (i < end) {
                  var firstByte = buf[i];
                  var codePoint = null;
                  var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
                  if (i + bytesPerSequence <= end) {
                    var secondByte = void 0, thirdByte = void 0, fourthByte = void 0, tempCodePoint = void 0;
                    switch (bytesPerSequence) {
                      case 1:
                        if (firstByte < 128) {
                          codePoint = firstByte;
                        }
                        break;
                      case 2:
                        secondByte = buf[i + 1];
                        if ((secondByte & 192) === 128) {
                          tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
                          if (tempCodePoint > 127) {
                            codePoint = tempCodePoint;
                          }
                        }
                        break;
                      case 3:
                        secondByte = buf[i + 1];
                        thirdByte = buf[i + 2];
                        if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
                          tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
                          if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
                            codePoint = tempCodePoint;
                          }
                        }
                        break;
                      case 4:
                        secondByte = buf[i + 1];
                        thirdByte = buf[i + 2];
                        fourthByte = buf[i + 3];
                        if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
                          tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
                          if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
                            codePoint = tempCodePoint;
                          }
                        }
                    }
                  }
                  if (codePoint === null) {
                    codePoint = 65533;
                    bytesPerSequence = 1;
                  } else if (codePoint > 65535) {
                    codePoint -= 65536;
                    res.push(codePoint >>> 10 & 1023 | 55296);
                    codePoint = 56320 | codePoint & 1023;
                  }
                  res.push(codePoint);
                  i += bytesPerSequence;
                }
                return decodeCodePointsArray(res);
              }
              var MAX_ARGUMENTS_LENGTH = 4096;
              function decodeCodePointsArray(codePoints) {
                var len = codePoints.length;
                if (len <= MAX_ARGUMENTS_LENGTH) {
                  return String.fromCharCode.apply(String, codePoints);
                }
                var res = "";
                var i = 0;
                while (i < len) {
                  res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
                }
                return res;
              }
              function asciiSlice(buf, start, end) {
                var ret = "";
                end = Math.min(buf.length, end);
                for (var i = start; i < end; ++i) {
                  ret += String.fromCharCode(buf[i] & 127);
                }
                return ret;
              }
              function latin1Slice(buf, start, end) {
                var ret = "";
                end = Math.min(buf.length, end);
                for (var i = start; i < end; ++i) {
                  ret += String.fromCharCode(buf[i]);
                }
                return ret;
              }
              function hexSlice(buf, start, end) {
                var len = buf.length;
                if (!start || start < 0) start = 0;
                if (!end || end < 0 || end > len) end = len;
                var out = "";
                for (var i = start; i < end; ++i) {
                  out += hexSliceLookupTable[buf[i]];
                }
                return out;
              }
              function utf16leSlice(buf, start, end) {
                var bytes = buf.slice(start, end);
                var res = "";
                for (var i = 0; i < bytes.length - 1; i += 2) {
                  res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
                }
                return res;
              }
              Buffer2.prototype.slice = function slice(start, end) {
                var len = this.length;
                start = ~~start;
                end = end === void 0 ? len : ~~end;
                if (start < 0) {
                  start += len;
                  if (start < 0) start = 0;
                } else if (start > len) {
                  start = len;
                }
                if (end < 0) {
                  end += len;
                  if (end < 0) end = 0;
                } else if (end > len) {
                  end = len;
                }
                if (end < start) end = start;
                var newBuf = this.subarray(start, end);
                Object.setPrototypeOf(newBuf, Buffer2.prototype);
                return newBuf;
              };
              function checkOffset(offset, ext, length) {
                if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
                if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
              }
              Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
                offset = offset >>> 0;
                byteLength2 = byteLength2 >>> 0;
                if (!noAssert) checkOffset(offset, byteLength2, this.length);
                var val = this[offset];
                var mul = 1;
                var i = 0;
                while (++i < byteLength2 && (mul *= 256)) {
                  val += this[offset + i] * mul;
                }
                return val;
              };
              Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
                offset = offset >>> 0;
                byteLength2 = byteLength2 >>> 0;
                if (!noAssert) {
                  checkOffset(offset, byteLength2, this.length);
                }
                var val = this[offset + --byteLength2];
                var mul = 1;
                while (byteLength2 > 0 && (mul *= 256)) {
                  val += this[offset + --byteLength2] * mul;
                }
                return val;
              };
              Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 1, this.length);
                return this[offset];
              };
              Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 2, this.length);
                return this[offset] | this[offset + 1] << 8;
              };
              Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 2, this.length);
                return this[offset] << 8 | this[offset + 1];
              };
              Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 4, this.length);
                return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
              };
              Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 4, this.length);
                return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
              };
              Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
                offset = offset >>> 0;
                validateNumber(offset, "offset");
                var first = this[offset];
                var last = this[offset + 7];
                if (first === void 0 || last === void 0) {
                  boundsError(offset, this.length - 8);
                }
                var lo = first + this[++offset] * Math.pow(2, 8) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 24);
                var hi = this[++offset] + this[++offset] * Math.pow(2, 8) + this[++offset] * Math.pow(2, 16) + last * Math.pow(2, 24);
                return BigInt(lo) + (BigInt(hi) << BigInt(32));
              });
              Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
                offset = offset >>> 0;
                validateNumber(offset, "offset");
                var first = this[offset];
                var last = this[offset + 7];
                if (first === void 0 || last === void 0) {
                  boundsError(offset, this.length - 8);
                }
                var hi = first * Math.pow(2, 24) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + this[++offset];
                var lo = this[++offset] * Math.pow(2, 24) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + last;
                return (BigInt(hi) << BigInt(32)) + BigInt(lo);
              });
              Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
                offset = offset >>> 0;
                byteLength2 = byteLength2 >>> 0;
                if (!noAssert) checkOffset(offset, byteLength2, this.length);
                var val = this[offset];
                var mul = 1;
                var i = 0;
                while (++i < byteLength2 && (mul *= 256)) {
                  val += this[offset + i] * mul;
                }
                mul *= 128;
                if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
                return val;
              };
              Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
                offset = offset >>> 0;
                byteLength2 = byteLength2 >>> 0;
                if (!noAssert) checkOffset(offset, byteLength2, this.length);
                var i = byteLength2;
                var mul = 1;
                var val = this[offset + --i];
                while (i > 0 && (mul *= 256)) {
                  val += this[offset + --i] * mul;
                }
                mul *= 128;
                if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
                return val;
              };
              Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 1, this.length);
                if (!(this[offset] & 128)) return this[offset];
                return (255 - this[offset] + 1) * -1;
              };
              Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 2, this.length);
                var val = this[offset] | this[offset + 1] << 8;
                return val & 32768 ? val | 4294901760 : val;
              };
              Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 2, this.length);
                var val = this[offset + 1] | this[offset] << 8;
                return val & 32768 ? val | 4294901760 : val;
              };
              Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 4, this.length);
                return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
              };
              Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 4, this.length);
                return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
              };
              Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
                offset = offset >>> 0;
                validateNumber(offset, "offset");
                var first = this[offset];
                var last = this[offset + 7];
                if (first === void 0 || last === void 0) {
                  boundsError(offset, this.length - 8);
                }
                var val = this[offset + 4] + this[offset + 5] * Math.pow(2, 8) + this[offset + 6] * Math.pow(2, 16) + (last << 24);
                return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * Math.pow(2, 8) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 24));
              });
              Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
                offset = offset >>> 0;
                validateNumber(offset, "offset");
                var first = this[offset];
                var last = this[offset + 7];
                if (first === void 0 || last === void 0) {
                  boundsError(offset, this.length - 8);
                }
                var val = (first << 24) + // Overflow
                this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + this[++offset];
                return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * Math.pow(2, 24) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + last);
              });
              Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 4, this.length);
                return ieee754.read(this, offset, true, 23, 4);
              };
              Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 4, this.length);
                return ieee754.read(this, offset, false, 23, 4);
              };
              Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 8, this.length);
                return ieee754.read(this, offset, true, 52, 8);
              };
              Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
                offset = offset >>> 0;
                if (!noAssert) checkOffset(offset, 8, this.length);
                return ieee754.read(this, offset, false, 52, 8);
              };
              function checkInt(buf, value, offset, ext, max, min) {
                if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
                if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
                if (offset + ext > buf.length) throw new RangeError("Index out of range");
              }
              Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
                value = +value;
                offset = offset >>> 0;
                byteLength2 = byteLength2 >>> 0;
                if (!noAssert) {
                  var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
                  checkInt(this, value, offset, byteLength2, maxBytes, 0);
                }
                var mul = 1;
                var i = 0;
                this[offset] = value & 255;
                while (++i < byteLength2 && (mul *= 256)) {
                  this[offset + i] = value / mul & 255;
                }
                return offset + byteLength2;
              };
              Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
                value = +value;
                offset = offset >>> 0;
                byteLength2 = byteLength2 >>> 0;
                if (!noAssert) {
                  var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
                  checkInt(this, value, offset, byteLength2, maxBytes, 0);
                }
                var i = byteLength2 - 1;
                var mul = 1;
                this[offset + i] = value & 255;
                while (--i >= 0 && (mul *= 256)) {
                  this[offset + i] = value / mul & 255;
                }
                return offset + byteLength2;
              };
              Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
                this[offset] = value & 255;
                return offset + 1;
              };
              Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
                this[offset] = value & 255;
                this[offset + 1] = value >>> 8;
                return offset + 2;
              };
              Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
                this[offset] = value >>> 8;
                this[offset + 1] = value & 255;
                return offset + 2;
              };
              Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
                this[offset + 3] = value >>> 24;
                this[offset + 2] = value >>> 16;
                this[offset + 1] = value >>> 8;
                this[offset] = value & 255;
                return offset + 4;
              };
              Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
                this[offset] = value >>> 24;
                this[offset + 1] = value >>> 16;
                this[offset + 2] = value >>> 8;
                this[offset + 3] = value & 255;
                return offset + 4;
              };
              function wrtBigUInt64LE(buf, value, offset, min, max) {
                checkIntBI(value, min, max, buf, offset, 7);
                var lo = Number(value & BigInt(4294967295));
                buf[offset++] = lo;
                lo = lo >> 8;
                buf[offset++] = lo;
                lo = lo >> 8;
                buf[offset++] = lo;
                lo = lo >> 8;
                buf[offset++] = lo;
                var hi = Number(value >> BigInt(32) & BigInt(4294967295));
                buf[offset++] = hi;
                hi = hi >> 8;
                buf[offset++] = hi;
                hi = hi >> 8;
                buf[offset++] = hi;
                hi = hi >> 8;
                buf[offset++] = hi;
                return offset;
              }
              function wrtBigUInt64BE(buf, value, offset, min, max) {
                checkIntBI(value, min, max, buf, offset, 7);
                var lo = Number(value & BigInt(4294967295));
                buf[offset + 7] = lo;
                lo = lo >> 8;
                buf[offset + 6] = lo;
                lo = lo >> 8;
                buf[offset + 5] = lo;
                lo = lo >> 8;
                buf[offset + 4] = lo;
                var hi = Number(value >> BigInt(32) & BigInt(4294967295));
                buf[offset + 3] = hi;
                hi = hi >> 8;
                buf[offset + 2] = hi;
                hi = hi >> 8;
                buf[offset + 1] = hi;
                hi = hi >> 8;
                buf[offset] = hi;
                return offset + 8;
              }
              Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value) {
                var offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
                return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
              });
              Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value) {
                var offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
                return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
              });
              Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) {
                  var limit = Math.pow(2, 8 * byteLength2 - 1);
                  checkInt(this, value, offset, byteLength2, limit - 1, -limit);
                }
                var i = 0;
                var mul = 1;
                var sub = 0;
                this[offset] = value & 255;
                while (++i < byteLength2 && (mul *= 256)) {
                  if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
                    sub = 1;
                  }
                  this[offset + i] = (value / mul >> 0) - sub & 255;
                }
                return offset + byteLength2;
              };
              Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) {
                  var limit = Math.pow(2, 8 * byteLength2 - 1);
                  checkInt(this, value, offset, byteLength2, limit - 1, -limit);
                }
                var i = byteLength2 - 1;
                var mul = 1;
                var sub = 0;
                this[offset + i] = value & 255;
                while (--i >= 0 && (mul *= 256)) {
                  if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
                    sub = 1;
                  }
                  this[offset + i] = (value / mul >> 0) - sub & 255;
                }
                return offset + byteLength2;
              };
              Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
                if (value < 0) value = 255 + value + 1;
                this[offset] = value & 255;
                return offset + 1;
              };
              Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
                this[offset] = value & 255;
                this[offset + 1] = value >>> 8;
                return offset + 2;
              };
              Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
                this[offset] = value >>> 8;
                this[offset + 1] = value & 255;
                return offset + 2;
              };
              Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
                this[offset] = value & 255;
                this[offset + 1] = value >>> 8;
                this[offset + 2] = value >>> 16;
                this[offset + 3] = value >>> 24;
                return offset + 4;
              };
              Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
                if (value < 0) value = 4294967295 + value + 1;
                this[offset] = value >>> 24;
                this[offset + 1] = value >>> 16;
                this[offset + 2] = value >>> 8;
                this[offset + 3] = value & 255;
                return offset + 4;
              };
              Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value) {
                var offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
                return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
              });
              Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value) {
                var offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
                return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
              });
              function checkIEEE754(buf, value, offset, ext, max, min) {
                if (offset + ext > buf.length) throw new RangeError("Index out of range");
                if (offset < 0) throw new RangeError("Index out of range");
              }
              function writeFloat(buf, value, offset, littleEndian, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) {
                  checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22);
                }
                ieee754.write(buf, value, offset, littleEndian, 23, 4);
                return offset + 4;
              }
              Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
                return writeFloat(this, value, offset, true, noAssert);
              };
              Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
                return writeFloat(this, value, offset, false, noAssert);
              };
              function writeDouble(buf, value, offset, littleEndian, noAssert) {
                value = +value;
                offset = offset >>> 0;
                if (!noAssert) {
                  checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292);
                }
                ieee754.write(buf, value, offset, littleEndian, 52, 8);
                return offset + 8;
              }
              Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
                return writeDouble(this, value, offset, true, noAssert);
              };
              Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
                return writeDouble(this, value, offset, false, noAssert);
              };
              Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
                if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer");
                if (!start) start = 0;
                if (!end && end !== 0) end = this.length;
                if (targetStart >= target.length) targetStart = target.length;
                if (!targetStart) targetStart = 0;
                if (end > 0 && end < start) end = start;
                if (end === start) return 0;
                if (target.length === 0 || this.length === 0) return 0;
                if (targetStart < 0) {
                  throw new RangeError("targetStart out of bounds");
                }
                if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
                if (end < 0) throw new RangeError("sourceEnd out of bounds");
                if (end > this.length) end = this.length;
                if (target.length - targetStart < end - start) {
                  end = target.length - targetStart + start;
                }
                var len = end - start;
                if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
                  this.copyWithin(targetStart, start, end);
                } else {
                  Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
                }
                return len;
              };
              Buffer2.prototype.fill = function fill(val, start, end, encoding) {
                if (typeof val === "string") {
                  if (typeof start === "string") {
                    encoding = start;
                    start = 0;
                    end = this.length;
                  } else if (typeof end === "string") {
                    encoding = end;
                    end = this.length;
                  }
                  if (encoding !== void 0 && typeof encoding !== "string") {
                    throw new TypeError("encoding must be a string");
                  }
                  if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
                    throw new TypeError("Unknown encoding: " + encoding);
                  }
                  if (val.length === 1) {
                    var code = val.charCodeAt(0);
                    if (encoding === "utf8" && code < 128 || encoding === "latin1") {
                      val = code;
                    }
                  }
                } else if (typeof val === "number") {
                  val = val & 255;
                } else if (typeof val === "boolean") {
                  val = Number(val);
                }
                if (start < 0 || this.length < start || this.length < end) {
                  throw new RangeError("Out of range index");
                }
                if (end <= start) {
                  return this;
                }
                start = start >>> 0;
                end = end === void 0 ? this.length : end >>> 0;
                if (!val) val = 0;
                var i;
                if (typeof val === "number") {
                  for (i = start; i < end; ++i) {
                    this[i] = val;
                  }
                } else {
                  var bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding);
                  var len = bytes.length;
                  if (len === 0) {
                    throw new TypeError('The value "' + val + '" is invalid for argument "value"');
                  }
                  for (i = 0; i < end - start; ++i) {
                    this[i + start] = bytes[i % len];
                  }
                }
                return this;
              };
              var errors = {};
              function E2(sym, getMessage, Base) {
                errors[sym] = /* @__PURE__ */ function(_Base) {
                  function NodeError() {
                    var _this;
                    _classCallCheck(this, NodeError);
                    _this = _callSuper(this, NodeError);
                    Object.defineProperty(_this, "message", {
                      value: getMessage.apply(_this, arguments),
                      writable: true,
                      configurable: true
                    });
                    _this.name = "".concat(_this.name, " [").concat(sym, "]");
                    _this.stack;
                    delete _this.name;
                    return _this;
                  }
                  _inherits(NodeError, _Base);
                  return _createClass(NodeError, [{
                    key: "code",
                    get: function get() {
                      return sym;
                    },
                    set: function set(value) {
                      Object.defineProperty(this, "code", {
                        configurable: true,
                        enumerable: true,
                        value,
                        writable: true
                      });
                    }
                  }, {
                    key: "toString",
                    value: function toString() {
                      return "".concat(this.name, " [").concat(sym, "]: ").concat(this.message);
                    }
                  }]);
                }(Base);
              }
              E2("ERR_BUFFER_OUT_OF_BOUNDS", function(name2) {
                if (name2) {
                  return "".concat(name2, " is outside of buffer bounds");
                }
                return "Attempt to access memory outside buffer bounds";
              }, RangeError);
              E2("ERR_INVALID_ARG_TYPE", function(name2, actual) {
                return 'The "'.concat(name2, '" argument must be of type number. Received type ').concat(_typeof(actual));
              }, TypeError);
              E2("ERR_OUT_OF_RANGE", function(str, range, input) {
                var msg = 'The value of "'.concat(str, '" is out of range.');
                var received = input;
                if (Number.isInteger(input) && Math.abs(input) > Math.pow(2, 32)) {
                  received = addNumericalSeparator(String(input));
                } else if (typeof input === "bigint") {
                  received = String(input);
                  if (input > Math.pow(BigInt(2), BigInt(32)) || input < -Math.pow(BigInt(2), BigInt(32))) {
                    received = addNumericalSeparator(received);
                  }
                  received += "n";
                }
                msg += " It must be ".concat(range, ". Received ").concat(received);
                return msg;
              }, RangeError);
              function addNumericalSeparator(val) {
                var res = "";
                var i = val.length;
                var start = val[0] === "-" ? 1 : 0;
                for (; i >= start + 4; i -= 3) {
                  res = "_".concat(val.slice(i - 3, i)).concat(res);
                }
                return "".concat(val.slice(0, i)).concat(res);
              }
              function checkBounds(buf, offset, byteLength2) {
                validateNumber(offset, "offset");
                if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
                  boundsError(offset, buf.length - (byteLength2 + 1));
                }
              }
              function checkIntBI(value, min, max, buf, offset, byteLength2) {
                if (value > max || value < min) {
                  var n = typeof min === "bigint" ? "n" : "";
                  var range;
                  if (byteLength2 > 3) {
                    if (min === 0 || min === BigInt(0)) {
                      range = ">= 0".concat(n, " and < 2").concat(n, " ** ").concat((byteLength2 + 1) * 8).concat(n);
                    } else {
                      range = ">= -(2".concat(n, " ** ").concat((byteLength2 + 1) * 8 - 1).concat(n, ") and < 2 ** ") + "".concat((byteLength2 + 1) * 8 - 1).concat(n);
                    }
                  } else {
                    range = ">= ".concat(min).concat(n, " and <= ").concat(max).concat(n);
                  }
                  throw new errors.ERR_OUT_OF_RANGE("value", range, value);
                }
                checkBounds(buf, offset, byteLength2);
              }
              function validateNumber(value, name2) {
                if (typeof value !== "number") {
                  throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value);
                }
              }
              function boundsError(value, length, type) {
                if (Math.floor(value) !== value) {
                  validateNumber(value, type);
                  throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value);
                }
                if (length < 0) {
                  throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
                }
                throw new errors.ERR_OUT_OF_RANGE(type || "offset", ">= ".concat(type ? 1 : 0, " and <= ").concat(length), value);
              }
              var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
              function base64clean(str) {
                str = str.split("=")[0];
                str = str.trim().replace(INVALID_BASE64_RE, "");
                if (str.length < 2) return "";
                while (str.length % 4 !== 0) {
                  str = str + "=";
                }
                return str;
              }
              function utf8ToBytes(string, units) {
                units = units || Infinity;
                var codePoint;
                var length = string.length;
                var leadSurrogate = null;
                var bytes = [];
                for (var i = 0; i < length; ++i) {
                  codePoint = string.charCodeAt(i);
                  if (codePoint > 55295 && codePoint < 57344) {
                    if (!leadSurrogate) {
                      if (codePoint > 56319) {
                        if ((units -= 3) > -1) bytes.push(239, 191, 189);
                        continue;
                      } else if (i + 1 === length) {
                        if ((units -= 3) > -1) bytes.push(239, 191, 189);
                        continue;
                      }
                      leadSurrogate = codePoint;
                      continue;
                    }
                    if (codePoint < 56320) {
                      if ((units -= 3) > -1) bytes.push(239, 191, 189);
                      leadSurrogate = codePoint;
                      continue;
                    }
                    codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
                  } else if (leadSurrogate) {
                    if ((units -= 3) > -1) bytes.push(239, 191, 189);
                  }
                  leadSurrogate = null;
                  if (codePoint < 128) {
                    if ((units -= 1) < 0) break;
                    bytes.push(codePoint);
                  } else if (codePoint < 2048) {
                    if ((units -= 2) < 0) break;
                    bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
                  } else if (codePoint < 65536) {
                    if ((units -= 3) < 0) break;
                    bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
                  } else if (codePoint < 1114112) {
                    if ((units -= 4) < 0) break;
                    bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
                  } else {
                    throw new Error("Invalid code point");
                  }
                }
                return bytes;
              }
              function asciiToBytes(str) {
                var byteArray = [];
                for (var i = 0; i < str.length; ++i) {
                  byteArray.push(str.charCodeAt(i) & 255);
                }
                return byteArray;
              }
              function utf16leToBytes(str, units) {
                var c, hi, lo;
                var byteArray = [];
                for (var i = 0; i < str.length; ++i) {
                  if ((units -= 2) < 0) break;
                  c = str.charCodeAt(i);
                  hi = c >> 8;
                  lo = c % 256;
                  byteArray.push(lo);
                  byteArray.push(hi);
                }
                return byteArray;
              }
              function base64ToBytes(str) {
                return base64.toByteArray(base64clean(str));
              }
              function blitBuffer(src, dst, offset, length) {
                var i;
                for (i = 0; i < length; ++i) {
                  if (i + offset >= dst.length || i >= src.length) break;
                  dst[i + offset] = src[i];
                }
                return i;
              }
              function isInstance(obj, type) {
                return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
              }
              function numberIsNaN(obj) {
                return obj !== obj;
              }
              var hexSliceLookupTable = function() {
                var alphabet = "0123456789abcdef";
                var table = new Array(256);
                for (var i = 0; i < 16; ++i) {
                  var i16 = i * 16;
                  for (var j = 0; j < 16; ++j) {
                    table[i16 + j] = alphabet[i] + alphabet[j];
                  }
                }
                return table;
              }();
              function defineBigIntMethod(fn) {
                return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
              }
              function BufferBigIntNotDefined() {
                throw new Error("BigInt not supported");
              }
            }
          ),
          /***/
          4844: (
            /***/
            function(module2) {
              module2.exports = scaleAndAdd;
              function scaleAndAdd(out, a, b, scale) {
                out[0] = a[0] + b[0] * scale;
                out[1] = a[1] + b[1] * scale;
                out[2] = a[2] + b[2] * scale;
                out[3] = a[3] + b[3] * scale;
                return out;
              }
            }
          ),
          /***/
          4905: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var tokenize = __webpack_require__2(5874);
              module2.exports = tokenizeString;
              function tokenizeString(str, opt) {
                var generator = tokenize(opt);
                var tokens = [];
                tokens = tokens.concat(generator(str));
                tokens = tokens.concat(generator(null));
                return tokens;
              }
            }
          ),
          /***/
          4935: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createTextSprites;
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var vectorizeText = __webpack_require__2(4359);
              var createShader = __webpack_require__2(1879).Q;
              var globals = window || process.global || {};
              var __TEXT_CACHE = globals.__TEXT_CACHE || {};
              globals.__TEXT_CACHE = {};
              var VERTEX_SIZE = 3;
              function TextSprites(gl2, shader, buffer, vao) {
                this.gl = gl2;
                this.shader = shader;
                this.buffer = buffer;
                this.vao = vao;
                this.tickOffset = this.tickCount = this.labelOffset = this.labelCount = null;
              }
              var proto = TextSprites.prototype;
              var SHAPE = [0, 0];
              proto.bind = function(model, view, projection, pixelScale) {
                this.vao.bind();
                this.shader.bind();
                var uniforms = this.shader.uniforms;
                uniforms.model = model;
                uniforms.view = view;
                uniforms.projection = projection;
                uniforms.pixelScale = pixelScale;
                SHAPE[0] = this.gl.drawingBufferWidth;
                SHAPE[1] = this.gl.drawingBufferHeight;
                this.shader.uniforms.resolution = SHAPE;
              };
              proto.unbind = function() {
                this.vao.unbind();
              };
              proto.update = function(bounds, labels, labelFont, ticks, tickFont) {
                var data = [];
                function addItem(t, text, font2, size, lineSpacing2, styletags2) {
                  var fontKey = [
                    font2.style,
                    font2.weight,
                    font2.variant,
                    font2.family
                  ].join("_");
                  var fontcache = __TEXT_CACHE[fontKey];
                  if (!fontcache) {
                    fontcache = __TEXT_CACHE[fontKey] = {};
                  }
                  var mesh = fontcache[text];
                  if (!mesh) {
                    mesh = fontcache[text] = tryVectorizeText(text, {
                      triangles: true,
                      font: font2.family,
                      fontStyle: font2.style,
                      fontWeight: font2.weight,
                      fontVariant: font2.variant,
                      textAlign: "center",
                      textBaseline: "middle",
                      lineSpacing: lineSpacing2,
                      styletags: styletags2
                    });
                  }
                  var scale = (size || 12) / 12;
                  var positions = mesh.positions;
                  var cells = mesh.cells;
                  for (var i2 = 0, nc = cells.length; i2 < nc; ++i2) {
                    var c = cells[i2];
                    for (var j = 2; j >= 0; --j) {
                      var p = positions[c[j]];
                      data.push(scale * p[0], -scale * p[1], t);
                    }
                  }
                }
                var tickOffset = [0, 0, 0];
                var tickCount = [0, 0, 0];
                var labelOffset = [0, 0, 0];
                var labelCount = [0, 0, 0];
                var lineSpacing = 1.25;
                var styletags = {
                  breaklines: true,
                  bolds: true,
                  italics: true,
                  subscripts: true,
                  superscripts: true
                };
                for (var d = 0; d < 3; ++d) {
                  labelOffset[d] = data.length / VERTEX_SIZE | 0;
                  addItem(
                    0.5 * (bounds[0][d] + bounds[1][d]),
                    labels[d],
                    labelFont[d],
                    12,
                    // labelFontSize
                    lineSpacing,
                    styletags
                  );
                  labelCount[d] = (data.length / VERTEX_SIZE | 0) - labelOffset[d];
                  tickOffset[d] = data.length / VERTEX_SIZE | 0;
                  for (var i = 0; i < ticks[d].length; ++i) {
                    if (!ticks[d][i].text) {
                      continue;
                    }
                    var font = {
                      family: ticks[d][i].font || tickFont[d].family,
                      style: tickFont[d].fontStyle || tickFont[d].style,
                      weight: tickFont[d].fontWeight || tickFont[d].weight,
                      variant: tickFont[d].fontVariant || tickFont[d].variant
                    };
                    addItem(
                      ticks[d][i].x,
                      ticks[d][i].text,
                      font,
                      ticks[d][i].fontSize || 12,
                      lineSpacing,
                      styletags
                    );
                  }
                  tickCount[d] = (data.length / VERTEX_SIZE | 0) - tickOffset[d];
                }
                this.buffer.update(data);
                this.tickOffset = tickOffset;
                this.tickCount = tickCount;
                this.labelOffset = labelOffset;
                this.labelCount = labelCount;
              };
              proto.drawTicks = function(d, scale, angle, offset, color2, axis, alignDir, alignOpt) {
                if (!this.tickCount[d]) {
                  return;
                }
                this.shader.uniforms.axis = axis;
                this.shader.uniforms.color = color2;
                this.shader.uniforms.angle = angle;
                this.shader.uniforms.scale = scale;
                this.shader.uniforms.offset = offset;
                this.shader.uniforms.alignDir = alignDir;
                this.shader.uniforms.alignOpt = alignOpt;
                this.vao.draw(this.gl.TRIANGLES, this.tickCount[d], this.tickOffset[d]);
              };
              proto.drawLabel = function(d, scale, angle, offset, color2, axis, alignDir, alignOpt) {
                if (!this.labelCount[d]) {
                  return;
                }
                this.shader.uniforms.axis = axis;
                this.shader.uniforms.color = color2;
                this.shader.uniforms.angle = angle;
                this.shader.uniforms.scale = scale;
                this.shader.uniforms.offset = offset;
                this.shader.uniforms.alignDir = alignDir;
                this.shader.uniforms.alignOpt = alignOpt;
                this.vao.draw(this.gl.TRIANGLES, this.labelCount[d], this.labelOffset[d]);
              };
              proto.dispose = function() {
                this.shader.dispose();
                this.vao.dispose();
                this.buffer.dispose();
              };
              function tryVectorizeText(text, options) {
                try {
                  return vectorizeText(text, options);
                } catch (e) {
                  console.warn('error vectorizing text:"' + text + '" error:', e);
                  return {
                    cells: [],
                    positions: []
                  };
                }
              }
              function createTextSprites(gl2, bounds, labels, labelFont, ticks, tickFont) {
                var buffer = createBuffer(gl2);
                var vao = createVAO(gl2, [
                  {
                    "buffer": buffer,
                    "size": 3
                  }
                ]);
                var shader = createShader(gl2);
                shader.attributes.position.location = 0;
                var result = new TextSprites(
                  gl2,
                  shader,
                  buffer,
                  vao
                );
                result.update(bounds, labels, labelFont, ticks, tickFont);
                return result;
              }
            }
          ),
          /***/
          5023: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bsearch = __webpack_require__2(2478);
              module2.exports = classifyFaces;
              function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) {
                this.cells = cells;
                this.neighbor = neighbor;
                this.flags = flags;
                this.constraint = constraint;
                this.active = active;
                this.next = next;
                this.boundary = boundary;
              }
              var proto = FaceIndex.prototype;
              function compareCell(a, b) {
                return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
              }
              proto.locate = /* @__PURE__ */ function() {
                var key = [0, 0, 0];
                return function(a, b, c) {
                  var x = a, y = b, z = c;
                  if (b < c) {
                    if (b < a) {
                      x = b;
                      y = c;
                      z = a;
                    }
                  } else if (c < a) {
                    x = c;
                    y = a;
                    z = b;
                  }
                  if (x < 0) {
                    return -1;
                  }
                  key[0] = x;
                  key[1] = y;
                  key[2] = z;
                  return bsearch.eq(this.cells, key, compareCell);
                };
              }();
              function indexCells(triangulation, infinity) {
                var cells = triangulation.cells();
                var nc = cells.length;
                for (var i = 0; i < nc; ++i) {
                  var c = cells[i];
                  var x = c[0], y = c[1], z = c[2];
                  if (y < z) {
                    if (y < x) {
                      c[0] = y;
                      c[1] = z;
                      c[2] = x;
                    }
                  } else if (z < x) {
                    c[0] = z;
                    c[1] = x;
                    c[2] = y;
                  }
                }
                cells.sort(compareCell);
                var flags = new Array(nc);
                for (var i = 0; i < flags.length; ++i) {
                  flags[i] = 0;
                }
                var active = [];
                var next = [];
                var neighbor = new Array(3 * nc);
                var constraint = new Array(3 * nc);
                var boundary = null;
                if (infinity) {
                  boundary = [];
                }
                var index = new FaceIndex(
                  cells,
                  neighbor,
                  constraint,
                  flags,
                  active,
                  next,
                  boundary
                );
                for (var i = 0; i < nc; ++i) {
                  var c = cells[i];
                  for (var j = 0; j < 3; ++j) {
                    var x = c[j], y = c[(j + 1) % 3];
                    var a = neighbor[3 * i + j] = index.locate(y, x, triangulation.opposite(y, x));
                    var b = constraint[3 * i + j] = triangulation.isConstraint(x, y);
                    if (a < 0) {
                      if (b) {
                        next.push(i);
                      } else {
                        active.push(i);
                        flags[i] = 1;
                      }
                      if (infinity) {
                        boundary.push([y, x, -1]);
                      }
                    }
                  }
                }
                return index;
              }
              function filterCells(cells, flags, target) {
                var ptr = 0;
                for (var i = 0; i < cells.length; ++i) {
                  if (flags[i] === target) {
                    cells[ptr++] = cells[i];
                  }
                }
                cells.length = ptr;
                return cells;
              }
              function classifyFaces(triangulation, target, infinity) {
                var index = indexCells(triangulation, infinity);
                if (target === 0) {
                  if (infinity) {
                    return index.cells.concat(index.boundary);
                  } else {
                    return index.cells;
                  }
                }
                var side = 1;
                var active = index.active;
                var next = index.next;
                var flags = index.flags;
                var cells = index.cells;
                var constraint = index.constraint;
                var neighbor = index.neighbor;
                while (active.length > 0 || next.length > 0) {
                  while (active.length > 0) {
                    var t = active.pop();
                    if (flags[t] === -side) {
                      continue;
                    }
                    flags[t] = side;
                    var c = cells[t];
                    for (var j = 0; j < 3; ++j) {
                      var f = neighbor[3 * t + j];
                      if (f >= 0 && flags[f] === 0) {
                        if (constraint[3 * t + j]) {
                          next.push(f);
                        } else {
                          active.push(f);
                          flags[f] = side;
                        }
                      }
                    }
                  }
                  var tmp = next;
                  next = active;
                  active = tmp;
                  next.length = 0;
                  side = -side;
                }
                var result = filterCells(cells, flags, target);
                if (infinity) {
                  return result.concat(index.boundary);
                }
                return result;
              }
            }
          ),
          /***/
          5033: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = extractPlanes;
              function extractPlanes(M, zNear, zFar) {
                var z = zNear || 0;
                var zf = zFar || 1;
                return [
                  [M[12] + M[0], M[13] + M[1], M[14] + M[2], M[15] + M[3]],
                  [M[12] - M[0], M[13] - M[1], M[14] - M[2], M[15] - M[3]],
                  [M[12] + M[4], M[13] + M[5], M[14] + M[6], M[15] + M[7]],
                  [M[12] - M[4], M[13] - M[5], M[14] - M[6], M[15] - M[7]],
                  [z * M[12] + M[8], z * M[13] + M[9], z * M[14] + M[10], z * M[15] + M[11]],
                  [zf * M[12] - M[8], zf * M[13] - M[9], zf * M[14] - M[10], zf * M[15] - M[11]]
                ];
              }
            }
          ),
          /***/
          5085: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = preprocessPolygon;
              var orient = __webpack_require__2(3250)[3];
              var makeSlabs = __webpack_require__2(4209);
              var makeIntervalTree = __webpack_require__2(3352);
              var bsearch = __webpack_require__2(2478);
              function visitInterval() {
                return true;
              }
              function intervalSearch(table) {
                return function(x, y) {
                  var tree = table[x];
                  if (tree) {
                    return !!tree.queryPoint(y, visitInterval);
                  }
                  return false;
                };
              }
              function buildVerticalIndex(segments) {
                var table = {};
                for (var i = 0; i < segments.length; ++i) {
                  var s = segments[i];
                  var x = s[0][0];
                  var y0 = s[0][1];
                  var y1 = s[1][1];
                  var p = [Math.min(y0, y1), Math.max(y0, y1)];
                  if (x in table) {
                    table[x].push(p);
                  } else {
                    table[x] = [p];
                  }
                }
                var intervalTable = {};
                var keys = Object.keys(table);
                for (var i = 0; i < keys.length; ++i) {
                  var segs = table[keys[i]];
                  intervalTable[keys[i]] = makeIntervalTree(segs);
                }
                return intervalSearch(intervalTable);
              }
              function buildSlabSearch(slabs, coordinates) {
                return function(p) {
                  var bucket = bsearch.le(coordinates, p[0]);
                  if (bucket < 0) {
                    return 1;
                  }
                  var root = slabs[bucket];
                  if (!root) {
                    if (bucket > 0 && coordinates[bucket] === p[0]) {
                      root = slabs[bucket - 1];
                    } else {
                      return 1;
                    }
                  }
                  var lastOrientation = 1;
                  while (root) {
                    var s = root.key;
                    var o = orient(p, s[0], s[1]);
                    if (s[0][0] < s[1][0]) {
                      if (o < 0) {
                        root = root.left;
                      } else if (o > 0) {
                        lastOrientation = -1;
                        root = root.right;
                      } else {
                        return 0;
                      }
                    } else {
                      if (o > 0) {
                        root = root.left;
                      } else if (o < 0) {
                        lastOrientation = 1;
                        root = root.right;
                      } else {
                        return 0;
                      }
                    }
                  }
                  return lastOrientation;
                };
              }
              function classifyEmpty(p) {
                return 1;
              }
              function createClassifyVertical(testVertical) {
                return function classify(p) {
                  if (testVertical(p[0], p[1])) {
                    return 0;
                  }
                  return 1;
                };
              }
              function createClassifyPointDegen(testVertical, testNormal) {
                return function classify(p) {
                  if (testVertical(p[0], p[1])) {
                    return 0;
                  }
                  return testNormal(p);
                };
              }
              function preprocessPolygon(loops) {
                var numLoops = loops.length;
                var segments = [];
                var vsegments = [];
                var ptr = 0;
                for (var i = 0; i < numLoops; ++i) {
                  var loop = loops[i];
                  var numVertices = loop.length;
                  for (var s = numVertices - 1, t = 0; t < numVertices; s = t++) {
                    var a = loop[s];
                    var b = loop[t];
                    if (a[0] === b[0]) {
                      vsegments.push([a, b]);
                    } else {
                      segments.push([a, b]);
                    }
                  }
                }
                if (segments.length === 0) {
                  if (vsegments.length === 0) {
                    return classifyEmpty;
                  } else {
                    return createClassifyVertical(buildVerticalIndex(vsegments));
                  }
                }
                var slabs = makeSlabs(segments);
                var testSlab = buildSlabSearch(slabs.slabs, slabs.coordinates);
                if (vsegments.length === 0) {
                  return testSlab;
                } else {
                  return createClassifyPointDegen(
                    buildVerticalIndex(vsegments),
                    testSlab
                  );
                }
              }
            }
          ),
          /***/
          5091: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              "use strict";
              exports2.shader = getShaderReference;
              exports2.program = createProgram;
              var GLError = __webpack_require__2(8866);
              var formatCompilerError = __webpack_require__2(2992);
              var weakMap = typeof WeakMap === "undefined" ? __webpack_require__2(606) : WeakMap;
              var CACHE = new weakMap();
              var SHADER_COUNTER = 0;
              function ShaderReference(id, src, type, shader, programs, count, cache) {
                this.id = id;
                this.src = src;
                this.type = type;
                this.shader = shader;
                this.count = count;
                this.programs = [];
                this.cache = cache;
              }
              ShaderReference.prototype.dispose = function() {
                if (--this.count === 0) {
                  var cache = this.cache;
                  var gl2 = cache.gl;
                  var programs = this.programs;
                  for (var i = 0, n = programs.length; i < n; ++i) {
                    var p = cache.programs[programs[i]];
                    if (p) {
                      delete cache.programs[i];
                      gl2.deleteProgram(p);
                    }
                  }
                  gl2.deleteShader(this.shader);
                  delete cache.shaders[this.type === gl2.FRAGMENT_SHADER | 0][this.src];
                }
              };
              function ContextCache(gl2) {
                this.gl = gl2;
                this.shaders = [{}, {}];
                this.programs = {};
              }
              var proto = ContextCache.prototype;
              function compileShader(gl2, type, src) {
                var shader = gl2.createShader(type);
                gl2.shaderSource(shader, src);
                gl2.compileShader(shader);
                if (!gl2.getShaderParameter(shader, gl2.COMPILE_STATUS)) {
                  var errLog = gl2.getShaderInfoLog(shader);
                  try {
                    var fmt = formatCompilerError(errLog, src, type);
                  } catch (e) {
                    console.warn("Failed to format compiler error: " + e);
                    throw new GLError(errLog, "Error compiling shader:\n" + errLog);
                  }
                  throw new GLError(errLog, fmt.short, fmt.long);
                }
                return shader;
              }
              proto.getShaderReference = function(type, src) {
                var gl2 = this.gl;
                var shaders = this.shaders[type === gl2.FRAGMENT_SHADER | 0];
                var shader = shaders[src];
                if (!shader || !gl2.isShader(shader.shader)) {
                  var shaderObj = compileShader(gl2, type, src);
                  shader = shaders[src] = new ShaderReference(
                    SHADER_COUNTER++,
                    src,
                    type,
                    shaderObj,
                    [],
                    1,
                    this
                  );
                } else {
                  shader.count += 1;
                }
                return shader;
              };
              function linkProgram(gl2, vshader, fshader, attribs, locations) {
                var program = gl2.createProgram();
                gl2.attachShader(program, vshader);
                gl2.attachShader(program, fshader);
                for (var i = 0; i < attribs.length; ++i) {
                  gl2.bindAttribLocation(program, locations[i], attribs[i]);
                }
                gl2.linkProgram(program);
                if (!gl2.getProgramParameter(program, gl2.LINK_STATUS)) {
                  var errLog = gl2.getProgramInfoLog(program);
                  throw new GLError(errLog, "Error linking program: " + errLog);
                }
                return program;
              }
              proto.getProgram = function(vref, fref, attribs, locations) {
                var token = [vref.id, fref.id, attribs.join(":"), locations.join(":")].join("@");
                var prog = this.programs[token];
                if (!prog || !this.gl.isProgram(prog)) {
                  this.programs[token] = prog = linkProgram(
                    this.gl,
                    vref.shader,
                    fref.shader,
                    attribs,
                    locations
                  );
                  vref.programs.push(token);
                  fref.programs.push(token);
                }
                return prog;
              };
              function getCache(gl2) {
                var ctxCache = CACHE.get(gl2);
                if (!ctxCache) {
                  ctxCache = new ContextCache(gl2);
                  CACHE.set(gl2, ctxCache);
                }
                return ctxCache;
              }
              function getShaderReference(gl2, type, src) {
                return getCache(gl2).getShaderReference(type, src);
              }
              function createProgram(gl2, vref, fref, attribs, locations) {
                return getCache(gl2).getProgram(vref, fref, attribs, locations);
              }
            }
          ),
          /***/
          5093: (
            /***/
            function(module2) {
              module2.exports = negate;
              function negate(out, a) {
                out[0] = -a[0];
                out[1] = -a[1];
                out[2] = -a[2];
                return out;
              }
            }
          ),
          /***/
          5137: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = forEach;
              var vec = __webpack_require__2(1091)();
              function forEach(a, stride, offset, count, fn, arg) {
                var i, l;
                if (!stride) {
                  stride = 3;
                }
                if (!offset) {
                  offset = 0;
                }
                if (count) {
                  l = Math.min(count * stride + offset, a.length);
                } else {
                  l = a.length;
                }
                for (i = offset; i < l; i += stride) {
                  vec[0] = a[i];
                  vec[1] = a[i + 1];
                  vec[2] = a[i + 2];
                  fn(vec, vec, arg);
                  a[i] = vec[0];
                  a[i + 1] = vec[1];
                  a[i + 2] = vec[2];
                }
                return a;
              }
            }
          ),
          /***/
          5171: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var gl10 = __webpack_require__2(737);
              module2.exports = function lookupConstant(number) {
                return gl10[number];
              };
            }
          ),
          /***/
          5177: (
            /***/
            function(module2) {
              module2.exports = normalize;
              function normalize(out, a) {
                var x = a[0], y = a[1], z = a[2], w = a[3];
                var len = x * x + y * y + z * z + w * w;
                if (len > 0) {
                  len = 1 / Math.sqrt(len);
                  out[0] = x * len;
                  out[1] = y * len;
                  out[2] = z * len;
                  out[3] = w * len;
                }
                return out;
              }
            }
          ),
          /***/
          5202: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var robustDot = __webpack_require__2(1944);
              var robustSum = __webpack_require__2(8210);
              module2.exports = splitPolygon;
              module2.exports.positive = positive;
              module2.exports.negative = negative;
              function planeT(p, plane) {
                var r = robustSum(robustDot(p, plane), [plane[plane.length - 1]]);
                return r[r.length - 1];
              }
              function lerpW(a, wa, b, wb) {
                var d = wb - wa;
                var t = -wa / d;
                if (t < 0) {
                  t = 0;
                } else if (t > 1) {
                  t = 1;
                }
                var ti = 1 - t;
                var n = a.length;
                var r = new Array(n);
                for (var i = 0; i < n; ++i) {
                  r[i] = t * a[i] + ti * b[i];
                }
                return r;
              }
              function splitPolygon(points, plane) {
                var pos = [];
                var neg = [];
                var a = planeT(points[points.length - 1], plane);
                for (var s = points[points.length - 1], t = points[0], i = 0; i < points.length; ++i, s = t) {
                  t = points[i];
                  var b = planeT(t, plane);
                  if (a < 0 && b > 0 || a > 0 && b < 0) {
                    var p = lerpW(s, b, t, a);
                    pos.push(p);
                    neg.push(p.slice());
                  }
                  if (b < 0) {
                    neg.push(t.slice());
                  } else if (b > 0) {
                    pos.push(t.slice());
                  } else {
                    pos.push(t.slice());
                    neg.push(t.slice());
                  }
                  a = b;
                }
                return { positive: pos, negative: neg };
              }
              function positive(points, plane) {
                var pos = [];
                var a = planeT(points[points.length - 1], plane);
                for (var s = points[points.length - 1], t = points[0], i = 0; i < points.length; ++i, s = t) {
                  t = points[i];
                  var b = planeT(t, plane);
                  if (a < 0 && b > 0 || a > 0 && b < 0) {
                    pos.push(lerpW(s, b, t, a));
                  }
                  if (b >= 0) {
                    pos.push(t.slice());
                  }
                  a = b;
                }
                return pos;
              }
              function negative(points, plane) {
                var neg = [];
                var a = planeT(points[points.length - 1], plane);
                for (var s = points[points.length - 1], t = points[0], i = 0; i < points.length; ++i, s = t) {
                  t = points[i];
                  var b = planeT(t, plane);
                  if (a < 0 && b > 0 || a > 0 && b < 0) {
                    neg.push(lerpW(s, b, t, a));
                  }
                  if (b <= 0) {
                    neg.push(t.slice());
                  }
                  a = b;
                }
                return neg;
              }
            }
          ),
          /***/
          5219: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = function(str) {
                var l = str.length, a;
                for (var i = 0; i < l; i++) {
                  a = str.charCodeAt(i);
                  if ((a < 9 || a > 13) && a !== 32 && a !== 133 && a !== 160 && a !== 5760 && a !== 6158 && (a < 8192 || a > 8205) && a !== 8232 && a !== 8233 && a !== 8239 && a !== 8287 && a !== 8288 && a !== 12288 && a !== 65279) {
                    return false;
                  }
                }
                return true;
              };
            }
          ),
          /***/
          5250: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = twoProduct;
              var SPLITTER = +(Math.pow(2, 27) + 1);
              function twoProduct(a, b, result) {
                var x = a * b;
                var c = SPLITTER * a;
                var abig = c - a;
                var ahi = c - abig;
                var alo = a - ahi;
                var d = SPLITTER * b;
                var bbig = d - b;
                var bhi = d - bbig;
                var blo = b - bhi;
                var err1 = x - ahi * bhi;
                var err2 = err1 - alo * bhi;
                var err3 = err2 - ahi * blo;
                var y = alo * blo - err3;
                if (result) {
                  result[0] = y;
                  result[1] = x;
                  return result;
                }
                return [y, x];
              }
            }
          ),
          /***/
          5298: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              var CACHED_CWiseOp = {
                "float64,2,1,0": function() {
                  return function divseq_cwise_loop_2s1s0m3f64(SS, a0, t02, p0, Y0) {
                    var s0 = SS[0], s1 = SS[1], s2 = SS[2], t0p0 = t02[0], t0p1 = t02[1], t0p2 = t02[2];
                    p0 |= 0;
                    var i0 = 0, i1 = 0, i2 = 0, d0s0 = t0p2, d0s1 = t0p1 - s2 * t0p2, d0s2 = t0p0 - s1 * t0p1;
                    for (i2 = 0; i2 < s0; ++i2) {
                      for (i1 = 0; i1 < s1; ++i1) {
                        for (i0 = 0; i0 < s2; ++i0) {
                          a0[p0] /= Y0;
                          p0 += d0s0;
                        }
                        p0 += d0s1;
                      }
                      p0 += d0s2;
                    }
                  };
                },
                "uint8,2,0,1,float64,2,1,0": function() {
                  return function muls_cwise_loop_2s0s1m1u8f64(SS, a0, t02, p0, a1, t12, p1, Y0) {
                    var s0 = SS[0], s1 = SS[1], s2 = SS[2], t0p0 = t02[0], t0p1 = t02[1], t0p2 = t02[2], t1p0 = t12[0], t1p1 = t12[1], t1p2 = t12[2];
                    p0 |= 0;
                    p1 |= 0;
                    var offset0 = p0;
                    var offset1 = p1;
                    for (var j1 = SS[0] | 0; j1 > 0; ) {
                      if (j1 < 64) {
                        s0 = j1;
                        j1 = 0;
                      } else {
                        s0 = 64;
                        j1 -= 64;
                      }
                      for (var j2 = SS[1] | 0; j2 > 0; ) {
                        if (j2 < 64) {
                          s1 = j2;
                          j2 = 0;
                        } else {
                          s1 = 64;
                          j2 -= 64;
                        }
                        p0 = offset0 + j1 * t0p0 + j2 * t0p1;
                        p1 = offset1 + j1 * t1p0 + j2 * t1p1;
                        var i0 = 0, i1 = 0, i2 = 0, d0s0 = t0p2, d0s1 = t0p0 - s2 * t0p2, d0s2 = t0p1 - s0 * t0p0, d1s0 = t1p2, d1s1 = t1p0 - s2 * t1p2, d1s2 = t1p1 - s0 * t1p0;
                        for (i2 = 0; i2 < s1; ++i2) {
                          for (i1 = 0; i1 < s0; ++i1) {
                            for (i0 = 0; i0 < s2; ++i0) {
                              a0[p0] = a1[p1] * Y0;
                              p0 += d0s0;
                              p1 += d1s0;
                            }
                            p0 += d0s1;
                            p1 += d1s1;
                          }
                          p0 += d0s2;
                          p1 += d1s2;
                        }
                      }
                    }
                  };
                },
                "float32,1,0,float32,1,0": function() {
                  return function assign_cwise_loop_1s0m2f32(SS, a0, t02, p0, a1, t12, p1) {
                    var s0 = SS[0], s1 = SS[1], t0p0 = t02[0], t0p1 = t02[1], t1p0 = t12[0], t1p1 = t12[1];
                    p0 |= 0;
                    p1 |= 0;
                    var i0 = 0, i1 = 0, d0s0 = t0p1, d0s1 = t0p0 - s1 * t0p1, d1s0 = t1p1, d1s1 = t1p0 - s1 * t1p1;
                    for (i1 = 0; i1 < s0; ++i1) {
                      for (i0 = 0; i0 < s1; ++i0) {
                        a0[p0] = a1[p1];
                        p0 += d0s0;
                        p1 += d1s0;
                      }
                      p0 += d0s1;
                      p1 += d1s1;
                    }
                  };
                },
                "float32,1,0,float32,0,1": function() {
                  return function assign_cwise_loop_1s0m0f32(SS, a0, t02, p0, a1, t12, p1) {
                    var s0 = SS[0], s1 = SS[1], t0p0 = t02[0], t0p1 = t02[1], t1p0 = t12[0], t1p1 = t12[1];
                    p0 |= 0;
                    p1 |= 0;
                    var offset0 = p0;
                    var offset1 = p1;
                    for (var j0 = SS[1] | 0; j0 > 0; ) {
                      if (j0 < 64) {
                        s1 = j0;
                        j0 = 0;
                      } else {
                        s1 = 64;
                        j0 -= 64;
                      }
                      for (var j1 = SS[0] | 0; j1 > 0; ) {
                        if (j1 < 64) {
                          s0 = j1;
                          j1 = 0;
                        } else {
                          s0 = 64;
                          j1 -= 64;
                        }
                        p0 = offset0 + j0 * t0p1 + j1 * t0p0;
                        p1 = offset1 + j0 * t1p1 + j1 * t1p0;
                        var i0 = 0, i1 = 0, d0s0 = t0p1, d0s1 = t0p0 - s1 * t0p1, d1s0 = t1p1, d1s1 = t1p0 - s1 * t1p1;
                        for (i1 = 0; i1 < s0; ++i1) {
                          for (i0 = 0; i0 < s1; ++i0) {
                            a0[p0] = a1[p1];
                            p0 += d0s0;
                            p1 += d1s0;
                          }
                          p0 += d0s1;
                          p1 += d1s1;
                        }
                      }
                    }
                  };
                },
                "uint8,2,0,1,uint8,1,2,0": function() {
                  return function assign_cwise_loop_2s0s1m0u8(SS, a0, t02, p0, a1, t12, p1) {
                    var s0 = SS[0], s1 = SS[1], s2 = SS[2], t0p0 = t02[0], t0p1 = t02[1], t0p2 = t02[2], t1p0 = t12[0], t1p1 = t12[1], t1p2 = t12[2];
                    p0 |= 0;
                    p1 |= 0;
                    var offset0 = p0;
                    var offset1 = p1;
                    for (var j0 = SS[2] | 0; j0 > 0; ) {
                      if (j0 < 64) {
                        s2 = j0;
                        j0 = 0;
                      } else {
                        s2 = 64;
                        j0 -= 64;
                      }
                      for (var j1 = SS[0] | 0; j1 > 0; ) {
                        if (j1 < 64) {
                          s0 = j1;
                          j1 = 0;
                        } else {
                          s0 = 64;
                          j1 -= 64;
                        }
                        for (var j2 = SS[1] | 0; j2 > 0; ) {
                          if (j2 < 64) {
                            s1 = j2;
                            j2 = 0;
                          } else {
                            s1 = 64;
                            j2 -= 64;
                          }
                          p0 = offset0 + j0 * t0p2 + j1 * t0p0 + j2 * t0p1;
                          p1 = offset1 + j0 * t1p2 + j1 * t1p0 + j2 * t1p1;
                          var i0 = 0, i1 = 0, i2 = 0, d0s0 = t0p2, d0s1 = t0p0 - s2 * t0p2, d0s2 = t0p1 - s0 * t0p0, d1s0 = t1p2, d1s1 = t1p0 - s2 * t1p2, d1s2 = t1p1 - s0 * t1p0;
                          for (i2 = 0; i2 < s1; ++i2) {
                            for (i1 = 0; i1 < s0; ++i1) {
                              for (i0 = 0; i0 < s2; ++i0) {
                                a0[p0] = a1[p1];
                                p0 += d0s0;
                                p1 += d1s0;
                              }
                              p0 += d0s1;
                              p1 += d1s1;
                            }
                            p0 += d0s2;
                            p1 += d1s2;
                          }
                        }
                      }
                    }
                  };
                },
                "uint8,2,0,1,array,2,0,1": function() {
                  return function assign_cwise_loop_2s0s1m3u8a(SS, a0, t02, p0, a1, t12, p1) {
                    var s0 = SS[0], s1 = SS[1], s2 = SS[2], t0p0 = t02[0], t0p1 = t02[1], t0p2 = t02[2], t1p0 = t12[0], t1p1 = t12[1], t1p2 = t12[2];
                    p0 |= 0;
                    p1 |= 0;
                    var i0 = 0, i1 = 0, i2 = 0, d0s0 = t0p2, d0s1 = t0p0 - s2 * t0p2, d0s2 = t0p1 - s0 * t0p0, d1s0 = t1p2, d1s1 = t1p0 - s2 * t1p2, d1s2 = t1p1 - s0 * t1p0;
                    for (i2 = 0; i2 < s1; ++i2) {
                      for (i1 = 0; i1 < s0; ++i1) {
                        for (i0 = 0; i0 < s2; ++i0) {
                          a0[p0] = a1[p1];
                          p0 += d0s0;
                          p1 += d1s0;
                        }
                        p0 += d0s1;
                        p1 += d1s1;
                      }
                      p0 += d0s2;
                      p1 += d1s2;
                    }
                  };
                }
              };
              function generateCWiseOp(proc, typesig) {
                var key = typesig.join(",");
                var f = CACHED_CWiseOp[key];
                return f();
              }
              var compile = generateCWiseOp;
              var CACHED_thunk = {
                mul: function(compile2) {
                  var CACHED = {};
                  return function mul_cwise_thunk(array0, array1, array2) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, t22 = array2.dtype, r2 = array2.order, type = [t02, r0.join(), t12, r1.join(), t22, r2.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1, t22, r2]);
                    }
                    return proc(
                      array0.shape.slice(0),
                      array0.data,
                      array0.stride,
                      array0.offset | 0,
                      array1.data,
                      array1.stride,
                      array1.offset | 0,
                      array2.data,
                      array2.stride,
                      array2.offset | 0
                    );
                  };
                },
                muls: function(compile2) {
                  var CACHED = {};
                  return function muls_cwise_thunk(array0, array1, scalar2) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, type = [t02, r0.join(), t12, r1.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1]);
                    }
                    return proc(
                      array0.shape.slice(0),
                      array0.data,
                      array0.stride,
                      array0.offset | 0,
                      array1.data,
                      array1.stride,
                      array1.offset | 0,
                      scalar2
                    );
                  };
                },
                mulseq: function(compile2) {
                  var CACHED = {};
                  return function mulseq_cwise_thunk(array0, scalar1) {
                    var t02 = array0.dtype, r0 = array0.order, type = [t02, r0.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0]);
                    }
                    return proc(array0.shape.slice(0), array0.data, array0.stride, array0.offset | 0, scalar1);
                  };
                },
                div: function(compile2) {
                  var CACHED = {};
                  return function div_cwise_thunk(array0, array1, array2) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, t22 = array2.dtype, r2 = array2.order, type = [t02, r0.join(), t12, r1.join(), t22, r2.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1, t22, r2]);
                    }
                    return proc(
                      array0.shape.slice(0),
                      array0.data,
                      array0.stride,
                      array0.offset | 0,
                      array1.data,
                      array1.stride,
                      array1.offset | 0,
                      array2.data,
                      array2.stride,
                      array2.offset | 0
                    );
                  };
                },
                divs: function(compile2) {
                  var CACHED = {};
                  return function divs_cwise_thunk(array0, array1, scalar2) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, type = [t02, r0.join(), t12, r1.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1]);
                    }
                    return proc(
                      array0.shape.slice(0),
                      array0.data,
                      array0.stride,
                      array0.offset | 0,
                      array1.data,
                      array1.stride,
                      array1.offset | 0,
                      scalar2
                    );
                  };
                },
                divseq: function(compile2) {
                  var CACHED = {};
                  return function divseq_cwise_thunk(array0, scalar1) {
                    var t02 = array0.dtype, r0 = array0.order, type = [t02, r0.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0]);
                    }
                    return proc(array0.shape.slice(0), array0.data, array0.stride, array0.offset | 0, scalar1);
                  };
                },
                assign: function(compile2) {
                  var CACHED = {};
                  return function assign_cwise_thunk(array0, array1) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, type = [t02, r0.join(), t12, r1.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1]);
                    }
                    return proc(
                      array0.shape.slice(0),
                      array0.data,
                      array0.stride,
                      array0.offset | 0,
                      array1.data,
                      array1.stride,
                      array1.offset | 0
                    );
                  };
                }
              };
              function createThunk(proc) {
                var thunk = CACHED_thunk[proc.funcName];
                return thunk(compile.bind(void 0, proc));
              }
              function makeOp(user_args) {
                return createThunk({
                  funcName: user_args.funcName
                });
              }
              var assign_ops = {
                mul: "*",
                div: "/"
              };
              (function() {
                for (var id in assign_ops) {
                  exports2[id] = makeOp({
                    funcName: id
                  });
                  exports2[id + "s"] = makeOp({
                    funcName: id + "s"
                  });
                  exports2[id + "seq"] = makeOp({
                    funcName: id + "seq"
                  });
                }
              })();
              exports2.assign = makeOp({
                funcName: "assign"
              });
            }
          ),
          /***/
          5304: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createBackgroundCube;
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createShader = __webpack_require__2(1879).bg;
              function BackgroundCube(gl2, buffer, vao, shader) {
                this.gl = gl2;
                this.buffer = buffer;
                this.vao = vao;
                this.shader = shader;
              }
              var proto = BackgroundCube.prototype;
              proto.draw = function(model, view, projection, bounds, enable, colors) {
                var needsBG = false;
                for (var i = 0; i < 3; ++i) {
                  needsBG = needsBG || enable[i];
                }
                if (!needsBG) {
                  return;
                }
                var gl2 = this.gl;
                gl2.enable(gl2.POLYGON_OFFSET_FILL);
                gl2.polygonOffset(1, 2);
                this.shader.bind();
                this.shader.uniforms = {
                  model,
                  view,
                  projection,
                  bounds,
                  enable,
                  colors
                };
                this.vao.bind();
                this.vao.draw(this.gl.TRIANGLES, 36);
                this.vao.unbind();
                gl2.disable(gl2.POLYGON_OFFSET_FILL);
              };
              proto.dispose = function() {
                this.vao.dispose();
                this.buffer.dispose();
                this.shader.dispose();
              };
              function createBackgroundCube(gl2) {
                var vertices = [];
                var indices = [];
                var ptr = 0;
                for (var d = 0; d < 3; ++d) {
                  var u = (d + 1) % 3;
                  var v = (d + 2) % 3;
                  var x = [0, 0, 0];
                  var c = [0, 0, 0];
                  for (var s = -1; s <= 1; s += 2) {
                    indices.push(
                      ptr,
                      ptr + 2,
                      ptr + 1,
                      ptr + 1,
                      ptr + 2,
                      ptr + 3
                    );
                    x[d] = s;
                    c[d] = s;
                    for (var i = -1; i <= 1; i += 2) {
                      x[u] = i;
                      for (var j = -1; j <= 1; j += 2) {
                        x[v] = j;
                        vertices.push(
                          x[0],
                          x[1],
                          x[2],
                          c[0],
                          c[1],
                          c[2]
                        );
                        ptr += 1;
                      }
                    }
                    var tt = u;
                    u = v;
                    v = tt;
                  }
                }
                var buffer = createBuffer(gl2, new Float32Array(vertices));
                var elements = createBuffer(gl2, new Uint16Array(indices), gl2.ELEMENT_ARRAY_BUFFER);
                var vao = createVAO(gl2, [
                  {
                    buffer,
                    type: gl2.FLOAT,
                    size: 3,
                    offset: 0,
                    stride: 24
                  },
                  {
                    buffer,
                    type: gl2.FLOAT,
                    size: 3,
                    offset: 12,
                    stride: 24
                  }
                ], elements);
                var shader = createShader(gl2);
                shader.attributes.position.location = 0;
                shader.attributes.normal.location = 1;
                return new BackgroundCube(gl2, buffer, vao, shader);
              }
            }
          ),
          /***/
          5352: (
            /***/
            function(module2) {
              module2.exports = transformMat4;
              function transformMat4(out, a, m) {
                var x = a[0], y = a[1], z = a[2], w = a[3];
                out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
                out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
                out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
                out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
                return out;
              }
            }
          ),
          /***/
          5382: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var robustSum = __webpack_require__2(8210);
              var robustScale = __webpack_require__2(3012);
              module2.exports = robustProduct;
              function robustProduct(a, b) {
                if (a.length === 1) {
                  return robustScale(b, a[0]);
                }
                if (b.length === 1) {
                  return robustScale(a, b[0]);
                }
                if (a.length === 0 || b.length === 0) {
                  return [0];
                }
                var r = [0];
                if (a.length < b.length) {
                  for (var i = 0; i < a.length; ++i) {
                    r = robustSum(r, robustScale(b, a[i]));
                  }
                } else {
                  for (var i = 0; i < b.length; ++i) {
                    r = robustSum(r, robustScale(a, b[i]));
                  }
                }
                return r;
              }
            }
          ),
          /***/
          5445: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = axesProperties;
              var getPlanes = __webpack_require__2(5033);
              var splitPoly = __webpack_require__2(5202);
              var cubeParams = __webpack_require__2(6429);
              var m4mul = __webpack_require__2(6760);
              var m4transpose = __webpack_require__2(5665);
              var v4transformMat4 = __webpack_require__2(5352);
              var identity2 = new Float32Array([
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ]);
              var mvp = new Float32Array(16);
              function AxesRange3D(lo, hi, pixelsPerDataUnit) {
                this.lo = lo;
                this.hi = hi;
                this.pixelsPerDataUnit = pixelsPerDataUnit;
              }
              var SCRATCH_P = [0, 0, 0, 1];
              var SCRATCH_Q = [0, 0, 0, 1];
              function gradient(result, M, v, width, height) {
                for (var i = 0; i < 3; ++i) {
                  var p = SCRATCH_P;
                  var q = SCRATCH_Q;
                  for (var j = 0; j < 3; ++j) {
                    q[j] = p[j] = v[j];
                  }
                  q[3] = p[3] = 1;
                  q[i] += 1;
                  v4transformMat4(q, q, M);
                  if (q[3] < 0) {
                    result[i] = Infinity;
                  }
                  p[i] -= 1;
                  v4transformMat4(p, p, M);
                  if (p[3] < 0) {
                    result[i] = Infinity;
                  }
                  var dx = (p[0] / p[3] - q[0] / q[3]) * width;
                  var dy = (p[1] / p[3] - q[1] / q[3]) * height;
                  result[i] = 0.25 * Math.sqrt(dx * dx + dy * dy);
                }
                return result;
              }
              var RANGES = [
                new AxesRange3D(Infinity, -Infinity, Infinity),
                new AxesRange3D(Infinity, -Infinity, Infinity),
                new AxesRange3D(Infinity, -Infinity, Infinity)
              ];
              var SCRATCH_X = [0, 0, 0];
              function axesProperties(axes, camera, width, height, params) {
                var model = camera.model || identity2;
                var view = camera.view || identity2;
                var projection = camera.projection || identity2;
                var isOrtho = camera._ortho || false;
                var bounds = axes.bounds;
                var params = params || cubeParams(model, view, projection, bounds, isOrtho);
                var axis = params.axis;
                m4mul(mvp, view, model);
                m4mul(mvp, projection, mvp);
                var ranges = RANGES;
                for (var i = 0; i < 3; ++i) {
                  ranges[i].lo = Infinity;
                  ranges[i].hi = -Infinity;
                  ranges[i].pixelsPerDataUnit = Infinity;
                }
                var frustum = getPlanes(m4transpose(mvp, mvp));
                m4transpose(mvp, mvp);
                for (var d = 0; d < 3; ++d) {
                  var u = (d + 1) % 3;
                  var v = (d + 2) % 3;
                  var x = SCRATCH_X;
                  i_loop:
                    for (var i = 0; i < 2; ++i) {
                      var poly = [];
                      if (axis[d] < 0 === !!i) {
                        continue;
                      }
                      x[d] = bounds[i][d];
                      for (var j = 0; j < 2; ++j) {
                        x[u] = bounds[j ^ i][u];
                        for (var k = 0; k < 2; ++k) {
                          x[v] = bounds[k ^ j ^ i][v];
                          poly.push(x.slice());
                        }
                      }
                      var Q = isOrtho ? 5 : 4;
                      for (var j = Q; j === Q; ++j) {
                        if (poly.length === 0) {
                          continue i_loop;
                        }
                        poly = splitPoly.positive(poly, frustum[j]);
                      }
                      for (var j = 0; j < poly.length; ++j) {
                        var v = poly[j];
                        var grad = gradient(SCRATCH_X, mvp, v, width, height);
                        for (var k = 0; k < 3; ++k) {
                          ranges[k].lo = Math.min(ranges[k].lo, v[k]);
                          ranges[k].hi = Math.max(ranges[k].hi, v[k]);
                          if (k !== d) {
                            ranges[k].pixelsPerDataUnit = Math.min(ranges[k].pixelsPerDataUnit, Math.abs(grad[k]));
                          }
                        }
                      }
                    }
                }
                return ranges;
              }
            }
          ),
          /***/
          5455: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(7056);
            }
          ),
          /***/
          5486: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(3066);
            }
          ),
          /***/
          5542: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bsearch = __webpack_require__2(2478);
              module2.exports = createTriangulation;
              function Triangulation(stars, edges) {
                this.stars = stars;
                this.edges = edges;
              }
              var proto = Triangulation.prototype;
              function removePair(list, j, k) {
                for (var i = 1, n = list.length; i < n; i += 2) {
                  if (list[i - 1] === j && list[i] === k) {
                    list[i - 1] = list[n - 2];
                    list[i] = list[n - 1];
                    list.length = n - 2;
                    return;
                  }
                }
              }
              proto.isConstraint = /* @__PURE__ */ function() {
                var e = [0, 0];
                function compareLex(a, b) {
                  return a[0] - b[0] || a[1] - b[1];
                }
                return function(i, j) {
                  e[0] = Math.min(i, j);
                  e[1] = Math.max(i, j);
                  return bsearch.eq(this.edges, e, compareLex) >= 0;
                };
              }();
              proto.removeTriangle = function(i, j, k) {
                var stars = this.stars;
                removePair(stars[i], j, k);
                removePair(stars[j], k, i);
                removePair(stars[k], i, j);
              };
              proto.addTriangle = function(i, j, k) {
                var stars = this.stars;
                stars[i].push(j, k);
                stars[j].push(k, i);
                stars[k].push(i, j);
              };
              proto.opposite = function(j, i) {
                var list = this.stars[i];
                for (var k = 1, n = list.length; k < n; k += 2) {
                  if (list[k] === j) {
                    return list[k - 1];
                  }
                }
                return -1;
              };
              proto.flip = function(i, j) {
                var a = this.opposite(i, j);
                var b = this.opposite(j, i);
                this.removeTriangle(i, j, a);
                this.removeTriangle(j, i, b);
                this.addTriangle(i, b, a);
                this.addTriangle(j, a, b);
              };
              proto.edges = function() {
                var stars = this.stars;
                var result = [];
                for (var i = 0, n = stars.length; i < n; ++i) {
                  var list = stars[i];
                  for (var j = 0, m = list.length; j < m; j += 2) {
                    result.push([list[j], list[j + 1]]);
                  }
                }
                return result;
              };
              proto.cells = function() {
                var stars = this.stars;
                var result = [];
                for (var i = 0, n = stars.length; i < n; ++i) {
                  var list = stars[i];
                  for (var j = 0, m = list.length; j < m; j += 2) {
                    var s = list[j];
                    var t = list[j + 1];
                    if (i < Math.min(s, t)) {
                      result.push([i, s, t]);
                    }
                  }
                }
                return result;
              };
              function createTriangulation(numVerts, edges) {
                var stars = new Array(numVerts);
                for (var i = 0; i < numVerts; ++i) {
                  stars[i] = [];
                }
                return new Triangulation(stars, edges);
              }
            }
          ),
          /***/
          5567: (
            /***/
            function(module2) {
              module2.exports = rotateX;
              function rotateX(out, a, rad) {
                var s = Math.sin(rad), c = Math.cos(rad), a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
                if (a !== out) {
                  out[0] = a[0];
                  out[1] = a[1];
                  out[2] = a[2];
                  out[3] = a[3];
                  out[12] = a[12];
                  out[13] = a[13];
                  out[14] = a[14];
                  out[15] = a[15];
                }
                out[4] = a10 * c + a20 * s;
                out[5] = a11 * c + a21 * s;
                out[6] = a12 * c + a22 * s;
                out[7] = a13 * c + a23 * s;
                out[8] = a20 * c - a10 * s;
                out[9] = a21 * c - a11 * s;
                out[10] = a22 * c - a12 * s;
                out[11] = a23 * c - a13 * s;
                return out;
              }
              ;
            }
          ),
          /***/
          5572: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var rationalize = __webpack_require__2(869);
              module2.exports = sub;
              function sub(a, b) {
                return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1]));
              }
            }
          ),
          /***/
          5609: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = trimLeaves;
              var e2a = __webpack_require__2(3134);
              function trimLeaves(edges, positions) {
                var adj = e2a(edges, positions.length);
                var live = new Array(positions.length);
                var nbhd = new Array(positions.length);
                var dead = [];
                for (var i = 0; i < positions.length; ++i) {
                  var count = adj[i].length;
                  nbhd[i] = count;
                  live[i] = true;
                  if (count <= 1) {
                    dead.push(i);
                  }
                }
                while (dead.length > 0) {
                  var v = dead.pop();
                  live[v] = false;
                  var n = adj[v];
                  for (var i = 0; i < n.length; ++i) {
                    var u = n[i];
                    if (--nbhd[u] === 0) {
                      dead.push(u);
                    }
                  }
                }
                var newIndex = new Array(positions.length);
                var npositions = [];
                for (var i = 0; i < positions.length; ++i) {
                  if (live[i]) {
                    var v = npositions.length;
                    newIndex[i] = v;
                    npositions.push(positions[i]);
                  } else {
                    newIndex[i] = -1;
                  }
                }
                var nedges = [];
                for (var i = 0; i < edges.length; ++i) {
                  var e = edges[i];
                  if (live[e[0]] && live[e[1]]) {
                    nedges.push([newIndex[e[0]], newIndex[e[1]]]);
                  }
                }
                return [nedges, npositions];
              }
            }
          ),
          /***/
          5632: (
            /***/
            function(module2) {
              module2.exports = add;
              function add(out, a, b) {
                out[0] = a[0] + b[0];
                out[1] = a[1] + b[1];
                out[2] = a[2] + b[2];
                return out;
              }
            }
          ),
          /***/
          5665: (
            /***/
            function(module2) {
              module2.exports = transpose;
              function transpose(out, a) {
                if (out === a) {
                  var a01 = a[1], a02 = a[2], a03 = a[3], a12 = a[6], a13 = a[7], a23 = a[11];
                  out[1] = a[4];
                  out[2] = a[8];
                  out[3] = a[12];
                  out[4] = a01;
                  out[6] = a[9];
                  out[7] = a[13];
                  out[8] = a02;
                  out[9] = a12;
                  out[11] = a[14];
                  out[12] = a03;
                  out[13] = a13;
                  out[14] = a23;
                } else {
                  out[0] = a[0];
                  out[1] = a[4];
                  out[2] = a[8];
                  out[3] = a[12];
                  out[4] = a[1];
                  out[5] = a[5];
                  out[6] = a[9];
                  out[7] = a[13];
                  out[8] = a[2];
                  out[9] = a[6];
                  out[10] = a[10];
                  out[11] = a[14];
                  out[12] = a[3];
                  out[13] = a[7];
                  out[14] = a[11];
                  out[15] = a[15];
                }
                return out;
              }
              ;
            }
          ),
          /***/
          5673: (
            /***/
            function(module2) {
              module2.exports = transformMat4;
              function transformMat4(out, a, m) {
                var x = a[0], y = a[1], z = a[2], w = m[3] * x + m[7] * y + m[11] * z + m[15];
                w = w || 1;
                out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
                out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
                out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
                return out;
              }
            }
          ),
          /***/
          5714: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createLinePlot;
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createTexture = __webpack_require__2(7766);
              var UINT8_VIEW = new Uint8Array(4);
              var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer);
              function unpackFloat(x, y, z, w) {
                UINT8_VIEW[0] = w;
                UINT8_VIEW[1] = z;
                UINT8_VIEW[2] = y;
                UINT8_VIEW[3] = x;
                return FLOAT_VIEW[0];
              }
              var bsearch = __webpack_require__2(2478);
              var ndarray = __webpack_require__2(9618);
              var shaders = __webpack_require__2(7319);
              var createShader = shaders.createShader;
              var createPickShader = shaders.createPickShader;
              var identity2 = [
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ];
              function distance(a, b) {
                var s = 0;
                for (var i = 0; i < 3; ++i) {
                  var d = a[i] - b[i];
                  s += d * d;
                }
                return Math.sqrt(s);
              }
              function filterClipBounds(bounds) {
                var result = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]];
                for (var i = 0; i < 3; ++i) {
                  result[0][i] = Math.max(bounds[0][i], result[0][i]);
                  result[1][i] = Math.min(bounds[1][i], result[1][i]);
                }
                return result;
              }
              function PickResult(tau, position, index, dataCoordinate) {
                this.arcLength = tau;
                this.position = position;
                this.index = index;
                this.dataCoordinate = dataCoordinate;
              }
              function LinePlot(gl2, shader, pickShader, buffer, vao, texture) {
                this.gl = gl2;
                this.shader = shader;
                this.pickShader = pickShader;
                this.buffer = buffer;
                this.vao = vao;
                this.clipBounds = [
                  [-Infinity, -Infinity, -Infinity],
                  [Infinity, Infinity, Infinity]
                ];
                this.points = [];
                this.arcLength = [];
                this.vertexCount = 0;
                this.bounds = [[0, 0, 0], [0, 0, 0]];
                this.pickId = 0;
                this.lineWidth = 1;
                this.texture = texture;
                this.dashScale = 1;
                this.opacity = 1;
                this.hasAlpha = false;
                this.dirty = true;
                this.pixelRatio = 1;
              }
              var proto = LinePlot.prototype;
              proto.isTransparent = function() {
                return this.hasAlpha;
              };
              proto.isOpaque = function() {
                return !this.hasAlpha;
              };
              proto.pickSlots = 1;
              proto.setPickBase = function(id) {
                this.pickId = id;
              };
              proto.drawTransparent = proto.draw = function(camera) {
                if (!this.vertexCount) return;
                var gl2 = this.gl;
                var shader = this.shader;
                var vao = this.vao;
                shader.bind();
                shader.uniforms = {
                  model: camera.model || identity2,
                  view: camera.view || identity2,
                  projection: camera.projection || identity2,
                  clipBounds: filterClipBounds(this.clipBounds),
                  dashTexture: this.texture.bind(),
                  dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1],
                  opacity: this.opacity,
                  screenShape: [gl2.drawingBufferWidth, gl2.drawingBufferHeight],
                  pixelRatio: this.pixelRatio
                };
                vao.bind();
                vao.draw(gl2.TRIANGLE_STRIP, this.vertexCount);
                vao.unbind();
              };
              proto.drawPick = function(camera) {
                if (!this.vertexCount) return;
                var gl2 = this.gl;
                var shader = this.pickShader;
                var vao = this.vao;
                shader.bind();
                shader.uniforms = {
                  model: camera.model || identity2,
                  view: camera.view || identity2,
                  projection: camera.projection || identity2,
                  pickId: this.pickId,
                  clipBounds: filterClipBounds(this.clipBounds),
                  screenShape: [gl2.drawingBufferWidth, gl2.drawingBufferHeight],
                  pixelRatio: this.pixelRatio
                };
                vao.bind();
                vao.draw(gl2.TRIANGLE_STRIP, this.vertexCount);
                vao.unbind();
              };
              proto.update = function(options) {
                var i, j;
                this.dirty = true;
                var connectGaps = !!options.connectGaps;
                if ("dashScale" in options) {
                  this.dashScale = options.dashScale;
                }
                this.hasAlpha = false;
                if ("opacity" in options) {
                  this.opacity = +options.opacity;
                  if (this.opacity < 1) {
                    this.hasAlpha = true;
                  }
                }
                var buffer = [];
                var arcLengthArray = [];
                var pointArray = [];
                var arcLength = 0;
                var vertexCount = 0;
                var bounds = [
                  [Infinity, Infinity, Infinity],
                  [-Infinity, -Infinity, -Infinity]
                ];
                var positions = options.position || options.positions;
                if (positions) {
                  var colors = options.color || options.colors || [0, 0, 0, 1];
                  var lineWidth = options.lineWidth || 1;
                  var hadGap = false;
                  fill_loop:
                    for (i = 1; i < positions.length; ++i) {
                      var a = positions[i - 1];
                      var b = positions[i];
                      arcLengthArray.push(arcLength);
                      pointArray.push(a.slice());
                      for (j = 0; j < 3; ++j) {
                        if (isNaN(a[j]) || isNaN(b[j]) || !isFinite(a[j]) || !isFinite(b[j])) {
                          if (!connectGaps && buffer.length > 0) {
                            for (var k = 0; k < 24; ++k) {
                              buffer.push(buffer[buffer.length - 12]);
                            }
                            vertexCount += 2;
                            hadGap = true;
                          }
                          continue fill_loop;
                        }
                        bounds[0][j] = Math.min(bounds[0][j], a[j], b[j]);
                        bounds[1][j] = Math.max(bounds[1][j], a[j], b[j]);
                      }
                      var acolor, bcolor;
                      if (Array.isArray(colors[0])) {
                        acolor = colors.length > i - 1 ? colors[i - 1] : (
                          // using index value
                          colors.length > 0 ? colors[colors.length - 1] : (
                            // using last item
                            [0, 0, 0, 1]
                          )
                        );
                        bcolor = colors.length > i ? colors[i] : (
                          // using index value
                          colors.length > 0 ? colors[colors.length - 1] : (
                            // using last item
                            [0, 0, 0, 1]
                          )
                        );
                      } else {
                        acolor = bcolor = colors;
                      }
                      if (acolor.length === 3) {
                        acolor = [acolor[0], acolor[1], acolor[2], 1];
                      }
                      if (bcolor.length === 3) {
                        bcolor = [bcolor[0], bcolor[1], bcolor[2], 1];
                      }
                      if (!this.hasAlpha && acolor[3] < 1) this.hasAlpha = true;
                      var w0;
                      if (Array.isArray(lineWidth)) {
                        w0 = lineWidth.length > i - 1 ? lineWidth[i - 1] : (
                          // using index value
                          lineWidth.length > 0 ? lineWidth[lineWidth.length - 1] : (
                            // using last item
                            [0, 0, 0, 1]
                          )
                        );
                      } else {
                        w0 = lineWidth;
                      }
                      var t02 = arcLength;
                      arcLength += distance(a, b);
                      if (hadGap) {
                        for (j = 0; j < 2; ++j) {
                          buffer.push(
                            a[0],
                            a[1],
                            a[2],
                            b[0],
                            b[1],
                            b[2],
                            t02,
                            w0,
                            acolor[0],
                            acolor[1],
                            acolor[2],
                            acolor[3]
                          );
                        }
                        vertexCount += 2;
                        hadGap = false;
                      }
                      buffer.push(
                        a[0],
                        a[1],
                        a[2],
                        b[0],
                        b[1],
                        b[2],
                        t02,
                        w0,
                        acolor[0],
                        acolor[1],
                        acolor[2],
                        acolor[3],
                        a[0],
                        a[1],
                        a[2],
                        b[0],
                        b[1],
                        b[2],
                        t02,
                        -w0,
                        acolor[0],
                        acolor[1],
                        acolor[2],
                        acolor[3],
                        b[0],
                        b[1],
                        b[2],
                        a[0],
                        a[1],
                        a[2],
                        arcLength,
                        -w0,
                        bcolor[0],
                        bcolor[1],
                        bcolor[2],
                        bcolor[3],
                        b[0],
                        b[1],
                        b[2],
                        a[0],
                        a[1],
                        a[2],
                        arcLength,
                        w0,
                        bcolor[0],
                        bcolor[1],
                        bcolor[2],
                        bcolor[3]
                      );
                      vertexCount += 4;
                    }
                }
                this.buffer.update(buffer);
                arcLengthArray.push(arcLength);
                pointArray.push(positions[positions.length - 1].slice());
                this.bounds = bounds;
                this.vertexCount = vertexCount;
                this.points = pointArray;
                this.arcLength = arcLengthArray;
                if ("dashes" in options) {
                  var dashArray = options.dashes;
                  var prefixSum = dashArray.slice();
                  prefixSum.unshift(0);
                  for (i = 1; i < prefixSum.length; ++i) {
                    prefixSum[i] = prefixSum[i - 1] + prefixSum[i];
                  }
                  var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4]);
                  for (i = 0; i < 256; ++i) {
                    for (j = 0; j < 4; ++j) {
                      dashTexture.set(i, 0, j, 0);
                    }
                    if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255) & 1) {
                      dashTexture.set(i, 0, 0, 0);
                    } else {
                      dashTexture.set(i, 0, 0, 255);
                    }
                  }
                  this.texture.setPixels(dashTexture);
                }
              };
              proto.dispose = function() {
                this.shader.dispose();
                this.vao.dispose();
                this.buffer.dispose();
              };
              proto.pick = function(selection) {
                if (!selection) {
                  return null;
                }
                if (selection.id !== this.pickId) {
                  return null;
                }
                var tau = unpackFloat(
                  selection.value[0],
                  selection.value[1],
                  selection.value[2],
                  0
                );
                var index = bsearch.le(this.arcLength, tau);
                if (index < 0) {
                  return null;
                }
                if (index === this.arcLength.length - 1) {
                  return new PickResult(
                    this.arcLength[this.arcLength.length - 1],
                    this.points[this.points.length - 1].slice(),
                    index
                  );
                }
                var a = this.points[index];
                var b = this.points[Math.min(index + 1, this.points.length - 1)];
                var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index]);
                var ti = 1 - t;
                var x = [0, 0, 0];
                for (var i = 0; i < 3; ++i) {
                  x[i] = ti * a[i] + t * b[i];
                }
                var dataIndex = Math.min(t < 0.5 ? index : index + 1, this.points.length - 1);
                return new PickResult(
                  tau,
                  x,
                  dataIndex,
                  this.points[dataIndex]
                );
              };
              function createLinePlot(options) {
                var gl2 = options.gl || options.scene && options.scene.gl;
                var shader = createShader(gl2);
                shader.attributes.position.location = 0;
                shader.attributes.nextPosition.location = 1;
                shader.attributes.arcLength.location = 2;
                shader.attributes.lineWidth.location = 3;
                shader.attributes.color.location = 4;
                var pickShader = createPickShader(gl2);
                pickShader.attributes.position.location = 0;
                pickShader.attributes.nextPosition.location = 1;
                pickShader.attributes.arcLength.location = 2;
                pickShader.attributes.lineWidth.location = 3;
                pickShader.attributes.color.location = 4;
                var buffer = createBuffer(gl2);
                var vao = createVAO(gl2, [
                  {
                    "buffer": buffer,
                    "size": 3,
                    "offset": 0,
                    "stride": 48
                  },
                  {
                    "buffer": buffer,
                    "size": 3,
                    "offset": 12,
                    "stride": 48
                  },
                  {
                    "buffer": buffer,
                    "size": 1,
                    "offset": 24,
                    "stride": 48
                  },
                  {
                    "buffer": buffer,
                    "size": 1,
                    "offset": 28,
                    "stride": 48
                  },
                  {
                    "buffer": buffer,
                    "size": 4,
                    "offset": 32,
                    "stride": 48
                  }
                ]);
                var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]);
                for (var i = 0; i < 256 * 4; ++i) {
                  defaultTexture.data[i] = 255;
                }
                var texture = createTexture(gl2, defaultTexture);
                texture.wrap = gl2.REPEAT;
                var linePlot = new LinePlot(gl2, shader, pickShader, buffer, vao, texture);
                linePlot.update(options);
                return linePlot;
              }
            }
          ),
          /***/
          5716: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var BN = __webpack_require__2(6859);
              module2.exports = sign;
              function sign(x) {
                return x.cmp(new BN(0));
              }
            }
          ),
          /***/
          5721: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = convexHull1d;
              function convexHull1d(points) {
                var lo = 0;
                var hi = 0;
                for (var i = 1; i < points.length; ++i) {
                  if (points[i][0] < points[lo][0]) {
                    lo = i;
                  }
                  if (points[i][0] > points[hi][0]) {
                    hi = i;
                  }
                }
                if (lo < hi) {
                  return [[lo], [hi]];
                } else if (lo > hi) {
                  return [[hi], [lo]];
                } else {
                  return [[lo]];
                }
              }
            }
          ),
          /***/
          5771: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var compareCell = __webpack_require__2(8507);
              var compareOrientedCell = __webpack_require__2(3788);
              var orientation = __webpack_require__2(2419);
              module2.exports = reduceCellComplex;
              function reduceCellComplex(cells) {
                cells.sort(compareOrientedCell);
                var n = cells.length;
                var ptr = 0;
                for (var i = 0; i < n; ++i) {
                  var c = cells[i];
                  var o = orientation(c);
                  if (o === 0) {
                    continue;
                  }
                  if (ptr > 0) {
                    var f = cells[ptr - 1];
                    if (compareCell(c, f) === 0 && orientation(f) !== o) {
                      ptr -= 1;
                      continue;
                    }
                  }
                  cells[ptr++] = c;
                }
                cells.length = ptr;
                return cells;
              }
            }
          ),
          /***/
          5838: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = float2rat;
              var rat = __webpack_require__2(7842);
              function float2rat(v) {
                var result = new Array(v.length);
                for (var i = 0; i < v.length; ++i) {
                  result[i] = rat(v[i]);
                }
                return result;
              }
            }
          ),
          /***/
          5847: (
            /***/
            function(module2) {
              module2.exports = multiply;
              function multiply(out, a, b) {
                out[0] = a[0] * b[0];
                out[1] = a[1] * b[1];
                out[2] = a[2] * b[2];
                return out;
              }
            }
          ),
          /***/
          5874: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = tokenize;
              var literals100 = __webpack_require__2(620), operators = __webpack_require__2(7827), builtins100 = __webpack_require__2(6852), literals300es = __webpack_require__2(7932), builtins300es = __webpack_require__2(3508);
              var NORMAL = 999, TOKEN = 9999, BLOCK_COMMENT = 0, LINE_COMMENT = 1, PREPROCESSOR = 2, OPERATOR = 3, INTEGER = 4, FLOAT = 5, IDENT = 6, BUILTIN = 7, KEYWORD = 8, WHITESPACE = 9, EOF = 10, HEX = 11;
              var map = [
                "block-comment",
                "line-comment",
                "preprocessor",
                "operator",
                "integer",
                "float",
                "ident",
                "builtin",
                "keyword",
                "whitespace",
                "eof",
                "integer"
              ];
              function tokenize(opt) {
                var i = 0, total = 0, mode = NORMAL, c, last, content = [], tokens = [], token_idx = 0, token_offs = 0, line = 1, col = 0, start = 0, isnum = false, isoperator = false, input = "", len;
                opt = opt || {};
                var allBuiltins = builtins100;
                var allLiterals = literals100;
                if (opt.version === "300 es") {
                  allBuiltins = builtins300es;
                  allLiterals = literals300es;
                }
                var builtinsDict = {}, literalsDict = {};
                for (var i = 0; i < allBuiltins.length; i++) {
                  builtinsDict[allBuiltins[i]] = true;
                }
                for (var i = 0; i < allLiterals.length; i++) {
                  literalsDict[allLiterals[i]] = true;
                }
                return function(data) {
                  tokens = [];
                  if (data !== null) return write(data);
                  return end();
                };
                function token(data) {
                  if (data.length) {
                    tokens.push({
                      type: map[mode],
                      data,
                      position: start,
                      line,
                      column: col
                    });
                  }
                }
                function write(chunk) {
                  i = 0;
                  if (chunk.toString) chunk = chunk.toString();
                  input += chunk.replace(/\r\n/g, "\n");
                  len = input.length;
                  var last2;
                  while (c = input[i], i < len) {
                    last2 = i;
                    switch (mode) {
                      case BLOCK_COMMENT:
                        i = block_comment();
                        break;
                      case LINE_COMMENT:
                        i = line_comment();
                        break;
                      case PREPROCESSOR:
                        i = preprocessor();
                        break;
                      case OPERATOR:
                        i = operator();
                        break;
                      case INTEGER:
                        i = integer();
                        break;
                      case HEX:
                        i = hex2();
                        break;
                      case FLOAT:
                        i = decimal();
                        break;
                      case TOKEN:
                        i = readtoken();
                        break;
                      case WHITESPACE:
                        i = whitespace();
                        break;
                      case NORMAL:
                        i = normal();
                        break;
                    }
                    if (last2 !== i) {
                      switch (input[last2]) {
                        case "\n":
                          col = 0;
                          ++line;
                          break;
                        default:
                          ++col;
                          break;
                      }
                    }
                  }
                  total += i;
                  input = input.slice(i);
                  return tokens;
                }
                function end(chunk) {
                  if (content.length) {
                    token(content.join(""));
                  }
                  mode = EOF;
                  token("(eof)");
                  return tokens;
                }
                function normal() {
                  content = content.length ? [] : content;
                  if (last === "/" && c === "*") {
                    start = total + i - 1;
                    mode = BLOCK_COMMENT;
                    last = c;
                    return i + 1;
                  }
                  if (last === "/" && c === "/") {
                    start = total + i - 1;
                    mode = LINE_COMMENT;
                    last = c;
                    return i + 1;
                  }
                  if (c === "#") {
                    mode = PREPROCESSOR;
                    start = total + i;
                    return i;
                  }
                  if (/\s/.test(c)) {
                    mode = WHITESPACE;
                    start = total + i;
                    return i;
                  }
                  isnum = /\d/.test(c);
                  isoperator = /[^\w_]/.test(c);
                  start = total + i;
                  mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN;
                  return i;
                }
                function whitespace() {
                  if (/[^\s]/g.test(c)) {
                    token(content.join(""));
                    mode = NORMAL;
                    return i;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
                function preprocessor() {
                  if ((c === "\r" || c === "\n") && last !== "\\") {
                    token(content.join(""));
                    mode = NORMAL;
                    return i;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
                function line_comment() {
                  return preprocessor();
                }
                function block_comment() {
                  if (c === "/" && last === "*") {
                    content.push(c);
                    token(content.join(""));
                    mode = NORMAL;
                    return i + 1;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
                function operator() {
                  if (last === "." && /\d/.test(c)) {
                    mode = FLOAT;
                    return i;
                  }
                  if (last === "/" && c === "*") {
                    mode = BLOCK_COMMENT;
                    return i;
                  }
                  if (last === "/" && c === "/") {
                    mode = LINE_COMMENT;
                    return i;
                  }
                  if (c === "." && content.length) {
                    while (determine_operator(content)) ;
                    mode = FLOAT;
                    return i;
                  }
                  if (c === ";" || c === ")" || c === "(") {
                    if (content.length) while (determine_operator(content)) ;
                    token(c);
                    mode = NORMAL;
                    return i + 1;
                  }
                  var is_composite_operator = content.length === 2 && c !== "=";
                  if (/[\w_\d\s]/.test(c) || is_composite_operator) {
                    while (determine_operator(content)) ;
                    mode = NORMAL;
                    return i;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
                function determine_operator(buf) {
                  var j = 0, idx, res;
                  do {
                    idx = operators.indexOf(buf.slice(0, buf.length + j).join(""));
                    res = operators[idx];
                    if (idx === -1) {
                      if (j-- + buf.length > 0) continue;
                      res = buf.slice(0, 1).join("");
                    }
                    token(res);
                    start += res.length;
                    content = content.slice(res.length);
                    return content.length;
                  } while (1);
                }
                function hex2() {
                  if (/[^a-fA-F0-9]/.test(c)) {
                    token(content.join(""));
                    mode = NORMAL;
                    return i;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
                function integer() {
                  if (c === ".") {
                    content.push(c);
                    mode = FLOAT;
                    last = c;
                    return i + 1;
                  }
                  if (/[eE]/.test(c)) {
                    content.push(c);
                    mode = FLOAT;
                    last = c;
                    return i + 1;
                  }
                  if (c === "x" && content.length === 1 && content[0] === "0") {
                    mode = HEX;
                    content.push(c);
                    last = c;
                    return i + 1;
                  }
                  if (/[^\d]/.test(c)) {
                    token(content.join(""));
                    mode = NORMAL;
                    return i;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
                function decimal() {
                  if (c === "f") {
                    content.push(c);
                    last = c;
                    i += 1;
                  }
                  if (/[eE]/.test(c)) {
                    content.push(c);
                    last = c;
                    return i + 1;
                  }
                  if ((c === "-" || c === "+") && /[eE]/.test(last)) {
                    content.push(c);
                    last = c;
                    return i + 1;
                  }
                  if (/[^\d]/.test(c)) {
                    token(content.join(""));
                    mode = NORMAL;
                    return i;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
                function readtoken() {
                  if (/[^\d\w_]/.test(c)) {
                    var contentstr = content.join("");
                    if (literalsDict[contentstr]) {
                      mode = KEYWORD;
                    } else if (builtinsDict[contentstr]) {
                      mode = BUILTIN;
                    } else {
                      mode = IDENT;
                    }
                    token(content.join(""));
                    mode = NORMAL;
                    return i;
                  }
                  content.push(c);
                  last = c;
                  return i + 1;
                }
              }
            }
          ),
          /***/
          5878: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = simplifyPolygon;
              var orient = __webpack_require__2(3250);
              var sc = __webpack_require__2(2014);
              function errorWeight(base, a, b) {
                var area = Math.abs(orient(base, a, b));
                var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2));
                return area / perim;
              }
              function simplifyPolygon(cells, positions, minArea) {
                var n = positions.length;
                var nc = cells.length;
                var inv = new Array(n);
                var outv = new Array(n);
                var weights = new Array(n);
                var dead = new Array(n);
                for (var i = 0; i < n; ++i) {
                  inv[i] = outv[i] = -1;
                  weights[i] = Infinity;
                  dead[i] = false;
                }
                for (var i = 0; i < nc; ++i) {
                  var c = cells[i];
                  if (c.length !== 2) {
                    throw new Error("Input must be a graph");
                  }
                  var s = c[1];
                  var t = c[0];
                  if (outv[t] !== -1) {
                    outv[t] = -2;
                  } else {
                    outv[t] = s;
                  }
                  if (inv[s] !== -1) {
                    inv[s] = -2;
                  } else {
                    inv[s] = t;
                  }
                }
                function computeWeight(i2) {
                  if (dead[i2]) {
                    return Infinity;
                  }
                  var s2 = inv[i2];
                  var t4 = outv[i2];
                  if (s2 < 0 || t4 < 0) {
                    return Infinity;
                  } else {
                    return errorWeight(positions[i2], positions[s2], positions[t4]);
                  }
                }
                function heapSwap(i2, j) {
                  var a = heap[i2];
                  var b = heap[j];
                  heap[i2] = b;
                  heap[j] = a;
                  index[a] = j;
                  index[b] = i2;
                }
                function heapWeight(i2) {
                  return weights[heap[i2]];
                }
                function heapParent(i2) {
                  if (i2 & 1) {
                    return i2 - 1 >> 1;
                  }
                  return (i2 >> 1) - 1;
                }
                function heapDown(i2) {
                  var w2 = heapWeight(i2);
                  while (true) {
                    var tw = w2;
                    var left = 2 * i2 + 1;
                    var right = 2 * (i2 + 1);
                    var next = i2;
                    if (left < heapCount) {
                      var lw = heapWeight(left);
                      if (lw < tw) {
                        next = left;
                        tw = lw;
                      }
                    }
                    if (right < heapCount) {
                      var rw = heapWeight(right);
                      if (rw < tw) {
                        next = right;
                      }
                    }
                    if (next === i2) {
                      return i2;
                    }
                    heapSwap(i2, next);
                    i2 = next;
                  }
                }
                function heapUp(i2) {
                  var w2 = heapWeight(i2);
                  while (i2 > 0) {
                    var parent = heapParent(i2);
                    if (parent >= 0) {
                      var pw = heapWeight(parent);
                      if (w2 < pw) {
                        heapSwap(i2, parent);
                        i2 = parent;
                        continue;
                      }
                    }
                    return i2;
                  }
                }
                function heapPop() {
                  if (heapCount > 0) {
                    var head = heap[0];
                    heapSwap(0, heapCount - 1);
                    heapCount -= 1;
                    heapDown(0);
                    return head;
                  }
                  return -1;
                }
                function heapUpdate(i2, w2) {
                  var a = heap[i2];
                  if (weights[a] === w2) {
                    return i2;
                  }
                  weights[a] = -Infinity;
                  heapUp(i2);
                  heapPop();
                  weights[a] = w2;
                  heapCount += 1;
                  return heapUp(heapCount - 1);
                }
                function kill(i2) {
                  if (dead[i2]) {
                    return;
                  }
                  dead[i2] = true;
                  var s2 = inv[i2];
                  var t4 = outv[i2];
                  if (inv[t4] >= 0) {
                    inv[t4] = s2;
                  }
                  if (outv[s2] >= 0) {
                    outv[s2] = t4;
                  }
                  if (index[s2] >= 0) {
                    heapUpdate(index[s2], computeWeight(s2));
                  }
                  if (index[t4] >= 0) {
                    heapUpdate(index[t4], computeWeight(t4));
                  }
                }
                var heap = [];
                var index = new Array(n);
                for (var i = 0; i < n; ++i) {
                  var w = weights[i] = computeWeight(i);
                  if (w < Infinity) {
                    index[i] = heap.length;
                    heap.push(i);
                  } else {
                    index[i] = -1;
                  }
                }
                var heapCount = heap.length;
                for (var i = heapCount >> 1; i >= 0; --i) {
                  heapDown(i);
                }
                while (true) {
                  var hmin = heapPop();
                  if (hmin < 0 || weights[hmin] > minArea) {
                    break;
                  }
                  kill(hmin);
                }
                var npositions = [];
                for (var i = 0; i < n; ++i) {
                  if (!dead[i]) {
                    index[i] = npositions.length;
                    npositions.push(positions[i].slice());
                  }
                }
                var nv = npositions.length;
                function tortoiseHare(seq, start) {
                  if (seq[start] < 0) {
                    return start;
                  }
                  var t4 = start;
                  var h = start;
                  do {
                    var nh = seq[h];
                    if (!dead[h] || nh < 0 || nh === h) {
                      break;
                    }
                    h = nh;
                    nh = seq[h];
                    if (!dead[h] || nh < 0 || nh === h) {
                      break;
                    }
                    h = nh;
                    t4 = seq[t4];
                  } while (t4 !== h);
                  for (var v = start; v !== h; v = seq[v]) {
                    seq[v] = h;
                  }
                  return h;
                }
                var ncells = [];
                cells.forEach(function(c2) {
                  var tin = tortoiseHare(inv, c2[0]);
                  var tout = tortoiseHare(outv, c2[1]);
                  if (tin >= 0 && tout >= 0 && tin !== tout) {
                    var cin = index[tin];
                    var cout = index[tout];
                    if (cin !== cout) {
                      ncells.push([cin, cout]);
                    }
                  }
                });
                sc.unique(sc.normalize(ncells));
                return {
                  positions: npositions,
                  edges: ncells
                };
              }
            }
          ),
          /***/
          5911: (
            /***/
            function(module2) {
              module2.exports = cross;
              function cross(out, a, b) {
                var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2];
                out[0] = ay * bz - az * by;
                out[1] = az * bx - ax * bz;
                out[2] = ax * by - ay * bx;
                return out;
              }
            }
          ),
          /***/
          5964: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = function(a) {
                return !a && a !== 0 ? "" : a.toString();
              };
            }
          ),
          /***/
          5995: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = alphaComplex;
              var delaunay = __webpack_require__2(7642);
              var circumradius = __webpack_require__2(6037);
              function alphaComplex(alpha, points) {
                return delaunay(points).filter(function(cell) {
                  var simplex = new Array(cell.length);
                  for (var i = 0; i < cell.length; ++i) {
                    simplex[i] = points[cell[i]];
                  }
                  return circumradius(simplex) * alpha < 1;
                });
              }
            }
          ),
          /***/
          6037: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = circumradius;
              var circumcenter = __webpack_require__2(3628);
              function circumradius(points) {
                var center = circumcenter(points);
                var avgDist = 0;
                for (var i = 0; i < points.length; ++i) {
                  var p = points[i];
                  for (var j = 0; j < center.length; ++j) {
                    avgDist += Math.pow(p[j] - center[j], 2);
                  }
                }
                return Math.sqrt(avgDist / points.length);
              }
            }
          ),
          /***/
          6079: (
            /***/
            function(module2) {
              module2.exports = rotate;
              function rotate(out, a, rad, axis) {
                var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22;
                if (Math.abs(len) < 1e-6) {
                  return null;
                }
                len = 1 / len;
                x *= len;
                y *= len;
                z *= len;
                s = Math.sin(rad);
                c = Math.cos(rad);
                t = 1 - c;
                a00 = a[0];
                a01 = a[1];
                a02 = a[2];
                a03 = a[3];
                a10 = a[4];
                a11 = a[5];
                a12 = a[6];
                a13 = a[7];
                a20 = a[8];
                a21 = a[9];
                a22 = a[10];
                a23 = a[11];
                b00 = x * x * t + c;
                b01 = y * x * t + z * s;
                b02 = z * x * t - y * s;
                b10 = x * y * t - z * s;
                b11 = y * y * t + c;
                b12 = z * y * t + x * s;
                b20 = x * z * t + y * s;
                b21 = y * z * t - x * s;
                b22 = z * z * t + c;
                out[0] = a00 * b00 + a10 * b01 + a20 * b02;
                out[1] = a01 * b00 + a11 * b01 + a21 * b02;
                out[2] = a02 * b00 + a12 * b01 + a22 * b02;
                out[3] = a03 * b00 + a13 * b01 + a23 * b02;
                out[4] = a00 * b10 + a10 * b11 + a20 * b12;
                out[5] = a01 * b10 + a11 * b11 + a21 * b12;
                out[6] = a02 * b10 + a12 * b11 + a22 * b12;
                out[7] = a03 * b10 + a13 * b11 + a23 * b12;
                out[8] = a00 * b20 + a10 * b21 + a20 * b22;
                out[9] = a01 * b20 + a11 * b21 + a21 * b22;
                out[10] = a02 * b20 + a12 * b21 + a22 * b22;
                out[11] = a03 * b20 + a13 * b21 + a23 * b22;
                if (a !== out) {
                  out[12] = a[12];
                  out[13] = a[13];
                  out[14] = a[14];
                  out[15] = a[15];
                }
                return out;
              }
              ;
            }
          ),
          /***/
          6141: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(2953);
            }
          ),
          /***/
          6199: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var dup = __webpack_require__2(1338);
              var CACHED_CWiseOp = {
                zero: function(SS, a0, t02, p0) {
                  var s0 = SS[0], t0p0 = t02[0];
                  p0 |= 0;
                  var i0 = 0, d0s0 = t0p0;
                  for (i0 = 0; i0 < s0; ++i0) {
                    a0[p0] = 0;
                    p0 += d0s0;
                  }
                },
                fdTemplate1: function(SS, a0, t02, p0, a1, t12, p1) {
                  var s0 = SS[0], t0p0 = t02[0], t1p0 = t12[0], q0 = -1 * t0p0, q1 = t0p0;
                  p0 |= 0;
                  p1 |= 0;
                  var i0 = 0, d0s0 = t0p0, d1s0 = t1p0;
                  for (i0 = 0; i0 < s0; ++i0) {
                    a1[p1] = 0.5 * (a0[p0 + q0] - a0[p0 + q1]);
                    p0 += d0s0;
                    p1 += d1s0;
                  }
                },
                fdTemplate2: function(SS, a0, t02, p0, a1, t12, p1, a2, t22, p2) {
                  var s0 = SS[0], s1 = SS[1], t0p0 = t02[0], t0p1 = t02[1], t1p0 = t12[0], t1p1 = t12[1], t2p0 = t22[0], t2p1 = t22[1], q0 = -1 * t0p0, q1 = t0p0, q2 = -1 * t0p1, q3 = t0p1;
                  p0 |= 0;
                  p1 |= 0;
                  p2 |= 0;
                  var i0 = 0, i1 = 0, d0s0 = t0p1, d0s1 = t0p0 - s1 * t0p1, d1s0 = t1p1, d1s1 = t1p0 - s1 * t1p1, d2s0 = t2p1, d2s1 = t2p0 - s1 * t2p1;
                  for (i1 = 0; i1 < s0; ++i1) {
                    for (i0 = 0; i0 < s1; ++i0) {
                      a1[p1] = 0.5 * (a0[p0 + q0] - a0[p0 + q1]);
                      a2[p2] = 0.5 * (a0[p0 + q2] - a0[p0 + q3]);
                      p0 += d0s0;
                      p1 += d1s0;
                      p2 += d2s0;
                    }
                    p0 += d0s1;
                    p1 += d1s1;
                    p2 += d2s1;
                  }
                }
              };
              var CACHED_thunk = {
                cdiff: function(compile2) {
                  var CACHED = {};
                  return function cdiff_cwise_thunk(array0, array1, array2) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, t22 = array2.dtype, r2 = array2.order, type = [t02, r0.join(), t12, r1.join(), t22, r2.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1, t22, r2]);
                    }
                    return proc(array0.shape.slice(0), array0.data, array0.stride, array0.offset | 0, array1.data, array1.stride, array1.offset | 0, array2.data, array2.stride, array2.offset | 0);
                  };
                },
                zero: function(compile2) {
                  var CACHED = {};
                  return function zero_cwise_thunk(array0) {
                    var t02 = array0.dtype, r0 = array0.order, type = [t02, r0.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0]);
                    }
                    return proc(array0.shape.slice(0), array0.data, array0.stride, array0.offset | 0);
                  };
                },
                fdTemplate1: function(compile2) {
                  var CACHED = {};
                  return function fdTemplate1_cwise_thunk(array0, array1) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, type = [t02, r0.join(), t12, r1.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1]);
                    }
                    return proc(array0.shape.slice(0), array0.data, array0.stride, array0.offset | 0, array1.data, array1.stride, array1.offset | 0);
                  };
                },
                fdTemplate2: function(compile2) {
                  var CACHED = {};
                  return function fdTemplate2_cwise_thunk(array0, array1, array4) {
                    var t02 = array0.dtype, r0 = array0.order, t12 = array1.dtype, r1 = array1.order, t4 = array4.dtype, r4 = array4.order, type = [t02, r0.join(), t12, r1.join(), t4, r4.join()].join(), proc = CACHED[type];
                    if (!proc) {
                      CACHED[type] = proc = compile2([t02, r0, t12, r1, t4, r4]);
                    }
                    return proc(array0.shape.slice(0), array0.data, array0.stride, array0.offset | 0, array1.data, array1.stride, array1.offset | 0, array4.data, array4.stride, array4.offset | 0);
                  };
                }
              };
              function createThunk(proc) {
                var thunk = CACHED_thunk[proc.funcName];
                return thunk(compile.bind(void 0, proc));
              }
              function compile(proc) {
                return CACHED_CWiseOp[proc.funcName];
              }
              function cwiseCompiler(user_args) {
                return createThunk({
                  funcName: user_args.funcName
                });
              }
              var TEMPLATE_CACHE = {};
              var GRADIENT_CACHE = {};
              var EmptyProc = {
                body: "",
                args: [],
                thisVars: [],
                localVars: []
              };
              var centralDiff = cwiseCompiler({
                funcName: "cdiff"
              });
              var zeroOut = cwiseCompiler({
                funcName: "zero"
              });
              function generateTemplate(d) {
                if (d in TEMPLATE_CACHE) {
                  return TEMPLATE_CACHE[d];
                }
                return TEMPLATE_CACHE[d] = cwiseCompiler({
                  funcName: "fdTemplate" + d
                });
              }
              function CACHED_link(diff, zero2, grad1, grad2) {
                return function(dst, src) {
                  var s = src.shape.slice();
                  if (s[0] > 2 && s[1] > 2) {
                    grad2(
                      src.pick(-1, -1).lo(1, 1).hi(s[0] - 2, s[1] - 2),
                      dst.pick(-1, -1, 0).lo(1, 1).hi(s[0] - 2, s[1] - 2),
                      dst.pick(-1, -1, 1).lo(1, 1).hi(s[0] - 2, s[1] - 2)
                    );
                  }
                  if (s[1] > 2) {
                    grad1(
                      src.pick(0, -1).lo(1).hi(s[1] - 2),
                      dst.pick(0, -1, 1).lo(1).hi(s[1] - 2)
                    );
                    zero2(
                      dst.pick(0, -1, 0).lo(1).hi(s[1] - 2)
                    );
                  }
                  if (s[1] > 2) {
                    grad1(
                      src.pick(s[0] - 1, -1).lo(1).hi(s[1] - 2),
                      dst.pick(s[0] - 1, -1, 1).lo(1).hi(s[1] - 2)
                    );
                    zero2(
                      dst.pick(s[0] - 1, -1, 0).lo(1).hi(s[1] - 2)
                    );
                  }
                  if (s[0] > 2) {
                    grad1(
                      src.pick(-1, 0).lo(1).hi(s[0] - 2),
                      dst.pick(-1, 0, 0).lo(1).hi(s[0] - 2)
                    );
                    zero2(
                      dst.pick(-1, 0, 1).lo(1).hi(s[0] - 2)
                    );
                  }
                  if (s[0] > 2) {
                    grad1(
                      src.pick(-1, s[1] - 1).lo(1).hi(s[0] - 2),
                      dst.pick(-1, s[1] - 1, 0).lo(1).hi(s[0] - 2)
                    );
                    zero2(
                      dst.pick(-1, s[1] - 1, 1).lo(1).hi(s[0] - 2)
                    );
                  }
                  dst.set(0, 0, 0, 0);
                  dst.set(0, 0, 1, 0);
                  dst.set(s[0] - 1, 0, 0, 0);
                  dst.set(s[0] - 1, 0, 1, 0);
                  dst.set(0, s[1] - 1, 0, 0);
                  dst.set(0, s[1] - 1, 1, 0);
                  dst.set(s[0] - 1, s[1] - 1, 0, 0);
                  dst.set(s[0] - 1, s[1] - 1, 1, 0);
                  return dst;
                };
              }
              function generateGradient(boundaryConditions) {
                var token = boundaryConditions.join();
                var proc = GRADIENT_CACHE[token];
                if (proc) {
                  return proc;
                }
                var d = boundaryConditions.length;
                var linkArgs = [centralDiff, zeroOut];
                for (var i = 1; i <= d; ++i) {
                  linkArgs.push(generateTemplate(i));
                }
                var link = CACHED_link;
                var proc = link.apply(void 0, linkArgs);
                GRADIENT_CACHE[token] = proc;
                return proc;
              }
              module2.exports = function gradient(out, inp, bc) {
                if (!Array.isArray(bc)) {
                  if (typeof bc === "string") {
                    bc = dup(inp.dimension, bc);
                  } else {
                    bc = dup(inp.dimension, "clamp");
                  }
                }
                if (inp.size === 0) {
                  return out;
                }
                if (inp.dimension === 0) {
                  out.set(0);
                  return out;
                }
                var cached = generateGradient(bc);
                return cached(out, inp);
              };
            }
          ),
          /***/
          6204: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = boundary;
              function boundary(cells) {
                var i, j, k;
                var n = cells.length;
                var sz = 0;
                for (i = 0; i < n; ++i) {
                  sz += cells[i].length;
                }
                var result = new Array(sz);
                var ptr = 0;
                for (i = 0; i < n; ++i) {
                  var c = cells[i];
                  var d = c.length;
                  for (j = 0; j < d; ++j) {
                    var b = result[ptr++] = new Array(d - 1);
                    var p = 0;
                    for (k = 0; k < d; ++k) {
                      if (k === j) {
                        continue;
                      }
                      b[p++] = c[k];
                    }
                    if (j & 1) {
                      var tmp = b[1];
                      b[1] = b[0];
                      b[0] = tmp;
                    }
                  }
                }
                return result;
              }
            }
          ),
          /***/
          6296: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createViewController;
              var createTurntable = __webpack_require__2(7261);
              var createOrbit = __webpack_require__2(9977);
              var createMatrix = __webpack_require__2(1811);
              function ViewController(controllers, mode) {
                this._controllerNames = Object.keys(controllers);
                this._controllerList = this._controllerNames.map(function(n) {
                  return controllers[n];
                });
                this._mode = mode;
                this._active = controllers[mode];
                if (!this._active) {
                  this._mode = "turntable";
                  this._active = controllers.turntable;
                }
                this.modes = this._controllerNames;
                this.computedMatrix = this._active.computedMatrix;
                this.computedEye = this._active.computedEye;
                this.computedUp = this._active.computedUp;
                this.computedCenter = this._active.computedCenter;
                this.computedRadius = this._active.computedRadius;
              }
              var proto = ViewController.prototype;
              proto.flush = function(a0) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].flush(a0);
                }
              };
              proto.idle = function(a0) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].idle(a0);
                }
              };
              proto.lookAt = function(a0, a1, a2, a3) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].lookAt(a0, a1, a2, a3);
                }
              };
              proto.rotate = function(a0, a1, a2, a3) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].rotate(a0, a1, a2, a3);
                }
              };
              proto.pan = function(a0, a1, a2, a3) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].pan(a0, a1, a2, a3);
                }
              };
              proto.translate = function(a0, a1, a2, a3) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].translate(a0, a1, a2, a3);
                }
              };
              proto.setMatrix = function(a0, a1) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].setMatrix(a0, a1);
                }
              };
              proto.setDistanceLimits = function(a0, a1) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].setDistanceLimits(a0, a1);
                }
              };
              proto.setDistance = function(a0, a1) {
                var cc = this._controllerList;
                for (var i = 0; i < cc.length; ++i) {
                  cc[i].setDistance(a0, a1);
                }
              };
              proto.recalcMatrix = function(t) {
                this._active.recalcMatrix(t);
              };
              proto.getDistance = function(t) {
                return this._active.getDistance(t);
              };
              proto.getDistanceLimits = function(out) {
                return this._active.getDistanceLimits(out);
              };
              proto.lastT = function() {
                return this._active.lastT();
              };
              proto.setMode = function(mode) {
                if (mode === this._mode) {
                  return;
                }
                var idx = this._controllerNames.indexOf(mode);
                if (idx < 0) {
                  return;
                }
                var prev = this._active;
                var next = this._controllerList[idx];
                var lastT = Math.max(prev.lastT(), next.lastT());
                prev.recalcMatrix(lastT);
                next.setMatrix(lastT, prev.computedMatrix);
                this._active = next;
                this._mode = mode;
                this.computedMatrix = this._active.computedMatrix;
                this.computedEye = this._active.computedEye;
                this.computedUp = this._active.computedUp;
                this.computedCenter = this._active.computedCenter;
                this.computedRadius = this._active.computedRadius;
              };
              proto.getMode = function() {
                return this._mode;
              };
              function createViewController(options) {
                options = options || {};
                var eye = options.eye || [0, 0, 1];
                var center = options.center || [0, 0, 0];
                var up = options.up || [0, 1, 0];
                var limits = options.distanceLimits || [0, Infinity];
                var mode = options.mode || "turntable";
                var turntable = createTurntable();
                var orbit = createOrbit();
                var matrix = createMatrix();
                turntable.setDistanceLimits(limits[0], limits[1]);
                turntable.lookAt(0, eye, center, up);
                orbit.setDistanceLimits(limits[0], limits[1]);
                orbit.lookAt(0, eye, center, up);
                matrix.setDistanceLimits(limits[0], limits[1]);
                matrix.lookAt(0, eye, center, up);
                return new ViewController({
                  turntable,
                  orbit,
                  matrix
                }, mode);
              }
            }
          ),
          /***/
          6330: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var isBN = __webpack_require__2(1533);
              module2.exports = isRat;
              function isRat(x) {
                return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1]);
              }
            }
          ),
          /***/
          6405: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var vec3 = __webpack_require__2(2931);
              module2.exports = function(vectorfield, bounds) {
                var positions = vectorfield.positions;
                var vectors = vectorfield.vectors;
                var geo = {
                  positions: [],
                  vertexIntensity: [],
                  vertexIntensityBounds: vectorfield.vertexIntensityBounds,
                  vectors: [],
                  cells: [],
                  coneOffset: vectorfield.coneOffset,
                  colormap: vectorfield.colormap
                };
                if (vectorfield.positions.length === 0) {
                  if (bounds) {
                    bounds[0] = [0, 0, 0];
                    bounds[1] = [0, 0, 0];
                  }
                  return geo;
                }
                var maxNorm = 0;
                var minX = Infinity, maxX = -Infinity;
                var minY = Infinity, maxY = -Infinity;
                var minZ = Infinity, maxZ = -Infinity;
                var p2 = null;
                var u2 = null;
                var positionVectors = [];
                var vectorScale = Infinity;
                var skipIt = false;
                var rawSizemodemode = vectorfield.coneSizemode === "raw";
                for (var i = 0; i < positions.length; i++) {
                  var p = positions[i];
                  minX = Math.min(p[0], minX);
                  maxX = Math.max(p[0], maxX);
                  minY = Math.min(p[1], minY);
                  maxY = Math.max(p[1], maxY);
                  minZ = Math.min(p[2], minZ);
                  maxZ = Math.max(p[2], maxZ);
                  var u = vectors[i];
                  if (vec3.length(u) > maxNorm) {
                    maxNorm = vec3.length(u);
                  }
                  if (i && !rawSizemodemode) {
                    var q = 2 * vec3.distance(p2, p) / (vec3.length(u2) + vec3.length(u));
                    if (q) {
                      vectorScale = Math.min(vectorScale, q);
                      skipIt = false;
                    } else {
                      skipIt = true;
                    }
                  }
                  if (!skipIt) {
                    p2 = p;
                    u2 = u;
                  }
                  positionVectors.push(u);
                }
                var minV = [minX, minY, minZ];
                var maxV = [maxX, maxY, maxZ];
                if (bounds) {
                  bounds[0] = minV;
                  bounds[1] = maxV;
                }
                if (maxNorm === 0) {
                  maxNorm = 1;
                }
                var invertedMaxNorm = 1 / maxNorm;
                if (!isFinite(vectorScale)) {
                  vectorScale = 1;
                }
                geo.vectorScale = vectorScale;
                var coneScale = vectorfield.coneSize || (rawSizemodemode ? 1 : 0.5);
                if (vectorfield.absoluteConeSize) {
                  coneScale = vectorfield.absoluteConeSize * invertedMaxNorm;
                }
                geo.coneScale = coneScale;
                for (var i = 0, j = 0; i < positions.length; i++) {
                  var p = positions[i];
                  var x = p[0], y = p[1], z = p[2];
                  var d = positionVectors[i];
                  var intensity = vec3.length(d) * invertedMaxNorm;
                  for (var k = 0, l = 8; k < l; k++) {
                    geo.positions.push([x, y, z, j++]);
                    geo.positions.push([x, y, z, j++]);
                    geo.positions.push([x, y, z, j++]);
                    geo.positions.push([x, y, z, j++]);
                    geo.positions.push([x, y, z, j++]);
                    geo.positions.push([x, y, z, j++]);
                    geo.vectors.push(d);
                    geo.vectors.push(d);
                    geo.vectors.push(d);
                    geo.vectors.push(d);
                    geo.vectors.push(d);
                    geo.vectors.push(d);
                    geo.vertexIntensity.push(intensity, intensity, intensity);
                    geo.vertexIntensity.push(intensity, intensity, intensity);
                    var m = geo.positions.length;
                    geo.cells.push([m - 6, m - 5, m - 4], [m - 3, m - 2, m - 1]);
                  }
                }
                return geo;
              };
              var shaders = __webpack_require__2(614);
              module2.exports.createMesh = __webpack_require__2(9060);
              module2.exports.createConeMesh = function(gl2, params) {
                return module2.exports.createMesh(gl2, params, {
                  shaders,
                  traceType: "cone"
                });
              };
            }
          ),
          /***/
          6429: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = getCubeEdges;
              var bits = __webpack_require__2(8828);
              var multiply = __webpack_require__2(6760);
              var splitPoly = __webpack_require__2(5202);
              var orient = __webpack_require__2(3250);
              var mvp = new Array(16);
              var pCubeVerts = new Array(8);
              var cubeVerts = new Array(8);
              var x = new Array(3);
              var zero3 = [0, 0, 0];
              (function() {
                for (var i = 0; i < 8; ++i) {
                  pCubeVerts[i] = [1, 1, 1, 1];
                  cubeVerts[i] = [1, 1, 1];
                }
              })();
              function transformHg(result, x2, mat) {
                for (var i = 0; i < 4; ++i) {
                  result[i] = mat[12 + i];
                  for (var j = 0; j < 3; ++j) {
                    result[i] += x2[j] * mat[4 * j + i];
                  }
                }
              }
              var FRUSTUM_PLANES = [
                [0, 0, 1, 0, 0],
                [0, 0, -1, 1, 0],
                [0, -1, 0, 1, 0],
                [0, 1, 0, 1, 0],
                [-1, 0, 0, 1, 0],
                [1, 0, 0, 1, 0]
              ];
              function polygonArea(p) {
                for (var i = 0; i < FRUSTUM_PLANES.length; ++i) {
                  p = splitPoly.positive(p, FRUSTUM_PLANES[i]);
                  if (p.length < 3) {
                    return 0;
                  }
                }
                var base = p[0];
                var ax = base[0] / base[3];
                var ay = base[1] / base[3];
                var area = 0;
                for (var i = 1; i + 1 < p.length; ++i) {
                  var b = p[i];
                  var c = p[i + 1];
                  var bx = b[0] / b[3];
                  var by = b[1] / b[3];
                  var cx = c[0] / c[3];
                  var cy = c[1] / c[3];
                  var ux = bx - ax;
                  var uy = by - ay;
                  var vx = cx - ax;
                  var vy = cy - ay;
                  area += Math.abs(ux * vy - uy * vx);
                }
                return area;
              }
              var CUBE_EDGES = [1, 1, 1];
              var CUBE_AXIS = [0, 0, 0];
              var CUBE_RESULT = {
                cubeEdges: CUBE_EDGES,
                axis: CUBE_AXIS
              };
              function getCubeEdges(model, view, projection, bounds, ortho) {
                multiply(mvp, view, model);
                multiply(mvp, projection, mvp);
                var ptr = 0;
                for (var i = 0; i < 2; ++i) {
                  x[2] = bounds[i][2];
                  for (var j = 0; j < 2; ++j) {
                    x[1] = bounds[j][1];
                    for (var k = 0; k < 2; ++k) {
                      x[0] = bounds[k][0];
                      transformHg(pCubeVerts[ptr], x, mvp);
                      ptr += 1;
                    }
                  }
                }
                var closest = -1;
                for (var i = 0; i < 8; ++i) {
                  var w = pCubeVerts[i][3];
                  for (var l = 0; l < 3; ++l) {
                    cubeVerts[i][l] = pCubeVerts[i][l] / w;
                  }
                  if (ortho) cubeVerts[i][2] *= -1;
                  if (w < 0) {
                    if (closest < 0) {
                      closest = i;
                    } else if (cubeVerts[i][2] < cubeVerts[closest][2]) {
                      closest = i;
                    }
                  }
                }
                if (closest < 0) {
                  closest = 0;
                  for (var d = 0; d < 3; ++d) {
                    var u = (d + 2) % 3;
                    var v = (d + 1) % 3;
                    var o0 = -1;
                    var o1 = -1;
                    for (var s = 0; s < 2; ++s) {
                      var f0 = s << d;
                      var f1 = f0 + (s << u) + (1 - s << v);
                      var f2 = f0 + (1 - s << u) + (s << v);
                      if (orient(cubeVerts[f0], cubeVerts[f1], cubeVerts[f2], zero3) < 0) {
                        continue;
                      }
                      if (s) {
                        o0 = 1;
                      } else {
                        o1 = 1;
                      }
                    }
                    if (o0 < 0 || o1 < 0) {
                      if (o1 > o0) {
                        closest |= 1 << d;
                      }
                      continue;
                    }
                    for (var s = 0; s < 2; ++s) {
                      var f0 = s << d;
                      var f1 = f0 + (s << u) + (1 - s << v);
                      var f2 = f0 + (1 - s << u) + (s << v);
                      var o = polygonArea([
                        pCubeVerts[f0],
                        pCubeVerts[f1],
                        pCubeVerts[f2],
                        pCubeVerts[f0 + (1 << u) + (1 << v)]
                      ]);
                      if (s) {
                        o0 = o;
                      } else {
                        o1 = o;
                      }
                    }
                    if (o1 > o0) {
                      closest |= 1 << d;
                      continue;
                    }
                  }
                }
                var farthest = 7 ^ closest;
                var bottom = -1;
                for (var i = 0; i < 8; ++i) {
                  if (i === closest || i === farthest) {
                    continue;
                  }
                  if (bottom < 0) {
                    bottom = i;
                  } else if (cubeVerts[bottom][1] > cubeVerts[i][1]) {
                    bottom = i;
                  }
                }
                var left = -1;
                for (var i = 0; i < 3; ++i) {
                  var idx = bottom ^ 1 << i;
                  if (idx === closest || idx === farthest) {
                    continue;
                  }
                  if (left < 0) {
                    left = idx;
                  }
                  var v = cubeVerts[idx];
                  if (v[0] < cubeVerts[left][0]) {
                    left = idx;
                  }
                }
                var right = -1;
                for (var i = 0; i < 3; ++i) {
                  var idx = bottom ^ 1 << i;
                  if (idx === closest || idx === farthest || idx === left) {
                    continue;
                  }
                  if (right < 0) {
                    right = idx;
                  }
                  var v = cubeVerts[idx];
                  if (v[0] > cubeVerts[right][0]) {
                    right = idx;
                  }
                }
                var cubeEdges = CUBE_EDGES;
                cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0;
                cubeEdges[bits.log2(left ^ bottom)] = bottom & left;
                cubeEdges[bits.log2(bottom ^ right)] = bottom & right;
                var top = right ^ 7;
                if (top === closest || top === farthest) {
                  top = left ^ 7;
                  cubeEdges[bits.log2(right ^ top)] = top & right;
                } else {
                  cubeEdges[bits.log2(left ^ top)] = top & left;
                }
                var axis = CUBE_AXIS;
                var cutCorner = closest;
                for (var d = 0; d < 3; ++d) {
                  if (cutCorner & 1 << d) {
                    axis[d] = -1;
                  } else {
                    axis[d] = 1;
                  }
                }
                return CUBE_RESULT;
              }
            }
          ),
          /***/
          6444: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              exports2.create = defaultTicks;
              exports2.equal = ticksEqual;
              function prettyPrint(spacing, i) {
                var stepStr = spacing + "";
                var u = stepStr.indexOf(".");
                var sigFigs = 0;
                if (u >= 0) {
                  sigFigs = stepStr.length - u - 1;
                }
                var shift = Math.pow(10, sigFigs);
                var x = Math.round(spacing * i * shift);
                var xstr = x + "";
                if (xstr.indexOf("e") >= 0) {
                  return xstr;
                }
                var xi = x / shift, xf = x % shift;
                if (x < 0) {
                  xi = -Math.ceil(xi) | 0;
                  xf = -xf | 0;
                } else {
                  xi = Math.floor(xi) | 0;
                  xf = xf | 0;
                }
                var xis = "" + xi;
                if (x < 0) {
                  xis = "-" + xis;
                }
                if (sigFigs) {
                  var xs = "" + xf;
                  while (xs.length < sigFigs) {
                    xs = "0" + xs;
                  }
                  return xis + "." + xs;
                } else {
                  return xis;
                }
              }
              function defaultTicks(bounds, tickSpacing) {
                var array = [];
                for (var d = 0; d < 3; ++d) {
                  var ticks = [];
                  var m = 0.5 * (bounds[0][d] + bounds[1][d]);
                  for (var t = 0; t * tickSpacing[d] <= bounds[1][d]; ++t) {
                    ticks.push({ x: t * tickSpacing[d], text: prettyPrint(tickSpacing[d], t) });
                  }
                  for (var t = -1; t * tickSpacing[d] >= bounds[0][d]; --t) {
                    ticks.push({ x: t * tickSpacing[d], text: prettyPrint(tickSpacing[d], t) });
                  }
                  array.push(ticks);
                }
                return array;
              }
              function ticksEqual(ticksA, ticksB) {
                for (var i = 0; i < 3; ++i) {
                  if (ticksA[i].length !== ticksB[i].length) {
                    return false;
                  }
                  for (var j = 0; j < ticksA[i].length; ++j) {
                    var a = ticksA[i][j];
                    var b = ticksB[i][j];
                    if (a.x !== b.x || a.text !== b.text || a.font !== b.font || a.fontColor !== b.fontColor || a.fontSize !== b.fontSize || a.dx !== b.dx || a.dy !== b.dy) {
                      return false;
                    }
                  }
                }
                return true;
              }
            }
          ),
          /***/
          6468: (
            /***/
            function(module2) {
              module2.exports = function _atob(str) {
                return atob(str);
              };
            }
          ),
          /***/
          6504: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var rationalize = __webpack_require__2(869);
              module2.exports = mul;
              function mul(a, b) {
                return rationalize(a[0].mul(b[0]), a[1].mul(b[1]));
              }
            }
          ),
          /***/
          6582: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var identity2 = __webpack_require__2(7894);
              module2.exports = lookAt;
              function lookAt(out, eye, center, up) {
                var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, eyex = eye[0], eyey = eye[1], eyez = eye[2], upx = up[0], upy = up[1], upz = up[2], centerx = center[0], centery = center[1], centerz = center[2];
                if (Math.abs(eyex - centerx) < 1e-6 && Math.abs(eyey - centery) < 1e-6 && Math.abs(eyez - centerz) < 1e-6) {
                  return identity2(out);
                }
                z0 = eyex - centerx;
                z1 = eyey - centery;
                z2 = eyez - centerz;
                len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
                z0 *= len;
                z1 *= len;
                z2 *= len;
                x0 = upy * z2 - upz * z1;
                x1 = upz * z0 - upx * z2;
                x2 = upx * z1 - upy * z0;
                len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
                if (!len) {
                  x0 = 0;
                  x1 = 0;
                  x2 = 0;
                } else {
                  len = 1 / len;
                  x0 *= len;
                  x1 *= len;
                  x2 *= len;
                }
                y0 = z1 * x2 - z2 * x1;
                y1 = z2 * x0 - z0 * x2;
                y2 = z0 * x1 - z1 * x0;
                len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
                if (!len) {
                  y0 = 0;
                  y1 = 0;
                  y2 = 0;
                } else {
                  len = 1 / len;
                  y0 *= len;
                  y1 *= len;
                  y2 *= len;
                }
                out[0] = x0;
                out[1] = y0;
                out[2] = z0;
                out[3] = 0;
                out[4] = x1;
                out[5] = y1;
                out[6] = z1;
                out[7] = 0;
                out[8] = x2;
                out[9] = y2;
                out[10] = z2;
                out[11] = 0;
                out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
                out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
                out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
                out[15] = 1;
                return out;
              }
              ;
            }
          ),
          /***/
          6621: (
            /***/
            function(module2) {
              module2.exports = scale;
              function scale(out, a, b) {
                out[0] = a[0] * b;
                out[1] = a[1] * b;
                out[2] = a[2] * b;
                return out;
              }
            }
          ),
          /***/
          6658: (
            /***/
            function(module2) {
              module2.exports = lerp;
              function lerp(out, a, b, t) {
                var ax = a[0], ay = a[1], az = a[2];
                out[0] = ax + t * (b[0] - ax);
                out[1] = ay + t * (b[1] - ay);
                out[2] = az + t * (b[2] - az);
                return out;
              }
            }
          ),
          /***/
          6690: (
            /***/
            function(module2) {
              module2.exports = divide;
              function divide(out, a, b) {
                out[0] = a[0] / b[0];
                out[1] = a[1] / b[1];
                out[2] = a[2] / b[2];
                return out;
              }
            }
          ),
          /***/
          6729: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var colorScale = __webpack_require__2(3642);
              var lerp = __webpack_require__2(395);
              module2.exports = createColormap;
              function createColormap(spec) {
                var indicies, fromrgba, torgba, nsteps, cmap, colormap, format, nshades, colors, alpha, i;
                if (!spec) spec = {};
                nshades = (spec.nshades || 72) - 1;
                format = spec.format || "hex";
                colormap = spec.colormap;
                if (!colormap) colormap = "jet";
                if (typeof colormap === "string") {
                  colormap = colormap.toLowerCase();
                  if (!colorScale[colormap]) {
                    throw Error(colormap + " not a supported colorscale");
                  }
                  cmap = colorScale[colormap];
                } else if (Array.isArray(colormap)) {
                  cmap = colormap.slice();
                } else {
                  throw Error("unsupported colormap option", colormap);
                }
                if (cmap.length > nshades + 1) {
                  throw new Error(
                    colormap + " map requires nshades to be at least size " + cmap.length
                  );
                }
                if (!Array.isArray(spec.alpha)) {
                  if (typeof spec.alpha === "number") {
                    alpha = [spec.alpha, spec.alpha];
                  } else {
                    alpha = [1, 1];
                  }
                } else if (spec.alpha.length !== 2) {
                  alpha = [1, 1];
                } else {
                  alpha = spec.alpha.slice();
                }
                indicies = cmap.map(function(c) {
                  return Math.round(c.index * nshades);
                });
                alpha[0] = Math.min(Math.max(alpha[0], 0), 1);
                alpha[1] = Math.min(Math.max(alpha[1], 0), 1);
                var steps = cmap.map(function(c, i2) {
                  var index = cmap[i2].index;
                  var rgba3 = cmap[i2].rgb.slice();
                  if (rgba3.length === 4 && rgba3[3] >= 0 && rgba3[3] <= 1) {
                    return rgba3;
                  }
                  rgba3[3] = alpha[0] + (alpha[1] - alpha[0]) * index;
                  return rgba3;
                });
                var colors = [];
                for (i = 0; i < indicies.length - 1; ++i) {
                  nsteps = indicies[i + 1] - indicies[i];
                  fromrgba = steps[i];
                  torgba = steps[i + 1];
                  for (var j = 0; j < nsteps; j++) {
                    var amt = j / nsteps;
                    colors.push([
                      Math.round(lerp(fromrgba[0], torgba[0], amt)),
                      Math.round(lerp(fromrgba[1], torgba[1], amt)),
                      Math.round(lerp(fromrgba[2], torgba[2], amt)),
                      lerp(fromrgba[3], torgba[3], amt)
                    ]);
                  }
                }
                colors.push(cmap[cmap.length - 1].rgb.concat(alpha[1]));
                if (format === "hex") colors = colors.map(rgb2hex);
                else if (format === "rgbaString") colors = colors.map(rgbaStr);
                else if (format === "float") colors = colors.map(rgb2float);
                return colors;
              }
              ;
              function rgb2float(rgba3) {
                return [
                  rgba3[0] / 255,
                  rgba3[1] / 255,
                  rgba3[2] / 255,
                  rgba3[3]
                ];
              }
              function rgb2hex(rgba3) {
                var dig, hex2 = "#";
                for (var i = 0; i < 3; ++i) {
                  dig = rgba3[i];
                  dig = dig.toString(16);
                  hex2 += ("00" + dig).substr(dig.length);
                }
                return hex2;
              }
              function rgbaStr(rgba3) {
                return "rgba(" + rgba3.join(",") + ")";
              }
            }
          ),
          /***/
          6740: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              var glslify = __webpack_require__2(3236);
              var triVertSrc = glslify(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 color, position;\nattribute vec2 uv;\n\nuniform float vectorScale, tubeScale;\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 eyePosition, lightPosition;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  // Scale the vector magnitude to stay constant with\n  // model & view changes.\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * tubePosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  f_lightDirection = lightPosition - cameraCoordinate.xyz;\n  f_eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  f_normal = normalize((vec4(normal, 0.0) * inverseModel).xyz);\n\n  // vec4 m_position  = model * vec4(tubePosition, 1.0);\n  vec4 t_position  = view * tubePosition;\n  gl_Position      = projection * t_position;\n\n  f_color          = color;\n  f_data           = tubePosition.xyz;\n  f_position       = position.xyz;\n  f_uv             = uv;\n}\n"]);
              var triFragSrc = glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision highp float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\nfloat cookTorranceSpecular(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal, f_lightDirection, f_eyeDirection, f_data, f_position;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = min(1.0, max(0.0, cookTorranceSpecular(L, V, N, roughness, fresnel)));\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}\n"]);
              var pickVertSrc = glslify(["precision highp float;\n\nprecision highp float;\n#define GLSLIFY 1\n\nvec3 getOrthogonalVector(vec3 v) {\n  // Return up-vector for only-z vector.\n  // Return ax + by + cz = 0, a point that lies on the plane that has v as a normal and that isn't (0,0,0).\n  // From the above if-statement we have ||a|| > 0  U  ||b|| > 0.\n  // Assign z = 0, x = -b, y = a:\n  // a*-b + b*a + c*0 = -ba + ba + 0 = 0\n  if (v.x*v.x > v.z*v.z || v.y*v.y > v.z*v.z) {\n    return normalize(vec3(-v.y, v.x, 0.0));\n  } else {\n    return normalize(vec3(0.0, v.z, -v.y));\n  }\n}\n\n// Calculate the tube vertex and normal at the given index.\n//\n// The returned vertex is for a tube ring with its center at origin, radius of length(d), pointing in the direction of d.\n//\n// Each tube segment is made up of a ring of vertices.\n// These vertices are used to make up the triangles of the tube by connecting them together in the vertex array.\n// The indexes of tube segments run from 0 to 8.\n//\nvec3 getTubePosition(vec3 d, float index, out vec3 normal) {\n  float segmentCount = 8.0;\n\n  float angle = 2.0 * 3.14159 * (index / segmentCount);\n\n  vec3 u = getOrthogonalVector(d);\n  vec3 v = normalize(cross(u, d));\n\n  vec3 x = u * cos(angle) * length(d);\n  vec3 y = v * sin(angle) * length(d);\n  vec3 v3 = x + y;\n\n  normal = normalize(v3);\n\n  return v3;\n}\n\nattribute vec4 vector;\nattribute vec4 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform float tubeScale;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  vec3 normal;\n  vec3 XYZ = getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal);\n  vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(XYZ, 0.0);\n\n  gl_Position = projection * (view * tubePosition);\n  f_id        = id;\n  f_position  = position.xyz;\n}\n"]);
              var pickFragSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], f_position)) discard;\n\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);
              exports2.meshShader = {
                vertex: triVertSrc,
                fragment: triFragSrc,
                attributes: [
                  { name: "position", type: "vec4" },
                  { name: "color", type: "vec4" },
                  { name: "uv", type: "vec2" },
                  { name: "vector", type: "vec4" }
                ]
              };
              exports2.pickShader = {
                vertex: pickVertSrc,
                fragment: pickFragSrc,
                attributes: [
                  { name: "position", type: "vec4" },
                  { name: "id", type: "vec4" },
                  { name: "vector", type: "vec4" }
                ]
              };
            }
          ),
          /***/
          6743: (
            /***/
            function(module2) {
              module2.exports = fromRotationTranslation;
              function fromRotationTranslation(out, q, v) {
                var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
                out[0] = 1 - (yy + zz);
                out[1] = xy + wz;
                out[2] = xz - wy;
                out[3] = 0;
                out[4] = xy - wz;
                out[5] = 1 - (xx + zz);
                out[6] = yz + wx;
                out[7] = 0;
                out[8] = xz + wy;
                out[9] = yz - wx;
                out[10] = 1 - (xx + yy);
                out[11] = 0;
                out[12] = v[0];
                out[13] = v[1];
                out[14] = v[2];
                out[15] = 1;
                return out;
              }
              ;
            }
          ),
          /***/
          6760: (
            /***/
            function(module2) {
              module2.exports = multiply;
              function multiply(out, a, b) {
                var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
                var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
                out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = b[4];
                b1 = b[5];
                b2 = b[6];
                b3 = b[7];
                out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = b[8];
                b1 = b[9];
                b2 = b[10];
                b3 = b[11];
                out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                b0 = b[12];
                b1 = b[13];
                b2 = b[14];
                b3 = b[15];
                out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
                out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
                out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
                out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
                return out;
              }
              ;
            }
          ),
          /***/
          6768: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var BN = __webpack_require__2(6859);
              module2.exports = str2BN;
              function str2BN(x) {
                return new BN(x);
              }
            }
          ),
          /***/
          6803: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              "use strict";
              var __webpack_unused_export__;
              "use restrict";
              var bits = __webpack_require__2(8828), UnionFind = __webpack_require__2(1755);
              function dimension(cells) {
                var d = 0, max = Math.max;
                for (var i = 0, il = cells.length; i < il; ++i) {
                  d = max(d, cells[i].length);
                }
                return d - 1;
              }
              __webpack_unused_export__ = dimension;
              function countVertices(cells) {
                var vc = -1, max = Math.max;
                for (var i = 0, il = cells.length; i < il; ++i) {
                  var c = cells[i];
                  for (var j = 0, jl = c.length; j < jl; ++j) {
                    vc = max(vc, c[j]);
                  }
                }
                return vc + 1;
              }
              __webpack_unused_export__ = countVertices;
              function cloneCells(cells) {
                var ncells = new Array(cells.length);
                for (var i = 0, il = cells.length; i < il; ++i) {
                  ncells[i] = cells[i].slice(0);
                }
                return ncells;
              }
              __webpack_unused_export__ = cloneCells;
              function compareCells(a, b) {
                var n = a.length, t = a.length - b.length, min = Math.min;
                if (t) {
                  return t;
                }
                switch (n) {
                  case 0:
                    return 0;
                  case 1:
                    return a[0] - b[0];
                  case 2:
                    var d = a[0] + a[1] - b[0] - b[1];
                    if (d) {
                      return d;
                    }
                    return min(a[0], a[1]) - min(b[0], b[1]);
                  case 3:
                    var l1 = a[0] + a[1], m1 = b[0] + b[1];
                    d = l1 + a[2] - (m1 + b[2]);
                    if (d) {
                      return d;
                    }
                    var l0 = min(a[0], a[1]), m0 = min(b[0], b[1]), d = min(l0, a[2]) - min(m0, b[2]);
                    if (d) {
                      return d;
                    }
                    return min(l0 + a[2], l1) - min(m0 + b[2], m1);
                  //TODO: Maybe optimize n=4 as well?
                  default:
                    var as = a.slice(0);
                    as.sort();
                    var bs = b.slice(0);
                    bs.sort();
                    for (var i = 0; i < n; ++i) {
                      t = as[i] - bs[i];
                      if (t) {
                        return t;
                      }
                    }
                    return 0;
                }
              }
              exports2.Fw = compareCells;
              function compareZipped(a, b) {
                return compareCells(a[0], b[0]);
              }
              function normalize(cells, attr) {
                if (attr) {
                  var len = cells.length;
                  var zipped = new Array(len);
                  for (var i = 0; i < len; ++i) {
                    zipped[i] = [cells[i], attr[i]];
                  }
                  zipped.sort(compareZipped);
                  for (var i = 0; i < len; ++i) {
                    cells[i] = zipped[i][0];
                    attr[i] = zipped[i][1];
                  }
                  return cells;
                } else {
                  cells.sort(compareCells);
                  return cells;
                }
              }
              __webpack_unused_export__ = normalize;
              function unique(cells) {
                if (cells.length === 0) {
                  return [];
                }
                var ptr = 1, len = cells.length;
                for (var i = 1; i < len; ++i) {
                  var a = cells[i];
                  if (compareCells(a, cells[i - 1])) {
                    if (i === ptr) {
                      ptr++;
                      continue;
                    }
                    cells[ptr++] = a;
                  }
                }
                cells.length = ptr;
                return cells;
              }
              __webpack_unused_export__ = unique;
              function findCell(cells, c) {
                var lo = 0, hi = cells.length - 1, r = -1;
                while (lo <= hi) {
                  var mid = lo + hi >> 1, s = compareCells(cells[mid], c);
                  if (s <= 0) {
                    if (s === 0) {
                      r = mid;
                    }
                    lo = mid + 1;
                  } else if (s > 0) {
                    hi = mid - 1;
                  }
                }
                return r;
              }
              __webpack_unused_export__ = findCell;
              function incidence(from_cells, to_cells) {
                var index = new Array(from_cells.length);
                for (var i = 0, il = index.length; i < il; ++i) {
                  index[i] = [];
                }
                var b = [];
                for (var i = 0, n = to_cells.length; i < n; ++i) {
                  var c = to_cells[i];
                  var cl = c.length;
                  for (var k = 1, kn = 1 << cl; k < kn; ++k) {
                    b.length = bits.popCount(k);
                    var l = 0;
                    for (var j = 0; j < cl; ++j) {
                      if (k & 1 << j) {
                        b[l++] = c[j];
                      }
                    }
                    var idx = findCell(from_cells, b);
                    if (idx < 0) {
                      continue;
                    }
                    while (true) {
                      index[idx++].push(i);
                      if (idx >= from_cells.length || compareCells(from_cells[idx], b) !== 0) {
                        break;
                      }
                    }
                  }
                }
                return index;
              }
              __webpack_unused_export__ = incidence;
              function dual(cells, vertex_count) {
                if (!vertex_count) {
                  return incidence(unique(skeleton(cells, 0)), cells, 0);
                }
                var res = new Array(vertex_count);
                for (var i = 0; i < vertex_count; ++i) {
                  res[i] = [];
                }
                for (var i = 0, len = cells.length; i < len; ++i) {
                  var c = cells[i];
                  for (var j = 0, cl = c.length; j < cl; ++j) {
                    res[c[j]].push(i);
                  }
                }
                return res;
              }
              __webpack_unused_export__ = dual;
              function explode(cells) {
                var result = [];
                for (var i = 0, il = cells.length; i < il; ++i) {
                  var c = cells[i], cl = c.length | 0;
                  for (var j = 1, jl = 1 << cl; j < jl; ++j) {
                    var b = [];
                    for (var k = 0; k < cl; ++k) {
                      if (j >>> k & 1) {
                        b.push(c[k]);
                      }
                    }
                    result.push(b);
                  }
                }
                return normalize(result);
              }
              __webpack_unused_export__ = explode;
              function skeleton(cells, n) {
                if (n < 0) {
                  return [];
                }
                var result = [], k0 = (1 << n + 1) - 1;
                for (var i = 0; i < cells.length; ++i) {
                  var c = cells[i];
                  for (var k = k0; k < 1 << c.length; k = bits.nextCombination(k)) {
                    var b = new Array(n + 1), l = 0;
                    for (var j = 0; j < c.length; ++j) {
                      if (k & 1 << j) {
                        b[l++] = c[j];
                      }
                    }
                    result.push(b);
                  }
                }
                return normalize(result);
              }
              __webpack_unused_export__ = skeleton;
              function boundary(cells) {
                var res = [];
                for (var i = 0, il = cells.length; i < il; ++i) {
                  var c = cells[i];
                  for (var j = 0, cl = c.length; j < cl; ++j) {
                    var b = new Array(c.length - 1);
                    for (var k = 0, l = 0; k < cl; ++k) {
                      if (k !== j) {
                        b[l++] = c[k];
                      }
                    }
                    res.push(b);
                  }
                }
                return normalize(res);
              }
              __webpack_unused_export__ = boundary;
              function connectedComponents_dense(cells, vertex_count) {
                var labels = new UnionFind(vertex_count);
                for (var i = 0; i < cells.length; ++i) {
                  var c = cells[i];
                  for (var j = 0; j < c.length; ++j) {
                    for (var k = j + 1; k < c.length; ++k) {
                      labels.link(c[j], c[k]);
                    }
                  }
                }
                var components = [], component_labels = labels.ranks;
                for (var i = 0; i < component_labels.length; ++i) {
                  component_labels[i] = -1;
                }
                for (var i = 0; i < cells.length; ++i) {
                  var l = labels.find(cells[i][0]);
                  if (component_labels[l] < 0) {
                    component_labels[l] = components.length;
                    components.push([cells[i].slice(0)]);
                  } else {
                    components[component_labels[l]].push(cells[i].slice(0));
                  }
                }
                return components;
              }
              function connectedComponents_sparse(cells) {
                var vertices = unique(normalize(skeleton(cells, 0))), labels = new UnionFind(vertices.length);
                for (var i = 0; i < cells.length; ++i) {
                  var c = cells[i];
                  for (var j = 0; j < c.length; ++j) {
                    var vj = findCell(vertices, [c[j]]);
                    for (var k = j + 1; k < c.length; ++k) {
                      labels.link(vj, findCell(vertices, [c[k]]));
                    }
                  }
                }
                var components = [], component_labels = labels.ranks;
                for (var i = 0; i < component_labels.length; ++i) {
                  component_labels[i] = -1;
                }
                for (var i = 0; i < cells.length; ++i) {
                  var l = labels.find(findCell(vertices, [cells[i][0]]));
                  if (component_labels[l] < 0) {
                    component_labels[l] = components.length;
                    components.push([cells[i].slice(0)]);
                  } else {
                    components[component_labels[l]].push(cells[i].slice(0));
                  }
                }
                return components;
              }
              function connectedComponents(cells, vertex_count) {
                if (vertex_count) {
                  return connectedComponents_dense(cells, vertex_count);
                }
                return connectedComponents_sparse(cells);
              }
              __webpack_unused_export__ = connectedComponents;
            }
          ),
          /***/
          6808: (
            /***/
            function(module2) {
              module2.exports = length;
              function length(a) {
                var x = a[0], y = a[1], z = a[2], w = a[3];
                return Math.sqrt(x * x + y * y + z * z + w * w);
              }
            }
          ),
          /***/
          6843: (
            /***/
            function(module2) {
              module2.exports = subtract;
              function subtract(out, a, b) {
                out[0] = a[0] - b[0];
                out[1] = a[1] - b[1];
                out[2] = a[2] - b[2];
                return out;
              }
            }
          ),
          /***/
          6852: (
            /***/
            function(module2) {
              module2.exports = [
                // Keep this list sorted
                "abs",
                "acos",
                "all",
                "any",
                "asin",
                "atan",
                "ceil",
                "clamp",
                "cos",
                "cross",
                "dFdx",
                "dFdy",
                "degrees",
                "distance",
                "dot",
                "equal",
                "exp",
                "exp2",
                "faceforward",
                "floor",
                "fract",
                "gl_BackColor",
                "gl_BackLightModelProduct",
                "gl_BackLightProduct",
                "gl_BackMaterial",
                "gl_BackSecondaryColor",
                "gl_ClipPlane",
                "gl_ClipVertex",
                "gl_Color",
                "gl_DepthRange",
                "gl_DepthRangeParameters",
                "gl_EyePlaneQ",
                "gl_EyePlaneR",
                "gl_EyePlaneS",
                "gl_EyePlaneT",
                "gl_Fog",
                "gl_FogCoord",
                "gl_FogFragCoord",
                "gl_FogParameters",
                "gl_FragColor",
                "gl_FragCoord",
                "gl_FragData",
                "gl_FragDepth",
                "gl_FragDepthEXT",
                "gl_FrontColor",
                "gl_FrontFacing",
                "gl_FrontLightModelProduct",
                "gl_FrontLightProduct",
                "gl_FrontMaterial",
                "gl_FrontSecondaryColor",
                "gl_LightModel",
                "gl_LightModelParameters",
                "gl_LightModelProducts",
                "gl_LightProducts",
                "gl_LightSource",
                "gl_LightSourceParameters",
                "gl_MaterialParameters",
                "gl_MaxClipPlanes",
                "gl_MaxCombinedTextureImageUnits",
                "gl_MaxDrawBuffers",
                "gl_MaxFragmentUniformComponents",
                "gl_MaxLights",
                "gl_MaxTextureCoords",
                "gl_MaxTextureImageUnits",
                "gl_MaxTextureUnits",
                "gl_MaxVaryingFloats",
                "gl_MaxVertexAttribs",
                "gl_MaxVertexTextureImageUnits",
                "gl_MaxVertexUniformComponents",
                "gl_ModelViewMatrix",
                "gl_ModelViewMatrixInverse",
                "gl_ModelViewMatrixInverseTranspose",
                "gl_ModelViewMatrixTranspose",
                "gl_ModelViewProjectionMatrix",
                "gl_ModelViewProjectionMatrixInverse",
                "gl_ModelViewProjectionMatrixInverseTranspose",
                "gl_ModelViewProjectionMatrixTranspose",
                "gl_MultiTexCoord0",
                "gl_MultiTexCoord1",
                "gl_MultiTexCoord2",
                "gl_MultiTexCoord3",
                "gl_MultiTexCoord4",
                "gl_MultiTexCoord5",
                "gl_MultiTexCoord6",
                "gl_MultiTexCoord7",
                "gl_Normal",
                "gl_NormalMatrix",
                "gl_NormalScale",
                "gl_ObjectPlaneQ",
                "gl_ObjectPlaneR",
                "gl_ObjectPlaneS",
                "gl_ObjectPlaneT",
                "gl_Point",
                "gl_PointCoord",
                "gl_PointParameters",
                "gl_PointSize",
                "gl_Position",
                "gl_ProjectionMatrix",
                "gl_ProjectionMatrixInverse",
                "gl_ProjectionMatrixInverseTranspose",
                "gl_ProjectionMatrixTranspose",
                "gl_SecondaryColor",
                "gl_TexCoord",
                "gl_TextureEnvColor",
                "gl_TextureMatrix",
                "gl_TextureMatrixInverse",
                "gl_TextureMatrixInverseTranspose",
                "gl_TextureMatrixTranspose",
                "gl_Vertex",
                "greaterThan",
                "greaterThanEqual",
                "inversesqrt",
                "length",
                "lessThan",
                "lessThanEqual",
                "log",
                "log2",
                "matrixCompMult",
                "max",
                "min",
                "mix",
                "mod",
                "normalize",
                "not",
                "notEqual",
                "pow",
                "radians",
                "reflect",
                "refract",
                "sign",
                "sin",
                "smoothstep",
                "sqrt",
                "step",
                "tan",
                "texture2D",
                "texture2DLod",
                "texture2DProj",
                "texture2DProjLod",
                "textureCube",
                "textureCubeLod",
                "texture2DLodEXT",
                "texture2DProjLodEXT",
                "textureCubeLodEXT",
                "texture2DGradEXT",
                "texture2DProjGradEXT",
                "textureCubeGradEXT"
              ];
            }
          ),
          /***/
          6859: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2 = __webpack_require__2.nmd(module2);
              (function(module3, exports2) {
                "use strict";
                function assert(val, msg) {
                  if (!val) throw new Error(msg || "Assertion failed");
                }
                function inherits(ctor, superCtor) {
                  ctor.super_ = superCtor;
                  var TempCtor = function() {
                  };
                  TempCtor.prototype = superCtor.prototype;
                  ctor.prototype = new TempCtor();
                  ctor.prototype.constructor = ctor;
                }
                function BN(number, base, endian) {
                  if (BN.isBN(number)) {
                    return number;
                  }
                  this.negative = 0;
                  this.words = null;
                  this.length = 0;
                  this.red = null;
                  if (number !== null) {
                    if (base === "le" || base === "be") {
                      endian = base;
                      base = 10;
                    }
                    this._init(number || 0, base || 10, endian || "be");
                  }
                }
                if (typeof module3 === "object") {
                  module3.exports = BN;
                } else {
                  exports2.BN = BN;
                }
                BN.BN = BN;
                BN.wordSize = 26;
                var Buffer2;
                try {
                  if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") {
                    Buffer2 = window.Buffer;
                  } else {
                    Buffer2 = __webpack_require__2(7790).Buffer;
                  }
                } catch (e) {
                }
                BN.isBN = function isBN(num) {
                  if (num instanceof BN) {
                    return true;
                  }
                  return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
                };
                BN.max = function max(left, right) {
                  if (left.cmp(right) > 0) return left;
                  return right;
                };
                BN.min = function min(left, right) {
                  if (left.cmp(right) < 0) return left;
                  return right;
                };
                BN.prototype._init = function init(number, base, endian) {
                  if (typeof number === "number") {
                    return this._initNumber(number, base, endian);
                  }
                  if (typeof number === "object") {
                    return this._initArray(number, base, endian);
                  }
                  if (base === "hex") {
                    base = 16;
                  }
                  assert(base === (base | 0) && base >= 2 && base <= 36);
                  number = number.toString().replace(/\s+/g, "");
                  var start = 0;
                  if (number[0] === "-") {
                    start++;
                    this.negative = 1;
                  }
                  if (start < number.length) {
                    if (base === 16) {
                      this._parseHex(number, start, endian);
                    } else {
                      this._parseBase(number, base, start);
                      if (endian === "le") {
                        this._initArray(this.toArray(), base, endian);
                      }
                    }
                  }
                };
                BN.prototype._initNumber = function _initNumber(number, base, endian) {
                  if (number < 0) {
                    this.negative = 1;
                    number = -number;
                  }
                  if (number < 67108864) {
                    this.words = [number & 67108863];
                    this.length = 1;
                  } else if (number < 4503599627370496) {
                    this.words = [
                      number & 67108863,
                      number / 67108864 & 67108863
                    ];
                    this.length = 2;
                  } else {
                    assert(number < 9007199254740992);
                    this.words = [
                      number & 67108863,
                      number / 67108864 & 67108863,
                      1
                    ];
                    this.length = 3;
                  }
                  if (endian !== "le") return;
                  this._initArray(this.toArray(), base, endian);
                };
                BN.prototype._initArray = function _initArray(number, base, endian) {
                  assert(typeof number.length === "number");
                  if (number.length <= 0) {
                    this.words = [0];
                    this.length = 1;
                    return this;
                  }
                  this.length = Math.ceil(number.length / 3);
                  this.words = new Array(this.length);
                  for (var i = 0; i < this.length; i++) {
                    this.words[i] = 0;
                  }
                  var j, w;
                  var off = 0;
                  if (endian === "be") {
                    for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
                      w = number[i] | number[i - 1] << 8 | number[i - 2] << 16;
                      this.words[j] |= w << off & 67108863;
                      this.words[j + 1] = w >>> 26 - off & 67108863;
                      off += 24;
                      if (off >= 26) {
                        off -= 26;
                        j++;
                      }
                    }
                  } else if (endian === "le") {
                    for (i = 0, j = 0; i < number.length; i += 3) {
                      w = number[i] | number[i + 1] << 8 | number[i + 2] << 16;
                      this.words[j] |= w << off & 67108863;
                      this.words[j + 1] = w >>> 26 - off & 67108863;
                      off += 24;
                      if (off >= 26) {
                        off -= 26;
                        j++;
                      }
                    }
                  }
                  return this.strip();
                };
                function parseHex4Bits(string, index) {
                  var c = string.charCodeAt(index);
                  if (c >= 65 && c <= 70) {
                    return c - 55;
                  } else if (c >= 97 && c <= 102) {
                    return c - 87;
                  } else {
                    return c - 48 & 15;
                  }
                }
                function parseHexByte(string, lowerBound, index) {
                  var r = parseHex4Bits(string, index);
                  if (index - 1 >= lowerBound) {
                    r |= parseHex4Bits(string, index - 1) << 4;
                  }
                  return r;
                }
                BN.prototype._parseHex = function _parseHex(number, start, endian) {
                  this.length = Math.ceil((number.length - start) / 6);
                  this.words = new Array(this.length);
                  for (var i = 0; i < this.length; i++) {
                    this.words[i] = 0;
                  }
                  var off = 0;
                  var j = 0;
                  var w;
                  if (endian === "be") {
                    for (i = number.length - 1; i >= start; i -= 2) {
                      w = parseHexByte(number, start, i) << off;
                      this.words[j] |= w & 67108863;
                      if (off >= 18) {
                        off -= 18;
                        j += 1;
                        this.words[j] |= w >>> 26;
                      } else {
                        off += 8;
                      }
                    }
                  } else {
                    var parseLength = number.length - start;
                    for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
                      w = parseHexByte(number, start, i) << off;
                      this.words[j] |= w & 67108863;
                      if (off >= 18) {
                        off -= 18;
                        j += 1;
                        this.words[j] |= w >>> 26;
                      } else {
                        off += 8;
                      }
                    }
                  }
                  this.strip();
                };
                function parseBase(str, start, end, mul) {
                  var r = 0;
                  var len = Math.min(str.length, end);
                  for (var i = start; i < len; i++) {
                    var c = str.charCodeAt(i) - 48;
                    r *= mul;
                    if (c >= 49) {
                      r += c - 49 + 10;
                    } else if (c >= 17) {
                      r += c - 17 + 10;
                    } else {
                      r += c;
                    }
                  }
                  return r;
                }
                BN.prototype._parseBase = function _parseBase(number, base, start) {
                  this.words = [0];
                  this.length = 1;
                  for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base) {
                    limbLen++;
                  }
                  limbLen--;
                  limbPow = limbPow / base | 0;
                  var total = number.length - start;
                  var mod = total % limbLen;
                  var end = Math.min(total, total - mod) + start;
                  var word = 0;
                  for (var i = start; i < end; i += limbLen) {
                    word = parseBase(number, i, i + limbLen, base);
                    this.imuln(limbPow);
                    if (this.words[0] + word < 67108864) {
                      this.words[0] += word;
                    } else {
                      this._iaddn(word);
                    }
                  }
                  if (mod !== 0) {
                    var pow = 1;
                    word = parseBase(number, i, number.length, base);
                    for (i = 0; i < mod; i++) {
                      pow *= base;
                    }
                    this.imuln(pow);
                    if (this.words[0] + word < 67108864) {
                      this.words[0] += word;
                    } else {
                      this._iaddn(word);
                    }
                  }
                  this.strip();
                };
                BN.prototype.copy = function copy(dest) {
                  dest.words = new Array(this.length);
                  for (var i = 0; i < this.length; i++) {
                    dest.words[i] = this.words[i];
                  }
                  dest.length = this.length;
                  dest.negative = this.negative;
                  dest.red = this.red;
                };
                BN.prototype.clone = function clone() {
                  var r = new BN(null);
                  this.copy(r);
                  return r;
                };
                BN.prototype._expand = function _expand(size) {
                  while (this.length < size) {
                    this.words[this.length++] = 0;
                  }
                  return this;
                };
                BN.prototype.strip = function strip() {
                  while (this.length > 1 && this.words[this.length - 1] === 0) {
                    this.length--;
                  }
                  return this._normSign();
                };
                BN.prototype._normSign = function _normSign() {
                  if (this.length === 1 && this.words[0] === 0) {
                    this.negative = 0;
                  }
                  return this;
                };
                BN.prototype.inspect = function inspect() {
                  return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
                };
                var zeros = [
                  "",
                  "0",
                  "00",
                  "000",
                  "0000",
                  "00000",
                  "000000",
                  "0000000",
                  "00000000",
                  "000000000",
                  "0000000000",
                  "00000000000",
                  "000000000000",
                  "0000000000000",
                  "00000000000000",
                  "000000000000000",
                  "0000000000000000",
                  "00000000000000000",
                  "000000000000000000",
                  "0000000000000000000",
                  "00000000000000000000",
                  "000000000000000000000",
                  "0000000000000000000000",
                  "00000000000000000000000",
                  "000000000000000000000000",
                  "0000000000000000000000000"
                ];
                var groupSizes = [
                  0,
                  0,
                  25,
                  16,
                  12,
                  11,
                  10,
                  9,
                  8,
                  8,
                  7,
                  7,
                  7,
                  7,
                  6,
                  6,
                  6,
                  6,
                  6,
                  6,
                  6,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5,
                  5
                ];
                var groupBases = [
                  0,
                  0,
                  33554432,
                  43046721,
                  16777216,
                  48828125,
                  60466176,
                  40353607,
                  16777216,
                  43046721,
                  1e7,
                  19487171,
                  35831808,
                  62748517,
                  7529536,
                  11390625,
                  16777216,
                  24137569,
                  34012224,
                  47045881,
                  64e6,
                  4084101,
                  5153632,
                  6436343,
                  7962624,
                  9765625,
                  11881376,
                  14348907,
                  17210368,
                  20511149,
                  243e5,
                  28629151,
                  33554432,
                  39135393,
                  45435424,
                  52521875,
                  60466176
                ];
                BN.prototype.toString = function toString(base, padding) {
                  base = base || 10;
                  padding = padding | 0 || 1;
                  var out;
                  if (base === 16 || base === "hex") {
                    out = "";
                    var off = 0;
                    var carry = 0;
                    for (var i = 0; i < this.length; i++) {
                      var w = this.words[i];
                      var word = ((w << off | carry) & 16777215).toString(16);
                      carry = w >>> 24 - off & 16777215;
                      if (carry !== 0 || i !== this.length - 1) {
                        out = zeros[6 - word.length] + word + out;
                      } else {
                        out = word + out;
                      }
                      off += 2;
                      if (off >= 26) {
                        off -= 26;
                        i--;
                      }
                    }
                    if (carry !== 0) {
                      out = carry.toString(16) + out;
                    }
                    while (out.length % padding !== 0) {
                      out = "0" + out;
                    }
                    if (this.negative !== 0) {
                      out = "-" + out;
                    }
                    return out;
                  }
                  if (base === (base | 0) && base >= 2 && base <= 36) {
                    var groupSize = groupSizes[base];
                    var groupBase = groupBases[base];
                    out = "";
                    var c = this.clone();
                    c.negative = 0;
                    while (!c.isZero()) {
                      var r = c.modn(groupBase).toString(base);
                      c = c.idivn(groupBase);
                      if (!c.isZero()) {
                        out = zeros[groupSize - r.length] + r + out;
                      } else {
                        out = r + out;
                      }
                    }
                    if (this.isZero()) {
                      out = "0" + out;
                    }
                    while (out.length % padding !== 0) {
                      out = "0" + out;
                    }
                    if (this.negative !== 0) {
                      out = "-" + out;
                    }
                    return out;
                  }
                  assert(false, "Base should be between 2 and 36");
                };
                BN.prototype.toNumber = function toNumber() {
                  var ret = this.words[0];
                  if (this.length === 2) {
                    ret += this.words[1] * 67108864;
                  } else if (this.length === 3 && this.words[2] === 1) {
                    ret += 4503599627370496 + this.words[1] * 67108864;
                  } else if (this.length > 2) {
                    assert(false, "Number can only safely store up to 53 bits");
                  }
                  return this.negative !== 0 ? -ret : ret;
                };
                BN.prototype.toJSON = function toJSON() {
                  return this.toString(16);
                };
                BN.prototype.toBuffer = function toBuffer(endian, length) {
                  assert(typeof Buffer2 !== "undefined");
                  return this.toArrayLike(Buffer2, endian, length);
                };
                BN.prototype.toArray = function toArray(endian, length) {
                  return this.toArrayLike(Array, endian, length);
                };
                BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) {
                  var byteLength = this.byteLength();
                  var reqLength = length || Math.max(1, byteLength);
                  assert(byteLength <= reqLength, "byte array longer than desired length");
                  assert(reqLength > 0, "Requested array length <= 0");
                  this.strip();
                  var littleEndian = endian === "le";
                  var res = new ArrayType(reqLength);
                  var b, i;
                  var q = this.clone();
                  if (!littleEndian) {
                    for (i = 0; i < reqLength - byteLength; i++) {
                      res[i] = 0;
                    }
                    for (i = 0; !q.isZero(); i++) {
                      b = q.andln(255);
                      q.iushrn(8);
                      res[reqLength - i - 1] = b;
                    }
                  } else {
                    for (i = 0; !q.isZero(); i++) {
                      b = q.andln(255);
                      q.iushrn(8);
                      res[i] = b;
                    }
                    for (; i < reqLength; i++) {
                      res[i] = 0;
                    }
                  }
                  return res;
                };
                if (Math.clz32) {
                  BN.prototype._countBits = function _countBits(w) {
                    return 32 - Math.clz32(w);
                  };
                } else {
                  BN.prototype._countBits = function _countBits(w) {
                    var t = w;
                    var r = 0;
                    if (t >= 4096) {
                      r += 13;
                      t >>>= 13;
                    }
                    if (t >= 64) {
                      r += 7;
                      t >>>= 7;
                    }
                    if (t >= 8) {
                      r += 4;
                      t >>>= 4;
                    }
                    if (t >= 2) {
                      r += 2;
                      t >>>= 2;
                    }
                    return r + t;
                  };
                }
                BN.prototype._zeroBits = function _zeroBits(w) {
                  if (w === 0) return 26;
                  var t = w;
                  var r = 0;
                  if ((t & 8191) === 0) {
                    r += 13;
                    t >>>= 13;
                  }
                  if ((t & 127) === 0) {
                    r += 7;
                    t >>>= 7;
                  }
                  if ((t & 15) === 0) {
                    r += 4;
                    t >>>= 4;
                  }
                  if ((t & 3) === 0) {
                    r += 2;
                    t >>>= 2;
                  }
                  if ((t & 1) === 0) {
                    r++;
                  }
                  return r;
                };
                BN.prototype.bitLength = function bitLength() {
                  var w = this.words[this.length - 1];
                  var hi = this._countBits(w);
                  return (this.length - 1) * 26 + hi;
                };
                function toBitArray(num) {
                  var w = new Array(num.bitLength());
                  for (var bit = 0; bit < w.length; bit++) {
                    var off = bit / 26 | 0;
                    var wbit = bit % 26;
                    w[bit] = (num.words[off] & 1 << wbit) >>> wbit;
                  }
                  return w;
                }
                BN.prototype.zeroBits = function zeroBits() {
                  if (this.isZero()) return 0;
                  var r = 0;
                  for (var i = 0; i < this.length; i++) {
                    var b = this._zeroBits(this.words[i]);
                    r += b;
                    if (b !== 26) break;
                  }
                  return r;
                };
                BN.prototype.byteLength = function byteLength() {
                  return Math.ceil(this.bitLength() / 8);
                };
                BN.prototype.toTwos = function toTwos(width) {
                  if (this.negative !== 0) {
                    return this.abs().inotn(width).iaddn(1);
                  }
                  return this.clone();
                };
                BN.prototype.fromTwos = function fromTwos(width) {
                  if (this.testn(width - 1)) {
                    return this.notn(width).iaddn(1).ineg();
                  }
                  return this.clone();
                };
                BN.prototype.isNeg = function isNeg() {
                  return this.negative !== 0;
                };
                BN.prototype.neg = function neg() {
                  return this.clone().ineg();
                };
                BN.prototype.ineg = function ineg() {
                  if (!this.isZero()) {
                    this.negative ^= 1;
                  }
                  return this;
                };
                BN.prototype.iuor = function iuor(num) {
                  while (this.length < num.length) {
                    this.words[this.length++] = 0;
                  }
                  for (var i = 0; i < num.length; i++) {
                    this.words[i] = this.words[i] | num.words[i];
                  }
                  return this.strip();
                };
                BN.prototype.ior = function ior(num) {
                  assert((this.negative | num.negative) === 0);
                  return this.iuor(num);
                };
                BN.prototype.or = function or(num) {
                  if (this.length > num.length) return this.clone().ior(num);
                  return num.clone().ior(this);
                };
                BN.prototype.uor = function uor(num) {
                  if (this.length > num.length) return this.clone().iuor(num);
                  return num.clone().iuor(this);
                };
                BN.prototype.iuand = function iuand(num) {
                  var b;
                  if (this.length > num.length) {
                    b = num;
                  } else {
                    b = this;
                  }
                  for (var i = 0; i < b.length; i++) {
                    this.words[i] = this.words[i] & num.words[i];
                  }
                  this.length = b.length;
                  return this.strip();
                };
                BN.prototype.iand = function iand(num) {
                  assert((this.negative | num.negative) === 0);
                  return this.iuand(num);
                };
                BN.prototype.and = function and(num) {
                  if (this.length > num.length) return this.clone().iand(num);
                  return num.clone().iand(this);
                };
                BN.prototype.uand = function uand(num) {
                  if (this.length > num.length) return this.clone().iuand(num);
                  return num.clone().iuand(this);
                };
                BN.prototype.iuxor = function iuxor(num) {
                  var a;
                  var b;
                  if (this.length > num.length) {
                    a = this;
                    b = num;
                  } else {
                    a = num;
                    b = this;
                  }
                  for (var i = 0; i < b.length; i++) {
                    this.words[i] = a.words[i] ^ b.words[i];
                  }
                  if (this !== a) {
                    for (; i < a.length; i++) {
                      this.words[i] = a.words[i];
                    }
                  }
                  this.length = a.length;
                  return this.strip();
                };
                BN.prototype.ixor = function ixor(num) {
                  assert((this.negative | num.negative) === 0);
                  return this.iuxor(num);
                };
                BN.prototype.xor = function xor(num) {
                  if (this.length > num.length) return this.clone().ixor(num);
                  return num.clone().ixor(this);
                };
                BN.prototype.uxor = function uxor(num) {
                  if (this.length > num.length) return this.clone().iuxor(num);
                  return num.clone().iuxor(this);
                };
                BN.prototype.inotn = function inotn(width) {
                  assert(typeof width === "number" && width >= 0);
                  var bytesNeeded = Math.ceil(width / 26) | 0;
                  var bitsLeft = width % 26;
                  this._expand(bytesNeeded);
                  if (bitsLeft > 0) {
                    bytesNeeded--;
                  }
                  for (var i = 0; i < bytesNeeded; i++) {
                    this.words[i] = ~this.words[i] & 67108863;
                  }
                  if (bitsLeft > 0) {
                    this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft;
                  }
                  return this.strip();
                };
                BN.prototype.notn = function notn(width) {
                  return this.clone().inotn(width);
                };
                BN.prototype.setn = function setn(bit, val) {
                  assert(typeof bit === "number" && bit >= 0);
                  var off = bit / 26 | 0;
                  var wbit = bit % 26;
                  this._expand(off + 1);
                  if (val) {
                    this.words[off] = this.words[off] | 1 << wbit;
                  } else {
                    this.words[off] = this.words[off] & ~(1 << wbit);
                  }
                  return this.strip();
                };
                BN.prototype.iadd = function iadd(num) {
                  var r;
                  if (this.negative !== 0 && num.negative === 0) {
                    this.negative = 0;
                    r = this.isub(num);
                    this.negative ^= 1;
                    return this._normSign();
                  } else if (this.negative === 0 && num.negative !== 0) {
                    num.negative = 0;
                    r = this.isub(num);
                    num.negative = 1;
                    return r._normSign();
                  }
                  var a, b;
                  if (this.length > num.length) {
                    a = this;
                    b = num;
                  } else {
                    a = num;
                    b = this;
                  }
                  var carry = 0;
                  for (var i = 0; i < b.length; i++) {
                    r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
                    this.words[i] = r & 67108863;
                    carry = r >>> 26;
                  }
                  for (; carry !== 0 && i < a.length; i++) {
                    r = (a.words[i] | 0) + carry;
                    this.words[i] = r & 67108863;
                    carry = r >>> 26;
                  }
                  this.length = a.length;
                  if (carry !== 0) {
                    this.words[this.length] = carry;
                    this.length++;
                  } else if (a !== this) {
                    for (; i < a.length; i++) {
                      this.words[i] = a.words[i];
                    }
                  }
                  return this;
                };
                BN.prototype.add = function add(num) {
                  var res;
                  if (num.negative !== 0 && this.negative === 0) {
                    num.negative = 0;
                    res = this.sub(num);
                    num.negative ^= 1;
                    return res;
                  } else if (num.negative === 0 && this.negative !== 0) {
                    this.negative = 0;
                    res = num.sub(this);
                    this.negative = 1;
                    return res;
                  }
                  if (this.length > num.length) return this.clone().iadd(num);
                  return num.clone().iadd(this);
                };
                BN.prototype.isub = function isub(num) {
                  if (num.negative !== 0) {
                    num.negative = 0;
                    var r = this.iadd(num);
                    num.negative = 1;
                    return r._normSign();
                  } else if (this.negative !== 0) {
                    this.negative = 0;
                    this.iadd(num);
                    this.negative = 1;
                    return this._normSign();
                  }
                  var cmp = this.cmp(num);
                  if (cmp === 0) {
                    this.negative = 0;
                    this.length = 1;
                    this.words[0] = 0;
                    return this;
                  }
                  var a, b;
                  if (cmp > 0) {
                    a = this;
                    b = num;
                  } else {
                    a = num;
                    b = this;
                  }
                  var carry = 0;
                  for (var i = 0; i < b.length; i++) {
                    r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
                    carry = r >> 26;
                    this.words[i] = r & 67108863;
                  }
                  for (; carry !== 0 && i < a.length; i++) {
                    r = (a.words[i] | 0) + carry;
                    carry = r >> 26;
                    this.words[i] = r & 67108863;
                  }
                  if (carry === 0 && i < a.length && a !== this) {
                    for (; i < a.length; i++) {
                      this.words[i] = a.words[i];
                    }
                  }
                  this.length = Math.max(this.length, i);
                  if (a !== this) {
                    this.negative = 1;
                  }
                  return this.strip();
                };
                BN.prototype.sub = function sub(num) {
                  return this.clone().isub(num);
                };
                function smallMulTo(self2, num, out) {
                  out.negative = num.negative ^ self2.negative;
                  var len = self2.length + num.length | 0;
                  out.length = len;
                  len = len - 1 | 0;
                  var a = self2.words[0] | 0;
                  var b = num.words[0] | 0;
                  var r = a * b;
                  var lo = r & 67108863;
                  var carry = r / 67108864 | 0;
                  out.words[0] = lo;
                  for (var k = 1; k < len; k++) {
                    var ncarry = carry >>> 26;
                    var rword = carry & 67108863;
                    var maxJ = Math.min(k, num.length - 1);
                    for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) {
                      var i = k - j | 0;
                      a = self2.words[i] | 0;
                      b = num.words[j] | 0;
                      r = a * b + rword;
                      ncarry += r / 67108864 | 0;
                      rword = r & 67108863;
                    }
                    out.words[k] = rword | 0;
                    carry = ncarry | 0;
                  }
                  if (carry !== 0) {
                    out.words[k] = carry | 0;
                  } else {
                    out.length--;
                  }
                  return out.strip();
                }
                var comb10MulTo = function comb10MulTo2(self2, num, out) {
                  var a = self2.words;
                  var b = num.words;
                  var o = out.words;
                  var c = 0;
                  var lo;
                  var mid;
                  var hi;
                  var a0 = a[0] | 0;
                  var al0 = a0 & 8191;
                  var ah0 = a0 >>> 13;
                  var a1 = a[1] | 0;
                  var al1 = a1 & 8191;
                  var ah1 = a1 >>> 13;
                  var a2 = a[2] | 0;
                  var al2 = a2 & 8191;
                  var ah2 = a2 >>> 13;
                  var a3 = a[3] | 0;
                  var al3 = a3 & 8191;
                  var ah3 = a3 >>> 13;
                  var a4 = a[4] | 0;
                  var al4 = a4 & 8191;
                  var ah4 = a4 >>> 13;
                  var a5 = a[5] | 0;
                  var al5 = a5 & 8191;
                  var ah5 = a5 >>> 13;
                  var a6 = a[6] | 0;
                  var al6 = a6 & 8191;
                  var ah6 = a6 >>> 13;
                  var a7 = a[7] | 0;
                  var al7 = a7 & 8191;
                  var ah7 = a7 >>> 13;
                  var a8 = a[8] | 0;
                  var al8 = a8 & 8191;
                  var ah8 = a8 >>> 13;
                  var a9 = a[9] | 0;
                  var al9 = a9 & 8191;
                  var ah9 = a9 >>> 13;
                  var b0 = b[0] | 0;
                  var bl0 = b0 & 8191;
                  var bh0 = b0 >>> 13;
                  var b1 = b[1] | 0;
                  var bl1 = b1 & 8191;
                  var bh1 = b1 >>> 13;
                  var b2 = b[2] | 0;
                  var bl2 = b2 & 8191;
                  var bh2 = b2 >>> 13;
                  var b3 = b[3] | 0;
                  var bl3 = b3 & 8191;
                  var bh3 = b3 >>> 13;
                  var b4 = b[4] | 0;
                  var bl4 = b4 & 8191;
                  var bh4 = b4 >>> 13;
                  var b5 = b[5] | 0;
                  var bl5 = b5 & 8191;
                  var bh5 = b5 >>> 13;
                  var b6 = b[6] | 0;
                  var bl6 = b6 & 8191;
                  var bh6 = b6 >>> 13;
                  var b7 = b[7] | 0;
                  var bl7 = b7 & 8191;
                  var bh7 = b7 >>> 13;
                  var b8 = b[8] | 0;
                  var bl8 = b8 & 8191;
                  var bh8 = b8 >>> 13;
                  var b9 = b[9] | 0;
                  var bl9 = b9 & 8191;
                  var bh9 = b9 >>> 13;
                  out.negative = self2.negative ^ num.negative;
                  out.length = 19;
                  lo = Math.imul(al0, bl0);
                  mid = Math.imul(al0, bh0);
                  mid = mid + Math.imul(ah0, bl0) | 0;
                  hi = Math.imul(ah0, bh0);
                  var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0;
                  w0 &= 67108863;
                  lo = Math.imul(al1, bl0);
                  mid = Math.imul(al1, bh0);
                  mid = mid + Math.imul(ah1, bl0) | 0;
                  hi = Math.imul(ah1, bh0);
                  lo = lo + Math.imul(al0, bl1) | 0;
                  mid = mid + Math.imul(al0, bh1) | 0;
                  mid = mid + Math.imul(ah0, bl1) | 0;
                  hi = hi + Math.imul(ah0, bh1) | 0;
                  var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0;
                  w1 &= 67108863;
                  lo = Math.imul(al2, bl0);
                  mid = Math.imul(al2, bh0);
                  mid = mid + Math.imul(ah2, bl0) | 0;
                  hi = Math.imul(ah2, bh0);
                  lo = lo + Math.imul(al1, bl1) | 0;
                  mid = mid + Math.imul(al1, bh1) | 0;
                  mid = mid + Math.imul(ah1, bl1) | 0;
                  hi = hi + Math.imul(ah1, bh1) | 0;
                  lo = lo + Math.imul(al0, bl2) | 0;
                  mid = mid + Math.imul(al0, bh2) | 0;
                  mid = mid + Math.imul(ah0, bl2) | 0;
                  hi = hi + Math.imul(ah0, bh2) | 0;
                  var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0;
                  w2 &= 67108863;
                  lo = Math.imul(al3, bl0);
                  mid = Math.imul(al3, bh0);
                  mid = mid + Math.imul(ah3, bl0) | 0;
                  hi = Math.imul(ah3, bh0);
                  lo = lo + Math.imul(al2, bl1) | 0;
                  mid = mid + Math.imul(al2, bh1) | 0;
                  mid = mid + Math.imul(ah2, bl1) | 0;
                  hi = hi + Math.imul(ah2, bh1) | 0;
                  lo = lo + Math.imul(al1, bl2) | 0;
                  mid = mid + Math.imul(al1, bh2) | 0;
                  mid = mid + Math.imul(ah1, bl2) | 0;
                  hi = hi + Math.imul(ah1, bh2) | 0;
                  lo = lo + Math.imul(al0, bl3) | 0;
                  mid = mid + Math.imul(al0, bh3) | 0;
                  mid = mid + Math.imul(ah0, bl3) | 0;
                  hi = hi + Math.imul(ah0, bh3) | 0;
                  var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0;
                  w3 &= 67108863;
                  lo = Math.imul(al4, bl0);
                  mid = Math.imul(al4, bh0);
                  mid = mid + Math.imul(ah4, bl0) | 0;
                  hi = Math.imul(ah4, bh0);
                  lo = lo + Math.imul(al3, bl1) | 0;
                  mid = mid + Math.imul(al3, bh1) | 0;
                  mid = mid + Math.imul(ah3, bl1) | 0;
                  hi = hi + Math.imul(ah3, bh1) | 0;
                  lo = lo + Math.imul(al2, bl2) | 0;
                  mid = mid + Math.imul(al2, bh2) | 0;
                  mid = mid + Math.imul(ah2, bl2) | 0;
                  hi = hi + Math.imul(ah2, bh2) | 0;
                  lo = lo + Math.imul(al1, bl3) | 0;
                  mid = mid + Math.imul(al1, bh3) | 0;
                  mid = mid + Math.imul(ah1, bl3) | 0;
                  hi = hi + Math.imul(ah1, bh3) | 0;
                  lo = lo + Math.imul(al0, bl4) | 0;
                  mid = mid + Math.imul(al0, bh4) | 0;
                  mid = mid + Math.imul(ah0, bl4) | 0;
                  hi = hi + Math.imul(ah0, bh4) | 0;
                  var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0;
                  w4 &= 67108863;
                  lo = Math.imul(al5, bl0);
                  mid = Math.imul(al5, bh0);
                  mid = mid + Math.imul(ah5, bl0) | 0;
                  hi = Math.imul(ah5, bh0);
                  lo = lo + Math.imul(al4, bl1) | 0;
                  mid = mid + Math.imul(al4, bh1) | 0;
                  mid = mid + Math.imul(ah4, bl1) | 0;
                  hi = hi + Math.imul(ah4, bh1) | 0;
                  lo = lo + Math.imul(al3, bl2) | 0;
                  mid = mid + Math.imul(al3, bh2) | 0;
                  mid = mid + Math.imul(ah3, bl2) | 0;
                  hi = hi + Math.imul(ah3, bh2) | 0;
                  lo = lo + Math.imul(al2, bl3) | 0;
                  mid = mid + Math.imul(al2, bh3) | 0;
                  mid = mid + Math.imul(ah2, bl3) | 0;
                  hi = hi + Math.imul(ah2, bh3) | 0;
                  lo = lo + Math.imul(al1, bl4) | 0;
                  mid = mid + Math.imul(al1, bh4) | 0;
                  mid = mid + Math.imul(ah1, bl4) | 0;
                  hi = hi + Math.imul(ah1, bh4) | 0;
                  lo = lo + Math.imul(al0, bl5) | 0;
                  mid = mid + Math.imul(al0, bh5) | 0;
                  mid = mid + Math.imul(ah0, bl5) | 0;
                  hi = hi + Math.imul(ah0, bh5) | 0;
                  var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0;
                  w5 &= 67108863;
                  lo = Math.imul(al6, bl0);
                  mid = Math.imul(al6, bh0);
                  mid = mid + Math.imul(ah6, bl0) | 0;
                  hi = Math.imul(ah6, bh0);
                  lo = lo + Math.imul(al5, bl1) | 0;
                  mid = mid + Math.imul(al5, bh1) | 0;
                  mid = mid + Math.imul(ah5, bl1) | 0;
                  hi = hi + Math.imul(ah5, bh1) | 0;
                  lo = lo + Math.imul(al4, bl2) | 0;
                  mid = mid + Math.imul(al4, bh2) | 0;
                  mid = mid + Math.imul(ah4, bl2) | 0;
                  hi = hi + Math.imul(ah4, bh2) | 0;
                  lo = lo + Math.imul(al3, bl3) | 0;
                  mid = mid + Math.imul(al3, bh3) | 0;
                  mid = mid + Math.imul(ah3, bl3) | 0;
                  hi = hi + Math.imul(ah3, bh3) | 0;
                  lo = lo + Math.imul(al2, bl4) | 0;
                  mid = mid + Math.imul(al2, bh4) | 0;
                  mid = mid + Math.imul(ah2, bl4) | 0;
                  hi = hi + Math.imul(ah2, bh4) | 0;
                  lo = lo + Math.imul(al1, bl5) | 0;
                  mid = mid + Math.imul(al1, bh5) | 0;
                  mid = mid + Math.imul(ah1, bl5) | 0;
                  hi = hi + Math.imul(ah1, bh5) | 0;
                  lo = lo + Math.imul(al0, bl6) | 0;
                  mid = mid + Math.imul(al0, bh6) | 0;
                  mid = mid + Math.imul(ah0, bl6) | 0;
                  hi = hi + Math.imul(ah0, bh6) | 0;
                  var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0;
                  w6 &= 67108863;
                  lo = Math.imul(al7, bl0);
                  mid = Math.imul(al7, bh0);
                  mid = mid + Math.imul(ah7, bl0) | 0;
                  hi = Math.imul(ah7, bh0);
                  lo = lo + Math.imul(al6, bl1) | 0;
                  mid = mid + Math.imul(al6, bh1) | 0;
                  mid = mid + Math.imul(ah6, bl1) | 0;
                  hi = hi + Math.imul(ah6, bh1) | 0;
                  lo = lo + Math.imul(al5, bl2) | 0;
                  mid = mid + Math.imul(al5, bh2) | 0;
                  mid = mid + Math.imul(ah5, bl2) | 0;
                  hi = hi + Math.imul(ah5, bh2) | 0;
                  lo = lo + Math.imul(al4, bl3) | 0;
                  mid = mid + Math.imul(al4, bh3) | 0;
                  mid = mid + Math.imul(ah4, bl3) | 0;
                  hi = hi + Math.imul(ah4, bh3) | 0;
                  lo = lo + Math.imul(al3, bl4) | 0;
                  mid = mid + Math.imul(al3, bh4) | 0;
                  mid = mid + Math.imul(ah3, bl4) | 0;
                  hi = hi + Math.imul(ah3, bh4) | 0;
                  lo = lo + Math.imul(al2, bl5) | 0;
                  mid = mid + Math.imul(al2, bh5) | 0;
                  mid = mid + Math.imul(ah2, bl5) | 0;
                  hi = hi + Math.imul(ah2, bh5) | 0;
                  lo = lo + Math.imul(al1, bl6) | 0;
                  mid = mid + Math.imul(al1, bh6) | 0;
                  mid = mid + Math.imul(ah1, bl6) | 0;
                  hi = hi + Math.imul(ah1, bh6) | 0;
                  lo = lo + Math.imul(al0, bl7) | 0;
                  mid = mid + Math.imul(al0, bh7) | 0;
                  mid = mid + Math.imul(ah0, bl7) | 0;
                  hi = hi + Math.imul(ah0, bh7) | 0;
                  var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0;
                  w7 &= 67108863;
                  lo = Math.imul(al8, bl0);
                  mid = Math.imul(al8, bh0);
                  mid = mid + Math.imul(ah8, bl0) | 0;
                  hi = Math.imul(ah8, bh0);
                  lo = lo + Math.imul(al7, bl1) | 0;
                  mid = mid + Math.imul(al7, bh1) | 0;
                  mid = mid + Math.imul(ah7, bl1) | 0;
                  hi = hi + Math.imul(ah7, bh1) | 0;
                  lo = lo + Math.imul(al6, bl2) | 0;
                  mid = mid + Math.imul(al6, bh2) | 0;
                  mid = mid + Math.imul(ah6, bl2) | 0;
                  hi = hi + Math.imul(ah6, bh2) | 0;
                  lo = lo + Math.imul(al5, bl3) | 0;
                  mid = mid + Math.imul(al5, bh3) | 0;
                  mid = mid + Math.imul(ah5, bl3) | 0;
                  hi = hi + Math.imul(ah5, bh3) | 0;
                  lo = lo + Math.imul(al4, bl4) | 0;
                  mid = mid + Math.imul(al4, bh4) | 0;
                  mid = mid + Math.imul(ah4, bl4) | 0;
                  hi = hi + Math.imul(ah4, bh4) | 0;
                  lo = lo + Math.imul(al3, bl5) | 0;
                  mid = mid + Math.imul(al3, bh5) | 0;
                  mid = mid + Math.imul(ah3, bl5) | 0;
                  hi = hi + Math.imul(ah3, bh5) | 0;
                  lo = lo + Math.imul(al2, bl6) | 0;
                  mid = mid + Math.imul(al2, bh6) | 0;
                  mid = mid + Math.imul(ah2, bl6) | 0;
                  hi = hi + Math.imul(ah2, bh6) | 0;
                  lo = lo + Math.imul(al1, bl7) | 0;
                  mid = mid + Math.imul(al1, bh7) | 0;
                  mid = mid + Math.imul(ah1, bl7) | 0;
                  hi = hi + Math.imul(ah1, bh7) | 0;
                  lo = lo + Math.imul(al0, bl8) | 0;
                  mid = mid + Math.imul(al0, bh8) | 0;
                  mid = mid + Math.imul(ah0, bl8) | 0;
                  hi = hi + Math.imul(ah0, bh8) | 0;
                  var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0;
                  w8 &= 67108863;
                  lo = Math.imul(al9, bl0);
                  mid = Math.imul(al9, bh0);
                  mid = mid + Math.imul(ah9, bl0) | 0;
                  hi = Math.imul(ah9, bh0);
                  lo = lo + Math.imul(al8, bl1) | 0;
                  mid = mid + Math.imul(al8, bh1) | 0;
                  mid = mid + Math.imul(ah8, bl1) | 0;
                  hi = hi + Math.imul(ah8, bh1) | 0;
                  lo = lo + Math.imul(al7, bl2) | 0;
                  mid = mid + Math.imul(al7, bh2) | 0;
                  mid = mid + Math.imul(ah7, bl2) | 0;
                  hi = hi + Math.imul(ah7, bh2) | 0;
                  lo = lo + Math.imul(al6, bl3) | 0;
                  mid = mid + Math.imul(al6, bh3) | 0;
                  mid = mid + Math.imul(ah6, bl3) | 0;
                  hi = hi + Math.imul(ah6, bh3) | 0;
                  lo = lo + Math.imul(al5, bl4) | 0;
                  mid = mid + Math.imul(al5, bh4) | 0;
                  mid = mid + Math.imul(ah5, bl4) | 0;
                  hi = hi + Math.imul(ah5, bh4) | 0;
                  lo = lo + Math.imul(al4, bl5) | 0;
                  mid = mid + Math.imul(al4, bh5) | 0;
                  mid = mid + Math.imul(ah4, bl5) | 0;
                  hi = hi + Math.imul(ah4, bh5) | 0;
                  lo = lo + Math.imul(al3, bl6) | 0;
                  mid = mid + Math.imul(al3, bh6) | 0;
                  mid = mid + Math.imul(ah3, bl6) | 0;
                  hi = hi + Math.imul(ah3, bh6) | 0;
                  lo = lo + Math.imul(al2, bl7) | 0;
                  mid = mid + Math.imul(al2, bh7) | 0;
                  mid = mid + Math.imul(ah2, bl7) | 0;
                  hi = hi + Math.imul(ah2, bh7) | 0;
                  lo = lo + Math.imul(al1, bl8) | 0;
                  mid = mid + Math.imul(al1, bh8) | 0;
                  mid = mid + Math.imul(ah1, bl8) | 0;
                  hi = hi + Math.imul(ah1, bh8) | 0;
                  lo = lo + Math.imul(al0, bl9) | 0;
                  mid = mid + Math.imul(al0, bh9) | 0;
                  mid = mid + Math.imul(ah0, bl9) | 0;
                  hi = hi + Math.imul(ah0, bh9) | 0;
                  var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0;
                  w9 &= 67108863;
                  lo = Math.imul(al9, bl1);
                  mid = Math.imul(al9, bh1);
                  mid = mid + Math.imul(ah9, bl1) | 0;
                  hi = Math.imul(ah9, bh1);
                  lo = lo + Math.imul(al8, bl2) | 0;
                  mid = mid + Math.imul(al8, bh2) | 0;
                  mid = mid + Math.imul(ah8, bl2) | 0;
                  hi = hi + Math.imul(ah8, bh2) | 0;
                  lo = lo + Math.imul(al7, bl3) | 0;
                  mid = mid + Math.imul(al7, bh3) | 0;
                  mid = mid + Math.imul(ah7, bl3) | 0;
                  hi = hi + Math.imul(ah7, bh3) | 0;
                  lo = lo + Math.imul(al6, bl4) | 0;
                  mid = mid + Math.imul(al6, bh4) | 0;
                  mid = mid + Math.imul(ah6, bl4) | 0;
                  hi = hi + Math.imul(ah6, bh4) | 0;
                  lo = lo + Math.imul(al5, bl5) | 0;
                  mid = mid + Math.imul(al5, bh5) | 0;
                  mid = mid + Math.imul(ah5, bl5) | 0;
                  hi = hi + Math.imul(ah5, bh5) | 0;
                  lo = lo + Math.imul(al4, bl6) | 0;
                  mid = mid + Math.imul(al4, bh6) | 0;
                  mid = mid + Math.imul(ah4, bl6) | 0;
                  hi = hi + Math.imul(ah4, bh6) | 0;
                  lo = lo + Math.imul(al3, bl7) | 0;
                  mid = mid + Math.imul(al3, bh7) | 0;
                  mid = mid + Math.imul(ah3, bl7) | 0;
                  hi = hi + Math.imul(ah3, bh7) | 0;
                  lo = lo + Math.imul(al2, bl8) | 0;
                  mid = mid + Math.imul(al2, bh8) | 0;
                  mid = mid + Math.imul(ah2, bl8) | 0;
                  hi = hi + Math.imul(ah2, bh8) | 0;
                  lo = lo + Math.imul(al1, bl9) | 0;
                  mid = mid + Math.imul(al1, bh9) | 0;
                  mid = mid + Math.imul(ah1, bl9) | 0;
                  hi = hi + Math.imul(ah1, bh9) | 0;
                  var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0;
                  w10 &= 67108863;
                  lo = Math.imul(al9, bl2);
                  mid = Math.imul(al9, bh2);
                  mid = mid + Math.imul(ah9, bl2) | 0;
                  hi = Math.imul(ah9, bh2);
                  lo = lo + Math.imul(al8, bl3) | 0;
                  mid = mid + Math.imul(al8, bh3) | 0;
                  mid = mid + Math.imul(ah8, bl3) | 0;
                  hi = hi + Math.imul(ah8, bh3) | 0;
                  lo = lo + Math.imul(al7, bl4) | 0;
                  mid = mid + Math.imul(al7, bh4) | 0;
                  mid = mid + Math.imul(ah7, bl4) | 0;
                  hi = hi + Math.imul(ah7, bh4) | 0;
                  lo = lo + Math.imul(al6, bl5) | 0;
                  mid = mid + Math.imul(al6, bh5) | 0;
                  mid = mid + Math.imul(ah6, bl5) | 0;
                  hi = hi + Math.imul(ah6, bh5) | 0;
                  lo = lo + Math.imul(al5, bl6) | 0;
                  mid = mid + Math.imul(al5, bh6) | 0;
                  mid = mid + Math.imul(ah5, bl6) | 0;
                  hi = hi + Math.imul(ah5, bh6) | 0;
                  lo = lo + Math.imul(al4, bl7) | 0;
                  mid = mid + Math.imul(al4, bh7) | 0;
                  mid = mid + Math.imul(ah4, bl7) | 0;
                  hi = hi + Math.imul(ah4, bh7) | 0;
                  lo = lo + Math.imul(al3, bl8) | 0;
                  mid = mid + Math.imul(al3, bh8) | 0;
                  mid = mid + Math.imul(ah3, bl8) | 0;
                  hi = hi + Math.imul(ah3, bh8) | 0;
                  lo = lo + Math.imul(al2, bl9) | 0;
                  mid = mid + Math.imul(al2, bh9) | 0;
                  mid = mid + Math.imul(ah2, bl9) | 0;
                  hi = hi + Math.imul(ah2, bh9) | 0;
                  var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0;
                  w11 &= 67108863;
                  lo = Math.imul(al9, bl3);
                  mid = Math.imul(al9, bh3);
                  mid = mid + Math.imul(ah9, bl3) | 0;
                  hi = Math.imul(ah9, bh3);
                  lo = lo + Math.imul(al8, bl4) | 0;
                  mid = mid + Math.imul(al8, bh4) | 0;
                  mid = mid + Math.imul(ah8, bl4) | 0;
                  hi = hi + Math.imul(ah8, bh4) | 0;
                  lo = lo + Math.imul(al7, bl5) | 0;
                  mid = mid + Math.imul(al7, bh5) | 0;
                  mid = mid + Math.imul(ah7, bl5) | 0;
                  hi = hi + Math.imul(ah7, bh5) | 0;
                  lo = lo + Math.imul(al6, bl6) | 0;
                  mid = mid + Math.imul(al6, bh6) | 0;
                  mid = mid + Math.imul(ah6, bl6) | 0;
                  hi = hi + Math.imul(ah6, bh6) | 0;
                  lo = lo + Math.imul(al5, bl7) | 0;
                  mid = mid + Math.imul(al5, bh7) | 0;
                  mid = mid + Math.imul(ah5, bl7) | 0;
                  hi = hi + Math.imul(ah5, bh7) | 0;
                  lo = lo + Math.imul(al4, bl8) | 0;
                  mid = mid + Math.imul(al4, bh8) | 0;
                  mid = mid + Math.imul(ah4, bl8) | 0;
                  hi = hi + Math.imul(ah4, bh8) | 0;
                  lo = lo + Math.imul(al3, bl9) | 0;
                  mid = mid + Math.imul(al3, bh9) | 0;
                  mid = mid + Math.imul(ah3, bl9) | 0;
                  hi = hi + Math.imul(ah3, bh9) | 0;
                  var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0;
                  w12 &= 67108863;
                  lo = Math.imul(al9, bl4);
                  mid = Math.imul(al9, bh4);
                  mid = mid + Math.imul(ah9, bl4) | 0;
                  hi = Math.imul(ah9, bh4);
                  lo = lo + Math.imul(al8, bl5) | 0;
                  mid = mid + Math.imul(al8, bh5) | 0;
                  mid = mid + Math.imul(ah8, bl5) | 0;
                  hi = hi + Math.imul(ah8, bh5) | 0;
                  lo = lo + Math.imul(al7, bl6) | 0;
                  mid = mid + Math.imul(al7, bh6) | 0;
                  mid = mid + Math.imul(ah7, bl6) | 0;
                  hi = hi + Math.imul(ah7, bh6) | 0;
                  lo = lo + Math.imul(al6, bl7) | 0;
                  mid = mid + Math.imul(al6, bh7) | 0;
                  mid = mid + Math.imul(ah6, bl7) | 0;
                  hi = hi + Math.imul(ah6, bh7) | 0;
                  lo = lo + Math.imul(al5, bl8) | 0;
                  mid = mid + Math.imul(al5, bh8) | 0;
                  mid = mid + Math.imul(ah5, bl8) | 0;
                  hi = hi + Math.imul(ah5, bh8) | 0;
                  lo = lo + Math.imul(al4, bl9) | 0;
                  mid = mid + Math.imul(al4, bh9) | 0;
                  mid = mid + Math.imul(ah4, bl9) | 0;
                  hi = hi + Math.imul(ah4, bh9) | 0;
                  var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0;
                  w13 &= 67108863;
                  lo = Math.imul(al9, bl5);
                  mid = Math.imul(al9, bh5);
                  mid = mid + Math.imul(ah9, bl5) | 0;
                  hi = Math.imul(ah9, bh5);
                  lo = lo + Math.imul(al8, bl6) | 0;
                  mid = mid + Math.imul(al8, bh6) | 0;
                  mid = mid + Math.imul(ah8, bl6) | 0;
                  hi = hi + Math.imul(ah8, bh6) | 0;
                  lo = lo + Math.imul(al7, bl7) | 0;
                  mid = mid + Math.imul(al7, bh7) | 0;
                  mid = mid + Math.imul(ah7, bl7) | 0;
                  hi = hi + Math.imul(ah7, bh7) | 0;
                  lo = lo + Math.imul(al6, bl8) | 0;
                  mid = mid + Math.imul(al6, bh8) | 0;
                  mid = mid + Math.imul(ah6, bl8) | 0;
                  hi = hi + Math.imul(ah6, bh8) | 0;
                  lo = lo + Math.imul(al5, bl9) | 0;
                  mid = mid + Math.imul(al5, bh9) | 0;
                  mid = mid + Math.imul(ah5, bl9) | 0;
                  hi = hi + Math.imul(ah5, bh9) | 0;
                  var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0;
                  w14 &= 67108863;
                  lo = Math.imul(al9, bl6);
                  mid = Math.imul(al9, bh6);
                  mid = mid + Math.imul(ah9, bl6) | 0;
                  hi = Math.imul(ah9, bh6);
                  lo = lo + Math.imul(al8, bl7) | 0;
                  mid = mid + Math.imul(al8, bh7) | 0;
                  mid = mid + Math.imul(ah8, bl7) | 0;
                  hi = hi + Math.imul(ah8, bh7) | 0;
                  lo = lo + Math.imul(al7, bl8) | 0;
                  mid = mid + Math.imul(al7, bh8) | 0;
                  mid = mid + Math.imul(ah7, bl8) | 0;
                  hi = hi + Math.imul(ah7, bh8) | 0;
                  lo = lo + Math.imul(al6, bl9) | 0;
                  mid = mid + Math.imul(al6, bh9) | 0;
                  mid = mid + Math.imul(ah6, bl9) | 0;
                  hi = hi + Math.imul(ah6, bh9) | 0;
                  var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0;
                  w15 &= 67108863;
                  lo = Math.imul(al9, bl7);
                  mid = Math.imul(al9, bh7);
                  mid = mid + Math.imul(ah9, bl7) | 0;
                  hi = Math.imul(ah9, bh7);
                  lo = lo + Math.imul(al8, bl8) | 0;
                  mid = mid + Math.imul(al8, bh8) | 0;
                  mid = mid + Math.imul(ah8, bl8) | 0;
                  hi = hi + Math.imul(ah8, bh8) | 0;
                  lo = lo + Math.imul(al7, bl9) | 0;
                  mid = mid + Math.imul(al7, bh9) | 0;
                  mid = mid + Math.imul(ah7, bl9) | 0;
                  hi = hi + Math.imul(ah7, bh9) | 0;
                  var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0;
                  w16 &= 67108863;
                  lo = Math.imul(al9, bl8);
                  mid = Math.imul(al9, bh8);
                  mid = mid + Math.imul(ah9, bl8) | 0;
                  hi = Math.imul(ah9, bh8);
                  lo = lo + Math.imul(al8, bl9) | 0;
                  mid = mid + Math.imul(al8, bh9) | 0;
                  mid = mid + Math.imul(ah8, bl9) | 0;
                  hi = hi + Math.imul(ah8, bh9) | 0;
                  var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0;
                  w17 &= 67108863;
                  lo = Math.imul(al9, bl9);
                  mid = Math.imul(al9, bh9);
                  mid = mid + Math.imul(ah9, bl9) | 0;
                  hi = Math.imul(ah9, bh9);
                  var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0;
                  c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0;
                  w18 &= 67108863;
                  o[0] = w0;
                  o[1] = w1;
                  o[2] = w2;
                  o[3] = w3;
                  o[4] = w4;
                  o[5] = w5;
                  o[6] = w6;
                  o[7] = w7;
                  o[8] = w8;
                  o[9] = w9;
                  o[10] = w10;
                  o[11] = w11;
                  o[12] = w12;
                  o[13] = w13;
                  o[14] = w14;
                  o[15] = w15;
                  o[16] = w16;
                  o[17] = w17;
                  o[18] = w18;
                  if (c !== 0) {
                    o[19] = c;
                    out.length++;
                  }
                  return out;
                };
                if (!Math.imul) {
                  comb10MulTo = smallMulTo;
                }
                function bigMulTo(self2, num, out) {
                  out.negative = num.negative ^ self2.negative;
                  out.length = self2.length + num.length;
                  var carry = 0;
                  var hncarry = 0;
                  for (var k = 0; k < out.length - 1; k++) {
                    var ncarry = hncarry;
                    hncarry = 0;
                    var rword = carry & 67108863;
                    var maxJ = Math.min(k, num.length - 1);
                    for (var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++) {
                      var i = k - j;
                      var a = self2.words[i] | 0;
                      var b = num.words[j] | 0;
                      var r = a * b;
                      var lo = r & 67108863;
                      ncarry = ncarry + (r / 67108864 | 0) | 0;
                      lo = lo + rword | 0;
                      rword = lo & 67108863;
                      ncarry = ncarry + (lo >>> 26) | 0;
                      hncarry += ncarry >>> 26;
                      ncarry &= 67108863;
                    }
                    out.words[k] = rword;
                    carry = ncarry;
                    ncarry = hncarry;
                  }
                  if (carry !== 0) {
                    out.words[k] = carry;
                  } else {
                    out.length--;
                  }
                  return out.strip();
                }
                function jumboMulTo(self2, num, out) {
                  var fftm = new FFTM();
                  return fftm.mulp(self2, num, out);
                }
                BN.prototype.mulTo = function mulTo(num, out) {
                  var res;
                  var len = this.length + num.length;
                  if (this.length === 10 && num.length === 10) {
                    res = comb10MulTo(this, num, out);
                  } else if (len < 63) {
                    res = smallMulTo(this, num, out);
                  } else if (len < 1024) {
                    res = bigMulTo(this, num, out);
                  } else {
                    res = jumboMulTo(this, num, out);
                  }
                  return res;
                };
                function FFTM(x, y) {
                  this.x = x;
                  this.y = y;
                }
                FFTM.prototype.makeRBT = function makeRBT(N) {
                  var t = new Array(N);
                  var l = BN.prototype._countBits(N) - 1;
                  for (var i = 0; i < N; i++) {
                    t[i] = this.revBin(i, l, N);
                  }
                  return t;
                };
                FFTM.prototype.revBin = function revBin(x, l, N) {
                  if (x === 0 || x === N - 1) return x;
                  var rb = 0;
                  for (var i = 0; i < l; i++) {
                    rb |= (x & 1) << l - i - 1;
                    x >>= 1;
                  }
                  return rb;
                };
                FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) {
                  for (var i = 0; i < N; i++) {
                    rtws[i] = rws[rbt[i]];
                    itws[i] = iws[rbt[i]];
                  }
                };
                FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N, rbt) {
                  this.permute(rbt, rws, iws, rtws, itws, N);
                  for (var s = 1; s < N; s <<= 1) {
                    var l = s << 1;
                    var rtwdf = Math.cos(2 * Math.PI / l);
                    var itwdf = Math.sin(2 * Math.PI / l);
                    for (var p = 0; p < N; p += l) {
                      var rtwdf_ = rtwdf;
                      var itwdf_ = itwdf;
                      for (var j = 0; j < s; j++) {
                        var re = rtws[p + j];
                        var ie = itws[p + j];
                        var ro = rtws[p + j + s];
                        var io = itws[p + j + s];
                        var rx = rtwdf_ * ro - itwdf_ * io;
                        io = rtwdf_ * io + itwdf_ * ro;
                        ro = rx;
                        rtws[p + j] = re + ro;
                        itws[p + j] = ie + io;
                        rtws[p + j + s] = re - ro;
                        itws[p + j + s] = ie - io;
                        if (j !== l) {
                          rx = rtwdf * rtwdf_ - itwdf * itwdf_;
                          itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
                          rtwdf_ = rx;
                        }
                      }
                    }
                  }
                };
                FFTM.prototype.guessLen13b = function guessLen13b(n, m) {
                  var N = Math.max(m, n) | 1;
                  var odd = N & 1;
                  var i = 0;
                  for (N = N / 2 | 0; N; N = N >>> 1) {
                    i++;
                  }
                  return 1 << i + 1 + odd;
                };
                FFTM.prototype.conjugate = function conjugate(rws, iws, N) {
                  if (N <= 1) return;
                  for (var i = 0; i < N / 2; i++) {
                    var t = rws[i];
                    rws[i] = rws[N - i - 1];
                    rws[N - i - 1] = t;
                    t = iws[i];
                    iws[i] = -iws[N - i - 1];
                    iws[N - i - 1] = -t;
                  }
                };
                FFTM.prototype.normalize13b = function normalize13b(ws, N) {
                  var carry = 0;
                  for (var i = 0; i < N / 2; i++) {
                    var w = Math.round(ws[2 * i + 1] / N) * 8192 + Math.round(ws[2 * i] / N) + carry;
                    ws[i] = w & 67108863;
                    if (w < 67108864) {
                      carry = 0;
                    } else {
                      carry = w / 67108864 | 0;
                    }
                  }
                  return ws;
                };
                FFTM.prototype.convert13b = function convert13b(ws, len, rws, N) {
                  var carry = 0;
                  for (var i = 0; i < len; i++) {
                    carry = carry + (ws[i] | 0);
                    rws[2 * i] = carry & 8191;
                    carry = carry >>> 13;
                    rws[2 * i + 1] = carry & 8191;
                    carry = carry >>> 13;
                  }
                  for (i = 2 * len; i < N; ++i) {
                    rws[i] = 0;
                  }
                  assert(carry === 0);
                  assert((carry & ~8191) === 0);
                };
                FFTM.prototype.stub = function stub(N) {
                  var ph = new Array(N);
                  for (var i = 0; i < N; i++) {
                    ph[i] = 0;
                  }
                  return ph;
                };
                FFTM.prototype.mulp = function mulp(x, y, out) {
                  var N = 2 * this.guessLen13b(x.length, y.length);
                  var rbt = this.makeRBT(N);
                  var _ = this.stub(N);
                  var rws = new Array(N);
                  var rwst = new Array(N);
                  var iwst = new Array(N);
                  var nrws = new Array(N);
                  var nrwst = new Array(N);
                  var niwst = new Array(N);
                  var rmws = out.words;
                  rmws.length = N;
                  this.convert13b(x.words, x.length, rws, N);
                  this.convert13b(y.words, y.length, nrws, N);
                  this.transform(rws, _, rwst, iwst, N, rbt);
                  this.transform(nrws, _, nrwst, niwst, N, rbt);
                  for (var i = 0; i < N; i++) {
                    var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
                    iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
                    rwst[i] = rx;
                  }
                  this.conjugate(rwst, iwst, N);
                  this.transform(rwst, iwst, rmws, _, N, rbt);
                  this.conjugate(rmws, _, N);
                  this.normalize13b(rmws, N);
                  out.negative = x.negative ^ y.negative;
                  out.length = x.length + y.length;
                  return out.strip();
                };
                BN.prototype.mul = function mul(num) {
                  var out = new BN(null);
                  out.words = new Array(this.length + num.length);
                  return this.mulTo(num, out);
                };
                BN.prototype.mulf = function mulf(num) {
                  var out = new BN(null);
                  out.words = new Array(this.length + num.length);
                  return jumboMulTo(this, num, out);
                };
                BN.prototype.imul = function imul(num) {
                  return this.clone().mulTo(num, this);
                };
                BN.prototype.imuln = function imuln(num) {
                  assert(typeof num === "number");
                  assert(num < 67108864);
                  var carry = 0;
                  for (var i = 0; i < this.length; i++) {
                    var w = (this.words[i] | 0) * num;
                    var lo = (w & 67108863) + (carry & 67108863);
                    carry >>= 26;
                    carry += w / 67108864 | 0;
                    carry += lo >>> 26;
                    this.words[i] = lo & 67108863;
                  }
                  if (carry !== 0) {
                    this.words[i] = carry;
                    this.length++;
                  }
                  return this;
                };
                BN.prototype.muln = function muln(num) {
                  return this.clone().imuln(num);
                };
                BN.prototype.sqr = function sqr() {
                  return this.mul(this);
                };
                BN.prototype.isqr = function isqr() {
                  return this.imul(this.clone());
                };
                BN.prototype.pow = function pow(num) {
                  var w = toBitArray(num);
                  if (w.length === 0) return new BN(1);
                  var res = this;
                  for (var i = 0; i < w.length; i++, res = res.sqr()) {
                    if (w[i] !== 0) break;
                  }
                  if (++i < w.length) {
                    for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
                      if (w[i] === 0) continue;
                      res = res.mul(q);
                    }
                  }
                  return res;
                };
                BN.prototype.iushln = function iushln(bits) {
                  assert(typeof bits === "number" && bits >= 0);
                  var r = bits % 26;
                  var s = (bits - r) / 26;
                  var carryMask = 67108863 >>> 26 - r << 26 - r;
                  var i;
                  if (r !== 0) {
                    var carry = 0;
                    for (i = 0; i < this.length; i++) {
                      var newCarry = this.words[i] & carryMask;
                      var c = (this.words[i] | 0) - newCarry << r;
                      this.words[i] = c | carry;
                      carry = newCarry >>> 26 - r;
                    }
                    if (carry) {
                      this.words[i] = carry;
                      this.length++;
                    }
                  }
                  if (s !== 0) {
                    for (i = this.length - 1; i >= 0; i--) {
                      this.words[i + s] = this.words[i];
                    }
                    for (i = 0; i < s; i++) {
                      this.words[i] = 0;
                    }
                    this.length += s;
                  }
                  return this.strip();
                };
                BN.prototype.ishln = function ishln(bits) {
                  assert(this.negative === 0);
                  return this.iushln(bits);
                };
                BN.prototype.iushrn = function iushrn(bits, hint, extended) {
                  assert(typeof bits === "number" && bits >= 0);
                  var h;
                  if (hint) {
                    h = (hint - hint % 26) / 26;
                  } else {
                    h = 0;
                  }
                  var r = bits % 26;
                  var s = Math.min((bits - r) / 26, this.length);
                  var mask = 67108863 ^ 67108863 >>> r << r;
                  var maskedWords = extended;
                  h -= s;
                  h = Math.max(0, h);
                  if (maskedWords) {
                    for (var i = 0; i < s; i++) {
                      maskedWords.words[i] = this.words[i];
                    }
                    maskedWords.length = s;
                  }
                  if (s === 0) {
                  } else if (this.length > s) {
                    this.length -= s;
                    for (i = 0; i < this.length; i++) {
                      this.words[i] = this.words[i + s];
                    }
                  } else {
                    this.words[0] = 0;
                    this.length = 1;
                  }
                  var carry = 0;
                  for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
                    var word = this.words[i] | 0;
                    this.words[i] = carry << 26 - r | word >>> r;
                    carry = word & mask;
                  }
                  if (maskedWords && carry !== 0) {
                    maskedWords.words[maskedWords.length++] = carry;
                  }
                  if (this.length === 0) {
                    this.words[0] = 0;
                    this.length = 1;
                  }
                  return this.strip();
                };
                BN.prototype.ishrn = function ishrn(bits, hint, extended) {
                  assert(this.negative === 0);
                  return this.iushrn(bits, hint, extended);
                };
                BN.prototype.shln = function shln(bits) {
                  return this.clone().ishln(bits);
                };
                BN.prototype.ushln = function ushln(bits) {
                  return this.clone().iushln(bits);
                };
                BN.prototype.shrn = function shrn(bits) {
                  return this.clone().ishrn(bits);
                };
                BN.prototype.ushrn = function ushrn(bits) {
                  return this.clone().iushrn(bits);
                };
                BN.prototype.testn = function testn(bit) {
                  assert(typeof bit === "number" && bit >= 0);
                  var r = bit % 26;
                  var s = (bit - r) / 26;
                  var q = 1 << r;
                  if (this.length <= s) return false;
                  var w = this.words[s];
                  return !!(w & q);
                };
                BN.prototype.imaskn = function imaskn(bits) {
                  assert(typeof bits === "number" && bits >= 0);
                  var r = bits % 26;
                  var s = (bits - r) / 26;
                  assert(this.negative === 0, "imaskn works only with positive numbers");
                  if (this.length <= s) {
                    return this;
                  }
                  if (r !== 0) {
                    s++;
                  }
                  this.length = Math.min(s, this.length);
                  if (r !== 0) {
                    var mask = 67108863 ^ 67108863 >>> r << r;
                    this.words[this.length - 1] &= mask;
                  }
                  return this.strip();
                };
                BN.prototype.maskn = function maskn(bits) {
                  return this.clone().imaskn(bits);
                };
                BN.prototype.iaddn = function iaddn(num) {
                  assert(typeof num === "number");
                  assert(num < 67108864);
                  if (num < 0) return this.isubn(-num);
                  if (this.negative !== 0) {
                    if (this.length === 1 && (this.words[0] | 0) < num) {
                      this.words[0] = num - (this.words[0] | 0);
                      this.negative = 0;
                      return this;
                    }
                    this.negative = 0;
                    this.isubn(num);
                    this.negative = 1;
                    return this;
                  }
                  return this._iaddn(num);
                };
                BN.prototype._iaddn = function _iaddn(num) {
                  this.words[0] += num;
                  for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) {
                    this.words[i] -= 67108864;
                    if (i === this.length - 1) {
                      this.words[i + 1] = 1;
                    } else {
                      this.words[i + 1]++;
                    }
                  }
                  this.length = Math.max(this.length, i + 1);
                  return this;
                };
                BN.prototype.isubn = function isubn(num) {
                  assert(typeof num === "number");
                  assert(num < 67108864);
                  if (num < 0) return this.iaddn(-num);
                  if (this.negative !== 0) {
                    this.negative = 0;
                    this.iaddn(num);
                    this.negative = 1;
                    return this;
                  }
                  this.words[0] -= num;
                  if (this.length === 1 && this.words[0] < 0) {
                    this.words[0] = -this.words[0];
                    this.negative = 1;
                  } else {
                    for (var i = 0; i < this.length && this.words[i] < 0; i++) {
                      this.words[i] += 67108864;
                      this.words[i + 1] -= 1;
                    }
                  }
                  return this.strip();
                };
                BN.prototype.addn = function addn(num) {
                  return this.clone().iaddn(num);
                };
                BN.prototype.subn = function subn(num) {
                  return this.clone().isubn(num);
                };
                BN.prototype.iabs = function iabs() {
                  this.negative = 0;
                  return this;
                };
                BN.prototype.abs = function abs() {
                  return this.clone().iabs();
                };
                BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
                  var len = num.length + shift;
                  var i;
                  this._expand(len);
                  var w;
                  var carry = 0;
                  for (i = 0; i < num.length; i++) {
                    w = (this.words[i + shift] | 0) + carry;
                    var right = (num.words[i] | 0) * mul;
                    w -= right & 67108863;
                    carry = (w >> 26) - (right / 67108864 | 0);
                    this.words[i + shift] = w & 67108863;
                  }
                  for (; i < this.length - shift; i++) {
                    w = (this.words[i + shift] | 0) + carry;
                    carry = w >> 26;
                    this.words[i + shift] = w & 67108863;
                  }
                  if (carry === 0) return this.strip();
                  assert(carry === -1);
                  carry = 0;
                  for (i = 0; i < this.length; i++) {
                    w = -(this.words[i] | 0) + carry;
                    carry = w >> 26;
                    this.words[i] = w & 67108863;
                  }
                  this.negative = 1;
                  return this.strip();
                };
                BN.prototype._wordDiv = function _wordDiv(num, mode) {
                  var shift = this.length - num.length;
                  var a = this.clone();
                  var b = num;
                  var bhi = b.words[b.length - 1] | 0;
                  var bhiBits = this._countBits(bhi);
                  shift = 26 - bhiBits;
                  if (shift !== 0) {
                    b = b.ushln(shift);
                    a.iushln(shift);
                    bhi = b.words[b.length - 1] | 0;
                  }
                  var m = a.length - b.length;
                  var q;
                  if (mode !== "mod") {
                    q = new BN(null);
                    q.length = m + 1;
                    q.words = new Array(q.length);
                    for (var i = 0; i < q.length; i++) {
                      q.words[i] = 0;
                    }
                  }
                  var diff = a.clone()._ishlnsubmul(b, 1, m);
                  if (diff.negative === 0) {
                    a = diff;
                    if (q) {
                      q.words[m] = 1;
                    }
                  }
                  for (var j = m - 1; j >= 0; j--) {
                    var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0);
                    qj = Math.min(qj / bhi | 0, 67108863);
                    a._ishlnsubmul(b, qj, j);
                    while (a.negative !== 0) {
                      qj--;
                      a.negative = 0;
                      a._ishlnsubmul(b, 1, j);
                      if (!a.isZero()) {
                        a.negative ^= 1;
                      }
                    }
                    if (q) {
                      q.words[j] = qj;
                    }
                  }
                  if (q) {
                    q.strip();
                  }
                  a.strip();
                  if (mode !== "div" && shift !== 0) {
                    a.iushrn(shift);
                  }
                  return {
                    div: q || null,
                    mod: a
                  };
                };
                BN.prototype.divmod = function divmod(num, mode, positive) {
                  assert(!num.isZero());
                  if (this.isZero()) {
                    return {
                      div: new BN(0),
                      mod: new BN(0)
                    };
                  }
                  var div, mod, res;
                  if (this.negative !== 0 && num.negative === 0) {
                    res = this.neg().divmod(num, mode);
                    if (mode !== "mod") {
                      div = res.div.neg();
                    }
                    if (mode !== "div") {
                      mod = res.mod.neg();
                      if (positive && mod.negative !== 0) {
                        mod.iadd(num);
                      }
                    }
                    return {
                      div,
                      mod
                    };
                  }
                  if (this.negative === 0 && num.negative !== 0) {
                    res = this.divmod(num.neg(), mode);
                    if (mode !== "mod") {
                      div = res.div.neg();
                    }
                    return {
                      div,
                      mod: res.mod
                    };
                  }
                  if ((this.negative & num.negative) !== 0) {
                    res = this.neg().divmod(num.neg(), mode);
                    if (mode !== "div") {
                      mod = res.mod.neg();
                      if (positive && mod.negative !== 0) {
                        mod.isub(num);
                      }
                    }
                    return {
                      div: res.div,
                      mod
                    };
                  }
                  if (num.length > this.length || this.cmp(num) < 0) {
                    return {
                      div: new BN(0),
                      mod: this
                    };
                  }
                  if (num.length === 1) {
                    if (mode === "div") {
                      return {
                        div: this.divn(num.words[0]),
                        mod: null
                      };
                    }
                    if (mode === "mod") {
                      return {
                        div: null,
                        mod: new BN(this.modn(num.words[0]))
                      };
                    }
                    return {
                      div: this.divn(num.words[0]),
                      mod: new BN(this.modn(num.words[0]))
                    };
                  }
                  return this._wordDiv(num, mode);
                };
                BN.prototype.div = function div(num) {
                  return this.divmod(num, "div", false).div;
                };
                BN.prototype.mod = function mod(num) {
                  return this.divmod(num, "mod", false).mod;
                };
                BN.prototype.umod = function umod(num) {
                  return this.divmod(num, "mod", true).mod;
                };
                BN.prototype.divRound = function divRound(num) {
                  var dm = this.divmod(num);
                  if (dm.mod.isZero()) return dm.div;
                  var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
                  var half = num.ushrn(1);
                  var r2 = num.andln(1);
                  var cmp = mod.cmp(half);
                  if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
                  return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
                };
                BN.prototype.modn = function modn(num) {
                  assert(num <= 67108863);
                  var p = (1 << 26) % num;
                  var acc = 0;
                  for (var i = this.length - 1; i >= 0; i--) {
                    acc = (p * acc + (this.words[i] | 0)) % num;
                  }
                  return acc;
                };
                BN.prototype.idivn = function idivn(num) {
                  assert(num <= 67108863);
                  var carry = 0;
                  for (var i = this.length - 1; i >= 0; i--) {
                    var w = (this.words[i] | 0) + carry * 67108864;
                    this.words[i] = w / num | 0;
                    carry = w % num;
                  }
                  return this.strip();
                };
                BN.prototype.divn = function divn(num) {
                  return this.clone().idivn(num);
                };
                BN.prototype.egcd = function egcd(p) {
                  assert(p.negative === 0);
                  assert(!p.isZero());
                  var x = this;
                  var y = p.clone();
                  if (x.negative !== 0) {
                    x = x.umod(p);
                  } else {
                    x = x.clone();
                  }
                  var A2 = new BN(1);
                  var B2 = new BN(0);
                  var C2 = new BN(0);
                  var D2 = new BN(1);
                  var g = 0;
                  while (x.isEven() && y.isEven()) {
                    x.iushrn(1);
                    y.iushrn(1);
                    ++g;
                  }
                  var yp = y.clone();
                  var xp = x.clone();
                  while (!x.isZero()) {
                    for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ;
                    if (i > 0) {
                      x.iushrn(i);
                      while (i-- > 0) {
                        if (A2.isOdd() || B2.isOdd()) {
                          A2.iadd(yp);
                          B2.isub(xp);
                        }
                        A2.iushrn(1);
                        B2.iushrn(1);
                      }
                    }
                    for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ;
                    if (j > 0) {
                      y.iushrn(j);
                      while (j-- > 0) {
                        if (C2.isOdd() || D2.isOdd()) {
                          C2.iadd(yp);
                          D2.isub(xp);
                        }
                        C2.iushrn(1);
                        D2.iushrn(1);
                      }
                    }
                    if (x.cmp(y) >= 0) {
                      x.isub(y);
                      A2.isub(C2);
                      B2.isub(D2);
                    } else {
                      y.isub(x);
                      C2.isub(A2);
                      D2.isub(B2);
                    }
                  }
                  return {
                    a: C2,
                    b: D2,
                    gcd: y.iushln(g)
                  };
                };
                BN.prototype._invmp = function _invmp(p) {
                  assert(p.negative === 0);
                  assert(!p.isZero());
                  var a = this;
                  var b = p.clone();
                  if (a.negative !== 0) {
                    a = a.umod(p);
                  } else {
                    a = a.clone();
                  }
                  var x1 = new BN(1);
                  var x2 = new BN(0);
                  var delta = b.clone();
                  while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
                    for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1) ;
                    if (i > 0) {
                      a.iushrn(i);
                      while (i-- > 0) {
                        if (x1.isOdd()) {
                          x1.iadd(delta);
                        }
                        x1.iushrn(1);
                      }
                    }
                    for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ;
                    if (j > 0) {
                      b.iushrn(j);
                      while (j-- > 0) {
                        if (x2.isOdd()) {
                          x2.iadd(delta);
                        }
                        x2.iushrn(1);
                      }
                    }
                    if (a.cmp(b) >= 0) {
                      a.isub(b);
                      x1.isub(x2);
                    } else {
                      b.isub(a);
                      x2.isub(x1);
                    }
                  }
                  var res;
                  if (a.cmpn(1) === 0) {
                    res = x1;
                  } else {
                    res = x2;
                  }
                  if (res.cmpn(0) < 0) {
                    res.iadd(p);
                  }
                  return res;
                };
                BN.prototype.gcd = function gcd(num) {
                  if (this.isZero()) return num.abs();
                  if (num.isZero()) return this.abs();
                  var a = this.clone();
                  var b = num.clone();
                  a.negative = 0;
                  b.negative = 0;
                  for (var shift = 0; a.isEven() && b.isEven(); shift++) {
                    a.iushrn(1);
                    b.iushrn(1);
                  }
                  do {
                    while (a.isEven()) {
                      a.iushrn(1);
                    }
                    while (b.isEven()) {
                      b.iushrn(1);
                    }
                    var r = a.cmp(b);
                    if (r < 0) {
                      var t = a;
                      a = b;
                      b = t;
                    } else if (r === 0 || b.cmpn(1) === 0) {
                      break;
                    }
                    a.isub(b);
                  } while (true);
                  return b.iushln(shift);
                };
                BN.prototype.invm = function invm(num) {
                  return this.egcd(num).a.umod(num);
                };
                BN.prototype.isEven = function isEven() {
                  return (this.words[0] & 1) === 0;
                };
                BN.prototype.isOdd = function isOdd() {
                  return (this.words[0] & 1) === 1;
                };
                BN.prototype.andln = function andln(num) {
                  return this.words[0] & num;
                };
                BN.prototype.bincn = function bincn(bit) {
                  assert(typeof bit === "number");
                  var r = bit % 26;
                  var s = (bit - r) / 26;
                  var q = 1 << r;
                  if (this.length <= s) {
                    this._expand(s + 1);
                    this.words[s] |= q;
                    return this;
                  }
                  var carry = q;
                  for (var i = s; carry !== 0 && i < this.length; i++) {
                    var w = this.words[i] | 0;
                    w += carry;
                    carry = w >>> 26;
                    w &= 67108863;
                    this.words[i] = w;
                  }
                  if (carry !== 0) {
                    this.words[i] = carry;
                    this.length++;
                  }
                  return this;
                };
                BN.prototype.isZero = function isZero() {
                  return this.length === 1 && this.words[0] === 0;
                };
                BN.prototype.cmpn = function cmpn(num) {
                  var negative = num < 0;
                  if (this.negative !== 0 && !negative) return -1;
                  if (this.negative === 0 && negative) return 1;
                  this.strip();
                  var res;
                  if (this.length > 1) {
                    res = 1;
                  } else {
                    if (negative) {
                      num = -num;
                    }
                    assert(num <= 67108863, "Number is too big");
                    var w = this.words[0] | 0;
                    res = w === num ? 0 : w < num ? -1 : 1;
                  }
                  if (this.negative !== 0) return -res | 0;
                  return res;
                };
                BN.prototype.cmp = function cmp(num) {
                  if (this.negative !== 0 && num.negative === 0) return -1;
                  if (this.negative === 0 && num.negative !== 0) return 1;
                  var res = this.ucmp(num);
                  if (this.negative !== 0) return -res | 0;
                  return res;
                };
                BN.prototype.ucmp = function ucmp(num) {
                  if (this.length > num.length) return 1;
                  if (this.length < num.length) return -1;
                  var res = 0;
                  for (var i = this.length - 1; i >= 0; i--) {
                    var a = this.words[i] | 0;
                    var b = num.words[i] | 0;
                    if (a === b) continue;
                    if (a < b) {
                      res = -1;
                    } else if (a > b) {
                      res = 1;
                    }
                    break;
                  }
                  return res;
                };
                BN.prototype.gtn = function gtn(num) {
                  return this.cmpn(num) === 1;
                };
                BN.prototype.gt = function gt(num) {
                  return this.cmp(num) === 1;
                };
                BN.prototype.gten = function gten(num) {
                  return this.cmpn(num) >= 0;
                };
                BN.prototype.gte = function gte(num) {
                  return this.cmp(num) >= 0;
                };
                BN.prototype.ltn = function ltn(num) {
                  return this.cmpn(num) === -1;
                };
                BN.prototype.lt = function lt(num) {
                  return this.cmp(num) === -1;
                };
                BN.prototype.lten = function lten(num) {
                  return this.cmpn(num) <= 0;
                };
                BN.prototype.lte = function lte(num) {
                  return this.cmp(num) <= 0;
                };
                BN.prototype.eqn = function eqn(num) {
                  return this.cmpn(num) === 0;
                };
                BN.prototype.eq = function eq(num) {
                  return this.cmp(num) === 0;
                };
                BN.red = function red(num) {
                  return new Red(num);
                };
                BN.prototype.toRed = function toRed(ctx) {
                  assert(!this.red, "Already a number in reduction context");
                  assert(this.negative === 0, "red works only with positives");
                  return ctx.convertTo(this)._forceRed(ctx);
                };
                BN.prototype.fromRed = function fromRed() {
                  assert(this.red, "fromRed works only with numbers in reduction context");
                  return this.red.convertFrom(this);
                };
                BN.prototype._forceRed = function _forceRed(ctx) {
                  this.red = ctx;
                  return this;
                };
                BN.prototype.forceRed = function forceRed(ctx) {
                  assert(!this.red, "Already a number in reduction context");
                  return this._forceRed(ctx);
                };
                BN.prototype.redAdd = function redAdd(num) {
                  assert(this.red, "redAdd works only with red numbers");
                  return this.red.add(this, num);
                };
                BN.prototype.redIAdd = function redIAdd(num) {
                  assert(this.red, "redIAdd works only with red numbers");
                  return this.red.iadd(this, num);
                };
                BN.prototype.redSub = function redSub(num) {
                  assert(this.red, "redSub works only with red numbers");
                  return this.red.sub(this, num);
                };
                BN.prototype.redISub = function redISub(num) {
                  assert(this.red, "redISub works only with red numbers");
                  return this.red.isub(this, num);
                };
                BN.prototype.redShl = function redShl(num) {
                  assert(this.red, "redShl works only with red numbers");
                  return this.red.shl(this, num);
                };
                BN.prototype.redMul = function redMul(num) {
                  assert(this.red, "redMul works only with red numbers");
                  this.red._verify2(this, num);
                  return this.red.mul(this, num);
                };
                BN.prototype.redIMul = function redIMul(num) {
                  assert(this.red, "redMul works only with red numbers");
                  this.red._verify2(this, num);
                  return this.red.imul(this, num);
                };
                BN.prototype.redSqr = function redSqr() {
                  assert(this.red, "redSqr works only with red numbers");
                  this.red._verify1(this);
                  return this.red.sqr(this);
                };
                BN.prototype.redISqr = function redISqr() {
                  assert(this.red, "redISqr works only with red numbers");
                  this.red._verify1(this);
                  return this.red.isqr(this);
                };
                BN.prototype.redSqrt = function redSqrt() {
                  assert(this.red, "redSqrt works only with red numbers");
                  this.red._verify1(this);
                  return this.red.sqrt(this);
                };
                BN.prototype.redInvm = function redInvm() {
                  assert(this.red, "redInvm works only with red numbers");
                  this.red._verify1(this);
                  return this.red.invm(this);
                };
                BN.prototype.redNeg = function redNeg() {
                  assert(this.red, "redNeg works only with red numbers");
                  this.red._verify1(this);
                  return this.red.neg(this);
                };
                BN.prototype.redPow = function redPow(num) {
                  assert(this.red && !num.red, "redPow(normalNum)");
                  this.red._verify1(this);
                  return this.red.pow(this, num);
                };
                var primes = {
                  k256: null,
                  p224: null,
                  p192: null,
                  p25519: null
                };
                function MPrime(name2, p) {
                  this.name = name2;
                  this.p = new BN(p, 16);
                  this.n = this.p.bitLength();
                  this.k = new BN(1).iushln(this.n).isub(this.p);
                  this.tmp = this._tmp();
                }
                MPrime.prototype._tmp = function _tmp() {
                  var tmp = new BN(null);
                  tmp.words = new Array(Math.ceil(this.n / 13));
                  return tmp;
                };
                MPrime.prototype.ireduce = function ireduce(num) {
                  var r = num;
                  var rlen;
                  do {
                    this.split(r, this.tmp);
                    r = this.imulK(r);
                    r = r.iadd(this.tmp);
                    rlen = r.bitLength();
                  } while (rlen > this.n);
                  var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
                  if (cmp === 0) {
                    r.words[0] = 0;
                    r.length = 1;
                  } else if (cmp > 0) {
                    r.isub(this.p);
                  } else {
                    if (r.strip !== void 0) {
                      r.strip();
                    } else {
                      r._strip();
                    }
                  }
                  return r;
                };
                MPrime.prototype.split = function split(input, out) {
                  input.iushrn(this.n, 0, out);
                };
                MPrime.prototype.imulK = function imulK(num) {
                  return num.imul(this.k);
                };
                function K256() {
                  MPrime.call(
                    this,
                    "k256",
                    "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"
                  );
                }
                inherits(K256, MPrime);
                K256.prototype.split = function split(input, output) {
                  var mask = 4194303;
                  var outLen = Math.min(input.length, 9);
                  for (var i = 0; i < outLen; i++) {
                    output.words[i] = input.words[i];
                  }
                  output.length = outLen;
                  if (input.length <= 9) {
                    input.words[0] = 0;
                    input.length = 1;
                    return;
                  }
                  var prev = input.words[9];
                  output.words[output.length++] = prev & mask;
                  for (i = 10; i < input.length; i++) {
                    var next = input.words[i] | 0;
                    input.words[i - 10] = (next & mask) << 4 | prev >>> 22;
                    prev = next;
                  }
                  prev >>>= 22;
                  input.words[i - 10] = prev;
                  if (prev === 0 && input.length > 10) {
                    input.length -= 10;
                  } else {
                    input.length -= 9;
                  }
                };
                K256.prototype.imulK = function imulK(num) {
                  num.words[num.length] = 0;
                  num.words[num.length + 1] = 0;
                  num.length += 2;
                  var lo = 0;
                  for (var i = 0; i < num.length; i++) {
                    var w = num.words[i] | 0;
                    lo += w * 977;
                    num.words[i] = lo & 67108863;
                    lo = w * 64 + (lo / 67108864 | 0);
                  }
                  if (num.words[num.length - 1] === 0) {
                    num.length--;
                    if (num.words[num.length - 1] === 0) {
                      num.length--;
                    }
                  }
                  return num;
                };
                function P224() {
                  MPrime.call(
                    this,
                    "p224",
                    "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"
                  );
                }
                inherits(P224, MPrime);
                function P192() {
                  MPrime.call(
                    this,
                    "p192",
                    "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"
                  );
                }
                inherits(P192, MPrime);
                function P25519() {
                  MPrime.call(
                    this,
                    "25519",
                    "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"
                  );
                }
                inherits(P25519, MPrime);
                P25519.prototype.imulK = function imulK(num) {
                  var carry = 0;
                  for (var i = 0; i < num.length; i++) {
                    var hi = (num.words[i] | 0) * 19 + carry;
                    var lo = hi & 67108863;
                    hi >>>= 26;
                    num.words[i] = lo;
                    carry = hi;
                  }
                  if (carry !== 0) {
                    num.words[num.length++] = carry;
                  }
                  return num;
                };
                BN._prime = function prime(name2) {
                  if (primes[name2]) return primes[name2];
                  var prime2;
                  if (name2 === "k256") {
                    prime2 = new K256();
                  } else if (name2 === "p224") {
                    prime2 = new P224();
                  } else if (name2 === "p192") {
                    prime2 = new P192();
                  } else if (name2 === "p25519") {
                    prime2 = new P25519();
                  } else {
                    throw new Error("Unknown prime " + name2);
                  }
                  primes[name2] = prime2;
                  return prime2;
                };
                function Red(m) {
                  if (typeof m === "string") {
                    var prime = BN._prime(m);
                    this.m = prime.p;
                    this.prime = prime;
                  } else {
                    assert(m.gtn(1), "modulus must be greater than 1");
                    this.m = m;
                    this.prime = null;
                  }
                }
                Red.prototype._verify1 = function _verify1(a) {
                  assert(a.negative === 0, "red works only with positives");
                  assert(a.red, "red works only with red numbers");
                };
                Red.prototype._verify2 = function _verify2(a, b) {
                  assert((a.negative | b.negative) === 0, "red works only with positives");
                  assert(
                    a.red && a.red === b.red,
                    "red works only with red numbers"
                  );
                };
                Red.prototype.imod = function imod(a) {
                  if (this.prime) return this.prime.ireduce(a)._forceRed(this);
                  return a.umod(this.m)._forceRed(this);
                };
                Red.prototype.neg = function neg(a) {
                  if (a.isZero()) {
                    return a.clone();
                  }
                  return this.m.sub(a)._forceRed(this);
                };
                Red.prototype.add = function add(a, b) {
                  this._verify2(a, b);
                  var res = a.add(b);
                  if (res.cmp(this.m) >= 0) {
                    res.isub(this.m);
                  }
                  return res._forceRed(this);
                };
                Red.prototype.iadd = function iadd(a, b) {
                  this._verify2(a, b);
                  var res = a.iadd(b);
                  if (res.cmp(this.m) >= 0) {
                    res.isub(this.m);
                  }
                  return res;
                };
                Red.prototype.sub = function sub(a, b) {
                  this._verify2(a, b);
                  var res = a.sub(b);
                  if (res.cmpn(0) < 0) {
                    res.iadd(this.m);
                  }
                  return res._forceRed(this);
                };
                Red.prototype.isub = function isub(a, b) {
                  this._verify2(a, b);
                  var res = a.isub(b);
                  if (res.cmpn(0) < 0) {
                    res.iadd(this.m);
                  }
                  return res;
                };
                Red.prototype.shl = function shl(a, num) {
                  this._verify1(a);
                  return this.imod(a.ushln(num));
                };
                Red.prototype.imul = function imul(a, b) {
                  this._verify2(a, b);
                  return this.imod(a.imul(b));
                };
                Red.prototype.mul = function mul(a, b) {
                  this._verify2(a, b);
                  return this.imod(a.mul(b));
                };
                Red.prototype.isqr = function isqr(a) {
                  return this.imul(a, a.clone());
                };
                Red.prototype.sqr = function sqr(a) {
                  return this.mul(a, a);
                };
                Red.prototype.sqrt = function sqrt(a) {
                  if (a.isZero()) return a.clone();
                  var mod3 = this.m.andln(3);
                  assert(mod3 % 2 === 1);
                  if (mod3 === 3) {
                    var pow = this.m.add(new BN(1)).iushrn(2);
                    return this.pow(a, pow);
                  }
                  var q = this.m.subn(1);
                  var s = 0;
                  while (!q.isZero() && q.andln(1) === 0) {
                    s++;
                    q.iushrn(1);
                  }
                  assert(!q.isZero());
                  var one2 = new BN(1).toRed(this);
                  var nOne = one2.redNeg();
                  var lpow = this.m.subn(1).iushrn(1);
                  var z = this.m.bitLength();
                  z = new BN(2 * z * z).toRed(this);
                  while (this.pow(z, lpow).cmp(nOne) !== 0) {
                    z.redIAdd(nOne);
                  }
                  var c = this.pow(z, q);
                  var r = this.pow(a, q.addn(1).iushrn(1));
                  var t = this.pow(a, q);
                  var m = s;
                  while (t.cmp(one2) !== 0) {
                    var tmp = t;
                    for (var i = 0; tmp.cmp(one2) !== 0; i++) {
                      tmp = tmp.redSqr();
                    }
                    assert(i < m);
                    var b = this.pow(c, new BN(1).iushln(m - i - 1));
                    r = r.redMul(b);
                    c = b.redSqr();
                    t = t.redMul(c);
                    m = i;
                  }
                  return r;
                };
                Red.prototype.invm = function invm(a) {
                  var inv = a._invmp(this.m);
                  if (inv.negative !== 0) {
                    inv.negative = 0;
                    return this.imod(inv).redNeg();
                  } else {
                    return this.imod(inv);
                  }
                };
                Red.prototype.pow = function pow(a, num) {
                  if (num.isZero()) return new BN(1).toRed(this);
                  if (num.cmpn(1) === 0) return a.clone();
                  var windowSize = 4;
                  var wnd = new Array(1 << windowSize);
                  wnd[0] = new BN(1).toRed(this);
                  wnd[1] = a;
                  for (var i = 2; i < wnd.length; i++) {
                    wnd[i] = this.mul(wnd[i - 1], a);
                  }
                  var res = wnd[0];
                  var current = 0;
                  var currentLen = 0;
                  var start = num.bitLength() % 26;
                  if (start === 0) {
                    start = 26;
                  }
                  for (i = num.length - 1; i >= 0; i--) {
                    var word = num.words[i];
                    for (var j = start - 1; j >= 0; j--) {
                      var bit = word >> j & 1;
                      if (res !== wnd[0]) {
                        res = this.sqr(res);
                      }
                      if (bit === 0 && current === 0) {
                        currentLen = 0;
                        continue;
                      }
                      current <<= 1;
                      current |= bit;
                      currentLen++;
                      if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
                      res = this.mul(res, wnd[current]);
                      currentLen = 0;
                      current = 0;
                    }
                    start = 26;
                  }
                  return res;
                };
                Red.prototype.convertTo = function convertTo(num) {
                  var r = num.umod(this.m);
                  return r === num ? r.clone() : r;
                };
                Red.prototype.convertFrom = function convertFrom(num) {
                  var res = num.clone();
                  res.red = null;
                  return res;
                };
                BN.mont = function mont(num) {
                  return new Mont(num);
                };
                function Mont(m) {
                  Red.call(this, m);
                  this.shift = this.m.bitLength();
                  if (this.shift % 26 !== 0) {
                    this.shift += 26 - this.shift % 26;
                  }
                  this.r = new BN(1).iushln(this.shift);
                  this.r2 = this.imod(this.r.sqr());
                  this.rinv = this.r._invmp(this.m);
                  this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
                  this.minv = this.minv.umod(this.r);
                  this.minv = this.r.sub(this.minv);
                }
                inherits(Mont, Red);
                Mont.prototype.convertTo = function convertTo(num) {
                  return this.imod(num.ushln(this.shift));
                };
                Mont.prototype.convertFrom = function convertFrom(num) {
                  var r = this.imod(num.mul(this.rinv));
                  r.red = null;
                  return r;
                };
                Mont.prototype.imul = function imul(a, b) {
                  if (a.isZero() || b.isZero()) {
                    a.words[0] = 0;
                    a.length = 1;
                    return a;
                  }
                  var t = a.imul(b);
                  var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
                  var u = t.isub(c).iushrn(this.shift);
                  var res = u;
                  if (u.cmp(this.m) >= 0) {
                    res = u.isub(this.m);
                  } else if (u.cmpn(0) < 0) {
                    res = u.iadd(this.m);
                  }
                  return res._forceRed(this);
                };
                Mont.prototype.mul = function mul(a, b) {
                  if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
                  var t = a.mul(b);
                  var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
                  var u = t.isub(c).iushrn(this.shift);
                  var res = u;
                  if (u.cmp(this.m) >= 0) {
                    res = u.isub(this.m);
                  } else if (u.cmpn(0) < 0) {
                    res = u.iadd(this.m);
                  }
                  return res._forceRed(this);
                };
                Mont.prototype.invm = function invm(a) {
                  var res = this.imod(a._invmp(this.m).mul(this.r2));
                  return res._forceRed(this);
                };
              })(module2, this);
            }
          ),
          /***/
          6860: (
            /***/
            function(module2) {
              module2.exports = subtract;
              function subtract(out, a, b) {
                out[0] = a[0] - b[0];
                out[1] = a[1] - b[1];
                out[2] = a[2] - b[2];
                out[3] = a[3] - b[3];
                return out;
              }
            }
          ),
          /***/
          6864: (
            /***/
            function(module2) {
              module2.exports = create;
              function create() {
                var out = new Float32Array(16);
                out[0] = 1;
                out[1] = 0;
                out[2] = 0;
                out[3] = 0;
                out[4] = 0;
                out[5] = 1;
                out[6] = 0;
                out[7] = 0;
                out[8] = 0;
                out[9] = 0;
                out[10] = 1;
                out[11] = 0;
                out[12] = 0;
                out[13] = 0;
                out[14] = 0;
                out[15] = 1;
                return out;
              }
              ;
            }
          ),
          /***/
          6867: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = boxIntersectWrapper;
              var pool = __webpack_require__2(1888);
              var sweep = __webpack_require__2(855);
              var boxIntersectIter = __webpack_require__2(7150);
              function boxEmpty(d, box) {
                for (var j = 0; j < d; ++j) {
                  if (!(box[j] <= box[j + d])) {
                    return true;
                  }
                }
                return false;
              }
              function convertBoxes(boxes, d, data, ids) {
                var ptr = 0;
                var count = 0;
                for (var i = 0, n = boxes.length; i < n; ++i) {
                  var b = boxes[i];
                  if (boxEmpty(d, b)) {
                    continue;
                  }
                  for (var j = 0; j < 2 * d; ++j) {
                    data[ptr++] = b[j];
                  }
                  ids[count++] = i;
                }
                return count;
              }
              function boxIntersect(red, blue, visit, full) {
                var n = red.length;
                var m = blue.length;
                if (n <= 0 || m <= 0) {
                  return;
                }
                var d = red[0].length >>> 1;
                if (d <= 0) {
                  return;
                }
                var retval;
                var redList = pool.mallocDouble(2 * d * n);
                var redIds = pool.mallocInt32(n);
                n = convertBoxes(red, d, redList, redIds);
                if (n > 0) {
                  if (d === 1 && full) {
                    sweep.init(n);
                    retval = sweep.sweepComplete(
                      d,
                      visit,
                      0,
                      n,
                      redList,
                      redIds,
                      0,
                      n,
                      redList,
                      redIds
                    );
                  } else {
                    var blueList = pool.mallocDouble(2 * d * m);
                    var blueIds = pool.mallocInt32(m);
                    m = convertBoxes(blue, d, blueList, blueIds);
                    if (m > 0) {
                      sweep.init(n + m);
                      if (d === 1) {
                        retval = sweep.sweepBipartite(
                          d,
                          visit,
                          0,
                          n,
                          redList,
                          redIds,
                          0,
                          m,
                          blueList,
                          blueIds
                        );
                      } else {
                        retval = boxIntersectIter(
                          d,
                          visit,
                          full,
                          n,
                          redList,
                          redIds,
                          m,
                          blueList,
                          blueIds
                        );
                      }
                      pool.free(blueList);
                      pool.free(blueIds);
                    }
                  }
                  pool.free(redList);
                  pool.free(redIds);
                }
                return retval;
              }
              var RESULT;
              function appendItem(i, j) {
                RESULT.push([i, j]);
              }
              function intersectFullArray(x) {
                RESULT = [];
                boxIntersect(x, x, appendItem, true);
                return RESULT;
              }
              function intersectBipartiteArray(x, y) {
                RESULT = [];
                boxIntersect(x, y, appendItem, false);
                return RESULT;
              }
              function boxIntersectWrapper(arg0, arg1, arg2) {
                switch (arguments.length) {
                  case 1:
                    return intersectFullArray(arg0);
                  case 2:
                    if (typeof arg1 === "function") {
                      return boxIntersect(arg0, arg0, arg1, true);
                    } else {
                      return intersectBipartiteArray(arg0, arg1);
                    }
                  case 3:
                    return boxIntersect(arg0, arg1, arg2, false);
                  default:
                    throw new Error("box-intersect: Invalid arguments");
                }
              }
            }
          ),
          /***/
          6894: (
            /***/
            function(module2) {
              module2.exports = rotateX;
              function rotateX(out, a, b, c) {
                var by = b[1];
                var bz = b[2];
                var py = a[1] - by;
                var pz = a[2] - bz;
                var sc = Math.sin(c);
                var cc = Math.cos(c);
                out[0] = a[0];
                out[1] = by + py * cc - pz * sc;
                out[2] = bz + py * sc + pz * cc;
                return out;
              }
            }
          ),
          /***/
          7004: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = compressExpansion;
              function compressExpansion(e) {
                var m = e.length;
                var Q = e[e.length - 1];
                var bottom = m;
                for (var i = m - 2; i >= 0; --i) {
                  var a = Q;
                  var b = e[i];
                  Q = a + b;
                  var bv = Q - a;
                  var q = b - bv;
                  if (q) {
                    e[--bottom] = Q;
                    Q = q;
                  }
                }
                var top = 0;
                for (var i = bottom; i < m; ++i) {
                  var a = e[i];
                  var b = Q;
                  Q = a + b;
                  var bv = Q - a;
                  var q = b - bv;
                  if (q) {
                    e[top++] = q;
                  }
                }
                e[top++] = Q;
                e.length = top;
                return e;
              }
            }
          ),
          /***/
          7056: (
            /***/
            function(module2) {
              module2.exports = distance;
              function distance(a, b) {
                var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2];
                return Math.sqrt(x * x + y * y + z * z);
              }
            }
          ),
          /***/
          7089: (
            /***/
            function(module2) {
              module2.exports = rotateZ;
              function rotateZ(out, a, rad) {
                var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
                if (a !== out) {
                  out[8] = a[8];
                  out[9] = a[9];
                  out[10] = a[10];
                  out[11] = a[11];
                  out[12] = a[12];
                  out[13] = a[13];
                  out[14] = a[14];
                  out[15] = a[15];
                }
                out[0] = a00 * c + a10 * s;
                out[1] = a01 * c + a11 * s;
                out[2] = a02 * c + a12 * s;
                out[3] = a03 * c + a13 * s;
                out[4] = a10 * c - a00 * s;
                out[5] = a11 * c - a01 * s;
                out[6] = a12 * c - a02 * s;
                out[7] = a13 * c - a03 * s;
                return out;
              }
              ;
            }
          ),
          /***/
          7150: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = boxIntersectIter;
              var pool = __webpack_require__2(1888);
              var bits = __webpack_require__2(8828);
              var bruteForce = __webpack_require__2(2455);
              var bruteForcePartial = bruteForce.partial;
              var bruteForceFull = bruteForce.full;
              var sweep = __webpack_require__2(855);
              var findMedian = __webpack_require__2(3545);
              var genPartition = __webpack_require__2(8105);
              var BRUTE_FORCE_CUTOFF = 128;
              var SCAN_CUTOFF = 1 << 22;
              var SCAN_COMPLETE_CUTOFF = 1 << 22;
              var partitionInteriorContainsInterval = genPartition(
                "!(lo>=p0)&&!(p1>=hi)"
              );
              var partitionStartEqual = genPartition(
                "lo===p0"
              );
              var partitionStartLessThan = genPartition(
                "lo<p0"
              );
              var partitionEndLessThanEqual = genPartition(
                "hi<=p0"
              );
              var partitionContainsPoint = genPartition(
                "lo<=p0&&p0<=hi"
              );
              var partitionContainsPointProper = genPartition(
                "lo<p0&&p0<=hi"
              );
              var IFRAME_SIZE = 6;
              var DFRAME_SIZE = 2;
              var INIT_CAPACITY = 1024;
              var BOX_ISTACK = pool.mallocInt32(INIT_CAPACITY);
              var BOX_DSTACK = pool.mallocDouble(INIT_CAPACITY);
              function iterInit(d, count) {
                var levels = 8 * bits.log2(count + 1) * (d + 1) | 0;
                var maxInts = bits.nextPow2(IFRAME_SIZE * levels);
                if (BOX_ISTACK.length < maxInts) {
                  pool.free(BOX_ISTACK);
                  BOX_ISTACK = pool.mallocInt32(maxInts);
                }
                var maxDoubles = bits.nextPow2(DFRAME_SIZE * levels);
                if (BOX_DSTACK.length < maxDoubles) {
                  pool.free(BOX_DSTACK);
                  BOX_DSTACK = pool.mallocDouble(maxDoubles);
                }
              }
              function iterPush(ptr, axis, redStart, redEnd, blueStart, blueEnd, state, lo, hi) {
                var iptr = IFRAME_SIZE * ptr;
                BOX_ISTACK[iptr] = axis;
                BOX_ISTACK[iptr + 1] = redStart;
                BOX_ISTACK[iptr + 2] = redEnd;
                BOX_ISTACK[iptr + 3] = blueStart;
                BOX_ISTACK[iptr + 4] = blueEnd;
                BOX_ISTACK[iptr + 5] = state;
                var dptr = DFRAME_SIZE * ptr;
                BOX_DSTACK[dptr] = lo;
                BOX_DSTACK[dptr + 1] = hi;
              }
              function onePointPartial(d, axis, visit, flip, redStart, redEnd, red, redIndex, blueOffset, blue, blueId) {
                var elemSize = 2 * d;
                var bluePtr = blueOffset * elemSize;
                var blueX = blue[bluePtr + axis];
                red_loop:
                  for (var i = redStart, redPtr = redStart * elemSize; i < redEnd; ++i, redPtr += elemSize) {
                    var r0 = red[redPtr + axis];
                    var r1 = red[redPtr + axis + d];
                    if (blueX < r0 || r1 < blueX) {
                      continue;
                    }
                    if (flip && blueX === r0) {
                      continue;
                    }
                    var redId = redIndex[i];
                    for (var j = axis + 1; j < d; ++j) {
                      var r0 = red[redPtr + j];
                      var r1 = red[redPtr + j + d];
                      var b0 = blue[bluePtr + j];
                      var b1 = blue[bluePtr + j + d];
                      if (r1 < b0 || b1 < r0) {
                        continue red_loop;
                      }
                    }
                    var retval;
                    if (flip) {
                      retval = visit(blueId, redId);
                    } else {
                      retval = visit(redId, blueId);
                    }
                    if (retval !== void 0) {
                      return retval;
                    }
                  }
              }
              function onePointFull(d, axis, visit, redStart, redEnd, red, redIndex, blueOffset, blue, blueId) {
                var elemSize = 2 * d;
                var bluePtr = blueOffset * elemSize;
                var blueX = blue[bluePtr + axis];
                red_loop:
                  for (var i = redStart, redPtr = redStart * elemSize; i < redEnd; ++i, redPtr += elemSize) {
                    var redId = redIndex[i];
                    if (redId === blueId) {
                      continue;
                    }
                    var r0 = red[redPtr + axis];
                    var r1 = red[redPtr + axis + d];
                    if (blueX < r0 || r1 < blueX) {
                      continue;
                    }
                    for (var j = axis + 1; j < d; ++j) {
                      var r0 = red[redPtr + j];
                      var r1 = red[redPtr + j + d];
                      var b0 = blue[bluePtr + j];
                      var b1 = blue[bluePtr + j + d];
                      if (r1 < b0 || b1 < r0) {
                        continue red_loop;
                      }
                    }
                    var retval = visit(redId, blueId);
                    if (retval !== void 0) {
                      return retval;
                    }
                  }
              }
              function boxIntersectIter(d, visit, initFull, xSize, xBoxes, xIndex, ySize, yBoxes, yIndex) {
                iterInit(d, xSize + ySize);
                var top = 0;
                var elemSize = 2 * d;
                var retval;
                iterPush(
                  top++,
                  0,
                  0,
                  xSize,
                  0,
                  ySize,
                  initFull ? 16 : 0,
                  -Infinity,
                  Infinity
                );
                if (!initFull) {
                  iterPush(
                    top++,
                    0,
                    0,
                    ySize,
                    0,
                    xSize,
                    1,
                    -Infinity,
                    Infinity
                  );
                }
                while (top > 0) {
                  top -= 1;
                  var iptr = top * IFRAME_SIZE;
                  var axis = BOX_ISTACK[iptr];
                  var redStart = BOX_ISTACK[iptr + 1];
                  var redEnd = BOX_ISTACK[iptr + 2];
                  var blueStart = BOX_ISTACK[iptr + 3];
                  var blueEnd = BOX_ISTACK[iptr + 4];
                  var state = BOX_ISTACK[iptr + 5];
                  var dptr = top * DFRAME_SIZE;
                  var lo = BOX_DSTACK[dptr];
                  var hi = BOX_DSTACK[dptr + 1];
                  var flip = state & 1;
                  var full = !!(state & 16);
                  var red = xBoxes;
                  var redIndex = xIndex;
                  var blue = yBoxes;
                  var blueIndex = yIndex;
                  if (flip) {
                    red = yBoxes;
                    redIndex = yIndex;
                    blue = xBoxes;
                    blueIndex = xIndex;
                  }
                  if (state & 2) {
                    redEnd = partitionStartLessThan(
                      d,
                      axis,
                      redStart,
                      redEnd,
                      red,
                      redIndex,
                      hi
                    );
                    if (redStart >= redEnd) {
                      continue;
                    }
                  }
                  if (state & 4) {
                    redStart = partitionEndLessThanEqual(
                      d,
                      axis,
                      redStart,
                      redEnd,
                      red,
                      redIndex,
                      lo
                    );
                    if (redStart >= redEnd) {
                      continue;
                    }
                  }
                  var redCount = redEnd - redStart;
                  var blueCount = blueEnd - blueStart;
                  if (full) {
                    if (d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) {
                      retval = sweep.scanComplete(
                        d,
                        axis,
                        visit,
                        redStart,
                        redEnd,
                        red,
                        redIndex,
                        blueStart,
                        blueEnd,
                        blue,
                        blueIndex
                      );
                      if (retval !== void 0) {
                        return retval;
                      }
                      continue;
                    }
                  } else {
                    if (d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) {
                      retval = bruteForcePartial(
                        d,
                        axis,
                        visit,
                        flip,
                        redStart,
                        redEnd,
                        red,
                        redIndex,
                        blueStart,
                        blueEnd,
                        blue,
                        blueIndex
                      );
                      if (retval !== void 0) {
                        return retval;
                      }
                      continue;
                    } else if (d * redCount * blueCount < SCAN_CUTOFF) {
                      retval = sweep.scanBipartite(
                        d,
                        axis,
                        visit,
                        flip,
                        redStart,
                        redEnd,
                        red,
                        redIndex,
                        blueStart,
                        blueEnd,
                        blue,
                        blueIndex
                      );
                      if (retval !== void 0) {
                        return retval;
                      }
                      continue;
                    }
                  }
                  var red0 = partitionInteriorContainsInterval(
                    d,
                    axis,
                    redStart,
                    redEnd,
                    red,
                    redIndex,
                    lo,
                    hi
                  );
                  if (redStart < red0) {
                    if (d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) {
                      retval = bruteForceFull(
                        d,
                        axis + 1,
                        visit,
                        redStart,
                        red0,
                        red,
                        redIndex,
                        blueStart,
                        blueEnd,
                        blue,
                        blueIndex
                      );
                      if (retval !== void 0) {
                        return retval;
                      }
                    } else if (axis === d - 2) {
                      if (flip) {
                        retval = sweep.sweepBipartite(
                          d,
                          visit,
                          blueStart,
                          blueEnd,
                          blue,
                          blueIndex,
                          redStart,
                          red0,
                          red,
                          redIndex
                        );
                      } else {
                        retval = sweep.sweepBipartite(
                          d,
                          visit,
                          redStart,
                          red0,
                          red,
                          redIndex,
                          blueStart,
                          blueEnd,
                          blue,
                          blueIndex
                        );
                      }
                      if (retval !== void 0) {
                        return retval;
                      }
                    } else {
                      iterPush(
                        top++,
                        axis + 1,
                        redStart,
                        red0,
                        blueStart,
                        blueEnd,
                        flip,
                        -Infinity,
                        Infinity
                      );
                      iterPush(
                        top++,
                        axis + 1,
                        blueStart,
                        blueEnd,
                        redStart,
                        red0,
                        flip ^ 1,
                        -Infinity,
                        Infinity
                      );
                    }
                  }
                  if (red0 < redEnd) {
                    var blue0 = findMedian(
                      d,
                      axis,
                      blueStart,
                      blueEnd,
                      blue,
                      blueIndex
                    );
                    var mid = blue[elemSize * blue0 + axis];
                    var blue1 = partitionStartEqual(
                      d,
                      axis,
                      blue0,
                      blueEnd,
                      blue,
                      blueIndex,
                      mid
                    );
                    if (blue1 < blueEnd) {
                      iterPush(
                        top++,
                        axis,
                        red0,
                        redEnd,
                        blue1,
                        blueEnd,
                        (flip | 4) + (full ? 16 : 0),
                        mid,
                        hi
                      );
                    }
                    if (blueStart < blue0) {
                      iterPush(
                        top++,
                        axis,
                        red0,
                        redEnd,
                        blueStart,
                        blue0,
                        (flip | 2) + (full ? 16 : 0),
                        lo,
                        mid
                      );
                    }
                    if (blue0 + 1 === blue1) {
                      if (full) {
                        retval = onePointFull(
                          d,
                          axis,
                          visit,
                          red0,
                          redEnd,
                          red,
                          redIndex,
                          blue0,
                          blue,
                          blueIndex[blue0]
                        );
                      } else {
                        retval = onePointPartial(
                          d,
                          axis,
                          visit,
                          flip,
                          red0,
                          redEnd,
                          red,
                          redIndex,
                          blue0,
                          blue,
                          blueIndex[blue0]
                        );
                      }
                      if (retval !== void 0) {
                        return retval;
                      }
                    } else if (blue0 < blue1) {
                      var red1;
                      if (full) {
                        red1 = partitionContainsPoint(
                          d,
                          axis,
                          red0,
                          redEnd,
                          red,
                          redIndex,
                          mid
                        );
                        if (red0 < red1) {
                          var redX = partitionStartEqual(
                            d,
                            axis,
                            red0,
                            red1,
                            red,
                            redIndex,
                            mid
                          );
                          if (axis === d - 2) {
                            if (red0 < redX) {
                              retval = sweep.sweepComplete(
                                d,
                                visit,
                                red0,
                                redX,
                                red,
                                redIndex,
                                blue0,
                                blue1,
                                blue,
                                blueIndex
                              );
                              if (retval !== void 0) {
                                return retval;
                              }
                            }
                            if (redX < red1) {
                              retval = sweep.sweepBipartite(
                                d,
                                visit,
                                redX,
                                red1,
                                red,
                                redIndex,
                                blue0,
                                blue1,
                                blue,
                                blueIndex
                              );
                              if (retval !== void 0) {
                                return retval;
                              }
                            }
                          } else {
                            if (red0 < redX) {
                              iterPush(
                                top++,
                                axis + 1,
                                red0,
                                redX,
                                blue0,
                                blue1,
                                16,
                                -Infinity,
                                Infinity
                              );
                            }
                            if (redX < red1) {
                              iterPush(
                                top++,
                                axis + 1,
                                redX,
                                red1,
                                blue0,
                                blue1,
                                0,
                                -Infinity,
                                Infinity
                              );
                              iterPush(
                                top++,
                                axis + 1,
                                blue0,
                                blue1,
                                redX,
                                red1,
                                1,
                                -Infinity,
                                Infinity
                              );
                            }
                          }
                        }
                      } else {
                        if (flip) {
                          red1 = partitionContainsPointProper(
                            d,
                            axis,
                            red0,
                            redEnd,
                            red,
                            redIndex,
                            mid
                          );
                        } else {
                          red1 = partitionContainsPoint(
                            d,
                            axis,
                            red0,
                            redEnd,
                            red,
                            redIndex,
                            mid
                          );
                        }
                        if (red0 < red1) {
                          if (axis === d - 2) {
                            if (flip) {
                              retval = sweep.sweepBipartite(
                                d,
                                visit,
                                blue0,
                                blue1,
                                blue,
                                blueIndex,
                                red0,
                                red1,
                                red,
                                redIndex
                              );
                            } else {
                              retval = sweep.sweepBipartite(
                                d,
                                visit,
                                red0,
                                red1,
                                red,
                                redIndex,
                                blue0,
                                blue1,
                                blue,
                                blueIndex
                              );
                            }
                          } else {
                            iterPush(
                              top++,
                              axis + 1,
                              red0,
                              red1,
                              blue0,
                              blue1,
                              flip,
                              -Infinity,
                              Infinity
                            );
                            iterPush(
                              top++,
                              axis + 1,
                              blue0,
                              blue1,
                              red0,
                              red1,
                              flip ^ 1,
                              -Infinity,
                              Infinity
                            );
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          ),
          /***/
          7163: (
            /***/
            function(module2) {
              module2.exports = function(obj) {
                return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer);
              };
              function isBuffer(obj) {
                return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
              }
              function isSlowBuffer(obj) {
                return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isBuffer(obj.slice(0, 0));
              }
            }
          ),
          /***/
          7169: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var weakMap = typeof WeakMap === "undefined" ? __webpack_require__2(1538) : WeakMap;
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var TriangleCache = new weakMap();
              function createABigTriangle(gl2) {
                var triangleVAO = TriangleCache.get(gl2);
                var handle = triangleVAO && (triangleVAO._triangleBuffer.handle || triangleVAO._triangleBuffer.buffer);
                if (!handle || !gl2.isBuffer(handle)) {
                  var buf = createBuffer(gl2, new Float32Array([-1, -1, -1, 4, 4, -1]));
                  triangleVAO = createVAO(gl2, [
                    {
                      buffer: buf,
                      type: gl2.FLOAT,
                      size: 2
                    }
                  ]);
                  triangleVAO._triangleBuffer = buf;
                  TriangleCache.set(gl2, triangleVAO);
                }
                triangleVAO.bind();
                gl2.drawArrays(gl2.TRIANGLES, 0, 3);
                triangleVAO.unbind();
              }
              module2.exports = createABigTriangle;
            }
          ),
          /***/
          7182: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var mat4 = {
                identity: __webpack_require__2(7894),
                translate: __webpack_require__2(7656),
                multiply: __webpack_require__2(6760),
                create: __webpack_require__2(6864),
                scale: __webpack_require__2(2504),
                fromRotationTranslation: __webpack_require__2(6743)
              };
              var rotationMatrix = mat4.create();
              var temp = mat4.create();
              module2.exports = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
                mat4.identity(matrix);
                mat4.fromRotationTranslation(matrix, quaternion, translation);
                matrix[3] = perspective[0];
                matrix[7] = perspective[1];
                matrix[11] = perspective[2];
                matrix[15] = perspective[3];
                mat4.identity(temp);
                if (skew[2] !== 0) {
                  temp[9] = skew[2];
                  mat4.multiply(matrix, matrix, temp);
                }
                if (skew[1] !== 0) {
                  temp[9] = 0;
                  temp[8] = skew[1];
                  mat4.multiply(matrix, matrix, temp);
                }
                if (skew[0] !== 0) {
                  temp[8] = 0;
                  temp[4] = skew[0];
                  mat4.multiply(matrix, matrix, temp);
                }
                mat4.scale(matrix, matrix, scale);
                return matrix;
              };
            }
          ),
          /***/
          7201: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6;
              var DEFAULT_FACE_NORMALS_EPSILON = 1e-6;
              var createShader = __webpack_require__2(9405);
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createTexture = __webpack_require__2(7766);
              var normals = __webpack_require__2(8406);
              var multiply = __webpack_require__2(6760);
              var invert = __webpack_require__2(7608);
              var ndarray = __webpack_require__2(9618);
              var colormap = __webpack_require__2(6729);
              var getContour = __webpack_require__2(7765);
              var pool = __webpack_require__2(1888);
              var shaders = __webpack_require__2(840);
              var closestPoint = __webpack_require__2(7626);
              var meshShader = shaders.meshShader;
              var wireShader = shaders.wireShader;
              var pointShader = shaders.pointShader;
              var pickShader = shaders.pickShader;
              var pointPickShader = shaders.pointPickShader;
              var contourShader = shaders.contourShader;
              var IDENTITY = [
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ];
              function SimplicialMesh(gl2, texture, triShader, lineShader, pointShader2, pickShader2, pointPickShader2, contourShader2, trianglePositions, triangleIds, triangleColors, triangleUVs, triangleNormals, triangleVAO, edgePositions, edgeIds, edgeColors, edgeUVs, edgeVAO, pointPositions, pointIds, pointColors, pointUVs, pointSizes, pointVAO, contourPositions, contourVAO) {
                this.gl = gl2;
                this.pixelRatio = 1;
                this.cells = [];
                this.positions = [];
                this.intensity = [];
                this.texture = texture;
                this.dirty = true;
                this.triShader = triShader;
                this.lineShader = lineShader;
                this.pointShader = pointShader2;
                this.pickShader = pickShader2;
                this.pointPickShader = pointPickShader2;
                this.contourShader = contourShader2;
                this.trianglePositions = trianglePositions;
                this.triangleColors = triangleColors;
                this.triangleNormals = triangleNormals;
                this.triangleUVs = triangleUVs;
                this.triangleIds = triangleIds;
                this.triangleVAO = triangleVAO;
                this.triangleCount = 0;
                this.lineWidth = 1;
                this.edgePositions = edgePositions;
                this.edgeColors = edgeColors;
                this.edgeUVs = edgeUVs;
                this.edgeIds = edgeIds;
                this.edgeVAO = edgeVAO;
                this.edgeCount = 0;
                this.pointPositions = pointPositions;
                this.pointColors = pointColors;
                this.pointUVs = pointUVs;
                this.pointSizes = pointSizes;
                this.pointIds = pointIds;
                this.pointVAO = pointVAO;
                this.pointCount = 0;
                this.contourLineWidth = 1;
                this.contourPositions = contourPositions;
                this.contourVAO = contourVAO;
                this.contourCount = 0;
                this.contourColor = [0, 0, 0];
                this.contourEnable = true;
                this.pickVertex = true;
                this.pickId = 1;
                this.bounds = [
                  [Infinity, Infinity, Infinity],
                  [-Infinity, -Infinity, -Infinity]
                ];
                this.clipBounds = [
                  [-Infinity, -Infinity, -Infinity],
                  [Infinity, Infinity, Infinity]
                ];
                this.lightPosition = [1e5, 1e5, 0];
                this.ambientLight = 0.8;
                this.diffuseLight = 0.8;
                this.specularLight = 2;
                this.roughness = 0.5;
                this.fresnel = 1.5;
                this.opacity = 1;
                this.hasAlpha = false;
                this.opacityscale = false;
                this._model = IDENTITY;
                this._view = IDENTITY;
                this._projection = IDENTITY;
                this._resolution = [1, 1];
              }
              var proto = SimplicialMesh.prototype;
              proto.isOpaque = function() {
                return !this.hasAlpha;
              };
              proto.isTransparent = function() {
                return this.hasAlpha;
              };
              proto.pickSlots = 1;
              proto.setPickBase = function(id) {
                this.pickId = id;
              };
              function getOpacityFromScale(ratio, opacityscale) {
                if (!opacityscale) return 1;
                if (!opacityscale.length) return 1;
                for (var i = 0; i < opacityscale.length; ++i) {
                  if (opacityscale.length < 2) return 1;
                  if (opacityscale[i][0] === ratio) return opacityscale[i][1];
                  if (opacityscale[i][0] > ratio && i > 0) {
                    var d = (opacityscale[i][0] - ratio) / (opacityscale[i][0] - opacityscale[i - 1][0]);
                    return opacityscale[i][1] * (1 - d) + d * opacityscale[i - 1][1];
                  }
                }
                return 1;
              }
              function genColormap(param, opacityscale) {
                var colors = colormap({
                  colormap: param,
                  nshades: 256,
                  format: "rgba"
                });
                var result = new Uint8Array(256 * 4);
                for (var i = 0; i < 256; ++i) {
                  var c = colors[i];
                  for (var j = 0; j < 3; ++j) {
                    result[4 * i + j] = c[j];
                  }
                  if (!opacityscale) {
                    result[4 * i + 3] = 255 * c[3];
                  } else {
                    result[4 * i + 3] = 255 * getOpacityFromScale(i / 255, opacityscale);
                  }
                }
                return ndarray(result, [256, 256, 4], [4, 0, 1]);
              }
              function takeZComponent(array) {
                var n = array.length;
                var result = new Array(n);
                for (var i = 0; i < n; ++i) {
                  result[i] = array[i][2];
                }
                return result;
              }
              proto.highlight = function(selection) {
                if (!selection || !this.contourEnable) {
                  this.contourCount = 0;
                  return;
                }
                var level = getContour(this.cells, this.intensity, selection.intensity);
                var cells = level.cells;
                var vertexIds = level.vertexIds;
                var vertexWeights = level.vertexWeights;
                var numCells = cells.length;
                var result = pool.mallocFloat32(2 * 3 * numCells);
                var ptr = 0;
                for (var i = 0; i < numCells; ++i) {
                  var c = cells[i];
                  for (var j = 0; j < 2; ++j) {
                    var v = c[0];
                    if (c.length === 2) {
                      v = c[j];
                    }
                    var a = vertexIds[v][0];
                    var b = vertexIds[v][1];
                    var w = vertexWeights[v];
                    var wi = 1 - w;
                    var pa = this.positions[a];
                    var pb = this.positions[b];
                    for (var k = 0; k < 3; ++k) {
                      result[ptr++] = w * pa[k] + wi * pb[k];
                    }
                  }
                }
                this.contourCount = ptr / 3 | 0;
                this.contourPositions.update(result.subarray(0, ptr));
                pool.free(result);
              };
              proto.update = function(params) {
                params = params || {};
                var gl2 = this.gl;
                this.dirty = true;
                if ("contourEnable" in params) {
                  this.contourEnable = params.contourEnable;
                }
                if ("contourColor" in params) {
                  this.contourColor = params.contourColor;
                }
                if ("lineWidth" in params) {
                  this.lineWidth = params.lineWidth;
                }
                if ("lightPosition" in params) {
                  this.lightPosition = params.lightPosition;
                }
                this.hasAlpha = false;
                if ("opacity" in params) {
                  this.opacity = params.opacity;
                  if (this.opacity < 1) {
                    this.hasAlpha = true;
                  }
                }
                if ("opacityscale" in params) {
                  this.opacityscale = params.opacityscale;
                  this.hasAlpha = true;
                }
                if ("ambient" in params) {
                  this.ambientLight = params.ambient;
                }
                if ("diffuse" in params) {
                  this.diffuseLight = params.diffuse;
                }
                if ("specular" in params) {
                  this.specularLight = params.specular;
                }
                if ("roughness" in params) {
                  this.roughness = params.roughness;
                }
                if ("fresnel" in params) {
                  this.fresnel = params.fresnel;
                }
                if (params.texture) {
                  this.texture.dispose();
                  this.texture = createTexture(gl2, params.texture);
                } else if (params.colormap) {
                  this.texture.shape = [256, 256];
                  this.texture.minFilter = gl2.LINEAR_MIPMAP_LINEAR;
                  this.texture.magFilter = gl2.LINEAR;
                  this.texture.setPixels(genColormap(params.colormap, this.opacityscale));
                  this.texture.generateMipmap();
                }
                var cells = params.cells;
                var positions = params.positions;
                if (!positions || !cells) {
                  return;
                }
                var tPos = [];
                var tCol = [];
                var tNor = [];
                var tUVs = [];
                var tIds = [];
                var ePos = [];
                var eCol = [];
                var eUVs = [];
                var eIds = [];
                var pPos = [];
                var pCol = [];
                var pUVs = [];
                var pSiz = [];
                var pIds = [];
                this.cells = cells;
                this.positions = positions;
                var vertexNormals = params.vertexNormals;
                var cellNormals = params.cellNormals;
                var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void 0 ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon;
                var faceNormalsEpsilon = params.faceNormalsEpsilon === void 0 ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon;
                if (params.useFacetNormals && !cellNormals) {
                  cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon);
                }
                if (!cellNormals && !vertexNormals) {
                  vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon);
                }
                var vertexColors = params.vertexColors;
                var cellColors = params.cellColors;
                var meshColor = params.meshColor || [1, 1, 1, 1];
                var vertexUVs = params.vertexUVs;
                var vertexIntensity = params.vertexIntensity;
                var cellUVs = params.cellUVs;
                var cellIntensity = params.cellIntensity;
                var intensityLo = Infinity;
                var intensityHi = -Infinity;
                if (!vertexUVs && !cellUVs) {
                  if (vertexIntensity) {
                    if (params.vertexIntensityBounds) {
                      intensityLo = +params.vertexIntensityBounds[0];
                      intensityHi = +params.vertexIntensityBounds[1];
                    } else {
                      for (var i = 0; i < vertexIntensity.length; ++i) {
                        var f = vertexIntensity[i];
                        intensityLo = Math.min(intensityLo, f);
                        intensityHi = Math.max(intensityHi, f);
                      }
                    }
                  } else if (cellIntensity) {
                    if (params.cellIntensityBounds) {
                      intensityLo = +params.cellIntensityBounds[0];
                      intensityHi = +params.cellIntensityBounds[1];
                    } else {
                      for (var i = 0; i < cellIntensity.length; ++i) {
                        var f = cellIntensity[i];
                        intensityLo = Math.min(intensityLo, f);
                        intensityHi = Math.max(intensityHi, f);
                      }
                    }
                  } else {
                    for (var i = 0; i < positions.length; ++i) {
                      var f = positions[i][2];
                      intensityLo = Math.min(intensityLo, f);
                      intensityHi = Math.max(intensityHi, f);
                    }
                  }
                }
                if (vertexIntensity) {
                  this.intensity = vertexIntensity;
                } else if (cellIntensity) {
                  this.intensity = cellIntensity;
                } else {
                  this.intensity = takeZComponent(positions);
                }
                this.pickVertex = !(cellIntensity || cellColors);
                var pointSizes = params.pointSizes;
                var meshPointSize = params.pointSize || 1;
                this.bounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
                for (var i = 0; i < positions.length; ++i) {
                  var p = positions[i];
                  for (var j = 0; j < 3; ++j) {
                    if (isNaN(p[j]) || !isFinite(p[j])) {
                      continue;
                    }
                    this.bounds[0][j] = Math.min(this.bounds[0][j], p[j]);
                    this.bounds[1][j] = Math.max(this.bounds[1][j], p[j]);
                  }
                }
                var triangleCount = 0;
                var edgeCount = 0;
                var pointCount = 0;
                fill_loop:
                  for (var i = 0; i < cells.length; ++i) {
                    var cell = cells[i];
                    switch (cell.length) {
                      case 1:
                        var v = cell[0];
                        var p = positions[v];
                        for (var j = 0; j < 3; ++j) {
                          if (isNaN(p[j]) || !isFinite(p[j])) {
                            continue fill_loop;
                          }
                        }
                        pPos.push(p[0], p[1], p[2]);
                        var c;
                        if (vertexColors) {
                          c = vertexColors[v];
                        } else if (cellColors) {
                          c = cellColors[i];
                        } else {
                          c = meshColor;
                        }
                        if (this.opacityscale && vertexIntensity) {
                          tCol.push(
                            c[0],
                            c[1],
                            c[2],
                            this.opacity * getOpacityFromScale(
                              (vertexIntensity[v] - intensityLo) / (intensityHi - intensityLo),
                              this.opacityscale
                            )
                          );
                        } else if (c.length === 3) {
                          pCol.push(c[0], c[1], c[2], this.opacity);
                        } else {
                          pCol.push(c[0], c[1], c[2], c[3] * this.opacity);
                          if (c[3] < 1) this.hasAlpha = true;
                        }
                        var uv;
                        if (vertexUVs) {
                          uv = vertexUVs[v];
                        } else if (vertexIntensity) {
                          uv = [
                            (vertexIntensity[v] - intensityLo) / (intensityHi - intensityLo),
                            0
                          ];
                        } else if (cellUVs) {
                          uv = cellUVs[i];
                        } else if (cellIntensity) {
                          uv = [
                            (cellIntensity[i] - intensityLo) / (intensityHi - intensityLo),
                            0
                          ];
                        } else {
                          uv = [
                            (p[2] - intensityLo) / (intensityHi - intensityLo),
                            0
                          ];
                        }
                        pUVs.push(uv[0], uv[1]);
                        if (pointSizes) {
                          pSiz.push(pointSizes[v]);
                        } else {
                          pSiz.push(meshPointSize);
                        }
                        pIds.push(i);
                        pointCount += 1;
                        break;
                      case 2:
                        for (var j = 0; j < 2; ++j) {
                          var v = cell[j];
                          var p = positions[v];
                          for (var k = 0; k < 3; ++k) {
                            if (isNaN(p[k]) || !isFinite(p[k])) {
                              continue fill_loop;
                            }
                          }
                        }
                        for (var j = 0; j < 2; ++j) {
                          var v = cell[j];
                          var p = positions[v];
                          ePos.push(p[0], p[1], p[2]);
                          var c;
                          if (vertexColors) {
                            c = vertexColors[v];
                          } else if (cellColors) {
                            c = cellColors[i];
                          } else {
                            c = meshColor;
                          }
                          if (this.opacityscale && vertexIntensity) {
                            tCol.push(
                              c[0],
                              c[1],
                              c[2],
                              this.opacity * getOpacityFromScale(
                                (vertexIntensity[v] - intensityLo) / (intensityHi - intensityLo),
                                this.opacityscale
                              )
                            );
                          } else if (c.length === 3) {
                            eCol.push(c[0], c[1], c[2], this.opacity);
                          } else {
                            eCol.push(c[0], c[1], c[2], c[3] * this.opacity);
                            if (c[3] < 1) this.hasAlpha = true;
                          }
                          var uv;
                          if (vertexUVs) {
                            uv = vertexUVs[v];
                          } else if (vertexIntensity) {
                            uv = [
                              (vertexIntensity[v] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          } else if (cellUVs) {
                            uv = cellUVs[i];
                          } else if (cellIntensity) {
                            uv = [
                              (cellIntensity[i] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          } else {
                            uv = [
                              (p[2] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          }
                          eUVs.push(uv[0], uv[1]);
                          eIds.push(i);
                        }
                        edgeCount += 1;
                        break;
                      case 3:
                        for (var j = 0; j < 3; ++j) {
                          var v = cell[j];
                          var p = positions[v];
                          for (var k = 0; k < 3; ++k) {
                            if (isNaN(p[k]) || !isFinite(p[k])) {
                              continue fill_loop;
                            }
                          }
                        }
                        for (var j = 0; j < 3; ++j) {
                          var v = cell[2 - j];
                          var p = positions[v];
                          tPos.push(p[0], p[1], p[2]);
                          var c;
                          if (vertexColors) {
                            c = vertexColors[v];
                          } else if (cellColors) {
                            c = cellColors[i];
                          } else {
                            c = meshColor;
                          }
                          if (!c) {
                            tCol.push(0.5, 0.5, 0.5, 1);
                          } else if (this.opacityscale && vertexIntensity) {
                            tCol.push(
                              c[0],
                              c[1],
                              c[2],
                              this.opacity * getOpacityFromScale(
                                (vertexIntensity[v] - intensityLo) / (intensityHi - intensityLo),
                                this.opacityscale
                              )
                            );
                          } else if (c.length === 3) {
                            tCol.push(c[0], c[1], c[2], this.opacity);
                          } else {
                            tCol.push(c[0], c[1], c[2], c[3] * this.opacity);
                            if (c[3] < 1) this.hasAlpha = true;
                          }
                          var uv;
                          if (vertexUVs) {
                            uv = vertexUVs[v];
                          } else if (vertexIntensity) {
                            uv = [
                              (vertexIntensity[v] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          } else if (cellUVs) {
                            uv = cellUVs[i];
                          } else if (cellIntensity) {
                            uv = [
                              (cellIntensity[i] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          } else {
                            uv = [
                              (p[2] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          }
                          tUVs.push(uv[0], uv[1]);
                          var q;
                          if (vertexNormals) {
                            q = vertexNormals[v];
                          } else {
                            q = cellNormals[i];
                          }
                          tNor.push(q[0], q[1], q[2]);
                          tIds.push(i);
                        }
                        triangleCount += 1;
                        break;
                      default:
                        break;
                    }
                  }
                this.pointCount = pointCount;
                this.edgeCount = edgeCount;
                this.triangleCount = triangleCount;
                this.pointPositions.update(pPos);
                this.pointColors.update(pCol);
                this.pointUVs.update(pUVs);
                this.pointSizes.update(pSiz);
                this.pointIds.update(new Uint32Array(pIds));
                this.edgePositions.update(ePos);
                this.edgeColors.update(eCol);
                this.edgeUVs.update(eUVs);
                this.edgeIds.update(new Uint32Array(eIds));
                this.trianglePositions.update(tPos);
                this.triangleColors.update(tCol);
                this.triangleUVs.update(tUVs);
                this.triangleNormals.update(tNor);
                this.triangleIds.update(new Uint32Array(tIds));
              };
              proto.drawTransparent = proto.draw = function(params) {
                params = params || {};
                var gl2 = this.gl;
                var model = params.model || IDENTITY;
                var view = params.view || IDENTITY;
                var projection = params.projection || IDENTITY;
                var clipBounds = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]];
                for (var i = 0; i < 3; ++i) {
                  clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]);
                  clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]);
                }
                var uniforms = {
                  model,
                  view,
                  projection,
                  inverseModel: IDENTITY.slice(),
                  clipBounds,
                  kambient: this.ambientLight,
                  kdiffuse: this.diffuseLight,
                  kspecular: this.specularLight,
                  roughness: this.roughness,
                  fresnel: this.fresnel,
                  eyePosition: [0, 0, 0],
                  lightPosition: [0, 0, 0],
                  contourColor: this.contourColor,
                  texture: 0
                };
                uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model);
                gl2.disable(gl2.CULL_FACE);
                this.texture.bind(0);
                var invCameraMatrix = new Array(16);
                multiply(invCameraMatrix, uniforms.view, uniforms.model);
                multiply(invCameraMatrix, uniforms.projection, invCameraMatrix);
                invert(invCameraMatrix, invCameraMatrix);
                for (var i = 0; i < 3; ++i) {
                  uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15];
                }
                var w = invCameraMatrix[15];
                for (var i = 0; i < 3; ++i) {
                  w += this.lightPosition[i] * invCameraMatrix[4 * i + 3];
                }
                for (var i = 0; i < 3; ++i) {
                  var s = invCameraMatrix[12 + i];
                  for (var j = 0; j < 3; ++j) {
                    s += invCameraMatrix[4 * j + i] * this.lightPosition[j];
                  }
                  uniforms.lightPosition[i] = s / w;
                }
                if (this.triangleCount > 0) {
                  var shader = this.triShader;
                  shader.bind();
                  shader.uniforms = uniforms;
                  this.triangleVAO.bind();
                  gl2.drawArrays(gl2.TRIANGLES, 0, this.triangleCount * 3);
                  this.triangleVAO.unbind();
                }
                if (this.edgeCount > 0 && this.lineWidth > 0) {
                  var shader = this.lineShader;
                  shader.bind();
                  shader.uniforms = uniforms;
                  this.edgeVAO.bind();
                  gl2.lineWidth(this.lineWidth * this.pixelRatio);
                  gl2.drawArrays(gl2.LINES, 0, this.edgeCount * 2);
                  this.edgeVAO.unbind();
                }
                if (this.pointCount > 0) {
                  var shader = this.pointShader;
                  shader.bind();
                  shader.uniforms = uniforms;
                  this.pointVAO.bind();
                  gl2.drawArrays(gl2.POINTS, 0, this.pointCount);
                  this.pointVAO.unbind();
                }
                if (this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) {
                  var shader = this.contourShader;
                  shader.bind();
                  shader.uniforms = uniforms;
                  this.contourVAO.bind();
                  gl2.drawArrays(gl2.LINES, 0, this.contourCount);
                  this.contourVAO.unbind();
                }
              };
              proto.drawPick = function(params) {
                params = params || {};
                var gl2 = this.gl;
                var model = params.model || IDENTITY;
                var view = params.view || IDENTITY;
                var projection = params.projection || IDENTITY;
                var clipBounds = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]];
                for (var i = 0; i < 3; ++i) {
                  clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]);
                  clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]);
                }
                this._model = [].slice.call(model);
                this._view = [].slice.call(view);
                this._projection = [].slice.call(projection);
                this._resolution = [gl2.drawingBufferWidth, gl2.drawingBufferHeight];
                var uniforms = {
                  model,
                  view,
                  projection,
                  clipBounds,
                  pickId: this.pickId / 255
                };
                var shader = this.pickShader;
                shader.bind();
                shader.uniforms = uniforms;
                if (this.triangleCount > 0) {
                  this.triangleVAO.bind();
                  gl2.drawArrays(gl2.TRIANGLES, 0, this.triangleCount * 3);
                  this.triangleVAO.unbind();
                }
                if (this.edgeCount > 0) {
                  this.edgeVAO.bind();
                  gl2.lineWidth(this.lineWidth * this.pixelRatio);
                  gl2.drawArrays(gl2.LINES, 0, this.edgeCount * 2);
                  this.edgeVAO.unbind();
                }
                if (this.pointCount > 0) {
                  var shader = this.pointPickShader;
                  shader.bind();
                  shader.uniforms = uniforms;
                  this.pointVAO.bind();
                  gl2.drawArrays(gl2.POINTS, 0, this.pointCount);
                  this.pointVAO.unbind();
                }
              };
              proto.pick = function(pickData) {
                if (!pickData) {
                  return null;
                }
                if (pickData.id !== this.pickId) {
                  return null;
                }
                var cellId = pickData.value[0] + 256 * pickData.value[1] + 65536 * pickData.value[2];
                var cell = this.cells[cellId];
                var positions = this.positions;
                var simplex = new Array(cell.length);
                for (var i = 0; i < cell.length; ++i) {
                  simplex[i] = positions[cell[i]];
                }
                var x = pickData.coord[0];
                var y = pickData.coord[1];
                if (!this.pickVertex) {
                  var A2 = this.positions[cell[0]];
                  var B2 = this.positions[cell[1]];
                  var C2 = this.positions[cell[2]];
                  var dataCoordinate = [
                    (A2[0] + B2[0] + C2[0]) / 3,
                    (A2[1] + B2[1] + C2[1]) / 3,
                    (A2[2] + B2[2] + C2[2]) / 3
                  ];
                  return {
                    _cellCenter: true,
                    position: [x, y],
                    index: cellId,
                    cell,
                    cellId,
                    intensity: this.intensity[cellId],
                    dataCoordinate
                  };
                }
                var data = closestPoint(
                  simplex,
                  [x * this.pixelRatio, this._resolution[1] - y * this.pixelRatio],
                  this._model,
                  this._view,
                  this._projection,
                  this._resolution
                );
                if (!data) {
                  return null;
                }
                var weights = data[2];
                var interpIntensity = 0;
                for (var i = 0; i < cell.length; ++i) {
                  interpIntensity += weights[i] * this.intensity[cell[i]];
                }
                return {
                  position: data[1],
                  index: cell[data[0]],
                  cell,
                  cellId,
                  intensity: interpIntensity,
                  dataCoordinate: this.positions[cell[data[0]]]
                };
              };
              proto.dispose = function() {
                this.texture.dispose();
                this.triShader.dispose();
                this.lineShader.dispose();
                this.pointShader.dispose();
                this.pickShader.dispose();
                this.pointPickShader.dispose();
                this.triangleVAO.dispose();
                this.trianglePositions.dispose();
                this.triangleColors.dispose();
                this.triangleUVs.dispose();
                this.triangleNormals.dispose();
                this.triangleIds.dispose();
                this.edgeVAO.dispose();
                this.edgePositions.dispose();
                this.edgeColors.dispose();
                this.edgeUVs.dispose();
                this.edgeIds.dispose();
                this.pointVAO.dispose();
                this.pointPositions.dispose();
                this.pointColors.dispose();
                this.pointUVs.dispose();
                this.pointSizes.dispose();
                this.pointIds.dispose();
                this.contourVAO.dispose();
                this.contourPositions.dispose();
                this.contourShader.dispose();
              };
              function createMeshShader(gl2) {
                var shader = createShader(gl2, meshShader.vertex, meshShader.fragment);
                shader.attributes.position.location = 0;
                shader.attributes.color.location = 2;
                shader.attributes.uv.location = 3;
                shader.attributes.normal.location = 4;
                return shader;
              }
              function createWireShader(gl2) {
                var shader = createShader(gl2, wireShader.vertex, wireShader.fragment);
                shader.attributes.position.location = 0;
                shader.attributes.color.location = 2;
                shader.attributes.uv.location = 3;
                return shader;
              }
              function createPointShader(gl2) {
                var shader = createShader(gl2, pointShader.vertex, pointShader.fragment);
                shader.attributes.position.location = 0;
                shader.attributes.color.location = 2;
                shader.attributes.uv.location = 3;
                shader.attributes.pointSize.location = 4;
                return shader;
              }
              function createPickShader(gl2) {
                var shader = createShader(gl2, pickShader.vertex, pickShader.fragment);
                shader.attributes.position.location = 0;
                shader.attributes.id.location = 1;
                return shader;
              }
              function createPointPickShader(gl2) {
                var shader = createShader(gl2, pointPickShader.vertex, pointPickShader.fragment);
                shader.attributes.position.location = 0;
                shader.attributes.id.location = 1;
                shader.attributes.pointSize.location = 4;
                return shader;
              }
              function createContourShader(gl2) {
                var shader = createShader(gl2, contourShader.vertex, contourShader.fragment);
                shader.attributes.position.location = 0;
                return shader;
              }
              function createSimplicialMesh(gl2, params) {
                if (arguments.length === 1) {
                  params = gl2;
                  gl2 = params.gl;
                }
                var ext = gl2.getExtension("OES_standard_derivatives") || gl2.getExtension("MOZ_OES_standard_derivatives") || gl2.getExtension("WEBKIT_OES_standard_derivatives");
                if (!ext)
                  throw new Error("derivatives not supported");
                var triShader = createMeshShader(gl2);
                var lineShader = createWireShader(gl2);
                var pointShader2 = createPointShader(gl2);
                var pickShader2 = createPickShader(gl2);
                var pointPickShader2 = createPointPickShader(gl2);
                var contourShader2 = createContourShader(gl2);
                var meshTexture = createTexture(
                  gl2,
                  ndarray(new Uint8Array([255, 255, 255, 255]), [1, 1, 4])
                );
                meshTexture.generateMipmap();
                meshTexture.minFilter = gl2.LINEAR_MIPMAP_LINEAR;
                meshTexture.magFilter = gl2.LINEAR;
                var trianglePositions = createBuffer(gl2);
                var triangleColors = createBuffer(gl2);
                var triangleUVs = createBuffer(gl2);
                var triangleNormals = createBuffer(gl2);
                var triangleIds = createBuffer(gl2);
                var triangleVAO = createVAO(gl2, [
                  {
                    buffer: trianglePositions,
                    type: gl2.FLOAT,
                    size: 3
                  },
                  {
                    buffer: triangleIds,
                    type: gl2.UNSIGNED_BYTE,
                    size: 4,
                    normalized: true
                  },
                  {
                    buffer: triangleColors,
                    type: gl2.FLOAT,
                    size: 4
                  },
                  {
                    buffer: triangleUVs,
                    type: gl2.FLOAT,
                    size: 2
                  },
                  {
                    buffer: triangleNormals,
                    type: gl2.FLOAT,
                    size: 3
                  }
                ]);
                var edgePositions = createBuffer(gl2);
                var edgeColors = createBuffer(gl2);
                var edgeUVs = createBuffer(gl2);
                var edgeIds = createBuffer(gl2);
                var edgeVAO = createVAO(gl2, [
                  {
                    buffer: edgePositions,
                    type: gl2.FLOAT,
                    size: 3
                  },
                  {
                    buffer: edgeIds,
                    type: gl2.UNSIGNED_BYTE,
                    size: 4,
                    normalized: true
                  },
                  {
                    buffer: edgeColors,
                    type: gl2.FLOAT,
                    size: 4
                  },
                  {
                    buffer: edgeUVs,
                    type: gl2.FLOAT,
                    size: 2
                  }
                ]);
                var pointPositions = createBuffer(gl2);
                var pointColors = createBuffer(gl2);
                var pointUVs = createBuffer(gl2);
                var pointSizes = createBuffer(gl2);
                var pointIds = createBuffer(gl2);
                var pointVAO = createVAO(gl2, [
                  {
                    buffer: pointPositions,
                    type: gl2.FLOAT,
                    size: 3
                  },
                  {
                    buffer: pointIds,
                    type: gl2.UNSIGNED_BYTE,
                    size: 4,
                    normalized: true
                  },
                  {
                    buffer: pointColors,
                    type: gl2.FLOAT,
                    size: 4
                  },
                  {
                    buffer: pointUVs,
                    type: gl2.FLOAT,
                    size: 2
                  },
                  {
                    buffer: pointSizes,
                    type: gl2.FLOAT,
                    size: 1
                  }
                ]);
                var contourPositions = createBuffer(gl2);
                var contourVAO = createVAO(gl2, [
                  {
                    buffer: contourPositions,
                    type: gl2.FLOAT,
                    size: 3
                  }
                ]);
                var mesh = new SimplicialMesh(
                  gl2,
                  meshTexture,
                  triShader,
                  lineShader,
                  pointShader2,
                  pickShader2,
                  pointPickShader2,
                  contourShader2,
                  trianglePositions,
                  triangleIds,
                  triangleColors,
                  triangleUVs,
                  triangleNormals,
                  triangleVAO,
                  edgePositions,
                  edgeIds,
                  edgeColors,
                  edgeUVs,
                  edgeVAO,
                  pointPositions,
                  pointIds,
                  pointColors,
                  pointUVs,
                  pointSizes,
                  pointVAO,
                  contourPositions,
                  contourVAO
                );
                mesh.update(params);
                return mesh;
              }
              module2.exports = createSimplicialMesh;
            }
          ),
          /***/
          7261: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createTurntableController;
              var filterVector = __webpack_require__2(9215);
              var invert44 = __webpack_require__2(7608);
              var rotateM = __webpack_require__2(6079);
              var cross = __webpack_require__2(5911);
              var normalize3 = __webpack_require__2(3536);
              var dot3 = __webpack_require__2(244);
              function len3(x, y, z) {
                return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
              }
              function clamp1(x) {
                return Math.min(1, Math.max(-1, x));
              }
              function findOrthoPair(v) {
                var vx = Math.abs(v[0]);
                var vy = Math.abs(v[1]);
                var vz = Math.abs(v[2]);
                var u = [0, 0, 0];
                if (vx > Math.max(vy, vz)) {
                  u[2] = 1;
                } else if (vy > Math.max(vx, vz)) {
                  u[0] = 1;
                } else {
                  u[1] = 1;
                }
                var vv = 0;
                var uv = 0;
                for (var i = 0; i < 3; ++i) {
                  vv += v[i] * v[i];
                  uv += u[i] * v[i];
                }
                for (var i = 0; i < 3; ++i) {
                  u[i] -= uv / vv * v[i];
                }
                normalize3(u, u);
                return u;
              }
              function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, phi) {
                this.center = filterVector(center);
                this.up = filterVector(up);
                this.right = filterVector(right);
                this.radius = filterVector([radius]);
                this.angle = filterVector([theta, phi]);
                this.angle.bounds = [[-Infinity, -Math.PI / 2], [Infinity, Math.PI / 2]];
                this.setDistanceLimits(zoomMin, zoomMax);
                this.computedCenter = this.center.curve(0);
                this.computedUp = this.up.curve(0);
                this.computedRight = this.right.curve(0);
                this.computedRadius = this.radius.curve(0);
                this.computedAngle = this.angle.curve(0);
                this.computedToward = [0, 0, 0];
                this.computedEye = [0, 0, 0];
                this.computedMatrix = new Array(16);
                for (var i = 0; i < 16; ++i) {
                  this.computedMatrix[i] = 0.5;
                }
                this.recalcMatrix(0);
              }
              var proto = TurntableController.prototype;
              proto.setDistanceLimits = function(minDist, maxDist) {
                if (minDist > 0) {
                  minDist = Math.log(minDist);
                } else {
                  minDist = -Infinity;
                }
                if (maxDist > 0) {
                  maxDist = Math.log(maxDist);
                } else {
                  maxDist = Infinity;
                }
                maxDist = Math.max(maxDist, minDist);
                this.radius.bounds[0][0] = minDist;
                this.radius.bounds[1][0] = maxDist;
              };
              proto.getDistanceLimits = function(out) {
                var bounds = this.radius.bounds[0];
                if (out) {
                  out[0] = Math.exp(bounds[0][0]);
                  out[1] = Math.exp(bounds[1][0]);
                  return out;
                }
                return [Math.exp(bounds[0][0]), Math.exp(bounds[1][0])];
              };
              proto.recalcMatrix = function(t) {
                this.center.curve(t);
                this.up.curve(t);
                this.right.curve(t);
                this.radius.curve(t);
                this.angle.curve(t);
                var up = this.computedUp;
                var right = this.computedRight;
                var uu = 0;
                var ur = 0;
                for (var i = 0; i < 3; ++i) {
                  ur += up[i] * right[i];
                  uu += up[i] * up[i];
                }
                var ul = Math.sqrt(uu);
                var rr = 0;
                for (var i = 0; i < 3; ++i) {
                  right[i] -= up[i] * ur / uu;
                  rr += right[i] * right[i];
                  up[i] /= ul;
                }
                var rl = Math.sqrt(rr);
                for (var i = 0; i < 3; ++i) {
                  right[i] /= rl;
                }
                var toward = this.computedToward;
                cross(toward, up, right);
                normalize3(toward, toward);
                var radius = Math.exp(this.computedRadius[0]);
                var theta = this.computedAngle[0];
                var phi = this.computedAngle[1];
                var ctheta = Math.cos(theta);
                var stheta = Math.sin(theta);
                var cphi = Math.cos(phi);
                var sphi = Math.sin(phi);
                var center = this.computedCenter;
                var wx = ctheta * cphi;
                var wy = stheta * cphi;
                var wz = sphi;
                var sx = -ctheta * sphi;
                var sy = -stheta * sphi;
                var sz = cphi;
                var eye = this.computedEye;
                var mat = this.computedMatrix;
                for (var i = 0; i < 3; ++i) {
                  var x = wx * right[i] + wy * toward[i] + wz * up[i];
                  mat[4 * i + 1] = sx * right[i] + sy * toward[i] + sz * up[i];
                  mat[4 * i + 2] = x;
                  mat[4 * i + 3] = 0;
                }
                var ax = mat[1];
                var ay = mat[5];
                var az = mat[9];
                var bx = mat[2];
                var by = mat[6];
                var bz = mat[10];
                var cx = ay * bz - az * by;
                var cy = az * bx - ax * bz;
                var cz = ax * by - ay * bx;
                var cl = len3(cx, cy, cz);
                cx /= cl;
                cy /= cl;
                cz /= cl;
                mat[0] = cx;
                mat[4] = cy;
                mat[8] = cz;
                for (var i = 0; i < 3; ++i) {
                  eye[i] = center[i] + mat[2 + 4 * i] * radius;
                }
                for (var i = 0; i < 3; ++i) {
                  var rr = 0;
                  for (var j = 0; j < 3; ++j) {
                    rr += mat[i + 4 * j] * eye[j];
                  }
                  mat[12 + i] = -rr;
                }
                mat[15] = 1;
              };
              proto.getMatrix = function(t, result) {
                this.recalcMatrix(t);
                var mat = this.computedMatrix;
                if (result) {
                  for (var i = 0; i < 16; ++i) {
                    result[i] = mat[i];
                  }
                  return result;
                }
                return mat;
              };
              var zAxis = [0, 0, 0];
              proto.rotate = function(t, dtheta, dphi, droll) {
                this.angle.move(t, dtheta, dphi);
                if (droll) {
                  this.recalcMatrix(t);
                  var mat = this.computedMatrix;
                  zAxis[0] = mat[2];
                  zAxis[1] = mat[6];
                  zAxis[2] = mat[10];
                  var up = this.computedUp;
                  var right = this.computedRight;
                  var toward = this.computedToward;
                  for (var i = 0; i < 3; ++i) {
                    mat[4 * i] = up[i];
                    mat[4 * i + 1] = right[i];
                    mat[4 * i + 2] = toward[i];
                  }
                  rotateM(mat, mat, droll, zAxis);
                  for (var i = 0; i < 3; ++i) {
                    up[i] = mat[4 * i];
                    right[i] = mat[4 * i + 1];
                  }
                  this.up.set(t, up[0], up[1], up[2]);
                  this.right.set(t, right[0], right[1], right[2]);
                }
              };
              proto.pan = function(t, dx, dy, dz) {
                dx = dx || 0;
                dy = dy || 0;
                dz = dz || 0;
                this.recalcMatrix(t);
                var mat = this.computedMatrix;
                var dist = Math.exp(this.computedRadius[0]);
                var ux = mat[1];
                var uy = mat[5];
                var uz = mat[9];
                var ul = len3(ux, uy, uz);
                ux /= ul;
                uy /= ul;
                uz /= ul;
                var rx = mat[0];
                var ry = mat[4];
                var rz = mat[8];
                var ru = rx * ux + ry * uy + rz * uz;
                rx -= ux * ru;
                ry -= uy * ru;
                rz -= uz * ru;
                var rl = len3(rx, ry, rz);
                rx /= rl;
                ry /= rl;
                rz /= rl;
                var vx = rx * dx + ux * dy;
                var vy = ry * dx + uy * dy;
                var vz = rz * dx + uz * dy;
                this.center.move(t, vx, vy, vz);
                var radius = Math.exp(this.computedRadius[0]);
                radius = Math.max(1e-4, radius + dz);
                this.radius.set(t, Math.log(radius));
              };
              proto.translate = function(t, dx, dy, dz) {
                this.center.move(
                  t,
                  dx || 0,
                  dy || 0,
                  dz || 0
                );
              };
              proto.setMatrix = function(t, mat, axes, noSnap) {
                var ushift = 1;
                if (typeof axes === "number") {
                  ushift = axes | 0;
                }
                if (ushift < 0 || ushift > 3) {
                  ushift = 1;
                }
                var vshift = (ushift + 2) % 3;
                var fshift = (ushift + 1) % 3;
                if (!mat) {
                  this.recalcMatrix(t);
                  mat = this.computedMatrix;
                }
                var ux = mat[ushift];
                var uy = mat[ushift + 4];
                var uz = mat[ushift + 8];
                if (!noSnap) {
                  var ul = len3(ux, uy, uz);
                  ux /= ul;
                  uy /= ul;
                  uz /= ul;
                } else {
                  var ax = Math.abs(ux);
                  var ay = Math.abs(uy);
                  var az = Math.abs(uz);
                  var am = Math.max(ax, ay, az);
                  if (ax === am) {
                    ux = ux < 0 ? -1 : 1;
                    uy = uz = 0;
                  } else if (az === am) {
                    uz = uz < 0 ? -1 : 1;
                    ux = uy = 0;
                  } else {
                    uy = uy < 0 ? -1 : 1;
                    ux = uz = 0;
                  }
                }
                var rx = mat[vshift];
                var ry = mat[vshift + 4];
                var rz = mat[vshift + 8];
                var ru = rx * ux + ry * uy + rz * uz;
                rx -= ux * ru;
                ry -= uy * ru;
                rz -= uz * ru;
                var rl = len3(rx, ry, rz);
                rx /= rl;
                ry /= rl;
                rz /= rl;
                var fx = uy * rz - uz * ry;
                var fy = uz * rx - ux * rz;
                var fz = ux * ry - uy * rx;
                var fl = len3(fx, fy, fz);
                fx /= fl;
                fy /= fl;
                fz /= fl;
                this.center.jump(t, ex, ey, ez);
                this.radius.idle(t);
                this.up.jump(t, ux, uy, uz);
                this.right.jump(t, rx, ry, rz);
                var phi, theta;
                if (ushift === 2) {
                  var cx = mat[1];
                  var cy = mat[5];
                  var cz = mat[9];
                  var cr = cx * rx + cy * ry + cz * rz;
                  var cf = cx * fx + cy * fy + cz * fz;
                  if (tu < 0) {
                    phi = -Math.PI / 2;
                  } else {
                    phi = Math.PI / 2;
                  }
                  theta = Math.atan2(cf, cr);
                } else {
                  var tx = mat[2];
                  var ty = mat[6];
                  var tz = mat[10];
                  var tu = tx * ux + ty * uy + tz * uz;
                  var tr = tx * rx + ty * ry + tz * rz;
                  var tf = tx * fx + ty * fy + tz * fz;
                  phi = Math.asin(clamp1(tu));
                  theta = Math.atan2(tf, tr);
                }
                this.angle.jump(t, theta, phi);
                this.recalcMatrix(t);
                var dx = mat[2];
                var dy = mat[6];
                var dz = mat[10];
                var imat = this.computedMatrix;
                invert44(imat, mat);
                var w = imat[15];
                var ex = imat[12] / w;
                var ey = imat[13] / w;
                var ez = imat[14] / w;
                var gs = Math.exp(this.computedRadius[0]);
                this.center.jump(t, ex - dx * gs, ey - dy * gs, ez - dz * gs);
              };
              proto.lastT = function() {
                return Math.max(
                  this.center.lastT(),
                  this.up.lastT(),
                  this.right.lastT(),
                  this.radius.lastT(),
                  this.angle.lastT()
                );
              };
              proto.idle = function(t) {
                this.center.idle(t);
                this.up.idle(t);
                this.right.idle(t);
                this.radius.idle(t);
                this.angle.idle(t);
              };
              proto.flush = function(t) {
                this.center.flush(t);
                this.up.flush(t);
                this.right.flush(t);
                this.radius.flush(t);
                this.angle.flush(t);
              };
              proto.setDistance = function(t, d) {
                if (d > 0) {
                  this.radius.set(t, Math.log(d));
                }
              };
              proto.lookAt = function(t, eye, center, up) {
                this.recalcMatrix(t);
                eye = eye || this.computedEye;
                center = center || this.computedCenter;
                up = up || this.computedUp;
                var ux = up[0];
                var uy = up[1];
                var uz = up[2];
                var ul = len3(ux, uy, uz);
                if (ul < 1e-6) {
                  return;
                }
                ux /= ul;
                uy /= ul;
                uz /= ul;
                var tx = eye[0] - center[0];
                var ty = eye[1] - center[1];
                var tz = eye[2] - center[2];
                var tl = len3(tx, ty, tz);
                if (tl < 1e-6) {
                  return;
                }
                tx /= tl;
                ty /= tl;
                tz /= tl;
                var right = this.computedRight;
                var rx = right[0];
                var ry = right[1];
                var rz = right[2];
                var ru = ux * rx + uy * ry + uz * rz;
                rx -= ru * ux;
                ry -= ru * uy;
                rz -= ru * uz;
                var rl = len3(rx, ry, rz);
                if (rl < 0.01) {
                  rx = uy * tz - uz * ty;
                  ry = uz * tx - ux * tz;
                  rz = ux * ty - uy * tx;
                  rl = len3(rx, ry, rz);
                  if (rl < 1e-6) {
                    return;
                  }
                }
                rx /= rl;
                ry /= rl;
                rz /= rl;
                this.up.set(t, ux, uy, uz);
                this.right.set(t, rx, ry, rz);
                this.center.set(t, center[0], center[1], center[2]);
                this.radius.set(t, Math.log(tl));
                var fx = uy * rz - uz * ry;
                var fy = uz * rx - ux * rz;
                var fz = ux * ry - uy * rx;
                var fl = len3(fx, fy, fz);
                fx /= fl;
                fy /= fl;
                fz /= fl;
                var tu = ux * tx + uy * ty + uz * tz;
                var tr = rx * tx + ry * ty + rz * tz;
                var tf = fx * tx + fy * ty + fz * tz;
                var phi = Math.asin(clamp1(tu));
                var theta = Math.atan2(tf, tr);
                var angleState = this.angle._state;
                var lastTheta = angleState[angleState.length - 1];
                var lastPhi = angleState[angleState.length - 2];
                lastTheta = lastTheta % (2 * Math.PI);
                var dp = Math.abs(lastTheta + 2 * Math.PI - theta);
                var d0 = Math.abs(lastTheta - theta);
                var dn = Math.abs(lastTheta - 2 * Math.PI - theta);
                if (dp < d0) {
                  lastTheta += 2 * Math.PI;
                }
                if (dn < d0) {
                  lastTheta -= 2 * Math.PI;
                }
                this.angle.jump(this.angle.lastT(), lastTheta, lastPhi);
                this.angle.set(t, theta, phi);
              };
              function createTurntableController(options) {
                options = options || {};
                var center = options.center || [0, 0, 0];
                var up = options.up || [0, 1, 0];
                var right = options.right || findOrthoPair(up);
                var radius = options.radius || 1;
                var theta = options.theta || 0;
                var phi = options.phi || 0;
                center = [].slice.call(center, 0, 3);
                up = [].slice.call(up, 0, 3);
                normalize3(up, up);
                right = [].slice.call(right, 0, 3);
                normalize3(right, right);
                if ("eye" in options) {
                  var eye = options.eye;
                  var toward = [
                    eye[0] - center[0],
                    eye[1] - center[1],
                    eye[2] - center[2]
                  ];
                  cross(right, toward, up);
                  if (len3(right[0], right[1], right[2]) < 1e-6) {
                    right = findOrthoPair(up);
                  } else {
                    normalize3(right, right);
                  }
                  radius = len3(toward[0], toward[1], toward[2]);
                  var ut = dot3(up, toward) / radius;
                  var rt = dot3(right, toward) / radius;
                  phi = Math.acos(ut);
                  theta = Math.acos(rt);
                }
                radius = Math.log(radius);
                return new TurntableController(
                  options.zoomMin,
                  options.zoomMax,
                  center,
                  up,
                  right,
                  radius,
                  theta,
                  phi
                );
              }
            }
          ),
          /***/
          7319: (
            /***/
            function(__unused_webpack_module, exports2, __webpack_require__2) {
              var glslify = __webpack_require__2(3236);
              var createShader = __webpack_require__2(9405);
              var vertSrc = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvec4 project(vec3 p) {\n  return projection * (view * (model * vec4(p, 1.0)));\n}\n\nvoid main() {\n  vec4 startPoint = project(position);\n  vec4 endPoint   = project(nextPosition);\n\n  vec2 A = startPoint.xy / startPoint.w;\n  vec2 B =   endPoint.xy /   endPoint.w;\n\n  float clipAngle = atan(\n    (B.y - A.y) * screenShape.y,\n    (B.x - A.x) * screenShape.x\n  );\n\n  vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(\n    sin(clipAngle),\n    -cos(clipAngle)\n  ) / screenShape;\n\n  gl_Position = vec4(startPoint.xy + startPoint.w * offset, startPoint.zw);\n\n  worldPosition = position;\n  pixelArcLength = arcLength;\n  fragColor = color;\n}\n"]);
              var forwardFrag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform vec3      clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float     dashScale;\nuniform float     opacity;\n\nvarying vec3    worldPosition;\nvarying float   pixelArcLength;\nvarying vec4    fragColor;\n\nvoid main() {\n  if (\n    outOfRange(clipBounds[0], clipBounds[1], worldPosition) ||\n    fragColor.a * opacity == 0.\n  ) discard;\n\n  float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n  if(dashWeight < 0.5) {\n    discard;\n  }\n  gl_FragColor = fragColor * opacity;\n}\n"]);
              var pickFrag = glslify(["precision highp float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX  1.70141184e38\n#define FLOAT_MIN  1.17549435e-38\n\n// https://github.com/mikolalysenko/glsl-read-float/blob/master/index.glsl\nvec4 packFloat(float v) {\n  float av = abs(v);\n\n  //Handle special cases\n  if(av < FLOAT_MIN) {\n    return vec4(0.0, 0.0, 0.0, 0.0);\n  } else if(v > FLOAT_MAX) {\n    return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n  } else if(v < -FLOAT_MAX) {\n    return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n  }\n\n  vec4 c = vec4(0,0,0,0);\n\n  //Compute exponent and mantissa\n  float e = floor(log2(av));\n  float m = av * pow(2.0, -e) - 1.0;\n\n  //Unpack mantissa\n  c[1] = floor(128.0 * m);\n  m -= c[1] / 128.0;\n  c[2] = floor(32768.0 * m);\n  m -= c[2] / 32768.0;\n  c[3] = floor(8388608.0 * m);\n\n  //Unpack exponent\n  float ebias = e + 127.0;\n  c[0] = floor(ebias / 2.0);\n  ebias -= c[0] * 2.0;\n  c[1] += floor(ebias) * 128.0;\n\n  //Unpack sign bit\n  c[0] += 128.0 * step(0.0, -v);\n\n  //Scale back to range\n  return c / 255.0;\n}\n\nbool outOfRange(float a, float b, float p) {\n  return ((p > max(a, b)) || \n          (p < min(a, b)));\n}\n\nbool outOfRange(vec2 a, vec2 b, vec2 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y));\n}\n\nbool outOfRange(vec3 a, vec3 b, vec3 p) {\n  return (outOfRange(a.x, b.x, p.x) ||\n          outOfRange(a.y, b.y, p.y) ||\n          outOfRange(a.z, b.z, p.z));\n}\n\nbool outOfRange(vec4 a, vec4 b, vec4 p) {\n  return outOfRange(a.xyz, b.xyz, p.xyz);\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n  if (outOfRange(clipBounds[0], clipBounds[1], worldPosition)) discard;\n\n  gl_FragColor = vec4(pickId/255.0, packFloat(pixelArcLength).xyz);\n}"]);
              var ATTRIBUTES = [
                { name: "position", type: "vec3" },
                { name: "nextPosition", type: "vec3" },
                { name: "arcLength", type: "float" },
                { name: "lineWidth", type: "float" },
                { name: "color", type: "vec4" }
              ];
              exports2.createShader = function(gl2) {
                return createShader(gl2, vertSrc, forwardFrag, null, ATTRIBUTES);
              };
              exports2.createPickShader = function(gl2) {
                return createShader(gl2, vertSrc, pickFrag, null, ATTRIBUTES);
              };
            }
          ),
          /***/
          7352: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var convexHull1d = __webpack_require__2(5721);
              var convexHull2d = __webpack_require__2(4750);
              var convexHullnd = __webpack_require__2(2690);
              module2.exports = convexHull;
              function convexHull(points) {
                var n = points.length;
                if (n === 0) {
                  return [];
                } else if (n === 1) {
                  return [[0]];
                }
                var d = points[0].length;
                if (d === 0) {
                  return [];
                } else if (d === 1) {
                  return convexHull1d(points);
                } else if (d === 2) {
                  return convexHull2d(points);
                }
                return convexHullnd(points, d);
              }
            }
          ),
          /***/
          7399: (
            /***/
            function(module2) {
              module2.exports = fromQuat;
              function fromQuat(out, q) {
                var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, yx = y * x2, yy = y * y2, zx = z * x2, zy = z * y2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
                out[0] = 1 - yy - zz;
                out[1] = yx + wz;
                out[2] = zx - wy;
                out[3] = 0;
                out[4] = yx - wz;
                out[5] = 1 - xx - zz;
                out[6] = zy + wx;
                out[7] = 0;
                out[8] = zx + wy;
                out[9] = zy - wx;
                out[10] = 1 - xx - yy;
                out[11] = 0;
                out[12] = 0;
                out[13] = 0;
                out[14] = 0;
                out[15] = 1;
                return out;
              }
              ;
            }
          ),
          /***/
          7417: (
            /***/
            function(module2) {
              module2.exports = max;
              function max(out, a, b) {
                out[0] = Math.max(a[0], b[0]);
                out[1] = Math.max(a[1], b[1]);
                out[2] = Math.max(a[2], b[2]);
                return out;
              }
            }
          ),
          /***/
          7442: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var lerp = __webpack_require__2(6658);
              var recompose = __webpack_require__2(7182);
              var decompose = __webpack_require__2(2652);
              var determinant = __webpack_require__2(9921);
              var slerp = __webpack_require__2(8648);
              var state0 = state();
              var state1 = state();
              var tmp = state();
              module2.exports = interpolate;
              function interpolate(out, start, end, alpha) {
                if (determinant(start) === 0 || determinant(end) === 0)
                  return false;
                var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion);
                var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion);
                if (!r0 || !r1)
                  return false;
                lerp(tmp.translate, state0.translate, state1.translate, alpha);
                lerp(tmp.skew, state0.skew, state1.skew, alpha);
                lerp(tmp.scale, state0.scale, state1.scale, alpha);
                lerp(tmp.perspective, state0.perspective, state1.perspective, alpha);
                slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha);
                recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion);
                return true;
              }
              function state() {
                return {
                  translate: vec3(),
                  scale: vec3(1),
                  skew: vec3(),
                  perspective: vec4(),
                  quaternion: vec4()
                };
              }
              function vec3(n) {
                return [n || 0, n || 0, n || 0];
              }
              function vec4() {
                return [0, 0, 0, 1];
              }
            }
          ),
          /***/
          7507: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              exports2.byteLength = byteLength;
              exports2.toByteArray = toByteArray;
              exports2.fromByteArray = fromByteArray;
              var lookup = [];
              var revLookup = [];
              var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
              var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
              for (var i = 0, len = code.length; i < len; ++i) {
                lookup[i] = code[i];
                revLookup[code.charCodeAt(i)] = i;
              }
              revLookup["-".charCodeAt(0)] = 62;
              revLookup["_".charCodeAt(0)] = 63;
              function getLens(b64) {
                var len2 = b64.length;
                if (len2 % 4 > 0) {
                  throw new Error("Invalid string. Length must be a multiple of 4");
                }
                var validLen = b64.indexOf("=");
                if (validLen === -1) validLen = len2;
                var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
                return [validLen, placeHoldersLen];
              }
              function byteLength(b64) {
                var lens = getLens(b64);
                var validLen = lens[0];
                var placeHoldersLen = lens[1];
                return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
              }
              function _byteLength(b64, validLen, placeHoldersLen) {
                return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
              }
              function toByteArray(b64) {
                var tmp;
                var lens = getLens(b64);
                var validLen = lens[0];
                var placeHoldersLen = lens[1];
                var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
                var curByte = 0;
                var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
                var i2;
                for (i2 = 0; i2 < len2; i2 += 4) {
                  tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
                  arr[curByte++] = tmp >> 16 & 255;
                  arr[curByte++] = tmp >> 8 & 255;
                  arr[curByte++] = tmp & 255;
                }
                if (placeHoldersLen === 2) {
                  tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
                  arr[curByte++] = tmp & 255;
                }
                if (placeHoldersLen === 1) {
                  tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
                  arr[curByte++] = tmp >> 8 & 255;
                  arr[curByte++] = tmp & 255;
                }
                return arr;
              }
              function tripletToBase64(num) {
                return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
              }
              function encodeChunk(uint8, start, end) {
                var tmp;
                var output = [];
                for (var i2 = start; i2 < end; i2 += 3) {
                  tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
                  output.push(tripletToBase64(tmp));
                }
                return output.join("");
              }
              function fromByteArray(uint8) {
                var tmp;
                var len2 = uint8.length;
                var extraBytes = len2 % 3;
                var parts = [];
                var maxChunkLength = 16383;
                for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
                  parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
                }
                if (extraBytes === 1) {
                  tmp = uint8[len2 - 1];
                  parts.push(
                    lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
                  );
                } else if (extraBytes === 2) {
                  tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
                  parts.push(
                    lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
                  );
                }
                return parts.join("");
              }
            }
          ),
          /***/
          7518: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bindAttribs = __webpack_require__2(1433);
              function VertexAttribute(location2, dimension, a, b, c, d) {
                this.location = location2;
                this.dimension = dimension;
                this.a = a;
                this.b = b;
                this.c = c;
                this.d = d;
              }
              VertexAttribute.prototype.bind = function(gl2) {
                switch (this.dimension) {
                  case 1:
                    gl2.vertexAttrib1f(this.location, this.a);
                    break;
                  case 2:
                    gl2.vertexAttrib2f(this.location, this.a, this.b);
                    break;
                  case 3:
                    gl2.vertexAttrib3f(this.location, this.a, this.b, this.c);
                    break;
                  case 4:
                    gl2.vertexAttrib4f(this.location, this.a, this.b, this.c, this.d);
                    break;
                }
              };
              function VAONative(gl2, ext, handle) {
                this.gl = gl2;
                this._ext = ext;
                this.handle = handle;
                this._attribs = [];
                this._useElements = false;
                this._elementsType = gl2.UNSIGNED_SHORT;
              }
              VAONative.prototype.bind = function() {
                this._ext.bindVertexArrayOES(this.handle);
                for (var i = 0; i < this._attribs.length; ++i) {
                  this._attribs[i].bind(this.gl);
                }
              };
              VAONative.prototype.unbind = function() {
                this._ext.bindVertexArrayOES(null);
              };
              VAONative.prototype.dispose = function() {
                this._ext.deleteVertexArrayOES(this.handle);
              };
              VAONative.prototype.update = function(attributes, elements, elementsType) {
                this.bind();
                bindAttribs(this.gl, elements, attributes);
                this.unbind();
                this._attribs.length = 0;
                if (attributes)
                  for (var i = 0; i < attributes.length; ++i) {
                    var a = attributes[i];
                    if (typeof a === "number") {
                      this._attribs.push(new VertexAttribute(i, 1, a));
                    } else if (Array.isArray(a)) {
                      this._attribs.push(new VertexAttribute(i, a.length, a[0], a[1], a[2], a[3]));
                    }
                  }
                this._useElements = !!elements;
                this._elementsType = elementsType || this.gl.UNSIGNED_SHORT;
              };
              VAONative.prototype.draw = function(mode, count, offset) {
                offset = offset || 0;
                var gl2 = this.gl;
                if (this._useElements) {
                  gl2.drawElements(mode, count, this._elementsType, offset);
                } else {
                  gl2.drawArrays(mode, offset, count);
                }
              };
              function createVAONative(gl2, ext) {
                return new VAONative(gl2, ext, ext.createVertexArrayOES());
              }
              module2.exports = createVAONative;
            }
          ),
          /***/
          7520: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var isBrowser = __webpack_require__2(9507);
              function detect() {
                var supported = false;
                try {
                  var opts = Object.defineProperty({}, "passive", {
                    get: function() {
                      supported = true;
                    }
                  });
                  window.addEventListener("test", null, opts);
                  window.removeEventListener("test", null, opts);
                } catch (e) {
                  supported = false;
                }
                return supported;
              }
              module2.exports = isBrowser && detect();
            }
          ),
          /***/
          7536: (
            /***/
            function(module2) {
              module2.exports = create;
              function create() {
                var out = new Float32Array(4);
                out[0] = 0;
                out[1] = 0;
                out[2] = 0;
                out[3] = 0;
                return out;
              }
            }
          ),
          /***/
          7608: (
            /***/
            function(module2) {
              module2.exports = invert;
              function invert(out, a) {
                var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
                if (!det) {
                  return null;
                }
                det = 1 / det;
                out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
                out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
                out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
                out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
                out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
                out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
                out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
                out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
                out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
                out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
                out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
                out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
                out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
                out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
                out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
                out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
                return out;
              }
              ;
            }
          ),
          /***/
          7626: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var barycentric = __webpack_require__2(2642);
              var closestPointToTriangle = __webpack_require__2(9346);
              module2.exports = closestPointToPickLocation;
              function xformMatrix(m, v) {
                var out = [0, 0, 0, 0];
                for (var i = 0; i < 4; ++i) {
                  for (var j = 0; j < 4; ++j) {
                    out[j] += m[4 * i + j] * v[i];
                  }
                }
                return out;
              }
              function projectVertex(v, model, view, projection, resolution) {
                var p = xformMatrix(
                  projection,
                  xformMatrix(
                    view,
                    xformMatrix(model, [v[0], v[1], v[2], 1])
                  )
                );
                for (var i = 0; i < 3; ++i) {
                  p[i] /= p[3];
                }
                return [0.5 * resolution[0] * (1 + p[0]), 0.5 * resolution[1] * (1 - p[1])];
              }
              function barycentricCoord(simplex, point) {
                if (simplex.length === 2) {
                  var d0 = 0;
                  var d1 = 0;
                  for (var i = 0; i < 2; ++i) {
                    d0 += Math.pow(point[i] - simplex[0][i], 2);
                    d1 += Math.pow(point[i] - simplex[1][i], 2);
                  }
                  d0 = Math.sqrt(d0);
                  d1 = Math.sqrt(d1);
                  if (d0 + d1 < 1e-6) {
                    return [1, 0];
                  }
                  return [d1 / (d0 + d1), d0 / (d1 + d0)];
                } else if (simplex.length === 3) {
                  var closestPoint = [0, 0];
                  closestPointToTriangle(simplex[0], simplex[1], simplex[2], point, closestPoint);
                  return barycentric(simplex, closestPoint);
                }
                return [];
              }
              function interpolate(simplex, weights) {
                var result = [0, 0, 0];
                for (var i = 0; i < simplex.length; ++i) {
                  var p = simplex[i];
                  var w = weights[i];
                  for (var j = 0; j < 3; ++j) {
                    result[j] += w * p[j];
                  }
                }
                return result;
              }
              function closestPointToPickLocation(simplex, pixelCoord, model, view, projection, resolution) {
                if (simplex.length === 1) {
                  return [0, simplex[0].slice()];
                }
                var simplex2D = new Array(simplex.length);
                for (var i = 0; i < simplex.length; ++i) {
                  simplex2D[i] = projectVertex(simplex[i], model, view, projection, resolution);
                }
                var closestIndex = 0;
                var closestDist = Infinity;
                for (var i = 0; i < simplex2D.length; ++i) {
                  var d2 = 0;
                  for (var j = 0; j < 2; ++j) {
                    d2 += Math.pow(simplex2D[i][j] - pixelCoord[j], 2);
                  }
                  if (d2 < closestDist) {
                    closestDist = d2;
                    closestIndex = i;
                  }
                }
                var weights = barycentricCoord(simplex2D, pixelCoord);
                var s = 0;
                for (var i = 0; i < 3; ++i) {
                  if (weights[i] < -1e-3 || weights[i] > 1.0001) {
                    return null;
                  }
                  s += weights[i];
                }
                if (Math.abs(s - 1) > 1e-3) {
                  return null;
                }
                return [closestIndex, interpolate(simplex, weights), weights];
              }
            }
          ),
          /***/
          7636: (
            /***/
            function(module2) {
              module2.exports = random;
              function random(out, scale) {
                scale = scale || 1;
                var r = Math.random() * 2 * Math.PI;
                var z = Math.random() * 2 - 1;
                var zScale = Math.sqrt(1 - z * z) * scale;
                out[0] = Math.cos(r) * zScale;
                out[1] = Math.sin(r) * zScale;
                out[2] = z * scale;
                return out;
              }
            }
          ),
          /***/
          7640: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var pool = __webpack_require__2(1888);
              function getMallocFree(dtype) {
                switch (dtype) {
                  case "uint32":
                    return [pool.mallocUint32, pool.freeUint32];
                  default:
                    return null;
                }
              }
              var CACHED_insertionSort = {
                "uint32,1,0": function(malloc, free) {
                  return function ndarrayInsertionSort1d0uint32(left, right, data, offset, s0, s1, n0, n1, d1, e1, f1) {
                    var i, j, cptr, ptr = left * s0 + offset, i1, scratch = malloc(n1), dptr, sptr, a, b;
                    for (i = left + 1; i <= right; ++i) {
                      j = i;
                      ptr += s0;
                      cptr = ptr;
                      dptr = 0;
                      sptr = ptr;
                      for (i1 = 0; i1 < n1; ++i1) {
                        scratch[dptr++] = data[sptr];
                        sptr += d1;
                      }
                      __g: while (j-- > left) {
                        dptr = 0;
                        sptr = cptr - s0;
                        __l: for (i1 = 0; i1 < n1; ++i1) {
                          a = data[sptr];
                          b = scratch[dptr];
                          if (a < b) {
                            break __g;
                          }
                          if (a > b) {
                            break __l;
                          }
                          sptr += e1;
                          dptr += f1;
                        }
                        dptr = cptr;
                        sptr = cptr - s0;
                        for (i1 = 0; i1 < n1; ++i1) {
                          data[dptr] = data[sptr];
                          dptr += d1;
                          sptr += d1;
                        }
                        cptr -= s0;
                      }
                      dptr = cptr;
                      sptr = 0;
                      for (i1 = 0; i1 < n1; ++i1) {
                        data[dptr] = scratch[sptr++];
                        dptr += d1;
                      }
                    }
                    free(scratch);
                  };
                }
              };
              function createInsertionSort(order, dtype) {
                var allocator = getMallocFree(dtype);
                var key = [dtype, order].join(",");
                var result = CACHED_insertionSort[key];
                if (allocator) {
                  return result(allocator[0], allocator[1]);
                } else {
                  return result();
                }
              }
              var CACHED_quickSort = {
                "uint32,1,0": function(insertionSort, malloc, free) {
                  return function ndarrayQuickSort1d0uint32(left, right, data, offset, s0, s1, n0, n1, d1, e1, f1) {
                    var sixth = (right - left + 1) / 6 | 0, index1 = left + sixth, index5 = right - sixth, index3 = left + right >> 1, index2 = index3 - sixth, index4 = index3 + sixth, el1 = index1, el2 = index2, el3 = index3, el4 = index4, el5 = index5, less = left + 1, great = right - 1, pivots_are_equal = true, tmp, tmp0, x, y, z, k, ptr0, ptr1, ptr2, comp_pivot1 = 0, comp_pivot2 = 0, comp = 0, i1, b_ptr0, b_ptr1, b_ptr2, b_ptr3, b_ptr4, b_ptr5, b_ptr6, b_ptr7, ptr3, ptr4, ptr5, ptr6, ptr7, pivot_ptr, ptr_shift, elementSize = n1, pivot1 = malloc(elementSize), pivot2 = malloc(elementSize);
                    b_ptr0 = s0 * el1;
                    b_ptr1 = s0 * el2;
                    ptr_shift = offset;
                    __l1: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el1;
                        el1 = el2;
                        el2 = tmp0;
                        break __l1;
                      }
                      if (comp < 0) {
                        break __l1;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el4;
                    b_ptr1 = s0 * el5;
                    ptr_shift = offset;
                    __l2: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el4;
                        el4 = el5;
                        el5 = tmp0;
                        break __l2;
                      }
                      if (comp < 0) {
                        break __l2;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el1;
                    b_ptr1 = s0 * el3;
                    ptr_shift = offset;
                    __l3: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el1;
                        el1 = el3;
                        el3 = tmp0;
                        break __l3;
                      }
                      if (comp < 0) {
                        break __l3;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el2;
                    b_ptr1 = s0 * el3;
                    ptr_shift = offset;
                    __l4: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el2;
                        el2 = el3;
                        el3 = tmp0;
                        break __l4;
                      }
                      if (comp < 0) {
                        break __l4;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el1;
                    b_ptr1 = s0 * el4;
                    ptr_shift = offset;
                    __l5: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el1;
                        el1 = el4;
                        el4 = tmp0;
                        break __l5;
                      }
                      if (comp < 0) {
                        break __l5;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el3;
                    b_ptr1 = s0 * el4;
                    ptr_shift = offset;
                    __l6: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el3;
                        el3 = el4;
                        el4 = tmp0;
                        break __l6;
                      }
                      if (comp < 0) {
                        break __l6;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el2;
                    b_ptr1 = s0 * el5;
                    ptr_shift = offset;
                    __l7: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el2;
                        el2 = el5;
                        el5 = tmp0;
                        break __l7;
                      }
                      if (comp < 0) {
                        break __l7;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el2;
                    b_ptr1 = s0 * el3;
                    ptr_shift = offset;
                    __l8: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el2;
                        el2 = el3;
                        el3 = tmp0;
                        break __l8;
                      }
                      if (comp < 0) {
                        break __l8;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el4;
                    b_ptr1 = s0 * el5;
                    ptr_shift = offset;
                    __l9: for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      comp = data[ptr0] - data[ptr1];
                      if (comp > 0) {
                        tmp0 = el4;
                        el4 = el5;
                        el5 = tmp0;
                        break __l9;
                      }
                      if (comp < 0) {
                        break __l9;
                      }
                      ptr_shift += e1;
                    }
                    b_ptr0 = s0 * el1;
                    b_ptr1 = s0 * el2;
                    b_ptr2 = s0 * el3;
                    b_ptr3 = s0 * el4;
                    b_ptr4 = s0 * el5;
                    b_ptr5 = s0 * index1;
                    b_ptr6 = s0 * index3;
                    b_ptr7 = s0 * index5;
                    pivot_ptr = 0;
                    ptr_shift = offset;
                    for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      ptr2 = b_ptr2 + ptr_shift;
                      ptr3 = b_ptr3 + ptr_shift;
                      ptr4 = b_ptr4 + ptr_shift;
                      ptr5 = b_ptr5 + ptr_shift;
                      ptr6 = b_ptr6 + ptr_shift;
                      ptr7 = b_ptr7 + ptr_shift;
                      pivot1[pivot_ptr] = data[ptr1];
                      pivot2[pivot_ptr] = data[ptr3];
                      pivots_are_equal = pivots_are_equal && pivot1[pivot_ptr] === pivot2[pivot_ptr];
                      x = data[ptr0];
                      y = data[ptr2];
                      z = data[ptr4];
                      data[ptr5] = x;
                      data[ptr6] = y;
                      data[ptr7] = z;
                      ++pivot_ptr;
                      ptr_shift += d1;
                    }
                    b_ptr0 = s0 * index2;
                    b_ptr1 = s0 * left;
                    ptr_shift = offset;
                    for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      data[ptr0] = data[ptr1];
                      ptr_shift += d1;
                    }
                    b_ptr0 = s0 * index4;
                    b_ptr1 = s0 * right;
                    ptr_shift = offset;
                    for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      data[ptr0] = data[ptr1];
                      ptr_shift += d1;
                    }
                    if (pivots_are_equal) {
                      for (k = less; k <= great; ++k) {
                        ptr0 = offset + k * s0;
                        pivot_ptr = 0;
                        __l10: for (i1 = 0; i1 < n1; ++i1) {
                          comp = data[ptr0] - pivot1[pivot_ptr];
                          if (comp !== 0) {
                            break __l10;
                          }
                          pivot_ptr += f1;
                          ptr0 += e1;
                        }
                        if (comp === 0) {
                          continue;
                        }
                        if (comp < 0) {
                          if (k !== less) {
                            b_ptr0 = s0 * k;
                            b_ptr1 = s0 * less;
                            ptr_shift = offset;
                            for (i1 = 0; i1 < n1; ++i1) {
                              ptr0 = b_ptr0 + ptr_shift;
                              ptr1 = b_ptr1 + ptr_shift;
                              tmp = data[ptr0];
                              data[ptr0] = data[ptr1];
                              data[ptr1] = tmp;
                              ptr_shift += d1;
                            }
                          }
                          ++less;
                        } else {
                          while (true) {
                            ptr0 = offset + great * s0;
                            pivot_ptr = 0;
                            __l11: for (i1 = 0; i1 < n1; ++i1) {
                              comp = data[ptr0] - pivot1[pivot_ptr];
                              if (comp !== 0) {
                                break __l11;
                              }
                              pivot_ptr += f1;
                              ptr0 += e1;
                            }
                            if (comp > 0) {
                              great--;
                            } else if (comp < 0) {
                              b_ptr0 = s0 * k;
                              b_ptr1 = s0 * less;
                              b_ptr2 = s0 * great;
                              ptr_shift = offset;
                              for (i1 = 0; i1 < n1; ++i1) {
                                ptr0 = b_ptr0 + ptr_shift;
                                ptr1 = b_ptr1 + ptr_shift;
                                ptr2 = b_ptr2 + ptr_shift;
                                tmp = data[ptr0];
                                data[ptr0] = data[ptr1];
                                data[ptr1] = data[ptr2];
                                data[ptr2] = tmp;
                                ptr_shift += d1;
                              }
                              ++less;
                              --great;
                              break;
                            } else {
                              b_ptr0 = s0 * k;
                              b_ptr1 = s0 * great;
                              ptr_shift = offset;
                              for (i1 = 0; i1 < n1; ++i1) {
                                ptr0 = b_ptr0 + ptr_shift;
                                ptr1 = b_ptr1 + ptr_shift;
                                tmp = data[ptr0];
                                data[ptr0] = data[ptr1];
                                data[ptr1] = tmp;
                                ptr_shift += d1;
                              }
                              --great;
                              break;
                            }
                          }
                        }
                      }
                    } else {
                      for (k = less; k <= great; ++k) {
                        ptr0 = offset + k * s0;
                        pivot_ptr = 0;
                        __l12: for (i1 = 0; i1 < n1; ++i1) {
                          comp_pivot1 = data[ptr0] - pivot1[pivot_ptr];
                          if (comp_pivot1 !== 0) {
                            break __l12;
                          }
                          pivot_ptr += f1;
                          ptr0 += e1;
                        }
                        if (comp_pivot1 < 0) {
                          if (k !== less) {
                            b_ptr0 = s0 * k;
                            b_ptr1 = s0 * less;
                            ptr_shift = offset;
                            for (i1 = 0; i1 < n1; ++i1) {
                              ptr0 = b_ptr0 + ptr_shift;
                              ptr1 = b_ptr1 + ptr_shift;
                              tmp = data[ptr0];
                              data[ptr0] = data[ptr1];
                              data[ptr1] = tmp;
                              ptr_shift += d1;
                            }
                          }
                          ++less;
                        } else {
                          ptr0 = offset + k * s0;
                          pivot_ptr = 0;
                          __l13: for (i1 = 0; i1 < n1; ++i1) {
                            comp_pivot2 = data[ptr0] - pivot2[pivot_ptr];
                            if (comp_pivot2 !== 0) {
                              break __l13;
                            }
                            pivot_ptr += f1;
                            ptr0 += e1;
                          }
                          if (comp_pivot2 > 0) {
                            while (true) {
                              ptr0 = offset + great * s0;
                              pivot_ptr = 0;
                              __l14: for (i1 = 0; i1 < n1; ++i1) {
                                comp = data[ptr0] - pivot2[pivot_ptr];
                                if (comp !== 0) {
                                  break __l14;
                                }
                                pivot_ptr += f1;
                                ptr0 += e1;
                              }
                              if (comp > 0) {
                                if (--great < k) {
                                  break;
                                }
                                continue;
                              } else {
                                ptr0 = offset + great * s0;
                                pivot_ptr = 0;
                                __l15: for (i1 = 0; i1 < n1; ++i1) {
                                  comp = data[ptr0] - pivot1[pivot_ptr];
                                  if (comp !== 0) {
                                    break __l15;
                                  }
                                  pivot_ptr += f1;
                                  ptr0 += e1;
                                }
                                if (comp < 0) {
                                  b_ptr0 = s0 * k;
                                  b_ptr1 = s0 * less;
                                  b_ptr2 = s0 * great;
                                  ptr_shift = offset;
                                  for (i1 = 0; i1 < n1; ++i1) {
                                    ptr0 = b_ptr0 + ptr_shift;
                                    ptr1 = b_ptr1 + ptr_shift;
                                    ptr2 = b_ptr2 + ptr_shift;
                                    tmp = data[ptr0];
                                    data[ptr0] = data[ptr1];
                                    data[ptr1] = data[ptr2];
                                    data[ptr2] = tmp;
                                    ptr_shift += d1;
                                  }
                                  ++less;
                                  --great;
                                } else {
                                  b_ptr0 = s0 * k;
                                  b_ptr1 = s0 * great;
                                  ptr_shift = offset;
                                  for (i1 = 0; i1 < n1; ++i1) {
                                    ptr0 = b_ptr0 + ptr_shift;
                                    ptr1 = b_ptr1 + ptr_shift;
                                    tmp = data[ptr0];
                                    data[ptr0] = data[ptr1];
                                    data[ptr1] = tmp;
                                    ptr_shift += d1;
                                  }
                                  --great;
                                }
                                break;
                              }
                            }
                          }
                        }
                      }
                    }
                    b_ptr0 = s0 * left;
                    b_ptr1 = s0 * (less - 1);
                    pivot_ptr = 0;
                    ptr_shift = offset;
                    for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      data[ptr0] = data[ptr1];
                      data[ptr1] = pivot1[pivot_ptr];
                      ++pivot_ptr;
                      ptr_shift += d1;
                    }
                    b_ptr0 = s0 * right;
                    b_ptr1 = s0 * (great + 1);
                    pivot_ptr = 0;
                    ptr_shift = offset;
                    for (i1 = 0; i1 < n1; ++i1) {
                      ptr0 = b_ptr0 + ptr_shift;
                      ptr1 = b_ptr1 + ptr_shift;
                      data[ptr0] = data[ptr1];
                      data[ptr1] = pivot2[pivot_ptr];
                      ++pivot_ptr;
                      ptr_shift += d1;
                    }
                    if (less - 2 - left <= 32) {
                      insertionSort(left, less - 2, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    } else {
                      ndarrayQuickSort1d0uint32(left, less - 2, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    }
                    if (right - (great + 2) <= 32) {
                      insertionSort(great + 2, right, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    } else {
                      ndarrayQuickSort1d0uint32(great + 2, right, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    }
                    if (pivots_are_equal) {
                      free(pivot1);
                      free(pivot2);
                      return;
                    }
                    if (less < index1 && great > index5) {
                      __l16: while (true) {
                        ptr0 = offset + less * s0;
                        pivot_ptr = 0;
                        ptr_shift = offset;
                        for (i1 = 0; i1 < n1; ++i1) {
                          if (data[ptr0] !== pivot1[pivot_ptr]) {
                            break __l16;
                          }
                          ++pivot_ptr;
                          ptr0 += d1;
                        }
                        ++less;
                      }
                      __l17: while (true) {
                        ptr0 = offset + great * s0;
                        pivot_ptr = 0;
                        ptr_shift = offset;
                        for (i1 = 0; i1 < n1; ++i1) {
                          if (data[ptr0] !== pivot2[pivot_ptr]) {
                            break __l17;
                          }
                          ++pivot_ptr;
                          ptr0 += d1;
                        }
                        --great;
                      }
                      for (k = less; k <= great; ++k) {
                        ptr0 = offset + k * s0;
                        pivot_ptr = 0;
                        __l18: for (i1 = 0; i1 < n1; ++i1) {
                          comp_pivot1 = data[ptr0] - pivot1[pivot_ptr];
                          if (comp_pivot1 !== 0) {
                            break __l18;
                          }
                          pivot_ptr += f1;
                          ptr0 += e1;
                        }
                        if (comp_pivot1 === 0) {
                          if (k !== less) {
                            b_ptr0 = s0 * k;
                            b_ptr1 = s0 * less;
                            ptr_shift = offset;
                            for (i1 = 0; i1 < n1; ++i1) {
                              ptr0 = b_ptr0 + ptr_shift;
                              ptr1 = b_ptr1 + ptr_shift;
                              tmp = data[ptr0];
                              data[ptr0] = data[ptr1];
                              data[ptr1] = tmp;
                              ptr_shift += d1;
                            }
                          }
                          ++less;
                        } else {
                          ptr0 = offset + k * s0;
                          pivot_ptr = 0;
                          __l19: for (i1 = 0; i1 < n1; ++i1) {
                            comp_pivot2 = data[ptr0] - pivot2[pivot_ptr];
                            if (comp_pivot2 !== 0) {
                              break __l19;
                            }
                            pivot_ptr += f1;
                            ptr0 += e1;
                          }
                          if (comp_pivot2 === 0) {
                            while (true) {
                              ptr0 = offset + great * s0;
                              pivot_ptr = 0;
                              __l20: for (i1 = 0; i1 < n1; ++i1) {
                                comp = data[ptr0] - pivot2[pivot_ptr];
                                if (comp !== 0) {
                                  break __l20;
                                }
                                pivot_ptr += f1;
                                ptr0 += e1;
                              }
                              if (comp === 0) {
                                if (--great < k) {
                                  break;
                                }
                                continue;
                              } else {
                                ptr0 = offset + great * s0;
                                pivot_ptr = 0;
                                __l21: for (i1 = 0; i1 < n1; ++i1) {
                                  comp = data[ptr0] - pivot1[pivot_ptr];
                                  if (comp !== 0) {
                                    break __l21;
                                  }
                                  pivot_ptr += f1;
                                  ptr0 += e1;
                                }
                                if (comp < 0) {
                                  b_ptr0 = s0 * k;
                                  b_ptr1 = s0 * less;
                                  b_ptr2 = s0 * great;
                                  ptr_shift = offset;
                                  for (i1 = 0; i1 < n1; ++i1) {
                                    ptr0 = b_ptr0 + ptr_shift;
                                    ptr1 = b_ptr1 + ptr_shift;
                                    ptr2 = b_ptr2 + ptr_shift;
                                    tmp = data[ptr0];
                                    data[ptr0] = data[ptr1];
                                    data[ptr1] = data[ptr2];
                                    data[ptr2] = tmp;
                                    ptr_shift += d1;
                                  }
                                  ++less;
                                  --great;
                                } else {
                                  b_ptr0 = s0 * k;
                                  b_ptr1 = s0 * great;
                                  ptr_shift = offset;
                                  for (i1 = 0; i1 < n1; ++i1) {
                                    ptr0 = b_ptr0 + ptr_shift;
                                    ptr1 = b_ptr1 + ptr_shift;
                                    tmp = data[ptr0];
                                    data[ptr0] = data[ptr1];
                                    data[ptr1] = tmp;
                                    ptr_shift += d1;
                                  }
                                  --great;
                                }
                                break;
                              }
                            }
                          }
                        }
                      }
                    }
                    free(pivot1);
                    free(pivot2);
                    if (great - less <= 32) {
                      insertionSort(less, great, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    } else {
                      ndarrayQuickSort1d0uint32(less, great, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    }
                  };
                }
              };
              function createQuickSort(order, dtype, insertionSort) {
                var allocator = getMallocFree(dtype);
                var key = [dtype, order].join(",");
                var result = CACHED_quickSort[key];
                if (order.length > 1 && allocator) {
                  return result(insertionSort, allocator[0], allocator[1]);
                } else {
                  return result(insertionSort);
                }
              }
              var CACHED_sort = {
                "uint32,1,0": function(insertionSort, quickSort) {
                  return function(array) {
                    var data = array.data, offset = array.offset | 0, shape = array.shape, stride = array.stride, s0 = stride[0] | 0, n0 = shape[0] | 0, s1 = stride[1] | 0, n1 = shape[1] | 0, d1 = s1, e1 = s1, f1 = 1;
                    if (n0 <= 32) {
                      insertionSort(0, n0 - 1, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    } else {
                      quickSort(0, n0 - 1, data, offset, s0, s1, n0, n1, d1, e1, f1);
                    }
                  };
                }
              };
              function compileSort(order, dtype) {
                var key = [dtype, order].join(",");
                var result = CACHED_sort[key];
                var insertionSort = createInsertionSort(order, dtype);
                var quickSort = createQuickSort(order, dtype, insertionSort);
                return result(insertionSort, quickSort);
              }
              module2.exports = compileSort;
            }
          ),
          /***/
          7642: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var ch = __webpack_require__2(8954);
              var uniq = __webpack_require__2(1682);
              module2.exports = triangulate;
              function LiftedPoint(p, i) {
                this.point = p;
                this.index = i;
              }
              function compareLifted(a, b) {
                var ap = a.point;
                var bp = b.point;
                var d = ap.length;
                for (var i = 0; i < d; ++i) {
                  var s = bp[i] - ap[i];
                  if (s) {
                    return s;
                  }
                }
                return 0;
              }
              function triangulate1D(n, points, includePointAtInfinity) {
                if (n === 1) {
                  if (includePointAtInfinity) {
                    return [[-1, 0]];
                  } else {
                    return [];
                  }
                }
                var lifted = points.map(function(p, i2) {
                  return [p[0], i2];
                });
                lifted.sort(function(a2, b2) {
                  return a2[0] - b2[0];
                });
                var cells = new Array(n - 1);
                for (var i = 1; i < n; ++i) {
                  var a = lifted[i - 1];
                  var b = lifted[i];
                  cells[i - 1] = [a[1], b[1]];
                }
                if (includePointAtInfinity) {
                  cells.push(
                    [-1, cells[0][1]],
                    [cells[n - 1][1], -1]
                  );
                }
                return cells;
              }
              function triangulate(points, includePointAtInfinity) {
                var n = points.length;
                if (n === 0) {
                  return [];
                }
                var d = points[0].length;
                if (d < 1) {
                  return [];
                }
                if (d === 1) {
                  return triangulate1D(n, points, includePointAtInfinity);
                }
                var lifted = new Array(n);
                var upper = 1;
                for (var i = 0; i < n; ++i) {
                  var p = points[i];
                  var x = new Array(d + 1);
                  var l = 0;
                  for (var j = 0; j < d; ++j) {
                    var v = p[j];
                    x[j] = v;
                    l += v * v;
                  }
                  x[d] = l;
                  lifted[i] = new LiftedPoint(x, i);
                  upper = Math.max(l, upper);
                }
                uniq(lifted, compareLifted);
                n = lifted.length;
                var dpoints = new Array(n + d + 1);
                var dindex = new Array(n + d + 1);
                var u = (d + 1) * (d + 1) * upper;
                var y = new Array(d + 1);
                for (var i = 0; i <= d; ++i) {
                  y[i] = 0;
                }
                y[d] = u;
                dpoints[0] = y.slice();
                dindex[0] = -1;
                for (var i = 0; i <= d; ++i) {
                  var x = y.slice();
                  x[i] = 1;
                  dpoints[i + 1] = x;
                  dindex[i + 1] = -1;
                }
                for (var i = 0; i < n; ++i) {
                  var h = lifted[i];
                  dpoints[i + d + 1] = h.point;
                  dindex[i + d + 1] = h.index;
                }
                var hull = ch(dpoints, false);
                if (includePointAtInfinity) {
                  hull = hull.filter(function(cell) {
                    var count = 0;
                    for (var j2 = 0; j2 <= d; ++j2) {
                      var v2 = dindex[cell[j2]];
                      if (v2 < 0) {
                        if (++count >= 2) {
                          return false;
                        }
                      }
                      cell[j2] = v2;
                    }
                    return true;
                  });
                } else {
                  hull = hull.filter(function(cell) {
                    for (var i2 = 0; i2 <= d; ++i2) {
                      var v2 = dindex[cell[i2]];
                      if (v2 < 0) {
                        return false;
                      }
                      cell[i2] = v2;
                    }
                    return true;
                  });
                }
                if (d & 1) {
                  for (var i = 0; i < hull.length; ++i) {
                    var h = hull[i];
                    var x = h[0];
                    h[0] = h[1];
                    h[1] = x;
                  }
                }
                return hull;
              }
            }
          ),
          /***/
          7656: (
            /***/
            function(module2) {
              module2.exports = translate;
              function translate(out, a, v) {
                var x = v[0], y = v[1], z = v[2], a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23;
                if (a === out) {
                  out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
                  out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
                  out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
                  out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
                } else {
                  a00 = a[0];
                  a01 = a[1];
                  a02 = a[2];
                  a03 = a[3];
                  a10 = a[4];
                  a11 = a[5];
                  a12 = a[6];
                  a13 = a[7];
                  a20 = a[8];
                  a21 = a[9];
                  a22 = a[10];
                  a23 = a[11];
                  out[0] = a00;
                  out[1] = a01;
                  out[2] = a02;
                  out[3] = a03;
                  out[4] = a10;
                  out[5] = a11;
                  out[6] = a12;
                  out[7] = a13;
                  out[8] = a20;
                  out[9] = a21;
                  out[10] = a22;
                  out[11] = a23;
                  out[12] = a00 * x + a10 * y + a20 * z + a[12];
                  out[13] = a01 * x + a11 * y + a21 * z + a[13];
                  out[14] = a02 * x + a12 * y + a22 * z + a[14];
                  out[15] = a03 * x + a13 * y + a23 * z + a[15];
                }
                return out;
              }
              ;
            }
          ),
          /***/
          7718: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = vectorizeText;
              module2.exports.processPixels = processPixels;
              var surfaceNets = __webpack_require__2(3711);
              var ndarray = __webpack_require__2(9618);
              var simplify = __webpack_require__2(5878);
              var cleanPSLG = __webpack_require__2(332);
              var cdt2d = __webpack_require__2(2538);
              var toPolygonCrappy = __webpack_require__2(2095);
              var TAG_bold = "b";
              var CHR_bold = "b|";
              var TAG_italic = "i";
              var CHR_italic = "i|";
              var TAG_super = "sup";
              var CHR_super0 = "+";
              var CHR_super = "+1";
              var TAG_sub = "sub";
              var CHR_sub0 = "-";
              var CHR_sub = "-1";
              function parseTag(tag, TAG_CHR, str, map) {
                var opnTag = "<" + tag + ">";
                var clsTag = "</" + tag + ">";
                var nOPN = opnTag.length;
                var nCLS = clsTag.length;
                var isRecursive = TAG_CHR[0] === CHR_super0 || TAG_CHR[0] === CHR_sub0;
                var a = 0;
                var b = -nCLS;
                while (a > -1) {
                  a = str.indexOf(opnTag, a);
                  if (a === -1) break;
                  b = str.indexOf(clsTag, a + nOPN);
                  if (b === -1) break;
                  if (b <= a) break;
                  for (var i = a; i < b + nCLS; ++i) {
                    if (i < a + nOPN || i >= b) {
                      map[i] = null;
                      str = str.substr(0, i) + " " + str.substr(i + 1);
                    } else {
                      if (map[i] !== null) {
                        var pos = map[i].indexOf(TAG_CHR[0]);
                        if (pos === -1) {
                          map[i] += TAG_CHR;
                        } else {
                          if (isRecursive) {
                            map[i] = map[i].substr(0, pos + 1) + (1 + parseInt(map[i][pos + 1])) + map[i].substr(pos + 2);
                          }
                        }
                      }
                    }
                  }
                  var start = a + nOPN;
                  var remainingStr = str.substr(start, b - start);
                  var c = remainingStr.indexOf(opnTag);
                  if (c !== -1) a = c;
                  else a = b + nCLS;
                }
                return map;
              }
              function transformPositions(positions, options, size) {
                var align = options.textAlign || "start";
                var baseline = options.textBaseline || "alphabetic";
                var lo = [1 << 30, 1 << 30];
                var hi = [0, 0];
                var n = positions.length;
                for (var i = 0; i < n; ++i) {
                  var p = positions[i];
                  for (var j = 0; j < 2; ++j) {
                    lo[j] = Math.min(lo[j], p[j]) | 0;
                    hi[j] = Math.max(hi[j], p[j]) | 0;
                  }
                }
                var xShift = 0;
                switch (align) {
                  case "center":
                    xShift = -0.5 * (lo[0] + hi[0]);
                    break;
                  case "right":
                  case "end":
                    xShift = -hi[0];
                    break;
                  case "left":
                  case "start":
                    xShift = -lo[0];
                    break;
                  default:
                    throw new Error("vectorize-text: Unrecognized textAlign: '" + align + "'");
                }
                var yShift = 0;
                switch (baseline) {
                  case "hanging":
                  case "top":
                    yShift = -lo[1];
                    break;
                  case "middle":
                    yShift = -0.5 * (lo[1] + hi[1]);
                    break;
                  case "alphabetic":
                  case "ideographic":
                    yShift = -3 * size;
                    break;
                  case "bottom":
                    yShift = -hi[1];
                    break;
                  default:
                    throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'");
                }
                var scale = 1 / size;
                if ("lineHeight" in options) {
                  scale *= +options.lineHeight;
                } else if ("width" in options) {
                  scale = options.width / (hi[0] - lo[0]);
                } else if ("height" in options) {
                  scale = options.height / (hi[1] - lo[1]);
                }
                return positions.map(function(p2) {
                  return [scale * (p2[0] + xShift), scale * (p2[1] + yShift)];
                });
              }
              function getPixels(canvas, context, rawString, fontSize, lineSpacing, styletags) {
                rawString = rawString.replace(/\n/g, "");
                if (styletags.breaklines === true) {
                  rawString = rawString.replace(/\<br\>/g, "\n");
                } else {
                  rawString = rawString.replace(/\<br\>/g, " ");
                }
                var activeStyle = "";
                var map = [];
                for (j = 0; j < rawString.length; ++j) {
                  map[j] = activeStyle;
                }
                if (styletags.bolds === true) map = parseTag(TAG_bold, CHR_bold, rawString, map);
                if (styletags.italics === true) map = parseTag(TAG_italic, CHR_italic, rawString, map);
                if (styletags.superscripts === true) map = parseTag(TAG_super, CHR_super, rawString, map);
                if (styletags.subscripts === true) map = parseTag(TAG_sub, CHR_sub, rawString, map);
                var allStyles = [];
                var plainText = "";
                for (j = 0; j < rawString.length; ++j) {
                  if (map[j] !== null) {
                    plainText += rawString[j];
                    allStyles.push(map[j]);
                  }
                }
                var allTexts = plainText.split("\n");
                var numberOfLines = allTexts.length;
                var lineHeight = Math.round(lineSpacing * fontSize);
                var offsetX = fontSize;
                var offsetY = fontSize * 2;
                var maxWidth = 0;
                var minHeight = numberOfLines * lineHeight + offsetY;
                if (canvas.height < minHeight) {
                  canvas.height = minHeight;
                }
                context.fillStyle = "#000";
                context.fillRect(0, 0, canvas.width, canvas.height);
                context.fillStyle = "#fff";
                var i, j, xPos, yPos, zPos;
                var nDone = 0;
                var buffer = "";
                function writeBuffer() {
                  if (buffer !== "") {
                    var delta = context.measureText(buffer).width;
                    context.fillText(buffer, offsetX + xPos, offsetY + yPos);
                    xPos += delta;
                  }
                }
                function getTextFontSize() {
                  return "" + Math.round(zPos) + "px ";
                }
                function changeStyle(oldStyle, newStyle) {
                  var ctxFont = "" + context.font;
                  if (styletags.subscripts === true) {
                    var oldIndex_Sub = oldStyle.indexOf(CHR_sub0);
                    var newIndex_Sub = newStyle.indexOf(CHR_sub0);
                    var oldSub = oldIndex_Sub > -1 ? parseInt(oldStyle[1 + oldIndex_Sub]) : 0;
                    var newSub = newIndex_Sub > -1 ? parseInt(newStyle[1 + newIndex_Sub]) : 0;
                    if (oldSub !== newSub) {
                      ctxFont = ctxFont.replace(getTextFontSize(), "?px ");
                      zPos *= Math.pow(0.75, newSub - oldSub);
                      ctxFont = ctxFont.replace("?px ", getTextFontSize());
                    }
                    yPos += 0.25 * lineHeight * (newSub - oldSub);
                  }
                  if (styletags.superscripts === true) {
                    var oldIndex_Super = oldStyle.indexOf(CHR_super0);
                    var newIndex_Super = newStyle.indexOf(CHR_super0);
                    var oldSuper = oldIndex_Super > -1 ? parseInt(oldStyle[1 + oldIndex_Super]) : 0;
                    var newSuper = newIndex_Super > -1 ? parseInt(newStyle[1 + newIndex_Super]) : 0;
                    if (oldSuper !== newSuper) {
                      ctxFont = ctxFont.replace(getTextFontSize(), "?px ");
                      zPos *= Math.pow(0.75, newSuper - oldSuper);
                      ctxFont = ctxFont.replace("?px ", getTextFontSize());
                    }
                    yPos -= 0.25 * lineHeight * (newSuper - oldSuper);
                  }
                  if (styletags.bolds === true) {
                    var wasBold = oldStyle.indexOf(CHR_bold) > -1;
                    var is_Bold = newStyle.indexOf(CHR_bold) > -1;
                    if (!wasBold && is_Bold) {
                      if (wasItalic) {
                        ctxFont = ctxFont.replace("italic ", "italic bold ");
                      } else {
                        ctxFont = "bold " + ctxFont;
                      }
                    }
                    if (wasBold && !is_Bold) {
                      ctxFont = ctxFont.replace("bold ", "");
                    }
                  }
                  if (styletags.italics === true) {
                    var wasItalic = oldStyle.indexOf(CHR_italic) > -1;
                    var is_Italic = newStyle.indexOf(CHR_italic) > -1;
                    if (!wasItalic && is_Italic) {
                      ctxFont = "italic " + ctxFont;
                    }
                    if (wasItalic && !is_Italic) {
                      ctxFont = ctxFont.replace("italic ", "");
                    }
                  }
                  context.font = ctxFont;
                }
                for (i = 0; i < numberOfLines; ++i) {
                  var txt = allTexts[i] + "\n";
                  xPos = 0;
                  yPos = i * lineHeight;
                  zPos = fontSize;
                  buffer = "";
                  for (j = 0; j < txt.length; ++j) {
                    var style = j + nDone < allStyles.length ? allStyles[j + nDone] : allStyles[allStyles.length - 1];
                    if (activeStyle === style) {
                      buffer += txt[j];
                    } else {
                      writeBuffer();
                      buffer = txt[j];
                      if (style !== void 0) {
                        changeStyle(activeStyle, style);
                        activeStyle = style;
                      }
                    }
                  }
                  writeBuffer();
                  nDone += txt.length;
                  var width = Math.round(xPos + 2 * offsetX) | 0;
                  if (maxWidth < width) maxWidth = width;
                }
                var xCut = maxWidth;
                var yCut = offsetY + lineHeight * numberOfLines;
                var pixels = ndarray(context.getImageData(0, 0, xCut, yCut).data, [yCut, xCut, 4]);
                return pixels.pick(-1, -1, 0).transpose(1, 0);
              }
              function getContour(pixels, doSimplify) {
                var contour = surfaceNets(pixels, 128);
                if (doSimplify) {
                  return simplify(contour.cells, contour.positions, 0.25);
                }
                return {
                  edges: contour.cells,
                  positions: contour.positions
                };
              }
              function processPixelsImpl(pixels, options, size, simplify2) {
                var contour = getContour(pixels, simplify2);
                var positions = transformPositions(contour.positions, options, size);
                var edges = contour.edges;
                var flip = "ccw" === options.orientation;
                cleanPSLG(positions, edges);
                if (options.polygons || options.polygon || options.polyline) {
                  var result = toPolygonCrappy(edges, positions);
                  var nresult = new Array(result.length);
                  for (var i = 0; i < result.length; ++i) {
                    var loops = result[i];
                    var nloops = new Array(loops.length);
                    for (var j = 0; j < loops.length; ++j) {
                      var loop = loops[j];
                      var nloop = new Array(loop.length);
                      for (var k = 0; k < loop.length; ++k) {
                        nloop[k] = positions[loop[k]].slice();
                      }
                      if (flip) {
                        nloop.reverse();
                      }
                      nloops[j] = nloop;
                    }
                    nresult[i] = nloops;
                  }
                  return nresult;
                } else if (options.triangles || options.triangulate || options.triangle) {
                  return {
                    cells: cdt2d(positions, edges, {
                      delaunay: false,
                      exterior: false,
                      interior: true
                    }),
                    positions
                  };
                } else {
                  return {
                    edges,
                    positions
                  };
                }
              }
              function processPixels(pixels, options, size) {
                try {
                  return processPixelsImpl(pixels, options, size, true);
                } catch (e) {
                }
                try {
                  return processPixelsImpl(pixels, options, size, false);
                } catch (e) {
                }
                if (options.polygons || options.polyline || options.polygon) {
                  return [];
                }
                if (options.triangles || options.triangulate || options.triangle) {
                  return {
                    cells: [],
                    positions: []
                  };
                }
                return {
                  edges: [],
                  positions: []
                };
              }
              function vectorizeText(str, canvas, context, options) {
                var size = 64;
                var lineSpacing = 1.25;
                var styletags = {
                  breaklines: false,
                  bolds: false,
                  italics: false,
                  subscripts: false,
                  superscripts: false
                };
                if (options) {
                  if (options.size && options.size > 0) size = options.size;
                  if (options.lineSpacing && options.lineSpacing > 0) lineSpacing = options.lineSpacing;
                  if (options.styletags && options.styletags.breaklines) styletags.breaklines = options.styletags.breaklines ? true : false;
                  if (options.styletags && options.styletags.bolds) styletags.bolds = options.styletags.bolds ? true : false;
                  if (options.styletags && options.styletags.italics) styletags.italics = options.styletags.italics ? true : false;
                  if (options.styletags && options.styletags.subscripts) styletags.subscripts = options.styletags.subscripts ? true : false;
                  if (options.styletags && options.styletags.superscripts) styletags.superscripts = options.styletags.superscripts ? true : false;
                }
                context.font = [
                  options.fontStyle,
                  options.fontVariant,
                  options.fontWeight,
                  size + "px",
                  options.font
                ].filter(function(d) {
                  return d;
                }).join(" ");
                context.textAlign = "start";
                context.textBaseline = "alphabetic";
                context.direction = "ltr";
                var pixels = getPixels(canvas, context, str, size, lineSpacing, styletags);
                return processPixels(pixels, options, size);
              }
            }
          ),
          /***/
          7721: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bnsign = __webpack_require__2(5716);
              module2.exports = sign;
              function sign(x) {
                return bnsign(x[0]) * bnsign(x[1]);
              }
            }
          ),
          /***/
          7765: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = extractContour;
              var ndarray = __webpack_require__2(9618);
              var pool = __webpack_require__2(1888);
              var ndsort = __webpack_require__2(446);
              var contourAlgorithm = __webpack_require__2(1570);
              function getDimension(cells) {
                var numCells = cells.length;
                var d = 0;
                for (var i = 0; i < numCells; ++i) {
                  d = Math.max(d, cells[i].length) | 0;
                }
                return d - 1;
              }
              function getSigns(values, level) {
                var numVerts = values.length;
                var vertexSigns = pool.mallocUint8(numVerts);
                for (var i = 0; i < numVerts; ++i) {
                  vertexSigns[i] = values[i] < level | 0;
                }
                return vertexSigns;
              }
              function getEdges(cells, d) {
                var numCells = cells.length;
                var maxEdges = d * (d + 1) / 2 * numCells | 0;
                var edges = pool.mallocUint32(maxEdges * 2);
                var ePtr = 0;
                for (var i = 0; i < numCells; ++i) {
                  var c = cells[i];
                  var d = c.length;
                  for (var j = 0; j < d; ++j) {
                    for (var k = 0; k < j; ++k) {
                      var a = c[k];
                      var b = c[j];
                      edges[ePtr++] = Math.min(a, b) | 0;
                      edges[ePtr++] = Math.max(a, b) | 0;
                    }
                  }
                }
                var nedges = ePtr / 2 | 0;
                ndsort(ndarray(edges, [nedges, 2]));
                var ptr = 2;
                for (var i = 2; i < ePtr; i += 2) {
                  if (edges[i - 2] === edges[i] && edges[i - 1] === edges[i + 1]) {
                    continue;
                  }
                  edges[ptr++] = edges[i];
                  edges[ptr++] = edges[i + 1];
                }
                return ndarray(edges, [ptr / 2 | 0, 2]);
              }
              function getCrossingWeights(edges, values, signs, level) {
                var edata = edges.data;
                var numEdges = edges.shape[0];
                var weights = pool.mallocDouble(numEdges);
                var ptr = 0;
                for (var i = 0; i < numEdges; ++i) {
                  var a = edata[2 * i];
                  var b = edata[2 * i + 1];
                  if (signs[a] === signs[b]) {
                    continue;
                  }
                  var va = values[a];
                  var vb = values[b];
                  edata[2 * ptr] = a;
                  edata[2 * ptr + 1] = b;
                  weights[ptr++] = (vb - level) / (vb - va);
                }
                edges.shape[0] = ptr;
                return ndarray(weights, [ptr]);
              }
              function getCascade(edges, numVerts) {
                var result = pool.mallocInt32(numVerts * 2);
                var numEdges = edges.shape[0];
                var edata = edges.data;
                result[0] = 0;
                var lastV = 0;
                for (var i = 0; i < numEdges; ++i) {
                  var a = edata[2 * i];
                  if (a !== lastV) {
                    result[2 * lastV + 1] = i;
                    while (++lastV < a) {
                      result[2 * lastV] = i;
                      result[2 * lastV + 1] = i;
                    }
                    result[2 * lastV] = i;
                  }
                }
                result[2 * lastV + 1] = numEdges;
                while (++lastV < numVerts) {
                  result[2 * lastV] = result[2 * lastV + 1] = numEdges;
                }
                return result;
              }
              function unpackEdges(edges) {
                var ne = edges.shape[0] | 0;
                var edata = edges.data;
                var result = new Array(ne);
                for (var i = 0; i < ne; ++i) {
                  result[i] = [edata[2 * i], edata[2 * i + 1]];
                }
                return result;
              }
              function extractContour(cells, values, level, d) {
                level = level || 0;
                if (typeof d === "undefined") {
                  d = getDimension(cells);
                }
                var numCells = cells.length;
                if (numCells === 0 || d < 1) {
                  return {
                    cells: [],
                    vertexIds: [],
                    vertexWeights: []
                  };
                }
                var vertexSigns = getSigns(values, +level);
                var edges = getEdges(cells, d);
                var weights = getCrossingWeights(edges, values, vertexSigns, +level);
                var vcascade = getCascade(edges, values.length | 0);
                var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns);
                var uedges = unpackEdges(edges);
                var uweights = [].slice.call(weights.data, 0, weights.shape[0]);
                pool.free(vertexSigns);
                pool.free(edges.data);
                pool.free(weights.data);
                pool.free(vcascade);
                return {
                  cells: faces,
                  vertexIds: uedges,
                  vertexWeights: uweights
                };
              }
            }
          ),
          /***/
          7766: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var ndarray = __webpack_require__2(9618);
              var ops = __webpack_require__2(5298);
              var pool = __webpack_require__2(1888);
              module2.exports = createTexture2D;
              var linearTypes = null;
              var filterTypes = null;
              var wrapTypes = null;
              function lazyInitLinearTypes(gl2) {
                linearTypes = [
                  gl2.LINEAR,
                  gl2.NEAREST_MIPMAP_LINEAR,
                  gl2.LINEAR_MIPMAP_NEAREST,
                  gl2.LINEAR_MIPMAP_NEAREST
                ];
                filterTypes = [
                  gl2.NEAREST,
                  gl2.LINEAR,
                  gl2.NEAREST_MIPMAP_NEAREST,
                  gl2.NEAREST_MIPMAP_LINEAR,
                  gl2.LINEAR_MIPMAP_NEAREST,
                  gl2.LINEAR_MIPMAP_LINEAR
                ];
                wrapTypes = [
                  gl2.REPEAT,
                  gl2.CLAMP_TO_EDGE,
                  gl2.MIRRORED_REPEAT
                ];
              }
              function acceptTextureDOM(obj) {
                return "undefined" != typeof HTMLCanvasElement && obj instanceof HTMLCanvasElement || "undefined" != typeof HTMLImageElement && obj instanceof HTMLImageElement || "undefined" != typeof HTMLVideoElement && obj instanceof HTMLVideoElement || "undefined" != typeof ImageData && obj instanceof ImageData;
              }
              var convertFloatToUint8 = function(out, inp) {
                ops.muls(out, inp, 255);
              };
              function reshapeTexture(tex, w, h) {
                var gl2 = tex.gl;
                var maxSize = gl2.getParameter(gl2.MAX_TEXTURE_SIZE);
                if (w < 0 || w > maxSize || h < 0 || h > maxSize) {
                  throw new Error("gl-texture2d: Invalid texture size");
                }
                tex._shape = [w, h];
                tex.bind();
                gl2.texImage2D(gl2.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null);
                tex._mipLevels = [0];
                return tex;
              }
              function Texture2D(gl2, handle, width, height, format, type) {
                this.gl = gl2;
                this.handle = handle;
                this.format = format;
                this.type = type;
                this._shape = [width, height];
                this._mipLevels = [0];
                this._magFilter = gl2.NEAREST;
                this._minFilter = gl2.NEAREST;
                this._wrapS = gl2.CLAMP_TO_EDGE;
                this._wrapT = gl2.CLAMP_TO_EDGE;
                this._anisoSamples = 1;
                var parent = this;
                var wrapVector = [this._wrapS, this._wrapT];
                Object.defineProperties(wrapVector, [
                  {
                    get: function() {
                      return parent._wrapS;
                    },
                    set: function(v) {
                      return parent.wrapS = v;
                    }
                  },
                  {
                    get: function() {
                      return parent._wrapT;
                    },
                    set: function(v) {
                      return parent.wrapT = v;
                    }
                  }
                ]);
                this._wrapVector = wrapVector;
                var shapeVector = [this._shape[0], this._shape[1]];
                Object.defineProperties(shapeVector, [
                  {
                    get: function() {
                      return parent._shape[0];
                    },
                    set: function(v) {
                      return parent.width = v;
                    }
                  },
                  {
                    get: function() {
                      return parent._shape[1];
                    },
                    set: function(v) {
                      return parent.height = v;
                    }
                  }
                ]);
                this._shapeVector = shapeVector;
              }
              var proto = Texture2D.prototype;
              Object.defineProperties(proto, {
                minFilter: {
                  get: function() {
                    return this._minFilter;
                  },
                  set: function(v) {
                    this.bind();
                    var gl2 = this.gl;
                    if (this.type === gl2.FLOAT && linearTypes.indexOf(v) >= 0) {
                      if (!gl2.getExtension("OES_texture_float_linear")) {
                        v = gl2.NEAREST;
                      }
                    }
                    if (filterTypes.indexOf(v) < 0) {
                      throw new Error("gl-texture2d: Unknown filter mode " + v);
                    }
                    gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, v);
                    return this._minFilter = v;
                  }
                },
                magFilter: {
                  get: function() {
                    return this._magFilter;
                  },
                  set: function(v) {
                    this.bind();
                    var gl2 = this.gl;
                    if (this.type === gl2.FLOAT && linearTypes.indexOf(v) >= 0) {
                      if (!gl2.getExtension("OES_texture_float_linear")) {
                        v = gl2.NEAREST;
                      }
                    }
                    if (filterTypes.indexOf(v) < 0) {
                      throw new Error("gl-texture2d: Unknown filter mode " + v);
                    }
                    gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, v);
                    return this._magFilter = v;
                  }
                },
                mipSamples: {
                  get: function() {
                    return this._anisoSamples;
                  },
                  set: function(i) {
                    var psamples = this._anisoSamples;
                    this._anisoSamples = Math.max(i, 1) | 0;
                    if (psamples !== this._anisoSamples) {
                      var ext = this.gl.getExtension("EXT_texture_filter_anisotropic");
                      if (ext) {
                        this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples);
                      }
                    }
                    return this._anisoSamples;
                  }
                },
                wrapS: {
                  get: function() {
                    return this._wrapS;
                  },
                  set: function(v) {
                    this.bind();
                    if (wrapTypes.indexOf(v) < 0) {
                      throw new Error("gl-texture2d: Unknown wrap mode " + v);
                    }
                    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v);
                    return this._wrapS = v;
                  }
                },
                wrapT: {
                  get: function() {
                    return this._wrapT;
                  },
                  set: function(v) {
                    this.bind();
                    if (wrapTypes.indexOf(v) < 0) {
                      throw new Error("gl-texture2d: Unknown wrap mode " + v);
                    }
                    this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v);
                    return this._wrapT = v;
                  }
                },
                wrap: {
                  get: function() {
                    return this._wrapVector;
                  },
                  set: function(v) {
                    if (!Array.isArray(v)) {
                      v = [v, v];
                    }
                    if (v.length !== 2) {
                      throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");
                    }
                    for (var i = 0; i < 2; ++i) {
                      if (wrapTypes.indexOf(v[i]) < 0) {
                        throw new Error("gl-texture2d: Unknown wrap mode " + v);
                      }
                    }
                    this._wrapS = v[0];
                    this._wrapT = v[1];
                    var gl2 = this.gl;
                    this.bind();
                    gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, this._wrapS);
                    gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, this._wrapT);
                    return v;
                  }
                },
                shape: {
                  get: function() {
                    return this._shapeVector;
                  },
                  set: function(x) {
                    if (!Array.isArray(x)) {
                      x = [x | 0, x | 0];
                    } else {
                      if (x.length !== 2) {
                        throw new Error("gl-texture2d: Invalid texture shape");
                      }
                    }
                    reshapeTexture(this, x[0] | 0, x[1] | 0);
                    return [x[0] | 0, x[1] | 0];
                  }
                },
                width: {
                  get: function() {
                    return this._shape[0];
                  },
                  set: function(w) {
                    w = w | 0;
                    reshapeTexture(this, w, this._shape[1]);
                    return w;
                  }
                },
                height: {
                  get: function() {
                    return this._shape[1];
                  },
                  set: function(h) {
                    h = h | 0;
                    reshapeTexture(this, this._shape[0], h);
                    return h;
                  }
                }
              });
              proto.bind = function(unit) {
                var gl2 = this.gl;
                if (unit !== void 0) {
                  gl2.activeTexture(gl2.TEXTURE0 + (unit | 0));
                }
                gl2.bindTexture(gl2.TEXTURE_2D, this.handle);
                if (unit !== void 0) {
                  return unit | 0;
                }
                return gl2.getParameter(gl2.ACTIVE_TEXTURE) - gl2.TEXTURE0;
              };
              proto.dispose = function() {
                this.gl.deleteTexture(this.handle);
              };
              proto.generateMipmap = function() {
                this.bind();
                this.gl.generateMipmap(this.gl.TEXTURE_2D);
                var l = Math.min(this._shape[0], this._shape[1]);
                for (var i = 0; l > 0; ++i, l >>>= 1) {
                  if (this._mipLevels.indexOf(i) < 0) {
                    this._mipLevels.push(i);
                  }
                }
              };
              proto.setPixels = function(data, x_off, y_off, mip_level) {
                var gl2 = this.gl;
                this.bind();
                if (Array.isArray(x_off)) {
                  mip_level = y_off;
                  y_off = x_off[1] | 0;
                  x_off = x_off[0] | 0;
                } else {
                  x_off = x_off || 0;
                  y_off = y_off || 0;
                }
                mip_level = mip_level || 0;
                var directData = acceptTextureDOM(data) ? data : data.raw;
                if (directData) {
                  var needsMip = this._mipLevels.indexOf(mip_level) < 0;
                  if (needsMip) {
                    gl2.texImage2D(gl2.TEXTURE_2D, 0, this.format, this.format, this.type, directData);
                    this._mipLevels.push(mip_level);
                  } else {
                    gl2.texSubImage2D(gl2.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, directData);
                  }
                } else if (data.shape && data.stride && data.data) {
                  if (data.shape.length < 2 || x_off + data.shape[1] > this._shape[1] >>> mip_level || y_off + data.shape[0] > this._shape[0] >>> mip_level || x_off < 0 || y_off < 0) {
                    throw new Error("gl-texture2d: Texture dimensions are out of bounds");
                  }
                  texSubImageArray(gl2, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data);
                } else {
                  throw new Error("gl-texture2d: Unsupported data type");
                }
              };
              function isPacked(shape, stride) {
                if (shape.length === 3) {
                  return stride[2] === 1 && stride[1] === shape[0] * shape[2] && stride[0] === shape[2];
                }
                return stride[0] === 1 && stride[1] === shape[0];
              }
              function texSubImageArray(gl2, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) {
                var dtype = array.dtype;
                var shape = array.shape.slice();
                if (shape.length < 2 || shape.length > 3) {
                  throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");
                }
                var type = 0, format = 0;
                var packed = isPacked(shape, array.stride.slice());
                if (dtype === "float32") {
                  type = gl2.FLOAT;
                } else if (dtype === "float64") {
                  type = gl2.FLOAT;
                  packed = false;
                  dtype = "float32";
                } else if (dtype === "uint8") {
                  type = gl2.UNSIGNED_BYTE;
                } else {
                  type = gl2.UNSIGNED_BYTE;
                  packed = false;
                  dtype = "uint8";
                }
                var channels = 1;
                if (shape.length === 2) {
                  format = gl2.LUMINANCE;
                  shape = [shape[0], shape[1], 1];
                  array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset);
                } else if (shape.length === 3) {
                  if (shape[2] === 1) {
                    format = gl2.ALPHA;
                  } else if (shape[2] === 2) {
                    format = gl2.LUMINANCE_ALPHA;
                  } else if (shape[2] === 3) {
                    format = gl2.RGB;
                  } else if (shape[2] === 4) {
                    format = gl2.RGBA;
                  } else {
                    throw new Error("gl-texture2d: Invalid shape for pixel coords");
                  }
                  channels = shape[2];
                } else {
                  throw new Error("gl-texture2d: Invalid shape for texture");
                }
                if ((format === gl2.LUMINANCE || format === gl2.ALPHA) && (cformat === gl2.LUMINANCE || cformat === gl2.ALPHA)) {
                  format = cformat;
                }
                if (format !== cformat) {
                  throw new Error("gl-texture2d: Incompatible texture format for setPixels");
                }
                var size = array.size;
                var needsMip = mipLevels.indexOf(mip_level) < 0;
                if (needsMip) {
                  mipLevels.push(mip_level);
                }
                if (type === ctype && packed) {
                  if (array.offset === 0 && array.data.length === size) {
                    if (needsMip) {
                      gl2.texImage2D(gl2.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data);
                    } else {
                      gl2.texSubImage2D(gl2.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data);
                    }
                  } else {
                    if (needsMip) {
                      gl2.texImage2D(gl2.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset + size));
                    } else {
                      gl2.texSubImage2D(gl2.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset + size));
                    }
                  }
                } else {
                  var pack_buffer;
                  if (ctype === gl2.FLOAT) {
                    pack_buffer = pool.mallocFloat32(size);
                  } else {
                    pack_buffer = pool.mallocUint8(size);
                  }
                  var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2] * shape[0], 1]);
                  if (type === gl2.FLOAT && ctype === gl2.UNSIGNED_BYTE) {
                    convertFloatToUint8(pack_view, array);
                  } else {
                    ops.assign(pack_view, array);
                  }
                  if (needsMip) {
                    gl2.texImage2D(gl2.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size));
                  } else {
                    gl2.texSubImage2D(gl2.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size));
                  }
                  if (ctype === gl2.FLOAT) {
                    pool.freeFloat32(pack_buffer);
                  } else {
                    pool.freeUint8(pack_buffer);
                  }
                }
              }
              function initTexture(gl2) {
                var tex = gl2.createTexture();
                gl2.bindTexture(gl2.TEXTURE_2D, tex);
                gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.NEAREST);
                gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.NEAREST);
                gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
                gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
                return tex;
              }
              function createTextureShape(gl2, width, height, format, type) {
                var maxTextureSize = gl2.getParameter(gl2.MAX_TEXTURE_SIZE);
                if (width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) {
                  throw new Error("gl-texture2d: Invalid texture shape");
                }
                if (type === gl2.FLOAT && !gl2.getExtension("OES_texture_float")) {
                  throw new Error("gl-texture2d: Floating point textures not supported on this platform");
                }
                var tex = initTexture(gl2);
                gl2.texImage2D(gl2.TEXTURE_2D, 0, format, width, height, 0, format, type, null);
                return new Texture2D(gl2, tex, width, height, format, type);
              }
              function createTextureDOM(gl2, directData, width, height, format, type) {
                var tex = initTexture(gl2);
                gl2.texImage2D(gl2.TEXTURE_2D, 0, format, format, type, directData);
                return new Texture2D(gl2, tex, width, height, format, type);
              }
              function createTextureArray(gl2, array) {
                var dtype = array.dtype;
                var shape = array.shape.slice();
                var maxSize = gl2.getParameter(gl2.MAX_TEXTURE_SIZE);
                if (shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {
                  throw new Error("gl-texture2d: Invalid texture size");
                }
                var packed = isPacked(shape, array.stride.slice());
                var type = 0;
                if (dtype === "float32") {
                  type = gl2.FLOAT;
                } else if (dtype === "float64") {
                  type = gl2.FLOAT;
                  packed = false;
                  dtype = "float32";
                } else if (dtype === "uint8") {
                  type = gl2.UNSIGNED_BYTE;
                } else {
                  type = gl2.UNSIGNED_BYTE;
                  packed = false;
                  dtype = "uint8";
                }
                var format = 0;
                if (shape.length === 2) {
                  format = gl2.LUMINANCE;
                  shape = [shape[0], shape[1], 1];
                  array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset);
                } else if (shape.length === 3) {
                  if (shape[2] === 1) {
                    format = gl2.ALPHA;
                  } else if (shape[2] === 2) {
                    format = gl2.LUMINANCE_ALPHA;
                  } else if (shape[2] === 3) {
                    format = gl2.RGB;
                  } else if (shape[2] === 4) {
                    format = gl2.RGBA;
                  } else {
                    throw new Error("gl-texture2d: Invalid shape for pixel coords");
                  }
                } else {
                  throw new Error("gl-texture2d: Invalid shape for texture");
                }
                if (type === gl2.FLOAT && !gl2.getExtension("OES_texture_float")) {
                  type = gl2.UNSIGNED_BYTE;
                  packed = false;
                }
                var buffer, buf_store;
                var size = array.size;
                if (!packed) {
                  var stride = [shape[2], shape[2] * shape[0], 1];
                  buf_store = pool.malloc(size, dtype);
                  var buf_array = ndarray(buf_store, shape, stride, 0);
                  if ((dtype === "float32" || dtype === "float64") && type === gl2.UNSIGNED_BYTE) {
                    convertFloatToUint8(buf_array, array);
                  } else {
                    ops.assign(buf_array, array);
                  }
                  buffer = buf_store.subarray(0, size);
                } else if (array.offset === 0 && array.data.length === size) {
                  buffer = array.data;
                } else {
                  buffer = array.data.subarray(array.offset, array.offset + size);
                }
                var tex = initTexture(gl2);
                gl2.texImage2D(gl2.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer);
                if (!packed) {
                  pool.free(buf_store);
                }
                return new Texture2D(gl2, tex, shape[0], shape[1], format, type);
              }
              function createTexture2D(gl2) {
                if (arguments.length <= 1) {
                  throw new Error("gl-texture2d: Missing arguments for texture2d constructor");
                }
                if (!linearTypes) {
                  lazyInitLinearTypes(gl2);
                }
                if (typeof arguments[1] === "number") {
                  return createTextureShape(gl2, arguments[1], arguments[2], arguments[3] || gl2.RGBA, arguments[4] || gl2.UNSIGNED_BYTE);
                }
                if (Array.isArray(arguments[1])) {
                  return createTextureShape(gl2, arguments[1][0] | 0, arguments[1][1] | 0, arguments[2] || gl2.RGBA, arguments[3] || gl2.UNSIGNED_BYTE);
                }
                if (typeof arguments[1] === "object") {
                  var obj = arguments[1];
                  var directData = acceptTextureDOM(obj) ? obj : obj.raw;
                  if (directData) {
                    return createTextureDOM(gl2, directData, obj.width | 0, obj.height | 0, arguments[2] || gl2.RGBA, arguments[3] || gl2.UNSIGNED_BYTE);
                  } else if (obj.shape && obj.data && obj.stride) {
                    return createTextureArray(gl2, obj);
                  }
                }
                throw new Error("gl-texture2d: Invalid arguments for texture2d constructor");
              }
            }
          ),
          /***/
          7790: (
            /***/
            function() {
            }
          ),
          /***/
          7815: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var vec3 = __webpack_require__2(2931);
              var vec4 = __webpack_require__2(9970);
              var GRID_TYPES = ["xyz", "xzy", "yxz", "yzx", "zxy", "zyx"];
              var streamToTube = function(stream, maxDivergence, minDistance, maxNorm) {
                var points = stream.points;
                var velocities = stream.velocities;
                var divergences = stream.divergences;
                var verts = [];
                var faces = [];
                var vectors = [];
                var previousVerts = [];
                var currentVerts = [];
                var intensities = [];
                var previousIntensity = 0;
                var currentIntensity = 0;
                var currentVector = vec4.create();
                var previousVector = vec4.create();
                var facets = 8;
                for (var i = 0; i < points.length; i++) {
                  var p = points[i];
                  var fwd = velocities[i];
                  var r = divergences[i];
                  if (maxDivergence === 0) {
                    r = minDistance * 0.05;
                  }
                  currentIntensity = vec3.length(fwd) / maxNorm;
                  currentVector = vec4.create();
                  vec3.copy(currentVector, fwd);
                  currentVector[3] = r;
                  for (var a = 0; a < facets; a++) {
                    currentVerts[a] = [p[0], p[1], p[2], a];
                  }
                  if (previousVerts.length > 0) {
                    for (var a = 0; a < facets; a++) {
                      var a1 = (a + 1) % facets;
                      verts.push(
                        previousVerts[a],
                        currentVerts[a],
                        currentVerts[a1],
                        currentVerts[a1],
                        previousVerts[a1],
                        previousVerts[a]
                      );
                      vectors.push(
                        previousVector,
                        currentVector,
                        currentVector,
                        currentVector,
                        previousVector,
                        previousVector
                      );
                      intensities.push(
                        previousIntensity,
                        currentIntensity,
                        currentIntensity,
                        currentIntensity,
                        previousIntensity,
                        previousIntensity
                      );
                      var len = verts.length;
                      faces.push(
                        [len - 6, len - 5, len - 4],
                        [len - 3, len - 2, len - 1]
                      );
                    }
                  }
                  var tmp1 = previousVerts;
                  previousVerts = currentVerts;
                  currentVerts = tmp1;
                  var tmp2 = previousVector;
                  previousVector = currentVector;
                  currentVector = tmp2;
                  var tmp3 = previousIntensity;
                  previousIntensity = currentIntensity;
                  currentIntensity = tmp3;
                }
                return {
                  positions: verts,
                  cells: faces,
                  vectors,
                  vertexIntensity: intensities
                };
              };
              var createTubes = function(streams, colormap, maxDivergence, minDistance) {
                var maxNorm = 0;
                for (var i = 0; i < streams.length; i++) {
                  var velocities = streams[i].velocities;
                  for (var j = 0; j < velocities.length; j++) {
                    maxNorm = Math.max(
                      maxNorm,
                      vec3.length(velocities[j])
                    );
                  }
                }
                var tubes = streams.map(function(s) {
                  return streamToTube(s, maxDivergence, minDistance, maxNorm);
                });
                var positions = [];
                var cells = [];
                var vectors = [];
                var vertexIntensity = [];
                for (var i = 0; i < tubes.length; i++) {
                  var tube = tubes[i];
                  var offset = positions.length;
                  positions = positions.concat(tube.positions);
                  vectors = vectors.concat(tube.vectors);
                  vertexIntensity = vertexIntensity.concat(tube.vertexIntensity);
                  for (var j = 0; j < tube.cells.length; j++) {
                    var cell = tube.cells[j];
                    var newCell = [];
                    cells.push(newCell);
                    for (var k = 0; k < cell.length; k++) {
                      newCell.push(cell[k] + offset);
                    }
                  }
                }
                return {
                  positions,
                  cells,
                  vectors,
                  vertexIntensity,
                  colormap
                };
              };
              var findLastSmallerIndex = function(points, v) {
                var len = points.length;
                var i;
                for (i = 0; i < len; i++) {
                  var p = points[i];
                  if (p === v) return i;
                  else if (p > v) return i - 1;
                }
                return i;
              };
              var clamp = function(v, min, max) {
                return v < min ? min : v > max ? max : v;
              };
              var sampleMeshgrid = function(point, vectorField, gridInfo) {
                var vectors = vectorField.vectors;
                var meshgrid = vectorField.meshgrid;
                var x = point[0];
                var y = point[1];
                var z = point[2];
                var w = meshgrid[0].length;
                var h = meshgrid[1].length;
                var d = meshgrid[2].length;
                var x0 = findLastSmallerIndex(meshgrid[0], x);
                var y0 = findLastSmallerIndex(meshgrid[1], y);
                var z0 = findLastSmallerIndex(meshgrid[2], z);
                var x1 = x0 + 1;
                var y1 = y0 + 1;
                var z1 = z0 + 1;
                x0 = clamp(x0, 0, w - 1);
                x1 = clamp(x1, 0, w - 1);
                y0 = clamp(y0, 0, h - 1);
                y1 = clamp(y1, 0, h - 1);
                z0 = clamp(z0, 0, d - 1);
                z1 = clamp(z1, 0, d - 1);
                if (x0 < 0 || y0 < 0 || z0 < 0 || x1 > w - 1 || y1 > h - 1 || z1 > d - 1) {
                  return vec3.create();
                }
                var mX0 = meshgrid[0][x0];
                var mX1 = meshgrid[0][x1];
                var mY0 = meshgrid[1][y0];
                var mY1 = meshgrid[1][y1];
                var mZ0 = meshgrid[2][z0];
                var mZ1 = meshgrid[2][z1];
                var xf = (x - mX0) / (mX1 - mX0);
                var yf = (y - mY0) / (mY1 - mY0);
                var zf = (z - mZ0) / (mZ1 - mZ0);
                if (!isFinite(xf)) xf = 0.5;
                if (!isFinite(yf)) yf = 0.5;
                if (!isFinite(zf)) zf = 0.5;
                var x0off;
                var x1off;
                var y0off;
                var y1off;
                var z0off;
                var z1off;
                if (gridInfo.reversedX) {
                  x0 = w - 1 - x0;
                  x1 = w - 1 - x1;
                }
                if (gridInfo.reversedY) {
                  y0 = h - 1 - y0;
                  y1 = h - 1 - y1;
                }
                if (gridInfo.reversedZ) {
                  z0 = d - 1 - z0;
                  z1 = d - 1 - z1;
                }
                switch (gridInfo.filled) {
                  case 5:
                    z0off = z0;
                    z1off = z1;
                    y0off = y0 * d;
                    y1off = y1 * d;
                    x0off = x0 * d * h;
                    x1off = x1 * d * h;
                    break;
                  case 4:
                    z0off = z0;
                    z1off = z1;
                    x0off = x0 * d;
                    x1off = x1 * d;
                    y0off = y0 * d * w;
                    y1off = y1 * d * w;
                    break;
                  case 3:
                    y0off = y0;
                    y1off = y1;
                    z0off = z0 * h;
                    z1off = z1 * h;
                    x0off = x0 * h * d;
                    x1off = x1 * h * d;
                    break;
                  case 2:
                    y0off = y0;
                    y1off = y1;
                    x0off = x0 * h;
                    x1off = x1 * h;
                    z0off = z0 * h * w;
                    z1off = z1 * h * w;
                    break;
                  case 1:
                    x0off = x0;
                    x1off = x1;
                    z0off = z0 * w;
                    z1off = z1 * w;
                    y0off = y0 * w * d;
                    y1off = y1 * w * d;
                    break;
                  default:
                    x0off = x0;
                    x1off = x1;
                    y0off = y0 * w;
                    y1off = y1 * w;
                    z0off = z0 * w * h;
                    z1off = z1 * w * h;
                    break;
                }
                var v000 = vectors[x0off + y0off + z0off];
                var v001 = vectors[x0off + y0off + z1off];
                var v010 = vectors[x0off + y1off + z0off];
                var v011 = vectors[x0off + y1off + z1off];
                var v100 = vectors[x1off + y0off + z0off];
                var v101 = vectors[x1off + y0off + z1off];
                var v110 = vectors[x1off + y1off + z0off];
                var v111 = vectors[x1off + y1off + z1off];
                var c00 = vec3.create();
                var c01 = vec3.create();
                var c10 = vec3.create();
                var c11 = vec3.create();
                vec3.lerp(c00, v000, v100, xf);
                vec3.lerp(c01, v001, v101, xf);
                vec3.lerp(c10, v010, v110, xf);
                vec3.lerp(c11, v011, v111, xf);
                var c0 = vec3.create();
                var c1 = vec3.create();
                vec3.lerp(c0, c00, c10, yf);
                vec3.lerp(c1, c01, c11, yf);
                var c = vec3.create();
                vec3.lerp(c, c0, c1, zf);
                return c;
              };
              var vabs = function(dst, v) {
                var x = v[0];
                var y = v[1];
                var z = v[2];
                dst[0] = x < 0 ? -x : x;
                dst[1] = y < 0 ? -y : y;
                dst[2] = z < 0 ? -z : z;
                return dst;
              };
              var findMinSeparation = function(xs) {
                var minSeparation = Infinity;
                xs.sort(function(a, b) {
                  return a - b;
                });
                var len = xs.length;
                for (var i = 1; i < len; i++) {
                  var d = Math.abs(xs[i] - xs[i - 1]);
                  if (d < minSeparation) {
                    minSeparation = d;
                  }
                }
                return minSeparation;
              };
              var calculateMinPositionDistance = function(positions) {
                var xs = [], ys = [], zs = [];
                var xi = {}, yi = {}, zi = {};
                var len = positions.length;
                for (var i = 0; i < len; i++) {
                  var p = positions[i];
                  var x = p[0], y = p[1], z = p[2];
                  if (!xi[x]) {
                    xs.push(x);
                    xi[x] = true;
                  }
                  if (!yi[y]) {
                    ys.push(y);
                    yi[y] = true;
                  }
                  if (!zi[z]) {
                    zs.push(z);
                    zi[z] = true;
                  }
                }
                var xSep = findMinSeparation(xs);
                var ySep = findMinSeparation(ys);
                var zSep = findMinSeparation(zs);
                var minSeparation = Math.min(xSep, ySep, zSep);
                return isFinite(minSeparation) ? minSeparation : 1;
              };
              module2.exports = function(vectorField, bounds) {
                var positions = vectorField.startingPositions;
                var maxLength = vectorField.maxLength || 1e3;
                var tubeSize = vectorField.tubeSize || 1;
                var absoluteTubeSize = vectorField.absoluteTubeSize;
                var gridFill = vectorField.gridFill || "+x+y+z";
                var gridInfo = {};
                if (gridFill.indexOf("-x") !== -1) {
                  gridInfo.reversedX = true;
                }
                if (gridFill.indexOf("-y") !== -1) {
                  gridInfo.reversedY = true;
                }
                if (gridFill.indexOf("-z") !== -1) {
                  gridInfo.reversedZ = true;
                }
                gridInfo.filled = GRID_TYPES.indexOf(gridFill.replace(/-/g, "").replace(/\+/g, ""));
                var getVelocity = vectorField.getVelocity || function(p2) {
                  return sampleMeshgrid(p2, vectorField, gridInfo);
                };
                var getDivergence = vectorField.getDivergence || function(p2, v0) {
                  var dp = vec3.create();
                  var e = 1e-4;
                  vec3.add(dp, p2, [e, 0, 0]);
                  var vx = getVelocity(dp);
                  vec3.subtract(vx, vx, v0);
                  vec3.scale(vx, vx, 1 / e);
                  vec3.add(dp, p2, [0, e, 0]);
                  var vy = getVelocity(dp);
                  vec3.subtract(vy, vy, v0);
                  vec3.scale(vy, vy, 1 / e);
                  vec3.add(dp, p2, [0, 0, e]);
                  var vz = getVelocity(dp);
                  vec3.subtract(vz, vz, v0);
                  vec3.scale(vz, vz, 1 / e);
                  vec3.add(dp, vx, vy);
                  vec3.add(dp, dp, vz);
                  return dp;
                };
                var streams = [];
                var minX = bounds[0][0], minY = bounds[0][1], minZ = bounds[0][2];
                var maxX = bounds[1][0], maxY = bounds[1][1], maxZ = bounds[1][2];
                var inBounds = function(p2) {
                  var x = p2[0];
                  var y = p2[1];
                  var z = p2[2];
                  return !(x < minX || x > maxX || y < minY || y > maxY || z < minZ || z > maxZ);
                };
                var boundsSize = vec3.distance(bounds[0], bounds[1]);
                var maxStepSize = 10 * boundsSize / maxLength;
                var maxStepSizeSq = maxStepSize * maxStepSize;
                var minDistance = 1;
                var maxDivergence = 0;
                var len = positions.length;
                if (len > 1) {
                  minDistance = calculateMinPositionDistance(positions);
                }
                for (var i = 0; i < len; i++) {
                  var p = vec3.create();
                  vec3.copy(p, positions[i]);
                  var stream = [p];
                  var velocities = [];
                  var v = getVelocity(p);
                  var op = p;
                  velocities.push(v);
                  var divergences = [];
                  var dv = getDivergence(p, v);
                  var dvLength = vec3.length(dv);
                  if (isFinite(dvLength) && dvLength > maxDivergence) {
                    maxDivergence = dvLength;
                  }
                  divergences.push(dvLength);
                  streams.push({ points: stream, velocities, divergences });
                  var j = 0;
                  while (j < maxLength * 100 && stream.length < maxLength && inBounds(p)) {
                    j++;
                    var np = vec3.clone(v);
                    var sqLen = vec3.squaredLength(np);
                    if (sqLen === 0) {
                      break;
                    } else if (sqLen > maxStepSizeSq) {
                      vec3.scale(np, np, maxStepSize / Math.sqrt(sqLen));
                    }
                    vec3.add(np, np, p);
                    v = getVelocity(np);
                    if (vec3.squaredDistance(op, np) - maxStepSizeSq > -1e-4 * maxStepSizeSq) {
                      stream.push(np);
                      op = np;
                      velocities.push(v);
                      var dv = getDivergence(np, v);
                      var dvLength = vec3.length(dv);
                      if (isFinite(dvLength) && dvLength > maxDivergence) {
                        maxDivergence = dvLength;
                      }
                      divergences.push(dvLength);
                    }
                    p = np;
                  }
                }
                var tubes = createTubes(streams, vectorField.colormap, maxDivergence, minDistance);
                if (absoluteTubeSize) {
                  tubes.tubeScale = absoluteTubeSize;
                } else {
                  if (maxDivergence === 0) {
                    maxDivergence = 1;
                  }
                  tubes.tubeScale = tubeSize * 0.5 * minDistance / maxDivergence;
                }
                return tubes;
              };
              var shaders = __webpack_require__2(6740);
              var createMesh = __webpack_require__2(6405).createMesh;
              module2.exports.createTubeMesh = function(gl2, params) {
                return createMesh(gl2, params, {
                  shaders,
                  traceType: "streamtube"
                });
              };
            }
          ),
          /***/
          7827: (
            /***/
            function(module2) {
              module2.exports = [
                "<<=",
                ">>=",
                "++",
                "--",
                "<<",
                ">>",
                "<=",
                ">=",
                "==",
                "!=",
                "&&",
                "||",
                "+=",
                "-=",
                "*=",
                "/=",
                "%=",
                "&=",
                "^^",
                "^=",
                "|=",
                "(",
                ")",
                "[",
                "]",
                ".",
                "!",
                "~",
                "*",
                "/",
                "%",
                "+",
                "-",
                "<",
                ">",
                "&",
                "^",
                "|",
                "?",
                ":",
                "=",
                ",",
                ";",
                "{",
                "}"
              ];
            }
          ),
          /***/
          7842: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var isRat = __webpack_require__2(6330);
              var isBN = __webpack_require__2(1533);
              var num2bn = __webpack_require__2(2651);
              var str2bn = __webpack_require__2(6768);
              var rationalize = __webpack_require__2(869);
              var div = __webpack_require__2(8697);
              module2.exports = makeRational;
              function makeRational(numer, denom) {
                if (isRat(numer)) {
                  if (denom) {
                    return div(numer, makeRational(denom));
                  }
                  return [numer[0].clone(), numer[1].clone()];
                }
                var shift = 0;
                var a, b;
                if (isBN(numer)) {
                  a = numer.clone();
                } else if (typeof numer === "string") {
                  a = str2bn(numer);
                } else if (numer === 0) {
                  return [num2bn(0), num2bn(1)];
                } else if (numer === Math.floor(numer)) {
                  a = num2bn(numer);
                } else {
                  while (numer !== Math.floor(numer)) {
                    numer = numer * Math.pow(2, 256);
                    shift -= 256;
                  }
                  a = num2bn(numer);
                }
                if (isRat(denom)) {
                  a.mul(denom[1]);
                  b = denom[0].clone();
                } else if (isBN(denom)) {
                  b = denom.clone();
                } else if (typeof denom === "string") {
                  b = str2bn(denom);
                } else if (!denom) {
                  b = num2bn(1);
                } else if (denom === Math.floor(denom)) {
                  b = num2bn(denom);
                } else {
                  while (denom !== Math.floor(denom)) {
                    denom = denom * Math.pow(2, 256);
                    shift += 256;
                  }
                  b = num2bn(denom);
                }
                if (shift > 0) {
                  a = a.ushln(shift);
                } else if (shift < 0) {
                  b = b.ushln(-shift);
                }
                return rationalize(a, b);
              }
            }
          ),
          /***/
          7894: (
            /***/
            function(module2) {
              module2.exports = identity2;
              function identity2(out) {
                out[0] = 1;
                out[1] = 0;
                out[2] = 0;
                out[3] = 0;
                out[4] = 0;
                out[5] = 1;
                out[6] = 0;
                out[7] = 0;
                out[8] = 0;
                out[9] = 0;
                out[10] = 1;
                out[11] = 0;
                out[12] = 0;
                out[13] = 0;
                out[14] = 0;
                out[15] = 1;
                return out;
              }
              ;
            }
          ),
          /***/
          7932: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var v100 = __webpack_require__2(620);
              module2.exports = v100.slice().concat([
                "layout",
                "centroid",
                "smooth",
                "case",
                "mat2x2",
                "mat2x3",
                "mat2x4",
                "mat3x2",
                "mat3x3",
                "mat3x4",
                "mat4x2",
                "mat4x3",
                "mat4x4",
                "uvec2",
                "uvec3",
                "uvec4",
                "samplerCubeShadow",
                "sampler2DArray",
                "sampler2DArrayShadow",
                "isampler2D",
                "isampler3D",
                "isamplerCube",
                "isampler2DArray",
                "usampler2D",
                "usampler3D",
                "usamplerCube",
                "usampler2DArray",
                "coherent",
                "restrict",
                "readonly",
                "writeonly",
                "resource",
                "atomic_uint",
                "noperspective",
                "patch",
                "sample",
                "subroutine",
                "common",
                "partition",
                "active",
                "filter",
                "image1D",
                "image2D",
                "image3D",
                "imageCube",
                "iimage1D",
                "iimage2D",
                "iimage3D",
                "iimageCube",
                "uimage1D",
                "uimage2D",
                "uimage3D",
                "uimageCube",
                "image1DArray",
                "image2DArray",
                "iimage1DArray",
                "iimage2DArray",
                "uimage1DArray",
                "uimage2DArray",
                "image1DShadow",
                "image2DShadow",
                "image1DArrayShadow",
                "image2DArrayShadow",
                "imageBuffer",
                "iimageBuffer",
                "uimageBuffer",
                "sampler1DArray",
                "sampler1DArrayShadow",
                "isampler1D",
                "isampler1DArray",
                "usampler1D",
                "usampler1DArray",
                "isampler2DRect",
                "usampler2DRect",
                "samplerBuffer",
                "isamplerBuffer",
                "usamplerBuffer",
                "sampler2DMS",
                "isampler2DMS",
                "usampler2DMS",
                "sampler2DMSArray",
                "isampler2DMSArray",
                "usampler2DMSArray"
              ]);
            }
          ),
          /***/
          7960: (
            /***/
            function(module2) {
              module2.exports = squaredDistance;
              function squaredDistance(a, b) {
                var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2], w = b[3] - a[3];
                return x * x + y * y + z * z + w * w;
              }
            }
          ),
          /***/
          8105: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = genPartition;
              var P2F = {
                "lo===p0": lo_equal_p0,
                "lo<p0": lo_lessThan_p0,
                "lo<=p0": lo_lessOrEqual_p0,
                "hi<=p0": hi_lessOrEqual_p0,
                "lo<p0&&p0<=hi": lo_lessThan_p0_and_p0_lessOrEqual_hi,
                "lo<=p0&&p0<=hi": lo_lassOrEqual_p0_and_p0_lessOrEqual_hi,
                "!(lo>=p0)&&!(p1>=hi)": lo_lessThan_p0_and_p1_lessThan_hi
              };
              function genPartition(predicate) {
                return P2F[predicate];
              }
              function lo_equal_p0(a, b, c, d, e, f, p0) {
                for (var j = 2 * a, k = j * c, l = k, m = c, n = b, o = a + b, p = c; d > p; ++p, k += j) {
                  var lo = e[k + n];
                  if (lo === p0) if (m === p) m += 1, l += j;
                  else {
                    for (var s = 0; j > s; ++s) {
                      var t = e[k + s];
                      e[k + s] = e[l], e[l++] = t;
                    }
                    var u = f[p];
                    f[p] = f[m], f[m++] = u;
                  }
                }
                return m;
              }
              function lo_lessThan_p0(a, b, c, d, e, f, p0) {
                for (var j = 2 * a, k = j * c, l = k, m = c, n = b, o = a + b, p = c; d > p; ++p, k += j) {
                  var lo = e[k + n];
                  if (lo < p0) if (m === p) m += 1, l += j;
                  else {
                    for (var s = 0; j > s; ++s) {
                      var t = e[k + s];
                      e[k + s] = e[l], e[l++] = t;
                    }
                    var u = f[p];
                    f[p] = f[m], f[m++] = u;
                  }
                }
                return m;
              }
              function lo_lessOrEqual_p0(a, b, c, d, e, f, p0) {
                for (var j = 2 * a, k = j * c, l = k, m = c, n = b, o = a + b, p = c; d > p; ++p, k += j) {
                  var hi = e[k + o];
                  if (hi <= p0) if (m === p) m += 1, l += j;
                  else {
                    for (var s = 0; j > s; ++s) {
                      var t = e[k + s];
                      e[k + s] = e[l], e[l++] = t;
                    }
                    var u = f[p];
                    f[p] = f[m], f[m++] = u;
                  }
                }
                return m;
              }
              function hi_lessOrEqual_p0(a, b, c, d, e, f, p0) {
                for (var j = 2 * a, k = j * c, l = k, m = c, n = b, o = a + b, p = c; d > p; ++p, k += j) {
                  var hi = e[k + o];
                  if (hi <= p0) if (m === p) m += 1, l += j;
                  else {
                    for (var s = 0; j > s; ++s) {
                      var t = e[k + s];
                      e[k + s] = e[l], e[l++] = t;
                    }
                    var u = f[p];
                    f[p] = f[m], f[m++] = u;
                  }
                }
                return m;
              }
              function lo_lassOrEqual_p0_and_p0_lessOrEqual_hi(a, b, c, d, e, f, p0) {
                for (var j = 2 * a, k = j * c, l = k, m = c, n = b, o = a + b, p = c; d > p; ++p, k += j) {
                  var lo = e[k + n], hi = e[k + o];
                  if (lo <= p0 && p0 <= hi) if (m === p) m += 1, l += j;
                  else {
                    for (var s = 0; j > s; ++s) {
                      var t = e[k + s];
                      e[k + s] = e[l], e[l++] = t;
                    }
                    var u = f[p];
                    f[p] = f[m], f[m++] = u;
                  }
                }
                return m;
              }
              function lo_lessThan_p0_and_p0_lessOrEqual_hi(a, b, c, d, e, f, p0) {
                for (var j = 2 * a, k = j * c, l = k, m = c, n = b, o = a + b, p = c; d > p; ++p, k += j) {
                  var lo = e[k + n], hi = e[k + o];
                  if (lo < p0 && p0 <= hi) if (m === p) m += 1, l += j;
                  else {
                    for (var s = 0; j > s; ++s) {
                      var t = e[k + s];
                      e[k + s] = e[l], e[l++] = t;
                    }
                    var u = f[p];
                    f[p] = f[m], f[m++] = u;
                  }
                }
                return m;
              }
              function lo_lessThan_p0_and_p1_lessThan_hi(a, b, c, d, e, f, p0, p1) {
                for (var j = 2 * a, k = j * c, l = k, m = c, n = b, o = a + b, p = c; d > p; ++p, k += j) {
                  var lo = e[k + n], hi = e[k + o];
                  if (!(lo >= p0) && !(p1 >= hi)) if (m === p) m += 1, l += j;
                  else {
                    for (var s = 0; j > s; ++s) {
                      var t = e[k + s];
                      e[k + s] = e[l], e[l++] = t;
                    }
                    var u = f[p];
                    f[p] = f[m], f[m++] = u;
                  }
                }
                return m;
              }
            }
          ),
          /***/
          8107: (
            /***/
            function(module2) {
              module2.exports = min;
              function min(out, a, b) {
                out[0] = Math.min(a[0], b[0]);
                out[1] = Math.min(a[1], b[1]);
                out[2] = Math.min(a[2], b[2]);
                return out;
              }
            }
          ),
          /***/
          8116: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var createVAONative = __webpack_require__2(7518);
              var createVAOEmulated = __webpack_require__2(870);
              function ExtensionShim(gl2) {
                this.bindVertexArrayOES = gl2.bindVertexArray.bind(gl2);
                this.createVertexArrayOES = gl2.createVertexArray.bind(gl2);
                this.deleteVertexArrayOES = gl2.deleteVertexArray.bind(gl2);
              }
              function createVAO(gl2, attributes, elements, elementsType) {
                var ext = gl2.createVertexArray ? new ExtensionShim(gl2) : gl2.getExtension("OES_vertex_array_object");
                var vao;
                if (ext) {
                  vao = createVAONative(gl2, ext);
                } else {
                  vao = createVAOEmulated(gl2);
                }
                vao.update(attributes, elements, elementsType);
                return vao;
              }
              module2.exports = createVAO;
            }
          ),
          /***/
          8192: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = angle;
              var fromValues = __webpack_require__2(2825);
              var normalize = __webpack_require__2(3536);
              var dot = __webpack_require__2(244);
              function angle(a, b) {
                var tempA = fromValues(a[0], a[1], a[2]);
                var tempB = fromValues(b[0], b[1], b[2]);
                normalize(tempA, tempA);
                normalize(tempB, tempB);
                var cosine = dot(tempA, tempB);
                if (cosine > 1) {
                  return 0;
                } else {
                  return Math.acos(cosine);
                }
              }
            }
          ),
          /***/
          8210: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = linearExpansionSum;
              function scalarScalar(a, b) {
                var x = a + b;
                var bv = x - a;
                var av = x - bv;
                var br = b - bv;
                var ar = a - av;
                var y = ar + br;
                if (y) {
                  return [y, x];
                }
                return [x];
              }
              function linearExpansionSum(e, f) {
                var ne = e.length | 0;
                var nf = f.length | 0;
                if (ne === 1 && nf === 1) {
                  return scalarScalar(e[0], f[0]);
                }
                var n = ne + nf;
                var g = new Array(n);
                var count = 0;
                var eptr = 0;
                var fptr = 0;
                var abs = Math.abs;
                var ei = e[eptr];
                var ea = abs(ei);
                var fi = f[fptr];
                var fa = abs(fi);
                var a, b;
                if (ea < fa) {
                  b = ei;
                  eptr += 1;
                  if (eptr < ne) {
                    ei = e[eptr];
                    ea = abs(ei);
                  }
                } else {
                  b = fi;
                  fptr += 1;
                  if (fptr < nf) {
                    fi = f[fptr];
                    fa = abs(fi);
                  }
                }
                if (eptr < ne && ea < fa || fptr >= nf) {
                  a = ei;
                  eptr += 1;
                  if (eptr < ne) {
                    ei = e[eptr];
                    ea = abs(ei);
                  }
                } else {
                  a = fi;
                  fptr += 1;
                  if (fptr < nf) {
                    fi = f[fptr];
                    fa = abs(fi);
                  }
                }
                var x = a + b;
                var bv = x - a;
                var y = b - bv;
                var q0 = y;
                var q1 = x;
                var _x, _bv, _av, _br, _ar;
                while (eptr < ne && fptr < nf) {
                  if (ea < fa) {
                    a = ei;
                    eptr += 1;
                    if (eptr < ne) {
                      ei = e[eptr];
                      ea = abs(ei);
                    }
                  } else {
                    a = fi;
                    fptr += 1;
                    if (fptr < nf) {
                      fi = f[fptr];
                      fa = abs(fi);
                    }
                  }
                  b = q0;
                  x = a + b;
                  bv = x - a;
                  y = b - bv;
                  if (y) {
                    g[count++] = y;
                  }
                  _x = q1 + x;
                  _bv = _x - q1;
                  _av = _x - _bv;
                  _br = x - _bv;
                  _ar = q1 - _av;
                  q0 = _ar + _br;
                  q1 = _x;
                }
                while (eptr < ne) {
                  a = ei;
                  b = q0;
                  x = a + b;
                  bv = x - a;
                  y = b - bv;
                  if (y) {
                    g[count++] = y;
                  }
                  _x = q1 + x;
                  _bv = _x - q1;
                  _av = _x - _bv;
                  _br = x - _bv;
                  _ar = q1 - _av;
                  q0 = _ar + _br;
                  q1 = _x;
                  eptr += 1;
                  if (eptr < ne) {
                    ei = e[eptr];
                  }
                }
                while (fptr < nf) {
                  a = fi;
                  b = q0;
                  x = a + b;
                  bv = x - a;
                  y = b - bv;
                  if (y) {
                    g[count++] = y;
                  }
                  _x = q1 + x;
                  _bv = _x - q1;
                  _av = _x - _bv;
                  _br = x - _bv;
                  _ar = q1 - _av;
                  q0 = _ar + _br;
                  q1 = _x;
                  fptr += 1;
                  if (fptr < nf) {
                    fi = f[fptr];
                  }
                }
                if (q0) {
                  g[count++] = q0;
                }
                if (q1) {
                  g[count++] = q1;
                }
                if (!count) {
                  g[count++] = 0;
                }
                g.length = count;
                return g;
              }
            }
          ),
          /***/
          8277: (
            /***/
            function(module2) {
              "use strict";
              function CwiseOp() {
                return function(SS, a0, t02, p0, Y0) {
                  var s0 = SS[0], s1 = SS[1], s2 = SS[2], t0p0 = t02[0], t0p1 = t02[1], t0p2 = t02[2], index = [0, 0, 0];
                  p0 |= 0;
                  var i0 = 0, i1 = 0, i2 = 0, d0s0 = t0p2, d0s1 = t0p1 - s2 * t0p2, d0s2 = t0p0 - s1 * t0p1;
                  for (i2 = 0; i2 < s0; ++i2) {
                    for (i1 = 0; i1 < s1; ++i1) {
                      for (i0 = 0; i0 < s2; ++i0) {
                        {
                          var _inline_1_v = Y0, _inline_1_i;
                          for (_inline_1_i = 0; _inline_1_i < index.length - 1; ++_inline_1_i) {
                            _inline_1_v = _inline_1_v[index[_inline_1_i]];
                          }
                          a0[p0] = _inline_1_v[index[index.length - 1]];
                        }
                        p0 += d0s0;
                        ++index[2];
                      }
                      p0 += d0s1;
                      index[2] -= s2;
                      ++index[1];
                    }
                    p0 += d0s2;
                    index[1] -= s1;
                    ++index[0];
                  }
                };
              }
              function generateCWiseOp() {
                return CwiseOp();
              }
              var compile = generateCWiseOp;
              function thunk(compile2) {
                var CACHED = {};
                return function convert_cwise_thunk(array0, scalar1) {
                  var t02 = array0.dtype, r0 = array0.order, type = [t02, r0.join()].join(), proc = CACHED[type];
                  if (!proc) {
                    CACHED[type] = proc = compile2([t02, r0]);
                  }
                  return proc(
                    array0.shape.slice(0),
                    array0.data,
                    array0.stride,
                    array0.offset | 0,
                    scalar1
                  );
                };
              }
              function createThunk(proc) {
                return thunk(compile.bind(void 0, proc));
              }
              function compileCwise(user_args) {
                return createThunk({
                  funcName: user_args.funcName
                });
              }
              module2.exports = compileCwise({
                funcName: "convert"
              });
            }
          ),
          /***/
          8284: (
            /***/
            function(module2) {
              module2.exports = hiddenStore;
              function hiddenStore(obj, key) {
                var store = { identity: key };
                var valueOf = obj.valueOf;
                Object.defineProperty(obj, "valueOf", {
                  value: function(value) {
                    return value !== key ? valueOf.apply(this, arguments) : store;
                  },
                  writable: true
                });
                return store;
              }
            }
          ),
          /***/
          8406: (
            /***/
            function(__unused_webpack_module, exports2) {
              var DEFAULT_NORMALS_EPSILON = 1e-6;
              var DEFAULT_FACE_EPSILON = 1e-6;
              exports2.vertexNormals = function(faces, positions, specifiedEpsilon) {
                var N = positions.length;
                var normals = new Array(N);
                var epsilon = specifiedEpsilon === void 0 ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon;
                for (var i = 0; i < N; ++i) {
                  normals[i] = [0, 0, 0];
                }
                for (var i = 0; i < faces.length; ++i) {
                  var f = faces[i];
                  var p = 0;
                  var c = f[f.length - 1];
                  var n = f[0];
                  for (var j = 0; j < f.length; ++j) {
                    p = c;
                    c = n;
                    n = f[(j + 1) % f.length];
                    var v0 = positions[p];
                    var v1 = positions[c];
                    var v2 = positions[n];
                    var d01 = new Array(3);
                    var m01 = 0;
                    var d21 = new Array(3);
                    var m21 = 0;
                    for (var k = 0; k < 3; ++k) {
                      d01[k] = v0[k] - v1[k];
                      m01 += d01[k] * d01[k];
                      d21[k] = v2[k] - v1[k];
                      m21 += d21[k] * d21[k];
                    }
                    if (m01 * m21 > epsilon) {
                      var norm = normals[c];
                      var w = 1 / Math.sqrt(m01 * m21);
                      for (var k = 0; k < 3; ++k) {
                        var u = (k + 1) % 3;
                        var v = (k + 2) % 3;
                        norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]);
                      }
                    }
                  }
                }
                for (var i = 0; i < N; ++i) {
                  var norm = normals[i];
                  var m = 0;
                  for (var k = 0; k < 3; ++k) {
                    m += norm[k] * norm[k];
                  }
                  if (m > epsilon) {
                    var w = 1 / Math.sqrt(m);
                    for (var k = 0; k < 3; ++k) {
                      norm[k] *= w;
                    }
                  } else {
                    for (var k = 0; k < 3; ++k) {
                      norm[k] = 0;
                    }
                  }
                }
                return normals;
              };
              exports2.faceNormals = function(faces, positions, specifiedEpsilon) {
                var N = faces.length;
                var normals = new Array(N);
                var epsilon = specifiedEpsilon === void 0 ? DEFAULT_FACE_EPSILON : specifiedEpsilon;
                for (var i = 0; i < N; ++i) {
                  var f = faces[i];
                  var pos = new Array(3);
                  for (var j = 0; j < 3; ++j) {
                    pos[j] = positions[f[j]];
                  }
                  var d01 = new Array(3);
                  var d21 = new Array(3);
                  for (var j = 0; j < 3; ++j) {
                    d01[j] = pos[1][j] - pos[0][j];
                    d21[j] = pos[2][j] - pos[0][j];
                  }
                  var n = new Array(3);
                  var l = 0;
                  for (var j = 0; j < 3; ++j) {
                    var u = (j + 1) % 3;
                    var v = (j + 2) % 3;
                    n[j] = d01[u] * d21[v] - d01[v] * d21[u];
                    l += n[j] * n[j];
                  }
                  if (l > epsilon) {
                    l = 1 / Math.sqrt(l);
                  } else {
                    l = 0;
                  }
                  for (var j = 0; j < 3; ++j) {
                    n[j] *= l;
                  }
                  normals[i] = n;
                }
                return normals;
              };
            }
          ),
          /***/
          8418: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var isAllBlank = __webpack_require__2(5219);
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var pool = __webpack_require__2(1888);
              var mat4mult = __webpack_require__2(6760);
              var shaders = __webpack_require__2(1283);
              var getGlyph = __webpack_require__2(9366);
              var getSimpleString = __webpack_require__2(5964);
              var IDENTITY = [
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ];
              var ab = ArrayBuffer;
              var dv = DataView;
              function isTypedArray(a) {
                return ab.isView(a) && !(a instanceof dv);
              }
              function isArrayOrTypedArray(a) {
                return Array.isArray(a) || isTypedArray(a);
              }
              module2.exports = createPointCloud;
              function transformMat4(x, m) {
                var x0 = x[0];
                var x1 = x[1];
                var x2 = x[2];
                var x3 = x[3];
                x[0] = m[0] * x0 + m[4] * x1 + m[8] * x2 + m[12] * x3;
                x[1] = m[1] * x0 + m[5] * x1 + m[9] * x2 + m[13] * x3;
                x[2] = m[2] * x0 + m[6] * x1 + m[10] * x2 + m[14] * x3;
                x[3] = m[3] * x0 + m[7] * x1 + m[11] * x2 + m[15] * x3;
                return x;
              }
              function project(p, v, m, x) {
                transformMat4(x, x, m);
                transformMat4(x, x, v);
                return transformMat4(x, x, p);
              }
              function ScatterPlotPickResult(index, position) {
                this.index = index;
                this.dataCoordinate = this.position = position;
              }
              function fixOpacity(a) {
                if (a === true) return 1;
                if (a > 1) return 1;
                return a;
              }
              function PointCloud(gl2, shader, orthoShader, projectShader, pointBuffer, colorBuffer, glyphBuffer, idBuffer, vao, pickPerspectiveShader, pickOrthoShader, pickProjectShader) {
                this.gl = gl2;
                this.pixelRatio = 1;
                this.shader = shader;
                this.orthoShader = orthoShader;
                this.projectShader = projectShader;
                this.pointBuffer = pointBuffer;
                this.colorBuffer = colorBuffer;
                this.glyphBuffer = glyphBuffer;
                this.idBuffer = idBuffer;
                this.vao = vao;
                this.vertexCount = 0;
                this.lineVertexCount = 0;
                this.opacity = 1;
                this.hasAlpha = false;
                this.lineWidth = 0;
                this.projectScale = [2 / 3, 2 / 3, 2 / 3];
                this.projectOpacity = [1, 1, 1];
                this.projectHasAlpha = false;
                this.pickId = 0;
                this.pickPerspectiveShader = pickPerspectiveShader;
                this.pickOrthoShader = pickOrthoShader;
                this.pickProjectShader = pickProjectShader;
                this.points = [];
                this._selectResult = new ScatterPlotPickResult(0, [0, 0, 0]);
                this.useOrtho = true;
                this.bounds = [
                  [Infinity, Infinity, Infinity],
                  [-Infinity, -Infinity, -Infinity]
                ];
                this.axesProject = [true, true, true];
                this.axesBounds = [
                  [-Infinity, -Infinity, -Infinity],
                  [Infinity, Infinity, Infinity]
                ];
                this.highlightId = [1, 1, 1, 1];
                this.highlightScale = 2;
                this.clipBounds = [
                  [-Infinity, -Infinity, -Infinity],
                  [Infinity, Infinity, Infinity]
                ];
                this.dirty = true;
              }
              var proto = PointCloud.prototype;
              proto.pickSlots = 1;
              proto.setPickBase = function(pickBase) {
                this.pickId = pickBase;
              };
              proto.isTransparent = function() {
                if (this.hasAlpha) {
                  return true;
                }
                for (var i = 0; i < 3; ++i) {
                  if (this.axesProject[i] && this.projectHasAlpha) {
                    return true;
                  }
                }
                return false;
              };
              proto.isOpaque = function() {
                if (!this.hasAlpha) {
                  return true;
                }
                for (var i = 0; i < 3; ++i) {
                  if (this.axesProject[i] && !this.projectHasAlpha) {
                    return true;
                  }
                }
                return false;
              };
              var VIEW_SHAPE = [0, 0];
              var U_VEC = [0, 0, 0];
              var V_VEC = [0, 0, 0];
              var MU_VEC = [0, 0, 0, 1];
              var MV_VEC = [0, 0, 0, 1];
              var SCRATCH_MATRIX = IDENTITY.slice();
              var SCRATCH_VEC = [0, 0, 0];
              var CLIP_BOUNDS = [[0, 0, 0], [0, 0, 0]];
              function zeroVec(a) {
                a[0] = a[1] = a[2] = 0;
                return a;
              }
              function augment(hg, af) {
                hg[0] = af[0];
                hg[1] = af[1];
                hg[2] = af[2];
                hg[3] = 1;
                return hg;
              }
              function setComponent(out, v, i, x) {
                out[0] = v[0];
                out[1] = v[1];
                out[2] = v[2];
                out[i] = x;
                return out;
              }
              function getClipBounds(bounds) {
                var result = CLIP_BOUNDS;
                for (var i = 0; i < 2; ++i) {
                  for (var j = 0; j < 3; ++j) {
                    result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8);
                  }
                }
                return result;
              }
              function drawProject(shader, points, camera, pixelRatio) {
                var axesProject = points.axesProject;
                var gl2 = points.gl;
                var uniforms = shader.uniforms;
                var model = camera.model || IDENTITY;
                var view = camera.view || IDENTITY;
                var projection = camera.projection || IDENTITY;
                var bounds = points.axesBounds;
                var clipBounds = getClipBounds(points.clipBounds);
                var cubeAxis;
                if (points.axes && points.axes.lastCubeProps) {
                  cubeAxis = points.axes.lastCubeProps.axis;
                } else {
                  cubeAxis = [1, 1, 1];
                }
                VIEW_SHAPE[0] = 2 / gl2.drawingBufferWidth;
                VIEW_SHAPE[1] = 2 / gl2.drawingBufferHeight;
                shader.bind();
                uniforms.view = view;
                uniforms.projection = projection;
                uniforms.screenSize = VIEW_SHAPE;
                uniforms.highlightId = points.highlightId;
                uniforms.highlightScale = points.highlightScale;
                uniforms.clipBounds = clipBounds;
                uniforms.pickGroup = points.pickId / 255;
                uniforms.pixelRatio = pixelRatio;
                for (var i = 0; i < 3; ++i) {
                  if (!axesProject[i]) {
                    continue;
                  }
                  uniforms.scale = points.projectScale[i];
                  uniforms.opacity = points.projectOpacity[i];
                  var pmodel = SCRATCH_MATRIX;
                  for (var j = 0; j < 16; ++j) {
                    pmodel[j] = 0;
                  }
                  for (var j = 0; j < 4; ++j) {
                    pmodel[5 * j] = 1;
                  }
                  pmodel[5 * i] = 0;
                  if (cubeAxis[i] < 0) {
                    pmodel[12 + i] = bounds[0][i];
                  } else {
                    pmodel[12 + i] = bounds[1][i];
                  }
                  mat4mult(pmodel, model, pmodel);
                  uniforms.model = pmodel;
                  var u = (i + 1) % 3;
                  var v = (i + 2) % 3;
                  var du = zeroVec(U_VEC);
                  var dv2 = zeroVec(V_VEC);
                  du[u] = 1;
                  dv2[v] = 1;
                  var mdu = project(projection, view, model, augment(MU_VEC, du));
                  var mdv = project(projection, view, model, augment(MV_VEC, dv2));
                  if (Math.abs(mdu[1]) > Math.abs(mdv[1])) {
                    var tmp = mdu;
                    mdu = mdv;
                    mdv = tmp;
                    tmp = du;
                    du = dv2;
                    dv2 = tmp;
                    var t = u;
                    u = v;
                    v = t;
                  }
                  if (mdu[0] < 0) {
                    du[u] = -1;
                  }
                  if (mdv[1] > 0) {
                    dv2[v] = -1;
                  }
                  var su = 0;
                  var sv = 0;
                  for (var j = 0; j < 4; ++j) {
                    su += Math.pow(model[4 * u + j], 2);
                    sv += Math.pow(model[4 * v + j], 2);
                  }
                  du[u] /= Math.sqrt(su);
                  dv2[v] /= Math.sqrt(sv);
                  uniforms.axes[0] = du;
                  uniforms.axes[1] = dv2;
                  uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8);
                  uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8);
                  points.vao.bind();
                  points.vao.draw(gl2.TRIANGLES, points.vertexCount);
                  if (points.lineWidth > 0) {
                    gl2.lineWidth(points.lineWidth * pixelRatio);
                    points.vao.draw(gl2.LINES, points.lineVertexCount, points.vertexCount);
                  }
                  points.vao.unbind();
                }
              }
              var NEG_INFINITY3 = [-1e8, -1e8, -1e8];
              var POS_INFINITY3 = [1e8, 1e8, 1e8];
              var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3];
              function drawFull(shader, pshader, points, camera, pixelRatio, transparent, forceDraw) {
                var gl2 = points.gl;
                if (transparent === points.projectHasAlpha || forceDraw) {
                  drawProject(pshader, points, camera, pixelRatio);
                }
                if (transparent === points.hasAlpha || forceDraw) {
                  shader.bind();
                  var uniforms = shader.uniforms;
                  uniforms.model = camera.model || IDENTITY;
                  uniforms.view = camera.view || IDENTITY;
                  uniforms.projection = camera.projection || IDENTITY;
                  VIEW_SHAPE[0] = 2 / gl2.drawingBufferWidth;
                  VIEW_SHAPE[1] = 2 / gl2.drawingBufferHeight;
                  uniforms.screenSize = VIEW_SHAPE;
                  uniforms.highlightId = points.highlightId;
                  uniforms.highlightScale = points.highlightScale;
                  uniforms.fragClipBounds = CLIP_GROUP;
                  uniforms.clipBounds = points.axes.bounds;
                  uniforms.opacity = points.opacity;
                  uniforms.pickGroup = points.pickId / 255;
                  uniforms.pixelRatio = pixelRatio;
                  points.vao.bind();
                  points.vao.draw(gl2.TRIANGLES, points.vertexCount);
                  if (points.lineWidth > 0) {
                    gl2.lineWidth(points.lineWidth * pixelRatio);
                    points.vao.draw(gl2.LINES, points.lineVertexCount, points.vertexCount);
                  }
                  points.vao.unbind();
                }
              }
              proto.draw = function(camera) {
                var shader = this.useOrtho ? this.orthoShader : this.shader;
                drawFull(shader, this.projectShader, this, camera, this.pixelRatio, false, false);
              };
              proto.drawTransparent = function(camera) {
                var shader = this.useOrtho ? this.orthoShader : this.shader;
                drawFull(shader, this.projectShader, this, camera, this.pixelRatio, true, false);
              };
              proto.drawPick = function(camera) {
                var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader;
                drawFull(shader, this.pickProjectShader, this, camera, 1, true, true);
              };
              proto.pick = function(selected) {
                if (!selected) {
                  return null;
                }
                if (selected.id !== this.pickId) {
                  return null;
                }
                var x = selected.value[2] + (selected.value[1] << 8) + (selected.value[0] << 16);
                if (x >= this.pointCount || x < 0) {
                  return null;
                }
                var coord = this.points[x];
                var result = this._selectResult;
                result.index = x;
                for (var i = 0; i < 3; ++i) {
                  result.position[i] = result.dataCoordinate[i] = coord[i];
                }
                return result;
              };
              proto.highlight = function(selection) {
                if (!selection) {
                  this.highlightId = [1, 1, 1, 1];
                } else {
                  var pointId = selection.index;
                  var a0 = pointId & 255;
                  var a1 = pointId >> 8 & 255;
                  var a2 = pointId >> 16 & 255;
                  this.highlightId = [a0 / 255, a1 / 255, a2 / 255, 0];
                }
              };
              function get_glyphData(glyphs, index, font, pixelRatio) {
                var str;
                if (isArrayOrTypedArray(glyphs)) {
                  if (index < glyphs.length) {
                    str = glyphs[index];
                  } else {
                    str = void 0;
                  }
                } else {
                  str = glyphs;
                }
                str = getSimpleString(str);
                var visible = true;
                if (isAllBlank(str)) {
                  str = "\u25BC";
                  visible = false;
                }
                if (!font) font = {};
                var family = font.family;
                if (isArrayOrTypedArray(family)) family = family[index];
                if (!family) family = "normal";
                var weight = font.weight;
                if (isArrayOrTypedArray(weight)) weight = weight[index];
                if (!weight) weight = "normal";
                var style = font.style;
                if (isArrayOrTypedArray(style)) style = style[index];
                if (!style) style = "normal";
                var variant = font.variant;
                if (isArrayOrTypedArray(variant)) variant = variant[index];
                if (!variant) variant = "normal";
                var glyph = getGlyph(str, {
                  family,
                  weight,
                  style,
                  variant
                }, pixelRatio);
                var glyph = getGlyph(str, font, pixelRatio);
                return {
                  mesh: glyph[0],
                  lines: glyph[1],
                  bounds: glyph[2],
                  visible
                };
              }
              proto.update = function(options) {
                options = options || {};
                if ("perspective" in options) {
                  this.useOrtho = !options.perspective;
                }
                if ("orthographic" in options) {
                  this.useOrtho = !!options.orthographic;
                }
                if ("lineWidth" in options) {
                  this.lineWidth = options.lineWidth;
                }
                if ("project" in options) {
                  if (isArrayOrTypedArray(options.project)) {
                    this.axesProject = options.project;
                  } else {
                    var v = !!options.project;
                    this.axesProject = [v, v, v];
                  }
                }
                if ("projectScale" in options) {
                  if (isArrayOrTypedArray(options.projectScale)) {
                    this.projectScale = options.projectScale.slice();
                  } else {
                    var s = +options.projectScale;
                    this.projectScale = [s, s, s];
                  }
                }
                this.projectHasAlpha = false;
                if ("projectOpacity" in options) {
                  if (isArrayOrTypedArray(options.projectOpacity)) {
                    this.projectOpacity = options.projectOpacity.slice();
                  } else {
                    var s = +options.projectOpacity;
                    this.projectOpacity = [s, s, s];
                  }
                  for (var i = 0; i < 3; ++i) {
                    this.projectOpacity[i] = fixOpacity(this.projectOpacity[i]);
                    if (this.projectOpacity[i] < 1) {
                      this.projectHasAlpha = true;
                    }
                  }
                }
                this.hasAlpha = false;
                if ("opacity" in options) {
                  this.opacity = fixOpacity(options.opacity);
                  if (this.opacity < 1) {
                    this.hasAlpha = true;
                  }
                }
                this.dirty = true;
                var points = options.position;
                var font = {
                  family: options.font || "normal",
                  style: options.fontStyle || "normal",
                  weight: options.fontWeight || "normal",
                  variant: options.fontVariant || "normal"
                };
                var alignment = options.alignment || [0, 0];
                var alignmentX;
                var alignmentY;
                if (alignment.length === 2) {
                  alignmentX = alignment[0];
                  alignmentY = alignment[1];
                } else {
                  alignmentX = [];
                  alignmentY = [];
                  for (var i = 0; i < alignment.length; ++i) {
                    alignmentX[i] = alignment[i][0];
                    alignmentY[i] = alignment[i][1];
                  }
                }
                var lowerBound = [Infinity, Infinity, Infinity];
                var upperBound = [-Infinity, -Infinity, -Infinity];
                var glyphs = options.glyph;
                var colors = options.color;
                var sizes = options.size;
                var angles = options.angle;
                var lineColors = options.lineColor;
                var pickCounter = -1;
                var triVertexCount = 0;
                var lineVertexCount = 0;
                var numPoints = 0;
                if (points.length) {
                  numPoints = points.length;
                  count_loop:
                    for (var i = 0; i < numPoints; ++i) {
                      var x = points[i];
                      for (var j = 0; j < 3; ++j) {
                        if (isNaN(x[j]) || !isFinite(x[j])) {
                          continue count_loop;
                        }
                      }
                      var glyphData = get_glyphData(glyphs, i, font, this.pixelRatio);
                      var glyphMesh = glyphData.mesh;
                      var glyphLines = glyphData.lines;
                      var glyphBounds = glyphData.bounds;
                      triVertexCount += glyphMesh.cells.length * 3;
                      lineVertexCount += glyphLines.edges.length * 2;
                    }
                }
                var vertexCount = triVertexCount + lineVertexCount;
                var positionArray = pool.mallocFloat(3 * vertexCount);
                var colorArray = pool.mallocFloat(4 * vertexCount);
                var glyphArray = pool.mallocFloat(2 * vertexCount);
                var idArray = pool.mallocUint32(vertexCount);
                if (vertexCount > 0) {
                  var triOffset = 0;
                  var lineOffset = triVertexCount;
                  var color2 = [0, 0, 0, 1];
                  var lineColor = [0, 0, 0, 1];
                  var isColorArray = isArrayOrTypedArray(colors) && isArrayOrTypedArray(colors[0]);
                  var isLineColorArray = isArrayOrTypedArray(lineColors) && isArrayOrTypedArray(lineColors[0]);
                  fill_loop:
                    for (var i = 0; i < numPoints; ++i) {
                      pickCounter += 1;
                      var x = points[i];
                      for (var j = 0; j < 3; ++j) {
                        if (isNaN(x[j]) || !isFinite(x[j])) {
                          continue fill_loop;
                        }
                        upperBound[j] = Math.max(upperBound[j], x[j]);
                        lowerBound[j] = Math.min(lowerBound[j], x[j]);
                      }
                      var glyphData = get_glyphData(glyphs, i, font, this.pixelRatio);
                      var glyphMesh = glyphData.mesh;
                      var glyphLines = glyphData.lines;
                      var glyphBounds = glyphData.bounds;
                      var glyphVisible = glyphData.visible;
                      if (!glyphVisible) color2 = [1, 1, 1, 0];
                      else if (isArrayOrTypedArray(colors)) {
                        var c;
                        if (isColorArray) {
                          if (i < colors.length) {
                            c = colors[i];
                          } else {
                            c = [0, 0, 0, 0];
                          }
                        } else {
                          c = colors;
                        }
                        if (c.length === 3) {
                          for (var j = 0; j < 3; ++j) {
                            color2[j] = c[j];
                          }
                          color2[3] = 1;
                        } else if (c.length === 4) {
                          for (var j = 0; j < 4; ++j) {
                            color2[j] = c[j];
                          }
                          if (!this.hasAlpha && c[3] < 1) this.hasAlpha = true;
                        }
                      } else {
                        color2[0] = color2[1] = color2[2] = 0;
                        color2[3] = 1;
                      }
                      if (!glyphVisible) lineColor = [1, 1, 1, 0];
                      else if (isArrayOrTypedArray(lineColors)) {
                        var c;
                        if (isLineColorArray) {
                          if (i < lineColors.length) {
                            c = lineColors[i];
                          } else {
                            c = [0, 0, 0, 0];
                          }
                        } else {
                          c = lineColors;
                        }
                        if (c.length === 3) {
                          for (var j = 0; j < 3; ++j) {
                            lineColor[j] = c[j];
                          }
                          lineColor[j] = 1;
                        } else if (c.length === 4) {
                          for (var j = 0; j < 4; ++j) {
                            lineColor[j] = c[j];
                          }
                          if (!this.hasAlpha && c[3] < 1) this.hasAlpha = true;
                        }
                      } else {
                        lineColor[0] = lineColor[1] = lineColor[2] = 0;
                        lineColor[3] = 1;
                      }
                      var size = 0.5;
                      if (!glyphVisible) size = 0;
                      else if (isArrayOrTypedArray(sizes)) {
                        if (i < sizes.length) {
                          size = +sizes[i];
                        } else {
                          size = 12;
                        }
                      } else if (sizes) {
                        size = +sizes;
                      } else if (this.useOrtho) {
                        size = 12;
                      }
                      var angle = 0;
                      if (isArrayOrTypedArray(angles)) {
                        if (i < angles.length) {
                          angle = +angles[i];
                        } else {
                          angle = 0;
                        }
                      } else if (angles) {
                        angle = +angles;
                      }
                      var cos = Math.cos(angle);
                      var sin = Math.sin(angle);
                      var x = points[i];
                      for (var j = 0; j < 3; ++j) {
                        upperBound[j] = Math.max(upperBound[j], x[j]);
                        lowerBound[j] = Math.min(lowerBound[j], x[j]);
                      }
                      var textOffsetX = alignmentX;
                      var textOffsetY = alignmentY;
                      var textOffsetX = 0;
                      if (isArrayOrTypedArray(alignmentX)) {
                        if (i < alignmentX.length) {
                          textOffsetX = alignmentX[i];
                        } else {
                          textOffsetX = 0;
                        }
                      } else if (alignmentX) {
                        textOffsetX = alignmentX;
                      }
                      var textOffsetY = 0;
                      if (isArrayOrTypedArray(alignmentY)) {
                        if (i < alignmentY.length) {
                          textOffsetY = alignmentY[i];
                        } else {
                          textOffsetY = 0;
                        }
                      } else if (alignmentY) {
                        textOffsetY = alignmentY;
                      }
                      textOffsetX *= textOffsetX > 0 ? 1 - glyphBounds[0][0] : textOffsetX < 0 ? 1 + glyphBounds[1][0] : 1;
                      textOffsetY *= textOffsetY > 0 ? 1 - glyphBounds[0][1] : textOffsetY < 0 ? 1 + glyphBounds[1][1] : 1;
                      var textOffset = [textOffsetX, textOffsetY];
                      var cells = glyphMesh.cells || [];
                      var verts = glyphMesh.positions || [];
                      for (var j = 0; j < cells.length; ++j) {
                        var cell = cells[j];
                        for (var k = 0; k < 3; ++k) {
                          for (var l = 0; l < 3; ++l) {
                            positionArray[3 * triOffset + l] = x[l];
                          }
                          for (var l = 0; l < 4; ++l) {
                            colorArray[4 * triOffset + l] = color2[l];
                          }
                          idArray[triOffset] = pickCounter;
                          var p = verts[cell[k]];
                          glyphArray[2 * triOffset] = size * (cos * p[0] - sin * p[1] + textOffset[0]);
                          glyphArray[2 * triOffset + 1] = size * (sin * p[0] + cos * p[1] + textOffset[1]);
                          triOffset += 1;
                        }
                      }
                      var cells = glyphLines.edges;
                      var verts = glyphLines.positions;
                      for (var j = 0; j < cells.length; ++j) {
                        var cell = cells[j];
                        for (var k = 0; k < 2; ++k) {
                          for (var l = 0; l < 3; ++l) {
                            positionArray[3 * lineOffset + l] = x[l];
                          }
                          for (var l = 0; l < 4; ++l) {
                            colorArray[4 * lineOffset + l] = lineColor[l];
                          }
                          idArray[lineOffset] = pickCounter;
                          var p = verts[cell[k]];
                          glyphArray[2 * lineOffset] = size * (cos * p[0] - sin * p[1] + textOffset[0]);
                          glyphArray[2 * lineOffset + 1] = size * (sin * p[0] + cos * p[1] + textOffset[1]);
                          lineOffset += 1;
                        }
                      }
                    }
                }
                this.bounds = [lowerBound, upperBound];
                this.points = points;
                this.pointCount = points.length;
                this.vertexCount = triVertexCount;
                this.lineVertexCount = lineVertexCount;
                this.pointBuffer.update(positionArray);
                this.colorBuffer.update(colorArray);
                this.glyphBuffer.update(glyphArray);
                this.idBuffer.update(idArray);
                pool.free(positionArray);
                pool.free(colorArray);
                pool.free(glyphArray);
                pool.free(idArray);
              };
              proto.dispose = function() {
                this.shader.dispose();
                this.orthoShader.dispose();
                this.pickPerspectiveShader.dispose();
                this.pickOrthoShader.dispose();
                this.vao.dispose();
                this.pointBuffer.dispose();
                this.colorBuffer.dispose();
                this.glyphBuffer.dispose();
                this.idBuffer.dispose();
              };
              function createPointCloud(options) {
                var gl2 = options.gl;
                var shader = shaders.createPerspective(gl2);
                var orthoShader = shaders.createOrtho(gl2);
                var projectShader = shaders.createProject(gl2);
                var pickPerspectiveShader = shaders.createPickPerspective(gl2);
                var pickOrthoShader = shaders.createPickOrtho(gl2);
                var pickProjectShader = shaders.createPickProject(gl2);
                var pointBuffer = createBuffer(gl2);
                var colorBuffer = createBuffer(gl2);
                var glyphBuffer = createBuffer(gl2);
                var idBuffer = createBuffer(gl2);
                var vao = createVAO(gl2, [
                  {
                    buffer: pointBuffer,
                    size: 3,
                    type: gl2.FLOAT
                  },
                  {
                    buffer: colorBuffer,
                    size: 4,
                    type: gl2.FLOAT
                  },
                  {
                    buffer: glyphBuffer,
                    size: 2,
                    type: gl2.FLOAT
                  },
                  {
                    buffer: idBuffer,
                    size: 4,
                    type: gl2.UNSIGNED_BYTE,
                    normalized: true
                  }
                ]);
                var pointCloud = new PointCloud(
                  gl2,
                  shader,
                  orthoShader,
                  projectShader,
                  pointBuffer,
                  colorBuffer,
                  glyphBuffer,
                  idBuffer,
                  vao,
                  pickPerspectiveShader,
                  pickOrthoShader,
                  pickProjectShader
                );
                pointCloud.update(options);
                return pointCloud;
              }
            }
          ),
          /***/
          8489: (
            /***/
            function(module2) {
              module2.exports = scaleAndAdd;
              function scaleAndAdd(out, a, b, scale) {
                out[0] = a[0] + b[0] * scale;
                out[1] = a[1] + b[1] * scale;
                out[2] = a[2] + b[2] * scale;
                return out;
              }
            }
          ),
          /***/
          8507: (
            /***/
            function(module2) {
              module2.exports = compareCells;
              var min = Math.min;
              function compareInt(a, b) {
                return a - b;
              }
              function compareCells(a, b) {
                var n = a.length, t = a.length - b.length;
                if (t) {
                  return t;
                }
                switch (n) {
                  case 0:
                    return 0;
                  case 1:
                    return a[0] - b[0];
                  case 2:
                    return a[0] + a[1] - b[0] - b[1] || min(a[0], a[1]) - min(b[0], b[1]);
                  case 3:
                    var l1 = a[0] + a[1], m1 = b[0] + b[1];
                    t = l1 + a[2] - (m1 + b[2]);
                    if (t) {
                      return t;
                    }
                    var l0 = min(a[0], a[1]), m0 = min(b[0], b[1]);
                    return min(l0, a[2]) - min(m0, b[2]) || min(l0 + a[2], l1) - min(m0 + b[2], m1);
                  case 4:
                    var aw = a[0], ax = a[1], ay = a[2], az = a[3], bw = b[0], bx = b[1], by = b[2], bz = b[3];
                    return aw + ax + ay + az - (bw + bx + by + bz) || min(aw, ax, ay, az) - min(bw, bx, by, bz, bw) || min(aw + ax, aw + ay, aw + az, ax + ay, ax + az, ay + az) - min(bw + bx, bw + by, bw + bz, bx + by, bx + bz, by + bz) || min(aw + ax + ay, aw + ax + az, aw + ay + az, ax + ay + az) - min(bw + bx + by, bw + bx + bz, bw + by + bz, bx + by + bz);
                  default:
                    var as = a.slice().sort(compareInt);
                    var bs = b.slice().sort(compareInt);
                    for (var i = 0; i < n; ++i) {
                      t = as[i] - bs[i];
                      if (t) {
                        return t;
                      }
                    }
                    return 0;
                }
              }
            }
          ),
          /***/
          8512: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var toPX = __webpack_require__2(665);
              module2.exports = mouseWheelListen;
              function mouseWheelListen(element, callback, noScroll) {
                if (typeof element === "function") {
                  noScroll = !!callback;
                  callback = element;
                  element = window;
                }
                var lineHeight = toPX("ex", element);
                var listener = function(ev) {
                  if (noScroll) {
                    ev.preventDefault();
                  }
                  var dx = ev.deltaX || 0;
                  var dy = ev.deltaY || 0;
                  var dz = ev.deltaZ || 0;
                  var mode = ev.deltaMode;
                  var scale = 1;
                  switch (mode) {
                    case 1:
                      scale = lineHeight;
                      break;
                    case 2:
                      scale = window.innerHeight;
                      break;
                  }
                  dx *= scale;
                  dy *= scale;
                  dz *= scale;
                  if (dx || dy || dz) {
                    return callback(dx, dy, dz, ev);
                  }
                };
                element.addEventListener("wheel", listener);
                return listener;
              }
            }
          ),
          /***/
          8545: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = robustSubtract;
              function scalarScalar(a, b) {
                var x = a + b;
                var bv = x - a;
                var av = x - bv;
                var br = b - bv;
                var ar = a - av;
                var y = ar + br;
                if (y) {
                  return [y, x];
                }
                return [x];
              }
              function robustSubtract(e, f) {
                var ne = e.length | 0;
                var nf = f.length | 0;
                if (ne === 1 && nf === 1) {
                  return scalarScalar(e[0], -f[0]);
                }
                var n = ne + nf;
                var g = new Array(n);
                var count = 0;
                var eptr = 0;
                var fptr = 0;
                var abs = Math.abs;
                var ei = e[eptr];
                var ea = abs(ei);
                var fi = -f[fptr];
                var fa = abs(fi);
                var a, b;
                if (ea < fa) {
                  b = ei;
                  eptr += 1;
                  if (eptr < ne) {
                    ei = e[eptr];
                    ea = abs(ei);
                  }
                } else {
                  b = fi;
                  fptr += 1;
                  if (fptr < nf) {
                    fi = -f[fptr];
                    fa = abs(fi);
                  }
                }
                if (eptr < ne && ea < fa || fptr >= nf) {
                  a = ei;
                  eptr += 1;
                  if (eptr < ne) {
                    ei = e[eptr];
                    ea = abs(ei);
                  }
                } else {
                  a = fi;
                  fptr += 1;
                  if (fptr < nf) {
                    fi = -f[fptr];
                    fa = abs(fi);
                  }
                }
                var x = a + b;
                var bv = x - a;
                var y = b - bv;
                var q0 = y;
                var q1 = x;
                var _x, _bv, _av, _br, _ar;
                while (eptr < ne && fptr < nf) {
                  if (ea < fa) {
                    a = ei;
                    eptr += 1;
                    if (eptr < ne) {
                      ei = e[eptr];
                      ea = abs(ei);
                    }
                  } else {
                    a = fi;
                    fptr += 1;
                    if (fptr < nf) {
                      fi = -f[fptr];
                      fa = abs(fi);
                    }
                  }
                  b = q0;
                  x = a + b;
                  bv = x - a;
                  y = b - bv;
                  if (y) {
                    g[count++] = y;
                  }
                  _x = q1 + x;
                  _bv = _x - q1;
                  _av = _x - _bv;
                  _br = x - _bv;
                  _ar = q1 - _av;
                  q0 = _ar + _br;
                  q1 = _x;
                }
                while (eptr < ne) {
                  a = ei;
                  b = q0;
                  x = a + b;
                  bv = x - a;
                  y = b - bv;
                  if (y) {
                    g[count++] = y;
                  }
                  _x = q1 + x;
                  _bv = _x - q1;
                  _av = _x - _bv;
                  _br = x - _bv;
                  _ar = q1 - _av;
                  q0 = _ar + _br;
                  q1 = _x;
                  eptr += 1;
                  if (eptr < ne) {
                    ei = e[eptr];
                  }
                }
                while (fptr < nf) {
                  a = fi;
                  b = q0;
                  x = a + b;
                  bv = x - a;
                  y = b - bv;
                  if (y) {
                    g[count++] = y;
                  }
                  _x = q1 + x;
                  _bv = _x - q1;
                  _av = _x - _bv;
                  _br = x - _bv;
                  _ar = q1 - _av;
                  q0 = _ar + _br;
                  q1 = _x;
                  fptr += 1;
                  if (fptr < nf) {
                    fi = -f[fptr];
                  }
                }
                if (q0) {
                  g[count++] = q0;
                }
                if (q1) {
                  g[count++] = q1;
                }
                if (!count) {
                  g[count++] = 0;
                }
                g.length = count;
                return g;
              }
            }
          ),
          /***/
          8572: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = function signum(x) {
                if (x < 0) {
                  return -1;
                }
                if (x > 0) {
                  return 1;
                }
                return 0;
              };
            }
          ),
          /***/
          8648: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = __webpack_require__2(783);
            }
          ),
          /***/
          8692: (
            /***/
            function(module2) {
              module2.exports = rotateZ;
              function rotateZ(out, a, b, c) {
                var bx = b[0];
                var by = b[1];
                var px = a[0] - bx;
                var py = a[1] - by;
                var sc = Math.sin(c);
                var cc = Math.cos(c);
                out[0] = bx + px * cc - py * sc;
                out[1] = by + px * sc + py * cc;
                out[2] = a[2];
                return out;
              }
            }
          ),
          /***/
          8697: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var rationalize = __webpack_require__2(869);
              module2.exports = div;
              function div(a, b) {
                return rationalize(a[0].mul(b[1]), a[1].mul(b[0]));
              }
            }
          ),
          /***/
          8731: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createAttributeWrapper;
              var GLError = __webpack_require__2(8866);
              function ShaderAttribute(gl2, wrapper, index, locations, dimension, constFunc) {
                this._gl = gl2;
                this._wrapper = wrapper;
                this._index = index;
                this._locations = locations;
                this._dimension = dimension;
                this._constFunc = constFunc;
              }
              var proto = ShaderAttribute.prototype;
              proto.pointer = function setAttribPointer(type, normalized, stride, offset) {
                var self2 = this;
                var gl2 = self2._gl;
                var location2 = self2._locations[self2._index];
                gl2.vertexAttribPointer(
                  location2,
                  self2._dimension,
                  type || gl2.FLOAT,
                  !!normalized,
                  stride || 0,
                  offset || 0
                );
                gl2.enableVertexAttribArray(location2);
              };
              proto.set = function(x0, x1, x2, x3) {
                return this._constFunc(this._locations[this._index], x0, x1, x2, x3);
              };
              Object.defineProperty(proto, "location", {
                get: function() {
                  return this._locations[this._index];
                },
                set: function(v) {
                  if (v !== this._locations[this._index]) {
                    this._locations[this._index] = v | 0;
                    this._wrapper.program = null;
                  }
                  return v | 0;
                }
              });
              var allFns = [
                function(gl2, v, x0) {
                  if (x0.length === void 0) {
                    return gl2.vertexAttrib1f(v, x0);
                  } else {
                    return gl2.vertexAttrib1fv(v, x0);
                  }
                },
                function(gl2, v, x0, x1) {
                  if (x0.length === void 0) {
                    return gl2.vertexAttrib2f(v, x0, x1);
                  } else {
                    return gl2.vertexAttrib2fv(v, x0);
                  }
                },
                function(gl2, v, x0, x1, x2) {
                  if (x0.length === void 0) {
                    return gl2.vertexAttrib3f(v, x0, x1, x2);
                  } else {
                    return gl2.vertexAttrib3fv(v, x0);
                  }
                },
                function(gl2, v, x0, x1, x2, x3) {
                  if (x0.length === void 0) {
                    return gl2.vertexAttrib4f(v, x0, x1, x2, x3);
                  } else {
                    return gl2.vertexAttrib4fv(v, x0);
                  }
                }
              ];
              function addVectorAttribute(gl2, wrapper, index, locations, dimension, obj, name2) {
                var constFunc = allFns[dimension];
                var attr = new ShaderAttribute(
                  gl2,
                  wrapper,
                  index,
                  locations,
                  dimension,
                  constFunc
                );
                Object.defineProperty(obj, name2, {
                  set: function(x) {
                    gl2.disableVertexAttribArray(locations[index]);
                    constFunc(gl2, locations[index], x);
                    return x;
                  },
                  get: function() {
                    return attr;
                  },
                  enumerable: true
                });
              }
              function addMatrixAttribute(gl2, wrapper, index, locations, dimension, obj, name2) {
                var parts = new Array(dimension);
                var attrs = new Array(dimension);
                for (var i = 0; i < dimension; ++i) {
                  addVectorAttribute(
                    gl2,
                    wrapper,
                    index[i],
                    locations,
                    dimension,
                    parts,
                    i
                  );
                  attrs[i] = parts[i];
                }
                Object.defineProperty(parts, "location", {
                  set: function(v) {
                    if (Array.isArray(v)) {
                      for (var i2 = 0; i2 < dimension; ++i2) {
                        attrs[i2].location = v[i2];
                      }
                    } else {
                      for (var i2 = 0; i2 < dimension; ++i2) {
                        attrs[i2].location = v + i2;
                      }
                    }
                    return v;
                  },
                  get: function() {
                    var result = new Array(dimension);
                    for (var i2 = 0; i2 < dimension; ++i2) {
                      result[i2] = locations[index[i2]];
                    }
                    return result;
                  },
                  enumerable: true
                });
                parts.pointer = function(type, normalized, stride, offset) {
                  type = type || gl2.FLOAT;
                  normalized = !!normalized;
                  stride = stride || dimension * dimension;
                  offset = offset || 0;
                  for (var i2 = 0; i2 < dimension; ++i2) {
                    var location2 = locations[index[i2]];
                    gl2.vertexAttribPointer(
                      location2,
                      dimension,
                      type,
                      normalized,
                      stride,
                      offset + i2 * dimension
                    );
                    gl2.enableVertexAttribArray(location2);
                  }
                };
                var scratch = new Array(dimension);
                var vertexAttrib = gl2["vertexAttrib" + dimension + "fv"];
                Object.defineProperty(obj, name2, {
                  set: function(x) {
                    for (var i2 = 0; i2 < dimension; ++i2) {
                      var loc = locations[index[i2]];
                      gl2.disableVertexAttribArray(loc);
                      if (Array.isArray(x[0])) {
                        vertexAttrib.call(gl2, loc, x[i2]);
                      } else {
                        for (var j = 0; j < dimension; ++j) {
                          scratch[j] = x[dimension * i2 + j];
                        }
                        vertexAttrib.call(gl2, loc, scratch);
                      }
                    }
                    return x;
                  },
                  get: function() {
                    return parts;
                  },
                  enumerable: true
                });
              }
              function createAttributeWrapper(gl2, wrapper, attributes, locations) {
                var obj = {};
                for (var i = 0, n = attributes.length; i < n; ++i) {
                  var a = attributes[i];
                  var name2 = a.name;
                  var type = a.type;
                  var locs = a.locations;
                  switch (type) {
                    case "bool":
                    case "int":
                    case "float":
                      addVectorAttribute(
                        gl2,
                        wrapper,
                        locs[0],
                        locations,
                        1,
                        obj,
                        name2
                      );
                      break;
                    default:
                      if (type.indexOf("vec") >= 0) {
                        var d = type.charCodeAt(type.length - 1) - 48;
                        if (d < 2 || d > 4) {
                          throw new GLError("", "Invalid data type for attribute " + name2 + ": " + type);
                        }
                        addVectorAttribute(
                          gl2,
                          wrapper,
                          locs[0],
                          locations,
                          d,
                          obj,
                          name2
                        );
                      } else if (type.indexOf("mat") >= 0) {
                        var d = type.charCodeAt(type.length - 1) - 48;
                        if (d < 2 || d > 4) {
                          throw new GLError("", "Invalid data type for attribute " + name2 + ": " + type);
                        }
                        addMatrixAttribute(
                          gl2,
                          wrapper,
                          locs,
                          locations,
                          d,
                          obj,
                          name2
                        );
                      } else {
                        throw new GLError("", "Unknown data type for attribute " + name2 + ": " + type);
                      }
                      break;
                  }
                }
                return obj;
              }
            }
          ),
          /***/
          8828: (
            /***/
            function(__unused_webpack_module, exports2) {
              "use strict";
              "use restrict";
              var INT_BITS = 32;
              exports2.INT_BITS = INT_BITS;
              exports2.INT_MAX = 2147483647;
              exports2.INT_MIN = -1 << INT_BITS - 1;
              exports2.sign = function(v) {
                return (v > 0) - (v < 0);
              };
              exports2.abs = function(v) {
                var mask = v >> INT_BITS - 1;
                return (v ^ mask) - mask;
              };
              exports2.min = function(x, y) {
                return y ^ (x ^ y) & -(x < y);
              };
              exports2.max = function(x, y) {
                return x ^ (x ^ y) & -(x < y);
              };
              exports2.isPow2 = function(v) {
                return !(v & v - 1) && !!v;
              };
              exports2.log2 = function(v) {
                var r, shift;
                r = (v > 65535) << 4;
                v >>>= r;
                shift = (v > 255) << 3;
                v >>>= shift;
                r |= shift;
                shift = (v > 15) << 2;
                v >>>= shift;
                r |= shift;
                shift = (v > 3) << 1;
                v >>>= shift;
                r |= shift;
                return r | v >> 1;
              };
              exports2.log10 = function(v) {
                return v >= 1e9 ? 9 : v >= 1e8 ? 8 : v >= 1e7 ? 7 : v >= 1e6 ? 6 : v >= 1e5 ? 5 : v >= 1e4 ? 4 : v >= 1e3 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0;
              };
              exports2.popCount = function(v) {
                v = v - (v >>> 1 & 1431655765);
                v = (v & 858993459) + (v >>> 2 & 858993459);
                return (v + (v >>> 4) & 252645135) * 16843009 >>> 24;
              };
              function countTrailingZeros(v) {
                var c = 32;
                v &= -v;
                if (v) c--;
                if (v & 65535) c -= 16;
                if (v & 16711935) c -= 8;
                if (v & 252645135) c -= 4;
                if (v & 858993459) c -= 2;
                if (v & 1431655765) c -= 1;
                return c;
              }
              exports2.countTrailingZeros = countTrailingZeros;
              exports2.nextPow2 = function(v) {
                v += v === 0;
                --v;
                v |= v >>> 1;
                v |= v >>> 2;
                v |= v >>> 4;
                v |= v >>> 8;
                v |= v >>> 16;
                return v + 1;
              };
              exports2.prevPow2 = function(v) {
                v |= v >>> 1;
                v |= v >>> 2;
                v |= v >>> 4;
                v |= v >>> 8;
                v |= v >>> 16;
                return v - (v >>> 1);
              };
              exports2.parity = function(v) {
                v ^= v >>> 16;
                v ^= v >>> 8;
                v ^= v >>> 4;
                v &= 15;
                return 27030 >>> v & 1;
              };
              var REVERSE_TABLE = new Array(256);
              (function(tab) {
                for (var i = 0; i < 256; ++i) {
                  var v = i, r = i, s = 7;
                  for (v >>>= 1; v; v >>>= 1) {
                    r <<= 1;
                    r |= v & 1;
                    --s;
                  }
                  tab[i] = r << s & 255;
                }
              })(REVERSE_TABLE);
              exports2.reverse = function(v) {
                return REVERSE_TABLE[v & 255] << 24 | REVERSE_TABLE[v >>> 8 & 255] << 16 | REVERSE_TABLE[v >>> 16 & 255] << 8 | REVERSE_TABLE[v >>> 24 & 255];
              };
              exports2.interleave2 = function(x, y) {
                x &= 65535;
                x = (x | x << 8) & 16711935;
                x = (x | x << 4) & 252645135;
                x = (x | x << 2) & 858993459;
                x = (x | x << 1) & 1431655765;
                y &= 65535;
                y = (y | y << 8) & 16711935;
                y = (y | y << 4) & 252645135;
                y = (y | y << 2) & 858993459;
                y = (y | y << 1) & 1431655765;
                return x | y << 1;
              };
              exports2.deinterleave2 = function(v, n) {
                v = v >>> n & 1431655765;
                v = (v | v >>> 1) & 858993459;
                v = (v | v >>> 2) & 252645135;
                v = (v | v >>> 4) & 16711935;
                v = (v | v >>> 16) & 65535;
                return v << 16 >> 16;
              };
              exports2.interleave3 = function(x, y, z) {
                x &= 1023;
                x = (x | x << 16) & 4278190335;
                x = (x | x << 8) & 251719695;
                x = (x | x << 4) & 3272356035;
                x = (x | x << 2) & 1227133513;
                y &= 1023;
                y = (y | y << 16) & 4278190335;
                y = (y | y << 8) & 251719695;
                y = (y | y << 4) & 3272356035;
                y = (y | y << 2) & 1227133513;
                x |= y << 1;
                z &= 1023;
                z = (z | z << 16) & 4278190335;
                z = (z | z << 8) & 251719695;
                z = (z | z << 4) & 3272356035;
                z = (z | z << 2) & 1227133513;
                return x | z << 2;
              };
              exports2.deinterleave3 = function(v, n) {
                v = v >>> n & 1227133513;
                v = (v | v >>> 2) & 3272356035;
                v = (v | v >>> 4) & 251719695;
                v = (v | v >>> 8) & 4278190335;
                v = (v | v >>> 16) & 1023;
                return v << 22 >> 22;
              };
              exports2.nextCombination = function(v) {
                var t = v | v - 1;
                return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1;
              };
            }
          ),
          /***/
          8866: (
            /***/
            function(module2) {
              function GLError(rawError, shortMessage, longMessage) {
                this.shortMessage = shortMessage || "";
                this.longMessage = longMessage || "";
                this.rawError = rawError || "";
                this.message = "gl-shader: " + (shortMessage || rawError || "") + (longMessage ? "\n" + longMessage : "");
                this.stack = new Error().stack;
              }
              GLError.prototype = new Error();
              GLError.prototype.name = "GLError";
              GLError.prototype.constructor = GLError;
              module2.exports = GLError;
            }
          ),
          /***/
          8902: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var bsearch = __webpack_require__2(2478);
              var orient = __webpack_require__2(3250)[3];
              var EVENT_POINT = 0;
              var EVENT_END = 1;
              var EVENT_START = 2;
              module2.exports = monotoneTriangulate;
              function PartialHull(a, b, idx, lowerIds, upperIds) {
                this.a = a;
                this.b = b;
                this.idx = idx;
                this.lowerIds = lowerIds;
                this.upperIds = upperIds;
              }
              function Event(a, b, type, idx) {
                this.a = a;
                this.b = b;
                this.type = type;
                this.idx = idx;
              }
              function compareEvent(a, b) {
                var d = a.a[0] - b.a[0] || a.a[1] - b.a[1] || a.type - b.type;
                if (d) {
                  return d;
                }
                if (a.type !== EVENT_POINT) {
                  d = orient(a.a, a.b, b.b);
                  if (d) {
                    return d;
                  }
                }
                return a.idx - b.idx;
              }
              function testPoint(hull, p) {
                return orient(hull.a, hull.b, p);
              }
              function addPoint(cells, hulls, points, p, idx) {
                var lo = bsearch.lt(hulls, p, testPoint);
                var hi = bsearch.gt(hulls, p, testPoint);
                for (var i = lo; i < hi; ++i) {
                  var hull = hulls[i];
                  var lowerIds = hull.lowerIds;
                  var m = lowerIds.length;
                  while (m > 1 && orient(
                    points[lowerIds[m - 2]],
                    points[lowerIds[m - 1]],
                    p
                  ) > 0) {
                    cells.push(
                      [
                        lowerIds[m - 1],
                        lowerIds[m - 2],
                        idx
                      ]
                    );
                    m -= 1;
                  }
                  lowerIds.length = m;
                  lowerIds.push(idx);
                  var upperIds = hull.upperIds;
                  var m = upperIds.length;
                  while (m > 1 && orient(
                    points[upperIds[m - 2]],
                    points[upperIds[m - 1]],
                    p
                  ) < 0) {
                    cells.push(
                      [
                        upperIds[m - 2],
                        upperIds[m - 1],
                        idx
                      ]
                    );
                    m -= 1;
                  }
                  upperIds.length = m;
                  upperIds.push(idx);
                }
              }
              function findSplit(hull, edge) {
                var d;
                if (hull.a[0] < edge.a[0]) {
                  d = orient(hull.a, hull.b, edge.a);
                } else {
                  d = orient(edge.b, edge.a, hull.a);
                }
                if (d) {
                  return d;
                }
                if (edge.b[0] < hull.b[0]) {
                  d = orient(hull.a, hull.b, edge.b);
                } else {
                  d = orient(edge.b, edge.a, hull.b);
                }
                return d || hull.idx - edge.idx;
              }
              function splitHulls(hulls, points, event) {
                var splitIdx = bsearch.le(hulls, event, findSplit);
                var hull = hulls[splitIdx];
                var upperIds = hull.upperIds;
                var x = upperIds[upperIds.length - 1];
                hull.upperIds = [x];
                hulls.splice(
                  splitIdx + 1,
                  0,
                  new PartialHull(event.a, event.b, event.idx, [x], upperIds)
                );
              }
              function mergeHulls(hulls, points, event) {
                var tmp = event.a;
                event.a = event.b;
                event.b = tmp;
                var mergeIdx = bsearch.eq(hulls, event, findSplit);
                var upper = hulls[mergeIdx];
                var lower = hulls[mergeIdx - 1];
                lower.upperIds = upper.upperIds;
                hulls.splice(mergeIdx, 1);
              }
              function monotoneTriangulate(points, edges) {
                var numPoints = points.length;
                var numEdges = edges.length;
                var events = [];
                for (var i = 0; i < numPoints; ++i) {
                  events.push(new Event(
                    points[i],
                    null,
                    EVENT_POINT,
                    i
                  ));
                }
                for (var i = 0; i < numEdges; ++i) {
                  var e = edges[i];
                  var a = points[e[0]];
                  var b = points[e[1]];
                  if (a[0] < b[0]) {
                    events.push(
                      new Event(a, b, EVENT_START, i),
                      new Event(b, a, EVENT_END, i)
                    );
                  } else if (a[0] > b[0]) {
                    events.push(
                      new Event(b, a, EVENT_START, i),
                      new Event(a, b, EVENT_END, i)
                    );
                  }
                }
                events.sort(compareEvent);
                var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52);
                var hull = [new PartialHull([minX, 1], [minX, 0], -1, [], [], [], [])];
                var cells = [];
                for (var i = 0, numEvents = events.length; i < numEvents; ++i) {
                  var event = events[i];
                  var type = event.type;
                  if (type === EVENT_POINT) {
                    addPoint(cells, hull, points, event.a, event.idx);
                  } else if (type === EVENT_START) {
                    splitHulls(hull, points, event);
                  } else {
                    mergeHulls(hull, points, event);
                  }
                }
                return cells;
              }
            }
          ),
          /***/
          8954: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = incrementalConvexHull;
              var orient = __webpack_require__2(3250);
              var compareCell = __webpack_require__2(6803).Fw;
              function Simplex(vertices, adjacent, boundary) {
                this.vertices = vertices;
                this.adjacent = adjacent;
                this.boundary = boundary;
                this.lastVisited = -1;
              }
              Simplex.prototype.flip = function() {
                var t = this.vertices[0];
                this.vertices[0] = this.vertices[1];
                this.vertices[1] = t;
                var u = this.adjacent[0];
                this.adjacent[0] = this.adjacent[1];
                this.adjacent[1] = u;
              };
              function GlueFacet(vertices, cell, index) {
                this.vertices = vertices;
                this.cell = cell;
                this.index = index;
              }
              function compareGlue(a, b) {
                return compareCell(a.vertices, b.vertices);
              }
              function wrapper(test) {
                return function() {
                  var tuple = this.tuple;
                  return test.apply(this, tuple);
                };
              }
              function bakeOrient(d) {
                var test = orient[d + 1];
                if (!test) {
                  test = orient;
                }
                return wrapper(test);
              }
              var BAKED = [];
              function Triangulation(dimension, vertices, simplices) {
                this.dimension = dimension;
                this.vertices = vertices;
                this.simplices = simplices;
                this.interior = simplices.filter(function(c) {
                  return !c.boundary;
                });
                this.tuple = new Array(dimension + 1);
                for (var i = 0; i <= dimension; ++i) {
                  this.tuple[i] = this.vertices[i];
                }
                var o = BAKED[dimension];
                if (!o) {
                  o = BAKED[dimension] = bakeOrient(dimension);
                }
                this.orient = o;
              }
              var proto = Triangulation.prototype;
              proto.handleBoundaryDegeneracy = function(cell, point) {
                var d = this.dimension;
                var n = this.vertices.length - 1;
                var tuple = this.tuple;
                var verts = this.vertices;
                var toVisit = [cell];
                cell.lastVisited = -n;
                while (toVisit.length > 0) {
                  cell = toVisit.pop();
                  var cellAdj = cell.adjacent;
                  for (var i = 0; i <= d; ++i) {
                    var neighbor = cellAdj[i];
                    if (!neighbor.boundary || neighbor.lastVisited <= -n) {
                      continue;
                    }
                    var nv = neighbor.vertices;
                    for (var j = 0; j <= d; ++j) {
                      var vv = nv[j];
                      if (vv < 0) {
                        tuple[j] = point;
                      } else {
                        tuple[j] = verts[vv];
                      }
                    }
                    var o = this.orient();
                    if (o > 0) {
                      return neighbor;
                    }
                    neighbor.lastVisited = -n;
                    if (o === 0) {
                      toVisit.push(neighbor);
                    }
                  }
                }
                return null;
              };
              proto.walk = function(point, random) {
                var n = this.vertices.length - 1;
                var d = this.dimension;
                var verts = this.vertices;
                var tuple = this.tuple;
                var initIndex = random ? this.interior.length * Math.random() | 0 : this.interior.length - 1;
                var cell = this.interior[initIndex];
                outerLoop:
                  while (!cell.boundary) {
                    var cellVerts = cell.vertices;
                    var cellAdj = cell.adjacent;
                    for (var i = 0; i <= d; ++i) {
                      tuple[i] = verts[cellVerts[i]];
                    }
                    cell.lastVisited = n;
                    for (var i = 0; i <= d; ++i) {
                      var neighbor = cellAdj[i];
                      if (neighbor.lastVisited >= n) {
                        continue;
                      }
                      var prev = tuple[i];
                      tuple[i] = point;
                      var o = this.orient();
                      tuple[i] = prev;
                      if (o < 0) {
                        cell = neighbor;
                        continue outerLoop;
                      } else {
                        if (!neighbor.boundary) {
                          neighbor.lastVisited = n;
                        } else {
                          neighbor.lastVisited = -n;
                        }
                      }
                    }
                    return;
                  }
                return cell;
              };
              proto.addPeaks = function(point, cell) {
                var n = this.vertices.length - 1;
                var d = this.dimension;
                var verts = this.vertices;
                var tuple = this.tuple;
                var interior = this.interior;
                var simplices = this.simplices;
                var tovisit = [cell];
                cell.lastVisited = n;
                cell.vertices[cell.vertices.indexOf(-1)] = n;
                cell.boundary = false;
                interior.push(cell);
                var glueFacets = [];
                while (tovisit.length > 0) {
                  var cell = tovisit.pop();
                  var cellVerts = cell.vertices;
                  var cellAdj = cell.adjacent;
                  var indexOfN = cellVerts.indexOf(n);
                  if (indexOfN < 0) {
                    continue;
                  }
                  for (var i = 0; i <= d; ++i) {
                    if (i === indexOfN) {
                      continue;
                    }
                    var neighbor = cellAdj[i];
                    if (!neighbor.boundary || neighbor.lastVisited >= n) {
                      continue;
                    }
                    var nv = neighbor.vertices;
                    if (neighbor.lastVisited !== -n) {
                      var indexOfNeg1 = 0;
                      for (var j = 0; j <= d; ++j) {
                        if (nv[j] < 0) {
                          indexOfNeg1 = j;
                          tuple[j] = point;
                        } else {
                          tuple[j] = verts[nv[j]];
                        }
                      }
                      var o = this.orient();
                      if (o > 0) {
                        nv[indexOfNeg1] = n;
                        neighbor.boundary = false;
                        interior.push(neighbor);
                        tovisit.push(neighbor);
                        neighbor.lastVisited = n;
                        continue;
                      } else {
                        neighbor.lastVisited = -n;
                      }
                    }
                    var na = neighbor.adjacent;
                    var vverts = cellVerts.slice();
                    var vadj = cellAdj.slice();
                    var ncell = new Simplex(vverts, vadj, true);
                    simplices.push(ncell);
                    var opposite = na.indexOf(cell);
                    if (opposite < 0) {
                      continue;
                    }
                    na[opposite] = ncell;
                    vadj[indexOfN] = neighbor;
                    vverts[i] = -1;
                    vadj[i] = cell;
                    cellAdj[i] = ncell;
                    ncell.flip();
                    for (var j = 0; j <= d; ++j) {
                      var uu = vverts[j];
                      if (uu < 0 || uu === n) {
                        continue;
                      }
                      var nface = new Array(d - 1);
                      var nptr = 0;
                      for (var k = 0; k <= d; ++k) {
                        var vv = vverts[k];
                        if (vv < 0 || k === j) {
                          continue;
                        }
                        nface[nptr++] = vv;
                      }
                      glueFacets.push(new GlueFacet(nface, ncell, j));
                    }
                  }
                }
                glueFacets.sort(compareGlue);
                for (var i = 0; i + 1 < glueFacets.length; i += 2) {
                  var a = glueFacets[i];
                  var b = glueFacets[i + 1];
                  var ai = a.index;
                  var bi = b.index;
                  if (ai < 0 || bi < 0) {
                    continue;
                  }
                  a.cell.adjacent[a.index] = b.cell;
                  b.cell.adjacent[b.index] = a.cell;
                }
              };
              proto.insert = function(point, random) {
                var verts = this.vertices;
                verts.push(point);
                var cell = this.walk(point, random);
                if (!cell) {
                  return;
                }
                var d = this.dimension;
                var tuple = this.tuple;
                for (var i = 0; i <= d; ++i) {
                  var vv = cell.vertices[i];
                  if (vv < 0) {
                    tuple[i] = point;
                  } else {
                    tuple[i] = verts[vv];
                  }
                }
                var o = this.orient(tuple);
                if (o < 0) {
                  return;
                } else if (o === 0) {
                  cell = this.handleBoundaryDegeneracy(cell, point);
                  if (!cell) {
                    return;
                  }
                }
                this.addPeaks(point, cell);
              };
              proto.boundary = function() {
                var d = this.dimension;
                var boundary = [];
                var cells = this.simplices;
                var nc = cells.length;
                for (var i = 0; i < nc; ++i) {
                  var c = cells[i];
                  if (c.boundary) {
                    var bcell = new Array(d);
                    var cv = c.vertices;
                    var ptr = 0;
                    var parity = 0;
                    for (var j = 0; j <= d; ++j) {
                      if (cv[j] >= 0) {
                        bcell[ptr++] = cv[j];
                      } else {
                        parity = j & 1;
                      }
                    }
                    if (parity === (d & 1)) {
                      var t = bcell[0];
                      bcell[0] = bcell[1];
                      bcell[1] = t;
                    }
                    boundary.push(bcell);
                  }
                }
                return boundary;
              };
              function incrementalConvexHull(points, randomSearch) {
                var n = points.length;
                if (n === 0) {
                  throw new Error("Must have at least d+1 points");
                }
                var d = points[0].length;
                if (n <= d) {
                  throw new Error("Must input at least d+1 points");
                }
                var initialSimplex = points.slice(0, d + 1);
                var o = orient.apply(void 0, initialSimplex);
                if (o === 0) {
                  throw new Error("Input not in general position");
                }
                var initialCoords = new Array(d + 1);
                for (var i = 0; i <= d; ++i) {
                  initialCoords[i] = i;
                }
                if (o < 0) {
                  initialCoords[0] = 1;
                  initialCoords[1] = 0;
                }
                var initialCell = new Simplex(initialCoords, new Array(d + 1), false);
                var boundary = initialCell.adjacent;
                var list = new Array(d + 2);
                for (var i = 0; i <= d; ++i) {
                  var verts = initialCoords.slice();
                  for (var j = 0; j <= d; ++j) {
                    if (j === i) {
                      verts[j] = -1;
                    }
                  }
                  var t = verts[0];
                  verts[0] = verts[1];
                  verts[1] = t;
                  var cell = new Simplex(verts, new Array(d + 1), true);
                  boundary[i] = cell;
                  list[i] = cell;
                }
                list[d + 1] = initialCell;
                for (var i = 0; i <= d; ++i) {
                  var verts = boundary[i].vertices;
                  var adj = boundary[i].adjacent;
                  for (var j = 0; j <= d; ++j) {
                    var v = verts[j];
                    if (v < 0) {
                      adj[j] = initialCell;
                      continue;
                    }
                    for (var k = 0; k <= d; ++k) {
                      if (boundary[k].vertices.indexOf(v) < 0) {
                        adj[j] = boundary[k];
                      }
                    }
                  }
                }
                var triangles = new Triangulation(d, initialSimplex, list);
                var useRandom = !!randomSearch;
                for (var i = d + 1; i < n; ++i) {
                  triangles.insert(points[i], useRandom);
                }
                return triangles.boundary();
              }
            }
          ),
          /***/
          8987: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var rat = __webpack_require__2(7842);
              var mul = __webpack_require__2(6504);
              module2.exports = muls;
              function muls(a, x) {
                var s = rat(x);
                var n = a.length;
                var r = new Array(n);
                for (var i = 0; i < n; ++i) {
                  r[i] = mul(a[i], s);
                }
                return r;
              }
            }
          ),
          /***/
          9060: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var createShader = __webpack_require__2(9405);
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createTexture = __webpack_require__2(7766);
              var multiply = __webpack_require__2(6760);
              var invert = __webpack_require__2(7608);
              var ndarray = __webpack_require__2(9618);
              var colormap = __webpack_require__2(6729);
              var IDENTITY = [
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ];
              function VectorMesh(gl2, texture, triShader, pickShader, trianglePositions, triangleVectors, triangleIds, triangleColors, triangleUVs, triangleVAO, traceType) {
                this.gl = gl2;
                this.pixelRatio = 1;
                this.cells = [];
                this.positions = [];
                this.intensity = [];
                this.texture = texture;
                this.dirty = true;
                this.triShader = triShader;
                this.pickShader = pickShader;
                this.trianglePositions = trianglePositions;
                this.triangleVectors = triangleVectors;
                this.triangleColors = triangleColors;
                this.triangleUVs = triangleUVs;
                this.triangleIds = triangleIds;
                this.triangleVAO = triangleVAO;
                this.triangleCount = 0;
                this.pickId = 1;
                this.bounds = [
                  [Infinity, Infinity, Infinity],
                  [-Infinity, -Infinity, -Infinity]
                ];
                this.clipBounds = [
                  [-Infinity, -Infinity, -Infinity],
                  [Infinity, Infinity, Infinity]
                ];
                this.lightPosition = [1e5, 1e5, 0];
                this.ambientLight = 0.8;
                this.diffuseLight = 0.8;
                this.specularLight = 2;
                this.roughness = 0.5;
                this.fresnel = 1.5;
                this.opacity = 1;
                this.traceType = traceType;
                this.tubeScale = 1;
                this.coneScale = 2;
                this.vectorScale = 1;
                this.coneOffset = 0.25;
                this._model = IDENTITY;
                this._view = IDENTITY;
                this._projection = IDENTITY;
                this._resolution = [1, 1];
              }
              var proto = VectorMesh.prototype;
              proto.isOpaque = function() {
                return this.opacity >= 1;
              };
              proto.isTransparent = function() {
                return this.opacity < 1;
              };
              proto.pickSlots = 1;
              proto.setPickBase = function(id) {
                this.pickId = id;
              };
              function genColormap(param) {
                var colors = colormap({
                  colormap: param,
                  nshades: 256,
                  format: "rgba"
                });
                var result = new Uint8Array(256 * 4);
                for (var i = 0; i < 256; ++i) {
                  var c = colors[i];
                  for (var j = 0; j < 3; ++j) {
                    result[4 * i + j] = c[j];
                  }
                  result[4 * i + 3] = c[3] * 255;
                }
                return ndarray(result, [256, 256, 4], [4, 0, 1]);
              }
              function takeZComponent(array) {
                var n = array.length;
                var result = new Array(n);
                for (var i = 0; i < n; ++i) {
                  result[i] = array[i][2];
                }
                return result;
              }
              proto.update = function(params) {
                params = params || {};
                var gl2 = this.gl;
                this.dirty = true;
                if ("lightPosition" in params) {
                  this.lightPosition = params.lightPosition;
                }
                if ("opacity" in params) {
                  this.opacity = params.opacity;
                }
                if ("ambient" in params) {
                  this.ambientLight = params.ambient;
                }
                if ("diffuse" in params) {
                  this.diffuseLight = params.diffuse;
                }
                if ("specular" in params) {
                  this.specularLight = params.specular;
                }
                if ("roughness" in params) {
                  this.roughness = params.roughness;
                }
                if ("fresnel" in params) {
                  this.fresnel = params.fresnel;
                }
                if (params.tubeScale !== void 0) {
                  this.tubeScale = params.tubeScale;
                }
                if (params.vectorScale !== void 0) {
                  this.vectorScale = params.vectorScale;
                }
                if (params.coneScale !== void 0) {
                  this.coneScale = params.coneScale;
                }
                if (params.coneOffset !== void 0) {
                  this.coneOffset = params.coneOffset;
                }
                if (params.colormap) {
                  this.texture.shape = [256, 256];
                  this.texture.minFilter = gl2.LINEAR_MIPMAP_LINEAR;
                  this.texture.magFilter = gl2.LINEAR;
                  this.texture.setPixels(genColormap(params.colormap));
                  this.texture.generateMipmap();
                }
                var cells = params.cells;
                var positions = params.positions;
                var vectors = params.vectors;
                if (!positions || !cells || !vectors) {
                  return;
                }
                var tPos = [];
                var tVec = [];
                var tCol = [];
                var tUVs = [];
                var tIds = [];
                this.cells = cells;
                this.positions = positions;
                this.vectors = vectors;
                var meshColor = params.meshColor || [1, 1, 1, 1];
                var vertexIntensity = params.vertexIntensity;
                var intensityLo = Infinity;
                var intensityHi = -Infinity;
                if (vertexIntensity) {
                  if (params.vertexIntensityBounds) {
                    intensityLo = +params.vertexIntensityBounds[0];
                    intensityHi = +params.vertexIntensityBounds[1];
                  } else {
                    for (var i = 0; i < vertexIntensity.length; ++i) {
                      var f = vertexIntensity[i];
                      intensityLo = Math.min(intensityLo, f);
                      intensityHi = Math.max(intensityHi, f);
                    }
                  }
                } else {
                  for (var i = 0; i < positions.length; ++i) {
                    var f = positions[i][2];
                    intensityLo = Math.min(intensityLo, f);
                    intensityHi = Math.max(intensityHi, f);
                  }
                }
                if (vertexIntensity) {
                  this.intensity = vertexIntensity;
                } else {
                  this.intensity = takeZComponent(positions);
                }
                this.bounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
                for (var i = 0; i < positions.length; ++i) {
                  var p = positions[i];
                  for (var j = 0; j < 3; ++j) {
                    if (isNaN(p[j]) || !isFinite(p[j])) {
                      continue;
                    }
                    this.bounds[0][j] = Math.min(this.bounds[0][j], p[j]);
                    this.bounds[1][j] = Math.max(this.bounds[1][j], p[j]);
                  }
                }
                var triangleCount = 0;
                fill_loop:
                  for (var i = 0; i < cells.length; ++i) {
                    var cell = cells[i];
                    switch (cell.length) {
                      case 3:
                        for (var j = 0; j < 3; ++j) {
                          var v = cell[j];
                          var p = positions[v];
                          for (var k = 0; k < 3; ++k) {
                            if (isNaN(p[k]) || !isFinite(p[k])) {
                              continue fill_loop;
                            }
                          }
                        }
                        for (var j = 0; j < 3; ++j) {
                          var v = cell[2 - j];
                          var p = positions[v];
                          tPos.push(p[0], p[1], p[2], p[3]);
                          var w = vectors[v];
                          tVec.push(w[0], w[1], w[2], w[3] || 0);
                          var c = meshColor;
                          if (c.length === 3) {
                            tCol.push(c[0], c[1], c[2], 1);
                          } else {
                            tCol.push(c[0], c[1], c[2], c[3]);
                          }
                          var uv;
                          if (vertexIntensity) {
                            uv = [
                              (vertexIntensity[v] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          } else {
                            uv = [
                              (p[2] - intensityLo) / (intensityHi - intensityLo),
                              0
                            ];
                          }
                          tUVs.push(uv[0], uv[1]);
                          tIds.push(i);
                        }
                        triangleCount += 1;
                        break;
                      default:
                        break;
                    }
                  }
                this.triangleCount = triangleCount;
                this.trianglePositions.update(tPos);
                this.triangleVectors.update(tVec);
                this.triangleColors.update(tCol);
                this.triangleUVs.update(tUVs);
                this.triangleIds.update(new Uint32Array(tIds));
              };
              proto.drawTransparent = proto.draw = function(params) {
                params = params || {};
                var gl2 = this.gl;
                var model = params.model || IDENTITY;
                var view = params.view || IDENTITY;
                var projection = params.projection || IDENTITY;
                var clipBounds = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]];
                for (var i = 0; i < 3; ++i) {
                  clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]);
                  clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]);
                }
                var uniforms = {
                  model,
                  view,
                  projection,
                  inverseModel: IDENTITY.slice(),
                  clipBounds,
                  kambient: this.ambientLight,
                  kdiffuse: this.diffuseLight,
                  kspecular: this.specularLight,
                  roughness: this.roughness,
                  fresnel: this.fresnel,
                  eyePosition: [0, 0, 0],
                  lightPosition: [0, 0, 0],
                  opacity: this.opacity,
                  tubeScale: this.tubeScale,
                  vectorScale: this.vectorScale,
                  coneScale: this.coneScale,
                  coneOffset: this.coneOffset,
                  texture: 0
                };
                uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model);
                gl2.disable(gl2.CULL_FACE);
                this.texture.bind(0);
                var invCameraMatrix = new Array(16);
                multiply(invCameraMatrix, uniforms.view, uniforms.model);
                multiply(invCameraMatrix, uniforms.projection, invCameraMatrix);
                invert(invCameraMatrix, invCameraMatrix);
                for (var i = 0; i < 3; ++i) {
                  uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15];
                }
                var w = invCameraMatrix[15];
                for (var i = 0; i < 3; ++i) {
                  w += this.lightPosition[i] * invCameraMatrix[4 * i + 3];
                }
                for (var i = 0; i < 3; ++i) {
                  var s = invCameraMatrix[12 + i];
                  for (var j = 0; j < 3; ++j) {
                    s += invCameraMatrix[4 * j + i] * this.lightPosition[j];
                  }
                  uniforms.lightPosition[i] = s / w;
                }
                if (this.triangleCount > 0) {
                  var shader = this.triShader;
                  shader.bind();
                  shader.uniforms = uniforms;
                  this.triangleVAO.bind();
                  gl2.drawArrays(gl2.TRIANGLES, 0, this.triangleCount * 3);
                  this.triangleVAO.unbind();
                }
              };
              proto.drawPick = function(params) {
                params = params || {};
                var gl2 = this.gl;
                var model = params.model || IDENTITY;
                var view = params.view || IDENTITY;
                var projection = params.projection || IDENTITY;
                var clipBounds = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]];
                for (var i = 0; i < 3; ++i) {
                  clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]);
                  clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]);
                }
                this._model = [].slice.call(model);
                this._view = [].slice.call(view);
                this._projection = [].slice.call(projection);
                this._resolution = [gl2.drawingBufferWidth, gl2.drawingBufferHeight];
                var uniforms = {
                  model,
                  view,
                  projection,
                  clipBounds,
                  tubeScale: this.tubeScale,
                  vectorScale: this.vectorScale,
                  coneScale: this.coneScale,
                  coneOffset: this.coneOffset,
                  pickId: this.pickId / 255
                };
                var shader = this.pickShader;
                shader.bind();
                shader.uniforms = uniforms;
                if (this.triangleCount > 0) {
                  this.triangleVAO.bind();
                  gl2.drawArrays(gl2.TRIANGLES, 0, this.triangleCount * 3);
                  this.triangleVAO.unbind();
                }
              };
              proto.pick = function(pickData) {
                if (!pickData) {
                  return null;
                }
                if (pickData.id !== this.pickId) {
                  return null;
                }
                var cellId = pickData.value[0] + 256 * pickData.value[1] + 65536 * pickData.value[2];
                var cell = this.cells[cellId];
                var pos = this.positions[cell[1]].slice(0, 3);
                var result = {
                  position: pos,
                  dataCoordinate: pos,
                  index: Math.floor(cell[1] / 48)
                };
                if (this.traceType === "cone") {
                  result.index = Math.floor(cell[1] / 48);
                } else if (this.traceType === "streamtube") {
                  result.intensity = this.intensity[cell[1]];
                  result.velocity = this.vectors[cell[1]].slice(0, 3);
                  result.divergence = this.vectors[cell[1]][3];
                  result.index = cellId;
                }
                return result;
              };
              proto.dispose = function() {
                this.texture.dispose();
                this.triShader.dispose();
                this.pickShader.dispose();
                this.triangleVAO.dispose();
                this.trianglePositions.dispose();
                this.triangleVectors.dispose();
                this.triangleColors.dispose();
                this.triangleUVs.dispose();
                this.triangleIds.dispose();
              };
              function createMeshShader(gl2, shaders) {
                var shader = createShader(
                  gl2,
                  shaders.meshShader.vertex,
                  shaders.meshShader.fragment,
                  null,
                  shaders.meshShader.attributes
                );
                shader.attributes.position.location = 0;
                shader.attributes.color.location = 2;
                shader.attributes.uv.location = 3;
                shader.attributes.vector.location = 4;
                return shader;
              }
              function createPickShader(gl2, shaders) {
                var shader = createShader(
                  gl2,
                  shaders.pickShader.vertex,
                  shaders.pickShader.fragment,
                  null,
                  shaders.pickShader.attributes
                );
                shader.attributes.position.location = 0;
                shader.attributes.id.location = 1;
                shader.attributes.vector.location = 4;
                return shader;
              }
              function createVectorMesh(gl2, params, opts) {
                var shaders = opts.shaders;
                if (arguments.length === 1) {
                  params = gl2;
                  gl2 = params.gl;
                }
                var triShader = createMeshShader(gl2, shaders);
                var pickShader = createPickShader(gl2, shaders);
                var meshTexture = createTexture(
                  gl2,
                  ndarray(new Uint8Array([255, 255, 255, 255]), [1, 1, 4])
                );
                meshTexture.generateMipmap();
                meshTexture.minFilter = gl2.LINEAR_MIPMAP_LINEAR;
                meshTexture.magFilter = gl2.LINEAR;
                var trianglePositions = createBuffer(gl2);
                var triangleVectors = createBuffer(gl2);
                var triangleColors = createBuffer(gl2);
                var triangleUVs = createBuffer(gl2);
                var triangleIds = createBuffer(gl2);
                var triangleVAO = createVAO(gl2, [
                  {
                    buffer: trianglePositions,
                    type: gl2.FLOAT,
                    size: 4
                  },
                  {
                    buffer: triangleIds,
                    type: gl2.UNSIGNED_BYTE,
                    size: 4,
                    normalized: true
                  },
                  {
                    buffer: triangleColors,
                    type: gl2.FLOAT,
                    size: 4
                  },
                  {
                    buffer: triangleUVs,
                    type: gl2.FLOAT,
                    size: 2
                  },
                  {
                    buffer: triangleVectors,
                    type: gl2.FLOAT,
                    size: 4
                  }
                ]);
                var mesh = new VectorMesh(
                  gl2,
                  meshTexture,
                  triShader,
                  pickShader,
                  trianglePositions,
                  triangleVectors,
                  triangleIds,
                  triangleColors,
                  triangleUVs,
                  triangleVAO,
                  opts.traceType || "cone"
                );
                mesh.update(params);
                return mesh;
              }
              module2.exports = createVectorMesh;
            }
          ),
          /***/
          9127: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = boundary;
              var bnd = __webpack_require__2(6204);
              var reduce = __webpack_require__2(5771);
              function boundary(cells) {
                return reduce(bnd(cells));
              }
            }
          ),
          /***/
          9131: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var vecNormalize = __webpack_require__2(5177);
              var vecScale = __webpack_require__2(9288);
              module2.exports = random;
              function random(out, scale) {
                scale = scale || 1;
                out[0] = Math.random();
                out[1] = Math.random();
                out[2] = Math.random();
                out[3] = Math.random();
                vecNormalize(out, out);
                vecScale(out, out, scale);
                return out;
              }
            }
          ),
          /***/
          9165: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createErrorBars;
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createShader = __webpack_require__2(3436);
              var IDENTITY = [
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ];
              function ErrorBars(gl2, buffer, vao, shader) {
                this.gl = gl2;
                this.shader = shader;
                this.buffer = buffer;
                this.vao = vao;
                this.pixelRatio = 1;
                this.bounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
                this.clipBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]];
                this.lineWidth = [1, 1, 1];
                this.capSize = [10, 10, 10];
                this.lineCount = [0, 0, 0];
                this.lineOffset = [0, 0, 0];
                this.opacity = 1;
                this.hasAlpha = false;
              }
              var proto = ErrorBars.prototype;
              proto.isOpaque = function() {
                return !this.hasAlpha;
              };
              proto.isTransparent = function() {
                return this.hasAlpha;
              };
              proto.drawTransparent = proto.draw = function(cameraParams) {
                var gl2 = this.gl;
                var uniforms = this.shader.uniforms;
                this.shader.bind();
                var view = uniforms.view = cameraParams.view || IDENTITY;
                var projection = uniforms.projection = cameraParams.projection || IDENTITY;
                uniforms.model = cameraParams.model || IDENTITY;
                uniforms.clipBounds = this.clipBounds;
                uniforms.opacity = this.opacity;
                var cx = view[12];
                var cy = view[13];
                var cz = view[14];
                var cw = view[15];
                var isOrtho = cameraParams._ortho || false;
                var orthoFix = isOrtho ? 2 : 1;
                var pixelScaleF = orthoFix * this.pixelRatio * (projection[3] * cx + projection[7] * cy + projection[11] * cz + projection[15] * cw) / gl2.drawingBufferHeight;
                this.vao.bind();
                for (var i = 0; i < 3; ++i) {
                  gl2.lineWidth(this.lineWidth[i] * this.pixelRatio);
                  uniforms.capSize = this.capSize[i] * pixelScaleF;
                  if (this.lineCount[i]) {
                    gl2.drawArrays(gl2.LINES, this.lineOffset[i], this.lineCount[i]);
                  }
                }
                this.vao.unbind();
              };
              function updateBounds(bounds, point) {
                for (var i = 0; i < 3; ++i) {
                  bounds[0][i] = Math.min(bounds[0][i], point[i]);
                  bounds[1][i] = Math.max(bounds[1][i], point[i]);
                }
              }
              var FACE_TABLE = function() {
                var table = new Array(3);
                for (var d = 0; d < 3; ++d) {
                  var row = [];
                  for (var j = 1; j <= 2; ++j) {
                    for (var s = -1; s <= 1; s += 2) {
                      var u = (j + d) % 3;
                      var y = [0, 0, 0];
                      y[u] = s;
                      row.push(y);
                    }
                  }
                  table[d] = row;
                }
                return table;
              }();
              function emitFace(verts, x, c, d) {
                var offsets = FACE_TABLE[d];
                for (var i = 0; i < offsets.length; ++i) {
                  var o = offsets[i];
                  verts.push(
                    x[0],
                    x[1],
                    x[2],
                    c[0],
                    c[1],
                    c[2],
                    c[3],
                    o[0],
                    o[1],
                    o[2]
                  );
                }
                return offsets.length;
              }
              proto.update = function(options) {
                options = options || {};
                if ("lineWidth" in options) {
                  this.lineWidth = options.lineWidth;
                  if (!Array.isArray(this.lineWidth)) {
                    this.lineWidth = [this.lineWidth, this.lineWidth, this.lineWidth];
                  }
                }
                if ("capSize" in options) {
                  this.capSize = options.capSize;
                  if (!Array.isArray(this.capSize)) {
                    this.capSize = [this.capSize, this.capSize, this.capSize];
                  }
                }
                this.hasAlpha = false;
                if ("opacity" in options) {
                  this.opacity = +options.opacity;
                  if (this.opacity < 1) {
                    this.hasAlpha = true;
                  }
                }
                var color2 = options.color || [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
                var position = options.position;
                var error = options.error;
                if (!Array.isArray(color2[0])) {
                  color2 = [color2, color2, color2];
                }
                if (position && error) {
                  var verts = [];
                  var n = position.length;
                  var vertexCount = 0;
                  this.bounds = [
                    [Infinity, Infinity, Infinity],
                    [-Infinity, -Infinity, -Infinity]
                  ];
                  this.lineCount = [0, 0, 0];
                  for (var j = 0; j < 3; ++j) {
                    this.lineOffset[j] = vertexCount;
                    i_loop:
                      for (var i = 0; i < n; ++i) {
                        var p = position[i];
                        for (var k = 0; k < 3; ++k) {
                          if (isNaN(p[k]) || !isFinite(p[k])) {
                            continue i_loop;
                          }
                        }
                        var e = error[i];
                        var c = color2[j];
                        if (Array.isArray(c[0])) {
                          c = color2[i];
                        }
                        if (c.length === 3) {
                          c = [c[0], c[1], c[2], 1];
                        } else if (c.length === 4) {
                          c = [c[0], c[1], c[2], c[3]];
                          if (!this.hasAlpha && c[3] < 1) this.hasAlpha = true;
                        }
                        if (isNaN(e[0][j]) || isNaN(e[1][j])) {
                          continue;
                        }
                        if (e[0][j] < 0) {
                          var x = p.slice();
                          x[j] += e[0][j];
                          verts.push(
                            p[0],
                            p[1],
                            p[2],
                            c[0],
                            c[1],
                            c[2],
                            c[3],
                            0,
                            0,
                            0,
                            x[0],
                            x[1],
                            x[2],
                            c[0],
                            c[1],
                            c[2],
                            c[3],
                            0,
                            0,
                            0
                          );
                          updateBounds(this.bounds, x);
                          vertexCount += 2 + emitFace(verts, x, c, j);
                        }
                        if (e[1][j] > 0) {
                          var x = p.slice();
                          x[j] += e[1][j];
                          verts.push(
                            p[0],
                            p[1],
                            p[2],
                            c[0],
                            c[1],
                            c[2],
                            c[3],
                            0,
                            0,
                            0,
                            x[0],
                            x[1],
                            x[2],
                            c[0],
                            c[1],
                            c[2],
                            c[3],
                            0,
                            0,
                            0
                          );
                          updateBounds(this.bounds, x);
                          vertexCount += 2 + emitFace(verts, x, c, j);
                        }
                      }
                    this.lineCount[j] = vertexCount - this.lineOffset[j];
                  }
                  this.buffer.update(verts);
                }
              };
              proto.dispose = function() {
                this.shader.dispose();
                this.buffer.dispose();
                this.vao.dispose();
              };
              function createErrorBars(options) {
                var gl2 = options.gl;
                var buffer = createBuffer(gl2);
                var vao = createVAO(gl2, [
                  {
                    buffer,
                    type: gl2.FLOAT,
                    size: 3,
                    offset: 0,
                    stride: 40
                  },
                  {
                    buffer,
                    type: gl2.FLOAT,
                    size: 4,
                    offset: 12,
                    stride: 40
                  },
                  {
                    buffer,
                    type: gl2.FLOAT,
                    size: 3,
                    offset: 28,
                    stride: 40
                  }
                ]);
                var shader = createShader(gl2);
                shader.attributes.position.location = 0;
                shader.attributes.color.location = 1;
                shader.attributes.offset.location = 2;
                var result = new ErrorBars(gl2, buffer, vao, shader);
                result.update(options);
                return result;
              }
            }
          ),
          /***/
          9215: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createFilteredVector;
              var cubicHermite = __webpack_require__2(4769);
              var bsearch = __webpack_require__2(2478);
              function clamp(lo, hi, x) {
                return Math.min(hi, Math.max(lo, x));
              }
              function FilteredVector(state0, velocity0, t02) {
                this.dimension = state0.length;
                this.bounds = [new Array(this.dimension), new Array(this.dimension)];
                for (var i = 0; i < this.dimension; ++i) {
                  this.bounds[0][i] = -Infinity;
                  this.bounds[1][i] = Infinity;
                }
                this._state = state0.slice().reverse();
                this._velocity = velocity0.slice().reverse();
                this._time = [t02];
                this._scratch = [state0.slice(), state0.slice(), state0.slice(), state0.slice(), state0.slice()];
              }
              var proto = FilteredVector.prototype;
              proto.flush = function(t) {
                var idx = bsearch.gt(this._time, t) - 1;
                if (idx <= 0) {
                  return;
                }
                this._time.splice(0, idx);
                this._state.splice(0, idx * this.dimension);
                this._velocity.splice(0, idx * this.dimension);
              };
              proto.curve = function(t) {
                var time = this._time;
                var n = time.length;
                var idx = bsearch.le(time, t);
                var result = this._scratch[0];
                var state = this._state;
                var velocity = this._velocity;
                var d = this.dimension;
                var bounds = this.bounds;
                if (idx < 0) {
                  var ptr = d - 1;
                  for (var i = 0; i < d; ++i, --ptr) {
                    result[i] = state[ptr];
                  }
                } else if (idx >= n - 1) {
                  var ptr = state.length - 1;
                  var tf = t - time[n - 1];
                  for (var i = 0; i < d; ++i, --ptr) {
                    result[i] = state[ptr] + tf * velocity[ptr];
                  }
                } else {
                  var ptr = d * (idx + 1) - 1;
                  var t02 = time[idx];
                  var t12 = time[idx + 1];
                  var dt = t12 - t02 || 1;
                  var x0 = this._scratch[1];
                  var x1 = this._scratch[2];
                  var v0 = this._scratch[3];
                  var v1 = this._scratch[4];
                  var steady = true;
                  for (var i = 0; i < d; ++i, --ptr) {
                    x0[i] = state[ptr];
                    v0[i] = velocity[ptr] * dt;
                    x1[i] = state[ptr + d];
                    v1[i] = velocity[ptr + d] * dt;
                    steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0);
                  }
                  if (steady) {
                    for (var i = 0; i < d; ++i) {
                      result[i] = x0[i];
                    }
                  } else {
                    cubicHermite(x0, v0, x1, v1, (t - t02) / dt, result);
                  }
                }
                var lo = bounds[0];
                var hi = bounds[1];
                for (var i = 0; i < d; ++i) {
                  result[i] = clamp(lo[i], hi[i], result[i]);
                }
                return result;
              };
              proto.dcurve = function(t) {
                var time = this._time;
                var n = time.length;
                var idx = bsearch.le(time, t);
                var result = this._scratch[0];
                var state = this._state;
                var velocity = this._velocity;
                var d = this.dimension;
                if (idx >= n - 1) {
                  var ptr = state.length - 1;
                  var tf = t - time[n - 1];
                  for (var i = 0; i < d; ++i, --ptr) {
                    result[i] = velocity[ptr];
                  }
                } else {
                  var ptr = d * (idx + 1) - 1;
                  var t02 = time[idx];
                  var t12 = time[idx + 1];
                  var dt = t12 - t02 || 1;
                  var x0 = this._scratch[1];
                  var x1 = this._scratch[2];
                  var v0 = this._scratch[3];
                  var v1 = this._scratch[4];
                  var steady = true;
                  for (var i = 0; i < d; ++i, --ptr) {
                    x0[i] = state[ptr];
                    v0[i] = velocity[ptr] * dt;
                    x1[i] = state[ptr + d];
                    v1[i] = velocity[ptr + d] * dt;
                    steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0);
                  }
                  if (steady) {
                    for (var i = 0; i < d; ++i) {
                      result[i] = 0;
                    }
                  } else {
                    cubicHermite.derivative(x0, v0, x1, v1, (t - t02) / dt, result);
                    for (var i = 0; i < d; ++i) {
                      result[i] /= dt;
                    }
                  }
                }
                return result;
              };
              proto.lastT = function() {
                var time = this._time;
                return time[time.length - 1];
              };
              proto.stable = function() {
                var velocity = this._velocity;
                var ptr = velocity.length;
                for (var i = this.dimension - 1; i >= 0; --i) {
                  if (velocity[--ptr]) {
                    return false;
                  }
                }
                return true;
              };
              proto.jump = function(t) {
                var t02 = this.lastT();
                var d = this.dimension;
                if (t < t02 || arguments.length !== d + 1) {
                  return;
                }
                var state = this._state;
                var velocity = this._velocity;
                var ptr = state.length - this.dimension;
                var bounds = this.bounds;
                var lo = bounds[0];
                var hi = bounds[1];
                this._time.push(t02, t);
                for (var j = 0; j < 2; ++j) {
                  for (var i = 0; i < d; ++i) {
                    state.push(state[ptr++]);
                    velocity.push(0);
                  }
                }
                this._time.push(t);
                for (var i = d; i > 0; --i) {
                  state.push(clamp(lo[i - 1], hi[i - 1], arguments[i]));
                  velocity.push(0);
                }
              };
              proto.push = function(t) {
                var t02 = this.lastT();
                var d = this.dimension;
                if (t < t02 || arguments.length !== d + 1) {
                  return;
                }
                var state = this._state;
                var velocity = this._velocity;
                var ptr = state.length - this.dimension;
                var dt = t - t02;
                var bounds = this.bounds;
                var lo = bounds[0];
                var hi = bounds[1];
                var sf = dt > 1e-6 ? 1 / dt : 0;
                this._time.push(t);
                for (var i = d; i > 0; --i) {
                  var xc = clamp(lo[i - 1], hi[i - 1], arguments[i]);
                  state.push(xc);
                  velocity.push((xc - state[ptr++]) * sf);
                }
              };
              proto.set = function(t) {
                var d = this.dimension;
                if (t < this.lastT() || arguments.length !== d + 1) {
                  return;
                }
                var state = this._state;
                var velocity = this._velocity;
                var bounds = this.bounds;
                var lo = bounds[0];
                var hi = bounds[1];
                this._time.push(t);
                for (var i = d; i > 0; --i) {
                  state.push(clamp(lo[i - 1], hi[i - 1], arguments[i]));
                  velocity.push(0);
                }
              };
              proto.move = function(t) {
                var t02 = this.lastT();
                var d = this.dimension;
                if (t <= t02 || arguments.length !== d + 1) {
                  return;
                }
                var state = this._state;
                var velocity = this._velocity;
                var statePtr = state.length - this.dimension;
                var bounds = this.bounds;
                var lo = bounds[0];
                var hi = bounds[1];
                var dt = t - t02;
                var sf = dt > 1e-6 ? 1 / dt : 0;
                this._time.push(t);
                for (var i = d; i > 0; --i) {
                  var dx = arguments[i];
                  state.push(clamp(lo[i - 1], hi[i - 1], state[statePtr++] + dx));
                  velocity.push(dx * sf);
                }
              };
              proto.idle = function(t) {
                var t02 = this.lastT();
                if (t < t02) {
                  return;
                }
                var d = this.dimension;
                var state = this._state;
                var velocity = this._velocity;
                var statePtr = state.length - d;
                var bounds = this.bounds;
                var lo = bounds[0];
                var hi = bounds[1];
                var dt = t - t02;
                this._time.push(t);
                for (var i = d - 1; i >= 0; --i) {
                  state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr]));
                  velocity.push(0);
                  statePtr += 1;
                }
              };
              function getZero(d) {
                var result = new Array(d);
                for (var i = 0; i < d; ++i) {
                  result[i] = 0;
                }
                return result;
              }
              function createFilteredVector(initState, initVelocity, initTime) {
                switch (arguments.length) {
                  case 0:
                    return new FilteredVector([0], [0], 0);
                  case 1:
                    if (typeof initState === "number") {
                      var zero2 = getZero(initState);
                      return new FilteredVector(zero2, zero2, 0);
                    } else {
                      return new FilteredVector(initState, getZero(initState.length), 0);
                    }
                  case 2:
                    if (typeof initVelocity === "number") {
                      var zero2 = getZero(initState.length);
                      return new FilteredVector(initState, zero2, +initVelocity);
                    } else {
                      initTime = 0;
                    }
                  case 3:
                    if (initState.length !== initVelocity.length) {
                      throw new Error("state and velocity lengths must match");
                    }
                    return new FilteredVector(initState, initVelocity, initTime);
                }
              }
            }
          ),
          /***/
          9216: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = isMobile;
              module2.exports.isMobile = isMobile;
              module2.exports["default"] = isMobile;
              var mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|samsungbrowser.*mobile|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;
              var notMobileRE = /CrOS/;
              var tabletRE = /android|ipad|playbook|silk/i;
              function isMobile(opts) {
                if (!opts) opts = {};
                var ua = opts.ua;
                if (!ua && typeof navigator !== "undefined") ua = navigator.userAgent;
                if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") {
                  ua = ua.headers["user-agent"];
                }
                if (typeof ua !== "string") return false;
                var result = mobileRE.test(ua) && !notMobileRE.test(ua) || !!opts.tablet && tabletRE.test(ua);
                if (!result && opts.tablet && opts.featureDetect && navigator && navigator.maxTouchPoints > 1 && ua.indexOf("Macintosh") !== -1 && ua.indexOf("Safari") !== -1) {
                  result = true;
                }
                return result;
              }
            }
          ),
          /***/
          9226: (
            /***/
            function(module2) {
              module2.exports = ceil;
              function ceil(out, a) {
                out[0] = Math.ceil(a[0]);
                out[1] = Math.ceil(a[1]);
                out[2] = Math.ceil(a[2]);
                return out;
              }
            }
          ),
          /***/
          9265: (
            /***/
            function(module2) {
              module2.exports = exactEquals;
              function exactEquals(a, b) {
                return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
              }
            }
          ),
          /***/
          9288: (
            /***/
            function(module2) {
              module2.exports = scale;
              function scale(out, a, b) {
                out[0] = a[0] * b;
                out[1] = a[1] * b;
                out[2] = a[2] * b;
                out[3] = a[3] * b;
                return out;
              }
            }
          ),
          /***/
          9346: (
            /***/
            function(module2) {
              "use strict";
              var diff = new Float64Array(4);
              var edge0 = new Float64Array(4);
              var edge1 = new Float64Array(4);
              function closestPoint2d(V0, V1, V2, point, result) {
                if (diff.length < point.length) {
                  diff = new Float64Array(point.length);
                  edge0 = new Float64Array(point.length);
                  edge1 = new Float64Array(point.length);
                }
                for (var i = 0; i < point.length; ++i) {
                  diff[i] = V0[i] - point[i];
                  edge0[i] = V1[i] - V0[i];
                  edge1[i] = V2[i] - V0[i];
                }
                var a00 = 0, a01 = 0, a11 = 0, b0 = 0, b1 = 0, c = 0;
                for (var i = 0; i < point.length; ++i) {
                  var e0 = edge0[i], e1 = edge1[i], d = diff[i];
                  a00 += e0 * e0;
                  a01 += e0 * e1;
                  a11 += e1 * e1;
                  b0 += d * e0;
                  b1 += d * e1;
                  c += d * d;
                }
                var det = Math.abs(a00 * a11 - a01 * a01);
                var s = a01 * b1 - a11 * b0;
                var t = a01 * b0 - a00 * b1;
                var sqrDistance;
                if (s + t <= det) {
                  if (s < 0) {
                    if (t < 0) {
                      if (b0 < 0) {
                        t = 0;
                        if (-b0 >= a00) {
                          s = 1;
                          sqrDistance = a00 + 2 * b0 + c;
                        } else {
                          s = -b0 / a00;
                          sqrDistance = b0 * s + c;
                        }
                      } else {
                        s = 0;
                        if (b1 >= 0) {
                          t = 0;
                          sqrDistance = c;
                        } else if (-b1 >= a11) {
                          t = 1;
                          sqrDistance = a11 + 2 * b1 + c;
                        } else {
                          t = -b1 / a11;
                          sqrDistance = b1 * t + c;
                        }
                      }
                    } else {
                      s = 0;
                      if (b1 >= 0) {
                        t = 0;
                        sqrDistance = c;
                      } else if (-b1 >= a11) {
                        t = 1;
                        sqrDistance = a11 + 2 * b1 + c;
                      } else {
                        t = -b1 / a11;
                        sqrDistance = b1 * t + c;
                      }
                    }
                  } else if (t < 0) {
                    t = 0;
                    if (b0 >= 0) {
                      s = 0;
                      sqrDistance = c;
                    } else if (-b0 >= a00) {
                      s = 1;
                      sqrDistance = a00 + 2 * b0 + c;
                    } else {
                      s = -b0 / a00;
                      sqrDistance = b0 * s + c;
                    }
                  } else {
                    var invDet = 1 / det;
                    s *= invDet;
                    t *= invDet;
                    sqrDistance = s * (a00 * s + a01 * t + 2 * b0) + t * (a01 * s + a11 * t + 2 * b1) + c;
                  }
                } else {
                  var tmp0, tmp1, numer, denom;
                  if (s < 0) {
                    tmp0 = a01 + b0;
                    tmp1 = a11 + b1;
                    if (tmp1 > tmp0) {
                      numer = tmp1 - tmp0;
                      denom = a00 - 2 * a01 + a11;
                      if (numer >= denom) {
                        s = 1;
                        t = 0;
                        sqrDistance = a00 + 2 * b0 + c;
                      } else {
                        s = numer / denom;
                        t = 1 - s;
                        sqrDistance = s * (a00 * s + a01 * t + 2 * b0) + t * (a01 * s + a11 * t + 2 * b1) + c;
                      }
                    } else {
                      s = 0;
                      if (tmp1 <= 0) {
                        t = 1;
                        sqrDistance = a11 + 2 * b1 + c;
                      } else if (b1 >= 0) {
                        t = 0;
                        sqrDistance = c;
                      } else {
                        t = -b1 / a11;
                        sqrDistance = b1 * t + c;
                      }
                    }
                  } else if (t < 0) {
                    tmp0 = a01 + b1;
                    tmp1 = a00 + b0;
                    if (tmp1 > tmp0) {
                      numer = tmp1 - tmp0;
                      denom = a00 - 2 * a01 + a11;
                      if (numer >= denom) {
                        t = 1;
                        s = 0;
                        sqrDistance = a11 + 2 * b1 + c;
                      } else {
                        t = numer / denom;
                        s = 1 - t;
                        sqrDistance = s * (a00 * s + a01 * t + 2 * b0) + t * (a01 * s + a11 * t + 2 * b1) + c;
                      }
                    } else {
                      t = 0;
                      if (tmp1 <= 0) {
                        s = 1;
                        sqrDistance = a00 + 2 * b0 + c;
                      } else if (b0 >= 0) {
                        s = 0;
                        sqrDistance = c;
                      } else {
                        s = -b0 / a00;
                        sqrDistance = b0 * s + c;
                      }
                    }
                  } else {
                    numer = a11 + b1 - a01 - b0;
                    if (numer <= 0) {
                      s = 0;
                      t = 1;
                      sqrDistance = a11 + 2 * b1 + c;
                    } else {
                      denom = a00 - 2 * a01 + a11;
                      if (numer >= denom) {
                        s = 1;
                        t = 0;
                        sqrDistance = a00 + 2 * b0 + c;
                      } else {
                        s = numer / denom;
                        t = 1 - s;
                        sqrDistance = s * (a00 * s + a01 * t + 2 * b0) + t * (a01 * s + a11 * t + 2 * b1) + c;
                      }
                    }
                  }
                }
                var u = 1 - s - t;
                for (var i = 0; i < point.length; ++i) {
                  result[i] = u * V0[i] + s * V1[i] + t * V2[i];
                }
                if (sqrDistance < 0) {
                  return 0;
                }
                return sqrDistance;
              }
              module2.exports = closestPoint2d;
            }
          ),
          /***/
          9362: (
            /***/
            function(module2) {
              "use strict";
              module2.exports = fastTwoSum;
              function fastTwoSum(a, b, result) {
                var x = a + b;
                var bv = x - a;
                var av = x - bv;
                var br = b - bv;
                var ar = a - av;
                if (result) {
                  result[0] = ar + br;
                  result[1] = x;
                  return result;
                }
                return [ar + br, x];
              }
            }
          ),
          /***/
          9366: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var vectorizeText = __webpack_require__2(4359);
              module2.exports = getGlyph;
              var GLYPH_CACHE = {};
              function getGlyph(symbol, font, pixelRatio) {
                var fontKey = [
                  font.style,
                  font.weight,
                  font.variant,
                  font.family
                ].join("_");
                var fontCache = GLYPH_CACHE[fontKey];
                if (!fontCache) {
                  fontCache = GLYPH_CACHE[fontKey] = {};
                }
                if (symbol in fontCache) {
                  return fontCache[symbol];
                }
                var config = {
                  textAlign: "center",
                  textBaseline: "middle",
                  lineHeight: 1,
                  font: font.family,
                  fontStyle: font.style,
                  fontWeight: font.weight,
                  fontVariant: font.variant,
                  lineSpacing: 1.25,
                  styletags: {
                    breaklines: true,
                    bolds: true,
                    italics: true,
                    subscripts: true,
                    superscripts: true
                  }
                };
                config.triangles = true;
                var triSymbol = vectorizeText(symbol, config);
                config.triangles = false;
                var lineSymbol = vectorizeText(symbol, config);
                var i, j;
                if (pixelRatio && pixelRatio !== 1) {
                  for (i = 0; i < triSymbol.positions.length; ++i) {
                    for (j = 0; j < triSymbol.positions[i].length; ++j) {
                      triSymbol.positions[i][j] /= pixelRatio;
                    }
                  }
                  for (i = 0; i < lineSymbol.positions.length; ++i) {
                    for (j = 0; j < lineSymbol.positions[i].length; ++j) {
                      lineSymbol.positions[i][j] /= pixelRatio;
                    }
                  }
                }
                var bounds = [[Infinity, Infinity], [-Infinity, -Infinity]];
                var n = lineSymbol.positions.length;
                for (i = 0; i < n; ++i) {
                  var p = lineSymbol.positions[i];
                  for (j = 0; j < 2; ++j) {
                    bounds[0][j] = Math.min(bounds[0][j], p[j]);
                    bounds[1][j] = Math.max(bounds[1][j], p[j]);
                  }
                }
                return fontCache[symbol] = [triSymbol, lineSymbol, bounds];
              }
            }
          ),
          /***/
          9405: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var createUniformWrapper = __webpack_require__2(3327);
              var createAttributeWrapper = __webpack_require__2(8731);
              var makeReflect = __webpack_require__2(216);
              var shaderCache = __webpack_require__2(5091);
              var runtime = __webpack_require__2(2145);
              var GLError = __webpack_require__2(8866);
              function Shader(gl2) {
                this.gl = gl2;
                this.gl.lastAttribCount = 0;
                this._vref = this._fref = this._relink = this.vertShader = this.fragShader = this.program = this.attributes = this.uniforms = this.types = null;
              }
              var proto = Shader.prototype;
              proto.bind = function() {
                if (!this.program) {
                  this._relink();
                }
                var i;
                var newAttribCount = this.gl.getProgramParameter(this.program, this.gl.ACTIVE_ATTRIBUTES);
                var oldAttribCount = this.gl.lastAttribCount;
                if (newAttribCount > oldAttribCount) {
                  for (i = oldAttribCount; i < newAttribCount; i++) {
                    this.gl.enableVertexAttribArray(i);
                  }
                } else if (oldAttribCount > newAttribCount) {
                  for (i = newAttribCount; i < oldAttribCount; i++) {
                    this.gl.disableVertexAttribArray(i);
                  }
                }
                this.gl.lastAttribCount = newAttribCount;
                this.gl.useProgram(this.program);
              };
              proto.dispose = function() {
                var oldAttribCount = this.gl.lastAttribCount;
                for (var i = 0; i < oldAttribCount; i++) {
                  this.gl.disableVertexAttribArray(i);
                }
                this.gl.lastAttribCount = 0;
                if (this._fref) {
                  this._fref.dispose();
                }
                if (this._vref) {
                  this._vref.dispose();
                }
                this.attributes = this.types = this.vertShader = this.fragShader = this.program = this._relink = this._fref = this._vref = null;
              };
              function compareAttributes(a, b) {
                if (a.name < b.name) {
                  return -1;
                }
                return 1;
              }
              proto.update = function(vertSource, fragSource, uniforms, attributes) {
                if (!fragSource || arguments.length === 1) {
                  var obj = vertSource;
                  vertSource = obj.vertex;
                  fragSource = obj.fragment;
                  uniforms = obj.uniforms;
                  attributes = obj.attributes;
                }
                var wrapper = this;
                var gl2 = wrapper.gl;
                var pvref = wrapper._vref;
                wrapper._vref = shaderCache.shader(gl2, gl2.VERTEX_SHADER, vertSource);
                if (pvref) {
                  pvref.dispose();
                }
                wrapper.vertShader = wrapper._vref.shader;
                var pfref = this._fref;
                wrapper._fref = shaderCache.shader(gl2, gl2.FRAGMENT_SHADER, fragSource);
                if (pfref) {
                  pfref.dispose();
                }
                wrapper.fragShader = wrapper._fref.shader;
                if (!uniforms || !attributes) {
                  var testProgram = gl2.createProgram();
                  gl2.attachShader(testProgram, wrapper.fragShader);
                  gl2.attachShader(testProgram, wrapper.vertShader);
                  gl2.linkProgram(testProgram);
                  if (!gl2.getProgramParameter(testProgram, gl2.LINK_STATUS)) {
                    var errLog = gl2.getProgramInfoLog(testProgram);
                    throw new GLError(errLog, "Error linking program:" + errLog);
                  }
                  uniforms = uniforms || runtime.uniforms(gl2, testProgram);
                  attributes = attributes || runtime.attributes(gl2, testProgram);
                  gl2.deleteProgram(testProgram);
                }
                attributes = attributes.slice();
                attributes.sort(compareAttributes);
                var attributeUnpacked = [];
                var attributeNames = [];
                var attributeLocations = [];
                var i;
                for (i = 0; i < attributes.length; ++i) {
                  var attr = attributes[i];
                  if (attr.type.indexOf("mat") >= 0) {
                    var size = attr.type.charAt(attr.type.length - 1) | 0;
                    var locVector = new Array(size);
                    for (var j = 0; j < size; ++j) {
                      locVector[j] = attributeLocations.length;
                      attributeNames.push(attr.name + "[" + j + "]");
                      if (typeof attr.location === "number") {
                        attributeLocations.push(attr.location + j);
                      } else if (Array.isArray(attr.location) && attr.location.length === size && typeof attr.location[j] === "number") {
                        attributeLocations.push(attr.location[j] | 0);
                      } else {
                        attributeLocations.push(-1);
                      }
                    }
                    attributeUnpacked.push({
                      name: attr.name,
                      type: attr.type,
                      locations: locVector
                    });
                  } else {
                    attributeUnpacked.push({
                      name: attr.name,
                      type: attr.type,
                      locations: [attributeLocations.length]
                    });
                    attributeNames.push(attr.name);
                    if (typeof attr.location === "number") {
                      attributeLocations.push(attr.location | 0);
                    } else {
                      attributeLocations.push(-1);
                    }
                  }
                }
                var curLocation = 0;
                for (i = 0; i < attributeLocations.length; ++i) {
                  if (attributeLocations[i] < 0) {
                    while (attributeLocations.indexOf(curLocation) >= 0) {
                      curLocation += 1;
                    }
                    attributeLocations[i] = curLocation;
                  }
                }
                var uniformLocations = new Array(uniforms.length);
                function relink() {
                  wrapper.program = shaderCache.program(
                    gl2,
                    wrapper._vref,
                    wrapper._fref,
                    attributeNames,
                    attributeLocations
                  );
                  for (var i2 = 0; i2 < uniforms.length; ++i2) {
                    uniformLocations[i2] = gl2.getUniformLocation(
                      wrapper.program,
                      uniforms[i2].name
                    );
                  }
                }
                relink();
                wrapper._relink = relink;
                wrapper.types = {
                  uniforms: makeReflect(uniforms),
                  attributes: makeReflect(attributes)
                };
                wrapper.attributes = createAttributeWrapper(
                  gl2,
                  wrapper,
                  attributeUnpacked,
                  attributeLocations
                );
                Object.defineProperty(wrapper, "uniforms", createUniformWrapper(
                  gl2,
                  wrapper,
                  uniforms,
                  uniformLocations
                ));
              };
              function createShader(gl2, vertSource, fragSource, uniforms, attributes) {
                var shader = new Shader(gl2);
                shader.update(
                  vertSource,
                  fragSource,
                  uniforms,
                  attributes
                );
                return shader;
              }
              module2.exports = createShader;
            }
          ),
          /***/
          9499: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createSurfacePlot;
              var bits = __webpack_require__2(8828);
              var createBuffer = __webpack_require__2(2762);
              var createVAO = __webpack_require__2(8116);
              var createTexture = __webpack_require__2(7766);
              var pool = __webpack_require__2(1888);
              var colormap = __webpack_require__2(6729);
              var ops = __webpack_require__2(5298);
              var pack = __webpack_require__2(9994);
              var ndarray = __webpack_require__2(9618);
              var surfaceNets = __webpack_require__2(3711);
              var multiply = __webpack_require__2(6760);
              var invert = __webpack_require__2(7608);
              var bsearch = __webpack_require__2(2478);
              var gradient = __webpack_require__2(6199);
              var shaders = __webpack_require__2(990);
              var createShader = shaders.createShader;
              var createContourShader = shaders.createContourShader;
              var createPickShader = shaders.createPickShader;
              var createPickContourShader = shaders.createPickContourShader;
              var SURFACE_VERTEX_SIZE = 4 * (4 + 3 + 3);
              var IDENTITY = [
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1,
                0,
                0,
                0,
                0,
                1
              ];
              var QUAD = [
                [0, 0],
                [0, 1],
                [1, 0],
                [1, 1],
                [1, 0],
                [0, 1]
              ];
              var PERMUTATIONS = [
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0]
              ];
              (function() {
                for (var i = 0; i < 3; ++i) {
                  var p = PERMUTATIONS[i];
                  var u = (i + 1) % 3;
                  var v = (i + 2) % 3;
                  p[u + 0] = 1;
                  p[v + 3] = 1;
                  p[i + 6] = 1;
                }
              })();
              function SurfacePickResult(position, index, uv, level, dataCoordinate) {
                this.position = position;
                this.index = index;
                this.uv = uv;
                this.level = level;
                this.dataCoordinate = dataCoordinate;
              }
              var N_COLORS = 256;
              function SurfacePlot(gl2, shape, bounds, shader, pickShader, coordinates, vao, colorMap, contourShader, contourPickShader, contourBuffer, contourVAO, dynamicBuffer, dynamicVAO, objectOffset) {
                this.gl = gl2;
                this.shape = shape;
                this.bounds = bounds;
                this.objectOffset = objectOffset;
                this.intensityBounds = [];
                this._shader = shader;
                this._pickShader = pickShader;
                this._coordinateBuffer = coordinates;
                this._vao = vao;
                this._colorMap = colorMap;
                this._contourShader = contourShader;
                this._contourPickShader = contourPickShader;
                this._contourBuffer = contourBuffer;
                this._contourVAO = contourVAO;
                this._contourOffsets = [[], [], []];
                this._contourCounts = [[], [], []];
                this._vertexCount = 0;
                this._pickResult = new SurfacePickResult([0, 0, 0], [0, 0], [0, 0], [0, 0, 0], [0, 0, 0]);
                this._dynamicBuffer = dynamicBuffer;
                this._dynamicVAO = dynamicVAO;
                this._dynamicOffsets = [0, 0, 0];
                this._dynamicCounts = [0, 0, 0];
                this.contourWidth = [1, 1, 1];
                this.contourLevels = [[1], [1], [1]];
                this.contourTint = [0, 0, 0];
                this.contourColor = [[0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1]];
                this.showContour = true;
                this.showSurface = true;
                this.enableHighlight = [true, true, true];
                this.highlightColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.highlightTint = [1, 1, 1];
                this.highlightLevel = [-1, -1, -1];
                this.enableDynamic = [true, true, true];
                this.dynamicLevel = [NaN, NaN, NaN];
                this.dynamicColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
                this.dynamicTint = [1, 1, 1];
                this.dynamicWidth = [1, 1, 1];
                this.axesBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
                this.surfaceProject = [false, false, false];
                this.contourProject = [
                  [false, false, false],
                  [false, false, false],
                  [false, false, false]
                ];
                this.colorBounds = [false, false];
                this._field = [
                  ndarray(pool.mallocFloat(1024), [0, 0]),
                  ndarray(pool.mallocFloat(1024), [0, 0]),
                  ndarray(pool.mallocFloat(1024), [0, 0])
                ];
                this.pickId = 1;
                this.clipBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]];
                this.snapToData = false;
                this.pixelRatio = 1;
                this.opacity = 1;
                this.lightPosition = [10, 1e4, 0];
                this.ambientLight = 0.8;
                this.diffuseLight = 0.8;
                this.specularLight = 2;
                this.roughness = 0.5;
                this.fresnel = 1.5;
                this.vertexColor = 0;
                this.dirty = true;
              }
              var proto = SurfacePlot.prototype;
              proto.genColormap = function(name2, opacityscale) {
                var hasAlpha = false;
                var x = pack([colormap({
                  colormap: name2,
                  nshades: N_COLORS,
                  format: "rgba"
                }).map(function(c, i) {
                  var a = opacityscale ? getOpacityFromScale(i / 255, opacityscale) : c[3];
                  if (a < 1) hasAlpha = true;
                  return [c[0], c[1], c[2], 255 * a];
                })]);
                ops.divseq(x, 255);
                this.hasAlphaScale = hasAlpha;
                return x;
              };
              proto.isTransparent = function() {
                return this.opacity < 1 || this.hasAlphaScale;
              };
              proto.isOpaque = function() {
                return !this.isTransparent();
              };
              proto.pickSlots = 1;
              proto.setPickBase = function(id) {
                this.pickId = id;
              };
              function getOpacityFromScale(ratio, opacityscale) {
                if (!opacityscale) return 1;
                if (!opacityscale.length) return 1;
                for (var i = 0; i < opacityscale.length; ++i) {
                  if (opacityscale.length < 2) return 1;
                  if (opacityscale[i][0] === ratio) return opacityscale[i][1];
                  if (opacityscale[i][0] > ratio && i > 0) {
                    var d = (opacityscale[i][0] - ratio) / (opacityscale[i][0] - opacityscale[i - 1][0]);
                    return opacityscale[i][1] * (1 - d) + d * opacityscale[i - 1][1];
                  }
                }
                return 1;
              }
              var ZERO_VEC = [0, 0, 0];
              var PROJECT_DATA = {
                showSurface: false,
                showContour: false,
                projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()],
                clipBounds: [
                  [[0, 0, 0], [0, 0, 0]],
                  [[0, 0, 0], [0, 0, 0]],
                  [[0, 0, 0], [0, 0, 0]]
                ]
              };
              function computeProjectionData(camera, obj) {
                var i, j, k;
                var cubeAxis = obj.axes && obj.axes.lastCubeProps.axis || ZERO_VEC;
                var showSurface = obj.showSurface;
                var showContour = obj.showContour;
                for (i = 0; i < 3; ++i) {
                  showSurface = showSurface || obj.surfaceProject[i];
                  for (j = 0; j < 3; ++j) {
                    showContour = showContour || obj.contourProject[i][j];
                  }
                }
                for (i = 0; i < 3; ++i) {
                  var axisSquish = PROJECT_DATA.projections[i];
                  for (j = 0; j < 16; ++j) {
                    axisSquish[j] = 0;
                  }
                  for (j = 0; j < 4; ++j) {
                    axisSquish[5 * j] = 1;
                  }
                  axisSquish[5 * i] = 0;
                  axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i];
                  multiply(axisSquish, camera.model, axisSquish);
                  var nclipBounds = PROJECT_DATA.clipBounds[i];
                  for (k = 0; k < 2; ++k) {
                    for (j = 0; j < 3; ++j) {
                      nclipBounds[k][j] = camera.clipBounds[k][j];
                    }
                  }
                  nclipBounds[0][i] = -1e8;
                  nclipBounds[1][i] = 1e8;
                }
                PROJECT_DATA.showSurface = showSurface;
                PROJECT_DATA.showContour = showContour;
                return PROJECT_DATA;
              }
              var UNIFORMS = {
                model: IDENTITY,
                view: IDENTITY,
                projection: IDENTITY,
                inverseModel: IDENTITY.slice(),
                lowerBound: [0, 0, 0],
                upperBound: [0, 0, 0],
                colorMap: 0,
                clipBounds: [[0, 0, 0], [0, 0, 0]],
                height: 0,
                contourTint: 0,
                contourColor: [0, 0, 0, 1],
                permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1],
                zOffset: -1e-4,
                objectOffset: [0, 0, 0],
                kambient: 1,
                kdiffuse: 1,
                kspecular: 1,
                lightPosition: [1e3, 1e3, 1e3],
                eyePosition: [0, 0, 0],
                roughness: 1,
                fresnel: 1,
                opacity: 1,
                vertexColor: 0
              };
              var MATRIX_INVERSE = IDENTITY.slice();
              var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1];
              function drawCore(params, transparent) {
                params = params || {};
                var gl2 = this.gl;
                gl2.disable(gl2.CULL_FACE);
                this._colorMap.bind(0);
                var uniforms = UNIFORMS;
                uniforms.model = params.model || IDENTITY;
                uniforms.view = params.view || IDENTITY;
                uniforms.projection = params.projection || IDENTITY;
                uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]];
                uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]];
                uniforms.objectOffset = this.objectOffset;
                uniforms.contourColor = this.contourColor[0];
                uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model);
                for (var i = 0; i < 2; ++i) {
                  var clipClamped = uniforms.clipBounds[i];
                  for (var j = 0; j < 3; ++j) {
                    clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8);
                  }
                }
                uniforms.kambient = this.ambientLight;
                uniforms.kdiffuse = this.diffuseLight;
                uniforms.kspecular = this.specularLight;
                uniforms.roughness = this.roughness;
                uniforms.fresnel = this.fresnel;
                uniforms.opacity = this.opacity;
                uniforms.height = 0;
                uniforms.permutation = DEFAULT_PERM;
                uniforms.vertexColor = this.vertexColor;
                var invCameraMatrix = MATRIX_INVERSE;
                multiply(invCameraMatrix, uniforms.view, uniforms.model);
                multiply(invCameraMatrix, uniforms.projection, invCameraMatrix);
                invert(invCameraMatrix, invCameraMatrix);
                for (i = 0; i < 3; ++i) {
                  uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15];
                }
                var w = invCameraMatrix[15];
                for (i = 0; i < 3; ++i) {
                  w += this.lightPosition[i] * invCameraMatrix[4 * i + 3];
                }
                for (i = 0; i < 3; ++i) {
                  var s = invCameraMatrix[12 + i];
                  for (j = 0; j < 3; ++j) {
                    s += invCameraMatrix[4 * j + i] * this.lightPosition[j];
                  }
                  uniforms.lightPosition[i] = s / w;
                }
                var projectData = computeProjectionData(uniforms, this);
                if (projectData.showSurface) {
                  this._shader.bind();
                  this._shader.uniforms = uniforms;
                  this._vao.bind();
                  if (this.showSurface && this._vertexCount) {
                    this._vao.draw(gl2.TRIANGLES, this._vertexCount);
                  }
                  for (i = 0; i < 3; ++i) {
                    if (!this.surfaceProject[i] || !this.vertexCount) {
                      continue;
                    }
                    this._shader.uniforms.model = projectData.projections[i];
                    this._shader.uniforms.clipBounds = projectData.clipBounds[i];
                    this._vao.draw(gl2.TRIANGLES, this._vertexCount);
                  }
                  this._vao.unbind();
                }
                if (projectData.showContour) {
                  var shader = this._contourShader;
                  uniforms.kambient = 1;
                  uniforms.kdiffuse = 0;
                  uniforms.kspecular = 0;
                  uniforms.opacity = 1;
                  shader.bind();
                  shader.uniforms = uniforms;
                  var vao = this._contourVAO;
                  vao.bind();
                  for (i = 0; i < 3; ++i) {
                    shader.uniforms.permutation = PERMUTATIONS[i];
                    gl2.lineWidth(this.contourWidth[i] * this.pixelRatio);
                    for (j = 0; j < this.contourLevels[i].length; ++j) {
                      if (j === this.highlightLevel[i]) {
                        shader.uniforms.contourColor = this.highlightColor[i];
                        shader.uniforms.contourTint = this.highlightTint[i];
                      } else if (j === 0 || j - 1 === this.highlightLevel[i]) {
                        shader.uniforms.contourColor = this.contourColor[i];
                        shader.uniforms.contourTint = this.contourTint[i];
                      }
                      if (!this._contourCounts[i][j]) {
                        continue;
                      }
                      shader.uniforms.height = this.contourLevels[i][j];
                      vao.draw(gl2.LINES, this._contourCounts[i][j], this._contourOffsets[i][j]);
                    }
                  }
                  for (i = 0; i < 3; ++i) {
                    shader.uniforms.model = projectData.projections[i];
                    shader.uniforms.clipBounds = projectData.clipBounds[i];
                    for (j = 0; j < 3; ++j) {
                      if (!this.contourProject[i][j]) {
                        continue;
                      }
                      shader.uniforms.permutation = PERMUTATIONS[j];
                      gl2.lineWidth(this.contourWidth[j] * this.pixelRatio);
                      for (var k = 0; k < this.contourLevels[j].length; ++k) {
                        if (k === this.highlightLevel[j]) {
                          shader.uniforms.contourColor = this.highlightColor[j];
                          shader.uniforms.contourTint = this.highlightTint[j];
                        } else if (k === 0 || k - 1 === this.highlightLevel[j]) {
                          shader.uniforms.contourColor = this.contourColor[j];
                          shader.uniforms.contourTint = this.contourTint[j];
                        }
                        if (!this._contourCounts[j][k]) {
                          continue;
                        }
                        shader.uniforms.height = this.contourLevels[j][k];
                        vao.draw(gl2.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]);
                      }
                    }
                  }
                  vao.unbind();
                  vao = this._dynamicVAO;
                  vao.bind();
                  for (i = 0; i < 3; ++i) {
                    if (this._dynamicCounts[i] === 0) {
                      continue;
                    }
                    shader.uniforms.model = uniforms.model;
                    shader.uniforms.clipBounds = uniforms.clipBounds;
                    shader.uniforms.permutation = PERMUTATIONS[i];
                    gl2.lineWidth(this.dynamicWidth[i] * this.pixelRatio);
                    shader.uniforms.contourColor = this.dynamicColor[i];
                    shader.uniforms.contourTint = this.dynamicTint[i];
                    shader.uniforms.height = this.dynamicLevel[i];
                    vao.draw(gl2.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]);
                    for (j = 0; j < 3; ++j) {
                      if (!this.contourProject[j][i]) {
                        continue;
                      }
                      shader.uniforms.model = projectData.projections[j];
                      shader.uniforms.clipBounds = projectData.clipBounds[j];
                      vao.draw(gl2.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]);
                    }
                  }
                  vao.unbind();
                }
              }
              proto.draw = function(params) {
                return drawCore.call(this, params, false);
              };
              proto.drawTransparent = function(params) {
                return drawCore.call(this, params, true);
              };
              var PICK_UNIFORMS = {
                model: IDENTITY,
                view: IDENTITY,
                projection: IDENTITY,
                inverseModel: IDENTITY,
                clipBounds: [[0, 0, 0], [0, 0, 0]],
                height: 0,
                shape: [0, 0],
                pickId: 0,
                lowerBound: [0, 0, 0],
                upperBound: [0, 0, 0],
                zOffset: 0,
                objectOffset: [0, 0, 0],
                permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1],
                lightPosition: [0, 0, 0],
                eyePosition: [0, 0, 0]
              };
              proto.drawPick = function(params) {
                params = params || {};
                var gl2 = this.gl;
                gl2.disable(gl2.CULL_FACE);
                var uniforms = PICK_UNIFORMS;
                uniforms.model = params.model || IDENTITY;
                uniforms.view = params.view || IDENTITY;
                uniforms.projection = params.projection || IDENTITY;
                uniforms.shape = this._field[2].shape;
                uniforms.pickId = this.pickId / 255;
                uniforms.lowerBound = this.bounds[0];
                uniforms.upperBound = this.bounds[1];
                uniforms.objectOffset = this.objectOffset;
                uniforms.permutation = DEFAULT_PERM;
                for (var i = 0; i < 2; ++i) {
                  var clipClamped = uniforms.clipBounds[i];
                  for (var j = 0; j < 3; ++j) {
                    clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8);
                  }
                }
                var projectData = computeProjectionData(uniforms, this);
                if (projectData.showSurface) {
                  this._pickShader.bind();
                  this._pickShader.uniforms = uniforms;
                  this._vao.bind();
                  this._vao.draw(gl2.TRIANGLES, this._vertexCount);
                  for (i = 0; i < 3; ++i) {
                    if (!this.surfaceProject[i]) {
                      continue;
                    }
                    this._pickShader.uniforms.model = projectData.projections[i];
                    this._pickShader.uniforms.clipBounds = projectData.clipBounds[i];
                    this._vao.draw(gl2.TRIANGLES, this._vertexCount);
                  }
                  this._vao.unbind();
                }
                if (projectData.showContour) {
                  var shader = this._contourPickShader;
                  shader.bind();
                  shader.uniforms = uniforms;
                  var vao = this._contourVAO;
                  vao.bind();
                  for (j = 0; j < 3; ++j) {
                    gl2.lineWidth(this.contourWidth[j] * this.pixelRatio);
                    shader.uniforms.permutation = PERMUTATIONS[j];
                    for (i = 0; i < this.contourLevels[j].length; ++i) {
                      if (this._contourCounts[j][i]) {
                        shader.uniforms.height = this.contourLevels[j][i];
                        vao.draw(gl2.LINES, this._contourCounts[j][i], this._contourOffsets[j][i]);
                      }
                    }
                  }
                  for (i = 0; i < 3; ++i) {
                    shader.uniforms.model = projectData.projections[i];
                    shader.uniforms.clipBounds = projectData.clipBounds[i];
                    for (j = 0; j < 3; ++j) {
                      if (!this.contourProject[i][j]) {
                        continue;
                      }
                      shader.uniforms.permutation = PERMUTATIONS[j];
                      gl2.lineWidth(this.contourWidth[j] * this.pixelRatio);
                      for (var k = 0; k < this.contourLevels[j].length; ++k) {
                        if (this._contourCounts[j][k]) {
                          shader.uniforms.height = this.contourLevels[j][k];
                          vao.draw(gl2.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]);
                        }
                      }
                    }
                  }
                  vao.unbind();
                }
              };
              proto.pick = function(selection) {
                if (!selection) {
                  return null;
                }
                if (selection.id !== this.pickId) {
                  return null;
                }
                var shape = this._field[2].shape;
                var result = this._pickResult;
                var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16) / 255;
                var ix = Math.floor(x);
                var fx = x - ix;
                var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16) / 255;
                var iy = Math.floor(y);
                var fy = y - iy;
                ix += 1;
                iy += 1;
                var pos = result.position;
                pos[0] = pos[1] = pos[2] = 0;
                for (var dx = 0; dx < 2; ++dx) {
                  var s = dx ? fx : 1 - fx;
                  for (var dy = 0; dy < 2; ++dy) {
                    var t = dy ? fy : 1 - fy;
                    var r = ix + dx;
                    var c = iy + dy;
                    var w = s * t;
                    for (var i = 0; i < 3; ++i) {
                      pos[i] += this._field[i].get(r, c) * w;
                    }
                  }
                }
                var levelIndex = this._pickResult.level;
                for (var j = 0; j < 3; ++j) {
                  levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j]);
                  if (levelIndex[j] < 0) {
                    if (this.contourLevels[j].length > 0) {
                      levelIndex[j] = 0;
                    }
                  } else if (levelIndex[j] < this.contourLevels[j].length - 1) {
                    var a = this.contourLevels[j][levelIndex[j]];
                    var b = this.contourLevels[j][levelIndex[j] + 1];
                    if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) {
                      levelIndex[j] += 1;
                    }
                  }
                }
                result.index[0] = fx < 0.5 ? ix : ix + 1;
                result.index[1] = fy < 0.5 ? iy : iy + 1;
                result.uv[0] = x / shape[0];
                result.uv[1] = y / shape[1];
                for (i = 0; i < 3; ++i) {
                  result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1]);
                }
                return result;
              };
              proto.padField = function(dstField, srcField) {
                var srcShape = srcField.shape.slice();
                var dstShape = dstField.shape.slice();
                ops.assign(dstField.lo(1, 1).hi(srcShape[0], srcShape[1]), srcField);
                ops.assign(
                  dstField.lo(1).hi(srcShape[0], 1),
                  srcField.hi(srcShape[0], 1)
                );
                ops.assign(
                  dstField.lo(1, dstShape[1] - 1).hi(srcShape[0], 1),
                  srcField.lo(0, srcShape[1] - 1).hi(srcShape[0], 1)
                );
                ops.assign(
                  dstField.lo(0, 1).hi(1, srcShape[1]),
                  srcField.hi(1)
                );
                ops.assign(
                  dstField.lo(dstShape[0] - 1, 1).hi(1, srcShape[1]),
                  srcField.lo(srcShape[0] - 1)
                );
                dstField.set(0, 0, srcField.get(0, 0));
                dstField.set(0, dstShape[1] - 1, srcField.get(0, srcShape[1] - 1));
                dstField.set(dstShape[0] - 1, 0, srcField.get(srcShape[0] - 1, 0));
                dstField.set(dstShape[0] - 1, dstShape[1] - 1, srcField.get(srcShape[0] - 1, srcShape[1] - 1));
              };
              function handleArray(param, ctor) {
                if (Array.isArray(param)) {
                  return [ctor(param[0]), ctor(param[1]), ctor(param[2])];
                }
                return [ctor(param), ctor(param), ctor(param)];
              }
              function toColor(x) {
                if (Array.isArray(x)) {
                  if (x.length === 3) {
                    return [x[0], x[1], x[2], 1];
                  }
                  return [x[0], x[1], x[2], x[3]];
                }
                return [0, 0, 0, 1];
              }
              function handleColor(param) {
                if (Array.isArray(param)) {
                  if (Array.isArray(param)) {
                    return [
                      toColor(param[0]),
                      toColor(param[1]),
                      toColor(param[2])
                    ];
                  } else {
                    var c = toColor(param);
                    return [
                      c.slice(),
                      c.slice(),
                      c.slice()
                    ];
                  }
                }
              }
              proto.update = function(params) {
                params = params || {};
                this.objectOffset = params.objectOffset || this.objectOffset;
                this.dirty = true;
                if ("contourWidth" in params) {
                  this.contourWidth = handleArray(params.contourWidth, Number);
                }
                if ("showContour" in params) {
                  this.showContour = handleArray(params.showContour, Boolean);
                }
                if ("showSurface" in params) {
                  this.showSurface = !!params.showSurface;
                }
                if ("contourTint" in params) {
                  this.contourTint = handleArray(params.contourTint, Boolean);
                }
                if ("contourColor" in params) {
                  this.contourColor = handleColor(params.contourColor);
                }
                if ("contourProject" in params) {
                  this.contourProject = handleArray(params.contourProject, function(x2) {
                    return handleArray(x2, Boolean);
                  });
                }
                if ("surfaceProject" in params) {
                  this.surfaceProject = params.surfaceProject;
                }
                if ("dynamicColor" in params) {
                  this.dynamicColor = handleColor(params.dynamicColor);
                }
                if ("dynamicTint" in params) {
                  this.dynamicTint = handleArray(params.dynamicTint, Number);
                }
                if ("dynamicWidth" in params) {
                  this.dynamicWidth = handleArray(params.dynamicWidth, Number);
                }
                if ("opacity" in params) {
                  this.opacity = params.opacity;
                }
                if ("opacityscale" in params) {
                  this.opacityscale = params.opacityscale;
                }
                if ("colorBounds" in params) {
                  this.colorBounds = params.colorBounds;
                }
                if ("vertexColor" in params) {
                  this.vertexColor = params.vertexColor ? 1 : 0;
                }
                if ("colormap" in params) {
                  this._colorMap.setPixels(this.genColormap(params.colormap, this.opacityscale));
                }
                var field = params.field || params.coords && params.coords[2] || null;
                var levelsChanged = false;
                if (!field) {
                  if (this._field[2].shape[0] || this._field[2].shape[2]) {
                    field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2);
                  } else {
                    field = this._field[2].hi(0, 0);
                  }
                }
                if ("field" in params || "coords" in params) {
                  var fsize = (field.shape[0] + 2) * (field.shape[1] + 2);
                  if (fsize > this._field[2].data.length) {
                    pool.freeFloat(this._field[2].data);
                    this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize));
                  }
                  this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]);
                  this.padField(this._field[2], field);
                  this.shape = field.shape.slice();
                  var shape = this.shape;
                  for (var i = 0; i < 2; ++i) {
                    if (this._field[2].size > this._field[i].data.length) {
                      pool.freeFloat(this._field[i].data);
                      this._field[i].data = pool.mallocFloat(this._field[2].size);
                    }
                    this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2]);
                  }
                  if (params.coords) {
                    var coords = params.coords;
                    if (!Array.isArray(coords) || coords.length !== 3) {
                      throw new Error("gl-surface: invalid coordinates for x/y");
                    }
                    for (i = 0; i < 2; ++i) {
                      var coord = coords[i];
                      for (j = 0; j < 2; ++j) {
                        if (coord.shape[j] !== shape[j]) {
                          throw new Error("gl-surface: coords have incorrect shape");
                        }
                      }
                      this.padField(this._field[i], coord);
                    }
                  } else if (params.ticks) {
                    var ticks = params.ticks;
                    if (!Array.isArray(ticks) || ticks.length !== 2) {
                      throw new Error("gl-surface: invalid ticks");
                    }
                    for (i = 0; i < 2; ++i) {
                      var tick = ticks[i];
                      if (Array.isArray(tick) || tick.length) {
                        tick = ndarray(tick);
                      }
                      if (tick.shape[0] !== shape[i]) {
                        throw new Error("gl-surface: invalid tick length");
                      }
                      var tick2 = ndarray(tick.data, shape);
                      tick2.stride[i] = tick.stride[0];
                      tick2.stride[i ^ 1] = 0;
                      this.padField(this._field[i], tick2);
                    }
                  } else {
                    for (i = 0; i < 2; ++i) {
                      var offset = [0, 0];
                      offset[i] = 1;
                      this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0);
                    }
                    this._field[0].set(0, 0, 0);
                    for (var j = 0; j < shape[0]; ++j) {
                      this._field[0].set(j + 1, 0, j);
                    }
                    this._field[0].set(shape[0] + 1, 0, shape[0] - 1);
                    this._field[1].set(0, 0, 0);
                    for (j = 0; j < shape[1]; ++j) {
                      this._field[1].set(0, j + 1, j);
                    }
                    this._field[1].set(0, shape[1] + 1, shape[1] - 1);
                  }
                  var fields = this._field;
                  var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]);
                  for (i = 0; i < 3; ++i) {
                    gradient(dfields.pick(i), fields[i], "mirror");
                  }
                  var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]);
                  for (i = 0; i < shape[0] + 2; ++i) {
                    for (j = 0; j < shape[1] + 2; ++j) {
                      var dxdu = dfields.get(0, i, j, 0);
                      var dxdv = dfields.get(0, i, j, 1);
                      var dydu = dfields.get(1, i, j, 0);
                      var dydv = dfields.get(1, i, j, 1);
                      var dzdu = dfields.get(2, i, j, 0);
                      var dzdv = dfields.get(2, i, j, 1);
                      var nx = dydu * dzdv - dydv * dzdu;
                      var ny = dzdu * dxdv - dzdv * dxdu;
                      var nz = dxdu * dydv - dxdv * dydu;
                      var nl = Math.sqrt(nx * nx + ny * ny + nz * nz);
                      if (nl < 1e-8) {
                        nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz));
                        if (nl < 1e-8) {
                          nz = 1;
                          ny = nx = 0;
                          nl = 1;
                        } else {
                          nl = 1 / nl;
                        }
                      } else {
                        nl = 1 / Math.sqrt(nl);
                      }
                      normals.set(i, j, 0, nx * nl);
                      normals.set(i, j, 1, ny * nl);
                      normals.set(i, j, 2, nz * nl);
                    }
                  }
                  pool.free(dfields.data);
                  var lo = [Infinity, Infinity, Infinity];
                  var hi = [-Infinity, -Infinity, -Infinity];
                  var lo_intensity = Infinity;
                  var hi_intensity = -Infinity;
                  var count = (shape[0] - 1) * (shape[1] - 1) * 6;
                  var tverts = pool.mallocFloat(bits.nextPow2(10 * count));
                  var tptr = 0;
                  var vertexCount = 0;
                  for (i = 0; i < shape[0] - 1; ++i) {
                    j_loop:
                      for (j = 0; j < shape[1] - 1; ++j) {
                        for (var dx = 0; dx < 2; ++dx) {
                          for (var dy = 0; dy < 2; ++dy) {
                            for (var k = 0; k < 3; ++k) {
                              var f = this._field[k].get(1 + i + dx, 1 + j + dy);
                              if (isNaN(f) || !isFinite(f)) {
                                continue j_loop;
                              }
                            }
                          }
                        }
                        for (k = 0; k < 6; ++k) {
                          var r = i + QUAD[k][0];
                          var c = j + QUAD[k][1];
                          var tx = this._field[0].get(r + 1, c + 1);
                          var ty = this._field[1].get(r + 1, c + 1);
                          f = this._field[2].get(r + 1, c + 1);
                          nx = normals.get(r + 1, c + 1, 0);
                          ny = normals.get(r + 1, c + 1, 1);
                          nz = normals.get(r + 1, c + 1, 2);
                          if (params.intensity) {
                            vf = params.intensity.get(r, c);
                          }
                          var vf = params.intensity ? params.intensity.get(r, c) : f + this.objectOffset[2];
                          tverts[tptr++] = r;
                          tverts[tptr++] = c;
                          tverts[tptr++] = tx;
                          tverts[tptr++] = ty;
                          tverts[tptr++] = f;
                          tverts[tptr++] = 0;
                          tverts[tptr++] = vf;
                          tverts[tptr++] = nx;
                          tverts[tptr++] = ny;
                          tverts[tptr++] = nz;
                          lo[0] = Math.min(lo[0], tx + this.objectOffset[0]);
                          lo[1] = Math.min(lo[1], ty + this.objectOffset[1]);
                          lo[2] = Math.min(lo[2], f + this.objectOffset[2]);
                          lo_intensity = Math.min(lo_intensity, vf);
                          hi[0] = Math.max(hi[0], tx + this.objectOffset[0]);
                          hi[1] = Math.max(hi[1], ty + this.objectOffset[1]);
                          hi[2] = Math.max(hi[2], f + this.objectOffset[2]);
                          hi_intensity = Math.max(hi_intensity, vf);
                          vertexCount += 1;
                        }
                      }
                  }
                  if (params.intensityBounds) {
                    lo_intensity = +params.intensityBounds[0];
                    hi_intensity = +params.intensityBounds[1];
                  }
                  for (i = 6; i < tptr; i += 10) {
                    tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity);
                  }
                  this._vertexCount = vertexCount;
                  this._coordinateBuffer.update(tverts.subarray(0, tptr));
                  pool.freeFloat(tverts);
                  pool.free(normals.data);
                  this.bounds = [lo, hi];
                  this.intensity = params.intensity || this._field[2];
                  if (this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) {
                    levelsChanged = true;
                  }
                  this.intensityBounds = [lo_intensity, hi_intensity];
                }
                if ("levels" in params) {
                  var levels = params.levels;
                  if (!Array.isArray(levels[0])) {
                    levels = [[], [], levels];
                  } else {
                    levels = levels.slice();
                  }
                  for (i = 0; i < 3; ++i) {
                    levels[i] = levels[i].slice();
                    levels[i].sort(function(a, b) {
                      return a - b;
                    });
                  }
                  for (i = 0; i < 3; ++i) {
                    for (j = 0; j < levels[i].length; ++j) {
                      levels[i][j] -= this.objectOffset[i];
                    }
                  }
                  change_test:
                    for (i = 0; i < 3; ++i) {
                      if (levels[i].length !== this.contourLevels[i].length) {
                        levelsChanged = true;
                        break;
                      }
                      for (j = 0; j < levels[i].length; ++j) {
                        if (levels[i][j] !== this.contourLevels[i][j]) {
                          levelsChanged = true;
                          break change_test;
                        }
                      }
                    }
                  this.contourLevels = levels;
                }
                if (levelsChanged) {
                  fields = this._field;
                  shape = this.shape;
                  var contourVerts = [];
                  for (var dim = 0; dim < 3; ++dim) {
                    var contourLevel = this.contourLevels[dim];
                    var levelOffsets = [];
                    var levelCounts = [];
                    var parts = [0, 0, 0];
                    for (i = 0; i < contourLevel.length; ++i) {
                      var graph = surfaceNets(this._field[dim], contourLevel[i]);
                      levelOffsets.push(contourVerts.length / 5 | 0);
                      vertexCount = 0;
                      edge_loop:
                        for (j = 0; j < graph.cells.length; ++j) {
                          var e = graph.cells[j];
                          for (k = 0; k < 2; ++k) {
                            var p = graph.positions[e[k]];
                            var x = p[0];
                            var ix = Math.floor(x) | 0;
                            var fx = x - ix;
                            var y = p[1];
                            var iy = Math.floor(y) | 0;
                            var fy = y - iy;
                            var hole = false;
                            axis_loop:
                              for (var axis = 0; axis < 3; ++axis) {
                                parts[axis] = 0;
                                var iu = (dim + axis + 1) % 3;
                                for (dx = 0; dx < 2; ++dx) {
                                  var s = dx ? fx : 1 - fx;
                                  r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0;
                                  for (dy = 0; dy < 2; ++dy) {
                                    var t = dy ? fy : 1 - fy;
                                    c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0;
                                    if (axis < 2) {
                                      f = this._field[iu].get(r, c);
                                    } else {
                                      f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0]);
                                    }
                                    if (!isFinite(f) || isNaN(f)) {
                                      hole = true;
                                      break axis_loop;
                                    }
                                    var w = s * t;
                                    parts[axis] += w * f;
                                  }
                                }
                              }
                            if (!hole) {
                              contourVerts.push(
                                parts[0],
                                parts[1],
                                p[0],
                                p[1],
                                parts[2]
                              );
                              vertexCount += 1;
                            } else {
                              if (k > 0) {
                                for (var l = 0; l < 5; ++l) {
                                  contourVerts.pop();
                                }
                                vertexCount -= 1;
                              }
                              continue edge_loop;
                            }
                          }
                        }
                      levelCounts.push(vertexCount);
                    }
                    this._contourOffsets[dim] = levelOffsets;
                    this._contourCounts[dim] = levelCounts;
                  }
                  var floatBuffer = pool.mallocFloat(contourVerts.length);
                  for (i = 0; i < contourVerts.length; ++i) {
                    floatBuffer[i] = contourVerts[i];
                  }
                  this._contourBuffer.update(floatBuffer);
                  pool.freeFloat(floatBuffer);
                }
              };
              proto.dispose = function() {
                this._shader.dispose();
                this._vao.dispose();
                this._coordinateBuffer.dispose();
                this._colorMap.dispose();
                this._contourBuffer.dispose();
                this._contourVAO.dispose();
                this._contourShader.dispose();
                this._contourPickShader.dispose();
                this._dynamicBuffer.dispose();
                this._dynamicVAO.dispose();
                for (var i = 0; i < 3; ++i) {
                  pool.freeFloat(this._field[i].data);
                }
              };
              proto.highlight = function(selection) {
                var i;
                if (!selection) {
                  this._dynamicCounts = [0, 0, 0];
                  this.dyanamicLevel = [NaN, NaN, NaN];
                  this.highlightLevel = [-1, -1, -1];
                  return;
                }
                for (i = 0; i < 3; ++i) {
                  if (this.enableHighlight[i]) {
                    this.highlightLevel[i] = selection.level[i];
                  } else {
                    this.highlightLevel[i] = -1;
                  }
                }
                var levels;
                if (this.snapToData) {
                  levels = selection.dataCoordinate;
                } else {
                  levels = selection.position;
                }
                for (i = 0; i < 3; ++i) {
                  levels[i] -= this.objectOffset[i];
                }
                if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) && (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) && (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) {
                  return;
                }
                var vertexCount = 0;
                var shape = this.shape;
                var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1]);
                for (var d = 0; d < 3; ++d) {
                  if (!this.enableDynamic[d]) {
                    this.dynamicLevel[d] = NaN;
                    this._dynamicCounts[d] = 0;
                    continue;
                  }
                  this.dynamicLevel[d] = levels[d];
                  var u = (d + 1) % 3;
                  var v = (d + 2) % 3;
                  var f = this._field[d];
                  var g = this._field[u];
                  var h = this._field[v];
                  var graph = surfaceNets(f, levels[d]);
                  var edges = graph.cells;
                  var positions = graph.positions;
                  this._dynamicOffsets[d] = vertexCount;
                  for (i = 0; i < edges.length; ++i) {
                    var e = edges[i];
                    for (var j = 0; j < 2; ++j) {
                      var p = positions[e[j]];
                      var x = +p[0];
                      var ix = x | 0;
                      var jx = Math.min(ix + 1, shape[0]) | 0;
                      var fx = x - ix;
                      var hx = 1 - fx;
                      var y = +p[1];
                      var iy = y | 0;
                      var jy = Math.min(iy + 1, shape[1]) | 0;
                      var fy = y - iy;
                      var hy = 1 - fy;
                      var w00 = hx * hy;
                      var w01 = hx * fy;
                      var w10 = fx * hy;
                      var w11 = fx * fy;
                      var cu = w00 * g.get(ix, iy) + w01 * g.get(ix, jy) + w10 * g.get(jx, iy) + w11 * g.get(jx, jy);
                      var cv = w00 * h.get(ix, iy) + w01 * h.get(ix, jy) + w10 * h.get(jx, iy) + w11 * h.get(jx, jy);
                      if (isNaN(cu) || isNaN(cv)) {
                        if (j) {
                          vertexCount -= 1;
                        }
                        break;
                      }
                      scratchBuffer[2 * vertexCount + 0] = cu;
                      scratchBuffer[2 * vertexCount + 1] = cv;
                      vertexCount += 1;
                    }
                  }
                  this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d];
                }
                this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount));
                pool.freeFloat(scratchBuffer);
              };
              function createSurfacePlot(params) {
                var gl2 = params.gl;
                var shader = createShader(gl2);
                var pickShader = createPickShader(gl2);
                var contourShader = createContourShader(gl2);
                var contourPickShader = createPickContourShader(gl2);
                var coordinateBuffer = createBuffer(gl2);
                var vao = createVAO(gl2, [
                  {
                    buffer: coordinateBuffer,
                    size: 4,
                    stride: SURFACE_VERTEX_SIZE,
                    offset: 0
                  },
                  {
                    buffer: coordinateBuffer,
                    size: 3,
                    stride: SURFACE_VERTEX_SIZE,
                    offset: 16
                  },
                  {
                    buffer: coordinateBuffer,
                    size: 3,
                    stride: SURFACE_VERTEX_SIZE,
                    offset: 28
                  }
                ]);
                var contourBuffer = createBuffer(gl2);
                var contourVAO = createVAO(gl2, [
                  {
                    buffer: contourBuffer,
                    size: 4,
                    stride: 20,
                    offset: 0
                  },
                  {
                    buffer: contourBuffer,
                    size: 1,
                    stride: 20,
                    offset: 16
                  }
                ]);
                var dynamicBuffer = createBuffer(gl2);
                var dynamicVAO = createVAO(gl2, [
                  {
                    buffer: dynamicBuffer,
                    size: 2,
                    type: gl2.FLOAT
                  }
                ]);
                var cmap = createTexture(gl2, 1, N_COLORS, gl2.RGBA, gl2.UNSIGNED_BYTE);
                cmap.minFilter = gl2.LINEAR;
                cmap.magFilter = gl2.LINEAR;
                var surface = new SurfacePlot(
                  gl2,
                  [0, 0],
                  // shape
                  [[0, 0, 0], [0, 0, 0]],
                  // bounds
                  shader,
                  pickShader,
                  coordinateBuffer,
                  vao,
                  cmap,
                  contourShader,
                  contourPickShader,
                  contourBuffer,
                  contourVAO,
                  dynamicBuffer,
                  dynamicVAO,
                  [0, 0, 0]
                  // objectOffset
                );
                var nparams = {
                  levels: [[], [], []]
                };
                for (var id in params) {
                  nparams[id] = params[id];
                }
                nparams.colormap = nparams.colormap || "jet";
                surface.update(nparams);
                return surface;
              }
            }
          ),
          /***/
          9507: (
            /***/
            function(module2) {
              module2.exports = true;
            }
          ),
          /***/
          9618: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              var isBuffer = __webpack_require__2(7163);
              var hasTypedArrays = typeof Float64Array !== "undefined";
              function compare1st(a, b) {
                return a[0] - b[0];
              }
              function order() {
                var stride = this.stride;
                var terms = new Array(stride.length);
                var i;
                for (i = 0; i < terms.length; ++i) {
                  terms[i] = [Math.abs(stride[i]), i];
                }
                terms.sort(compare1st);
                var result = new Array(terms.length);
                for (i = 0; i < result.length; ++i) {
                  result[i] = terms[i][1];
                }
                return result;
              }
              var allFns = {
                // Special case for trivial arrays
                T: function(dtype) {
                  function View(a) {
                    this.data = a;
                  }
                  var proto = View.prototype;
                  proto.dtype = dtype;
                  proto.index = function() {
                    return -1;
                  };
                  proto.size = 0;
                  proto.dimension = -1;
                  proto.shape = proto.stride = proto.order = [];
                  proto.lo = proto.hi = proto.transpose = proto.step = function() {
                    return new View(this.data);
                  };
                  proto.get = proto.set = function() {
                  };
                  proto.pick = function() {
                    return null;
                  };
                  return function construct(a) {
                    return new View(a);
                  };
                },
                // Special case for 0d arrays
                0: function(dtype, TrivialArray) {
                  function View(a, d) {
                    this.data = a;
                    this.offset = d;
                  }
                  var proto = View.prototype;
                  proto.dtype = dtype;
                  proto.index = function() {
                    return this.offset;
                  };
                  proto.dimension = 0;
                  proto.size = 1;
                  proto.shape = proto.stride = proto.order = [];
                  proto.lo = proto.hi = proto.transpose = proto.step = function copy() {
                    return new View(this.data, this.offset);
                  };
                  proto.pick = function pick() {
                    return TrivialArray(this.data);
                  };
                  proto.valueOf = proto.get = function get() {
                    return dtype === "generic" ? this.data.get(this.offset) : this.data[this.offset];
                  };
                  proto.set = function set(v) {
                    return dtype === "generic" ? this.data.set(this.offset, v) : this.data[this.offset] = v;
                  };
                  return function construct(a, b, c, d) {
                    return new View(a, d);
                  };
                },
                1: function(dtype, CTOR_LIST, ORDER) {
                  function View(a, b0, c0, d) {
                    this.data = a;
                    this.shape = [b0];
                    this.stride = [c0];
                    this.offset = d | 0;
                  }
                  var proto = View.prototype;
                  proto.dtype = dtype;
                  proto.dimension = 1;
                  Object.defineProperty(proto, "size", {
                    get: function size() {
                      return this.shape[0];
                    }
                  });
                  proto.order = [0];
                  proto.set = function set(i0, v) {
                    return dtype === "generic" ? this.data.set(this.offset + this.stride[0] * i0, v) : this.data[this.offset + this.stride[0] * i0] = v;
                  };
                  proto.get = function get(i0) {
                    return dtype === "generic" ? this.data.get(this.offset + this.stride[0] * i0) : this.data[this.offset + this.stride[0] * i0];
                  };
                  proto.index = function index(i0) {
                    return this.offset + this.stride[0] * i0;
                  };
                  proto.hi = function hi(i0) {
                    return new View(this.data, typeof i0 !== "number" || i0 < 0 ? this.shape[0] : i0 | 0, this.stride[0], this.offset);
                  };
                  proto.lo = function lo(i0) {
                    var b = this.offset, d = 0, a0 = this.shape[0], c0 = this.stride[0];
                    if (typeof i0 === "number" && i0 >= 0) {
                      d = i0 | 0;
                      b += c0 * d;
                      a0 -= d;
                    }
                    return new View(this.data, a0, c0, b);
                  };
                  proto.step = function step(i0) {
                    var a0 = this.shape[0], b0 = this.stride[0], c = this.offset, d = 0, ceil = Math.ceil;
                    if (typeof i0 === "number") {
                      d = i0 | 0;
                      if (d < 0) {
                        c += b0 * (a0 - 1);
                        a0 = ceil(-a0 / d);
                      } else {
                        a0 = ceil(a0 / d);
                      }
                      b0 *= d;
                    }
                    return new View(this.data, a0, b0, c);
                  };
                  proto.transpose = function transpose(i0) {
                    i0 = i0 === void 0 ? 0 : i0 | 0;
                    var a = this.shape, b = this.stride;
                    return new View(this.data, a[i0], b[i0], this.offset);
                  };
                  proto.pick = function pick(i0) {
                    var a = [], b = [], c = this.offset;
                    if (typeof i0 === "number" && i0 >= 0) {
                      c = c + this.stride[0] * i0 | 0;
                    } else {
                      a.push(this.shape[0]);
                      b.push(this.stride[0]);
                    }
                    var ctor = CTOR_LIST[a.length + 1];
                    return ctor(this.data, a, b, c);
                  };
                  return function construct(data, shape, stride, offset) {
                    return new View(data, shape[0], stride[0], offset);
                  };
                },
                2: function(dtype, CTOR_LIST, ORDER) {
                  function View(a, b0, b1, c0, c1, d) {
                    this.data = a;
                    this.shape = [b0, b1];
                    this.stride = [c0, c1];
                    this.offset = d | 0;
                  }
                  var proto = View.prototype;
                  proto.dtype = dtype;
                  proto.dimension = 2;
                  Object.defineProperty(proto, "size", {
                    get: function size() {
                      return this.shape[0] * this.shape[1];
                    }
                  });
                  Object.defineProperty(proto, "order", {
                    get: function order2() {
                      return Math.abs(this.stride[0]) > Math.abs(this.stride[1]) ? [1, 0] : [0, 1];
                    }
                  });
                  proto.set = function set(i0, i1, v) {
                    return dtype === "generic" ? this.data.set(this.offset + this.stride[0] * i0 + this.stride[1] * i1, v) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1] = v;
                  };
                  proto.get = function get(i0, i1) {
                    return dtype === "generic" ? this.data.get(this.offset + this.stride[0] * i0 + this.stride[1] * i1) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1];
                  };
                  proto.index = function index(i0, i1) {
                    return this.offset + this.stride[0] * i0 + this.stride[1] * i1;
                  };
                  proto.hi = function hi(i0, i1) {
                    return new View(
                      this.data,
                      typeof i0 !== "number" || i0 < 0 ? this.shape[0] : i0 | 0,
                      typeof i1 !== "number" || i1 < 0 ? this.shape[1] : i1 | 0,
                      this.stride[0],
                      this.stride[1],
                      this.offset
                    );
                  };
                  proto.lo = function lo(i0, i1) {
                    var b = this.offset, d = 0, a0 = this.shape[0], a1 = this.shape[1], c0 = this.stride[0], c1 = this.stride[1];
                    if (typeof i0 === "number" && i0 >= 0) {
                      d = i0 | 0;
                      b += c0 * d;
                      a0 -= d;
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      d = i1 | 0;
                      b += c1 * d;
                      a1 -= d;
                    }
                    return new View(this.data, a0, a1, c0, c1, b);
                  };
                  proto.step = function step(i0, i1) {
                    var a0 = this.shape[0], a1 = this.shape[1], b0 = this.stride[0], b1 = this.stride[1], c = this.offset, d = 0, ceil = Math.ceil;
                    if (typeof i0 === "number") {
                      d = i0 | 0;
                      if (d < 0) {
                        c += b0 * (a0 - 1);
                        a0 = ceil(-a0 / d);
                      } else {
                        a0 = ceil(a0 / d);
                      }
                      b0 *= d;
                    }
                    if (typeof i1 === "number") {
                      d = i1 | 0;
                      if (d < 0) {
                        c += b1 * (a1 - 1);
                        a1 = ceil(-a1 / d);
                      } else {
                        a1 = ceil(a1 / d);
                      }
                      b1 *= d;
                    }
                    return new View(this.data, a0, a1, b0, b1, c);
                  };
                  proto.transpose = function transpose(i0, i1) {
                    i0 = i0 === void 0 ? 0 : i0 | 0;
                    i1 = i1 === void 0 ? 1 : i1 | 0;
                    var a = this.shape, b = this.stride;
                    return new View(this.data, a[i0], a[i1], b[i0], b[i1], this.offset);
                  };
                  proto.pick = function pick(i0, i1) {
                    var a = [], b = [], c = this.offset;
                    if (typeof i0 === "number" && i0 >= 0) {
                      c = c + this.stride[0] * i0 | 0;
                    } else {
                      a.push(this.shape[0]);
                      b.push(this.stride[0]);
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      c = c + this.stride[1] * i1 | 0;
                    } else {
                      a.push(this.shape[1]);
                      b.push(this.stride[1]);
                    }
                    var ctor = CTOR_LIST[a.length + 1];
                    return ctor(this.data, a, b, c);
                  };
                  return function construct(data, shape, stride, offset) {
                    return new View(data, shape[0], shape[1], stride[0], stride[1], offset);
                  };
                },
                3: function(dtype, CTOR_LIST, ORDER) {
                  function View(a, b0, b1, b2, c0, c1, c2, d) {
                    this.data = a;
                    this.shape = [b0, b1, b2];
                    this.stride = [c0, c1, c2];
                    this.offset = d | 0;
                  }
                  var proto = View.prototype;
                  proto.dtype = dtype;
                  proto.dimension = 3;
                  Object.defineProperty(proto, "size", {
                    get: function size() {
                      return this.shape[0] * this.shape[1] * this.shape[2];
                    }
                  });
                  Object.defineProperty(proto, "order", {
                    get: function order2() {
                      var s0 = Math.abs(this.stride[0]), s1 = Math.abs(this.stride[1]), s2 = Math.abs(this.stride[2]);
                      if (s0 > s1) {
                        if (s1 > s2) {
                          return [2, 1, 0];
                        } else if (s0 > s2) {
                          return [1, 2, 0];
                        } else {
                          return [1, 0, 2];
                        }
                      } else if (s0 > s2) {
                        return [2, 0, 1];
                      } else if (s2 > s1) {
                        return [0, 1, 2];
                      } else {
                        return [0, 2, 1];
                      }
                    }
                  });
                  proto.set = function set(i0, i1, i2, v) {
                    return dtype === "generic" ? this.data.set(this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2, v) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2] = v;
                  };
                  proto.get = function get(i0, i1, i2) {
                    return dtype === "generic" ? this.data.get(this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2];
                  };
                  proto.index = function index(i0, i1, i2) {
                    return this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2;
                  };
                  proto.hi = function hi(i0, i1, i2) {
                    return new View(
                      this.data,
                      typeof i0 !== "number" || i0 < 0 ? this.shape[0] : i0 | 0,
                      typeof i1 !== "number" || i1 < 0 ? this.shape[1] : i1 | 0,
                      typeof i2 !== "number" || i2 < 0 ? this.shape[2] : i2 | 0,
                      this.stride[0],
                      this.stride[1],
                      this.stride[2],
                      this.offset
                    );
                  };
                  proto.lo = function lo(i0, i1, i2) {
                    var b = this.offset, d = 0, a0 = this.shape[0], a1 = this.shape[1], a2 = this.shape[2], c0 = this.stride[0], c1 = this.stride[1], c2 = this.stride[2];
                    if (typeof i0 === "number" && i0 >= 0) {
                      d = i0 | 0;
                      b += c0 * d;
                      a0 -= d;
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      d = i1 | 0;
                      b += c1 * d;
                      a1 -= d;
                    }
                    if (typeof i2 === "number" && i2 >= 0) {
                      d = i2 | 0;
                      b += c2 * d;
                      a2 -= d;
                    }
                    return new View(this.data, a0, a1, a2, c0, c1, c2, b);
                  };
                  proto.step = function step(i0, i1, i2) {
                    var a0 = this.shape[0], a1 = this.shape[1], a2 = this.shape[2], b0 = this.stride[0], b1 = this.stride[1], b2 = this.stride[2], c = this.offset, d = 0, ceil = Math.ceil;
                    if (typeof i0 === "number") {
                      d = i0 | 0;
                      if (d < 0) {
                        c += b0 * (a0 - 1);
                        a0 = ceil(-a0 / d);
                      } else {
                        a0 = ceil(a0 / d);
                      }
                      b0 *= d;
                    }
                    if (typeof i1 === "number") {
                      d = i1 | 0;
                      if (d < 0) {
                        c += b1 * (a1 - 1);
                        a1 = ceil(-a1 / d);
                      } else {
                        a1 = ceil(a1 / d);
                      }
                      b1 *= d;
                    }
                    if (typeof i2 === "number") {
                      d = i2 | 0;
                      if (d < 0) {
                        c += b2 * (a2 - 1);
                        a2 = ceil(-a2 / d);
                      } else {
                        a2 = ceil(a2 / d);
                      }
                      b2 *= d;
                    }
                    return new View(this.data, a0, a1, a2, b0, b1, b2, c);
                  };
                  proto.transpose = function transpose(i0, i1, i2) {
                    i0 = i0 === void 0 ? 0 : i0 | 0;
                    i1 = i1 === void 0 ? 1 : i1 | 0;
                    i2 = i2 === void 0 ? 2 : i2 | 0;
                    var a = this.shape, b = this.stride;
                    return new View(this.data, a[i0], a[i1], a[i2], b[i0], b[i1], b[i2], this.offset);
                  };
                  proto.pick = function pick(i0, i1, i2) {
                    var a = [], b = [], c = this.offset;
                    if (typeof i0 === "number" && i0 >= 0) {
                      c = c + this.stride[0] * i0 | 0;
                    } else {
                      a.push(this.shape[0]);
                      b.push(this.stride[0]);
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      c = c + this.stride[1] * i1 | 0;
                    } else {
                      a.push(this.shape[1]);
                      b.push(this.stride[1]);
                    }
                    if (typeof i2 === "number" && i2 >= 0) {
                      c = c + this.stride[2] * i2 | 0;
                    } else {
                      a.push(this.shape[2]);
                      b.push(this.stride[2]);
                    }
                    var ctor = CTOR_LIST[a.length + 1];
                    return ctor(this.data, a, b, c);
                  };
                  return function construct(data, shape, stride, offset) {
                    return new View(data, shape[0], shape[1], shape[2], stride[0], stride[1], stride[2], offset);
                  };
                },
                4: function(dtype, CTOR_LIST, ORDER) {
                  function View(a, b0, b1, b2, b3, c0, c1, c2, c3, d) {
                    this.data = a;
                    this.shape = [b0, b1, b2, b3];
                    this.stride = [c0, c1, c2, c3];
                    this.offset = d | 0;
                  }
                  var proto = View.prototype;
                  proto.dtype = dtype;
                  proto.dimension = 4;
                  Object.defineProperty(proto, "size", {
                    get: function size() {
                      return this.shape[0] * this.shape[1] * this.shape[2] * this.shape[3];
                    }
                  });
                  Object.defineProperty(proto, "order", { get: ORDER });
                  proto.set = function set(i0, i1, i2, i3, v) {
                    return dtype === "generic" ? this.data.set(this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3, v) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3] = v;
                  };
                  proto.get = function get(i0, i1, i2, i3) {
                    return dtype === "generic" ? this.data.get(this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3];
                  };
                  proto.index = function index(i0, i1, i2, i3) {
                    return this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3;
                  };
                  proto.hi = function hi(i0, i1, i2, i3) {
                    return new View(
                      this.data,
                      typeof i0 !== "number" || i0 < 0 ? this.shape[0] : i0 | 0,
                      typeof i1 !== "number" || i1 < 0 ? this.shape[1] : i1 | 0,
                      typeof i2 !== "number" || i2 < 0 ? this.shape[2] : i2 | 0,
                      typeof i3 !== "number" || i3 < 0 ? this.shape[3] : i3 | 0,
                      this.stride[0],
                      this.stride[1],
                      this.stride[2],
                      this.stride[3],
                      this.offset
                    );
                  };
                  proto.lo = function lo(i0, i1, i2, i3) {
                    var b = this.offset, d = 0, a0 = this.shape[0], a1 = this.shape[1], a2 = this.shape[2], a3 = this.shape[3], c0 = this.stride[0], c1 = this.stride[1], c2 = this.stride[2], c3 = this.stride[3];
                    if (typeof i0 === "number" && i0 >= 0) {
                      d = i0 | 0;
                      b += c0 * d;
                      a0 -= d;
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      d = i1 | 0;
                      b += c1 * d;
                      a1 -= d;
                    }
                    if (typeof i2 === "number" && i2 >= 0) {
                      d = i2 | 0;
                      b += c2 * d;
                      a2 -= d;
                    }
                    if (typeof i3 === "number" && i3 >= 0) {
                      d = i3 | 0;
                      b += c3 * d;
                      a3 -= d;
                    }
                    return new View(this.data, a0, a1, a2, a3, c0, c1, c2, c3, b);
                  };
                  proto.step = function step(i0, i1, i2, i3) {
                    var a0 = this.shape[0], a1 = this.shape[1], a2 = this.shape[2], a3 = this.shape[3], b0 = this.stride[0], b1 = this.stride[1], b2 = this.stride[2], b3 = this.stride[3], c = this.offset, d = 0, ceil = Math.ceil;
                    if (typeof i0 === "number") {
                      d = i0 | 0;
                      if (d < 0) {
                        c += b0 * (a0 - 1);
                        a0 = ceil(-a0 / d);
                      } else {
                        a0 = ceil(a0 / d);
                      }
                      b0 *= d;
                    }
                    if (typeof i1 === "number") {
                      d = i1 | 0;
                      if (d < 0) {
                        c += b1 * (a1 - 1);
                        a1 = ceil(-a1 / d);
                      } else {
                        a1 = ceil(a1 / d);
                      }
                      b1 *= d;
                    }
                    if (typeof i2 === "number") {
                      d = i2 | 0;
                      if (d < 0) {
                        c += b2 * (a2 - 1);
                        a2 = ceil(-a2 / d);
                      } else {
                        a2 = ceil(a2 / d);
                      }
                      b2 *= d;
                    }
                    if (typeof i3 === "number") {
                      d = i3 | 0;
                      if (d < 0) {
                        c += b3 * (a3 - 1);
                        a3 = ceil(-a3 / d);
                      } else {
                        a3 = ceil(a3 / d);
                      }
                      b3 *= d;
                    }
                    return new View(this.data, a0, a1, a2, a3, b0, b1, b2, b3, c);
                  };
                  proto.transpose = function transpose(i0, i1, i2, i3) {
                    i0 = i0 === void 0 ? 0 : i0 | 0;
                    i1 = i1 === void 0 ? 1 : i1 | 0;
                    i2 = i2 === void 0 ? 2 : i2 | 0;
                    i3 = i3 === void 0 ? 3 : i3 | 0;
                    var a = this.shape, b = this.stride;
                    return new View(this.data, a[i0], a[i1], a[i2], a[i3], b[i0], b[i1], b[i2], b[i3], this.offset);
                  };
                  proto.pick = function pick(i0, i1, i2, i3) {
                    var a = [], b = [], c = this.offset;
                    if (typeof i0 === "number" && i0 >= 0) {
                      c = c + this.stride[0] * i0 | 0;
                    } else {
                      a.push(this.shape[0]);
                      b.push(this.stride[0]);
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      c = c + this.stride[1] * i1 | 0;
                    } else {
                      a.push(this.shape[1]);
                      b.push(this.stride[1]);
                    }
                    if (typeof i2 === "number" && i2 >= 0) {
                      c = c + this.stride[2] * i2 | 0;
                    } else {
                      a.push(this.shape[2]);
                      b.push(this.stride[2]);
                    }
                    if (typeof i3 === "number" && i3 >= 0) {
                      c = c + this.stride[3] * i3 | 0;
                    } else {
                      a.push(this.shape[3]);
                      b.push(this.stride[3]);
                    }
                    var ctor = CTOR_LIST[a.length + 1];
                    return ctor(this.data, a, b, c);
                  };
                  return function construct(data, shape, stride, offset) {
                    return new View(data, shape[0], shape[1], shape[2], shape[3], stride[0], stride[1], stride[2], stride[3], offset);
                  };
                },
                5: function anonymous(dtype, CTOR_LIST, ORDER) {
                  function View(a, b0, b1, b2, b3, b4, c0, c1, c2, c3, c4, d) {
                    this.data = a;
                    this.shape = [b0, b1, b2, b3, b4];
                    this.stride = [c0, c1, c2, c3, c4];
                    this.offset = d | 0;
                  }
                  var proto = View.prototype;
                  proto.dtype = dtype;
                  proto.dimension = 5;
                  Object.defineProperty(proto, "size", {
                    get: function size() {
                      return this.shape[0] * this.shape[1] * this.shape[2] * this.shape[3] * this.shape[4];
                    }
                  });
                  Object.defineProperty(proto, "order", { get: ORDER });
                  proto.set = function set(i0, i1, i2, i3, i4, v) {
                    return dtype === "generic" ? this.data.set(
                      this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3 + this.stride[4] * i4,
                      v
                    ) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3 + this.stride[4] * i4] = v;
                  };
                  proto.get = function get(i0, i1, i2, i3, i4) {
                    return dtype === "generic" ? this.data.get(
                      this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3 + this.stride[4] * i4
                    ) : this.data[this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3 + this.stride[4] * i4];
                  };
                  proto.index = function index(i0, i1, i2, i3, i4) {
                    return this.offset + this.stride[0] * i0 + this.stride[1] * i1 + this.stride[2] * i2 + this.stride[3] * i3 + this.stride[4] * i4;
                  };
                  proto.hi = function hi(i0, i1, i2, i3, i4) {
                    return new View(
                      this.data,
                      typeof i0 !== "number" || i0 < 0 ? this.shape[0] : i0 | 0,
                      typeof i1 !== "number" || i1 < 0 ? this.shape[1] : i1 | 0,
                      typeof i2 !== "number" || i2 < 0 ? this.shape[2] : i2 | 0,
                      typeof i3 !== "number" || i3 < 0 ? this.shape[3] : i3 | 0,
                      typeof i4 !== "number" || i4 < 0 ? this.shape[4] : i4 | 0,
                      this.stride[0],
                      this.stride[1],
                      this.stride[2],
                      this.stride[3],
                      this.stride[4],
                      this.offset
                    );
                  };
                  proto.lo = function lo(i0, i1, i2, i3, i4) {
                    var b = this.offset, d = 0, a0 = this.shape[0], a1 = this.shape[1], a2 = this.shape[2], a3 = this.shape[3], a4 = this.shape[4], c0 = this.stride[0], c1 = this.stride[1], c2 = this.stride[2], c3 = this.stride[3], c4 = this.stride[4];
                    if (typeof i0 === "number" && i0 >= 0) {
                      d = i0 | 0;
                      b += c0 * d;
                      a0 -= d;
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      d = i1 | 0;
                      b += c1 * d;
                      a1 -= d;
                    }
                    if (typeof i2 === "number" && i2 >= 0) {
                      d = i2 | 0;
                      b += c2 * d;
                      a2 -= d;
                    }
                    if (typeof i3 === "number" && i3 >= 0) {
                      d = i3 | 0;
                      b += c3 * d;
                      a3 -= d;
                    }
                    if (typeof i4 === "number" && i4 >= 0) {
                      d = i4 | 0;
                      b += c4 * d;
                      a4 -= d;
                    }
                    return new View(this.data, a0, a1, a2, a3, a4, c0, c1, c2, c3, c4, b);
                  };
                  proto.step = function step(i0, i1, i2, i3, i4) {
                    var a0 = this.shape[0], a1 = this.shape[1], a2 = this.shape[2], a3 = this.shape[3], a4 = this.shape[4], b0 = this.stride[0], b1 = this.stride[1], b2 = this.stride[2], b3 = this.stride[3], b4 = this.stride[4], c = this.offset, d = 0, ceil = Math.ceil;
                    if (typeof i0 === "number") {
                      d = i0 | 0;
                      if (d < 0) {
                        c += b0 * (a0 - 1);
                        a0 = ceil(-a0 / d);
                      } else {
                        a0 = ceil(a0 / d);
                      }
                      b0 *= d;
                    }
                    if (typeof i1 === "number") {
                      d = i1 | 0;
                      if (d < 0) {
                        c += b1 * (a1 - 1);
                        a1 = ceil(-a1 / d);
                      } else {
                        a1 = ceil(a1 / d);
                      }
                      b1 *= d;
                    }
                    if (typeof i2 === "number") {
                      d = i2 | 0;
                      if (d < 0) {
                        c += b2 * (a2 - 1);
                        a2 = ceil(-a2 / d);
                      } else {
                        a2 = ceil(a2 / d);
                      }
                      b2 *= d;
                    }
                    if (typeof i3 === "number") {
                      d = i3 | 0;
                      if (d < 0) {
                        c += b3 * (a3 - 1);
                        a3 = ceil(-a3 / d);
                      } else {
                        a3 = ceil(a3 / d);
                      }
                      b3 *= d;
                    }
                    if (typeof i4 === "number") {
                      d = i4 | 0;
                      if (d < 0) {
                        c += b4 * (a4 - 1);
                        a4 = ceil(-a4 / d);
                      } else {
                        a4 = ceil(a4 / d);
                      }
                      b4 *= d;
                    }
                    return new View(this.data, a0, a1, a2, a3, a4, b0, b1, b2, b3, b4, c);
                  };
                  proto.transpose = function transpose(i0, i1, i2, i3, i4) {
                    i0 = i0 === void 0 ? 0 : i0 | 0;
                    i1 = i1 === void 0 ? 1 : i1 | 0;
                    i2 = i2 === void 0 ? 2 : i2 | 0;
                    i3 = i3 === void 0 ? 3 : i3 | 0;
                    i4 = i4 === void 0 ? 4 : i4 | 0;
                    var a = this.shape, b = this.stride;
                    return new View(this.data, a[i0], a[i1], a[i2], a[i3], a[i4], b[i0], b[i1], b[i2], b[i3], b[i4], this.offset);
                  };
                  proto.pick = function pick(i0, i1, i2, i3, i4) {
                    var a = [], b = [], c = this.offset;
                    if (typeof i0 === "number" && i0 >= 0) {
                      c = c + this.stride[0] * i0 | 0;
                    } else {
                      a.push(this.shape[0]);
                      b.push(this.stride[0]);
                    }
                    if (typeof i1 === "number" && i1 >= 0) {
                      c = c + this.stride[1] * i1 | 0;
                    } else {
                      a.push(this.shape[1]);
                      b.push(this.stride[1]);
                    }
                    if (typeof i2 === "number" && i2 >= 0) {
                      c = c + this.stride[2] * i2 | 0;
                    } else {
                      a.push(this.shape[2]);
                      b.push(this.stride[2]);
                    }
                    if (typeof i3 === "number" && i3 >= 0) {
                      c = c + this.stride[3] * i3 | 0;
                    } else {
                      a.push(this.shape[3]);
                      b.push(this.stride[3]);
                    }
                    if (typeof i4 === "number" && i4 >= 0) {
                      c = c + this.stride[4] * i4 | 0;
                    } else {
                      a.push(this.shape[4]);
                      b.push(this.stride[4]);
                    }
                    var ctor = CTOR_LIST[a.length + 1];
                    return ctor(this.data, a, b, c);
                  };
                  return function construct(data, shape, stride, offset) {
                    return new View(
                      data,
                      shape[0],
                      shape[1],
                      shape[2],
                      shape[3],
                      shape[4],
                      stride[0],
                      stride[1],
                      stride[2],
                      stride[3],
                      stride[4],
                      offset
                    );
                  };
                }
              };
              function compileConstructor(inType, inDimension) {
                var dKey = inDimension === -1 ? "T" : String(inDimension);
                var procedure = allFns[dKey];
                if (inDimension === -1) {
                  return procedure(inType);
                } else if (inDimension === 0) {
                  return procedure(inType, CACHED_CONSTRUCTORS[inType][0]);
                }
                return procedure(inType, CACHED_CONSTRUCTORS[inType], order);
              }
              function arrayDType(data) {
                if (isBuffer(data)) {
                  return "buffer";
                }
                if (hasTypedArrays) {
                  switch (Object.prototype.toString.call(data)) {
                    case "[object Float64Array]":
                      return "float64";
                    case "[object Float32Array]":
                      return "float32";
                    case "[object Int8Array]":
                      return "int8";
                    case "[object Int16Array]":
                      return "int16";
                    case "[object Int32Array]":
                      return "int32";
                    case "[object Uint8ClampedArray]":
                      return "uint8_clamped";
                    case "[object Uint8Array]":
                      return "uint8";
                    case "[object Uint16Array]":
                      return "uint16";
                    case "[object Uint32Array]":
                      return "uint32";
                    case "[object BigInt64Array]":
                      return "bigint64";
                    case "[object BigUint64Array]":
                      return "biguint64";
                  }
                }
                if (Array.isArray(data)) {
                  return "array";
                }
                return "generic";
              }
              var CACHED_CONSTRUCTORS = {
                "generic": [],
                "buffer": [],
                "array": [],
                // typed arrays
                "float32": [],
                "float64": [],
                "int8": [],
                "int16": [],
                "int32": [],
                "uint8_clamped": [],
                "uint8": [],
                "uint16": [],
                "uint32": [],
                "bigint64": [],
                "biguint64": []
              };
              (function() {
                for (var id in CACHED_CONSTRUCTORS) {
                  CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1));
                }
              });
              function wrappedNDArrayCtor(data, shape, stride, offset) {
                if (data === void 0) {
                  var ctor = CACHED_CONSTRUCTORS.array[0];
                  return ctor([]);
                } else if (typeof data === "number") {
                  data = [data];
                }
                if (shape === void 0) {
                  shape = [data.length];
                }
                var d = shape.length;
                if (stride === void 0) {
                  stride = new Array(d);
                  for (var i = d - 1, sz = 1; i >= 0; --i) {
                    stride[i] = sz;
                    sz *= shape[i];
                  }
                }
                if (offset === void 0) {
                  offset = 0;
                  for (var i = 0; i < d; ++i) {
                    if (stride[i] < 0) {
                      offset -= (shape[i] - 1) * stride[i];
                    }
                  }
                }
                var inType = arrayDType(data);
                var ctor_list = CACHED_CONSTRUCTORS[inType];
                while (ctor_list.length <= d + 1) {
                  ctor_list.push(compileConstructor(inType, ctor_list.length - 1));
                }
                var ctor = ctor_list[d + 1];
                return ctor(data, shape, stride, offset);
              }
              module2.exports = wrappedNDArrayCtor;
            }
          ),
          /***/
          9921: (
            /***/
            function(module2) {
              module2.exports = determinant;
              function determinant(a) {
                var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
                return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
              }
              ;
            }
          ),
          /***/
          9922: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = equals;
              var EPSILON = __webpack_require__2(2613);
              function equals(a, b) {
                var a0 = a[0];
                var a1 = a[1];
                var a2 = a[2];
                var b0 = b[0];
                var b1 = b[1];
                var b2 = b[2];
                return Math.abs(a0 - b0) <= EPSILON * Math.max(1, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1, Math.abs(a2), Math.abs(b2));
              }
            }
          ),
          /***/
          9970: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              module2.exports = {
                create: __webpack_require__2(7536),
                clone: __webpack_require__2(2335),
                fromValues: __webpack_require__2(3390),
                copy: __webpack_require__2(2933),
                set: __webpack_require__2(4578),
                add: __webpack_require__2(4361),
                subtract: __webpack_require__2(6860),
                multiply: __webpack_require__2(3576),
                divide: __webpack_require__2(1373),
                min: __webpack_require__2(2334),
                max: __webpack_require__2(160),
                scale: __webpack_require__2(9288),
                scaleAndAdd: __webpack_require__2(4844),
                distance: __webpack_require__2(4691),
                squaredDistance: __webpack_require__2(7960),
                length: __webpack_require__2(6808),
                squaredLength: __webpack_require__2(483),
                negate: __webpack_require__2(1498),
                inverse: __webpack_require__2(4494),
                normalize: __webpack_require__2(5177),
                dot: __webpack_require__2(3750),
                lerp: __webpack_require__2(2573),
                random: __webpack_require__2(9131),
                transformMat4: __webpack_require__2(5352),
                transformQuat: __webpack_require__2(4041)
              };
            }
          ),
          /***/
          9977: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              module2.exports = createOrbitController;
              var filterVector = __webpack_require__2(9215);
              var lookAt = __webpack_require__2(6582);
              var mat4FromQuat = __webpack_require__2(7399);
              var invert44 = __webpack_require__2(7608);
              var quatFromFrame = __webpack_require__2(4081);
              function len3(x, y, z) {
                return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
              }
              function len4(w, x, y, z) {
                return Math.sqrt(Math.pow(w, 2) + Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
              }
              function normalize4(out, a) {
                var ax = a[0];
                var ay = a[1];
                var az = a[2];
                var aw = a[3];
                var al = len4(ax, ay, az, aw);
                if (al > 1e-6) {
                  out[0] = ax / al;
                  out[1] = ay / al;
                  out[2] = az / al;
                  out[3] = aw / al;
                } else {
                  out[0] = out[1] = out[2] = 0;
                  out[3] = 1;
                }
              }
              function OrbitCameraController(initQuat, initCenter, initRadius) {
                this.radius = filterVector([initRadius]);
                this.center = filterVector(initCenter);
                this.rotation = filterVector(initQuat);
                this.computedRadius = this.radius.curve(0);
                this.computedCenter = this.center.curve(0);
                this.computedRotation = this.rotation.curve(0);
                this.computedUp = [0.1, 0, 0];
                this.computedEye = [0.1, 0, 0];
                this.computedMatrix = [0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                this.recalcMatrix(0);
              }
              var proto = OrbitCameraController.prototype;
              proto.lastT = function() {
                return Math.max(
                  this.radius.lastT(),
                  this.center.lastT(),
                  this.rotation.lastT()
                );
              };
              proto.recalcMatrix = function(t) {
                this.radius.curve(t);
                this.center.curve(t);
                this.rotation.curve(t);
                var quat = this.computedRotation;
                normalize4(quat, quat);
                var mat = this.computedMatrix;
                mat4FromQuat(mat, quat);
                var center = this.computedCenter;
                var eye = this.computedEye;
                var up = this.computedUp;
                var radius = Math.exp(this.computedRadius[0]);
                eye[0] = center[0] + radius * mat[2];
                eye[1] = center[1] + radius * mat[6];
                eye[2] = center[2] + radius * mat[10];
                up[0] = mat[1];
                up[1] = mat[5];
                up[2] = mat[9];
                for (var i = 0; i < 3; ++i) {
                  var rr = 0;
                  for (var j = 0; j < 3; ++j) {
                    rr += mat[i + 4 * j] * eye[j];
                  }
                  mat[12 + i] = -rr;
                }
              };
              proto.getMatrix = function(t, result) {
                this.recalcMatrix(t);
                var m = this.computedMatrix;
                if (result) {
                  for (var i = 0; i < 16; ++i) {
                    result[i] = m[i];
                  }
                  return result;
                }
                return m;
              };
              proto.idle = function(t) {
                this.center.idle(t);
                this.radius.idle(t);
                this.rotation.idle(t);
              };
              proto.flush = function(t) {
                this.center.flush(t);
                this.radius.flush(t);
                this.rotation.flush(t);
              };
              proto.pan = function(t, dx, dy, dz) {
                dx = dx || 0;
                dy = dy || 0;
                dz = dz || 0;
                this.recalcMatrix(t);
                var mat = this.computedMatrix;
                var ux = mat[1];
                var uy = mat[5];
                var uz = mat[9];
                var ul = len3(ux, uy, uz);
                ux /= ul;
                uy /= ul;
                uz /= ul;
                var rx = mat[0];
                var ry = mat[4];
                var rz = mat[8];
                var ru = rx * ux + ry * uy + rz * uz;
                rx -= ux * ru;
                ry -= uy * ru;
                rz -= uz * ru;
                var rl = len3(rx, ry, rz);
                rx /= rl;
                ry /= rl;
                rz /= rl;
                var fx = mat[2];
                var fy = mat[6];
                var fz = mat[10];
                var fu = fx * ux + fy * uy + fz * uz;
                var fr = fx * rx + fy * ry + fz * rz;
                fx -= fu * ux + fr * rx;
                fy -= fu * uy + fr * ry;
                fz -= fu * uz + fr * rz;
                var fl = len3(fx, fy, fz);
                fx /= fl;
                fy /= fl;
                fz /= fl;
                var vx = rx * dx + ux * dy;
                var vy = ry * dx + uy * dy;
                var vz = rz * dx + uz * dy;
                this.center.move(t, vx, vy, vz);
                var radius = Math.exp(this.computedRadius[0]);
                radius = Math.max(1e-4, radius + dz);
                this.radius.set(t, Math.log(radius));
              };
              proto.rotate = function(t, dx, dy, dz) {
                this.recalcMatrix(t);
                dx = dx || 0;
                dy = dy || 0;
                var mat = this.computedMatrix;
                var rx = mat[0];
                var ry = mat[4];
                var rz = mat[8];
                var ux = mat[1];
                var uy = mat[5];
                var uz = mat[9];
                var fx = mat[2];
                var fy = mat[6];
                var fz = mat[10];
                var qx = dx * rx + dy * ux;
                var qy = dx * ry + dy * uy;
                var qz = dx * rz + dy * uz;
                var bx = -(fy * qz - fz * qy);
                var by = -(fz * qx - fx * qz);
                var bz = -(fx * qy - fy * qx);
                var bw = Math.sqrt(Math.max(0, 1 - Math.pow(bx, 2) - Math.pow(by, 2) - Math.pow(bz, 2)));
                var bl = len4(bx, by, bz, bw);
                if (bl > 1e-6) {
                  bx /= bl;
                  by /= bl;
                  bz /= bl;
                  bw /= bl;
                } else {
                  bx = by = bz = 0;
                  bw = 1;
                }
                var rotation = this.computedRotation;
                var ax = rotation[0];
                var ay = rotation[1];
                var az = rotation[2];
                var aw = rotation[3];
                var cx = ax * bw + aw * bx + ay * bz - az * by;
                var cy = ay * bw + aw * by + az * bx - ax * bz;
                var cz = az * bw + aw * bz + ax * by - ay * bx;
                var cw = aw * bw - ax * bx - ay * by - az * bz;
                if (dz) {
                  bx = fx;
                  by = fy;
                  bz = fz;
                  var s = Math.sin(dz) / len3(bx, by, bz);
                  bx *= s;
                  by *= s;
                  bz *= s;
                  bw = Math.cos(dx);
                  cx = cx * bw + cw * bx + cy * bz - cz * by;
                  cy = cy * bw + cw * by + cz * bx - cx * bz;
                  cz = cz * bw + cw * bz + cx * by - cy * bx;
                  cw = cw * bw - cx * bx - cy * by - cz * bz;
                }
                var cl = len4(cx, cy, cz, cw);
                if (cl > 1e-6) {
                  cx /= cl;
                  cy /= cl;
                  cz /= cl;
                  cw /= cl;
                } else {
                  cx = cy = cz = 0;
                  cw = 1;
                }
                this.rotation.set(t, cx, cy, cz, cw);
              };
              proto.lookAt = function(t, eye, center, up) {
                this.recalcMatrix(t);
                center = center || this.computedCenter;
                eye = eye || this.computedEye;
                up = up || this.computedUp;
                var mat = this.computedMatrix;
                lookAt(mat, eye, center, up);
                var rotation = this.computedRotation;
                quatFromFrame(
                  rotation,
                  mat[0],
                  mat[1],
                  mat[2],
                  mat[4],
                  mat[5],
                  mat[6],
                  mat[8],
                  mat[9],
                  mat[10]
                );
                normalize4(rotation, rotation);
                this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3]);
                var fl = 0;
                for (var i = 0; i < 3; ++i) {
                  fl += Math.pow(center[i] - eye[i], 2);
                }
                this.radius.set(t, 0.5 * Math.log(Math.max(fl, 1e-6)));
                this.center.set(t, center[0], center[1], center[2]);
              };
              proto.translate = function(t, dx, dy, dz) {
                this.center.move(
                  t,
                  dx || 0,
                  dy || 0,
                  dz || 0
                );
              };
              proto.setMatrix = function(t, matrix) {
                var rotation = this.computedRotation;
                quatFromFrame(
                  rotation,
                  matrix[0],
                  matrix[1],
                  matrix[2],
                  matrix[4],
                  matrix[5],
                  matrix[6],
                  matrix[8],
                  matrix[9],
                  matrix[10]
                );
                normalize4(rotation, rotation);
                this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3]);
                var mat = this.computedMatrix;
                invert44(mat, matrix);
                var w = mat[15];
                if (Math.abs(w) > 1e-6) {
                  var cx = mat[12] / w;
                  var cy = mat[13] / w;
                  var cz = mat[14] / w;
                  this.recalcMatrix(t);
                  var r = Math.exp(this.computedRadius[0]);
                  this.center.set(t, cx - mat[2] * r, cy - mat[6] * r, cz - mat[10] * r);
                  this.radius.idle(t);
                } else {
                  this.center.idle(t);
                  this.radius.idle(t);
                }
              };
              proto.setDistance = function(t, d) {
                if (d > 0) {
                  this.radius.set(t, Math.log(d));
                }
              };
              proto.setDistanceLimits = function(lo, hi) {
                if (lo > 0) {
                  lo = Math.log(lo);
                } else {
                  lo = -Infinity;
                }
                if (hi > 0) {
                  hi = Math.log(hi);
                } else {
                  hi = Infinity;
                }
                hi = Math.max(hi, lo);
                this.radius.bounds[0][0] = lo;
                this.radius.bounds[1][0] = hi;
              };
              proto.getDistanceLimits = function(out) {
                var bounds = this.radius.bounds;
                if (out) {
                  out[0] = Math.exp(bounds[0][0]);
                  out[1] = Math.exp(bounds[1][0]);
                  return out;
                }
                return [Math.exp(bounds[0][0]), Math.exp(bounds[1][0])];
              };
              proto.toJSON = function() {
                this.recalcMatrix(this.lastT());
                return {
                  center: this.computedCenter.slice(),
                  rotation: this.computedRotation.slice(),
                  distance: Math.log(this.computedRadius[0]),
                  zoomMin: this.radius.bounds[0][0],
                  zoomMax: this.radius.bounds[1][0]
                };
              };
              proto.fromJSON = function(options) {
                var t = this.lastT();
                var c = options.center;
                if (c) {
                  this.center.set(t, c[0], c[1], c[2]);
                }
                var r = options.rotation;
                if (r) {
                  this.rotation.set(t, r[0], r[1], r[2], r[3]);
                }
                var d = options.distance;
                if (d && d > 0) {
                  this.radius.set(t, Math.log(d));
                }
                this.setDistanceLimits(options.zoomMin, options.zoomMax);
              };
              function createOrbitController(options) {
                options = options || {};
                var center = options.center || [0, 0, 0];
                var rotation = options.rotation || [0, 0, 0, 1];
                var radius = options.radius || 1;
                center = [].slice.call(center, 0, 3);
                rotation = [].slice.call(rotation, 0, 4);
                normalize4(rotation, rotation);
                var result = new OrbitCameraController(
                  rotation,
                  center,
                  Math.log(radius)
                );
                result.setDistanceLimits(options.zoomMin, options.zoomMax);
                if ("eye" in options || "up" in options) {
                  result.lookAt(0, options.eye, options.center, options.up);
                }
                return result;
              }
            }
          ),
          /***/
          9994: (
            /***/
            function(module2, __unused_webpack_exports, __webpack_require__2) {
              "use strict";
              var ndarray = __webpack_require__2(9618);
              var do_convert = __webpack_require__2(8277);
              module2.exports = function convert(arr, result) {
                var shape = [], c = arr, sz = 1;
                while (Array.isArray(c)) {
                  shape.push(c.length);
                  sz *= c.length;
                  c = c[0];
                }
                if (shape.length === 0) {
                  return ndarray();
                }
                if (!result) {
                  result = ndarray(new Float64Array(sz), shape);
                }
                do_convert(result, arr);
                return result;
              };
            }
          )
          /******/
        };
        var __webpack_module_cache__ = {};
        function __webpack_require__(moduleId) {
          var cachedModule = __webpack_module_cache__[moduleId];
          if (cachedModule !== void 0) {
            return cachedModule.exports;
          }
          var module2 = __webpack_module_cache__[moduleId] = {
            /******/
            id: moduleId,
            /******/
            loaded: false,
            /******/
            exports: {}
            /******/
          };
          __webpack_modules__[moduleId].call(module2.exports, module2, module2.exports, __webpack_require__);
          module2.loaded = true;
          return module2.exports;
        }
        !function() {
          __webpack_require__.g = function() {
            if (typeof globalThis === "object") return globalThis;
            try {
              return this || new Function("return this")();
            } catch (e) {
              if (typeof window === "object") return window;
            }
          }();
        }();
        !function() {
          __webpack_require__.nmd = function(module2) {
            module2.paths = [];
            if (!module2.children) module2.children = [];
            return module2;
          };
        }();
        var __webpack_exports__ = __webpack_require__(1964);
        module.exports = __webpack_exports__;
      })();
    }
  });

  // node_modules/color-name/index.js
  var require_color_name = __commonJS({
    "node_modules/color-name/index.js"(exports, module) {
      "use strict";
      module.exports = {
        "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],
        "green": [0, 128, 0],
        "greenyellow": [173, 255, 47],
        "grey": [128, 128, 128],
        "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],
        "rebeccapurple": [102, 51, 153],
        "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]
      };
    }
  });

  // node_modules/color-normalize/node_modules/color-parse/index.js
  var require_color_parse = __commonJS({
    "node_modules/color-normalize/node_modules/color-parse/index.js"(exports, module) {
      "use strict";
      var names2 = require_color_name();
      module.exports = parse2;
      var baseHues2 = {
        red: 0,
        orange: 60,
        yellow: 120,
        green: 180,
        blue: 240,
        purple: 300
      };
      function parse2(cstr) {
        var m, parts = [], alpha = 1, space;
        if (typeof cstr === "string") {
          cstr = cstr.toLowerCase();
          if (names2[cstr]) {
            parts = names2[cstr].slice();
            space = "rgb";
          } else if (cstr === "transparent") {
            alpha = 0;
            space = "rgb";
            parts = [0, 0, 0];
          } else if (/^#[A-Fa-f0-9]+$/.test(cstr)) {
            var base = cstr.slice(1);
            var size = base.length;
            var isShort = size <= 4;
            alpha = 1;
            if (isShort) {
              parts = [
                parseInt(base[0] + base[0], 16),
                parseInt(base[1] + base[1], 16),
                parseInt(base[2] + base[2], 16)
              ];
              if (size === 4) {
                alpha = parseInt(base[3] + base[3], 16) / 255;
              }
            } else {
              parts = [
                parseInt(base[0] + base[1], 16),
                parseInt(base[2] + base[3], 16),
                parseInt(base[4] + base[5], 16)
              ];
              if (size === 8) {
                alpha = parseInt(base[6] + base[7], 16) / 255;
              }
            }
            if (!parts[0]) parts[0] = 0;
            if (!parts[1]) parts[1] = 0;
            if (!parts[2]) parts[2] = 0;
            space = "rgb";
          } else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) {
            var name2 = m[1];
            var isRGB = name2 === "rgb";
            var base = name2.replace(/a$/, "");
            space = base;
            var size = base === "cmyk" ? 4 : base === "gray" ? 1 : 3;
            parts = m[2].trim().split(/\s*[,\/]\s*|\s+/).map(function(x, i) {
              if (/%$/.test(x)) {
                if (i === size) return parseFloat(x) / 100;
                if (base === "rgb") return parseFloat(x) * 255 / 100;
                return parseFloat(x);
              } else if (base[i] === "h") {
                if (/deg$/.test(x)) {
                  return parseFloat(x);
                } else if (baseHues2[x] !== void 0) {
                  return baseHues2[x];
                }
              }
              return parseFloat(x);
            });
            if (name2 === base) parts.push(1);
            alpha = isRGB ? 1 : parts[size] === void 0 ? 1 : parts[size];
            parts = parts.slice(0, size);
          } else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) {
            parts = cstr.match(/([0-9]+)/g).map(function(value) {
              return parseFloat(value);
            });
            space = cstr.match(/([a-z])/ig).join("").toLowerCase();
          }
        } else if (!isNaN(cstr)) {
          space = "rgb";
          parts = [cstr >>> 16, (cstr & 65280) >>> 8, cstr & 255];
        } else if (Array.isArray(cstr) || cstr.length) {
          parts = [cstr[0], cstr[1], cstr[2]];
          space = "rgb";
          alpha = cstr.length === 4 ? cstr[3] : 1;
        } else if (cstr instanceof Object) {
          if (cstr.r != null || cstr.red != null || cstr.R != null) {
            space = "rgb";
            parts = [
              cstr.r || cstr.red || cstr.R || 0,
              cstr.g || cstr.green || cstr.G || 0,
              cstr.b || cstr.blue || cstr.B || 0
            ];
          } else {
            space = "hsl";
            parts = [
              cstr.h || cstr.hue || cstr.H || 0,
              cstr.s || cstr.saturation || cstr.S || 0,
              cstr.l || cstr.lightness || cstr.L || cstr.b || cstr.brightness
            ];
          }
          alpha = cstr.a || cstr.alpha || cstr.opacity || 1;
          if (cstr.opacity != null) alpha /= 100;
        }
        return {
          space,
          values: parts,
          alpha
        };
      }
    }
  });

  // node_modules/color-normalize/node_modules/color-rgba/index.js
  var require_color_rgba = __commonJS({
    "node_modules/color-normalize/node_modules/color-rgba/index.js"(exports, module) {
      "use strict";
      var parse2 = require_color_parse();
      module.exports = function rgba3(color2) {
        if (Array.isArray(color2) && color2.raw) color2 = String.raw.apply(null, arguments);
        var values, i, l;
        var parsed = parse2(color2);
        if (!parsed.space) return [];
        var min = [0, 0, 0], max = parsed.space[0] === "h" ? [360, 100, 100] : [255, 255, 255];
        values = Array(3);
        values[0] = Math.min(Math.max(parsed.values[0], min[0]), max[0]);
        values[1] = Math.min(Math.max(parsed.values[1], min[1]), max[1]);
        values[2] = Math.min(Math.max(parsed.values[2], min[2]), max[2]);
        if (parsed.space[0] === "h") values = hsl2rgb2(values);
        values.push(Math.min(Math.max(parsed.alpha, 0), 1));
        return values;
      };
      function hsl2rgb2(hsl3) {
        var h = hsl3[0] / 360, s = hsl3[1] / 100, l = hsl3[2] / 100, t12, t22, t32, rgb2, val, i = 0;
        if (s === 0) return val = l * 255, [val, val, val];
        t22 = l < 0.5 ? l * (1 + s) : l + s - l * s;
        t12 = 2 * l - t22;
        rgb2 = [0, 0, 0];
        for (; i < 3; ) {
          t32 = h + 1 / 3 * -(i - 1);
          t32 < 0 ? t32++ : t32 > 1 && t32--;
          val = 6 * t32 < 1 ? t12 + (t22 - t12) * 6 * t32 : 2 * t32 < 1 ? t22 : 3 * t32 < 2 ? t12 + (t22 - t12) * (2 / 3 - t32) * 6 : t12;
          rgb2[i++] = val * 255;
        }
        return rgb2;
      }
    }
  });

  // node_modules/clamp/index.js
  var require_clamp = __commonJS({
    "node_modules/clamp/index.js"(exports, module) {
      module.exports = clamp;
      function clamp(value, min, max) {
        return min < max ? value < min ? min : value > max ? max : value : value < max ? max : value > min ? min : value;
      }
    }
  });

  // node_modules/dtype/index.js
  var require_dtype = __commonJS({
    "node_modules/dtype/index.js"(exports, module) {
      module.exports = function(dtype) {
        switch (dtype) {
          case "int8":
            return Int8Array;
          case "int16":
            return Int16Array;
          case "int32":
            return Int32Array;
          case "uint8":
            return Uint8Array;
          case "uint16":
            return Uint16Array;
          case "uint32":
            return Uint32Array;
          case "float32":
            return Float32Array;
          case "float64":
            return Float64Array;
          case "array":
            return Array;
          case "uint8_clamped":
            return Uint8ClampedArray;
        }
      };
    }
  });

  // node_modules/color-normalize/index.js
  var require_color_normalize = __commonJS({
    "node_modules/color-normalize/index.js"(exports, module) {
      "use strict";
      var rgba3 = require_color_rgba();
      var clamp = require_clamp();
      var dtype = require_dtype();
      module.exports = function normalize(color2, type) {
        if (type === "float" || !type) type = "array";
        if (type === "uint") type = "uint8";
        if (type === "uint_clamped") type = "uint8_clamped";
        var Ctor = dtype(type);
        var output = new Ctor(4);
        var normalize2 = type !== "uint8" && type !== "uint8_clamped";
        if (!color2.length || typeof color2 === "string") {
          color2 = rgba3(color2);
          color2[0] /= 255;
          color2[1] /= 255;
          color2[2] /= 255;
        }
        if (isInt(color2)) {
          output[0] = color2[0];
          output[1] = color2[1];
          output[2] = color2[2];
          output[3] = color2[3] != null ? color2[3] : 255;
          if (normalize2) {
            output[0] /= 255;
            output[1] /= 255;
            output[2] /= 255;
            output[3] /= 255;
          }
          return output;
        }
        if (!normalize2) {
          output[0] = clamp(Math.floor(color2[0] * 255), 0, 255);
          output[1] = clamp(Math.floor(color2[1] * 255), 0, 255);
          output[2] = clamp(Math.floor(color2[2] * 255), 0, 255);
          output[3] = color2[3] == null ? 255 : clamp(Math.floor(color2[3] * 255), 0, 255);
        } else {
          output[0] = color2[0];
          output[1] = color2[1];
          output[2] = color2[2];
          output[3] = color2[3] != null ? color2[3] : 1;
        }
        return output;
      };
      function isInt(color2) {
        if (color2 instanceof Uint8Array || color2 instanceof Uint8ClampedArray) return true;
        if (Array.isArray(color2) && (color2[0] > 1 || color2[0] === 0) && (color2[1] > 1 || color2[1] === 0) && (color2[2] > 1 || color2[2] === 0) && (!color2[3] || color2[3] > 1)) return true;
        return false;
      }
    }
  });

  // src/lib/str2rgbarray.js
  var require_str2rgbarray = __commonJS({
    "src/lib/str2rgbarray.js"(exports, module) {
      "use strict";
      var rgba3 = require_color_normalize();
      function str2RgbaArray(color2) {
        if (!color2) return [0, 0, 0, 1];
        return rgba3(color2);
      }
      module.exports = str2RgbaArray;
    }
  });

  // src/lib/gl_format_color.js
  var require_gl_format_color = __commonJS({
    "src/lib/gl_format_color.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var tinycolor = require_tinycolor();
      var rgba3 = require_color_normalize();
      var Colorscale = require_colorscale();
      var colorDflt = require_attributes3().defaultLine;
      var isArrayOrTypedArray = require_array().isArrayOrTypedArray;
      var colorDfltRgba = rgba3(colorDflt);
      var opacityDflt = 1;
      function calculateColor(colorIn, opacityIn) {
        var colorOut = colorIn;
        colorOut[3] *= opacityIn;
        return colorOut;
      }
      function validateColor(colorIn) {
        if (isNumeric(colorIn)) return colorDfltRgba;
        var colorOut = rgba3(colorIn);
        return colorOut.length ? colorOut : colorDfltRgba;
      }
      function validateOpacity(opacityIn) {
        return isNumeric(opacityIn) ? opacityIn : opacityDflt;
      }
      function formatColor(containerIn, opacityIn, len) {
        var colorIn = containerIn.color;
        if (colorIn && colorIn._inputArray) colorIn = colorIn._inputArray;
        var isArrayColorIn = isArrayOrTypedArray(colorIn);
        var isArrayOpacityIn = isArrayOrTypedArray(opacityIn);
        var cOpts = Colorscale.extractOpts(containerIn);
        var colorOut = [];
        var sclFunc, getColor, getOpacity, colori, opacityi;
        if (cOpts.colorscale !== void 0) {
          sclFunc = Colorscale.makeColorScaleFuncFromTrace(containerIn);
        } else {
          sclFunc = validateColor;
        }
        if (isArrayColorIn) {
          getColor = function(c, i2) {
            return c[i2] === void 0 ? colorDfltRgba : rgba3(sclFunc(c[i2]));
          };
        } else getColor = validateColor;
        if (isArrayOpacityIn) {
          getOpacity = function(o, i2) {
            return o[i2] === void 0 ? opacityDflt : validateOpacity(o[i2]);
          };
        } else getOpacity = validateOpacity;
        if (isArrayColorIn || isArrayOpacityIn) {
          for (var i = 0; i < len; i++) {
            colori = getColor(colorIn, i);
            opacityi = getOpacity(opacityIn, i);
            colorOut[i] = calculateColor(colori, opacityi);
          }
        } else colorOut = calculateColor(rgba3(colorIn), opacityIn);
        return colorOut;
      }
      function parseColorScale(cont) {
        var cOpts = Colorscale.extractOpts(cont);
        var colorscale = cOpts.colorscale;
        if (cOpts.reversescale) colorscale = Colorscale.flipScale(cOpts.colorscale);
        return colorscale.map(function(elem) {
          var index = elem[0];
          var color2 = tinycolor(elem[1]);
          var rgb2 = color2.toRgb();
          return {
            index,
            rgb: [rgb2.r, rgb2.g, rgb2.b, rgb2.a]
          };
        });
      }
      module.exports = {
        formatColor,
        parseColorScale
      };
    }
  });

  // src/constants/gl3d_dashes.js
  var require_gl3d_dashes = __commonJS({
    "src/constants/gl3d_dashes.js"(exports, module) {
      "use strict";
      module.exports = {
        solid: [[], 0],
        dot: [[0.5, 1], 200],
        dash: [[0.5, 1], 50],
        longdash: [[0.5, 1], 10],
        dashdot: [[0.5, 0.625, 0.875, 1], 50],
        longdashdot: [[0.5, 0.7, 0.8, 1], 10]
      };
    }
  });

  // src/constants/gl3d_markers.js
  var require_gl3d_markers = __commonJS({
    "src/constants/gl3d_markers.js"(exports, module) {
      "use strict";
      module.exports = {
        circle: "\u25CF",
        "circle-open": "\u25CB",
        square: "\u25A0",
        "square-open": "\u25A1",
        diamond: "\u25C6",
        "diamond-open": "\u25C7",
        cross: "+",
        x: "\u274C"
      };
    }
  });

  // src/traces/scatter3d/calc_errors.js
  var require_calc_errors = __commonJS({
    "src/traces/scatter3d/calc_errors.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      function calculateAxisErrors(data, params, scaleFactor, axis) {
        if (!params || !params.visible) return null;
        var computeError = Registry.getComponentMethod("errorbars", "makeComputeError")(params);
        var result = new Array(data.length);
        for (var i = 0; i < data.length; i++) {
          var errors = computeError(+data[i], i);
          if (axis.type === "log") {
            var point = axis.c2l(data[i]);
            var min = data[i] - errors[0];
            var max = data[i] + errors[1];
            result[i] = [
              (axis.c2l(min, true) - point) * scaleFactor,
              (axis.c2l(max, true) - point) * scaleFactor
            ];
            if (min > 0) {
              var lower = axis.c2l(min);
              if (!axis._lowerLogErrorBound) axis._lowerLogErrorBound = lower;
              axis._lowerErrorBound = Math.min(axis._lowerLogErrorBound, lower);
            }
          } else {
            result[i] = [
              -errors[0] * scaleFactor,
              errors[1] * scaleFactor
            ];
          }
        }
        return result;
      }
      function dataLength(array) {
        for (var i = 0; i < array.length; i++) {
          if (array[i]) return array[i].length;
        }
        return 0;
      }
      function calculateErrors(data, scaleFactor, sceneLayout) {
        var errors = [
          calculateAxisErrors(data.x, data.error_x, scaleFactor[0], sceneLayout.xaxis),
          calculateAxisErrors(data.y, data.error_y, scaleFactor[1], sceneLayout.yaxis),
          calculateAxisErrors(data.z, data.error_z, scaleFactor[2], sceneLayout.zaxis)
        ];
        var n = dataLength(errors);
        if (n === 0) return null;
        var errorBounds = new Array(n);
        for (var i = 0; i < n; i++) {
          var bound = [[0, 0, 0], [0, 0, 0]];
          for (var j = 0; j < 3; j++) {
            if (errors[j]) {
              for (var k = 0; k < 2; k++) {
                bound[k][j] = errors[j][i][k];
              }
            }
          }
          errorBounds[i] = bound;
        }
        return errorBounds;
      }
      module.exports = calculateErrors;
    }
  });

  // src/traces/scatter3d/convert.js
  var require_convert2 = __commonJS({
    "src/traces/scatter3d/convert.js"(exports, module) {
      "use strict";
      var createLinePlot = require_stackgl_modules().gl_line3d;
      var createScatterPlot = require_stackgl_modules().gl_scatter3d;
      var createErrorBars = require_stackgl_modules().gl_error3d;
      var createMesh = require_stackgl_modules().gl_mesh3d;
      var triangulate = require_stackgl_modules().delaunay_triangulate;
      var Lib = require_lib();
      var str2RgbaArray = require_str2rgbarray();
      var formatColor = require_gl_format_color().formatColor;
      var makeBubbleSizeFn = require_make_bubble_size_func();
      var DASH_PATTERNS = require_gl3d_dashes();
      var MARKER_SYMBOLS = require_gl3d_markers();
      var Axes = require_axes();
      var appendArrayPointValue = require_helpers2().appendArrayPointValue;
      var calculateError = require_calc_errors();
      function LineWithMarkers(scene, uid) {
        this.scene = scene;
        this.uid = uid;
        this.linePlot = null;
        this.scatterPlot = null;
        this.errorBars = null;
        this.textMarkers = null;
        this.delaunayMesh = null;
        this.color = null;
        this.mode = "";
        this.dataPoints = [];
        this.axesBounds = [
          [-Infinity, -Infinity, -Infinity],
          [Infinity, Infinity, Infinity]
        ];
        this.textLabels = null;
        this.data = null;
      }
      var proto = LineWithMarkers.prototype;
      proto.handlePick = function(selection) {
        if (selection.object && (selection.object === this.linePlot || selection.object === this.delaunayMesh || selection.object === this.textMarkers || selection.object === this.scatterPlot)) {
          var ind = selection.index = selection.data.index;
          if (selection.object.highlight) {
            selection.object.highlight(null);
          }
          if (this.scatterPlot) {
            selection.object = this.scatterPlot;
            this.scatterPlot.highlight(selection.data);
          }
          selection.textLabel = "";
          if (this.textLabels) {
            if (Lib.isArrayOrTypedArray(this.textLabels)) {
              if (this.textLabels[ind] || this.textLabels[ind] === 0) {
                selection.textLabel = this.textLabels[ind];
              }
            } else {
              selection.textLabel = this.textLabels;
            }
          }
          selection.traceCoordinate = [this.data.x[ind], this.data.y[ind], this.data.z[ind]];
          return true;
        }
      };
      function constructDelaunay(points, color2, axis) {
        var u = (axis + 1) % 3;
        var v = (axis + 2) % 3;
        var filteredPoints = [];
        var filteredIds = [];
        var i;
        for (i = 0; i < points.length; ++i) {
          var p = points[i];
          if (isNaN(p[u]) || !isFinite(p[u]) || isNaN(p[v]) || !isFinite(p[v])) {
            continue;
          }
          filteredPoints.push([p[u], p[v]]);
          filteredIds.push(i);
        }
        var cells = triangulate(filteredPoints);
        for (i = 0; i < cells.length; ++i) {
          var c = cells[i];
          for (var j = 0; j < c.length; ++j) {
            c[j] = filteredIds[c[j]];
          }
        }
        return {
          positions: points,
          cells,
          meshColor: color2
        };
      }
      function calculateErrorParams(errors) {
        var capSize = [0, 0, 0];
        var color2 = [
          [0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]
        ];
        var lineWidth = [1, 1, 1];
        for (var i = 0; i < 3; i++) {
          var e = errors[i];
          if (e && e.copy_zstyle !== false && errors[2].visible !== false) e = errors[2];
          if (!e || !e.visible) continue;
          capSize[i] = e.width / 2;
          color2[i] = str2RgbaArray(e.color);
          lineWidth[i] = e.thickness;
        }
        return { capSize, color: color2, lineWidth };
      }
      function parseAlignmentX(a) {
        if (a === null || a === void 0) return 0;
        return a.indexOf("left") > -1 ? -1 : a.indexOf("right") > -1 ? 1 : 0;
      }
      function parseAlignmentY(a) {
        if (a === null || a === void 0) return 0;
        return a.indexOf("top") > -1 ? -1 : a.indexOf("bottom") > -1 ? 1 : 0;
      }
      function calculateTextOffset(tp) {
        var defaultAlignmentX = 0;
        var defaultAlignmentY = 0;
        var textOffset = [defaultAlignmentX, defaultAlignmentY];
        if (Array.isArray(tp)) {
          for (var i = 0; i < tp.length; i++) {
            textOffset[i] = [defaultAlignmentX, defaultAlignmentY];
            if (tp[i]) {
              textOffset[i][0] = parseAlignmentX(tp[i]);
              textOffset[i][1] = parseAlignmentY(tp[i]);
            }
          }
        } else {
          textOffset[0] = parseAlignmentX(tp);
          textOffset[1] = parseAlignmentY(tp);
        }
        return textOffset;
      }
      function calculateSize(sizeIn, sizeFn) {
        return sizeFn(sizeIn * 4);
      }
      function calculateSymbol(symbolIn) {
        return MARKER_SYMBOLS[symbolIn];
      }
      function formatParam(paramIn, len, calculate, dflt, extraFn) {
        var paramOut = null;
        if (Lib.isArrayOrTypedArray(paramIn)) {
          paramOut = [];
          for (var i = 0; i < len; i++) {
            if (paramIn[i] === void 0) paramOut[i] = dflt;
            else paramOut[i] = calculate(paramIn[i], extraFn);
          }
        } else paramOut = calculate(paramIn, Lib.identity);
        return paramOut;
      }
      function convertPlotlyOptions(scene, data) {
        var points = [];
        var sceneLayout = scene.fullSceneLayout;
        var scaleFactor = scene.dataScale;
        var xaxis = sceneLayout.xaxis;
        var yaxis = sceneLayout.yaxis;
        var zaxis = sceneLayout.zaxis;
        var marker = data.marker;
        var line = data.line;
        var x = data.x || [];
        var y = data.y || [];
        var z = data.z || [];
        var len = x.length;
        var xcalendar = data.xcalendar;
        var ycalendar = data.ycalendar;
        var zcalendar = data.zcalendar;
        var xc, yc, zc;
        var params, i;
        var text;
        for (i = 0; i < len; i++) {
          xc = xaxis.d2l(x[i], 0, xcalendar) * scaleFactor[0];
          yc = yaxis.d2l(y[i], 0, ycalendar) * scaleFactor[1];
          zc = zaxis.d2l(z[i], 0, zcalendar) * scaleFactor[2];
          points[i] = [xc, yc, zc];
        }
        if (Array.isArray(data.text)) {
          text = data.text;
        } else if (Lib.isTypedArray(data.text)) {
          text = Array.from(data.text);
        } else if (data.text !== void 0) {
          text = new Array(len);
          for (i = 0; i < len; i++) text[i] = data.text;
        }
        function formatter(axName, val) {
          var ax = sceneLayout[axName];
          return Axes.tickText(ax, ax.d2l(val), true).text;
        }
        var texttemplate = data.texttemplate;
        if (texttemplate) {
          var fullLayout = scene.fullLayout;
          var d3locale = fullLayout._d3locale;
          var isArray = Array.isArray(texttemplate);
          var N = isArray ? Math.min(texttemplate.length, len) : len;
          var txt = isArray ? function(i2) {
            return texttemplate[i2];
          } : function() {
            return texttemplate;
          };
          text = new Array(N);
          for (i = 0; i < N; i++) {
            var d = { x: x[i], y: y[i], z: z[i] };
            var labels = {
              xLabel: formatter("xaxis", x[i]),
              yLabel: formatter("yaxis", y[i]),
              zLabel: formatter("zaxis", z[i])
            };
            var pointValues = {};
            appendArrayPointValue(pointValues, data, i);
            text[i] = Lib.texttemplateString({
              data: [pointValues, d, data._meta],
              fallback: data.texttemplatefallback,
              labels,
              locale: d3locale,
              template: txt(i)
            });
          }
        }
        params = {
          position: points,
          mode: data.mode,
          text
        };
        if ("line" in data) {
          params.lineColor = formatColor(line, 1, len);
          params.lineWidth = line.width;
          params.lineDashes = line.dash;
        }
        if ("marker" in data) {
          var sizeFn = makeBubbleSizeFn(data);
          params.scatterColor = formatColor(marker, 1, len);
          params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn);
          params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, "\u25CF");
          params.scatterLineWidth = marker.line.width;
          params.scatterLineColor = formatColor(marker.line, 1, len);
          params.scatterAngle = 0;
        }
        if ("textposition" in data) {
          params.textOffset = calculateTextOffset(data.textposition);
          params.textColor = formatColor(data.textfont, 1, len);
          params.textSize = formatParam(data.textfont.size, len, Lib.identity, 12);
          params.textFontFamily = data.textfont.family;
          params.textFontWeight = data.textfont.weight;
          params.textFontStyle = data.textfont.style;
          params.textFontVariant = data.textfont.variant;
          params.textAngle = 0;
        }
        var dims = ["x", "y", "z"];
        params.project = [false, false, false];
        params.projectScale = [1, 1, 1];
        params.projectOpacity = [1, 1, 1];
        for (i = 0; i < 3; ++i) {
          var projection = data.projection[dims[i]];
          if (params.project[i] = projection.show) {
            params.projectOpacity[i] = projection.opacity;
            params.projectScale[i] = projection.scale;
          }
        }
        params.errorBounds = calculateError(data, scaleFactor, sceneLayout);
        var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]);
        params.errorColor = errorParams.color;
        params.errorLineWidth = errorParams.lineWidth;
        params.errorCapSize = errorParams.capSize;
        params.delaunayAxis = data.surfaceaxis;
        params.delaunayColor = str2RgbaArray(data.surfacecolor);
        return params;
      }
      function _arrayToColor(color2) {
        if (Lib.isArrayOrTypedArray(color2)) {
          var c = color2[0];
          if (Lib.isArrayOrTypedArray(c)) color2 = c;
          return "rgb(" + color2.slice(0, 3).map(function(x) {
            return Math.round(x * 255);
          }) + ")";
        }
        return null;
      }
      function arrayToColor(colors) {
        if (!Lib.isArrayOrTypedArray(colors)) {
          return null;
        }
        if (colors.length === 4 && typeof colors[0] === "number") {
          return _arrayToColor(colors);
        }
        return colors.map(_arrayToColor);
      }
      proto.update = function(data) {
        var gl2 = this.scene.glplot.gl;
        var lineOptions;
        var scatterOptions;
        var errorOptions;
        var textOptions;
        var dashPattern = DASH_PATTERNS.solid;
        this.data = data;
        var options = convertPlotlyOptions(this.scene, data);
        if ("mode" in options) {
          this.mode = options.mode;
        }
        if ("lineDashes" in options) {
          if (options.lineDashes in DASH_PATTERNS) {
            dashPattern = DASH_PATTERNS[options.lineDashes];
          }
        }
        this.color = arrayToColor(options.scatterColor) || arrayToColor(options.lineColor);
        this.dataPoints = options.position;
        lineOptions = {
          gl: this.scene.glplot.gl,
          position: options.position,
          color: options.lineColor,
          lineWidth: options.lineWidth || 1,
          dashes: dashPattern[0],
          dashScale: dashPattern[1],
          opacity: data.opacity,
          connectGaps: data.connectgaps
        };
        if (this.mode.indexOf("lines") !== -1) {
          if (this.linePlot) this.linePlot.update(lineOptions);
          else {
            this.linePlot = createLinePlot(lineOptions);
            this.linePlot._trace = this;
            this.scene.glplot.add(this.linePlot);
          }
        } else if (this.linePlot) {
          this.scene.glplot.remove(this.linePlot);
          this.linePlot.dispose();
          this.linePlot = null;
        }
        var scatterOpacity = data.opacity;
        if (data.marker && data.marker.opacity !== void 0) scatterOpacity *= data.marker.opacity;
        scatterOptions = {
          gl: this.scene.glplot.gl,
          position: options.position,
          color: options.scatterColor,
          size: options.scatterSize,
          glyph: options.scatterMarker,
          opacity: scatterOpacity,
          orthographic: true,
          lineWidth: options.scatterLineWidth,
          lineColor: options.scatterLineColor,
          project: options.project,
          projectScale: options.projectScale,
          projectOpacity: options.projectOpacity
        };
        if (this.mode.indexOf("markers") !== -1) {
          if (this.scatterPlot) this.scatterPlot.update(scatterOptions);
          else {
            this.scatterPlot = createScatterPlot(scatterOptions);
            this.scatterPlot._trace = this;
            this.scatterPlot.highlightScale = 1;
            this.scene.glplot.add(this.scatterPlot);
          }
        } else if (this.scatterPlot) {
          this.scene.glplot.remove(this.scatterPlot);
          this.scatterPlot.dispose();
          this.scatterPlot = null;
        }
        textOptions = {
          gl: this.scene.glplot.gl,
          position: options.position,
          glyph: options.text,
          color: options.textColor,
          size: options.textSize,
          angle: options.textAngle,
          alignment: options.textOffset,
          font: options.textFontFamily,
          fontWeight: options.textFontWeight,
          fontStyle: options.textFontStyle,
          fontVariant: options.textFontVariant,
          orthographic: true,
          lineWidth: 0,
          project: false,
          opacity: data.opacity
        };
        this.textLabels = data.hovertext || data.text;
        if (this.mode.indexOf("text") !== -1) {
          if (this.textMarkers) this.textMarkers.update(textOptions);
          else {
            this.textMarkers = createScatterPlot(textOptions);
            this.textMarkers._trace = this;
            this.textMarkers.highlightScale = 1;
            this.scene.glplot.add(this.textMarkers);
          }
        } else if (this.textMarkers) {
          this.scene.glplot.remove(this.textMarkers);
          this.textMarkers.dispose();
          this.textMarkers = null;
        }
        errorOptions = {
          gl: this.scene.glplot.gl,
          position: options.position,
          color: options.errorColor,
          error: options.errorBounds,
          lineWidth: options.errorLineWidth,
          capSize: options.errorCapSize,
          opacity: data.opacity
        };
        if (this.errorBars) {
          if (options.errorBounds) {
            this.errorBars.update(errorOptions);
          } else {
            this.scene.glplot.remove(this.errorBars);
            this.errorBars.dispose();
            this.errorBars = null;
          }
        } else if (options.errorBounds) {
          this.errorBars = createErrorBars(errorOptions);
          this.errorBars._trace = this;
          this.scene.glplot.add(this.errorBars);
        }
        if (options.delaunayAxis >= 0) {
          var delaunayOptions = constructDelaunay(options.position, options.delaunayColor, options.delaunayAxis);
          delaunayOptions.opacity = data.opacity;
          if (this.delaunayMesh) {
            this.delaunayMesh.update(delaunayOptions);
          } else {
            delaunayOptions.gl = gl2;
            this.delaunayMesh = createMesh(delaunayOptions);
            this.delaunayMesh._trace = this;
            this.scene.glplot.add(this.delaunayMesh);
          }
        } else if (this.delaunayMesh) {
          this.scene.glplot.remove(this.delaunayMesh);
          this.delaunayMesh.dispose();
          this.delaunayMesh = null;
        }
      };
      proto.dispose = function() {
        if (this.linePlot) {
          this.scene.glplot.remove(this.linePlot);
          this.linePlot.dispose();
        }
        if (this.scatterPlot) {
          this.scene.glplot.remove(this.scatterPlot);
          this.scatterPlot.dispose();
        }
        if (this.errorBars) {
          this.scene.glplot.remove(this.errorBars);
          this.errorBars.dispose();
        }
        if (this.textMarkers) {
          this.scene.glplot.remove(this.textMarkers);
          this.textMarkers.dispose();
        }
        if (this.delaunayMesh) {
          this.scene.glplot.remove(this.delaunayMesh);
          this.delaunayMesh.dispose();
        }
      };
      function createLineWithMarkers(scene, data) {
        var plot = new LineWithMarkers(scene, data.uid);
        plot.update(data);
        return plot;
      }
      module.exports = createLineWithMarkers;
    }
  });

  // src/traces/scatter3d/attributes.js
  var require_attributes40 = __commonJS({
    "src/traces/scatter3d/attributes.js"(exports, module) {
      "use strict";
      var scatterAttrs = require_attributes12();
      var fontAttrs = require_font_attributes();
      var colorAttributes = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var baseAttrs = require_attributes2();
      var DASHES = require_gl3d_dashes();
      var MARKER_SYMBOLS = require_gl3d_markers();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var sortObjectKeys = require_sort_object_keys();
      var scatterLineAttrs = scatterAttrs.line;
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      var lineAttrs = extendFlat(
        {
          width: scatterLineAttrs.width,
          dash: {
            valType: "enumerated",
            values: sortObjectKeys(DASHES),
            dflt: "solid"
          }
        },
        colorAttributes("line")
      );
      function makeProjectionAttr(axLetter) {
        return {
          show: {
            valType: "boolean",
            dflt: false
          },
          opacity: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 1
          },
          scale: {
            valType: "number",
            min: 0,
            max: 10,
            dflt: 2 / 3
          }
        };
      }
      var attrs = module.exports = overrideAll(
        {
          x: scatterAttrs.x,
          y: scatterAttrs.y,
          z: {
            valType: "data_array"
          },
          text: extendFlat({}, scatterAttrs.text, {}),
          texttemplate: texttemplateAttrs(),
          texttemplatefallback: templatefallbackAttrs({ editType: "calc" }),
          hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs(),
          xhoverformat: axisHoverFormat("x"),
          yhoverformat: axisHoverFormat("y"),
          zhoverformat: axisHoverFormat("z"),
          mode: extendFlat(
            {},
            scatterAttrs.mode,
            // shouldn't this be on-par with 2D?
            { dflt: "lines+markers" }
          ),
          surfaceaxis: {
            valType: "enumerated",
            values: [-1, 0, 1, 2],
            dflt: -1
          },
          surfacecolor: {
            valType: "color"
          },
          projection: {
            x: makeProjectionAttr("x"),
            y: makeProjectionAttr("y"),
            z: makeProjectionAttr("z")
          },
          connectgaps: scatterAttrs.connectgaps,
          line: lineAttrs,
          marker: extendFlat(
            {
              // Parity with scatter.js?
              symbol: {
                valType: "enumerated",
                values: sortObjectKeys(MARKER_SYMBOLS),
                dflt: "circle",
                arrayOk: true
              },
              size: extendFlat({}, scatterMarkerAttrs.size, { dflt: 8 }),
              sizeref: scatterMarkerAttrs.sizeref,
              sizemin: scatterMarkerAttrs.sizemin,
              sizemode: scatterMarkerAttrs.sizemode,
              opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
                arrayOk: false
              }),
              colorbar: scatterMarkerAttrs.colorbar,
              line: extendFlat(
                {
                  width: extendFlat({}, scatterMarkerLineAttrs.width, { arrayOk: false })
                },
                colorAttributes("marker.line")
              )
            },
            colorAttributes("marker")
          ),
          textposition: extendFlat({}, scatterAttrs.textposition, { dflt: "top center" }),
          textfont: fontAttrs({
            noFontShadow: true,
            noFontLineposition: true,
            noFontTextcase: true,
            editType: "calc",
            colorEditType: "style",
            arrayOk: true,
            variantValues: ["normal", "small-caps"]
          }),
          opacity: baseAttrs.opacity,
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
        },
        "calc",
        "nested"
      );
      attrs.x.editType = attrs.y.editType = attrs.z.editType = "calc+clearAxisTypes";
    }
  });

  // src/traces/scatter3d/defaults.js
  var require_defaults36 = __commonJS({
    "src/traces/scatter3d/defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleTextDefaults = require_text_defaults();
      var attributes = require_attributes40();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("zhoverformat");
        coerce("mode");
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
            noAngle: true,
            noLineDash: true,
            noSelect: true
          });
        }
        if (subTypes.hasLines(traceOut)) {
          coerce("connectgaps");
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce, {
            noSelect: true,
            noFontShadow: true,
            noFontLineposition: true,
            noFontTextcase: true
          });
        }
        var lineColor = (traceOut.line || {}).color;
        var markerColor = (traceOut.marker || {}).color;
        if (coerce("surfaceaxis") >= 0) coerce("surfacecolor", lineColor || markerColor);
        var dims = ["x", "y", "z"];
        for (var i = 0; i < 3; ++i) {
          var projection = "projection." + dims[i];
          if (coerce(projection + ".show")) {
            coerce(projection + ".opacity");
            coerce(projection + ".scale");
          }
        }
        var errorBarsSupplyDefaults = Registry.getComponentMethod("errorbars", "supplyDefaults");
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "z" });
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "y", inherit: "z" });
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "x", inherit: "z" });
      };
      function handleXYZDefaults(traceIn, traceOut, coerce, layout) {
        var len = 0;
        var x = coerce("x");
        var y = coerce("y");
        var z = coerce("z");
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y", "z"], layout);
        if (x && y && z) {
          len = Math.min(x.length, y.length, z.length);
          traceOut._length = traceOut._xlength = traceOut._ylength = traceOut._zlength = len;
        }
        return len;
      }
    }
  });

  // src/traces/scatter3d/calc.js
  var require_calc21 = __commonJS({
    "src/traces/scatter3d/calc.js"(exports, module) {
      "use strict";
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcColorscale = require_colorscale_calc();
      module.exports = function calc(gd, trace) {
        var cd = [{ x: false, y: false, trace, t: {} }];
        arraysToCalcdata(cd, trace);
        calcColorscale(gd, trace);
        return cd;
      };
    }
  });

  // node_modules/get-canvas-context/index.js
  var require_get_canvas_context = __commonJS({
    "node_modules/get-canvas-context/index.js"(exports, module) {
      module.exports = getCanvasContext;
      function getCanvasContext(type, opts) {
        if (typeof type !== "string") {
          throw new TypeError("must specify type string");
        }
        opts = opts || {};
        if (typeof document === "undefined" && !opts.canvas) {
          return null;
        }
        var canvas = opts.canvas || document.createElement("canvas");
        if (typeof opts.width === "number") {
          canvas.width = opts.width;
        }
        if (typeof opts.height === "number") {
          canvas.height = opts.height;
        }
        var attribs = opts;
        var gl2;
        try {
          var names2 = [type];
          if (type.indexOf("webgl") === 0) {
            names2.push("experimental-" + type);
          }
          for (var i = 0; i < names2.length; i++) {
            gl2 = canvas.getContext(names2[i], attribs);
            if (gl2) return gl2;
          }
        } catch (e) {
          gl2 = null;
        }
        return gl2 || null;
      }
    }
  });

  // node_modules/webgl-context/index.js
  var require_webgl_context = __commonJS({
    "node_modules/webgl-context/index.js"(exports, module) {
      var getContext = require_get_canvas_context();
      module.exports = function getWebGLContext(opt) {
        return getContext("webgl", opt);
      };
    }
  });

  // src/lib/show_no_webgl_msg.js
  var require_show_no_webgl_msg = __commonJS({
    "src/lib/show_no_webgl_msg.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var noop = function() {
      };
      module.exports = function showNoWebGlMsg(scene) {
        for (var prop in scene) {
          if (typeof scene[prop] === "function") scene[prop] = noop;
        }
        scene.destroy = function() {
          scene.container.parentNode.removeChild(scene.container);
        };
        var div = document.createElement("div");
        div.className = "no-webgl";
        div.style.cursor = "pointer";
        div.style.fontSize = "24px";
        div.style.color = Color2.defaults[0];
        div.style.position = "absolute";
        div.style.left = div.style.top = "0px";
        div.style.width = div.style.height = "100%";
        div.style["background-color"] = Color2.lightLine;
        div.style["z-index"] = 30;
        var p = document.createElement("p");
        p.textContent = "WebGL is not supported by your browser - visit https://get.webgl.org for more info";
        p.style.position = "relative";
        p.style.top = "50%";
        p.style.left = "50%";
        p.style.height = "30%";
        p.style.width = "50%";
        p.style.margin = "-15% 0 0 -25%";
        div.appendChild(p);
        scene.container.appendChild(div);
        scene.container.style.background = "#FFFFFF";
        scene.container.onclick = function() {
          window.open("https://get.webgl.org");
        };
        return false;
      };
    }
  });

  // src/plots/gl3d/layout/convert.js
  var require_convert3 = __commonJS({
    "src/plots/gl3d/layout/convert.js"(exports, module) {
      "use strict";
      var str2RgbaArray = require_str2rgbarray();
      var Lib = require_lib();
      var AXES_NAMES = ["xaxis", "yaxis", "zaxis"];
      function AxesOptions() {
        this.bounds = [
          [-10, -10, -10],
          [10, 10, 10]
        ];
        this.ticks = [[], [], []];
        this.tickEnable = [true, true, true];
        this.tickFont = ["sans-serif", "sans-serif", "sans-serif"];
        this.tickSize = [12, 12, 12];
        this.tickFontWeight = ["normal", "normal", "normal", "normal"];
        this.tickFontStyle = ["normal", "normal", "normal", "normal"];
        this.tickFontVariant = ["normal", "normal", "normal", "normal"];
        this.tickAngle = [0, 0, 0];
        this.tickColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
        this.tickPad = [18, 18, 18];
        this.labels = ["x", "y", "z"];
        this.labelEnable = [true, true, true];
        this.labelFont = ["Open Sans", "Open Sans", "Open Sans"];
        this.labelSize = [20, 20, 20];
        this.labelFontWeight = ["normal", "normal", "normal", "normal"];
        this.labelFontStyle = ["normal", "normal", "normal", "normal"];
        this.labelFontVariant = ["normal", "normal", "normal", "normal"];
        this.labelColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
        this.labelPad = [30, 30, 30];
        this.lineEnable = [true, true, true];
        this.lineMirror = [false, false, false];
        this.lineWidth = [1, 1, 1];
        this.lineColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
        this.lineTickEnable = [true, true, true];
        this.lineTickMirror = [false, false, false];
        this.lineTickLength = [10, 10, 10];
        this.lineTickWidth = [1, 1, 1];
        this.lineTickColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
        this.gridEnable = [true, true, true];
        this.gridWidth = [1, 1, 1];
        this.gridColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
        this.zeroEnable = [true, true, true];
        this.zeroLineColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]];
        this.zeroLineWidth = [2, 2, 2];
        this.backgroundEnable = [true, true, true];
        this.backgroundColor = [
          [0.8, 0.8, 0.8, 0.5],
          [0.8, 0.8, 0.8, 0.5],
          [0.8, 0.8, 0.8, 0.5]
        ];
        this._defaultTickPad = this.tickPad.slice();
        this._defaultLabelPad = this.labelPad.slice();
        this._defaultLineTickLength = this.lineTickLength.slice();
      }
      var proto = AxesOptions.prototype;
      proto.merge = function(fullLayout, sceneLayout) {
        var opts = this;
        for (var i = 0; i < 3; ++i) {
          var axes = sceneLayout[AXES_NAMES[i]];
          if (!axes.visible) {
            opts.tickEnable[i] = false;
            opts.labelEnable[i] = false;
            opts.lineEnable[i] = false;
            opts.lineTickEnable[i] = false;
            opts.gridEnable[i] = false;
            opts.zeroEnable[i] = false;
            opts.backgroundEnable[i] = false;
            continue;
          }
          opts.labels[i] = fullLayout._meta ? Lib.templateString(axes.title.text, fullLayout._meta) : axes.title.text;
          if ("font" in axes.title) {
            if (axes.title.font.color) opts.labelColor[i] = str2RgbaArray(axes.title.font.color);
            if (axes.title.font.family) opts.labelFont[i] = axes.title.font.family;
            if (axes.title.font.size) opts.labelSize[i] = axes.title.font.size;
            if (axes.title.font.weight) opts.labelFontWeight[i] = axes.title.font.weight;
            if (axes.title.font.style) opts.labelFontStyle[i] = axes.title.font.style;
            if (axes.title.font.variant) opts.labelFontVariant[i] = axes.title.font.variant;
          }
          if ("showline" in axes) opts.lineEnable[i] = axes.showline;
          if ("linecolor" in axes) opts.lineColor[i] = str2RgbaArray(axes.linecolor);
          if ("linewidth" in axes) opts.lineWidth[i] = axes.linewidth;
          if ("showgrid" in axes) opts.gridEnable[i] = axes.showgrid;
          if ("gridcolor" in axes) opts.gridColor[i] = str2RgbaArray(axes.gridcolor);
          if ("gridwidth" in axes) opts.gridWidth[i] = axes.gridwidth;
          if (axes.type === "log") opts.zeroEnable[i] = false;
          else if ("zeroline" in axes) opts.zeroEnable[i] = axes.zeroline;
          if ("zerolinecolor" in axes) opts.zeroLineColor[i] = str2RgbaArray(axes.zerolinecolor);
          if ("zerolinewidth" in axes) opts.zeroLineWidth[i] = axes.zerolinewidth;
          if ("ticks" in axes && !!axes.ticks) opts.lineTickEnable[i] = true;
          else opts.lineTickEnable[i] = false;
          if ("ticklen" in axes) {
            opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen;
          }
          if ("tickcolor" in axes) opts.lineTickColor[i] = str2RgbaArray(axes.tickcolor);
          if ("tickwidth" in axes) opts.lineTickWidth[i] = axes.tickwidth;
          if ("tickangle" in axes) {
            opts.tickAngle[i] = axes.tickangle === "auto" ? -3600 : (
              // i.e. special number to set auto option
              Math.PI * -axes.tickangle / 180
            );
          }
          if ("showticklabels" in axes) opts.tickEnable[i] = axes.showticklabels;
          if ("tickfont" in axes) {
            if (axes.tickfont.color) opts.tickColor[i] = str2RgbaArray(axes.tickfont.color);
            if (axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family;
            if (axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size;
            if (axes.tickfont.weight) opts.tickFontWeight[i] = axes.tickfont.weight;
            if (axes.tickfont.style) opts.tickFontStyle[i] = axes.tickfont.style;
            if (axes.tickfont.variant) opts.tickFontVariant[i] = axes.tickfont.variant;
          }
          if ("mirror" in axes) {
            if (["ticks", "all", "allticks"].indexOf(axes.mirror) !== -1) {
              opts.lineTickMirror[i] = true;
              opts.lineMirror[i] = true;
            } else if (axes.mirror === true) {
              opts.lineTickMirror[i] = false;
              opts.lineMirror[i] = true;
            } else {
              opts.lineTickMirror[i] = false;
              opts.lineMirror[i] = false;
            }
          } else opts.lineMirror[i] = false;
          if ("showbackground" in axes && axes.showbackground !== false) {
            opts.backgroundEnable[i] = true;
            opts.backgroundColor[i] = str2RgbaArray(axes.backgroundcolor);
          } else opts.backgroundEnable[i] = false;
        }
      };
      function createAxesOptions(fullLayout, sceneLayout) {
        var result = new AxesOptions();
        result.merge(fullLayout, sceneLayout);
        return result;
      }
      module.exports = createAxesOptions;
    }
  });

  // src/plots/gl3d/layout/spikes.js
  var require_spikes = __commonJS({
    "src/plots/gl3d/layout/spikes.js"(exports, module) {
      "use strict";
      var str2RGBArray = require_str2rgbarray();
      var AXES_NAMES = ["xaxis", "yaxis", "zaxis"];
      function SpikeOptions() {
        this.enabled = [true, true, true];
        this.colors = [
          [0, 0, 0, 1],
          [0, 0, 0, 1],
          [0, 0, 0, 1]
        ];
        this.drawSides = [true, true, true];
        this.lineWidth = [1, 1, 1];
      }
      var proto = SpikeOptions.prototype;
      proto.merge = function(sceneLayout) {
        for (var i = 0; i < 3; ++i) {
          var axes = sceneLayout[AXES_NAMES[i]];
          if (!axes.visible) {
            this.enabled[i] = false;
            this.drawSides[i] = false;
            continue;
          }
          this.enabled[i] = axes.showspikes;
          this.colors[i] = str2RGBArray(axes.spikecolor);
          this.drawSides[i] = axes.spikesides;
          this.lineWidth[i] = axes.spikethickness;
        }
      };
      function createSpikeOptions(layout) {
        var result = new SpikeOptions();
        result.merge(layout);
        return result;
      }
      module.exports = createSpikeOptions;
    }
  });

  // src/plots/gl3d/layout/tick_marks.js
  var require_tick_marks = __commonJS({
    "src/plots/gl3d/layout/tick_marks.js"(exports, module) {
      "use strict";
      module.exports = computeTickMarks;
      var Axes = require_axes();
      var Lib = require_lib();
      var AXES_NAMES = ["xaxis", "yaxis", "zaxis"];
      var centerPoint = [0, 0, 0];
      function contourLevelsFromTicks(ticks) {
        var result = new Array(3);
        for (var i = 0; i < 3; ++i) {
          var tlevel = ticks[i];
          var clevel = new Array(tlevel.length);
          for (var j = 0; j < tlevel.length; ++j) {
            clevel[j] = tlevel[j].x;
          }
          result[i] = clevel;
        }
        return result;
      }
      function computeTickMarks(scene) {
        var axesOptions = scene.axesOptions;
        var glRange = scene.glplot.axesPixels;
        var sceneLayout = scene.fullSceneLayout;
        var ticks = [[], [], []];
        for (var i = 0; i < 3; ++i) {
          var axes = sceneLayout[AXES_NAMES[i]];
          axes._length = (glRange[i].hi - glRange[i].lo) * glRange[i].pixelsPerDataUnit / scene.dataScale[i];
          if (Math.abs(axes._length) === Infinity || isNaN(axes._length)) {
            ticks[i] = [];
          } else {
            axes._input_range = axes.range.slice();
            axes.range[0] = glRange[i].lo / scene.dataScale[i];
            axes.range[1] = glRange[i].hi / scene.dataScale[i];
            axes._m = 1 / (scene.dataScale[i] * glRange[i].pixelsPerDataUnit);
            if (axes.range[0] === axes.range[1]) {
              axes.range[0] -= 1;
              axes.range[1] += 1;
            }
            var tickModeCached = axes.tickmode;
            if (axes.tickmode === "auto") {
              axes.tickmode = "linear";
              var nticks = axes.nticks || Lib.constrain(axes._length / 40, 4, 9);
              Axes.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks);
            }
            var dataTicks = Axes.calcTicks(axes, { msUTC: true });
            for (var j = 0; j < dataTicks.length; ++j) {
              dataTicks[j].x = dataTicks[j].x * scene.dataScale[i];
              if (axes.type === "date") {
                dataTicks[j].text = dataTicks[j].text.replace(/\<br\>/g, " ");
              }
            }
            ticks[i] = dataTicks;
            axes.tickmode = tickModeCached;
          }
        }
        axesOptions.ticks = ticks;
        for (var i = 0; i < 3; ++i) {
          centerPoint[i] = 0.5 * (scene.glplot.bounds[0][i] + scene.glplot.bounds[1][i]);
          for (var j = 0; j < 2; ++j) {
            axesOptions.bounds[j][i] = scene.glplot.bounds[j][i];
          }
        }
        scene.contourLevels = contourLevelsFromTicks(ticks);
      }
    }
  });

  // src/plots/gl3d/scene.js
  var require_scene = __commonJS({
    "src/plots/gl3d/scene.js"(exports, module) {
      "use strict";
      var glPlot3d = require_stackgl_modules().gl_plot3d;
      var createCamera = glPlot3d.createCamera;
      var createPlot = glPlot3d.createScene;
      var getContext = require_webgl_context();
      var passiveSupported = require_has_passive_events();
      var Registry = require_registry();
      var Lib = require_lib();
      var preserveDrawingBuffer = Lib.preserveDrawingBuffer();
      var Axes = require_axes();
      var Fx = require_fx();
      var str2RGBAarray = require_str2rgbarray();
      var showNoWebGlMsg = require_show_no_webgl_msg();
      var project = require_project();
      var createAxesOptions = require_convert3();
      var createSpikeOptions = require_spikes();
      var computeTickMarks = require_tick_marks();
      var applyAutorangeOptions = require_autorange().applyAutorangeOptions;
      var STATIC_CANVAS;
      var STATIC_CONTEXT;
      var tabletmode = false;
      function Scene(options, fullLayout) {
        var sceneContainer = document.createElement("div");
        var plotContainer = options.container;
        this.graphDiv = options.graphDiv;
        var svgContainer = document.createElementNS(
          "http://www.w3.org/2000/svg",
          "svg"
        );
        svgContainer.style.position = "absolute";
        svgContainer.style.top = svgContainer.style.left = "0px";
        svgContainer.style.width = svgContainer.style.height = "100%";
        svgContainer.style["z-index"] = 20;
        svgContainer.style["pointer-events"] = "none";
        sceneContainer.appendChild(svgContainer);
        this.svgContainer = svgContainer;
        sceneContainer.id = options.id;
        sceneContainer.style.position = "absolute";
        sceneContainer.style.top = sceneContainer.style.left = "0px";
        sceneContainer.style.width = sceneContainer.style.height = "100%";
        plotContainer.appendChild(sceneContainer);
        this.fullLayout = fullLayout;
        this.id = options.id || "scene";
        this.fullSceneLayout = fullLayout[this.id];
        this.plotArgs = [[], {}, {}];
        this.axesOptions = createAxesOptions(fullLayout, fullLayout[this.id]);
        this.spikeOptions = createSpikeOptions(fullLayout[this.id]);
        this.container = sceneContainer;
        this.staticMode = !!options.staticPlot;
        this.pixelRatio = this.pixelRatio || options.plotGlPixelRatio || 2;
        this.dataScale = [1, 1, 1];
        this.contourLevels = [[], [], []];
        this.convertAnnotations = Registry.getComponentMethod("annotations3d", "convert");
        this.drawAnnotations = Registry.getComponentMethod("annotations3d", "draw");
        this.initializeGLPlot();
      }
      var proto = Scene.prototype;
      proto.prepareOptions = function() {
        var scene = this;
        var opts = {
          canvas: scene.canvas,
          gl: scene.gl,
          glOptions: {
            preserveDrawingBuffer,
            premultipliedAlpha: true,
            antialias: true
          },
          container: scene.container,
          axes: scene.axesOptions,
          spikes: scene.spikeOptions,
          pickRadius: 10,
          snapToData: true,
          autoScale: true,
          autoBounds: false,
          cameraObject: scene.camera,
          pixelRatio: scene.pixelRatio
        };
        if (scene.staticMode) {
          if (!STATIC_CONTEXT) {
            STATIC_CANVAS = document.createElement("canvas");
            STATIC_CONTEXT = getContext({
              canvas: STATIC_CANVAS,
              preserveDrawingBuffer: true,
              premultipliedAlpha: true,
              antialias: true
            });
            if (!STATIC_CONTEXT) {
              throw new Error("error creating static canvas/context for image server");
            }
          }
          opts.gl = STATIC_CONTEXT;
          opts.canvas = STATIC_CANVAS;
        }
        return opts;
      };
      var firstInit = true;
      proto.tryCreatePlot = function() {
        var scene = this;
        var opts = scene.prepareOptions();
        var success = true;
        try {
          scene.glplot = createPlot(opts);
        } catch (e) {
          if (scene.staticMode || !firstInit || preserveDrawingBuffer) {
            success = false;
          } else {
            Lib.warn([
              "webgl setup failed possibly due to",
              "false preserveDrawingBuffer config.",
              "The mobile/tablet device may not be detected by is-mobile module.",
              "Enabling preserveDrawingBuffer in second attempt to create webgl scene..."
            ].join(" "));
            try {
              preserveDrawingBuffer = opts.glOptions.preserveDrawingBuffer = true;
              scene.glplot = createPlot(opts);
            } catch (e2) {
              preserveDrawingBuffer = opts.glOptions.preserveDrawingBuffer = false;
              success = false;
            }
          }
        }
        firstInit = false;
        return success;
      };
      proto.initializeGLCamera = function() {
        var scene = this;
        var cameraData = scene.fullSceneLayout.camera;
        var isOrtho = cameraData.projection.type === "orthographic";
        scene.camera = createCamera(scene.container, {
          center: [cameraData.center.x, cameraData.center.y, cameraData.center.z],
          eye: [cameraData.eye.x, cameraData.eye.y, cameraData.eye.z],
          up: [cameraData.up.x, cameraData.up.y, cameraData.up.z],
          _ortho: isOrtho,
          zoomMin: 0.01,
          zoomMax: 100,
          mode: "orbit"
        });
      };
      proto.initializeGLPlot = function() {
        var scene = this;
        scene.initializeGLCamera();
        var success = scene.tryCreatePlot();
        if (!success) return showNoWebGlMsg(scene);
        scene.traces = {};
        scene.make4thDimension();
        var gd = scene.graphDiv;
        var layout = gd.layout;
        var makeUpdate = function() {
          var update = {};
          if (scene.isCameraChanged(layout)) {
            update[scene.id + ".camera"] = scene.getCamera();
          }
          if (scene.isAspectChanged(layout)) {
            update[scene.id + ".aspectratio"] = scene.glplot.getAspectratio();
            if (layout[scene.id].aspectmode !== "manual") {
              scene.fullSceneLayout.aspectmode = layout[scene.id].aspectmode = update[scene.id + ".aspectmode"] = "manual";
            }
          }
          return update;
        };
        var relayoutCallback = function(scene2) {
          if (scene2.fullSceneLayout.dragmode === false) return;
          var update = makeUpdate();
          scene2.saveLayout(layout);
          scene2.graphDiv.emit("plotly_relayout", update);
        };
        if (scene.glplot.canvas) {
          scene.glplot.canvas.addEventListener("mouseup", function() {
            relayoutCallback(scene);
          });
          scene.glplot.canvas.addEventListener("touchstart", function() {
            tabletmode = true;
          });
          scene.glplot.canvas.addEventListener("wheel", function(e) {
            if (gd._context._scrollZoom.gl3d) {
              if (scene.camera._ortho) {
                var s = e.deltaX > e.deltaY ? 1.1 : 1 / 1.1;
                var o = scene.glplot.getAspectratio();
                scene.glplot.setAspectratio({
                  x: s * o.x,
                  y: s * o.y,
                  z: s * o.z
                });
              }
              relayoutCallback(scene);
            }
          }, passiveSupported ? { passive: false } : false);
          scene.glplot.canvas.addEventListener("mousemove", function() {
            if (scene.fullSceneLayout.dragmode === false) return;
            if (scene.camera.mouseListener.buttons === 0) return;
            var update = makeUpdate();
            scene.graphDiv.emit("plotly_relayouting", update);
          });
          if (!scene.staticMode) {
            scene.glplot.canvas.addEventListener("webglcontextlost", function(event) {
              if (gd && gd.emit) {
                gd.emit("plotly_webglcontextlost", {
                  event,
                  layer: scene.id
                });
              }
            }, false);
          }
        }
        scene.glplot.oncontextloss = function() {
          scene.recoverContext();
        };
        scene.glplot.onrender = function() {
          scene.render();
        };
        return true;
      };
      proto.render = function() {
        var scene = this;
        var gd = scene.graphDiv;
        var trace;
        var svgContainer = scene.svgContainer;
        var clientRect = scene.container.getBoundingClientRect();
        gd._fullLayout._calcInverseTransform(gd);
        var scaleX = gd._fullLayout._invScaleX;
        var scaleY = gd._fullLayout._invScaleY;
        var width = clientRect.width * scaleX;
        var height = clientRect.height * scaleY;
        svgContainer.setAttributeNS(null, "viewBox", "0 0 " + width + " " + height);
        svgContainer.setAttributeNS(null, "width", width);
        svgContainer.setAttributeNS(null, "height", height);
        computeTickMarks(scene);
        scene.glplot.axes.update(scene.axesOptions);
        var keys = Object.keys(scene.traces);
        var lastPicked = null;
        var selection = scene.glplot.selection;
        for (var i = 0; i < keys.length; ++i) {
          trace = scene.traces[keys[i]];
          if (trace.data.hoverinfo !== "skip" && trace.handlePick(selection)) {
            lastPicked = trace;
          }
          if (trace.setContourLevels) trace.setContourLevels();
        }
        function formatter(axLetter, val, hoverformat) {
          var ax = scene.fullSceneLayout[axLetter + "axis"];
          if (ax.type !== "log") {
            val = ax.d2l(val);
          }
          return Axes.hoverLabelText(ax, val, hoverformat);
        }
        if (lastPicked !== null) {
          var pdata = project(scene.glplot.cameraParams, selection.dataCoordinate);
          trace = lastPicked.data;
          var traceNow = gd._fullData[trace.index];
          var ptNumber = selection.index;
          var labels = {
            xLabel: formatter("x", selection.traceCoordinate[0], trace.xhoverformat),
            yLabel: formatter("y", selection.traceCoordinate[1], trace.yhoverformat),
            zLabel: formatter("z", selection.traceCoordinate[2], trace.zhoverformat)
          };
          var hoverinfo = Fx.castHoverinfo(traceNow, scene.fullLayout, ptNumber);
          var hoverinfoParts = (hoverinfo || "").split("+");
          var isHoverinfoAll = hoverinfo && hoverinfo === "all";
          if (!traceNow.hovertemplate && !isHoverinfoAll) {
            if (hoverinfoParts.indexOf("x") === -1) labels.xLabel = void 0;
            if (hoverinfoParts.indexOf("y") === -1) labels.yLabel = void 0;
            if (hoverinfoParts.indexOf("z") === -1) labels.zLabel = void 0;
            if (hoverinfoParts.indexOf("text") === -1) selection.textLabel = void 0;
            if (hoverinfoParts.indexOf("name") === -1) lastPicked.name = void 0;
          }
          var tx;
          var vectorTx = [];
          if (trace.type === "cone" || trace.type === "streamtube") {
            labels.uLabel = formatter("x", selection.traceCoordinate[3], trace.uhoverformat);
            if (isHoverinfoAll || hoverinfoParts.indexOf("u") !== -1) {
              vectorTx.push("u: " + labels.uLabel);
            }
            labels.vLabel = formatter("y", selection.traceCoordinate[4], trace.vhoverformat);
            if (isHoverinfoAll || hoverinfoParts.indexOf("v") !== -1) {
              vectorTx.push("v: " + labels.vLabel);
            }
            labels.wLabel = formatter("z", selection.traceCoordinate[5], trace.whoverformat);
            if (isHoverinfoAll || hoverinfoParts.indexOf("w") !== -1) {
              vectorTx.push("w: " + labels.wLabel);
            }
            labels.normLabel = selection.traceCoordinate[6].toPrecision(3);
            if (isHoverinfoAll || hoverinfoParts.indexOf("norm") !== -1) {
              vectorTx.push("norm: " + labels.normLabel);
            }
            if (trace.type === "streamtube") {
              labels.divergenceLabel = selection.traceCoordinate[7].toPrecision(3);
              if (isHoverinfoAll || hoverinfoParts.indexOf("divergence") !== -1) {
                vectorTx.push("divergence: " + labels.divergenceLabel);
              }
            }
            if (selection.textLabel) {
              vectorTx.push(selection.textLabel);
            }
            tx = vectorTx.join("<br>");
          } else if (trace.type === "isosurface" || trace.type === "volume") {
            labels.valueLabel = Axes.hoverLabelText(scene._mockAxis, scene._mockAxis.d2l(selection.traceCoordinate[3]), trace.valuehoverformat);
            vectorTx.push("value: " + labels.valueLabel);
            if (selection.textLabel) {
              vectorTx.push(selection.textLabel);
            }
            tx = vectorTx.join("<br>");
          } else {
            tx = selection.textLabel;
          }
          var pointData = {
            x: selection.traceCoordinate[0],
            y: selection.traceCoordinate[1],
            z: selection.traceCoordinate[2],
            data: traceNow._input,
            fullData: traceNow,
            curveNumber: traceNow.index,
            pointNumber: ptNumber
          };
          Fx.appendArrayPointValue(pointData, traceNow, ptNumber);
          if (trace._module.eventData) {
            pointData = traceNow._module.eventData(pointData, selection, traceNow, {}, ptNumber);
          }
          var eventData = { points: [pointData] };
          if (scene.fullSceneLayout.hovermode) {
            var bbox = [];
            Fx.loneHover({
              trace: traceNow,
              x: (0.5 + 0.5 * pdata[0] / pdata[3]) * width,
              y: (0.5 - 0.5 * pdata[1] / pdata[3]) * height,
              xLabel: labels.xLabel,
              yLabel: labels.yLabel,
              zLabel: labels.zLabel,
              text: tx,
              name: lastPicked.name,
              color: Fx.castHoverOption(traceNow, ptNumber, "bgcolor") || lastPicked.color,
              borderColor: Fx.castHoverOption(traceNow, ptNumber, "bordercolor"),
              fontFamily: Fx.castHoverOption(traceNow, ptNumber, "font.family"),
              fontSize: Fx.castHoverOption(traceNow, ptNumber, "font.size"),
              fontColor: Fx.castHoverOption(traceNow, ptNumber, "font.color"),
              nameLength: Fx.castHoverOption(traceNow, ptNumber, "namelength"),
              textAlign: Fx.castHoverOption(traceNow, ptNumber, "align"),
              hovertemplate: Lib.castOption(traceNow, ptNumber, "hovertemplate"),
              hovertemplateLabels: Lib.extendFlat({}, pointData, labels),
              eventData: [pointData]
            }, {
              container: svgContainer,
              gd,
              inOut_bbox: bbox
            });
            pointData.bbox = bbox[0];
          }
          if (selection.distance < 5 && (selection.buttons || tabletmode)) {
            gd.emit("plotly_click", eventData);
          } else {
            gd.emit("plotly_hover", eventData);
          }
          this.oldEventData = eventData;
        } else {
          Fx.loneUnhover(svgContainer);
          if (this.oldEventData) gd.emit("plotly_unhover", this.oldEventData);
          this.oldEventData = void 0;
        }
        scene.drawAnnotations(scene);
      };
      proto.recoverContext = function() {
        var scene = this;
        scene.glplot.dispose();
        var tryRecover = function() {
          if (scene.glplot.gl.isContextLost()) {
            requestAnimationFrame(tryRecover);
            return;
          }
          if (!scene.initializeGLPlot()) {
            Lib.error("Catastrophic and unrecoverable WebGL error. Context lost.");
            return;
          }
          scene.plot.apply(scene, scene.plotArgs);
        };
        requestAnimationFrame(tryRecover);
      };
      var axisProperties = ["xaxis", "yaxis", "zaxis"];
      function computeTraceBounds(scene, trace, bounds) {
        var fullSceneLayout = scene.fullSceneLayout;
        for (var d = 0; d < 3; d++) {
          var axisName = axisProperties[d];
          var axLetter = axisName.charAt(0);
          var ax = fullSceneLayout[axisName];
          var coords = trace[axLetter];
          var calendar = trace[axLetter + "calendar"];
          var len = trace["_" + axLetter + "length"];
          if (!Lib.isArrayOrTypedArray(coords)) {
            bounds[0][d] = Math.min(bounds[0][d], 0);
            bounds[1][d] = Math.max(bounds[1][d], len - 1);
          } else {
            var v;
            for (var i = 0; i < (len || coords.length); i++) {
              if (Lib.isArrayOrTypedArray(coords[i])) {
                for (var j = 0; j < coords[i].length; ++j) {
                  v = ax.d2l(coords[i][j], 0, calendar);
                  if (!isNaN(v) && isFinite(v)) {
                    bounds[0][d] = Math.min(bounds[0][d], v);
                    bounds[1][d] = Math.max(bounds[1][d], v);
                  }
                }
              } else {
                v = ax.d2l(coords[i], 0, calendar);
                if (!isNaN(v) && isFinite(v)) {
                  bounds[0][d] = Math.min(bounds[0][d], v);
                  bounds[1][d] = Math.max(bounds[1][d], v);
                }
              }
            }
          }
        }
      }
      function computeAnnotationBounds(scene, bounds) {
        var fullSceneLayout = scene.fullSceneLayout;
        var annotations = fullSceneLayout.annotations || [];
        for (var d = 0; d < 3; d++) {
          var axisName = axisProperties[d];
          var axLetter = axisName.charAt(0);
          var ax = fullSceneLayout[axisName];
          for (var j = 0; j < annotations.length; j++) {
            var ann = annotations[j];
            if (ann.visible) {
              var pos = ax.r2l(ann[axLetter]);
              if (!isNaN(pos) && isFinite(pos)) {
                bounds[0][d] = Math.min(bounds[0][d], pos);
                bounds[1][d] = Math.max(bounds[1][d], pos);
              }
            }
          }
        }
      }
      proto.plot = function(sceneData, fullLayout, layout) {
        var scene = this;
        scene.plotArgs = [sceneData, fullLayout, layout];
        if (scene.glplot.contextLost) return;
        var data, trace;
        var i, j, axis, axisType;
        var fullSceneLayout = fullLayout[scene.id];
        var sceneLayout = layout[scene.id];
        scene.fullLayout = fullLayout;
        scene.fullSceneLayout = fullSceneLayout;
        scene.axesOptions.merge(fullLayout, fullSceneLayout);
        scene.spikeOptions.merge(fullSceneLayout);
        scene.setViewport(fullSceneLayout);
        scene.updateFx(fullSceneLayout.dragmode, fullSceneLayout.hovermode);
        scene.camera.enableWheel = scene.graphDiv._context._scrollZoom.gl3d;
        scene.glplot.setClearColor(str2RGBAarray(fullSceneLayout.bgcolor));
        scene.setConvert(axis);
        if (!sceneData) sceneData = [];
        else if (!Array.isArray(sceneData)) sceneData = [sceneData];
        var dataBounds = [
          [Infinity, Infinity, Infinity],
          [-Infinity, -Infinity, -Infinity]
        ];
        for (i = 0; i < sceneData.length; ++i) {
          data = sceneData[i];
          if (data.visible !== true || data._length === 0) continue;
          computeTraceBounds(this, data, dataBounds);
        }
        computeAnnotationBounds(this, dataBounds);
        var dataScale = [1, 1, 1];
        for (j = 0; j < 3; ++j) {
          if (dataBounds[1][j] === dataBounds[0][j]) {
            dataScale[j] = 1;
          } else {
            dataScale[j] = 1 / (dataBounds[1][j] - dataBounds[0][j]);
          }
        }
        scene.dataScale = dataScale;
        scene.convertAnnotations(this);
        for (i = 0; i < sceneData.length; ++i) {
          data = sceneData[i];
          if (data.visible !== true || data._length === 0) {
            continue;
          }
          trace = scene.traces[data.uid];
          if (trace) {
            if (trace.data.type === data.type) {
              trace.update(data);
            } else {
              trace.dispose();
              trace = data._module.plot(this, data);
              scene.traces[data.uid] = trace;
            }
          } else {
            trace = data._module.plot(this, data);
            scene.traces[data.uid] = trace;
          }
          trace.name = data.name;
        }
        var traceIds = Object.keys(scene.traces);
        traceIdLoop:
          for (i = 0; i < traceIds.length; ++i) {
            for (j = 0; j < sceneData.length; ++j) {
              if (sceneData[j].uid === traceIds[i] && (sceneData[j].visible === true && sceneData[j]._length !== 0)) {
                continue traceIdLoop;
              }
            }
            trace = scene.traces[traceIds[i]];
            trace.dispose();
            delete scene.traces[traceIds[i]];
          }
        scene.glplot.objects.sort(function(a, b) {
          return a._trace.data.index - b._trace.data.index;
        });
        var sceneBounds = [[0, 0, 0], [0, 0, 0]];
        var axisDataRange = [];
        var axisTypeRatios = {};
        for (i = 0; i < 3; ++i) {
          axis = fullSceneLayout[axisProperties[i]];
          axisType = axis.type;
          if (axisType in axisTypeRatios) {
            axisTypeRatios[axisType].acc *= dataScale[i];
            axisTypeRatios[axisType].count += 1;
          } else {
            axisTypeRatios[axisType] = {
              acc: dataScale[i],
              count: 1
            };
          }
          var range;
          if (axis.autorange) {
            sceneBounds[0][i] = Infinity;
            sceneBounds[1][i] = -Infinity;
            var objects = scene.glplot.objects;
            var annotations = scene.fullSceneLayout.annotations || [];
            var axLetter = axis._name.charAt(0);
            for (j = 0; j < objects.length; j++) {
              var obj = objects[j];
              var objBounds = obj.bounds;
              var pad = obj._trace.data._pad || 0;
              if (obj.constructor.name === "ErrorBars" && axis._lowerLogErrorBound) {
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], axis._lowerLogErrorBound);
              } else {
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], objBounds[0][i] / dataScale[i] - pad);
              }
              sceneBounds[1][i] = Math.max(sceneBounds[1][i], objBounds[1][i] / dataScale[i] + pad);
            }
            for (j = 0; j < annotations.length; j++) {
              var ann = annotations[j];
              if (ann.visible) {
                var pos = axis.r2l(ann[axLetter]);
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], pos);
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], pos);
              }
            }
            if ("rangemode" in axis && axis.rangemode === "tozero") {
              sceneBounds[0][i] = Math.min(sceneBounds[0][i], 0);
              sceneBounds[1][i] = Math.max(sceneBounds[1][i], 0);
            }
            if (sceneBounds[0][i] > sceneBounds[1][i]) {
              sceneBounds[0][i] = -1;
              sceneBounds[1][i] = 1;
            } else {
              var d = sceneBounds[1][i] - sceneBounds[0][i];
              sceneBounds[0][i] -= d / 32;
              sceneBounds[1][i] += d / 32;
            }
            range = [
              sceneBounds[0][i],
              sceneBounds[1][i]
            ];
            range = applyAutorangeOptions(range, axis);
            sceneBounds[0][i] = range[0];
            sceneBounds[1][i] = range[1];
            if (axis.isReversed()) {
              var tmp = sceneBounds[0][i];
              sceneBounds[0][i] = sceneBounds[1][i];
              sceneBounds[1][i] = tmp;
            }
          } else {
            range = axis.range;
            sceneBounds[0][i] = axis.r2l(range[0]);
            sceneBounds[1][i] = axis.r2l(range[1]);
          }
          if (sceneBounds[0][i] === sceneBounds[1][i]) {
            sceneBounds[0][i] -= 1;
            sceneBounds[1][i] += 1;
          }
          axisDataRange[i] = sceneBounds[1][i] - sceneBounds[0][i];
          axis.range = [
            sceneBounds[0][i],
            sceneBounds[1][i]
          ];
          axis.limitRange();
          scene.glplot.setBounds(i, {
            min: axis.range[0] * dataScale[i],
            max: axis.range[1] * dataScale[i]
          });
        }
        var aspectRatio;
        var aspectmode = fullSceneLayout.aspectmode;
        if (aspectmode === "cube") {
          aspectRatio = [1, 1, 1];
        } else if (aspectmode === "manual") {
          var userRatio = fullSceneLayout.aspectratio;
          aspectRatio = [userRatio.x, userRatio.y, userRatio.z];
        } else if (aspectmode === "auto" || aspectmode === "data") {
          var axesScaleRatio = [1, 1, 1];
          for (i = 0; i < 3; ++i) {
            axis = fullSceneLayout[axisProperties[i]];
            axisType = axis.type;
            var axisRatio = axisTypeRatios[axisType];
            axesScaleRatio[i] = Math.pow(axisRatio.acc, 1 / axisRatio.count) / dataScale[i];
          }
          if (aspectmode === "data") {
            aspectRatio = axesScaleRatio;
          } else {
            if (Math.max.apply(null, axesScaleRatio) / Math.min.apply(null, axesScaleRatio) <= 4) {
              aspectRatio = axesScaleRatio;
            } else {
              aspectRatio = [1, 1, 1];
            }
          }
        } else {
          throw new Error("scene.js aspectRatio was not one of the enumerated types");
        }
        fullSceneLayout.aspectratio.x = sceneLayout.aspectratio.x = aspectRatio[0];
        fullSceneLayout.aspectratio.y = sceneLayout.aspectratio.y = aspectRatio[1];
        fullSceneLayout.aspectratio.z = sceneLayout.aspectratio.z = aspectRatio[2];
        scene.glplot.setAspectratio(fullSceneLayout.aspectratio);
        if (!scene.viewInitial.aspectratio) {
          scene.viewInitial.aspectratio = {
            x: fullSceneLayout.aspectratio.x,
            y: fullSceneLayout.aspectratio.y,
            z: fullSceneLayout.aspectratio.z
          };
        }
        if (!scene.viewInitial.aspectmode) {
          scene.viewInitial.aspectmode = fullSceneLayout.aspectmode;
        }
        var domain = fullSceneLayout.domain || null;
        var size = fullLayout._size || null;
        if (domain && size) {
          var containerStyle = scene.container.style;
          containerStyle.position = "absolute";
          containerStyle.left = size.l + domain.x[0] * size.w + "px";
          containerStyle.top = size.t + (1 - domain.y[1]) * size.h + "px";
          containerStyle.width = size.w * (domain.x[1] - domain.x[0]) + "px";
          containerStyle.height = size.h * (domain.y[1] - domain.y[0]) + "px";
        }
        scene.glplot.redraw();
      };
      proto.destroy = function() {
        var scene = this;
        if (!scene.glplot) return;
        scene.camera.mouseListener.enabled = false;
        scene.container.removeEventListener("wheel", scene.camera.wheelListener);
        scene.camera = null;
        scene.glplot.dispose();
        scene.container.parentNode.removeChild(scene.container);
        scene.glplot = null;
      };
      function getCameraArrays(camera) {
        return [
          [camera.eye.x, camera.eye.y, camera.eye.z],
          [camera.center.x, camera.center.y, camera.center.z],
          [camera.up.x, camera.up.y, camera.up.z]
        ];
      }
      function getLayoutCamera(camera) {
        return {
          up: { x: camera.up[0], y: camera.up[1], z: camera.up[2] },
          center: { x: camera.center[0], y: camera.center[1], z: camera.center[2] },
          eye: { x: camera.eye[0], y: camera.eye[1], z: camera.eye[2] },
          projection: { type: camera._ortho === true ? "orthographic" : "perspective" }
        };
      }
      proto.getCamera = function() {
        var scene = this;
        scene.camera.view.recalcMatrix(scene.camera.view.lastT());
        return getLayoutCamera(scene.camera);
      };
      proto.setViewport = function(sceneLayout) {
        var scene = this;
        var cameraData = sceneLayout.camera;
        scene.camera.lookAt.apply(this, getCameraArrays(cameraData));
        scene.glplot.setAspectratio(sceneLayout.aspectratio);
        var newOrtho = cameraData.projection.type === "orthographic";
        var oldOrtho = scene.camera._ortho;
        if (newOrtho !== oldOrtho) {
          scene.glplot.redraw();
          scene.glplot.clearRGBA();
          scene.glplot.dispose();
          scene.initializeGLPlot();
        }
      };
      proto.isCameraChanged = function(layout) {
        var scene = this;
        var cameraData = scene.getCamera();
        var cameraNestedProp = Lib.nestedProperty(layout, scene.id + ".camera");
        var cameraDataLastSave = cameraNestedProp.get();
        function same(x, y, i2, j2) {
          var vectors = ["up", "center", "eye"];
          var components = ["x", "y", "z"];
          return y[vectors[i2]] && x[vectors[i2]][components[j2]] === y[vectors[i2]][components[j2]];
        }
        var changed = false;
        if (cameraDataLastSave === void 0) {
          changed = true;
        } else {
          for (var i = 0; i < 3; i++) {
            for (var j = 0; j < 3; j++) {
              if (!same(cameraData, cameraDataLastSave, i, j)) {
                changed = true;
                break;
              }
            }
          }
          if (!cameraDataLastSave.projection || cameraData.projection && cameraData.projection.type !== cameraDataLastSave.projection.type) {
            changed = true;
          }
        }
        return changed;
      };
      proto.isAspectChanged = function(layout) {
        var scene = this;
        var aspectData = scene.glplot.getAspectratio();
        var aspectNestedProp = Lib.nestedProperty(layout, scene.id + ".aspectratio");
        var aspectDataLastSave = aspectNestedProp.get();
        return aspectDataLastSave === void 0 || (aspectDataLastSave.x !== aspectData.x || aspectDataLastSave.y !== aspectData.y || aspectDataLastSave.z !== aspectData.z);
      };
      proto.saveLayout = function(layout) {
        var scene = this;
        var fullLayout = scene.fullLayout;
        var cameraData;
        var cameraNestedProp;
        var cameraDataLastSave;
        var aspectData;
        var aspectNestedProp;
        var aspectDataLastSave;
        var cameraChanged = scene.isCameraChanged(layout);
        var aspectChanged = scene.isAspectChanged(layout);
        var hasChanged = cameraChanged || aspectChanged;
        if (hasChanged) {
          var preGUI = {};
          if (cameraChanged) {
            cameraData = scene.getCamera();
            cameraNestedProp = Lib.nestedProperty(layout, scene.id + ".camera");
            cameraDataLastSave = cameraNestedProp.get();
            preGUI[scene.id + ".camera"] = cameraDataLastSave;
          }
          if (aspectChanged) {
            aspectData = scene.glplot.getAspectratio();
            aspectNestedProp = Lib.nestedProperty(layout, scene.id + ".aspectratio");
            aspectDataLastSave = aspectNestedProp.get();
            preGUI[scene.id + ".aspectratio"] = aspectDataLastSave;
          }
          Registry.call("_storeDirectGUIEdit", layout, fullLayout._preGUI, preGUI);
          if (cameraChanged) {
            cameraNestedProp.set(cameraData);
            var cameraFullNP = Lib.nestedProperty(fullLayout, scene.id + ".camera");
            cameraFullNP.set(cameraData);
          }
          if (aspectChanged) {
            aspectNestedProp.set(aspectData);
            var aspectFullNP = Lib.nestedProperty(fullLayout, scene.id + ".aspectratio");
            aspectFullNP.set(aspectData);
            scene.glplot.redraw();
          }
        }
        return hasChanged;
      };
      proto.updateFx = function(dragmode, hovermode) {
        var scene = this;
        var camera = scene.camera;
        if (camera) {
          if (dragmode === "orbit") {
            camera.mode = "orbit";
            camera.keyBindingMode = "rotate";
          } else if (dragmode === "turntable") {
            camera.up = [0, 0, 1];
            camera.mode = "turntable";
            camera.keyBindingMode = "rotate";
            var gd = scene.graphDiv;
            var fullLayout = gd._fullLayout;
            var fullCamera = scene.fullSceneLayout.camera;
            var x = fullCamera.up.x;
            var y = fullCamera.up.y;
            var z = fullCamera.up.z;
            if (z / Math.sqrt(x * x + y * y + z * z) < 0.999) {
              var attr = scene.id + ".camera.up";
              var zUp = { x: 0, y: 0, z: 1 };
              var edits = {};
              edits[attr] = zUp;
              var layout = gd.layout;
              Registry.call("_storeDirectGUIEdit", layout, fullLayout._preGUI, edits);
              fullCamera.up = zUp;
              Lib.nestedProperty(layout, attr).set(zUp);
            }
          } else {
            camera.keyBindingMode = dragmode;
          }
        }
        scene.fullSceneLayout.hovermode = hovermode;
      };
      function flipPixels(pixels, w, h) {
        for (var i = 0, q = h - 1; i < q; ++i, --q) {
          for (var j = 0; j < w; ++j) {
            for (var k = 0; k < 4; ++k) {
              var a = 4 * (w * i + j) + k;
              var b = 4 * (w * q + j) + k;
              var tmp = pixels[a];
              pixels[a] = pixels[b];
              pixels[b] = tmp;
            }
          }
        }
      }
      function correctRGB(pixels, w, h) {
        for (var i = 0; i < h; ++i) {
          for (var j = 0; j < w; ++j) {
            var k = 4 * (w * i + j);
            var a = pixels[k + 3];
            if (a > 0) {
              var q = 255 / a;
              for (var l = 0; l < 3; ++l) {
                pixels[k + l] = Math.min(q * pixels[k + l], 255);
              }
            }
          }
        }
      }
      proto.toImage = function(format) {
        var scene = this;
        if (!format) format = "png";
        if (scene.staticMode) scene.container.appendChild(STATIC_CANVAS);
        scene.glplot.redraw();
        var gl2 = scene.glplot.gl;
        var w = gl2.drawingBufferWidth;
        var h = gl2.drawingBufferHeight;
        gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
        var pixels = new Uint8Array(w * h * 4);
        gl2.readPixels(0, 0, w, h, gl2.RGBA, gl2.UNSIGNED_BYTE, pixels);
        flipPixels(pixels, w, h);
        correctRGB(pixels, w, h);
        var canvas = document.createElement("canvas");
        canvas.width = w;
        canvas.height = h;
        var context = canvas.getContext("2d", { willReadFrequently: true });
        var imageData = context.createImageData(w, h);
        imageData.data.set(pixels);
        context.putImageData(imageData, 0, 0);
        var dataURL;
        switch (format) {
          case "jpeg":
            dataURL = canvas.toDataURL("image/jpeg");
            break;
          case "webp":
            dataURL = canvas.toDataURL("image/webp");
            break;
          default:
            dataURL = canvas.toDataURL("image/png");
        }
        if (scene.staticMode) scene.container.removeChild(STATIC_CANVAS);
        return dataURL;
      };
      proto.setConvert = function() {
        var scene = this;
        for (var i = 0; i < 3; i++) {
          var ax = scene.fullSceneLayout[axisProperties[i]];
          Axes.setConvert(ax, scene.fullLayout);
          ax.setScale = Lib.noop;
        }
      };
      proto.make4thDimension = function() {
        var scene = this;
        var gd = scene.graphDiv;
        var fullLayout = gd._fullLayout;
        scene._mockAxis = {
          type: "linear",
          showexponent: "all",
          exponentformat: "B"
        };
        Axes.setConvert(scene._mockAxis, fullLayout);
      };
      module.exports = Scene;
    }
  });

  // src/plots/gl3d/layout/attributes.js
  var require_attributes41 = __commonJS({
    "src/plots/gl3d/layout/attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        scene: {
          valType: "subplotid",
          dflt: "scene",
          editType: "calc+clearAxisTypes"
        }
      };
    }
  });

  // src/plots/gl3d/layout/axis_attributes.js
  var require_axis_attributes = __commonJS({
    "src/plots/gl3d/layout/axis_attributes.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var axesAttrs = require_layout_attributes4();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      module.exports = overrideAll({
        visible: axesAttrs.visible,
        showspikes: {
          valType: "boolean",
          dflt: true
        },
        spikesides: {
          valType: "boolean",
          dflt: true
        },
        spikethickness: {
          valType: "number",
          min: 0,
          dflt: 2
        },
        spikecolor: {
          valType: "color",
          dflt: Color2.defaultLine
        },
        showbackground: {
          valType: "boolean",
          dflt: false
        },
        backgroundcolor: {
          valType: "color",
          dflt: "rgba(204, 204, 204, 0.5)"
        },
        showaxeslabels: {
          valType: "boolean",
          dflt: true
        },
        color: axesAttrs.color,
        categoryorder: axesAttrs.categoryorder,
        categoryarray: axesAttrs.categoryarray,
        title: {
          text: axesAttrs.title.text,
          font: axesAttrs.title.font
        },
        type: extendFlat({}, axesAttrs.type, {
          values: ["-", "linear", "log", "date", "category"]
        }),
        autotypenumbers: axesAttrs.autotypenumbers,
        autorange: axesAttrs.autorange,
        autorangeoptions: {
          minallowed: axesAttrs.autorangeoptions.minallowed,
          maxallowed: axesAttrs.autorangeoptions.maxallowed,
          clipmin: axesAttrs.autorangeoptions.clipmin,
          clipmax: axesAttrs.autorangeoptions.clipmax,
          include: axesAttrs.autorangeoptions.include,
          editType: "plot"
        },
        rangemode: axesAttrs.rangemode,
        minallowed: axesAttrs.minallowed,
        maxallowed: axesAttrs.maxallowed,
        range: extendFlat({}, axesAttrs.range, {
          items: [
            { valType: "any", editType: "plot", impliedEdits: { "^autorange": false } },
            { valType: "any", editType: "plot", impliedEdits: { "^autorange": false } }
          ],
          anim: false
        }),
        // ticks
        tickmode: axesAttrs.minor.tickmode,
        nticks: axesAttrs.nticks,
        tick0: axesAttrs.tick0,
        dtick: axesAttrs.dtick,
        tickvals: axesAttrs.tickvals,
        ticktext: axesAttrs.ticktext,
        ticks: axesAttrs.ticks,
        mirror: axesAttrs.mirror,
        ticklen: axesAttrs.ticklen,
        tickwidth: axesAttrs.tickwidth,
        tickcolor: axesAttrs.tickcolor,
        showticklabels: axesAttrs.showticklabels,
        labelalias: axesAttrs.labelalias,
        tickfont: axesAttrs.tickfont,
        tickangle: axesAttrs.tickangle,
        tickprefix: axesAttrs.tickprefix,
        showtickprefix: axesAttrs.showtickprefix,
        ticksuffix: axesAttrs.ticksuffix,
        showticksuffix: axesAttrs.showticksuffix,
        showexponent: axesAttrs.showexponent,
        exponentformat: axesAttrs.exponentformat,
        minexponent: axesAttrs.minexponent,
        separatethousands: axesAttrs.separatethousands,
        tickformat: axesAttrs.tickformat,
        tickformatstops: axesAttrs.tickformatstops,
        hoverformat: axesAttrs.hoverformat,
        // lines and grids
        showline: axesAttrs.showline,
        linecolor: axesAttrs.linecolor,
        linewidth: axesAttrs.linewidth,
        showgrid: axesAttrs.showgrid,
        gridcolor: extendFlat(
          {},
          axesAttrs.gridcolor,
          // shouldn't this be on-par with 2D?
          { dflt: "rgb(204, 204, 204)" }
        ),
        gridwidth: axesAttrs.gridwidth,
        zeroline: axesAttrs.zeroline,
        zerolinecolor: axesAttrs.zerolinecolor,
        zerolinewidth: axesAttrs.zerolinewidth
      }, "plot", "from-root");
    }
  });

  // src/plots/gl3d/layout/layout_attributes.js
  var require_layout_attributes17 = __commonJS({
    "src/plots/gl3d/layout/layout_attributes.js"(exports, module) {
      "use strict";
      var gl3dAxisAttrs = require_axis_attributes();
      var domainAttrs = require_domain().attributes;
      var extendFlat = require_extend().extendFlat;
      var counterRegex = require_lib().counterRegex;
      function makeCameraVector(x, y, z) {
        return {
          x: {
            valType: "number",
            dflt: x,
            editType: "camera"
          },
          y: {
            valType: "number",
            dflt: y,
            editType: "camera"
          },
          z: {
            valType: "number",
            dflt: z,
            editType: "camera"
          },
          editType: "camera"
        };
      }
      module.exports = {
        _arrayAttrRegexps: [counterRegex("scene", ".annotations", true)],
        bgcolor: {
          valType: "color",
          dflt: "rgba(0,0,0,0)",
          editType: "plot"
        },
        camera: {
          up: extendFlat(makeCameraVector(0, 0, 1), {}),
          center: extendFlat(makeCameraVector(0, 0, 0), {}),
          eye: extendFlat(makeCameraVector(1.25, 1.25, 1.25), {}),
          projection: {
            type: {
              valType: "enumerated",
              values: ["perspective", "orthographic"],
              dflt: "perspective",
              editType: "calc"
            },
            editType: "calc"
          },
          editType: "camera"
        },
        domain: domainAttrs({ name: "scene", editType: "plot" }),
        aspectmode: {
          valType: "enumerated",
          values: ["auto", "cube", "data", "manual"],
          dflt: "auto",
          editType: "plot",
          impliedEdits: {
            "aspectratio.x": void 0,
            "aspectratio.y": void 0,
            "aspectratio.z": void 0
          }
        },
        aspectratio: {
          // must be positive (0's are coerced to 1)
          x: {
            valType: "number",
            min: 0,
            editType: "plot",
            impliedEdits: { "^aspectmode": "manual" }
          },
          y: {
            valType: "number",
            min: 0,
            editType: "plot",
            impliedEdits: { "^aspectmode": "manual" }
          },
          z: {
            valType: "number",
            min: 0,
            editType: "plot",
            impliedEdits: { "^aspectmode": "manual" }
          },
          editType: "plot",
          impliedEdits: { aspectmode: "manual" }
        },
        xaxis: gl3dAxisAttrs,
        yaxis: gl3dAxisAttrs,
        zaxis: gl3dAxisAttrs,
        dragmode: {
          valType: "enumerated",
          values: ["orbit", "turntable", "zoom", "pan", false],
          editType: "plot"
        },
        hovermode: {
          valType: "enumerated",
          values: ["closest", false],
          dflt: "closest",
          editType: "modebar"
        },
        uirevision: {
          valType: "any",
          editType: "none"
        },
        editType: "plot"
      };
    }
  });

  // src/plots/gl3d/layout/axis_defaults.js
  var require_axis_defaults2 = __commonJS({
    "src/plots/gl3d/layout/axis_defaults.js"(exports, module) {
      "use strict";
      var colorMix = require_tinycolor().mix;
      var Lib = require_lib();
      var Template = require_plot_template();
      var layoutAttributes = require_axis_attributes();
      var handleTypeDefaults = require_type_defaults();
      var handleAxisDefaults = require_axis_defaults();
      var axesNames = ["xaxis", "yaxis", "zaxis"];
      var gridLightness = 100 * (204 - 68) / (255 - 68);
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) {
        var containerIn, containerOut;
        function coerce(attr, dflt) {
          return Lib.coerce(containerIn, containerOut, layoutAttributes, attr, dflt);
        }
        for (var j = 0; j < axesNames.length; j++) {
          var axName = axesNames[j];
          containerIn = layoutIn[axName] || {};
          containerOut = Template.newContainer(layoutOut, axName);
          containerOut._id = axName[0] + options.scene;
          containerOut._name = axName;
          handleTypeDefaults(containerIn, containerOut, coerce, options);
          handleAxisDefaults(
            containerIn,
            containerOut,
            coerce,
            {
              font: options.font,
              letter: axName[0],
              data: options.data,
              showGrid: true,
              noAutotickangles: true,
              noMinorloglabels: true,
              noTicklabelindex: true,
              noTickson: true,
              noTicklabelmode: true,
              noTicklabelshift: true,
              noTicklabelstandoff: true,
              noTicklabelstep: true,
              noTicklabelposition: true,
              noTicklabeloverflow: true,
              noInsiderange: true,
              noUnifiedhovertitle: true,
              bgColor: options.bgColor,
              calendar: options.calendar
            },
            options.fullLayout
          );
          coerce("gridcolor", colorMix(containerOut.color, options.bgColor, gridLightness).toRgbString());
          coerce("title.text", axName[0]);
          containerOut.setScale = Lib.noop;
          if (coerce("showspikes")) {
            coerce("spikesides");
            coerce("spikethickness");
            coerce("spikecolor", containerOut.color);
          }
          coerce("showaxeslabels");
          if (coerce("showbackground")) coerce("backgroundcolor");
        }
      };
    }
  });

  // src/plots/gl3d/layout/defaults.js
  var require_defaults37 = __commonJS({
    "src/plots/gl3d/layout/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var Registry = require_registry();
      var handleSubplotDefaults = require_subplot_defaults();
      var supplyGl3dAxisLayoutDefaults = require_axis_defaults2();
      var layoutAttributes = require_layout_attributes17();
      var getSubplotData = require_get_data().getSubplotData;
      var GL3D = "gl3d";
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        var hasNon3D = layoutOut._basePlotModules.length > 1;
        function getDfltFromLayout(attr) {
          if (hasNon3D) return;
          var isValid = Lib.validate(layoutIn[attr], layoutAttributes[attr]);
          if (isValid) return layoutIn[attr];
        }
        handleSubplotDefaults(layoutIn, layoutOut, fullData, {
          type: GL3D,
          attributes: layoutAttributes,
          handleDefaults: handleGl3dDefaults,
          fullLayout: layoutOut,
          font: layoutOut.font,
          fullData,
          getDfltFromLayout,
          autotypenumbersDflt: layoutOut.autotypenumbers,
          paper_bgcolor: layoutOut.paper_bgcolor,
          calendar: layoutOut.calendar
        });
      };
      function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) {
        var bgcolor = coerce("bgcolor");
        var bgColorCombined = Color2.combine(bgcolor, opts.paper_bgcolor);
        var cameraKeys = ["up", "center", "eye"];
        for (var j = 0; j < cameraKeys.length; j++) {
          coerce("camera." + cameraKeys[j] + ".x");
          coerce("camera." + cameraKeys[j] + ".y");
          coerce("camera." + cameraKeys[j] + ".z");
        }
        coerce("camera.projection.type");
        var hasAspect = !!coerce("aspectratio.x") && !!coerce("aspectratio.y") && !!coerce("aspectratio.z");
        var defaultAspectMode = hasAspect ? "manual" : "auto";
        var aspectMode = coerce("aspectmode", defaultAspectMode);
        if (!hasAspect) {
          sceneLayoutIn.aspectratio = sceneLayoutOut.aspectratio = { x: 1, y: 1, z: 1 };
          if (aspectMode === "manual") sceneLayoutOut.aspectmode = "auto";
          sceneLayoutIn.aspectmode = sceneLayoutOut.aspectmode;
        }
        var fullGl3dData = getSubplotData(opts.fullData, GL3D, opts.id);
        supplyGl3dAxisLayoutDefaults(sceneLayoutIn, sceneLayoutOut, {
          font: opts.font,
          scene: opts.id,
          data: fullGl3dData,
          bgColor: bgColorCombined,
          calendar: opts.calendar,
          autotypenumbersDflt: opts.autotypenumbersDflt,
          fullLayout: opts.fullLayout
        });
        Registry.getComponentMethod("annotations3d", "handleDefaults")(
          sceneLayoutIn,
          sceneLayoutOut,
          opts
        );
        var dragmode = opts.getDfltFromLayout("dragmode");
        if (dragmode !== false) {
          if (!dragmode) {
            dragmode = "orbit";
            if (sceneLayoutIn.camera && sceneLayoutIn.camera.up) {
              var x = sceneLayoutIn.camera.up.x;
              var y = sceneLayoutIn.camera.up.y;
              var z = sceneLayoutIn.camera.up.z;
              if (z !== 0) {
                if (!x || !y || !z) {
                  dragmode = "turntable";
                } else if (z / Math.sqrt(x * x + y * y + z * z) > 0.999) {
                  dragmode = "turntable";
                }
              }
            } else {
              dragmode = "turntable";
            }
          }
        }
        coerce("dragmode", dragmode);
        coerce("hovermode", opts.getDfltFromLayout("hovermode"));
      }
    }
  });

  // src/plots/gl3d/index.js
  var require_gl3d = __commonJS({
    "src/plots/gl3d/index.js"(exports) {
      "use strict";
      var overrideAll = require_edit_types().overrideAll;
      var fxAttrs = require_layout_attributes();
      var Scene = require_scene();
      var getSubplotData = require_get_data().getSubplotData;
      var Lib = require_lib();
      var xmlnsNamespaces = require_xmlns_namespaces();
      var GL3D = "gl3d";
      var SCENE = "scene";
      exports.name = GL3D;
      exports.attr = SCENE;
      exports.idRoot = SCENE;
      exports.idRegex = exports.attrRegex = Lib.counterRegex("scene");
      exports.attributes = require_attributes41();
      exports.layoutAttributes = require_layout_attributes17();
      exports.baseLayoutAttrOverrides = overrideAll({
        hoverlabel: fxAttrs.hoverlabel
      }, "plot", "nested");
      exports.supplyLayoutDefaults = require_defaults37();
      exports.plot = function plot(gd) {
        var fullLayout = gd._fullLayout;
        var fullData = gd._fullData;
        var sceneIds = fullLayout._subplots[GL3D];
        for (var i = 0; i < sceneIds.length; i++) {
          var sceneId = sceneIds[i];
          var fullSceneData = getSubplotData(fullData, GL3D, sceneId);
          var sceneLayout = fullLayout[sceneId];
          var camera = sceneLayout.camera;
          var scene = sceneLayout._scene;
          if (!scene) {
            scene = new Scene(
              {
                id: sceneId,
                graphDiv: gd,
                container: gd.querySelector(".gl-container"),
                staticPlot: gd._context.staticPlot,
                plotGlPixelRatio: gd._context.plotGlPixelRatio,
                camera
              },
              fullLayout
            );
            sceneLayout._scene = scene;
          }
          if (!scene.viewInitial) {
            scene.viewInitial = {
              up: {
                x: camera.up.x,
                y: camera.up.y,
                z: camera.up.z
              },
              eye: {
                x: camera.eye.x,
                y: camera.eye.y,
                z: camera.eye.z
              },
              center: {
                x: camera.center.x,
                y: camera.center.y,
                z: camera.center.z
              }
            };
          }
          scene.plot(fullSceneData, fullLayout, gd.layout);
        }
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldSceneKeys = oldFullLayout._subplots[GL3D] || [];
        for (var i = 0; i < oldSceneKeys.length; i++) {
          var oldSceneKey = oldSceneKeys[i];
          if (!newFullLayout[oldSceneKey] && !!oldFullLayout[oldSceneKey]._scene) {
            oldFullLayout[oldSceneKey]._scene.destroy();
            if (oldFullLayout._infolayer) {
              oldFullLayout._infolayer.selectAll(".annotation-" + oldSceneKey).remove();
            }
          }
        }
      };
      exports.toSVG = function(gd) {
        var fullLayout = gd._fullLayout;
        var sceneIds = fullLayout._subplots[GL3D];
        var size = fullLayout._size;
        for (var i = 0; i < sceneIds.length; i++) {
          var sceneLayout = fullLayout[sceneIds[i]];
          var domain = sceneLayout.domain;
          var scene = sceneLayout._scene;
          var imageData = scene.toImage("png");
          var image = fullLayout._glimages.append("svg:image");
          image.attr({
            xmlns: xmlnsNamespaces.svg,
            "xlink:href": imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: "none"
          });
          scene.destroy();
        }
      };
      exports.cleanId = function cleanId(id) {
        if (!id.match(/^scene[0-9]*$/)) return;
        var sceneNum = id.slice(5);
        if (sceneNum === "1") sceneNum = "";
        return SCENE + sceneNum;
      };
      exports.updateFx = function(gd) {
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[GL3D];
        for (var i = 0; i < subplotIds.length; i++) {
          var subplotObj = fullLayout[subplotIds[i]]._scene;
          subplotObj.updateFx(fullLayout.dragmode, fullLayout.hovermode);
        }
      };
    }
  });

  // src/traces/scatter3d/index.js
  var require_scatter3d = __commonJS({
    "src/traces/scatter3d/index.js"(exports, module) {
      "use strict";
      module.exports = {
        plot: require_convert2(),
        attributes: require_attributes40(),
        markerSymbols: require_gl3d_markers(),
        supplyDefaults: require_defaults36(),
        colorbar: [
          {
            container: "marker",
            min: "cmin",
            max: "cmax"
          },
          {
            container: "line",
            min: "cmin",
            max: "cmax"
          }
        ],
        calc: require_calc21(),
        moduleType: "trace",
        name: "scatter3d",
        basePlotModule: require_gl3d(),
        categories: ["gl3d", "symbols", "showLegend", "scatter-like"],
        meta: {}
      };
    }
  });

  // lib/scatter3d.js
  var require_scatter3d2 = __commonJS({
    "lib/scatter3d.js"(exports, module) {
      "use strict";
      module.exports = require_scatter3d();
    }
  });

  // src/traces/surface/attributes.js
  var require_attributes42 = __commonJS({
    "src/traces/surface/attributes.js"(exports, module) {
      "use strict";
      var Color2 = require_color();
      var colorScaleAttrs = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      function makeContourProjAttr(axLetter) {
        return {
          valType: "boolean",
          dflt: false
        };
      }
      function makeContourAttr(axLetter) {
        return {
          show: {
            valType: "boolean",
            dflt: false
          },
          start: {
            valType: "number",
            dflt: null,
            editType: "plot"
            // impliedEdits: {'^autocontour': false},
          },
          end: {
            valType: "number",
            dflt: null,
            editType: "plot"
            // impliedEdits: {'^autocontour': false},
          },
          size: {
            valType: "number",
            dflt: null,
            min: 0,
            editType: "plot"
            // impliedEdits: {'^autocontour': false},
          },
          project: {
            x: makeContourProjAttr("x"),
            y: makeContourProjAttr("y"),
            z: makeContourProjAttr("z")
          },
          color: {
            valType: "color",
            dflt: Color2.defaultLine
          },
          usecolormap: {
            valType: "boolean",
            dflt: false
          },
          width: {
            valType: "number",
            min: 1,
            max: 16,
            dflt: 2
          },
          highlight: {
            valType: "boolean",
            dflt: true
          },
          highlightcolor: {
            valType: "color",
            dflt: Color2.defaultLine
          },
          highlightwidth: {
            valType: "number",
            min: 1,
            max: 16,
            dflt: 2
          }
        };
      }
      var attrs = module.exports = overrideAll(
        extendFlat(
          {
            z: {
              valType: "data_array"
            },
            x: {
              valType: "data_array"
            },
            y: {
              valType: "data_array"
            },
            text: {
              valType: "string",
              dflt: "",
              arrayOk: true
            },
            hovertext: {
              valType: "string",
              dflt: "",
              arrayOk: true
            },
            hovertemplate: hovertemplateAttrs(),
            hovertemplatefallback: templatefallbackAttrs(),
            xhoverformat: axisHoverFormat("x"),
            yhoverformat: axisHoverFormat("y"),
            zhoverformat: axisHoverFormat("z"),
            connectgaps: {
              valType: "boolean",
              dflt: false,
              editType: "calc"
            },
            surfacecolor: {
              valType: "data_array"
            }
          },
          colorScaleAttrs("", {
            colorAttr: "z or surfacecolor",
            showScaleDflt: true,
            autoColorDflt: false,
            editTypeOverride: "calc"
          }),
          {
            contours: {
              x: makeContourAttr("x"),
              y: makeContourAttr("y"),
              z: makeContourAttr("z")
            },
            hidesurface: {
              valType: "boolean",
              dflt: false
            },
            lightposition: {
              x: {
                valType: "number",
                min: -1e5,
                max: 1e5,
                dflt: 10
              },
              y: {
                valType: "number",
                min: -1e5,
                max: 1e5,
                dflt: 1e4
              },
              z: {
                valType: "number",
                min: -1e5,
                max: 1e5,
                dflt: 0
              }
            },
            lighting: {
              ambient: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 0.8
              },
              diffuse: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 0.8
              },
              specular: {
                valType: "number",
                min: 0,
                max: 2,
                dflt: 0.05,
                description: "Represents the level that incident rays are reflected in a single direction, causing shine."
              },
              roughness: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 0.5,
                description: "Alters specular reflection; the rougher the surface, the wider and less contrasty the shine."
              },
              fresnel: {
                valType: "number",
                min: 0,
                max: 5,
                dflt: 0.2
              }
            },
            opacity: {
              valType: "number",
              min: 0,
              max: 1,
              dflt: 1
            },
            opacityscale: {
              valType: "any",
              editType: "calc"
            },
            hoverinfo: extendFlat({}, baseAttrs.hoverinfo),
            showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
          }
        ),
        "calc",
        "nested"
      );
      attrs.x.editType = attrs.y.editType = attrs.z.editType = "calc+clearAxisTypes";
    }
  });

  // src/traces/surface/defaults.js
  var require_defaults38 = __commonJS({
    "src/traces/surface/defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes42();
      var MIN = 0.1;
      function createWave(n, minOpacity) {
        var arr = [];
        var steps = 32;
        for (var i = 0; i < steps; i++) {
          var u = i / (steps - 1);
          var v = minOpacity + (1 - minOpacity) * (1 - Math.pow(Math.sin(n * u * Math.PI), 2));
          arr.push([u, Math.max(0, Math.min(1, v))]);
        }
        return arr;
      }
      function isValidScaleArray(scl) {
        var highestVal = 0;
        if (!Array.isArray(scl) || scl.length < 2) return false;
        if (!scl[0] || !scl[scl.length - 1]) return false;
        if (+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;
        for (var i = 0; i < scl.length; i++) {
          var si = scl[i];
          if (si.length !== 2 || +si[0] < highestVal) {
            return false;
          }
          highestVal = +si[0];
        }
        return true;
      }
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        var i, j;
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var x = coerce("x");
        var y = coerce("y");
        var z = coerce("z");
        if (!z || !z.length || (x ? x.length < 1 : false) || (y ? y.length < 1 : false)) {
          traceOut.visible = false;
          return;
        }
        traceOut._xlength = Array.isArray(x) && Lib.isArrayOrTypedArray(x[0]) ? z.length : z[0].length;
        traceOut._ylength = z.length;
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y", "z"], layout);
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("zhoverformat");
        [
          "lighting.ambient",
          "lighting.diffuse",
          "lighting.specular",
          "lighting.roughness",
          "lighting.fresnel",
          "lightposition.x",
          "lightposition.y",
          "lightposition.z",
          "hidesurface",
          "connectgaps",
          "opacity"
        ].forEach(function(x2) {
          coerce(x2);
        });
        var surfaceColor = coerce("surfacecolor");
        var dims = ["x", "y", "z"];
        for (i = 0; i < 3; ++i) {
          var contourDim = "contours." + dims[i];
          var show = coerce(contourDim + ".show");
          var highlight = coerce(contourDim + ".highlight");
          if (show || highlight) {
            for (j = 0; j < 3; ++j) {
              coerce(contourDim + ".project." + dims[j]);
            }
          }
          if (show) {
            coerce(contourDim + ".color");
            coerce(contourDim + ".width");
            coerce(contourDim + ".usecolormap");
          }
          if (highlight) {
            coerce(contourDim + ".highlightcolor");
            coerce(contourDim + ".highlightwidth");
          }
          coerce(contourDim + ".start");
          coerce(contourDim + ".end");
          coerce(contourDim + ".size");
        }
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "c" });
        opacityscaleDefaults(traceIn, traceOut, layout, coerce);
        traceOut._length = null;
      }
      function opacityscaleDefaults(traceIn, traceOut, layout, coerce) {
        var opacityscale = coerce("opacityscale");
        if (opacityscale === "max") {
          traceOut.opacityscale = [
            [0, MIN],
            [1, 1]
          ];
        } else if (opacityscale === "min") {
          traceOut.opacityscale = [
            [0, 1],
            [1, MIN]
          ];
        } else if (opacityscale === "extremes") {
          traceOut.opacityscale = createWave(1, MIN);
        } else if (!isValidScaleArray(opacityscale)) {
          traceOut.opacityscale = void 0;
        }
      }
      module.exports = {
        supplyDefaults,
        opacityscaleDefaults
      };
    }
  });

  // src/traces/surface/calc.js
  var require_calc22 = __commonJS({
    "src/traces/surface/calc.js"(exports, module) {
      "use strict";
      var colorscaleCalc = require_calc();
      module.exports = function calc(gd, trace) {
        if (trace.surfacecolor) {
          colorscaleCalc(gd, trace, {
            vals: trace.surfacecolor,
            containerStr: "",
            cLetter: "c"
          });
        } else {
          colorscaleCalc(gd, trace, {
            vals: trace.z,
            containerStr: "",
            cLetter: "c"
          });
        }
      };
    }
  });

  // src/traces/surface/convert.js
  var require_convert4 = __commonJS({
    "src/traces/surface/convert.js"(exports, module) {
      "use strict";
      var createSurface = require_stackgl_modules().gl_surface3d;
      var ndarray = require_stackgl_modules().ndarray;
      var ndarrayInterp2d = require_stackgl_modules().ndarray_linear_interpolate.d2;
      var interp2d = require_interp2d();
      var findEmpties = require_find_empties();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var parseColorScale = require_gl_format_color().parseColorScale;
      var str2RgbaArray = require_str2rgbarray();
      var extractOpts = require_colorscale().extractOpts;
      function SurfaceTrace(scene, surface, uid) {
        this.scene = scene;
        this.uid = uid;
        this.surface = surface;
        this.data = null;
        this.showContour = [false, false, false];
        this.contourStart = [null, null, null];
        this.contourEnd = [null, null, null];
        this.contourSize = [0, 0, 0];
        this.minValues = [Infinity, Infinity, Infinity];
        this.maxValues = [-Infinity, -Infinity, -Infinity];
        this.dataScaleX = 1;
        this.dataScaleY = 1;
        this.refineData = true;
        this.objectOffset = [0, 0, 0];
      }
      var proto = SurfaceTrace.prototype;
      proto.getXat = function(a, b, calendar, axis) {
        var v = !isArrayOrTypedArray(this.data.x) ? a : isArrayOrTypedArray(this.data.x[0]) ? this.data.x[b][a] : this.data.x[a];
        return calendar === void 0 ? v : axis.d2l(v, 0, calendar);
      };
      proto.getYat = function(a, b, calendar, axis) {
        var v = !isArrayOrTypedArray(this.data.y) ? b : isArrayOrTypedArray(this.data.y[0]) ? this.data.y[b][a] : this.data.y[b];
        return calendar === void 0 ? v : axis.d2l(v, 0, calendar);
      };
      proto.getZat = function(a, b, calendar, axis) {
        var v = this.data.z[b][a];
        if (v === null && this.data.connectgaps && this.data._interpolatedZ) {
          v = this.data._interpolatedZ[b][a];
        }
        return calendar === void 0 ? v : axis.d2l(v, 0, calendar);
      };
      proto.handlePick = function(selection) {
        if (selection.object === this.surface) {
          var xRatio = (selection.data.index[0] - 1) / this.dataScaleX - 1;
          var yRatio = (selection.data.index[1] - 1) / this.dataScaleY - 1;
          var j = Math.max(Math.min(Math.round(xRatio), this.data.z[0].length - 1), 0);
          var k = Math.max(Math.min(Math.round(yRatio), this.data._ylength - 1), 0);
          selection.index = [j, k];
          selection.traceCoordinate = [
            this.getXat(j, k),
            this.getYat(j, k),
            this.getZat(j, k)
          ];
          selection.dataCoordinate = [
            this.getXat(j, k, this.data.xcalendar, this.scene.fullSceneLayout.xaxis),
            this.getYat(j, k, this.data.ycalendar, this.scene.fullSceneLayout.yaxis),
            this.getZat(j, k, this.data.zcalendar, this.scene.fullSceneLayout.zaxis)
          ];
          for (var i = 0; i < 3; i++) {
            var v = selection.dataCoordinate[i];
            if (v !== null && v !== void 0) {
              selection.dataCoordinate[i] *= this.scene.dataScale[i];
            }
          }
          var text = this.data.hovertext || this.data.text;
          if (isArrayOrTypedArray(text) && text[k] && text[k][j] !== void 0) {
            selection.textLabel = text[k][j];
          } else if (text) {
            selection.textLabel = text;
          } else {
            selection.textLabel = "";
          }
          selection.data.dataCoordinate = selection.dataCoordinate.slice();
          this.surface.highlight(selection.data);
          this.scene.glplot.spikes.position = selection.dataCoordinate;
          return true;
        }
      };
      function isColormapCircular(colormap) {
        var first = colormap[0].rgb;
        var last = colormap[colormap.length - 1].rgb;
        return first[0] === last[0] && first[1] === last[1] && first[2] === last[2] && first[3] === last[3];
      }
      var shortPrimes = [
        2,
        3,
        5,
        7,
        11,
        13,
        17,
        19,
        23,
        29,
        31,
        37,
        41,
        43,
        47,
        53,
        59,
        61,
        67,
        71,
        73,
        79,
        83,
        89,
        97,
        101,
        103,
        107,
        109,
        113,
        127,
        131,
        137,
        139,
        149,
        151,
        157,
        163,
        167,
        173,
        179,
        181,
        191,
        193,
        197,
        199,
        211,
        223,
        227,
        229,
        233,
        239,
        241,
        251,
        257,
        263,
        269,
        271,
        277,
        281,
        283,
        293,
        307,
        311,
        313,
        317,
        331,
        337,
        347,
        349,
        353,
        359,
        367,
        373,
        379,
        383,
        389,
        397,
        401,
        409,
        419,
        421,
        431,
        433,
        439,
        443,
        449,
        457,
        461,
        463,
        467,
        479,
        487,
        491,
        499,
        503,
        509,
        521,
        523,
        541,
        547,
        557,
        563,
        569,
        571,
        577,
        587,
        593,
        599,
        601,
        607,
        613,
        617,
        619,
        631,
        641,
        643,
        647,
        653,
        659,
        661,
        673,
        677,
        683,
        691,
        701,
        709,
        719,
        727,
        733,
        739,
        743,
        751,
        757,
        761,
        769,
        773,
        787,
        797,
        809,
        811,
        821,
        823,
        827,
        829,
        839,
        853,
        857,
        859,
        863,
        877,
        881,
        883,
        887,
        907,
        911,
        919,
        929,
        937,
        941,
        947,
        953,
        967,
        971,
        977,
        983,
        991,
        997,
        1009,
        1013,
        1019,
        1021,
        1031,
        1033,
        1039,
        1049,
        1051,
        1061,
        1063,
        1069,
        1087,
        1091,
        1093,
        1097,
        1103,
        1109,
        1117,
        1123,
        1129,
        1151,
        1153,
        1163,
        1171,
        1181,
        1187,
        1193,
        1201,
        1213,
        1217,
        1223,
        1229,
        1231,
        1237,
        1249,
        1259,
        1277,
        1279,
        1283,
        1289,
        1291,
        1297,
        1301,
        1303,
        1307,
        1319,
        1321,
        1327,
        1361,
        1367,
        1373,
        1381,
        1399,
        1409,
        1423,
        1427,
        1429,
        1433,
        1439,
        1447,
        1451,
        1453,
        1459,
        1471,
        1481,
        1483,
        1487,
        1489,
        1493,
        1499,
        1511,
        1523,
        1531,
        1543,
        1549,
        1553,
        1559,
        1567,
        1571,
        1579,
        1583,
        1597,
        1601,
        1607,
        1609,
        1613,
        1619,
        1621,
        1627,
        1637,
        1657,
        1663,
        1667,
        1669,
        1693,
        1697,
        1699,
        1709,
        1721,
        1723,
        1733,
        1741,
        1747,
        1753,
        1759,
        1777,
        1783,
        1787,
        1789,
        1801,
        1811,
        1823,
        1831,
        1847,
        1861,
        1867,
        1871,
        1873,
        1877,
        1879,
        1889,
        1901,
        1907,
        1913,
        1931,
        1933,
        1949,
        1951,
        1973,
        1979,
        1987,
        1993,
        1997,
        1999,
        2003,
        2011,
        2017,
        2027,
        2029,
        2039,
        2053,
        2063,
        2069,
        2081,
        2083,
        2087,
        2089,
        2099,
        2111,
        2113,
        2129,
        2131,
        2137,
        2141,
        2143,
        2153,
        2161,
        2179,
        2203,
        2207,
        2213,
        2221,
        2237,
        2239,
        2243,
        2251,
        2267,
        2269,
        2273,
        2281,
        2287,
        2293,
        2297,
        2309,
        2311,
        2333,
        2339,
        2341,
        2347,
        2351,
        2357,
        2371,
        2377,
        2381,
        2383,
        2389,
        2393,
        2399,
        2411,
        2417,
        2423,
        2437,
        2441,
        2447,
        2459,
        2467,
        2473,
        2477,
        2503,
        2521,
        2531,
        2539,
        2543,
        2549,
        2551,
        2557,
        2579,
        2591,
        2593,
        2609,
        2617,
        2621,
        2633,
        2647,
        2657,
        2659,
        2663,
        2671,
        2677,
        2683,
        2687,
        2689,
        2693,
        2699,
        2707,
        2711,
        2713,
        2719,
        2729,
        2731,
        2741,
        2749,
        2753,
        2767,
        2777,
        2789,
        2791,
        2797,
        2801,
        2803,
        2819,
        2833,
        2837,
        2843,
        2851,
        2857,
        2861,
        2879,
        2887,
        2897,
        2903,
        2909,
        2917,
        2927,
        2939,
        2953,
        2957,
        2963,
        2969,
        2971,
        2999
      ];
      function getPow(a, b) {
        if (a < b) return 0;
        var n = 0;
        while (Math.floor(a % b) === 0) {
          a /= b;
          n++;
        }
        return n;
      }
      function getFactors(a) {
        var powers = [];
        for (var i = 0; i < shortPrimes.length; i++) {
          var b = shortPrimes[i];
          powers.push(
            getPow(a, b)
          );
        }
        return powers;
      }
      function smallestDivisor(a) {
        var A2 = getFactors(a);
        var result = a;
        for (var i = 0; i < shortPrimes.length; i++) {
          if (A2[i] > 0) {
            result = shortPrimes[i];
            break;
          }
        }
        return result;
      }
      function leastCommonMultiple(a, b) {
        if (a < 1 || b < 1) return void 0;
        var A2 = getFactors(a);
        var B2 = getFactors(b);
        var n = 1;
        for (var i = 0; i < shortPrimes.length; i++) {
          n *= Math.pow(
            shortPrimes[i],
            Math.max(A2[i], B2[i])
          );
        }
        return n;
      }
      function arrayLCM(A2) {
        if (A2.length === 0) return void 0;
        var n = 1;
        for (var i = 0; i < A2.length; i++) {
          n = leastCommonMultiple(n, A2[i]);
        }
        return n;
      }
      proto.calcXnums = function(xlen) {
        var i;
        var nums = [];
        for (i = 1; i < xlen; i++) {
          var a = this.getXat(i - 1, 0);
          var b = this.getXat(i, 0);
          if (b !== a && a !== void 0 && a !== null && b !== void 0 && b !== null) {
            nums[i - 1] = Math.abs(b - a);
          } else {
            nums[i - 1] = 0;
          }
        }
        var totalDist = 0;
        for (i = 1; i < xlen; i++) {
          totalDist += nums[i - 1];
        }
        for (i = 1; i < xlen; i++) {
          if (nums[i - 1] === 0) {
            nums[i - 1] = 1;
          } else {
            nums[i - 1] = Math.round(totalDist / nums[i - 1]);
          }
        }
        return nums;
      };
      proto.calcYnums = function(ylen) {
        var i;
        var nums = [];
        for (i = 1; i < ylen; i++) {
          var a = this.getYat(0, i - 1);
          var b = this.getYat(0, i);
          if (b !== a && a !== void 0 && a !== null && b !== void 0 && b !== null) {
            nums[i - 1] = Math.abs(b - a);
          } else {
            nums[i - 1] = 0;
          }
        }
        var totalDist = 0;
        for (i = 1; i < ylen; i++) {
          totalDist += nums[i - 1];
        }
        for (i = 1; i < ylen; i++) {
          if (nums[i - 1] === 0) {
            nums[i - 1] = 1;
          } else {
            nums[i - 1] = Math.round(totalDist / nums[i - 1]);
          }
        }
        return nums;
      };
      var highlyComposites = [1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260];
      var MIN_RESOLUTION = highlyComposites[9];
      var MAX_RESOLUTION = highlyComposites[13];
      proto.estimateScale = function(resSrc, axis) {
        var nums = axis === 0 ? this.calcXnums(resSrc) : this.calcYnums(resSrc);
        var resDst = 1 + arrayLCM(nums);
        while (resDst < MIN_RESOLUTION) {
          resDst *= 2;
        }
        while (resDst > MAX_RESOLUTION) {
          resDst--;
          resDst /= smallestDivisor(resDst);
          resDst++;
          if (resDst < MIN_RESOLUTION) {
            resDst = MAX_RESOLUTION;
          }
        }
        var scale = Math.round(resDst / resSrc);
        return scale > 1 ? scale : 1;
      };
      function fnHomography(out, inp, X) {
        var w = X[8] + X[2] * inp[0] + X[5] * inp[1];
        out[0] = (X[6] + X[0] * inp[0] + X[3] * inp[1]) / w;
        out[1] = (X[7] + X[1] * inp[0] + X[4] * inp[1]) / w;
        return out;
      }
      function homography(dest, src, X) {
        warp(dest, src, fnHomography, X);
        return dest;
      }
      function warp(dest, src, func, X) {
        var warped = [0, 0];
        var ni = dest.shape[0];
        var nj = dest.shape[1];
        for (var i = 0; i < ni; i++) {
          for (var j = 0; j < nj; j++) {
            func(warped, [i, j], X);
            dest.set(i, j, ndarrayInterp2d(src, warped[0], warped[1]));
          }
        }
        return dest;
      }
      proto.refineCoords = function(coords) {
        var scaleW = this.dataScaleX;
        var scaleH = this.dataScaleY;
        var width = coords[0].shape[0];
        var height = coords[0].shape[1];
        var newWidth = Math.floor(coords[0].shape[0] * scaleW + 1) | 0;
        var newHeight = Math.floor(coords[0].shape[1] * scaleH + 1) | 0;
        var padWidth = 1 + width + 1;
        var padHeight = 1 + height + 1;
        var padImg = ndarray(new Float32Array(padWidth * padHeight), [padWidth, padHeight]);
        var X = [
          1 / scaleW,
          0,
          0,
          0,
          1 / scaleH,
          0,
          0,
          0,
          1
        ];
        for (var i = 0; i < coords.length; ++i) {
          this.surface.padField(padImg, coords[i]);
          var scaledImg = ndarray(new Float32Array(newWidth * newHeight), [newWidth, newHeight]);
          homography(scaledImg, padImg, X);
          coords[i] = scaledImg;
        }
      };
      function insertIfNewLevel(arr, newValue) {
        var found = false;
        for (var k = 0; k < arr.length; k++) {
          if (newValue === arr[k]) {
            found = true;
            break;
          }
        }
        if (found === false) arr.push(newValue);
      }
      proto.setContourLevels = function() {
        var newLevels = [[], [], []];
        var useNewLevels = [false, false, false];
        var needsUpdate = false;
        var i, j, value;
        for (i = 0; i < 3; ++i) {
          if (this.showContour[i]) {
            needsUpdate = true;
            if (this.contourSize[i] > 0 && this.contourStart[i] !== null && this.contourEnd[i] !== null && this.contourEnd[i] > this.contourStart[i]) {
              useNewLevels[i] = true;
              for (j = this.contourStart[i]; j < this.contourEnd[i]; j += this.contourSize[i]) {
                value = j * this.scene.dataScale[i];
                insertIfNewLevel(newLevels[i], value);
              }
            }
          }
        }
        if (needsUpdate) {
          var allLevels = [[], [], []];
          for (i = 0; i < 3; ++i) {
            if (this.showContour[i]) {
              allLevels[i] = useNewLevels[i] ? newLevels[i] : this.scene.contourLevels[i];
            }
          }
          this.surface.update({ levels: allLevels });
        }
      };
      proto.update = function(data) {
        var scene = this.scene;
        var sceneLayout = scene.fullSceneLayout;
        var surface = this.surface;
        var colormap = parseColorScale(data);
        var scaleFactor = scene.dataScale;
        var xlen = data.z[0].length;
        var ylen = data._ylength;
        var contourLevels = scene.contourLevels;
        this.data = data;
        var i, j, k, v;
        var rawCoords = [];
        for (i = 0; i < 3; i++) {
          rawCoords[i] = [];
          for (j = 0; j < xlen; j++) {
            rawCoords[i][j] = [];
          }
        }
        for (j = 0; j < xlen; j++) {
          for (k = 0; k < ylen; k++) {
            rawCoords[0][j][k] = this.getXat(j, k, data.xcalendar, sceneLayout.xaxis);
            rawCoords[1][j][k] = this.getYat(j, k, data.ycalendar, sceneLayout.yaxis);
            rawCoords[2][j][k] = this.getZat(j, k, data.zcalendar, sceneLayout.zaxis);
          }
        }
        if (data.connectgaps) {
          data._emptypoints = findEmpties(rawCoords[2]);
          interp2d(rawCoords[2], data._emptypoints);
          data._interpolatedZ = [];
          for (j = 0; j < xlen; j++) {
            data._interpolatedZ[j] = [];
            for (k = 0; k < ylen; k++) {
              data._interpolatedZ[j][k] = rawCoords[2][j][k];
            }
          }
        }
        for (i = 0; i < 3; i++) {
          for (j = 0; j < xlen; j++) {
            for (k = 0; k < ylen; k++) {
              v = rawCoords[i][j][k];
              if (v === null || v === void 0) {
                rawCoords[i][j][k] = NaN;
              } else {
                v = rawCoords[i][j][k] *= scaleFactor[i];
              }
            }
          }
        }
        for (i = 0; i < 3; i++) {
          for (j = 0; j < xlen; j++) {
            for (k = 0; k < ylen; k++) {
              v = rawCoords[i][j][k];
              if (v !== null && v !== void 0) {
                if (this.minValues[i] > v) {
                  this.minValues[i] = v;
                }
                if (this.maxValues[i] < v) {
                  this.maxValues[i] = v;
                }
              }
            }
          }
        }
        for (i = 0; i < 3; i++) {
          this.objectOffset[i] = 0.5 * (this.minValues[i] + this.maxValues[i]);
        }
        for (i = 0; i < 3; i++) {
          for (j = 0; j < xlen; j++) {
            for (k = 0; k < ylen; k++) {
              v = rawCoords[i][j][k];
              if (v !== null && v !== void 0) {
                rawCoords[i][j][k] -= this.objectOffset[i];
              }
            }
          }
        }
        var coords = [
          ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
          ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
          ndarray(new Float32Array(xlen * ylen), [xlen, ylen])
        ];
        for (i = 0; i < 3; i++) {
          for (j = 0; j < xlen; j++) {
            for (k = 0; k < ylen; k++) {
              coords[i].set(j, k, rawCoords[i][j][k]);
            }
          }
        }
        rawCoords = [];
        var params = {
          colormap,
          levels: [[], [], []],
          showContour: [true, true, true],
          showSurface: !data.hidesurface,
          contourProject: [
            [false, false, false],
            [false, false, false],
            [false, false, false]
          ],
          contourWidth: [1, 1, 1],
          contourColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
          contourTint: [1, 1, 1],
          dynamicColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
          dynamicWidth: [1, 1, 1],
          dynamicTint: [1, 1, 1],
          opacityscale: data.opacityscale,
          opacity: data.opacity
        };
        var cOpts = extractOpts(data);
        params.intensityBounds = [cOpts.min, cOpts.max];
        if (data.surfacecolor) {
          var intensity = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]);
          for (j = 0; j < xlen; j++) {
            for (k = 0; k < ylen; k++) {
              intensity.set(j, k, data.surfacecolor[k][j]);
            }
          }
          coords.push(intensity);
        } else {
          params.intensityBounds[0] *= scaleFactor[2];
          params.intensityBounds[1] *= scaleFactor[2];
        }
        if (MAX_RESOLUTION < coords[0].shape[0] || MAX_RESOLUTION < coords[0].shape[1]) {
          this.refineData = false;
        }
        if (this.refineData === true) {
          this.dataScaleX = this.estimateScale(coords[0].shape[0], 0);
          this.dataScaleY = this.estimateScale(coords[0].shape[1], 1);
          if (this.dataScaleX !== 1 || this.dataScaleY !== 1) {
            this.refineCoords(coords);
          }
        }
        if (data.surfacecolor) {
          params.intensity = coords.pop();
        }
        var highlightEnable = [true, true, true];
        var axis = ["x", "y", "z"];
        for (i = 0; i < 3; ++i) {
          var contourParams = data.contours[axis[i]];
          highlightEnable[i] = contourParams.highlight;
          params.showContour[i] = contourParams.show || contourParams.highlight;
          if (!params.showContour[i]) continue;
          params.contourProject[i] = [
            contourParams.project.x,
            contourParams.project.y,
            contourParams.project.z
          ];
          if (contourParams.show) {
            this.showContour[i] = true;
            params.levels[i] = contourLevels[i];
            surface.highlightColor[i] = params.contourColor[i] = str2RgbaArray(contourParams.color);
            if (contourParams.usecolormap) {
              surface.highlightTint[i] = params.contourTint[i] = 0;
            } else {
              surface.highlightTint[i] = params.contourTint[i] = 1;
            }
            params.contourWidth[i] = contourParams.width;
            this.contourStart[i] = contourParams.start;
            this.contourEnd[i] = contourParams.end;
            this.contourSize[i] = contourParams.size;
          } else {
            this.showContour[i] = false;
            this.contourStart[i] = null;
            this.contourEnd[i] = null;
            this.contourSize[i] = 0;
          }
          if (contourParams.highlight) {
            params.dynamicColor[i] = str2RgbaArray(contourParams.highlightcolor);
            params.dynamicWidth[i] = contourParams.highlightwidth;
          }
        }
        if (isColormapCircular(colormap)) {
          params.vertexColor = true;
        }
        params.objectOffset = this.objectOffset;
        params.coords = coords;
        surface.update(params);
        surface.visible = data.visible;
        surface.enableDynamic = highlightEnable;
        surface.enableHighlight = highlightEnable;
        surface.snapToData = true;
        if ("lighting" in data) {
          surface.ambientLight = data.lighting.ambient;
          surface.diffuseLight = data.lighting.diffuse;
          surface.specularLight = data.lighting.specular;
          surface.roughness = data.lighting.roughness;
          surface.fresnel = data.lighting.fresnel;
        }
        if ("lightposition" in data) {
          surface.lightPosition = [data.lightposition.x, data.lightposition.y, data.lightposition.z];
        }
      };
      proto.dispose = function() {
        this.scene.glplot.remove(this.surface);
        this.surface.dispose();
      };
      function createSurfaceTrace(scene, data) {
        var gl2 = scene.glplot.gl;
        var surface = createSurface({ gl: gl2 });
        var result = new SurfaceTrace(scene, surface, data.uid);
        surface._trace = result;
        result.update(data);
        scene.glplot.add(surface);
        return result;
      }
      module.exports = createSurfaceTrace;
    }
  });

  // src/traces/surface/index.js
  var require_surface = __commonJS({
    "src/traces/surface/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes42(),
        supplyDefaults: require_defaults38().supplyDefaults,
        colorbar: {
          min: "cmin",
          max: "cmax"
        },
        calc: require_calc22(),
        plot: require_convert4(),
        moduleType: "trace",
        name: "surface",
        basePlotModule: require_gl3d(),
        categories: ["gl3d", "2dMap", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/surface.js
  var require_surface2 = __commonJS({
    "lib/surface.js"(exports, module) {
      "use strict";
      module.exports = require_surface();
    }
  });

  // src/traces/mesh3d/attributes.js
  var require_attributes43 = __commonJS({
    "src/traces/mesh3d/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var surfaceAttrs = require_attributes42();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      module.exports = extendFlat(
        {
          x: {
            valType: "data_array",
            editType: "calc+clearAxisTypes"
          },
          y: {
            valType: "data_array",
            editType: "calc+clearAxisTypes"
          },
          z: {
            valType: "data_array",
            editType: "calc+clearAxisTypes"
          },
          i: {
            valType: "data_array",
            editType: "calc"
          },
          j: {
            valType: "data_array",
            editType: "calc"
          },
          k: {
            valType: "data_array",
            editType: "calc"
          },
          text: {
            valType: "string",
            dflt: "",
            arrayOk: true,
            editType: "calc"
          },
          hovertext: {
            valType: "string",
            dflt: "",
            arrayOk: true,
            editType: "calc"
          },
          hovertemplate: hovertemplateAttrs({ editType: "calc" }),
          hovertemplatefallback: templatefallbackAttrs({ editType: "calc" }),
          xhoverformat: axisHoverFormat("x"),
          yhoverformat: axisHoverFormat("y"),
          zhoverformat: axisHoverFormat("z"),
          delaunayaxis: {
            valType: "enumerated",
            values: ["x", "y", "z"],
            dflt: "z",
            editType: "calc"
          },
          alphahull: {
            valType: "number",
            dflt: -1,
            editType: "calc"
          },
          intensity: {
            valType: "data_array",
            editType: "calc"
          },
          intensitymode: {
            valType: "enumerated",
            values: ["vertex", "cell"],
            dflt: "vertex",
            editType: "calc"
          },
          // Color field
          color: {
            valType: "color",
            editType: "calc"
          },
          vertexcolor: {
            valType: "data_array",
            editType: "calc"
          },
          facecolor: {
            valType: "data_array",
            editType: "calc"
          }
        },
        colorScaleAttrs("", {
          colorAttr: "`intensity`",
          showScaleDflt: true,
          editTypeOverride: "calc"
        }),
        {
          opacity: surfaceAttrs.opacity,
          // Flat shaded mode
          flatshading: {
            valType: "boolean",
            dflt: false,
            editType: "calc"
          },
          contour: {
            show: extendFlat({}, surfaceAttrs.contours.x.show, {}),
            color: surfaceAttrs.contours.x.color,
            width: surfaceAttrs.contours.x.width,
            editType: "calc"
          },
          lightposition: {
            x: extendFlat({}, surfaceAttrs.lightposition.x, { dflt: 1e5 }),
            y: extendFlat({}, surfaceAttrs.lightposition.y, { dflt: 1e5 }),
            z: extendFlat({}, surfaceAttrs.lightposition.z, { dflt: 0 }),
            editType: "calc"
          },
          lighting: extendFlat(
            {
              vertexnormalsepsilon: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 1e-12,
                // otherwise finely tessellated things eg. the brain will have no specular light reflection
                editType: "calc",
                description: "Epsilon for vertex normals calculation avoids math issues arising from degenerate geometry."
              },
              facenormalsepsilon: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 1e-6,
                // even the brain model doesn't appear to need finer than this
                editType: "calc",
                description: "Epsilon for face normals calculation avoids math issues arising from degenerate geometry."
              },
              editType: "calc"
            },
            surfaceAttrs.lighting
          ),
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, { editType: "calc" }),
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
        }
      );
    }
  });

  // src/traces/isosurface/attributes.js
  var require_attributes44 = __commonJS({
    "src/traces/isosurface/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var meshAttrs = require_attributes43();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      function makeSliceAttr(axLetter) {
        return {
          show: {
            valType: "boolean",
            dflt: false
          },
          locations: {
            valType: "data_array",
            dflt: []
          },
          fill: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 1
          }
        };
      }
      function makeCapAttr(axLetter) {
        return {
          show: {
            valType: "boolean",
            dflt: true
          },
          fill: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 1
          }
        };
      }
      var attrs = module.exports = overrideAll(
        extendFlat(
          {
            x: {
              valType: "data_array"
            },
            y: {
              valType: "data_array"
            },
            z: {
              valType: "data_array"
            },
            value: {
              valType: "data_array"
            },
            isomin: {
              valType: "number"
            },
            isomax: {
              valType: "number"
            },
            surface: {
              show: {
                valType: "boolean",
                dflt: true
              },
              count: {
                valType: "integer",
                dflt: 2,
                min: 1
              },
              fill: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 1
              },
              pattern: {
                valType: "flaglist",
                flags: ["A", "B", "C", "D", "E"],
                extras: ["all", "odd", "even"],
                dflt: "all"
              }
            },
            spaceframe: {
              show: {
                valType: "boolean",
                dflt: false
              },
              fill: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 0.15
              }
            },
            slices: {
              x: makeSliceAttr("x"),
              y: makeSliceAttr("y"),
              z: makeSliceAttr("z")
            },
            caps: {
              x: makeCapAttr("x"),
              y: makeCapAttr("y"),
              z: makeCapAttr("z")
            },
            text: {
              valType: "string",
              dflt: "",
              arrayOk: true
            },
            hovertext: {
              valType: "string",
              dflt: "",
              arrayOk: true
            },
            hovertemplate: hovertemplateAttrs(),
            hovertemplatefallback: templatefallbackAttrs(),
            xhoverformat: axisHoverFormat("x"),
            yhoverformat: axisHoverFormat("y"),
            zhoverformat: axisHoverFormat("z"),
            valuehoverformat: axisHoverFormat("value", 1),
            showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
          },
          colorScaleAttrs("", {
            colorAttr: "`value`",
            showScaleDflt: true,
            editTypeOverride: "calc"
          }),
          {
            opacity: meshAttrs.opacity,
            lightposition: meshAttrs.lightposition,
            lighting: meshAttrs.lighting,
            flatshading: meshAttrs.flatshading,
            contour: meshAttrs.contour,
            hoverinfo: extendFlat({}, baseAttrs.hoverinfo)
          }
        ),
        "calc",
        "nested"
      );
      attrs.flatshading.dflt = true;
      attrs.lighting.facenormalsepsilon.dflt = 0;
      attrs.x.editType = attrs.y.editType = attrs.z.editType = attrs.value.editType = "calc+clearAxisTypes";
    }
  });

  // src/traces/isosurface/defaults.js
  var require_defaults39 = __commonJS({
    "src/traces/isosurface/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Registry = require_registry();
      var attributes = require_attributes44();
      var colorscaleDefaults = require_defaults2();
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        supplyIsoDefaults(traceIn, traceOut, defaultColor, layout, coerce);
      }
      function supplyIsoDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
        var isomin = coerce("isomin");
        var isomax = coerce("isomax");
        if (isomax !== void 0 && isomax !== null && isomin !== void 0 && isomin !== null && isomin > isomax) {
          traceOut.isomin = null;
          traceOut.isomax = null;
        }
        var x = coerce("x");
        var y = coerce("y");
        var z = coerce("z");
        var value = coerce("value");
        if (!x || !x.length || !y || !y.length || !z || !z.length || !value || !value.length) {
          traceOut.visible = false;
          return;
        }
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y", "z"], layout);
        coerce("valuehoverformat");
        ["x", "y", "z"].forEach(function(dim) {
          coerce(dim + "hoverformat");
          var capDim = "caps." + dim;
          var showCap = coerce(capDim + ".show");
          if (showCap) {
            coerce(capDim + ".fill");
          }
          var sliceDim = "slices." + dim;
          var showSlice = coerce(sliceDim + ".show");
          if (showSlice) {
            coerce(sliceDim + ".fill");
            coerce(sliceDim + ".locations");
          }
        });
        var showSpaceframe = coerce("spaceframe.show");
        if (showSpaceframe) {
          coerce("spaceframe.fill");
        }
        var showSurface = coerce("surface.show");
        if (showSurface) {
          coerce("surface.count");
          coerce("surface.fill");
          coerce("surface.pattern");
        }
        var showContour = coerce("contour.show");
        if (showContour) {
          coerce("contour.color");
          coerce("contour.width");
        }
        [
          "text",
          "hovertext",
          "hovertemplate",
          "lighting.ambient",
          "lighting.diffuse",
          "lighting.specular",
          "lighting.roughness",
          "lighting.fresnel",
          "lighting.vertexnormalsepsilon",
          "lighting.facenormalsepsilon",
          "lightposition.x",
          "lightposition.y",
          "lightposition.z",
          "flatshading",
          "opacity"
        ].forEach(function(x2) {
          coerce(x2);
        });
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "c" });
        traceOut._length = null;
      }
      module.exports = {
        supplyDefaults,
        supplyIsoDefaults
      };
    }
  });

  // src/traces/streamtube/calc.js
  var require_calc23 = __commonJS({
    "src/traces/streamtube/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleCalc = require_calc();
      function calc(gd, trace) {
        trace._len = Math.min(
          trace.u.length,
          trace.v.length,
          trace.w.length,
          trace.x.length,
          trace.y.length,
          trace.z.length
        );
        trace._u = filter(trace.u, trace._len);
        trace._v = filter(trace.v, trace._len);
        trace._w = filter(trace.w, trace._len);
        trace._x = filter(trace.x, trace._len);
        trace._y = filter(trace.y, trace._len);
        trace._z = filter(trace.z, trace._len);
        var grid = processGrid(trace);
        trace._gridFill = grid.fill;
        trace._Xs = grid.Xs;
        trace._Ys = grid.Ys;
        trace._Zs = grid.Zs;
        trace._len = grid.len;
        var slen = 0;
        var startx, starty, startz;
        if (trace.starts) {
          startx = filter(trace.starts.x || []);
          starty = filter(trace.starts.y || []);
          startz = filter(trace.starts.z || []);
          slen = Math.min(startx.length, starty.length, startz.length);
        }
        trace._startsX = startx || [];
        trace._startsY = starty || [];
        trace._startsZ = startz || [];
        var normMax = 0;
        var normMin = Infinity;
        var i;
        for (i = 0; i < trace._len; i++) {
          var u = trace._u[i];
          var v = trace._v[i];
          var w = trace._w[i];
          var norm = Math.sqrt(u * u + v * v + w * w);
          normMax = Math.max(normMax, norm);
          normMin = Math.min(normMin, norm);
        }
        colorscaleCalc(gd, trace, {
          vals: [normMin, normMax],
          containerStr: "",
          cLetter: "c"
        });
        for (i = 0; i < slen; i++) {
          var sx = startx[i];
          grid.xMax = Math.max(grid.xMax, sx);
          grid.xMin = Math.min(grid.xMin, sx);
          var sy = starty[i];
          grid.yMax = Math.max(grid.yMax, sy);
          grid.yMin = Math.min(grid.yMin, sy);
          var sz = startz[i];
          grid.zMax = Math.max(grid.zMax, sz);
          grid.zMin = Math.min(grid.zMin, sz);
        }
        trace._slen = slen;
        trace._normMax = normMax;
        trace._xbnds = [grid.xMin, grid.xMax];
        trace._ybnds = [grid.yMin, grid.yMax];
        trace._zbnds = [grid.zMin, grid.zMax];
      }
      function processGrid(trace) {
        var x = trace._x;
        var y = trace._y;
        var z = trace._z;
        var len = trace._len;
        var i, j, k;
        var xMax = -Infinity;
        var xMin = Infinity;
        var yMax = -Infinity;
        var yMin = Infinity;
        var zMax = -Infinity;
        var zMin = Infinity;
        var gridFill = "";
        var filledX;
        var filledY;
        var filledZ;
        var firstX, lastX;
        var firstY, lastY;
        var firstZ, lastZ;
        if (len) {
          firstX = x[0];
          firstY = y[0];
          firstZ = z[0];
        }
        if (len > 1) {
          lastX = x[len - 1];
          lastY = y[len - 1];
          lastZ = z[len - 1];
        }
        for (i = 0; i < len; i++) {
          xMax = Math.max(xMax, x[i]);
          xMin = Math.min(xMin, x[i]);
          yMax = Math.max(yMax, y[i]);
          yMin = Math.min(yMin, y[i]);
          zMax = Math.max(zMax, z[i]);
          zMin = Math.min(zMin, z[i]);
          if (!filledX && x[i] !== firstX) {
            filledX = true;
            gridFill += "x";
          }
          if (!filledY && y[i] !== firstY) {
            filledY = true;
            gridFill += "y";
          }
          if (!filledZ && z[i] !== firstZ) {
            filledZ = true;
            gridFill += "z";
          }
        }
        if (!filledX) gridFill += "x";
        if (!filledY) gridFill += "y";
        if (!filledZ) gridFill += "z";
        var Xs = distinctVals(trace._x);
        var Ys = distinctVals(trace._y);
        var Zs = distinctVals(trace._z);
        gridFill = gridFill.replace("x", (firstX > lastX ? "-" : "+") + "x");
        gridFill = gridFill.replace("y", (firstY > lastY ? "-" : "+") + "y");
        gridFill = gridFill.replace("z", (firstZ > lastZ ? "-" : "+") + "z");
        var empty = function() {
          len = 0;
          Xs = [];
          Ys = [];
          Zs = [];
        };
        if (!len || len < Xs.length * Ys.length * Zs.length) empty();
        var getArray = function(c) {
          return c === "x" ? x : c === "y" ? y : z;
        };
        var getVals = function(c) {
          return c === "x" ? Xs : c === "y" ? Ys : Zs;
        };
        var getDir = function(c) {
          return c[len - 1] < c[0] ? -1 : 1;
        };
        var arrK = getArray(gridFill[1]);
        var arrJ = getArray(gridFill[3]);
        var arrI = getArray(gridFill[5]);
        var nk = getVals(gridFill[1]).length;
        var nj = getVals(gridFill[3]).length;
        var ni = getVals(gridFill[5]).length;
        var arbitrary = false;
        var getIndex = function(_i, _j, _k) {
          return nk * (nj * _i + _j) + _k;
        };
        var dirK = getDir(getArray(gridFill[1]));
        var dirJ = getDir(getArray(gridFill[3]));
        var dirI = getDir(getArray(gridFill[5]));
        for (i = 0; i < ni - 1; i++) {
          for (j = 0; j < nj - 1; j++) {
            for (k = 0; k < nk - 1; k++) {
              var q000 = getIndex(i, j, k);
              var q001 = getIndex(i, j, k + 1);
              var q010 = getIndex(i, j + 1, k);
              var q100 = getIndex(i + 1, j, k);
              if (!(arrK[q000] * dirK < arrK[q001] * dirK) || !(arrJ[q000] * dirJ < arrJ[q010] * dirJ) || !(arrI[q000] * dirI < arrI[q100] * dirI)) {
                arbitrary = true;
              }
              if (arbitrary) break;
            }
            if (arbitrary) break;
          }
          if (arbitrary) break;
        }
        if (arbitrary) {
          Lib.warn("Encountered arbitrary coordinates! Unable to input data grid.");
          empty();
        }
        return {
          xMin,
          yMin,
          zMin,
          xMax,
          yMax,
          zMax,
          Xs,
          Ys,
          Zs,
          len,
          fill: gridFill
        };
      }
      function distinctVals(col) {
        return Lib.distinctVals(col).vals;
      }
      function filter(arr, len) {
        if (len === void 0) len = arr.length;
        if (Lib.isTypedArray(arr)) return arr.subarray(0, len);
        var values = [];
        for (var i = 0; i < len; i++) {
          values[i] = +arr[i];
        }
        return values;
      }
      module.exports = {
        calc,
        filter,
        processGrid
      };
    }
  });

  // src/traces/isosurface/calc.js
  var require_calc24 = __commonJS({
    "src/traces/isosurface/calc.js"(exports, module) {
      "use strict";
      var colorscaleCalc = require_calc();
      var processGrid = require_calc23().processGrid;
      var filter = require_calc23().filter;
      module.exports = function calc(gd, trace) {
        trace._len = Math.min(
          trace.x.length,
          trace.y.length,
          trace.z.length,
          trace.value.length
        );
        trace._x = filter(trace.x, trace._len);
        trace._y = filter(trace.y, trace._len);
        trace._z = filter(trace.z, trace._len);
        trace._value = filter(trace.value, trace._len);
        var grid = processGrid(trace);
        trace._gridFill = grid.fill;
        trace._Xs = grid.Xs;
        trace._Ys = grid.Ys;
        trace._Zs = grid.Zs;
        trace._len = grid.len;
        var min = Infinity;
        var max = -Infinity;
        for (var i = 0; i < trace._len; i++) {
          var v = trace._value[i];
          min = Math.min(min, v);
          max = Math.max(max, v);
        }
        trace._minValues = min;
        trace._maxValues = max;
        trace._vMin = trace.isomin === void 0 || trace.isomin === null ? min : trace.isomin;
        trace._vMax = trace.isomax === void 0 || trace.isomax === null ? max : trace.isomax;
        colorscaleCalc(gd, trace, {
          vals: [trace._vMin, trace._vMax],
          containerStr: "",
          cLetter: "c"
        });
      };
    }
  });

  // src/plots/gl3d/zip3.js
  var require_zip3 = __commonJS({
    "src/plots/gl3d/zip3.js"(exports, module) {
      "use strict";
      module.exports = function zip3(x, y, z, len) {
        len = len || x.length;
        var result = new Array(len);
        for (var i = 0; i < len; i++) {
          result[i] = [x[i], y[i], z[i]];
        }
        return result;
      };
    }
  });

  // src/traces/isosurface/convert.js
  var require_convert5 = __commonJS({
    "src/traces/isosurface/convert.js"(exports, module) {
      "use strict";
      var createMesh = require_stackgl_modules().gl_mesh3d;
      var parseColorScale = require_gl_format_color().parseColorScale;
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var str2RgbaArray = require_str2rgbarray();
      var extractOpts = require_colorscale().extractOpts;
      var zip3 = require_zip3();
      var findNearestOnAxis = function(w, arr) {
        for (var q = arr.length - 1; q > 0; q--) {
          var min = Math.min(arr[q], arr[q - 1]);
          var max = Math.max(arr[q], arr[q - 1]);
          if (max > min && min < w && w <= max) {
            return {
              id: q,
              distRatio: (max - w) / (max - min)
            };
          }
        }
        return {
          id: 0,
          distRatio: 0
        };
      };
      function IsosurfaceTrace(scene, mesh, uid) {
        this.scene = scene;
        this.uid = uid;
        this.mesh = mesh;
        this.name = "";
        this.data = null;
        this.showContour = false;
      }
      var proto = IsosurfaceTrace.prototype;
      proto.handlePick = function(selection) {
        if (selection.object === this.mesh) {
          var rawId = selection.data.index;
          var x = this.data._meshX[rawId];
          var y = this.data._meshY[rawId];
          var z = this.data._meshZ[rawId];
          var height = this.data._Ys.length;
          var depth = this.data._Zs.length;
          var i = findNearestOnAxis(x, this.data._Xs).id;
          var j = findNearestOnAxis(y, this.data._Ys).id;
          var k = findNearestOnAxis(z, this.data._Zs).id;
          var selectIndex = selection.index = k + depth * j + depth * height * i;
          selection.traceCoordinate = [
            this.data._meshX[selectIndex],
            this.data._meshY[selectIndex],
            this.data._meshZ[selectIndex],
            this.data._value[selectIndex]
          ];
          var text = this.data.hovertext || this.data.text;
          if (isArrayOrTypedArray(text) && text[selectIndex] !== void 0) {
            selection.textLabel = text[selectIndex];
          } else if (text) {
            selection.textLabel = text;
          }
          return true;
        }
      };
      proto.update = function(data) {
        var scene = this.scene;
        var layout = scene.fullSceneLayout;
        this.data = generateIsoMeshes(data);
        function toDataCoords(axis, coord, scale, calendar) {
          return coord.map(function(x) {
            return axis.d2l(x, 0, calendar) * scale;
          });
        }
        var positions = zip3(
          toDataCoords(layout.xaxis, data._meshX, scene.dataScale[0], data.xcalendar),
          toDataCoords(layout.yaxis, data._meshY, scene.dataScale[1], data.ycalendar),
          toDataCoords(layout.zaxis, data._meshZ, scene.dataScale[2], data.zcalendar)
        );
        var cells = zip3(data._meshI, data._meshJ, data._meshK);
        var config = {
          positions,
          cells,
          lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
          ambient: data.lighting.ambient,
          diffuse: data.lighting.diffuse,
          specular: data.lighting.specular,
          roughness: data.lighting.roughness,
          fresnel: data.lighting.fresnel,
          vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
          faceNormalsEpsilon: data.lighting.facenormalsepsilon,
          opacity: data.opacity,
          contourEnable: data.contour.show,
          contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
          contourWidth: data.contour.width,
          useFacetNormals: data.flatshading
        };
        var cOpts = extractOpts(data);
        config.vertexIntensity = data._meshIntensity;
        config.vertexIntensityBounds = [cOpts.min, cOpts.max];
        config.colormap = parseColorScale(data);
        this.mesh.update(config);
      };
      proto.dispose = function() {
        this.scene.glplot.remove(this.mesh);
        this.mesh.dispose();
      };
      var GRID_TYPES = ["xyz", "xzy", "yxz", "yzx", "zxy", "zyx"];
      function generateIsoMeshes(data) {
        data._meshI = [];
        data._meshJ = [];
        data._meshK = [];
        var showSurface = data.surface.show;
        var showSpaceframe = data.spaceframe.show;
        var surfaceFill = data.surface.fill;
        var spaceframeFill = data.spaceframe.fill;
        var drawingSurface = false;
        var drawingSpaceframe = false;
        var numFaces = 0;
        var numVertices;
        var beginVertextLength;
        var Xs = data._Xs;
        var Ys = data._Ys;
        var Zs = data._Zs;
        var width = Xs.length;
        var height = Ys.length;
        var depth = Zs.length;
        var filled = GRID_TYPES.indexOf(data._gridFill.replace(/-/g, "").replace(/\+/g, ""));
        var getIndex = function(i, j, k) {
          switch (filled) {
            case 5:
              return k + depth * j + depth * height * i;
            case 4:
              return k + depth * i + depth * width * j;
            case 3:
              return j + height * k + height * depth * i;
            case 2:
              return j + height * i + height * width * k;
            case 1:
              return i + width * k + width * depth * j;
            default:
              return i + width * j + width * height * k;
          }
        };
        var minValues = data._minValues;
        var maxValues = data._maxValues;
        var vMin = data._vMin;
        var vMax = data._vMax;
        var allXs;
        var allYs;
        var allZs;
        var allVs;
        function findVertexId(x, y, z) {
          var len = allVs.length;
          for (var f = beginVertextLength; f < len; f++) {
            if (x === allXs[f] && y === allYs[f] && z === allZs[f]) {
              return f;
            }
          }
          return -1;
        }
        function beginGroup() {
          beginVertextLength = numVertices;
        }
        function emptyVertices() {
          allXs = [];
          allYs = [];
          allZs = [];
          allVs = [];
          numVertices = 0;
          beginGroup();
        }
        function addVertex(x, y, z, v) {
          allXs.push(x);
          allYs.push(y);
          allZs.push(z);
          allVs.push(v);
          numVertices++;
          return numVertices - 1;
        }
        function addFace(a, b, c) {
          data._meshI.push(a);
          data._meshJ.push(b);
          data._meshK.push(c);
          numFaces++;
          return numFaces - 1;
        }
        function getCenter(A2, B2, C2) {
          var M = [];
          for (var i = 0; i < A2.length; i++) {
            M[i] = (A2[i] + B2[i] + C2[i]) / 3;
          }
          return M;
        }
        function getBetween(A2, B2, r) {
          var M = [];
          for (var i = 0; i < A2.length; i++) {
            M[i] = A2[i] * (1 - r) + r * B2[i];
          }
          return M;
        }
        var activeFill;
        function setFill(fill) {
          activeFill = fill;
        }
        function createOpenTri(xyzv, abc) {
          var A2 = xyzv[0];
          var B2 = xyzv[1];
          var C2 = xyzv[2];
          var G = getCenter(A2, B2, C2);
          var r = Math.sqrt(1 - activeFill);
          var p1 = getBetween(G, A2, r);
          var p2 = getBetween(G, B2, r);
          var p3 = getBetween(G, C2, r);
          var a = abc[0];
          var b = abc[1];
          var c = abc[2];
          return {
            xyzv: [
              [A2, B2, p2],
              [p2, p1, A2],
              [B2, C2, p3],
              [p3, p2, B2],
              [C2, A2, p1],
              [p1, p3, C2]
            ],
            abc: [
              [a, b, -1],
              [-1, -1, a],
              [b, c, -1],
              [-1, -1, b],
              [c, a, -1],
              [-1, -1, c]
            ]
          };
        }
        function styleIncludes(style, char) {
          if (style === "all" || style === null) return true;
          return style.indexOf(char) > -1;
        }
        function mapValue(style, value) {
          if (style === null) return value;
          return style;
        }
        function drawTri(style, xyzv, abc) {
          beginGroup();
          var allXYZVs = [xyzv];
          var allABCs = [abc];
          if (activeFill >= 1) {
            allXYZVs = [xyzv];
            allABCs = [abc];
          } else if (activeFill > 0) {
            var openTri = createOpenTri(xyzv, abc);
            allXYZVs = openTri.xyzv;
            allABCs = openTri.abc;
          }
          for (var f = 0; f < allXYZVs.length; f++) {
            xyzv = allXYZVs[f];
            abc = allABCs[f];
            var pnts = [];
            for (var i = 0; i < 3; i++) {
              var x = xyzv[i][0];
              var y = xyzv[i][1];
              var z = xyzv[i][2];
              var v = xyzv[i][3];
              var id = abc[i] > -1 ? abc[i] : findVertexId(x, y, z);
              if (id > -1) {
                pnts[i] = id;
              } else {
                pnts[i] = addVertex(x, y, z, mapValue(style, v));
              }
            }
            addFace(pnts[0], pnts[1], pnts[2]);
          }
        }
        function drawQuad(style, xyzv, abcd) {
          var makeTri = function(i, j, k) {
            drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
          };
          makeTri(0, 1, 2);
          makeTri(2, 3, 0);
        }
        function drawTetra(style, xyzv, abcd) {
          var makeTri = function(i, j, k) {
            drawTri(style, [xyzv[i], xyzv[j], xyzv[k]], [abcd[i], abcd[j], abcd[k]]);
          };
          makeTri(0, 1, 2);
          makeTri(3, 0, 1);
          makeTri(2, 3, 0);
          makeTri(1, 2, 3);
        }
        function calcIntersection(pointOut, pointIn, min, max) {
          var value = pointOut[3];
          if (value < min) value = min;
          if (value > max) value = max;
          var ratio = (pointOut[3] - value) / (pointOut[3] - pointIn[3] + 1e-9);
          var result = [];
          for (var s = 0; s < 4; s++) {
            result[s] = (1 - ratio) * pointOut[s] + ratio * pointIn[s];
          }
          return result;
        }
        function inRange(value, min, max) {
          return value >= min && value <= max;
        }
        function almostInFinalRange(value) {
          var vErr = 1e-3 * (vMax - vMin);
          return value >= vMin - vErr && value <= vMax + vErr;
        }
        function getXYZV(indecies) {
          var xyzv = [];
          for (var q = 0; q < 4; q++) {
            var index = indecies[q];
            xyzv.push(
              [
                data._x[index],
                data._y[index],
                data._z[index],
                data._value[index]
              ]
            );
          }
          return xyzv;
        }
        var MAX_PASS = 3;
        function tryCreateTri(style, xyzv, abc, min, max, nPass) {
          if (!nPass) nPass = 1;
          abc = [-1, -1, -1];
          var result = false;
          var ok = [
            inRange(xyzv[0][3], min, max),
            inRange(xyzv[1][3], min, max),
            inRange(xyzv[2][3], min, max)
          ];
          if (!ok[0] && !ok[1] && !ok[2]) {
            return false;
          }
          var tryDrawTri = function(style2, xyzv2, abc2) {
            if (
              // we check here if the points are in `real` iso-min/max range
              almostInFinalRange(xyzv2[0][3]) && almostInFinalRange(xyzv2[1][3]) && almostInFinalRange(xyzv2[2][3])
            ) {
              drawTri(style2, xyzv2, abc2);
              return true;
            } else if (nPass < MAX_PASS) {
              return tryCreateTri(style2, xyzv2, abc2, vMin, vMax, ++nPass);
            }
            return false;
          };
          if (ok[0] && ok[1] && ok[2]) {
            return tryDrawTri(style, xyzv, abc) || result;
          }
          var interpolated = false;
          [
            [0, 1, 2],
            [2, 0, 1],
            [1, 2, 0]
          ].forEach(function(e) {
            if (ok[e[0]] && ok[e[1]] && !ok[e[2]]) {
              var A2 = xyzv[e[0]];
              var B2 = xyzv[e[1]];
              var C2 = xyzv[e[2]];
              var p1 = calcIntersection(C2, A2, min, max);
              var p2 = calcIntersection(C2, B2, min, max);
              result = tryDrawTri(style, [p2, p1, A2], [-1, -1, abc[e[0]]]) || result;
              result = tryDrawTri(style, [A2, B2, p2], [abc[e[0]], abc[e[1]], -1]) || result;
              interpolated = true;
            }
          });
          if (interpolated) return result;
          [
            [0, 1, 2],
            [1, 2, 0],
            [2, 0, 1]
          ].forEach(function(e) {
            if (ok[e[0]] && !ok[e[1]] && !ok[e[2]]) {
              var A2 = xyzv[e[0]];
              var B2 = xyzv[e[1]];
              var C2 = xyzv[e[2]];
              var p1 = calcIntersection(B2, A2, min, max);
              var p2 = calcIntersection(C2, A2, min, max);
              result = tryDrawTri(style, [p2, p1, A2], [-1, -1, abc[e[0]]]) || result;
              interpolated = true;
            }
          });
          return result;
        }
        function tryCreateTetra(style, abcd, min, max) {
          var result = false;
          var xyzv = getXYZV(abcd);
          var ok = [
            inRange(xyzv[0][3], min, max),
            inRange(xyzv[1][3], min, max),
            inRange(xyzv[2][3], min, max),
            inRange(xyzv[3][3], min, max)
          ];
          if (!ok[0] && !ok[1] && !ok[2] && !ok[3]) {
            return result;
          }
          if (ok[0] && ok[1] && ok[2] && ok[3]) {
            if (drawingSpaceframe) {
              result = drawTetra(style, xyzv, abcd) || result;
            }
            return result;
          }
          var interpolated = false;
          [
            [0, 1, 2, 3],
            [3, 0, 1, 2],
            [2, 3, 0, 1],
            [1, 2, 3, 0]
          ].forEach(function(e) {
            if (ok[e[0]] && ok[e[1]] && ok[e[2]] && !ok[e[3]]) {
              var A2 = xyzv[e[0]];
              var B2 = xyzv[e[1]];
              var C2 = xyzv[e[2]];
              var D2 = xyzv[e[3]];
              if (drawingSpaceframe) {
                result = drawTri(style, [A2, B2, C2], [abcd[e[0]], abcd[e[1]], abcd[e[2]]]) || result;
              } else {
                var p1 = calcIntersection(D2, A2, min, max);
                var p2 = calcIntersection(D2, B2, min, max);
                var p3 = calcIntersection(D2, C2, min, max);
                result = drawTri(null, [p1, p2, p3], [-1, -1, -1]) || result;
              }
              interpolated = true;
            }
          });
          if (interpolated) return result;
          [
            [0, 1, 2, 3],
            [1, 2, 3, 0],
            [2, 3, 0, 1],
            [3, 0, 1, 2],
            [0, 2, 3, 1],
            [1, 3, 2, 0]
          ].forEach(function(e) {
            if (ok[e[0]] && ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
              var A2 = xyzv[e[0]];
              var B2 = xyzv[e[1]];
              var C2 = xyzv[e[2]];
              var D2 = xyzv[e[3]];
              var p1 = calcIntersection(C2, A2, min, max);
              var p2 = calcIntersection(C2, B2, min, max);
              var p3 = calcIntersection(D2, B2, min, max);
              var p4 = calcIntersection(D2, A2, min, max);
              if (drawingSpaceframe) {
                result = drawTri(style, [A2, p4, p1], [abcd[e[0]], -1, -1]) || result;
                result = drawTri(style, [B2, p2, p3], [abcd[e[1]], -1, -1]) || result;
              } else {
                result = drawQuad(null, [p1, p2, p3, p4], [-1, -1, -1, -1]) || result;
              }
              interpolated = true;
            }
          });
          if (interpolated) return result;
          [
            [0, 1, 2, 3],
            [1, 2, 3, 0],
            [2, 3, 0, 1],
            [3, 0, 1, 2]
          ].forEach(function(e) {
            if (ok[e[0]] && !ok[e[1]] && !ok[e[2]] && !ok[e[3]]) {
              var A2 = xyzv[e[0]];
              var B2 = xyzv[e[1]];
              var C2 = xyzv[e[2]];
              var D2 = xyzv[e[3]];
              var p1 = calcIntersection(B2, A2, min, max);
              var p2 = calcIntersection(C2, A2, min, max);
              var p3 = calcIntersection(D2, A2, min, max);
              if (drawingSpaceframe) {
                result = drawTri(style, [A2, p1, p2], [abcd[e[0]], -1, -1]) || result;
                result = drawTri(style, [A2, p2, p3], [abcd[e[0]], -1, -1]) || result;
                result = drawTri(style, [A2, p3, p1], [abcd[e[0]], -1, -1]) || result;
              } else {
                result = drawTri(null, [p1, p2, p3], [-1, -1, -1]) || result;
              }
              interpolated = true;
            }
          });
          return result;
        }
        function addCube(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max) {
          var result = false;
          if (drawingSurface) {
            if (styleIncludes(style, "A")) {
              result = tryCreateTetra(null, [p000, p001, p010, p100], min, max) || result;
            }
            if (styleIncludes(style, "B")) {
              result = tryCreateTetra(null, [p001, p010, p011, p111], min, max) || result;
            }
            if (styleIncludes(style, "C")) {
              result = tryCreateTetra(null, [p001, p100, p101, p111], min, max) || result;
            }
            if (styleIncludes(style, "D")) {
              result = tryCreateTetra(null, [p010, p100, p110, p111], min, max) || result;
            }
            if (styleIncludes(style, "E")) {
              result = tryCreateTetra(null, [p001, p010, p100, p111], min, max) || result;
            }
          }
          if (drawingSpaceframe) {
            result = tryCreateTetra(style, [p001, p010, p100, p111], min, max) || result;
          }
          return result;
        }
        function addRect(style, a, b, c, d, min, max, previousResult) {
          return [
            previousResult[0] === true ? true : tryCreateTri(style, getXYZV([a, b, c]), [a, b, c], min, max),
            previousResult[1] === true ? true : tryCreateTri(style, getXYZV([c, d, a]), [c, d, a], min, max)
          ];
        }
        function begin2dCell(style, p00, p01, p10, p11, min, max, isEven, previousResult) {
          if (isEven) {
            return addRect(style, p00, p01, p11, p10, min, max, previousResult);
          } else {
            return addRect(style, p01, p11, p10, p00, min, max, previousResult);
          }
        }
        function beginSection(style, i, j, k, min, max, distRatios) {
          var result = false;
          var A2, B2, C2, D2;
          var makeSection = function() {
            result = tryCreateTri(style, [A2, B2, C2], [-1, -1, -1], min, max) || result;
            result = tryCreateTri(style, [C2, D2, A2], [-1, -1, -1], min, max) || result;
          };
          var rX = distRatios[0];
          var rY = distRatios[1];
          var rZ = distRatios[2];
          if (rX) {
            A2 = getBetween(getXYZV([getIndex(i, j - 0, k - 0)])[0], getXYZV([getIndex(i - 1, j - 0, k - 0)])[0], rX);
            B2 = getBetween(getXYZV([getIndex(i, j - 0, k - 1)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rX);
            C2 = getBetween(getXYZV([getIndex(i, j - 1, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rX);
            D2 = getBetween(getXYZV([getIndex(i, j - 1, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rX);
            makeSection();
          }
          if (rY) {
            A2 = getBetween(getXYZV([getIndex(i - 0, j, k - 0)])[0], getXYZV([getIndex(i - 0, j - 1, k - 0)])[0], rY);
            B2 = getBetween(getXYZV([getIndex(i - 0, j, k - 1)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rY);
            C2 = getBetween(getXYZV([getIndex(i - 1, j, k - 1)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rY);
            D2 = getBetween(getXYZV([getIndex(i - 1, j, k - 0)])[0], getXYZV([getIndex(i - 1, j - 1, k - 0)])[0], rY);
            makeSection();
          }
          if (rZ) {
            A2 = getBetween(getXYZV([getIndex(i - 0, j - 0, k)])[0], getXYZV([getIndex(i - 0, j - 0, k - 1)])[0], rZ);
            B2 = getBetween(getXYZV([getIndex(i - 0, j - 1, k)])[0], getXYZV([getIndex(i - 0, j - 1, k - 1)])[0], rZ);
            C2 = getBetween(getXYZV([getIndex(i - 1, j - 1, k)])[0], getXYZV([getIndex(i - 1, j - 1, k - 1)])[0], rZ);
            D2 = getBetween(getXYZV([getIndex(i - 1, j - 0, k)])[0], getXYZV([getIndex(i - 1, j - 0, k - 1)])[0], rZ);
            makeSection();
          }
          return result;
        }
        function begin3dCell(style, p000, p001, p010, p011, p100, p101, p110, p111, min, max, isEven) {
          var cellStyle = style;
          if (isEven) {
            if (drawingSurface && style === "even") cellStyle = null;
            return addCube(cellStyle, p000, p001, p010, p011, p100, p101, p110, p111, min, max);
          } else {
            if (drawingSurface && style === "odd") cellStyle = null;
            return addCube(cellStyle, p111, p110, p101, p100, p011, p010, p001, p000, min, max);
          }
        }
        function draw2dX(style, items, min, max, previousResult) {
          var result = [];
          var n = 0;
          for (var q = 0; q < items.length; q++) {
            var i = items[q];
            for (var k = 1; k < depth; k++) {
              for (var j = 1; j < height; j++) {
                result.push(
                  begin2dCell(
                    style,
                    getIndex(i, j - 1, k - 1),
                    getIndex(i, j - 1, k),
                    getIndex(i, j, k - 1),
                    getIndex(i, j, k),
                    min,
                    max,
                    (i + j + k) % 2,
                    previousResult && previousResult[n] ? previousResult[n] : []
                  )
                );
                n++;
              }
            }
          }
          return result;
        }
        function draw2dY(style, items, min, max, previousResult) {
          var result = [];
          var n = 0;
          for (var q = 0; q < items.length; q++) {
            var j = items[q];
            for (var i = 1; i < width; i++) {
              for (var k = 1; k < depth; k++) {
                result.push(
                  begin2dCell(
                    style,
                    getIndex(i - 1, j, k - 1),
                    getIndex(i, j, k - 1),
                    getIndex(i - 1, j, k),
                    getIndex(i, j, k),
                    min,
                    max,
                    (i + j + k) % 2,
                    previousResult && previousResult[n] ? previousResult[n] : []
                  )
                );
                n++;
              }
            }
          }
          return result;
        }
        function draw2dZ(style, items, min, max, previousResult) {
          var result = [];
          var n = 0;
          for (var q = 0; q < items.length; q++) {
            var k = items[q];
            for (var j = 1; j < height; j++) {
              for (var i = 1; i < width; i++) {
                result.push(
                  begin2dCell(
                    style,
                    getIndex(i - 1, j - 1, k),
                    getIndex(i - 1, j, k),
                    getIndex(i, j - 1, k),
                    getIndex(i, j, k),
                    min,
                    max,
                    (i + j + k) % 2,
                    previousResult && previousResult[n] ? previousResult[n] : []
                  )
                );
                n++;
              }
            }
          }
          return result;
        }
        function draw3d(style, min, max) {
          for (var k = 1; k < depth; k++) {
            for (var j = 1; j < height; j++) {
              for (var i = 1; i < width; i++) {
                begin3dCell(
                  style,
                  getIndex(i - 1, j - 1, k - 1),
                  getIndex(i - 1, j - 1, k),
                  getIndex(i - 1, j, k - 1),
                  getIndex(i - 1, j, k),
                  getIndex(i, j - 1, k - 1),
                  getIndex(i, j - 1, k),
                  getIndex(i, j, k - 1),
                  getIndex(i, j, k),
                  min,
                  max,
                  (i + j + k) % 2
                );
              }
            }
          }
        }
        function drawSpaceframe(style, min, max) {
          drawingSpaceframe = true;
          draw3d(style, min, max);
          drawingSpaceframe = false;
        }
        function drawSurface(style, min, max) {
          drawingSurface = true;
          draw3d(style, min, max);
          drawingSurface = false;
        }
        function drawSectionX(style, items, min, max, distRatios, previousResult) {
          var result = [];
          var n = 0;
          for (var q = 0; q < items.length; q++) {
            var i = items[q];
            for (var k = 1; k < depth; k++) {
              for (var j = 1; j < height; j++) {
                result.push(
                  beginSection(
                    style,
                    i,
                    j,
                    k,
                    min,
                    max,
                    distRatios[q],
                    previousResult && previousResult[n] ? previousResult[n] : []
                  )
                );
                n++;
              }
            }
          }
          return result;
        }
        function drawSectionY(style, items, min, max, distRatios, previousResult) {
          var result = [];
          var n = 0;
          for (var q = 0; q < items.length; q++) {
            var j = items[q];
            for (var i = 1; i < width; i++) {
              for (var k = 1; k < depth; k++) {
                result.push(
                  beginSection(
                    style,
                    i,
                    j,
                    k,
                    min,
                    max,
                    distRatios[q],
                    previousResult && previousResult[n] ? previousResult[n] : []
                  )
                );
                n++;
              }
            }
          }
          return result;
        }
        function drawSectionZ(style, items, min, max, distRatios, previousResult) {
          var result = [];
          var n = 0;
          for (var q = 0; q < items.length; q++) {
            var k = items[q];
            for (var j = 1; j < height; j++) {
              for (var i = 1; i < width; i++) {
                result.push(
                  beginSection(
                    style,
                    i,
                    j,
                    k,
                    min,
                    max,
                    distRatios[q],
                    previousResult && previousResult[n] ? previousResult[n] : []
                  )
                );
                n++;
              }
            }
          }
          return result;
        }
        function createRange(a, b) {
          var range = [];
          for (var q = a; q < b; q++) {
            range.push(q);
          }
          return range;
        }
        function insertGridPoints() {
          for (var i = 0; i < width; i++) {
            for (var j = 0; j < height; j++) {
              for (var k = 0; k < depth; k++) {
                var index = getIndex(i, j, k);
                addVertex(
                  data._x[index],
                  data._y[index],
                  data._z[index],
                  data._value[index]
                );
              }
            }
          }
        }
        function drawAll() {
          emptyVertices();
          insertGridPoints();
          var activeStyle = null;
          if (showSpaceframe && spaceframeFill) {
            setFill(spaceframeFill);
            drawSpaceframe(activeStyle, vMin, vMax);
          }
          if (showSurface && surfaceFill) {
            setFill(surfaceFill);
            var surfacePattern = data.surface.pattern;
            var surfaceCount = data.surface.count;
            for (var q = 0; q < surfaceCount; q++) {
              var ratio = surfaceCount === 1 ? 0.5 : q / (surfaceCount - 1);
              var level = (1 - ratio) * vMin + ratio * vMax;
              var d1 = Math.abs(level - minValues);
              var d2 = Math.abs(level - maxValues);
              var ranges = d1 > d2 ? [minValues, level] : [level, maxValues];
              drawSurface(surfacePattern, ranges[0], ranges[1]);
            }
          }
          var setupMinMax = [
            [Math.min(vMin, maxValues), Math.max(vMin, maxValues)],
            [Math.min(minValues, vMax), Math.max(minValues, vMax)]
          ];
          ["x", "y", "z"].forEach(function(e) {
            var preRes = [];
            for (var s = 0; s < setupMinMax.length; s++) {
              var count = 0;
              var activeMin = setupMinMax[s][0];
              var activeMax = setupMinMax[s][1];
              var slice = data.slices[e];
              if (slice.show && slice.fill) {
                setFill(slice.fill);
                var exactIndices = [];
                var ceilIndices = [];
                var distRatios = [];
                if (slice.locations.length) {
                  for (var q2 = 0; q2 < slice.locations.length; q2++) {
                    var near = findNearestOnAxis(
                      slice.locations[q2],
                      e === "x" ? Xs : e === "y" ? Ys : Zs
                    );
                    if (near.distRatio === 0) {
                      exactIndices.push(near.id);
                    } else if (near.id > 0) {
                      ceilIndices.push(near.id);
                      if (e === "x") {
                        distRatios.push([near.distRatio, 0, 0]);
                      } else if (e === "y") {
                        distRatios.push([0, near.distRatio, 0]);
                      } else {
                        distRatios.push([0, 0, near.distRatio]);
                      }
                    }
                  }
                } else {
                  if (e === "x") {
                    exactIndices = createRange(1, width - 1);
                  } else if (e === "y") {
                    exactIndices = createRange(1, height - 1);
                  } else {
                    exactIndices = createRange(1, depth - 1);
                  }
                }
                if (ceilIndices.length > 0) {
                  if (e === "x") {
                    preRes[count] = drawSectionX(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
                  } else if (e === "y") {
                    preRes[count] = drawSectionY(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
                  } else {
                    preRes[count] = drawSectionZ(activeStyle, ceilIndices, activeMin, activeMax, distRatios, preRes[count]);
                  }
                  count++;
                }
                if (exactIndices.length > 0) {
                  if (e === "x") {
                    preRes[count] = draw2dX(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
                  } else if (e === "y") {
                    preRes[count] = draw2dY(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
                  } else {
                    preRes[count] = draw2dZ(activeStyle, exactIndices, activeMin, activeMax, preRes[count]);
                  }
                  count++;
                }
              }
              var cap = data.caps[e];
              if (cap.show && cap.fill) {
                setFill(cap.fill);
                if (e === "x") {
                  preRes[count] = draw2dX(activeStyle, [0, width - 1], activeMin, activeMax, preRes[count]);
                } else if (e === "y") {
                  preRes[count] = draw2dY(activeStyle, [0, height - 1], activeMin, activeMax, preRes[count]);
                } else {
                  preRes[count] = draw2dZ(activeStyle, [0, depth - 1], activeMin, activeMax, preRes[count]);
                }
                count++;
              }
            }
          });
          if (numFaces === 0) {
            emptyVertices();
          }
          data._meshX = allXs;
          data._meshY = allYs;
          data._meshZ = allZs;
          data._meshIntensity = allVs;
          data._Xs = Xs;
          data._Ys = Ys;
          data._Zs = Zs;
        }
        drawAll();
        return data;
      }
      function createIsosurfaceTrace(scene, data) {
        var gl2 = scene.glplot.gl;
        var mesh = createMesh({ gl: gl2 });
        var result = new IsosurfaceTrace(scene, mesh, data.uid);
        mesh._trace = result;
        result.update(data);
        scene.glplot.add(mesh);
        return result;
      }
      module.exports = {
        findNearestOnAxis,
        generateIsoMeshes,
        createIsosurfaceTrace
      };
    }
  });

  // src/traces/isosurface/index.js
  var require_isosurface = __commonJS({
    "src/traces/isosurface/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes44(),
        supplyDefaults: require_defaults39().supplyDefaults,
        calc: require_calc24(),
        colorbar: {
          min: "cmin",
          max: "cmax"
        },
        plot: require_convert5().createIsosurfaceTrace,
        moduleType: "trace",
        name: "isosurface",
        basePlotModule: require_gl3d(),
        categories: ["gl3d", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/isosurface.js
  var require_isosurface2 = __commonJS({
    "lib/isosurface.js"(exports, module) {
      "use strict";
      module.exports = require_isosurface();
    }
  });

  // src/traces/volume/attributes.js
  var require_attributes45 = __commonJS({
    "src/traces/volume/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var isosurfaceAttrs = require_attributes44();
      var surfaceAttrs = require_attributes42();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var attrs = module.exports = overrideAll(
        extendFlat(
          {
            x: isosurfaceAttrs.x,
            y: isosurfaceAttrs.y,
            z: isosurfaceAttrs.z,
            value: isosurfaceAttrs.value,
            isomin: isosurfaceAttrs.isomin,
            isomax: isosurfaceAttrs.isomax,
            surface: isosurfaceAttrs.surface,
            spaceframe: {
              show: {
                valType: "boolean",
                dflt: false
              },
              fill: {
                valType: "number",
                min: 0,
                max: 1,
                dflt: 1
              }
            },
            slices: isosurfaceAttrs.slices,
            caps: isosurfaceAttrs.caps,
            text: isosurfaceAttrs.text,
            hovertext: isosurfaceAttrs.hovertext,
            xhoverformat: isosurfaceAttrs.xhoverformat,
            yhoverformat: isosurfaceAttrs.yhoverformat,
            zhoverformat: isosurfaceAttrs.zhoverformat,
            valuehoverformat: isosurfaceAttrs.valuehoverformat,
            hovertemplate: isosurfaceAttrs.hovertemplate,
            hovertemplatefallback: isosurfaceAttrs.hovertemplatefallback
          },
          colorScaleAttrs("", {
            colorAttr: "`value`",
            showScaleDflt: true,
            editTypeOverride: "calc"
          }),
          {
            colorbar: isosurfaceAttrs.colorbar,
            opacity: isosurfaceAttrs.opacity,
            opacityscale: surfaceAttrs.opacityscale,
            lightposition: isosurfaceAttrs.lightposition,
            lighting: isosurfaceAttrs.lighting,
            flatshading: isosurfaceAttrs.flatshading,
            contour: isosurfaceAttrs.contour,
            hoverinfo: extendFlat({}, baseAttrs.hoverinfo),
            showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
          }
        ),
        "calc",
        "nested"
      );
      attrs.x.editType = attrs.y.editType = attrs.z.editType = attrs.value.editType = "calc+clearAxisTypes";
    }
  });

  // src/traces/volume/defaults.js
  var require_defaults40 = __commonJS({
    "src/traces/volume/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes45();
      var supplyIsoDefaults = require_defaults39().supplyIsoDefaults;
      var opacityscaleDefaults = require_defaults38().opacityscaleDefaults;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        supplyIsoDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        opacityscaleDefaults(traceIn, traceOut, layout, coerce);
      };
    }
  });

  // src/traces/volume/convert.js
  var require_convert6 = __commonJS({
    "src/traces/volume/convert.js"(exports, module) {
      "use strict";
      var createMesh = require_stackgl_modules().gl_mesh3d;
      var parseColorScale = require_gl_format_color().parseColorScale;
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var str2RgbaArray = require_str2rgbarray();
      var extractOpts = require_colorscale().extractOpts;
      var zip3 = require_zip3();
      var findNearestOnAxis = require_convert5().findNearestOnAxis;
      var generateIsoMeshes = require_convert5().generateIsoMeshes;
      function VolumeTrace(scene, mesh, uid) {
        this.scene = scene;
        this.uid = uid;
        this.mesh = mesh;
        this.name = "";
        this.data = null;
        this.showContour = false;
      }
      var proto = VolumeTrace.prototype;
      proto.handlePick = function(selection) {
        if (selection.object === this.mesh) {
          var rawId = selection.data.index;
          var x = this.data._meshX[rawId];
          var y = this.data._meshY[rawId];
          var z = this.data._meshZ[rawId];
          var height = this.data._Ys.length;
          var depth = this.data._Zs.length;
          var i = findNearestOnAxis(x, this.data._Xs).id;
          var j = findNearestOnAxis(y, this.data._Ys).id;
          var k = findNearestOnAxis(z, this.data._Zs).id;
          var selectIndex = selection.index = k + depth * j + depth * height * i;
          selection.traceCoordinate = [
            this.data._meshX[selectIndex],
            this.data._meshY[selectIndex],
            this.data._meshZ[selectIndex],
            this.data._value[selectIndex]
          ];
          var text = this.data.hovertext || this.data.text;
          if (isArrayOrTypedArray(text) && text[selectIndex] !== void 0) {
            selection.textLabel = text[selectIndex];
          } else if (text) {
            selection.textLabel = text;
          }
          return true;
        }
      };
      proto.update = function(data) {
        var scene = this.scene;
        var layout = scene.fullSceneLayout;
        this.data = generateIsoMeshes(data);
        function toDataCoords(axis, coord, scale, calendar) {
          return coord.map(function(x) {
            return axis.d2l(x, 0, calendar) * scale;
          });
        }
        var positions = zip3(
          toDataCoords(layout.xaxis, data._meshX, scene.dataScale[0], data.xcalendar),
          toDataCoords(layout.yaxis, data._meshY, scene.dataScale[1], data.ycalendar),
          toDataCoords(layout.zaxis, data._meshZ, scene.dataScale[2], data.zcalendar)
        );
        var cells = zip3(data._meshI, data._meshJ, data._meshK);
        var config = {
          positions,
          cells,
          lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
          ambient: data.lighting.ambient,
          diffuse: data.lighting.diffuse,
          specular: data.lighting.specular,
          roughness: data.lighting.roughness,
          fresnel: data.lighting.fresnel,
          vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
          faceNormalsEpsilon: data.lighting.facenormalsepsilon,
          opacity: data.opacity,
          opacityscale: data.opacityscale,
          contourEnable: data.contour.show,
          contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
          contourWidth: data.contour.width,
          useFacetNormals: data.flatshading
        };
        var cOpts = extractOpts(data);
        config.vertexIntensity = data._meshIntensity;
        config.vertexIntensityBounds = [cOpts.min, cOpts.max];
        config.colormap = parseColorScale(data);
        this.mesh.update(config);
      };
      proto.dispose = function() {
        this.scene.glplot.remove(this.mesh);
        this.mesh.dispose();
      };
      function createVolumeTrace(scene, data) {
        var gl2 = scene.glplot.gl;
        var mesh = createMesh({ gl: gl2 });
        var result = new VolumeTrace(scene, mesh, data.uid);
        mesh._trace = result;
        result.update(data);
        scene.glplot.add(mesh);
        return result;
      }
      module.exports = createVolumeTrace;
    }
  });

  // src/traces/volume/index.js
  var require_volume = __commonJS({
    "src/traces/volume/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes45(),
        supplyDefaults: require_defaults40(),
        calc: require_calc24(),
        colorbar: {
          min: "cmin",
          max: "cmax"
        },
        plot: require_convert6(),
        moduleType: "trace",
        name: "volume",
        basePlotModule: require_gl3d(),
        categories: ["gl3d", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/volume.js
  var require_volume2 = __commonJS({
    "lib/volume.js"(exports, module) {
      "use strict";
      module.exports = require_volume();
    }
  });

  // src/traces/mesh3d/defaults.js
  var require_defaults41 = __commonJS({
    "src/traces/mesh3d/defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes43();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        function readComponents(array) {
          var ret = array.map(function(attr) {
            var result = coerce(attr);
            if (result && Lib.isArrayOrTypedArray(result)) return result;
            return null;
          });
          return ret.every(function(x) {
            return x && x.length === ret[0].length;
          }) && ret;
        }
        var coords = readComponents(["x", "y", "z"]);
        if (!coords) {
          traceOut.visible = false;
          return;
        }
        readComponents(["i", "j", "k"]);
        if (traceOut.i && (!traceOut.j || !traceOut.k) || traceOut.j && (!traceOut.k || !traceOut.i) || traceOut.k && (!traceOut.i || !traceOut.j)) {
          traceOut.visible = false;
          return;
        }
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x", "y", "z"], layout);
        [
          "lighting.ambient",
          "lighting.diffuse",
          "lighting.specular",
          "lighting.roughness",
          "lighting.fresnel",
          "lighting.vertexnormalsepsilon",
          "lighting.facenormalsepsilon",
          "lightposition.x",
          "lightposition.y",
          "lightposition.z",
          "flatshading",
          "alphahull",
          "delaunayaxis",
          "opacity"
        ].forEach(function(x) {
          coerce(x);
        });
        var showContour = coerce("contour.show");
        if (showContour) {
          coerce("contour.color");
          coerce("contour.width");
        }
        if ("intensity" in traceIn) {
          coerce("intensity");
          coerce("intensitymode");
          colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "c" });
        } else {
          traceOut.showscale = false;
          if ("facecolor" in traceIn) coerce("facecolor");
          else if ("vertexcolor" in traceIn) coerce("vertexcolor");
          else coerce("color", defaultColor);
        }
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("zhoverformat");
        traceOut._length = null;
      };
    }
  });

  // src/traces/mesh3d/calc.js
  var require_calc25 = __commonJS({
    "src/traces/mesh3d/calc.js"(exports, module) {
      "use strict";
      var colorscaleCalc = require_calc();
      module.exports = function calc(gd, trace) {
        if (trace.intensity) {
          colorscaleCalc(gd, trace, {
            vals: trace.intensity,
            containerStr: "",
            cLetter: "c"
          });
        }
      };
    }
  });

  // src/traces/mesh3d/convert.js
  var require_convert7 = __commonJS({
    "src/traces/mesh3d/convert.js"(exports, module) {
      "use strict";
      var createMesh = require_stackgl_modules().gl_mesh3d;
      var triangulate = require_stackgl_modules().delaunay_triangulate;
      var alphaShape = require_stackgl_modules().alpha_shape;
      var convexHull = require_stackgl_modules().convex_hull;
      var parseColorScale = require_gl_format_color().parseColorScale;
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var str2RgbaArray = require_str2rgbarray();
      var extractOpts = require_colorscale().extractOpts;
      var zip3 = require_zip3();
      function Mesh3DTrace(scene, mesh, uid) {
        this.scene = scene;
        this.uid = uid;
        this.mesh = mesh;
        this.name = "";
        this.color = "#fff";
        this.data = null;
        this.showContour = false;
      }
      var proto = Mesh3DTrace.prototype;
      proto.handlePick = function(selection) {
        if (selection.object === this.mesh) {
          var selectIndex = selection.index = selection.data.index;
          if (selection.data._cellCenter) {
            selection.traceCoordinate = selection.data.dataCoordinate;
          } else {
            selection.traceCoordinate = [
              this.data.x[selectIndex],
              this.data.y[selectIndex],
              this.data.z[selectIndex]
            ];
          }
          var text = this.data.hovertext || this.data.text;
          if (isArrayOrTypedArray(text) && text[selectIndex] !== void 0) {
            selection.textLabel = text[selectIndex];
          } else if (text) {
            selection.textLabel = text;
          }
          return true;
        }
      };
      function parseColorArray(colors) {
        var b = [];
        var len = colors.length;
        for (var i = 0; i < len; i++) {
          b[i] = str2RgbaArray(colors[i]);
        }
        return b;
      }
      function toDataCoords(axis, coord, scale, calendar) {
        var b = [];
        var len = coord.length;
        for (var i = 0; i < len; i++) {
          b[i] = axis.d2l(coord[i], 0, calendar) * scale;
        }
        return b;
      }
      function toRoundIndex(a) {
        var b = [];
        var len = a.length;
        for (var i = 0; i < len; i++) {
          b[i] = Math.round(a[i]);
        }
        return b;
      }
      function delaunayCells(delaunayaxis, positions) {
        var d = ["x", "y", "z"].indexOf(delaunayaxis);
        var b = [];
        var len = positions.length;
        for (var i = 0; i < len; i++) {
          b[i] = [positions[i][(d + 1) % 3], positions[i][(d + 2) % 3]];
        }
        return triangulate(b);
      }
      function hasValidIndices(list, numVertices) {
        var len = list.length;
        for (var i = 0; i < len; i++) {
          if (list[i] <= -0.5 || list[i] >= numVertices - 0.5) {
            return false;
          }
        }
        return true;
      }
      proto.update = function(data) {
        var scene = this.scene;
        var layout = scene.fullSceneLayout;
        this.data = data;
        var numVertices = data.x.length;
        var positions = zip3(
          toDataCoords(layout.xaxis, data.x, scene.dataScale[0], data.xcalendar),
          toDataCoords(layout.yaxis, data.y, scene.dataScale[1], data.ycalendar),
          toDataCoords(layout.zaxis, data.z, scene.dataScale[2], data.zcalendar)
        );
        var cells;
        if (data.i && data.j && data.k) {
          if (data.i.length !== data.j.length || data.j.length !== data.k.length || !hasValidIndices(data.i, numVertices) || !hasValidIndices(data.j, numVertices) || !hasValidIndices(data.k, numVertices)) {
            return;
          }
          cells = zip3(
            toRoundIndex(data.i),
            toRoundIndex(data.j),
            toRoundIndex(data.k)
          );
        } else if (data.alphahull === 0) {
          cells = convexHull(positions);
        } else if (data.alphahull > 0) {
          cells = alphaShape(data.alphahull, positions);
        } else {
          cells = delaunayCells(data.delaunayaxis, positions);
        }
        var config = {
          positions,
          cells,
          lightPosition: [data.lightposition.x, data.lightposition.y, data.lightposition.z],
          ambient: data.lighting.ambient,
          diffuse: data.lighting.diffuse,
          specular: data.lighting.specular,
          roughness: data.lighting.roughness,
          fresnel: data.lighting.fresnel,
          vertexNormalsEpsilon: data.lighting.vertexnormalsepsilon,
          faceNormalsEpsilon: data.lighting.facenormalsepsilon,
          opacity: data.opacity,
          contourEnable: data.contour.show,
          contourColor: str2RgbaArray(data.contour.color).slice(0, 3),
          contourWidth: data.contour.width,
          useFacetNormals: data.flatshading
        };
        if (data.intensity) {
          var cOpts = extractOpts(data);
          this.color = "#fff";
          var mode = data.intensitymode;
          config[mode + "Intensity"] = data.intensity;
          config[mode + "IntensityBounds"] = [cOpts.min, cOpts.max];
          config.colormap = parseColorScale(data);
        } else if (data.vertexcolor) {
          this.color = data.vertexcolor[0];
          config.vertexColors = parseColorArray(data.vertexcolor);
        } else if (data.facecolor) {
          this.color = data.facecolor[0];
          config.cellColors = parseColorArray(data.facecolor);
        } else {
          this.color = data.color;
          config.meshColor = str2RgbaArray(data.color);
        }
        this.mesh.update(config);
      };
      proto.dispose = function() {
        this.scene.glplot.remove(this.mesh);
        this.mesh.dispose();
      };
      function createMesh3DTrace(scene, data) {
        var gl2 = scene.glplot.gl;
        var mesh = createMesh({ gl: gl2 });
        var result = new Mesh3DTrace(scene, mesh, data.uid);
        mesh._trace = result;
        result.update(data);
        scene.glplot.add(mesh);
        return result;
      }
      module.exports = createMesh3DTrace;
    }
  });

  // src/traces/mesh3d/index.js
  var require_mesh3d = __commonJS({
    "src/traces/mesh3d/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes43(),
        supplyDefaults: require_defaults41(),
        calc: require_calc25(),
        colorbar: {
          min: "cmin",
          max: "cmax"
        },
        plot: require_convert7(),
        moduleType: "trace",
        name: "mesh3d",
        basePlotModule: require_gl3d(),
        categories: ["gl3d", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/mesh3d.js
  var require_mesh3d2 = __commonJS({
    "lib/mesh3d.js"(exports, module) {
      "use strict";
      module.exports = require_mesh3d();
    }
  });

  // src/traces/cone/attributes.js
  var require_attributes46 = __commonJS({
    "src/traces/cone/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var mesh3dAttrs = require_attributes43();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      var attrs = {
        x: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        y: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        z: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        u: {
          valType: "data_array",
          editType: "calc"
        },
        v: {
          valType: "data_array",
          editType: "calc"
        },
        w: {
          valType: "data_array",
          editType: "calc"
        },
        // TODO add way to specify cone positions independently of the vector field
        // provided, similar to MATLAB's coneplot Cx/Cy/Cz meshgrids,
        // see https://www.mathworks.com/help/matlab/ref/coneplot.html
        //
        // Alternatively, if our goal is only to 'fill in gaps' in the vector data,
        // we could try to extend the heatmap 'connectgaps' algorithm to 3D.
        // From AJ: this particular algorithm which amounts to a Poisson equation,
        // both for interpolation and extrapolation - is the right one to use for
        // cones too.  It makes a field with zero divergence, which is a good
        // baseline assumption for vector fields.
        //
        // cones: {
        //     // potential attributes to add:
        //     //
        //     // - meshmode: 'cartesian-product', 'pts', 'grid'
        //     //
        //     // under `meshmode: 'grid'`
        //     // - (x|y|z)grid.start
        //     // - (x|y|z)grid.end
        //     // - (x|y|z)grid.size
        //
        //     x: {
        //         valType: 'data_array',
        //         editType: 'calc',
        //
        //     },
        //     y: {
        //         valType: 'data_array',
        //         editType: 'calc',
        //
        //     },
        //     z: {
        //         valType: 'data_array',
        //         editType: 'calc',
        //
        //     },
        //
        //     editType: 'calc',
        //
        // },
        sizemode: {
          valType: "enumerated",
          values: ["scaled", "absolute", "raw"],
          editType: "calc",
          dflt: "scaled"
        },
        sizeref: {
          valType: "number",
          editType: "calc",
          min: 0
        },
        anchor: {
          valType: "enumerated",
          editType: "calc",
          values: ["tip", "tail", "cm", "center"],
          dflt: "cm"
        },
        text: {
          valType: "string",
          dflt: "",
          arrayOk: true,
          editType: "calc"
        },
        hovertext: {
          valType: "string",
          dflt: "",
          arrayOk: true,
          editType: "calc"
        },
        hovertemplate: hovertemplateAttrs({ editType: "calc" }, { keys: ["norm"] }),
        hovertemplatefallback: templatefallbackAttrs({ editType: "calc" }),
        uhoverformat: axisHoverFormat("u", 1),
        vhoverformat: axisHoverFormat("v", 1),
        whoverformat: axisHoverFormat("w", 1),
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        zhoverformat: axisHoverFormat("z"),
        showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
      };
      extendFlat(
        attrs,
        colorScaleAttrs("", {
          colorAttr: "u/v/w norm",
          showScaleDflt: true,
          editTypeOverride: "calc"
        })
      );
      var fromMesh3d = ["opacity", "lightposition", "lighting"];
      fromMesh3d.forEach(function(k) {
        attrs[k] = mesh3dAttrs[k];
      });
      attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
        editType: "calc",
        flags: ["x", "y", "z", "u", "v", "w", "norm", "text", "name"],
        dflt: "x+y+z+norm+text+name"
      });
      module.exports = attrs;
    }
  });

  // src/traces/cone/defaults.js
  var require_defaults42 = __commonJS({
    "src/traces/cone/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes46();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var u = coerce("u");
        var v = coerce("v");
        var w = coerce("w");
        var x = coerce("x");
        var y = coerce("y");
        var z = coerce("z");
        if (!u || !u.length || !v || !v.length || !w || !w.length || !x || !x.length || !y || !y.length || !z || !z.length) {
          traceOut.visible = false;
          return;
        }
        var sizemode = coerce("sizemode");
        coerce("sizeref", sizemode === "raw" ? 1 : 0.5);
        coerce("anchor");
        coerce("lighting.ambient");
        coerce("lighting.diffuse");
        coerce("lighting.specular");
        coerce("lighting.roughness");
        coerce("lighting.fresnel");
        coerce("lightposition.x");
        coerce("lightposition.y");
        coerce("lightposition.z");
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "c" });
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("uhoverformat");
        coerce("vhoverformat");
        coerce("whoverformat");
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("zhoverformat");
        traceOut._length = null;
      };
    }
  });

  // src/traces/cone/calc.js
  var require_calc26 = __commonJS({
    "src/traces/cone/calc.js"(exports, module) {
      "use strict";
      var colorscaleCalc = require_calc();
      module.exports = function calc(gd, trace) {
        var u = trace.u;
        var v = trace.v;
        var w = trace.w;
        var len = Math.min(
          trace.x.length,
          trace.y.length,
          trace.z.length,
          u.length,
          v.length,
          w.length
        );
        var normMax = -Infinity;
        var normMin = Infinity;
        for (var i = 0; i < len; i++) {
          var uu = u[i];
          var vv = v[i];
          var ww = w[i];
          var norm = Math.sqrt(uu * uu + vv * vv + ww * ww);
          normMax = Math.max(normMax, norm);
          normMin = Math.min(normMin, norm);
        }
        trace._len = len;
        trace._normMax = normMax;
        colorscaleCalc(gd, trace, {
          vals: [normMin, normMax],
          containerStr: "",
          cLetter: "c"
        });
      };
    }
  });

  // src/traces/cone/convert.js
  var require_convert8 = __commonJS({
    "src/traces/cone/convert.js"(exports, module) {
      "use strict";
      var conePlot = require_stackgl_modules().gl_cone3d;
      var createConeMesh = require_stackgl_modules().gl_cone3d.createConeMesh;
      var simpleMap = require_lib().simpleMap;
      var parseColorScale = require_gl_format_color().parseColorScale;
      var extractOpts = require_colorscale().extractOpts;
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var zip3 = require_zip3();
      function Cone(scene, uid) {
        this.scene = scene;
        this.uid = uid;
        this.mesh = null;
        this.data = null;
      }
      var proto = Cone.prototype;
      proto.handlePick = function(selection) {
        if (selection.object === this.mesh) {
          var selectIndex = selection.index = selection.data.index;
          var xx = this.data.x[selectIndex];
          var yy = this.data.y[selectIndex];
          var zz = this.data.z[selectIndex];
          var uu = this.data.u[selectIndex];
          var vv = this.data.v[selectIndex];
          var ww = this.data.w[selectIndex];
          selection.traceCoordinate = [
            xx,
            yy,
            zz,
            uu,
            vv,
            ww,
            Math.sqrt(uu * uu + vv * vv + ww * ww)
          ];
          var text = this.data.hovertext || this.data.text;
          if (isArrayOrTypedArray(text) && text[selectIndex] !== void 0) {
            selection.textLabel = text[selectIndex];
          } else if (text) {
            selection.textLabel = text;
          }
          return true;
        }
      };
      var axisName2scaleIndex = { xaxis: 0, yaxis: 1, zaxis: 2 };
      var anchor2coneOffset = { tip: 1, tail: 0, cm: 0.25, center: 0.5 };
      var anchor2coneSpan = { tip: 1, tail: 1, cm: 0.75, center: 0.5 };
      function convert(scene, trace) {
        var sceneLayout = scene.fullSceneLayout;
        var dataScale = scene.dataScale;
        var coneOpts = {};
        function toDataCoords(arr, axisName) {
          var ax = sceneLayout[axisName];
          var scale = dataScale[axisName2scaleIndex[axisName]];
          return simpleMap(arr, function(v) {
            return ax.d2l(v) * scale;
          });
        }
        coneOpts.vectors = zip3(
          toDataCoords(trace.u, "xaxis"),
          toDataCoords(trace.v, "yaxis"),
          toDataCoords(trace.w, "zaxis"),
          trace._len
        );
        coneOpts.positions = zip3(
          toDataCoords(trace.x, "xaxis"),
          toDataCoords(trace.y, "yaxis"),
          toDataCoords(trace.z, "zaxis"),
          trace._len
        );
        var cOpts = extractOpts(trace);
        coneOpts.colormap = parseColorScale(trace);
        coneOpts.vertexIntensityBounds = [cOpts.min / trace._normMax, cOpts.max / trace._normMax];
        coneOpts.coneOffset = anchor2coneOffset[trace.anchor];
        var sizemode = trace.sizemode;
        if (sizemode === "scaled") {
          coneOpts.coneSize = trace.sizeref || 0.5;
        } else if (sizemode === "absolute") {
          coneOpts.coneSize = trace.sizeref && trace._normMax ? trace.sizeref / trace._normMax : 0.5;
        } else if (sizemode === "raw") {
          coneOpts.coneSize = trace.sizeref;
        }
        coneOpts.coneSizemode = sizemode;
        var meshData = conePlot(coneOpts);
        var lp = trace.lightposition;
        meshData.lightPosition = [lp.x, lp.y, lp.z];
        meshData.ambient = trace.lighting.ambient;
        meshData.diffuse = trace.lighting.diffuse;
        meshData.specular = trace.lighting.specular;
        meshData.roughness = trace.lighting.roughness;
        meshData.fresnel = trace.lighting.fresnel;
        meshData.opacity = trace.opacity;
        trace._pad = anchor2coneSpan[trace.anchor] * meshData.vectorScale * meshData.coneScale * trace._normMax;
        return meshData;
      }
      proto.update = function(data) {
        this.data = data;
        var meshData = convert(this.scene, data);
        this.mesh.update(meshData);
      };
      proto.dispose = function() {
        this.scene.glplot.remove(this.mesh);
        this.mesh.dispose();
      };
      function createConeTrace(scene, data) {
        var gl2 = scene.glplot.gl;
        var meshData = convert(scene, data);
        var mesh = createConeMesh(gl2, meshData);
        var cone = new Cone(scene, data.uid);
        cone.mesh = mesh;
        cone.data = data;
        mesh._trace = cone;
        scene.glplot.add(mesh);
        return cone;
      }
      module.exports = createConeTrace;
    }
  });

  // src/traces/cone/index.js
  var require_cone = __commonJS({
    "src/traces/cone/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "cone",
        basePlotModule: require_gl3d(),
        categories: ["gl3d", "showLegend"],
        attributes: require_attributes46(),
        supplyDefaults: require_defaults42(),
        colorbar: {
          min: "cmin",
          max: "cmax"
        },
        calc: require_calc26(),
        plot: require_convert8(),
        eventData: function(out, pt) {
          out.norm = pt.traceCoordinate[6];
          return out;
        },
        meta: {}
      };
    }
  });

  // lib/cone.js
  var require_cone2 = __commonJS({
    "lib/cone.js"(exports, module) {
      "use strict";
      module.exports = require_cone();
    }
  });

  // src/traces/streamtube/attributes.js
  var require_attributes47 = __commonJS({
    "src/traces/streamtube/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var mesh3dAttrs = require_attributes43();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      var attrs = {
        x: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        y: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        z: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        u: {
          valType: "data_array",
          editType: "calc"
        },
        v: {
          valType: "data_array",
          editType: "calc"
        },
        w: {
          valType: "data_array",
          editType: "calc"
        },
        starts: {
          x: {
            valType: "data_array",
            editType: "calc"
          },
          y: {
            valType: "data_array",
            editType: "calc"
          },
          z: {
            valType: "data_array",
            editType: "calc"
          },
          editType: "calc"
        },
        maxdisplayed: {
          valType: "integer",
          min: 0,
          dflt: 1e3,
          editType: "calc"
        },
        // TODO
        //
        // Should add 'absolute' (like cone traces have), but currently gl-streamtube3d's
        // `absoluteTubeSize` doesn't behave well enough for our needs.
        //
        // 'fixed' would be a nice addition to plot stream 'lines', see
        // https://github.com/plotly/plotly.js/commit/812be20750e21e0a1831975001c248d365850f73#r29129877
        //
        // sizemode: {
        //     valType: 'enumerated',
        //     values: ['scaled', 'absolute', 'fixed'],
        //     dflt: 'scaled',
        //     editType: 'calc',
        //
        // },
        sizeref: {
          valType: "number",
          editType: "calc",
          min: 0,
          dflt: 1
        },
        text: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        hovertext: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        hovertemplate: hovertemplateAttrs(
          { editType: "calc" },
          { keys: ["tubex", "tubey", "tubez", "tubeu", "tubev", "tubew", "norm", "divergence"] }
        ),
        hovertemplatefallback: templatefallbackAttrs({ editType: "calc" }),
        uhoverformat: axisHoverFormat("u", 1),
        vhoverformat: axisHoverFormat("v", 1),
        whoverformat: axisHoverFormat("w", 1),
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        zhoverformat: axisHoverFormat("z"),
        showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
      };
      extendFlat(
        attrs,
        colorScaleAttrs("", {
          colorAttr: "u/v/w norm",
          showScaleDflt: true,
          editTypeOverride: "calc"
        })
      );
      var fromMesh3d = ["opacity", "lightposition", "lighting"];
      fromMesh3d.forEach(function(k) {
        attrs[k] = mesh3dAttrs[k];
      });
      attrs.hoverinfo = extendFlat({}, baseAttrs.hoverinfo, {
        editType: "calc",
        flags: ["x", "y", "z", "u", "v", "w", "norm", "divergence", "text", "name"],
        dflt: "x+y+z+norm+text+name"
      });
      module.exports = attrs;
    }
  });

  // src/traces/streamtube/defaults.js
  var require_defaults43 = __commonJS({
    "src/traces/streamtube/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes47();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var u = coerce("u");
        var v = coerce("v");
        var w = coerce("w");
        var x = coerce("x");
        var y = coerce("y");
        var z = coerce("z");
        if (!u || !u.length || !v || !v.length || !w || !w.length || !x || !x.length || !y || !y.length || !z || !z.length) {
          traceOut.visible = false;
          return;
        }
        coerce("starts.x");
        coerce("starts.y");
        coerce("starts.z");
        coerce("maxdisplayed");
        coerce("sizeref");
        coerce("lighting.ambient");
        coerce("lighting.diffuse");
        coerce("lighting.specular");
        coerce("lighting.roughness");
        coerce("lighting.fresnel");
        coerce("lightposition.x");
        coerce("lightposition.y");
        coerce("lightposition.z");
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "c" });
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("uhoverformat");
        coerce("vhoverformat");
        coerce("whoverformat");
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("zhoverformat");
        traceOut._length = null;
      };
    }
  });

  // src/traces/streamtube/convert.js
  var require_convert9 = __commonJS({
    "src/traces/streamtube/convert.js"(exports, module) {
      "use strict";
      var tube2mesh = require_stackgl_modules().gl_streamtube3d;
      var createTubeMesh = tube2mesh.createTubeMesh;
      var Lib = require_lib();
      var parseColorScale = require_gl_format_color().parseColorScale;
      var extractOpts = require_colorscale().extractOpts;
      var zip3 = require_zip3();
      var axisName2scaleIndex = { xaxis: 0, yaxis: 1, zaxis: 2 };
      function Streamtube(scene, uid) {
        this.scene = scene;
        this.uid = uid;
        this.mesh = null;
        this.data = null;
      }
      var proto = Streamtube.prototype;
      proto.handlePick = function(selection) {
        var sceneLayout = this.scene.fullSceneLayout;
        var dataScale = this.scene.dataScale;
        function fromDataScale(v, axisName) {
          var ax = sceneLayout[axisName];
          var scale = dataScale[axisName2scaleIndex[axisName]];
          return ax.l2c(v) / scale;
        }
        if (selection.object === this.mesh) {
          var pos = selection.data.position;
          var uvx = selection.data.velocity;
          selection.traceCoordinate = [
            fromDataScale(pos[0], "xaxis"),
            fromDataScale(pos[1], "yaxis"),
            fromDataScale(pos[2], "zaxis"),
            fromDataScale(uvx[0], "xaxis"),
            fromDataScale(uvx[1], "yaxis"),
            fromDataScale(uvx[2], "zaxis"),
            // u/v/w norm
            selection.data.intensity * this.data._normMax,
            // divergence
            selection.data.divergence
          ];
          selection.textLabel = this.data.hovertext || this.data.text;
          return true;
        }
      };
      function getDfltStartingPositions(vec) {
        var len = vec.length;
        var s;
        if (len > 2) {
          s = vec.slice(1, len - 1);
        } else if (len === 2) {
          s = [(vec[0] + vec[1]) / 2];
        } else {
          s = vec;
        }
        return s;
      }
      function getBoundPads(vec) {
        var len = vec.length;
        if (len === 1) {
          return [0.5, 0.5];
        } else {
          return [vec[1] - vec[0], vec[len - 1] - vec[len - 2]];
        }
      }
      function convert(scene, trace) {
        var sceneLayout = scene.fullSceneLayout;
        var dataScale = scene.dataScale;
        var len = trace._len;
        var tubeOpts = {};
        function toDataCoords(arr, axisName) {
          var ax = sceneLayout[axisName];
          var scale = dataScale[axisName2scaleIndex[axisName]];
          return Lib.simpleMap(arr, function(v) {
            return ax.d2l(v) * scale;
          });
        }
        tubeOpts.vectors = zip3(
          toDataCoords(trace._u, "xaxis"),
          toDataCoords(trace._v, "yaxis"),
          toDataCoords(trace._w, "zaxis"),
          len
        );
        if (!len) {
          return {
            positions: [],
            cells: []
          };
        }
        var meshx = toDataCoords(trace._Xs, "xaxis");
        var meshy = toDataCoords(trace._Ys, "yaxis");
        var meshz = toDataCoords(trace._Zs, "zaxis");
        tubeOpts.meshgrid = [meshx, meshy, meshz];
        tubeOpts.gridFill = trace._gridFill;
        var slen = trace._slen;
        if (slen) {
          tubeOpts.startingPositions = zip3(
            toDataCoords(trace._startsX, "xaxis"),
            toDataCoords(trace._startsY, "yaxis"),
            toDataCoords(trace._startsZ, "zaxis")
          );
        } else {
          var sy0 = meshy[0];
          var sx = getDfltStartingPositions(meshx);
          var sz = getDfltStartingPositions(meshz);
          var startingPositions = new Array(sx.length * sz.length);
          var m = 0;
          for (var i = 0; i < sx.length; i++) {
            for (var k = 0; k < sz.length; k++) {
              startingPositions[m++] = [sx[i], sy0, sz[k]];
            }
          }
          tubeOpts.startingPositions = startingPositions;
        }
        tubeOpts.colormap = parseColorScale(trace);
        tubeOpts.tubeSize = trace.sizeref;
        tubeOpts.maxLength = trace.maxdisplayed;
        var xbnds = toDataCoords(trace._xbnds, "xaxis");
        var ybnds = toDataCoords(trace._ybnds, "yaxis");
        var zbnds = toDataCoords(trace._zbnds, "zaxis");
        var xpads = getBoundPads(meshx);
        var ypads = getBoundPads(meshy);
        var zpads = getBoundPads(meshz);
        var bounds = [
          [xbnds[0] - xpads[0], ybnds[0] - ypads[0], zbnds[0] - zpads[0]],
          [xbnds[1] + xpads[1], ybnds[1] + ypads[1], zbnds[1] + zpads[1]]
        ];
        var meshData = tube2mesh(tubeOpts, bounds);
        var cOpts = extractOpts(trace);
        meshData.vertexIntensityBounds = [cOpts.min / trace._normMax, cOpts.max / trace._normMax];
        var lp = trace.lightposition;
        meshData.lightPosition = [lp.x, lp.y, lp.z];
        meshData.ambient = trace.lighting.ambient;
        meshData.diffuse = trace.lighting.diffuse;
        meshData.specular = trace.lighting.specular;
        meshData.roughness = trace.lighting.roughness;
        meshData.fresnel = trace.lighting.fresnel;
        meshData.opacity = trace.opacity;
        trace._pad = meshData.tubeScale * trace.sizeref * 2;
        return meshData;
      }
      proto.update = function(data) {
        this.data = data;
        var meshData = convert(this.scene, data);
        this.mesh.update(meshData);
      };
      proto.dispose = function() {
        this.scene.glplot.remove(this.mesh);
        this.mesh.dispose();
      };
      function createStreamtubeTrace(scene, data) {
        var gl2 = scene.glplot.gl;
        var meshData = convert(scene, data);
        var mesh = createTubeMesh(gl2, meshData);
        var streamtube = new Streamtube(scene, data.uid);
        streamtube.mesh = mesh;
        streamtube.data = data;
        mesh._trace = streamtube;
        scene.glplot.add(mesh);
        return streamtube;
      }
      module.exports = createStreamtubeTrace;
    }
  });

  // src/traces/streamtube/index.js
  var require_streamtube = __commonJS({
    "src/traces/streamtube/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "streamtube",
        basePlotModule: require_gl3d(),
        categories: ["gl3d", "showLegend"],
        attributes: require_attributes47(),
        supplyDefaults: require_defaults43(),
        colorbar: {
          min: "cmin",
          max: "cmax"
        },
        calc: require_calc23().calc,
        plot: require_convert9(),
        eventData: function(out, pt) {
          out.tubex = out.x;
          out.tubey = out.y;
          out.tubez = out.z;
          out.tubeu = pt.traceCoordinate[3];
          out.tubev = pt.traceCoordinate[4];
          out.tubew = pt.traceCoordinate[5];
          out.norm = pt.traceCoordinate[6];
          out.divergence = pt.traceCoordinate[7];
          delete out.x;
          delete out.y;
          delete out.z;
          return out;
        },
        meta: {}
      };
    }
  });

  // lib/streamtube.js
  var require_streamtube2 = __commonJS({
    "lib/streamtube.js"(exports, module) {
      "use strict";
      module.exports = require_streamtube();
    }
  });

  // src/traces/scattergeo/attributes.js
  var require_attributes48 = __commonJS({
    "src/traces/scattergeo/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterAttrs = require_attributes12();
      var baseAttrs = require_attributes2();
      var colorAttributes = require_attributes8();
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterLineAttrs = scatterAttrs.line;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      var breakingChangeWarning = [
        "The library used by the *country names* `locationmode` option is changing in an upcoming version.",
        "Country names in existing plots may not work in the new version."
      ].join(" ");
      module.exports = overrideAll(
        {
          lon: {
            valType: "data_array"
          },
          lat: {
            valType: "data_array"
          },
          locations: {
            valType: "data_array"
          },
          locationmode: {
            valType: "enumerated",
            values: ["ISO-3", "USA-states", "country names", "geojson-id"],
            dflt: "ISO-3"
          },
          geojson: {
            valType: "any",
            editType: "calc"
          },
          featureidkey: {
            valType: "string",
            editType: "calc",
            dflt: "id"
          },
          mode: extendFlat({}, scatterAttrs.mode, { dflt: "markers" }),
          text: extendFlat({}, scatterAttrs.text, {}),
          texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["lat", "lon", "location", "text"] }),
          texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
          hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
          textfont: scatterAttrs.textfont,
          textposition: scatterAttrs.textposition,
          line: {
            color: scatterLineAttrs.color,
            width: scatterLineAttrs.width,
            dash
          },
          connectgaps: scatterAttrs.connectgaps,
          marker: extendFlat(
            {
              symbol: scatterMarkerAttrs.symbol,
              opacity: scatterMarkerAttrs.opacity,
              angle: scatterMarkerAttrs.angle,
              angleref: extendFlat({}, scatterMarkerAttrs.angleref, {
                values: ["previous", "up", "north"]
              }),
              standoff: scatterMarkerAttrs.standoff,
              size: scatterMarkerAttrs.size,
              sizeref: scatterMarkerAttrs.sizeref,
              sizemin: scatterMarkerAttrs.sizemin,
              sizemode: scatterMarkerAttrs.sizemode,
              colorbar: scatterMarkerAttrs.colorbar,
              line: extendFlat(
                {
                  width: scatterMarkerLineAttrs.width,
                  dash: scatterMarkerLineAttrs.dash
                },
                colorAttributes("marker.line")
              ),
              gradient: scatterMarkerAttrs.gradient
            },
            colorAttributes("marker")
          ),
          fill: {
            valType: "enumerated",
            values: ["none", "toself"],
            dflt: "none"
          },
          fillcolor: makeFillcolorAttr(),
          selected: scatterAttrs.selected,
          unselected: scatterAttrs.unselected,
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
            flags: ["lon", "lat", "location", "text", "name"]
          }),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs()
        },
        "calc",
        "nested"
      );
    }
  });

  // src/traces/scattergeo/defaults.js
  var require_defaults44 = __commonJS({
    "src/traces/scattergeo/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var attributes = require_attributes48();
      var locationmodeBreakingChangeWarning = [
        "The library used by the *country names* `locationmode` option is changing in the next major version.",
        "Some country names in existing plots may not work in the new version.",
        "To ensure consistent behavior, consider setting `locationmode` to *ISO-3*."
      ].join(" ");
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var locations = coerce("locations");
        var len;
        if (locations && locations.length) {
          var geojson = coerce("geojson");
          var locationmodeDflt;
          if (typeof geojson === "string" && geojson !== "" || Lib.isPlainObject(geojson)) {
            locationmodeDflt = "geojson-id";
          }
          var locationMode = coerce("locationmode", locationmodeDflt);
          if (locationMode === "country names") {
            Lib.warn(locationmodeBreakingChangeWarning);
          }
          if (locationMode === "geojson-id") {
            coerce("featureidkey");
          }
          len = locations.length;
        } else {
          var lon = coerce("lon") || [];
          var lat = coerce("lat") || [];
          len = Math.min(lon.length, lat.length);
        }
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("mode");
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { gradient: true });
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
          coerce("connectgaps");
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce);
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        }
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/scattergeo/format_labels.js
  var require_format_labels3 = __commonJS({
    "src/traces/scattergeo/format_labels.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var labels = {};
        var geo = fullLayout[trace.geo]._subplot;
        var ax = geo.mockAxis;
        var lonlat = cdi.lonlat;
        labels.lonLabel = Axes.tickText(ax, ax.c2l(lonlat[0]), true).text;
        labels.latLabel = Axes.tickText(ax, ax.c2l(lonlat[1]), true).text;
        return labels;
      };
    }
  });

  // src/traces/scattergeo/calc.js
  var require_calc27 = __commonJS({
    "src/traces/scattergeo/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var BADNUM = require_numerical().BADNUM;
      var calcMarkerColorscale = require_colorscale_calc();
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcSelection = require_calc_selection();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var _ = require_lib()._;
      function isNonBlankString(v) {
        return v && typeof v === "string";
      }
      module.exports = function calc(gd, trace) {
        var hasLocationData = isArrayOrTypedArray(trace.locations);
        var len = hasLocationData ? trace.locations.length : trace._length;
        var calcTrace = new Array(len);
        var isValidLoc;
        if (trace.geojson) {
          isValidLoc = function(v) {
            return isNonBlankString(v) || isNumeric(v);
          };
        } else {
          isValidLoc = isNonBlankString;
        }
        for (var i = 0; i < len; i++) {
          var calcPt = calcTrace[i] = {};
          if (hasLocationData) {
            var loc = trace.locations[i];
            calcPt.loc = isValidLoc(loc) ? loc : null;
          } else {
            var lon = trace.lon[i];
            var lat = trace.lat[i];
            if (isNumeric(lon) && isNumeric(lat)) calcPt.lonlat = [+lon, +lat];
            else calcPt.lonlat = [BADNUM, BADNUM];
          }
        }
        arraysToCalcdata(calcTrace, trace);
        calcMarkerColorscale(gd, trace);
        calcSelection(calcTrace, trace);
        if (len) {
          calcTrace[0].t = {
            labels: {
              lat: _(gd, "lat:") + " ",
              lon: _(gd, "lon:") + " "
            }
          };
        }
        return calcTrace;
      };
    }
  });

  // src/plots/geo/constants.js
  var require_constants22 = __commonJS({
    "src/plots/geo/constants.js"(exports) {
      "use strict";
      exports.projNames = {
        airy: "airy",
        aitoff: "aitoff",
        "albers usa": "albersUsa",
        albers: "albers",
        // 'armadillo': 'armadillo',
        august: "august",
        "azimuthal equal area": "azimuthalEqualArea",
        "azimuthal equidistant": "azimuthalEquidistant",
        baker: "baker",
        // 'berghaus': 'berghaus',
        bertin1953: "bertin1953",
        boggs: "boggs",
        bonne: "bonne",
        bottomley: "bottomley",
        bromley: "bromley",
        // 'chamberlin africa': 'chamberlinAfrica',
        // 'chamberlin': 'chamberlin',
        collignon: "collignon",
        "conic conformal": "conicConformal",
        "conic equal area": "conicEqualArea",
        "conic equidistant": "conicEquidistant",
        craig: "craig",
        craster: "craster",
        "cylindrical equal area": "cylindricalEqualArea",
        "cylindrical stereographic": "cylindricalStereographic",
        eckert1: "eckert1",
        eckert2: "eckert2",
        eckert3: "eckert3",
        eckert4: "eckert4",
        eckert5: "eckert5",
        eckert6: "eckert6",
        eisenlohr: "eisenlohr",
        "equal earth": "equalEarth",
        equirectangular: "equirectangular",
        fahey: "fahey",
        "foucaut sinusoidal": "foucautSinusoidal",
        foucaut: "foucaut",
        // 'gilbert': 'gilbert',
        // 'gingery': 'gingery',
        ginzburg4: "ginzburg4",
        ginzburg5: "ginzburg5",
        ginzburg6: "ginzburg6",
        ginzburg8: "ginzburg8",
        ginzburg9: "ginzburg9",
        gnomonic: "gnomonic",
        "gringorten quincuncial": "gringortenQuincuncial",
        gringorten: "gringorten",
        guyou: "guyou",
        // 'hammer retroazimuthal': 'hammerRetroazimuthal',
        hammer: "hammer",
        // 'healpix': 'healpix',
        hill: "hill",
        homolosine: "homolosine",
        hufnagel: "hufnagel",
        hyperelliptical: "hyperelliptical",
        // 'interrupted boggs': 'interruptedBoggs',
        // 'interrupted homolosine': 'interruptedHomolosine',
        // 'interrupted mollweide hemispheres': 'interruptedMollweideHemispheres',
        // 'interrupted mollweide': 'interruptedMollweide',
        // 'interrupted quartic authalic': 'interruptedQuarticAuthalic',
        // 'interrupted sinu mollweide': 'interruptedSinuMollweide',
        // 'interrupted sinusoidal': 'interruptedSinusoidal',
        kavrayskiy7: "kavrayskiy7",
        lagrange: "lagrange",
        larrivee: "larrivee",
        laskowski: "laskowski",
        // 'littrow': 'littrow',
        loximuthal: "loximuthal",
        mercator: "mercator",
        miller: "miller",
        // 'modified stereographic alaska': 'modifiedStereographicAlaska',
        // 'modified stereographic gs48': 'modifiedStereographicGs48',
        // 'modified stereographic gs50': 'modifiedStereographicGs50',
        // 'modified stereographic lee': 'modifiedStereographicLee',
        // 'modified stereographic miller': 'modifiedStereographicMiller',
        // 'modified stereographic': 'modifiedStereographic',
        mollweide: "mollweide",
        "mt flat polar parabolic": "mtFlatPolarParabolic",
        "mt flat polar quartic": "mtFlatPolarQuartic",
        "mt flat polar sinusoidal": "mtFlatPolarSinusoidal",
        "natural earth": "naturalEarth",
        "natural earth1": "naturalEarth1",
        "natural earth2": "naturalEarth2",
        "nell hammer": "nellHammer",
        nicolosi: "nicolosi",
        orthographic: "orthographic",
        patterson: "patterson",
        "peirce quincuncial": "peirceQuincuncial",
        polyconic: "polyconic",
        // 'polyhedral butterfly': 'polyhedralButterfly',
        // 'polyhedral collignon': 'polyhedralCollignon',
        // 'polyhedral waterman': 'polyhedralWaterman',
        "rectangular polyconic": "rectangularPolyconic",
        robinson: "robinson",
        satellite: "satellite",
        "sinu mollweide": "sinuMollweide",
        sinusoidal: "sinusoidal",
        stereographic: "stereographic",
        times: "times",
        "transverse mercator": "transverseMercator",
        // 'two point azimuthalUsa': 'twoPointAzimuthalUsa',
        // 'two point azimuthal': 'twoPointAzimuthal',
        // 'two point equidistantUsa': 'twoPointEquidistantUsa',
        // 'two point equidistant': 'twoPointEquidistant',
        "van der grinten": "vanDerGrinten",
        "van der grinten2": "vanDerGrinten2",
        "van der grinten3": "vanDerGrinten3",
        "van der grinten4": "vanDerGrinten4",
        wagner4: "wagner4",
        wagner6: "wagner6",
        // 'wagner7': 'wagner7',
        // 'wagner': 'wagner',
        wiechel: "wiechel",
        "winkel tripel": "winkel3",
        winkel3: "winkel3"
      };
      exports.axesNames = ["lonaxis", "lataxis"];
      exports.lonaxisSpan = {
        orthographic: 180,
        "azimuthal equal area": 360,
        "azimuthal equidistant": 360,
        "conic conformal": 180,
        gnomonic: 160,
        stereographic: 180,
        "transverse mercator": 180,
        "*": 360
      };
      exports.lataxisSpan = {
        "conic conformal": 150,
        stereographic: 179.5,
        "*": 180
      };
      exports.scopeDefaults = {
        world: {
          lonaxisRange: [-180, 180],
          lataxisRange: [-90, 90],
          projType: "equirectangular",
          projRotate: [0, 0, 0]
        },
        usa: {
          lonaxisRange: [-180, -50],
          lataxisRange: [15, 80],
          projType: "albers usa"
        },
        europe: {
          lonaxisRange: [-30, 60],
          lataxisRange: [30, 85],
          projType: "conic conformal",
          projRotate: [15, 0, 0],
          projParallels: [0, 60]
        },
        asia: {
          lonaxisRange: [22, 160],
          lataxisRange: [-15, 55],
          projType: "mercator",
          projRotate: [0, 0, 0]
        },
        africa: {
          lonaxisRange: [-30, 60],
          lataxisRange: [-40, 40],
          projType: "mercator",
          projRotate: [0, 0, 0]
        },
        "north america": {
          lonaxisRange: [-180, -45],
          lataxisRange: [5, 85],
          projType: "conic conformal",
          projRotate: [-100, 0, 0],
          projParallels: [29.5, 45.5]
        },
        "south america": {
          lonaxisRange: [-100, -30],
          lataxisRange: [-60, 15],
          projType: "mercator",
          projRotate: [0, 0, 0]
        },
        antarctica: {
          lonaxisRange: [-180, 180],
          lataxisRange: [-90, -60],
          projType: "equirectangular",
          projRotate: [0, 0, 0]
        },
        oceania: {
          lonaxisRange: [-180, 180],
          lataxisRange: [-50, 25],
          projType: "equirectangular",
          projRotate: [0, 0, 0]
        }
      };
      exports.clipPad = 1e-3;
      exports.precision = 0.1;
      exports.landColor = "#F0DC82";
      exports.waterColor = "#3399FF";
      exports.locationmodeToLayer = {
        "ISO-3": "countries",
        "USA-states": "subunits",
        "country names": "countries"
      };
      exports.sphereSVG = { type: "Sphere" };
      exports.fillLayers = {
        ocean: 1,
        land: 1,
        lakes: 1
      };
      exports.lineLayers = {
        subunits: 1,
        countries: 1,
        coastlines: 1,
        rivers: 1,
        frame: 1
      };
      exports.layers = [
        "bg",
        "ocean",
        "land",
        "lakes",
        "subunits",
        "countries",
        "coastlines",
        "rivers",
        "lataxis",
        "lonaxis",
        "frame",
        "backplot",
        "frontplot"
      ];
      exports.layersForChoropleth = [
        "bg",
        "ocean",
        "land",
        "subunits",
        "countries",
        "coastlines",
        "lataxis",
        "lonaxis",
        "frame",
        "backplot",
        "rivers",
        "lakes",
        "frontplot"
      ];
      exports.layerNameToAdjective = {
        ocean: "ocean",
        land: "land",
        lakes: "lake",
        subunits: "subunit",
        countries: "country",
        coastlines: "coastline",
        rivers: "river",
        frame: "frame"
      };
    }
  });

  // node_modules/topojson-client/dist/topojson-client.js
  var require_topojson_client = __commonJS({
    "node_modules/topojson-client/dist/topojson-client.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.topojson = global2.topojson || {}));
      })(exports, function(exports2) {
        "use strict";
        function identity2(x) {
          return x;
        }
        function transform(transform2) {
          if (transform2 == null) return identity2;
          var x0, y0, kx = transform2.scale[0], ky = transform2.scale[1], dx = transform2.translate[0], dy = transform2.translate[1];
          return function(input, i) {
            if (!i) x0 = y0 = 0;
            var j = 2, n = input.length, output = new Array(n);
            output[0] = (x0 += input[0]) * kx + dx;
            output[1] = (y0 += input[1]) * ky + dy;
            while (j < n) output[j] = input[j], ++j;
            return output;
          };
        }
        function bbox(topology) {
          var t = transform(topology.transform), key, x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0;
          function bboxPoint(p) {
            p = t(p);
            if (p[0] < x0) x0 = p[0];
            if (p[0] > x1) x1 = p[0];
            if (p[1] < y0) y0 = p[1];
            if (p[1] > y1) y1 = p[1];
          }
          function bboxGeometry(o) {
            switch (o.type) {
              case "GeometryCollection":
                o.geometries.forEach(bboxGeometry);
                break;
              case "Point":
                bboxPoint(o.coordinates);
                break;
              case "MultiPoint":
                o.coordinates.forEach(bboxPoint);
                break;
            }
          }
          topology.arcs.forEach(function(arc) {
            var i = -1, n = arc.length, p;
            while (++i < n) {
              p = t(arc[i], i);
              if (p[0] < x0) x0 = p[0];
              if (p[0] > x1) x1 = p[0];
              if (p[1] < y0) y0 = p[1];
              if (p[1] > y1) y1 = p[1];
            }
          });
          for (key in topology.objects) {
            bboxGeometry(topology.objects[key]);
          }
          return [x0, y0, x1, y1];
        }
        function reverse(array, n) {
          var t, j = array.length, i = j - n;
          while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
        }
        function feature(topology, o) {
          if (typeof o === "string") o = topology.objects[o];
          return o.type === "GeometryCollection" ? { type: "FeatureCollection", features: o.geometries.map(function(o2) {
            return feature$1(topology, o2);
          }) } : feature$1(topology, o);
        }
        function feature$1(topology, o) {
          var id = o.id, bbox2 = o.bbox, properties = o.properties == null ? {} : o.properties, geometry = object(topology, o);
          return id == null && bbox2 == null ? { type: "Feature", properties, geometry } : bbox2 == null ? { type: "Feature", id, properties, geometry } : { type: "Feature", id, bbox: bbox2, properties, geometry };
        }
        function object(topology, o) {
          var transformPoint = transform(topology.transform), arcs = topology.arcs;
          function arc(i, points) {
            if (points.length) points.pop();
            for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) {
              points.push(transformPoint(a[k], k));
            }
            if (i < 0) reverse(points, n);
          }
          function point(p) {
            return transformPoint(p);
          }
          function line(arcs2) {
            var points = [];
            for (var i = 0, n = arcs2.length; i < n; ++i) arc(arcs2[i], points);
            if (points.length < 2) points.push(points[0]);
            return points;
          }
          function ring(arcs2) {
            var points = line(arcs2);
            while (points.length < 4) points.push(points[0]);
            return points;
          }
          function polygon(arcs2) {
            return arcs2.map(ring);
          }
          function geometry(o2) {
            var type = o2.type, coordinates;
            switch (type) {
              case "GeometryCollection":
                return { type, geometries: o2.geometries.map(geometry) };
              case "Point":
                coordinates = point(o2.coordinates);
                break;
              case "MultiPoint":
                coordinates = o2.coordinates.map(point);
                break;
              case "LineString":
                coordinates = line(o2.arcs);
                break;
              case "MultiLineString":
                coordinates = o2.arcs.map(line);
                break;
              case "Polygon":
                coordinates = polygon(o2.arcs);
                break;
              case "MultiPolygon":
                coordinates = o2.arcs.map(polygon);
                break;
              default:
                return null;
            }
            return { type, coordinates };
          }
          return geometry(o);
        }
        function stitch(topology, arcs) {
          var stitchedArcs = {}, fragmentByStart = {}, fragmentByEnd = {}, fragments = [], emptyIndex = -1;
          arcs.forEach(function(i, j) {
            var arc = topology.arcs[i < 0 ? ~i : i], t;
            if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
              t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
            }
          });
          arcs.forEach(function(i) {
            var e = ends(i), start = e[0], end = e[1], f, g;
            if (f = fragmentByEnd[start]) {
              delete fragmentByEnd[f.end];
              f.push(i);
              f.end = end;
              if (g = fragmentByStart[end]) {
                delete fragmentByStart[g.start];
                var fg = g === f ? f : f.concat(g);
                fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
              } else {
                fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
              }
            } else if (f = fragmentByStart[end]) {
              delete fragmentByStart[f.start];
              f.unshift(i);
              f.start = start;
              if (g = fragmentByEnd[start]) {
                delete fragmentByEnd[g.end];
                var gf = g === f ? f : g.concat(f);
                fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
              } else {
                fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
              }
            } else {
              f = [i];
              fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
            }
          });
          function ends(i) {
            var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
            if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) {
              p1[0] += dp[0], p1[1] += dp[1];
            });
            else p1 = arc[arc.length - 1];
            return i < 0 ? [p1, p0] : [p0, p1];
          }
          function flush(fragmentByEnd2, fragmentByStart2) {
            for (var k in fragmentByEnd2) {
              var f = fragmentByEnd2[k];
              delete fragmentByStart2[f.start];
              delete f.start;
              delete f.end;
              f.forEach(function(i) {
                stitchedArcs[i < 0 ? ~i : i] = 1;
              });
              fragments.push(f);
            }
          }
          flush(fragmentByEnd, fragmentByStart);
          flush(fragmentByStart, fragmentByEnd);
          arcs.forEach(function(i) {
            if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]);
          });
          return fragments;
        }
        function mesh(topology) {
          return object(topology, meshArcs.apply(this, arguments));
        }
        function meshArcs(topology, object2, filter) {
          var arcs, i, n;
          if (arguments.length > 1) arcs = extractArcs(topology, object2, filter);
          else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i;
          return { type: "MultiLineString", arcs: stitch(topology, arcs) };
        }
        function extractArcs(topology, object2, filter) {
          var arcs = [], geomsByArc = [], geom;
          function extract0(i) {
            var j = i < 0 ? ~i : i;
            (geomsByArc[j] || (geomsByArc[j] = [])).push({ i, g: geom });
          }
          function extract1(arcs2) {
            arcs2.forEach(extract0);
          }
          function extract2(arcs2) {
            arcs2.forEach(extract1);
          }
          function extract3(arcs2) {
            arcs2.forEach(extract2);
          }
          function geometry(o) {
            switch (geom = o, o.type) {
              case "GeometryCollection":
                o.geometries.forEach(geometry);
                break;
              case "LineString":
                extract1(o.arcs);
                break;
              case "MultiLineString":
              case "Polygon":
                extract2(o.arcs);
                break;
              case "MultiPolygon":
                extract3(o.arcs);
                break;
            }
          }
          geometry(object2);
          geomsByArc.forEach(filter == null ? function(geoms) {
            arcs.push(geoms[0].i);
          } : function(geoms) {
            if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i);
          });
          return arcs;
        }
        function planarRingArea(ring) {
          var i = -1, n = ring.length, a, b = ring[n - 1], area = 0;
          while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0];
          return Math.abs(area);
        }
        function merge(topology) {
          return object(topology, mergeArcs.apply(this, arguments));
        }
        function mergeArcs(topology, objects) {
          var polygonsByArc = {}, polygons = [], groups = [];
          objects.forEach(geometry);
          function geometry(o) {
            switch (o.type) {
              case "GeometryCollection":
                o.geometries.forEach(geometry);
                break;
              case "Polygon":
                extract(o.arcs);
                break;
              case "MultiPolygon":
                o.arcs.forEach(extract);
                break;
            }
          }
          function extract(polygon) {
            polygon.forEach(function(ring) {
              ring.forEach(function(arc) {
                (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
              });
            });
            polygons.push(polygon);
          }
          function area(ring) {
            return planarRingArea(object(topology, { type: "Polygon", arcs: [ring] }).coordinates[0]);
          }
          polygons.forEach(function(polygon) {
            if (!polygon._) {
              var group = [], neighbors2 = [polygon];
              polygon._ = 1;
              groups.push(group);
              while (polygon = neighbors2.pop()) {
                group.push(polygon);
                polygon.forEach(function(ring) {
                  ring.forEach(function(arc) {
                    polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon2) {
                      if (!polygon2._) {
                        polygon2._ = 1;
                        neighbors2.push(polygon2);
                      }
                    });
                  });
                });
              }
            }
          });
          polygons.forEach(function(polygon) {
            delete polygon._;
          });
          return {
            type: "MultiPolygon",
            arcs: groups.map(function(polygons2) {
              var arcs = [], n;
              polygons2.forEach(function(polygon) {
                polygon.forEach(function(ring) {
                  ring.forEach(function(arc) {
                    if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
                      arcs.push(arc);
                    }
                  });
                });
              });
              arcs = stitch(topology, arcs);
              if ((n = arcs.length) > 1) {
                for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) {
                  if ((ki = area(arcs[i])) > k) {
                    t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki;
                  }
                }
              }
              return arcs;
            }).filter(function(arcs) {
              return arcs.length > 0;
            })
          };
        }
        function bisect(a, x) {
          var lo = 0, hi = a.length;
          while (lo < hi) {
            var mid = lo + hi >>> 1;
            if (a[mid] < x) lo = mid + 1;
            else hi = mid;
          }
          return lo;
        }
        function neighbors(objects) {
          var indexesByArc = {}, neighbors2 = objects.map(function() {
            return [];
          });
          function line(arcs, i2) {
            arcs.forEach(function(a) {
              if (a < 0) a = ~a;
              var o = indexesByArc[a];
              if (o) o.push(i2);
              else indexesByArc[a] = [i2];
            });
          }
          function polygon(arcs, i2) {
            arcs.forEach(function(arc) {
              line(arc, i2);
            });
          }
          function geometry(o, i2) {
            if (o.type === "GeometryCollection") o.geometries.forEach(function(o2) {
              geometry(o2, i2);
            });
            else if (o.type in geometryType) geometryType[o.type](o.arcs, i2);
          }
          var geometryType = {
            LineString: line,
            MultiLineString: polygon,
            Polygon: polygon,
            MultiPolygon: function(arcs, i2) {
              arcs.forEach(function(arc) {
                polygon(arc, i2);
              });
            }
          };
          objects.forEach(geometry);
          for (var i in indexesByArc) {
            for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
              for (var k = j + 1; k < m; ++k) {
                var ij = indexes[j], ik = indexes[k], n;
                if ((n = neighbors2[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik);
                if ((n = neighbors2[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij);
              }
            }
          }
          return neighbors2;
        }
        function untransform(transform2) {
          if (transform2 == null) return identity2;
          var x0, y0, kx = transform2.scale[0], ky = transform2.scale[1], dx = transform2.translate[0], dy = transform2.translate[1];
          return function(input, i) {
            if (!i) x0 = y0 = 0;
            var j = 2, n = input.length, output = new Array(n), x1 = Math.round((input[0] - dx) / kx), y1 = Math.round((input[1] - dy) / ky);
            output[0] = x1 - x0, x0 = x1;
            output[1] = y1 - y0, y0 = y1;
            while (j < n) output[j] = input[j], ++j;
            return output;
          };
        }
        function quantize(topology, transform2) {
          if (topology.transform) throw new Error("already quantized");
          if (!transform2 || !transform2.scale) {
            if (!((n = Math.floor(transform2)) >= 2)) throw new Error("n must be \u22652");
            box = topology.bbox || bbox(topology);
            var x0 = box[0], y0 = box[1], x1 = box[2], y1 = box[3], n;
            transform2 = { scale: [x1 - x0 ? (x1 - x0) / (n - 1) : 1, y1 - y0 ? (y1 - y0) / (n - 1) : 1], translate: [x0, y0] };
          } else {
            box = topology.bbox;
          }
          var t = untransform(transform2), box, key, inputs = topology.objects, outputs = {};
          function quantizePoint(point) {
            return t(point);
          }
          function quantizeGeometry(input) {
            var output;
            switch (input.type) {
              case "GeometryCollection":
                output = { type: "GeometryCollection", geometries: input.geometries.map(quantizeGeometry) };
                break;
              case "Point":
                output = { type: "Point", coordinates: quantizePoint(input.coordinates) };
                break;
              case "MultiPoint":
                output = { type: "MultiPoint", coordinates: input.coordinates.map(quantizePoint) };
                break;
              default:
                return input;
            }
            if (input.id != null) output.id = input.id;
            if (input.bbox != null) output.bbox = input.bbox;
            if (input.properties != null) output.properties = input.properties;
            return output;
          }
          function quantizeArc(input) {
            var i = 0, j = 1, n2 = input.length, p, output = new Array(n2);
            output[0] = t(input[0], 0);
            while (++i < n2) if ((p = t(input[i], i))[0] || p[1]) output[j++] = p;
            if (j === 1) output[j++] = [0, 0];
            output.length = j;
            return output;
          }
          for (key in inputs) outputs[key] = quantizeGeometry(inputs[key]);
          return {
            type: "Topology",
            bbox: box,
            transform: transform2,
            objects: outputs,
            arcs: topology.arcs.map(quantizeArc)
          };
        }
        exports2.bbox = bbox;
        exports2.feature = feature;
        exports2.merge = merge;
        exports2.mergeArcs = mergeArcs;
        exports2.mesh = mesh;
        exports2.meshArcs = meshArcs;
        exports2.neighbors = neighbors;
        exports2.quantize = quantize;
        exports2.transform = transform;
        exports2.untransform = untransform;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // src/lib/topojson_utils.js
  var require_topojson_utils = __commonJS({
    "src/lib/topojson_utils.js"(exports, module) {
      "use strict";
      var topojsonUtils = module.exports = {};
      var locationmodeToLayer = require_constants22().locationmodeToLayer;
      var topojsonFeature = require_topojson_client().feature;
      topojsonUtils.getTopojsonName = function(geoLayout) {
        return [
          geoLayout.scope.replace(/ /g, "-"),
          "_",
          geoLayout.resolution.toString(),
          "m"
        ].join("");
      };
      topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) {
        topojsonURL += topojsonURL.endsWith("/") ? "" : "/";
        return `${topojsonURL}${topojsonName}.json`;
      };
      topojsonUtils.getTopojsonFeatures = function(trace, topojson) {
        var layer = locationmodeToLayer[trace.locationmode];
        var obj = topojson.objects[layer];
        return topojsonFeature(topojson, obj).features;
      };
    }
  });

  // src/lib/geojson_utils.js
  var require_geojson_utils = __commonJS({
    "src/lib/geojson_utils.js"(exports) {
      "use strict";
      var BADNUM = require_numerical().BADNUM;
      exports.calcTraceToLineCoords = function(calcTrace) {
        var trace = calcTrace[0].trace;
        var connectgaps = trace.connectgaps;
        var coords = [];
        var lineString = [];
        for (var i = 0; i < calcTrace.length; i++) {
          var calcPt = calcTrace[i];
          var lonlat = calcPt.lonlat;
          if (lonlat[0] !== BADNUM) {
            lineString.push(lonlat);
          } else if (!connectgaps && lineString.length > 0) {
            coords.push(lineString);
            lineString = [];
          }
        }
        if (lineString.length > 0) {
          coords.push(lineString);
        }
        return coords;
      };
      exports.makeLine = function(coords) {
        if (coords.length === 1) {
          return {
            type: "LineString",
            coordinates: coords[0]
          };
        } else {
          return {
            type: "MultiLineString",
            coordinates: coords
          };
        }
      };
      exports.makePolygon = function(coords) {
        if (coords.length === 1) {
          return {
            type: "Polygon",
            coordinates: coords
          };
        } else {
          var _coords = new Array(coords.length);
          for (var i = 0; i < coords.length; i++) {
            _coords[i] = [coords[i]];
          }
          return {
            type: "MultiPolygon",
            coordinates: _coords
          };
        }
      };
      exports.makeBlank = function() {
        return {
          type: "Point",
          coordinates: []
        };
      };
    }
  });

  // node_modules/country-regex/index.js
  var require_country_regex = __commonJS({
    "node_modules/country-regex/index.js"(exports, module) {
      module.exports = {
        AFG: "afghan",
        ALA: "\\b\\wland",
        ALB: "albania",
        DZA: "algeria",
        ASM: "^(?=.*americ).*samoa",
        AND: "andorra",
        AGO: "angola",
        AIA: "anguill?a",
        ATA: "antarctica",
        ATG: "antigua",
        ARG: "argentin",
        ARM: "armenia",
        ABW: "^(?!.*bonaire).*\\baruba",
        AUS: "australia",
        AUT: "^(?!.*hungary).*austria|\\baustri.*\\bemp",
        AZE: "azerbaijan",
        BHS: "bahamas",
        BHR: "bahrain",
        BGD: "bangladesh|^(?=.*east).*paki?stan",
        BRB: "barbados",
        BLR: "belarus|byelo",
        BEL: "^(?!.*luxem).*belgium",
        BLZ: "belize|^(?=.*british).*honduras",
        BEN: "benin|dahome",
        BMU: "bermuda",
        BTN: "bhutan",
        BOL: "bolivia",
        BES: "^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",
        BIH: "herzegovina|bosnia",
        BWA: "botswana|bechuana",
        BVT: "bouvet",
        BRA: "brazil",
        IOT: "british.?indian.?ocean",
        BRN: "brunei",
        BGR: "bulgaria",
        BFA: "burkina|\\bfaso|upper.?volta",
        BDI: "burundi",
        CPV: "verde",
        KHM: "cambodia|kampuchea|khmer",
        CMR: "cameroon",
        CAN: "canada",
        CYM: "cayman",
        CAF: "\\bcentral.african.republic",
        TCD: "\\bchad",
        CHL: "\\bchile",
        CHN: "^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai)(?!.*\\brep).*china|^(?=.*peo)(?=.*rep).*china",
        CXR: "christmas",
        CCK: "\\bcocos|keeling",
        COL: "colombia",
        COM: "comoro",
        COG: "^(?!.*\\bdem)(?!.*\\bd[\\.]?r)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo",
        COK: "\\bcook",
        CRI: "costa.?rica",
        CIV: "ivoire|ivory",
        HRV: "croatia",
        CUB: "\\bcuba",
        CUW: "^(?!.*bonaire).*\\bcura(c|\xE7)ao",
        CYP: "cyprus",
        CSK: "czechoslovakia",
        CZE: "^(?=.*rep).*czech|czechia|bohemia",
        COD: "\\bdem.*congo|congo.*\\bdem|congo.*\\bd[\\.]?r|\\bd[\\.]?r.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc",
        DNK: "denmark",
        DJI: "djibouti",
        DMA: "dominica(?!n)",
        DOM: "dominican.rep",
        ECU: "ecuador",
        EGY: "egypt",
        SLV: "el.?salvador",
        GNQ: "guine.*eq|eq.*guine|^(?=.*span).*guinea",
        ERI: "eritrea",
        EST: "estonia",
        ETH: "ethiopia|abyssinia",
        FLK: "falkland|malvinas",
        FRO: "faroe|faeroe",
        FJI: "fiji",
        FIN: "finland",
        FRA: "^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",
        GUF: "^(?=.*french).*guiana",
        PYF: "french.?polynesia|tahiti",
        ATF: "french.?southern",
        GAB: "gabon",
        GMB: "gambia",
        GEO: "^(?!.*south).*georgia",
        DDR: "german.?democratic.?republic|democratic.?republic.*germany|east.germany",
        DEU: "^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",
        GHA: "ghana|gold.?coast",
        GIB: "gibraltar",
        GRC: "greece|hellenic|hellas",
        GRL: "greenland",
        GRD: "grenada",
        GLP: "guadeloupe",
        GUM: "\\bguam",
        GTM: "guatemala",
        GGY: "guernsey",
        GIN: "^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",
        GNB: "bissau|^(?=.*portu).*guinea",
        GUY: "guyana|british.?guiana",
        HTI: "haiti",
        HMD: "heard.*mcdonald",
        VAT: "holy.?see|vatican|papal.?st",
        HND: "^(?!.*brit).*honduras",
        HKG: "hong.?kong",
        HUN: "^(?!.*austr).*hungary",
        ISL: "iceland",
        IND: "india(?!.*ocea)",
        IDN: "indonesia",
        IRN: "\\biran|persia",
        IRQ: "\\biraq|mesopotamia",
        IRL: "(^ireland)|(^republic.*ireland)",
        IMN: "^(?=.*isle).*\\bman",
        ISR: "israel",
        ITA: "italy",
        JAM: "jamaica",
        JPN: "japan",
        JEY: "jersey",
        JOR: "jordan",
        KAZ: "kazak",
        KEN: "kenya|british.?east.?africa|east.?africa.?prot",
        KIR: "kiribati",
        PRK: "^(?=.*democrat|people|north|d.*p.*.r).*\\bkorea|dprk|korea.*(d.*p.*r)",
        KWT: "kuwait",
        KGZ: "kyrgyz|kirghiz",
        LAO: "\\blaos?\\b",
        LVA: "latvia",
        LBN: "lebanon",
        LSO: "lesotho|basuto",
        LBR: "liberia",
        LBY: "libya",
        LIE: "liechtenstein",
        LTU: "lithuania",
        LUX: "^(?!.*belg).*luxem",
        MAC: "maca(o|u)",
        MDG: "madagascar|malagasy",
        MWI: "malawi|nyasa",
        MYS: "malaysia",
        MDV: "maldive",
        MLI: "\\bmali\\b",
        MLT: "\\bmalta",
        MHL: "marshall",
        MTQ: "martinique",
        MRT: "mauritania",
        MUS: "mauritius",
        MYT: "\\bmayotte",
        MEX: "\\bmexic",
        FSM: "fed.*micronesia|micronesia.*fed",
        MCO: "monaco",
        MNG: "mongolia",
        MNE: "^(?!.*serbia).*montenegro",
        MSR: "montserrat",
        MAR: "morocco|\\bmaroc",
        MOZ: "mozambique",
        MMR: "myanmar|burma",
        NAM: "namibia",
        NRU: "nauru",
        NPL: "nepal",
        NLD: "^(?!.*\\bant)(?!.*\\bcarib).*netherlands",
        ANT: "^(?=.*\\bant).*(nether|dutch)",
        NCL: "new.?caledonia",
        NZL: "new.?zealand",
        NIC: "nicaragua",
        NER: "\\bniger(?!ia)",
        NGA: "nigeria",
        NIU: "niue",
        NFK: "norfolk",
        MNP: "mariana",
        NOR: "norway",
        OMN: "\\boman|trucial",
        PAK: "^(?!.*east).*paki?stan",
        PLW: "palau",
        PSE: "palestin|\\bgaza|west.?bank",
        PAN: "panama",
        PNG: "papua|new.?guinea",
        PRY: "paraguay",
        PER: "peru",
        PHL: "philippines",
        PCN: "pitcairn",
        POL: "poland",
        PRT: "portugal",
        PRI: "puerto.?rico",
        QAT: "qatar",
        KOR: "^(?!.*d.*p.*r)(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea(?!.*d.*p.*r)",
        MDA: "moldov|b(a|e)ssarabia",
        REU: "r(e|\xE9)union",
        ROU: "r(o|u|ou)mania",
        RUS: "\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",
        RWA: "rwanda",
        BLM: "barth(e|\xE9)lemy",
        SHN: "helena",
        KNA: "kitts|\\bnevis",
        LCA: "\\blucia",
        MAF: "^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",
        SPM: "miquelon",
        VCT: "vincent",
        WSM: "^(?!.*amer).*samoa",
        SMR: "san.?marino",
        STP: "\\bs(a|\xE3)o.?tom(e|\xE9)",
        SAU: "\\bsa\\w*.?arabia",
        SEN: "senegal",
        SRB: "^(?!.*monte).*serbia",
        SYC: "seychell",
        SLE: "sierra",
        SGP: "singapore",
        SXM: "^(?!.*martin)(?!.*saba).*maarten",
        SVK: "^(?!.*cze).*slovak",
        SVN: "slovenia",
        SLB: "solomon",
        SOM: "somali",
        ZAF: "south.africa|s\\\\..?africa",
        SGS: "south.?georgia|sandwich",
        SSD: "\\bs\\w*.?sudan",
        ESP: "spain",
        LKA: "sri.?lanka|ceylon",
        SDN: "^(?!.*\\bs(?!u)).*sudan",
        SUR: "surinam|dutch.?guiana",
        SJM: "svalbard",
        SWZ: "swaziland",
        SWE: "sweden",
        CHE: "switz|swiss",
        SYR: "syria",
        TWN: "taiwan|taipei|formosa|^(?!.*peo)(?=.*rep).*china",
        TJK: "tajik",
        THA: "thailand|\\bsiam",
        MKD: "macedonia|fyrom",
        TLS: "^(?=.*leste).*timor|^(?=.*east).*timor",
        TGO: "togo",
        TKL: "tokelau",
        TON: "tonga",
        TTO: "trinidad|tobago",
        TUN: "tunisia",
        TUR: "turkey",
        TKM: "turkmen",
        TCA: "turks",
        TUV: "tuvalu",
        UGA: "uganda",
        UKR: "ukrain",
        ARE: "emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",
        GBR: "united.?kingdom|britain|^u\\.?k\\.?$",
        TZA: "tanzania",
        USA: "united.?states\\b(?!.*islands)|\\bu\\.?s\\.?a\\.?\\b|^\\s*u\\.?s\\.?\\b(?!.*islands)",
        UMI: "minor.?outlying.?is",
        URY: "uruguay",
        UZB: "uzbek",
        VUT: "vanuatu|new.?hebrides",
        VEN: "venezuela",
        VNM: "^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",
        VGB: "^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",
        VIR: "^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",
        WLF: "futuna|wallis",
        ESH: "western.sahara",
        YEM: "^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",
        YMD: "^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",
        YUG: "yugoslavia",
        ZMB: "zambia|northern.?rhodesia",
        EAZ: "zanzibar",
        ZWE: "zimbabwe|^(?!.*northern).*rhodesia"
      };
    }
  });

  // node_modules/@turf/helpers/dist/cjs/index.cjs
  var require_cjs = __commonJS({
    "node_modules/@turf/helpers/dist/cjs/index.cjs"(exports) {
      "use strict";
      Object.defineProperty(exports, "__esModule", { value: true });
      var earthRadius = 63710088e-1;
      var factors = {
        centimeters: earthRadius * 100,
        centimetres: earthRadius * 100,
        degrees: 360 / (2 * Math.PI),
        feet: earthRadius * 3.28084,
        inches: earthRadius * 39.37,
        kilometers: earthRadius / 1e3,
        kilometres: earthRadius / 1e3,
        meters: earthRadius,
        metres: earthRadius,
        miles: earthRadius / 1609.344,
        millimeters: earthRadius * 1e3,
        millimetres: earthRadius * 1e3,
        nauticalmiles: earthRadius / 1852,
        radians: 1,
        yards: earthRadius * 1.0936
      };
      var areaFactors = {
        acres: 247105e-9,
        centimeters: 1e4,
        centimetres: 1e4,
        feet: 10.763910417,
        hectares: 1e-4,
        inches: 1550.003100006,
        kilometers: 1e-6,
        kilometres: 1e-6,
        meters: 1,
        metres: 1,
        miles: 386e-9,
        nauticalmiles: 29155334959812285e-23,
        millimeters: 1e6,
        millimetres: 1e6,
        yards: 1.195990046
      };
      function feature(geom, properties, options = {}) {
        const feat = { type: "Feature" };
        if (options.id === 0 || options.id) {
          feat.id = options.id;
        }
        if (options.bbox) {
          feat.bbox = options.bbox;
        }
        feat.properties = properties || {};
        feat.geometry = geom;
        return feat;
      }
      function geometry(type, coordinates, _options = {}) {
        switch (type) {
          case "Point":
            return point(coordinates).geometry;
          case "LineString":
            return lineString(coordinates).geometry;
          case "Polygon":
            return polygon(coordinates).geometry;
          case "MultiPoint":
            return multiPoint(coordinates).geometry;
          case "MultiLineString":
            return multiLineString(coordinates).geometry;
          case "MultiPolygon":
            return multiPolygon(coordinates).geometry;
          default:
            throw new Error(type + " is invalid");
        }
      }
      function point(coordinates, properties, options = {}) {
        if (!coordinates) {
          throw new Error("coordinates is required");
        }
        if (!Array.isArray(coordinates)) {
          throw new Error("coordinates must be an Array");
        }
        if (coordinates.length < 2) {
          throw new Error("coordinates must be at least 2 numbers long");
        }
        if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {
          throw new Error("coordinates must contain numbers");
        }
        const geom = {
          type: "Point",
          coordinates
        };
        return feature(geom, properties, options);
      }
      function points(coordinates, properties, options = {}) {
        return featureCollection(
          coordinates.map((coords) => {
            return point(coords, properties);
          }),
          options
        );
      }
      function polygon(coordinates, properties, options = {}) {
        for (const ring of coordinates) {
          if (ring.length < 4) {
            throw new Error(
              "Each LinearRing of a Polygon must have 4 or more Positions."
            );
          }
          if (ring[ring.length - 1].length !== ring[0].length) {
            throw new Error("First and last Position are not equivalent.");
          }
          for (let j = 0; j < ring[ring.length - 1].length; j++) {
            if (ring[ring.length - 1][j] !== ring[0][j]) {
              throw new Error("First and last Position are not equivalent.");
            }
          }
        }
        const geom = {
          type: "Polygon",
          coordinates
        };
        return feature(geom, properties, options);
      }
      function polygons(coordinates, properties, options = {}) {
        return featureCollection(
          coordinates.map((coords) => {
            return polygon(coords, properties);
          }),
          options
        );
      }
      function lineString(coordinates, properties, options = {}) {
        if (coordinates.length < 2) {
          throw new Error("coordinates must be an array of two or more positions");
        }
        const geom = {
          type: "LineString",
          coordinates
        };
        return feature(geom, properties, options);
      }
      function lineStrings(coordinates, properties, options = {}) {
        return featureCollection(
          coordinates.map((coords) => {
            return lineString(coords, properties);
          }),
          options
        );
      }
      function featureCollection(features, options = {}) {
        const fc = { type: "FeatureCollection" };
        if (options.id) {
          fc.id = options.id;
        }
        if (options.bbox) {
          fc.bbox = options.bbox;
        }
        fc.features = features;
        return fc;
      }
      function multiLineString(coordinates, properties, options = {}) {
        const geom = {
          type: "MultiLineString",
          coordinates
        };
        return feature(geom, properties, options);
      }
      function multiPoint(coordinates, properties, options = {}) {
        const geom = {
          type: "MultiPoint",
          coordinates
        };
        return feature(geom, properties, options);
      }
      function multiPolygon(coordinates, properties, options = {}) {
        const geom = {
          type: "MultiPolygon",
          coordinates
        };
        return feature(geom, properties, options);
      }
      function geometryCollection(geometries, properties, options = {}) {
        const geom = {
          type: "GeometryCollection",
          geometries
        };
        return feature(geom, properties, options);
      }
      function round(num, precision = 0) {
        if (precision && !(precision >= 0)) {
          throw new Error("precision must be a positive number");
        }
        const multiplier = Math.pow(10, precision || 0);
        return Math.round(num * multiplier) / multiplier;
      }
      function radiansToLength(radians2, units = "kilometers") {
        const factor = factors[units];
        if (!factor) {
          throw new Error(units + " units is invalid");
        }
        return radians2 * factor;
      }
      function lengthToRadians(distance, units = "kilometers") {
        const factor = factors[units];
        if (!factor) {
          throw new Error(units + " units is invalid");
        }
        return distance / factor;
      }
      function lengthToDegrees(distance, units) {
        return radiansToDegrees(lengthToRadians(distance, units));
      }
      function bearingToAzimuth(bearing) {
        let angle = bearing % 360;
        if (angle < 0) {
          angle += 360;
        }
        return angle;
      }
      function azimuthToBearing(angle) {
        angle = angle % 360;
        if (angle > 180) {
          return angle - 360;
        } else if (angle < -180) {
          return angle + 360;
        }
        return angle;
      }
      function radiansToDegrees(radians2) {
        const normalisedRadians = radians2 % (2 * Math.PI);
        return normalisedRadians * 180 / Math.PI;
      }
      function degreesToRadians(degrees3) {
        const normalisedDegrees = degrees3 % 360;
        return normalisedDegrees * Math.PI / 180;
      }
      function convertLength(length, originalUnit = "kilometers", finalUnit = "kilometers") {
        if (!(length >= 0)) {
          throw new Error("length must be a positive number");
        }
        return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);
      }
      function convertArea(area, originalUnit = "meters", finalUnit = "kilometers") {
        if (!(area >= 0)) {
          throw new Error("area must be a positive number");
        }
        const startFactor = areaFactors[originalUnit];
        if (!startFactor) {
          throw new Error("invalid original units");
        }
        const finalFactor = areaFactors[finalUnit];
        if (!finalFactor) {
          throw new Error("invalid final units");
        }
        return area / startFactor * finalFactor;
      }
      function isNumber(num) {
        return !isNaN(num) && num !== null && !Array.isArray(num);
      }
      function isObject(input) {
        return input !== null && typeof input === "object" && !Array.isArray(input);
      }
      function validateBBox(bbox) {
        if (!bbox) {
          throw new Error("bbox is required");
        }
        if (!Array.isArray(bbox)) {
          throw new Error("bbox must be an Array");
        }
        if (bbox.length !== 4 && bbox.length !== 6) {
          throw new Error("bbox must be an Array of 4 or 6 numbers");
        }
        bbox.forEach((num) => {
          if (!isNumber(num)) {
            throw new Error("bbox must only contain numbers");
          }
        });
      }
      function validateId(id) {
        if (!id) {
          throw new Error("id is required");
        }
        if (["string", "number"].indexOf(typeof id) === -1) {
          throw new Error("id must be a number or a string");
        }
      }
      exports.areaFactors = areaFactors;
      exports.azimuthToBearing = azimuthToBearing;
      exports.bearingToAzimuth = bearingToAzimuth;
      exports.convertArea = convertArea;
      exports.convertLength = convertLength;
      exports.degreesToRadians = degreesToRadians;
      exports.earthRadius = earthRadius;
      exports.factors = factors;
      exports.feature = feature;
      exports.featureCollection = featureCollection;
      exports.geometry = geometry;
      exports.geometryCollection = geometryCollection;
      exports.isNumber = isNumber;
      exports.isObject = isObject;
      exports.lengthToDegrees = lengthToDegrees;
      exports.lengthToRadians = lengthToRadians;
      exports.lineString = lineString;
      exports.lineStrings = lineStrings;
      exports.multiLineString = multiLineString;
      exports.multiPoint = multiPoint;
      exports.multiPolygon = multiPolygon;
      exports.point = point;
      exports.points = points;
      exports.polygon = polygon;
      exports.polygons = polygons;
      exports.radiansToDegrees = radiansToDegrees;
      exports.radiansToLength = radiansToLength;
      exports.round = round;
      exports.validateBBox = validateBBox;
      exports.validateId = validateId;
    }
  });

  // node_modules/@turf/meta/dist/cjs/index.cjs
  var require_cjs2 = __commonJS({
    "node_modules/@turf/meta/dist/cjs/index.cjs"(exports) {
      "use strict";
      Object.defineProperty(exports, "__esModule", { value: true });
      var _helpers = require_cjs();
      function coordEach(geojson, callback, excludeWrapCoord) {
        if (geojson === null) return;
        var j, k, l, geometry, stopG, coords, geometryMaybeCollection, wrapShrink = 0, coordIndex = 0, isGeometryCollection, type = geojson.type, isFeatureCollection = type === "FeatureCollection", isFeature = type === "Feature", stop = isFeatureCollection ? geojson.features.length : 1;
        for (var featureIndex = 0; featureIndex < stop; featureIndex++) {
          geometryMaybeCollection = isFeatureCollection ? geojson.features[featureIndex].geometry : isFeature ? geojson.geometry : geojson;
          isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === "GeometryCollection" : false;
          stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
          for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {
            var multiFeatureIndex = 0;
            var geometryIndex = 0;
            geometry = isGeometryCollection ? geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;
            if (geometry === null) continue;
            coords = geometry.coordinates;
            var geomType = geometry.type;
            wrapShrink = excludeWrapCoord && (geomType === "Polygon" || geomType === "MultiPolygon") ? 1 : 0;
            switch (geomType) {
              case null:
                break;
              case "Point":
                if (callback(
                  coords,
                  coordIndex,
                  featureIndex,
                  multiFeatureIndex,
                  geometryIndex
                ) === false)
                  return false;
                coordIndex++;
                multiFeatureIndex++;
                break;
              case "LineString":
              case "MultiPoint":
                for (j = 0; j < coords.length; j++) {
                  if (callback(
                    coords[j],
                    coordIndex,
                    featureIndex,
                    multiFeatureIndex,
                    geometryIndex
                  ) === false)
                    return false;
                  coordIndex++;
                  if (geomType === "MultiPoint") multiFeatureIndex++;
                }
                if (geomType === "LineString") multiFeatureIndex++;
                break;
              case "Polygon":
              case "MultiLineString":
                for (j = 0; j < coords.length; j++) {
                  for (k = 0; k < coords[j].length - wrapShrink; k++) {
                    if (callback(
                      coords[j][k],
                      coordIndex,
                      featureIndex,
                      multiFeatureIndex,
                      geometryIndex
                    ) === false)
                      return false;
                    coordIndex++;
                  }
                  if (geomType === "MultiLineString") multiFeatureIndex++;
                  if (geomType === "Polygon") geometryIndex++;
                }
                if (geomType === "Polygon") multiFeatureIndex++;
                break;
              case "MultiPolygon":
                for (j = 0; j < coords.length; j++) {
                  geometryIndex = 0;
                  for (k = 0; k < coords[j].length; k++) {
                    for (l = 0; l < coords[j][k].length - wrapShrink; l++) {
                      if (callback(
                        coords[j][k][l],
                        coordIndex,
                        featureIndex,
                        multiFeatureIndex,
                        geometryIndex
                      ) === false)
                        return false;
                      coordIndex++;
                    }
                    geometryIndex++;
                  }
                  multiFeatureIndex++;
                }
                break;
              case "GeometryCollection":
                for (j = 0; j < geometry.geometries.length; j++)
                  if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false)
                    return false;
                break;
              default:
                throw new Error("Unknown Geometry Type");
            }
          }
        }
      }
      function coordReduce(geojson, callback, initialValue, excludeWrapCoord) {
        var previousValue = initialValue;
        coordEach(
          geojson,
          function(currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
            if (coordIndex === 0 && initialValue === void 0)
              previousValue = currentCoord;
            else
              previousValue = callback(
                previousValue,
                currentCoord,
                coordIndex,
                featureIndex,
                multiFeatureIndex,
                geometryIndex
              );
          },
          excludeWrapCoord
        );
        return previousValue;
      }
      function propEach(geojson, callback) {
        var i;
        switch (geojson.type) {
          case "FeatureCollection":
            for (i = 0; i < geojson.features.length; i++) {
              if (callback(geojson.features[i].properties, i) === false) break;
            }
            break;
          case "Feature":
            callback(geojson.properties, 0);
            break;
        }
      }
      function propReduce(geojson, callback, initialValue) {
        var previousValue = initialValue;
        propEach(geojson, function(currentProperties, featureIndex) {
          if (featureIndex === 0 && initialValue === void 0)
            previousValue = currentProperties;
          else
            previousValue = callback(previousValue, currentProperties, featureIndex);
        });
        return previousValue;
      }
      function featureEach(geojson, callback) {
        if (geojson.type === "Feature") {
          callback(geojson, 0);
        } else if (geojson.type === "FeatureCollection") {
          for (var i = 0; i < geojson.features.length; i++) {
            if (callback(geojson.features[i], i) === false) break;
          }
        }
      }
      function featureReduce(geojson, callback, initialValue) {
        var previousValue = initialValue;
        featureEach(geojson, function(currentFeature, featureIndex) {
          if (featureIndex === 0 && initialValue === void 0)
            previousValue = currentFeature;
          else previousValue = callback(previousValue, currentFeature, featureIndex);
        });
        return previousValue;
      }
      function coordAll(geojson) {
        var coords = [];
        coordEach(geojson, function(coord) {
          coords.push(coord);
        });
        return coords;
      }
      function geomEach(geojson, callback) {
        var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, featureProperties, featureBBox, featureId, featureIndex = 0, isFeatureCollection = geojson.type === "FeatureCollection", isFeature = geojson.type === "Feature", stop = isFeatureCollection ? geojson.features.length : 1;
        for (i = 0; i < stop; i++) {
          geometryMaybeCollection = isFeatureCollection ? geojson.features[i].geometry : isFeature ? geojson.geometry : geojson;
          featureProperties = isFeatureCollection ? geojson.features[i].properties : isFeature ? geojson.properties : {};
          featureBBox = isFeatureCollection ? geojson.features[i].bbox : isFeature ? geojson.bbox : void 0;
          featureId = isFeatureCollection ? geojson.features[i].id : isFeature ? geojson.id : void 0;
          isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === "GeometryCollection" : false;
          stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
          for (g = 0; g < stopG; g++) {
            geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection;
            if (geometry === null) {
              if (callback(
                null,
                featureIndex,
                featureProperties,
                featureBBox,
                featureId
              ) === false)
                return false;
              continue;
            }
            switch (geometry.type) {
              case "Point":
              case "LineString":
              case "MultiPoint":
              case "Polygon":
              case "MultiLineString":
              case "MultiPolygon": {
                if (callback(
                  geometry,
                  featureIndex,
                  featureProperties,
                  featureBBox,
                  featureId
                ) === false)
                  return false;
                break;
              }
              case "GeometryCollection": {
                for (j = 0; j < geometry.geometries.length; j++) {
                  if (callback(
                    geometry.geometries[j],
                    featureIndex,
                    featureProperties,
                    featureBBox,
                    featureId
                  ) === false)
                    return false;
                }
                break;
              }
              default:
                throw new Error("Unknown Geometry Type");
            }
          }
          featureIndex++;
        }
      }
      function geomReduce(geojson, callback, initialValue) {
        var previousValue = initialValue;
        geomEach(
          geojson,
          function(currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {
            if (featureIndex === 0 && initialValue === void 0)
              previousValue = currentGeometry;
            else
              previousValue = callback(
                previousValue,
                currentGeometry,
                featureIndex,
                featureProperties,
                featureBBox,
                featureId
              );
          }
        );
        return previousValue;
      }
      function flattenEach(geojson, callback) {
        geomEach(geojson, function(geometry, featureIndex, properties, bbox, id) {
          var type = geometry === null ? null : geometry.type;
          switch (type) {
            case null:
            case "Point":
            case "LineString":
            case "Polygon":
              if (callback(
                _helpers.feature.call(void 0, geometry, properties, { bbox, id }),
                featureIndex,
                0
              ) === false)
                return false;
              return;
          }
          var geomType;
          switch (type) {
            case "MultiPoint":
              geomType = "Point";
              break;
            case "MultiLineString":
              geomType = "LineString";
              break;
            case "MultiPolygon":
              geomType = "Polygon";
              break;
          }
          for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) {
            var coordinate = geometry.coordinates[multiFeatureIndex];
            var geom = {
              type: geomType,
              coordinates: coordinate
            };
            if (callback(_helpers.feature.call(void 0, geom, properties), featureIndex, multiFeatureIndex) === false)
              return false;
          }
        });
      }
      function flattenReduce(geojson, callback, initialValue) {
        var previousValue = initialValue;
        flattenEach(
          geojson,
          function(currentFeature, featureIndex, multiFeatureIndex) {
            if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === void 0)
              previousValue = currentFeature;
            else
              previousValue = callback(
                previousValue,
                currentFeature,
                featureIndex,
                multiFeatureIndex
              );
          }
        );
        return previousValue;
      }
      function segmentEach(geojson, callback) {
        flattenEach(geojson, function(feature2, featureIndex, multiFeatureIndex) {
          var segmentIndex = 0;
          if (!feature2.geometry) return;
          var type = feature2.geometry.type;
          if (type === "Point" || type === "MultiPoint") return;
          var previousCoords;
          var previousFeatureIndex = 0;
          var previousMultiIndex = 0;
          var prevGeomIndex = 0;
          if (coordEach(
            feature2,
            function(currentCoord, coordIndex, featureIndexCoord, multiPartIndexCoord, geometryIndex) {
              if (previousCoords === void 0 || featureIndex > previousFeatureIndex || multiPartIndexCoord > previousMultiIndex || geometryIndex > prevGeomIndex) {
                previousCoords = currentCoord;
                previousFeatureIndex = featureIndex;
                previousMultiIndex = multiPartIndexCoord;
                prevGeomIndex = geometryIndex;
                segmentIndex = 0;
                return;
              }
              var currentSegment = _helpers.lineString.call(
                void 0,
                [previousCoords, currentCoord],
                feature2.properties
              );
              if (callback(
                currentSegment,
                featureIndex,
                multiFeatureIndex,
                geometryIndex,
                segmentIndex
              ) === false)
                return false;
              segmentIndex++;
              previousCoords = currentCoord;
            }
          ) === false)
            return false;
        });
      }
      function segmentReduce(geojson, callback, initialValue) {
        var previousValue = initialValue;
        var started = false;
        segmentEach(
          geojson,
          function(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {
            if (started === false && initialValue === void 0)
              previousValue = currentSegment;
            else
              previousValue = callback(
                previousValue,
                currentSegment,
                featureIndex,
                multiFeatureIndex,
                geometryIndex,
                segmentIndex
              );
            started = true;
          }
        );
        return previousValue;
      }
      function lineEach(geojson, callback) {
        if (!geojson) throw new Error("geojson is required");
        flattenEach(geojson, function(feature2, featureIndex, multiFeatureIndex) {
          if (feature2.geometry === null) return;
          var type = feature2.geometry.type;
          var coords = feature2.geometry.coordinates;
          switch (type) {
            case "LineString":
              if (callback(feature2, featureIndex, multiFeatureIndex, 0, 0) === false)
                return false;
              break;
            case "Polygon":
              for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) {
                if (callback(
                  _helpers.lineString.call(void 0, coords[geometryIndex], feature2.properties),
                  featureIndex,
                  multiFeatureIndex,
                  geometryIndex
                ) === false)
                  return false;
              }
              break;
          }
        });
      }
      function lineReduce(geojson, callback, initialValue) {
        var previousValue = initialValue;
        lineEach(
          geojson,
          function(currentLine, featureIndex, multiFeatureIndex, geometryIndex) {
            if (featureIndex === 0 && initialValue === void 0)
              previousValue = currentLine;
            else
              previousValue = callback(
                previousValue,
                currentLine,
                featureIndex,
                multiFeatureIndex,
                geometryIndex
              );
          }
        );
        return previousValue;
      }
      function findSegment(geojson, options) {
        options = options || {};
        if (!_helpers.isObject.call(void 0, options)) throw new Error("options is invalid");
        var featureIndex = options.featureIndex || 0;
        var multiFeatureIndex = options.multiFeatureIndex || 0;
        var geometryIndex = options.geometryIndex || 0;
        var segmentIndex = options.segmentIndex || 0;
        var properties = options.properties;
        var geometry;
        switch (geojson.type) {
          case "FeatureCollection":
            if (featureIndex < 0)
              featureIndex = geojson.features.length + featureIndex;
            properties = properties || geojson.features[featureIndex].properties;
            geometry = geojson.features[featureIndex].geometry;
            break;
          case "Feature":
            properties = properties || geojson.properties;
            geometry = geojson.geometry;
            break;
          case "Point":
          case "MultiPoint":
            return null;
          case "LineString":
          case "Polygon":
          case "MultiLineString":
          case "MultiPolygon":
            geometry = geojson;
            break;
          default:
            throw new Error("geojson is invalid");
        }
        if (geometry === null) return null;
        var coords = geometry.coordinates;
        switch (geometry.type) {
          case "Point":
          case "MultiPoint":
            return null;
          case "LineString":
            if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;
            return _helpers.lineString.call(
              void 0,
              [coords[segmentIndex], coords[segmentIndex + 1]],
              properties,
              options
            );
          case "Polygon":
            if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;
            if (segmentIndex < 0)
              segmentIndex = coords[geometryIndex].length + segmentIndex - 1;
            return _helpers.lineString.call(
              void 0,
              [
                coords[geometryIndex][segmentIndex],
                coords[geometryIndex][segmentIndex + 1]
              ],
              properties,
              options
            );
          case "MultiLineString":
            if (multiFeatureIndex < 0)
              multiFeatureIndex = coords.length + multiFeatureIndex;
            if (segmentIndex < 0)
              segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;
            return _helpers.lineString.call(
              void 0,
              [
                coords[multiFeatureIndex][segmentIndex],
                coords[multiFeatureIndex][segmentIndex + 1]
              ],
              properties,
              options
            );
          case "MultiPolygon":
            if (multiFeatureIndex < 0)
              multiFeatureIndex = coords.length + multiFeatureIndex;
            if (geometryIndex < 0)
              geometryIndex = coords[multiFeatureIndex].length + geometryIndex;
            if (segmentIndex < 0)
              segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;
            return _helpers.lineString.call(
              void 0,
              [
                coords[multiFeatureIndex][geometryIndex][segmentIndex],
                coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]
              ],
              properties,
              options
            );
        }
        throw new Error("geojson is invalid");
      }
      function findPoint(geojson, options) {
        options = options || {};
        if (!_helpers.isObject.call(void 0, options)) throw new Error("options is invalid");
        var featureIndex = options.featureIndex || 0;
        var multiFeatureIndex = options.multiFeatureIndex || 0;
        var geometryIndex = options.geometryIndex || 0;
        var coordIndex = options.coordIndex || 0;
        var properties = options.properties;
        var geometry;
        switch (geojson.type) {
          case "FeatureCollection":
            if (featureIndex < 0)
              featureIndex = geojson.features.length + featureIndex;
            properties = properties || geojson.features[featureIndex].properties;
            geometry = geojson.features[featureIndex].geometry;
            break;
          case "Feature":
            properties = properties || geojson.properties;
            geometry = geojson.geometry;
            break;
          case "Point":
          case "MultiPoint":
            return null;
          case "LineString":
          case "Polygon":
          case "MultiLineString":
          case "MultiPolygon":
            geometry = geojson;
            break;
          default:
            throw new Error("geojson is invalid");
        }
        if (geometry === null) return null;
        var coords = geometry.coordinates;
        switch (geometry.type) {
          case "Point":
            return _helpers.point.call(void 0, coords, properties, options);
          case "MultiPoint":
            if (multiFeatureIndex < 0)
              multiFeatureIndex = coords.length + multiFeatureIndex;
            return _helpers.point.call(void 0, coords[multiFeatureIndex], properties, options);
          case "LineString":
            if (coordIndex < 0) coordIndex = coords.length + coordIndex;
            return _helpers.point.call(void 0, coords[coordIndex], properties, options);
          case "Polygon":
            if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;
            if (coordIndex < 0)
              coordIndex = coords[geometryIndex].length + coordIndex;
            return _helpers.point.call(void 0, coords[geometryIndex][coordIndex], properties, options);
          case "MultiLineString":
            if (multiFeatureIndex < 0)
              multiFeatureIndex = coords.length + multiFeatureIndex;
            if (coordIndex < 0)
              coordIndex = coords[multiFeatureIndex].length + coordIndex;
            return _helpers.point.call(void 0, coords[multiFeatureIndex][coordIndex], properties, options);
          case "MultiPolygon":
            if (multiFeatureIndex < 0)
              multiFeatureIndex = coords.length + multiFeatureIndex;
            if (geometryIndex < 0)
              geometryIndex = coords[multiFeatureIndex].length + geometryIndex;
            if (coordIndex < 0)
              coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex;
            return _helpers.point.call(
              void 0,
              coords[multiFeatureIndex][geometryIndex][coordIndex],
              properties,
              options
            );
        }
        throw new Error("geojson is invalid");
      }
      exports.coordAll = coordAll;
      exports.coordEach = coordEach;
      exports.coordReduce = coordReduce;
      exports.featureEach = featureEach;
      exports.featureReduce = featureReduce;
      exports.findPoint = findPoint;
      exports.findSegment = findSegment;
      exports.flattenEach = flattenEach;
      exports.flattenReduce = flattenReduce;
      exports.geomEach = geomEach;
      exports.geomReduce = geomReduce;
      exports.lineEach = lineEach;
      exports.lineReduce = lineReduce;
      exports.propEach = propEach;
      exports.propReduce = propReduce;
      exports.segmentEach = segmentEach;
      exports.segmentReduce = segmentReduce;
    }
  });

  // node_modules/@turf/area/dist/cjs/index.cjs
  var require_cjs3 = __commonJS({
    "node_modules/@turf/area/dist/cjs/index.cjs"(exports) {
      "use strict";
      Object.defineProperty(exports, "__esModule", { value: true });
      var _helpers = require_cjs();
      var _meta = require_cjs2();
      function area(geojson) {
        return _meta.geomReduce.call(
          void 0,
          geojson,
          (value, geom) => {
            return value + calculateArea(geom);
          },
          0
        );
      }
      function calculateArea(geom) {
        let total = 0;
        let i;
        switch (geom.type) {
          case "Polygon":
            return polygonArea(geom.coordinates);
          case "MultiPolygon":
            for (i = 0; i < geom.coordinates.length; i++) {
              total += polygonArea(geom.coordinates[i]);
            }
            return total;
          case "Point":
          case "MultiPoint":
          case "LineString":
          case "MultiLineString":
            return 0;
        }
        return 0;
      }
      function polygonArea(coords) {
        let total = 0;
        if (coords && coords.length > 0) {
          total += Math.abs(ringArea(coords[0]));
          for (let i = 1; i < coords.length; i++) {
            total -= Math.abs(ringArea(coords[i]));
          }
        }
        return total;
      }
      var FACTOR = _helpers.earthRadius * _helpers.earthRadius / 2;
      var PI_OVER_180 = Math.PI / 180;
      function ringArea(coords) {
        const coordsLength = coords.length - 1;
        if (coordsLength <= 2)
          return 0;
        let total = 0;
        let i = 0;
        while (i < coordsLength) {
          const lower = coords[i];
          const middle = coords[i + 1 === coordsLength ? 0 : i + 1];
          const upper = coords[i + 2 >= coordsLength ? (i + 2) % coordsLength : i + 2];
          const lowerX = lower[0] * PI_OVER_180;
          const middleY = middle[1] * PI_OVER_180;
          const upperX = upper[0] * PI_OVER_180;
          total += (upperX - lowerX) * Math.sin(middleY);
          i++;
        }
        return total * FACTOR;
      }
      var turf_area_default = area;
      exports.area = area;
      exports.default = turf_area_default;
    }
  });

  // node_modules/@turf/centroid/dist/cjs/index.cjs
  var require_cjs4 = __commonJS({
    "node_modules/@turf/centroid/dist/cjs/index.cjs"(exports) {
      "use strict";
      Object.defineProperty(exports, "__esModule", { value: true });
      var _helpers = require_cjs();
      var _meta = require_cjs2();
      function centroid(geojson, options = {}) {
        let xSum = 0;
        let ySum = 0;
        let len = 0;
        _meta.coordEach.call(
          void 0,
          geojson,
          function(coord) {
            xSum += coord[0];
            ySum += coord[1];
            len++;
          },
          true
        );
        return _helpers.point.call(void 0, [xSum / len, ySum / len], options.properties);
      }
      var turf_centroid_default = centroid;
      exports.centroid = centroid;
      exports.default = turf_centroid_default;
    }
  });

  // node_modules/@turf/bbox/dist/cjs/index.cjs
  var require_cjs5 = __commonJS({
    "node_modules/@turf/bbox/dist/cjs/index.cjs"(exports) {
      "use strict";
      Object.defineProperty(exports, "__esModule", { value: true });
      var _meta = require_cjs2();
      function bbox(geojson, options = {}) {
        if (geojson.bbox != null && true !== options.recompute) {
          return geojson.bbox;
        }
        const result = [Infinity, Infinity, -Infinity, -Infinity];
        _meta.coordEach.call(void 0, geojson, (coord) => {
          if (result[0] > coord[0]) {
            result[0] = coord[0];
          }
          if (result[1] > coord[1]) {
            result[1] = coord[1];
          }
          if (result[2] < coord[0]) {
            result[2] = coord[0];
          }
          if (result[3] < coord[1]) {
            result[3] = coord[1];
          }
        });
        return result;
      }
      var turf_bbox_default = bbox;
      exports.bbox = bbox;
      exports.default = turf_bbox_default;
    }
  });

  // src/lib/geo_location_utils.js
  var require_geo_location_utils = __commonJS({
    "src/lib/geo_location_utils.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var countryRegex = require_country_regex();
      var { area: turfArea } = require_cjs3();
      var { centroid: turfCentroid } = require_cjs4();
      var { bbox: turfBbox } = require_cjs5();
      var identity2 = require_identity2();
      var loggers = require_loggers();
      var isPlainObject = require_is_plain_object();
      var nestedProperty = require_nested_property();
      var polygon = require_polygon();
      var countryIds = Object.keys(countryRegex);
      var locationmodeToIdFinder = {
        "ISO-3": identity2,
        "USA-states": identity2,
        "country names": countryNameToISO3
      };
      function countryNameToISO3(countryName) {
        for (var i = 0; i < countryIds.length; i++) {
          var iso3 = countryIds[i];
          var regex = new RegExp(countryRegex[iso3]);
          if (regex.test(countryName.trim().toLowerCase())) return iso3;
        }
        loggers.log("Unrecognized country name: " + countryName + ".");
        return false;
      }
      function locationToFeature(locationmode, location2, features) {
        if (!location2 || typeof location2 !== "string") return false;
        var locationId = locationmodeToIdFinder[locationmode](location2);
        var filteredFeatures;
        var f, i;
        if (locationId) {
          if (locationmode === "USA-states") {
            filteredFeatures = [];
            for (i = 0; i < features.length; i++) {
              f = features[i];
              if (f.properties && f.properties.gu && f.properties.gu === "USA") {
                filteredFeatures.push(f);
              }
            }
          } else {
            filteredFeatures = features;
          }
          for (i = 0; i < filteredFeatures.length; i++) {
            f = filteredFeatures[i];
            if (f.id === locationId) return f;
          }
          loggers.log([
            "Location with id",
            locationId,
            "does not have a matching topojson feature at this resolution."
          ].join(" "));
        }
        return false;
      }
      function feature2polygons(feature) {
        var geometry = feature.geometry;
        var coords = geometry.coordinates;
        var loc = feature.id;
        var polygons = [];
        var appendPolygon, j, k, m;
        function doesCrossAntiMerdian(pts) {
          for (var l = 0; l < pts.length - 1; l++) {
            if (pts[l][0] > 0 && pts[l + 1][0] < 0) return l;
          }
          return null;
        }
        if (loc === "RUS" || loc === "FJI") {
          appendPolygon = function(_pts) {
            var pts;
            if (doesCrossAntiMerdian(_pts) === null) {
              pts = _pts;
            } else {
              pts = new Array(_pts.length);
              for (m = 0; m < _pts.length; m++) {
                pts[m] = [
                  _pts[m][0] < 0 ? _pts[m][0] + 360 : _pts[m][0],
                  _pts[m][1]
                ];
              }
            }
            polygons.push(polygon.tester(pts));
          };
        } else if (loc === "ATA") {
          appendPolygon = function(pts) {
            var crossAntiMeridianIndex = doesCrossAntiMerdian(pts);
            if (crossAntiMeridianIndex === null) {
              return polygons.push(polygon.tester(pts));
            }
            var stitch = new Array(pts.length + 1);
            var si = 0;
            for (m = 0; m < pts.length; m++) {
              if (m > crossAntiMeridianIndex) {
                stitch[si++] = [pts[m][0] + 360, pts[m][1]];
              } else if (m === crossAntiMeridianIndex) {
                stitch[si++] = pts[m];
                stitch[si++] = [pts[m][0], -90];
              } else {
                stitch[si++] = pts[m];
              }
            }
            var tester = polygon.tester(stitch);
            tester.pts.pop();
            polygons.push(tester);
          };
        } else {
          appendPolygon = function(pts) {
            polygons.push(polygon.tester(pts));
          };
        }
        switch (geometry.type) {
          case "MultiPolygon":
            for (j = 0; j < coords.length; j++) {
              for (k = 0; k < coords[j].length; k++) {
                appendPolygon(coords[j][k]);
              }
            }
            break;
          case "Polygon":
            for (j = 0; j < coords.length; j++) {
              appendPolygon(coords[j]);
            }
            break;
        }
        return polygons;
      }
      function getTraceGeojson(trace) {
        var g = trace.geojson;
        var PlotlyGeoAssets2 = window.PlotlyGeoAssets || {};
        var geojsonIn = typeof g === "string" ? PlotlyGeoAssets2[g] : g;
        if (!isPlainObject(geojsonIn)) {
          loggers.error("Oops ... something went wrong when fetching " + g);
          return false;
        }
        return geojsonIn;
      }
      function extractTraceFeature(calcTrace) {
        var trace = calcTrace[0].trace;
        var geojsonIn = getTraceGeojson(trace);
        if (!geojsonIn) return false;
        var lookup = {};
        var featuresOut = [];
        var i;
        for (i = 0; i < trace._length; i++) {
          var cdi = calcTrace[i];
          if (cdi.loc || cdi.loc === 0) {
            lookup[cdi.loc] = cdi;
          }
        }
        function appendFeature(fIn) {
          var id = nestedProperty(fIn, trace.featureidkey || "id").get();
          var cdi2 = lookup[id];
          if (cdi2) {
            var geometry = fIn.geometry;
            if (geometry.type === "Polygon" || geometry.type === "MultiPolygon") {
              var fOut = {
                type: "Feature",
                id,
                geometry,
                properties: {}
              };
              if (fOut.geometry.coordinates.length > 0) {
                fOut.properties.ct = findCentroid(fOut);
              } else {
                fOut.properties.ct = [NaN, NaN];
              }
              cdi2.fIn = fIn;
              cdi2.fOut = fOut;
              featuresOut.push(fOut);
            } else {
              loggers.log([
                "Location",
                cdi2.loc,
                "does not have a valid GeoJSON geometry.",
                "Traces with locationmode *geojson-id* only support",
                "*Polygon* and *MultiPolygon* geometries."
              ].join(" "));
            }
          }
          delete lookup[id];
        }
        switch (geojsonIn.type) {
          case "FeatureCollection":
            var featuresIn = geojsonIn.features;
            for (i = 0; i < featuresIn.length; i++) {
              appendFeature(featuresIn[i]);
            }
            break;
          case "Feature":
            appendFeature(geojsonIn);
            break;
          default:
            loggers.warn([
              "Invalid GeoJSON type",
              (geojsonIn.type || "none") + ".",
              "Traces with locationmode *geojson-id* only support",
              "*FeatureCollection* and *Feature* types."
            ].join(" "));
            return false;
        }
        for (var loc in lookup) {
          loggers.log([
            "Location *" + loc + "*",
            "does not have a matching feature with id-key",
            "*" + trace.featureidkey + "*."
          ].join(" "));
        }
        return featuresOut;
      }
      function findCentroid(feature) {
        var geometry = feature.geometry;
        var poly;
        if (geometry.type === "MultiPolygon") {
          var coords = geometry.coordinates;
          var maxArea = 0;
          for (var i = 0; i < coords.length; i++) {
            var polyi = { type: "Polygon", coordinates: coords[i] };
            var area = turfArea(polyi);
            if (area > maxArea) {
              maxArea = area;
              poly = polyi;
            }
          }
        } else {
          poly = geometry;
        }
        return turfCentroid(poly).geometry.coordinates;
      }
      function fetchTraceGeoData(calcData) {
        var PlotlyGeoAssets2 = window.PlotlyGeoAssets || {};
        var promises = [];
        function fetch2(url2) {
          return new Promise(function(resolve, reject) {
            d3.json(url2, function(err, d) {
              if (err) {
                delete PlotlyGeoAssets2[url2];
                var msg = err.status === 404 ? 'GeoJSON at URL "' + url2 + '" does not exist.' : "Unexpected error while fetching from " + url2;
                return reject(new Error(msg));
              }
              PlotlyGeoAssets2[url2] = d;
              return resolve(d);
            });
          });
        }
        function wait(url2) {
          return new Promise(function(resolve, reject) {
            var cnt = 0;
            var interval = setInterval(function() {
              if (PlotlyGeoAssets2[url2] && PlotlyGeoAssets2[url2] !== "pending") {
                clearInterval(interval);
                return resolve(PlotlyGeoAssets2[url2]);
              }
              if (cnt > 100) {
                clearInterval(interval);
                return reject("Unexpected error while fetching from " + url2);
              }
              cnt++;
            }, 50);
          });
        }
        for (var i = 0; i < calcData.length; i++) {
          var trace = calcData[i][0].trace;
          var url = trace.geojson;
          if (typeof url === "string") {
            if (!PlotlyGeoAssets2[url]) {
              PlotlyGeoAssets2[url] = "pending";
              promises.push(fetch2(url));
            } else if (PlotlyGeoAssets2[url] === "pending") {
              promises.push(wait(url));
            }
          }
        }
        return promises;
      }
      function computeBbox(d) {
        return turfBbox(d);
      }
      module.exports = {
        locationToFeature,
        feature2polygons,
        getTraceGeojson,
        extractTraceFeature,
        fetchTraceGeoData,
        computeBbox
      };
    }
  });

  // src/traces/scattergeo/style.js
  var require_style17 = __commonJS({
    "src/traces/scattergeo/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var Color2 = require_color();
      var scatterStyle = require_style2();
      var stylePoints = scatterStyle.stylePoints;
      var styleText = scatterStyle.styleText;
      module.exports = function style(gd, calcTrace) {
        if (calcTrace) styleTrace(gd, calcTrace);
      };
      function styleTrace(gd, calcTrace) {
        var trace = calcTrace[0].trace;
        var s = calcTrace[0].node3;
        s.style("opacity", calcTrace[0].trace.opacity);
        stylePoints(s, trace, gd);
        styleText(s, trace, gd);
        s.selectAll("path.js-line").style("fill", "none").each(function(d) {
          var path = d3.select(this);
          var trace2 = d.trace;
          var line = trace2.line || {};
          path.call(Color2.stroke, line.color).call(Drawing.dashLine, line.dash || "", line.width || 0);
          if (trace2.fill !== "none") {
            path.call(Color2.fill, trace2.fillcolor);
          }
        });
      }
    }
  });

  // src/traces/scattergeo/plot.js
  var require_plot17 = __commonJS({
    "src/traces/scattergeo/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var getTopojsonFeatures = require_topojson_utils().getTopojsonFeatures;
      var geoJsonUtils = require_geojson_utils();
      var geoUtils = require_geo_location_utils();
      var findExtremes = require_autorange().findExtremes;
      var BADNUM = require_numerical().BADNUM;
      var calcMarkerSize = require_calc3().calcMarkerSize;
      var subTypes = require_subtypes();
      var style = require_style17();
      function plot(gd, geo, calcData) {
        var scatterLayer = geo.layers.frontplot.select(".scatterlayer");
        var gTraces = Lib.makeTraceGroups(scatterLayer, calcData, "trace scattergeo");
        function removeBADNUM(d, node) {
          if (d.lonlat[0] === BADNUM) {
            d3.select(node).remove();
          }
        }
        gTraces.selectAll("*").remove();
        gTraces.each(function(calcTrace) {
          var s = d3.select(this);
          var trace = calcTrace[0].trace;
          if (subTypes.hasLines(trace) || trace.fill !== "none") {
            var lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
            var lineData = trace.fill !== "none" ? geoJsonUtils.makePolygon(lineCoords) : geoJsonUtils.makeLine(lineCoords);
            s.selectAll("path.js-line").data([{ geojson: lineData, trace }]).enter().append("path").classed("js-line", true).style("stroke-miterlimit", 2);
          }
          if (subTypes.hasMarkers(trace)) {
            s.selectAll("path.point").data(Lib.identity).enter().append("path").classed("point", true).each(function(calcPt) {
              removeBADNUM(calcPt, this);
            });
          }
          if (subTypes.hasText(trace)) {
            s.selectAll("g").data(Lib.identity).enter().append("g").append("text").each(function(calcPt) {
              removeBADNUM(calcPt, this);
            });
          }
          style(gd, calcTrace);
        });
      }
      function calcGeoJSON(calcTrace, fullLayout) {
        var trace = calcTrace[0].trace;
        var geoLayout = fullLayout[trace.geo];
        var geo = geoLayout._subplot;
        var len = trace._length;
        var i, calcPt;
        if (Lib.isArrayOrTypedArray(trace.locations)) {
          var locationmode = trace.locationmode;
          var features = locationmode === "geojson-id" ? geoUtils.extractTraceFeature(calcTrace) : getTopojsonFeatures(trace, geo.topojson);
          for (i = 0; i < len; i++) {
            calcPt = calcTrace[i];
            var feature = locationmode === "geojson-id" ? calcPt.fOut : geoUtils.locationToFeature(locationmode, calcPt.loc, features);
            calcPt.lonlat = feature ? feature.properties.ct : [BADNUM, BADNUM];
          }
        }
        var opts = { padded: true };
        var lonArray;
        var latArray;
        if (geoLayout.fitbounds === "geojson" && trace.locationmode === "geojson-id") {
          var bboxGeojson = geoUtils.computeBbox(geoUtils.getTraceGeojson(trace));
          lonArray = [bboxGeojson[0], bboxGeojson[2]];
          latArray = [bboxGeojson[1], bboxGeojson[3]];
        } else {
          lonArray = new Array(len);
          latArray = new Array(len);
          for (i = 0; i < len; i++) {
            calcPt = calcTrace[i];
            lonArray[i] = calcPt.lonlat[0];
            latArray[i] = calcPt.lonlat[1];
          }
          opts.ppad = calcMarkerSize(trace, len);
        }
        trace._extremes.lon = findExtremes(geoLayout.lonaxis._ax, lonArray, opts);
        trace._extremes.lat = findExtremes(geoLayout.lataxis._ax, latArray, opts);
      }
      module.exports = {
        calcGeoJSON,
        plot
      };
    }
  });

  // src/traces/scattergeo/hover.js
  var require_hover14 = __commonJS({
    "src/traces/scattergeo/hover.js"(exports, module) {
      "use strict";
      var Fx = require_fx();
      var BADNUM = require_numerical().BADNUM;
      var getTraceColor = require_get_trace_color();
      var fillText = require_lib().fillText;
      var attributes = require_attributes48();
      module.exports = function hoverPoints(pointData, xval, yval) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var geo = pointData.subplot;
        var isLonLatOverEdges = geo.projection.isLonLatOverEdges;
        var project = geo.project;
        function distFn(d) {
          var lonlat2 = d.lonlat;
          if (lonlat2[0] === BADNUM) return Infinity;
          if (isLonLatOverEdges(lonlat2)) return Infinity;
          var pt = project(lonlat2);
          var px = project([xval, yval]);
          var dx = Math.abs(pt[0] - px[0]);
          var dy = Math.abs(pt[1] - px[1]);
          var rad2 = Math.max(3, d.mrc || 0);
          return Math.max(Math.sqrt(dx * dx + dy * dy) - rad2, 1 - 3 / rad2);
        }
        Fx.getClosest(cd, distFn, pointData);
        if (pointData.index === false) return;
        var di = cd[pointData.index];
        var lonlat = di.lonlat;
        var pos = [xa.c2p(lonlat), ya.c2p(lonlat)];
        var rad = di.mrc || 1;
        pointData.x0 = pos[0] - rad;
        pointData.x1 = pos[0] + rad;
        pointData.y0 = pos[1] - rad;
        pointData.y1 = pos[1] + rad;
        pointData.loc = di.loc;
        pointData.lon = lonlat[0];
        pointData.lat = lonlat[1];
        var fullLayout = {};
        fullLayout[trace.geo] = { _subplot: geo };
        var labels = trace._module.formatLabels(di, trace, fullLayout);
        pointData.lonLabel = labels.lonLabel;
        pointData.latLabel = labels.latLabel;
        pointData.color = getTraceColor(trace, di);
        pointData.extraText = getExtraText(trace, di, pointData, cd[0].t.labels);
        pointData.hovertemplate = trace.hovertemplate;
        return [pointData];
      };
      function getExtraText(trace, pt, pointData, labels) {
        if (trace.hovertemplate) return;
        var hoverinfo = pt.hi || trace.hoverinfo;
        var parts = hoverinfo === "all" ? attributes.hoverinfo.flags : hoverinfo.split("+");
        var hasLocation = parts.indexOf("location") !== -1 && Array.isArray(trace.locations);
        var hasLon = parts.indexOf("lon") !== -1;
        var hasLat = parts.indexOf("lat") !== -1;
        var hasText = parts.indexOf("text") !== -1;
        var text = [];
        function format(val) {
          return val + "\xB0";
        }
        if (hasLocation) {
          text.push(pt.loc);
        } else if (hasLon && hasLat) {
          text.push("(" + format(pointData.latLabel) + ", " + format(pointData.lonLabel) + ")");
        } else if (hasLon) {
          text.push(labels.lon + format(pointData.lonLabel));
        } else if (hasLat) {
          text.push(labels.lat + format(pointData.latLabel));
        }
        if (hasText) {
          fillText(pt, trace, text);
        }
        return text.join("<br>");
      }
    }
  });

  // src/traces/scattergeo/event_data.js
  var require_event_data9 = __commonJS({
    "src/traces/scattergeo/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt, trace, cd, pointNumber) {
        out.lon = pt.lon;
        out.lat = pt.lat;
        out.location = pt.loc ? pt.loc : null;
        var cdi = cd[pointNumber];
        if (cdi.fIn && cdi.fIn.properties) {
          out.properties = cdi.fIn.properties;
        }
        return out;
      };
    }
  });

  // src/traces/scattergeo/select.js
  var require_select5 = __commonJS({
    "src/traces/scattergeo/select.js"(exports, module) {
      "use strict";
      var subtypes = require_subtypes();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var trace = cd[0].trace;
        var di, lonlat, x, y, i;
        var hasOnlyLines = !subtypes.hasMarkers(trace) && !subtypes.hasText(trace);
        if (hasOnlyLines) return [];
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            di = cd[i];
            lonlat = di.lonlat;
            if (lonlat[0] === BADNUM) continue;
            x = xa.c2p(lonlat);
            y = ya.c2p(lonlat);
            if (selectionTester.contains([x, y], null, i, searchInfo)) {
              selection.push({
                pointNumber: i,
                lon: lonlat[0],
                lat: lonlat[1]
              });
              di.selected = 1;
            } else {
              di.selected = 0;
            }
          }
        }
        return selection;
      };
    }
  });

  // node_modules/d3-array/dist/d3-array.js
  var require_d3_array = __commonJS({
    "node_modules/d3-array/dist/d3-array.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : factory(global2.d3 = global2.d3 || {});
      })(exports, function(exports2) {
        "use strict";
        function ascending(a, b) {
          return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
        }
        function bisector(compare) {
          if (compare.length === 1) compare = ascendingComparator(compare);
          return {
            left: function(a, x, lo, hi) {
              if (lo == null) lo = 0;
              if (hi == null) hi = a.length;
              while (lo < hi) {
                var mid = lo + hi >>> 1;
                if (compare(a[mid], x) < 0) lo = mid + 1;
                else hi = mid;
              }
              return lo;
            },
            right: function(a, x, lo, hi) {
              if (lo == null) lo = 0;
              if (hi == null) hi = a.length;
              while (lo < hi) {
                var mid = lo + hi >>> 1;
                if (compare(a[mid], x) > 0) hi = mid;
                else lo = mid + 1;
              }
              return lo;
            }
          };
        }
        function ascendingComparator(f) {
          return function(d, x) {
            return ascending(f(d), x);
          };
        }
        var ascendingBisect = bisector(ascending);
        var bisectRight = ascendingBisect.right;
        var bisectLeft = ascendingBisect.left;
        function pairs(array2, f) {
          if (f == null) f = pair;
          var i = 0, n = array2.length - 1, p = array2[0], pairs2 = new Array(n < 0 ? 0 : n);
          while (i < n) pairs2[i] = f(p, p = array2[++i]);
          return pairs2;
        }
        function pair(a, b) {
          return [a, b];
        }
        function cross(values0, values1, reduce) {
          var n0 = values0.length, n1 = values1.length, values = new Array(n0 * n1), i0, i1, i, value0;
          if (reduce == null) reduce = pair;
          for (i0 = i = 0; i0 < n0; ++i0) {
            for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {
              values[i] = reduce(value0, values1[i1]);
            }
          }
          return values;
        }
        function descending(a, b) {
          return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
        }
        function number(x) {
          return x === null ? NaN : +x;
        }
        function variance(values, valueof) {
          var n = values.length, m = 0, i = -1, mean2 = 0, value, delta, sum2 = 0;
          if (valueof == null) {
            while (++i < n) {
              if (!isNaN(value = number(values[i]))) {
                delta = value - mean2;
                mean2 += delta / ++m;
                sum2 += delta * (value - mean2);
              }
            }
          } else {
            while (++i < n) {
              if (!isNaN(value = number(valueof(values[i], i, values)))) {
                delta = value - mean2;
                mean2 += delta / ++m;
                sum2 += delta * (value - mean2);
              }
            }
          }
          if (m > 1) return sum2 / (m - 1);
        }
        function deviation(array2, f) {
          var v = variance(array2, f);
          return v ? Math.sqrt(v) : v;
        }
        function extent(values, valueof) {
          var n = values.length, i = -1, value, min2, max2;
          if (valueof == null) {
            while (++i < n) {
              if ((value = values[i]) != null && value >= value) {
                min2 = max2 = value;
                while (++i < n) {
                  if ((value = values[i]) != null) {
                    if (min2 > value) min2 = value;
                    if (max2 < value) max2 = value;
                  }
                }
              }
            }
          } else {
            while (++i < n) {
              if ((value = valueof(values[i], i, values)) != null && value >= value) {
                min2 = max2 = value;
                while (++i < n) {
                  if ((value = valueof(values[i], i, values)) != null) {
                    if (min2 > value) min2 = value;
                    if (max2 < value) max2 = value;
                  }
                }
              }
            }
          }
          return [min2, max2];
        }
        var array = Array.prototype;
        var slice = array.slice;
        var map = array.map;
        function constant(x) {
          return function() {
            return x;
          };
        }
        function identity2(x) {
          return x;
        }
        function range(start, stop, step) {
          start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
          var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range2 = new Array(n);
          while (++i < n) {
            range2[i] = start + i * step;
          }
          return range2;
        }
        var e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2);
        function ticks(start, stop, count) {
          var reverse, i = -1, n, ticks2, step;
          stop = +stop, start = +start, count = +count;
          if (start === stop && count > 0) return [start];
          if (reverse = stop < start) n = start, start = stop, stop = n;
          if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];
          if (step > 0) {
            start = Math.ceil(start / step);
            stop = Math.floor(stop / step);
            ticks2 = new Array(n = Math.ceil(stop - start + 1));
            while (++i < n) ticks2[i] = (start + i) * step;
          } else {
            start = Math.floor(start * step);
            stop = Math.ceil(stop * step);
            ticks2 = new Array(n = Math.ceil(start - stop + 1));
            while (++i < n) ticks2[i] = (start - i) / step;
          }
          if (reverse) ticks2.reverse();
          return ticks2;
        }
        function tickIncrement(start, stop, count) {
          var step = (stop - start) / Math.max(0, count), power = Math.floor(Math.log(step) / Math.LN10), error = step / Math.pow(10, power);
          return power >= 0 ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power) : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
        }
        function tickStep(start, stop, count) {
          var step0 = Math.abs(stop - start) / Math.max(0, count), step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)), error = step0 / step1;
          if (error >= e10) step1 *= 10;
          else if (error >= e5) step1 *= 5;
          else if (error >= e2) step1 *= 2;
          return stop < start ? -step1 : step1;
        }
        function sturges(values) {
          return Math.ceil(Math.log(values.length) / Math.LN2) + 1;
        }
        function histogram() {
          var value = identity2, domain = extent, threshold = sturges;
          function histogram2(data) {
            var i, n = data.length, x, values = new Array(n);
            for (i = 0; i < n; ++i) {
              values[i] = value(data[i], i, data);
            }
            var xz = domain(values), x0 = xz[0], x1 = xz[1], tz = threshold(values, x0, x1);
            if (!Array.isArray(tz)) {
              tz = tickStep(x0, x1, tz);
              tz = range(Math.ceil(x0 / tz) * tz, x1, tz);
            }
            var m = tz.length;
            while (tz[0] <= x0) tz.shift(), --m;
            while (tz[m - 1] > x1) tz.pop(), --m;
            var bins = new Array(m + 1), bin;
            for (i = 0; i <= m; ++i) {
              bin = bins[i] = [];
              bin.x0 = i > 0 ? tz[i - 1] : x0;
              bin.x1 = i < m ? tz[i] : x1;
            }
            for (i = 0; i < n; ++i) {
              x = values[i];
              if (x0 <= x && x <= x1) {
                bins[bisectRight(tz, x, 0, m)].push(data[i]);
              }
            }
            return bins;
          }
          histogram2.value = function(_) {
            return arguments.length ? (value = typeof _ === "function" ? _ : constant(_), histogram2) : value;
          };
          histogram2.domain = function(_) {
            return arguments.length ? (domain = typeof _ === "function" ? _ : constant([_[0], _[1]]), histogram2) : domain;
          };
          histogram2.thresholds = function(_) {
            return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram2) : threshold;
          };
          return histogram2;
        }
        function quantile(values, p, valueof) {
          if (valueof == null) valueof = number;
          if (!(n = values.length)) return;
          if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);
          if (p >= 1) return +valueof(values[n - 1], n - 1, values);
          var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = +valueof(values[i0], i0, values), value1 = +valueof(values[i0 + 1], i0 + 1, values);
          return value0 + (value1 - value0) * (i - i0);
        }
        function freedmanDiaconis(values, min2, max2) {
          values = map.call(values, number).sort(ascending);
          return Math.ceil((max2 - min2) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));
        }
        function scott(values, min2, max2) {
          return Math.ceil((max2 - min2) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));
        }
        function max(values, valueof) {
          var n = values.length, i = -1, value, max2;
          if (valueof == null) {
            while (++i < n) {
              if ((value = values[i]) != null && value >= value) {
                max2 = value;
                while (++i < n) {
                  if ((value = values[i]) != null && value > max2) {
                    max2 = value;
                  }
                }
              }
            }
          } else {
            while (++i < n) {
              if ((value = valueof(values[i], i, values)) != null && value >= value) {
                max2 = value;
                while (++i < n) {
                  if ((value = valueof(values[i], i, values)) != null && value > max2) {
                    max2 = value;
                  }
                }
              }
            }
          }
          return max2;
        }
        function mean(values, valueof) {
          var n = values.length, m = n, i = -1, value, sum2 = 0;
          if (valueof == null) {
            while (++i < n) {
              if (!isNaN(value = number(values[i]))) sum2 += value;
              else --m;
            }
          } else {
            while (++i < n) {
              if (!isNaN(value = number(valueof(values[i], i, values)))) sum2 += value;
              else --m;
            }
          }
          if (m) return sum2 / m;
        }
        function median(values, valueof) {
          var n = values.length, i = -1, value, numbers = [];
          if (valueof == null) {
            while (++i < n) {
              if (!isNaN(value = number(values[i]))) {
                numbers.push(value);
              }
            }
          } else {
            while (++i < n) {
              if (!isNaN(value = number(valueof(values[i], i, values)))) {
                numbers.push(value);
              }
            }
          }
          return quantile(numbers.sort(ascending), 0.5);
        }
        function merge(arrays) {
          var n = arrays.length, m, i = -1, j = 0, merged, array2;
          while (++i < n) j += arrays[i].length;
          merged = new Array(j);
          while (--n >= 0) {
            array2 = arrays[n];
            m = array2.length;
            while (--m >= 0) {
              merged[--j] = array2[m];
            }
          }
          return merged;
        }
        function min(values, valueof) {
          var n = values.length, i = -1, value, min2;
          if (valueof == null) {
            while (++i < n) {
              if ((value = values[i]) != null && value >= value) {
                min2 = value;
                while (++i < n) {
                  if ((value = values[i]) != null && min2 > value) {
                    min2 = value;
                  }
                }
              }
            }
          } else {
            while (++i < n) {
              if ((value = valueof(values[i], i, values)) != null && value >= value) {
                min2 = value;
                while (++i < n) {
                  if ((value = valueof(values[i], i, values)) != null && min2 > value) {
                    min2 = value;
                  }
                }
              }
            }
          }
          return min2;
        }
        function permute(array2, indexes) {
          var i = indexes.length, permutes = new Array(i);
          while (i--) permutes[i] = array2[indexes[i]];
          return permutes;
        }
        function scan(values, compare) {
          if (!(n = values.length)) return;
          var n, i = 0, j = 0, xi, xj = values[j];
          if (compare == null) compare = ascending;
          while (++i < n) {
            if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {
              xj = xi, j = i;
            }
          }
          if (compare(xj, xj) === 0) return j;
        }
        function shuffle(array2, i0, i1) {
          var m = (i1 == null ? array2.length : i1) - (i0 = i0 == null ? 0 : +i0), t, i;
          while (m) {
            i = Math.random() * m-- | 0;
            t = array2[m + i0];
            array2[m + i0] = array2[i + i0];
            array2[i + i0] = t;
          }
          return array2;
        }
        function sum(values, valueof) {
          var n = values.length, i = -1, value, sum2 = 0;
          if (valueof == null) {
            while (++i < n) {
              if (value = +values[i]) sum2 += value;
            }
          } else {
            while (++i < n) {
              if (value = +valueof(values[i], i, values)) sum2 += value;
            }
          }
          return sum2;
        }
        function transpose(matrix) {
          if (!(n = matrix.length)) return [];
          for (var i = -1, m = min(matrix, length), transpose2 = new Array(m); ++i < m; ) {
            for (var j = -1, n, row = transpose2[i] = new Array(n); ++j < n; ) {
              row[j] = matrix[j][i];
            }
          }
          return transpose2;
        }
        function length(d) {
          return d.length;
        }
        function zip() {
          return transpose(arguments);
        }
        exports2.bisect = bisectRight;
        exports2.bisectRight = bisectRight;
        exports2.bisectLeft = bisectLeft;
        exports2.ascending = ascending;
        exports2.bisector = bisector;
        exports2.cross = cross;
        exports2.descending = descending;
        exports2.deviation = deviation;
        exports2.extent = extent;
        exports2.histogram = histogram;
        exports2.thresholdFreedmanDiaconis = freedmanDiaconis;
        exports2.thresholdScott = scott;
        exports2.thresholdSturges = sturges;
        exports2.max = max;
        exports2.mean = mean;
        exports2.median = median;
        exports2.merge = merge;
        exports2.min = min;
        exports2.pairs = pairs;
        exports2.permute = permute;
        exports2.quantile = quantile;
        exports2.range = range;
        exports2.scan = scan;
        exports2.shuffle = shuffle;
        exports2.sum = sum;
        exports2.ticks = ticks;
        exports2.tickIncrement = tickIncrement;
        exports2.tickStep = tickStep;
        exports2.transpose = transpose;
        exports2.variance = variance;
        exports2.zip = zip;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-geo/dist/d3-geo.js
  var require_d3_geo = __commonJS({
    "node_modules/d3-geo/dist/d3-geo.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require_d3_array()) : typeof define === "function" && false ? define(["exports", "d3-array"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}, global2.d3));
      })(exports, function(exports2, d3Array) {
        "use strict";
        function adder() {
          return new Adder();
        }
        function Adder() {
          this.reset();
        }
        Adder.prototype = {
          constructor: Adder,
          reset: function() {
            this.s = // rounded value
            this.t = 0;
          },
          add: function(y) {
            add(temp, y, this.t);
            add(this, temp.s, this.s);
            if (this.s) this.t += temp.t;
            else this.s = temp.t;
          },
          valueOf: function() {
            return this.s;
          }
        };
        var temp = new Adder();
        function add(adder2, a, b) {
          var x = adder2.s = a + b, bv = x - a, av = x - bv;
          adder2.t = a - av + (b - bv);
        }
        var epsilon = 1e-6;
        var epsilon22 = 1e-12;
        var pi = Math.PI;
        var halfPi = pi / 2;
        var quarterPi = pi / 4;
        var tau = pi * 2;
        var degrees3 = 180 / pi;
        var radians2 = pi / 180;
        var abs = Math.abs;
        var atan = Math.atan;
        var atan2 = Math.atan2;
        var cos = Math.cos;
        var ceil = Math.ceil;
        var exp = Math.exp;
        var log = Math.log;
        var pow = Math.pow;
        var sin = Math.sin;
        var sign = Math.sign || function(x) {
          return x > 0 ? 1 : x < 0 ? -1 : 0;
        };
        var sqrt = Math.sqrt;
        var tan = Math.tan;
        function acos(x) {
          return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
        }
        function asin(x) {
          return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);
        }
        function haversin(x) {
          return (x = sin(x / 2)) * x;
        }
        function noop() {
        }
        function streamGeometry(geometry, stream) {
          if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {
            streamGeometryType[geometry.type](geometry, stream);
          }
        }
        var streamObjectType = {
          Feature: function(object2, stream) {
            streamGeometry(object2.geometry, stream);
          },
          FeatureCollection: function(object2, stream) {
            var features = object2.features, i = -1, n = features.length;
            while (++i < n) streamGeometry(features[i].geometry, stream);
          }
        };
        var streamGeometryType = {
          Sphere: function(object2, stream) {
            stream.sphere();
          },
          Point: function(object2, stream) {
            object2 = object2.coordinates;
            stream.point(object2[0], object2[1], object2[2]);
          },
          MultiPoint: function(object2, stream) {
            var coordinates2 = object2.coordinates, i = -1, n = coordinates2.length;
            while (++i < n) object2 = coordinates2[i], stream.point(object2[0], object2[1], object2[2]);
          },
          LineString: function(object2, stream) {
            streamLine(object2.coordinates, stream, 0);
          },
          MultiLineString: function(object2, stream) {
            var coordinates2 = object2.coordinates, i = -1, n = coordinates2.length;
            while (++i < n) streamLine(coordinates2[i], stream, 0);
          },
          Polygon: function(object2, stream) {
            streamPolygon(object2.coordinates, stream);
          },
          MultiPolygon: function(object2, stream) {
            var coordinates2 = object2.coordinates, i = -1, n = coordinates2.length;
            while (++i < n) streamPolygon(coordinates2[i], stream);
          },
          GeometryCollection: function(object2, stream) {
            var geometries = object2.geometries, i = -1, n = geometries.length;
            while (++i < n) streamGeometry(geometries[i], stream);
          }
        };
        function streamLine(coordinates2, stream, closed) {
          var i = -1, n = coordinates2.length - closed, coordinate;
          stream.lineStart();
          while (++i < n) coordinate = coordinates2[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);
          stream.lineEnd();
        }
        function streamPolygon(coordinates2, stream) {
          var i = -1, n = coordinates2.length;
          stream.polygonStart();
          while (++i < n) streamLine(coordinates2[i], stream, 1);
          stream.polygonEnd();
        }
        function geoStream(object2, stream) {
          if (object2 && streamObjectType.hasOwnProperty(object2.type)) {
            streamObjectType[object2.type](object2, stream);
          } else {
            streamGeometry(object2, stream);
          }
        }
        var areaRingSum = adder();
        var areaSum = adder(), lambda00, phi00, lambda0, cosPhi0, sinPhi0;
        var areaStream = {
          point: noop,
          lineStart: noop,
          lineEnd: noop,
          polygonStart: function() {
            areaRingSum.reset();
            areaStream.lineStart = areaRingStart;
            areaStream.lineEnd = areaRingEnd;
          },
          polygonEnd: function() {
            var areaRing = +areaRingSum;
            areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);
            this.lineStart = this.lineEnd = this.point = noop;
          },
          sphere: function() {
            areaSum.add(tau);
          }
        };
        function areaRingStart() {
          areaStream.point = areaPointFirst;
        }
        function areaRingEnd() {
          areaPoint(lambda00, phi00);
        }
        function areaPointFirst(lambda, phi) {
          areaStream.point = areaPoint;
          lambda00 = lambda, phi00 = phi;
          lambda *= radians2, phi *= radians2;
          lambda0 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi);
        }
        function areaPoint(lambda, phi) {
          lambda *= radians2, phi *= radians2;
          phi = phi / 2 + quarterPi;
          var dLambda = lambda - lambda0, sdLambda = dLambda >= 0 ? 1 : -1, adLambda = sdLambda * dLambda, cosPhi = cos(phi), sinPhi = sin(phi), k = sinPhi0 * sinPhi, u = cosPhi0 * cosPhi + k * cos(adLambda), v = k * sdLambda * sin(adLambda);
          areaRingSum.add(atan2(v, u));
          lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;
        }
        function area(object2) {
          areaSum.reset();
          geoStream(object2, areaStream);
          return areaSum * 2;
        }
        function spherical(cartesian2) {
          return [atan2(cartesian2[1], cartesian2[0]), asin(cartesian2[2])];
        }
        function cartesian(spherical2) {
          var lambda = spherical2[0], phi = spherical2[1], cosPhi = cos(phi);
          return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];
        }
        function cartesianDot(a, b) {
          return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
        }
        function cartesianCross(a, b) {
          return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
        }
        function cartesianAddInPlace(a, b) {
          a[0] += b[0], a[1] += b[1], a[2] += b[2];
        }
        function cartesianScale(vector, k) {
          return [vector[0] * k, vector[1] * k, vector[2] * k];
        }
        function cartesianNormalizeInPlace(d) {
          var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
          d[0] /= l, d[1] /= l, d[2] /= l;
        }
        var lambda0$1, phi0, lambda1, phi1, lambda2, lambda00$1, phi00$1, p0, deltaSum = adder(), ranges, range;
        var boundsStream = {
          point: boundsPoint,
          lineStart: boundsLineStart,
          lineEnd: boundsLineEnd,
          polygonStart: function() {
            boundsStream.point = boundsRingPoint;
            boundsStream.lineStart = boundsRingStart;
            boundsStream.lineEnd = boundsRingEnd;
            deltaSum.reset();
            areaStream.polygonStart();
          },
          polygonEnd: function() {
            areaStream.polygonEnd();
            boundsStream.point = boundsPoint;
            boundsStream.lineStart = boundsLineStart;
            boundsStream.lineEnd = boundsLineEnd;
            if (areaRingSum < 0) lambda0$1 = -(lambda1 = 180), phi0 = -(phi1 = 90);
            else if (deltaSum > epsilon) phi1 = 90;
            else if (deltaSum < -epsilon) phi0 = -90;
            range[0] = lambda0$1, range[1] = lambda1;
          },
          sphere: function() {
            lambda0$1 = -(lambda1 = 180), phi0 = -(phi1 = 90);
          }
        };
        function boundsPoint(lambda, phi) {
          ranges.push(range = [lambda0$1 = lambda, lambda1 = lambda]);
          if (phi < phi0) phi0 = phi;
          if (phi > phi1) phi1 = phi;
        }
        function linePoint(lambda, phi) {
          var p = cartesian([lambda * radians2, phi * radians2]);
          if (p0) {
            var normal = cartesianCross(p0, p), equatorial = [normal[1], -normal[0], 0], inflection = cartesianCross(equatorial, normal);
            cartesianNormalizeInPlace(inflection);
            inflection = spherical(inflection);
            var delta = lambda - lambda2, sign2 = delta > 0 ? 1 : -1, lambdai = inflection[0] * degrees3 * sign2, phii, antimeridian = abs(delta) > 180;
            if (antimeridian ^ (sign2 * lambda2 < lambdai && lambdai < sign2 * lambda)) {
              phii = inflection[1] * degrees3;
              if (phii > phi1) phi1 = phii;
            } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign2 * lambda2 < lambdai && lambdai < sign2 * lambda)) {
              phii = -inflection[1] * degrees3;
              if (phii < phi0) phi0 = phii;
            } else {
              if (phi < phi0) phi0 = phi;
              if (phi > phi1) phi1 = phi;
            }
            if (antimeridian) {
              if (lambda < lambda2) {
                if (angle(lambda0$1, lambda) > angle(lambda0$1, lambda1)) lambda1 = lambda;
              } else {
                if (angle(lambda, lambda1) > angle(lambda0$1, lambda1)) lambda0$1 = lambda;
              }
            } else {
              if (lambda1 >= lambda0$1) {
                if (lambda < lambda0$1) lambda0$1 = lambda;
                if (lambda > lambda1) lambda1 = lambda;
              } else {
                if (lambda > lambda2) {
                  if (angle(lambda0$1, lambda) > angle(lambda0$1, lambda1)) lambda1 = lambda;
                } else {
                  if (angle(lambda, lambda1) > angle(lambda0$1, lambda1)) lambda0$1 = lambda;
                }
              }
            }
          } else {
            ranges.push(range = [lambda0$1 = lambda, lambda1 = lambda]);
          }
          if (phi < phi0) phi0 = phi;
          if (phi > phi1) phi1 = phi;
          p0 = p, lambda2 = lambda;
        }
        function boundsLineStart() {
          boundsStream.point = linePoint;
        }
        function boundsLineEnd() {
          range[0] = lambda0$1, range[1] = lambda1;
          boundsStream.point = boundsPoint;
          p0 = null;
        }
        function boundsRingPoint(lambda, phi) {
          if (p0) {
            var delta = lambda - lambda2;
            deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
          } else {
            lambda00$1 = lambda, phi00$1 = phi;
          }
          areaStream.point(lambda, phi);
          linePoint(lambda, phi);
        }
        function boundsRingStart() {
          areaStream.lineStart();
        }
        function boundsRingEnd() {
          boundsRingPoint(lambda00$1, phi00$1);
          areaStream.lineEnd();
          if (abs(deltaSum) > epsilon) lambda0$1 = -(lambda1 = 180);
          range[0] = lambda0$1, range[1] = lambda1;
          p0 = null;
        }
        function angle(lambda02, lambda12) {
          return (lambda12 -= lambda02) < 0 ? lambda12 + 360 : lambda12;
        }
        function rangeCompare(a, b) {
          return a[0] - b[0];
        }
        function rangeContains(range2, x) {
          return range2[0] <= range2[1] ? range2[0] <= x && x <= range2[1] : x < range2[0] || range2[1] < x;
        }
        function bounds(feature) {
          var i, n, a, b, merged, deltaMax, delta;
          phi1 = lambda1 = -(lambda0$1 = phi0 = Infinity);
          ranges = [];
          geoStream(feature, boundsStream);
          if (n = ranges.length) {
            ranges.sort(rangeCompare);
            for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {
              b = ranges[i];
              if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {
                if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
                if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
              } else {
                merged.push(a = b);
              }
            }
            for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {
              b = merged[i];
              if ((delta = angle(a[1], b[0])) > deltaMax) deltaMax = delta, lambda0$1 = b[0], lambda1 = a[1];
            }
          }
          ranges = range = null;
          return lambda0$1 === Infinity || phi0 === Infinity ? [[NaN, NaN], [NaN, NaN]] : [[lambda0$1, phi0], [lambda1, phi1]];
        }
        var W0, W1, X0, Y0, Z0, X1, Y1, Z1, X2, Y2, Z2, lambda00$2, phi00$2, x0, y0, z0;
        var centroidStream = {
          sphere: noop,
          point: centroidPoint,
          lineStart: centroidLineStart,
          lineEnd: centroidLineEnd,
          polygonStart: function() {
            centroidStream.lineStart = centroidRingStart;
            centroidStream.lineEnd = centroidRingEnd;
          },
          polygonEnd: function() {
            centroidStream.lineStart = centroidLineStart;
            centroidStream.lineEnd = centroidLineEnd;
          }
        };
        function centroidPoint(lambda, phi) {
          lambda *= radians2, phi *= radians2;
          var cosPhi = cos(phi);
          centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi));
        }
        function centroidPointCartesian(x, y, z) {
          ++W0;
          X0 += (x - X0) / W0;
          Y0 += (y - Y0) / W0;
          Z0 += (z - Z0) / W0;
        }
        function centroidLineStart() {
          centroidStream.point = centroidLinePointFirst;
        }
        function centroidLinePointFirst(lambda, phi) {
          lambda *= radians2, phi *= radians2;
          var cosPhi = cos(phi);
          x0 = cosPhi * cos(lambda);
          y0 = cosPhi * sin(lambda);
          z0 = sin(phi);
          centroidStream.point = centroidLinePoint;
          centroidPointCartesian(x0, y0, z0);
        }
        function centroidLinePoint(lambda, phi) {
          lambda *= radians2, phi *= radians2;
          var cosPhi = cos(phi), x = cosPhi * cos(lambda), y = cosPhi * sin(lambda), z = sin(phi), w = atan2(sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
          W1 += w;
          X1 += w * (x0 + (x0 = x));
          Y1 += w * (y0 + (y0 = y));
          Z1 += w * (z0 + (z0 = z));
          centroidPointCartesian(x0, y0, z0);
        }
        function centroidLineEnd() {
          centroidStream.point = centroidPoint;
        }
        function centroidRingStart() {
          centroidStream.point = centroidRingPointFirst;
        }
        function centroidRingEnd() {
          centroidRingPoint(lambda00$2, phi00$2);
          centroidStream.point = centroidPoint;
        }
        function centroidRingPointFirst(lambda, phi) {
          lambda00$2 = lambda, phi00$2 = phi;
          lambda *= radians2, phi *= radians2;
          centroidStream.point = centroidRingPoint;
          var cosPhi = cos(phi);
          x0 = cosPhi * cos(lambda);
          y0 = cosPhi * sin(lambda);
          z0 = sin(phi);
          centroidPointCartesian(x0, y0, z0);
        }
        function centroidRingPoint(lambda, phi) {
          lambda *= radians2, phi *= radians2;
          var cosPhi = cos(phi), x = cosPhi * cos(lambda), y = cosPhi * sin(lambda), z = sin(phi), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = sqrt(cx * cx + cy * cy + cz * cz), w = asin(m), v = m && -w / m;
          X2 += v * cx;
          Y2 += v * cy;
          Z2 += v * cz;
          W1 += w;
          X1 += w * (x0 + (x0 = x));
          Y1 += w * (y0 + (y0 = y));
          Z1 += w * (z0 + (z0 = z));
          centroidPointCartesian(x0, y0, z0);
        }
        function centroid(object2) {
          W0 = W1 = X0 = Y0 = Z0 = X1 = Y1 = Z1 = X2 = Y2 = Z2 = 0;
          geoStream(object2, centroidStream);
          var x = X2, y = Y2, z = Z2, m = x * x + y * y + z * z;
          if (m < epsilon22) {
            x = X1, y = Y1, z = Z1;
            if (W1 < epsilon) x = X0, y = Y0, z = Z0;
            m = x * x + y * y + z * z;
            if (m < epsilon22) return [NaN, NaN];
          }
          return [atan2(y, x) * degrees3, asin(z / sqrt(m)) * degrees3];
        }
        function constant(x) {
          return function() {
            return x;
          };
        }
        function compose(a, b) {
          function compose2(x, y) {
            return x = a(x, y), b(x[0], x[1]);
          }
          if (a.invert && b.invert) compose2.invert = function(x, y) {
            return x = b.invert(x, y), x && a.invert(x[0], x[1]);
          };
          return compose2;
        }
        function rotationIdentity(lambda, phi) {
          return [abs(lambda) > pi ? lambda + Math.round(-lambda / tau) * tau : lambda, phi];
        }
        rotationIdentity.invert = rotationIdentity;
        function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {
          return (deltaLambda %= tau) ? deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma)) : rotationLambda(deltaLambda) : deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma) : rotationIdentity;
        }
        function forwardRotationLambda(deltaLambda) {
          return function(lambda, phi) {
            return lambda += deltaLambda, [lambda > pi ? lambda - tau : lambda < -pi ? lambda + tau : lambda, phi];
          };
        }
        function rotationLambda(deltaLambda) {
          var rotation2 = forwardRotationLambda(deltaLambda);
          rotation2.invert = forwardRotationLambda(-deltaLambda);
          return rotation2;
        }
        function rotationPhiGamma(deltaPhi, deltaGamma) {
          var cosDeltaPhi = cos(deltaPhi), sinDeltaPhi = sin(deltaPhi), cosDeltaGamma = cos(deltaGamma), sinDeltaGamma = sin(deltaGamma);
          function rotation2(lambda, phi) {
            var cosPhi = cos(phi), x = cos(lambda) * cosPhi, y = sin(lambda) * cosPhi, z = sin(phi), k = z * cosDeltaPhi + x * sinDeltaPhi;
            return [
              atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),
              asin(k * cosDeltaGamma + y * sinDeltaGamma)
            ];
          }
          rotation2.invert = function(lambda, phi) {
            var cosPhi = cos(phi), x = cos(lambda) * cosPhi, y = sin(lambda) * cosPhi, z = sin(phi), k = z * cosDeltaGamma - y * sinDeltaGamma;
            return [
              atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),
              asin(k * cosDeltaPhi - x * sinDeltaPhi)
            ];
          };
          return rotation2;
        }
        function rotation(rotate) {
          rotate = rotateRadians(rotate[0] * radians2, rotate[1] * radians2, rotate.length > 2 ? rotate[2] * radians2 : 0);
          function forward(coordinates2) {
            coordinates2 = rotate(coordinates2[0] * radians2, coordinates2[1] * radians2);
            return coordinates2[0] *= degrees3, coordinates2[1] *= degrees3, coordinates2;
          }
          forward.invert = function(coordinates2) {
            coordinates2 = rotate.invert(coordinates2[0] * radians2, coordinates2[1] * radians2);
            return coordinates2[0] *= degrees3, coordinates2[1] *= degrees3, coordinates2;
          };
          return forward;
        }
        function circleStream(stream, radius, delta, direction, t02, t12) {
          if (!delta) return;
          var cosRadius = cos(radius), sinRadius = sin(radius), step = direction * delta;
          if (t02 == null) {
            t02 = radius + direction * tau;
            t12 = radius - step / 2;
          } else {
            t02 = circleRadius(cosRadius, t02);
            t12 = circleRadius(cosRadius, t12);
            if (direction > 0 ? t02 < t12 : t02 > t12) t02 += direction * tau;
          }
          for (var point, t = t02; direction > 0 ? t > t12 : t < t12; t -= step) {
            point = spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]);
            stream.point(point[0], point[1]);
          }
        }
        function circleRadius(cosRadius, point) {
          point = cartesian(point), point[0] -= cosRadius;
          cartesianNormalizeInPlace(point);
          var radius = acos(-point[1]);
          return ((-point[2] < 0 ? -radius : radius) + tau - epsilon) % tau;
        }
        function circle() {
          var center = constant([0, 0]), radius = constant(90), precision = constant(6), ring, rotate, stream = { point };
          function point(x, y) {
            ring.push(x = rotate(x, y));
            x[0] *= degrees3, x[1] *= degrees3;
          }
          function circle2() {
            var c = center.apply(this, arguments), r = radius.apply(this, arguments) * radians2, p = precision.apply(this, arguments) * radians2;
            ring = [];
            rotate = rotateRadians(-c[0] * radians2, -c[1] * radians2, 0).invert;
            circleStream(stream, r, p, 1);
            c = { type: "Polygon", coordinates: [ring] };
            ring = rotate = null;
            return c;
          }
          circle2.center = function(_) {
            return arguments.length ? (center = typeof _ === "function" ? _ : constant([+_[0], +_[1]]), circle2) : center;
          };
          circle2.radius = function(_) {
            return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), circle2) : radius;
          };
          circle2.precision = function(_) {
            return arguments.length ? (precision = typeof _ === "function" ? _ : constant(+_), circle2) : precision;
          };
          return circle2;
        }
        function clipBuffer() {
          var lines = [], line;
          return {
            point: function(x, y, m) {
              line.push([x, y, m]);
            },
            lineStart: function() {
              lines.push(line = []);
            },
            lineEnd: noop,
            rejoin: function() {
              if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
            },
            result: function() {
              var result = lines;
              lines = [];
              line = null;
              return result;
            }
          };
        }
        function pointEqual(a, b) {
          return abs(a[0] - b[0]) < epsilon && abs(a[1] - b[1]) < epsilon;
        }
        function Intersection(point, points, other, entry) {
          this.x = point;
          this.z = points;
          this.o = other;
          this.e = entry;
          this.v = false;
          this.n = this.p = null;
        }
        function clipRejoin(segments, compareIntersection2, startInside, interpolate2, stream) {
          var subject = [], clip2 = [], i, n;
          segments.forEach(function(segment) {
            if ((n2 = segment.length - 1) <= 0) return;
            var n2, p02 = segment[0], p1 = segment[n2], x;
            if (pointEqual(p02, p1)) {
              if (!p02[2] && !p1[2]) {
                stream.lineStart();
                for (i = 0; i < n2; ++i) stream.point((p02 = segment[i])[0], p02[1]);
                stream.lineEnd();
                return;
              }
              p1[0] += 2 * epsilon;
            }
            subject.push(x = new Intersection(p02, segment, null, true));
            clip2.push(x.o = new Intersection(p02, null, x, false));
            subject.push(x = new Intersection(p1, segment, null, false));
            clip2.push(x.o = new Intersection(p1, null, x, true));
          });
          if (!subject.length) return;
          clip2.sort(compareIntersection2);
          link(subject);
          link(clip2);
          for (i = 0, n = clip2.length; i < n; ++i) {
            clip2[i].e = startInside = !startInside;
          }
          var start = subject[0], points, point;
          while (1) {
            var current = start, isSubject = true;
            while (current.v) if ((current = current.n) === start) return;
            points = current.z;
            stream.lineStart();
            do {
              current.v = current.o.v = true;
              if (current.e) {
                if (isSubject) {
                  for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);
                } else {
                  interpolate2(current.x, current.n.x, 1, stream);
                }
                current = current.n;
              } else {
                if (isSubject) {
                  points = current.p.z;
                  for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);
                } else {
                  interpolate2(current.x, current.p.x, -1, stream);
                }
                current = current.p;
              }
              current = current.o;
              points = current.z;
              isSubject = !isSubject;
            } while (!current.v);
            stream.lineEnd();
          }
        }
        function link(array) {
          if (!(n = array.length)) return;
          var n, i = 0, a = array[0], b;
          while (++i < n) {
            a.n = b = array[i];
            b.p = a;
            a = b;
          }
          a.n = b = array[0];
          b.p = a;
        }
        var sum = adder();
        function longitude(point) {
          if (abs(point[0]) <= pi)
            return point[0];
          else
            return sign(point[0]) * ((abs(point[0]) + pi) % tau - pi);
        }
        function polygonContains(polygon, point) {
          var lambda = longitude(point), phi = point[1], sinPhi = sin(phi), normal = [sin(lambda), -cos(lambda), 0], angle2 = 0, winding = 0;
          sum.reset();
          if (sinPhi === 1) phi = halfPi + epsilon;
          else if (sinPhi === -1) phi = -halfPi - epsilon;
          for (var i = 0, n = polygon.length; i < n; ++i) {
            if (!(m = (ring = polygon[i]).length)) continue;
            var ring, m, point0 = ring[m - 1], lambda02 = longitude(point0), phi02 = point0[1] / 2 + quarterPi, sinPhi02 = sin(phi02), cosPhi02 = cos(phi02);
            for (var j = 0; j < m; ++j, lambda02 = lambda12, sinPhi02 = sinPhi1, cosPhi02 = cosPhi1, point0 = point1) {
              var point1 = ring[j], lambda12 = longitude(point1), phi12 = point1[1] / 2 + quarterPi, sinPhi1 = sin(phi12), cosPhi1 = cos(phi12), delta = lambda12 - lambda02, sign2 = delta >= 0 ? 1 : -1, absDelta = sign2 * delta, antimeridian = absDelta > pi, k = sinPhi02 * sinPhi1;
              sum.add(atan2(k * sign2 * sin(absDelta), cosPhi02 * cosPhi1 + k * cos(absDelta)));
              angle2 += antimeridian ? delta + sign2 * tau : delta;
              if (antimeridian ^ lambda02 >= lambda ^ lambda12 >= lambda) {
                var arc = cartesianCross(cartesian(point0), cartesian(point1));
                cartesianNormalizeInPlace(arc);
                var intersection = cartesianCross(normal, arc);
                cartesianNormalizeInPlace(intersection);
                var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);
                if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {
                  winding += antimeridian ^ delta >= 0 ? 1 : -1;
                }
              }
            }
          }
          return (angle2 < -epsilon || angle2 < epsilon && sum < -epsilon) ^ winding & 1;
        }
        function clip(pointVisible, clipLine2, interpolate2, start) {
          return function(sink) {
            var line = clipLine2(sink), ringBuffer = clipBuffer(), ringSink = clipLine2(ringBuffer), polygonStarted = false, polygon, segments, ring;
            var clip2 = {
              point,
              lineStart,
              lineEnd,
              polygonStart: function() {
                clip2.point = pointRing;
                clip2.lineStart = ringStart;
                clip2.lineEnd = ringEnd;
                segments = [];
                polygon = [];
              },
              polygonEnd: function() {
                clip2.point = point;
                clip2.lineStart = lineStart;
                clip2.lineEnd = lineEnd;
                segments = d3Array.merge(segments);
                var startInside = polygonContains(polygon, start);
                if (segments.length) {
                  if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
                  clipRejoin(segments, compareIntersection, startInside, interpolate2, sink);
                } else if (startInside) {
                  if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
                  sink.lineStart();
                  interpolate2(null, null, 1, sink);
                  sink.lineEnd();
                }
                if (polygonStarted) sink.polygonEnd(), polygonStarted = false;
                segments = polygon = null;
              },
              sphere: function() {
                sink.polygonStart();
                sink.lineStart();
                interpolate2(null, null, 1, sink);
                sink.lineEnd();
                sink.polygonEnd();
              }
            };
            function point(lambda, phi) {
              if (pointVisible(lambda, phi)) sink.point(lambda, phi);
            }
            function pointLine(lambda, phi) {
              line.point(lambda, phi);
            }
            function lineStart() {
              clip2.point = pointLine;
              line.lineStart();
            }
            function lineEnd() {
              clip2.point = point;
              line.lineEnd();
            }
            function pointRing(lambda, phi) {
              ring.push([lambda, phi]);
              ringSink.point(lambda, phi);
            }
            function ringStart() {
              ringSink.lineStart();
              ring = [];
            }
            function ringEnd() {
              pointRing(ring[0][0], ring[0][1]);
              ringSink.lineEnd();
              var clean = ringSink.clean(), ringSegments = ringBuffer.result(), i, n = ringSegments.length, m, segment, point2;
              ring.pop();
              polygon.push(ring);
              ring = null;
              if (!n) return;
              if (clean & 1) {
                segment = ringSegments[0];
                if ((m = segment.length - 1) > 0) {
                  if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
                  sink.lineStart();
                  for (i = 0; i < m; ++i) sink.point((point2 = segment[i])[0], point2[1]);
                  sink.lineEnd();
                }
                return;
              }
              if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
              segments.push(ringSegments.filter(validSegment));
            }
            return clip2;
          };
        }
        function validSegment(segment) {
          return segment.length > 1;
        }
        function compareIntersection(a, b) {
          return ((a = a.x)[0] < 0 ? a[1] - halfPi - epsilon : halfPi - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfPi - epsilon : halfPi - b[1]);
        }
        var clipAntimeridian = clip(
          function() {
            return true;
          },
          clipAntimeridianLine,
          clipAntimeridianInterpolate,
          [-pi, -halfPi]
        );
        function clipAntimeridianLine(stream) {
          var lambda02 = NaN, phi02 = NaN, sign0 = NaN, clean;
          return {
            lineStart: function() {
              stream.lineStart();
              clean = 1;
            },
            point: function(lambda12, phi12) {
              var sign1 = lambda12 > 0 ? pi : -pi, delta = abs(lambda12 - lambda02);
              if (abs(delta - pi) < epsilon) {
                stream.point(lambda02, phi02 = (phi02 + phi12) / 2 > 0 ? halfPi : -halfPi);
                stream.point(sign0, phi02);
                stream.lineEnd();
                stream.lineStart();
                stream.point(sign1, phi02);
                stream.point(lambda12, phi02);
                clean = 0;
              } else if (sign0 !== sign1 && delta >= pi) {
                if (abs(lambda02 - sign0) < epsilon) lambda02 -= sign0 * epsilon;
                if (abs(lambda12 - sign1) < epsilon) lambda12 -= sign1 * epsilon;
                phi02 = clipAntimeridianIntersect(lambda02, phi02, lambda12, phi12);
                stream.point(sign0, phi02);
                stream.lineEnd();
                stream.lineStart();
                stream.point(sign1, phi02);
                clean = 0;
              }
              stream.point(lambda02 = lambda12, phi02 = phi12);
              sign0 = sign1;
            },
            lineEnd: function() {
              stream.lineEnd();
              lambda02 = phi02 = NaN;
            },
            clean: function() {
              return 2 - clean;
            }
          };
        }
        function clipAntimeridianIntersect(lambda02, phi02, lambda12, phi12) {
          var cosPhi02, cosPhi1, sinLambda0Lambda1 = sin(lambda02 - lambda12);
          return abs(sinLambda0Lambda1) > epsilon ? atan((sin(phi02) * (cosPhi1 = cos(phi12)) * sin(lambda12) - sin(phi12) * (cosPhi02 = cos(phi02)) * sin(lambda02)) / (cosPhi02 * cosPhi1 * sinLambda0Lambda1)) : (phi02 + phi12) / 2;
        }
        function clipAntimeridianInterpolate(from, to, direction, stream) {
          var phi;
          if (from == null) {
            phi = direction * halfPi;
            stream.point(-pi, phi);
            stream.point(0, phi);
            stream.point(pi, phi);
            stream.point(pi, 0);
            stream.point(pi, -phi);
            stream.point(0, -phi);
            stream.point(-pi, -phi);
            stream.point(-pi, 0);
            stream.point(-pi, phi);
          } else if (abs(from[0] - to[0]) > epsilon) {
            var lambda = from[0] < to[0] ? pi : -pi;
            phi = direction * lambda / 2;
            stream.point(-lambda, phi);
            stream.point(0, phi);
            stream.point(lambda, phi);
          } else {
            stream.point(to[0], to[1]);
          }
        }
        function clipCircle(radius) {
          var cr = cos(radius), delta = 6 * radians2, smallRadius = cr > 0, notHemisphere = abs(cr) > epsilon;
          function interpolate2(from, to, direction, stream) {
            circleStream(stream, radius, delta, direction, from, to);
          }
          function visible(lambda, phi) {
            return cos(lambda) * cos(phi) > cr;
          }
          function clipLine2(stream) {
            var point0, c0, v0, v00, clean;
            return {
              lineStart: function() {
                v00 = v0 = false;
                clean = 1;
              },
              point: function(lambda, phi) {
                var point1 = [lambda, phi], point2, v = visible(lambda, phi), c = smallRadius ? v ? 0 : code(lambda, phi) : v ? code(lambda + (lambda < 0 ? pi : -pi), phi) : 0;
                if (!point0 && (v00 = v0 = v)) stream.lineStart();
                if (v !== v0) {
                  point2 = intersect(point0, point1);
                  if (!point2 || pointEqual(point0, point2) || pointEqual(point1, point2))
                    point1[2] = 1;
                }
                if (v !== v0) {
                  clean = 0;
                  if (v) {
                    stream.lineStart();
                    point2 = intersect(point1, point0);
                    stream.point(point2[0], point2[1]);
                  } else {
                    point2 = intersect(point0, point1);
                    stream.point(point2[0], point2[1], 2);
                    stream.lineEnd();
                  }
                  point0 = point2;
                } else if (notHemisphere && point0 && smallRadius ^ v) {
                  var t;
                  if (!(c & c0) && (t = intersect(point1, point0, true))) {
                    clean = 0;
                    if (smallRadius) {
                      stream.lineStart();
                      stream.point(t[0][0], t[0][1]);
                      stream.point(t[1][0], t[1][1]);
                      stream.lineEnd();
                    } else {
                      stream.point(t[1][0], t[1][1]);
                      stream.lineEnd();
                      stream.lineStart();
                      stream.point(t[0][0], t[0][1], 3);
                    }
                  }
                }
                if (v && (!point0 || !pointEqual(point0, point1))) {
                  stream.point(point1[0], point1[1]);
                }
                point0 = point1, v0 = v, c0 = c;
              },
              lineEnd: function() {
                if (v0) stream.lineEnd();
                point0 = null;
              },
              // Rejoin first and last segments if there were intersections and the first
              // and last points were visible.
              clean: function() {
                return clean | (v00 && v0) << 1;
              }
            };
          }
          function intersect(a, b, two) {
            var pa = cartesian(a), pb = cartesian(b);
            var n1 = [1, 0, 0], n2 = cartesianCross(pa, pb), n2n2 = cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
            if (!determinant) return !two && a;
            var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = cartesianCross(n1, n2), A5 = cartesianScale(n1, c1), B2 = cartesianScale(n2, c2);
            cartesianAddInPlace(A5, B2);
            var u = n1xn2, w = cartesianDot(A5, u), uu = cartesianDot(u, u), t22 = w * w - uu * (cartesianDot(A5, A5) - 1);
            if (t22 < 0) return;
            var t = sqrt(t22), q = cartesianScale(u, (-w - t) / uu);
            cartesianAddInPlace(q, A5);
            q = spherical(q);
            if (!two) return q;
            var lambda02 = a[0], lambda12 = b[0], phi02 = a[1], phi12 = b[1], z;
            if (lambda12 < lambda02) z = lambda02, lambda02 = lambda12, lambda12 = z;
            var delta2 = lambda12 - lambda02, polar = abs(delta2 - pi) < epsilon, meridian = polar || delta2 < epsilon;
            if (!polar && phi12 < phi02) z = phi02, phi02 = phi12, phi12 = z;
            if (meridian ? polar ? phi02 + phi12 > 0 ^ q[1] < (abs(q[0] - lambda02) < epsilon ? phi02 : phi12) : phi02 <= q[1] && q[1] <= phi12 : delta2 > pi ^ (lambda02 <= q[0] && q[0] <= lambda12)) {
              var q1 = cartesianScale(u, (-w + t) / uu);
              cartesianAddInPlace(q1, A5);
              return [q, spherical(q1)];
            }
          }
          function code(lambda, phi) {
            var r = smallRadius ? radius : pi - radius, code2 = 0;
            if (lambda < -r) code2 |= 1;
            else if (lambda > r) code2 |= 2;
            if (phi < -r) code2 |= 4;
            else if (phi > r) code2 |= 8;
            return code2;
          }
          return clip(visible, clipLine2, interpolate2, smallRadius ? [0, -radius] : [-pi, radius - pi]);
        }
        function clipLine(a, b, x02, y02, x12, y12) {
          var ax = a[0], ay = a[1], bx = b[0], by = b[1], t02 = 0, t12 = 1, dx = bx - ax, dy = by - ay, r;
          r = x02 - ax;
          if (!dx && r > 0) return;
          r /= dx;
          if (dx < 0) {
            if (r < t02) return;
            if (r < t12) t12 = r;
          } else if (dx > 0) {
            if (r > t12) return;
            if (r > t02) t02 = r;
          }
          r = x12 - ax;
          if (!dx && r < 0) return;
          r /= dx;
          if (dx < 0) {
            if (r > t12) return;
            if (r > t02) t02 = r;
          } else if (dx > 0) {
            if (r < t02) return;
            if (r < t12) t12 = r;
          }
          r = y02 - ay;
          if (!dy && r > 0) return;
          r /= dy;
          if (dy < 0) {
            if (r < t02) return;
            if (r < t12) t12 = r;
          } else if (dy > 0) {
            if (r > t12) return;
            if (r > t02) t02 = r;
          }
          r = y12 - ay;
          if (!dy && r < 0) return;
          r /= dy;
          if (dy < 0) {
            if (r > t12) return;
            if (r > t02) t02 = r;
          } else if (dy > 0) {
            if (r < t02) return;
            if (r < t12) t12 = r;
          }
          if (t02 > 0) a[0] = ax + t02 * dx, a[1] = ay + t02 * dy;
          if (t12 < 1) b[0] = ax + t12 * dx, b[1] = ay + t12 * dy;
          return true;
        }
        var clipMax = 1e9, clipMin = -clipMax;
        function clipRectangle(x02, y02, x12, y12) {
          function visible(x, y) {
            return x02 <= x && x <= x12 && y02 <= y && y <= y12;
          }
          function interpolate2(from, to, direction, stream) {
            var a = 0, a1 = 0;
            if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoint(from, to) < 0 ^ direction > 0) {
              do
                stream.point(a === 0 || a === 3 ? x02 : x12, a > 1 ? y12 : y02);
              while ((a = (a + direction + 4) % 4) !== a1);
            } else {
              stream.point(to[0], to[1]);
            }
          }
          function corner(p, direction) {
            return abs(p[0] - x02) < epsilon ? direction > 0 ? 0 : 3 : abs(p[0] - x12) < epsilon ? direction > 0 ? 2 : 1 : abs(p[1] - y02) < epsilon ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
          }
          function compareIntersection2(a, b) {
            return comparePoint(a.x, b.x);
          }
          function comparePoint(a, b) {
            var ca = corner(a, 1), cb = corner(b, 1);
            return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
          }
          return function(stream) {
            var activeStream = stream, bufferStream = clipBuffer(), segments, polygon, ring, x__, y__, v__, x_, y_, v_, first, clean;
            var clipStream = {
              point,
              lineStart,
              lineEnd,
              polygonStart,
              polygonEnd
            };
            function point(x, y) {
              if (visible(x, y)) activeStream.point(x, y);
            }
            function polygonInside() {
              var winding = 0;
              for (var i = 0, n = polygon.length; i < n; ++i) {
                for (var ring2 = polygon[i], j = 1, m = ring2.length, point2 = ring2[0], a0, a1, b0 = point2[0], b1 = point2[1]; j < m; ++j) {
                  a0 = b0, a1 = b1, point2 = ring2[j], b0 = point2[0], b1 = point2[1];
                  if (a1 <= y12) {
                    if (b1 > y12 && (b0 - a0) * (y12 - a1) > (b1 - a1) * (x02 - a0)) ++winding;
                  } else {
                    if (b1 <= y12 && (b0 - a0) * (y12 - a1) < (b1 - a1) * (x02 - a0)) --winding;
                  }
                }
              }
              return winding;
            }
            function polygonStart() {
              activeStream = bufferStream, segments = [], polygon = [], clean = true;
            }
            function polygonEnd() {
              var startInside = polygonInside(), cleanInside = clean && startInside, visible2 = (segments = d3Array.merge(segments)).length;
              if (cleanInside || visible2) {
                stream.polygonStart();
                if (cleanInside) {
                  stream.lineStart();
                  interpolate2(null, null, 1, stream);
                  stream.lineEnd();
                }
                if (visible2) {
                  clipRejoin(segments, compareIntersection2, startInside, interpolate2, stream);
                }
                stream.polygonEnd();
              }
              activeStream = stream, segments = polygon = ring = null;
            }
            function lineStart() {
              clipStream.point = linePoint2;
              if (polygon) polygon.push(ring = []);
              first = true;
              v_ = false;
              x_ = y_ = NaN;
            }
            function lineEnd() {
              if (segments) {
                linePoint2(x__, y__);
                if (v__ && v_) bufferStream.rejoin();
                segments.push(bufferStream.result());
              }
              clipStream.point = point;
              if (v_) activeStream.lineEnd();
            }
            function linePoint2(x, y) {
              var v = visible(x, y);
              if (polygon) ring.push([x, y]);
              if (first) {
                x__ = x, y__ = y, v__ = v;
                first = false;
                if (v) {
                  activeStream.lineStart();
                  activeStream.point(x, y);
                }
              } else {
                if (v && v_) activeStream.point(x, y);
                else {
                  var a = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))], b = [x = Math.max(clipMin, Math.min(clipMax, x)), y = Math.max(clipMin, Math.min(clipMax, y))];
                  if (clipLine(a, b, x02, y02, x12, y12)) {
                    if (!v_) {
                      activeStream.lineStart();
                      activeStream.point(a[0], a[1]);
                    }
                    activeStream.point(b[0], b[1]);
                    if (!v) activeStream.lineEnd();
                    clean = false;
                  } else if (v) {
                    activeStream.lineStart();
                    activeStream.point(x, y);
                    clean = false;
                  }
                }
              }
              x_ = x, y_ = y, v_ = v;
            }
            return clipStream;
          };
        }
        function extent() {
          var x02 = 0, y02 = 0, x12 = 960, y12 = 500, cache, cacheStream, clip2;
          return clip2 = {
            stream: function(stream) {
              return cache && cacheStream === stream ? cache : cache = clipRectangle(x02, y02, x12, y12)(cacheStream = stream);
            },
            extent: function(_) {
              return arguments.length ? (x02 = +_[0][0], y02 = +_[0][1], x12 = +_[1][0], y12 = +_[1][1], cache = cacheStream = null, clip2) : [[x02, y02], [x12, y12]];
            }
          };
        }
        var lengthSum = adder(), lambda0$2, sinPhi0$1, cosPhi0$1;
        var lengthStream = {
          sphere: noop,
          point: noop,
          lineStart: lengthLineStart,
          lineEnd: noop,
          polygonStart: noop,
          polygonEnd: noop
        };
        function lengthLineStart() {
          lengthStream.point = lengthPointFirst;
          lengthStream.lineEnd = lengthLineEnd;
        }
        function lengthLineEnd() {
          lengthStream.point = lengthStream.lineEnd = noop;
        }
        function lengthPointFirst(lambda, phi) {
          lambda *= radians2, phi *= radians2;
          lambda0$2 = lambda, sinPhi0$1 = sin(phi), cosPhi0$1 = cos(phi);
          lengthStream.point = lengthPoint;
        }
        function lengthPoint(lambda, phi) {
          lambda *= radians2, phi *= radians2;
          var sinPhi = sin(phi), cosPhi = cos(phi), delta = abs(lambda - lambda0$2), cosDelta = cos(delta), sinDelta = sin(delta), x = cosPhi * sinDelta, y = cosPhi0$1 * sinPhi - sinPhi0$1 * cosPhi * cosDelta, z = sinPhi0$1 * sinPhi + cosPhi0$1 * cosPhi * cosDelta;
          lengthSum.add(atan2(sqrt(x * x + y * y), z));
          lambda0$2 = lambda, sinPhi0$1 = sinPhi, cosPhi0$1 = cosPhi;
        }
        function length(object2) {
          lengthSum.reset();
          geoStream(object2, lengthStream);
          return +lengthSum;
        }
        var coordinates = [null, null], object = { type: "LineString", coordinates };
        function distance(a, b) {
          coordinates[0] = a;
          coordinates[1] = b;
          return length(object);
        }
        var containsObjectType = {
          Feature: function(object2, point) {
            return containsGeometry(object2.geometry, point);
          },
          FeatureCollection: function(object2, point) {
            var features = object2.features, i = -1, n = features.length;
            while (++i < n) if (containsGeometry(features[i].geometry, point)) return true;
            return false;
          }
        };
        var containsGeometryType = {
          Sphere: function() {
            return true;
          },
          Point: function(object2, point) {
            return containsPoint(object2.coordinates, point);
          },
          MultiPoint: function(object2, point) {
            var coordinates2 = object2.coordinates, i = -1, n = coordinates2.length;
            while (++i < n) if (containsPoint(coordinates2[i], point)) return true;
            return false;
          },
          LineString: function(object2, point) {
            return containsLine(object2.coordinates, point);
          },
          MultiLineString: function(object2, point) {
            var coordinates2 = object2.coordinates, i = -1, n = coordinates2.length;
            while (++i < n) if (containsLine(coordinates2[i], point)) return true;
            return false;
          },
          Polygon: function(object2, point) {
            return containsPolygon(object2.coordinates, point);
          },
          MultiPolygon: function(object2, point) {
            var coordinates2 = object2.coordinates, i = -1, n = coordinates2.length;
            while (++i < n) if (containsPolygon(coordinates2[i], point)) return true;
            return false;
          },
          GeometryCollection: function(object2, point) {
            var geometries = object2.geometries, i = -1, n = geometries.length;
            while (++i < n) if (containsGeometry(geometries[i], point)) return true;
            return false;
          }
        };
        function containsGeometry(geometry, point) {
          return geometry && containsGeometryType.hasOwnProperty(geometry.type) ? containsGeometryType[geometry.type](geometry, point) : false;
        }
        function containsPoint(coordinates2, point) {
          return distance(coordinates2, point) === 0;
        }
        function containsLine(coordinates2, point) {
          var ao, bo, ab;
          for (var i = 0, n = coordinates2.length; i < n; i++) {
            bo = distance(coordinates2[i], point);
            if (bo === 0) return true;
            if (i > 0) {
              ab = distance(coordinates2[i], coordinates2[i - 1]);
              if (ab > 0 && ao <= ab && bo <= ab && (ao + bo - ab) * (1 - Math.pow((ao - bo) / ab, 2)) < epsilon22 * ab)
                return true;
            }
            ao = bo;
          }
          return false;
        }
        function containsPolygon(coordinates2, point) {
          return !!polygonContains(coordinates2.map(ringRadians), pointRadians(point));
        }
        function ringRadians(ring) {
          return ring = ring.map(pointRadians), ring.pop(), ring;
        }
        function pointRadians(point) {
          return [point[0] * radians2, point[1] * radians2];
        }
        function contains(object2, point) {
          return (object2 && containsObjectType.hasOwnProperty(object2.type) ? containsObjectType[object2.type] : containsGeometry)(object2, point);
        }
        function graticuleX(y02, y12, dy) {
          var y = d3Array.range(y02, y12 - epsilon, dy).concat(y12);
          return function(x) {
            return y.map(function(y2) {
              return [x, y2];
            });
          };
        }
        function graticuleY(x02, x12, dx) {
          var x = d3Array.range(x02, x12 - epsilon, dx).concat(x12);
          return function(y) {
            return x.map(function(x2) {
              return [x2, y];
            });
          };
        }
        function graticule() {
          var x12, x02, X12, X02, y12, y02, Y12, Y02, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
          function graticule2() {
            return { type: "MultiLineString", coordinates: lines() };
          }
          function lines() {
            return d3Array.range(ceil(X02 / DX) * DX, X12, DX).map(X).concat(d3Array.range(ceil(Y02 / DY) * DY, Y12, DY).map(Y)).concat(d3Array.range(ceil(x02 / dx) * dx, x12, dx).filter(function(x2) {
              return abs(x2 % DX) > epsilon;
            }).map(x)).concat(d3Array.range(ceil(y02 / dy) * dy, y12, dy).filter(function(y2) {
              return abs(y2 % DY) > epsilon;
            }).map(y));
          }
          graticule2.lines = function() {
            return lines().map(function(coordinates2) {
              return { type: "LineString", coordinates: coordinates2 };
            });
          };
          graticule2.outline = function() {
            return {
              type: "Polygon",
              coordinates: [
                X(X02).concat(
                  Y(Y12).slice(1),
                  X(X12).reverse().slice(1),
                  Y(Y02).reverse().slice(1)
                )
              ]
            };
          };
          graticule2.extent = function(_) {
            if (!arguments.length) return graticule2.extentMinor();
            return graticule2.extentMajor(_).extentMinor(_);
          };
          graticule2.extentMajor = function(_) {
            if (!arguments.length) return [[X02, Y02], [X12, Y12]];
            X02 = +_[0][0], X12 = +_[1][0];
            Y02 = +_[0][1], Y12 = +_[1][1];
            if (X02 > X12) _ = X02, X02 = X12, X12 = _;
            if (Y02 > Y12) _ = Y02, Y02 = Y12, Y12 = _;
            return graticule2.precision(precision);
          };
          graticule2.extentMinor = function(_) {
            if (!arguments.length) return [[x02, y02], [x12, y12]];
            x02 = +_[0][0], x12 = +_[1][0];
            y02 = +_[0][1], y12 = +_[1][1];
            if (x02 > x12) _ = x02, x02 = x12, x12 = _;
            if (y02 > y12) _ = y02, y02 = y12, y12 = _;
            return graticule2.precision(precision);
          };
          graticule2.step = function(_) {
            if (!arguments.length) return graticule2.stepMinor();
            return graticule2.stepMajor(_).stepMinor(_);
          };
          graticule2.stepMajor = function(_) {
            if (!arguments.length) return [DX, DY];
            DX = +_[0], DY = +_[1];
            return graticule2;
          };
          graticule2.stepMinor = function(_) {
            if (!arguments.length) return [dx, dy];
            dx = +_[0], dy = +_[1];
            return graticule2;
          };
          graticule2.precision = function(_) {
            if (!arguments.length) return precision;
            precision = +_;
            x = graticuleX(y02, y12, 90);
            y = graticuleY(x02, x12, precision);
            X = graticuleX(Y02, Y12, 90);
            Y = graticuleY(X02, X12, precision);
            return graticule2;
          };
          return graticule2.extentMajor([[-180, -90 + epsilon], [180, 90 - epsilon]]).extentMinor([[-180, -80 - epsilon], [180, 80 + epsilon]]);
        }
        function graticule10() {
          return graticule()();
        }
        function interpolate(a, b) {
          var x02 = a[0] * radians2, y02 = a[1] * radians2, x12 = b[0] * radians2, y12 = b[1] * radians2, cy0 = cos(y02), sy0 = sin(y02), cy1 = cos(y12), sy1 = sin(y12), kx0 = cy0 * cos(x02), ky0 = cy0 * sin(x02), kx1 = cy1 * cos(x12), ky1 = cy1 * sin(x12), d = 2 * asin(sqrt(haversin(y12 - y02) + cy0 * cy1 * haversin(x12 - x02))), k = sin(d);
          var interpolate2 = d ? function(t) {
            var B2 = sin(t *= d) / k, A5 = sin(d - t) / k, x = A5 * kx0 + B2 * kx1, y = A5 * ky0 + B2 * ky1, z = A5 * sy0 + B2 * sy1;
            return [
              atan2(y, x) * degrees3,
              atan2(z, sqrt(x * x + y * y)) * degrees3
            ];
          } : function() {
            return [x02 * degrees3, y02 * degrees3];
          };
          interpolate2.distance = d;
          return interpolate2;
        }
        function identity2(x) {
          return x;
        }
        var areaSum$1 = adder(), areaRingSum$1 = adder(), x00, y00, x0$1, y0$1;
        var areaStream$1 = {
          point: noop,
          lineStart: noop,
          lineEnd: noop,
          polygonStart: function() {
            areaStream$1.lineStart = areaRingStart$1;
            areaStream$1.lineEnd = areaRingEnd$1;
          },
          polygonEnd: function() {
            areaStream$1.lineStart = areaStream$1.lineEnd = areaStream$1.point = noop;
            areaSum$1.add(abs(areaRingSum$1));
            areaRingSum$1.reset();
          },
          result: function() {
            var area2 = areaSum$1 / 2;
            areaSum$1.reset();
            return area2;
          }
        };
        function areaRingStart$1() {
          areaStream$1.point = areaPointFirst$1;
        }
        function areaPointFirst$1(x, y) {
          areaStream$1.point = areaPoint$1;
          x00 = x0$1 = x, y00 = y0$1 = y;
        }
        function areaPoint$1(x, y) {
          areaRingSum$1.add(y0$1 * x - x0$1 * y);
          x0$1 = x, y0$1 = y;
        }
        function areaRingEnd$1() {
          areaPoint$1(x00, y00);
        }
        var x0$2 = Infinity, y0$2 = x0$2, x1 = -x0$2, y1 = x1;
        var boundsStream$1 = {
          point: boundsPoint$1,
          lineStart: noop,
          lineEnd: noop,
          polygonStart: noop,
          polygonEnd: noop,
          result: function() {
            var bounds2 = [[x0$2, y0$2], [x1, y1]];
            x1 = y1 = -(y0$2 = x0$2 = Infinity);
            return bounds2;
          }
        };
        function boundsPoint$1(x, y) {
          if (x < x0$2) x0$2 = x;
          if (x > x1) x1 = x;
          if (y < y0$2) y0$2 = y;
          if (y > y1) y1 = y;
        }
        var X0$1 = 0, Y0$1 = 0, Z0$1 = 0, X1$1 = 0, Y1$1 = 0, Z1$1 = 0, X2$1 = 0, Y2$1 = 0, Z2$1 = 0, x00$1, y00$1, x0$3, y0$3;
        var centroidStream$1 = {
          point: centroidPoint$1,
          lineStart: centroidLineStart$1,
          lineEnd: centroidLineEnd$1,
          polygonStart: function() {
            centroidStream$1.lineStart = centroidRingStart$1;
            centroidStream$1.lineEnd = centroidRingEnd$1;
          },
          polygonEnd: function() {
            centroidStream$1.point = centroidPoint$1;
            centroidStream$1.lineStart = centroidLineStart$1;
            centroidStream$1.lineEnd = centroidLineEnd$1;
          },
          result: function() {
            var centroid2 = Z2$1 ? [X2$1 / Z2$1, Y2$1 / Z2$1] : Z1$1 ? [X1$1 / Z1$1, Y1$1 / Z1$1] : Z0$1 ? [X0$1 / Z0$1, Y0$1 / Z0$1] : [NaN, NaN];
            X0$1 = Y0$1 = Z0$1 = X1$1 = Y1$1 = Z1$1 = X2$1 = Y2$1 = Z2$1 = 0;
            return centroid2;
          }
        };
        function centroidPoint$1(x, y) {
          X0$1 += x;
          Y0$1 += y;
          ++Z0$1;
        }
        function centroidLineStart$1() {
          centroidStream$1.point = centroidPointFirstLine;
        }
        function centroidPointFirstLine(x, y) {
          centroidStream$1.point = centroidPointLine;
          centroidPoint$1(x0$3 = x, y0$3 = y);
        }
        function centroidPointLine(x, y) {
          var dx = x - x0$3, dy = y - y0$3, z = sqrt(dx * dx + dy * dy);
          X1$1 += z * (x0$3 + x) / 2;
          Y1$1 += z * (y0$3 + y) / 2;
          Z1$1 += z;
          centroidPoint$1(x0$3 = x, y0$3 = y);
        }
        function centroidLineEnd$1() {
          centroidStream$1.point = centroidPoint$1;
        }
        function centroidRingStart$1() {
          centroidStream$1.point = centroidPointFirstRing;
        }
        function centroidRingEnd$1() {
          centroidPointRing(x00$1, y00$1);
        }
        function centroidPointFirstRing(x, y) {
          centroidStream$1.point = centroidPointRing;
          centroidPoint$1(x00$1 = x0$3 = x, y00$1 = y0$3 = y);
        }
        function centroidPointRing(x, y) {
          var dx = x - x0$3, dy = y - y0$3, z = sqrt(dx * dx + dy * dy);
          X1$1 += z * (x0$3 + x) / 2;
          Y1$1 += z * (y0$3 + y) / 2;
          Z1$1 += z;
          z = y0$3 * x - x0$3 * y;
          X2$1 += z * (x0$3 + x);
          Y2$1 += z * (y0$3 + y);
          Z2$1 += z * 3;
          centroidPoint$1(x0$3 = x, y0$3 = y);
        }
        function PathContext(context) {
          this._context = context;
        }
        PathContext.prototype = {
          _radius: 4.5,
          pointRadius: function(_) {
            return this._radius = _, this;
          },
          polygonStart: function() {
            this._line = 0;
          },
          polygonEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._point = 0;
          },
          lineEnd: function() {
            if (this._line === 0) this._context.closePath();
            this._point = NaN;
          },
          point: function(x, y) {
            switch (this._point) {
              case 0: {
                this._context.moveTo(x, y);
                this._point = 1;
                break;
              }
              case 1: {
                this._context.lineTo(x, y);
                break;
              }
              default: {
                this._context.moveTo(x + this._radius, y);
                this._context.arc(x, y, this._radius, 0, tau);
                break;
              }
            }
          },
          result: noop
        };
        var lengthSum$1 = adder(), lengthRing, x00$2, y00$2, x0$4, y0$4;
        var lengthStream$1 = {
          point: noop,
          lineStart: function() {
            lengthStream$1.point = lengthPointFirst$1;
          },
          lineEnd: function() {
            if (lengthRing) lengthPoint$1(x00$2, y00$2);
            lengthStream$1.point = noop;
          },
          polygonStart: function() {
            lengthRing = true;
          },
          polygonEnd: function() {
            lengthRing = null;
          },
          result: function() {
            var length2 = +lengthSum$1;
            lengthSum$1.reset();
            return length2;
          }
        };
        function lengthPointFirst$1(x, y) {
          lengthStream$1.point = lengthPoint$1;
          x00$2 = x0$4 = x, y00$2 = y0$4 = y;
        }
        function lengthPoint$1(x, y) {
          x0$4 -= x, y0$4 -= y;
          lengthSum$1.add(sqrt(x0$4 * x0$4 + y0$4 * y0$4));
          x0$4 = x, y0$4 = y;
        }
        function PathString() {
          this._string = [];
        }
        PathString.prototype = {
          _radius: 4.5,
          _circle: circle$1(4.5),
          pointRadius: function(_) {
            if ((_ = +_) !== this._radius) this._radius = _, this._circle = null;
            return this;
          },
          polygonStart: function() {
            this._line = 0;
          },
          polygonEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._point = 0;
          },
          lineEnd: function() {
            if (this._line === 0) this._string.push("Z");
            this._point = NaN;
          },
          point: function(x, y) {
            switch (this._point) {
              case 0: {
                this._string.push("M", x, ",", y);
                this._point = 1;
                break;
              }
              case 1: {
                this._string.push("L", x, ",", y);
                break;
              }
              default: {
                if (this._circle == null) this._circle = circle$1(this._radius);
                this._string.push("M", x, ",", y, this._circle);
                break;
              }
            }
          },
          result: function() {
            if (this._string.length) {
              var result = this._string.join("");
              this._string = [];
              return result;
            } else {
              return null;
            }
          }
        };
        function circle$1(radius) {
          return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
        }
        function index(projection2, context) {
          var pointRadius = 4.5, projectionStream, contextStream;
          function path(object2) {
            if (object2) {
              if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
              geoStream(object2, projectionStream(contextStream));
            }
            return contextStream.result();
          }
          path.area = function(object2) {
            geoStream(object2, projectionStream(areaStream$1));
            return areaStream$1.result();
          };
          path.measure = function(object2) {
            geoStream(object2, projectionStream(lengthStream$1));
            return lengthStream$1.result();
          };
          path.bounds = function(object2) {
            geoStream(object2, projectionStream(boundsStream$1));
            return boundsStream$1.result();
          };
          path.centroid = function(object2) {
            geoStream(object2, projectionStream(centroidStream$1));
            return centroidStream$1.result();
          };
          path.projection = function(_) {
            return arguments.length ? (projectionStream = _ == null ? (projection2 = null, identity2) : (projection2 = _).stream, path) : projection2;
          };
          path.context = function(_) {
            if (!arguments.length) return context;
            contextStream = _ == null ? (context = null, new PathString()) : new PathContext(context = _);
            if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
            return path;
          };
          path.pointRadius = function(_) {
            if (!arguments.length) return pointRadius;
            pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
            return path;
          };
          return path.projection(projection2).context(context);
        }
        function transform(methods) {
          return {
            stream: transformer(methods)
          };
        }
        function transformer(methods) {
          return function(stream) {
            var s = new TransformStream();
            for (var key in methods) s[key] = methods[key];
            s.stream = stream;
            return s;
          };
        }
        function TransformStream() {
        }
        TransformStream.prototype = {
          constructor: TransformStream,
          point: function(x, y) {
            this.stream.point(x, y);
          },
          sphere: function() {
            this.stream.sphere();
          },
          lineStart: function() {
            this.stream.lineStart();
          },
          lineEnd: function() {
            this.stream.lineEnd();
          },
          polygonStart: function() {
            this.stream.polygonStart();
          },
          polygonEnd: function() {
            this.stream.polygonEnd();
          }
        };
        function fit(projection2, fitBounds, object2) {
          var clip2 = projection2.clipExtent && projection2.clipExtent();
          projection2.scale(150).translate([0, 0]);
          if (clip2 != null) projection2.clipExtent(null);
          geoStream(object2, projection2.stream(boundsStream$1));
          fitBounds(boundsStream$1.result());
          if (clip2 != null) projection2.clipExtent(clip2);
          return projection2;
        }
        function fitExtent(projection2, extent2, object2) {
          return fit(projection2, function(b) {
            var w = extent2[1][0] - extent2[0][0], h = extent2[1][1] - extent2[0][1], k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])), x = +extent2[0][0] + (w - k * (b[1][0] + b[0][0])) / 2, y = +extent2[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;
            projection2.scale(150 * k).translate([x, y]);
          }, object2);
        }
        function fitSize(projection2, size, object2) {
          return fitExtent(projection2, [[0, 0], size], object2);
        }
        function fitWidth(projection2, width, object2) {
          return fit(projection2, function(b) {
            var w = +width, k = w / (b[1][0] - b[0][0]), x = (w - k * (b[1][0] + b[0][0])) / 2, y = -k * b[0][1];
            projection2.scale(150 * k).translate([x, y]);
          }, object2);
        }
        function fitHeight(projection2, height, object2) {
          return fit(projection2, function(b) {
            var h = +height, k = h / (b[1][1] - b[0][1]), x = -k * b[0][0], y = (h - k * (b[1][1] + b[0][1])) / 2;
            projection2.scale(150 * k).translate([x, y]);
          }, object2);
        }
        var maxDepth = 16, cosMinDistance = cos(30 * radians2);
        function resample(project, delta2) {
          return +delta2 ? resample$1(project, delta2) : resampleNone(project);
        }
        function resampleNone(project) {
          return transformer({
            point: function(x, y) {
              x = project(x, y);
              this.stream.point(x[0], x[1]);
            }
          });
        }
        function resample$1(project, delta2) {
          function resampleLineTo(x02, y02, lambda02, a0, b0, c0, x12, y12, lambda12, a1, b1, c1, depth, stream) {
            var dx = x12 - x02, dy = y12 - y02, d2 = dx * dx + dy * dy;
            if (d2 > 4 * delta2 && depth--) {
              var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = sqrt(a * a + b * b + c * c), phi2 = asin(c /= m), lambda22 = abs(abs(c) - 1) < epsilon || abs(lambda02 - lambda12) < epsilon ? (lambda02 + lambda12) / 2 : atan2(b, a), p = project(lambda22, phi2), x2 = p[0], y2 = p[1], dx2 = x2 - x02, dy2 = y2 - y02, dz = dy * dx2 - dx * dy2;
              if (dz * dz / d2 > delta2 || abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
                resampleLineTo(x02, y02, lambda02, a0, b0, c0, x2, y2, lambda22, a /= m, b /= m, c, depth, stream);
                stream.point(x2, y2);
                resampleLineTo(x2, y2, lambda22, a, b, c, x12, y12, lambda12, a1, b1, c1, depth, stream);
              }
            }
          }
          return function(stream) {
            var lambda002, x002, y002, a00, b00, c00, lambda02, x02, y02, a0, b0, c0;
            var resampleStream = {
              point,
              lineStart,
              lineEnd,
              polygonStart: function() {
                stream.polygonStart();
                resampleStream.lineStart = ringStart;
              },
              polygonEnd: function() {
                stream.polygonEnd();
                resampleStream.lineStart = lineStart;
              }
            };
            function point(x, y) {
              x = project(x, y);
              stream.point(x[0], x[1]);
            }
            function lineStart() {
              x02 = NaN;
              resampleStream.point = linePoint2;
              stream.lineStart();
            }
            function linePoint2(lambda, phi) {
              var c = cartesian([lambda, phi]), p = project(lambda, phi);
              resampleLineTo(x02, y02, lambda02, a0, b0, c0, x02 = p[0], y02 = p[1], lambda02 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
              stream.point(x02, y02);
            }
            function lineEnd() {
              resampleStream.point = point;
              stream.lineEnd();
            }
            function ringStart() {
              lineStart();
              resampleStream.point = ringPoint;
              resampleStream.lineEnd = ringEnd;
            }
            function ringPoint(lambda, phi) {
              linePoint2(lambda002 = lambda, phi), x002 = x02, y002 = y02, a00 = a0, b00 = b0, c00 = c0;
              resampleStream.point = linePoint2;
            }
            function ringEnd() {
              resampleLineTo(x02, y02, lambda02, a0, b0, c0, x002, y002, lambda002, a00, b00, c00, maxDepth, stream);
              resampleStream.lineEnd = lineEnd;
              lineEnd();
            }
            return resampleStream;
          };
        }
        var transformRadians = transformer({
          point: function(x, y) {
            this.stream.point(x * radians2, y * radians2);
          }
        });
        function transformRotate(rotate) {
          return transformer({
            point: function(x, y) {
              var r = rotate(x, y);
              return this.stream.point(r[0], r[1]);
            }
          });
        }
        function scaleTranslate(k, dx, dy, sx, sy) {
          function transform2(x, y) {
            x *= sx;
            y *= sy;
            return [dx + k * x, dy - k * y];
          }
          transform2.invert = function(x, y) {
            return [(x - dx) / k * sx, (dy - y) / k * sy];
          };
          return transform2;
        }
        function scaleTranslateRotate(k, dx, dy, sx, sy, alpha) {
          var cosAlpha = cos(alpha), sinAlpha = sin(alpha), a = cosAlpha * k, b = sinAlpha * k, ai = cosAlpha / k, bi = sinAlpha / k, ci = (sinAlpha * dy - cosAlpha * dx) / k, fi = (sinAlpha * dx + cosAlpha * dy) / k;
          function transform2(x, y) {
            x *= sx;
            y *= sy;
            return [a * x - b * y + dx, dy - b * x - a * y];
          }
          transform2.invert = function(x, y) {
            return [sx * (ai * x - bi * y + ci), sy * (fi - bi * x - ai * y)];
          };
          return transform2;
        }
        function projection(project) {
          return projectionMutator(function() {
            return project;
          })();
        }
        function projectionMutator(projectAt) {
          var project, k = 150, x = 480, y = 250, lambda = 0, phi = 0, deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, alpha = 0, sx = 1, sy = 1, theta = null, preclip = clipAntimeridian, x02 = null, y02, x12, y12, postclip = identity2, delta2 = 0.5, projectResample, projectTransform, projectRotateTransform, cache, cacheStream;
          function projection2(point) {
            return projectRotateTransform(point[0] * radians2, point[1] * radians2);
          }
          function invert(point) {
            point = projectRotateTransform.invert(point[0], point[1]);
            return point && [point[0] * degrees3, point[1] * degrees3];
          }
          projection2.stream = function(stream) {
            return cache && cacheStream === stream ? cache : cache = transformRadians(transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));
          };
          projection2.preclip = function(_) {
            return arguments.length ? (preclip = _, theta = void 0, reset()) : preclip;
          };
          projection2.postclip = function(_) {
            return arguments.length ? (postclip = _, x02 = y02 = x12 = y12 = null, reset()) : postclip;
          };
          projection2.clipAngle = function(_) {
            return arguments.length ? (preclip = +_ ? clipCircle(theta = _ * radians2) : (theta = null, clipAntimeridian), reset()) : theta * degrees3;
          };
          projection2.clipExtent = function(_) {
            return arguments.length ? (postclip = _ == null ? (x02 = y02 = x12 = y12 = null, identity2) : clipRectangle(x02 = +_[0][0], y02 = +_[0][1], x12 = +_[1][0], y12 = +_[1][1]), reset()) : x02 == null ? null : [[x02, y02], [x12, y12]];
          };
          projection2.scale = function(_) {
            return arguments.length ? (k = +_, recenter()) : k;
          };
          projection2.translate = function(_) {
            return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];
          };
          projection2.center = function(_) {
            return arguments.length ? (lambda = _[0] % 360 * radians2, phi = _[1] % 360 * radians2, recenter()) : [lambda * degrees3, phi * degrees3];
          };
          projection2.rotate = function(_) {
            return arguments.length ? (deltaLambda = _[0] % 360 * radians2, deltaPhi = _[1] % 360 * radians2, deltaGamma = _.length > 2 ? _[2] % 360 * radians2 : 0, recenter()) : [deltaLambda * degrees3, deltaPhi * degrees3, deltaGamma * degrees3];
          };
          projection2.angle = function(_) {
            return arguments.length ? (alpha = _ % 360 * radians2, recenter()) : alpha * degrees3;
          };
          projection2.reflectX = function(_) {
            return arguments.length ? (sx = _ ? -1 : 1, recenter()) : sx < 0;
          };
          projection2.reflectY = function(_) {
            return arguments.length ? (sy = _ ? -1 : 1, recenter()) : sy < 0;
          };
          projection2.precision = function(_) {
            return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt(delta2);
          };
          projection2.fitExtent = function(extent2, object2) {
            return fitExtent(projection2, extent2, object2);
          };
          projection2.fitSize = function(size, object2) {
            return fitSize(projection2, size, object2);
          };
          projection2.fitWidth = function(width, object2) {
            return fitWidth(projection2, width, object2);
          };
          projection2.fitHeight = function(height, object2) {
            return fitHeight(projection2, height, object2);
          };
          function recenter() {
            var center = scaleTranslateRotate(k, 0, 0, sx, sy, alpha).apply(null, project(lambda, phi)), transform2 = (alpha ? scaleTranslateRotate : scaleTranslate)(k, x - center[0], y - center[1], sx, sy, alpha);
            rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma);
            projectTransform = compose(project, transform2);
            projectRotateTransform = compose(rotate, projectTransform);
            projectResample = resample(projectTransform, delta2);
            return reset();
          }
          function reset() {
            cache = cacheStream = null;
            return projection2;
          }
          return function() {
            project = projectAt.apply(this, arguments);
            projection2.invert = project.invert && invert;
            return recenter();
          };
        }
        function conicProjection(projectAt) {
          var phi02 = 0, phi12 = pi / 3, m = projectionMutator(projectAt), p = m(phi02, phi12);
          p.parallels = function(_) {
            return arguments.length ? m(phi02 = _[0] * radians2, phi12 = _[1] * radians2) : [phi02 * degrees3, phi12 * degrees3];
          };
          return p;
        }
        function cylindricalEqualAreaRaw(phi02) {
          var cosPhi02 = cos(phi02);
          function forward(lambda, phi) {
            return [lambda * cosPhi02, sin(phi) / cosPhi02];
          }
          forward.invert = function(x, y) {
            return [x / cosPhi02, asin(y * cosPhi02)];
          };
          return forward;
        }
        function conicEqualAreaRaw(y02, y12) {
          var sy0 = sin(y02), n = (sy0 + sin(y12)) / 2;
          if (abs(n) < epsilon) return cylindricalEqualAreaRaw(y02);
          var c = 1 + sy0 * (2 * n - sy0), r0 = sqrt(c) / n;
          function project(x, y) {
            var r = sqrt(c - 2 * n * sin(y)) / n;
            return [r * sin(x *= n), r0 - r * cos(x)];
          }
          project.invert = function(x, y) {
            var r0y = r0 - y, l = atan2(x, abs(r0y)) * sign(r0y);
            if (r0y * n < 0)
              l -= pi * sign(x) * sign(r0y);
            return [l / n, asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))];
          };
          return project;
        }
        function conicEqualArea() {
          return conicProjection(conicEqualAreaRaw).scale(155.424).center([0, 33.6442]);
        }
        function albers() {
          return conicEqualArea().parallels([29.5, 45.5]).scale(1070).translate([480, 250]).rotate([96, 0]).center([-0.6, 38.7]);
        }
        function multiplex(streams) {
          var n = streams.length;
          return {
            point: function(x, y) {
              var i = -1;
              while (++i < n) streams[i].point(x, y);
            },
            sphere: function() {
              var i = -1;
              while (++i < n) streams[i].sphere();
            },
            lineStart: function() {
              var i = -1;
              while (++i < n) streams[i].lineStart();
            },
            lineEnd: function() {
              var i = -1;
              while (++i < n) streams[i].lineEnd();
            },
            polygonStart: function() {
              var i = -1;
              while (++i < n) streams[i].polygonStart();
            },
            polygonEnd: function() {
              var i = -1;
              while (++i < n) streams[i].polygonEnd();
            }
          };
        }
        function albersUsa() {
          var cache, cacheStream, lower48 = albers(), lower48Point, alaska = conicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, hawaii = conicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, point, pointStream = { point: function(x, y) {
            point = [x, y];
          } };
          function albersUsa2(coordinates2) {
            var x = coordinates2[0], y = coordinates2[1];
            return point = null, (lower48Point.point(x, y), point) || (alaskaPoint.point(x, y), point) || (hawaiiPoint.point(x, y), point);
          }
          albersUsa2.invert = function(coordinates2) {
            var k = lower48.scale(), t = lower48.translate(), x = (coordinates2[0] - t[0]) / k, y = (coordinates2[1] - t[1]) / k;
            return (y >= 0.12 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii : lower48).invert(coordinates2);
          };
          albersUsa2.stream = function(stream) {
            return cache && cacheStream === stream ? cache : cache = multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);
          };
          albersUsa2.precision = function(_) {
            if (!arguments.length) return lower48.precision();
            lower48.precision(_), alaska.precision(_), hawaii.precision(_);
            return reset();
          };
          albersUsa2.scale = function(_) {
            if (!arguments.length) return lower48.scale();
            lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);
            return albersUsa2.translate(lower48.translate());
          };
          albersUsa2.translate = function(_) {
            if (!arguments.length) return lower48.translate();
            var k = lower48.scale(), x = +_[0], y = +_[1];
            lower48Point = lower48.translate(_).clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]]).stream(pointStream);
            alaskaPoint = alaska.translate([x - 0.307 * k, y + 0.201 * k]).clipExtent([[x - 0.425 * k + epsilon, y + 0.12 * k + epsilon], [x - 0.214 * k - epsilon, y + 0.234 * k - epsilon]]).stream(pointStream);
            hawaiiPoint = hawaii.translate([x - 0.205 * k, y + 0.212 * k]).clipExtent([[x - 0.214 * k + epsilon, y + 0.166 * k + epsilon], [x - 0.115 * k - epsilon, y + 0.234 * k - epsilon]]).stream(pointStream);
            return reset();
          };
          albersUsa2.fitExtent = function(extent2, object2) {
            return fitExtent(albersUsa2, extent2, object2);
          };
          albersUsa2.fitSize = function(size, object2) {
            return fitSize(albersUsa2, size, object2);
          };
          albersUsa2.fitWidth = function(width, object2) {
            return fitWidth(albersUsa2, width, object2);
          };
          albersUsa2.fitHeight = function(height, object2) {
            return fitHeight(albersUsa2, height, object2);
          };
          function reset() {
            cache = cacheStream = null;
            return albersUsa2;
          }
          return albersUsa2.scale(1070);
        }
        function azimuthalRaw(scale) {
          return function(x, y) {
            var cx = cos(x), cy = cos(y), k = scale(cx * cy);
            return [
              k * cy * sin(x),
              k * sin(y)
            ];
          };
        }
        function azimuthalInvert(angle2) {
          return function(x, y) {
            var z = sqrt(x * x + y * y), c = angle2(z), sc = sin(c), cc = cos(c);
            return [
              atan2(x * sc, z * cc),
              asin(z && y * sc / z)
            ];
          };
        }
        var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {
          return sqrt(2 / (1 + cxcy));
        });
        azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {
          return 2 * asin(z / 2);
        });
        function azimuthalEqualArea() {
          return projection(azimuthalEqualAreaRaw).scale(124.75).clipAngle(180 - 1e-3);
        }
        var azimuthalEquidistantRaw = azimuthalRaw(function(c) {
          return (c = acos(c)) && c / sin(c);
        });
        azimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {
          return z;
        });
        function azimuthalEquidistant() {
          return projection(azimuthalEquidistantRaw).scale(79.4188).clipAngle(180 - 1e-3);
        }
        function mercatorRaw(lambda, phi) {
          return [lambda, log(tan((halfPi + phi) / 2))];
        }
        mercatorRaw.invert = function(x, y) {
          return [x, 2 * atan(exp(y)) - halfPi];
        };
        function mercator() {
          return mercatorProjection(mercatorRaw).scale(961 / tau);
        }
        function mercatorProjection(project) {
          var m = projection(project), center = m.center, scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, x02 = null, y02, x12, y12;
          m.scale = function(_) {
            return arguments.length ? (scale(_), reclip()) : scale();
          };
          m.translate = function(_) {
            return arguments.length ? (translate(_), reclip()) : translate();
          };
          m.center = function(_) {
            return arguments.length ? (center(_), reclip()) : center();
          };
          m.clipExtent = function(_) {
            return arguments.length ? (_ == null ? x02 = y02 = x12 = y12 = null : (x02 = +_[0][0], y02 = +_[0][1], x12 = +_[1][0], y12 = +_[1][1]), reclip()) : x02 == null ? null : [[x02, y02], [x12, y12]];
          };
          function reclip() {
            var k = pi * scale(), t = m(rotation(m.rotate()).invert([0, 0]));
            return clipExtent(x02 == null ? [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]] : project === mercatorRaw ? [[Math.max(t[0] - k, x02), y02], [Math.min(t[0] + k, x12), y12]] : [[x02, Math.max(t[1] - k, y02)], [x12, Math.min(t[1] + k, y12)]]);
          }
          return reclip();
        }
        function tany(y) {
          return tan((halfPi + y) / 2);
        }
        function conicConformalRaw(y02, y12) {
          var cy0 = cos(y02), n = y02 === y12 ? sin(y02) : log(cy0 / cos(y12)) / log(tany(y12) / tany(y02)), f = cy0 * pow(tany(y02), n) / n;
          if (!n) return mercatorRaw;
          function project(x, y) {
            if (f > 0) {
              if (y < -halfPi + epsilon) y = -halfPi + epsilon;
            } else {
              if (y > halfPi - epsilon) y = halfPi - epsilon;
            }
            var r = f / pow(tany(y), n);
            return [r * sin(n * x), f - r * cos(n * x)];
          }
          project.invert = function(x, y) {
            var fy = f - y, r = sign(n) * sqrt(x * x + fy * fy), l = atan2(x, abs(fy)) * sign(fy);
            if (fy * n < 0)
              l -= pi * sign(x) * sign(fy);
            return [l / n, 2 * atan(pow(f / r, 1 / n)) - halfPi];
          };
          return project;
        }
        function conicConformal() {
          return conicProjection(conicConformalRaw).scale(109.5).parallels([30, 30]);
        }
        function equirectangularRaw(lambda, phi) {
          return [lambda, phi];
        }
        equirectangularRaw.invert = equirectangularRaw;
        function equirectangular() {
          return projection(equirectangularRaw).scale(152.63);
        }
        function conicEquidistantRaw(y02, y12) {
          var cy0 = cos(y02), n = y02 === y12 ? sin(y02) : (cy0 - cos(y12)) / (y12 - y02), g = cy0 / n + y02;
          if (abs(n) < epsilon) return equirectangularRaw;
          function project(x, y) {
            var gy = g - y, nx = n * x;
            return [gy * sin(nx), g - gy * cos(nx)];
          }
          project.invert = function(x, y) {
            var gy = g - y, l = atan2(x, abs(gy)) * sign(gy);
            if (gy * n < 0)
              l -= pi * sign(x) * sign(gy);
            return [l / n, g - sign(n) * sqrt(x * x + gy * gy)];
          };
          return project;
        }
        function conicEquidistant() {
          return conicProjection(conicEquidistantRaw).scale(131.154).center([0, 13.9389]);
        }
        var A1 = 1.340264, A2 = -0.081106, A3 = 893e-6, A4 = 3796e-6, M = sqrt(3) / 2, iterations = 12;
        function equalEarthRaw(lambda, phi) {
          var l = asin(M * sin(phi)), l2 = l * l, l6 = l2 * l2 * l2;
          return [
            lambda * cos(l) / (M * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2))),
            l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2))
          ];
        }
        equalEarthRaw.invert = function(x, y) {
          var l = y, l2 = l * l, l6 = l2 * l2 * l2;
          for (var i = 0, delta, fy, fpy; i < iterations; ++i) {
            fy = l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2)) - y;
            fpy = A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2);
            l -= delta = fy / fpy, l2 = l * l, l6 = l2 * l2 * l2;
            if (abs(delta) < epsilon22) break;
          }
          return [
            M * x * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2)) / cos(l),
            asin(sin(l) / M)
          ];
        };
        function equalEarth() {
          return projection(equalEarthRaw).scale(177.158);
        }
        function gnomonicRaw(x, y) {
          var cy = cos(y), k = cos(x) * cy;
          return [cy * sin(x) / k, sin(y) / k];
        }
        gnomonicRaw.invert = azimuthalInvert(atan);
        function gnomonic() {
          return projection(gnomonicRaw).scale(144.049).clipAngle(60);
        }
        function identity$1() {
          var k = 1, tx = 0, ty = 0, sx = 1, sy = 1, alpha = 0, ca, sa, x02 = null, y02, x12, y12, kx = 1, ky = 1, transform2 = transformer({
            point: function(x, y) {
              var p = projection2([x, y]);
              this.stream.point(p[0], p[1]);
            }
          }), postclip = identity2, cache, cacheStream;
          function reset() {
            kx = k * sx;
            ky = k * sy;
            cache = cacheStream = null;
            return projection2;
          }
          function projection2(p) {
            var x = p[0] * kx, y = p[1] * ky;
            if (alpha) {
              var t = y * ca - x * sa;
              x = x * ca + y * sa;
              y = t;
            }
            return [x + tx, y + ty];
          }
          projection2.invert = function(p) {
            var x = p[0] - tx, y = p[1] - ty;
            if (alpha) {
              var t = y * ca + x * sa;
              x = x * ca - y * sa;
              y = t;
            }
            return [x / kx, y / ky];
          };
          projection2.stream = function(stream) {
            return cache && cacheStream === stream ? cache : cache = transform2(postclip(cacheStream = stream));
          };
          projection2.postclip = function(_) {
            return arguments.length ? (postclip = _, x02 = y02 = x12 = y12 = null, reset()) : postclip;
          };
          projection2.clipExtent = function(_) {
            return arguments.length ? (postclip = _ == null ? (x02 = y02 = x12 = y12 = null, identity2) : clipRectangle(x02 = +_[0][0], y02 = +_[0][1], x12 = +_[1][0], y12 = +_[1][1]), reset()) : x02 == null ? null : [[x02, y02], [x12, y12]];
          };
          projection2.scale = function(_) {
            return arguments.length ? (k = +_, reset()) : k;
          };
          projection2.translate = function(_) {
            return arguments.length ? (tx = +_[0], ty = +_[1], reset()) : [tx, ty];
          };
          projection2.angle = function(_) {
            return arguments.length ? (alpha = _ % 360 * radians2, sa = sin(alpha), ca = cos(alpha), reset()) : alpha * degrees3;
          };
          projection2.reflectX = function(_) {
            return arguments.length ? (sx = _ ? -1 : 1, reset()) : sx < 0;
          };
          projection2.reflectY = function(_) {
            return arguments.length ? (sy = _ ? -1 : 1, reset()) : sy < 0;
          };
          projection2.fitExtent = function(extent2, object2) {
            return fitExtent(projection2, extent2, object2);
          };
          projection2.fitSize = function(size, object2) {
            return fitSize(projection2, size, object2);
          };
          projection2.fitWidth = function(width, object2) {
            return fitWidth(projection2, width, object2);
          };
          projection2.fitHeight = function(height, object2) {
            return fitHeight(projection2, height, object2);
          };
          return projection2;
        }
        function naturalEarth1Raw(lambda, phi) {
          var phi2 = phi * phi, phi4 = phi2 * phi2;
          return [
            lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (3971e-6 * phi2 - 1529e-6 * phi4))),
            phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 5916e-6 * phi4)))
          ];
        }
        naturalEarth1Raw.invert = function(x, y) {
          var phi = y, i = 25, delta;
          do {
            var phi2 = phi * phi, phi4 = phi2 * phi2;
            phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 5916e-6 * phi4))) - y) / (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 5916e-6 * 11 * phi4)));
          } while (abs(delta) > epsilon && --i > 0);
          return [
            x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (3971e-6 - 1529e-6 * phi2)))),
            phi
          ];
        };
        function naturalEarth1() {
          return projection(naturalEarth1Raw).scale(175.295);
        }
        function orthographicRaw(x, y) {
          return [cos(y) * sin(x), sin(y)];
        }
        orthographicRaw.invert = azimuthalInvert(asin);
        function orthographic() {
          return projection(orthographicRaw).scale(249.5).clipAngle(90 + epsilon);
        }
        function stereographicRaw(x, y) {
          var cy = cos(y), k = 1 + cos(x) * cy;
          return [cy * sin(x) / k, sin(y) / k];
        }
        stereographicRaw.invert = azimuthalInvert(function(z) {
          return 2 * atan(z);
        });
        function stereographic() {
          return projection(stereographicRaw).scale(250).clipAngle(142);
        }
        function transverseMercatorRaw(lambda, phi) {
          return [log(tan((halfPi + phi) / 2)), -lambda];
        }
        transverseMercatorRaw.invert = function(x, y) {
          return [-y, 2 * atan(exp(x)) - halfPi];
        };
        function transverseMercator() {
          var m = mercatorProjection(transverseMercatorRaw), center = m.center, rotate = m.rotate;
          m.center = function(_) {
            return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);
          };
          m.rotate = function(_) {
            return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);
          };
          return rotate([0, 0, 90]).scale(159.155);
        }
        exports2.geoAlbers = albers;
        exports2.geoAlbersUsa = albersUsa;
        exports2.geoArea = area;
        exports2.geoAzimuthalEqualArea = azimuthalEqualArea;
        exports2.geoAzimuthalEqualAreaRaw = azimuthalEqualAreaRaw;
        exports2.geoAzimuthalEquidistant = azimuthalEquidistant;
        exports2.geoAzimuthalEquidistantRaw = azimuthalEquidistantRaw;
        exports2.geoBounds = bounds;
        exports2.geoCentroid = centroid;
        exports2.geoCircle = circle;
        exports2.geoClipAntimeridian = clipAntimeridian;
        exports2.geoClipCircle = clipCircle;
        exports2.geoClipExtent = extent;
        exports2.geoClipRectangle = clipRectangle;
        exports2.geoConicConformal = conicConformal;
        exports2.geoConicConformalRaw = conicConformalRaw;
        exports2.geoConicEqualArea = conicEqualArea;
        exports2.geoConicEqualAreaRaw = conicEqualAreaRaw;
        exports2.geoConicEquidistant = conicEquidistant;
        exports2.geoConicEquidistantRaw = conicEquidistantRaw;
        exports2.geoContains = contains;
        exports2.geoDistance = distance;
        exports2.geoEqualEarth = equalEarth;
        exports2.geoEqualEarthRaw = equalEarthRaw;
        exports2.geoEquirectangular = equirectangular;
        exports2.geoEquirectangularRaw = equirectangularRaw;
        exports2.geoGnomonic = gnomonic;
        exports2.geoGnomonicRaw = gnomonicRaw;
        exports2.geoGraticule = graticule;
        exports2.geoGraticule10 = graticule10;
        exports2.geoIdentity = identity$1;
        exports2.geoInterpolate = interpolate;
        exports2.geoLength = length;
        exports2.geoMercator = mercator;
        exports2.geoMercatorRaw = mercatorRaw;
        exports2.geoNaturalEarth1 = naturalEarth1;
        exports2.geoNaturalEarth1Raw = naturalEarth1Raw;
        exports2.geoOrthographic = orthographic;
        exports2.geoOrthographicRaw = orthographicRaw;
        exports2.geoPath = index;
        exports2.geoProjection = projection;
        exports2.geoProjectionMutator = projectionMutator;
        exports2.geoRotation = rotation;
        exports2.geoStereographic = stereographic;
        exports2.geoStereographicRaw = stereographicRaw;
        exports2.geoStream = geoStream;
        exports2.geoTransform = transform;
        exports2.geoTransverseMercator = transverseMercator;
        exports2.geoTransverseMercatorRaw = transverseMercatorRaw;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-geo-projection/dist/d3-geo-projection.js
  var require_d3_geo_projection = __commonJS({
    "node_modules/d3-geo-projection/dist/d3-geo-projection.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require_d3_geo(), require_d3_array()) : typeof define === "function" && false ? define(["exports", "d3-geo", "d3-array"], factory) : factory(global2.d3 = global2.d3 || {}, global2.d3, global2.d3);
      })(exports, function(exports2, d3Geo, d3Array) {
        "use strict";
        var abs = Math.abs;
        var atan = Math.atan;
        var atan2 = Math.atan2;
        var cos = Math.cos;
        var exp = Math.exp;
        var floor = Math.floor;
        var log = Math.log;
        var max = Math.max;
        var min = Math.min;
        var pow = Math.pow;
        var round = Math.round;
        var sign = Math.sign || function(x) {
          return x > 0 ? 1 : x < 0 ? -1 : 0;
        };
        var sin = Math.sin;
        var tan = Math.tan;
        var epsilon = 1e-6;
        var epsilon22 = 1e-12;
        var pi = Math.PI;
        var halfPi = pi / 2;
        var quarterPi = pi / 4;
        var sqrt1_2 = Math.SQRT1_2;
        var sqrt2 = sqrt(2);
        var sqrtPi = sqrt(pi);
        var tau = pi * 2;
        var degrees3 = 180 / pi;
        var radians2 = pi / 180;
        function sinci(x) {
          return x ? x / Math.sin(x) : 1;
        }
        function asin(x) {
          return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);
        }
        function acos(x) {
          return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
        }
        function sqrt(x) {
          return x > 0 ? Math.sqrt(x) : 0;
        }
        function tanh2(x) {
          x = exp(2 * x);
          return (x - 1) / (x + 1);
        }
        function sinh2(x) {
          return (exp(x) - exp(-x)) / 2;
        }
        function cosh2(x) {
          return (exp(x) + exp(-x)) / 2;
        }
        function arsinh(x) {
          return log(x + sqrt(x * x + 1));
        }
        function arcosh(x) {
          return log(x + sqrt(x * x - 1));
        }
        function airyRaw(beta) {
          var tanBeta_2 = tan(beta / 2), b = 2 * log(cos(beta / 2)) / (tanBeta_2 * tanBeta_2);
          function forward(x, y) {
            var cosx = cos(x), cosy = cos(y), siny = sin(y), cosz = cosy * cosx, k2 = -((1 - cosz ? log((1 + cosz) / 2) / (1 - cosz) : -0.5) + b / (1 + cosz));
            return [k2 * cosy * sin(x), k2 * siny];
          }
          forward.invert = function(x, y) {
            var r = sqrt(x * x + y * y), z = -beta / 2, i = 50, delta;
            if (!r) return [0, 0];
            do {
              var z_2 = z / 2, cosz_2 = cos(z_2), sinz_2 = sin(z_2), tanz_2 = sinz_2 / cosz_2, lnsecz_2 = -log(abs(cosz_2));
              z -= delta = (2 / tanz_2 * lnsecz_2 - b * tanz_2 - r) / (-lnsecz_2 / (sinz_2 * sinz_2) + 1 - b / (2 * cosz_2 * cosz_2)) * (cosz_2 < 0 ? 0.7 : 1);
            } while (abs(delta) > epsilon && --i > 0);
            var sinz = sin(z);
            return [atan2(x * sinz, r * cos(z)), asin(y * sinz / r)];
          };
          return forward;
        }
        function airy() {
          var beta = halfPi, m = d3Geo.geoProjectionMutator(airyRaw), p = m(beta);
          p.radius = function(_) {
            return arguments.length ? m(beta = _ * radians2) : beta * degrees3;
          };
          return p.scale(179.976).clipAngle(147);
        }
        function aitoffRaw(x, y) {
          var cosy = cos(y), sincia = sinci(acos(cosy * cos(x /= 2)));
          return [2 * cosy * sin(x) * sincia, sin(y) * sincia];
        }
        aitoffRaw.invert = function(x, y) {
          if (x * x + 4 * y * y > pi * pi + epsilon) return;
          var x12 = x, y12 = y, i = 25;
          do {
            var sinx = sin(x12), sinx_2 = sin(x12 / 2), cosx_2 = cos(x12 / 2), siny = sin(y12), cosy = cos(y12), sin_2y = sin(2 * y12), sin2y = siny * siny, cos2y = cosy * cosy, sin2x_2 = sinx_2 * sinx_2, c = 1 - cos2y * cosx_2 * cosx_2, e = c ? acos(cosy * cosx_2) * sqrt(f = 1 / c) : f = 0, f, fx = 2 * e * cosy * sinx_2 - x, fy = e * siny - y, dxdx = f * (cos2y * sin2x_2 + e * cosy * cosx_2 * sin2y), dxdy = f * (0.5 * sinx * sin_2y - e * 2 * siny * sinx_2), dydx = f * 0.25 * (sin_2y * sinx_2 - e * siny * cos2y * sinx), dydy = f * (sin2y * cosx_2 + e * sin2x_2 * cosy), z = dxdy * dydx - dydy * dxdx;
            if (!z) break;
            var dx = (fy * dxdy - fx * dydy) / z, dy = (fx * dydx - fy * dxdx) / z;
            x12 -= dx, y12 -= dy;
          } while ((abs(dx) > epsilon || abs(dy) > epsilon) && --i > 0);
          return [x12, y12];
        };
        function aitoff() {
          return d3Geo.geoProjection(aitoffRaw).scale(152.63);
        }
        function armadilloRaw(phi02) {
          var sinPhi0 = sin(phi02), cosPhi0 = cos(phi02), sPhi0 = phi02 >= 0 ? 1 : -1, tanPhi0 = tan(sPhi0 * phi02), k2 = (1 + sinPhi0 - cosPhi0) / 2;
          function forward(lambda, phi) {
            var cosPhi = cos(phi), cosLambda = cos(lambda /= 2);
            return [
              (1 + cosPhi) * sin(lambda),
              (sPhi0 * phi > -atan2(cosLambda, tanPhi0) - 1e-3 ? 0 : -sPhi0 * 10) + k2 + sin(phi) * cosPhi0 - (1 + cosPhi) * sinPhi0 * cosLambda
              // TODO D3 core should allow null or [NaN, NaN] to be returned.
            ];
          }
          forward.invert = function(x, y) {
            var lambda = 0, phi = 0, i = 50;
            do {
              var cosLambda = cos(lambda), sinLambda = sin(lambda), cosPhi = cos(phi), sinPhi = sin(phi), A3 = 1 + cosPhi, fx = A3 * sinLambda - x, fy = k2 + sinPhi * cosPhi0 - A3 * sinPhi0 * cosLambda - y, dxdLambda = A3 * cosLambda / 2, dxdPhi = -sinLambda * sinPhi, dydLambda = sinPhi0 * A3 * sinLambda / 2, dydPhi = cosPhi0 * cosPhi + sinPhi0 * cosLambda * sinPhi, denominator = dxdPhi * dydLambda - dydPhi * dxdLambda, dLambda = (fy * dxdPhi - fx * dydPhi) / denominator / 2, dPhi = (fx * dydLambda - fy * dxdLambda) / denominator;
              if (abs(dPhi) > 2) dPhi /= 2;
              lambda -= dLambda, phi -= dPhi;
            } while ((abs(dLambda) > epsilon || abs(dPhi) > epsilon) && --i > 0);
            return sPhi0 * phi > -atan2(cos(lambda), tanPhi0) - 1e-3 ? [lambda * 2, phi] : null;
          };
          return forward;
        }
        function armadillo() {
          var phi02 = 20 * radians2, sPhi0 = phi02 >= 0 ? 1 : -1, tanPhi0 = tan(sPhi0 * phi02), m = d3Geo.geoProjectionMutator(armadilloRaw), p = m(phi02), stream_ = p.stream;
          p.parallel = function(_) {
            if (!arguments.length) return phi02 * degrees3;
            tanPhi0 = tan((sPhi0 = (phi02 = _ * radians2) >= 0 ? 1 : -1) * phi02);
            return m(phi02);
          };
          p.stream = function(stream) {
            var rotate = p.rotate(), rotateStream = stream_(stream), sphereStream = (p.rotate([0, 0]), stream_(stream)), precision = p.precision();
            p.rotate(rotate);
            rotateStream.sphere = function() {
              sphereStream.polygonStart(), sphereStream.lineStart();
              for (var lambda = sPhi0 * -180; sPhi0 * lambda < 180; lambda += sPhi0 * 90)
                sphereStream.point(lambda, sPhi0 * 90);
              if (phi02) while (sPhi0 * (lambda -= 3 * sPhi0 * precision) >= -180) {
                sphereStream.point(lambda, sPhi0 * -atan2(cos(lambda * radians2 / 2), tanPhi0) * degrees3);
              }
              sphereStream.lineEnd(), sphereStream.polygonEnd();
            };
            return rotateStream;
          };
          return p.scale(218.695).center([0, 28.0974]);
        }
        function augustRaw(lambda, phi) {
          var tanPhi = tan(phi / 2), k2 = sqrt(1 - tanPhi * tanPhi), c = 1 + k2 * cos(lambda /= 2), x = sin(lambda) * k2 / c, y = tanPhi / c, x2 = x * x, y2 = y * y;
          return [
            4 / 3 * x * (3 + x2 - 3 * y2),
            4 / 3 * y * (3 + 3 * x2 - y2)
          ];
        }
        augustRaw.invert = function(x, y) {
          x *= 3 / 8, y *= 3 / 8;
          if (!x && abs(y) > 1) return null;
          var x2 = x * x, y2 = y * y, s = 1 + x2 + y2, sin3Eta = sqrt((s - sqrt(s * s - 4 * y * y)) / 2), eta = asin(sin3Eta) / 3, xi = sin3Eta ? arcosh(abs(y / sin3Eta)) / 3 : arsinh(abs(x)) / 3, cosEta = cos(eta), coshXi = cosh2(xi), d = coshXi * coshXi - cosEta * cosEta;
          return [
            sign(x) * 2 * atan2(sinh2(xi) * cosEta, 0.25 - d),
            sign(y) * 2 * atan2(coshXi * sin(eta), 0.25 + d)
          ];
        };
        function august() {
          return d3Geo.geoProjection(augustRaw).scale(66.1603);
        }
        var sqrt8 = sqrt(8), phi0 = log(1 + sqrt2);
        function bakerRaw(lambda, phi) {
          var phi02 = abs(phi);
          return phi02 < quarterPi ? [lambda, log(tan(quarterPi + phi / 2))] : [lambda * cos(phi02) * (2 * sqrt2 - 1 / sin(phi02)), sign(phi) * (2 * sqrt2 * (phi02 - quarterPi) - log(tan(phi02 / 2)))];
        }
        bakerRaw.invert = function(x, y) {
          if ((y02 = abs(y)) < phi0) return [x, 2 * atan(exp(y)) - halfPi];
          var phi = quarterPi, i = 25, delta, y02;
          do {
            var cosPhi_2 = cos(phi / 2), tanPhi_2 = tan(phi / 2);
            phi -= delta = (sqrt8 * (phi - quarterPi) - log(tanPhi_2) - y02) / (sqrt8 - cosPhi_2 * cosPhi_2 / (2 * tanPhi_2));
          } while (abs(delta) > epsilon22 && --i > 0);
          return [x / (cos(phi) * (sqrt8 - 1 / sin(phi))), sign(y) * phi];
        };
        function baker() {
          return d3Geo.geoProjection(bakerRaw).scale(112.314);
        }
        function berghausRaw(lobes2) {
          var k2 = 2 * pi / lobes2;
          function forward(lambda, phi) {
            var p = d3Geo.geoAzimuthalEquidistantRaw(lambda, phi);
            if (abs(lambda) > halfPi) {
              var theta = atan2(p[1], p[0]), r = sqrt(p[0] * p[0] + p[1] * p[1]), theta0 = k2 * round((theta - halfPi) / k2) + halfPi, alpha = atan2(sin(theta -= theta0), 2 - cos(theta));
              theta = theta0 + asin(pi / r * sin(alpha)) - alpha;
              p[0] = r * cos(theta);
              p[1] = r * sin(theta);
            }
            return p;
          }
          forward.invert = function(x, y) {
            var r = sqrt(x * x + y * y);
            if (r > halfPi) {
              var theta = atan2(y, x), theta0 = k2 * round((theta - halfPi) / k2) + halfPi, s = theta > theta0 ? -1 : 1, A3 = r * cos(theta0 - theta), cotAlpha = 1 / tan(s * acos((A3 - pi) / sqrt(pi * (pi - 2 * A3) + r * r)));
              theta = theta0 + 2 * atan((cotAlpha + s * sqrt(cotAlpha * cotAlpha - 3)) / 3);
              x = r * cos(theta), y = r * sin(theta);
            }
            return d3Geo.geoAzimuthalEquidistantRaw.invert(x, y);
          };
          return forward;
        }
        function berghaus() {
          var lobes2 = 5, m = d3Geo.geoProjectionMutator(berghausRaw), p = m(lobes2), projectionStream = p.stream, epsilon$$1 = 0.01, cr = -cos(epsilon$$1 * radians2), sr = sin(epsilon$$1 * radians2);
          p.lobes = function(_) {
            return arguments.length ? m(lobes2 = +_) : lobes2;
          };
          p.stream = function(stream) {
            var rotate = p.rotate(), rotateStream = projectionStream(stream), sphereStream = (p.rotate([0, 0]), projectionStream(stream));
            p.rotate(rotate);
            rotateStream.sphere = function() {
              sphereStream.polygonStart(), sphereStream.lineStart();
              for (var i = 0, delta = 360 / lobes2, delta0 = 2 * pi / lobes2, phi = 90 - 180 / lobes2, phi02 = halfPi; i < lobes2; ++i, phi -= delta, phi02 -= delta0) {
                sphereStream.point(atan2(sr * cos(phi02), cr) * degrees3, asin(sr * sin(phi02)) * degrees3);
                if (phi < -90) {
                  sphereStream.point(-90, -180 - phi - epsilon$$1);
                  sphereStream.point(-90, -180 - phi + epsilon$$1);
                } else {
                  sphereStream.point(90, phi + epsilon$$1);
                  sphereStream.point(90, phi - epsilon$$1);
                }
              }
              sphereStream.lineEnd(), sphereStream.polygonEnd();
            };
            return rotateStream;
          };
          return p.scale(87.8076).center([0, 17.1875]).clipAngle(180 - 1e-3);
        }
        function hammerRaw(A3, B3) {
          if (arguments.length < 2) B3 = A3;
          if (B3 === 1) return d3Geo.geoAzimuthalEqualAreaRaw;
          if (B3 === Infinity) return hammerQuarticAuthalicRaw;
          function forward(lambda, phi) {
            var coordinates = d3Geo.geoAzimuthalEqualAreaRaw(lambda / B3, phi);
            coordinates[0] *= A3;
            return coordinates;
          }
          forward.invert = function(x, y) {
            var coordinates = d3Geo.geoAzimuthalEqualAreaRaw.invert(x / A3, y);
            coordinates[0] *= B3;
            return coordinates;
          };
          return forward;
        }
        function hammerQuarticAuthalicRaw(lambda, phi) {
          return [
            lambda * cos(phi) / cos(phi /= 2),
            2 * sin(phi)
          ];
        }
        hammerQuarticAuthalicRaw.invert = function(x, y) {
          var phi = 2 * asin(y / 2);
          return [
            x * cos(phi / 2) / cos(phi),
            phi
          ];
        };
        function hammer() {
          var B3 = 2, m = d3Geo.geoProjectionMutator(hammerRaw), p = m(B3);
          p.coefficient = function(_) {
            if (!arguments.length) return B3;
            return m(B3 = +_);
          };
          return p.scale(169.529);
        }
        function solve(f, y, x) {
          var steps = 100, delta, f0, f1;
          x = x === void 0 ? 0 : +x;
          y = +y;
          do {
            f0 = f(x);
            f1 = f(x + epsilon);
            if (f0 === f1) f1 = f0 + epsilon;
            x -= delta = -1 * epsilon * (f0 - y) / (f0 - f1);
          } while (steps-- > 0 && abs(delta) > epsilon);
          return steps < 0 ? NaN : x;
        }
        function solve2d(f, MAX_ITERATIONS, eps) {
          if (MAX_ITERATIONS === void 0) MAX_ITERATIONS = 40;
          if (eps === void 0) eps = epsilon22;
          return function(x, y, a, b) {
            var err2, da, db;
            a = a === void 0 ? 0 : +a;
            b = b === void 0 ? 0 : +b;
            for (var i = 0; i < MAX_ITERATIONS; i++) {
              var p = f(a, b), tx = p[0] - x, ty = p[1] - y;
              if (abs(tx) < eps && abs(ty) < eps) break;
              var h = tx * tx + ty * ty;
              if (h > err2) {
                a -= da /= 2;
                b -= db /= 2;
                continue;
              }
              err2 = h;
              var ea = (a > 0 ? -1 : 1) * eps, eb = (b > 0 ? -1 : 1) * eps, pa = f(a + ea, b), pb = f(a, b + eb), dxa = (pa[0] - p[0]) / ea, dya = (pa[1] - p[1]) / ea, dxb = (pb[0] - p[0]) / eb, dyb = (pb[1] - p[1]) / eb, D2 = dyb * dxa - dya * dxb, l = (abs(D2) < 0.5 ? 0.5 : 1) / D2;
              da = (ty * dxb - tx * dyb) * l;
              db = (tx * dya - ty * dxa) * l;
              a += da;
              b += db;
              if (abs(da) < eps && abs(db) < eps) break;
            }
            return [a, b];
          };
        }
        function bertin1953Raw() {
          var hammer$$1 = hammerRaw(1.68, 2), fu = 1.4, k2 = 12;
          function forward(lambda, phi) {
            if (lambda + phi < -fu) {
              var u = (lambda - phi + 1.6) * (lambda + phi + fu) / 8;
              lambda += u;
              phi -= 0.8 * u * sin(phi + pi / 2);
            }
            var r = hammer$$1(lambda, phi);
            var d = (1 - cos(lambda * phi)) / k2;
            if (r[1] < 0) {
              r[0] *= 1 + d;
            }
            if (r[1] > 0) {
              r[1] *= 1 + d / 1.5 * r[0] * r[0];
            }
            return r;
          }
          forward.invert = solve2d(forward);
          return forward;
        }
        function bertin() {
          return d3Geo.geoProjection(bertin1953Raw()).rotate([-16.5, -42]).scale(176.57).center([7.93, 0.09]);
        }
        function mollweideBromleyTheta(cp, phi) {
          var cpsinPhi = cp * sin(phi), i = 30, delta;
          do
            phi -= delta = (phi + sin(phi) - cpsinPhi) / (1 + cos(phi));
          while (abs(delta) > epsilon && --i > 0);
          return phi / 2;
        }
        function mollweideBromleyRaw(cx, cy, cp) {
          function forward(lambda, phi) {
            return [cx * lambda * cos(phi = mollweideBromleyTheta(cp, phi)), cy * sin(phi)];
          }
          forward.invert = function(x, y) {
            return y = asin(y / cy), [x / (cx * cos(y)), asin((2 * y + sin(2 * y)) / cp)];
          };
          return forward;
        }
        var mollweideRaw = mollweideBromleyRaw(sqrt2 / halfPi, sqrt2, pi);
        function mollweide() {
          return d3Geo.geoProjection(mollweideRaw).scale(169.529);
        }
        var k = 2.00276, w = 1.11072;
        function boggsRaw(lambda, phi) {
          var theta = mollweideBromleyTheta(pi, phi);
          return [k * lambda / (1 / cos(phi) + w / cos(theta)), (phi + sqrt2 * sin(theta)) / k];
        }
        boggsRaw.invert = function(x, y) {
          var ky = k * y, theta = y < 0 ? -quarterPi : quarterPi, i = 25, delta, phi;
          do {
            phi = ky - sqrt2 * sin(theta);
            theta -= delta = (sin(2 * theta) + 2 * theta - pi * sin(phi)) / (2 * cos(2 * theta) + 2 + pi * cos(phi) * sqrt2 * cos(theta));
          } while (abs(delta) > epsilon && --i > 0);
          phi = ky - sqrt2 * sin(theta);
          return [x * (1 / cos(phi) + w / cos(theta)) / k, phi];
        };
        function boggs() {
          return d3Geo.geoProjection(boggsRaw).scale(160.857);
        }
        function parallel1(projectAt) {
          var phi02 = 0, m = d3Geo.geoProjectionMutator(projectAt), p = m(phi02);
          p.parallel = function(_) {
            return arguments.length ? m(phi02 = _ * radians2) : phi02 * degrees3;
          };
          return p;
        }
        function sinusoidalRaw(lambda, phi) {
          return [lambda * cos(phi), phi];
        }
        sinusoidalRaw.invert = function(x, y) {
          return [x / cos(y), y];
        };
        function sinusoidal() {
          return d3Geo.geoProjection(sinusoidalRaw).scale(152.63);
        }
        function bonneRaw(phi02) {
          if (!phi02) return sinusoidalRaw;
          var cotPhi0 = 1 / tan(phi02);
          function forward(lambda, phi) {
            var rho = cotPhi0 + phi02 - phi, e = rho ? lambda * cos(phi) / rho : rho;
            return [rho * sin(e), cotPhi0 - rho * cos(e)];
          }
          forward.invert = function(x, y) {
            var rho = sqrt(x * x + (y = cotPhi0 - y) * y), phi = cotPhi0 + phi02 - rho;
            return [rho / cos(phi) * atan2(x, y), phi];
          };
          return forward;
        }
        function bonne() {
          return parallel1(bonneRaw).scale(123.082).center([0, 26.1441]).parallel(45);
        }
        function bottomleyRaw(sinPsi) {
          function forward(lambda, phi) {
            var rho = halfPi - phi, eta = rho ? lambda * sinPsi * sin(rho) / rho : rho;
            return [rho * sin(eta) / sinPsi, halfPi - rho * cos(eta)];
          }
          forward.invert = function(x, y) {
            var x12 = x * sinPsi, y12 = halfPi - y, rho = sqrt(x12 * x12 + y12 * y12), eta = atan2(x12, y12);
            return [(rho ? rho / sin(rho) : 1) * eta / sinPsi, halfPi - rho];
          };
          return forward;
        }
        function bottomley() {
          var sinPsi = 0.5, m = d3Geo.geoProjectionMutator(bottomleyRaw), p = m(sinPsi);
          p.fraction = function(_) {
            return arguments.length ? m(sinPsi = +_) : sinPsi;
          };
          return p.scale(158.837);
        }
        var bromleyRaw = mollweideBromleyRaw(1, 4 / pi, pi);
        function bromley() {
          return d3Geo.geoProjection(bromleyRaw).scale(152.63);
        }
        function distance(dPhi, c1, s1, c2, s2, dLambda) {
          var cosdLambda = cos(dLambda), r;
          if (abs(dPhi) > 1 || abs(dLambda) > 1) {
            r = acos(s1 * s2 + c1 * c2 * cosdLambda);
          } else {
            var sindPhi = sin(dPhi / 2), sindLambda = sin(dLambda / 2);
            r = 2 * asin(sqrt(sindPhi * sindPhi + c1 * c2 * sindLambda * sindLambda));
          }
          return abs(r) > epsilon ? [r, atan2(c2 * sin(dLambda), c1 * s2 - s1 * c2 * cosdLambda)] : [0, 0];
        }
        function angle(b, c, a) {
          return acos((b * b + c * c - a * a) / (2 * b * c));
        }
        function longitude(lambda) {
          return lambda - 2 * pi * floor((lambda + pi) / (2 * pi));
        }
        function chamberlinRaw(p0, p1, p2) {
          var points2 = [
            [p0[0], p0[1], sin(p0[1]), cos(p0[1])],
            [p1[0], p1[1], sin(p1[1]), cos(p1[1])],
            [p2[0], p2[1], sin(p2[1]), cos(p2[1])]
          ];
          for (var a = points2[2], b, i = 0; i < 3; ++i, a = b) {
            b = points2[i];
            a.v = distance(b[1] - a[1], a[3], a[2], b[3], b[2], b[0] - a[0]);
            a.point = [0, 0];
          }
          var beta0 = angle(points2[0].v[0], points2[2].v[0], points2[1].v[0]), beta1 = angle(points2[0].v[0], points2[1].v[0], points2[2].v[0]), beta2 = pi - beta0;
          points2[2].point[1] = 0;
          points2[0].point[0] = -(points2[1].point[0] = points2[0].v[0] / 2);
          var mean = [
            points2[2].point[0] = points2[0].point[0] + points2[2].v[0] * cos(beta0),
            2 * (points2[0].point[1] = points2[1].point[1] = points2[2].v[0] * sin(beta0))
          ];
          function forward(lambda, phi) {
            var sinPhi = sin(phi), cosPhi = cos(phi), v = new Array(3), i2;
            for (i2 = 0; i2 < 3; ++i2) {
              var p = points2[i2];
              v[i2] = distance(phi - p[1], p[3], p[2], cosPhi, sinPhi, lambda - p[0]);
              if (!v[i2][0]) return p.point;
              v[i2][1] = longitude(v[i2][1] - p.v[1]);
            }
            var point = mean.slice();
            for (i2 = 0; i2 < 3; ++i2) {
              var j = i2 == 2 ? 0 : i2 + 1;
              var a2 = angle(points2[i2].v[0], v[i2][0], v[j][0]);
              if (v[i2][1] < 0) a2 = -a2;
              if (!i2) {
                point[0] += v[i2][0] * cos(a2);
                point[1] -= v[i2][0] * sin(a2);
              } else if (i2 == 1) {
                a2 = beta1 - a2;
                point[0] -= v[i2][0] * cos(a2);
                point[1] -= v[i2][0] * sin(a2);
              } else {
                a2 = beta2 - a2;
                point[0] += v[i2][0] * cos(a2);
                point[1] += v[i2][0] * sin(a2);
              }
            }
            point[0] /= 3, point[1] /= 3;
            return point;
          }
          return forward;
        }
        function pointRadians(p) {
          return p[0] *= radians2, p[1] *= radians2, p;
        }
        function chamberlinAfrica() {
          return chamberlin([0, 22], [45, 22], [22.5, -22]).scale(380).center([22.5, 2]);
        }
        function chamberlin(p0, p1, p2) {
          var c = d3Geo.geoCentroid({ type: "MultiPoint", coordinates: [p0, p1, p2] }), R = [-c[0], -c[1]], r = d3Geo.geoRotation(R), f = chamberlinRaw(pointRadians(r(p0)), pointRadians(r(p1)), pointRadians(r(p2)));
          f.invert = solve2d(f);
          var p = d3Geo.geoProjection(f).rotate(R), center = p.center;
          delete p.rotate;
          p.center = function(_) {
            return arguments.length ? center(r(_)) : r.invert(center());
          };
          return p.clipAngle(90);
        }
        function collignonRaw(lambda, phi) {
          var alpha = sqrt(1 - sin(phi));
          return [2 / sqrtPi * lambda * alpha, sqrtPi * (1 - alpha)];
        }
        collignonRaw.invert = function(x, y) {
          var lambda = (lambda = y / sqrtPi - 1) * lambda;
          return [lambda > 0 ? x * sqrt(pi / lambda) / 2 : 0, asin(1 - lambda)];
        };
        function collignon() {
          return d3Geo.geoProjection(collignonRaw).scale(95.6464).center([0, 30]);
        }
        function craigRaw(phi02) {
          var tanPhi0 = tan(phi02);
          function forward(lambda, phi) {
            return [lambda, (lambda ? lambda / sin(lambda) : 1) * (sin(phi) * cos(lambda) - tanPhi0 * cos(phi))];
          }
          forward.invert = tanPhi0 ? function(x, y) {
            if (x) y *= sin(x) / x;
            var cosLambda = cos(x);
            return [x, 2 * atan2(sqrt(cosLambda * cosLambda + tanPhi0 * tanPhi0 - y * y) - cosLambda, tanPhi0 - y)];
          } : function(x, y) {
            return [x, asin(x ? y * tan(x) / x : y)];
          };
          return forward;
        }
        function craig() {
          return parallel1(craigRaw).scale(249.828).clipAngle(90);
        }
        var sqrt3 = sqrt(3);
        function crasterRaw(lambda, phi) {
          return [sqrt3 * lambda * (2 * cos(2 * phi / 3) - 1) / sqrtPi, sqrt3 * sqrtPi * sin(phi / 3)];
        }
        crasterRaw.invert = function(x, y) {
          var phi = 3 * asin(y / (sqrt3 * sqrtPi));
          return [sqrtPi * x / (sqrt3 * (2 * cos(2 * phi / 3) - 1)), phi];
        };
        function craster() {
          return d3Geo.geoProjection(crasterRaw).scale(156.19);
        }
        function cylindricalEqualAreaRaw(phi02) {
          var cosPhi0 = cos(phi02);
          function forward(lambda, phi) {
            return [lambda * cosPhi0, sin(phi) / cosPhi0];
          }
          forward.invert = function(x, y) {
            return [x / cosPhi0, asin(y * cosPhi0)];
          };
          return forward;
        }
        function cylindricalEqualArea() {
          return parallel1(cylindricalEqualAreaRaw).parallel(38.58).scale(195.044);
        }
        function cylindricalStereographicRaw(phi02) {
          var cosPhi0 = cos(phi02);
          function forward(lambda, phi) {
            return [lambda * cosPhi0, (1 + cosPhi0) * tan(phi / 2)];
          }
          forward.invert = function(x, y) {
            return [x / cosPhi0, atan(y / (1 + cosPhi0)) * 2];
          };
          return forward;
        }
        function cylindricalStereographic() {
          return parallel1(cylindricalStereographicRaw).scale(124.75);
        }
        function eckert1Raw(lambda, phi) {
          var alpha = sqrt(8 / (3 * pi));
          return [
            alpha * lambda * (1 - abs(phi) / pi),
            alpha * phi
          ];
        }
        eckert1Raw.invert = function(x, y) {
          var alpha = sqrt(8 / (3 * pi)), phi = y / alpha;
          return [
            x / (alpha * (1 - abs(phi) / pi)),
            phi
          ];
        };
        function eckert1() {
          return d3Geo.geoProjection(eckert1Raw).scale(165.664);
        }
        function eckert2Raw(lambda, phi) {
          var alpha = sqrt(4 - 3 * sin(abs(phi)));
          return [
            2 / sqrt(6 * pi) * lambda * alpha,
            sign(phi) * sqrt(2 * pi / 3) * (2 - alpha)
          ];
        }
        eckert2Raw.invert = function(x, y) {
          var alpha = 2 - abs(y) / sqrt(2 * pi / 3);
          return [
            x * sqrt(6 * pi) / (2 * alpha),
            sign(y) * asin((4 - alpha * alpha) / 3)
          ];
        };
        function eckert2() {
          return d3Geo.geoProjection(eckert2Raw).scale(165.664);
        }
        function eckert3Raw(lambda, phi) {
          var k2 = sqrt(pi * (4 + pi));
          return [
            2 / k2 * lambda * (1 + sqrt(1 - 4 * phi * phi / (pi * pi))),
            4 / k2 * phi
          ];
        }
        eckert3Raw.invert = function(x, y) {
          var k2 = sqrt(pi * (4 + pi)) / 2;
          return [
            x * k2 / (1 + sqrt(1 - y * y * (4 + pi) / (4 * pi))),
            y * k2 / 2
          ];
        };
        function eckert3() {
          return d3Geo.geoProjection(eckert3Raw).scale(180.739);
        }
        function eckert4Raw(lambda, phi) {
          var k2 = (2 + halfPi) * sin(phi);
          phi /= 2;
          for (var i = 0, delta = Infinity; i < 10 && abs(delta) > epsilon; i++) {
            var cosPhi = cos(phi);
            phi -= delta = (phi + sin(phi) * (cosPhi + 2) - k2) / (2 * cosPhi * (1 + cosPhi));
          }
          return [
            2 / sqrt(pi * (4 + pi)) * lambda * (1 + cos(phi)),
            2 * sqrt(pi / (4 + pi)) * sin(phi)
          ];
        }
        eckert4Raw.invert = function(x, y) {
          var A3 = y * sqrt((4 + pi) / pi) / 2, k2 = asin(A3), c = cos(k2);
          return [
            x / (2 / sqrt(pi * (4 + pi)) * (1 + c)),
            asin((k2 + A3 * (c + 2)) / (2 + halfPi))
          ];
        };
        function eckert4() {
          return d3Geo.geoProjection(eckert4Raw).scale(180.739);
        }
        function eckert5Raw(lambda, phi) {
          return [
            lambda * (1 + cos(phi)) / sqrt(2 + pi),
            2 * phi / sqrt(2 + pi)
          ];
        }
        eckert5Raw.invert = function(x, y) {
          var k2 = sqrt(2 + pi), phi = y * k2 / 2;
          return [
            k2 * x / (1 + cos(phi)),
            phi
          ];
        };
        function eckert5() {
          return d3Geo.geoProjection(eckert5Raw).scale(173.044);
        }
        function eckert6Raw(lambda, phi) {
          var k2 = (1 + halfPi) * sin(phi);
          for (var i = 0, delta = Infinity; i < 10 && abs(delta) > epsilon; i++) {
            phi -= delta = (phi + sin(phi) - k2) / (1 + cos(phi));
          }
          k2 = sqrt(2 + pi);
          return [
            lambda * (1 + cos(phi)) / k2,
            2 * phi / k2
          ];
        }
        eckert6Raw.invert = function(x, y) {
          var j = 1 + halfPi, k2 = sqrt(j / 2);
          return [
            x * 2 * k2 / (1 + cos(y *= k2)),
            asin((y + sin(y)) / j)
          ];
        };
        function eckert6() {
          return d3Geo.geoProjection(eckert6Raw).scale(173.044);
        }
        var eisenlohrK = 3 + 2 * sqrt2;
        function eisenlohrRaw(lambda, phi) {
          var s0 = sin(lambda /= 2), c0 = cos(lambda), k2 = sqrt(cos(phi)), c1 = cos(phi /= 2), t = sin(phi) / (c1 + sqrt2 * c0 * k2), c = sqrt(2 / (1 + t * t)), v = sqrt((sqrt2 * c1 + (c0 + s0) * k2) / (sqrt2 * c1 + (c0 - s0) * k2));
          return [
            eisenlohrK * (c * (v - 1 / v) - 2 * log(v)),
            eisenlohrK * (c * t * (v + 1 / v) - 2 * atan(t))
          ];
        }
        eisenlohrRaw.invert = function(x, y) {
          if (!(p = augustRaw.invert(x / 1.2, y * 1.065))) return null;
          var lambda = p[0], phi = p[1], i = 20, p;
          x /= eisenlohrK, y /= eisenlohrK;
          do {
            var _0 = lambda / 2, _1 = phi / 2, s0 = sin(_0), c0 = cos(_0), s1 = sin(_1), c1 = cos(_1), cos1 = cos(phi), k2 = sqrt(cos1), t = s1 / (c1 + sqrt2 * c0 * k2), t22 = t * t, c = sqrt(2 / (1 + t22)), v0 = sqrt2 * c1 + (c0 + s0) * k2, v1 = sqrt2 * c1 + (c0 - s0) * k2, v2 = v0 / v1, v = sqrt(v2), vm1v = v - 1 / v, vp1v = v + 1 / v, fx = c * vm1v - 2 * log(v) - x, fy = c * t * vp1v - 2 * atan(t) - y, deltatDeltaLambda = s1 && sqrt1_2 * k2 * s0 * t22 / s1, deltatDeltaPhi = (sqrt2 * c0 * c1 + k2) / (2 * (c1 + sqrt2 * c0 * k2) * (c1 + sqrt2 * c0 * k2) * k2), deltacDeltat = -0.5 * t * c * c * c, deltacDeltaLambda = deltacDeltat * deltatDeltaLambda, deltacDeltaPhi = deltacDeltat * deltatDeltaPhi, A3 = (A3 = 2 * c1 + sqrt2 * k2 * (c0 - s0)) * A3 * v, deltavDeltaLambda = (sqrt2 * c0 * c1 * k2 + cos1) / A3, deltavDeltaPhi = -(sqrt2 * s0 * s1) / (k2 * A3), deltaxDeltaLambda = vm1v * deltacDeltaLambda - 2 * deltavDeltaLambda / v + c * (deltavDeltaLambda + deltavDeltaLambda / v2), deltaxDeltaPhi = vm1v * deltacDeltaPhi - 2 * deltavDeltaPhi / v + c * (deltavDeltaPhi + deltavDeltaPhi / v2), deltayDeltaLambda = t * vp1v * deltacDeltaLambda - 2 * deltatDeltaLambda / (1 + t22) + c * vp1v * deltatDeltaLambda + c * t * (deltavDeltaLambda - deltavDeltaLambda / v2), deltayDeltaPhi = t * vp1v * deltacDeltaPhi - 2 * deltatDeltaPhi / (1 + t22) + c * vp1v * deltatDeltaPhi + c * t * (deltavDeltaPhi - deltavDeltaPhi / v2), denominator = deltaxDeltaPhi * deltayDeltaLambda - deltayDeltaPhi * deltaxDeltaLambda;
            if (!denominator) break;
            var deltaLambda = (fy * deltaxDeltaPhi - fx * deltayDeltaPhi) / denominator, deltaPhi = (fx * deltayDeltaLambda - fy * deltaxDeltaLambda) / denominator;
            lambda -= deltaLambda;
            phi = max(-halfPi, min(halfPi, phi - deltaPhi));
          } while ((abs(deltaLambda) > epsilon || abs(deltaPhi) > epsilon) && --i > 0);
          return abs(abs(phi) - halfPi) < epsilon ? [0, phi] : i && [lambda, phi];
        };
        function eisenlohr() {
          return d3Geo.geoProjection(eisenlohrRaw).scale(62.5271);
        }
        var faheyK = cos(35 * radians2);
        function faheyRaw(lambda, phi) {
          var t = tan(phi / 2);
          return [lambda * faheyK * sqrt(1 - t * t), (1 + faheyK) * t];
        }
        faheyRaw.invert = function(x, y) {
          var t = y / (1 + faheyK);
          return [x && x / (faheyK * sqrt(1 - t * t)), 2 * atan(t)];
        };
        function fahey() {
          return d3Geo.geoProjection(faheyRaw).scale(137.152);
        }
        function foucautRaw(lambda, phi) {
          var k2 = phi / 2, cosk = cos(k2);
          return [2 * lambda / sqrtPi * cos(phi) * cosk * cosk, sqrtPi * tan(k2)];
        }
        foucautRaw.invert = function(x, y) {
          var k2 = atan(y / sqrtPi), cosk = cos(k2), phi = 2 * k2;
          return [x * sqrtPi / 2 / (cos(phi) * cosk * cosk), phi];
        };
        function foucaut() {
          return d3Geo.geoProjection(foucautRaw).scale(135.264);
        }
        function foucautSinusoidalRaw(alpha) {
          var beta = 1 - alpha, equatorial = raw(pi, 0)[0] - raw(-pi, 0)[0], polar = raw(0, halfPi)[1] - raw(0, -halfPi)[1], ratio = sqrt(2 * polar / equatorial);
          function raw(lambda, phi) {
            var cosphi = cos(phi), sinphi = sin(phi);
            return [
              cosphi / (beta + alpha * cosphi) * lambda,
              beta * phi + alpha * sinphi
            ];
          }
          function forward(lambda, phi) {
            var p = raw(lambda, phi);
            return [p[0] * ratio, p[1] / ratio];
          }
          function forwardMeridian(phi) {
            return forward(0, phi)[1];
          }
          forward.invert = function(x, y) {
            var phi = solve(forwardMeridian, y), lambda = x / ratio * (alpha + beta / cos(phi));
            return [lambda, phi];
          };
          return forward;
        }
        function foucautSinusoidal() {
          var alpha = 0.5, m = d3Geo.geoProjectionMutator(foucautSinusoidalRaw), p = m(alpha);
          p.alpha = function(_) {
            return arguments.length ? m(alpha = +_) : alpha;
          };
          return p.scale(168.725);
        }
        function gilbertForward(point) {
          return [point[0] / 2, asin(tan(point[1] / 2 * radians2)) * degrees3];
        }
        function gilbertInvert(point) {
          return [point[0] * 2, 2 * atan(sin(point[1] * radians2)) * degrees3];
        }
        function gilbert(projectionType) {
          if (projectionType == null) projectionType = d3Geo.geoOrthographic;
          var projection = projectionType(), equirectangular = d3Geo.geoEquirectangular().scale(degrees3).precision(0).clipAngle(null).translate([0, 0]);
          function gilbert2(point) {
            return projection(gilbertForward(point));
          }
          if (projection.invert) gilbert2.invert = function(point) {
            return gilbertInvert(projection.invert(point));
          };
          gilbert2.stream = function(stream) {
            var s1 = projection.stream(stream), s0 = equirectangular.stream({
              point: function(lambda, phi) {
                s1.point(lambda / 2, asin(tan(-phi / 2 * radians2)) * degrees3);
              },
              lineStart: function() {
                s1.lineStart();
              },
              lineEnd: function() {
                s1.lineEnd();
              },
              polygonStart: function() {
                s1.polygonStart();
              },
              polygonEnd: function() {
                s1.polygonEnd();
              }
            });
            s0.sphere = s1.sphere;
            return s0;
          };
          function property(name2) {
            gilbert2[name2] = function() {
              return arguments.length ? (projection[name2].apply(projection, arguments), gilbert2) : projection[name2]();
            };
          }
          gilbert2.rotate = function(_) {
            return arguments.length ? (equirectangular.rotate(_), gilbert2) : equirectangular.rotate();
          };
          gilbert2.center = function(_) {
            return arguments.length ? (projection.center(gilbertForward(_)), gilbert2) : gilbertInvert(projection.center());
          };
          property("angle");
          property("clipAngle");
          property("clipExtent");
          property("fitExtent");
          property("fitHeight");
          property("fitSize");
          property("fitWidth");
          property("scale");
          property("translate");
          property("precision");
          return gilbert2.scale(249.5);
        }
        function gingeryRaw(rho, n) {
          var k2 = 2 * pi / n, rho2 = rho * rho;
          function forward(lambda, phi) {
            var p = d3Geo.geoAzimuthalEquidistantRaw(lambda, phi), x = p[0], y = p[1], r2 = x * x + y * y;
            if (r2 > rho2) {
              var r = sqrt(r2), theta = atan2(y, x), theta0 = k2 * round(theta / k2), alpha = theta - theta0, rhoCosAlpha = rho * cos(alpha), k_ = (rho * sin(alpha) - alpha * sin(rhoCosAlpha)) / (halfPi - rhoCosAlpha), s_ = gingeryLength(alpha, k_), e = (pi - rho) / gingeryIntegrate(s_, rhoCosAlpha, pi);
              x = r;
              var i = 50, delta;
              do {
                x -= delta = (rho + gingeryIntegrate(s_, rhoCosAlpha, x) * e - r) / (s_(x) * e);
              } while (abs(delta) > epsilon && --i > 0);
              y = alpha * sin(x);
              if (x < halfPi) y -= k_ * (x - halfPi);
              var s = sin(theta0), c = cos(theta0);
              p[0] = x * c - y * s;
              p[1] = x * s + y * c;
            }
            return p;
          }
          forward.invert = function(x, y) {
            var r2 = x * x + y * y;
            if (r2 > rho2) {
              var r = sqrt(r2), theta = atan2(y, x), theta0 = k2 * round(theta / k2), dTheta = theta - theta0;
              x = r * cos(dTheta);
              y = r * sin(dTheta);
              var x_halfPi = x - halfPi, sinx = sin(x), alpha = y / sinx, delta = x < halfPi ? Infinity : 0, i = 10;
              while (true) {
                var rhosinAlpha = rho * sin(alpha), rhoCosAlpha = rho * cos(alpha), sinRhoCosAlpha = sin(rhoCosAlpha), halfPi_RhoCosAlpha = halfPi - rhoCosAlpha, k_ = (rhosinAlpha - alpha * sinRhoCosAlpha) / halfPi_RhoCosAlpha, s_ = gingeryLength(alpha, k_);
                if (abs(delta) < epsilon22 || !--i) break;
                alpha -= delta = (alpha * sinx - k_ * x_halfPi - y) / (sinx - x_halfPi * 2 * (halfPi_RhoCosAlpha * (rhoCosAlpha + alpha * rhosinAlpha * cos(rhoCosAlpha) - sinRhoCosAlpha) - rhosinAlpha * (rhosinAlpha - alpha * sinRhoCosAlpha)) / (halfPi_RhoCosAlpha * halfPi_RhoCosAlpha));
              }
              r = rho + gingeryIntegrate(s_, rhoCosAlpha, x) * (pi - rho) / gingeryIntegrate(s_, rhoCosAlpha, pi);
              theta = theta0 + alpha;
              x = r * cos(theta);
              y = r * sin(theta);
            }
            return d3Geo.geoAzimuthalEquidistantRaw.invert(x, y);
          };
          return forward;
        }
        function gingeryLength(alpha, k2) {
          return function(x) {
            var y_ = alpha * cos(x);
            if (x < halfPi) y_ -= k2;
            return sqrt(1 + y_ * y_);
          };
        }
        function gingeryIntegrate(f, a, b) {
          var n = 50, h = (b - a) / n, s = f(a) + f(b);
          for (var i = 1, x = a; i < n; ++i) s += 2 * f(x += h);
          return s * 0.5 * h;
        }
        function gingery() {
          var n = 6, rho = 30 * radians2, cRho = cos(rho), sRho = sin(rho), m = d3Geo.geoProjectionMutator(gingeryRaw), p = m(rho, n), stream_ = p.stream, epsilon$$1 = 0.01, cr = -cos(epsilon$$1 * radians2), sr = sin(epsilon$$1 * radians2);
          p.radius = function(_) {
            if (!arguments.length) return rho * degrees3;
            cRho = cos(rho = _ * radians2);
            sRho = sin(rho);
            return m(rho, n);
          };
          p.lobes = function(_) {
            if (!arguments.length) return n;
            return m(rho, n = +_);
          };
          p.stream = function(stream) {
            var rotate = p.rotate(), rotateStream = stream_(stream), sphereStream = (p.rotate([0, 0]), stream_(stream));
            p.rotate(rotate);
            rotateStream.sphere = function() {
              sphereStream.polygonStart(), sphereStream.lineStart();
              for (var i = 0, delta = 2 * pi / n, phi = 0; i < n; ++i, phi -= delta) {
                sphereStream.point(atan2(sr * cos(phi), cr) * degrees3, asin(sr * sin(phi)) * degrees3);
                sphereStream.point(atan2(sRho * cos(phi - delta / 2), cRho) * degrees3, asin(sRho * sin(phi - delta / 2)) * degrees3);
              }
              sphereStream.lineEnd(), sphereStream.polygonEnd();
            };
            return rotateStream;
          };
          return p.rotate([90, -40]).scale(91.7095).clipAngle(180 - 1e-3);
        }
        function ginzburgPolyconicRaw(a, b, c, d, e, f, g, h) {
          if (arguments.length < 8) h = 0;
          function forward(lambda, phi) {
            if (!phi) return [a * lambda / pi, 0];
            var phi2 = phi * phi, xB = a + phi2 * (b + phi2 * (c + phi2 * d)), yB = phi * (e - 1 + phi2 * (f - h + phi2 * g)), m = (xB * xB + yB * yB) / (2 * yB), alpha = lambda * asin(xB / m) / pi;
            return [m * sin(alpha), phi * (1 + phi2 * h) + m * (1 - cos(alpha))];
          }
          forward.invert = function(x, y) {
            var lambda = pi * x / a, phi = y, deltaLambda, deltaPhi, i = 50;
            do {
              var phi2 = phi * phi, xB = a + phi2 * (b + phi2 * (c + phi2 * d)), yB = phi * (e - 1 + phi2 * (f - h + phi2 * g)), p = xB * xB + yB * yB, q = 2 * yB, m = p / q, m2 = m * m, dAlphadLambda = asin(xB / m) / pi, alpha = lambda * dAlphadLambda, xB2 = xB * xB, dxBdPhi = (2 * b + phi2 * (4 * c + phi2 * 6 * d)) * phi, dyBdPhi = e + phi2 * (3 * f + phi2 * 5 * g), dpdPhi = 2 * (xB * dxBdPhi + yB * (dyBdPhi - 1)), dqdPhi = 2 * (dyBdPhi - 1), dmdPhi = (dpdPhi * q - p * dqdPhi) / (q * q), cosAlpha = cos(alpha), sinAlpha = sin(alpha), mcosAlpha = m * cosAlpha, msinAlpha = m * sinAlpha, dAlphadPhi = lambda / pi * (1 / sqrt(1 - xB2 / m2)) * (dxBdPhi * m - xB * dmdPhi) / m2, fx = msinAlpha - x, fy = phi * (1 + phi2 * h) + m - mcosAlpha - y, deltaxDeltaPhi = dmdPhi * sinAlpha + mcosAlpha * dAlphadPhi, deltaxDeltaLambda = mcosAlpha * dAlphadLambda, deltayDeltaPhi = 1 + dmdPhi - (dmdPhi * cosAlpha - msinAlpha * dAlphadPhi), deltayDeltaLambda = msinAlpha * dAlphadLambda, denominator = deltaxDeltaPhi * deltayDeltaLambda - deltayDeltaPhi * deltaxDeltaLambda;
              if (!denominator) break;
              lambda -= deltaLambda = (fy * deltaxDeltaPhi - fx * deltayDeltaPhi) / denominator;
              phi -= deltaPhi = (fx * deltayDeltaLambda - fy * deltaxDeltaLambda) / denominator;
            } while ((abs(deltaLambda) > epsilon || abs(deltaPhi) > epsilon) && --i > 0);
            return [lambda, phi];
          };
          return forward;
        }
        var ginzburg4Raw = ginzburgPolyconicRaw(2.8284, -1.6988, 0.75432, -0.18071, 1.76003, -0.38914, 0.042555);
        function ginzburg4() {
          return d3Geo.geoProjection(ginzburg4Raw).scale(149.995);
        }
        var ginzburg5Raw = ginzburgPolyconicRaw(2.583819, -0.835827, 0.170354, -0.038094, 1.543313, -0.411435, 0.082742);
        function ginzburg5() {
          return d3Geo.geoProjection(ginzburg5Raw).scale(153.93);
        }
        var ginzburg6Raw = ginzburgPolyconicRaw(5 / 6 * pi, -0.62636, -0.0344, 0, 1.3493, -0.05524, 0, 0.045);
        function ginzburg6() {
          return d3Geo.geoProjection(ginzburg6Raw).scale(130.945);
        }
        function ginzburg8Raw(lambda, phi) {
          var lambda2 = lambda * lambda, phi2 = phi * phi;
          return [
            lambda * (1 - 0.162388 * phi2) * (0.87 - 952426e-9 * lambda2 * lambda2),
            phi * (1 + phi2 / 12)
          ];
        }
        ginzburg8Raw.invert = function(x, y) {
          var lambda = x, phi = y, i = 50, delta;
          do {
            var phi2 = phi * phi;
            phi -= delta = (phi * (1 + phi2 / 12) - y) / (1 + phi2 / 4);
          } while (abs(delta) > epsilon && --i > 0);
          i = 50;
          x /= 1 - 0.162388 * phi2;
          do {
            var lambda4 = (lambda4 = lambda * lambda) * lambda4;
            lambda -= delta = (lambda * (0.87 - 952426e-9 * lambda4) - x) / (0.87 - 476213e-8 * lambda4);
          } while (abs(delta) > epsilon && --i > 0);
          return [lambda, phi];
        };
        function ginzburg8() {
          return d3Geo.geoProjection(ginzburg8Raw).scale(131.747);
        }
        var ginzburg9Raw = ginzburgPolyconicRaw(2.6516, -0.76534, 0.19123, -0.047094, 1.36289, -0.13965, 0.031762);
        function ginzburg9() {
          return d3Geo.geoProjection(ginzburg9Raw).scale(131.087);
        }
        function squareRaw(project) {
          var dx = project(halfPi, 0)[0] - project(-halfPi, 0)[0];
          function projectSquare(lambda, phi) {
            var s = lambda > 0 ? -0.5 : 0.5, point = project(lambda + s * pi, phi);
            point[0] -= s * dx;
            return point;
          }
          if (project.invert) projectSquare.invert = function(x, y) {
            var s = x > 0 ? -0.5 : 0.5, location2 = project.invert(x + s * dx, y), lambda = location2[0] - s * pi;
            if (lambda < -pi) lambda += 2 * pi;
            else if (lambda > pi) lambda -= 2 * pi;
            location2[0] = lambda;
            return location2;
          };
          return projectSquare;
        }
        function gringortenRaw(lambda, phi) {
          var sLambda = sign(lambda), sPhi = sign(phi), cosPhi = cos(phi), x = cos(lambda) * cosPhi, y = sin(lambda) * cosPhi, z = sin(sPhi * phi);
          lambda = abs(atan2(y, z));
          phi = asin(x);
          if (abs(lambda - halfPi) > epsilon) lambda %= halfPi;
          var point = gringortenHexadecant(lambda > pi / 4 ? halfPi - lambda : lambda, phi);
          if (lambda > pi / 4) z = point[0], point[0] = -point[1], point[1] = -z;
          return point[0] *= sLambda, point[1] *= -sPhi, point;
        }
        gringortenRaw.invert = function(x, y) {
          if (abs(x) > 1) x = sign(x) * 2 - x;
          if (abs(y) > 1) y = sign(y) * 2 - y;
          var sx = sign(x), sy = sign(y), x02 = -sx * x, y02 = -sy * y, t = y02 / x02 < 1, p = gringortenHexadecantInvert(t ? y02 : x02, t ? x02 : y02), lambda = p[0], phi = p[1], cosPhi = cos(phi);
          if (t) lambda = -halfPi - lambda;
          return [sx * (atan2(sin(lambda) * cosPhi, -sin(phi)) + pi), sy * asin(cos(lambda) * cosPhi)];
        };
        function gringortenHexadecant(lambda, phi) {
          if (phi === halfPi) return [0, 0];
          var sinPhi = sin(phi), r = sinPhi * sinPhi, r2 = r * r, j = 1 + r2, k2 = 1 + 3 * r2, q = 1 - r2, z = asin(1 / sqrt(j)), v = q + r * j * z, p2 = (1 - sinPhi) / v, p = sqrt(p2), a2 = p2 * j, a = sqrt(a2), h = p * q, x, i;
          if (lambda === 0) return [0, -(h + r * a)];
          var cosPhi = cos(phi), secPhi = 1 / cosPhi, drdPhi = 2 * sinPhi * cosPhi, dvdPhi = (-3 * r + z * k2) * drdPhi, dp2dPhi = (-v * cosPhi - (1 - sinPhi) * dvdPhi) / (v * v), dpdPhi = 0.5 * dp2dPhi / p, dhdPhi = q * dpdPhi - 2 * r * p * drdPhi, dra2dPhi = r * j * dp2dPhi + p2 * k2 * drdPhi, mu = -secPhi * drdPhi, nu = -secPhi * dra2dPhi, zeta = -2 * secPhi * dhdPhi, lambda1 = 4 * lambda / pi, delta;
          if (lambda > 0.222 * pi || phi < pi / 4 && lambda > 0.175 * pi) {
            x = (h + r * sqrt(a2 * (1 + r2) - h * h)) / (1 + r2);
            if (lambda > pi / 4) return [x, x];
            var x12 = x, x02 = 0.5 * x;
            x = 0.5 * (x02 + x12), i = 50;
            do {
              var g = sqrt(a2 - x * x), f = x * (zeta + mu * g) + nu * asin(x / a) - lambda1;
              if (!f) break;
              if (f < 0) x02 = x;
              else x12 = x;
              x = 0.5 * (x02 + x12);
            } while (abs(x12 - x02) > epsilon && --i > 0);
          } else {
            x = epsilon, i = 25;
            do {
              var x2 = x * x, g2 = sqrt(a2 - x2), zetaMug = zeta + mu * g2, f2 = x * zetaMug + nu * asin(x / a) - lambda1, df = zetaMug + (nu - mu * x2) / g2;
              x -= delta = g2 ? f2 / df : 0;
            } while (abs(delta) > epsilon && --i > 0);
          }
          return [x, -h - r * sqrt(a2 - x * x)];
        }
        function gringortenHexadecantInvert(x, y) {
          var x02 = 0, x12 = 1, r = 0.5, i = 50;
          while (true) {
            var r2 = r * r, sinPhi = sqrt(r), z = asin(1 / sqrt(1 + r2)), v = 1 - r2 + r * (1 + r2) * z, p2 = (1 - sinPhi) / v, p = sqrt(p2), a2 = p2 * (1 + r2), h = p * (1 - r2), g2 = a2 - x * x, g = sqrt(g2), y02 = y + h + r * g;
            if (abs(x12 - x02) < epsilon22 || --i === 0 || y02 === 0) break;
            if (y02 > 0) x02 = r;
            else x12 = r;
            r = 0.5 * (x02 + x12);
          }
          if (!i) return null;
          var phi = asin(sinPhi), cosPhi = cos(phi), secPhi = 1 / cosPhi, drdPhi = 2 * sinPhi * cosPhi, dvdPhi = (-3 * r + z * (1 + 3 * r2)) * drdPhi, dp2dPhi = (-v * cosPhi - (1 - sinPhi) * dvdPhi) / (v * v), dpdPhi = 0.5 * dp2dPhi / p, dhdPhi = (1 - r2) * dpdPhi - 2 * r * p * drdPhi, zeta = -2 * secPhi * dhdPhi, mu = -secPhi * drdPhi, nu = -secPhi * (r * (1 + r2) * dp2dPhi + p2 * (1 + 3 * r2) * drdPhi);
          return [pi / 4 * (x * (zeta + mu * g) + nu * asin(x / sqrt(a2))), phi];
        }
        function gringorten() {
          return d3Geo.geoProjection(squareRaw(gringortenRaw)).scale(239.75);
        }
        function ellipticJi(u, v, m) {
          var a, b, c;
          if (!u) {
            b = ellipticJ(v, 1 - m);
            return [
              [0, b[0] / b[1]],
              [1 / b[1], 0],
              [b[2] / b[1], 0]
            ];
          }
          a = ellipticJ(u, m);
          if (!v) return [[a[0], 0], [a[1], 0], [a[2], 0]];
          b = ellipticJ(v, 1 - m);
          c = b[1] * b[1] + m * a[0] * a[0] * b[0] * b[0];
          return [
            [a[0] * b[2] / c, a[1] * a[2] * b[0] * b[1] / c],
            [a[1] * b[1] / c, -a[0] * a[2] * b[0] * b[2] / c],
            [a[2] * b[1] * b[2] / c, -m * a[0] * a[1] * b[0] / c]
          ];
        }
        function ellipticJ(u, m) {
          var ai, b, phi, t, twon;
          if (m < epsilon) {
            t = sin(u);
            b = cos(u);
            ai = m * (u - t * b) / 4;
            return [
              t - ai * b,
              b + ai * t,
              1 - m * t * t / 2,
              u - ai
            ];
          }
          if (m >= 1 - epsilon) {
            ai = (1 - m) / 4;
            b = cosh2(u);
            t = tanh2(u);
            phi = 1 / b;
            twon = b * sinh2(u);
            return [
              t + ai * (twon - u) / (b * b),
              phi - ai * t * phi * (twon - u),
              phi + ai * t * phi * (twon + u),
              2 * atan(exp(u)) - halfPi + ai * (twon - u) / b
            ];
          }
          var a = [1, 0, 0, 0, 0, 0, 0, 0, 0], c = [sqrt(m), 0, 0, 0, 0, 0, 0, 0, 0], i = 0;
          b = sqrt(1 - m);
          twon = 1;
          while (abs(c[i] / a[i]) > epsilon && i < 8) {
            ai = a[i++];
            c[i] = (ai - b) / 2;
            a[i] = (ai + b) / 2;
            b = sqrt(ai * b);
            twon *= 2;
          }
          phi = twon * a[i] * u;
          do {
            t = c[i] * sin(b = phi) / a[i];
            phi = (asin(t) + phi) / 2;
          } while (--i);
          return [sin(phi), t = cos(phi), t / cos(phi - b), phi];
        }
        function ellipticFi(phi, psi, m) {
          var r = abs(phi), i = abs(psi), sinhPsi = sinh2(i);
          if (r) {
            var cscPhi = 1 / sin(r), cotPhi2 = 1 / (tan(r) * tan(r)), b = -(cotPhi2 + m * (sinhPsi * sinhPsi * cscPhi * cscPhi) - 1 + m), c = (m - 1) * cotPhi2, cotLambda2 = (-b + sqrt(b * b - 4 * c)) / 2;
            return [
              ellipticF(atan(1 / sqrt(cotLambda2)), m) * sign(phi),
              ellipticF(atan(sqrt((cotLambda2 / cotPhi2 - 1) / m)), 1 - m) * sign(psi)
            ];
          }
          return [
            0,
            ellipticF(atan(sinhPsi), 1 - m) * sign(psi)
          ];
        }
        function ellipticF(phi, m) {
          if (!m) return phi;
          if (m === 1) return log(tan(phi / 2 + quarterPi));
          var a = 1, b = sqrt(1 - m), c = sqrt(m);
          for (var i = 0; abs(c) > epsilon; i++) {
            if (phi % pi) {
              var dPhi = atan(b * tan(phi) / a);
              if (dPhi < 0) dPhi += pi;
              phi += dPhi + ~~(phi / pi) * pi;
            } else phi += phi;
            c = (a + b) / 2;
            b = sqrt(a * b);
            c = ((a = c) - b) / 2;
          }
          return phi / (pow(2, i) * a);
        }
        function guyouRaw(lambda, phi) {
          var k_ = (sqrt2 - 1) / (sqrt2 + 1), k2 = sqrt(1 - k_ * k_), K3 = ellipticF(halfPi, k2 * k2), f = -1, psi = log(tan(pi / 4 + abs(phi) / 2)), r = exp(f * psi) / sqrt(k_), at = guyouComplexAtan(r * cos(f * lambda), r * sin(f * lambda)), t = ellipticFi(at[0], at[1], k2 * k2);
          return [-t[1], (phi >= 0 ? 1 : -1) * (0.5 * K3 - t[0])];
        }
        function guyouComplexAtan(x, y) {
          var x2 = x * x, y_1 = y + 1, t = 1 - x2 - y * y;
          return [
            0.5 * ((x >= 0 ? halfPi : -halfPi) - atan2(t, 2 * x)),
            -0.25 * log(t * t + 4 * x2) + 0.5 * log(y_1 * y_1 + x2)
          ];
        }
        function guyouComplexDivide(a, b) {
          var denominator = b[0] * b[0] + b[1] * b[1];
          return [
            (a[0] * b[0] + a[1] * b[1]) / denominator,
            (a[1] * b[0] - a[0] * b[1]) / denominator
          ];
        }
        guyouRaw.invert = function(x, y) {
          var k_ = (sqrt2 - 1) / (sqrt2 + 1), k2 = sqrt(1 - k_ * k_), K3 = ellipticF(halfPi, k2 * k2), f = -1, j = ellipticJi(0.5 * K3 - y, -x, k2 * k2), tn = guyouComplexDivide(j[0], j[1]), lambda = atan2(tn[1], tn[0]) / f;
          return [
            lambda,
            2 * atan(exp(0.5 / f * log(k_ * tn[0] * tn[0] + k_ * tn[1] * tn[1]))) - halfPi
          ];
        };
        function guyou() {
          return d3Geo.geoProjection(squareRaw(guyouRaw)).scale(151.496);
        }
        function hammerRetroazimuthalRaw(phi02) {
          var sinPhi0 = sin(phi02), cosPhi0 = cos(phi02), rotate = hammerRetroazimuthalRotation(phi02);
          rotate.invert = hammerRetroazimuthalRotation(-phi02);
          function forward(lambda, phi) {
            var p = rotate(lambda, phi);
            lambda = p[0], phi = p[1];
            var sinPhi = sin(phi), cosPhi = cos(phi), cosLambda = cos(lambda), z = acos(sinPhi0 * sinPhi + cosPhi0 * cosPhi * cosLambda), sinz = sin(z), K3 = abs(sinz) > epsilon ? z / sinz : 1;
            return [
              K3 * cosPhi0 * sin(lambda),
              (abs(lambda) > halfPi ? K3 : -K3) * (sinPhi0 * cosPhi - cosPhi0 * sinPhi * cosLambda)
            ];
          }
          forward.invert = function(x, y) {
            var rho = sqrt(x * x + y * y), sinz = -sin(rho), cosz = cos(rho), a = rho * cosz, b = -y * sinz, c = rho * sinPhi0, d = sqrt(a * a + b * b - c * c), phi = atan2(a * c + b * d, b * c - a * d), lambda = (rho > halfPi ? -1 : 1) * atan2(x * sinz, rho * cos(phi) * cosz + y * sin(phi) * sinz);
            return rotate.invert(lambda, phi);
          };
          return forward;
        }
        function hammerRetroazimuthalRotation(phi02) {
          var sinPhi0 = sin(phi02), cosPhi0 = cos(phi02);
          return function(lambda, phi) {
            var cosPhi = cos(phi), x = cos(lambda) * cosPhi, y = sin(lambda) * cosPhi, z = sin(phi);
            return [
              atan2(y, x * cosPhi0 - z * sinPhi0),
              asin(z * cosPhi0 + x * sinPhi0)
            ];
          };
        }
        function hammerRetroazimuthal() {
          var phi02 = 0, m = d3Geo.geoProjectionMutator(hammerRetroazimuthalRaw), p = m(phi02), rotate_ = p.rotate, stream_ = p.stream, circle = d3Geo.geoCircle();
          p.parallel = function(_) {
            if (!arguments.length) return phi02 * degrees3;
            var r = p.rotate();
            return m(phi02 = _ * radians2).rotate(r);
          };
          p.rotate = function(_) {
            if (!arguments.length) return _ = rotate_.call(p), _[1] += phi02 * degrees3, _;
            rotate_.call(p, [_[0], _[1] - phi02 * degrees3]);
            circle.center([-_[0], -_[1]]);
            return p;
          };
          p.stream = function(stream) {
            stream = stream_(stream);
            stream.sphere = function() {
              stream.polygonStart();
              var epsilon$$1 = 0.01, ring = circle.radius(90 - epsilon$$1)().coordinates[0], n = ring.length - 1, i = -1, p2;
              stream.lineStart();
              while (++i < n) stream.point((p2 = ring[i])[0], p2[1]);
              stream.lineEnd();
              ring = circle.radius(90 + epsilon$$1)().coordinates[0];
              n = ring.length - 1;
              stream.lineStart();
              while (--i >= 0) stream.point((p2 = ring[i])[0], p2[1]);
              stream.lineEnd();
              stream.polygonEnd();
            };
            return stream;
          };
          return p.scale(79.4187).parallel(45).clipAngle(180 - 1e-3);
        }
        var K2 = 3, healpixParallel = asin(1 - 1 / K2) * degrees3, healpixLambert = cylindricalEqualAreaRaw(0);
        function healpixRaw(H) {
          var phi02 = healpixParallel * radians2, dx = collignonRaw(pi, phi02)[0] - collignonRaw(-pi, phi02)[0], y02 = healpixLambert(0, phi02)[1], y12 = collignonRaw(0, phi02)[1], dy1 = sqrtPi - y12, k2 = tau / H, w2 = 4 / tau, h = y02 + dy1 * dy1 * 4 / tau;
          function forward(lambda, phi) {
            var point, phi2 = abs(phi);
            if (phi2 > phi02) {
              var i = min(H - 1, max(0, floor((lambda + pi) / k2)));
              lambda += pi * (H - 1) / H - i * k2;
              point = collignonRaw(lambda, phi2);
              point[0] = point[0] * tau / dx - tau * (H - 1) / (2 * H) + i * tau / H;
              point[1] = y02 + (point[1] - y12) * 4 * dy1 / tau;
              if (phi < 0) point[1] = -point[1];
            } else {
              point = healpixLambert(lambda, phi);
            }
            point[0] *= w2, point[1] /= h;
            return point;
          }
          forward.invert = function(x, y) {
            x /= w2, y *= h;
            var y2 = abs(y);
            if (y2 > y02) {
              var i = min(H - 1, max(0, floor((x + pi) / k2)));
              x = (x + pi * (H - 1) / H - i * k2) * dx / tau;
              var point = collignonRaw.invert(x, 0.25 * (y2 - y02) * tau / dy1 + y12);
              point[0] -= pi * (H - 1) / H - i * k2;
              if (y < 0) point[1] = -point[1];
              return point;
            }
            return healpixLambert.invert(x, y);
          };
          return forward;
        }
        function sphereTop(x, i) {
          return [x, i & 1 ? 90 - epsilon : healpixParallel];
        }
        function sphereBottom(x, i) {
          return [x, i & 1 ? -90 + epsilon : -healpixParallel];
        }
        function sphereNudge(d) {
          return [d[0] * (1 - epsilon), d[1]];
        }
        function sphere(step) {
          var c = [].concat(
            d3Array.range(-180, 180 + step / 2, step).map(sphereTop),
            d3Array.range(180, -180 - step / 2, -step).map(sphereBottom)
          );
          return {
            type: "Polygon",
            coordinates: [step === 180 ? c.map(sphereNudge) : c]
          };
        }
        function healpix() {
          var H = 4, m = d3Geo.geoProjectionMutator(healpixRaw), p = m(H), stream_ = p.stream;
          p.lobes = function(_) {
            return arguments.length ? m(H = +_) : H;
          };
          p.stream = function(stream) {
            var rotate = p.rotate(), rotateStream = stream_(stream), sphereStream = (p.rotate([0, 0]), stream_(stream));
            p.rotate(rotate);
            rotateStream.sphere = function() {
              d3Geo.geoStream(sphere(180 / H), sphereStream);
            };
            return rotateStream;
          };
          return p.scale(239.75);
        }
        function hillRaw(K3) {
          var L = 1 + K3, sinBt = sin(1 / L), Bt = asin(sinBt), A3 = 2 * sqrt(pi / (B3 = pi + 4 * Bt * L)), B3, rho0 = 0.5 * A3 * (L + sqrt(K3 * (2 + K3))), K22 = K3 * K3, L2 = L * L;
          function forward(lambda, phi) {
            var t = 1 - sin(phi), rho, omega;
            if (t && t < 2) {
              var theta = halfPi - phi, i = 25, delta;
              do {
                var sinTheta = sin(theta), cosTheta = cos(theta), Bt_Bt1 = Bt + atan2(sinTheta, L - cosTheta), C2 = 1 + L2 - 2 * L * cosTheta;
                theta -= delta = (theta - K22 * Bt - L * sinTheta + C2 * Bt_Bt1 - 0.5 * t * B3) / (2 * L * sinTheta * Bt_Bt1);
              } while (abs(delta) > epsilon22 && --i > 0);
              rho = A3 * sqrt(C2);
              omega = lambda * Bt_Bt1 / pi;
            } else {
              rho = A3 * (K3 + t);
              omega = lambda * Bt / pi;
            }
            return [
              rho * sin(omega),
              rho0 - rho * cos(omega)
            ];
          }
          forward.invert = function(x, y) {
            var rho2 = x * x + (y -= rho0) * y, cosTheta = (1 + L2 - rho2 / (A3 * A3)) / (2 * L), theta = acos(cosTheta), sinTheta = sin(theta), Bt_Bt1 = Bt + atan2(sinTheta, L - cosTheta);
            return [
              asin(x / sqrt(rho2)) * pi / Bt_Bt1,
              asin(1 - 2 * (theta - K22 * Bt - L * sinTheta + (1 + L2 - 2 * L * cosTheta) * Bt_Bt1) / B3)
            ];
          };
          return forward;
        }
        function hill() {
          var K3 = 1, m = d3Geo.geoProjectionMutator(hillRaw), p = m(K3);
          p.ratio = function(_) {
            return arguments.length ? m(K3 = +_) : K3;
          };
          return p.scale(167.774).center([0, 18.67]);
        }
        var sinuMollweidePhi = 0.7109889596207567;
        var sinuMollweideY = 0.0528035274542;
        function sinuMollweideRaw(lambda, phi) {
          return phi > -sinuMollweidePhi ? (lambda = mollweideRaw(lambda, phi), lambda[1] += sinuMollweideY, lambda) : sinusoidalRaw(lambda, phi);
        }
        sinuMollweideRaw.invert = function(x, y) {
          return y > -sinuMollweidePhi ? mollweideRaw.invert(x, y - sinuMollweideY) : sinusoidalRaw.invert(x, y);
        };
        function sinuMollweide() {
          return d3Geo.geoProjection(sinuMollweideRaw).rotate([-20, -55]).scale(164.263).center([0, -5.4036]);
        }
        function homolosineRaw(lambda, phi) {
          return abs(phi) > sinuMollweidePhi ? (lambda = mollweideRaw(lambda, phi), lambda[1] -= phi > 0 ? sinuMollweideY : -sinuMollweideY, lambda) : sinusoidalRaw(lambda, phi);
        }
        homolosineRaw.invert = function(x, y) {
          return abs(y) > sinuMollweidePhi ? mollweideRaw.invert(x, y + (y > 0 ? sinuMollweideY : -sinuMollweideY)) : sinusoidalRaw.invert(x, y);
        };
        function homolosine() {
          return d3Geo.geoProjection(homolosineRaw).scale(152.63);
        }
        function hufnagelRaw(a, b, psiMax, ratio) {
          var k2 = sqrt(
            4 * pi / (2 * psiMax + (1 + a - b / 2) * sin(2 * psiMax) + (a + b) / 2 * sin(4 * psiMax) + b / 2 * sin(6 * psiMax))
          ), c = sqrt(
            ratio * sin(psiMax) * sqrt((1 + a * cos(2 * psiMax) + b * cos(4 * psiMax)) / (1 + a + b))
          ), M = psiMax * mapping(1);
          function radius(psi) {
            return sqrt(1 + a * cos(2 * psi) + b * cos(4 * psi));
          }
          function mapping(t) {
            var psi = t * psiMax;
            return (2 * psi + (1 + a - b / 2) * sin(2 * psi) + (a + b) / 2 * sin(4 * psi) + b / 2 * sin(6 * psi)) / psiMax;
          }
          function inversemapping(psi) {
            return radius(psi) * sin(psi);
          }
          var forward = function(lambda, phi) {
            var psi = psiMax * solve(mapping, M * sin(phi) / psiMax, phi / pi);
            if (isNaN(psi)) psi = psiMax * sign(phi);
            var kr = k2 * radius(psi);
            return [kr * c * lambda / pi * cos(psi), kr / c * sin(psi)];
          };
          forward.invert = function(x, y) {
            var psi = solve(inversemapping, y * c / k2);
            return [
              x * pi / (cos(psi) * k2 * c * radius(psi)),
              asin(psiMax * mapping(psi / psiMax) / M)
            ];
          };
          if (psiMax === 0) {
            k2 = sqrt(ratio / pi);
            forward = function(lambda, phi) {
              return [lambda * k2, sin(phi) / k2];
            };
            forward.invert = function(x, y) {
              return [x / k2, asin(y * k2)];
            };
          }
          return forward;
        }
        function hufnagel() {
          var a = 1, b = 0, psiMax = 45 * radians2, ratio = 2, mutate = d3Geo.geoProjectionMutator(hufnagelRaw), projection = mutate(a, b, psiMax, ratio);
          projection.a = function(_) {
            return arguments.length ? mutate(a = +_, b, psiMax, ratio) : a;
          };
          projection.b = function(_) {
            return arguments.length ? mutate(a, b = +_, psiMax, ratio) : b;
          };
          projection.psiMax = function(_) {
            return arguments.length ? mutate(a, b, psiMax = +_ * radians2, ratio) : psiMax * degrees3;
          };
          projection.ratio = function(_) {
            return arguments.length ? mutate(a, b, psiMax, ratio = +_) : ratio;
          };
          return projection.scale(180.739);
        }
        function adsimp(f, a, b, fa, fm, fb, V0, tol, maxdepth, depth, state) {
          if (state.nanEncountered) {
            return NaN;
          }
          var h, f1, f2, sl, sr, s2, m, V1, V2, err;
          h = b - a;
          f1 = f(a + h * 0.25);
          f2 = f(b - h * 0.25);
          if (isNaN(f1)) {
            state.nanEncountered = true;
            return;
          }
          if (isNaN(f2)) {
            state.nanEncountered = true;
            return;
          }
          sl = h * (fa + 4 * f1 + fm) / 12;
          sr = h * (fm + 4 * f2 + fb) / 12;
          s2 = sl + sr;
          err = (s2 - V0) / 15;
          if (depth > maxdepth) {
            state.maxDepthCount++;
            return s2 + err;
          } else if (Math.abs(err) < tol) {
            return s2 + err;
          } else {
            m = a + h * 0.5;
            V1 = adsimp(f, a, m, fa, f1, fm, sl, tol * 0.5, maxdepth, depth + 1, state);
            if (isNaN(V1)) {
              state.nanEncountered = true;
              return NaN;
            }
            V2 = adsimp(f, m, b, fm, f2, fb, sr, tol * 0.5, maxdepth, depth + 1, state);
            if (isNaN(V2)) {
              state.nanEncountered = true;
              return NaN;
            }
            return V1 + V2;
          }
        }
        function integrate(f, a, b, tol, maxdepth) {
          var state = {
            maxDepthCount: 0,
            nanEncountered: false
          };
          if (tol === void 0) {
            tol = 1e-8;
          }
          if (maxdepth === void 0) {
            maxdepth = 20;
          }
          var fa = f(a);
          var fm = f(0.5 * (a + b));
          var fb = f(b);
          var V0 = (fa + 4 * fm + fb) * (b - a) / 6;
          var result = adsimp(f, a, b, fa, fm, fb, V0, tol, maxdepth, 1, state);
          return result;
        }
        function hyperellipticalRaw(alpha, k2, gamma2) {
          function elliptic(f) {
            return alpha + (1 - alpha) * pow(1 - pow(f, k2), 1 / k2);
          }
          function z(f) {
            return integrate(elliptic, 0, f, 1e-4);
          }
          var G = 1 / z(1), n = 1e3, m = (1 + 1e-8) * G, approx = [];
          for (var i = 0; i <= n; i++)
            approx.push(z(i / n) * m);
          function Y(sinphi) {
            var rmin = 0, rmax = n, r = n >> 1;
            do {
              if (approx[r] > sinphi) rmax = r;
              else rmin = r;
              r = rmin + rmax >> 1;
            } while (r > rmin);
            var u = approx[r + 1] - approx[r];
            if (u) u = (sinphi - approx[r + 1]) / u;
            return (r + 1 + u) / n;
          }
          var ratio = 2 * Y(1) / pi * G / gamma2;
          var forward = function(lambda, phi) {
            var y = Y(abs(sin(phi))), x = elliptic(y) * lambda;
            y /= ratio;
            return [x, phi >= 0 ? y : -y];
          };
          forward.invert = function(x, y) {
            var phi;
            y *= ratio;
            if (abs(y) < 1) phi = sign(y) * asin(z(abs(y)) * G);
            return [x / elliptic(abs(y)), phi];
          };
          return forward;
        }
        function hyperelliptical() {
          var alpha = 0, k2 = 2.5, gamma2 = 1.183136, m = d3Geo.geoProjectionMutator(hyperellipticalRaw), p = m(alpha, k2, gamma2);
          p.alpha = function(_) {
            return arguments.length ? m(alpha = +_, k2, gamma2) : alpha;
          };
          p.k = function(_) {
            return arguments.length ? m(alpha, k2 = +_, gamma2) : k2;
          };
          p.gamma = function(_) {
            return arguments.length ? m(alpha, k2, gamma2 = +_) : gamma2;
          };
          return p.scale(152.63);
        }
        function pointEqual(a, b) {
          return abs(a[0] - b[0]) < epsilon && abs(a[1] - b[1]) < epsilon;
        }
        function interpolateLine(coordinates, m) {
          var i = -1, n = coordinates.length, p0 = coordinates[0], p1, dx, dy, resampled = [];
          while (++i < n) {
            p1 = coordinates[i];
            dx = (p1[0] - p0[0]) / m;
            dy = (p1[1] - p0[1]) / m;
            for (var j = 0; j < m; ++j) resampled.push([p0[0] + j * dx, p0[1] + j * dy]);
            p0 = p1;
          }
          resampled.push(p1);
          return resampled;
        }
        function interpolateSphere(lobes2) {
          var coordinates = [], lobe, lambda0, phi02, phi1, lambda2, phi2, i, n = lobes2[0].length;
          for (i = 0; i < n; ++i) {
            lobe = lobes2[0][i];
            lambda0 = lobe[0][0], phi02 = lobe[0][1], phi1 = lobe[1][1];
            lambda2 = lobe[2][0], phi2 = lobe[2][1];
            coordinates.push(interpolateLine([
              [lambda0 + epsilon, phi02 + epsilon],
              [lambda0 + epsilon, phi1 - epsilon],
              [lambda2 - epsilon, phi1 - epsilon],
              [lambda2 - epsilon, phi2 + epsilon]
            ], 30));
          }
          for (i = lobes2[1].length - 1; i >= 0; --i) {
            lobe = lobes2[1][i];
            lambda0 = lobe[0][0], phi02 = lobe[0][1], phi1 = lobe[1][1];
            lambda2 = lobe[2][0], phi2 = lobe[2][1];
            coordinates.push(interpolateLine([
              [lambda2 - epsilon, phi2 - epsilon],
              [lambda2 - epsilon, phi1 + epsilon],
              [lambda0 + epsilon, phi1 + epsilon],
              [lambda0 + epsilon, phi02 - epsilon]
            ], 30));
          }
          return {
            type: "Polygon",
            coordinates: [d3Array.merge(coordinates)]
          };
        }
        function interrupt(project, lobes2, inverse2) {
          var sphere2, bounds;
          function forward(lambda, phi) {
            var sign$$1 = phi < 0 ? -1 : 1, lobe = lobes2[+(phi < 0)];
            for (var i = 0, n = lobe.length - 1; i < n && lambda > lobe[i][2][0]; ++i) ;
            var p2 = project(lambda - lobe[i][1][0], phi);
            p2[0] += project(lobe[i][1][0], sign$$1 * phi > sign$$1 * lobe[i][0][1] ? lobe[i][0][1] : phi)[0];
            return p2;
          }
          if (inverse2) {
            forward.invert = inverse2(forward);
          } else if (project.invert) {
            forward.invert = function(x, y) {
              var bound = bounds[+(y < 0)], lobe = lobes2[+(y < 0)];
              for (var i = 0, n = bound.length; i < n; ++i) {
                var b = bound[i];
                if (b[0][0] <= x && x < b[1][0] && b[0][1] <= y && y < b[1][1]) {
                  var p2 = project.invert(x - project(lobe[i][1][0], 0)[0], y);
                  p2[0] += lobe[i][1][0];
                  return pointEqual(forward(p2[0], p2[1]), [x, y]) ? p2 : null;
                }
              }
            };
          }
          var p = d3Geo.geoProjection(forward), stream_ = p.stream;
          p.stream = function(stream) {
            var rotate = p.rotate(), rotateStream = stream_(stream), sphereStream = (p.rotate([0, 0]), stream_(stream));
            p.rotate(rotate);
            rotateStream.sphere = function() {
              d3Geo.geoStream(sphere2, sphereStream);
            };
            return rotateStream;
          };
          p.lobes = function(_) {
            if (!arguments.length) return lobes2.map(function(lobe) {
              return lobe.map(function(l) {
                return [
                  [l[0][0] * degrees3, l[0][1] * degrees3],
                  [l[1][0] * degrees3, l[1][1] * degrees3],
                  [l[2][0] * degrees3, l[2][1] * degrees3]
                ];
              });
            });
            sphere2 = interpolateSphere(_);
            lobes2 = _.map(function(lobe) {
              return lobe.map(function(l) {
                return [
                  [l[0][0] * radians2, l[0][1] * radians2],
                  [l[1][0] * radians2, l[1][1] * radians2],
                  [l[2][0] * radians2, l[2][1] * radians2]
                ];
              });
            });
            bounds = lobes2.map(function(lobe) {
              return lobe.map(function(l) {
                var x02 = project(l[0][0], l[0][1])[0], x12 = project(l[2][0], l[2][1])[0], y02 = project(l[1][0], l[0][1])[1], y12 = project(l[1][0], l[1][1])[1], t;
                if (y02 > y12) t = y02, y02 = y12, y12 = t;
                return [[x02, y02], [x12, y12]];
              });
            });
            return p;
          };
          if (lobes2 != null) p.lobes(lobes2);
          return p;
        }
        var lobes = [[
          // northern hemisphere
          [[-180, 0], [-100, 90], [-40, 0]],
          [[-40, 0], [30, 90], [180, 0]]
        ], [
          // southern hemisphere
          [[-180, 0], [-160, -90], [-100, 0]],
          [[-100, 0], [-60, -90], [-20, 0]],
          [[-20, 0], [20, -90], [80, 0]],
          [[80, 0], [140, -90], [180, 0]]
        ]];
        function boggs$1() {
          return interrupt(boggsRaw, lobes).scale(160.857);
        }
        var lobes$1 = [[
          // northern hemisphere
          [[-180, 0], [-100, 90], [-40, 0]],
          [[-40, 0], [30, 90], [180, 0]]
        ], [
          // southern hemisphere
          [[-180, 0], [-160, -90], [-100, 0]],
          [[-100, 0], [-60, -90], [-20, 0]],
          [[-20, 0], [20, -90], [80, 0]],
          [[80, 0], [140, -90], [180, 0]]
        ]];
        function homolosine$1() {
          return interrupt(homolosineRaw, lobes$1).scale(152.63);
        }
        var lobes$2 = [[
          // northern hemisphere
          [[-180, 0], [-100, 90], [-40, 0]],
          [[-40, 0], [30, 90], [180, 0]]
        ], [
          // southern hemisphere
          [[-180, 0], [-160, -90], [-100, 0]],
          [[-100, 0], [-60, -90], [-20, 0]],
          [[-20, 0], [20, -90], [80, 0]],
          [[80, 0], [140, -90], [180, 0]]
        ]];
        function mollweide$1() {
          return interrupt(mollweideRaw, lobes$2).scale(169.529);
        }
        var lobes$3 = [[
          // northern hemisphere
          [[-180, 0], [-90, 90], [0, 0]],
          [[0, 0], [90, 90], [180, 0]]
        ], [
          // southern hemisphere
          [[-180, 0], [-90, -90], [0, 0]],
          [[0, 0], [90, -90], [180, 0]]
        ]];
        function mollweideHemispheres() {
          return interrupt(mollweideRaw, lobes$3).scale(169.529).rotate([20, 0]);
        }
        var lobes$4 = [[
          // northern hemisphere
          [[-180, 35], [-30, 90], [0, 35]],
          [[0, 35], [30, 90], [180, 35]]
        ], [
          // southern hemisphere
          [[-180, -10], [-102, -90], [-65, -10]],
          [[-65, -10], [5, -90], [77, -10]],
          [[77, -10], [103, -90], [180, -10]]
        ]];
        function sinuMollweide$1() {
          return interrupt(sinuMollweideRaw, lobes$4, solve2d).rotate([-20, -55]).scale(164.263).center([0, -5.4036]);
        }
        var lobes$5 = [[
          // northern hemisphere
          [[-180, 0], [-110, 90], [-40, 0]],
          [[-40, 0], [0, 90], [40, 0]],
          [[40, 0], [110, 90], [180, 0]]
        ], [
          // southern hemisphere
          [[-180, 0], [-110, -90], [-40, 0]],
          [[-40, 0], [0, -90], [40, 0]],
          [[40, 0], [110, -90], [180, 0]]
        ]];
        function sinusoidal$1() {
          return interrupt(sinusoidalRaw, lobes$5).scale(152.63).rotate([-20, 0]);
        }
        function kavrayskiy7Raw(lambda, phi) {
          return [3 / tau * lambda * sqrt(pi * pi / 3 - phi * phi), phi];
        }
        kavrayskiy7Raw.invert = function(x, y) {
          return [tau / 3 * x / sqrt(pi * pi / 3 - y * y), y];
        };
        function kavrayskiy7() {
          return d3Geo.geoProjection(kavrayskiy7Raw).scale(158.837);
        }
        function lagrangeRaw(n) {
          function forward(lambda, phi) {
            if (abs(abs(phi) - halfPi) < epsilon) return [0, phi < 0 ? -2 : 2];
            var sinPhi = sin(phi), v = pow((1 + sinPhi) / (1 - sinPhi), n / 2), c = 0.5 * (v + 1 / v) + cos(lambda *= n);
            return [
              2 * sin(lambda) / c,
              (v - 1 / v) / c
            ];
          }
          forward.invert = function(x, y) {
            var y02 = abs(y);
            if (abs(y02 - 2) < epsilon) return x ? null : [0, sign(y) * halfPi];
            if (y02 > 2) return null;
            x /= 2, y /= 2;
            var x2 = x * x, y2 = y * y, t = 2 * y / (1 + x2 + y2);
            t = pow((1 + t) / (1 - t), 1 / n);
            return [
              atan2(2 * x, 1 - x2 - y2) / n,
              asin((t - 1) / (t + 1))
            ];
          };
          return forward;
        }
        function lagrange() {
          var n = 0.5, m = d3Geo.geoProjectionMutator(lagrangeRaw), p = m(n);
          p.spacing = function(_) {
            return arguments.length ? m(n = +_) : n;
          };
          return p.scale(124.75);
        }
        var pi_sqrt2 = pi / sqrt2;
        function larriveeRaw(lambda, phi) {
          return [
            lambda * (1 + sqrt(cos(phi))) / 2,
            phi / (cos(phi / 2) * cos(lambda / 6))
          ];
        }
        larriveeRaw.invert = function(x, y) {
          var x02 = abs(x), y02 = abs(y), lambda = epsilon, phi = halfPi;
          if (y02 < pi_sqrt2) phi *= y02 / pi_sqrt2;
          else lambda += 6 * acos(pi_sqrt2 / y02);
          for (var i = 0; i < 25; i++) {
            var sinPhi = sin(phi), sqrtcosPhi = sqrt(cos(phi)), sinPhi_2 = sin(phi / 2), cosPhi_2 = cos(phi / 2), sinLambda_6 = sin(lambda / 6), cosLambda_6 = cos(lambda / 6), f0 = 0.5 * lambda * (1 + sqrtcosPhi) - x02, f1 = phi / (cosPhi_2 * cosLambda_6) - y02, df0dPhi = sqrtcosPhi ? -0.25 * lambda * sinPhi / sqrtcosPhi : 0, df0dLambda = 0.5 * (1 + sqrtcosPhi), df1dPhi = (1 + 0.5 * phi * sinPhi_2 / cosPhi_2) / (cosPhi_2 * cosLambda_6), df1dLambda = phi / cosPhi_2 * (sinLambda_6 / 6) / (cosLambda_6 * cosLambda_6), denom = df0dPhi * df1dLambda - df1dPhi * df0dLambda, dPhi = (f0 * df1dLambda - f1 * df0dLambda) / denom, dLambda = (f1 * df0dPhi - f0 * df1dPhi) / denom;
            phi -= dPhi;
            lambda -= dLambda;
            if (abs(dPhi) < epsilon && abs(dLambda) < epsilon) break;
          }
          return [x < 0 ? -lambda : lambda, y < 0 ? -phi : phi];
        };
        function larrivee() {
          return d3Geo.geoProjection(larriveeRaw).scale(97.2672);
        }
        function laskowskiRaw(lambda, phi) {
          var lambda2 = lambda * lambda, phi2 = phi * phi;
          return [
            lambda * (0.975534 + phi2 * (-0.119161 + lambda2 * -0.0143059 + phi2 * -0.0547009)),
            phi * (1.00384 + lambda2 * (0.0802894 + phi2 * -0.02855 + lambda2 * 199025e-9) + phi2 * (0.0998909 + phi2 * -0.0491032))
          ];
        }
        laskowskiRaw.invert = function(x, y) {
          var lambda = sign(x) * pi, phi = y / 2, i = 50;
          do {
            var lambda2 = lambda * lambda, phi2 = phi * phi, lambdaPhi = lambda * phi, fx = lambda * (0.975534 + phi2 * (-0.119161 + lambda2 * -0.0143059 + phi2 * -0.0547009)) - x, fy = phi * (1.00384 + lambda2 * (0.0802894 + phi2 * -0.02855 + lambda2 * 199025e-9) + phi2 * (0.0998909 + phi2 * -0.0491032)) - y, deltaxDeltaLambda = 0.975534 - phi2 * (0.119161 + 3 * lambda2 * 0.0143059 + phi2 * 0.0547009), deltaxDeltaPhi = -lambdaPhi * (2 * 0.119161 + 4 * 0.0547009 * phi2 + 2 * 0.0143059 * lambda2), deltayDeltaLambda = lambdaPhi * (2 * 0.0802894 + 4 * 199025e-9 * lambda2 + 2 * -0.02855 * phi2), deltayDeltaPhi = 1.00384 + lambda2 * (0.0802894 + 199025e-9 * lambda2) + phi2 * (3 * (0.0998909 - 0.02855 * lambda2) - 5 * 0.0491032 * phi2), denominator = deltaxDeltaPhi * deltayDeltaLambda - deltayDeltaPhi * deltaxDeltaLambda, deltaLambda = (fy * deltaxDeltaPhi - fx * deltayDeltaPhi) / denominator, deltaPhi = (fx * deltayDeltaLambda - fy * deltaxDeltaLambda) / denominator;
            lambda -= deltaLambda, phi -= deltaPhi;
          } while ((abs(deltaLambda) > epsilon || abs(deltaPhi) > epsilon) && --i > 0);
          return i && [lambda, phi];
        };
        function laskowski() {
          return d3Geo.geoProjection(laskowskiRaw).scale(139.98);
        }
        function littrowRaw(lambda, phi) {
          return [
            sin(lambda) / cos(phi),
            tan(phi) * cos(lambda)
          ];
        }
        littrowRaw.invert = function(x, y) {
          var x2 = x * x, y2 = y * y, y2_1 = y2 + 1, x2_y2_1 = x2 + y2_1, cosPhi = x ? sqrt1_2 * sqrt((x2_y2_1 - sqrt(x2_y2_1 * x2_y2_1 - 4 * x2)) / x2) : 1 / sqrt(y2_1);
          return [
            asin(x * cosPhi),
            sign(y) * acos(cosPhi)
          ];
        };
        function littrow() {
          return d3Geo.geoProjection(littrowRaw).scale(144.049).clipAngle(90 - 1e-3);
        }
        function loximuthalRaw(phi02) {
          var cosPhi0 = cos(phi02), tanPhi0 = tan(quarterPi + phi02 / 2);
          function forward(lambda, phi) {
            var y = phi - phi02, x = abs(y) < epsilon ? lambda * cosPhi0 : abs(x = quarterPi + phi / 2) < epsilon || abs(abs(x) - halfPi) < epsilon ? 0 : lambda * y / log(tan(x) / tanPhi0);
            return [x, y];
          }
          forward.invert = function(x, y) {
            var lambda, phi = y + phi02;
            return [
              abs(y) < epsilon ? x / cosPhi0 : abs(lambda = quarterPi + phi / 2) < epsilon || abs(abs(lambda) - halfPi) < epsilon ? 0 : x * log(tan(lambda) / tanPhi0) / y,
              phi
            ];
          };
          return forward;
        }
        function loximuthal() {
          return parallel1(loximuthalRaw).parallel(40).scale(158.837);
        }
        function millerRaw(lambda, phi) {
          return [lambda, 1.25 * log(tan(quarterPi + 0.4 * phi))];
        }
        millerRaw.invert = function(x, y) {
          return [x, 2.5 * atan(exp(0.8 * y)) - 0.625 * pi];
        };
        function miller() {
          return d3Geo.geoProjection(millerRaw).scale(108.318);
        }
        function modifiedStereographicRaw(C2) {
          var m = C2.length - 1;
          function forward(lambda, phi) {
            var cosPhi = cos(phi), k2 = 2 / (1 + cosPhi * cos(lambda)), zr = k2 * cosPhi * sin(lambda), zi = k2 * sin(phi), i = m, w2 = C2[i], ar = w2[0], ai = w2[1], t;
            while (--i >= 0) {
              w2 = C2[i];
              ar = w2[0] + zr * (t = ar) - zi * ai;
              ai = w2[1] + zr * ai + zi * t;
            }
            ar = zr * (t = ar) - zi * ai;
            ai = zr * ai + zi * t;
            return [ar, ai];
          }
          forward.invert = function(x, y) {
            var i = 20, zr = x, zi = y;
            do {
              var j = m, w2 = C2[j], ar = w2[0], ai = w2[1], br = 0, bi = 0, t;
              while (--j >= 0) {
                w2 = C2[j];
                br = ar + zr * (t = br) - zi * bi;
                bi = ai + zr * bi + zi * t;
                ar = w2[0] + zr * (t = ar) - zi * ai;
                ai = w2[1] + zr * ai + zi * t;
              }
              br = ar + zr * (t = br) - zi * bi;
              bi = ai + zr * bi + zi * t;
              ar = zr * (t = ar) - zi * ai - x;
              ai = zr * ai + zi * t - y;
              var denominator = br * br + bi * bi, deltar, deltai;
              zr -= deltar = (ar * br + ai * bi) / denominator;
              zi -= deltai = (ai * br - ar * bi) / denominator;
            } while (abs(deltar) + abs(deltai) > epsilon * epsilon && --i > 0);
            if (i) {
              var rho = sqrt(zr * zr + zi * zi), c = 2 * atan(rho * 0.5), sinc = sin(c);
              return [atan2(zr * sinc, rho * cos(c)), rho ? asin(zi * sinc / rho) : 0];
            }
          };
          return forward;
        }
        var alaska = [[0.9972523, 0], [52513e-7, -41175e-7], [74606e-7, 48125e-7], [-0.0153783, -0.1968253], [0.0636871, -0.1408027], [0.3660976, -0.2937382]], gs48 = [[0.98879, 0], [0, 0], [-0.050909, 0], [0, 0], [0.075528, 0]], gs50 = [[0.984299, 0], [0.0211642, 37608e-7], [-0.1036018, -0.0575102], [-0.0329095, -0.0320119], [0.0499471, 0.1223335], [0.026046, 0.0899805], [7388e-7, -0.1435792], [75848e-7, -0.1334108], [-0.0216473, 0.0776645], [-0.0225161, 0.0853673]], miller$1 = [[0.9245, 0], [0, 0], [0.01943, 0]], lee = [[0.721316, 0], [0, 0], [-881625e-8, -617325e-8]];
        function modifiedStereographicAlaska() {
          return modifiedStereographic(alaska, [152, -64]).scale(1400).center([-160.908, 62.4864]).clipAngle(30).angle(7.8);
        }
        function modifiedStereographicGs48() {
          return modifiedStereographic(gs48, [95, -38]).scale(1e3).clipAngle(55).center([-96.5563, 38.8675]);
        }
        function modifiedStereographicGs50() {
          return modifiedStereographic(gs50, [120, -45]).scale(359.513).clipAngle(55).center([-117.474, 53.0628]);
        }
        function modifiedStereographicMiller() {
          return modifiedStereographic(miller$1, [-20, -18]).scale(209.091).center([20, 16.7214]).clipAngle(82);
        }
        function modifiedStereographicLee() {
          return modifiedStereographic(lee, [165, 10]).scale(250).clipAngle(130).center([-165, -10]);
        }
        function modifiedStereographic(coefficients, rotate) {
          var p = d3Geo.geoProjection(modifiedStereographicRaw(coefficients)).rotate(rotate).clipAngle(90), r = d3Geo.geoRotation(rotate), center = p.center;
          delete p.rotate;
          p.center = function(_) {
            return arguments.length ? center(r(_)) : r.invert(center());
          };
          return p;
        }
        var sqrt6 = sqrt(6), sqrt7 = sqrt(7);
        function mtFlatPolarParabolicRaw(lambda, phi) {
          var theta = asin(7 * sin(phi) / (3 * sqrt6));
          return [
            sqrt6 * lambda * (2 * cos(2 * theta / 3) - 1) / sqrt7,
            9 * sin(theta / 3) / sqrt7
          ];
        }
        mtFlatPolarParabolicRaw.invert = function(x, y) {
          var theta = 3 * asin(y * sqrt7 / 9);
          return [
            x * sqrt7 / (sqrt6 * (2 * cos(2 * theta / 3) - 1)),
            asin(sin(theta) * 3 * sqrt6 / 7)
          ];
        };
        function mtFlatPolarParabolic() {
          return d3Geo.geoProjection(mtFlatPolarParabolicRaw).scale(164.859);
        }
        function mtFlatPolarQuarticRaw(lambda, phi) {
          var k2 = (1 + sqrt1_2) * sin(phi), theta = phi;
          for (var i = 0, delta; i < 25; i++) {
            theta -= delta = (sin(theta / 2) + sin(theta) - k2) / (0.5 * cos(theta / 2) + cos(theta));
            if (abs(delta) < epsilon) break;
          }
          return [
            lambda * (1 + 2 * cos(theta) / cos(theta / 2)) / (3 * sqrt2),
            2 * sqrt(3) * sin(theta / 2) / sqrt(2 + sqrt2)
          ];
        }
        mtFlatPolarQuarticRaw.invert = function(x, y) {
          var sinTheta_2 = y * sqrt(2 + sqrt2) / (2 * sqrt(3)), theta = 2 * asin(sinTheta_2);
          return [
            3 * sqrt2 * x / (1 + 2 * cos(theta) / cos(theta / 2)),
            asin((sinTheta_2 + sin(theta)) / (1 + sqrt1_2))
          ];
        };
        function mtFlatPolarQuartic() {
          return d3Geo.geoProjection(mtFlatPolarQuarticRaw).scale(188.209);
        }
        function mtFlatPolarSinusoidalRaw(lambda, phi) {
          var A3 = sqrt(6 / (4 + pi)), k2 = (1 + pi / 4) * sin(phi), theta = phi / 2;
          for (var i = 0, delta; i < 25; i++) {
            theta -= delta = (theta / 2 + sin(theta) - k2) / (0.5 + cos(theta));
            if (abs(delta) < epsilon) break;
          }
          return [
            A3 * (0.5 + cos(theta)) * lambda / 1.5,
            A3 * theta
          ];
        }
        mtFlatPolarSinusoidalRaw.invert = function(x, y) {
          var A3 = sqrt(6 / (4 + pi)), theta = y / A3;
          if (abs(abs(theta) - halfPi) < epsilon) theta = theta < 0 ? -halfPi : halfPi;
          return [
            1.5 * x / (A3 * (0.5 + cos(theta))),
            asin((theta / 2 + sin(theta)) / (1 + pi / 4))
          ];
        };
        function mtFlatPolarSinusoidal() {
          return d3Geo.geoProjection(mtFlatPolarSinusoidalRaw).scale(166.518);
        }
        function naturalEarth2Raw(lambda, phi) {
          var phi2 = phi * phi, phi4 = phi2 * phi2, phi6 = phi2 * phi4;
          return [
            lambda * (0.84719 - 0.13063 * phi2 + phi6 * phi6 * (-0.04515 + 0.05494 * phi2 - 0.02326 * phi4 + 331e-5 * phi6)),
            phi * (1.01183 + phi4 * phi4 * (-0.02625 + 0.01926 * phi2 - 396e-5 * phi4))
          ];
        }
        naturalEarth2Raw.invert = function(x, y) {
          var phi = y, i = 25, delta, phi2, phi4, phi6;
          do {
            phi2 = phi * phi;
            phi4 = phi2 * phi2;
            phi -= delta = (phi * (1.01183 + phi4 * phi4 * (-0.02625 + 0.01926 * phi2 - 396e-5 * phi4)) - y) / (1.01183 + phi4 * phi4 * (9 * -0.02625 + 11 * 0.01926 * phi2 + 13 * -396e-5 * phi4));
          } while (abs(delta) > epsilon22 && --i > 0);
          phi2 = phi * phi;
          phi4 = phi2 * phi2;
          phi6 = phi2 * phi4;
          return [
            x / (0.84719 - 0.13063 * phi2 + phi6 * phi6 * (-0.04515 + 0.05494 * phi2 - 0.02326 * phi4 + 331e-5 * phi6)),
            phi
          ];
        };
        function naturalEarth2() {
          return d3Geo.geoProjection(naturalEarth2Raw).scale(175.295);
        }
        function nellHammerRaw(lambda, phi) {
          return [
            lambda * (1 + cos(phi)) / 2,
            2 * (phi - tan(phi / 2))
          ];
        }
        nellHammerRaw.invert = function(x, y) {
          var p = y / 2;
          for (var i = 0, delta = Infinity; i < 10 && abs(delta) > epsilon; ++i) {
            var c = cos(y / 2);
            y -= delta = (y - tan(y / 2) - p) / (1 - 0.5 / (c * c));
          }
          return [
            2 * x / (1 + cos(y)),
            y
          ];
        };
        function nellHammer() {
          return d3Geo.geoProjection(nellHammerRaw).scale(152.63);
        }
        var lobes$6 = [[
          // northern hemisphere
          [[-180, 0], [-90, 90], [0, 0]],
          [[0, 0], [90, 90], [180, 0]]
        ], [
          // southern hemisphere
          [[-180, 0], [-90, -90], [0, 0]],
          [[0, 0], [90, -90], [180, 0]]
        ]];
        function quarticAuthalic() {
          return interrupt(hammerRaw(Infinity), lobes$6).rotate([20, 0]).scale(152.63);
        }
        function nicolosiRaw(lambda, phi) {
          var sinPhi = sin(phi), q = cos(phi), s = sign(lambda);
          if (lambda === 0 || abs(phi) === halfPi) return [0, phi];
          else if (phi === 0) return [lambda, 0];
          else if (abs(lambda) === halfPi) return [lambda * q, halfPi * sinPhi];
          var b = pi / (2 * lambda) - 2 * lambda / pi, c = 2 * phi / pi, d = (1 - c * c) / (sinPhi - c);
          var b2 = b * b, d2 = d * d, b2d2 = 1 + b2 / d2, d2b2 = 1 + d2 / b2;
          var M = (b * sinPhi / d - b / 2) / b2d2, N = (d2 * sinPhi / b2 + d / 2) / d2b2, m = M * M + q * q / b2d2, n = N * N - (d2 * sinPhi * sinPhi / b2 + d * sinPhi - 1) / d2b2;
          return [
            halfPi * (M + sqrt(m) * s),
            halfPi * (N + sqrt(n < 0 ? 0 : n) * sign(-phi * b) * s)
          ];
        }
        nicolosiRaw.invert = function(x, y) {
          x /= halfPi;
          y /= halfPi;
          var x2 = x * x, y2 = y * y, x2y2 = x2 + y2, pi2 = pi * pi;
          return [
            x ? (x2y2 - 1 + sqrt((1 - x2y2) * (1 - x2y2) + 4 * x2)) / (2 * x) * halfPi : 0,
            solve(function(phi) {
              return x2y2 * (pi * sin(phi) - 2 * phi) * pi + 4 * phi * phi * (y - sin(phi)) + 2 * pi * phi - pi2 * y;
            }, 0)
          ];
        };
        function nicolosi() {
          return d3Geo.geoProjection(nicolosiRaw).scale(127.267);
        }
        var pattersonK1 = 1.0148, pattersonK2 = 0.23185, pattersonK3 = -0.14499, pattersonK4 = 0.02406, pattersonC1 = pattersonK1, pattersonC2 = 5 * pattersonK2, pattersonC3 = 7 * pattersonK3, pattersonC4 = 9 * pattersonK4, pattersonYmax = 1.790857183;
        function pattersonRaw(lambda, phi) {
          var phi2 = phi * phi;
          return [
            lambda,
            phi * (pattersonK1 + phi2 * phi2 * (pattersonK2 + phi2 * (pattersonK3 + pattersonK4 * phi2)))
          ];
        }
        pattersonRaw.invert = function(x, y) {
          if (y > pattersonYmax) y = pattersonYmax;
          else if (y < -pattersonYmax) y = -pattersonYmax;
          var yc = y, delta;
          do {
            var y2 = yc * yc;
            yc -= delta = (yc * (pattersonK1 + y2 * y2 * (pattersonK2 + y2 * (pattersonK3 + pattersonK4 * y2))) - y) / (pattersonC1 + y2 * y2 * (pattersonC2 + y2 * (pattersonC3 + pattersonC4 * y2)));
          } while (abs(delta) > epsilon);
          return [x, yc];
        };
        function patterson() {
          return d3Geo.geoProjection(pattersonRaw).scale(139.319);
        }
        function polyconicRaw(lambda, phi) {
          if (abs(phi) < epsilon) return [lambda, 0];
          var tanPhi = tan(phi), k2 = lambda * sin(phi);
          return [
            sin(k2) / tanPhi,
            phi + (1 - cos(k2)) / tanPhi
          ];
        }
        polyconicRaw.invert = function(x, y) {
          if (abs(y) < epsilon) return [x, 0];
          var k2 = x * x + y * y, phi = y * 0.5, i = 10, delta;
          do {
            var tanPhi = tan(phi), secPhi = 1 / cos(phi), j = k2 - 2 * y * phi + phi * phi;
            phi -= delta = (tanPhi * j + 2 * (phi - y)) / (2 + j * secPhi * secPhi + 2 * (phi - y) * tanPhi);
          } while (abs(delta) > epsilon && --i > 0);
          tanPhi = tan(phi);
          return [
            (abs(y) < abs(phi + 1 / tanPhi) ? asin(x * tanPhi) : sign(y) * sign(x) * (acos(abs(x * tanPhi)) + halfPi)) / sin(phi),
            phi
          ];
        };
        function polyconic() {
          return d3Geo.geoProjection(polyconicRaw).scale(103.74);
        }
        function matrix(a, b) {
          var u = subtract(a[1], a[0]), v = subtract(b[1], b[0]), phi = angle$1(u, v), s = length(u) / length(v);
          return multiply([
            1,
            0,
            a[0][0],
            0,
            1,
            a[0][1]
          ], multiply([
            s,
            0,
            0,
            0,
            s,
            0
          ], multiply([
            cos(phi),
            sin(phi),
            0,
            -sin(phi),
            cos(phi),
            0
          ], [
            1,
            0,
            -b[0][0],
            0,
            1,
            -b[0][1]
          ])));
        }
        function inverse(m) {
          var k2 = 1 / (m[0] * m[4] - m[1] * m[3]);
          return [
            k2 * m[4],
            -k2 * m[1],
            k2 * (m[1] * m[5] - m[2] * m[4]),
            -k2 * m[3],
            k2 * m[0],
            k2 * (m[2] * m[3] - m[0] * m[5])
          ];
        }
        function multiply(a, b) {
          return [
            a[0] * b[0] + a[1] * b[3],
            a[0] * b[1] + a[1] * b[4],
            a[0] * b[2] + a[1] * b[5] + a[2],
            a[3] * b[0] + a[4] * b[3],
            a[3] * b[1] + a[4] * b[4],
            a[3] * b[2] + a[4] * b[5] + a[5]
          ];
        }
        function subtract(a, b) {
          return [a[0] - b[0], a[1] - b[1]];
        }
        function length(v) {
          return sqrt(v[0] * v[0] + v[1] * v[1]);
        }
        function angle$1(a, b) {
          return atan2(a[0] * b[1] - a[1] * b[0], a[0] * b[0] + a[1] * b[1]);
        }
        function polyhedral(root, face, r) {
          recurse(root, { transform: null });
          function recurse(node, parent) {
            node.edges = faceEdges(node.face);
            if (parent.face) {
              var shared = node.shared = sharedEdge(node.face, parent.face), m = matrix(shared.map(parent.project), shared.map(node.project));
              node.transform = parent.transform ? multiply(parent.transform, m) : m;
              var edges = parent.edges;
              for (var i = 0, n = edges.length; i < n; ++i) {
                if (pointEqual$1(shared[0], edges[i][1]) && pointEqual$1(shared[1], edges[i][0])) edges[i] = node;
                if (pointEqual$1(shared[0], edges[i][0]) && pointEqual$1(shared[1], edges[i][1])) edges[i] = node;
              }
              edges = node.edges;
              for (i = 0, n = edges.length; i < n; ++i) {
                if (pointEqual$1(shared[0], edges[i][0]) && pointEqual$1(shared[1], edges[i][1])) edges[i] = parent;
                if (pointEqual$1(shared[0], edges[i][1]) && pointEqual$1(shared[1], edges[i][0])) edges[i] = parent;
              }
            } else {
              node.transform = parent.transform;
            }
            if (node.children) {
              node.children.forEach(function(child) {
                recurse(child, node);
              });
            }
            return node;
          }
          function forward(lambda, phi) {
            var node = face(lambda, phi), point = node.project([lambda * degrees3, phi * degrees3]), t;
            if (t = node.transform) {
              return [
                t[0] * point[0] + t[1] * point[1] + t[2],
                -(t[3] * point[0] + t[4] * point[1] + t[5])
              ];
            }
            point[1] = -point[1];
            return point;
          }
          if (hasInverse(root)) forward.invert = function(x, y) {
            var coordinates = faceInvert(root, [x, -y]);
            return coordinates && (coordinates[0] *= radians2, coordinates[1] *= radians2, coordinates);
          };
          function faceInvert(node, coordinates) {
            var invert = node.project.invert, t = node.transform, point = coordinates;
            if (t) {
              t = inverse(t);
              point = [
                t[0] * point[0] + t[1] * point[1] + t[2],
                t[3] * point[0] + t[4] * point[1] + t[5]
              ];
            }
            if (invert && node === faceDegrees(p = invert(point))) return p;
            var p, children = node.children;
            for (var i = 0, n = children && children.length; i < n; ++i) {
              if (p = faceInvert(children[i], coordinates)) return p;
            }
          }
          function faceDegrees(coordinates) {
            return face(coordinates[0] * radians2, coordinates[1] * radians2);
          }
          var proj = d3Geo.geoProjection(forward), stream_ = proj.stream;
          proj.stream = function(stream) {
            var rotate = proj.rotate(), rotateStream = stream_(stream), sphereStream = (proj.rotate([0, 0]), stream_(stream));
            proj.rotate(rotate);
            rotateStream.sphere = function() {
              sphereStream.polygonStart();
              sphereStream.lineStart();
              outline(sphereStream, root);
              sphereStream.lineEnd();
              sphereStream.polygonEnd();
            };
            return rotateStream;
          };
          return proj.angle(r == null ? -30 : r * degrees3);
        }
        function outline(stream, node, parent) {
          var point, edges = node.edges, n = edges.length, edge, multiPoint = { type: "MultiPoint", coordinates: node.face }, notPoles = node.face.filter(function(d) {
            return abs(d[1]) !== 90;
          }), b = d3Geo.geoBounds({ type: "MultiPoint", coordinates: notPoles }), inside = false, j = -1, dx = b[1][0] - b[0][0];
          var c = dx === 180 || dx === 360 ? [(b[0][0] + b[1][0]) / 2, (b[0][1] + b[1][1]) / 2] : d3Geo.geoCentroid(multiPoint);
          if (parent) while (++j < n) {
            if (edges[j] === parent) break;
          }
          ++j;
          for (var i = 0; i < n; ++i) {
            edge = edges[(i + j) % n];
            if (Array.isArray(edge)) {
              if (!inside) {
                stream.point((point = d3Geo.geoInterpolate(edge[0], c)(epsilon))[0], point[1]);
                inside = true;
              }
              stream.point((point = d3Geo.geoInterpolate(edge[1], c)(epsilon))[0], point[1]);
            } else {
              inside = false;
              if (edge !== parent) outline(stream, edge, node);
            }
          }
        }
        function pointEqual$1(a, b) {
          return a && b && a[0] === b[0] && a[1] === b[1];
        }
        function sharedEdge(a, b) {
          var x, y, n = a.length, found = null;
          for (var i = 0; i < n; ++i) {
            x = a[i];
            for (var j = b.length; --j >= 0; ) {
              y = b[j];
              if (x[0] === y[0] && x[1] === y[1]) {
                if (found) return [found, x];
                found = x;
              }
            }
          }
        }
        function faceEdges(face) {
          var n = face.length, edges = [];
          for (var a = face[n - 1], i = 0; i < n; ++i) edges.push([a, a = face[i]]);
          return edges;
        }
        function hasInverse(node) {
          return node.project.invert || node.children && node.children.some(hasInverse);
        }
        var octahedron = [
          [0, 90],
          [-90, 0],
          [0, 0],
          [90, 0],
          [180, 0],
          [0, -90]
        ];
        var octahedron$1 = [
          [0, 2, 1],
          [0, 3, 2],
          [5, 1, 2],
          [5, 2, 3],
          [0, 1, 4],
          [0, 4, 3],
          [5, 4, 1],
          [5, 3, 4]
        ].map(function(face) {
          return face.map(function(i) {
            return octahedron[i];
          });
        });
        function butterfly(faceProjection) {
          faceProjection = faceProjection || function(face) {
            var c = d3Geo.geoCentroid({ type: "MultiPoint", coordinates: face });
            return d3Geo.geoGnomonic().scale(1).translate([0, 0]).rotate([-c[0], -c[1]]);
          };
          var faces = octahedron$1.map(function(face) {
            return { face, project: faceProjection(face) };
          });
          [-1, 0, 0, 1, 0, 1, 4, 5].forEach(function(d, i) {
            var node = faces[d];
            node && (node.children || (node.children = [])).push(faces[i]);
          });
          return polyhedral(faces[0], function(lambda, phi) {
            return faces[lambda < -pi / 2 ? phi < 0 ? 6 : 4 : lambda < 0 ? phi < 0 ? 2 : 0 : lambda < pi / 2 ? phi < 0 ? 3 : 1 : phi < 0 ? 7 : 5];
          }).angle(-30).scale(101.858).center([0, 45]);
        }
        var kx = 2 / sqrt(3);
        function collignonK(a, b) {
          var p = collignonRaw(a, b);
          return [p[0] * kx, p[1]];
        }
        collignonK.invert = function(x, y) {
          return collignonRaw.invert(x / kx, y);
        };
        function collignon$1(faceProjection) {
          faceProjection = faceProjection || function(face) {
            var c = d3Geo.geoCentroid({ type: "MultiPoint", coordinates: face });
            return d3Geo.geoProjection(collignonK).translate([0, 0]).scale(1).rotate(c[1] > 0 ? [-c[0], 0] : [180 - c[0], 180]);
          };
          var faces = octahedron$1.map(function(face) {
            return { face, project: faceProjection(face) };
          });
          [-1, 0, 0, 1, 0, 1, 4, 5].forEach(function(d, i) {
            var node = faces[d];
            node && (node.children || (node.children = [])).push(faces[i]);
          });
          return polyhedral(faces[0], function(lambda, phi) {
            return faces[lambda < -pi / 2 ? phi < 0 ? 6 : 4 : lambda < 0 ? phi < 0 ? 2 : 0 : lambda < pi / 2 ? phi < 0 ? 3 : 1 : phi < 0 ? 7 : 5];
          }).angle(-30).scale(121.906).center([0, 48.5904]);
        }
        function waterman(faceProjection) {
          faceProjection = faceProjection || function(face2) {
            var c = face2.length === 6 ? d3Geo.geoCentroid({ type: "MultiPoint", coordinates: face2 }) : face2[0];
            return d3Geo.geoGnomonic().scale(1).translate([0, 0]).rotate([-c[0], -c[1]]);
          };
          var w5 = octahedron$1.map(function(face2) {
            var xyz = face2.map(cartesian), n = xyz.length, a = xyz[n - 1], b, hexagon = [];
            for (var i = 0; i < n; ++i) {
              b = xyz[i];
              hexagon.push(spherical([
                a[0] * 0.9486832980505138 + b[0] * 0.31622776601683794,
                a[1] * 0.9486832980505138 + b[1] * 0.31622776601683794,
                a[2] * 0.9486832980505138 + b[2] * 0.31622776601683794
              ]), spherical([
                b[0] * 0.9486832980505138 + a[0] * 0.31622776601683794,
                b[1] * 0.9486832980505138 + a[1] * 0.31622776601683794,
                b[2] * 0.9486832980505138 + a[2] * 0.31622776601683794
              ]));
              a = b;
            }
            return hexagon;
          });
          var cornerNormals = [];
          var parents = [-1, 0, 0, 1, 0, 1, 4, 5];
          w5.forEach(function(hexagon, j) {
            var face2 = octahedron$1[j], n = face2.length, normals = cornerNormals[j] = [];
            for (var i = 0; i < n; ++i) {
              w5.push([
                face2[i],
                hexagon[(i * 2 + 2) % (2 * n)],
                hexagon[(i * 2 + 1) % (2 * n)]
              ]);
              parents.push(j);
              normals.push(cross(
                cartesian(hexagon[(i * 2 + 2) % (2 * n)]),
                cartesian(hexagon[(i * 2 + 1) % (2 * n)])
              ));
            }
          });
          var faces = w5.map(function(face2) {
            return {
              project: faceProjection(face2),
              face: face2
            };
          });
          parents.forEach(function(d, i) {
            var parent = faces[d];
            parent && (parent.children || (parent.children = [])).push(faces[i]);
          });
          function face(lambda, phi) {
            var cosphi = cos(phi), p = [cosphi * cos(lambda), cosphi * sin(lambda), sin(phi)];
            var hexagon = lambda < -pi / 2 ? phi < 0 ? 6 : 4 : lambda < 0 ? phi < 0 ? 2 : 0 : lambda < pi / 2 ? phi < 0 ? 3 : 1 : phi < 0 ? 7 : 5;
            var n = cornerNormals[hexagon];
            return faces[dot(n[0], p) < 0 ? 8 + 3 * hexagon : dot(n[1], p) < 0 ? 8 + 3 * hexagon + 1 : dot(n[2], p) < 0 ? 8 + 3 * hexagon + 2 : hexagon];
          }
          return polyhedral(faces[0], face).angle(-30).scale(110.625).center([0, 45]);
        }
        function dot(a, b) {
          for (var i = 0, n = a.length, s = 0; i < n; ++i) s += a[i] * b[i];
          return s;
        }
        function cross(a, b) {
          return [
            a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0]
          ];
        }
        function spherical(cartesian2) {
          return [
            atan2(cartesian2[1], cartesian2[0]) * degrees3,
            asin(max(-1, min(1, cartesian2[2]))) * degrees3
          ];
        }
        function cartesian(coordinates) {
          var lambda = coordinates[0] * radians2, phi = coordinates[1] * radians2, cosphi = cos(phi);
          return [
            cosphi * cos(lambda),
            cosphi * sin(lambda),
            sin(phi)
          ];
        }
        function noop() {
        }
        function clockwise(ring) {
          if ((n = ring.length) < 4) return false;
          var i = 0, n, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
          while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
          return area <= 0;
        }
        function contains(ring, point) {
          var x = point[0], y = point[1], contains2 = false;
          for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
            var pi2 = ring[i], xi = pi2[0], yi = pi2[1], pj = ring[j], xj = pj[0], yj = pj[1];
            if (yi > y ^ yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) contains2 = !contains2;
          }
          return contains2;
        }
        function index(object, projection) {
          var stream = projection.stream, project;
          if (!stream) throw new Error("invalid projection");
          switch (object && object.type) {
            case "Feature":
              project = projectFeature;
              break;
            case "FeatureCollection":
              project = projectFeatureCollection;
              break;
            default:
              project = projectGeometry;
              break;
          }
          return project(object, stream);
        }
        function projectFeatureCollection(o, stream) {
          return {
            type: "FeatureCollection",
            features: o.features.map(function(f) {
              return projectFeature(f, stream);
            })
          };
        }
        function projectFeature(o, stream) {
          return {
            type: "Feature",
            id: o.id,
            properties: o.properties,
            geometry: projectGeometry(o.geometry, stream)
          };
        }
        function projectGeometryCollection(o, stream) {
          return {
            type: "GeometryCollection",
            geometries: o.geometries.map(function(o2) {
              return projectGeometry(o2, stream);
            })
          };
        }
        function projectGeometry(o, stream) {
          if (!o) return null;
          if (o.type === "GeometryCollection") return projectGeometryCollection(o, stream);
          var sink;
          switch (o.type) {
            case "Point":
              sink = sinkPoint;
              break;
            case "MultiPoint":
              sink = sinkPoint;
              break;
            case "LineString":
              sink = sinkLine;
              break;
            case "MultiLineString":
              sink = sinkLine;
              break;
            case "Polygon":
              sink = sinkPolygon;
              break;
            case "MultiPolygon":
              sink = sinkPolygon;
              break;
            case "Sphere":
              sink = sinkPolygon;
              break;
            default:
              return null;
          }
          d3Geo.geoStream(o, stream(sink));
          return sink.result();
        }
        var points = [], lines = [];
        var sinkPoint = {
          point: function(x, y) {
            points.push([x, y]);
          },
          result: function() {
            var result = !points.length ? null : points.length < 2 ? { type: "Point", coordinates: points[0] } : { type: "MultiPoint", coordinates: points };
            points = [];
            return result;
          }
        };
        var sinkLine = {
          lineStart: noop,
          point: function(x, y) {
            points.push([x, y]);
          },
          lineEnd: function() {
            if (points.length) lines.push(points), points = [];
          },
          result: function() {
            var result = !lines.length ? null : lines.length < 2 ? { type: "LineString", coordinates: lines[0] } : { type: "MultiLineString", coordinates: lines };
            lines = [];
            return result;
          }
        };
        var sinkPolygon = {
          polygonStart: noop,
          lineStart: noop,
          point: function(x, y) {
            points.push([x, y]);
          },
          lineEnd: function() {
            var n = points.length;
            if (n) {
              do
                points.push(points[0].slice());
              while (++n < 4);
              lines.push(points), points = [];
            }
          },
          polygonEnd: noop,
          result: function() {
            if (!lines.length) return null;
            var polygons = [], holes = [];
            lines.forEach(function(ring) {
              if (clockwise(ring)) polygons.push([ring]);
              else holes.push(ring);
            });
            holes.forEach(function(hole) {
              var point = hole[0];
              polygons.some(function(polygon) {
                if (contains(polygon[0], point)) {
                  polygon.push(hole);
                  return true;
                }
              }) || polygons.push([hole]);
            });
            lines = [];
            return !polygons.length ? null : polygons.length > 1 ? { type: "MultiPolygon", coordinates: polygons } : { type: "Polygon", coordinates: polygons[0] };
          }
        };
        function quincuncial(project) {
          var dx = project(halfPi, 0)[0] - project(-halfPi, 0)[0];
          function projectQuincuncial(lambda, phi) {
            var t = abs(lambda) < halfPi, p = project(t ? lambda : lambda > 0 ? lambda - pi : lambda + pi, phi), x = (p[0] - p[1]) * sqrt1_2, y = (p[0] + p[1]) * sqrt1_2;
            if (t) return [x, y];
            var d = dx * sqrt1_2, s = x > 0 ^ y > 0 ? -1 : 1;
            return [s * x - sign(y) * d, s * y - sign(x) * d];
          }
          if (project.invert) projectQuincuncial.invert = function(x02, y02) {
            var x = (x02 + y02) * sqrt1_2, y = (y02 - x02) * sqrt1_2, t = abs(x) < 0.5 * dx && abs(y) < 0.5 * dx;
            if (!t) {
              var d = dx * sqrt1_2, s = x > 0 ^ y > 0 ? -1 : 1, x12 = -s * x02 + (y > 0 ? 1 : -1) * d, y12 = -s * y02 + (x > 0 ? 1 : -1) * d;
              x = (-x12 - y12) * sqrt1_2;
              y = (x12 - y12) * sqrt1_2;
            }
            var p = project.invert(x, y);
            if (!t) p[0] += x > 0 ? pi : -pi;
            return p;
          };
          return d3Geo.geoProjection(projectQuincuncial).rotate([-90, -90, 45]).clipAngle(180 - 1e-3);
        }
        function gringorten$1() {
          return quincuncial(gringortenRaw).scale(176.423);
        }
        function peirce() {
          return quincuncial(guyouRaw).scale(111.48);
        }
        function quantize(input, digits) {
          if (!(0 <= (digits = +digits) && digits <= 20)) throw new Error("invalid digits");
          function quantizePoint(input2) {
            var n = input2.length, i = 2, output2 = new Array(n);
            output2[0] = +input2[0].toFixed(digits);
            output2[1] = +input2[1].toFixed(digits);
            while (i < n) output2[i] = input2[i], ++i;
            return output2;
          }
          function quantizePoints(input2) {
            return input2.map(quantizePoint);
          }
          function quantizePointsNoDuplicates(input2) {
            var point0 = quantizePoint(input2[0]);
            var output2 = [point0];
            for (var i = 1; i < input2.length; i++) {
              var point = quantizePoint(input2[i]);
              if (point.length > 2 || point[0] != point0[0] || point[1] != point0[1]) {
                output2.push(point);
                point0 = point;
              }
            }
            if (output2.length === 1 && input2.length > 1) {
              output2.push(quantizePoint(input2[input2.length - 1]));
            }
            return output2;
          }
          function quantizePolygon(input2) {
            return input2.map(quantizePointsNoDuplicates);
          }
          function quantizeGeometry(input2) {
            if (input2 == null) return input2;
            var output2;
            switch (input2.type) {
              case "GeometryCollection":
                output2 = { type: "GeometryCollection", geometries: input2.geometries.map(quantizeGeometry) };
                break;
              case "Point":
                output2 = { type: "Point", coordinates: quantizePoint(input2.coordinates) };
                break;
              case "MultiPoint":
                output2 = { type: input2.type, coordinates: quantizePoints(input2.coordinates) };
                break;
              case "LineString":
                output2 = { type: input2.type, coordinates: quantizePointsNoDuplicates(input2.coordinates) };
                break;
              case "MultiLineString":
              case "Polygon":
                output2 = { type: input2.type, coordinates: quantizePolygon(input2.coordinates) };
                break;
              case "MultiPolygon":
                output2 = { type: "MultiPolygon", coordinates: input2.coordinates.map(quantizePolygon) };
                break;
              default:
                return input2;
            }
            if (input2.bbox != null) output2.bbox = input2.bbox;
            return output2;
          }
          function quantizeFeature(input2) {
            var output2 = { type: "Feature", properties: input2.properties, geometry: quantizeGeometry(input2.geometry) };
            if (input2.id != null) output2.id = input2.id;
            if (input2.bbox != null) output2.bbox = input2.bbox;
            return output2;
          }
          if (input != null) switch (input.type) {
            case "Feature":
              return quantizeFeature(input);
            case "FeatureCollection": {
              var output = { type: "FeatureCollection", features: input.features.map(quantizeFeature) };
              if (input.bbox != null) output.bbox = input.bbox;
              return output;
            }
            default:
              return quantizeGeometry(input);
          }
          return input;
        }
        function rectangularPolyconicRaw(phi02) {
          var sinPhi0 = sin(phi02);
          function forward(lambda, phi) {
            var A3 = sinPhi0 ? tan(lambda * sinPhi0 / 2) / sinPhi0 : lambda / 2;
            if (!phi) return [2 * A3, -phi02];
            var E2 = 2 * atan(A3 * sin(phi)), cotPhi = 1 / tan(phi);
            return [
              sin(E2) * cotPhi,
              phi + (1 - cos(E2)) * cotPhi - phi02
            ];
          }
          forward.invert = function(x, y) {
            if (abs(y += phi02) < epsilon) return [sinPhi0 ? 2 * atan(sinPhi0 * x / 2) / sinPhi0 : x, 0];
            var k2 = x * x + y * y, phi = 0, i = 10, delta;
            do {
              var tanPhi = tan(phi), secPhi = 1 / cos(phi), j = k2 - 2 * y * phi + phi * phi;
              phi -= delta = (tanPhi * j + 2 * (phi - y)) / (2 + j * secPhi * secPhi + 2 * (phi - y) * tanPhi);
            } while (abs(delta) > epsilon && --i > 0);
            var E2 = x * (tanPhi = tan(phi)), A3 = tan(abs(y) < abs(phi + 1 / tanPhi) ? asin(E2) * 0.5 : acos(E2) * 0.5 + pi / 4) / sin(phi);
            return [
              sinPhi0 ? 2 * atan(sinPhi0 * A3) / sinPhi0 : 2 * A3,
              phi
            ];
          };
          return forward;
        }
        function rectangularPolyconic() {
          return parallel1(rectangularPolyconicRaw).scale(131.215);
        }
        var K$1 = [
          [0.9986, -0.062],
          [1, 0],
          [0.9986, 0.062],
          [0.9954, 0.124],
          [0.99, 0.186],
          [0.9822, 0.248],
          [0.973, 0.31],
          [0.96, 0.372],
          [0.9427, 0.434],
          [0.9216, 0.4958],
          [0.8962, 0.5571],
          [0.8679, 0.6176],
          [0.835, 0.6769],
          [0.7986, 0.7346],
          [0.7597, 0.7903],
          [0.7186, 0.8435],
          [0.6732, 0.8936],
          [0.6213, 0.9394],
          [0.5722, 0.9761],
          [0.5322, 1]
        ];
        K$1.forEach(function(d) {
          d[1] *= 1.0144;
        });
        function robinsonRaw(lambda, phi) {
          var i = min(18, abs(phi) * 36 / pi), i0 = floor(i), di = i - i0, ax = (k2 = K$1[i0])[0], ay = k2[1], bx = (k2 = K$1[++i0])[0], by = k2[1], cx = (k2 = K$1[min(19, ++i0)])[0], cy = k2[1], k2;
          return [
            lambda * (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2),
            (phi > 0 ? halfPi : -halfPi) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2)
          ];
        }
        robinsonRaw.invert = function(x, y) {
          var yy = y / halfPi, phi = yy * 90, i = min(18, abs(phi / 5)), i0 = max(0, floor(i));
          do {
            var ay = K$1[i0][1], by = K$1[i0 + 1][1], cy = K$1[min(19, i0 + 2)][1], u = cy - ay, v = cy - 2 * by + ay, t = 2 * (abs(yy) - by) / u, c = v / u, di = t * (1 - c * t * (1 - 2 * c * t));
            if (di >= 0 || i0 === 1) {
              phi = (y >= 0 ? 5 : -5) * (di + i);
              var j = 50, delta;
              do {
                i = min(18, abs(phi) / 5);
                i0 = floor(i);
                di = i - i0;
                ay = K$1[i0][1];
                by = K$1[i0 + 1][1];
                cy = K$1[min(19, i0 + 2)][1];
                phi -= (delta = (y >= 0 ? halfPi : -halfPi) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) - y) * degrees3;
              } while (abs(delta) > epsilon22 && --j > 0);
              break;
            }
          } while (--i0 >= 0);
          var ax = K$1[i0][0], bx = K$1[i0 + 1][0], cx = K$1[min(19, i0 + 2)][0];
          return [
            x / (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2),
            phi * radians2
          ];
        };
        function robinson() {
          return d3Geo.geoProjection(robinsonRaw).scale(152.63);
        }
        function satelliteVerticalRaw(P) {
          function forward(lambda, phi) {
            var cosPhi = cos(phi), k2 = (P - 1) / (P - cosPhi * cos(lambda));
            return [
              k2 * cosPhi * sin(lambda),
              k2 * sin(phi)
            ];
          }
          forward.invert = function(x, y) {
            var rho2 = x * x + y * y, rho = sqrt(rho2), sinc = (P - sqrt(1 - rho2 * (P + 1) / (P - 1))) / ((P - 1) / rho + rho / (P - 1));
            return [
              atan2(x * sinc, rho * sqrt(1 - sinc * sinc)),
              rho ? asin(y * sinc / rho) : 0
            ];
          };
          return forward;
        }
        function satelliteRaw(P, omega) {
          var vertical = satelliteVerticalRaw(P);
          if (!omega) return vertical;
          var cosOmega = cos(omega), sinOmega = sin(omega);
          function forward(lambda, phi) {
            var coordinates = vertical(lambda, phi), y = coordinates[1], A3 = y * sinOmega / (P - 1) + cosOmega;
            return [
              coordinates[0] * cosOmega / A3,
              y / A3
            ];
          }
          forward.invert = function(x, y) {
            var k2 = (P - 1) / (P - 1 - y * sinOmega);
            return vertical.invert(k2 * x, k2 * y * cosOmega);
          };
          return forward;
        }
        function satellite() {
          var distance2 = 2, omega = 0, m = d3Geo.geoProjectionMutator(satelliteRaw), p = m(distance2, omega);
          p.distance = function(_) {
            if (!arguments.length) return distance2;
            return m(distance2 = +_, omega);
          };
          p.tilt = function(_) {
            if (!arguments.length) return omega * degrees3;
            return m(distance2, omega = _ * radians2);
          };
          return p.scale(432.147).clipAngle(acos(1 / distance2) * degrees3 - 1e-6);
        }
        var epsilon$1 = 1e-4, epsilonInverse = 1e4, x0 = -180, x0e = x0 + epsilon$1, x1 = 180, x1e = x1 - epsilon$1, y0 = -90, y0e = y0 + epsilon$1, y1 = 90, y1e = y1 - epsilon$1;
        function nonempty(coordinates) {
          return coordinates.length > 0;
        }
        function quantize$1(x) {
          return Math.floor(x * epsilonInverse) / epsilonInverse;
        }
        function normalizePoint(y) {
          return y === y0 || y === y1 ? [0, y] : [x0, quantize$1(y)];
        }
        function clampPoint(p) {
          var x = p[0], y = p[1], clamped = false;
          if (x <= x0e) x = x0, clamped = true;
          else if (x >= x1e) x = x1, clamped = true;
          if (y <= y0e) y = y0, clamped = true;
          else if (y >= y1e) y = y1, clamped = true;
          return clamped ? [x, y] : p;
        }
        function clampPoints(points2) {
          return points2.map(clampPoint);
        }
        function extractFragments(rings, polygon, fragments) {
          for (var j = 0, m = rings.length; j < m; ++j) {
            var ring = rings[j].slice();
            fragments.push({ index: -1, polygon, ring });
            for (var i = 0, n = ring.length; i < n; ++i) {
              var point = ring[i], x = point[0], y = point[1];
              if (x <= x0e || x >= x1e || y <= y0e || y >= y1e) {
                ring[i] = clampPoint(point);
                for (var k2 = i + 1; k2 < n; ++k2) {
                  var pointk = ring[k2], xk = pointk[0], yk = pointk[1];
                  if (xk > x0e && xk < x1e && yk > y0e && yk < y1e) break;
                }
                if (k2 === i + 1) continue;
                if (i) {
                  var fragmentBefore = { index: -1, polygon, ring: ring.slice(0, i + 1) };
                  fragmentBefore.ring[fragmentBefore.ring.length - 1] = normalizePoint(y);
                  fragments[fragments.length - 1] = fragmentBefore;
                } else fragments.pop();
                if (k2 >= n) break;
                fragments.push({ index: -1, polygon, ring: ring = ring.slice(k2 - 1) });
                ring[0] = normalizePoint(ring[0][1]);
                i = -1;
                n = ring.length;
              }
            }
          }
        }
        function stitchFragments(fragments) {
          var i, n = fragments.length;
          var fragmentByStart = {}, fragmentByEnd = {}, fragment, start, startFragment, end, endFragment;
          for (i = 0; i < n; ++i) {
            fragment = fragments[i];
            start = fragment.ring[0];
            end = fragment.ring[fragment.ring.length - 1];
            if (start[0] === end[0] && start[1] === end[1]) {
              fragment.polygon.push(fragment.ring);
              fragments[i] = null;
              continue;
            }
            fragment.index = i;
            fragmentByStart[start] = fragmentByEnd[end] = fragment;
          }
          for (i = 0; i < n; ++i) {
            fragment = fragments[i];
            if (fragment) {
              start = fragment.ring[0];
              end = fragment.ring[fragment.ring.length - 1];
              startFragment = fragmentByEnd[start];
              endFragment = fragmentByStart[end];
              delete fragmentByStart[start];
              delete fragmentByEnd[end];
              if (start[0] === end[0] && start[1] === end[1]) {
                fragment.polygon.push(fragment.ring);
                continue;
              }
              if (startFragment) {
                delete fragmentByEnd[start];
                delete fragmentByStart[startFragment.ring[0]];
                startFragment.ring.pop();
                fragments[startFragment.index] = null;
                fragment = { index: -1, polygon: startFragment.polygon, ring: startFragment.ring.concat(fragment.ring) };
                if (startFragment === endFragment) {
                  fragment.polygon.push(fragment.ring);
                } else {
                  fragment.index = n++;
                  fragments.push(fragmentByStart[fragment.ring[0]] = fragmentByEnd[fragment.ring[fragment.ring.length - 1]] = fragment);
                }
              } else if (endFragment) {
                delete fragmentByStart[end];
                delete fragmentByEnd[endFragment.ring[endFragment.ring.length - 1]];
                fragment.ring.pop();
                fragment = { index: n++, polygon: endFragment.polygon, ring: fragment.ring.concat(endFragment.ring) };
                fragments[endFragment.index] = null;
                fragments.push(fragmentByStart[fragment.ring[0]] = fragmentByEnd[fragment.ring[fragment.ring.length - 1]] = fragment);
              } else {
                fragment.ring.push(fragment.ring[0]);
                fragment.polygon.push(fragment.ring);
              }
            }
          }
        }
        function stitchFeature(input) {
          var output = { type: "Feature", geometry: stitchGeometry(input.geometry) };
          if (input.id != null) output.id = input.id;
          if (input.bbox != null) output.bbox = input.bbox;
          if (input.properties != null) output.properties = input.properties;
          return output;
        }
        function stitchGeometry(input) {
          if (input == null) return input;
          var output, fragments, i, n;
          switch (input.type) {
            case "GeometryCollection":
              output = { type: "GeometryCollection", geometries: input.geometries.map(stitchGeometry) };
              break;
            case "Point":
              output = { type: "Point", coordinates: clampPoint(input.coordinates) };
              break;
            case "MultiPoint":
            case "LineString":
              output = { type: input.type, coordinates: clampPoints(input.coordinates) };
              break;
            case "MultiLineString":
              output = { type: "MultiLineString", coordinates: input.coordinates.map(clampPoints) };
              break;
            case "Polygon": {
              var polygon = [];
              extractFragments(input.coordinates, polygon, fragments = []);
              stitchFragments(fragments);
              output = { type: "Polygon", coordinates: polygon };
              break;
            }
            case "MultiPolygon": {
              fragments = [], i = -1, n = input.coordinates.length;
              var polygons = new Array(n);
              while (++i < n) extractFragments(input.coordinates[i], polygons[i] = [], fragments);
              stitchFragments(fragments);
              output = { type: "MultiPolygon", coordinates: polygons.filter(nonempty) };
              break;
            }
            default:
              return input;
          }
          if (input.bbox != null) output.bbox = input.bbox;
          return output;
        }
        function stitch(input) {
          if (input == null) return input;
          switch (input.type) {
            case "Feature":
              return stitchFeature(input);
            case "FeatureCollection": {
              var output = { type: "FeatureCollection", features: input.features.map(stitchFeature) };
              if (input.bbox != null) output.bbox = input.bbox;
              return output;
            }
            default:
              return stitchGeometry(input);
          }
        }
        function timesRaw(lambda, phi) {
          var t = tan(phi / 2), s = sin(quarterPi * t);
          return [
            lambda * (0.74482 - 0.34588 * s * s),
            1.70711 * t
          ];
        }
        timesRaw.invert = function(x, y) {
          var t = y / 1.70711, s = sin(quarterPi * t);
          return [
            x / (0.74482 - 0.34588 * s * s),
            2 * atan(t)
          ];
        };
        function times() {
          return d3Geo.geoProjection(timesRaw).scale(146.153);
        }
        function twoPoint(raw, p0, p1) {
          var i = d3Geo.geoInterpolate(p0, p1), o = i(0.5), a = d3Geo.geoRotation([-o[0], -o[1]])(p0), b = i.distance / 2, y = -asin(sin(a[1] * radians2) / sin(b)), R = [-o[0], -o[1], -(a[0] > 0 ? pi - y : y) * degrees3], p = d3Geo.geoProjection(raw(b)).rotate(R), r = d3Geo.geoRotation(R), center = p.center;
          delete p.rotate;
          p.center = function(_) {
            return arguments.length ? center(r(_)) : r.invert(center());
          };
          return p.clipAngle(90);
        }
        function twoPointAzimuthalRaw(d) {
          var cosd = cos(d);
          function forward(lambda, phi) {
            var coordinates = d3Geo.geoGnomonicRaw(lambda, phi);
            coordinates[0] *= cosd;
            return coordinates;
          }
          forward.invert = function(x, y) {
            return d3Geo.geoGnomonicRaw.invert(x / cosd, y);
          };
          return forward;
        }
        function twoPointAzimuthalUsa() {
          return twoPointAzimuthal([-158, 21.5], [-77, 39]).clipAngle(60).scale(400);
        }
        function twoPointAzimuthal(p0, p1) {
          return twoPoint(twoPointAzimuthalRaw, p0, p1);
        }
        function twoPointEquidistantRaw(z0) {
          if (!(z0 *= 2)) return d3Geo.geoAzimuthalEquidistantRaw;
          var lambdaa = -z0 / 2, lambdab = -lambdaa, z02 = z0 * z0, tanLambda0 = tan(lambdab), S = 0.5 / sin(lambdab);
          function forward(lambda, phi) {
            var za = acos(cos(phi) * cos(lambda - lambdaa)), zb = acos(cos(phi) * cos(lambda - lambdab)), ys = phi < 0 ? -1 : 1;
            za *= za, zb *= zb;
            return [
              (za - zb) / (2 * z0),
              ys * sqrt(4 * z02 * zb - (z02 - za + zb) * (z02 - za + zb)) / (2 * z0)
            ];
          }
          forward.invert = function(x, y) {
            var y2 = y * y, cosza = cos(sqrt(y2 + (t = x + lambdaa) * t)), coszb = cos(sqrt(y2 + (t = x + lambdab) * t)), t, d;
            return [
              atan2(d = cosza - coszb, t = (cosza + coszb) * tanLambda0),
              (y < 0 ? -1 : 1) * acos(sqrt(t * t + d * d) * S)
            ];
          };
          return forward;
        }
        function twoPointEquidistantUsa() {
          return twoPointEquidistant([-158, 21.5], [-77, 39]).clipAngle(130).scale(122.571);
        }
        function twoPointEquidistant(p0, p1) {
          return twoPoint(twoPointEquidistantRaw, p0, p1);
        }
        function vanDerGrintenRaw(lambda, phi) {
          if (abs(phi) < epsilon) return [lambda, 0];
          var sinTheta = abs(phi / halfPi), theta = asin(sinTheta);
          if (abs(lambda) < epsilon || abs(abs(phi) - halfPi) < epsilon) return [0, sign(phi) * pi * tan(theta / 2)];
          var cosTheta = cos(theta), A3 = abs(pi / lambda - lambda / pi) / 2, A22 = A3 * A3, G = cosTheta / (sinTheta + cosTheta - 1), P = G * (2 / sinTheta - 1), P2 = P * P, P2_A2 = P2 + A22, G_P2 = G - P2, Q = A22 + G;
          return [
            sign(lambda) * pi * (A3 * G_P2 + sqrt(A22 * G_P2 * G_P2 - P2_A2 * (G * G - P2))) / P2_A2,
            sign(phi) * pi * (P * Q - A3 * sqrt((A22 + 1) * P2_A2 - Q * Q)) / P2_A2
          ];
        }
        vanDerGrintenRaw.invert = function(x, y) {
          if (abs(y) < epsilon) return [x, 0];
          if (abs(x) < epsilon) return [0, halfPi * sin(2 * atan(y / pi))];
          var x2 = (x /= pi) * x, y2 = (y /= pi) * y, x2_y2 = x2 + y2, z = x2_y2 * x2_y2, c1 = -abs(y) * (1 + x2_y2), c2 = c1 - 2 * y2 + x2, c3 = -2 * c1 + 1 + 2 * y2 + z, d = y2 / c3 + (2 * c2 * c2 * c2 / (c3 * c3 * c3) - 9 * c1 * c2 / (c3 * c3)) / 27, a1 = (c1 - c2 * c2 / (3 * c3)) / c3, m1 = 2 * sqrt(-a1 / 3), theta1 = acos(3 * d / (a1 * m1)) / 3;
          return [
            pi * (x2_y2 - 1 + sqrt(1 + 2 * (x2 - y2) + z)) / (2 * x),
            sign(y) * pi * (-m1 * cos(theta1 + pi / 3) - c2 / (3 * c3))
          ];
        };
        function vanDerGrinten() {
          return d3Geo.geoProjection(vanDerGrintenRaw).scale(79.4183);
        }
        function vanDerGrinten2Raw(lambda, phi) {
          if (abs(phi) < epsilon) return [lambda, 0];
          var sinTheta = abs(phi / halfPi), theta = asin(sinTheta);
          if (abs(lambda) < epsilon || abs(abs(phi) - halfPi) < epsilon) return [0, sign(phi) * pi * tan(theta / 2)];
          var cosTheta = cos(theta), A3 = abs(pi / lambda - lambda / pi) / 2, A22 = A3 * A3, x12 = cosTheta * (sqrt(1 + A22) - A3 * cosTheta) / (1 + A22 * sinTheta * sinTheta);
          return [
            sign(lambda) * pi * x12,
            sign(phi) * pi * sqrt(1 - x12 * (2 * A3 + x12))
          ];
        }
        vanDerGrinten2Raw.invert = function(x, y) {
          if (!x) return [0, halfPi * sin(2 * atan(y / pi))];
          var x12 = abs(x / pi), A3 = (1 - x12 * x12 - (y /= pi) * y) / (2 * x12), A22 = A3 * A3, B3 = sqrt(A22 + 1);
          return [
            sign(x) * pi * (B3 - A3),
            sign(y) * halfPi * sin(2 * atan2(sqrt((1 - 2 * A3 * x12) * (A3 + B3) - x12), sqrt(B3 + A3 + x12)))
          ];
        };
        function vanDerGrinten2() {
          return d3Geo.geoProjection(vanDerGrinten2Raw).scale(79.4183);
        }
        function vanDerGrinten3Raw(lambda, phi) {
          if (abs(phi) < epsilon) return [lambda, 0];
          var sinTheta = phi / halfPi, theta = asin(sinTheta);
          if (abs(lambda) < epsilon || abs(abs(phi) - halfPi) < epsilon) return [0, pi * tan(theta / 2)];
          var A3 = (pi / lambda - lambda / pi) / 2, y12 = sinTheta / (1 + cos(theta));
          return [
            pi * (sign(lambda) * sqrt(A3 * A3 + 1 - y12 * y12) - A3),
            pi * y12
          ];
        }
        vanDerGrinten3Raw.invert = function(x, y) {
          if (!y) return [x, 0];
          var y12 = y / pi, A3 = (pi * pi * (1 - y12 * y12) - x * x) / (2 * pi * x);
          return [
            x ? pi * (sign(x) * sqrt(A3 * A3 + 1) - A3) : 0,
            halfPi * sin(2 * atan(y12))
          ];
        };
        function vanDerGrinten3() {
          return d3Geo.geoProjection(vanDerGrinten3Raw).scale(79.4183);
        }
        function vanDerGrinten4Raw(lambda, phi) {
          if (!phi) return [lambda, 0];
          var phi02 = abs(phi);
          if (!lambda || phi02 === halfPi) return [0, phi];
          var B3 = phi02 / halfPi, B22 = B3 * B3, C2 = (8 * B3 - B22 * (B22 + 2) - 5) / (2 * B22 * (B3 - 1)), C22 = C2 * C2, BC = B3 * C2, B_C2 = B22 + C22 + 2 * BC, B_3C = B3 + 3 * C2, lambda0 = lambda / halfPi, lambda1 = lambda0 + 1 / lambda0, D2 = sign(abs(lambda) - halfPi) * sqrt(lambda1 * lambda1 - 4), D22 = D2 * D2, F = B_C2 * (B22 + C22 * D22 - 1) + (1 - B22) * (B22 * (B_3C * B_3C + 4 * C22) + 12 * BC * C22 + 4 * C22 * C22), x12 = (D2 * (B_C2 + C22 - 1) + 2 * sqrt(F)) / (4 * B_C2 + D22);
          return [
            sign(lambda) * halfPi * x12,
            sign(phi) * halfPi * sqrt(1 + D2 * abs(x12) - x12 * x12)
          ];
        }
        vanDerGrinten4Raw.invert = function(x, y) {
          var delta;
          if (!x || !y) return [x, y];
          y /= pi;
          var x12 = sign(x) * x / halfPi, D2 = (x12 * x12 - 1 + 4 * y * y) / abs(x12), D22 = D2 * D2, B3 = 2 * y, i = 50;
          do {
            var B22 = B3 * B3, C2 = (8 * B3 - B22 * (B22 + 2) - 5) / (2 * B22 * (B3 - 1)), C_ = (3 * B3 - B22 * B3 - 10) / (2 * B22 * B3), C22 = C2 * C2, BC = B3 * C2, B_C = B3 + C2, B_C2 = B_C * B_C, B_3C = B3 + 3 * C2, F = B_C2 * (B22 + C22 * D22 - 1) + (1 - B22) * (B22 * (B_3C * B_3C + 4 * C22) + C22 * (12 * BC + 4 * C22)), F_ = -2 * B_C * (4 * BC * C22 + (1 - 4 * B22 + 3 * B22 * B22) * (1 + C_) + C22 * (-6 + 14 * B22 - D22 + (-8 + 8 * B22 - 2 * D22) * C_) + BC * (-8 + 12 * B22 + (-10 + 10 * B22 - D22) * C_)), sqrtF = sqrt(F), f = D2 * (B_C2 + C22 - 1) + 2 * sqrtF - x12 * (4 * B_C2 + D22), f_ = D2 * (2 * C2 * C_ + 2 * B_C * (1 + C_)) + F_ / sqrtF - 8 * B_C * (D2 * (-1 + C22 + B_C2) + 2 * sqrtF) * (1 + C_) / (D22 + 4 * B_C2);
            B3 -= delta = f / f_;
          } while (delta > epsilon && --i > 0);
          return [
            sign(x) * (sqrt(D2 * D2 + 4) + D2) * pi / 4,
            halfPi * B3
          ];
        };
        function vanDerGrinten4() {
          return d3Geo.geoProjection(vanDerGrinten4Raw).scale(127.16);
        }
        function wagnerFormula(cx, cy, m1, m2, n) {
          function forward(lambda, phi) {
            var s = m1 * sin(m2 * phi), c0 = sqrt(1 - s * s), c1 = sqrt(2 / (1 + c0 * cos(lambda *= n)));
            return [
              cx * c0 * c1 * sin(lambda),
              cy * s * c1
            ];
          }
          forward.invert = function(x, y) {
            var t12 = x / cx, t22 = y / cy, p = sqrt(t12 * t12 + t22 * t22), c = 2 * asin(p / 2);
            return [
              atan2(x * tan(c), cx * p) / n,
              p && asin(y * sin(c) / (cy * m1 * p)) / m2
            ];
          };
          return forward;
        }
        function wagnerRaw(poleline, parallels, inflation, ratio) {
          var phi1 = pi / 3;
          poleline = max(poleline, epsilon);
          parallels = max(parallels, epsilon);
          poleline = min(poleline, halfPi);
          parallels = min(parallels, pi - epsilon);
          inflation = max(inflation, 0);
          inflation = min(inflation, 100 - epsilon);
          ratio = max(ratio, epsilon);
          var vinflation = inflation / 100 + 1;
          var vratio = ratio / 100;
          var m2 = acos(vinflation * cos(phi1)) / phi1, m1 = sin(poleline) / sin(m2 * halfPi), n = parallels / pi, k2 = sqrt(vratio * sin(poleline / 2) / sin(parallels / 2)), cx = k2 / sqrt(n * m1 * m2), cy = 1 / (k2 * sqrt(n * m1 * m2));
          return wagnerFormula(cx, cy, m1, m2, n);
        }
        function wagner() {
          var poleline = 65 * radians2, parallels = 60 * radians2, inflation = 20, ratio = 200, mutate = d3Geo.geoProjectionMutator(wagnerRaw), projection = mutate(poleline, parallels, inflation, ratio);
          projection.poleline = function(_) {
            return arguments.length ? mutate(poleline = +_ * radians2, parallels, inflation, ratio) : poleline * degrees3;
          };
          projection.parallels = function(_) {
            return arguments.length ? mutate(poleline, parallels = +_ * radians2, inflation, ratio) : parallels * degrees3;
          };
          projection.inflation = function(_) {
            return arguments.length ? mutate(poleline, parallels, inflation = +_, ratio) : inflation;
          };
          projection.ratio = function(_) {
            return arguments.length ? mutate(poleline, parallels, inflation, ratio = +_) : ratio;
          };
          return projection.scale(163.775);
        }
        function wagner7() {
          return wagner().poleline(65).parallels(60).inflation(0).ratio(200).scale(172.633);
        }
        var A2 = 4 * pi + 3 * sqrt(3), B2 = 2 * sqrt(2 * pi * sqrt(3) / A2);
        var wagner4Raw = mollweideBromleyRaw(B2 * sqrt(3) / pi, B2, A2 / 6);
        function wagner4() {
          return d3Geo.geoProjection(wagner4Raw).scale(176.84);
        }
        function wagner6Raw(lambda, phi) {
          return [lambda * sqrt(1 - 3 * phi * phi / (pi * pi)), phi];
        }
        wagner6Raw.invert = function(x, y) {
          return [x / sqrt(1 - 3 * y * y / (pi * pi)), y];
        };
        function wagner6() {
          return d3Geo.geoProjection(wagner6Raw).scale(152.63);
        }
        function wiechelRaw(lambda, phi) {
          var cosPhi = cos(phi), sinPhi = cos(lambda) * cosPhi, sin1_Phi = 1 - sinPhi, cosLambda = cos(lambda = atan2(sin(lambda) * cosPhi, -sin(phi))), sinLambda = sin(lambda);
          cosPhi = sqrt(1 - sinPhi * sinPhi);
          return [
            sinLambda * cosPhi - cosLambda * sin1_Phi,
            -cosLambda * cosPhi - sinLambda * sin1_Phi
          ];
        }
        wiechelRaw.invert = function(x, y) {
          var w2 = (x * x + y * y) / -2, k2 = sqrt(-w2 * (2 + w2)), b = y * w2 + x * k2, a = x * w2 - y * k2, D2 = sqrt(a * a + b * b);
          return [
            atan2(k2 * b, D2 * (1 + w2)),
            D2 ? -asin(k2 * a / D2) : 0
          ];
        };
        function wiechel() {
          return d3Geo.geoProjection(wiechelRaw).rotate([0, -90, 45]).scale(124.75).clipAngle(180 - 1e-3);
        }
        function winkel3Raw(lambda, phi) {
          var coordinates = aitoffRaw(lambda, phi);
          return [
            (coordinates[0] + lambda / halfPi) / 2,
            (coordinates[1] + phi) / 2
          ];
        }
        winkel3Raw.invert = function(x, y) {
          var lambda = x, phi = y, i = 25;
          do {
            var cosphi = cos(phi), sinphi = sin(phi), sin_2phi = sin(2 * phi), sin2phi = sinphi * sinphi, cos2phi = cosphi * cosphi, sinlambda = sin(lambda), coslambda_2 = cos(lambda / 2), sinlambda_2 = sin(lambda / 2), sin2lambda_2 = sinlambda_2 * sinlambda_2, C2 = 1 - cos2phi * coslambda_2 * coslambda_2, E2 = C2 ? acos(cosphi * coslambda_2) * sqrt(F = 1 / C2) : F = 0, F, fx = 0.5 * (2 * E2 * cosphi * sinlambda_2 + lambda / halfPi) - x, fy = 0.5 * (E2 * sinphi + phi) - y, dxdlambda = 0.5 * F * (cos2phi * sin2lambda_2 + E2 * cosphi * coslambda_2 * sin2phi) + 0.5 / halfPi, dxdphi = F * (sinlambda * sin_2phi / 4 - E2 * sinphi * sinlambda_2), dydlambda = 0.125 * F * (sin_2phi * sinlambda_2 - E2 * sinphi * cos2phi * sinlambda), dydphi = 0.5 * F * (sin2phi * coslambda_2 + E2 * sin2lambda_2 * cosphi) + 0.5, denominator = dxdphi * dydlambda - dydphi * dxdlambda, dlambda = (fy * dxdphi - fx * dydphi) / denominator, dphi = (fx * dydlambda - fy * dxdlambda) / denominator;
            lambda -= dlambda, phi -= dphi;
          } while ((abs(dlambda) > epsilon || abs(dphi) > epsilon) && --i > 0);
          return [lambda, phi];
        };
        function winkel3() {
          return d3Geo.geoProjection(winkel3Raw).scale(158.837);
        }
        exports2.geoNaturalEarth = d3Geo.geoNaturalEarth1;
        exports2.geoNaturalEarthRaw = d3Geo.geoNaturalEarth1Raw;
        exports2.geoAiry = airy;
        exports2.geoAiryRaw = airyRaw;
        exports2.geoAitoff = aitoff;
        exports2.geoAitoffRaw = aitoffRaw;
        exports2.geoArmadillo = armadillo;
        exports2.geoArmadilloRaw = armadilloRaw;
        exports2.geoAugust = august;
        exports2.geoAugustRaw = augustRaw;
        exports2.geoBaker = baker;
        exports2.geoBakerRaw = bakerRaw;
        exports2.geoBerghaus = berghaus;
        exports2.geoBerghausRaw = berghausRaw;
        exports2.geoBertin1953 = bertin;
        exports2.geoBertin1953Raw = bertin1953Raw;
        exports2.geoBoggs = boggs;
        exports2.geoBoggsRaw = boggsRaw;
        exports2.geoBonne = bonne;
        exports2.geoBonneRaw = bonneRaw;
        exports2.geoBottomley = bottomley;
        exports2.geoBottomleyRaw = bottomleyRaw;
        exports2.geoBromley = bromley;
        exports2.geoBromleyRaw = bromleyRaw;
        exports2.geoChamberlin = chamberlin;
        exports2.geoChamberlinRaw = chamberlinRaw;
        exports2.geoChamberlinAfrica = chamberlinAfrica;
        exports2.geoCollignon = collignon;
        exports2.geoCollignonRaw = collignonRaw;
        exports2.geoCraig = craig;
        exports2.geoCraigRaw = craigRaw;
        exports2.geoCraster = craster;
        exports2.geoCrasterRaw = crasterRaw;
        exports2.geoCylindricalEqualArea = cylindricalEqualArea;
        exports2.geoCylindricalEqualAreaRaw = cylindricalEqualAreaRaw;
        exports2.geoCylindricalStereographic = cylindricalStereographic;
        exports2.geoCylindricalStereographicRaw = cylindricalStereographicRaw;
        exports2.geoEckert1 = eckert1;
        exports2.geoEckert1Raw = eckert1Raw;
        exports2.geoEckert2 = eckert2;
        exports2.geoEckert2Raw = eckert2Raw;
        exports2.geoEckert3 = eckert3;
        exports2.geoEckert3Raw = eckert3Raw;
        exports2.geoEckert4 = eckert4;
        exports2.geoEckert4Raw = eckert4Raw;
        exports2.geoEckert5 = eckert5;
        exports2.geoEckert5Raw = eckert5Raw;
        exports2.geoEckert6 = eckert6;
        exports2.geoEckert6Raw = eckert6Raw;
        exports2.geoEisenlohr = eisenlohr;
        exports2.geoEisenlohrRaw = eisenlohrRaw;
        exports2.geoFahey = fahey;
        exports2.geoFaheyRaw = faheyRaw;
        exports2.geoFoucaut = foucaut;
        exports2.geoFoucautRaw = foucautRaw;
        exports2.geoFoucautSinusoidal = foucautSinusoidal;
        exports2.geoFoucautSinusoidalRaw = foucautSinusoidalRaw;
        exports2.geoGilbert = gilbert;
        exports2.geoGingery = gingery;
        exports2.geoGingeryRaw = gingeryRaw;
        exports2.geoGinzburg4 = ginzburg4;
        exports2.geoGinzburg4Raw = ginzburg4Raw;
        exports2.geoGinzburg5 = ginzburg5;
        exports2.geoGinzburg5Raw = ginzburg5Raw;
        exports2.geoGinzburg6 = ginzburg6;
        exports2.geoGinzburg6Raw = ginzburg6Raw;
        exports2.geoGinzburg8 = ginzburg8;
        exports2.geoGinzburg8Raw = ginzburg8Raw;
        exports2.geoGinzburg9 = ginzburg9;
        exports2.geoGinzburg9Raw = ginzburg9Raw;
        exports2.geoGringorten = gringorten;
        exports2.geoGringortenRaw = gringortenRaw;
        exports2.geoGuyou = guyou;
        exports2.geoGuyouRaw = guyouRaw;
        exports2.geoHammer = hammer;
        exports2.geoHammerRaw = hammerRaw;
        exports2.geoHammerRetroazimuthal = hammerRetroazimuthal;
        exports2.geoHammerRetroazimuthalRaw = hammerRetroazimuthalRaw;
        exports2.geoHealpix = healpix;
        exports2.geoHealpixRaw = healpixRaw;
        exports2.geoHill = hill;
        exports2.geoHillRaw = hillRaw;
        exports2.geoHomolosine = homolosine;
        exports2.geoHomolosineRaw = homolosineRaw;
        exports2.geoHufnagel = hufnagel;
        exports2.geoHufnagelRaw = hufnagelRaw;
        exports2.geoHyperelliptical = hyperelliptical;
        exports2.geoHyperellipticalRaw = hyperellipticalRaw;
        exports2.geoInterrupt = interrupt;
        exports2.geoInterruptedBoggs = boggs$1;
        exports2.geoInterruptedHomolosine = homolosine$1;
        exports2.geoInterruptedMollweide = mollweide$1;
        exports2.geoInterruptedMollweideHemispheres = mollweideHemispheres;
        exports2.geoInterruptedSinuMollweide = sinuMollweide$1;
        exports2.geoInterruptedSinusoidal = sinusoidal$1;
        exports2.geoKavrayskiy7 = kavrayskiy7;
        exports2.geoKavrayskiy7Raw = kavrayskiy7Raw;
        exports2.geoLagrange = lagrange;
        exports2.geoLagrangeRaw = lagrangeRaw;
        exports2.geoLarrivee = larrivee;
        exports2.geoLarriveeRaw = larriveeRaw;
        exports2.geoLaskowski = laskowski;
        exports2.geoLaskowskiRaw = laskowskiRaw;
        exports2.geoLittrow = littrow;
        exports2.geoLittrowRaw = littrowRaw;
        exports2.geoLoximuthal = loximuthal;
        exports2.geoLoximuthalRaw = loximuthalRaw;
        exports2.geoMiller = miller;
        exports2.geoMillerRaw = millerRaw;
        exports2.geoModifiedStereographic = modifiedStereographic;
        exports2.geoModifiedStereographicRaw = modifiedStereographicRaw;
        exports2.geoModifiedStereographicAlaska = modifiedStereographicAlaska;
        exports2.geoModifiedStereographicGs48 = modifiedStereographicGs48;
        exports2.geoModifiedStereographicGs50 = modifiedStereographicGs50;
        exports2.geoModifiedStereographicMiller = modifiedStereographicMiller;
        exports2.geoModifiedStereographicLee = modifiedStereographicLee;
        exports2.geoMollweide = mollweide;
        exports2.geoMollweideRaw = mollweideRaw;
        exports2.geoMtFlatPolarParabolic = mtFlatPolarParabolic;
        exports2.geoMtFlatPolarParabolicRaw = mtFlatPolarParabolicRaw;
        exports2.geoMtFlatPolarQuartic = mtFlatPolarQuartic;
        exports2.geoMtFlatPolarQuarticRaw = mtFlatPolarQuarticRaw;
        exports2.geoMtFlatPolarSinusoidal = mtFlatPolarSinusoidal;
        exports2.geoMtFlatPolarSinusoidalRaw = mtFlatPolarSinusoidalRaw;
        exports2.geoNaturalEarth2 = naturalEarth2;
        exports2.geoNaturalEarth2Raw = naturalEarth2Raw;
        exports2.geoNellHammer = nellHammer;
        exports2.geoNellHammerRaw = nellHammerRaw;
        exports2.geoInterruptedQuarticAuthalic = quarticAuthalic;
        exports2.geoNicolosi = nicolosi;
        exports2.geoNicolosiRaw = nicolosiRaw;
        exports2.geoPatterson = patterson;
        exports2.geoPattersonRaw = pattersonRaw;
        exports2.geoPolyconic = polyconic;
        exports2.geoPolyconicRaw = polyconicRaw;
        exports2.geoPolyhedral = polyhedral;
        exports2.geoPolyhedralButterfly = butterfly;
        exports2.geoPolyhedralCollignon = collignon$1;
        exports2.geoPolyhedralWaterman = waterman;
        exports2.geoProject = index;
        exports2.geoGringortenQuincuncial = gringorten$1;
        exports2.geoPeirceQuincuncial = peirce;
        exports2.geoPierceQuincuncial = peirce;
        exports2.geoQuantize = quantize;
        exports2.geoQuincuncial = quincuncial;
        exports2.geoRectangularPolyconic = rectangularPolyconic;
        exports2.geoRectangularPolyconicRaw = rectangularPolyconicRaw;
        exports2.geoRobinson = robinson;
        exports2.geoRobinsonRaw = robinsonRaw;
        exports2.geoSatellite = satellite;
        exports2.geoSatelliteRaw = satelliteRaw;
        exports2.geoSinuMollweide = sinuMollweide;
        exports2.geoSinuMollweideRaw = sinuMollweideRaw;
        exports2.geoSinusoidal = sinusoidal;
        exports2.geoSinusoidalRaw = sinusoidalRaw;
        exports2.geoStitch = stitch;
        exports2.geoTimes = times;
        exports2.geoTimesRaw = timesRaw;
        exports2.geoTwoPointAzimuthal = twoPointAzimuthal;
        exports2.geoTwoPointAzimuthalRaw = twoPointAzimuthalRaw;
        exports2.geoTwoPointAzimuthalUsa = twoPointAzimuthalUsa;
        exports2.geoTwoPointEquidistant = twoPointEquidistant;
        exports2.geoTwoPointEquidistantRaw = twoPointEquidistantRaw;
        exports2.geoTwoPointEquidistantUsa = twoPointEquidistantUsa;
        exports2.geoVanDerGrinten = vanDerGrinten;
        exports2.geoVanDerGrintenRaw = vanDerGrintenRaw;
        exports2.geoVanDerGrinten2 = vanDerGrinten2;
        exports2.geoVanDerGrinten2Raw = vanDerGrinten2Raw;
        exports2.geoVanDerGrinten3 = vanDerGrinten3;
        exports2.geoVanDerGrinten3Raw = vanDerGrinten3Raw;
        exports2.geoVanDerGrinten4 = vanDerGrinten4;
        exports2.geoVanDerGrinten4Raw = vanDerGrinten4Raw;
        exports2.geoWagner = wagner;
        exports2.geoWagner7 = wagner7;
        exports2.geoWagnerRaw = wagnerRaw;
        exports2.geoWagner4 = wagner4;
        exports2.geoWagner4Raw = wagner4Raw;
        exports2.geoWagner6 = wagner6;
        exports2.geoWagner6Raw = wagner6Raw;
        exports2.geoWiechel = wiechel;
        exports2.geoWiechelRaw = wiechelRaw;
        exports2.geoWinkel3 = winkel3;
        exports2.geoWinkel3Raw = winkel3Raw;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // src/plots/geo/zoom.js
  var require_zoom = __commonJS({
    "src/plots/geo/zoom.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var Registry = require_registry();
      var radians2 = Math.PI / 180;
      var degrees3 = 180 / Math.PI;
      var zoomstartStyle = { cursor: "pointer" };
      var zoomendStyle = { cursor: "auto" };
      function createGeoZoom(geo, geoLayout) {
        var projection = geo.projection;
        var zoomConstructor;
        if (geoLayout._isScoped) {
          zoomConstructor = zoomScoped;
        } else if (geoLayout._isClipped) {
          zoomConstructor = zoomClipped;
        } else {
          zoomConstructor = zoomNonClipped;
        }
        return zoomConstructor(geo, projection);
      }
      module.exports = createGeoZoom;
      function initZoom(geo, projection) {
        return d3.behavior.zoom().translate(projection.translate()).scale(projection.scale());
      }
      function sync(geo, projection, cb) {
        var id = geo.id;
        var gd = geo.graphDiv;
        var layout = gd.layout;
        var userOpts = layout[id];
        var fullLayout = gd._fullLayout;
        var fullOpts = fullLayout[id];
        var preGUI = {};
        var eventData = {};
        function set(propStr, val) {
          preGUI[id + "." + propStr] = Lib.nestedProperty(userOpts, propStr).get();
          Registry.call("_storeDirectGUIEdit", layout, fullLayout._preGUI, preGUI);
          var fullNp = Lib.nestedProperty(fullOpts, propStr);
          if (fullNp.get() !== val) {
            fullNp.set(val);
            Lib.nestedProperty(userOpts, propStr).set(val);
            eventData[id + "." + propStr] = val;
          }
        }
        cb(set);
        set("projection.scale", projection.scale() / geo.fitScale);
        set("fitbounds", false);
        gd.emit("plotly_relayout", eventData);
      }
      function zoomScoped(geo, projection) {
        var zoom = initZoom(geo, projection);
        function handleZoomstart() {
          d3.select(this).style(zoomstartStyle);
        }
        function handleZoom() {
          projection.scale(d3.event.scale).translate(d3.event.translate);
          geo.render(true);
          var center = projection.invert(geo.midPt);
          geo.graphDiv.emit("plotly_relayouting", {
            "geo.projection.scale": projection.scale() / geo.fitScale,
            "geo.center.lon": center[0],
            "geo.center.lat": center[1]
          });
        }
        function syncCb(set) {
          var center = projection.invert(geo.midPt);
          set("center.lon", center[0]);
          set("center.lat", center[1]);
        }
        function handleZoomend() {
          d3.select(this).style(zoomendStyle);
          sync(geo, projection, syncCb);
        }
        zoom.on("zoomstart", handleZoomstart).on("zoom", handleZoom).on("zoomend", handleZoomend);
        return zoom;
      }
      function zoomNonClipped(geo, projection) {
        var zoom = initZoom(geo, projection);
        var INSIDETOLORANCEPXS = 2;
        var mouse0, rotate0, translate0, lastRotate, zoomPoint, mouse1, rotate1, point1, didZoom;
        function position2(x) {
          return projection.invert(x);
        }
        function outside(x) {
          var pos = position2(x);
          if (!pos) return true;
          var pt = projection(pos);
          return Math.abs(pt[0] - x[0]) > INSIDETOLORANCEPXS || Math.abs(pt[1] - x[1]) > INSIDETOLORANCEPXS;
        }
        function handleZoomstart() {
          d3.select(this).style(zoomstartStyle);
          mouse0 = d3.mouse(this);
          rotate0 = projection.rotate();
          translate0 = projection.translate();
          lastRotate = rotate0;
          zoomPoint = position2(mouse0);
        }
        function handleZoom() {
          mouse1 = d3.mouse(this);
          if (outside(mouse0)) {
            zoom.scale(projection.scale());
            zoom.translate(projection.translate());
            return;
          }
          projection.scale(d3.event.scale);
          projection.translate([translate0[0], d3.event.translate[1]]);
          if (!zoomPoint) {
            mouse0 = mouse1;
            zoomPoint = position2(mouse0);
          } else if (position2(mouse1)) {
            point1 = position2(mouse1);
            rotate1 = [lastRotate[0] + (point1[0] - zoomPoint[0]), rotate0[1], rotate0[2]];
            projection.rotate(rotate1);
            lastRotate = rotate1;
          }
          didZoom = true;
          geo.render(true);
          var rotate = projection.rotate();
          var center = projection.invert(geo.midPt);
          geo.graphDiv.emit("plotly_relayouting", {
            "geo.projection.scale": projection.scale() / geo.fitScale,
            "geo.center.lon": center[0],
            "geo.center.lat": center[1],
            "geo.projection.rotation.lon": -rotate[0]
          });
        }
        function handleZoomend() {
          d3.select(this).style(zoomendStyle);
          if (didZoom) sync(geo, projection, syncCb);
        }
        function syncCb(set) {
          var rotate = projection.rotate();
          var center = projection.invert(geo.midPt);
          set("projection.rotation.lon", -rotate[0]);
          set("center.lon", center[0]);
          set("center.lat", center[1]);
        }
        zoom.on("zoomstart", handleZoomstart).on("zoom", handleZoom).on("zoomend", handleZoomend);
        return zoom;
      }
      function zoomClipped(geo, projection) {
        var view = { r: projection.rotate(), k: projection.scale() };
        var zoom = initZoom(geo, projection);
        var event = d3eventDispatch(zoom, "zoomstart", "zoom", "zoomend");
        var zooming = 0;
        var zoomOn = zoom.on;
        var zoomPoint;
        zoom.on("zoomstart", function() {
          d3.select(this).style(zoomstartStyle);
          var mouse0 = d3.mouse(this);
          var rotate0 = projection.rotate();
          var lastRotate = rotate0;
          var translate0 = projection.translate();
          var q = quaternionFromEuler(rotate0);
          zoomPoint = position(projection, mouse0);
          zoomOn.call(zoom, "zoom", function() {
            var mouse1 = d3.mouse(this);
            projection.scale(view.k = d3.event.scale);
            if (!zoomPoint) {
              mouse0 = mouse1;
              zoomPoint = position(projection, mouse0);
            } else if (position(projection, mouse1)) {
              projection.rotate(rotate0).translate(translate0);
              var point1 = position(projection, mouse1);
              var between = rotateBetween(zoomPoint, point1);
              var newEuler = eulerFromQuaternion(multiply(q, between));
              var rotateAngles = view.r = unRoll(newEuler, zoomPoint, lastRotate);
              if (!isFinite(rotateAngles[0]) || !isFinite(rotateAngles[1]) || !isFinite(rotateAngles[2])) {
                rotateAngles = lastRotate;
              }
              projection.rotate(rotateAngles);
              lastRotate = rotateAngles;
            }
            zoomed(event.of(this, arguments));
          });
          zoomstarted(event.of(this, arguments));
        }).on("zoomend", function() {
          d3.select(this).style(zoomendStyle);
          zoomOn.call(zoom, "zoom", null);
          zoomended(event.of(this, arguments));
          sync(geo, projection, syncCb);
        }).on("zoom.redraw", function() {
          geo.render(true);
          var _rotate = projection.rotate();
          geo.graphDiv.emit("plotly_relayouting", {
            "geo.projection.scale": projection.scale() / geo.fitScale,
            "geo.projection.rotation.lon": -_rotate[0],
            "geo.projection.rotation.lat": -_rotate[1]
          });
        });
        function zoomstarted(dispatch) {
          if (!zooming++) dispatch({ type: "zoomstart" });
        }
        function zoomed(dispatch) {
          dispatch({ type: "zoom" });
        }
        function zoomended(dispatch) {
          if (!--zooming) dispatch({ type: "zoomend" });
        }
        function syncCb(set) {
          var _rotate = projection.rotate();
          set("projection.rotation.lon", -_rotate[0]);
          set("projection.rotation.lat", -_rotate[1]);
        }
        return d3.rebind(zoom, event, "on");
      }
      function position(projection, point) {
        var spherical = projection.invert(point);
        return spherical && isFinite(spherical[0]) && isFinite(spherical[1]) && cartesian(spherical);
      }
      function quaternionFromEuler(euler) {
        var lambda = 0.5 * euler[0] * radians2;
        var phi = 0.5 * euler[1] * radians2;
        var gamma2 = 0.5 * euler[2] * radians2;
        var sinLambda = Math.sin(lambda);
        var cosLambda = Math.cos(lambda);
        var sinPhi = Math.sin(phi);
        var cosPhi = Math.cos(phi);
        var sinGamma = Math.sin(gamma2);
        var cosGamma = Math.cos(gamma2);
        return [
          cosLambda * cosPhi * cosGamma + sinLambda * sinPhi * sinGamma,
          sinLambda * cosPhi * cosGamma - cosLambda * sinPhi * sinGamma,
          cosLambda * sinPhi * cosGamma + sinLambda * cosPhi * sinGamma,
          cosLambda * cosPhi * sinGamma - sinLambda * sinPhi * cosGamma
        ];
      }
      function multiply(a, b) {
        var a0 = a[0];
        var a1 = a[1];
        var a2 = a[2];
        var a3 = a[3];
        var b0 = b[0];
        var b1 = b[1];
        var b2 = b[2];
        var b3 = b[3];
        return [
          a0 * b0 - a1 * b1 - a2 * b2 - a3 * b3,
          a0 * b1 + a1 * b0 + a2 * b3 - a3 * b2,
          a0 * b2 - a1 * b3 + a2 * b0 + a3 * b1,
          a0 * b3 + a1 * b2 - a2 * b1 + a3 * b0
        ];
      }
      function rotateBetween(a, b) {
        if (!a || !b) return;
        var axis = cross(a, b);
        var norm = Math.sqrt(dot(axis, axis));
        var halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, dot(a, b))));
        var k = Math.sin(halfgamma) / norm;
        return norm && [Math.cos(halfgamma), axis[2] * k, -axis[1] * k, axis[0] * k];
      }
      function unRoll(rotateAngles, pt, lastRotate) {
        var ptRotated = rotateCartesian(pt, 2, rotateAngles[0]);
        ptRotated = rotateCartesian(ptRotated, 1, rotateAngles[1]);
        ptRotated = rotateCartesian(ptRotated, 0, rotateAngles[2] - lastRotate[2]);
        var x = pt[0];
        var y = pt[1];
        var z = pt[2];
        var f = ptRotated[0];
        var g = ptRotated[1];
        var h = ptRotated[2];
        var theta = Math.atan2(y, x) * degrees3;
        var a = Math.sqrt(x * x + y * y);
        var b;
        var newYaw1;
        if (Math.abs(g) > a) {
          newYaw1 = (g > 0 ? 90 : -90) - theta;
          b = 0;
        } else {
          newYaw1 = Math.asin(g / a) * degrees3 - theta;
          b = Math.sqrt(a * a - g * g);
        }
        var newYaw2 = 180 - newYaw1 - 2 * theta;
        var newPitch1 = (Math.atan2(h, f) - Math.atan2(z, b)) * degrees3;
        var newPitch2 = (Math.atan2(h, f) - Math.atan2(z, -b)) * degrees3;
        var dist1 = angleDistance(lastRotate[0], lastRotate[1], newYaw1, newPitch1);
        var dist2 = angleDistance(lastRotate[0], lastRotate[1], newYaw2, newPitch2);
        if (dist1 <= dist2) return [newYaw1, newPitch1, lastRotate[2]];
        else return [newYaw2, newPitch2, lastRotate[2]];
      }
      function angleDistance(yaw0, pitch0, yaw1, pitch1) {
        var dYaw = angleMod(yaw1 - yaw0);
        var dPitch = angleMod(pitch1 - pitch0);
        return Math.sqrt(dYaw * dYaw + dPitch * dPitch);
      }
      function angleMod(angle) {
        return (angle % 360 + 540) % 360 - 180;
      }
      function rotateCartesian(vector, axis, angle) {
        var angleRads = angle * radians2;
        var vectorOut = vector.slice();
        var ax1 = axis === 0 ? 1 : 0;
        var ax2 = axis === 2 ? 1 : 2;
        var cosa = Math.cos(angleRads);
        var sina = Math.sin(angleRads);
        vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;
        vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;
        return vectorOut;
      }
      function eulerFromQuaternion(q) {
        return [
          Math.atan2(2 * (q[0] * q[1] + q[2] * q[3]), 1 - 2 * (q[1] * q[1] + q[2] * q[2])) * degrees3,
          Math.asin(Math.max(-1, Math.min(1, 2 * (q[0] * q[2] - q[3] * q[1])))) * degrees3,
          Math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] * q[2] + q[3] * q[3])) * degrees3
        ];
      }
      function cartesian(spherical) {
        var lambda = spherical[0] * radians2;
        var phi = spherical[1] * radians2;
        var cosPhi = Math.cos(phi);
        return [
          cosPhi * Math.cos(lambda),
          cosPhi * Math.sin(lambda),
          Math.sin(phi)
        ];
      }
      function dot(a, b) {
        var s = 0;
        for (var i = 0, n = a.length; i < n; ++i) s += a[i] * b[i];
        return s;
      }
      function cross(a, b) {
        return [
          a[1] * b[2] - a[2] * b[1],
          a[2] * b[0] - a[0] * b[2],
          a[0] * b[1] - a[1] * b[0]
        ];
      }
      function d3eventDispatch(target) {
        var i = 0;
        var n = arguments.length;
        var argumentz = [];
        while (++i < n) argumentz.push(arguments[i]);
        var dispatch = d3.dispatch.apply(null, argumentz);
        dispatch.of = function(thiz, argumentz2) {
          return function(e1) {
            var e0;
            try {
              e0 = e1.sourceEvent = d3.event;
              e1.target = target;
              d3.event = e1;
              dispatch[e1.type].apply(thiz, argumentz2);
            } finally {
              d3.event = e0;
            }
          };
        };
        return dispatch;
      }
    }
  });

  // src/plots/geo/geo.js
  var require_geo = __commonJS({
    "src/plots/geo/geo.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var geo = require_d3_geo();
      var geoPath = geo.geoPath;
      var geoDistance = geo.geoDistance;
      var geoProjection = require_d3_geo_projection();
      var Registry = require_registry();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Fx = require_fx();
      var Plots = require_plots();
      var Axes = require_axes();
      var getAutoRange = require_autorange().getAutoRange;
      var dragElement = require_dragelement();
      var prepSelect = require_selections().prepSelect;
      var clearOutline = require_selections().clearOutline;
      var selectOnClick = require_selections().selectOnClick;
      var createGeoZoom = require_zoom();
      var constants = require_constants22();
      var geoUtils = require_geo_location_utils();
      var topojsonUtils = require_topojson_utils();
      var topojsonFeature = require_topojson_client().feature;
      function Geo(opts) {
        this.id = opts.id;
        this.graphDiv = opts.graphDiv;
        this.container = opts.container;
        this.topojsonURL = opts.topojsonURL;
        this.isStatic = opts.staticPlot;
        this.topojsonName = null;
        this.topojson = null;
        this.projection = null;
        this.scope = null;
        this.viewInitial = null;
        this.fitScale = null;
        this.bounds = null;
        this.midPt = null;
        this.hasChoropleth = false;
        this.traceHash = {};
        this.layers = {};
        this.basePaths = {};
        this.dataPaths = {};
        this.dataPoints = {};
        this.clipDef = null;
        this.clipRect = null;
        this.bgRect = null;
        this.makeFramework();
      }
      var proto = Geo.prototype;
      module.exports = function createGeo(opts) {
        return new Geo(opts);
      };
      proto.plot = function(geoCalcData, fullLayout, promises, replot) {
        var _this = this;
        if (replot) return _this.update(geoCalcData, fullLayout, true);
        _this._geoCalcData = geoCalcData;
        _this._fullLayout = fullLayout;
        var geoLayout = fullLayout[this.id];
        var geoPromises = [];
        var needsTopojson = false;
        for (var k in constants.layerNameToAdjective) {
          if (k !== "frame" && geoLayout["show" + k]) {
            needsTopojson = true;
            break;
          }
        }
        var hasMarkerAngles = false;
        for (var i = 0; i < geoCalcData.length; i++) {
          var trace = geoCalcData[0][0].trace;
          trace._geo = _this;
          if (trace.locationmode) {
            needsTopojson = true;
          }
          var marker = trace.marker;
          if (marker) {
            var angle = marker.angle;
            var angleref = marker.angleref;
            if (angle || angleref === "north" || angleref === "previous") hasMarkerAngles = true;
          }
        }
        this._hasMarkerAngles = hasMarkerAngles;
        if (needsTopojson) {
          var topojsonNameNew = topojsonUtils.getTopojsonName(geoLayout);
          if (_this.topojson === null || topojsonNameNew !== _this.topojsonName) {
            _this.topojsonName = topojsonNameNew;
            if (PlotlyGeoAssets.topojson[_this.topojsonName] === void 0) {
              geoPromises.push(_this.fetchTopojson());
            }
          }
        }
        geoPromises = geoPromises.concat(geoUtils.fetchTraceGeoData(geoCalcData));
        promises.push(new Promise(function(resolve, reject) {
          Promise.all(geoPromises).then(function() {
            _this.topojson = PlotlyGeoAssets.topojson[_this.topojsonName];
            _this.update(geoCalcData, fullLayout);
            resolve();
          }).catch(reject);
        }));
      };
      proto.fetchTopojson = function() {
        var _this = this;
        var topojsonPath = topojsonUtils.getTopojsonPath(_this.topojsonURL, _this.topojsonName);
        return new Promise(function(resolve, reject) {
          d3.json(topojsonPath, function(err, topojson) {
            if (err) {
              if (err.status === 404) {
                return reject(new Error([
                  "plotly.js could not find topojson file at",
                  topojsonPath + ".",
                  "Make sure the *topojsonURL* plot config option",
                  "is set properly."
                ].join(" ")));
              } else {
                return reject(new Error([
                  "unexpected error while fetching topojson file at",
                  topojsonPath
                ].join(" ")));
              }
            }
            PlotlyGeoAssets.topojson[_this.topojsonName] = topojson;
            resolve();
          });
        });
      };
      proto.update = function(geoCalcData, fullLayout, replot) {
        var geoLayout = fullLayout[this.id];
        this.hasChoropleth = false;
        for (var i = 0; i < geoCalcData.length; i++) {
          var calcTrace = geoCalcData[i];
          var trace = calcTrace[0].trace;
          if (trace.type === "choropleth") {
            this.hasChoropleth = true;
          }
          if (trace.visible === true && trace._length > 0) {
            trace._module.calcGeoJSON(calcTrace, fullLayout);
          }
        }
        if (!replot) {
          var hasInvalidBounds = this.updateProjection(geoCalcData, fullLayout);
          if (hasInvalidBounds) return;
          if (!this.viewInitial || this.scope !== geoLayout.scope) {
            this.saveViewInitial(geoLayout);
          }
        }
        this.scope = geoLayout.scope;
        this.updateBaseLayers(fullLayout, geoLayout);
        this.updateDims(fullLayout, geoLayout);
        this.updateFx(fullLayout, geoLayout);
        Plots.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout);
        var scatterLayer = this.layers.frontplot.select(".scatterlayer");
        this.dataPoints.point = scatterLayer.selectAll(".point");
        this.dataPoints.text = scatterLayer.selectAll("text");
        this.dataPaths.line = scatterLayer.selectAll(".js-line");
        var choroplethLayer = this.layers.backplot.select(".choroplethlayer");
        this.dataPaths.choropleth = choroplethLayer.selectAll("path");
        this._render();
      };
      proto.updateProjection = function(geoCalcData, fullLayout) {
        var gd = this.graphDiv;
        var geoLayout = fullLayout[this.id];
        var gs = fullLayout._size;
        var domain = geoLayout.domain;
        var projLayout = geoLayout.projection;
        var lonaxis = geoLayout.lonaxis;
        var lataxis = geoLayout.lataxis;
        var axLon = lonaxis._ax;
        var axLat = lataxis._ax;
        var projection = this.projection = getProjection(geoLayout);
        var extent = [[
          gs.l + gs.w * domain.x[0],
          gs.t + gs.h * (1 - domain.y[1])
        ], [
          gs.l + gs.w * domain.x[1],
          gs.t + gs.h * (1 - domain.y[0])
        ]];
        var center = geoLayout.center || {};
        var rotation = projLayout.rotation || {};
        var lonaxisRange = lonaxis.range || [];
        var lataxisRange = lataxis.range || [];
        if (geoLayout.fitbounds) {
          axLon._length = extent[1][0] - extent[0][0];
          axLat._length = extent[1][1] - extent[0][1];
          axLon.range = getAutoRange(gd, axLon);
          axLat.range = getAutoRange(gd, axLat);
          var midLon = (axLon.range[0] + axLon.range[1]) / 2;
          var midLat = (axLat.range[0] + axLat.range[1]) / 2;
          if (geoLayout._isScoped) {
            center = { lon: midLon, lat: midLat };
          } else if (geoLayout._isClipped) {
            center = { lon: midLon, lat: midLat };
            rotation = { lon: midLon, lat: midLat, roll: rotation.roll };
            var projType = projLayout.type;
            var lonHalfSpan = constants.lonaxisSpan[projType] / 2 || 180;
            var latHalfSpan = constants.lataxisSpan[projType] / 2 || 90;
            lonaxisRange = [midLon - lonHalfSpan, midLon + lonHalfSpan];
            lataxisRange = [midLat - latHalfSpan, midLat + latHalfSpan];
          } else {
            center = { lon: midLon, lat: midLat };
            rotation = { lon: midLon, lat: rotation.lat, roll: rotation.roll };
          }
        }
        projection.center([center.lon - rotation.lon, center.lat - rotation.lat]).rotate([-rotation.lon, -rotation.lat, rotation.roll]).parallels(projLayout.parallels);
        var rangeBox = makeRangeBox(lonaxisRange, lataxisRange);
        projection.fitExtent(extent, rangeBox);
        var b = this.bounds = projection.getBounds(rangeBox);
        var s = this.fitScale = projection.scale();
        var t = projection.translate();
        if (geoLayout.fitbounds) {
          var b2 = projection.getBounds(makeRangeBox(axLon.range, axLat.range));
          var k2 = Math.min(
            (b[1][0] - b[0][0]) / (b2[1][0] - b2[0][0]),
            (b[1][1] - b[0][1]) / (b2[1][1] - b2[0][1])
          );
          if (isFinite(k2)) {
            projection.scale(k2 * s);
          } else {
            Lib.warn("Something went wrong during" + this.id + "fitbounds computations.");
          }
        } else {
          projection.scale(projLayout.scale * s);
        }
        var midPt = this.midPt = [
          (b[0][0] + b[1][0]) / 2,
          (b[0][1] + b[1][1]) / 2
        ];
        projection.translate([t[0] + (midPt[0] - t[0]), t[1] + (midPt[1] - t[1])]).clipExtent(b);
        if (geoLayout._isAlbersUsa) {
          var centerPx = projection([center.lon, center.lat]);
          var tt = projection.translate();
          projection.translate([
            tt[0] - (centerPx[0] - tt[0]),
            tt[1] - (centerPx[1] - tt[1])
          ]);
        }
      };
      proto.updateBaseLayers = function(fullLayout, geoLayout) {
        var _this = this;
        var topojson = _this.topojson;
        var layers = _this.layers;
        var basePaths = _this.basePaths;
        function isAxisLayer(d) {
          return d === "lonaxis" || d === "lataxis";
        }
        function isLineLayer(d) {
          return Boolean(constants.lineLayers[d]);
        }
        function isFillLayer(d) {
          return Boolean(constants.fillLayers[d]);
        }
        var allLayers = this.hasChoropleth ? constants.layersForChoropleth : constants.layers;
        var layerData = allLayers.filter(function(d) {
          return isLineLayer(d) || isFillLayer(d) ? geoLayout["show" + d] : isAxisLayer(d) ? geoLayout[d].showgrid : true;
        });
        var join = _this.framework.selectAll(".layer").data(layerData, String);
        join.exit().each(function(d) {
          delete layers[d];
          delete basePaths[d];
          d3.select(this).remove();
        });
        join.enter().append("g").attr("class", function(d) {
          return "layer " + d;
        }).each(function(d) {
          var layer = layers[d] = d3.select(this);
          if (d === "bg") {
            _this.bgRect = layer.append("rect").style("pointer-events", "all");
          } else if (isAxisLayer(d)) {
            basePaths[d] = layer.append("path").style("fill", "none");
          } else if (d === "backplot") {
            layer.append("g").classed("choroplethlayer", true);
          } else if (d === "frontplot") {
            layer.append("g").classed("scatterlayer", true);
          } else if (isLineLayer(d)) {
            basePaths[d] = layer.append("path").style("fill", "none").style("stroke-miterlimit", 2);
          } else if (isFillLayer(d)) {
            basePaths[d] = layer.append("path").style("stroke", "none");
          }
        });
        join.order();
        join.each(function(d) {
          var path = basePaths[d];
          var adj = constants.layerNameToAdjective[d];
          if (d === "frame") {
            path.datum(constants.sphereSVG);
          } else if (isLineLayer(d) || isFillLayer(d)) {
            path.datum(topojsonFeature(topojson, topojson.objects[d]));
          } else if (isAxisLayer(d)) {
            path.datum(makeGraticule(d, geoLayout, fullLayout)).call(Color2.stroke, geoLayout[d].gridcolor).call(Drawing.dashLine, geoLayout[d].griddash, geoLayout[d].gridwidth);
          }
          if (isLineLayer(d)) {
            path.call(Color2.stroke, geoLayout[adj + "color"]).call(Drawing.dashLine, "", geoLayout[adj + "width"]);
          } else if (isFillLayer(d)) {
            path.call(Color2.fill, geoLayout[adj + "color"]);
          }
        });
      };
      proto.updateDims = function(fullLayout, geoLayout) {
        var b = this.bounds;
        var hFrameWidth = (geoLayout.framewidth || 0) / 2;
        var l = b[0][0] - hFrameWidth;
        var t = b[0][1] - hFrameWidth;
        var w = b[1][0] - l + hFrameWidth;
        var h = b[1][1] - t + hFrameWidth;
        Drawing.setRect(this.clipRect, l, t, w, h);
        this.bgRect.call(Drawing.setRect, l, t, w, h).call(Color2.fill, geoLayout.bgcolor);
        this.xaxis._offset = l;
        this.xaxis._length = w;
        this.yaxis._offset = t;
        this.yaxis._length = h;
      };
      proto.updateFx = function(fullLayout, geoLayout) {
        var _this = this;
        var gd = _this.graphDiv;
        var bgRect = _this.bgRect;
        var dragMode = fullLayout.dragmode;
        var clickMode = fullLayout.clickmode;
        if (_this.isStatic) return;
        function zoomReset() {
          var viewInitial = _this.viewInitial;
          var updateObj = {};
          for (var k in viewInitial) {
            updateObj[_this.id + "." + k] = viewInitial[k];
          }
          Registry.call("_guiRelayout", gd, updateObj);
          gd.emit("plotly_doubleclick", null);
        }
        function invert(lonlat) {
          return _this.projection.invert([
            lonlat[0] + _this.xaxis._offset,
            lonlat[1] + _this.yaxis._offset
          ]);
        }
        var fillRangeItems = function(eventData, poly) {
          if (poly.isRect) {
            var ranges = eventData.range = {};
            ranges[_this.id] = [
              invert([poly.xmin, poly.ymin]),
              invert([poly.xmax, poly.ymax])
            ];
          } else {
            var dataPts = eventData.lassoPoints = {};
            dataPts[_this.id] = poly.map(invert);
          }
        };
        var dragOptions = {
          element: _this.bgRect.node(),
          gd,
          plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis,
            fillRangeItems
          },
          xaxes: [_this.xaxis],
          yaxes: [_this.yaxis],
          subplot: _this.id,
          clickFn: function(numClicks) {
            if (numClicks === 2) {
              clearOutline(gd);
            }
          }
        };
        if (dragMode === "pan") {
          bgRect.node().onmousedown = null;
          bgRect.call(createGeoZoom(_this, geoLayout));
          bgRect.on("dblclick.zoom", zoomReset);
          if (!gd._context._scrollZoom.geo) {
            bgRect.on("wheel.zoom", null);
          }
        } else if (dragMode === "select" || dragMode === "lasso") {
          bgRect.on(".zoom", null);
          dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, dragOptions, dragMode);
          };
          dragElement.init(dragOptions);
        }
        bgRect.on("mousemove", function() {
          var lonlat = _this.projection.invert(Lib.getPositionFromD3Event());
          if (!lonlat) {
            return dragElement.unhover(gd, d3.event);
          }
          _this.xaxis.p2c = function() {
            return lonlat[0];
          };
          _this.yaxis.p2c = function() {
            return lonlat[1];
          };
          Fx.hover(gd, d3.event, _this.id);
        });
        bgRect.on("mouseout", function() {
          if (gd._dragging) return;
          dragElement.unhover(gd, d3.event);
        });
        bgRect.on("click", function() {
          if (dragMode !== "select" && dragMode !== "lasso") {
            if (clickMode.indexOf("select") > -1) {
              selectOnClick(
                d3.event,
                gd,
                [_this.xaxis],
                [_this.yaxis],
                _this.id,
                dragOptions
              );
            }
            if (clickMode.indexOf("event") > -1) {
              Fx.click(gd, d3.event);
            }
          }
        });
      };
      proto.makeFramework = function() {
        var _this = this;
        var gd = _this.graphDiv;
        var fullLayout = gd._fullLayout;
        var clipId = "clip" + fullLayout._uid + _this.id;
        _this.clipDef = fullLayout._clips.append("clipPath").attr("id", clipId);
        _this.clipRect = _this.clipDef.append("rect");
        _this.framework = d3.select(_this.container).append("g").attr("class", "geo " + _this.id).call(Drawing.setClipUrl, clipId, gd);
        _this.project = function(v) {
          var px = _this.projection(v);
          return px ? [px[0] - _this.xaxis._offset, px[1] - _this.yaxis._offset] : [null, null];
        };
        _this.xaxis = {
          _id: "x",
          c2p: function(v) {
            return _this.project(v)[0];
          }
        };
        _this.yaxis = {
          _id: "y",
          c2p: function(v) {
            return _this.project(v)[1];
          }
        };
        _this.mockAxis = {
          type: "linear",
          showexponent: "all",
          exponentformat: "B"
        };
        Axes.setConvert(_this.mockAxis, fullLayout);
      };
      proto.saveViewInitial = function(geoLayout) {
        var center = geoLayout.center || {};
        var projLayout = geoLayout.projection;
        var rotation = projLayout.rotation || {};
        this.viewInitial = {
          fitbounds: geoLayout.fitbounds,
          "projection.scale": projLayout.scale
        };
        var extra;
        if (geoLayout._isScoped) {
          extra = {
            "center.lon": center.lon,
            "center.lat": center.lat
          };
        } else if (geoLayout._isClipped) {
          extra = {
            "projection.rotation.lon": rotation.lon,
            "projection.rotation.lat": rotation.lat
          };
        } else {
          extra = {
            "center.lon": center.lon,
            "center.lat": center.lat,
            "projection.rotation.lon": rotation.lon
          };
        }
        Lib.extendFlat(this.viewInitial, extra);
      };
      proto.render = function(mayRedrawOnUpdates) {
        if (this._hasMarkerAngles && mayRedrawOnUpdates) {
          this.plot(this._geoCalcData, this._fullLayout, [], true);
        } else {
          this._render();
        }
      };
      proto._render = function() {
        var projection = this.projection;
        var pathFn = projection.getPath();
        var k;
        function translatePoints(d) {
          var lonlatPx = projection(d.lonlat);
          return lonlatPx ? strTranslate(lonlatPx[0], lonlatPx[1]) : null;
        }
        function hideShowPoints(d) {
          return projection.isLonLatOverEdges(d.lonlat) ? "none" : null;
        }
        for (k in this.basePaths) {
          this.basePaths[k].attr("d", pathFn);
        }
        for (k in this.dataPaths) {
          this.dataPaths[k].attr("d", function(d) {
            return pathFn(d.geojson);
          });
        }
        for (k in this.dataPoints) {
          this.dataPoints[k].attr("display", hideShowPoints).attr("transform", translatePoints);
        }
      };
      function getProjection(geoLayout) {
        var projLayout = geoLayout.projection;
        var projType = projLayout.type;
        var projName = constants.projNames[projType];
        projName = "geo" + Lib.titleCase(projName);
        var projFn = geo[projName] || geoProjection[projName];
        var projection = projFn();
        var clipAngle = geoLayout._isSatellite ? Math.acos(1 / projLayout.distance) * 180 / Math.PI : geoLayout._isClipped ? constants.lonaxisSpan[projType] / 2 : null;
        var methods = ["center", "rotate", "parallels", "clipExtent"];
        var dummyFn = function(_) {
          return _ ? projection : [];
        };
        for (var i = 0; i < methods.length; i++) {
          var m = methods[i];
          if (typeof projection[m] !== "function") {
            projection[m] = dummyFn;
          }
        }
        projection.isLonLatOverEdges = function(lonlat) {
          if (projection(lonlat) === null) {
            return true;
          }
          if (clipAngle) {
            var r = projection.rotate();
            var angle = geoDistance(lonlat, [-r[0], -r[1]]);
            var maxAngle = clipAngle * Math.PI / 180;
            return angle > maxAngle;
          } else {
            return false;
          }
        };
        projection.getPath = function() {
          return geoPath().projection(projection);
        };
        projection.getBounds = function(object) {
          return projection.getPath().bounds(object);
        };
        projection.precision(constants.precision);
        if (geoLayout._isSatellite) {
          projection.tilt(projLayout.tilt).distance(projLayout.distance);
        }
        if (clipAngle) {
          projection.clipAngle(clipAngle - constants.clipPad);
        }
        return projection;
      }
      function makeGraticule(axisName, geoLayout, fullLayout) {
        var epsilon = 1e-6;
        var precision = 2.5;
        var axLayout = geoLayout[axisName];
        var scopeDefaults = constants.scopeDefaults[geoLayout.scope];
        var rng;
        var oppRng;
        var coordFn;
        if (axisName === "lonaxis") {
          rng = scopeDefaults.lonaxisRange;
          oppRng = scopeDefaults.lataxisRange;
          coordFn = function(v2, l2) {
            return [v2, l2];
          };
        } else if (axisName === "lataxis") {
          rng = scopeDefaults.lataxisRange;
          oppRng = scopeDefaults.lonaxisRange;
          coordFn = function(v2, l2) {
            return [l2, v2];
          };
        }
        var dummyAx = {
          type: "linear",
          range: [rng[0], rng[1] - epsilon],
          tick0: axLayout.tick0,
          dtick: axLayout.dtick
        };
        Axes.setConvert(dummyAx, fullLayout);
        var vals = Axes.calcTicks(dummyAx);
        if (!geoLayout.isScoped && axisName === "lonaxis") {
          vals.pop();
        }
        var len = vals.length;
        var coords = new Array(len);
        for (var i = 0; i < len; i++) {
          var v = vals[i].x;
          var line = coords[i] = [];
          for (var l = oppRng[0]; l < oppRng[1] + precision; l += precision) {
            line.push(coordFn(v, l));
          }
        }
        return {
          type: "MultiLineString",
          coordinates: coords
        };
      }
      function makeRangeBox(lon, lat) {
        var clipPad = constants.clipPad;
        var lon0 = lon[0] + clipPad;
        var lon1 = lon[1] - clipPad;
        var lat0 = lat[0] + clipPad;
        var lat1 = lat[1] - clipPad;
        if (lon0 > 0 && lon1 < 0) lon1 += 360;
        var dlon4 = (lon1 - lon0) / 4;
        return {
          type: "Polygon",
          coordinates: [[
            [lon0, lat0],
            [lon0, lat1],
            [lon0 + dlon4, lat1],
            [lon0 + 2 * dlon4, lat1],
            [lon0 + 3 * dlon4, lat1],
            [lon1, lat1],
            [lon1, lat0],
            [lon1 - dlon4, lat0],
            [lon1 - 2 * dlon4, lat0],
            [lon1 - 3 * dlon4, lat0],
            [lon0, lat0]
          ]]
        };
      }
    }
  });

  // src/plots/geo/layout_attributes.js
  var require_layout_attributes18 = __commonJS({
    "src/plots/geo/layout_attributes.js"(exports, module) {
      "use strict";
      var colorAttrs = require_attributes3();
      var domainAttrs = require_domain().attributes;
      var dash = require_attributes4().dash;
      var constants = require_constants22();
      var overrideAll = require_edit_types().overrideAll;
      var sortObjectKeys = require_sort_object_keys();
      var geoAxesAttrs = {
        range: {
          valType: "info_array",
          items: [
            { valType: "number" },
            { valType: "number" }
          ]
        },
        showgrid: {
          valType: "boolean",
          dflt: false
        },
        tick0: {
          valType: "number",
          dflt: 0
        },
        dtick: {
          valType: "number"
        },
        gridcolor: {
          valType: "color",
          dflt: colorAttrs.lightLine
        },
        gridwidth: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        griddash: dash
      };
      var attrs = module.exports = overrideAll({
        domain: domainAttrs({ name: "geo" }, {}),
        fitbounds: {
          valType: "enumerated",
          values: [false, "locations", "geojson"],
          dflt: false,
          editType: "plot"
        },
        resolution: {
          valType: "enumerated",
          values: [110, 50],
          dflt: 110,
          coerceNumber: true
        },
        scope: {
          valType: "enumerated",
          values: sortObjectKeys(constants.scopeDefaults),
          dflt: "world"
        },
        projection: {
          type: {
            valType: "enumerated",
            values: sortObjectKeys(constants.projNames)
          },
          rotation: {
            lon: {
              valType: "number"
            },
            lat: {
              valType: "number"
            },
            roll: {
              valType: "number"
            }
          },
          tilt: {
            valType: "number",
            dflt: 0
          },
          distance: {
            valType: "number",
            min: 1.001,
            dflt: 2
          },
          parallels: {
            valType: "info_array",
            items: [
              { valType: "number" },
              { valType: "number" }
            ]
          },
          scale: {
            valType: "number",
            min: 0,
            dflt: 1
          }
        },
        center: {
          lon: {
            valType: "number"
          },
          lat: {
            valType: "number"
          }
        },
        visible: {
          valType: "boolean",
          dflt: true
        },
        showcoastlines: {
          valType: "boolean"
        },
        coastlinecolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine
        },
        coastlinewidth: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        showland: {
          valType: "boolean",
          dflt: false
        },
        landcolor: {
          valType: "color",
          dflt: constants.landColor
        },
        showocean: {
          valType: "boolean",
          dflt: false
        },
        oceancolor: {
          valType: "color",
          dflt: constants.waterColor
        },
        showlakes: {
          valType: "boolean",
          dflt: false
        },
        lakecolor: {
          valType: "color",
          dflt: constants.waterColor
        },
        showrivers: {
          valType: "boolean",
          dflt: false
        },
        rivercolor: {
          valType: "color",
          dflt: constants.waterColor
        },
        riverwidth: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        showcountries: {
          valType: "boolean"
        },
        countrycolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine
        },
        countrywidth: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        showsubunits: {
          valType: "boolean"
        },
        subunitcolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine
        },
        subunitwidth: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        showframe: {
          valType: "boolean"
        },
        framecolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine
        },
        framewidth: {
          valType: "number",
          min: 0,
          dflt: 1
        },
        bgcolor: {
          valType: "color",
          dflt: colorAttrs.background
        },
        lonaxis: geoAxesAttrs,
        lataxis: geoAxesAttrs
      }, "plot", "from-root");
      attrs.uirevision = {
        valType: "any",
        editType: "none"
      };
    }
  });

  // src/plots/geo/layout_defaults.js
  var require_layout_defaults16 = __commonJS({
    "src/plots/geo/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleSubplotDefaults = require_subplot_defaults();
      var getSubplotData = require_get_data().getSubplotData;
      var constants = require_constants22();
      var layoutAttributes = require_layout_attributes18();
      var axesNames = constants.axesNames;
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        handleSubplotDefaults(layoutIn, layoutOut, fullData, {
          type: "geo",
          attributes: layoutAttributes,
          handleDefaults: handleGeoDefaults,
          fullData,
          partition: "y"
        });
      };
      function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce, opts) {
        var subplotData = getSubplotData(opts.fullData, "geo", opts.id);
        var traceIndices = subplotData.map(function(t) {
          return t.index;
        });
        var resolution = coerce("resolution");
        var scope = coerce("scope");
        var scopeParams = constants.scopeDefaults[scope];
        var projType = coerce("projection.type", scopeParams.projType);
        var isAlbersUsa = geoLayoutOut._isAlbersUsa = projType === "albers usa";
        if (isAlbersUsa) scope = geoLayoutOut.scope = "usa";
        var isScoped = geoLayoutOut._isScoped = scope !== "world";
        var isSatellite = geoLayoutOut._isSatellite = projType === "satellite";
        var isConic = geoLayoutOut._isConic = projType.indexOf("conic") !== -1 || projType === "albers";
        var isClipped = geoLayoutOut._isClipped = !!constants.lonaxisSpan[projType];
        if (geoLayoutIn.visible === false) {
          var newTemplate = Lib.extendDeep({}, geoLayoutOut._template);
          newTemplate.showcoastlines = false;
          newTemplate.showcountries = false;
          newTemplate.showframe = false;
          newTemplate.showlakes = false;
          newTemplate.showland = false;
          newTemplate.showocean = false;
          newTemplate.showrivers = false;
          newTemplate.showsubunits = false;
          if (newTemplate.lonaxis) newTemplate.lonaxis.showgrid = false;
          if (newTemplate.lataxis) newTemplate.lataxis.showgrid = false;
          geoLayoutOut._template = newTemplate;
        }
        var visible = coerce("visible");
        var show;
        for (var i = 0; i < axesNames.length; i++) {
          var axisName = axesNames[i];
          var dtickDflt = [30, 10][i];
          var rangeDflt;
          if (isScoped) {
            rangeDflt = scopeParams[axisName + "Range"];
          } else {
            var dfltSpans = constants[axisName + "Span"];
            var hSpan = (dfltSpans[projType] || dfltSpans["*"]) / 2;
            var rot = coerce(
              "projection.rotation." + axisName.slice(0, 3),
              scopeParams.projRotate[i]
            );
            rangeDflt = [rot - hSpan, rot + hSpan];
          }
          var range = coerce(axisName + ".range", rangeDflt);
          coerce(axisName + ".tick0");
          coerce(axisName + ".dtick", dtickDflt);
          show = coerce(axisName + ".showgrid", !visible ? false : void 0);
          if (show) {
            coerce(axisName + ".gridcolor");
            coerce(axisName + ".gridwidth");
            coerce(axisName + ".griddash");
          }
          geoLayoutOut[axisName]._ax = {
            type: "linear",
            _id: axisName.slice(0, 3),
            _traceIndices: traceIndices,
            setScale: Lib.identity,
            c2l: Lib.identity,
            r2l: Lib.identity,
            autorange: true,
            range: range.slice(),
            _m: 1,
            _input: {}
          };
        }
        var lonRange = geoLayoutOut.lonaxis.range;
        var latRange = geoLayoutOut.lataxis.range;
        var lon0 = lonRange[0];
        var lon1 = lonRange[1];
        if (lon0 > 0 && lon1 < 0) lon1 += 360;
        var centerLon = (lon0 + lon1) / 2;
        var projLon;
        if (!isAlbersUsa) {
          var dfltProjRotate = isScoped ? scopeParams.projRotate : [centerLon, 0, 0];
          projLon = coerce("projection.rotation.lon", dfltProjRotate[0]);
          coerce("projection.rotation.lat", dfltProjRotate[1]);
          coerce("projection.rotation.roll", dfltProjRotate[2]);
          show = coerce("showcoastlines", !isScoped && visible);
          if (show) {
            coerce("coastlinecolor");
            coerce("coastlinewidth");
          }
          show = coerce("showocean", !visible ? false : void 0);
          if (show) coerce("oceancolor");
        }
        var centerLonDflt;
        var centerLatDflt;
        if (isAlbersUsa) {
          centerLonDflt = -96.6;
          centerLatDflt = 38.7;
        } else {
          centerLonDflt = isScoped ? centerLon : projLon;
          centerLatDflt = (latRange[0] + latRange[1]) / 2;
        }
        coerce("center.lon", centerLonDflt);
        coerce("center.lat", centerLatDflt);
        if (isSatellite) {
          coerce("projection.tilt");
          coerce("projection.distance");
        }
        if (isConic) {
          var dfltProjParallels = scopeParams.projParallels || [0, 60];
          coerce("projection.parallels", dfltProjParallels);
        }
        coerce("projection.scale");
        show = coerce("showland", !visible ? false : void 0);
        if (show) coerce("landcolor");
        show = coerce("showlakes", !visible ? false : void 0);
        if (show) coerce("lakecolor");
        show = coerce("showrivers", !visible ? false : void 0);
        if (show) {
          coerce("rivercolor");
          coerce("riverwidth");
        }
        show = coerce("showcountries", isScoped && scope !== "usa" && visible);
        if (show) {
          coerce("countrycolor");
          coerce("countrywidth");
        }
        if (scope === "usa" || scope === "north america" && resolution === 50) {
          coerce("showsubunits", visible);
          coerce("subunitcolor");
          coerce("subunitwidth");
        }
        if (!isScoped) {
          show = coerce("showframe", visible);
          if (show) {
            coerce("framecolor");
            coerce("framewidth");
          }
        }
        coerce("bgcolor");
        var fitBounds = coerce("fitbounds");
        if (fitBounds) {
          delete geoLayoutOut.projection.scale;
          if (isScoped) {
            delete geoLayoutOut.center.lon;
            delete geoLayoutOut.center.lat;
          } else if (isClipped) {
            delete geoLayoutOut.center.lon;
            delete geoLayoutOut.center.lat;
            delete geoLayoutOut.projection.rotation.lon;
            delete geoLayoutOut.projection.rotation.lat;
            delete geoLayoutOut.lonaxis.range;
            delete geoLayoutOut.lataxis.range;
          } else {
            delete geoLayoutOut.center.lon;
            delete geoLayoutOut.center.lat;
            delete geoLayoutOut.projection.rotation.lon;
          }
        }
      }
    }
  });

  // src/plots/geo/index.js
  var require_geo2 = __commonJS({
    "src/plots/geo/index.js"(exports, module) {
      "use strict";
      var getSubplotCalcData = require_get_data().getSubplotCalcData;
      var counterRegex = require_lib().counterRegex;
      var createGeo = require_geo();
      var GEO = "geo";
      var counter = counterRegex(GEO);
      var attributes = {};
      attributes[GEO] = {
        valType: "subplotid",
        dflt: GEO,
        editType: "calc"
      };
      function plotGeo(gd) {
        var fullLayout = gd._fullLayout;
        var calcData = gd.calcdata;
        var geoIds = fullLayout._subplots[GEO];
        for (var i = 0; i < geoIds.length; i++) {
          var geoId = geoIds[i];
          var geoCalcData = getSubplotCalcData(calcData, GEO, geoId);
          var geoLayout = fullLayout[geoId];
          var geo = geoLayout._subplot;
          if (!geo) {
            geo = createGeo({
              id: geoId,
              graphDiv: gd,
              container: fullLayout._geolayer.node(),
              topojsonURL: gd._context.topojsonURL,
              staticPlot: gd._context.staticPlot
            });
            fullLayout[geoId]._subplot = geo;
          }
          geo.plot(geoCalcData, fullLayout, gd._promises);
        }
      }
      function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldGeoKeys = oldFullLayout._subplots[GEO] || [];
        for (var i = 0; i < oldGeoKeys.length; i++) {
          var oldGeoKey = oldGeoKeys[i];
          var oldGeo = oldFullLayout[oldGeoKey]._subplot;
          if (!newFullLayout[oldGeoKey] && !!oldGeo) {
            oldGeo.framework.remove();
            oldGeo.clipDef.remove();
          }
        }
      }
      function updateFx(gd) {
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[GEO];
        for (var i = 0; i < subplotIds.length; i++) {
          var subplotLayout = fullLayout[subplotIds[i]];
          var subplotObj = subplotLayout._subplot;
          subplotObj.updateFx(fullLayout, subplotLayout);
        }
      }
      module.exports = {
        attr: GEO,
        name: GEO,
        idRoot: GEO,
        idRegex: counter,
        attrRegex: counter,
        attributes,
        layoutAttributes: require_layout_attributes18(),
        supplyLayoutDefaults: require_layout_defaults16(),
        plot: plotGeo,
        updateFx,
        clean
      };
    }
  });

  // src/traces/scattergeo/index.js
  var require_scattergeo = __commonJS({
    "src/traces/scattergeo/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes48(),
        supplyDefaults: require_defaults44(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels3(),
        calc: require_calc27(),
        calcGeoJSON: require_plot17().calcGeoJSON,
        plot: require_plot17().plot,
        style: require_style17(),
        styleOnSelect: require_style2().styleOnSelect,
        hoverPoints: require_hover14(),
        eventData: require_event_data9(),
        selectPoints: require_select5(),
        moduleType: "trace",
        name: "scattergeo",
        basePlotModule: require_geo2(),
        categories: ["geo", "symbols", "showLegend", "scatter-like"],
        meta: {}
      };
    }
  });

  // lib/scattergeo.js
  var require_scattergeo2 = __commonJS({
    "lib/scattergeo.js"(exports, module) {
      "use strict";
      module.exports = require_scattergeo();
    }
  });

  // src/traces/choropleth/attributes.js
  var require_attributes49 = __commonJS({
    "src/traces/choropleth/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var scatterGeoAttrs = require_attributes48();
      var colorScaleAttrs = require_attributes8();
      var baseAttrs = require_attributes2();
      var defaultLine = require_attributes3().defaultLine;
      var extendFlat = require_extend().extendFlat;
      var scatterGeoMarkerLineAttrs = scatterGeoAttrs.marker.line;
      module.exports = extendFlat(
        {
          locations: {
            valType: "data_array",
            editType: "calc"
          },
          locationmode: scatterGeoAttrs.locationmode,
          z: {
            valType: "data_array",
            editType: "calc"
          },
          geojson: extendFlat({}, scatterGeoAttrs.geojson, {}),
          featureidkey: scatterGeoAttrs.featureidkey,
          text: extendFlat({}, scatterGeoAttrs.text, {}),
          hovertext: extendFlat({}, scatterGeoAttrs.hovertext, {}),
          marker: {
            line: {
              color: extendFlat({}, scatterGeoMarkerLineAttrs.color, { dflt: defaultLine }),
              width: extendFlat({}, scatterGeoMarkerLineAttrs.width, { dflt: 1 }),
              editType: "calc"
            },
            opacity: {
              valType: "number",
              arrayOk: true,
              min: 0,
              max: 1,
              dflt: 1,
              editType: "style"
            },
            editType: "calc"
          },
          selected: {
            marker: {
              opacity: scatterGeoAttrs.selected.marker.opacity,
              editType: "plot"
            },
            editType: "plot"
          },
          unselected: {
            marker: {
              opacity: scatterGeoAttrs.unselected.marker.opacity,
              editType: "plot"
            },
            editType: "plot"
          },
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
            editType: "calc",
            flags: ["location", "z", "text", "name"]
          }),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs(),
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
        },
        colorScaleAttrs("", {
          cLetter: "z",
          editTypeOverride: "calc"
        })
      );
    }
  });

  // src/traces/choropleth/defaults.js
  var require_defaults45 = __commonJS({
    "src/traces/choropleth/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes49();
      var locationmodeBreakingChangeWarning = [
        "The library used by the *country names* `locationmode` option is changing in the next major version.",
        "Some country names in existing plots may not work in the new version.",
        "To ensure consistent behavior, consider setting `locationmode` to *ISO-3*."
      ].join(" ");
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var locations = coerce("locations");
        var z = coerce("z");
        if (!(locations && locations.length && Lib.isArrayOrTypedArray(z) && z.length)) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = Math.min(locations.length, z.length);
        var geojson = coerce("geojson");
        var locationmodeDflt;
        if (typeof geojson === "string" && geojson !== "" || Lib.isPlainObject(geojson)) {
          locationmodeDflt = "geojson-id";
        }
        var locationMode = coerce("locationmode", locationmodeDflt);
        if (locationMode === "country names") {
          Lib.warn(locationmodeBreakingChangeWarning);
        }
        if (locationMode === "geojson-id") {
          coerce("featureidkey");
        }
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var mlw = coerce("marker.line.width");
        if (mlw) coerce("marker.line.color");
        coerce("marker.opacity");
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "z" });
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/choropleth/calc.js
  var require_calc28 = __commonJS({
    "src/traces/choropleth/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var BADNUM = require_numerical().BADNUM;
      var colorscaleCalc = require_calc();
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcSelection = require_calc_selection();
      function isNonBlankString(v) {
        return v && typeof v === "string";
      }
      module.exports = function calc(gd, trace) {
        var len = trace._length;
        var calcTrace = new Array(len);
        var isValidLoc;
        if (trace.geojson) {
          isValidLoc = function(v) {
            return isNonBlankString(v) || isNumeric(v);
          };
        } else {
          isValidLoc = isNonBlankString;
        }
        for (var i = 0; i < len; i++) {
          var calcPt = calcTrace[i] = {};
          var loc = trace.locations[i];
          var z = trace.z[i];
          if (isValidLoc(loc) && isNumeric(z)) {
            calcPt.loc = loc;
            calcPt.z = z;
          } else {
            calcPt.loc = null;
            calcPt.z = BADNUM;
          }
          calcPt.index = i;
        }
        arraysToCalcdata(calcTrace, trace);
        colorscaleCalc(gd, trace, {
          vals: trace.z,
          containerStr: "",
          cLetter: "z"
        });
        calcSelection(calcTrace, trace);
        return calcTrace;
      };
    }
  });

  // src/traces/choropleth/style.js
  var require_style18 = __commonJS({
    "src/traces/choropleth/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Colorscale = require_colorscale();
      function style(gd, calcTrace) {
        if (calcTrace) styleTrace(gd, calcTrace);
      }
      function styleTrace(gd, calcTrace) {
        var trace = calcTrace[0].trace;
        var s = calcTrace[0].node3;
        var locs = s.selectAll(".choroplethlocation");
        var marker = trace.marker || {};
        var markerLine = marker.line || {};
        var sclFunc = Colorscale.makeColorScaleFuncFromTrace(trace);
        locs.each(function(d) {
          d3.select(this).attr("fill", sclFunc(d.z)).call(Color2.stroke, d.mlc || markerLine.color).call(Drawing.dashLine, "", d.mlw || markerLine.width || 0).style("opacity", marker.opacity);
        });
        Drawing.selectedPointStyle(locs, trace);
      }
      function styleOnSelect(gd, calcTrace) {
        var s = calcTrace[0].node3;
        var trace = calcTrace[0].trace;
        if (trace.selectedpoints) {
          Drawing.selectedPointStyle(s.selectAll(".choroplethlocation"), trace);
        } else {
          styleTrace(gd, calcTrace);
        }
      }
      module.exports = {
        style,
        styleOnSelect
      };
    }
  });

  // src/traces/choropleth/plot.js
  var require_plot18 = __commonJS({
    "src/traces/choropleth/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var geoUtils = require_geo_location_utils();
      var getTopojsonFeatures = require_topojson_utils().getTopojsonFeatures;
      var findExtremes = require_autorange().findExtremes;
      var style = require_style18().style;
      function plot(gd, geo, calcData) {
        var choroplethLayer = geo.layers.backplot.select(".choroplethlayer");
        Lib.makeTraceGroups(choroplethLayer, calcData, "trace choropleth").each(function(calcTrace) {
          var sel = d3.select(this);
          var paths = sel.selectAll("path.choroplethlocation").data(Lib.identity);
          paths.enter().append("path").classed("choroplethlocation", true);
          paths.exit().remove();
          style(gd, calcTrace);
        });
      }
      function calcGeoJSON(calcTrace, fullLayout) {
        var trace = calcTrace[0].trace;
        var geoLayout = fullLayout[trace.geo];
        var geo = geoLayout._subplot;
        var locationmode = trace.locationmode;
        var len = trace._length;
        var features = locationmode === "geojson-id" ? geoUtils.extractTraceFeature(calcTrace) : getTopojsonFeatures(trace, geo.topojson);
        var lonArray = [];
        var latArray = [];
        for (var i = 0; i < len; i++) {
          var calcPt = calcTrace[i];
          var feature = locationmode === "geojson-id" ? calcPt.fOut : geoUtils.locationToFeature(locationmode, calcPt.loc, features);
          if (feature) {
            calcPt.geojson = feature;
            calcPt.ct = feature.properties.ct;
            calcPt._polygons = geoUtils.feature2polygons(feature);
            var bboxFeature = geoUtils.computeBbox(feature);
            lonArray.push(bboxFeature[0], bboxFeature[2]);
            latArray.push(bboxFeature[1], bboxFeature[3]);
          } else {
            calcPt.geojson = null;
          }
        }
        if (geoLayout.fitbounds === "geojson" && locationmode === "geojson-id") {
          var bboxGeojson = geoUtils.computeBbox(geoUtils.getTraceGeojson(trace));
          lonArray = [bboxGeojson[0], bboxGeojson[2]];
          latArray = [bboxGeojson[1], bboxGeojson[3]];
        }
        var opts = { padded: true };
        trace._extremes.lon = findExtremes(geoLayout.lonaxis._ax, lonArray, opts);
        trace._extremes.lat = findExtremes(geoLayout.lataxis._ax, latArray, opts);
      }
      module.exports = {
        calcGeoJSON,
        plot
      };
    }
  });

  // src/traces/choropleth/hover.js
  var require_hover15 = __commonJS({
    "src/traces/choropleth/hover.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var attributes = require_attributes49();
      var fillText = require_lib().fillText;
      module.exports = function hoverPoints(pointData, xval, yval) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var geo = pointData.subplot;
        var pt, i, j, isInside;
        var xy = [xval, yval];
        var altXy = [xval + 360, yval];
        for (i = 0; i < cd.length; i++) {
          pt = cd[i];
          isInside = false;
          if (pt._polygons) {
            for (j = 0; j < pt._polygons.length; j++) {
              if (pt._polygons[j].contains(xy)) {
                isInside = !isInside;
              }
              if (pt._polygons[j].contains(altXy)) {
                isInside = !isInside;
              }
            }
            if (isInside) break;
          }
        }
        if (!isInside || !pt) return;
        pointData.x0 = pointData.x1 = pointData.xa.c2p(pt.ct);
        pointData.y0 = pointData.y1 = pointData.ya.c2p(pt.ct);
        pointData.index = pt.index;
        pointData.location = pt.loc;
        pointData.z = pt.z;
        pointData.zLabel = Axes.tickText(geo.mockAxis, geo.mockAxis.c2l(pt.z), "hover").text;
        pointData.hovertemplate = pt.hovertemplate;
        makeHoverInfo(pointData, trace, pt);
        return [pointData];
      };
      function makeHoverInfo(pointData, trace, pt) {
        if (trace.hovertemplate) return;
        var hoverinfo = pt.hi || trace.hoverinfo;
        var loc = String(pt.loc);
        var parts = hoverinfo === "all" ? attributes.hoverinfo.flags : hoverinfo.split("+");
        var hasName = parts.indexOf("name") !== -1;
        var hasLocation = parts.indexOf("location") !== -1;
        var hasZ = parts.indexOf("z") !== -1;
        var hasText = parts.indexOf("text") !== -1;
        var hasIdAsNameLabel = !hasName && hasLocation;
        var text = [];
        if (hasIdAsNameLabel) {
          pointData.nameOverride = loc;
        } else {
          if (hasName) pointData.nameOverride = trace.name;
          if (hasLocation) text.push(loc);
        }
        if (hasZ) {
          text.push(pointData.zLabel);
        }
        if (hasText) {
          fillText(pt, trace, text);
        }
        pointData.extraText = text.join("<br>");
      }
    }
  });

  // src/traces/choropleth/event_data.js
  var require_event_data10 = __commonJS({
    "src/traces/choropleth/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt, trace, cd, pointNumber) {
        out.location = pt.location;
        out.z = pt.z;
        var cdi = cd[pointNumber];
        if (cdi.fIn && cdi.fIn.properties) {
          out.properties = cdi.fIn.properties;
        }
        out.ct = cdi.ct;
        return out;
      };
    }
  });

  // src/traces/choropleth/select.js
  var require_select6 = __commonJS({
    "src/traces/choropleth/select.js"(exports, module) {
      "use strict";
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var i, di, ct, x, y;
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            di = cd[i];
            ct = di.ct;
            if (!ct) continue;
            x = xa.c2p(ct);
            y = ya.c2p(ct);
            if (selectionTester.contains([x, y], null, i, searchInfo)) {
              selection.push({
                pointNumber: i,
                lon: ct[0],
                lat: ct[1]
              });
              di.selected = 1;
            } else {
              di.selected = 0;
            }
          }
        }
        return selection;
      };
    }
  });

  // src/traces/choropleth/index.js
  var require_choropleth = __commonJS({
    "src/traces/choropleth/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes49(),
        supplyDefaults: require_defaults45(),
        colorbar: require_colorbar2(),
        calc: require_calc28(),
        calcGeoJSON: require_plot18().calcGeoJSON,
        plot: require_plot18().plot,
        style: require_style18().style,
        styleOnSelect: require_style18().styleOnSelect,
        hoverPoints: require_hover15(),
        eventData: require_event_data10(),
        selectPoints: require_select6(),
        moduleType: "trace",
        name: "choropleth",
        basePlotModule: require_geo2(),
        categories: ["geo", "noOpacity", "showLegend"],
        meta: {}
      };
    }
  });

  // lib/choropleth.js
  var require_choropleth2 = __commonJS({
    "lib/choropleth.js"(exports, module) {
      "use strict";
      module.exports = require_choropleth();
    }
  });

  // src/traces/scattergl/hover.js
  var require_hover16 = __commonJS({
    "src/traces/scattergl/hover.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      var getTraceColor = require_get_trace_color();
      function hoverPoints(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var stash = cd[0].t;
        var trace = cd[0].trace;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var x = stash.x;
        var y = stash.y;
        var xpx = xa.c2p(xval);
        var ypx = ya.c2p(yval);
        var maxDistance = pointData.distance;
        var ids;
        if (stash.tree) {
          var xl = xa.p2c(xpx - maxDistance);
          var xr = xa.p2c(xpx + maxDistance);
          var yl = ya.p2c(ypx - maxDistance);
          var yr = ya.p2c(ypx + maxDistance);
          if (hovermode === "x") {
            ids = stash.tree.range(
              Math.min(xl, xr),
              Math.min(ya._rl[0], ya._rl[1]),
              Math.max(xl, xr),
              Math.max(ya._rl[0], ya._rl[1])
            );
          } else {
            ids = stash.tree.range(
              Math.min(xl, xr),
              Math.min(yl, yr),
              Math.max(xl, xr),
              Math.max(yl, yr)
            );
          }
        } else {
          ids = stash.ids;
        }
        var k, closestId, ptx, pty, i, dx, dy, dist, dxy;
        var minDist = maxDistance;
        if (hovermode === "x") {
          var xPeriod = !!trace.xperiodalignment;
          var yPeriod = !!trace.yperiodalignment;
          for (i = 0; i < ids.length; i++) {
            k = ids[i];
            ptx = x[k];
            dx = Math.abs(xa.c2p(ptx) - xpx);
            if (xPeriod) {
              var x0 = xa.c2p(trace._xStarts[k]);
              var x1 = xa.c2p(trace._xEnds[k]);
              dx = xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity;
            }
            if (dx < minDist) {
              minDist = dx;
              pty = y[k];
              dy = ya.c2p(pty) - ypx;
              if (yPeriod) {
                var y0 = ya.c2p(trace._yStarts[k]);
                var y1 = ya.c2p(trace._yEnds[k]);
                dy = ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity;
              }
              dxy = Math.sqrt(dx * dx + dy * dy);
              closestId = ids[i];
            }
          }
        } else {
          for (i = ids.length - 1; i > -1; i--) {
            k = ids[i];
            ptx = x[k];
            pty = y[k];
            dx = xa.c2p(ptx) - xpx;
            dy = ya.c2p(pty) - ypx;
            dist = Math.sqrt(dx * dx + dy * dy);
            if (dist < minDist) {
              minDist = dxy = dist;
              closestId = k;
            }
          }
        }
        pointData.index = closestId;
        pointData.distance = minDist;
        pointData.dxy = dxy;
        if (closestId === void 0) return [pointData];
        return [calcHover(pointData, x, y, trace)];
      }
      function calcHover(pointData, x, y, trace) {
        var xa = pointData.xa;
        var ya = pointData.ya;
        var minDist = pointData.distance;
        var dxy = pointData.dxy;
        var id = pointData.index;
        var di = {
          pointNumber: id,
          x: x[id],
          y: y[id]
        };
        di.tx = Lib.isArrayOrTypedArray(trace.text) ? trace.text[id] : trace.text;
        di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext;
        di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata;
        di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition;
        var font = trace.textfont;
        if (font) {
          di.ts = Lib.isArrayOrTypedArray(font.size) ? font.size[id] : font.size;
          di.tc = Lib.isArrayOrTypedArray(font.color) ? font.color[id] : font.color;
          di.tf = Array.isArray(font.family) ? font.family[id] : font.family;
          di.tw = Array.isArray(font.weight) ? font.weight[id] : font.weight;
          di.ty = Array.isArray(font.style) ? font.style[id] : font.style;
          di.tv = Array.isArray(font.variant) ? font.variant[id] : font.variant;
        }
        var marker = trace.marker;
        if (marker) {
          di.ms = Lib.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size;
          di.mo = Lib.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity;
          di.mx = Lib.isArrayOrTypedArray(marker.symbol) ? marker.symbol[id] : marker.symbol;
          di.ma = Lib.isArrayOrTypedArray(marker.angle) ? marker.angle[id] : marker.angle;
          di.mc = Lib.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color;
        }
        var line = marker && marker.line;
        if (line) {
          di.mlc = Array.isArray(line.color) ? line.color[id] : line.color;
          di.mlw = Lib.isArrayOrTypedArray(line.width) ? line.width[id] : line.width;
        }
        var grad = marker && marker.gradient;
        if (grad && grad.type !== "none") {
          di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type;
          di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color;
        }
        var xp = xa.c2p(di.x, true);
        var yp = ya.c2p(di.y, true);
        var rad = di.mrc || 1;
        var hoverlabel = trace.hoverlabel;
        if (hoverlabel) {
          di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor;
          di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor;
          di.hts = Lib.isArrayOrTypedArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size;
          di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color;
          di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family;
          di.hnl = Lib.isArrayOrTypedArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength;
        }
        var hoverinfo = trace.hoverinfo;
        if (hoverinfo) {
          di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo;
        }
        var hovertemplate = trace.hovertemplate;
        if (hovertemplate) {
          di.ht = Array.isArray(hovertemplate) ? hovertemplate[id] : hovertemplate;
        }
        var fakeCd = {};
        fakeCd[pointData.index] = di;
        var origX = trace._origX;
        var origY = trace._origY;
        var pointData2 = Lib.extendFlat({}, pointData, {
          color: getTraceColor(trace, di),
          x0: xp - rad,
          x1: xp + rad,
          xLabelVal: origX ? origX[id] : di.x,
          y0: yp - rad,
          y1: yp + rad,
          yLabelVal: origY ? origY[id] : di.y,
          cd: fakeCd,
          distance: minDist,
          spikeDistance: dxy,
          hovertemplate: di.ht
        });
        if (di.htx) pointData2.text = di.htx;
        else if (di.tx) pointData2.text = di.tx;
        else if (trace.text) pointData2.text = trace.text;
        Lib.fillText(di, trace, pointData2);
        Registry.getComponentMethod("errorbars", "hoverInfo")(di, trace, pointData2);
        return pointData2;
      }
      module.exports = {
        hoverPoints,
        calcHover
      };
    }
  });

  // src/traces/scattergl/constants.js
  var require_constants23 = __commonJS({
    "src/traces/scattergl/constants.js"(exports, module) {
      "use strict";
      var SYMBOL_SIZE = 20;
      module.exports = {
        TOO_MANY_POINTS: 1e5,
        SYMBOL_SDF_SIZE: 200,
        SYMBOL_SIZE,
        SYMBOL_STROKE: SYMBOL_SIZE / 20,
        DOT_RE: /-dot/,
        OPEN_RE: /-open/,
        DASHES: {
          solid: [1],
          dot: [1, 1],
          dash: [4, 1],
          longdash: [8, 1],
          dashdot: [4, 1, 1, 1],
          longdashdot: [8, 1, 1, 1]
        }
      };
    }
  });

  // src/traces/scattergl/attributes.js
  var require_attributes50 = __commonJS({
    "src/traces/scattergl/attributes.js"(exports, module) {
      "use strict";
      var baseAttrs = require_attributes2();
      var fontAttrs = require_font_attributes();
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterAttrs = require_attributes12();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var colorScaleAttrs = require_attributes8();
      var sortObjectKeys = require_sort_object_keys();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var DASHES = require_constants23().DASHES;
      var scatterLineAttrs = scatterAttrs.line;
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      var attrs = module.exports = overrideAll(
        {
          x: scatterAttrs.x,
          x0: scatterAttrs.x0,
          dx: scatterAttrs.dx,
          y: scatterAttrs.y,
          y0: scatterAttrs.y0,
          dy: scatterAttrs.dy,
          xperiod: scatterAttrs.xperiod,
          yperiod: scatterAttrs.yperiod,
          xperiod0: scatterAttrs.xperiod0,
          yperiod0: scatterAttrs.yperiod0,
          xperiodalignment: scatterAttrs.xperiodalignment,
          yperiodalignment: scatterAttrs.yperiodalignment,
          xhoverformat: axisHoverFormat("x"),
          yhoverformat: axisHoverFormat("y"),
          text: scatterAttrs.text,
          hovertext: scatterAttrs.hovertext,
          textposition: scatterAttrs.textposition,
          textfont: fontAttrs({
            noFontShadow: true,
            noFontLineposition: true,
            noFontTextcase: true,
            editType: "calc",
            colorEditType: "style",
            arrayOk: true,
            noNumericWeightValues: true,
            variantValues: ["normal", "small-caps"]
          }),
          mode: {
            valType: "flaglist",
            flags: ["lines", "markers", "text"],
            extras: ["none"]
          },
          line: {
            color: scatterLineAttrs.color,
            width: scatterLineAttrs.width,
            shape: {
              valType: "enumerated",
              values: ["linear", "hv", "vh", "hvh", "vhv"],
              dflt: "linear",
              editType: "plot"
            },
            dash: {
              valType: "enumerated",
              values: sortObjectKeys(DASHES),
              dflt: "solid"
            }
          },
          marker: extendFlat({}, colorScaleAttrs("marker"), {
            symbol: scatterMarkerAttrs.symbol,
            angle: scatterMarkerAttrs.angle,
            size: scatterMarkerAttrs.size,
            sizeref: scatterMarkerAttrs.sizeref,
            sizemin: scatterMarkerAttrs.sizemin,
            sizemode: scatterMarkerAttrs.sizemode,
            opacity: scatterMarkerAttrs.opacity,
            colorbar: scatterMarkerAttrs.colorbar,
            line: extendFlat({}, colorScaleAttrs("marker.line"), {
              width: scatterMarkerLineAttrs.width
            })
          }),
          connectgaps: scatterAttrs.connectgaps,
          fill: extendFlat({}, scatterAttrs.fill, { dflt: "none" }),
          fillcolor: makeFillcolorAttr(),
          // no hoveron
          selected: {
            marker: scatterAttrs.selected.marker,
            textfont: scatterAttrs.selected.textfont
          },
          unselected: {
            marker: scatterAttrs.unselected.marker,
            textfont: scatterAttrs.unselected.textfont
          },
          opacity: baseAttrs.opacity
        },
        "calc",
        "nested"
      );
      attrs.x.editType = attrs.y.editType = attrs.x0.editType = attrs.y0.editType = "calc+clearAxisTypes";
      attrs.hovertemplate = scatterAttrs.hovertemplate;
      attrs.hovertemplatefallback = scatterAttrs.hovertemplatefallback;
      attrs.texttemplate = scatterAttrs.texttemplate;
      attrs.texttemplatefallback = scatterAttrs.texttemplatefallback;
    }
  });

  // src/traces/scattergl/helpers.js
  var require_helpers16 = __commonJS({
    "src/traces/scattergl/helpers.js"(exports) {
      "use strict";
      var constants = require_constants23();
      exports.isOpenSymbol = function(symbol) {
        return typeof symbol === "string" ? constants.OPEN_RE.test(symbol) : symbol % 200 > 100;
      };
      exports.isDotSymbol = function(symbol) {
        return typeof symbol === "string" ? constants.DOT_RE.test(symbol) : symbol > 200;
      };
    }
  });

  // src/traces/scattergl/defaults.js
  var require_defaults46 = __commonJS({
    "src/traces/scattergl/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Registry = require_registry();
      var helpers = require_helpers16();
      var attributes = require_attributes50();
      var constants = require_constants8();
      var subTypes = require_subtypes();
      var handleXYDefaults = require_xy_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var handleTextDefaults = require_text_defaults();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var isOpen = traceIn.marker ? helpers.isOpenSymbol(traceIn.marker.symbol) : false;
        var isBubble = subTypes.isBubble(traceIn);
        var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce);
        coerce("xhoverformat");
        coerce("yhoverformat");
        var defaultMode = len < constants.PTS_LINESONLY ? "lines+markers" : "lines";
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("mode", defaultMode);
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
            noAngleRef: true,
            noLineDash: true,
            noStandOff: true
          });
          coerce("marker.line.width", isOpen || isBubble ? 1 : 0);
        }
        if (subTypes.hasLines(traceOut)) {
          coerce("connectgaps");
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
          coerce("line.shape");
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce, {
            noFontShadow: true,
            noFontLineposition: true,
            noFontTextcase: true
          });
        }
        var lineColor = (traceOut.line || {}).color;
        var markerColor = (traceOut.marker || {}).color;
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        }
        var errorBarsSupplyDefaults = Registry.getComponentMethod("errorbars", "supplyDefaults");
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "y" });
        errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "x", inherit: "y" });
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/scattergl/format_labels.js
  var require_format_labels4 = __commonJS({
    "src/traces/scattergl/format_labels.js"(exports, module) {
      "use strict";
      var scatterFormatLabels = require_format_labels();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var i = cdi.i;
        if (!("x" in cdi)) cdi.x = trace._x[i];
        if (!("y" in cdi)) cdi.y = trace._y[i];
        return scatterFormatLabels(cdi, trace, fullLayout);
      };
    }
  });

  // node_modules/binary-search-bounds/search-bounds.js
  var require_search_bounds = __commonJS({
    "node_modules/binary-search-bounds/search-bounds.js"(exports, module) {
      "use strict";
      function ge(a, y, c, l, h) {
        var i = h + 1;
        while (l <= h) {
          var m = l + h >>> 1, x = a[m];
          var p = c !== void 0 ? c(x, y) : x - y;
          if (p >= 0) {
            i = m;
            h = m - 1;
          } else {
            l = m + 1;
          }
        }
        return i;
      }
      function gt(a, y, c, l, h) {
        var i = h + 1;
        while (l <= h) {
          var m = l + h >>> 1, x = a[m];
          var p = c !== void 0 ? c(x, y) : x - y;
          if (p > 0) {
            i = m;
            h = m - 1;
          } else {
            l = m + 1;
          }
        }
        return i;
      }
      function lt(a, y, c, l, h) {
        var i = l - 1;
        while (l <= h) {
          var m = l + h >>> 1, x = a[m];
          var p = c !== void 0 ? c(x, y) : x - y;
          if (p < 0) {
            i = m;
            l = m + 1;
          } else {
            h = m - 1;
          }
        }
        return i;
      }
      function le(a, y, c, l, h) {
        var i = l - 1;
        while (l <= h) {
          var m = l + h >>> 1, x = a[m];
          var p = c !== void 0 ? c(x, y) : x - y;
          if (p <= 0) {
            i = m;
            l = m + 1;
          } else {
            h = m - 1;
          }
        }
        return i;
      }
      function eq(a, y, c, l, h) {
        while (l <= h) {
          var m = l + h >>> 1, x = a[m];
          var p = c !== void 0 ? c(x, y) : x - y;
          if (p === 0) {
            return m;
          }
          if (p <= 0) {
            l = m + 1;
          } else {
            h = m - 1;
          }
        }
        return -1;
      }
      function norm(a, y, c, l, h, f) {
        if (typeof c === "function") {
          return f(a, y, c, l === void 0 ? 0 : l | 0, h === void 0 ? a.length - 1 : h | 0);
        }
        return f(a, y, void 0, c === void 0 ? 0 : c | 0, l === void 0 ? a.length - 1 : l | 0);
      }
      module.exports = {
        ge: function(a, y, c, l, h) {
          return norm(a, y, c, l, h, ge);
        },
        gt: function(a, y, c, l, h) {
          return norm(a, y, c, l, h, gt);
        },
        lt: function(a, y, c, l, h) {
          return norm(a, y, c, l, h, lt);
        },
        le: function(a, y, c, l, h) {
          return norm(a, y, c, l, h, le);
        },
        eq: function(a, y, c, l, h) {
          return norm(a, y, c, l, h, eq);
        }
      };
    }
  });

  // node_modules/pick-by-alias/index.js
  var require_pick_by_alias = __commonJS({
    "node_modules/pick-by-alias/index.js"(exports, module) {
      "use strict";
      module.exports = function pick(src, props, keepRest) {
        var result = {}, prop, i;
        if (typeof props === "string") props = toList(props);
        if (Array.isArray(props)) {
          var res = {};
          for (i = 0; i < props.length; i++) {
            res[props[i]] = true;
          }
          props = res;
        }
        for (prop in props) {
          props[prop] = toList(props[prop]);
        }
        var occupied = {};
        for (prop in props) {
          var aliases = props[prop];
          if (Array.isArray(aliases)) {
            for (i = 0; i < aliases.length; i++) {
              var alias = aliases[i];
              if (keepRest) {
                occupied[alias] = true;
              }
              if (alias in src) {
                result[prop] = src[alias];
                if (keepRest) {
                  for (var j = i; j < aliases.length; j++) {
                    occupied[aliases[j]] = true;
                  }
                }
                break;
              }
            }
          } else if (prop in src) {
            if (props[prop]) {
              result[prop] = src[prop];
            }
            if (keepRest) {
              occupied[prop] = true;
            }
          }
        }
        if (keepRest) {
          for (prop in src) {
            if (occupied[prop]) continue;
            result[prop] = src[prop];
          }
        }
        return result;
      };
      var CACHE = {};
      function toList(arg) {
        if (CACHE[arg]) return CACHE[arg];
        if (typeof arg === "string") {
          arg = CACHE[arg] = arg.split(/\s*,\s*|\s+/);
        }
        return arg;
      }
    }
  });

  // node_modules/parse-rect/index.js
  var require_parse_rect = __commonJS({
    "node_modules/parse-rect/index.js"(exports, module) {
      "use strict";
      var pick = require_pick_by_alias();
      module.exports = parseRect;
      function parseRect(arg) {
        var rect;
        if (arguments.length > 1) {
          arg = arguments;
        }
        if (typeof arg === "string") {
          arg = arg.split(/\s/).map(parseFloat);
        } else if (typeof arg === "number") {
          arg = [arg];
        }
        if (arg.length && typeof arg[0] === "number") {
          if (arg.length === 1) {
            rect = {
              width: arg[0],
              height: arg[0],
              x: 0,
              y: 0
            };
          } else if (arg.length === 2) {
            rect = {
              width: arg[0],
              height: arg[1],
              x: 0,
              y: 0
            };
          } else {
            rect = {
              x: arg[0],
              y: arg[1],
              width: arg[2] - arg[0] || 0,
              height: arg[3] - arg[1] || 0
            };
          }
        } else if (arg) {
          arg = pick(arg, {
            left: "x l left Left",
            top: "y t top Top",
            width: "w width W Width",
            height: "h height W Width",
            bottom: "b bottom Bottom",
            right: "r right Right"
          });
          rect = {
            x: arg.left || 0,
            y: arg.top || 0
          };
          if (arg.width == null) {
            if (arg.right) rect.width = arg.right - rect.x;
            else rect.width = 0;
          } else {
            rect.width = arg.width;
          }
          if (arg.height == null) {
            if (arg.bottom) rect.height = arg.bottom - rect.y;
            else rect.height = 0;
          } else {
            rect.height = arg.height;
          }
        }
        return rect;
      }
    }
  });

  // node_modules/array-bounds/index.js
  var require_array_bounds = __commonJS({
    "node_modules/array-bounds/index.js"(exports, module) {
      "use strict";
      module.exports = normalize;
      function normalize(arr, dim) {
        if (!arr || arr.length == null) throw Error("Argument should be an array");
        if (dim == null) dim = 1;
        else dim = Math.floor(dim);
        var bounds = Array(dim * 2);
        for (var offset = 0; offset < dim; offset++) {
          var max = -Infinity, min = Infinity, i = offset, l = arr.length;
          for (; i < l; i += dim) {
            if (arr[i] > max) max = arr[i];
            if (arr[i] < min) min = arr[i];
          }
          bounds[offset] = min;
          bounds[dim + offset] = max;
        }
        return bounds;
      }
    }
  });

  // node_modules/defined/index.js
  var require_defined = __commonJS({
    "node_modules/defined/index.js"(exports, module) {
      module.exports = function() {
        for (var i = 0; i < arguments.length; i++) {
          if (arguments[i] !== void 0) return arguments[i];
        }
      };
    }
  });

  // node_modules/flatten-vertex-data/index.js
  var require_flatten_vertex_data = __commonJS({
    "node_modules/flatten-vertex-data/index.js"(exports, module) {
      var dtype = require_dtype();
      module.exports = flattenVertexData;
      function flattenVertexData(data, output, offset) {
        if (!data) throw new TypeError("must specify data as first parameter");
        offset = +(offset || 0) | 0;
        if (Array.isArray(data) && (data[0] && typeof data[0][0] === "number")) {
          var dim = data[0].length;
          var length = data.length * dim;
          var i, j, k, l;
          if (!output || typeof output === "string") {
            output = new (dtype(output || "float32"))(length + offset);
          }
          var dstLength = output.length - offset;
          if (length !== dstLength) {
            throw new Error("source length " + length + " (" + dim + "x" + data.length + ") does not match destination length " + dstLength);
          }
          for (i = 0, k = offset; i < data.length; i++) {
            for (j = 0; j < dim; j++) {
              output[k++] = data[i][j] === null ? NaN : data[i][j];
            }
          }
        } else {
          if (!output || typeof output === "string") {
            var Ctor = dtype(output || "float32");
            if (Array.isArray(data) || output === "array") {
              output = new Ctor(data.length + offset);
              for (i = 0, k = offset, l = output.length; k < l; k++, i++) {
                output[k] = data[i] === null ? NaN : data[i];
              }
            } else {
              if (offset === 0) {
                output = new Ctor(data);
              } else {
                output = new Ctor(data.length + offset);
                output.set(data, offset);
              }
            }
          } else {
            output.set(data, offset);
          }
        }
        return output;
      }
    }
  });

  // node_modules/is-obj/index.js
  var require_is_obj = __commonJS({
    "node_modules/is-obj/index.js"(exports, module) {
      "use strict";
      module.exports = function(x) {
        var type = typeof x;
        return x !== null && (type === "object" || type === "function");
      };
    }
  });

  // node_modules/math-log2/index.js
  var require_math_log2 = __commonJS({
    "node_modules/math-log2/index.js"(exports, module) {
      "use strict";
      module.exports = Math.log2 || function(x) {
        return Math.log(x) * Math.LOG2E;
      };
    }
  });

  // node_modules/@plotly/point-cluster/quad.js
  var require_quad = __commonJS({
    "node_modules/@plotly/point-cluster/quad.js"(exports, module) {
      "use strict";
      var search = require_search_bounds();
      var clamp = require_clamp();
      var rect = require_parse_rect();
      var getBounds = require_array_bounds();
      var pick = require_pick_by_alias();
      var defined = require_defined();
      var flatten = require_flatten_vertex_data();
      var isObj = require_is_obj();
      var dtype = require_dtype();
      var log2 = require_math_log2();
      var MAX_GROUP_ID = 1073741824;
      module.exports = function cluster(srcPoints, options) {
        if (!options) options = {};
        srcPoints = flatten(srcPoints, "float64");
        options = pick(options, {
          bounds: "range bounds dataBox databox",
          maxDepth: "depth maxDepth maxdepth level maxLevel maxlevel levels",
          dtype: "type dtype format out dst output destination"
          // sort: 'sortBy sortby sort',
          // pick: 'pick levelPoint',
          // nodeSize: 'node nodeSize minNodeSize minSize size'
        });
        let maxDepth = defined(options.maxDepth, 255);
        let bounds = defined(options.bounds, getBounds(srcPoints, 2));
        if (bounds[0] === bounds[2]) bounds[2]++;
        if (bounds[1] === bounds[3]) bounds[3]++;
        let points = normalize(srcPoints, bounds);
        let n = srcPoints.length >>> 1;
        let ids;
        if (!options.dtype) options.dtype = "array";
        if (typeof options.dtype === "string") {
          ids = new (dtype(options.dtype))(n);
        } else if (options.dtype) {
          ids = options.dtype;
          if (Array.isArray(ids)) ids.length = n;
        }
        for (let i = 0; i < n; ++i) {
          ids[i] = i;
        }
        let levels = [];
        let sublevels = [];
        let groups = [];
        let offsets = [];
        sort(0, 0, 1, ids, 0, 1);
        let offset = 0;
        for (let level = 0; level < levels.length; level++) {
          let levelItems = levels[level];
          if (ids.set) ids.set(levelItems, offset);
          else {
            for (let i = 0, l = levelItems.length; i < l; i++) {
              ids[i + offset] = levelItems[i];
            }
          }
          let nextOffset = offset + levels[level].length;
          offsets[level] = [offset, nextOffset];
          offset = nextOffset;
        }
        ids.range = range;
        return ids;
        function sort(x, y, diam, ids2, level, group2) {
          if (!ids2.length) return null;
          let levelItems = levels[level] || (levels[level] = []);
          let levelGroups = groups[level] || (groups[level] = []);
          let sublevel = sublevels[level] || (sublevels[level] = []);
          let offset2 = levelItems.length;
          level++;
          if (level > maxDepth || group2 > MAX_GROUP_ID) {
            for (let i = 0; i < ids2.length; i++) {
              levelItems.push(ids2[i]);
              levelGroups.push(group2);
              sublevel.push(null, null, null, null);
            }
            return offset2;
          }
          levelItems.push(ids2[0]);
          levelGroups.push(group2);
          if (ids2.length <= 1) {
            sublevel.push(null, null, null, null);
            return offset2;
          }
          let d2 = diam * 0.5;
          let cx = x + d2, cy = y + d2;
          let lolo = [], lohi = [], hilo = [], hihi = [];
          for (let i = 1, l = ids2.length; i < l; i++) {
            let idx = ids2[i], x2 = points[idx * 2], y2 = points[idx * 2 + 1];
            x2 < cx ? y2 < cy ? lolo.push(idx) : lohi.push(idx) : y2 < cy ? hilo.push(idx) : hihi.push(idx);
          }
          group2 <<= 2;
          sublevel.push(
            sort(x, y, d2, lolo, level, group2),
            sort(x, cy, d2, lohi, level, group2 + 1),
            sort(cx, y, d2, hilo, level, group2 + 2),
            sort(cx, cy, d2, hihi, level, group2 + 3)
          );
          return offset2;
        }
        function range(...args) {
          let options2;
          if (isObj(args[args.length - 1])) {
            let arg = args.pop();
            if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) {
              args = [arg];
              options2 = {};
            }
            options2 = pick(arg, {
              level: "level maxLevel",
              d: "d diam diameter r radius px pxSize pixel pixelSize maxD size minSize",
              lod: "lod details ranges offsets"
            });
          } else {
            options2 = {};
          }
          if (!args.length) args = bounds;
          let box = rect(...args);
          let [minX, minY, maxX, maxY] = [
            Math.min(box.x, box.x + box.width),
            Math.min(box.y, box.y + box.height),
            Math.max(box.x, box.x + box.width),
            Math.max(box.y, box.y + box.height)
          ];
          let [nminX, nminY, nmaxX, nmaxY] = normalize([minX, minY, maxX, maxY], bounds);
          let maxLevel = defined(options2.level, levels.length);
          if (options2.d != null) {
            let d;
            if (typeof options2.d === "number") d = [options2.d, options2.d];
            else if (options2.d.length) d = options2.d;
            maxLevel = Math.min(
              Math.max(
                Math.ceil(-log2(Math.abs(d[0]) / (bounds[2] - bounds[0]))),
                Math.ceil(-log2(Math.abs(d[1]) / (bounds[3] - bounds[1])))
              ),
              maxLevel
            );
          }
          maxLevel = Math.min(maxLevel, levels.length);
          if (options2.lod) {
            return lod(nminX, nminY, nmaxX, nmaxY, maxLevel);
          }
          let selection = [];
          select(0, 0, 1, 0, 0, 1);
          function select(lox, loy, d, level, from, to) {
            if (from === null || to === null) return;
            let hix = lox + d;
            let hiy = loy + d;
            if (nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy) return;
            if (level >= maxLevel) return;
            if (from === to) return;
            let levelItems = levels[level];
            if (to === void 0) to = levelItems.length;
            for (let i = from; i < to; i++) {
              let id = levelItems[i];
              let px = srcPoints[id * 2];
              let py = srcPoints[id * 2 + 1];
              if (px >= minX && px <= maxX && py >= minY && py <= maxY) {
                selection.push(id);
              }
            }
            let offsets2 = sublevels[level];
            let off0 = offsets2[from * 4 + 0];
            let off1 = offsets2[from * 4 + 1];
            let off2 = offsets2[from * 4 + 2];
            let off3 = offsets2[from * 4 + 3];
            let end = nextOffset(offsets2, from + 1);
            let d2 = d * 0.5;
            let nextLevel = level + 1;
            select(lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end);
            select(lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end);
            select(lox + d2, loy, d2, nextLevel, off2, off3 || end);
            select(lox + d2, loy + d2, d2, nextLevel, off3, end);
          }
          function nextOffset(offsets2, from) {
            let offset2 = null, i = 0;
            while (offset2 === null) {
              offset2 = offsets2[from * 4 + i];
              i++;
              if (i > offsets2.length) return null;
            }
            return offset2;
          }
          return selection;
        }
        function lod(lox, loy, hix, hiy, maxLevel) {
          let ranges = [];
          for (let level = 0; level < maxLevel; level++) {
            let levelGroups = groups[level];
            let from = offsets[level][0];
            let levelGroupStart = group(lox, loy, level);
            let levelGroupEnd = group(hix, hiy, level);
            let startOffset = search.ge(levelGroups, levelGroupStart);
            let endOffset = search.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1);
            ranges[level] = [startOffset + from, endOffset + from];
          }
          return ranges;
        }
        function group(x, y, level) {
          let group2 = 1;
          let cx = 0.5, cy = 0.5;
          let diam = 0.5;
          for (let i = 0; i < level; i++) {
            group2 <<= 2;
            group2 += x < cx ? y < cy ? 0 : 1 : y < cy ? 2 : 3;
            diam *= 0.5;
            cx += x < cx ? -diam : diam;
            cy += y < cy ? -diam : diam;
          }
          return group2;
        }
      };
      function normalize(pts, bounds) {
        let [lox, loy, hix, hiy] = bounds;
        let scaleX = 1 / (hix - lox);
        let scaleY = 1 / (hiy - loy);
        let result = new Array(pts.length);
        for (let i = 0, n = pts.length / 2; i < n; i++) {
          result[2 * i] = clamp((pts[2 * i] - lox) * scaleX, 0, 1);
          result[2 * i + 1] = clamp((pts[2 * i + 1] - loy) * scaleY, 0, 1);
        }
        return result;
      }
    }
  });

  // node_modules/@plotly/point-cluster/index.js
  var require_point_cluster = __commonJS({
    "node_modules/@plotly/point-cluster/index.js"(exports, module) {
      "use strict";
      module.exports = require_quad();
    }
  });

  // node_modules/abs-svg-path/index.js
  var require_abs_svg_path = __commonJS({
    "node_modules/abs-svg-path/index.js"(exports, module) {
      module.exports = absolutize;
      function absolutize(path) {
        var startX = 0;
        var startY = 0;
        var x = 0;
        var y = 0;
        return path.map(function(seg) {
          seg = seg.slice();
          var type = seg[0];
          var command = type.toUpperCase();
          if (type != command) {
            seg[0] = command;
            switch (type) {
              case "a":
                seg[6] += x;
                seg[7] += y;
                break;
              case "v":
                seg[1] += y;
                break;
              case "h":
                seg[1] += x;
                break;
              default:
                for (var i = 1; i < seg.length; ) {
                  seg[i++] += x;
                  seg[i++] += y;
                }
            }
          }
          switch (command) {
            case "Z":
              x = startX;
              y = startY;
              break;
            case "H":
              x = seg[1];
              break;
            case "V":
              y = seg[1];
              break;
            case "M":
              x = startX = seg[1];
              y = startY = seg[2];
              break;
            default:
              x = seg[seg.length - 2];
              y = seg[seg.length - 1];
          }
          return seg;
        });
      }
    }
  });

  // node_modules/svg-arc-to-cubic-bezier/cjs/index.js
  var require_cjs6 = __commonJS({
    "node_modules/svg-arc-to-cubic-bezier/cjs/index.js"(exports, module) {
      "use strict";
      Object.defineProperty(exports, "__esModule", {
        value: true
      });
      var _slicedToArray = /* @__PURE__ */ function() {
        function sliceIterator(arr, i) {
          var _arr = [];
          var _n = true;
          var _d = false;
          var _e = void 0;
          try {
            for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
              _arr.push(_s.value);
              if (i && _arr.length === i) break;
            }
          } catch (err) {
            _d = true;
            _e = err;
          } finally {
            try {
              if (!_n && _i["return"]) _i["return"]();
            } finally {
              if (_d) throw _e;
            }
          }
          return _arr;
        }
        return function(arr, i) {
          if (Array.isArray(arr)) {
            return arr;
          } else if (Symbol.iterator in Object(arr)) {
            return sliceIterator(arr, i);
          } else {
            throw new TypeError("Invalid attempt to destructure non-iterable instance");
          }
        };
      }();
      var TAU = Math.PI * 2;
      var mapToEllipse = function mapToEllipse2(_ref, rx, ry, cosphi, sinphi, centerx, centery) {
        var x = _ref.x, y = _ref.y;
        x *= rx;
        y *= ry;
        var xp = cosphi * x - sinphi * y;
        var yp = sinphi * x + cosphi * y;
        return {
          x: xp + centerx,
          y: yp + centery
        };
      };
      var approxUnitArc = function approxUnitArc2(ang1, ang2) {
        var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4);
        var x1 = Math.cos(ang1);
        var y1 = Math.sin(ang1);
        var x2 = Math.cos(ang1 + ang2);
        var y2 = Math.sin(ang1 + ang2);
        return [{
          x: x1 - y1 * a,
          y: y1 + x1 * a
        }, {
          x: x2 + y2 * a,
          y: y2 - x2 * a
        }, {
          x: x2,
          y: y2
        }];
      };
      var vectorAngle = function vectorAngle2(ux, uy, vx, vy) {
        var sign = ux * vy - uy * vx < 0 ? -1 : 1;
        var dot = ux * vx + uy * vy;
        if (dot > 1) {
          dot = 1;
        }
        if (dot < -1) {
          dot = -1;
        }
        return sign * Math.acos(dot);
      };
      var getArcCenter = function getArcCenter2(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) {
        var rxsq = Math.pow(rx, 2);
        var rysq = Math.pow(ry, 2);
        var pxpsq = Math.pow(pxp, 2);
        var pypsq = Math.pow(pyp, 2);
        var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq;
        if (radicant < 0) {
          radicant = 0;
        }
        radicant /= rxsq * pypsq + rysq * pxpsq;
        radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
        var centerxp = radicant * rx / ry * pyp;
        var centeryp = radicant * -ry / rx * pxp;
        var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
        var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;
        var vx1 = (pxp - centerxp) / rx;
        var vy1 = (pyp - centeryp) / ry;
        var vx2 = (-pxp - centerxp) / rx;
        var vy2 = (-pyp - centeryp) / ry;
        var ang1 = vectorAngle(1, 0, vx1, vy1);
        var ang2 = vectorAngle(vx1, vy1, vx2, vy2);
        if (sweepFlag === 0 && ang2 > 0) {
          ang2 -= TAU;
        }
        if (sweepFlag === 1 && ang2 < 0) {
          ang2 += TAU;
        }
        return [centerx, centery, ang1, ang2];
      };
      var arcToBezier = function arcToBezier2(_ref2) {
        var px = _ref2.px, py = _ref2.py, cx = _ref2.cx, cy = _ref2.cy, rx = _ref2.rx, ry = _ref2.ry, _ref2$xAxisRotation = _ref2.xAxisRotation, xAxisRotation = _ref2$xAxisRotation === void 0 ? 0 : _ref2$xAxisRotation, _ref2$largeArcFlag = _ref2.largeArcFlag, largeArcFlag = _ref2$largeArcFlag === void 0 ? 0 : _ref2$largeArcFlag, _ref2$sweepFlag = _ref2.sweepFlag, sweepFlag = _ref2$sweepFlag === void 0 ? 0 : _ref2$sweepFlag;
        var curves = [];
        if (rx === 0 || ry === 0) {
          return [];
        }
        var sinphi = Math.sin(xAxisRotation * TAU / 360);
        var cosphi = Math.cos(xAxisRotation * TAU / 360);
        var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2;
        var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2;
        if (pxp === 0 && pyp === 0) {
          return [];
        }
        rx = Math.abs(rx);
        ry = Math.abs(ry);
        var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2);
        if (lambda > 1) {
          rx *= Math.sqrt(lambda);
          ry *= Math.sqrt(lambda);
        }
        var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), _getArcCenter2 = _slicedToArray(_getArcCenter, 4), centerx = _getArcCenter2[0], centery = _getArcCenter2[1], ang1 = _getArcCenter2[2], ang2 = _getArcCenter2[3];
        var ratio = Math.abs(ang2) / (TAU / 4);
        if (Math.abs(1 - ratio) < 1e-7) {
          ratio = 1;
        }
        var segments = Math.max(Math.ceil(ratio), 1);
        ang2 /= segments;
        for (var i = 0; i < segments; i++) {
          curves.push(approxUnitArc(ang1, ang2));
          ang1 += ang2;
        }
        return curves.map(function(curve) {
          var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), x1 = _mapToEllipse.x, y1 = _mapToEllipse.y;
          var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), x2 = _mapToEllipse2.x, y2 = _mapToEllipse2.y;
          var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), x = _mapToEllipse3.x, y = _mapToEllipse3.y;
          return { x1, y1, x2, y2, x, y };
        });
      };
      exports.default = arcToBezier;
      module.exports = exports.default;
    }
  });

  // node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.js
  var require_normalize_svg_path = __commonJS({
    "node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.js"(exports, module) {
      "use strict";
      module.exports = normalize;
      var arcToCurve = require_cjs6();
      function normalize(path) {
        var prev;
        var result = [];
        var bezierX = 0;
        var bezierY = 0;
        var startX = 0;
        var startY = 0;
        var quadX = null;
        var quadY = null;
        var x = 0;
        var y = 0;
        for (var i = 0, len = path.length; i < len; i++) {
          var seg = path[i];
          var command = seg[0];
          switch (command) {
            case "M":
              startX = seg[1];
              startY = seg[2];
              break;
            case "A":
              var curves = arcToCurve({
                px: x,
                py: y,
                cx: seg[6],
                cy: seg[7],
                rx: seg[1],
                ry: seg[2],
                xAxisRotation: seg[3],
                largeArcFlag: seg[4],
                sweepFlag: seg[5]
              });
              if (!curves.length) continue;
              for (var j = 0, c; j < curves.length; j++) {
                c = curves[j];
                seg = ["C", c.x1, c.y1, c.x2, c.y2, c.x, c.y];
                if (j < curves.length - 1) result.push(seg);
              }
              break;
            case "S":
              var cx = x;
              var cy = y;
              if (prev == "C" || prev == "S") {
                cx += cx - bezierX;
                cy += cy - bezierY;
              }
              seg = ["C", cx, cy, seg[1], seg[2], seg[3], seg[4]];
              break;
            case "T":
              if (prev == "Q" || prev == "T") {
                quadX = x * 2 - quadX;
                quadY = y * 2 - quadY;
              } else {
                quadX = x;
                quadY = y;
              }
              seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]);
              break;
            case "Q":
              quadX = seg[1];
              quadY = seg[2];
              seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]);
              break;
            case "L":
              seg = line(x, y, seg[1], seg[2]);
              break;
            case "H":
              seg = line(x, y, seg[1], y);
              break;
            case "V":
              seg = line(x, y, x, seg[1]);
              break;
            case "Z":
              seg = line(x, y, startX, startY);
              break;
          }
          prev = command;
          x = seg[seg.length - 2];
          y = seg[seg.length - 1];
          if (seg.length > 4) {
            bezierX = seg[seg.length - 4];
            bezierY = seg[seg.length - 3];
          } else {
            bezierX = x;
            bezierY = y;
          }
          result.push(seg);
        }
        return result;
      }
      function line(x1, y1, x2, y2) {
        return ["C", x1, y1, x2, y2, x2, y2];
      }
      function quadratic(x1, y1, cx, cy, x2, y2) {
        return [
          "C",
          x1 / 3 + 2 / 3 * cx,
          y1 / 3 + 2 / 3 * cy,
          x2 / 3 + 2 / 3 * cx,
          y2 / 3 + 2 / 3 * cy,
          x2,
          y2
        ];
      }
    }
  });

  // node_modules/is-svg-path/index.js
  var require_is_svg_path = __commonJS({
    "node_modules/is-svg-path/index.js"(exports, module) {
      "use strict";
      module.exports = function isPath(str) {
        if (typeof str !== "string") return false;
        str = str.trim();
        if (/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(str) && /[\dz]$/i.test(str) && str.length > 4) return true;
        return false;
      };
    }
  });

  // node_modules/svg-path-bounds/index.js
  var require_svg_path_bounds = __commonJS({
    "node_modules/svg-path-bounds/index.js"(exports, module) {
      "use strict";
      var parse2 = require_parse_svg_path();
      var abs = require_abs_svg_path();
      var normalize = require_normalize_svg_path();
      var isSvgPath = require_is_svg_path();
      var assert = require_assert();
      module.exports = pathBounds;
      function pathBounds(path) {
        if (Array.isArray(path) && path.length === 1 && typeof path[0] === "string") path = path[0];
        if (typeof path === "string") {
          assert(isSvgPath(path), "String is not an SVG path.");
          path = parse2(path);
        }
        assert(Array.isArray(path), "Argument should be a string or an array of path segments.");
        path = abs(path);
        path = normalize(path);
        if (!path.length) return [0, 0, 0, 0];
        var bounds = [Infinity, Infinity, -Infinity, -Infinity];
        for (var i = 0, l = path.length; i < l; i++) {
          var points = path[i].slice(1);
          for (var j = 0; j < points.length; j += 2) {
            if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0];
            if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1];
            if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0];
            if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1];
          }
        }
        return bounds;
      }
    }
  });

  // node_modules/normalize-svg-path/index.js
  var require_normalize_svg_path2 = __commonJS({
    "node_modules/normalize-svg-path/index.js"(exports, module) {
      var \u03C0 = Math.PI;
      var _120 = radians2(120);
      module.exports = normalize;
      function normalize(path) {
        var prev;
        var result = [];
        var bezierX = 0;
        var bezierY = 0;
        var startX = 0;
        var startY = 0;
        var quadX = null;
        var quadY = null;
        var x = 0;
        var y = 0;
        for (var i = 0, len = path.length; i < len; i++) {
          var seg = path[i];
          var command = seg[0];
          switch (command) {
            case "M":
              startX = seg[1];
              startY = seg[2];
              break;
            case "A":
              seg = arc(x, y, seg[1], seg[2], radians2(seg[3]), seg[4], seg[5], seg[6], seg[7]);
              seg.unshift("C");
              if (seg.length > 7) {
                result.push(seg.splice(0, 7));
                seg.unshift("C");
              }
              break;
            case "S":
              var cx = x;
              var cy = y;
              if (prev == "C" || prev == "S") {
                cx += cx - bezierX;
                cy += cy - bezierY;
              }
              seg = ["C", cx, cy, seg[1], seg[2], seg[3], seg[4]];
              break;
            case "T":
              if (prev == "Q" || prev == "T") {
                quadX = x * 2 - quadX;
                quadY = y * 2 - quadY;
              } else {
                quadX = x;
                quadY = y;
              }
              seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]);
              break;
            case "Q":
              quadX = seg[1];
              quadY = seg[2];
              seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]);
              break;
            case "L":
              seg = line(x, y, seg[1], seg[2]);
              break;
            case "H":
              seg = line(x, y, seg[1], y);
              break;
            case "V":
              seg = line(x, y, x, seg[1]);
              break;
            case "Z":
              seg = line(x, y, startX, startY);
              break;
          }
          prev = command;
          x = seg[seg.length - 2];
          y = seg[seg.length - 1];
          if (seg.length > 4) {
            bezierX = seg[seg.length - 4];
            bezierY = seg[seg.length - 3];
          } else {
            bezierX = x;
            bezierY = y;
          }
          result.push(seg);
        }
        return result;
      }
      function line(x1, y1, x2, y2) {
        return ["C", x1, y1, x2, y2, x2, y2];
      }
      function quadratic(x1, y1, cx, cy, x2, y2) {
        return [
          "C",
          x1 / 3 + 2 / 3 * cx,
          y1 / 3 + 2 / 3 * cy,
          x2 / 3 + 2 / 3 * cx,
          y2 / 3 + 2 / 3 * cy,
          x2,
          y2
        ];
      }
      function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
        if (!recursive) {
          var xy = rotate(x1, y1, -angle);
          x1 = xy.x;
          y1 = xy.y;
          xy = rotate(x2, y2, -angle);
          x2 = xy.x;
          y2 = xy.y;
          var x = (x1 - x2) / 2;
          var y = (y1 - y2) / 2;
          var h = x * x / (rx * rx) + y * y / (ry * ry);
          if (h > 1) {
            h = Math.sqrt(h);
            rx = h * rx;
            ry = h * ry;
          }
          var rx2 = rx * rx;
          var ry2 = ry * ry;
          var k = (large_arc_flag == sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)));
          if (k == Infinity) k = 1;
          var cx = k * rx * y / ry + (x1 + x2) / 2;
          var cy = k * -ry * x / rx + (y1 + y2) / 2;
          var f1 = Math.asin(((y1 - cy) / ry).toFixed(9));
          var f2 = Math.asin(((y2 - cy) / ry).toFixed(9));
          f1 = x1 < cx ? \u03C0 - f1 : f1;
          f2 = x2 < cx ? \u03C0 - f2 : f2;
          if (f1 < 0) f1 = \u03C0 * 2 + f1;
          if (f2 < 0) f2 = \u03C0 * 2 + f2;
          if (sweep_flag && f1 > f2) f1 = f1 - \u03C0 * 2;
          if (!sweep_flag && f2 > f1) f2 = f2 - \u03C0 * 2;
        } else {
          f1 = recursive[0];
          f2 = recursive[1];
          cx = recursive[2];
          cy = recursive[3];
        }
        if (Math.abs(f2 - f1) > _120) {
          var f2old = f2;
          var x2old = x2;
          var y2old = y2;
          f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
          x2 = cx + rx * Math.cos(f2);
          y2 = cy + ry * Math.sin(f2);
          var res = arc(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
        }
        var t = Math.tan((f2 - f1) / 4);
        var hx = 4 / 3 * rx * t;
        var hy = 4 / 3 * ry * t;
        var curve = [
          2 * x1 - (x1 + hx * Math.sin(f1)),
          2 * y1 - (y1 - hy * Math.cos(f1)),
          x2 + hx * Math.sin(f2),
          y2 - hy * Math.cos(f2),
          x2,
          y2
        ];
        if (recursive) return curve;
        if (res) curve = curve.concat(res);
        for (var i = 0; i < curve.length; ) {
          var rot = rotate(curve[i], curve[i + 1], angle);
          curve[i++] = rot.x;
          curve[i++] = rot.y;
        }
        return curve;
      }
      function rotate(x, y, rad) {
        return {
          x: x * Math.cos(rad) - y * Math.sin(rad),
          y: x * Math.sin(rad) + y * Math.cos(rad)
        };
      }
      function radians2(degress) {
        return degress * (\u03C0 / 180);
      }
    }
  });

  // node_modules/draw-svg-path/index.js
  var require_draw_svg_path = __commonJS({
    "node_modules/draw-svg-path/index.js"(exports, module) {
      var abs = require_abs_svg_path();
      var normalize = require_normalize_svg_path2();
      var methods = {
        "M": "moveTo",
        "C": "bezierCurveTo"
      };
      module.exports = function(context, segments) {
        context.beginPath();
        normalize(abs(segments)).forEach(
          function(segment) {
            var command = segment[0];
            var args = segment.slice(1);
            context[methods[command]].apply(context, args);
          }
        );
        context.closePath();
      };
    }
  });

  // node_modules/bitmap-sdf/index.js
  var require_bitmap_sdf = __commonJS({
    "node_modules/bitmap-sdf/index.js"(exports, module) {
      "use strict";
      var clamp = require_clamp();
      module.exports = calcSDF;
      var INF = 1e20;
      function calcSDF(src, options) {
        if (!options) options = {};
        var cutoff = options.cutoff == null ? 0.25 : options.cutoff;
        var radius = options.radius == null ? 8 : options.radius;
        var channel = options.channel || 0;
        var w, h, size, data, intData, stride, ctx, canvas, imgData, i, l;
        if (ArrayBuffer.isView(src) || Array.isArray(src)) {
          if (!options.width || !options.height) throw Error("For raw data width and height should be provided by options");
          w = options.width, h = options.height;
          data = src;
          if (!options.stride) stride = Math.floor(src.length / w / h);
          else stride = options.stride;
        } else {
          if (window.HTMLCanvasElement && src instanceof window.HTMLCanvasElement) {
            canvas = src;
            ctx = canvas.getContext("2d");
            w = canvas.width, h = canvas.height;
            imgData = ctx.getImageData(0, 0, w, h);
            data = imgData.data;
            stride = 4;
          } else if (window.CanvasRenderingContext2D && src instanceof window.CanvasRenderingContext2D) {
            canvas = src.canvas;
            ctx = src;
            w = canvas.width, h = canvas.height;
            imgData = ctx.getImageData(0, 0, w, h);
            data = imgData.data;
            stride = 4;
          } else if (window.ImageData && src instanceof window.ImageData) {
            imgData = src;
            w = src.width, h = src.height;
            data = imgData.data;
            stride = 4;
          }
        }
        size = Math.max(w, h);
        if (window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray || window.Uint8Array && data instanceof window.Uint8Array) {
          intData = data;
          data = Array(w * h);
          for (i = 0, l = intData.length; i < l; i++) {
            data[i] = intData[i * stride + channel] / 255;
          }
        } else {
          if (stride !== 1) throw Error("Raw data can have only 1 value per pixel");
        }
        var gridOuter = Array(w * h);
        var gridInner = Array(w * h);
        var f = Array(size);
        var d = Array(size);
        var z = Array(size + 1);
        var v = Array(size);
        for (i = 0, l = w * h; i < l; i++) {
          var a = data[i];
          gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2);
          gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);
        }
        edt(gridOuter, w, h, f, d, v, z);
        edt(gridInner, w, h, f, d, v, z);
        var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h);
        for (i = 0, l = w * h; i < l; i++) {
          dist[i] = clamp(1 - ((gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1);
        }
        return dist;
      }
      function edt(data, width, height, f, d, v, z) {
        for (var x = 0; x < width; x++) {
          for (var y = 0; y < height; y++) {
            f[y] = data[y * width + x];
          }
          edt1d(f, d, v, z, height);
          for (y = 0; y < height; y++) {
            data[y * width + x] = d[y];
          }
        }
        for (y = 0; y < height; y++) {
          for (x = 0; x < width; x++) {
            f[x] = data[y * width + x];
          }
          edt1d(f, d, v, z, width);
          for (x = 0; x < width; x++) {
            data[y * width + x] = Math.sqrt(d[x]);
          }
        }
      }
      function edt1d(f, d, v, z, n) {
        v[0] = 0;
        z[0] = -INF;
        z[1] = +INF;
        for (var q = 1, k = 0; q < n; q++) {
          var s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
          while (s <= z[k]) {
            k--;
            s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
          }
          k++;
          v[k] = q;
          z[k] = s;
          z[k + 1] = +INF;
        }
        for (q = 0, k = 0; q < n; q++) {
          while (z[k + 1] < q) k++;
          d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];
        }
      }
    }
  });

  // node_modules/svg-path-sdf/index.js
  var require_svg_path_sdf = __commonJS({
    "node_modules/svg-path-sdf/index.js"(exports, module) {
      "use strict";
      var pathBounds = require_svg_path_bounds();
      var parsePath = require_parse_svg_path();
      var drawPath = require_draw_svg_path();
      var isSvgPath = require_is_svg_path();
      var bitmapSdf = require_bitmap_sdf();
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      module.exports = pathSdf;
      function pathSdf(path, options) {
        if (!isSvgPath(path)) throw Error("Argument should be valid svg path string");
        if (!options) options = {};
        var w, h;
        if (options.shape) {
          w = options.shape[0];
          h = options.shape[1];
        } else {
          w = canvas.width = options.w || options.width || 200;
          h = canvas.height = options.h || options.height || 200;
        }
        var size = Math.min(w, h);
        var stroke = options.stroke || 0;
        var viewbox = options.viewbox || options.viewBox || pathBounds(path);
        var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])];
        var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2;
        ctx.fillStyle = "black";
        ctx.fillRect(0, 0, w, h);
        ctx.fillStyle = "white";
        if (stroke) {
          if (typeof stroke != "number") stroke = 1;
          if (stroke > 0) {
            ctx.strokeStyle = "white";
          } else {
            ctx.strokeStyle = "black";
          }
          ctx.lineWidth = Math.abs(stroke);
        }
        ctx.translate(w * 0.5, h * 0.5);
        ctx.scale(maxScale, maxScale);
        if (isPath2DSupported()) {
          var path2d = new Path2D(path);
          ctx.fill(path2d);
          stroke && ctx.stroke(path2d);
        } else {
          var segments = parsePath(path);
          drawPath(ctx, segments);
          ctx.fill();
          stroke && ctx.stroke();
        }
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        var data = bitmapSdf(ctx, {
          cutoff: options.cutoff != null ? options.cutoff : 0.5,
          radius: options.radius != null ? options.radius : size * 0.5
        });
        return data;
      }
      var path2DSupported;
      function isPath2DSupported() {
        if (path2DSupported != null) return path2DSupported;
        var ctx2 = document.createElement("canvas").getContext("2d");
        ctx2.canvas.width = ctx2.canvas.height = 1;
        if (!window.Path2D) return path2DSupported = false;
        var path = new Path2D("M0,0h1v1h-1v-1Z");
        ctx2.fillStyle = "black";
        ctx2.fill(path);
        var idata = ctx2.getImageData(0, 0, 1, 1);
        return path2DSupported = idata && idata.data && idata.data[3] === 255;
      }
    }
  });

  // src/traces/scattergl/convert.js
  var require_convert10 = __commonJS({
    "src/traces/scattergl/convert.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var svgSdf = require_svg_path_sdf();
      var rgba3 = require_color_normalize();
      var Registry = require_registry();
      var Lib = require_lib();
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var Drawing = require_drawing();
      var AxisIDs = require_axis_ids();
      var formatColor = require_gl_format_color().formatColor;
      var subTypes = require_subtypes();
      var makeBubbleSizeFn = require_make_bubble_size_func();
      var helpers = require_helpers16();
      var constants = require_constants23();
      var DESELECTDIM = require_interactions().DESELECTDIM;
      var TEXTOFFSETSIGN = {
        start: 1,
        left: 1,
        end: -1,
        right: -1,
        middle: 0,
        center: 0,
        bottom: 1,
        top: -1
      };
      var appendArrayPointValue = require_helpers2().appendArrayPointValue;
      function convertStyle(gd, trace) {
        var i;
        var opts = {
          marker: void 0,
          markerSel: void 0,
          markerUnsel: void 0,
          line: void 0,
          fill: void 0,
          errorX: void 0,
          errorY: void 0,
          text: void 0,
          textSel: void 0,
          textUnsel: void 0
        };
        var plotGlPixelRatio = gd._context.plotGlPixelRatio;
        if (trace.visible !== true) return opts;
        if (subTypes.hasText(trace)) {
          opts.text = convertTextStyle(gd, trace);
          opts.textSel = convertTextSelection(gd, trace, trace.selected);
          opts.textUnsel = convertTextSelection(gd, trace, trace.unselected);
        }
        if (subTypes.hasMarkers(trace)) {
          opts.marker = convertMarkerStyle(gd, trace);
          opts.markerSel = convertMarkerSelection(gd, trace, trace.selected);
          opts.markerUnsel = convertMarkerSelection(gd, trace, trace.unselected);
          if (!trace.unselected && isArrayOrTypedArray(trace.marker.opacity)) {
            var mo = trace.marker.opacity;
            opts.markerUnsel.opacity = new Array(mo.length);
            for (i = 0; i < mo.length; i++) {
              opts.markerUnsel.opacity[i] = DESELECTDIM * mo[i];
            }
          }
        }
        if (subTypes.hasLines(trace)) {
          opts.line = {
            overlay: true,
            thickness: trace.line.width * plotGlPixelRatio,
            color: trace.line.color,
            opacity: trace.opacity
          };
          var dashes = (constants.DASHES[trace.line.dash] || [1]).slice();
          for (i = 0; i < dashes.length; ++i) {
            dashes[i] *= trace.line.width * plotGlPixelRatio;
          }
          opts.line.dashes = dashes;
        }
        if (trace.error_x && trace.error_x.visible) {
          opts.errorX = convertErrorBarStyle(trace, trace.error_x, plotGlPixelRatio);
        }
        if (trace.error_y && trace.error_y.visible) {
          opts.errorY = convertErrorBarStyle(trace, trace.error_y, plotGlPixelRatio);
        }
        if (!!trace.fill && trace.fill !== "none") {
          opts.fill = {
            closed: true,
            fill: trace.fillcolor,
            thickness: 0
          };
        }
        return opts;
      }
      function convertTextStyle(gd, trace) {
        var fullLayout = gd._fullLayout;
        var count = trace._length;
        var textfontIn = trace.textfont;
        var textpositionIn = trace.textposition;
        var textPos = isArrayOrTypedArray(textpositionIn) ? textpositionIn : [textpositionIn];
        var tfc = textfontIn.color;
        var tfs = textfontIn.size;
        var tff = textfontIn.family;
        var tfw = textfontIn.weight;
        var tfy = textfontIn.style;
        var tfv = textfontIn.variant;
        var optsOut = {};
        var i;
        var plotGlPixelRatio = gd._context.plotGlPixelRatio;
        var texttemplate = trace.texttemplate;
        if (texttemplate) {
          optsOut.text = [];
          var d3locale = fullLayout._d3locale;
          var isArray = Array.isArray(texttemplate);
          var N = isArray ? Math.min(texttemplate.length, count) : count;
          var txt = isArray ? function(i2) {
            return texttemplate[i2];
          } : function() {
            return texttemplate;
          };
          for (i = 0; i < N; i++) {
            var d = { i };
            var labels = trace._module.formatLabels(d, trace, fullLayout);
            var pointValues = {};
            appendArrayPointValue(pointValues, trace, i);
            optsOut.text.push(
              Lib.texttemplateString({
                data: [pointValues, d, trace._meta],
                fallback: trace.texttemplatefallback,
                labels,
                locale: d3locale,
                template: txt(i)
              })
            );
          }
        } else {
          if (isArrayOrTypedArray(trace.text) && trace.text.length < count) {
            optsOut.text = trace.text.slice();
          } else {
            optsOut.text = trace.text;
          }
        }
        if (isArrayOrTypedArray(optsOut.text)) {
          for (i = optsOut.text.length; i < count; i++) {
            optsOut.text[i] = "";
          }
        }
        optsOut.opacity = trace.opacity;
        optsOut.font = {};
        optsOut.align = [];
        optsOut.baseline = [];
        for (i = 0; i < textPos.length; i++) {
          var tp = textPos[i].split(/\s+/);
          switch (tp[1]) {
            case "left":
              optsOut.align.push("right");
              break;
            case "right":
              optsOut.align.push("left");
              break;
            default:
              optsOut.align.push(tp[1]);
          }
          switch (tp[0]) {
            case "top":
              optsOut.baseline.push("bottom");
              break;
            case "bottom":
              optsOut.baseline.push("top");
              break;
            default:
              optsOut.baseline.push(tp[0]);
          }
        }
        if (isArrayOrTypedArray(tfc)) {
          optsOut.color = new Array(count);
          for (i = 0; i < count; i++) {
            optsOut.color[i] = tfc[i];
          }
        } else {
          optsOut.color = tfc;
        }
        if (isArrayOrTypedArray(tfs) || Array.isArray(tff) || isArrayOrTypedArray(tfw) || Array.isArray(tfy) || Array.isArray(tfv)) {
          optsOut.font = new Array(count);
          for (i = 0; i < count; i++) {
            var fonti = optsOut.font[i] = {};
            fonti.size = (Lib.isTypedArray(tfs) ? tfs[i] : isArrayOrTypedArray(tfs) ? isNumeric(tfs[i]) ? tfs[i] : 0 : tfs) * plotGlPixelRatio;
            fonti.family = Array.isArray(tff) ? tff[i] : tff;
            fonti.weight = weightFallBack(isArrayOrTypedArray(tfw) ? tfw[i] : tfw);
            fonti.style = Array.isArray(tfy) ? tfy[i] : tfy;
            fonti.variant = Array.isArray(tfv) ? tfv[i] : tfv;
          }
        } else {
          optsOut.font = {
            size: tfs * plotGlPixelRatio,
            family: tff,
            weight: weightFallBack(tfw),
            style: tfy,
            variant: tfv
          };
        }
        return optsOut;
      }
      function weightFallBack(w) {
        if (w <= 1e3) {
          return w > 500 ? "bold" : "normal";
        }
        return w;
      }
      function convertMarkerStyle(gd, trace) {
        var count = trace._length;
        var optsIn = trace.marker;
        var optsOut = {};
        var i;
        var multiSymbol = isArrayOrTypedArray(optsIn.symbol);
        var multiAngle = isArrayOrTypedArray(optsIn.angle);
        var multiColor = isArrayOrTypedArray(optsIn.color);
        var multiLineColor = isArrayOrTypedArray(optsIn.line.color);
        var multiOpacity = isArrayOrTypedArray(optsIn.opacity);
        var multiSize = isArrayOrTypedArray(optsIn.size);
        var multiLineWidth = isArrayOrTypedArray(optsIn.line.width);
        var isOpen;
        if (!multiSymbol) isOpen = helpers.isOpenSymbol(optsIn.symbol);
        if (multiSymbol || multiColor || multiLineColor || multiOpacity || multiAngle) {
          optsOut.symbols = new Array(count);
          optsOut.angles = new Array(count);
          optsOut.colors = new Array(count);
          optsOut.borderColors = new Array(count);
          var symbols = optsIn.symbol;
          var angles = optsIn.angle;
          var colors = formatColor(optsIn, optsIn.opacity, count);
          var borderColors = formatColor(optsIn.line, optsIn.opacity, count);
          if (!isArrayOrTypedArray(borderColors[0])) {
            var borderColor = borderColors;
            borderColors = Array(count);
            for (i = 0; i < count; i++) {
              borderColors[i] = borderColor;
            }
          }
          if (!isArrayOrTypedArray(colors[0])) {
            var color2 = colors;
            colors = Array(count);
            for (i = 0; i < count; i++) {
              colors[i] = color2;
            }
          }
          if (!isArrayOrTypedArray(symbols)) {
            var symbol = symbols;
            symbols = Array(count);
            for (i = 0; i < count; i++) {
              symbols[i] = symbol;
            }
          }
          if (!isArrayOrTypedArray(angles)) {
            var angle = angles;
            angles = Array(count);
            for (i = 0; i < count; i++) {
              angles[i] = angle;
            }
          }
          optsOut.symbols = symbols;
          optsOut.angles = angles;
          optsOut.colors = colors;
          optsOut.borderColors = borderColors;
          for (i = 0; i < count; i++) {
            if (multiSymbol) {
              isOpen = helpers.isOpenSymbol(optsIn.symbol[i]);
            }
            if (isOpen) {
              borderColors[i] = colors[i].slice();
              colors[i] = colors[i].slice();
              colors[i][3] = 0;
            }
          }
          optsOut.opacity = trace.opacity;
          optsOut.markers = new Array(count);
          for (i = 0; i < count; i++) {
            optsOut.markers[i] = getSymbolSdf(
              {
                mx: optsOut.symbols[i],
                ma: optsOut.angles[i]
              },
              trace
            );
          }
        } else {
          if (isOpen) {
            optsOut.color = rgba3(optsIn.color, "uint8");
            optsOut.color[3] = 0;
            optsOut.borderColor = rgba3(optsIn.color, "uint8");
          } else {
            optsOut.color = rgba3(optsIn.color, "uint8");
            optsOut.borderColor = rgba3(optsIn.line.color, "uint8");
          }
          optsOut.opacity = trace.opacity * optsIn.opacity;
          optsOut.marker = getSymbolSdf(
            {
              mx: optsIn.symbol,
              ma: optsIn.angle
            },
            trace
          );
        }
        var sizeFactor = 1;
        var markerSizeFunc = makeBubbleSizeFn(trace, sizeFactor);
        var s;
        if (multiSize || multiLineWidth) {
          var sizes = optsOut.sizes = new Array(count);
          var borderSizes = optsOut.borderSizes = new Array(count);
          var sizeTotal = 0;
          var sizeAvg;
          if (multiSize) {
            for (i = 0; i < count; i++) {
              sizes[i] = markerSizeFunc(optsIn.size[i]);
              sizeTotal += sizes[i];
            }
            sizeAvg = sizeTotal / count;
          } else {
            s = markerSizeFunc(optsIn.size);
            for (i = 0; i < count; i++) {
              sizes[i] = s;
            }
          }
          if (multiLineWidth) {
            for (i = 0; i < count; i++) {
              borderSizes[i] = optsIn.line.width[i];
            }
          } else {
            s = optsIn.line.width;
            for (i = 0; i < count; i++) {
              borderSizes[i] = s;
            }
          }
          optsOut.sizeAvg = sizeAvg;
        } else {
          optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10);
          optsOut.borderSizes = markerSizeFunc(optsIn.line.width);
        }
        return optsOut;
      }
      function convertMarkerSelection(gd, trace, target) {
        var optsIn = trace.marker;
        var optsOut = {};
        if (!target) return optsOut;
        if (target.marker && target.marker.symbol) {
          optsOut = convertMarkerStyle(gd, Lib.extendFlat({}, optsIn, target.marker));
        } else if (target.marker) {
          if (target.marker.size) optsOut.size = target.marker.size;
          if (target.marker.color) optsOut.colors = target.marker.color;
          if (target.marker.opacity !== void 0) optsOut.opacity = target.marker.opacity;
        }
        return optsOut;
      }
      function convertTextSelection(gd, trace, target) {
        var optsOut = {};
        if (!target) return optsOut;
        if (target.textfont) {
          var optsIn = {
            opacity: 1,
            text: trace.text,
            texttemplate: trace.texttemplate,
            textposition: trace.textposition,
            textfont: Lib.extendFlat({}, trace.textfont)
          };
          if (target.textfont) {
            Lib.extendFlat(optsIn.textfont, target.textfont);
          }
          optsOut = convertTextStyle(gd, optsIn);
        }
        return optsOut;
      }
      function convertErrorBarStyle(trace, target, plotGlPixelRatio) {
        var optsOut = {
          capSize: target.width * 2 * plotGlPixelRatio,
          lineWidth: target.thickness * plotGlPixelRatio,
          color: target.color
        };
        if (target.copy_ystyle) {
          optsOut = trace.error_y;
        }
        return optsOut;
      }
      var SYMBOL_SDF_SIZE = constants.SYMBOL_SDF_SIZE;
      var SYMBOL_SIZE = constants.SYMBOL_SIZE;
      var SYMBOL_STROKE = constants.SYMBOL_STROKE;
      var SYMBOL_SDF = {};
      var SYMBOL_SVG_CIRCLE = Drawing.symbolFuncs[0](SYMBOL_SIZE * 0.05);
      function getSymbolSdf(d, trace) {
        var symbol = d.mx;
        if (symbol === "circle") return null;
        var symbolPath, symbolSdf;
        var symbolNumber = Drawing.symbolNumber(symbol);
        var symbolFunc = Drawing.symbolFuncs[symbolNumber % 100];
        var symbolNoDot = !!Drawing.symbolNoDot[symbolNumber % 100];
        var symbolNoFill = !!Drawing.symbolNoFill[symbolNumber % 100];
        var isDot = helpers.isDotSymbol(symbol);
        if (d.ma) symbol += "_" + d.ma;
        if (SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol];
        var angle = Drawing.getMarkerAngle(d, trace);
        if (isDot && !symbolNoDot) {
          symbolPath = symbolFunc(SYMBOL_SIZE * 1.1, angle) + SYMBOL_SVG_CIRCLE;
        } else {
          symbolPath = symbolFunc(SYMBOL_SIZE, angle);
        }
        symbolSdf = svgSdf(symbolPath, {
          w: SYMBOL_SDF_SIZE,
          h: SYMBOL_SDF_SIZE,
          viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE],
          stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE
        });
        SYMBOL_SDF[symbol] = symbolSdf;
        return symbolSdf || null;
      }
      function convertLinePositions(gd, trace, positions) {
        var len = positions.length;
        var count = len / 2;
        var linePositions;
        var i;
        if (subTypes.hasLines(trace) && count) {
          if (trace.line.shape === "hv") {
            linePositions = [];
            for (i = 0; i < count - 1; i++) {
              if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                linePositions.push(NaN, NaN, NaN, NaN);
              } else {
                linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
                  linePositions.push(positions[i * 2 + 2], positions[i * 2 + 1]);
                } else {
                  linePositions.push(NaN, NaN);
                }
              }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
          } else if (trace.line.shape === "hvh") {
            linePositions = [];
            for (i = 0; i < count - 1; i++) {
              if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
                if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
                  linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                } else {
                  linePositions.push(NaN, NaN);
                }
                linePositions.push(NaN, NaN);
              } else {
                var midPtX = (positions[i * 2] + positions[i * 2 + 2]) / 2;
                linePositions.push(
                  positions[i * 2],
                  positions[i * 2 + 1],
                  midPtX,
                  positions[i * 2 + 1],
                  midPtX,
                  positions[i * 2 + 3]
                );
              }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
          } else if (trace.line.shape === "vhv") {
            linePositions = [];
            for (i = 0; i < count - 1; i++) {
              if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) {
                if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) {
                  linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                } else {
                  linePositions.push(NaN, NaN);
                }
                linePositions.push(NaN, NaN);
              } else {
                var midPtY = (positions[i * 2 + 1] + positions[i * 2 + 3]) / 2;
                linePositions.push(
                  positions[i * 2],
                  positions[i * 2 + 1],
                  positions[i * 2],
                  midPtY,
                  positions[i * 2 + 2],
                  midPtY
                );
              }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
          } else if (trace.line.shape === "vh") {
            linePositions = [];
            for (i = 0; i < count - 1; i++) {
              if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) {
                linePositions.push(NaN, NaN, NaN, NaN);
              } else {
                linePositions.push(positions[i * 2], positions[i * 2 + 1]);
                if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) {
                  linePositions.push(positions[i * 2], positions[i * 2 + 3]);
                } else {
                  linePositions.push(NaN, NaN);
                }
              }
            }
            linePositions.push(positions[len - 2], positions[len - 1]);
          } else {
            linePositions = positions;
          }
        }
        var hasNaN = false;
        for (i = 0; i < linePositions.length; i++) {
          if (isNaN(linePositions[i])) {
            hasNaN = true;
            break;
          }
        }
        var join = hasNaN || linePositions.length > constants.TOO_MANY_POINTS ? "rect" : subTypes.hasMarkers(trace) ? "rect" : "round";
        if (hasNaN && trace.connectgaps) {
          var lastX = linePositions[0];
          var lastY = linePositions[1];
          for (i = 0; i < linePositions.length; i += 2) {
            if (isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) {
              linePositions[i] = lastX;
              linePositions[i + 1] = lastY;
            } else {
              lastX = linePositions[i];
              lastY = linePositions[i + 1];
            }
          }
        }
        return {
          join,
          positions: linePositions
        };
      }
      function convertErrorBarPositions(gd, trace, positions, x, y) {
        var makeComputeError = Registry.getComponentMethod("errorbars", "makeComputeError");
        var xa = AxisIDs.getFromId(gd, trace.xaxis, "x");
        var ya = AxisIDs.getFromId(gd, trace.yaxis, "y");
        var count = positions.length / 2;
        var out = {};
        function convertOneAxis(coords, ax) {
          var axLetter = ax._id.charAt(0);
          var opts = trace["error_" + axLetter];
          if (opts && opts.visible && (ax.type === "linear" || ax.type === "log")) {
            var computeError = makeComputeError(opts);
            var pOffset = { x: 0, y: 1 }[axLetter];
            var eOffset = { x: [0, 1, 2, 3], y: [2, 3, 0, 1] }[axLetter];
            var errors = new Float64Array(4 * count);
            var minShoe = Infinity;
            var maxHat = -Infinity;
            for (var i = 0, j = 0; i < count; i++, j += 4) {
              var dc = coords[i];
              if (isNumeric(dc)) {
                var dl = positions[i * 2 + pOffset];
                var vals = computeError(dc, i);
                var lv = vals[0];
                var hv = vals[1];
                if (isNumeric(lv) && isNumeric(hv)) {
                  var shoe = dc - lv;
                  var hat = dc + hv;
                  errors[j + eOffset[0]] = dl - ax.c2l(shoe);
                  errors[j + eOffset[1]] = ax.c2l(hat) - dl;
                  errors[j + eOffset[2]] = 0;
                  errors[j + eOffset[3]] = 0;
                  minShoe = Math.min(minShoe, dc - lv);
                  maxHat = Math.max(maxHat, dc + hv);
                }
              }
            }
            out[axLetter] = {
              positions,
              errors,
              _bnds: [minShoe, maxHat]
            };
          }
        }
        convertOneAxis(x, xa);
        convertOneAxis(y, ya);
        return out;
      }
      function convertTextPosition(gd, trace, textOpts, markerOpts) {
        var count = trace._length;
        var out = {};
        var i;
        if (subTypes.hasMarkers(trace)) {
          var fontOpts = textOpts.font;
          var align = textOpts.align;
          var baseline = textOpts.baseline;
          out.offset = new Array(count);
          for (i = 0; i < count; i++) {
            var ms = markerOpts.sizes ? markerOpts.sizes[i] : markerOpts.size;
            var fs = isArrayOrTypedArray(fontOpts) ? fontOpts[i].size : fontOpts.size;
            var a = isArrayOrTypedArray(align) ? align.length > 1 ? align[i] : align[0] : align;
            var b = isArrayOrTypedArray(baseline) ? baseline.length > 1 ? baseline[i] : baseline[0] : baseline;
            var hSign = TEXTOFFSETSIGN[a];
            var vSign = TEXTOFFSETSIGN[b];
            var xPad = ms ? ms / 0.8 + 1 : 0;
            var yPad = -vSign * xPad - vSign * 0.5;
            out.offset[i] = [hSign * xPad / fs, yPad / fs];
          }
        }
        return out;
      }
      module.exports = {
        style: convertStyle,
        markerStyle: convertMarkerStyle,
        markerSelection: convertMarkerSelection,
        linePositions: convertLinePositions,
        errorBarPositions: convertErrorBarPositions,
        textPosition: convertTextPosition
      };
    }
  });

  // src/traces/scattergl/scene_update.js
  var require_scene_update = __commonJS({
    "src/traces/scattergl/scene_update.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function sceneUpdate(gd, subplot) {
        var scene = subplot._scene;
        var resetOpts = {
          // number of traces in subplot, since scene:subplot -> 1:1
          count: 0,
          // whether scene requires init hook in plot call (dirty plot call)
          dirty: true,
          // last used options
          lineOptions: [],
          fillOptions: [],
          markerOptions: [],
          markerSelectedOptions: [],
          markerUnselectedOptions: [],
          errorXOptions: [],
          errorYOptions: [],
          textOptions: [],
          textSelectedOptions: [],
          textUnselectedOptions: [],
          // selection batches
          selectBatch: [],
          unselectBatch: []
        };
        var initOpts = {
          fill2d: false,
          scatter2d: false,
          error2d: false,
          line2d: false,
          glText: false,
          select2d: false
        };
        if (!subplot._scene) {
          scene = subplot._scene = {};
          scene.init = function init() {
            Lib.extendFlat(scene, initOpts, resetOpts);
          };
          scene.init();
          scene.update = function update(opt) {
            var opts = Lib.repeat(opt, scene.count);
            if (scene.fill2d) scene.fill2d.update(opts);
            if (scene.scatter2d) scene.scatter2d.update(opts);
            if (scene.line2d) scene.line2d.update(opts);
            if (scene.error2d) scene.error2d.update(opts.concat(opts));
            if (scene.select2d) scene.select2d.update(opts);
            if (scene.glText) {
              for (var i = 0; i < scene.count; i++) {
                scene.glText[i].update(opt);
              }
            }
          };
          scene.draw = function draw() {
            var count = scene.count;
            var fill2d = scene.fill2d;
            var error2d = scene.error2d;
            var line2d = scene.line2d;
            var scatter2d = scene.scatter2d;
            var glText = scene.glText;
            var select2d = scene.select2d;
            var selectBatch = scene.selectBatch;
            var unselectBatch = scene.unselectBatch;
            for (var i = 0; i < count; i++) {
              if (fill2d && scene.fillOrder[i]) {
                fill2d.draw(scene.fillOrder[i]);
              }
              if (line2d && scene.lineOptions[i]) {
                line2d.draw(i);
              }
              if (error2d) {
                if (scene.errorXOptions[i]) error2d.draw(i);
                if (scene.errorYOptions[i]) error2d.draw(i + count);
              }
              if (scatter2d && scene.markerOptions[i]) {
                if (unselectBatch[i].length) {
                  var arg = Lib.repeat([], scene.count);
                  arg[i] = unselectBatch[i];
                  scatter2d.draw(arg);
                } else if (!selectBatch[i].length) {
                  scatter2d.draw(i);
                }
              }
              if (glText[i] && scene.textOptions[i]) {
                glText[i].render();
              }
            }
            if (select2d) {
              select2d.draw(selectBatch);
            }
            scene.dirty = false;
          };
          scene.destroy = function destroy() {
            if (scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy();
            if (scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy();
            if (scene.error2d && scene.error2d.destroy) scene.error2d.destroy();
            if (scene.line2d && scene.line2d.destroy) scene.line2d.destroy();
            if (scene.select2d && scene.select2d.destroy) scene.select2d.destroy();
            if (scene.glText) {
              scene.glText.forEach(function(text) {
                if (text.destroy) text.destroy();
              });
            }
            scene.lineOptions = null;
            scene.fillOptions = null;
            scene.markerOptions = null;
            scene.markerSelectedOptions = null;
            scene.markerUnselectedOptions = null;
            scene.errorXOptions = null;
            scene.errorYOptions = null;
            scene.textOptions = null;
            scene.textSelectedOptions = null;
            scene.textUnselectedOptions = null;
            scene.selectBatch = null;
            scene.unselectBatch = null;
            subplot._scene = null;
          };
        }
        if (!scene.dirty) {
          Lib.extendFlat(scene, resetOpts);
        }
        return scene;
      };
    }
  });

  // src/traces/scattergl/calc.js
  var require_calc29 = __commonJS({
    "src/traces/scattergl/calc.js"(exports, module) {
      "use strict";
      var cluster = require_point_cluster();
      var Lib = require_lib();
      var AxisIDs = require_axis_ids();
      var findExtremes = require_autorange().findExtremes;
      var alignPeriod = require_align_period();
      var scatterCalc = require_calc3();
      var calcMarkerSize = scatterCalc.calcMarkerSize;
      var calcAxisExpansion = scatterCalc.calcAxisExpansion;
      var setFirstScatter = scatterCalc.setFirstScatter;
      var calcColorscale = require_colorscale_calc();
      var convert = require_convert10();
      var sceneUpdate = require_scene_update();
      var BADNUM = require_numerical().BADNUM;
      var TOO_MANY_POINTS = require_constants23().TOO_MANY_POINTS;
      module.exports = function calc(gd, trace) {
        var fullLayout = gd._fullLayout;
        var xa = trace._xA = AxisIDs.getFromId(gd, trace.xaxis, "x");
        var ya = trace._yA = AxisIDs.getFromId(gd, trace.yaxis, "y");
        var subplot = fullLayout._plots[trace.xaxis + trace.yaxis];
        var len = trace._length;
        var hasTooManyPoints = len >= TOO_MANY_POINTS;
        var len2 = len * 2;
        var stash = {};
        var i;
        var origX = xa.makeCalcdata(trace, "x");
        var origY = ya.makeCalcdata(trace, "y");
        var xObj = alignPeriod(trace, xa, "x", origX);
        var yObj = alignPeriod(trace, ya, "y", origY);
        var x = xObj.vals;
        var y = yObj.vals;
        trace._x = x;
        trace._y = y;
        if (trace.xperiodalignment) {
          trace._origX = origX;
          trace._xStarts = xObj.starts;
          trace._xEnds = xObj.ends;
        }
        if (trace.yperiodalignment) {
          trace._origY = origY;
          trace._yStarts = yObj.starts;
          trace._yEnds = yObj.ends;
        }
        var positions = new Array(len2);
        var _ids = new Array(len);
        for (i = 0; i < len; i++) {
          positions[i * 2] = x[i] === BADNUM ? NaN : x[i];
          positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i];
          _ids[i] = i;
        }
        if (xa.type === "log") {
          for (i = 0; i < len2; i += 2) {
            positions[i] = xa.c2l(positions[i]);
          }
        }
        if (ya.type === "log") {
          for (i = 1; i < len2; i += 2) {
            positions[i] = ya.c2l(positions[i]);
          }
        }
        if (hasTooManyPoints && (xa.type !== "log" && ya.type !== "log")) {
          stash.tree = cluster(positions);
        } else {
          stash.ids = _ids;
        }
        calcColorscale(gd, trace);
        var opts = sceneOptions(gd, subplot, trace, positions, x, y);
        var scene = sceneUpdate(gd, subplot);
        setFirstScatter(fullLayout, trace);
        var ppad;
        if (!hasTooManyPoints) {
          ppad = calcMarkerSize(trace, len);
        } else if (opts.marker) {
          ppad = opts.marker.sizeAvg || Math.max(opts.marker.size, 3);
        }
        calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
        if (opts.errorX) expandForErrorBars(trace, xa, opts.errorX);
        if (opts.errorY) expandForErrorBars(trace, ya, opts.errorY);
        if (opts.fill && !scene.fill2d) scene.fill2d = true;
        if (opts.marker && !scene.scatter2d) scene.scatter2d = true;
        if (opts.line && !scene.line2d) scene.line2d = true;
        if ((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true;
        if (opts.text && !scene.glText) scene.glText = true;
        if (opts.marker) opts.marker.snap = len;
        scene.lineOptions.push(opts.line);
        scene.errorXOptions.push(opts.errorX);
        scene.errorYOptions.push(opts.errorY);
        scene.fillOptions.push(opts.fill);
        scene.markerOptions.push(opts.marker);
        scene.markerSelectedOptions.push(opts.markerSel);
        scene.markerUnselectedOptions.push(opts.markerUnsel);
        scene.textOptions.push(opts.text);
        scene.textSelectedOptions.push(opts.textSel);
        scene.textUnselectedOptions.push(opts.textUnsel);
        scene.selectBatch.push([]);
        scene.unselectBatch.push([]);
        stash._scene = scene;
        stash.index = scene.count;
        stash.x = x;
        stash.y = y;
        stash.positions = positions;
        scene.count++;
        return [{ x: false, y: false, t: stash, trace }];
      };
      function expandForErrorBars(trace, ax, opts) {
        var extremes = trace._extremes[ax._id];
        var errExt = findExtremes(ax, opts._bnds, { padded: true });
        extremes.min = extremes.min.concat(errExt.min);
        extremes.max = extremes.max.concat(errExt.max);
      }
      function sceneOptions(gd, subplot, trace, positions, x, y) {
        var opts = convert.style(gd, trace);
        if (opts.marker) {
          opts.marker.positions = positions;
        }
        if (opts.line && positions.length > 1) {
          Lib.extendFlat(
            opts.line,
            convert.linePositions(gd, trace, positions)
          );
        }
        if (opts.errorX || opts.errorY) {
          var errors = convert.errorBarPositions(gd, trace, positions, x, y);
          if (opts.errorX) {
            Lib.extendFlat(opts.errorX, errors.x);
          }
          if (opts.errorY) {
            Lib.extendFlat(opts.errorY, errors.y);
          }
        }
        if (opts.text) {
          Lib.extendFlat(
            opts.text,
            { positions },
            convert.textPosition(gd, trace, opts.text, opts.marker)
          );
          Lib.extendFlat(
            opts.textSel,
            { positions },
            convert.textPosition(gd, trace, opts.text, opts.markerSel)
          );
          Lib.extendFlat(
            opts.textUnsel,
            { positions },
            convert.textPosition(gd, trace, opts.text, opts.markerUnsel)
          );
        }
        return opts;
      }
    }
  });

  // src/traces/scattergl/edit_style.js
  var require_edit_style = __commonJS({
    "src/traces/scattergl/edit_style.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var DESELECTDIM = require_interactions().DESELECTDIM;
      function styleTextSelection(cd) {
        var cd0 = cd[0];
        var trace = cd0.trace;
        var stash = cd0.t;
        var scene = stash._scene;
        var index = stash.index;
        var els = scene.selectBatch[index];
        var unels = scene.unselectBatch[index];
        var baseOpts = scene.textOptions[index];
        var selOpts = scene.textSelectedOptions[index] || {};
        var unselOpts = scene.textUnselectedOptions[index] || {};
        var opts = Lib.extendFlat({}, baseOpts);
        var i, j;
        if (els.length || unels.length) {
          var stc = selOpts.color;
          var utc = unselOpts.color;
          var base = baseOpts.color;
          var hasArrayBase = Lib.isArrayOrTypedArray(base);
          opts.color = new Array(trace._length);
          for (i = 0; i < els.length; i++) {
            j = els[i];
            opts.color[j] = stc || (hasArrayBase ? base[j] : base);
          }
          for (i = 0; i < unels.length; i++) {
            j = unels[i];
            var basej = hasArrayBase ? base[j] : base;
            opts.color[j] = utc ? utc : stc ? basej : Color2.addOpacity(basej, DESELECTDIM);
          }
        }
        scene.glText[index].update(opts);
      }
      module.exports = {
        styleTextSelection
      };
    }
  });

  // src/traces/scattergl/select.js
  var require_select7 = __commonJS({
    "src/traces/scattergl/select.js"(exports, module) {
      "use strict";
      var subTypes = require_subtypes();
      var styleTextSelection = require_edit_style().styleTextSelection;
      module.exports = function select(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var trace = cd[0].trace;
        var stash = cd[0].t;
        var len = trace._length;
        var x = stash.x;
        var y = stash.y;
        var scene = stash._scene;
        var index = stash.index;
        if (!scene) return selection;
        var hasText = subTypes.hasText(trace);
        var hasMarkers = subTypes.hasMarkers(trace);
        var hasOnlyLines = !hasMarkers && !hasText;
        if (trace.visible !== true || hasOnlyLines) return selection;
        var els = [];
        var unels = [];
        if (selectionTester !== false && !selectionTester.degenerate) {
          for (var i = 0; i < len; i++) {
            if (selectionTester.contains([stash.xpx[i], stash.ypx[i]], false, i, searchInfo)) {
              els.push(i);
              selection.push({
                pointNumber: i,
                x: xa.c2d(x[i]),
                y: ya.c2d(y[i])
              });
            } else {
              unels.push(i);
            }
          }
        }
        if (hasMarkers) {
          var scatter2d = scene.scatter2d;
          if (!els.length && !unels.length) {
            var baseOpts = new Array(scene.count);
            baseOpts[index] = scene.markerOptions[index];
            scatter2d.update.apply(scatter2d, baseOpts);
          } else if (!scene.selectBatch[index].length && !scene.unselectBatch[index].length) {
            var unselOpts = new Array(scene.count);
            unselOpts[index] = scene.markerUnselectedOptions[index];
            scatter2d.update.apply(scatter2d, unselOpts);
          }
        }
        scene.selectBatch[index] = els;
        scene.unselectBatch[index] = unels;
        if (hasText) {
          styleTextSelection(cd);
        }
        return selection;
      };
    }
  });

  // src/traces/scattergl/base_index.js
  var require_base_index = __commonJS({
    "src/traces/scattergl/base_index.js"(exports, module) {
      "use strict";
      var hover = require_hover16();
      module.exports = {
        moduleType: "trace",
        name: "scattergl",
        basePlotModule: require_cartesian(),
        categories: ["gl", "regl", "cartesian", "symbols", "errorBarsOK", "showLegend", "scatter-like"],
        attributes: require_attributes50(),
        supplyDefaults: require_defaults46(),
        crossTraceDefaults: require_cross_trace_defaults2(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels4(),
        calc: require_calc29(),
        hoverPoints: hover.hoverPoints,
        selectPoints: require_select7(),
        meta: {}
      };
    }
  });

  // node_modules/color-id/index.js
  var require_color_id = __commonJS({
    "node_modules/color-id/index.js"(exports, module) {
      "use strict";
      var clamp = require_clamp();
      module.exports = toNumber;
      module.exports.to = toNumber;
      module.exports.from = fromNumber;
      function toNumber(rgba3, normalized) {
        if (normalized == null) normalized = true;
        var r = rgba3[0], g = rgba3[1], b = rgba3[2], a = rgba3[3];
        if (a == null) a = normalized ? 1 : 255;
        if (normalized) {
          r *= 255;
          g *= 255;
          b *= 255;
          a *= 255;
        }
        r = clamp(r, 0, 255) & 255;
        g = clamp(g, 0, 255) & 255;
        b = clamp(b, 0, 255) & 255;
        a = clamp(a, 0, 255) & 255;
        var n = r * 16777216 + (g << 16) + (b << 8) + a;
        return n;
      }
      function fromNumber(n, normalized) {
        n = +n;
        var r = n >>> 24;
        var g = (n & 16711680) >>> 16;
        var b = (n & 65280) >>> 8;
        var a = n & 255;
        if (normalized === false) return [r, g, b, a];
        return [r / 255, g / 255, b / 255, a / 255];
      }
    }
  });

  // node_modules/object-assign/index.js
  var require_object_assign = __commonJS({
    "node_modules/object-assign/index.js"(exports, module) {
      "use strict";
      var getOwnPropertySymbols = Object.getOwnPropertySymbols;
      var hasOwnProperty2 = Object.prototype.hasOwnProperty;
      var propIsEnumerable = Object.prototype.propertyIsEnumerable;
      function toObject(val) {
        if (val === null || val === void 0) {
          throw new TypeError("Object.assign cannot be called with null or undefined");
        }
        return Object(val);
      }
      function shouldUseNative() {
        try {
          if (!Object.assign) {
            return false;
          }
          var test1 = new String("abc");
          test1[5] = "de";
          if (Object.getOwnPropertyNames(test1)[0] === "5") {
            return false;
          }
          var test2 = {};
          for (var i = 0; i < 10; i++) {
            test2["_" + String.fromCharCode(i)] = i;
          }
          var order2 = Object.getOwnPropertyNames(test2).map(function(n) {
            return test2[n];
          });
          if (order2.join("") !== "0123456789") {
            return false;
          }
          var test3 = {};
          "abcdefghijklmnopqrst".split("").forEach(function(letter) {
            test3[letter] = letter;
          });
          if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
            return false;
          }
          return true;
        } catch (err) {
          return false;
        }
      }
      module.exports = shouldUseNative() ? Object.assign : function(target, source) {
        var from;
        var to = toObject(target);
        var symbols;
        for (var s = 1; s < arguments.length; s++) {
          from = Object(arguments[s]);
          for (var key in from) {
            if (hasOwnProperty2.call(from, key)) {
              to[key] = from[key];
            }
          }
          if (getOwnPropertySymbols) {
            symbols = getOwnPropertySymbols(from);
            for (var i = 0; i < symbols.length; i++) {
              if (propIsEnumerable.call(from, symbols[i])) {
                to[symbols[i]] = from[symbols[i]];
              }
            }
          }
        }
        return to;
      };
    }
  });

  // node_modules/glslify/browser.js
  var require_browser3 = __commonJS({
    "node_modules/glslify/browser.js"(exports, module) {
      module.exports = function(strings) {
        if (typeof strings === "string") strings = [strings];
        var exprs = [].slice.call(arguments, 1);
        var parts = [];
        for (var i = 0; i < strings.length - 1; i++) {
          parts.push(strings[i], exprs[i] || "");
        }
        parts.push(strings[i]);
        return parts.join("");
      };
    }
  });

  // node_modules/update-diff/index.js
  var require_update_diff = __commonJS({
    "node_modules/update-diff/index.js"(exports, module) {
      "use strict";
      module.exports = function updateDiff(obj, diff, mappers) {
        if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2);
        for (var i = 0, l = mappers.length; i < l; i++) {
          var dict = mappers[i];
          for (var prop in dict) {
            if (diff[prop] !== void 0 && !Array.isArray(diff[prop]) && obj[prop] === diff[prop]) continue;
            if (prop in diff) {
              var result;
              if (dict[prop] === true) result = diff[prop];
              else if (dict[prop] === false) continue;
              else if (typeof dict[prop] === "function") {
                result = dict[prop](diff[prop], obj, diff);
                if (result === void 0) continue;
              }
              obj[prop] = result;
            }
          }
        }
        return obj;
      };
    }
  });

  // node_modules/is-iexplorer/index.js
  var require_is_iexplorer = __commonJS({
    "node_modules/is-iexplorer/index.js"(exports, module) {
      "use strict";
      module.exports = typeof navigator !== "undefined" && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion));
    }
  });

  // node_modules/to-float32/index.js
  var require_to_float32 = __commonJS({
    "node_modules/to-float32/index.js"(exports, module) {
      "use strict";
      module.exports = float32;
      module.exports.float32 = module.exports.float = float32;
      module.exports.fract32 = module.exports.fract = fract32;
      var narr = new Float32Array(1);
      function fract32(arr, fract) {
        if (arr.length) {
          if (arr instanceof Float32Array) return new Float32Array(arr.length);
          if (!(fract instanceof Float32Array)) fract = float32(arr);
          for (var i = 0, l = fract.length; i < l; i++) {
            fract[i] = arr[i] - fract[i];
          }
          return fract;
        }
        return float32(arr - float32(arr));
      }
      function float32(arr) {
        if (arr.length) {
          if (arr instanceof Float32Array) return arr;
          return new Float32Array(arr);
        }
        narr[0] = arr;
        return narr[0];
      }
    }
  });

  // node_modules/regl-scatter2d/bundle.js
  var require_bundle = __commonJS({
    "node_modules/regl-scatter2d/bundle.js"(exports, module) {
      "use strict";
      function _iterableToArrayLimit(arr, i) {
        var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
        if (null != _i) {
          var _s, _e, _x, _r, _arr = [], _n = true, _d = false;
          try {
            if (_x = (_i = _i.call(arr)).next, 0 === i) {
              if (Object(_i) !== _i) return;
              _n = false;
            } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = true) ;
          } catch (err) {
            _d = true, _e = err;
          } finally {
            try {
              if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
            } finally {
              if (_d) throw _e;
            }
          }
          return _arr;
        }
      }
      function _slicedToArray(arr, i) {
        return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
      }
      function _toConsumableArray(arr) {
        return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
      }
      function _arrayWithoutHoles(arr) {
        if (Array.isArray(arr)) return _arrayLikeToArray(arr);
      }
      function _arrayWithHoles(arr) {
        if (Array.isArray(arr)) return arr;
      }
      function _iterableToArray(iter) {
        if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
      }
      function _unsupportedIterableToArray(o, minLen) {
        if (!o) return;
        if (typeof o === "string") return _arrayLikeToArray(o, minLen);
        var n = Object.prototype.toString.call(o).slice(8, -1);
        if (n === "Object" && o.constructor) n = o.constructor.name;
        if (n === "Map" || n === "Set") return Array.from(o);
        if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
      }
      function _arrayLikeToArray(arr, len) {
        if (len == null || len > arr.length) len = arr.length;
        for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
        return arr2;
      }
      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 _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.");
      }
      var rgba3 = require_color_normalize();
      var getBounds = require_array_bounds();
      var colorId = require_color_id();
      var cluster = require_point_cluster();
      var extend2 = require_object_assign();
      var glslify = require_browser3();
      var pick = require_pick_by_alias();
      var updateDiff = require_update_diff();
      var flatten = require_flatten_vertex_data();
      var ie = require_is_iexplorer();
      var f32 = require_to_float32();
      var parseRect = require_parse_rect();
      var scatter = Scatter;
      function Scatter(regl, options) {
        var _this = this;
        if (!(this instanceof Scatter)) return new Scatter(regl, options);
        if (typeof regl === "function") {
          if (!options) options = {};
          options.regl = regl;
        } else {
          options = regl;
          regl = null;
        }
        if (options && options.length) options.positions = options;
        regl = options.regl;
        var gl2 = regl._gl, paletteTexture, palette = [], paletteIds = {}, groups = [], markerTextures = [null], markerCache = [null];
        var maxColors = 255, maxSize = 100;
        this.tooManyColors = ie;
        paletteTexture = regl.texture({
          data: new Uint8Array(maxColors * 4),
          width: maxColors,
          height: 1,
          type: "uint8",
          format: "rgba",
          wrapS: "clamp",
          wrapT: "clamp",
          mag: "nearest",
          min: "nearest"
        });
        extend2(this, {
          regl,
          gl: gl2,
          groups,
          markerCache,
          markerTextures,
          palette,
          paletteIds,
          paletteTexture,
          maxColors,
          maxSize,
          canvas: gl2.canvas
        });
        this.update(options);
        var shaderOptions = {
          uniforms: {
            constPointSize: !!options.constPointSize,
            opacity: regl.prop("opacity"),
            paletteSize: function paletteSize(ctx, prop) {
              return [_this.tooManyColors ? 0 : maxColors, paletteTexture.height];
            },
            pixelRatio: regl.context("pixelRatio"),
            scale: regl.prop("scale"),
            scaleFract: regl.prop("scaleFract"),
            translate: regl.prop("translate"),
            translateFract: regl.prop("translateFract"),
            markerTexture: regl.prop("markerTexture"),
            paletteTexture
          },
          attributes: {
            // FIXME: optimize these parts
            x: function x(ctx, prop) {
              return prop.xAttr || {
                buffer: prop.positionBuffer,
                stride: 8,
                offset: 0
              };
            },
            y: function y(ctx, prop) {
              return prop.yAttr || {
                buffer: prop.positionBuffer,
                stride: 8,
                offset: 4
              };
            },
            xFract: function xFract(ctx, prop) {
              return prop.xAttr ? {
                constant: [0, 0]
              } : {
                buffer: prop.positionFractBuffer,
                stride: 8,
                offset: 0
              };
            },
            yFract: function yFract(ctx, prop) {
              return prop.yAttr ? {
                constant: [0, 0]
              } : {
                buffer: prop.positionFractBuffer,
                stride: 8,
                offset: 4
              };
            },
            size: function size(ctx, prop) {
              return prop.size.length ? {
                buffer: prop.sizeBuffer,
                stride: 2,
                offset: 0
              } : {
                constant: [Math.round(prop.size * 255 / _this.maxSize)]
              };
            },
            borderSize: function borderSize(ctx, prop) {
              return prop.borderSize.length ? {
                buffer: prop.sizeBuffer,
                stride: 2,
                offset: 1
              } : {
                constant: [Math.round(prop.borderSize * 255 / _this.maxSize)]
              };
            },
            colorId: function colorId2(ctx, prop) {
              return prop.color.length ? {
                buffer: prop.colorBuffer,
                stride: _this.tooManyColors ? 8 : 4,
                offset: 0
              } : {
                constant: _this.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [prop.color]
              };
            },
            borderColorId: function borderColorId(ctx, prop) {
              return prop.borderColor.length ? {
                buffer: prop.colorBuffer,
                stride: _this.tooManyColors ? 8 : 4,
                offset: _this.tooManyColors ? 4 : 2
              } : {
                constant: _this.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [prop.borderColor]
              };
            },
            isActive: function isActive(ctx, prop) {
              return prop.activation === true ? {
                constant: [1]
              } : prop.activation ? prop.activation : {
                constant: [0]
              };
            }
          },
          blend: {
            enable: true,
            color: [0, 0, 0, 1],
            // photoshop blending
            func: {
              srcRGB: "src alpha",
              dstRGB: "one minus src alpha",
              srcAlpha: "one minus dst alpha",
              dstAlpha: "one"
            }
          },
          scissor: {
            enable: true,
            box: regl.prop("viewport")
          },
          viewport: regl.prop("viewport"),
          stencil: {
            enable: false
          },
          depth: {
            enable: false
          },
          elements: regl.prop("elements"),
          count: regl.prop("count"),
          offset: regl.prop("offset"),
          primitive: "points"
        };
        var markerOptions = extend2({}, shaderOptions);
        markerOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\nuniform sampler2D markerTexture;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nfloat smoothStep(float x, float y) {\n  return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n  float dist = texture2D(markerTexture, gl_PointCoord).r, delta = fragWidth;\n\n  // max-distance alpha\n  if (dist < 0.003) discard;\n\n  // null-border case\n  if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n    float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n    gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n  }\n  else {\n    float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n    float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n    vec4 color = fragBorderColor;\n    color.a *= borderColorAmt;\n    color = mix(color, fragColor, colorAmt);\n    color.a *= opacity;\n\n    gl_FragColor = color;\n  }\n\n}\n"]);
        markerOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\n// `invariant` effectively turns off optimizations for the position.\n// We need this because -fast-math on M1 Macs is re-ordering\n// floating point operations in a way that causes floating point\n// precision limits to put points in the wrong locations.\ninvariant gl_Position;\n\nuniform bool constPointSize;\nuniform float pixelRatio;\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform sampler2D paletteTexture;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius, fragWidth, fragBorderColorLevel, fragColorLevel;\n\nfloat pointSizeScale = (constPointSize) ? 2. : pixelRatio;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(paletteTexture,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  // ignore inactive points\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = 2. * size * pointSizeScale;\n  fragPointSize = size * pixelRatio;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0., 1.);\n\n  fragColor = color;\n  fragBorderColor = borderColor;\n  fragWidth = 1. / gl_PointSize;\n\n  fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n  fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]);
        this.drawMarker = regl(markerOptions);
        var circleOptions = extend2({}, shaderOptions);
        circleOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nuniform float opacity;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n	float t;\n	t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n	return t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n	float radius, alpha = 1.0, delta = fragWidth;\n\n	radius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n	if (radius > 1.0 + delta) {\n		discard;\n	}\n\n	alpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n	float borderRadius = fragBorderRadius;\n	float ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n	vec4 color = mix(fragColor, fragBorderColor, ratio);\n	color.a *= alpha * opacity;\n	gl_FragColor = color;\n}\n"]);
        circleOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\n// `invariant` effectively turns off optimizations for the position.\n// We need this because -fast-math on M1 Macs is re-ordering\n// floating point operations in a way that causes floating point\n// precision limits to put points in the wrong locations.\ninvariant gl_Position;\n\nuniform bool constPointSize;\nuniform float pixelRatio;\nuniform vec2 paletteSize, scale, scaleFract, translate, translateFract;\nuniform sampler2D paletteTexture;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nfloat pointSizeScale = (constPointSize) ? 2. : pixelRatio;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n  return isDirect ? id / 255. : texture2D(paletteTexture,\n    vec2(\n      (id.x + .5) / paletteSize.x,\n      (id.y + .5) / paletteSize.y\n    )\n  );\n}\n\nvoid main() {\n  // ignore inactive points\n  if (isActive == 0.) return;\n\n  vec2 position = vec2(x, y);\n  vec2 positionFract = vec2(xFract, yFract);\n\n  vec4 color = getColor(colorId);\n  vec4 borderColor = getColor(borderColorId);\n\n  float size = size * maxSize / 255.;\n  float borderSize = borderSize * maxSize / 255.;\n\n  gl_PointSize = (size + borderSize) * pointSizeScale;\n\n  vec2 pos = (position + translate) * scale\n      + (positionFract + translateFract) * scale\n      + (position + translate) * scaleFract\n      + (positionFract + translateFract) * scaleFract;\n\n  gl_Position = vec4(pos * 2. - 1., 0., 1.);\n\n  fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n  fragColor = color;\n  fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n  fragWidth = 1. / gl_PointSize;\n}\n"]);
        if (ie) {
          circleOptions.frag = circleOptions.frag.replace("smoothstep", "smoothStep");
          markerOptions.frag = markerOptions.frag.replace("smoothstep", "smoothStep");
        }
        this.drawCircle = regl(circleOptions);
      }
      Scatter.defaults = {
        color: "black",
        borderColor: "transparent",
        borderSize: 0,
        size: 12,
        opacity: 1,
        marker: void 0,
        viewport: null,
        range: null,
        pixelSize: null,
        count: 0,
        offset: 0,
        bounds: null,
        positions: [],
        snap: 1e4
      };
      Scatter.prototype.render = function() {
        if (arguments.length) {
          this.update.apply(this, arguments);
        }
        this.draw();
        return this;
      };
      Scatter.prototype.draw = function() {
        var _this2 = this;
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        var groups = this.groups;
        if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) {
          args = args[0];
        }
        this.regl._refresh();
        if (args.length) {
          for (var i = 0; i < args.length; i++) {
            this.drawItem(i, args[i]);
          }
        } else {
          groups.forEach(function(group, i2) {
            _this2.drawItem(i2);
          });
        }
        return this;
      };
      Scatter.prototype.drawItem = function(id, els) {
        var groups = this.groups;
        var group = groups[id];
        if (typeof els === "number") {
          id = els;
          group = groups[els];
          els = null;
        }
        if (!(group && group.count && group.opacity)) return;
        if (group.activation[0]) {
          this.drawCircle(this.getMarkerDrawOptions(0, group, els));
        }
        var batch = [];
        for (var i = 1; i < group.activation.length; i++) {
          if (!group.activation[i] || group.activation[i] !== true && !group.activation[i].data.length) continue;
          batch.push.apply(batch, _toConsumableArray(this.getMarkerDrawOptions(i, group, els)));
        }
        if (batch.length) {
          this.drawMarker(batch);
        }
      };
      Scatter.prototype.getMarkerDrawOptions = function(markerId, group, elements) {
        var range = group.range, tree = group.tree, viewport = group.viewport, activation = group.activation, selectionBuffer = group.selectionBuffer, count = group.count;
        var regl = this.regl;
        if (!tree) {
          if (elements) {
            return [extend2({}, group, {
              markerTexture: this.markerTextures[markerId],
              activation: activation[markerId],
              count: elements.length,
              elements,
              offset: 0
            })];
          }
          return [extend2({}, group, {
            markerTexture: this.markerTextures[markerId],
            activation: activation[markerId],
            offset: 0
          })];
        }
        var batch = [];
        var lod = tree.range(range, {
          lod: true,
          px: [(range[2] - range[0]) / viewport.width, (range[3] - range[1]) / viewport.height]
        });
        if (elements) {
          var markerActivation = activation[markerId];
          var mask = markerActivation.data;
          var data = new Uint8Array(count);
          for (var i = 0; i < elements.length; i++) {
            var id = elements[i];
            data[id] = mask ? mask[id] : 1;
          }
          selectionBuffer.subdata(data);
        }
        for (var l = lod.length; l--; ) {
          var _lod$l = _slicedToArray(lod[l], 2), from = _lod$l[0], to = _lod$l[1];
          batch.push(extend2({}, group, {
            markerTexture: this.markerTextures[markerId],
            activation: elements ? selectionBuffer : activation[markerId],
            offset: from,
            count: to - from
          }));
        }
        return batch;
      };
      Scatter.prototype.update = function() {
        var _this3 = this;
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
        if (!args.length) return;
        if (args.length === 1 && Array.isArray(args[0])) args = args[0];
        var groups = this.groups, gl2 = this.gl, regl = this.regl, maxSize = this.maxSize, maxColors = this.maxColors, palette = this.palette;
        this.groups = groups = args.map(function(options, i) {
          var group = groups[i];
          if (options === void 0) return group;
          if (options === null) options = {
            positions: null
          };
          else if (typeof options === "function") options = {
            ondraw: options
          };
          else if (typeof options[0] === "number") options = {
            positions: options
          };
          options = pick(options, {
            positions: "positions data points",
            snap: "snap cluster lod tree",
            size: "sizes size radius",
            borderSize: "borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline",
            color: "colors color fill fill-color fillColor",
            borderColor: "borderColors borderColor stroke stroke-color strokeColor",
            marker: "markers marker shape",
            range: "range dataBox databox",
            viewport: "viewport viewPort viewBox viewbox",
            opacity: "opacity alpha transparency",
            bounds: "bound bounds boundaries limits",
            tooManyColors: "tooManyColors palette paletteMode optimizePalette enablePalette"
          });
          if (options.positions === null) options.positions = [];
          if (options.tooManyColors != null) _this3.tooManyColors = options.tooManyColors;
          if (!group) {
            groups[i] = group = {
              id: i,
              scale: null,
              translate: null,
              scaleFract: null,
              translateFract: null,
              // buffers for active markers
              activation: [],
              // buffer for filtered markers
              selectionBuffer: regl.buffer({
                data: new Uint8Array(0),
                usage: "stream",
                type: "uint8"
              }),
              // buffers with data: it is faster to switch them per-pass
              // than provide one congregate buffer
              sizeBuffer: regl.buffer({
                data: new Uint8Array(0),
                usage: "dynamic",
                type: "uint8"
              }),
              colorBuffer: regl.buffer({
                data: new Uint8Array(0),
                usage: "dynamic",
                type: "uint8"
              }),
              positionBuffer: regl.buffer({
                data: new Uint8Array(0),
                usage: "dynamic",
                type: "float"
              }),
              positionFractBuffer: regl.buffer({
                data: new Uint8Array(0),
                usage: "dynamic",
                type: "float"
              })
            };
            options = extend2({}, Scatter.defaults, options);
          }
          if (options.positions && !("marker" in options)) {
            options.marker = group.marker;
            delete group.marker;
          }
          if (options.marker && !("positions" in options)) {
            options.positions = group.positions;
            delete group.positions;
          }
          var hasSize = 0, hasColor = 0;
          updateDiff(group, options, [{
            snap: true,
            size: function size2(s, group2) {
              if (s == null) s = Scatter.defaults.size;
              hasSize += s && s.length ? 1 : 0;
              return s;
            },
            borderSize: function borderSize2(s, group2) {
              if (s == null) s = Scatter.defaults.borderSize;
              hasSize += s && s.length ? 1 : 0;
              return s;
            },
            opacity: parseFloat,
            // add colors to palette, save references
            color: function color3(c, group2) {
              if (c == null) c = Scatter.defaults.color;
              c = _this3.updateColor(c);
              hasColor++;
              return c;
            },
            borderColor: function borderColor2(c, group2) {
              if (c == null) c = Scatter.defaults.borderColor;
              c = _this3.updateColor(c);
              hasColor++;
              return c;
            },
            bounds: function bounds(_bounds, group2, options2) {
              if (!("range" in options2)) options2.range = null;
              return _bounds;
            },
            positions: function positions(_positions, group2, options2) {
              var snap = group2.snap;
              var positionBuffer = group2.positionBuffer, positionFractBuffer = group2.positionFractBuffer, selectionBuffer = group2.selectionBuffer;
              if (_positions.x || _positions.y) {
                if (_positions.x.length) {
                  group2.xAttr = {
                    buffer: regl.buffer(_positions.x),
                    offset: 0,
                    stride: 4,
                    count: _positions.x.length
                  };
                } else {
                  group2.xAttr = {
                    buffer: _positions.x.buffer,
                    offset: _positions.x.offset * 4 || 0,
                    stride: (_positions.x.stride || 1) * 4,
                    count: _positions.x.count
                  };
                }
                if (_positions.y.length) {
                  group2.yAttr = {
                    buffer: regl.buffer(_positions.y),
                    offset: 0,
                    stride: 4,
                    count: _positions.y.length
                  };
                } else {
                  group2.yAttr = {
                    buffer: _positions.y.buffer,
                    offset: _positions.y.offset * 4 || 0,
                    stride: (_positions.y.stride || 1) * 4,
                    count: _positions.y.count
                  };
                }
                group2.count = Math.max(group2.xAttr.count, group2.yAttr.count);
                return _positions;
              }
              _positions = flatten(_positions, "float64");
              var count2 = group2.count = Math.floor(_positions.length / 2);
              var bounds = group2.bounds = count2 ? getBounds(_positions, 2) : null;
              if (!options2.range && !group2.range) {
                delete group2.range;
                options2.range = bounds;
              }
              if (!options2.marker && !group2.marker) {
                delete group2.marker;
                options2.marker = null;
              }
              if (snap && (snap === true || count2 > snap)) {
                group2.tree = cluster(_positions, {
                  bounds
                });
              } else if (snap && snap.length) {
                group2.tree = snap;
              }
              if (group2.tree) {
                var opts = {
                  primitive: "points",
                  usage: "static",
                  data: group2.tree,
                  type: "uint32"
                };
                if (group2.elements) group2.elements(opts);
                else group2.elements = regl.elements(opts);
              }
              var float_data = f32.float32(_positions);
              positionBuffer({
                data: float_data,
                usage: "dynamic"
              });
              var frac_data = f32.fract32(_positions, float_data);
              positionFractBuffer({
                data: frac_data,
                usage: "dynamic"
              });
              selectionBuffer({
                data: new Uint8Array(count2),
                type: "uint8",
                usage: "stream"
              });
              return _positions;
            }
          }, {
            // create marker ids corresponding to known marker textures
            marker: function marker(markers, group2, options2) {
              var activation = group2.activation;
              activation.forEach(function(buffer) {
                return buffer && buffer.destroy && buffer.destroy();
              });
              activation.length = 0;
              if (!markers || typeof markers[0] === "number") {
                var id = _this3.addMarker(markers);
                activation[id] = true;
              } else {
                var markerMasks = [];
                for (var _i = 0, l = Math.min(markers.length, group2.count); _i < l; _i++) {
                  var _id = _this3.addMarker(markers[_i]);
                  if (!markerMasks[_id]) markerMasks[_id] = new Uint8Array(group2.count);
                  markerMasks[_id][_i] = 1;
                }
                for (var _id2 = 0; _id2 < markerMasks.length; _id2++) {
                  if (!markerMasks[_id2]) continue;
                  var opts = {
                    data: markerMasks[_id2],
                    type: "uint8",
                    usage: "static"
                  };
                  if (!activation[_id2]) {
                    activation[_id2] = regl.buffer(opts);
                  } else {
                    activation[_id2](opts);
                  }
                  activation[_id2].data = markerMasks[_id2];
                }
              }
              return markers;
            },
            range: function range(_range, group2, options2) {
              var bounds = group2.bounds;
              if (!bounds) return;
              if (!_range) _range = bounds;
              group2.scale = [1 / (_range[2] - _range[0]), 1 / (_range[3] - _range[1])];
              group2.translate = [-_range[0], -_range[1]];
              group2.scaleFract = f32.fract(group2.scale);
              group2.translateFract = f32.fract(group2.translate);
              return _range;
            },
            viewport: function viewport(vp) {
              var rect = parseRect(vp || [gl2.drawingBufferWidth, gl2.drawingBufferHeight]);
              return rect;
            }
          }]);
          if (hasSize) {
            var _group = group, count = _group.count, size = _group.size, borderSize = _group.borderSize, sizeBuffer = _group.sizeBuffer;
            var sizes = new Uint8Array(count * 2);
            if (size.length || borderSize.length) {
              for (var _i2 = 0; _i2 < count; _i2++) {
                sizes[_i2 * 2] = Math.round((size[_i2] == null ? size : size[_i2]) * 255 / maxSize);
                sizes[_i2 * 2 + 1] = Math.round((borderSize[_i2] == null ? borderSize : borderSize[_i2]) * 255 / maxSize);
              }
            }
            sizeBuffer({
              data: sizes,
              usage: "dynamic"
            });
          }
          if (hasColor) {
            var _group2 = group, _count = _group2.count, color2 = _group2.color, borderColor = _group2.borderColor, colorBuffer = _group2.colorBuffer;
            var colors;
            if (_this3.tooManyColors) {
              if (color2.length || borderColor.length) {
                colors = new Uint8Array(_count * 8);
                for (var _i3 = 0; _i3 < _count; _i3++) {
                  var _colorId = color2[_i3];
                  colors[_i3 * 8] = palette[_colorId * 4];
                  colors[_i3 * 8 + 1] = palette[_colorId * 4 + 1];
                  colors[_i3 * 8 + 2] = palette[_colorId * 4 + 2];
                  colors[_i3 * 8 + 3] = palette[_colorId * 4 + 3];
                  var borderColorId = borderColor[_i3];
                  colors[_i3 * 8 + 4] = palette[borderColorId * 4];
                  colors[_i3 * 8 + 5] = palette[borderColorId * 4 + 1];
                  colors[_i3 * 8 + 6] = palette[borderColorId * 4 + 2];
                  colors[_i3 * 8 + 7] = palette[borderColorId * 4 + 3];
                }
              }
            } else {
              if (color2.length || borderColor.length) {
                colors = new Uint8Array(_count * 4 + 2);
                for (var _i4 = 0; _i4 < _count; _i4++) {
                  if (color2[_i4] != null) {
                    colors[_i4 * 4] = color2[_i4] % maxColors;
                    colors[_i4 * 4 + 1] = Math.floor(color2[_i4] / maxColors);
                  }
                  if (borderColor[_i4] != null) {
                    colors[_i4 * 4 + 2] = borderColor[_i4] % maxColors;
                    colors[_i4 * 4 + 3] = Math.floor(borderColor[_i4] / maxColors);
                  }
                }
              }
            }
            colorBuffer({
              data: colors || new Uint8Array(0),
              type: "uint8",
              usage: "dynamic"
            });
          }
          return group;
        });
      };
      Scatter.prototype.addMarker = function(sdf) {
        var markerTextures = this.markerTextures, regl = this.regl, markerCache = this.markerCache;
        var pos = sdf == null ? 0 : markerCache.indexOf(sdf);
        if (pos >= 0) return pos;
        var distArr;
        if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) {
          distArr = sdf;
        } else {
          distArr = new Uint8Array(sdf.length);
          for (var i = 0, l = sdf.length; i < l; i++) {
            distArr[i] = sdf[i] * 255;
          }
        }
        var radius = Math.floor(Math.sqrt(distArr.length));
        pos = markerTextures.length;
        markerCache.push(sdf);
        markerTextures.push(regl.texture({
          channels: 1,
          data: distArr,
          radius,
          mag: "linear",
          min: "linear"
        }));
        return pos;
      };
      Scatter.prototype.updateColor = function(colors) {
        var paletteIds = this.paletteIds, palette = this.palette, maxColors = this.maxColors;
        if (!Array.isArray(colors)) {
          colors = [colors];
        }
        var idx = [];
        if (typeof colors[0] === "number") {
          var grouped = [];
          if (Array.isArray(colors)) {
            for (var i = 0; i < colors.length; i += 4) {
              grouped.push(colors.slice(i, i + 4));
            }
          } else {
            for (var _i5 = 0; _i5 < colors.length; _i5 += 4) {
              grouped.push(colors.subarray(_i5, _i5 + 4));
            }
          }
          colors = grouped;
        }
        for (var _i6 = 0; _i6 < colors.length; _i6++) {
          var color2 = colors[_i6];
          color2 = rgba3(color2, "uint8");
          var id = colorId(color2, false);
          if (paletteIds[id] == null) {
            var pos = palette.length;
            paletteIds[id] = Math.floor(pos / 4);
            palette[pos] = color2[0];
            palette[pos + 1] = color2[1];
            palette[pos + 2] = color2[2];
            palette[pos + 3] = color2[3];
          }
          idx[_i6] = paletteIds[id];
        }
        if (!this.tooManyColors && palette.length > maxColors * 4) this.tooManyColors = true;
        this.updatePalette(palette);
        return idx.length === 1 ? idx[0] : idx;
      };
      Scatter.prototype.updatePalette = function(palette) {
        if (this.tooManyColors) return;
        var maxColors = this.maxColors, paletteTexture = this.paletteTexture;
        var requiredHeight = Math.ceil(palette.length * 0.25 / maxColors);
        if (requiredHeight > 1) {
          palette = palette.slice();
          for (var i = palette.length * 0.25 % maxColors; i < requiredHeight * maxColors; i++) {
            palette.push(0, 0, 0, 0);
          }
        }
        if (paletteTexture.height < requiredHeight) {
          paletteTexture.resize(maxColors, requiredHeight);
        }
        paletteTexture.subimage({
          width: Math.min(palette.length * 0.25, maxColors),
          height: requiredHeight,
          data: palette
        }, 0, 0);
      };
      Scatter.prototype.destroy = function() {
        this.groups.forEach(function(group) {
          group.sizeBuffer.destroy();
          group.positionBuffer.destroy();
          group.positionFractBuffer.destroy();
          group.colorBuffer.destroy();
          group.activation.forEach(function(b) {
            return b && b.destroy && b.destroy();
          });
          group.selectionBuffer.destroy();
          if (group.elements) group.elements.destroy();
        });
        this.groups.length = 0;
        this.paletteTexture.destroy();
        this.markerTextures.forEach(function(txt) {
          return txt && txt.destroy && txt.destroy();
        });
        return this;
      };
      var extend$1 = require_object_assign();
      var reglScatter2d = function reglScatter2d2(regl, options) {
        var scatter$1 = new scatter(regl, options);
        var render = scatter$1.render.bind(scatter$1);
        extend$1(render, {
          render,
          update: scatter$1.update.bind(scatter$1),
          draw: scatter$1.draw.bind(scatter$1),
          destroy: scatter$1.destroy.bind(scatter$1),
          regl: scatter$1.regl,
          gl: scatter$1.gl,
          canvas: scatter$1.gl.canvas,
          groups: scatter$1.groups,
          markers: scatter$1.markerCache,
          palette: scatter$1.palette
        });
        return render;
      };
      module.exports = reglScatter2d;
    }
  });

  // node_modules/earcut/src/earcut.js
  var require_earcut = __commonJS({
    "node_modules/earcut/src/earcut.js"(exports, module) {
      "use strict";
      module.exports = earcut;
      module.exports.default = earcut;
      function earcut(data, holeIndices, dim) {
        dim = dim || 2;
        var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
        if (!outerNode || outerNode.next === outerNode.prev) return triangles;
        var minX, minY, maxX, maxY, x, y, invSize;
        if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
        if (data.length > 80 * dim) {
          minX = maxX = data[0];
          minY = maxY = data[1];
          for (var i = dim; i < outerLen; i += dim) {
            x = data[i];
            y = data[i + 1];
            if (x < minX) minX = x;
            if (y < minY) minY = y;
            if (x > maxX) maxX = x;
            if (y > maxY) maxY = y;
          }
          invSize = Math.max(maxX - minX, maxY - minY);
          invSize = invSize !== 0 ? 32767 / invSize : 0;
        }
        earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
        return triangles;
      }
      function linkedList(data, start, end, dim, clockwise) {
        var i, last;
        if (clockwise === signedArea(data, start, end, dim) > 0) {
          for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
        } else {
          for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
        }
        if (last && equals(last, last.next)) {
          removeNode(last);
          last = last.next;
        }
        return last;
      }
      function filterPoints(start, end) {
        if (!start) return start;
        if (!end) end = start;
        var p = start, again;
        do {
          again = false;
          if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
            removeNode(p);
            p = end = p.prev;
            if (p === p.next) break;
            again = true;
          } else {
            p = p.next;
          }
        } while (again || p !== end);
        return end;
      }
      function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
        if (!ear) return;
        if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
        var stop = ear, prev, next;
        while (ear.prev !== ear.next) {
          prev = ear.prev;
          next = ear.next;
          if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
            triangles.push(prev.i / dim | 0);
            triangles.push(ear.i / dim | 0);
            triangles.push(next.i / dim | 0);
            removeNode(ear);
            ear = next.next;
            stop = next.next;
            continue;
          }
          ear = next;
          if (ear === stop) {
            if (!pass) {
              earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
            } else if (pass === 1) {
              ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
              earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
            } else if (pass === 2) {
              splitEarcut(ear, triangles, dim, minX, minY, invSize);
            }
            break;
          }
        }
      }
      function isEar(ear) {
        var a = ear.prev, b = ear, c = ear.next;
        if (area(a, b, c) >= 0) return false;
        var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
        var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
        var p = c.next;
        while (p !== a) {
          if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
          p = p.next;
        }
        return true;
      }
      function isEarHashed(ear, minX, minY, invSize) {
        var a = ear.prev, b = ear, c = ear.next;
        if (area(a, b, c) >= 0) return false;
        var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
        var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy;
        var minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize);
        var p = ear.prevZ, n = ear.nextZ;
        while (p && p.z >= minZ && n && n.z <= maxZ) {
          if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
          p = p.prevZ;
          if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
          n = n.nextZ;
        }
        while (p && p.z >= minZ) {
          if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
          p = p.prevZ;
        }
        while (n && n.z <= maxZ) {
          if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
          n = n.nextZ;
        }
        return true;
      }
      function cureLocalIntersections(start, triangles, dim) {
        var p = start;
        do {
          var a = p.prev, b = p.next.next;
          if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
            triangles.push(a.i / dim | 0);
            triangles.push(p.i / dim | 0);
            triangles.push(b.i / dim | 0);
            removeNode(p);
            removeNode(p.next);
            p = start = b;
          }
          p = p.next;
        } while (p !== start);
        return filterPoints(p);
      }
      function splitEarcut(start, triangles, dim, minX, minY, invSize) {
        var a = start;
        do {
          var b = a.next.next;
          while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
              var c = splitPolygon(a, b);
              a = filterPoints(a, a.next);
              c = filterPoints(c, c.next);
              earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
              earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
              return;
            }
            b = b.next;
          }
          a = a.next;
        } while (a !== start);
      }
      function eliminateHoles(data, holeIndices, outerNode, dim) {
        var queue = [], i, len, start, end, list;
        for (i = 0, len = holeIndices.length; i < len; i++) {
          start = holeIndices[i] * dim;
          end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
          list = linkedList(data, start, end, dim, false);
          if (list === list.next) list.steiner = true;
          queue.push(getLeftmost(list));
        }
        queue.sort(compareX);
        for (i = 0; i < queue.length; i++) {
          outerNode = eliminateHole(queue[i], outerNode);
        }
        return outerNode;
      }
      function compareX(a, b) {
        return a.x - b.x;
      }
      function eliminateHole(hole, outerNode) {
        var bridge = findHoleBridge(hole, outerNode);
        if (!bridge) {
          return outerNode;
        }
        var bridgeReverse = splitPolygon(bridge, hole);
        filterPoints(bridgeReverse, bridgeReverse.next);
        return filterPoints(bridge, bridge.next);
      }
      function findHoleBridge(hole, outerNode) {
        var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
        do {
          if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
            var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
            if (x <= hx && x > qx) {
              qx = x;
              m = p.x < p.next.x ? p : p.next;
              if (x === hx) return m;
            }
          }
          p = p.next;
        } while (p !== outerNode);
        if (!m) return null;
        var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
        p = m;
        do {
          if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
            tan = Math.abs(hy - p.y) / (hx - p.x);
            if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
              m = p;
              tanMin = tan;
            }
          }
          p = p.next;
        } while (p !== stop);
        return m;
      }
      function sectorContainsSector(m, p) {
        return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
      }
      function indexCurve(start, minX, minY, invSize) {
        var p = start;
        do {
          if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
          p.prevZ = p.prev;
          p.nextZ = p.next;
          p = p.next;
        } while (p !== start);
        p.prevZ.nextZ = null;
        p.prevZ = null;
        sortLinked(p);
      }
      function sortLinked(list) {
        var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
        do {
          p = list;
          list = null;
          tail = null;
          numMerges = 0;
          while (p) {
            numMerges++;
            q = p;
            pSize = 0;
            for (i = 0; i < inSize; i++) {
              pSize++;
              q = q.nextZ;
              if (!q) break;
            }
            qSize = inSize;
            while (pSize > 0 || qSize > 0 && q) {
              if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
                e = p;
                p = p.nextZ;
                pSize--;
              } else {
                e = q;
                q = q.nextZ;
                qSize--;
              }
              if (tail) tail.nextZ = e;
              else list = e;
              e.prevZ = tail;
              tail = e;
            }
            p = q;
          }
          tail.nextZ = null;
          inSize *= 2;
        } while (numMerges > 1);
        return list;
      }
      function zOrder(x, y, minX, minY, invSize) {
        x = (x - minX) * invSize | 0;
        y = (y - minY) * invSize | 0;
        x = (x | x << 8) & 16711935;
        x = (x | x << 4) & 252645135;
        x = (x | x << 2) & 858993459;
        x = (x | x << 1) & 1431655765;
        y = (y | y << 8) & 16711935;
        y = (y | y << 4) & 252645135;
        y = (y | y << 2) & 858993459;
        y = (y | y << 1) & 1431655765;
        return x | y << 1;
      }
      function getLeftmost(start) {
        var p = start, leftmost = start;
        do {
          if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
          p = p.next;
        } while (p !== start);
        return leftmost;
      }
      function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
        return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && (ax - px) * (by - py) >= (bx - px) * (ay - py) && (bx - px) * (cy - py) >= (cx - px) * (by - py);
      }
      function isValidDiagonal(a, b) {
        return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
        (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
        (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
        equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0);
      }
      function area(p, q, r) {
        return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
      }
      function equals(p1, p2) {
        return p1.x === p2.x && p1.y === p2.y;
      }
      function intersects(p1, q1, p2, q2) {
        var o1 = sign(area(p1, q1, p2));
        var o2 = sign(area(p1, q1, q2));
        var o3 = sign(area(p2, q2, p1));
        var o4 = sign(area(p2, q2, q1));
        if (o1 !== o2 && o3 !== o4) return true;
        if (o1 === 0 && onSegment(p1, p2, q1)) return true;
        if (o2 === 0 && onSegment(p1, q2, q1)) return true;
        if (o3 === 0 && onSegment(p2, p1, q2)) return true;
        if (o4 === 0 && onSegment(p2, q1, q2)) return true;
        return false;
      }
      function onSegment(p, q, r) {
        return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
      }
      function sign(num) {
        return num > 0 ? 1 : num < 0 ? -1 : 0;
      }
      function intersectsPolygon(a, b) {
        var p = a;
        do {
          if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
          p = p.next;
        } while (p !== a);
        return false;
      }
      function locallyInside(a, b) {
        return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
      }
      function middleInside(a, b) {
        var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
        do {
          if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)
            inside = !inside;
          p = p.next;
        } while (p !== a);
        return inside;
      }
      function splitPolygon(a, b) {
        var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
        a.next = b;
        b.prev = a;
        a2.next = an;
        an.prev = a2;
        b2.next = a2;
        a2.prev = b2;
        bp.next = b2;
        b2.prev = bp;
        return b2;
      }
      function insertNode(i, x, y, last) {
        var p = new Node(i, x, y);
        if (!last) {
          p.prev = p;
          p.next = p;
        } else {
          p.next = last.next;
          p.prev = last;
          last.next.prev = p;
          last.next = p;
        }
        return p;
      }
      function removeNode(p) {
        p.next.prev = p.prev;
        p.prev.next = p.next;
        if (p.prevZ) p.prevZ.nextZ = p.nextZ;
        if (p.nextZ) p.nextZ.prevZ = p.prevZ;
      }
      function Node(i, x, y) {
        this.i = i;
        this.x = x;
        this.y = y;
        this.prev = null;
        this.next = null;
        this.z = 0;
        this.prevZ = null;
        this.nextZ = null;
        this.steiner = false;
      }
      earcut.deviation = function(data, holeIndices, dim, triangles) {
        var hasHoles = holeIndices && holeIndices.length;
        var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
        var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
        if (hasHoles) {
          for (var i = 0, len = holeIndices.length; i < len; i++) {
            var start = holeIndices[i] * dim;
            var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
            polygonArea -= Math.abs(signedArea(data, start, end, dim));
          }
        }
        var trianglesArea = 0;
        for (i = 0; i < triangles.length; i += 3) {
          var a = triangles[i] * dim;
          var b = triangles[i + 1] * dim;
          var c = triangles[i + 2] * dim;
          trianglesArea += Math.abs(
            (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1])
          );
        }
        return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
      };
      function signedArea(data, start, end, dim) {
        var sum = 0;
        for (var i = start, j = end - dim; i < end; i += dim) {
          sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
          j = i;
        }
        return sum;
      }
      earcut.flatten = function(data) {
        var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
        for (var i = 0; i < data.length; i++) {
          for (var j = 0; j < data[i].length; j++) {
            for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
          }
          if (i > 0) {
            holeIndex += data[i - 1].length;
            result.holes.push(holeIndex);
          }
        }
        return result;
      };
    }
  });

  // node_modules/array-normalize/index.js
  var require_array_normalize = __commonJS({
    "node_modules/array-normalize/index.js"(exports, module) {
      "use strict";
      var getBounds = require_array_bounds();
      module.exports = normalize;
      function normalize(arr, dim, bounds) {
        if (!arr || arr.length == null) throw Error("Argument should be an array");
        if (dim == null) dim = 1;
        if (bounds == null) bounds = getBounds(arr, dim);
        for (var offset = 0; offset < dim; offset++) {
          var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length;
          if (max === Infinity && min === -Infinity) {
            for (i = offset; i < l; i += dim) {
              arr[i] = arr[i] === max ? 1 : arr[i] === min ? 0 : 0.5;
            }
          } else if (max === Infinity) {
            for (i = offset; i < l; i += dim) {
              arr[i] = arr[i] === max ? 1 : 0;
            }
          } else if (min === -Infinity) {
            for (i = offset; i < l; i += dim) {
              arr[i] = arr[i] === min ? 0 : 1;
            }
          } else {
            var range = max - min;
            for (i = offset; i < l; i += dim) {
              if (!isNaN(arr[i])) {
                arr[i] = range === 0 ? 0.5 : (arr[i] - min) / range;
              }
            }
          }
        }
        return arr;
      }
    }
  });

  // node_modules/es6-weak-map/is-implemented.js
  var require_is_implemented = __commonJS({
    "node_modules/es6-weak-map/is-implemented.js"(exports, module) {
      "use strict";
      module.exports = function() {
        var weakMap, obj;
        if (typeof WeakMap !== "function") return false;
        try {
          weakMap = new WeakMap([[obj = {}, "one"], [{}, "two"], [{}, "three"]]);
        } catch (e) {
          return false;
        }
        if (String(weakMap) !== "[object WeakMap]") return false;
        if (typeof weakMap.set !== "function") return false;
        if (weakMap.set({}, 1) !== weakMap) return false;
        if (typeof weakMap.delete !== "function") return false;
        if (typeof weakMap.has !== "function") return false;
        if (weakMap.get(obj) !== "one") return false;
        return true;
      };
    }
  });

  // node_modules/es5-ext/function/noop.js
  var require_noop2 = __commonJS({
    "node_modules/es5-ext/function/noop.js"(exports, module) {
      "use strict";
      module.exports = function() {
      };
    }
  });

  // node_modules/es5-ext/object/is-value.js
  var require_is_value = __commonJS({
    "node_modules/es5-ext/object/is-value.js"(exports, module) {
      "use strict";
      var _undefined = require_noop2()();
      module.exports = function(val) {
        return val !== _undefined && val !== null;
      };
    }
  });

  // node_modules/es5-ext/object/set-prototype-of/is-implemented.js
  var require_is_implemented2 = __commonJS({
    "node_modules/es5-ext/object/set-prototype-of/is-implemented.js"(exports, module) {
      "use strict";
      var create = Object.create;
      var getPrototypeOf = Object.getPrototypeOf;
      var plainObject = {};
      module.exports = function() {
        var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create;
        if (typeof setPrototypeOf !== "function") return false;
        return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject;
      };
    }
  });

  // node_modules/es5-ext/object/is-object.js
  var require_is_object = __commonJS({
    "node_modules/es5-ext/object/is-object.js"(exports, module) {
      "use strict";
      var isValue = require_is_value();
      var map = { function: true, object: true };
      module.exports = function(value) {
        return isValue(value) && map[typeof value] || false;
      };
    }
  });

  // node_modules/es5-ext/object/valid-value.js
  var require_valid_value = __commonJS({
    "node_modules/es5-ext/object/valid-value.js"(exports, module) {
      "use strict";
      var isValue = require_is_value();
      module.exports = function(value) {
        if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
        return value;
      };
    }
  });

  // node_modules/es5-ext/object/create.js
  var require_create2 = __commonJS({
    "node_modules/es5-ext/object/create.js"(exports, module) {
      "use strict";
      var create = Object.create;
      var shim;
      if (!require_is_implemented2()()) {
        shim = require_shim3();
      }
      module.exports = function() {
        var nullObject, polyProps, desc;
        if (!shim) return create;
        if (shim.level !== 1) return create;
        nullObject = {};
        polyProps = {};
        desc = { configurable: false, enumerable: false, writable: true, value: void 0 };
        Object.getOwnPropertyNames(Object.prototype).forEach(function(name2) {
          if (name2 === "__proto__") {
            polyProps[name2] = {
              configurable: true,
              enumerable: false,
              writable: true,
              value: void 0
            };
            return;
          }
          polyProps[name2] = desc;
        });
        Object.defineProperties(nullObject, polyProps);
        Object.defineProperty(shim, "nullPolyfill", {
          configurable: false,
          enumerable: false,
          writable: false,
          value: nullObject
        });
        return function(prototype, props) {
          return create(prototype === null ? nullObject : prototype, props);
        };
      }();
    }
  });

  // node_modules/es5-ext/object/set-prototype-of/shim.js
  var require_shim3 = __commonJS({
    "node_modules/es5-ext/object/set-prototype-of/shim.js"(exports, module) {
      "use strict";
      var isObject = require_is_object();
      var value = require_valid_value();
      var objIsPrototypeOf = Object.prototype.isPrototypeOf;
      var defineProperty = Object.defineProperty;
      var nullDesc = { configurable: true, enumerable: false, writable: true, value: void 0 };
      var validate;
      validate = function(obj, prototype) {
        value(obj);
        if (prototype === null || isObject(prototype)) return obj;
        throw new TypeError("Prototype must be null or an object");
      };
      module.exports = function(status) {
        var fn, set;
        if (!status) return null;
        if (status.level === 2) {
          if (status.set) {
            set = status.set;
            fn = function(obj, prototype) {
              set.call(validate(obj, prototype), prototype);
              return obj;
            };
          } else {
            fn = function(obj, prototype) {
              validate(obj, prototype).__proto__ = prototype;
              return obj;
            };
          }
        } else {
          fn = function self2(obj, prototype) {
            var isNullBase;
            validate(obj, prototype);
            isNullBase = objIsPrototypeOf.call(self2.nullPolyfill, obj);
            if (isNullBase) delete self2.nullPolyfill.__proto__;
            if (prototype === null) prototype = self2.nullPolyfill;
            obj.__proto__ = prototype;
            if (isNullBase) defineProperty(self2.nullPolyfill, "__proto__", nullDesc);
            return obj;
          };
        }
        return Object.defineProperty(fn, "level", {
          configurable: false,
          enumerable: false,
          writable: false,
          value: status.level
        });
      }(
        function() {
          var tmpObj1 = /* @__PURE__ */ Object.create(null), tmpObj2 = {}, set, desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__");
          if (desc) {
            try {
              set = desc.set;
              set.call(tmpObj1, tmpObj2);
            } catch (ignore) {
            }
            if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set, level: 2 };
          }
          tmpObj1.__proto__ = tmpObj2;
          if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 };
          tmpObj1 = {};
          tmpObj1.__proto__ = tmpObj2;
          if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 };
          return false;
        }()
      );
      require_create2();
    }
  });

  // node_modules/es5-ext/object/set-prototype-of/index.js
  var require_set_prototype_of = __commonJS({
    "node_modules/es5-ext/object/set-prototype-of/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented2()() ? Object.setPrototypeOf : require_shim3();
    }
  });

  // node_modules/es5-ext/object/valid-object.js
  var require_valid_object = __commonJS({
    "node_modules/es5-ext/object/valid-object.js"(exports, module) {
      "use strict";
      var isObject = require_is_object();
      module.exports = function(value) {
        if (!isObject(value)) throw new TypeError(value + " is not an Object");
        return value;
      };
    }
  });

  // node_modules/es5-ext/string/random-uniq.js
  var require_random_uniq = __commonJS({
    "node_modules/es5-ext/string/random-uniq.js"(exports, module) {
      "use strict";
      var generated = /* @__PURE__ */ Object.create(null);
      var random = Math.random;
      module.exports = function() {
        var str;
        do {
          str = random().toString(36).slice(2);
        } while (generated[str]);
        return str;
      };
    }
  });

  // node_modules/type/value/is.js
  var require_is = __commonJS({
    "node_modules/type/value/is.js"(exports, module) {
      "use strict";
      var _undefined = void 0;
      module.exports = function(value) {
        return value !== _undefined && value !== null;
      };
    }
  });

  // node_modules/type/object/is.js
  var require_is2 = __commonJS({
    "node_modules/type/object/is.js"(exports, module) {
      "use strict";
      var isValue = require_is();
      var possibleTypes = {
        "object": true,
        "function": true,
        "undefined": true
        /* document.all */
      };
      module.exports = function(value) {
        if (!isValue(value)) return false;
        return hasOwnProperty.call(possibleTypes, typeof value);
      };
    }
  });

  // node_modules/type/prototype/is.js
  var require_is3 = __commonJS({
    "node_modules/type/prototype/is.js"(exports, module) {
      "use strict";
      var isObject = require_is2();
      module.exports = function(value) {
        if (!isObject(value)) return false;
        try {
          if (!value.constructor) return false;
          return value.constructor.prototype === value;
        } catch (error) {
          return false;
        }
      };
    }
  });

  // node_modules/type/function/is.js
  var require_is4 = __commonJS({
    "node_modules/type/function/is.js"(exports, module) {
      "use strict";
      var isPrototype = require_is3();
      module.exports = function(value) {
        if (typeof value !== "function") return false;
        if (!hasOwnProperty.call(value, "length")) return false;
        try {
          if (typeof value.length !== "number") return false;
          if (typeof value.call !== "function") return false;
          if (typeof value.apply !== "function") return false;
        } catch (error) {
          return false;
        }
        return !isPrototype(value);
      };
    }
  });

  // node_modules/type/plain-function/is.js
  var require_is5 = __commonJS({
    "node_modules/type/plain-function/is.js"(exports, module) {
      "use strict";
      var isFunction = require_is4();
      var classRe = /^\s*class[\s{/}]/;
      var functionToString = Function.prototype.toString;
      module.exports = function(value) {
        if (!isFunction(value)) return false;
        if (classRe.test(functionToString.call(value))) return false;
        return true;
      };
    }
  });

  // node_modules/es5-ext/object/assign/is-implemented.js
  var require_is_implemented3 = __commonJS({
    "node_modules/es5-ext/object/assign/is-implemented.js"(exports, module) {
      "use strict";
      module.exports = function() {
        var assign = Object.assign, obj;
        if (typeof assign !== "function") return false;
        obj = { foo: "raz" };
        assign(obj, { bar: "dwa" }, { trzy: "trzy" });
        return obj.foo + obj.bar + obj.trzy === "razdwatrzy";
      };
    }
  });

  // node_modules/es5-ext/object/keys/is-implemented.js
  var require_is_implemented4 = __commonJS({
    "node_modules/es5-ext/object/keys/is-implemented.js"(exports, module) {
      "use strict";
      module.exports = function() {
        try {
          Object.keys("primitive");
          return true;
        } catch (e) {
          return false;
        }
      };
    }
  });

  // node_modules/es5-ext/object/keys/shim.js
  var require_shim4 = __commonJS({
    "node_modules/es5-ext/object/keys/shim.js"(exports, module) {
      "use strict";
      var isValue = require_is_value();
      var keys = Object.keys;
      module.exports = function(object) {
        return keys(isValue(object) ? Object(object) : object);
      };
    }
  });

  // node_modules/es5-ext/object/keys/index.js
  var require_keys = __commonJS({
    "node_modules/es5-ext/object/keys/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented4()() ? Object.keys : require_shim4();
    }
  });

  // node_modules/es5-ext/object/assign/shim.js
  var require_shim5 = __commonJS({
    "node_modules/es5-ext/object/assign/shim.js"(exports, module) {
      "use strict";
      var keys = require_keys();
      var value = require_valid_value();
      var max = Math.max;
      module.exports = function(dest, src) {
        var error, i, length = max(arguments.length, 2), assign;
        dest = Object(value(dest));
        assign = function(key) {
          try {
            dest[key] = src[key];
          } catch (e) {
            if (!error) error = e;
          }
        };
        for (i = 1; i < length; ++i) {
          src = arguments[i];
          keys(src).forEach(assign);
        }
        if (error !== void 0) throw error;
        return dest;
      };
    }
  });

  // node_modules/es5-ext/object/assign/index.js
  var require_assign = __commonJS({
    "node_modules/es5-ext/object/assign/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented3()() ? Object.assign : require_shim5();
    }
  });

  // node_modules/es5-ext/object/normalize-options.js
  var require_normalize_options = __commonJS({
    "node_modules/es5-ext/object/normalize-options.js"(exports, module) {
      "use strict";
      var isValue = require_is_value();
      var forEach = Array.prototype.forEach;
      var create = Object.create;
      var process2 = function(src, obj) {
        var key;
        for (key in src) obj[key] = src[key];
      };
      module.exports = function(opts1) {
        var result = create(null);
        forEach.call(arguments, function(options) {
          if (!isValue(options)) return;
          process2(Object(options), result);
        });
        return result;
      };
    }
  });

  // node_modules/es5-ext/string/#/contains/is-implemented.js
  var require_is_implemented5 = __commonJS({
    "node_modules/es5-ext/string/#/contains/is-implemented.js"(exports, module) {
      "use strict";
      var str = "razdwatrzy";
      module.exports = function() {
        if (typeof str.contains !== "function") return false;
        return str.contains("dwa") === true && str.contains("foo") === false;
      };
    }
  });

  // node_modules/es5-ext/string/#/contains/shim.js
  var require_shim6 = __commonJS({
    "node_modules/es5-ext/string/#/contains/shim.js"(exports, module) {
      "use strict";
      var indexOf = String.prototype.indexOf;
      module.exports = function(searchString) {
        return indexOf.call(this, searchString, arguments[1]) > -1;
      };
    }
  });

  // node_modules/es5-ext/string/#/contains/index.js
  var require_contains = __commonJS({
    "node_modules/es5-ext/string/#/contains/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented5()() ? String.prototype.contains : require_shim6();
    }
  });

  // node_modules/d/index.js
  var require_d = __commonJS({
    "node_modules/d/index.js"(exports, module) {
      "use strict";
      var isValue = require_is();
      var isPlainFunction = require_is5();
      var assign = require_assign();
      var normalizeOpts = require_normalize_options();
      var contains = require_contains();
      var d = module.exports = function(dscr, value) {
        var c, e, w, options, desc;
        if (arguments.length < 2 || typeof dscr !== "string") {
          options = value;
          value = dscr;
          dscr = null;
        } else {
          options = arguments[2];
        }
        if (isValue(dscr)) {
          c = contains.call(dscr, "c");
          e = contains.call(dscr, "e");
          w = contains.call(dscr, "w");
        } else {
          c = w = true;
          e = false;
        }
        desc = { value, configurable: c, enumerable: e, writable: w };
        return !options ? desc : assign(normalizeOpts(options), desc);
      };
      d.gs = function(dscr, get, set) {
        var c, e, options, desc;
        if (typeof dscr !== "string") {
          options = set;
          set = get;
          get = dscr;
          dscr = null;
        } else {
          options = arguments[3];
        }
        if (!isValue(get)) {
          get = void 0;
        } else if (!isPlainFunction(get)) {
          options = get;
          get = set = void 0;
        } else if (!isValue(set)) {
          set = void 0;
        } else if (!isPlainFunction(set)) {
          options = set;
          set = void 0;
        }
        if (isValue(dscr)) {
          c = contains.call(dscr, "c");
          e = contains.call(dscr, "e");
        } else {
          c = true;
          e = false;
        }
        desc = { get, set, configurable: c, enumerable: e };
        return !options ? desc : assign(normalizeOpts(options), desc);
      };
    }
  });

  // node_modules/es5-ext/function/is-arguments.js
  var require_is_arguments2 = __commonJS({
    "node_modules/es5-ext/function/is-arguments.js"(exports, module) {
      "use strict";
      var objToString = Object.prototype.toString;
      var id = objToString.call(/* @__PURE__ */ function() {
        return arguments;
      }());
      module.exports = function(value) {
        return objToString.call(value) === id;
      };
    }
  });

  // node_modules/es5-ext/string/is-string.js
  var require_is_string = __commonJS({
    "node_modules/es5-ext/string/is-string.js"(exports, module) {
      "use strict";
      var objToString = Object.prototype.toString;
      var id = objToString.call("");
      module.exports = function(value) {
        return typeof value === "string" || value && typeof value === "object" && (value instanceof String || objToString.call(value) === id) || false;
      };
    }
  });

  // node_modules/ext/global-this/is-implemented.js
  var require_is_implemented6 = __commonJS({
    "node_modules/ext/global-this/is-implemented.js"(exports, module) {
      "use strict";
      module.exports = function() {
        if (typeof globalThis !== "object") return false;
        if (!globalThis) return false;
        return globalThis.Array === Array;
      };
    }
  });

  // node_modules/ext/global-this/implementation.js
  var require_implementation6 = __commonJS({
    "node_modules/ext/global-this/implementation.js"(exports, module) {
      var naiveFallback = function() {
        if (typeof self === "object" && self) return self;
        if (typeof window === "object" && window) return window;
        throw new Error("Unable to resolve global `this`");
      };
      module.exports = function() {
        if (this) return this;
        try {
          Object.defineProperty(Object.prototype, "__global__", {
            get: function() {
              return this;
            },
            configurable: true
          });
        } catch (error) {
          return naiveFallback();
        }
        try {
          if (!__global__) return naiveFallback();
          return __global__;
        } finally {
          delete Object.prototype.__global__;
        }
      }();
    }
  });

  // node_modules/ext/global-this/index.js
  var require_global_this = __commonJS({
    "node_modules/ext/global-this/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented6()() ? globalThis : require_implementation6();
    }
  });

  // node_modules/es6-symbol/is-implemented.js
  var require_is_implemented7 = __commonJS({
    "node_modules/es6-symbol/is-implemented.js"(exports, module) {
      "use strict";
      var global2 = require_global_this();
      var validTypes = { object: true, symbol: true };
      module.exports = function() {
        var Symbol2 = global2.Symbol;
        var symbol;
        if (typeof Symbol2 !== "function") return false;
        symbol = Symbol2("test symbol");
        try {
          String(symbol);
        } catch (e) {
          return false;
        }
        if (!validTypes[typeof Symbol2.iterator]) return false;
        if (!validTypes[typeof Symbol2.toPrimitive]) return false;
        if (!validTypes[typeof Symbol2.toStringTag]) return false;
        return true;
      };
    }
  });

  // node_modules/es6-symbol/is-symbol.js
  var require_is_symbol = __commonJS({
    "node_modules/es6-symbol/is-symbol.js"(exports, module) {
      "use strict";
      module.exports = function(value) {
        if (!value) return false;
        if (typeof value === "symbol") return true;
        if (!value.constructor) return false;
        if (value.constructor.name !== "Symbol") return false;
        return value[value.constructor.toStringTag] === "Symbol";
      };
    }
  });

  // node_modules/es6-symbol/validate-symbol.js
  var require_validate_symbol = __commonJS({
    "node_modules/es6-symbol/validate-symbol.js"(exports, module) {
      "use strict";
      var isSymbol = require_is_symbol();
      module.exports = function(value) {
        if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
        return value;
      };
    }
  });

  // node_modules/es6-symbol/lib/private/generate-name.js
  var require_generate_name = __commonJS({
    "node_modules/es6-symbol/lib/private/generate-name.js"(exports, module) {
      "use strict";
      var d = require_d();
      var create = Object.create;
      var defineProperty = Object.defineProperty;
      var objPrototype = Object.prototype;
      var created = create(null);
      module.exports = function(desc) {
        var postfix = 0, name2, ie11BugWorkaround;
        while (created[desc + (postfix || "")]) ++postfix;
        desc += postfix || "";
        created[desc] = true;
        name2 = "@@" + desc;
        defineProperty(
          objPrototype,
          name2,
          d.gs(null, function(value) {
            if (ie11BugWorkaround) return;
            ie11BugWorkaround = true;
            defineProperty(this, name2, d(value));
            ie11BugWorkaround = false;
          })
        );
        return name2;
      };
    }
  });

  // node_modules/es6-symbol/lib/private/setup/standard-symbols.js
  var require_standard_symbols = __commonJS({
    "node_modules/es6-symbol/lib/private/setup/standard-symbols.js"(exports, module) {
      "use strict";
      var d = require_d();
      var NativeSymbol = require_global_this().Symbol;
      module.exports = function(SymbolPolyfill) {
        return Object.defineProperties(SymbolPolyfill, {
          // To ensure proper interoperability with other native functions (e.g. Array.from)
          // fallback to eventual native implementation of given symbol
          hasInstance: d(
            "",
            NativeSymbol && NativeSymbol.hasInstance || SymbolPolyfill("hasInstance")
          ),
          isConcatSpreadable: d(
            "",
            NativeSymbol && NativeSymbol.isConcatSpreadable || SymbolPolyfill("isConcatSpreadable")
          ),
          iterator: d("", NativeSymbol && NativeSymbol.iterator || SymbolPolyfill("iterator")),
          match: d("", NativeSymbol && NativeSymbol.match || SymbolPolyfill("match")),
          replace: d("", NativeSymbol && NativeSymbol.replace || SymbolPolyfill("replace")),
          search: d("", NativeSymbol && NativeSymbol.search || SymbolPolyfill("search")),
          species: d("", NativeSymbol && NativeSymbol.species || SymbolPolyfill("species")),
          split: d("", NativeSymbol && NativeSymbol.split || SymbolPolyfill("split")),
          toPrimitive: d(
            "",
            NativeSymbol && NativeSymbol.toPrimitive || SymbolPolyfill("toPrimitive")
          ),
          toStringTag: d(
            "",
            NativeSymbol && NativeSymbol.toStringTag || SymbolPolyfill("toStringTag")
          ),
          unscopables: d(
            "",
            NativeSymbol && NativeSymbol.unscopables || SymbolPolyfill("unscopables")
          )
        });
      };
    }
  });

  // node_modules/es6-symbol/lib/private/setup/symbol-registry.js
  var require_symbol_registry = __commonJS({
    "node_modules/es6-symbol/lib/private/setup/symbol-registry.js"(exports, module) {
      "use strict";
      var d = require_d();
      var validateSymbol = require_validate_symbol();
      var registry = /* @__PURE__ */ Object.create(null);
      module.exports = function(SymbolPolyfill) {
        return Object.defineProperties(SymbolPolyfill, {
          for: d(function(key) {
            if (registry[key]) return registry[key];
            return registry[key] = SymbolPolyfill(String(key));
          }),
          keyFor: d(function(symbol) {
            var key;
            validateSymbol(symbol);
            for (key in registry) {
              if (registry[key] === symbol) return key;
            }
            return void 0;
          })
        });
      };
    }
  });

  // node_modules/es6-symbol/polyfill.js
  var require_polyfill4 = __commonJS({
    "node_modules/es6-symbol/polyfill.js"(exports, module) {
      "use strict";
      var d = require_d();
      var validateSymbol = require_validate_symbol();
      var NativeSymbol = require_global_this().Symbol;
      var generateName = require_generate_name();
      var setupStandardSymbols = require_standard_symbols();
      var setupSymbolRegistry = require_symbol_registry();
      var create = Object.create;
      var defineProperties = Object.defineProperties;
      var defineProperty = Object.defineProperty;
      var SymbolPolyfill;
      var HiddenSymbol;
      var isNativeSafe;
      if (typeof NativeSymbol === "function") {
        try {
          String(NativeSymbol());
          isNativeSafe = true;
        } catch (ignore) {
        }
      } else {
        NativeSymbol = null;
      }
      HiddenSymbol = function Symbol2(description) {
        if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor");
        return SymbolPolyfill(description);
      };
      module.exports = SymbolPolyfill = function Symbol2(description) {
        var symbol;
        if (this instanceof Symbol2) throw new TypeError("Symbol is not a constructor");
        if (isNativeSafe) return NativeSymbol(description);
        symbol = create(HiddenSymbol.prototype);
        description = description === void 0 ? "" : String(description);
        return defineProperties(symbol, {
          __description__: d("", description),
          __name__: d("", generateName(description))
        });
      };
      setupStandardSymbols(SymbolPolyfill);
      setupSymbolRegistry(SymbolPolyfill);
      defineProperties(HiddenSymbol.prototype, {
        constructor: d(SymbolPolyfill),
        toString: d("", function() {
          return this.__name__;
        })
      });
      defineProperties(SymbolPolyfill.prototype, {
        toString: d(function() {
          return "Symbol (" + validateSymbol(this).__description__ + ")";
        }),
        valueOf: d(function() {
          return validateSymbol(this);
        })
      });
      defineProperty(
        SymbolPolyfill.prototype,
        SymbolPolyfill.toPrimitive,
        d("", function() {
          var symbol = validateSymbol(this);
          if (typeof symbol === "symbol") return symbol;
          return symbol.toString();
        })
      );
      defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol"));
      defineProperty(
        HiddenSymbol.prototype,
        SymbolPolyfill.toStringTag,
        d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])
      );
      defineProperty(
        HiddenSymbol.prototype,
        SymbolPolyfill.toPrimitive,
        d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])
      );
    }
  });

  // node_modules/es6-symbol/index.js
  var require_es6_symbol = __commonJS({
    "node_modules/es6-symbol/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented7()() ? require_global_this().Symbol : require_polyfill4();
    }
  });

  // node_modules/es5-ext/array/#/clear.js
  var require_clear = __commonJS({
    "node_modules/es5-ext/array/#/clear.js"(exports, module) {
      "use strict";
      var value = require_valid_value();
      module.exports = function() {
        value(this).length = 0;
        return this;
      };
    }
  });

  // node_modules/es5-ext/object/valid-callable.js
  var require_valid_callable = __commonJS({
    "node_modules/es5-ext/object/valid-callable.js"(exports, module) {
      "use strict";
      module.exports = function(fn) {
        if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
        return fn;
      };
    }
  });

  // node_modules/type/string/coerce.js
  var require_coerce2 = __commonJS({
    "node_modules/type/string/coerce.js"(exports, module) {
      "use strict";
      var isValue = require_is();
      var isObject = require_is2();
      var objectToString = Object.prototype.toString;
      module.exports = function(value) {
        if (!isValue(value)) return null;
        if (isObject(value)) {
          var valueToString = value.toString;
          if (typeof valueToString !== "function") return null;
          if (valueToString === objectToString) return null;
        }
        try {
          return "" + value;
        } catch (error) {
          return null;
        }
      };
    }
  });

  // node_modules/type/lib/safe-to-string.js
  var require_safe_to_string = __commonJS({
    "node_modules/type/lib/safe-to-string.js"(exports, module) {
      "use strict";
      module.exports = function(value) {
        try {
          return value.toString();
        } catch (error) {
          try {
            return String(value);
          } catch (error2) {
            return null;
          }
        }
      };
    }
  });

  // node_modules/type/lib/to-short-string.js
  var require_to_short_string = __commonJS({
    "node_modules/type/lib/to-short-string.js"(exports, module) {
      "use strict";
      var safeToString = require_safe_to_string();
      var reNewLine = /[\n\r\u2028\u2029]/g;
      module.exports = function(value) {
        var string = safeToString(value);
        if (string === null) return "<Non-coercible to string value>";
        if (string.length > 100) string = string.slice(0, 99) + "\u2026";
        string = string.replace(reNewLine, function(char) {
          switch (char) {
            case "\n":
              return "\\n";
            case "\r":
              return "\\r";
            case "\u2028":
              return "\\u2028";
            case "\u2029":
              return "\\u2029";
            /* istanbul ignore next */
            default:
              throw new Error("Unexpected character");
          }
        });
        return string;
      };
    }
  });

  // node_modules/type/lib/resolve-exception.js
  var require_resolve_exception = __commonJS({
    "node_modules/type/lib/resolve-exception.js"(exports, module) {
      "use strict";
      var isValue = require_is();
      var isObject = require_is2();
      var stringCoerce = require_coerce2();
      var toShortString = require_to_short_string();
      var resolveMessage = function(message, value) {
        return message.replace("%v", toShortString(value));
      };
      module.exports = function(value, defaultMessage, inputOptions) {
        if (!isObject(inputOptions)) throw new TypeError(resolveMessage(defaultMessage, value));
        if (!isValue(value)) {
          if ("default" in inputOptions) return inputOptions["default"];
          if (inputOptions.isOptional) return null;
        }
        var errorMessage = stringCoerce(inputOptions.errorMessage);
        if (!isValue(errorMessage)) errorMessage = defaultMessage;
        throw new TypeError(resolveMessage(errorMessage, value));
      };
    }
  });

  // node_modules/type/value/ensure.js
  var require_ensure = __commonJS({
    "node_modules/type/value/ensure.js"(exports, module) {
      "use strict";
      var resolveException = require_resolve_exception();
      var is = require_is();
      module.exports = function(value) {
        if (is(value)) return value;
        return resolveException(value, "Cannot use %v", arguments[1]);
      };
    }
  });

  // node_modules/type/plain-function/ensure.js
  var require_ensure2 = __commonJS({
    "node_modules/type/plain-function/ensure.js"(exports, module) {
      "use strict";
      var resolveException = require_resolve_exception();
      var is = require_is5();
      module.exports = function(value) {
        if (is(value)) return value;
        return resolveException(value, "%v is not a plain function", arguments[1]);
      };
    }
  });

  // node_modules/es5-ext/array/from/is-implemented.js
  var require_is_implemented8 = __commonJS({
    "node_modules/es5-ext/array/from/is-implemented.js"(exports, module) {
      "use strict";
      module.exports = function() {
        var from = Array.from, arr, result;
        if (typeof from !== "function") return false;
        arr = ["raz", "dwa"];
        result = from(arr);
        return Boolean(result && result !== arr && result[1] === "dwa");
      };
    }
  });

  // node_modules/es5-ext/function/is-function.js
  var require_is_function = __commonJS({
    "node_modules/es5-ext/function/is-function.js"(exports, module) {
      "use strict";
      var objToString = Object.prototype.toString;
      var isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/);
      module.exports = function(value) {
        return typeof value === "function" && isFunctionStringTag(objToString.call(value));
      };
    }
  });

  // node_modules/es5-ext/math/sign/is-implemented.js
  var require_is_implemented9 = __commonJS({
    "node_modules/es5-ext/math/sign/is-implemented.js"(exports, module) {
      "use strict";
      module.exports = function() {
        var sign = Math.sign;
        if (typeof sign !== "function") return false;
        return sign(10) === 1 && sign(-20) === -1;
      };
    }
  });

  // node_modules/es5-ext/math/sign/shim.js
  var require_shim7 = __commonJS({
    "node_modules/es5-ext/math/sign/shim.js"(exports, module) {
      "use strict";
      module.exports = function(value) {
        value = Number(value);
        if (isNaN(value) || value === 0) return value;
        return value > 0 ? 1 : -1;
      };
    }
  });

  // node_modules/es5-ext/math/sign/index.js
  var require_sign2 = __commonJS({
    "node_modules/es5-ext/math/sign/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented9()() ? Math.sign : require_shim7();
    }
  });

  // node_modules/es5-ext/number/to-integer.js
  var require_to_integer = __commonJS({
    "node_modules/es5-ext/number/to-integer.js"(exports, module) {
      "use strict";
      var sign = require_sign2();
      var abs = Math.abs;
      var floor = Math.floor;
      module.exports = function(value) {
        if (isNaN(value)) return 0;
        value = Number(value);
        if (value === 0 || !isFinite(value)) return value;
        return sign(value) * floor(abs(value));
      };
    }
  });

  // node_modules/es5-ext/number/to-pos-integer.js
  var require_to_pos_integer = __commonJS({
    "node_modules/es5-ext/number/to-pos-integer.js"(exports, module) {
      "use strict";
      var toInteger = require_to_integer();
      var max = Math.max;
      module.exports = function(value) {
        return max(0, toInteger(value));
      };
    }
  });

  // node_modules/es5-ext/array/from/shim.js
  var require_shim8 = __commonJS({
    "node_modules/es5-ext/array/from/shim.js"(exports, module) {
      "use strict";
      var iteratorSymbol = require_es6_symbol().iterator;
      var isArguments = require_is_arguments2();
      var isFunction = require_is_function();
      var toPosInt = require_to_pos_integer();
      var callable = require_valid_callable();
      var validValue = require_valid_value();
      var isValue = require_is_value();
      var isString = require_is_string();
      var isArray = Array.isArray;
      var call = Function.prototype.call;
      var desc = { configurable: true, enumerable: true, writable: true, value: null };
      var defineProperty = Object.defineProperty;
      module.exports = function(arrayLike) {
        var mapFn = arguments[1], thisArg = arguments[2], Context, i, j, arr, length, code, iterator, result, getIterator, value;
        arrayLike = Object(validValue(arrayLike));
        if (isValue(mapFn)) callable(mapFn);
        if (!this || this === Array || !isFunction(this)) {
          if (!mapFn) {
            if (isArguments(arrayLike)) {
              length = arrayLike.length;
              if (length !== 1) return Array.apply(null, arrayLike);
              arr = new Array(1);
              arr[0] = arrayLike[0];
              return arr;
            }
            if (isArray(arrayLike)) {
              arr = new Array(length = arrayLike.length);
              for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
              return arr;
            }
          }
          arr = [];
        } else {
          Context = this;
        }
        if (!isArray(arrayLike)) {
          if ((getIterator = arrayLike[iteratorSymbol]) !== void 0) {
            iterator = callable(getIterator).call(arrayLike);
            if (Context) arr = new Context();
            result = iterator.next();
            i = 0;
            while (!result.done) {
              value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
              if (Context) {
                desc.value = value;
                defineProperty(arr, i, desc);
              } else {
                arr[i] = value;
              }
              result = iterator.next();
              ++i;
            }
            length = i;
          } else if (isString(arrayLike)) {
            length = arrayLike.length;
            if (Context) arr = new Context();
            for (i = 0, j = 0; i < length; ++i) {
              value = arrayLike[i];
              if (i + 1 < length) {
                code = value.charCodeAt(0);
                if (code >= 55296 && code <= 56319) value += arrayLike[++i];
              }
              value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
              if (Context) {
                desc.value = value;
                defineProperty(arr, j, desc);
              } else {
                arr[j] = value;
              }
              ++j;
            }
            length = j;
          }
        }
        if (length === void 0) {
          length = toPosInt(arrayLike.length);
          if (Context) arr = new Context(length);
          for (i = 0; i < length; ++i) {
            value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i];
            if (Context) {
              desc.value = value;
              defineProperty(arr, i, desc);
            } else {
              arr[i] = value;
            }
          }
        }
        if (Context) {
          desc.value = null;
          arr.length = length;
        }
        return arr;
      };
    }
  });

  // node_modules/es5-ext/array/from/index.js
  var require_from = __commonJS({
    "node_modules/es5-ext/array/from/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented8()() ? Array.from : require_shim8();
    }
  });

  // node_modules/es5-ext/object/copy.js
  var require_copy2 = __commonJS({
    "node_modules/es5-ext/object/copy.js"(exports, module) {
      "use strict";
      var aFrom = require_from();
      var assign = require_assign();
      var value = require_valid_value();
      module.exports = function(obj) {
        var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]);
        if (copy !== obj && !propertyNames) return copy;
        var result = {};
        if (propertyNames) {
          aFrom(propertyNames, function(propertyName) {
            if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName];
          });
        } else {
          assign(result, obj);
        }
        return result;
      };
    }
  });

  // node_modules/es5-ext/object/_iterate.js
  var require_iterate = __commonJS({
    "node_modules/es5-ext/object/_iterate.js"(exports, module) {
      "use strict";
      var callable = require_valid_callable();
      var value = require_valid_value();
      var bind = Function.prototype.bind;
      var call = Function.prototype.call;
      var keys = Object.keys;
      var objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
      module.exports = function(method, defVal) {
        return function(obj, cb) {
          var list, thisArg = arguments[2], compareFn = arguments[3];
          obj = Object(value(obj));
          callable(cb);
          list = keys(obj);
          if (compareFn) {
            list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : void 0);
          }
          if (typeof method !== "function") method = list[method];
          return call.call(method, list, function(key, index) {
            if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
            return call.call(cb, thisArg, obj[key], key, obj, index);
          });
        };
      };
    }
  });

  // node_modules/es5-ext/object/for-each.js
  var require_for_each2 = __commonJS({
    "node_modules/es5-ext/object/for-each.js"(exports, module) {
      "use strict";
      module.exports = require_iterate()("forEach");
    }
  });

  // node_modules/es5-ext/object/map.js
  var require_map = __commonJS({
    "node_modules/es5-ext/object/map.js"(exports, module) {
      "use strict";
      var callable = require_valid_callable();
      var forEach = require_for_each2();
      var call = Function.prototype.call;
      module.exports = function(obj, cb) {
        var result = {}, thisArg = arguments[2];
        callable(cb);
        forEach(obj, function(value, key, targetObj, index) {
          result[key] = call.call(cb, thisArg, value, key, targetObj, index);
        });
        return result;
      };
    }
  });

  // node_modules/d/auto-bind.js
  var require_auto_bind = __commonJS({
    "node_modules/d/auto-bind.js"(exports, module) {
      "use strict";
      var isValue = require_is();
      var ensureValue = require_ensure();
      var ensurePlainFunction = require_ensure2();
      var copy = require_copy2();
      var normalizeOptions = require_normalize_options();
      var map = require_map();
      var bind = Function.prototype.bind;
      var defineProperty = Object.defineProperty;
      var hasOwnProperty2 = Object.prototype.hasOwnProperty;
      var define2;
      define2 = function(name2, desc, options) {
        var value = ensureValue(desc) && ensurePlainFunction(desc.value), dgs;
        dgs = copy(desc);
        delete dgs.writable;
        delete dgs.value;
        dgs.get = function() {
          if (!options.overwriteDefinition && hasOwnProperty2.call(this, name2)) return value;
          desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this);
          defineProperty(this, name2, desc);
          return this[name2];
        };
        return dgs;
      };
      module.exports = function(props) {
        var options = normalizeOptions(arguments[1]);
        if (isValue(options.resolveContext)) ensurePlainFunction(options.resolveContext);
        return map(props, function(desc, name2) {
          return define2(name2, desc, options);
        });
      };
    }
  });

  // node_modules/es6-iterator/index.js
  var require_es6_iterator = __commonJS({
    "node_modules/es6-iterator/index.js"(exports, module) {
      "use strict";
      var clear = require_clear();
      var assign = require_assign();
      var callable = require_valid_callable();
      var value = require_valid_value();
      var d = require_d();
      var autoBind = require_auto_bind();
      var Symbol2 = require_es6_symbol();
      var defineProperty = Object.defineProperty;
      var defineProperties = Object.defineProperties;
      var Iterator;
      module.exports = Iterator = function(list, context) {
        if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'");
        defineProperties(this, {
          __list__: d("w", value(list)),
          __context__: d("w", context),
          __nextIndex__: d("w", 0)
        });
        if (!context) return;
        callable(context.on);
        context.on("_add", this._onAdd);
        context.on("_delete", this._onDelete);
        context.on("_clear", this._onClear);
      };
      delete Iterator.prototype.constructor;
      defineProperties(
        Iterator.prototype,
        assign(
          {
            _next: d(function() {
              var i;
              if (!this.__list__) return void 0;
              if (this.__redo__) {
                i = this.__redo__.shift();
                if (i !== void 0) return i;
              }
              if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++;
              this._unBind();
              return void 0;
            }),
            next: d(function() {
              return this._createResult(this._next());
            }),
            _createResult: d(function(i) {
              if (i === void 0) return { done: true, value: void 0 };
              return { done: false, value: this._resolve(i) };
            }),
            _resolve: d(function(i) {
              return this.__list__[i];
            }),
            _unBind: d(function() {
              this.__list__ = null;
              delete this.__redo__;
              if (!this.__context__) return;
              this.__context__.off("_add", this._onAdd);
              this.__context__.off("_delete", this._onDelete);
              this.__context__.off("_clear", this._onClear);
              this.__context__ = null;
            }),
            toString: d(function() {
              return "[object " + (this[Symbol2.toStringTag] || "Object") + "]";
            })
          },
          autoBind({
            _onAdd: d(function(index) {
              if (index >= this.__nextIndex__) return;
              ++this.__nextIndex__;
              if (!this.__redo__) {
                defineProperty(this, "__redo__", d("c", [index]));
                return;
              }
              this.__redo__.forEach(function(redo, i) {
                if (redo >= index) this.__redo__[i] = ++redo;
              }, this);
              this.__redo__.push(index);
            }),
            _onDelete: d(function(index) {
              var i;
              if (index >= this.__nextIndex__) return;
              --this.__nextIndex__;
              if (!this.__redo__) return;
              i = this.__redo__.indexOf(index);
              if (i !== -1) this.__redo__.splice(i, 1);
              this.__redo__.forEach(function(redo, j) {
                if (redo > index) this.__redo__[j] = --redo;
              }, this);
            }),
            _onClear: d(function() {
              if (this.__redo__) clear.call(this.__redo__);
              this.__nextIndex__ = 0;
            })
          })
        )
      );
      defineProperty(
        Iterator.prototype,
        Symbol2.iterator,
        d(function() {
          return this;
        })
      );
    }
  });

  // node_modules/es6-iterator/array.js
  var require_array2 = __commonJS({
    "node_modules/es6-iterator/array.js"(exports, module) {
      "use strict";
      var setPrototypeOf = require_set_prototype_of();
      var contains = require_contains();
      var d = require_d();
      var Symbol2 = require_es6_symbol();
      var Iterator = require_es6_iterator();
      var defineProperty = Object.defineProperty;
      var ArrayIterator;
      ArrayIterator = module.exports = function(arr, kind) {
        if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'");
        Iterator.call(this, arr);
        if (!kind) kind = "value";
        else if (contains.call(kind, "key+value")) kind = "key+value";
        else if (contains.call(kind, "key")) kind = "key";
        else kind = "value";
        defineProperty(this, "__kind__", d("", kind));
      };
      if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
      delete ArrayIterator.prototype.constructor;
      ArrayIterator.prototype = Object.create(Iterator.prototype, {
        _resolve: d(function(i) {
          if (this.__kind__ === "value") return this.__list__[i];
          if (this.__kind__ === "key+value") return [i, this.__list__[i]];
          return i;
        })
      });
      defineProperty(ArrayIterator.prototype, Symbol2.toStringTag, d("c", "Array Iterator"));
    }
  });

  // node_modules/es6-iterator/string.js
  var require_string = __commonJS({
    "node_modules/es6-iterator/string.js"(exports, module) {
      "use strict";
      var setPrototypeOf = require_set_prototype_of();
      var d = require_d();
      var Symbol2 = require_es6_symbol();
      var Iterator = require_es6_iterator();
      var defineProperty = Object.defineProperty;
      var StringIterator;
      StringIterator = module.exports = function(str) {
        if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'");
        str = String(str);
        Iterator.call(this, str);
        defineProperty(this, "__length__", d("", str.length));
      };
      if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
      delete StringIterator.prototype.constructor;
      StringIterator.prototype = Object.create(Iterator.prototype, {
        _next: d(function() {
          if (!this.__list__) return void 0;
          if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++;
          this._unBind();
          return void 0;
        }),
        _resolve: d(function(i) {
          var char = this.__list__[i], code;
          if (this.__nextIndex__ === this.__length__) return char;
          code = char.charCodeAt(0);
          if (code >= 55296 && code <= 56319) return char + this.__list__[this.__nextIndex__++];
          return char;
        })
      });
      defineProperty(StringIterator.prototype, Symbol2.toStringTag, d("c", "String Iterator"));
    }
  });

  // node_modules/es6-iterator/is-iterable.js
  var require_is_iterable = __commonJS({
    "node_modules/es6-iterator/is-iterable.js"(exports, module) {
      "use strict";
      var isArguments = require_is_arguments2();
      var isValue = require_is_value();
      var isString = require_is_string();
      var iteratorSymbol = require_es6_symbol().iterator;
      var isArray = Array.isArray;
      module.exports = function(value) {
        if (!isValue(value)) return false;
        if (isArray(value)) return true;
        if (isString(value)) return true;
        if (isArguments(value)) return true;
        return typeof value[iteratorSymbol] === "function";
      };
    }
  });

  // node_modules/es6-iterator/valid-iterable.js
  var require_valid_iterable = __commonJS({
    "node_modules/es6-iterator/valid-iterable.js"(exports, module) {
      "use strict";
      var isIterable = require_is_iterable();
      module.exports = function(value) {
        if (!isIterable(value)) throw new TypeError(value + " is not iterable");
        return value;
      };
    }
  });

  // node_modules/es6-iterator/get.js
  var require_get2 = __commonJS({
    "node_modules/es6-iterator/get.js"(exports, module) {
      "use strict";
      var isArguments = require_is_arguments2();
      var isString = require_is_string();
      var ArrayIterator = require_array2();
      var StringIterator = require_string();
      var iterable = require_valid_iterable();
      var iteratorSymbol = require_es6_symbol().iterator;
      module.exports = function(obj) {
        if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol]();
        if (isArguments(obj)) return new ArrayIterator(obj);
        if (isString(obj)) return new StringIterator(obj);
        return new ArrayIterator(obj);
      };
    }
  });

  // node_modules/es6-iterator/for-of.js
  var require_for_of = __commonJS({
    "node_modules/es6-iterator/for-of.js"(exports, module) {
      "use strict";
      var isArguments = require_is_arguments2();
      var callable = require_valid_callable();
      var isString = require_is_string();
      var get = require_get2();
      var isArray = Array.isArray;
      var call = Function.prototype.call;
      var some = Array.prototype.some;
      module.exports = function(iterable, cb) {
        var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code;
        if (isArray(iterable) || isArguments(iterable)) mode = "array";
        else if (isString(iterable)) mode = "string";
        else iterable = get(iterable);
        callable(cb);
        doBreak = function() {
          broken = true;
        };
        if (mode === "array") {
          some.call(iterable, function(value) {
            call.call(cb, thisArg, value, doBreak);
            return broken;
          });
          return;
        }
        if (mode === "string") {
          length = iterable.length;
          for (i = 0; i < length; ++i) {
            char = iterable[i];
            if (i + 1 < length) {
              code = char.charCodeAt(0);
              if (code >= 55296 && code <= 56319) char += iterable[++i];
            }
            call.call(cb, thisArg, char, doBreak);
            if (broken) break;
          }
          return;
        }
        result = iterable.next();
        while (!result.done) {
          call.call(cb, thisArg, result.value, doBreak);
          if (broken) return;
          result = iterable.next();
        }
      };
    }
  });

  // node_modules/es6-weak-map/is-native-implemented.js
  var require_is_native_implemented = __commonJS({
    "node_modules/es6-weak-map/is-native-implemented.js"(exports, module) {
      "use strict";
      module.exports = function() {
        if (typeof WeakMap !== "function") return false;
        return Object.prototype.toString.call(/* @__PURE__ */ new WeakMap()) === "[object WeakMap]";
      }();
    }
  });

  // node_modules/es6-weak-map/polyfill.js
  var require_polyfill5 = __commonJS({
    "node_modules/es6-weak-map/polyfill.js"(exports, module) {
      "use strict";
      var isValue = require_is_value();
      var setPrototypeOf = require_set_prototype_of();
      var object = require_valid_object();
      var ensureValue = require_valid_value();
      var randomUniq = require_random_uniq();
      var d = require_d();
      var getIterator = require_get2();
      var forOf = require_for_of();
      var toStringTagSymbol = require_es6_symbol().toStringTag;
      var isNative = require_is_native_implemented();
      var isArray = Array.isArray;
      var defineProperty = Object.defineProperty;
      var objHasOwnProperty = Object.prototype.hasOwnProperty;
      var getPrototypeOf = Object.getPrototypeOf;
      var WeakMapPoly;
      module.exports = WeakMapPoly = function() {
        var iterable = arguments[0], self2;
        if (!(this instanceof WeakMapPoly)) throw new TypeError("Constructor requires 'new'");
        self2 = isNative && setPrototypeOf && WeakMap !== WeakMapPoly ? setPrototypeOf(/* @__PURE__ */ new WeakMap(), getPrototypeOf(this)) : this;
        if (isValue(iterable)) {
          if (!isArray(iterable)) iterable = getIterator(iterable);
        }
        defineProperty(self2, "__weakMapData__", d("c", "$weakMap$" + randomUniq()));
        if (!iterable) return self2;
        forOf(iterable, function(val) {
          ensureValue(val);
          self2.set(val[0], val[1]);
        });
        return self2;
      };
      if (isNative) {
        if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
        WeakMapPoly.prototype = Object.create(WeakMap.prototype, { constructor: d(WeakMapPoly) });
      }
      Object.defineProperties(WeakMapPoly.prototype, {
        delete: d(function(key) {
          if (objHasOwnProperty.call(object(key), this.__weakMapData__)) {
            delete key[this.__weakMapData__];
            return true;
          }
          return false;
        }),
        get: d(function(key) {
          if (!objHasOwnProperty.call(object(key), this.__weakMapData__)) return void 0;
          return key[this.__weakMapData__];
        }),
        has: d(function(key) {
          return objHasOwnProperty.call(object(key), this.__weakMapData__);
        }),
        set: d(function(key, value) {
          defineProperty(object(key), this.__weakMapData__, d("c", value));
          return this;
        }),
        toString: d(function() {
          return "[object WeakMap]";
        })
      });
      defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d("c", "WeakMap"));
    }
  });

  // node_modules/es6-weak-map/index.js
  var require_es6_weak_map = __commonJS({
    "node_modules/es6-weak-map/index.js"(exports, module) {
      "use strict";
      module.exports = require_is_implemented()() ? WeakMap : require_polyfill5();
    }
  });

  // node_modules/array-find-index/index.js
  var require_array_find_index = __commonJS({
    "node_modules/array-find-index/index.js"(exports, module) {
      "use strict";
      module.exports = function(arr, predicate, ctx) {
        if (typeof Array.prototype.findIndex === "function") {
          return arr.findIndex(predicate, ctx);
        }
        if (typeof predicate !== "function") {
          throw new TypeError("predicate must be a function");
        }
        var list = Object(arr);
        var len = list.length;
        if (len === 0) {
          return -1;
        }
        for (var i = 0; i < len; i++) {
          if (predicate.call(ctx, list[i], i, list)) {
            return i;
          }
        }
        return -1;
      };
    }
  });

  // node_modules/regl-line2d/index.js
  var require_regl_line2d = __commonJS({
    "node_modules/regl-line2d/index.js"(exports, module) {
      "use strict";
      var rgba3 = require_color_normalize();
      var getBounds = require_array_bounds();
      var extend2 = require_object_assign();
      var pick = require_pick_by_alias();
      var flatten = require_flatten_vertex_data();
      var triangulate = require_earcut();
      var normalize = require_array_normalize();
      var { float32, fract32 } = require_to_float32();
      var WeakMap2 = require_es6_weak_map();
      var parseRect = require_parse_rect();
      var findIndex = require_array_find_index();
      var rectVert = `
precision highp float;

attribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;
attribute vec4 color;
attribute float lineEnd, lineTop;

uniform vec2 scale, scaleFract, translate, translateFract;
uniform float thickness, pixelRatio, id, depth;
uniform vec4 viewport;

varying vec4 fragColor;
varying vec2 tangent;

vec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {
	// the order is important
	return position * scale + translate
       + positionFract * scale + translateFract
       + position * scaleFract
       + positionFract * scaleFract;
}

void main() {
	float lineStart = 1. - lineEnd;
	float lineOffset = lineTop * 2. - 1.;

	vec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);
	tangent = normalize(diff * scale * viewport.zw);
	vec2 normal = vec2(-tangent.y, tangent.x);

	vec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart
		+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd

		+ thickness * normal * .5 * lineOffset / viewport.zw;

	gl_Position = vec4(position * 2.0 - 1.0, depth, 1);

	fragColor = color / 255.;
}
`;
      var rectFrag = `
precision highp float;

uniform float dashLength, pixelRatio, thickness, opacity, id;
uniform sampler2D dashTexture;

varying vec4 fragColor;
varying vec2 tangent;

void main() {
	float alpha = 1.;

	float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;
	float dash = texture2D(dashTexture, vec2(t, .5)).r;

	gl_FragColor = fragColor;
	gl_FragColor.a *= alpha * opacity * dash;
}
`;
      var fillVert = `
precision highp float;

attribute vec2 position, positionFract;

uniform vec4 color;
uniform vec2 scale, scaleFract, translate, translateFract;
uniform float pixelRatio, id;
uniform vec4 viewport;
uniform float opacity;

varying vec4 fragColor;

const float MAX_LINES = 256.;

void main() {
	float depth = (MAX_LINES - 4. - id) / (MAX_LINES);

	vec2 position = position * scale + translate
       + positionFract * scale + translateFract
       + position * scaleFract
       + positionFract * scaleFract;

	gl_Position = vec4(position * 2.0 - 1.0, depth, 1);

	fragColor = color / 255.;
	fragColor.a *= opacity;
}
`;
      var fillFrag = `
precision highp float;
varying vec4 fragColor;

void main() {
	gl_FragColor = fragColor;
}
`;
      var milterVert = `
precision highp float;

attribute vec2 aCoord, bCoord, nextCoord, prevCoord;
attribute vec4 aColor, bColor;
attribute float lineEnd, lineTop;

uniform vec2 scale, translate;
uniform float thickness, pixelRatio, id, depth;
uniform vec4 viewport;
uniform float miterLimit, miterMode;

varying vec4 fragColor;
varying vec4 startCutoff, endCutoff;
varying vec2 tangent;
varying vec2 startCoord, endCoord;
varying float enableStartMiter, enableEndMiter;

const float REVERSE_THRESHOLD = -.875;
const float MIN_DIFF = 1e-6;

// TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead
// TODO: precalculate dot products, normalize things beforehead etc.
// TODO: refactor to rectangular algorithm

float distToLine(vec2 p, vec2 a, vec2 b) {
	vec2 diff = b - a;
	vec2 perp = normalize(vec2(-diff.y, diff.x));
	return dot(p - a, perp);
}

bool isNaN( float val ){
  return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;
}

void main() {
	vec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;

  vec2 adjustedScale;
  adjustedScale.x = (abs(scale.x) < MIN_DIFF) ? MIN_DIFF : scale.x;
  adjustedScale.y = (abs(scale.y) < MIN_DIFF) ? MIN_DIFF : scale.y;

  vec2 scaleRatio = adjustedScale * viewport.zw;
	vec2 normalWidth = thickness / scaleRatio;

	float lineStart = 1. - lineEnd;
	float lineBot = 1. - lineTop;

	fragColor = (lineStart * aColor + lineEnd * bColor) / 255.;

	if (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;

	if (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);
	if (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);


	vec2 prevDiff = aCoord - prevCoord;
	vec2 currDiff = bCoord - aCoord;
	vec2 nextDiff = nextCoord - bCoord;

	vec2 prevTangent = normalize(prevDiff * scaleRatio);
	vec2 currTangent = normalize(currDiff * scaleRatio);
	vec2 nextTangent = normalize(nextDiff * scaleRatio);

	vec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);
	vec2 currNormal = vec2(-currTangent.y, currTangent.x);
	vec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);

	vec2 startJoinDirection = normalize(prevTangent - currTangent);
	vec2 endJoinDirection = normalize(currTangent - nextTangent);

	// collapsed/unidirectional segment cases
	// FIXME: there should be more elegant solution
	vec2 prevTanDiff = abs(prevTangent - currTangent);
	vec2 nextTanDiff = abs(nextTangent - currTangent);
	if (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {
		startJoinDirection = currNormal;
	}
	if (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {
		endJoinDirection = currNormal;
	}
	if (aCoord == bCoord) {
		endJoinDirection = startJoinDirection;
		currNormal = prevNormal;
		currTangent = prevTangent;
	}

	tangent = currTangent;

	//calculate join shifts relative to normals
	float startJoinShift = dot(currNormal, startJoinDirection);
	float endJoinShift = dot(currNormal, endJoinDirection);

	float startMiterRatio = abs(1. / startJoinShift);
	float endMiterRatio = abs(1. / endJoinShift);

	vec2 startJoin = startJoinDirection * startMiterRatio;
	vec2 endJoin = endJoinDirection * endMiterRatio;

	vec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;
	startTopJoin = sign(startJoinShift) * startJoin * .5;
	startBotJoin = -startTopJoin;

	endTopJoin = sign(endJoinShift) * endJoin * .5;
	endBotJoin = -endTopJoin;

	vec2 aTopCoord = aCoord + normalWidth * startTopJoin;
	vec2 bTopCoord = bCoord + normalWidth * endTopJoin;
	vec2 aBotCoord = aCoord + normalWidth * startBotJoin;
	vec2 bBotCoord = bCoord + normalWidth * endBotJoin;

	//miter anti-clipping
	float baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));
	float abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));

	//prevent close to reverse direction switch
	bool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) <  length(normalWidth * currNormal);
	bool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) <  length(normalWidth * currNormal);

	if (prevReverse) {
		//make join rectangular
		vec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;
		float normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);
		aBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;
		aTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;
	}
	else if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {
		//handle miter clipping
		bTopCoord -= normalWidth * endTopJoin;
		bTopCoord += normalize(endTopJoin * normalWidth) * baClipping;
	}

	if (nextReverse) {
		//make join rectangular
		vec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;
		float normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);
		bBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;
		bTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;
	}
	else if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {
		//handle miter clipping
		aBotCoord -= normalWidth * startBotJoin;
		aBotCoord += normalize(startBotJoin * normalWidth) * abClipping;
	}

	vec2 aTopPosition = (aTopCoord) * adjustedScale + translate;
	vec2 aBotPosition = (aBotCoord) * adjustedScale + translate;

	vec2 bTopPosition = (bTopCoord) * adjustedScale + translate;
	vec2 bBotPosition = (bBotCoord) * adjustedScale + translate;

	//position is normalized 0..1 coord on the screen
	vec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;

	startCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;
	endCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;

	gl_Position = vec4(position  * 2.0 - 1.0, depth, 1);

	enableStartMiter = step(dot(currTangent, prevTangent), .5);
	enableEndMiter = step(dot(currTangent, nextTangent), .5);

	//bevel miter cutoffs
	if (miterMode == 1.) {
		if (enableStartMiter == 1.) {
			vec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;
			startCutoff = vec4(aCoord, aCoord);
			startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;
			startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
			startCutoff += viewport.xyxy;
			startCutoff += startMiterWidth.xyxy;
		}

		if (enableEndMiter == 1.) {
			vec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;
			endCutoff = vec4(bCoord, bCoord);
			endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;
			endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
			endCutoff += viewport.xyxy;
			endCutoff += endMiterWidth.xyxy;
		}
	}

	//round miter cutoffs
	else if (miterMode == 2.) {
		if (enableStartMiter == 1.) {
			vec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;
			startCutoff = vec4(aCoord, aCoord);
			startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;
			startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
			startCutoff += viewport.xyxy;
			startCutoff += startMiterWidth.xyxy;
		}

		if (enableEndMiter == 1.) {
			vec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;
			endCutoff = vec4(bCoord, bCoord);
			endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x)  / scaleRatio;
			endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;
			endCutoff += viewport.xyxy;
			endCutoff += endMiterWidth.xyxy;
		}
	}
}
`;
      var milterFrag = `
precision highp float;

uniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;
uniform sampler2D dashTexture;

varying vec4 fragColor;
varying vec2 tangent;
varying vec4 startCutoff, endCutoff;
varying vec2 startCoord, endCoord;
varying float enableStartMiter, enableEndMiter;

float distToLine(vec2 p, vec2 a, vec2 b) {
	vec2 diff = b - a;
	vec2 perp = normalize(vec2(-diff.y, diff.x));
	return dot(p - a, perp);
}

void main() {
	float alpha = 1., distToStart, distToEnd;
	float cutoff = thickness * .5;

	//bevel miter
	if (miterMode == 1.) {
		if (enableStartMiter == 1.) {
			distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);
			if (distToStart < -1.) {
				discard;
				return;
			}
			alpha *= min(max(distToStart + 1., 0.), 1.);
		}

		if (enableEndMiter == 1.) {
			distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);
			if (distToEnd < -1.) {
				discard;
				return;
			}
			alpha *= min(max(distToEnd + 1., 0.), 1.);
		}
	}

	// round miter
	else if (miterMode == 2.) {
		if (enableStartMiter == 1.) {
			distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);
			if (distToStart < 0.) {
				float radius = length(gl_FragCoord.xy - startCoord);

				if(radius > cutoff + .5) {
					discard;
					return;
				}

				alpha -= smoothstep(cutoff - .5, cutoff + .5, radius);
			}
		}

		if (enableEndMiter == 1.) {
			distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);
			if (distToEnd < 0.) {
				float radius = length(gl_FragCoord.xy - endCoord);

				if(radius > cutoff + .5) {
					discard;
					return;
				}

				alpha -= smoothstep(cutoff - .5, cutoff + .5, radius);
			}
		}
	}

	float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;
	float dash = texture2D(dashTexture, vec2(t, .5)).r;

	gl_FragColor = fragColor;
	gl_FragColor.a *= alpha * opacity * dash;
}
`;
      module.exports = Line2D;
      function Line2D(regl, options) {
        if (!(this instanceof Line2D)) return new Line2D(regl, options);
        if (typeof regl === "function") {
          if (!options) options = {};
          options.regl = regl;
        } else {
          options = regl;
        }
        if (options.length) options.positions = options;
        regl = options.regl;
        if (!regl.hasExtension("ANGLE_instanced_arrays")) {
          throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");
        }
        this.gl = regl._gl;
        this.regl = regl;
        this.passes = [];
        this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl);
        this.update(options);
      }
      Line2D.dashMult = 2;
      Line2D.maxPatternLength = 256;
      Line2D.precisionThreshold = 3e6;
      Line2D.maxPoints = 1e4;
      Line2D.maxLines = 2048;
      Line2D.shaders = new WeakMap2();
      Line2D.createShaders = function(regl) {
        let offsetBuffer = regl.buffer({
          usage: "static",
          type: "float",
          data: [0, 1, 0, 0, 1, 1, 1, 0]
        });
        let shaderOptions = {
          primitive: "triangle strip",
          instances: regl.prop("count"),
          count: 4,
          offset: 0,
          uniforms: {
            miterMode: (ctx, prop) => prop.join === "round" ? 2 : 1,
            miterLimit: regl.prop("miterLimit"),
            scale: regl.prop("scale"),
            scaleFract: regl.prop("scaleFract"),
            translateFract: regl.prop("translateFract"),
            translate: regl.prop("translate"),
            thickness: regl.prop("thickness"),
            dashTexture: regl.prop("dashTexture"),
            opacity: regl.prop("opacity"),
            pixelRatio: regl.context("pixelRatio"),
            id: regl.prop("id"),
            dashLength: regl.prop("dashLength"),
            viewport: (c, p) => [p.viewport.x, p.viewport.y, c.viewportWidth, c.viewportHeight],
            depth: regl.prop("depth")
          },
          blend: {
            enable: true,
            color: [0, 0, 0, 0],
            equation: {
              rgb: "add",
              alpha: "add"
            },
            func: {
              srcRGB: "src alpha",
              dstRGB: "one minus src alpha",
              srcAlpha: "one minus dst alpha",
              dstAlpha: "one"
            }
          },
          depth: {
            enable: (c, p) => {
              return !p.overlay;
            }
          },
          stencil: { enable: false },
          scissor: {
            enable: true,
            box: regl.prop("viewport")
          },
          viewport: regl.prop("viewport")
        };
        let drawRectLine = regl(extend2({
          vert: rectVert,
          frag: rectFrag,
          attributes: {
            // if point is at the end of segment
            lineEnd: {
              buffer: offsetBuffer,
              divisor: 0,
              stride: 8,
              offset: 0
            },
            // if point is at the top of segment
            lineTop: {
              buffer: offsetBuffer,
              divisor: 0,
              stride: 8,
              offset: 4
            },
            // beginning of line coordinate
            aCoord: {
              buffer: regl.prop("positionBuffer"),
              stride: 8,
              offset: 8,
              divisor: 1
            },
            // end of line coordinate
            bCoord: {
              buffer: regl.prop("positionBuffer"),
              stride: 8,
              offset: 16,
              divisor: 1
            },
            aCoordFract: {
              buffer: regl.prop("positionFractBuffer"),
              stride: 8,
              offset: 8,
              divisor: 1
            },
            bCoordFract: {
              buffer: regl.prop("positionFractBuffer"),
              stride: 8,
              offset: 16,
              divisor: 1
            },
            color: {
              buffer: regl.prop("colorBuffer"),
              stride: 4,
              offset: 0,
              divisor: 1
            }
          }
        }, shaderOptions));
        let drawMiterLine;
        try {
          drawMiterLine = regl(extend2({
            // culling removes polygon creasing
            cull: {
              enable: true,
              face: "back"
            },
            vert: milterVert,
            frag: milterFrag,
            attributes: {
              // is line end
              lineEnd: {
                buffer: offsetBuffer,
                divisor: 0,
                stride: 8,
                offset: 0
              },
              // is line top
              lineTop: {
                buffer: offsetBuffer,
                divisor: 0,
                stride: 8,
                offset: 4
              },
              // left color
              aColor: {
                buffer: regl.prop("colorBuffer"),
                stride: 4,
                offset: 0,
                divisor: 1
              },
              // right color
              bColor: {
                buffer: regl.prop("colorBuffer"),
                stride: 4,
                offset: 4,
                divisor: 1
              },
              prevCoord: {
                buffer: regl.prop("positionBuffer"),
                stride: 8,
                offset: 0,
                divisor: 1
              },
              aCoord: {
                buffer: regl.prop("positionBuffer"),
                stride: 8,
                offset: 8,
                divisor: 1
              },
              bCoord: {
                buffer: regl.prop("positionBuffer"),
                stride: 8,
                offset: 16,
                divisor: 1
              },
              nextCoord: {
                buffer: regl.prop("positionBuffer"),
                stride: 8,
                offset: 24,
                divisor: 1
              }
            }
          }, shaderOptions));
        } catch (e) {
          drawMiterLine = drawRectLine;
        }
        let drawFill = regl({
          primitive: "triangle",
          elements: (ctx, prop) => prop.triangles,
          offset: 0,
          vert: fillVert,
          frag: fillFrag,
          uniforms: {
            scale: regl.prop("scale"),
            color: regl.prop("fill"),
            scaleFract: regl.prop("scaleFract"),
            translateFract: regl.prop("translateFract"),
            translate: regl.prop("translate"),
            opacity: regl.prop("opacity"),
            pixelRatio: regl.context("pixelRatio"),
            id: regl.prop("id"),
            viewport: (ctx, prop) => [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]
          },
          attributes: {
            position: {
              buffer: regl.prop("positionBuffer"),
              stride: 8,
              offset: 8
            },
            positionFract: {
              buffer: regl.prop("positionFractBuffer"),
              stride: 8,
              offset: 8
            }
          },
          blend: shaderOptions.blend,
          depth: { enable: false },
          scissor: shaderOptions.scissor,
          stencil: shaderOptions.stencil,
          viewport: shaderOptions.viewport
        });
        return {
          fill: drawFill,
          rect: drawRectLine,
          miter: drawMiterLine
        };
      };
      Line2D.defaults = {
        dashes: null,
        join: "miter",
        miterLimit: 1,
        thickness: 10,
        cap: "square",
        color: "black",
        opacity: 1,
        overlay: false,
        viewport: null,
        range: null,
        close: false,
        fill: null
      };
      Line2D.prototype.render = function(...args) {
        if (args.length) {
          this.update(...args);
        }
        this.draw();
      };
      Line2D.prototype.draw = function(...args) {
        (args.length ? args : this.passes).forEach((s, i) => {
          if (s && Array.isArray(s)) return this.draw(...s);
          if (typeof s === "number") s = this.passes[s];
          if (!(s && s.count > 1 && s.opacity)) return;
          this.regl._refresh();
          if (s.fill && s.triangles && s.triangles.length > 2) {
            this.shaders.fill(s);
          }
          if (!s.thickness) return;
          if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) {
            this.shaders.rect(s);
          } else if (s.join === "rect" || !s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints)) {
            this.shaders.rect(s);
          } else {
            this.shaders.miter(s);
          }
        });
        return this;
      };
      Line2D.prototype.update = function(options) {
        if (!options) return;
        if (options.length != null) {
          if (typeof options[0] === "number") options = [{ positions: options }];
        } else if (!Array.isArray(options)) options = [options];
        let { regl, gl: gl2 } = this;
        options.forEach((o, i) => {
          let state = this.passes[i];
          if (o === void 0) return;
          if (o === null) {
            this.passes[i] = null;
            return;
          }
          if (typeof o[0] === "number") o = { positions: o };
          o = pick(o, {
            positions: "positions points data coords",
            thickness: "thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth",
            join: "lineJoin linejoin join type mode",
            miterLimit: "miterlimit miterLimit",
            dashes: "dash dashes dasharray dash-array dashArray",
            color: "color colour stroke colors colours stroke-color strokeColor",
            fill: "fill fill-color fillColor",
            opacity: "alpha opacity",
            overlay: "overlay crease overlap intersect",
            close: "closed close closed-path closePath",
            range: "range dataBox",
            viewport: "viewport viewBox",
            hole: "holes hole hollow",
            splitNull: "splitNull"
          });
          if (!state) {
            this.passes[i] = state = {
              id: i,
              scale: null,
              scaleFract: null,
              translate: null,
              translateFract: null,
              count: 0,
              hole: [],
              depth: 0,
              dashLength: 1,
              dashTexture: regl.texture({
                channels: 1,
                data: new Uint8Array([255]),
                width: 1,
                height: 1,
                mag: "linear",
                min: "linear"
              }),
              colorBuffer: regl.buffer({
                usage: "dynamic",
                type: "uint8",
                data: new Uint8Array()
              }),
              positionBuffer: regl.buffer({
                usage: "dynamic",
                type: "float",
                data: new Uint8Array()
              }),
              positionFractBuffer: regl.buffer({
                usage: "dynamic",
                type: "float",
                data: new Uint8Array()
              })
            };
            o = extend2({}, Line2D.defaults, o);
          }
          if (o.thickness != null) state.thickness = parseFloat(o.thickness);
          if (o.opacity != null) state.opacity = parseFloat(o.opacity);
          if (o.miterLimit != null) state.miterLimit = parseFloat(o.miterLimit);
          if (o.overlay != null) {
            state.overlay = !!o.overlay;
            if (i < Line2D.maxLines) {
              state.depth = 2 * (Line2D.maxLines - 1 - i % Line2D.maxLines) / Line2D.maxLines - 1;
            }
          }
          if (o.join != null) state.join = o.join;
          if (o.hole != null) state.hole = o.hole;
          if (o.fill != null) state.fill = !o.fill ? null : rgba3(o.fill, "uint8");
          if (o.viewport != null) state.viewport = parseRect(o.viewport);
          if (!state.viewport) {
            state.viewport = parseRect([
              gl2.drawingBufferWidth,
              gl2.drawingBufferHeight
            ]);
          }
          if (o.close != null) state.close = o.close;
          if (o.positions === null) o.positions = [];
          if (o.positions) {
            let positions, count;
            if (o.positions.x && o.positions.y) {
              let xPos = o.positions.x;
              let yPos = o.positions.y;
              count = state.count = Math.max(
                xPos.length,
                yPos.length
              );
              positions = new Float64Array(count * 2);
              for (let i2 = 0; i2 < count; i2++) {
                positions[i2 * 2] = xPos[i2];
                positions[i2 * 2 + 1] = yPos[i2];
              }
            } else {
              positions = flatten(o.positions, "float64");
              count = state.count = Math.floor(positions.length / 2);
            }
            let bounds = state.bounds = getBounds(positions, 2);
            if (state.fill) {
              let pos = [];
              let ids = {};
              let lastId = 0;
              for (let i2 = 0, ptr = 0, l = state.count; i2 < l; i2++) {
                let x = positions[i2 * 2];
                let y = positions[i2 * 2 + 1];
                if (isNaN(x) || isNaN(y) || x == null || y == null) {
                  x = positions[lastId * 2];
                  y = positions[lastId * 2 + 1];
                  ids[i2] = lastId;
                } else {
                  lastId = i2;
                }
                pos[ptr++] = x;
                pos[ptr++] = y;
              }
              if (o.splitNull) {
                if (!(state.count - 1 in ids)) ids[state.count] = state.count - 1;
                let splits = Object.keys(ids).map(Number).sort((a, b) => a - b);
                let split_triangles = [];
                let base = 0;
                let hole_base = state.hole != null ? state.hole[0] : null;
                if (hole_base != null) {
                  let last_id = findIndex(splits, (e) => e >= hole_base);
                  splits = splits.slice(0, last_id);
                  splits.push(hole_base);
                }
                for (let i2 = 0; i2 < splits.length; i2++) {
                  let seg_pos = pos.slice(base * 2, splits[i2] * 2).concat(
                    hole_base ? pos.slice(hole_base * 2) : []
                  );
                  let hole = (state.hole || []).map((e) => e - hole_base + (splits[i2] - base));
                  let triangles = triangulate(seg_pos, hole);
                  triangles = triangles.map(
                    (e) => e + base + (e + base < splits[i2] ? 0 : hole_base - splits[i2])
                  );
                  split_triangles.push(...triangles);
                  base = splits[i2] + 1;
                }
                for (let i2 = 0, l = split_triangles.length; i2 < l; i2++) {
                  if (ids[split_triangles[i2]] != null) split_triangles[i2] = ids[split_triangles[i2]];
                }
                state.triangles = split_triangles;
              } else {
                let triangles = triangulate(pos, state.hole || []);
                for (let i2 = 0, l = triangles.length; i2 < l; i2++) {
                  if (ids[triangles[i2]] != null) triangles[i2] = ids[triangles[i2]];
                }
                state.triangles = triangles;
              }
            }
            let npos = new Float64Array(positions);
            normalize(npos, 2, bounds);
            let positionData = new Float64Array(count * 2 + 6);
            if (state.close) {
              if (positions[0] === positions[count * 2 - 2] && positions[1] === positions[count * 2 - 1]) {
                positionData[0] = npos[count * 2 - 4];
                positionData[1] = npos[count * 2 - 3];
              } else {
                positionData[0] = npos[count * 2 - 2];
                positionData[1] = npos[count * 2 - 1];
              }
            } else {
              positionData[0] = npos[0];
              positionData[1] = npos[1];
            }
            positionData.set(npos, 2);
            if (state.close) {
              if (positions[0] === positions[count * 2 - 2] && positions[1] === positions[count * 2 - 1]) {
                positionData[count * 2 + 2] = npos[2];
                positionData[count * 2 + 3] = npos[3];
                state.count -= 1;
              } else {
                positionData[count * 2 + 2] = npos[0];
                positionData[count * 2 + 3] = npos[1];
                positionData[count * 2 + 4] = npos[2];
                positionData[count * 2 + 5] = npos[3];
              }
            } else {
              positionData[count * 2 + 2] = npos[count * 2 - 2];
              positionData[count * 2 + 3] = npos[count * 2 - 1];
              positionData[count * 2 + 4] = npos[count * 2 - 2];
              positionData[count * 2 + 5] = npos[count * 2 - 1];
            }
            var float_data = float32(positionData);
            state.positionBuffer(float_data);
            var frac_data = fract32(positionData, float_data);
            state.positionFractBuffer(frac_data);
          }
          if (o.range) {
            state.range = o.range;
          } else if (!state.range) {
            state.range = state.bounds;
          }
          if ((o.range || o.positions) && state.count) {
            let bounds = state.bounds;
            let boundsW = bounds[2] - bounds[0], boundsH = bounds[3] - bounds[1];
            let rangeW = state.range[2] - state.range[0], rangeH = state.range[3] - state.range[1];
            state.scale = [
              boundsW / rangeW,
              boundsH / rangeH
            ];
            state.translate = [
              -state.range[0] / rangeW + bounds[0] / rangeW || 0,
              -state.range[1] / rangeH + bounds[1] / rangeH || 0
            ];
            state.scaleFract = fract32(state.scale);
            state.translateFract = fract32(state.translate);
          }
          if (o.dashes) {
            let dashLength = 0, dashData;
            if (!o.dashes || o.dashes.length < 2) {
              dashLength = 1;
              dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]);
            } else {
              dashLength = 0;
              for (let i2 = 0; i2 < o.dashes.length; ++i2) {
                dashLength += o.dashes[i2];
              }
              dashData = new Uint8Array(dashLength * Line2D.dashMult);
              let ptr = 0;
              let fillColor = 255;
              for (let k = 0; k < 2; k++) {
                for (let i2 = 0; i2 < o.dashes.length; ++i2) {
                  for (let j = 0, l = o.dashes[i2] * Line2D.dashMult * 0.5; j < l; ++j) {
                    dashData[ptr++] = fillColor;
                  }
                  fillColor ^= 255;
                }
              }
            }
            state.dashLength = dashLength;
            state.dashTexture({
              channels: 1,
              data: dashData,
              width: dashData.length,
              height: 1,
              mag: "linear",
              min: "linear"
            }, 0, 0);
          }
          if (o.color) {
            let count = state.count;
            let colors = o.color;
            if (!colors) colors = "transparent";
            let colorData = new Uint8Array(count * 4 + 4);
            if (!Array.isArray(colors) || typeof colors[0] === "number") {
              let c = rgba3(colors, "uint8");
              for (let i2 = 0; i2 < count + 1; i2++) {
                colorData.set(c, i2 * 4);
              }
            } else {
              for (let i2 = 0; i2 < count; i2++) {
                let c = rgba3(colors[i2], "uint8");
                colorData.set(c, i2 * 4);
              }
              colorData.set(rgba3(colors[0], "uint8"), count * 4);
            }
            state.colorBuffer({
              usage: "dynamic",
              type: "uint8",
              data: colorData
            });
          }
        });
        if (options.length < this.passes.length) {
          for (let i = options.length; i < this.passes.length; i++) {
            let pass = this.passes[i];
            if (!pass) continue;
            pass.colorBuffer.destroy();
            pass.positionBuffer.destroy();
            pass.dashTexture.destroy();
          }
          this.passes.length = options.length;
        }
        let passes = [];
        for (let i = 0; i < this.passes.length; i++) {
          if (this.passes[i] !== null) passes.push(this.passes[i]);
        }
        this.passes = passes;
        return this;
      };
      Line2D.prototype.destroy = function() {
        this.passes.forEach((pass) => {
          pass.colorBuffer.destroy();
          pass.positionBuffer.destroy();
          pass.dashTexture.destroy();
        });
        this.passes.length = 0;
        return this;
      };
    }
  });

  // node_modules/regl-error2d/index.js
  var require_regl_error2d = __commonJS({
    "node_modules/regl-error2d/index.js"(exports, module) {
      "use strict";
      var getBounds = require_array_bounds();
      var rgba3 = require_color_normalize();
      var updateDiff = require_update_diff();
      var pick = require_pick_by_alias();
      var extend2 = require_object_assign();
      var flatten = require_flatten_vertex_data();
      var { float32, fract32 } = require_to_float32();
      module.exports = Error2D;
      var WEIGHTS = [
        //direction, lineWidth shift, capSize shift
        // x-error bar
        [1, 0, 0, 1, 0, 0],
        [1, 0, 0, -1, 0, 0],
        [-1, 0, 0, -1, 0, 0],
        [-1, 0, 0, -1, 0, 0],
        [-1, 0, 0, 1, 0, 0],
        [1, 0, 0, 1, 0, 0],
        // x-error right cap
        [1, 0, -1, 0, 0, 1],
        [1, 0, -1, 0, 0, -1],
        [1, 0, 1, 0, 0, -1],
        [1, 0, 1, 0, 0, -1],
        [1, 0, 1, 0, 0, 1],
        [1, 0, -1, 0, 0, 1],
        // x-error left cap
        [-1, 0, -1, 0, 0, 1],
        [-1, 0, -1, 0, 0, -1],
        [-1, 0, 1, 0, 0, -1],
        [-1, 0, 1, 0, 0, -1],
        [-1, 0, 1, 0, 0, 1],
        [-1, 0, -1, 0, 0, 1],
        // y-error bar
        [0, 1, 1, 0, 0, 0],
        [0, 1, -1, 0, 0, 0],
        [0, -1, -1, 0, 0, 0],
        [0, -1, -1, 0, 0, 0],
        [0, 1, 1, 0, 0, 0],
        [0, -1, 1, 0, 0, 0],
        // y-error top cap
        [0, 1, 0, -1, 1, 0],
        [0, 1, 0, -1, -1, 0],
        [0, 1, 0, 1, -1, 0],
        [0, 1, 0, 1, 1, 0],
        [0, 1, 0, -1, 1, 0],
        [0, 1, 0, 1, -1, 0],
        // y-error bottom cap
        [0, -1, 0, -1, 1, 0],
        [0, -1, 0, -1, -1, 0],
        [0, -1, 0, 1, -1, 0],
        [0, -1, 0, 1, 1, 0],
        [0, -1, 0, -1, 1, 0],
        [0, -1, 0, 1, -1, 0]
      ];
      function Error2D(regl, options) {
        if (typeof regl === "function") {
          if (!options) options = {};
          options.regl = regl;
        } else {
          options = regl;
        }
        if (options.length) options.positions = options;
        regl = options.regl;
        if (!regl.hasExtension("ANGLE_instanced_arrays")) {
          throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");
        }
        let gl2 = regl._gl, drawErrors, positionBuffer, positionFractBuffer, colorBuffer, errorBuffer, meshBuffer, defaults = {
          color: "black",
          capSize: 5,
          lineWidth: 1,
          opacity: 1,
          viewport: null,
          range: null,
          offset: 0,
          count: 0,
          bounds: null,
          positions: [],
          errors: []
        }, groups = [];
        colorBuffer = regl.buffer({
          usage: "dynamic",
          type: "uint8",
          data: new Uint8Array(0)
        });
        positionBuffer = regl.buffer({
          usage: "dynamic",
          type: "float",
          data: new Uint8Array(0)
        });
        positionFractBuffer = regl.buffer({
          usage: "dynamic",
          type: "float",
          data: new Uint8Array(0)
        });
        errorBuffer = regl.buffer({
          usage: "dynamic",
          type: "float",
          data: new Uint8Array(0)
        });
        meshBuffer = regl.buffer({
          usage: "static",
          type: "float",
          data: WEIGHTS
        });
        update(options);
        drawErrors = regl({
          vert: `
		precision highp float;

		attribute vec2 position, positionFract;
		attribute vec4 error;
		attribute vec4 color;

		attribute vec2 direction, lineOffset, capOffset;

		uniform vec4 viewport;
		uniform float lineWidth, capSize;
		uniform vec2 scale, scaleFract, translate, translateFract;

		varying vec4 fragColor;

		void main() {
			fragColor = color / 255.;

			vec2 pixelOffset = lineWidth * lineOffset + (capSize + lineWidth) * capOffset;

			vec2 dxy = -step(.5, direction.xy) * error.xz + step(direction.xy, vec2(-.5)) * error.yw;

			vec2 position = position + dxy;

			vec2 pos = (position + translate) * scale
				+ (positionFract + translateFract) * scale
				+ (position + translate) * scaleFract
				+ (positionFract + translateFract) * scaleFract;

			pos += pixelOffset / viewport.zw;

			gl_Position = vec4(pos * 2. - 1., 0, 1);
		}
		`,
          frag: `
		precision highp float;

		varying vec4 fragColor;

		uniform float opacity;

		void main() {
			gl_FragColor = fragColor;
			gl_FragColor.a *= opacity;
		}
		`,
          uniforms: {
            range: regl.prop("range"),
            lineWidth: regl.prop("lineWidth"),
            capSize: regl.prop("capSize"),
            opacity: regl.prop("opacity"),
            scale: regl.prop("scale"),
            translate: regl.prop("translate"),
            scaleFract: regl.prop("scaleFract"),
            translateFract: regl.prop("translateFract"),
            viewport: (ctx, prop) => [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]
          },
          attributes: {
            //dynamic attributes
            color: {
              buffer: colorBuffer,
              offset: (ctx, prop) => prop.offset * 4,
              divisor: 1
            },
            position: {
              buffer: positionBuffer,
              offset: (ctx, prop) => prop.offset * 8,
              divisor: 1
            },
            positionFract: {
              buffer: positionFractBuffer,
              offset: (ctx, prop) => prop.offset * 8,
              divisor: 1
            },
            error: {
              buffer: errorBuffer,
              offset: (ctx, prop) => prop.offset * 16,
              divisor: 1
            },
            //static attributes
            direction: {
              buffer: meshBuffer,
              stride: 24,
              offset: 0
            },
            lineOffset: {
              buffer: meshBuffer,
              stride: 24,
              offset: 8
            },
            capOffset: {
              buffer: meshBuffer,
              stride: 24,
              offset: 16
            }
          },
          primitive: "triangles",
          blend: {
            enable: true,
            color: [0, 0, 0, 0],
            equation: {
              rgb: "add",
              alpha: "add"
            },
            func: {
              srcRGB: "src alpha",
              dstRGB: "one minus src alpha",
              srcAlpha: "one minus dst alpha",
              dstAlpha: "one"
            }
          },
          depth: {
            enable: false
          },
          scissor: {
            enable: true,
            box: regl.prop("viewport")
          },
          viewport: regl.prop("viewport"),
          stencil: false,
          instances: regl.prop("count"),
          count: WEIGHTS.length
        });
        extend2(error2d, {
          update,
          draw,
          destroy,
          regl,
          gl: gl2,
          canvas: gl2.canvas,
          groups
        });
        return error2d;
        function error2d(opts) {
          if (opts) {
            update(opts);
          } else if (opts === null) {
            destroy();
          }
          draw();
        }
        function draw(options2) {
          if (typeof options2 === "number") return drawGroup(options2);
          if (options2 && !Array.isArray(options2)) options2 = [options2];
          regl._refresh();
          groups.forEach((s, i) => {
            if (!s) return;
            if (options2) {
              if (!options2[i]) s.draw = false;
              else s.draw = true;
            }
            if (!s.draw) {
              s.draw = true;
              return;
            }
            drawGroup(i);
          });
        }
        function drawGroup(s) {
          if (typeof s === "number") s = groups[s];
          if (s == null) return;
          if (!(s && s.count && s.color && s.opacity && s.positions && s.positions.length > 1)) return;
          s.scaleRatio = [
            s.scale[0] * s.viewport.width,
            s.scale[1] * s.viewport.height
          ];
          drawErrors(s);
          if (s.after) s.after(s);
        }
        function update(options2) {
          if (!options2) return;
          if (options2.length != null) {
            if (typeof options2[0] === "number") options2 = [{ positions: options2 }];
          } else if (!Array.isArray(options2)) options2 = [options2];
          let pointCount = 0, errorCount = 0;
          error2d.groups = groups = options2.map((options3, i) => {
            let group = groups[i];
            if (!options3) return group;
            else if (typeof options3 === "function") options3 = { after: options3 };
            else if (typeof options3[0] === "number") options3 = { positions: options3 };
            options3 = pick(options3, {
              color: "color colors fill",
              capSize: "capSize cap capsize cap-size",
              lineWidth: "lineWidth line-width width line thickness",
              opacity: "opacity alpha",
              range: "range dataBox",
              viewport: "viewport viewBox",
              errors: "errors error",
              positions: "positions position data points"
            });
            if (!group) {
              groups[i] = group = {
                id: i,
                scale: null,
                translate: null,
                scaleFract: null,
                translateFract: null,
                draw: true
              };
              options3 = extend2({}, defaults, options3);
            }
            updateDiff(group, options3, [{
              lineWidth: (v) => +v * 0.5,
              capSize: (v) => +v * 0.5,
              opacity: parseFloat,
              errors: (errors) => {
                errors = flatten(errors);
                errorCount += errors.length;
                return errors;
              },
              positions: (positions, state) => {
                positions = flatten(positions, "float64");
                state.count = Math.floor(positions.length / 2);
                state.bounds = getBounds(positions, 2);
                state.offset = pointCount;
                pointCount += state.count;
                return positions;
              }
            }, {
              color: (colors, state) => {
                let count = state.count;
                if (!colors) colors = "transparent";
                if (!Array.isArray(colors) || typeof colors[0] === "number") {
                  let color2 = colors;
                  colors = Array(count);
                  for (let i2 = 0; i2 < count; i2++) {
                    colors[i2] = color2;
                  }
                }
                if (colors.length < count) throw Error("Not enough colors");
                let colorData = new Uint8Array(count * 4);
                for (let i2 = 0; i2 < count; i2++) {
                  let c = rgba3(colors[i2], "uint8");
                  colorData.set(c, i2 * 4);
                }
                return colorData;
              },
              range: (range, state, options4) => {
                let bounds = state.bounds;
                if (!range) range = bounds;
                state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])];
                state.translate = [-range[0], -range[1]];
                state.scaleFract = fract32(state.scale);
                state.translateFract = fract32(state.translate);
                return range;
              },
              viewport: (vp) => {
                let viewport;
                if (Array.isArray(vp)) {
                  viewport = {
                    x: vp[0],
                    y: vp[1],
                    width: vp[2] - vp[0],
                    height: vp[3] - vp[1]
                  };
                } else if (vp) {
                  viewport = {
                    x: vp.x || vp.left || 0,
                    y: vp.y || vp.top || 0
                  };
                  if (vp.right) viewport.width = vp.right - viewport.x;
                  else viewport.width = vp.w || vp.width || 0;
                  if (vp.bottom) viewport.height = vp.bottom - viewport.y;
                  else viewport.height = vp.h || vp.height || 0;
                } else {
                  viewport = {
                    x: 0,
                    y: 0,
                    width: gl2.drawingBufferWidth,
                    height: gl2.drawingBufferHeight
                  };
                }
                return viewport;
              }
            }]);
            return group;
          });
          if (pointCount || errorCount) {
            let len = groups.reduce((acc, group, i) => {
              return acc + (group ? group.count : 0);
            }, 0);
            let positionData = new Float64Array(len * 2);
            let colorData = new Uint8Array(len * 4);
            let errorData = new Float32Array(len * 4);
            groups.forEach((group, i) => {
              if (!group) return;
              let { positions, count, offset, color: color2, errors } = group;
              if (!count) return;
              colorData.set(color2, offset * 4);
              errorData.set(errors, offset * 4);
              positionData.set(positions, offset * 2);
            });
            var float_data = float32(positionData);
            positionBuffer(float_data);
            var frac_data = fract32(positionData, float_data);
            positionFractBuffer(frac_data);
            colorBuffer(colorData);
            errorBuffer(errorData);
          }
        }
        function destroy() {
          positionBuffer.destroy();
          positionFractBuffer.destroy();
          colorBuffer.destroy();
          errorBuffer.destroy();
          meshBuffer.destroy();
        }
      }
    }
  });

  // node_modules/unquote/index.js
  var require_unquote = __commonJS({
    "node_modules/unquote/index.js"(exports, module) {
      var reg = /[\'\"]/;
      module.exports = function unquote(str) {
        if (!str) {
          return "";
        }
        if (reg.test(str.charAt(0))) {
          str = str.substr(1);
        }
        if (reg.test(str.charAt(str.length - 1))) {
          str = str.substr(0, str.length - 1);
        }
        return str;
      };
    }
  });

  // node_modules/css-global-keywords/index.json
  var require_css_global_keywords = __commonJS({
    "node_modules/css-global-keywords/index.json"(exports, module) {
      module.exports = [
        "inherit",
        "initial",
        "unset"
      ];
    }
  });

  // node_modules/css-system-font-keywords/index.json
  var require_css_system_font_keywords = __commonJS({
    "node_modules/css-system-font-keywords/index.json"(exports, module) {
      module.exports = [
        "caption",
        "icon",
        "menu",
        "message-box",
        "small-caption",
        "status-bar"
      ];
    }
  });

  // node_modules/css-font-weight-keywords/index.json
  var require_css_font_weight_keywords = __commonJS({
    "node_modules/css-font-weight-keywords/index.json"(exports, module) {
      module.exports = [
        "normal",
        "bold",
        "bolder",
        "lighter",
        "100",
        "200",
        "300",
        "400",
        "500",
        "600",
        "700",
        "800",
        "900"
      ];
    }
  });

  // node_modules/css-font-style-keywords/index.json
  var require_css_font_style_keywords = __commonJS({
    "node_modules/css-font-style-keywords/index.json"(exports, module) {
      module.exports = [
        "normal",
        "italic",
        "oblique"
      ];
    }
  });

  // node_modules/css-font-stretch-keywords/index.json
  var require_css_font_stretch_keywords = __commonJS({
    "node_modules/css-font-stretch-keywords/index.json"(exports, module) {
      module.exports = [
        "normal",
        "condensed",
        "semi-condensed",
        "extra-condensed",
        "ultra-condensed",
        "expanded",
        "semi-expanded",
        "extra-expanded",
        "ultra-expanded"
      ];
    }
  });

  // node_modules/parenthesis/index.js
  var require_parenthesis = __commonJS({
    "node_modules/parenthesis/index.js"(exports, module) {
      "use strict";
      function parse2(str, opts) {
        if (typeof str !== "string") return [str];
        var res = [str];
        if (typeof opts === "string" || Array.isArray(opts)) {
          opts = { brackets: opts };
        } else if (!opts) opts = {};
        var brackets = opts.brackets ? Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets] : ["{}", "[]", "()"];
        var escape2 = opts.escape || "___";
        var flat = !!opts.flat;
        brackets.forEach(function(bracket) {
          var pRE = new RegExp(["\\", bracket[0], "[^\\", bracket[0], "\\", bracket[1], "]*\\", bracket[1]].join(""));
          var ids = [];
          function replaceToken(token, idx, str2) {
            var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1;
            ids.push(refId);
            return escape2 + refId + escape2;
          }
          res.forEach(function(str2, i) {
            var prevStr;
            var a = 0;
            while (str2 != prevStr) {
              prevStr = str2;
              str2 = str2.replace(pRE, replaceToken);
              if (a++ > 1e4) throw Error("References have circular dependency. Please, check them.");
            }
            res[i] = str2;
          });
          ids = ids.reverse();
          res = res.map(function(str2) {
            ids.forEach(function(id) {
              str2 = str2.replace(new RegExp("(\\" + escape2 + id + "\\" + escape2 + ")", "g"), bracket[0] + "$1" + bracket[1]);
            });
            return str2;
          });
        });
        var re = new RegExp("\\" + escape2 + "([0-9]+)\\" + escape2);
        function nest(str2, refs, escape3) {
          var res2 = [], match;
          var a = 0;
          while (match = re.exec(str2)) {
            if (a++ > 1e4) throw Error("Circular references in parenthesis");
            res2.push(str2.slice(0, match.index));
            res2.push(nest(refs[match[1]], refs));
            str2 = str2.slice(match.index + match[0].length);
          }
          res2.push(str2);
          return res2;
        }
        return flat ? res : nest(res[0], res);
      }
      function stringify(arg, opts) {
        if (opts && opts.flat) {
          var escape2 = opts && opts.escape || "___";
          var str = arg[0], prevStr;
          if (!str) return "";
          var re = new RegExp("\\" + escape2 + "([0-9]+)\\" + escape2);
          var a = 0;
          while (str != prevStr) {
            if (a++ > 1e4) throw Error("Circular references in " + arg);
            prevStr = str;
            str = str.replace(re, replaceRef);
          }
          return str;
        }
        return arg.reduce(function f(prev, curr) {
          if (Array.isArray(curr)) {
            curr = curr.reduce(f, "");
          }
          return prev + curr;
        }, "");
        function replaceRef(match, idx) {
          if (arg[idx] == null) throw Error("Reference " + idx + "is undefined");
          return arg[idx];
        }
      }
      function parenthesis(arg, opts) {
        if (Array.isArray(arg)) {
          return stringify(arg, opts);
        } else {
          return parse2(arg, opts);
        }
      }
      parenthesis.parse = parse2;
      parenthesis.stringify = stringify;
      module.exports = parenthesis;
    }
  });

  // node_modules/string-split-by/index.js
  var require_string_split_by = __commonJS({
    "node_modules/string-split-by/index.js"(exports, module) {
      "use strict";
      var paren = require_parenthesis();
      module.exports = function splitBy(string, separator, o) {
        if (string == null) throw Error("First argument should be a string");
        if (separator == null) throw Error("Separator should be a string or a RegExp");
        if (!o) o = {};
        else if (typeof o === "string" || Array.isArray(o)) {
          o = { ignore: o };
        }
        if (o.escape == null) o.escape = true;
        if (o.ignore == null) o.ignore = ["[]", "()", "{}", "<>", '""', "''", "``", "\u201C\u201D", "\xAB\xBB"];
        else {
          if (typeof o.ignore === "string") {
            o.ignore = [o.ignore];
          }
          o.ignore = o.ignore.map(function(pair) {
            if (pair.length === 1) pair = pair + pair;
            return pair;
          });
        }
        var tokens = paren.parse(string, { flat: true, brackets: o.ignore });
        var str = tokens[0];
        var parts = str.split(separator);
        if (o.escape) {
          var cleanParts = [];
          for (var i = 0; i < parts.length; i++) {
            var prev = parts[i];
            var part = parts[i + 1];
            if (prev[prev.length - 1] === "\\" && prev[prev.length - 2] !== "\\") {
              cleanParts.push(prev + separator + part);
              i++;
            } else {
              cleanParts.push(prev);
            }
          }
          parts = cleanParts;
        }
        for (var i = 0; i < parts.length; i++) {
          tokens[0] = parts[i];
          parts[i] = paren.stringify(tokens, { flat: true });
        }
        return parts;
      };
    }
  });

  // node_modules/css-font-size-keywords/index.json
  var require_css_font_size_keywords = __commonJS({
    "node_modules/css-font-size-keywords/index.json"(exports, module) {
      module.exports = [
        "xx-small",
        "x-small",
        "small",
        "medium",
        "large",
        "x-large",
        "xx-large",
        "larger",
        "smaller"
      ];
    }
  });

  // node_modules/css-font/lib/util.js
  var require_util3 = __commonJS({
    "node_modules/css-font/lib/util.js"(exports, module) {
      "use strict";
      var sizes = require_css_font_size_keywords();
      module.exports = {
        isSize: function isSize(value) {
          return /^[\d\.]/.test(value) || value.indexOf("/") !== -1 || sizes.indexOf(value) !== -1;
        }
      };
    }
  });

  // node_modules/css-font/parse.js
  var require_parse = __commonJS({
    "node_modules/css-font/parse.js"(exports, module) {
      "use strict";
      var unquote = require_unquote();
      var globalKeywords = require_css_global_keywords();
      var systemFontKeywords = require_css_system_font_keywords();
      var fontWeightKeywords = require_css_font_weight_keywords();
      var fontStyleKeywords = require_css_font_style_keywords();
      var fontStretchKeywords = require_css_font_stretch_keywords();
      var splitBy = require_string_split_by();
      var isSize = require_util3().isSize;
      module.exports = parseFont;
      var cache = parseFont.cache = {};
      function parseFont(value) {
        if (typeof value !== "string") throw new Error("Font argument must be a string.");
        if (cache[value]) return cache[value];
        if (value === "") {
          throw new Error("Cannot parse an empty string.");
        }
        if (systemFontKeywords.indexOf(value) !== -1) {
          return cache[value] = { system: value };
        }
        var font = {
          style: "normal",
          variant: "normal",
          weight: "normal",
          stretch: "normal",
          lineHeight: "normal",
          size: "1rem",
          family: ["serif"]
        };
        var tokens = splitBy(value, /\s+/);
        var token;
        while (token = tokens.shift()) {
          if (globalKeywords.indexOf(token) !== -1) {
            ["style", "variant", "weight", "stretch"].forEach(function(prop) {
              font[prop] = token;
            });
            return cache[value] = font;
          }
          if (fontStyleKeywords.indexOf(token) !== -1) {
            font.style = token;
            continue;
          }
          if (token === "normal" || token === "small-caps") {
            font.variant = token;
            continue;
          }
          if (fontStretchKeywords.indexOf(token) !== -1) {
            font.stretch = token;
            continue;
          }
          if (fontWeightKeywords.indexOf(token) !== -1) {
            font.weight = token;
            continue;
          }
          if (isSize(token)) {
            var parts = splitBy(token, "/");
            font.size = parts[0];
            if (parts[1] != null) {
              font.lineHeight = parseLineHeight(parts[1]);
            } else if (tokens[0] === "/") {
              tokens.shift();
              font.lineHeight = parseLineHeight(tokens.shift());
            }
            if (!tokens.length) {
              throw new Error("Missing required font-family.");
            }
            font.family = splitBy(tokens.join(" "), /\s*,\s*/).map(unquote);
            return cache[value] = font;
          }
          throw new Error("Unknown or unsupported font token: " + token);
        }
        throw new Error("Missing required font-size.");
      }
      function parseLineHeight(value) {
        var parsed = parseFloat(value);
        if (parsed.toString() === value) {
          return parsed;
        }
        return value;
      }
    }
  });

  // node_modules/css-font/stringify.js
  var require_stringify = __commonJS({
    "node_modules/css-font/stringify.js"(exports, module) {
      "use strict";
      var pick = require_pick_by_alias();
      var isSize = require_util3().isSize;
      var globals = a2o(require_css_global_keywords());
      var systems = a2o(require_css_system_font_keywords());
      var weights = a2o(require_css_font_weight_keywords());
      var styles = a2o(require_css_font_style_keywords());
      var stretches = a2o(require_css_font_stretch_keywords());
      var variants = { "normal": 1, "small-caps": 1 };
      var fams = {
        "serif": 1,
        "sans-serif": 1,
        "monospace": 1,
        "cursive": 1,
        "fantasy": 1,
        "system-ui": 1
      };
      var defaults = {
        style: "normal",
        variant: "normal",
        weight: "normal",
        stretch: "normal",
        size: "1rem",
        lineHeight: "normal",
        family: "serif"
      };
      module.exports = function stringifyFont(o) {
        o = pick(o, {
          style: "style fontstyle fontStyle font-style slope distinction",
          variant: "variant font-variant fontVariant fontvariant var capitalization",
          weight: "weight w font-weight fontWeight fontweight",
          stretch: "stretch font-stretch fontStretch fontstretch width",
          size: "size s font-size fontSize fontsize height em emSize",
          lineHeight: "lh line-height lineHeight lineheight leading",
          family: "font family fontFamily font-family fontfamily type typeface face",
          system: "system reserved default global"
        });
        if (o.system) {
          if (o.system) verify(o.system, systems);
          return o.system;
        }
        verify(o.style, styles);
        verify(o.variant, variants);
        verify(o.weight, weights);
        verify(o.stretch, stretches);
        if (o.size == null) o.size = defaults.size;
        if (typeof o.size === "number") o.size += "px";
        if (!isSize) throw Error("Bad size value `" + o.size + "`");
        if (!o.family) o.family = defaults.family;
        if (Array.isArray(o.family)) {
          if (!o.family.length) o.family = [defaults.family];
          o.family = o.family.map(function(f) {
            return fams[f] ? f : '"' + f + '"';
          }).join(", ");
        }
        var result = [];
        result.push(o.style);
        if (o.variant !== o.style) result.push(o.variant);
        if (o.weight !== o.variant && o.weight !== o.style) result.push(o.weight);
        if (o.stretch !== o.weight && o.stretch !== o.variant && o.stretch !== o.style) result.push(o.stretch);
        result.push(o.size + (o.lineHeight == null || o.lineHeight === "normal" || o.lineHeight + "" === "1" ? "" : "/" + o.lineHeight));
        result.push(o.family);
        return result.filter(Boolean).join(" ");
      };
      function verify(value, values) {
        if (value && !values[value] && !globals[value]) throw Error("Unknown keyword `" + value + "`");
        return value;
      }
      function a2o(a) {
        var o = {};
        for (var i = 0; i < a.length; i++) {
          o[a[i]] = 1;
        }
        return o;
      }
    }
  });

  // node_modules/css-font/index.js
  var require_css_font = __commonJS({
    "node_modules/css-font/index.js"(exports, module) {
      "use strict";
      module.exports = {
        parse: require_parse(),
        stringify: require_stringify()
      };
    }
  });

  // node_modules/regl/dist/regl.unchecked.js
  var require_regl_unchecked = __commonJS({
    "node_modules/regl/dist/regl.unchecked.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && false ? define(factory) : global2.createREGL = factory();
      })(exports, function() {
        "use strict";
        var extend2 = function(base, opts) {
          var keys = Object.keys(opts);
          for (var i = 0; i < keys.length; ++i) {
            base[keys[i]] = opts[keys[i]];
          }
          return base;
        };
        var VARIABLE_COUNTER = 0;
        var DYN_FUNC = 0;
        var DYN_CONSTANT = 5;
        var DYN_ARRAY = 6;
        function DynamicVariable(type, data) {
          this.id = VARIABLE_COUNTER++;
          this.type = type;
          this.data = data;
        }
        function escapeStr(str) {
          return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
        }
        function splitParts(str) {
          if (str.length === 0) {
            return [];
          }
          var firstChar = str.charAt(0);
          var lastChar = str.charAt(str.length - 1);
          if (str.length > 1 && firstChar === lastChar && (firstChar === '"' || firstChar === "'")) {
            return ['"' + escapeStr(str.substr(1, str.length - 2)) + '"'];
          }
          var parts = /\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str);
          if (parts) {
            return splitParts(str.substr(0, parts.index)).concat(splitParts(parts[1])).concat(splitParts(str.substr(parts.index + parts[0].length)));
          }
          var subparts = str.split(".");
          if (subparts.length === 1) {
            return ['"' + escapeStr(str) + '"'];
          }
          var result = [];
          for (var i = 0; i < subparts.length; ++i) {
            result = result.concat(splitParts(subparts[i]));
          }
          return result;
        }
        function toAccessorString(str) {
          return "[" + splitParts(str).join("][") + "]";
        }
        function defineDynamic(type, data) {
          return new DynamicVariable(type, toAccessorString(data + ""));
        }
        function isDynamic(x) {
          return typeof x === "function" && !x._reglType || x instanceof DynamicVariable;
        }
        function unbox(x, path) {
          if (typeof x === "function") {
            return new DynamicVariable(DYN_FUNC, x);
          } else if (typeof x === "number" || typeof x === "boolean") {
            return new DynamicVariable(DYN_CONSTANT, x);
          } else if (Array.isArray(x)) {
            return new DynamicVariable(DYN_ARRAY, x.map(function(y, i) {
              return unbox(y, path + "[" + i + "]");
            }));
          } else if (x instanceof DynamicVariable) {
            return x;
          }
        }
        var dynamic = {
          DynamicVariable,
          define: defineDynamic,
          isDynamic,
          unbox,
          accessor: toAccessorString
        };
        var raf = {
          next: typeof requestAnimationFrame === "function" ? function(cb) {
            return requestAnimationFrame(cb);
          } : function(cb) {
            return setTimeout(cb, 16);
          },
          cancel: typeof cancelAnimationFrame === "function" ? function(raf2) {
            return cancelAnimationFrame(raf2);
          } : clearTimeout
        };
        var clock = typeof performance !== "undefined" && performance.now ? function() {
          return performance.now();
        } : function() {
          return +/* @__PURE__ */ new Date();
        };
        function createStringStore() {
          var stringIds = { "": 0 };
          var stringValues = [""];
          return {
            id: function(str) {
              var result = stringIds[str];
              if (result) {
                return result;
              }
              result = stringIds[str] = stringValues.length;
              stringValues.push(str);
              return result;
            },
            str: function(id) {
              return stringValues[id];
            }
          };
        }
        function createCanvas(element, onDone, pixelRatio) {
          var canvas = document.createElement("canvas");
          extend2(canvas.style, {
            border: 0,
            margin: 0,
            padding: 0,
            top: 0,
            left: 0,
            width: "100%",
            height: "100%"
          });
          element.appendChild(canvas);
          if (element === document.body) {
            canvas.style.position = "absolute";
            extend2(element.style, {
              margin: 0,
              padding: 0
            });
          }
          function resize() {
            var w = window.innerWidth;
            var h = window.innerHeight;
            if (element !== document.body) {
              var bounds = canvas.getBoundingClientRect();
              w = bounds.right - bounds.left;
              h = bounds.bottom - bounds.top;
            }
            canvas.width = pixelRatio * w;
            canvas.height = pixelRatio * h;
          }
          var resizeObserver;
          if (element !== document.body && typeof ResizeObserver === "function") {
            resizeObserver = new ResizeObserver(function() {
              setTimeout(resize);
            });
            resizeObserver.observe(element);
          } else {
            window.addEventListener("resize", resize, false);
          }
          function onDestroy() {
            if (resizeObserver) {
              resizeObserver.disconnect();
            } else {
              window.removeEventListener("resize", resize);
            }
            element.removeChild(canvas);
          }
          resize();
          return {
            canvas,
            onDestroy
          };
        }
        function createContext(canvas, contextAttributes) {
          function get(name2) {
            try {
              return canvas.getContext(name2, contextAttributes);
            } catch (e) {
              return null;
            }
          }
          return get("webgl") || get("experimental-webgl") || get("webgl-experimental");
        }
        function isHTMLElement(obj) {
          return typeof obj.nodeName === "string" && typeof obj.appendChild === "function" && typeof obj.getBoundingClientRect === "function";
        }
        function isWebGLContext(obj) {
          return typeof obj.drawArrays === "function" || typeof obj.drawElements === "function";
        }
        function parseExtensions(input) {
          if (typeof input === "string") {
            return input.split();
          }
          return input;
        }
        function getElement(desc) {
          if (typeof desc === "string") {
            return document.querySelector(desc);
          }
          return desc;
        }
        function parseArgs(args_) {
          var args = args_ || {};
          var element, container, canvas, gl2;
          var contextAttributes = {};
          var extensions = [];
          var optionalExtensions = [];
          var pixelRatio = typeof window === "undefined" ? 1 : window.devicePixelRatio;
          var profile = false;
          var cachedCode = {};
          var onDone = function(err) {
            if (err) {
            }
          };
          var onDestroy = function() {
          };
          if (typeof args === "string") {
            element = document.querySelector(args);
          } else if (typeof args === "object") {
            if (isHTMLElement(args)) {
              element = args;
            } else if (isWebGLContext(args)) {
              gl2 = args;
              canvas = gl2.canvas;
            } else {
              if ("gl" in args) {
                gl2 = args.gl;
              } else if ("canvas" in args) {
                canvas = getElement(args.canvas);
              } else if ("container" in args) {
                container = getElement(args.container);
              }
              if ("attributes" in args) {
                contextAttributes = args.attributes;
              }
              if ("extensions" in args) {
                extensions = parseExtensions(args.extensions);
              }
              if ("optionalExtensions" in args) {
                optionalExtensions = parseExtensions(args.optionalExtensions);
              }
              if ("onDone" in args) {
                onDone = args.onDone;
              }
              if ("profile" in args) {
                profile = !!args.profile;
              }
              if ("pixelRatio" in args) {
                pixelRatio = +args.pixelRatio;
              }
              if ("cachedCode" in args) {
                cachedCode = args.cachedCode;
              }
            }
          } else {
          }
          if (element) {
            if (element.nodeName.toLowerCase() === "canvas") {
              canvas = element;
            } else {
              container = element;
            }
          }
          if (!gl2) {
            if (!canvas) {
              var result = createCanvas(container || document.body, onDone, pixelRatio);
              if (!result) {
                return null;
              }
              canvas = result.canvas;
              onDestroy = result.onDestroy;
            }
            if (contextAttributes.premultipliedAlpha === void 0) contextAttributes.premultipliedAlpha = true;
            gl2 = createContext(canvas, contextAttributes);
          }
          if (!gl2) {
            onDestroy();
            onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org");
            return null;
          }
          return {
            gl: gl2,
            canvas,
            container,
            extensions,
            optionalExtensions,
            pixelRatio,
            profile,
            cachedCode,
            onDone,
            onDestroy
          };
        }
        function createExtensionCache(gl2, config) {
          var extensions = {};
          function tryLoadExtension(name_) {
            var name3 = name_.toLowerCase();
            var ext;
            try {
              ext = extensions[name3] = gl2.getExtension(name3);
            } catch (e) {
            }
            return !!ext;
          }
          for (var i = 0; i < config.extensions.length; ++i) {
            var name2 = config.extensions[i];
            if (!tryLoadExtension(name2)) {
              config.onDestroy();
              config.onDone('"' + name2 + '" extension is not supported by the current WebGL context, try upgrading your system or a different browser');
              return null;
            }
          }
          config.optionalExtensions.forEach(tryLoadExtension);
          return {
            extensions,
            restore: function() {
              Object.keys(extensions).forEach(function(name3) {
                if (extensions[name3] && !tryLoadExtension(name3)) {
                  throw new Error("(regl): error restoring extension " + name3);
                }
              });
            }
          };
        }
        function loop(n, f) {
          var result = Array(n);
          for (var i = 0; i < n; ++i) {
            result[i] = f(i);
          }
          return result;
        }
        var GL_BYTE = 5120;
        var GL_UNSIGNED_BYTE$1 = 5121;
        var GL_SHORT = 5122;
        var GL_UNSIGNED_SHORT = 5123;
        var GL_INT = 5124;
        var GL_UNSIGNED_INT = 5125;
        var GL_FLOAT$1 = 5126;
        function nextPow16(v) {
          for (var i = 16; i <= 1 << 28; i *= 16) {
            if (v <= i) {
              return i;
            }
          }
          return 0;
        }
        function log2(v) {
          var r, shift;
          r = (v > 65535) << 4;
          v >>>= r;
          shift = (v > 255) << 3;
          v >>>= shift;
          r |= shift;
          shift = (v > 15) << 2;
          v >>>= shift;
          r |= shift;
          shift = (v > 3) << 1;
          v >>>= shift;
          r |= shift;
          return r | v >> 1;
        }
        function createPool() {
          var bufferPool = loop(8, function() {
            return [];
          });
          function alloc(n) {
            var sz = nextPow16(n);
            var bin = bufferPool[log2(sz) >> 2];
            if (bin.length > 0) {
              return bin.pop();
            }
            return new ArrayBuffer(sz);
          }
          function free(buf) {
            bufferPool[log2(buf.byteLength) >> 2].push(buf);
          }
          function allocType(type, n) {
            var result = null;
            switch (type) {
              case GL_BYTE:
                result = new Int8Array(alloc(n), 0, n);
                break;
              case GL_UNSIGNED_BYTE$1:
                result = new Uint8Array(alloc(n), 0, n);
                break;
              case GL_SHORT:
                result = new Int16Array(alloc(2 * n), 0, n);
                break;
              case GL_UNSIGNED_SHORT:
                result = new Uint16Array(alloc(2 * n), 0, n);
                break;
              case GL_INT:
                result = new Int32Array(alloc(4 * n), 0, n);
                break;
              case GL_UNSIGNED_INT:
                result = new Uint32Array(alloc(4 * n), 0, n);
                break;
              case GL_FLOAT$1:
                result = new Float32Array(alloc(4 * n), 0, n);
                break;
              default:
                return null;
            }
            if (result.length !== n) {
              return result.subarray(0, n);
            }
            return result;
          }
          function freeType(array) {
            free(array.buffer);
          }
          return {
            alloc,
            free,
            allocType,
            freeType
          };
        }
        var pool = createPool();
        pool.zero = createPool();
        var GL_SUBPIXEL_BITS = 3408;
        var GL_RED_BITS = 3410;
        var GL_GREEN_BITS = 3411;
        var GL_BLUE_BITS = 3412;
        var GL_ALPHA_BITS = 3413;
        var GL_DEPTH_BITS = 3414;
        var GL_STENCIL_BITS = 3415;
        var GL_ALIASED_POINT_SIZE_RANGE = 33901;
        var GL_ALIASED_LINE_WIDTH_RANGE = 33902;
        var GL_MAX_TEXTURE_SIZE = 3379;
        var GL_MAX_VIEWPORT_DIMS = 3386;
        var GL_MAX_VERTEX_ATTRIBS = 34921;
        var GL_MAX_VERTEX_UNIFORM_VECTORS = 36347;
        var GL_MAX_VARYING_VECTORS = 36348;
        var GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 35661;
        var GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 35660;
        var GL_MAX_TEXTURE_IMAGE_UNITS = 34930;
        var GL_MAX_FRAGMENT_UNIFORM_VECTORS = 36349;
        var GL_MAX_CUBE_MAP_TEXTURE_SIZE = 34076;
        var GL_MAX_RENDERBUFFER_SIZE = 34024;
        var GL_VENDOR = 7936;
        var GL_RENDERER = 7937;
        var GL_VERSION = 7938;
        var GL_SHADING_LANGUAGE_VERSION = 35724;
        var GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 34047;
        var GL_MAX_COLOR_ATTACHMENTS_WEBGL = 36063;
        var GL_MAX_DRAW_BUFFERS_WEBGL = 34852;
        var GL_TEXTURE_2D = 3553;
        var GL_TEXTURE_CUBE_MAP = 34067;
        var GL_TEXTURE_CUBE_MAP_POSITIVE_X = 34069;
        var GL_TEXTURE0 = 33984;
        var GL_RGBA = 6408;
        var GL_FLOAT = 5126;
        var GL_UNSIGNED_BYTE = 5121;
        var GL_FRAMEBUFFER = 36160;
        var GL_FRAMEBUFFER_COMPLETE = 36053;
        var GL_COLOR_ATTACHMENT0 = 36064;
        var GL_COLOR_BUFFER_BIT$1 = 16384;
        var wrapLimits = function(gl2, extensions) {
          var maxAnisotropic = 1;
          if (extensions.ext_texture_filter_anisotropic) {
            maxAnisotropic = gl2.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT);
          }
          var maxDrawbuffers = 1;
          var maxColorAttachments = 1;
          if (extensions.webgl_draw_buffers) {
            maxDrawbuffers = gl2.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL);
            maxColorAttachments = gl2.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL);
          }
          var readFloat = !!extensions.oes_texture_float;
          if (readFloat) {
            var readFloatTexture = gl2.createTexture();
            gl2.bindTexture(GL_TEXTURE_2D, readFloatTexture);
            gl2.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, null);
            var fbo = gl2.createFramebuffer();
            gl2.bindFramebuffer(GL_FRAMEBUFFER, fbo);
            gl2.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, readFloatTexture, 0);
            gl2.bindTexture(GL_TEXTURE_2D, null);
            if (gl2.checkFramebufferStatus(GL_FRAMEBUFFER) !== GL_FRAMEBUFFER_COMPLETE) readFloat = false;
            else {
              gl2.viewport(0, 0, 1, 1);
              gl2.clearColor(1, 0, 0, 1);
              gl2.clear(GL_COLOR_BUFFER_BIT$1);
              var pixels = pool.allocType(GL_FLOAT, 4);
              gl2.readPixels(0, 0, 1, 1, GL_RGBA, GL_FLOAT, pixels);
              if (gl2.getError()) readFloat = false;
              else {
                gl2.deleteFramebuffer(fbo);
                gl2.deleteTexture(readFloatTexture);
                readFloat = pixels[0] === 1;
              }
              pool.freeType(pixels);
            }
          }
          var isIE = typeof navigator !== "undefined" && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion) || /Edge/.test(navigator.userAgent));
          var npotTextureCube = true;
          if (!isIE) {
            var cubeTexture = gl2.createTexture();
            var data = pool.allocType(GL_UNSIGNED_BYTE, 36);
            gl2.activeTexture(GL_TEXTURE0);
            gl2.bindTexture(GL_TEXTURE_CUBE_MAP, cubeTexture);
            gl2.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, 3, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
            pool.freeType(data);
            gl2.bindTexture(GL_TEXTURE_CUBE_MAP, null);
            gl2.deleteTexture(cubeTexture);
            npotTextureCube = !gl2.getError();
          }
          return {
            // drawing buffer bit depth
            colorBits: [
              gl2.getParameter(GL_RED_BITS),
              gl2.getParameter(GL_GREEN_BITS),
              gl2.getParameter(GL_BLUE_BITS),
              gl2.getParameter(GL_ALPHA_BITS)
            ],
            depthBits: gl2.getParameter(GL_DEPTH_BITS),
            stencilBits: gl2.getParameter(GL_STENCIL_BITS),
            subpixelBits: gl2.getParameter(GL_SUBPIXEL_BITS),
            // supported extensions
            extensions: Object.keys(extensions).filter(function(ext) {
              return !!extensions[ext];
            }),
            // max aniso samples
            maxAnisotropic,
            // max draw buffers
            maxDrawbuffers,
            maxColorAttachments,
            // point and line size ranges
            pointSizeDims: gl2.getParameter(GL_ALIASED_POINT_SIZE_RANGE),
            lineWidthDims: gl2.getParameter(GL_ALIASED_LINE_WIDTH_RANGE),
            maxViewportDims: gl2.getParameter(GL_MAX_VIEWPORT_DIMS),
            maxCombinedTextureUnits: gl2.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS),
            maxCubeMapSize: gl2.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE),
            maxRenderbufferSize: gl2.getParameter(GL_MAX_RENDERBUFFER_SIZE),
            maxTextureUnits: gl2.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS),
            maxTextureSize: gl2.getParameter(GL_MAX_TEXTURE_SIZE),
            maxAttributes: gl2.getParameter(GL_MAX_VERTEX_ATTRIBS),
            maxVertexUniforms: gl2.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS),
            maxVertexTextureUnits: gl2.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS),
            maxVaryingVectors: gl2.getParameter(GL_MAX_VARYING_VECTORS),
            maxFragmentUniforms: gl2.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS),
            // vendor info
            glsl: gl2.getParameter(GL_SHADING_LANGUAGE_VERSION),
            renderer: gl2.getParameter(GL_RENDERER),
            vendor: gl2.getParameter(GL_VENDOR),
            version: gl2.getParameter(GL_VERSION),
            // quirks
            readFloat,
            npotTextureCube
          };
        };
        var isTypedArray = function(x) {
          return x instanceof Uint8Array || x instanceof Uint16Array || x instanceof Uint32Array || x instanceof Int8Array || x instanceof Int16Array || x instanceof Int32Array || x instanceof Float32Array || x instanceof Float64Array || x instanceof Uint8ClampedArray;
        };
        function isNDArrayLike(obj) {
          return !!obj && typeof obj === "object" && Array.isArray(obj.shape) && Array.isArray(obj.stride) && typeof obj.offset === "number" && obj.shape.length === obj.stride.length && (Array.isArray(obj.data) || isTypedArray(obj.data));
        }
        var values = function(obj) {
          return Object.keys(obj).map(function(key) {
            return obj[key];
          });
        };
        var flattenUtils = {
          shape: arrayShape$1,
          flatten: flattenArray
        };
        function flatten1D(array, nx, out) {
          for (var i = 0; i < nx; ++i) {
            out[i] = array[i];
          }
        }
        function flatten2D(array, nx, ny, out) {
          var ptr = 0;
          for (var i = 0; i < nx; ++i) {
            var row = array[i];
            for (var j = 0; j < ny; ++j) {
              out[ptr++] = row[j];
            }
          }
        }
        function flatten3D(array, nx, ny, nz, out, ptr_) {
          var ptr = ptr_;
          for (var i = 0; i < nx; ++i) {
            var row = array[i];
            for (var j = 0; j < ny; ++j) {
              var col = row[j];
              for (var k = 0; k < nz; ++k) {
                out[ptr++] = col[k];
              }
            }
          }
        }
        function flattenRec(array, shape, level, out, ptr) {
          var stride = 1;
          for (var i = level + 1; i < shape.length; ++i) {
            stride *= shape[i];
          }
          var n = shape[level];
          if (shape.length - level === 4) {
            var nx = shape[level + 1];
            var ny = shape[level + 2];
            var nz = shape[level + 3];
            for (i = 0; i < n; ++i) {
              flatten3D(array[i], nx, ny, nz, out, ptr);
              ptr += stride;
            }
          } else {
            for (i = 0; i < n; ++i) {
              flattenRec(array[i], shape, level + 1, out, ptr);
              ptr += stride;
            }
          }
        }
        function flattenArray(array, shape, type, out_) {
          var sz = 1;
          if (shape.length) {
            for (var i = 0; i < shape.length; ++i) {
              sz *= shape[i];
            }
          } else {
            sz = 0;
          }
          var out = out_ || pool.allocType(type, sz);
          switch (shape.length) {
            case 0:
              break;
            case 1:
              flatten1D(array, shape[0], out);
              break;
            case 2:
              flatten2D(array, shape[0], shape[1], out);
              break;
            case 3:
              flatten3D(array, shape[0], shape[1], shape[2], out, 0);
              break;
            default:
              flattenRec(array, shape, 0, out, 0);
          }
          return out;
        }
        function arrayShape$1(array_) {
          var shape = [];
          for (var array = array_; array.length; array = array[0]) {
            shape.push(array.length);
          }
          return shape;
        }
        var arrayTypes = {
          "[object Int8Array]": 5120,
          "[object Int16Array]": 5122,
          "[object Int32Array]": 5124,
          "[object Uint8Array]": 5121,
          "[object Uint8ClampedArray]": 5121,
          "[object Uint16Array]": 5123,
          "[object Uint32Array]": 5125,
          "[object Float32Array]": 5126,
          "[object Float64Array]": 5121,
          "[object ArrayBuffer]": 5121
        };
        var int8 = 5120;
        var int16 = 5122;
        var int32 = 5124;
        var uint8 = 5121;
        var uint16 = 5123;
        var uint32 = 5125;
        var float = 5126;
        var float32 = 5126;
        var glTypes = {
          int8,
          int16,
          int32,
          uint8,
          uint16,
          uint32,
          float,
          float32
        };
        var dynamic$1 = 35048;
        var stream = 35040;
        var usageTypes = {
          dynamic: dynamic$1,
          stream,
          "static": 35044
        };
        var arrayFlatten = flattenUtils.flatten;
        var arrayShape = flattenUtils.shape;
        var GL_STATIC_DRAW = 35044;
        var GL_STREAM_DRAW = 35040;
        var GL_UNSIGNED_BYTE$2 = 5121;
        var GL_FLOAT$2 = 5126;
        var DTYPES_SIZES = [];
        DTYPES_SIZES[5120] = 1;
        DTYPES_SIZES[5122] = 2;
        DTYPES_SIZES[5124] = 4;
        DTYPES_SIZES[5121] = 1;
        DTYPES_SIZES[5123] = 2;
        DTYPES_SIZES[5125] = 4;
        DTYPES_SIZES[5126] = 4;
        function typedArrayCode(data) {
          return arrayTypes[Object.prototype.toString.call(data)] | 0;
        }
        function copyArray(out, inp) {
          for (var i = 0; i < inp.length; ++i) {
            out[i] = inp[i];
          }
        }
        function transpose(result, data, shapeX, shapeY, strideX, strideY, offset) {
          var ptr = 0;
          for (var i = 0; i < shapeX; ++i) {
            for (var j = 0; j < shapeY; ++j) {
              result[ptr++] = data[strideX * i + strideY * j + offset];
            }
          }
        }
        function wrapBufferState(gl2, stats2, config, destroyBuffer) {
          var bufferCount = 0;
          var bufferSet = {};
          function REGLBuffer(type) {
            this.id = bufferCount++;
            this.buffer = gl2.createBuffer();
            this.type = type;
            this.usage = GL_STATIC_DRAW;
            this.byteLength = 0;
            this.dimension = 1;
            this.dtype = GL_UNSIGNED_BYTE$2;
            this.persistentData = null;
            if (config.profile) {
              this.stats = { size: 0 };
            }
          }
          REGLBuffer.prototype.bind = function() {
            gl2.bindBuffer(this.type, this.buffer);
          };
          REGLBuffer.prototype.destroy = function() {
            destroy(this);
          };
          var streamPool = [];
          function createStream(type, data) {
            var buffer = streamPool.pop();
            if (!buffer) {
              buffer = new REGLBuffer(type);
            }
            buffer.bind();
            initBufferFromData(buffer, data, GL_STREAM_DRAW, 0, 1, false);
            return buffer;
          }
          function destroyStream(stream$$1) {
            streamPool.push(stream$$1);
          }
          function initBufferFromTypedArray(buffer, data, usage) {
            buffer.byteLength = data.byteLength;
            gl2.bufferData(buffer.type, data, usage);
          }
          function initBufferFromData(buffer, data, usage, dtype, dimension, persist) {
            var shape;
            buffer.usage = usage;
            if (Array.isArray(data)) {
              buffer.dtype = dtype || GL_FLOAT$2;
              if (data.length > 0) {
                var flatData;
                if (Array.isArray(data[0])) {
                  shape = arrayShape(data);
                  var dim = 1;
                  for (var i = 1; i < shape.length; ++i) {
                    dim *= shape[i];
                  }
                  buffer.dimension = dim;
                  flatData = arrayFlatten(data, shape, buffer.dtype);
                  initBufferFromTypedArray(buffer, flatData, usage);
                  if (persist) {
                    buffer.persistentData = flatData;
                  } else {
                    pool.freeType(flatData);
                  }
                } else if (typeof data[0] === "number") {
                  buffer.dimension = dimension;
                  var typedData = pool.allocType(buffer.dtype, data.length);
                  copyArray(typedData, data);
                  initBufferFromTypedArray(buffer, typedData, usage);
                  if (persist) {
                    buffer.persistentData = typedData;
                  } else {
                    pool.freeType(typedData);
                  }
                } else if (isTypedArray(data[0])) {
                  buffer.dimension = data[0].length;
                  buffer.dtype = dtype || typedArrayCode(data[0]) || GL_FLOAT$2;
                  flatData = arrayFlatten(
                    data,
                    [data.length, data[0].length],
                    buffer.dtype
                  );
                  initBufferFromTypedArray(buffer, flatData, usage);
                  if (persist) {
                    buffer.persistentData = flatData;
                  } else {
                    pool.freeType(flatData);
                  }
                } else {
                }
              }
            } else if (isTypedArray(data)) {
              buffer.dtype = dtype || typedArrayCode(data);
              buffer.dimension = dimension;
              initBufferFromTypedArray(buffer, data, usage);
              if (persist) {
                buffer.persistentData = new Uint8Array(new Uint8Array(data.buffer));
              }
            } else if (isNDArrayLike(data)) {
              shape = data.shape;
              var stride = data.stride;
              var offset = data.offset;
              var shapeX = 0;
              var shapeY = 0;
              var strideX = 0;
              var strideY = 0;
              if (shape.length === 1) {
                shapeX = shape[0];
                shapeY = 1;
                strideX = stride[0];
                strideY = 0;
              } else if (shape.length === 2) {
                shapeX = shape[0];
                shapeY = shape[1];
                strideX = stride[0];
                strideY = stride[1];
              } else {
              }
              buffer.dtype = dtype || typedArrayCode(data.data) || GL_FLOAT$2;
              buffer.dimension = shapeY;
              var transposeData2 = pool.allocType(buffer.dtype, shapeX * shapeY);
              transpose(
                transposeData2,
                data.data,
                shapeX,
                shapeY,
                strideX,
                strideY,
                offset
              );
              initBufferFromTypedArray(buffer, transposeData2, usage);
              if (persist) {
                buffer.persistentData = transposeData2;
              } else {
                pool.freeType(transposeData2);
              }
            } else if (data instanceof ArrayBuffer) {
              buffer.dtype = GL_UNSIGNED_BYTE$2;
              buffer.dimension = dimension;
              initBufferFromTypedArray(buffer, data, usage);
              if (persist) {
                buffer.persistentData = new Uint8Array(new Uint8Array(data));
              }
            } else {
            }
          }
          function destroy(buffer) {
            stats2.bufferCount--;
            destroyBuffer(buffer);
            var handle = buffer.buffer;
            gl2.deleteBuffer(handle);
            buffer.buffer = null;
            delete bufferSet[buffer.id];
          }
          function createBuffer(options, type, deferInit, persistent) {
            stats2.bufferCount++;
            var buffer = new REGLBuffer(type);
            bufferSet[buffer.id] = buffer;
            function reglBuffer(options2) {
              var usage = GL_STATIC_DRAW;
              var data = null;
              var byteLength = 0;
              var dtype = 0;
              var dimension = 1;
              if (Array.isArray(options2) || isTypedArray(options2) || isNDArrayLike(options2) || options2 instanceof ArrayBuffer) {
                data = options2;
              } else if (typeof options2 === "number") {
                byteLength = options2 | 0;
              } else if (options2) {
                if ("data" in options2) {
                  data = options2.data;
                }
                if ("usage" in options2) {
                  usage = usageTypes[options2.usage];
                }
                if ("type" in options2) {
                  dtype = glTypes[options2.type];
                }
                if ("dimension" in options2) {
                  dimension = options2.dimension | 0;
                }
                if ("length" in options2) {
                  byteLength = options2.length | 0;
                }
              }
              buffer.bind();
              if (!data) {
                if (byteLength) gl2.bufferData(buffer.type, byteLength, usage);
                buffer.dtype = dtype || GL_UNSIGNED_BYTE$2;
                buffer.usage = usage;
                buffer.dimension = dimension;
                buffer.byteLength = byteLength;
              } else {
                initBufferFromData(buffer, data, usage, dtype, dimension, persistent);
              }
              if (config.profile) {
                buffer.stats.size = buffer.byteLength * DTYPES_SIZES[buffer.dtype];
              }
              return reglBuffer;
            }
            function setSubData(data, offset) {
              gl2.bufferSubData(buffer.type, offset, data);
            }
            function subdata(data, offset_) {
              var offset = (offset_ || 0) | 0;
              var shape;
              buffer.bind();
              if (isTypedArray(data) || data instanceof ArrayBuffer) {
                setSubData(data, offset);
              } else if (Array.isArray(data)) {
                if (data.length > 0) {
                  if (typeof data[0] === "number") {
                    var converted = pool.allocType(buffer.dtype, data.length);
                    copyArray(converted, data);
                    setSubData(converted, offset);
                    pool.freeType(converted);
                  } else if (Array.isArray(data[0]) || isTypedArray(data[0])) {
                    shape = arrayShape(data);
                    var flatData = arrayFlatten(data, shape, buffer.dtype);
                    setSubData(flatData, offset);
                    pool.freeType(flatData);
                  } else {
                  }
                }
              } else if (isNDArrayLike(data)) {
                shape = data.shape;
                var stride = data.stride;
                var shapeX = 0;
                var shapeY = 0;
                var strideX = 0;
                var strideY = 0;
                if (shape.length === 1) {
                  shapeX = shape[0];
                  shapeY = 1;
                  strideX = stride[0];
                  strideY = 0;
                } else if (shape.length === 2) {
                  shapeX = shape[0];
                  shapeY = shape[1];
                  strideX = stride[0];
                  strideY = stride[1];
                } else {
                }
                var dtype = Array.isArray(data.data) ? buffer.dtype : typedArrayCode(data.data);
                var transposeData2 = pool.allocType(dtype, shapeX * shapeY);
                transpose(
                  transposeData2,
                  data.data,
                  shapeX,
                  shapeY,
                  strideX,
                  strideY,
                  data.offset
                );
                setSubData(transposeData2, offset);
                pool.freeType(transposeData2);
              } else {
              }
              return reglBuffer;
            }
            if (!deferInit) {
              reglBuffer(options);
            }
            reglBuffer._reglType = "buffer";
            reglBuffer._buffer = buffer;
            reglBuffer.subdata = subdata;
            if (config.profile) {
              reglBuffer.stats = buffer.stats;
            }
            reglBuffer.destroy = function() {
              destroy(buffer);
            };
            return reglBuffer;
          }
          function restoreBuffers() {
            values(bufferSet).forEach(function(buffer) {
              buffer.buffer = gl2.createBuffer();
              gl2.bindBuffer(buffer.type, buffer.buffer);
              gl2.bufferData(
                buffer.type,
                buffer.persistentData || buffer.byteLength,
                buffer.usage
              );
            });
          }
          if (config.profile) {
            stats2.getTotalBufferSize = function() {
              var total = 0;
              Object.keys(bufferSet).forEach(function(key) {
                total += bufferSet[key].stats.size;
              });
              return total;
            };
          }
          return {
            create: createBuffer,
            createStream,
            destroyStream,
            clear: function() {
              values(bufferSet).forEach(destroy);
              streamPool.forEach(destroy);
            },
            getBuffer: function(wrapper) {
              if (wrapper && wrapper._buffer instanceof REGLBuffer) {
                return wrapper._buffer;
              }
              return null;
            },
            restore: restoreBuffers,
            _initBuffer: initBufferFromData
          };
        }
        var points = 0;
        var point = 0;
        var lines = 1;
        var line = 1;
        var triangles = 4;
        var triangle = 4;
        var primTypes = {
          points,
          point,
          lines,
          line,
          triangles,
          triangle,
          "line loop": 2,
          "line strip": 3,
          "triangle strip": 5,
          "triangle fan": 6
        };
        var GL_POINTS = 0;
        var GL_LINES = 1;
        var GL_TRIANGLES = 4;
        var GL_BYTE$1 = 5120;
        var GL_UNSIGNED_BYTE$3 = 5121;
        var GL_SHORT$1 = 5122;
        var GL_UNSIGNED_SHORT$1 = 5123;
        var GL_INT$1 = 5124;
        var GL_UNSIGNED_INT$1 = 5125;
        var GL_ELEMENT_ARRAY_BUFFER = 34963;
        var GL_STREAM_DRAW$1 = 35040;
        var GL_STATIC_DRAW$1 = 35044;
        function wrapElementsState(gl2, extensions, bufferState, stats2) {
          var elementSet = {};
          var elementCount = 0;
          var elementTypes = {
            "uint8": GL_UNSIGNED_BYTE$3,
            "uint16": GL_UNSIGNED_SHORT$1
          };
          if (extensions.oes_element_index_uint) {
            elementTypes.uint32 = GL_UNSIGNED_INT$1;
          }
          function REGLElementBuffer(buffer) {
            this.id = elementCount++;
            elementSet[this.id] = this;
            this.buffer = buffer;
            this.primType = GL_TRIANGLES;
            this.vertCount = 0;
            this.type = 0;
          }
          REGLElementBuffer.prototype.bind = function() {
            this.buffer.bind();
          };
          var bufferPool = [];
          function createElementStream(data) {
            var result = bufferPool.pop();
            if (!result) {
              result = new REGLElementBuffer(bufferState.create(
                null,
                GL_ELEMENT_ARRAY_BUFFER,
                true,
                false
              )._buffer);
            }
            initElements(result, data, GL_STREAM_DRAW$1, -1, -1, 0, 0);
            return result;
          }
          function destroyElementStream(elements) {
            bufferPool.push(elements);
          }
          function initElements(elements, data, usage, prim, count, byteLength, type) {
            elements.buffer.bind();
            var dtype;
            if (data) {
              var predictedType = type;
              if (!type && (!isTypedArray(data) || isNDArrayLike(data) && !isTypedArray(data.data))) {
                predictedType = extensions.oes_element_index_uint ? GL_UNSIGNED_INT$1 : GL_UNSIGNED_SHORT$1;
              }
              bufferState._initBuffer(
                elements.buffer,
                data,
                usage,
                predictedType,
                3
              );
            } else {
              gl2.bufferData(GL_ELEMENT_ARRAY_BUFFER, byteLength, usage);
              elements.buffer.dtype = dtype || GL_UNSIGNED_BYTE$3;
              elements.buffer.usage = usage;
              elements.buffer.dimension = 3;
              elements.buffer.byteLength = byteLength;
            }
            dtype = type;
            if (!type) {
              switch (elements.buffer.dtype) {
                case GL_UNSIGNED_BYTE$3:
                case GL_BYTE$1:
                  dtype = GL_UNSIGNED_BYTE$3;
                  break;
                case GL_UNSIGNED_SHORT$1:
                case GL_SHORT$1:
                  dtype = GL_UNSIGNED_SHORT$1;
                  break;
                case GL_UNSIGNED_INT$1:
                case GL_INT$1:
                  dtype = GL_UNSIGNED_INT$1;
                  break;
                default:
              }
              elements.buffer.dtype = dtype;
            }
            elements.type = dtype;
            var vertCount = count;
            if (vertCount < 0) {
              vertCount = elements.buffer.byteLength;
              if (dtype === GL_UNSIGNED_SHORT$1) {
                vertCount >>= 1;
              } else if (dtype === GL_UNSIGNED_INT$1) {
                vertCount >>= 2;
              }
            }
            elements.vertCount = vertCount;
            var primType = prim;
            if (prim < 0) {
              primType = GL_TRIANGLES;
              var dimension = elements.buffer.dimension;
              if (dimension === 1) primType = GL_POINTS;
              if (dimension === 2) primType = GL_LINES;
              if (dimension === 3) primType = GL_TRIANGLES;
            }
            elements.primType = primType;
          }
          function destroyElements(elements) {
            stats2.elementsCount--;
            delete elementSet[elements.id];
            elements.buffer.destroy();
            elements.buffer = null;
          }
          function createElements(options, persistent) {
            var buffer = bufferState.create(null, GL_ELEMENT_ARRAY_BUFFER, true);
            var elements = new REGLElementBuffer(buffer._buffer);
            stats2.elementsCount++;
            function reglElements(options2) {
              if (!options2) {
                buffer();
                elements.primType = GL_TRIANGLES;
                elements.vertCount = 0;
                elements.type = GL_UNSIGNED_BYTE$3;
              } else if (typeof options2 === "number") {
                buffer(options2);
                elements.primType = GL_TRIANGLES;
                elements.vertCount = options2 | 0;
                elements.type = GL_UNSIGNED_BYTE$3;
              } else {
                var data = null;
                var usage = GL_STATIC_DRAW$1;
                var primType = -1;
                var vertCount = -1;
                var byteLength = 0;
                var dtype = 0;
                if (Array.isArray(options2) || isTypedArray(options2) || isNDArrayLike(options2)) {
                  data = options2;
                } else {
                  if ("data" in options2) {
                    data = options2.data;
                  }
                  if ("usage" in options2) {
                    usage = usageTypes[options2.usage];
                  }
                  if ("primitive" in options2) {
                    primType = primTypes[options2.primitive];
                  }
                  if ("count" in options2) {
                    vertCount = options2.count | 0;
                  }
                  if ("type" in options2) {
                    dtype = elementTypes[options2.type];
                  }
                  if ("length" in options2) {
                    byteLength = options2.length | 0;
                  } else {
                    byteLength = vertCount;
                    if (dtype === GL_UNSIGNED_SHORT$1 || dtype === GL_SHORT$1) {
                      byteLength *= 2;
                    } else if (dtype === GL_UNSIGNED_INT$1 || dtype === GL_INT$1) {
                      byteLength *= 4;
                    }
                  }
                }
                initElements(
                  elements,
                  data,
                  usage,
                  primType,
                  vertCount,
                  byteLength,
                  dtype
                );
              }
              return reglElements;
            }
            reglElements(options);
            reglElements._reglType = "elements";
            reglElements._elements = elements;
            reglElements.subdata = function(data, offset) {
              buffer.subdata(data, offset);
              return reglElements;
            };
            reglElements.destroy = function() {
              destroyElements(elements);
            };
            return reglElements;
          }
          return {
            create: createElements,
            createStream: createElementStream,
            destroyStream: destroyElementStream,
            getElements: function(elements) {
              if (typeof elements === "function" && elements._elements instanceof REGLElementBuffer) {
                return elements._elements;
              }
              return null;
            },
            clear: function() {
              values(elementSet).forEach(destroyElements);
            }
          };
        }
        var FLOAT = new Float32Array(1);
        var INT = new Uint32Array(FLOAT.buffer);
        var GL_UNSIGNED_SHORT$3 = 5123;
        function convertToHalfFloat(array) {
          var ushorts = pool.allocType(GL_UNSIGNED_SHORT$3, array.length);
          for (var i = 0; i < array.length; ++i) {
            if (isNaN(array[i])) {
              ushorts[i] = 65535;
            } else if (array[i] === Infinity) {
              ushorts[i] = 31744;
            } else if (array[i] === -Infinity) {
              ushorts[i] = 64512;
            } else {
              FLOAT[0] = array[i];
              var x = INT[0];
              var sgn = x >>> 31 << 15;
              var exp = (x << 1 >>> 24) - 127;
              var frac = x >> 13 & (1 << 10) - 1;
              if (exp < -24) {
                ushorts[i] = sgn;
              } else if (exp < -14) {
                var s = -14 - exp;
                ushorts[i] = sgn + (frac + (1 << 10) >> s);
              } else if (exp > 15) {
                ushorts[i] = sgn + 31744;
              } else {
                ushorts[i] = sgn + (exp + 15 << 10) + frac;
              }
            }
          }
          return ushorts;
        }
        function isArrayLike(s) {
          return Array.isArray(s) || isTypedArray(s);
        }
        var GL_COMPRESSED_TEXTURE_FORMATS = 34467;
        var GL_TEXTURE_2D$1 = 3553;
        var GL_TEXTURE_CUBE_MAP$1 = 34067;
        var GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 = 34069;
        var GL_RGBA$1 = 6408;
        var GL_ALPHA = 6406;
        var GL_RGB = 6407;
        var GL_LUMINANCE = 6409;
        var GL_LUMINANCE_ALPHA = 6410;
        var GL_RGBA4 = 32854;
        var GL_RGB5_A1 = 32855;
        var GL_RGB565 = 36194;
        var GL_UNSIGNED_SHORT_4_4_4_4 = 32819;
        var GL_UNSIGNED_SHORT_5_5_5_1 = 32820;
        var GL_UNSIGNED_SHORT_5_6_5 = 33635;
        var GL_UNSIGNED_INT_24_8_WEBGL = 34042;
        var GL_DEPTH_COMPONENT = 6402;
        var GL_DEPTH_STENCIL = 34041;
        var GL_SRGB_EXT = 35904;
        var GL_SRGB_ALPHA_EXT = 35906;
        var GL_HALF_FLOAT_OES = 36193;
        var GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 33776;
        var GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 33777;
        var GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 33778;
        var GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 33779;
        var GL_COMPRESSED_RGB_ATC_WEBGL = 35986;
        var GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 35987;
        var GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 34798;
        var GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 35840;
        var GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 35841;
        var GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 35842;
        var GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 35843;
        var GL_COMPRESSED_RGB_ETC1_WEBGL = 36196;
        var GL_UNSIGNED_BYTE$4 = 5121;
        var GL_UNSIGNED_SHORT$2 = 5123;
        var GL_UNSIGNED_INT$2 = 5125;
        var GL_FLOAT$3 = 5126;
        var GL_TEXTURE_WRAP_S = 10242;
        var GL_TEXTURE_WRAP_T = 10243;
        var GL_REPEAT = 10497;
        var GL_CLAMP_TO_EDGE = 33071;
        var GL_MIRRORED_REPEAT = 33648;
        var GL_TEXTURE_MAG_FILTER = 10240;
        var GL_TEXTURE_MIN_FILTER = 10241;
        var GL_NEAREST = 9728;
        var GL_LINEAR = 9729;
        var GL_NEAREST_MIPMAP_NEAREST = 9984;
        var GL_LINEAR_MIPMAP_NEAREST = 9985;
        var GL_NEAREST_MIPMAP_LINEAR = 9986;
        var GL_LINEAR_MIPMAP_LINEAR = 9987;
        var GL_GENERATE_MIPMAP_HINT = 33170;
        var GL_DONT_CARE = 4352;
        var GL_FASTEST = 4353;
        var GL_NICEST = 4354;
        var GL_TEXTURE_MAX_ANISOTROPY_EXT = 34046;
        var GL_UNPACK_ALIGNMENT = 3317;
        var GL_UNPACK_FLIP_Y_WEBGL = 37440;
        var GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL = 37441;
        var GL_UNPACK_COLORSPACE_CONVERSION_WEBGL = 37443;
        var GL_BROWSER_DEFAULT_WEBGL = 37444;
        var GL_TEXTURE0$1 = 33984;
        var MIPMAP_FILTERS = [
          GL_NEAREST_MIPMAP_NEAREST,
          GL_NEAREST_MIPMAP_LINEAR,
          GL_LINEAR_MIPMAP_NEAREST,
          GL_LINEAR_MIPMAP_LINEAR
        ];
        var CHANNELS_FORMAT = [
          0,
          GL_LUMINANCE,
          GL_LUMINANCE_ALPHA,
          GL_RGB,
          GL_RGBA$1
        ];
        var FORMAT_CHANNELS = {};
        FORMAT_CHANNELS[GL_LUMINANCE] = FORMAT_CHANNELS[GL_ALPHA] = FORMAT_CHANNELS[GL_DEPTH_COMPONENT] = 1;
        FORMAT_CHANNELS[GL_DEPTH_STENCIL] = FORMAT_CHANNELS[GL_LUMINANCE_ALPHA] = 2;
        FORMAT_CHANNELS[GL_RGB] = FORMAT_CHANNELS[GL_SRGB_EXT] = 3;
        FORMAT_CHANNELS[GL_RGBA$1] = FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT] = 4;
        function objectName(str) {
          return "[object " + str + "]";
        }
        var CANVAS_CLASS = objectName("HTMLCanvasElement");
        var OFFSCREENCANVAS_CLASS = objectName("OffscreenCanvas");
        var CONTEXT2D_CLASS = objectName("CanvasRenderingContext2D");
        var BITMAP_CLASS = objectName("ImageBitmap");
        var IMAGE_CLASS = objectName("HTMLImageElement");
        var VIDEO_CLASS = objectName("HTMLVideoElement");
        var PIXEL_CLASSES = Object.keys(arrayTypes).concat([
          CANVAS_CLASS,
          OFFSCREENCANVAS_CLASS,
          CONTEXT2D_CLASS,
          BITMAP_CLASS,
          IMAGE_CLASS,
          VIDEO_CLASS
        ]);
        var TYPE_SIZES = [];
        TYPE_SIZES[GL_UNSIGNED_BYTE$4] = 1;
        TYPE_SIZES[GL_FLOAT$3] = 4;
        TYPE_SIZES[GL_HALF_FLOAT_OES] = 2;
        TYPE_SIZES[GL_UNSIGNED_SHORT$2] = 2;
        TYPE_SIZES[GL_UNSIGNED_INT$2] = 4;
        var FORMAT_SIZES_SPECIAL = [];
        FORMAT_SIZES_SPECIAL[GL_RGBA4] = 2;
        FORMAT_SIZES_SPECIAL[GL_RGB5_A1] = 2;
        FORMAT_SIZES_SPECIAL[GL_RGB565] = 2;
        FORMAT_SIZES_SPECIAL[GL_DEPTH_STENCIL] = 4;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ATC_WEBGL] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ETC1_WEBGL] = 0.5;
        function isNumericArray(arr) {
          return Array.isArray(arr) && (arr.length === 0 || typeof arr[0] === "number");
        }
        function isRectArray(arr) {
          if (!Array.isArray(arr)) {
            return false;
          }
          var width = arr.length;
          if (width === 0 || !isArrayLike(arr[0])) {
            return false;
          }
          return true;
        }
        function classString(x) {
          return Object.prototype.toString.call(x);
        }
        function isCanvasElement(object) {
          return classString(object) === CANVAS_CLASS;
        }
        function isOffscreenCanvas(object) {
          return classString(object) === OFFSCREENCANVAS_CLASS;
        }
        function isContext2D(object) {
          return classString(object) === CONTEXT2D_CLASS;
        }
        function isBitmap(object) {
          return classString(object) === BITMAP_CLASS;
        }
        function isImageElement(object) {
          return classString(object) === IMAGE_CLASS;
        }
        function isVideoElement(object) {
          return classString(object) === VIDEO_CLASS;
        }
        function isPixelData(object) {
          if (!object) {
            return false;
          }
          var className = classString(object);
          if (PIXEL_CLASSES.indexOf(className) >= 0) {
            return true;
          }
          return isNumericArray(object) || isRectArray(object) || isNDArrayLike(object);
        }
        function typedArrayCode$1(data) {
          return arrayTypes[Object.prototype.toString.call(data)] | 0;
        }
        function convertData(result, data) {
          var n = data.length;
          switch (result.type) {
            case GL_UNSIGNED_BYTE$4:
            case GL_UNSIGNED_SHORT$2:
            case GL_UNSIGNED_INT$2:
            case GL_FLOAT$3:
              var converted = pool.allocType(result.type, n);
              converted.set(data);
              result.data = converted;
              break;
            case GL_HALF_FLOAT_OES:
              result.data = convertToHalfFloat(data);
              break;
            default:
          }
        }
        function preConvert(image, n) {
          return pool.allocType(
            image.type === GL_HALF_FLOAT_OES ? GL_FLOAT$3 : image.type,
            n
          );
        }
        function postConvert(image, data) {
          if (image.type === GL_HALF_FLOAT_OES) {
            image.data = convertToHalfFloat(data);
            pool.freeType(data);
          } else {
            image.data = data;
          }
        }
        function transposeData(image, array, strideX, strideY, strideC, offset) {
          var w = image.width;
          var h = image.height;
          var c = image.channels;
          var n = w * h * c;
          var data = preConvert(image, n);
          var p = 0;
          for (var i = 0; i < h; ++i) {
            for (var j = 0; j < w; ++j) {
              for (var k = 0; k < c; ++k) {
                data[p++] = array[strideX * j + strideY * i + strideC * k + offset];
              }
            }
          }
          postConvert(image, data);
        }
        function getTextureSize(format, type, width, height, isMipmap, isCube) {
          var s;
          if (typeof FORMAT_SIZES_SPECIAL[format] !== "undefined") {
            s = FORMAT_SIZES_SPECIAL[format];
          } else {
            s = FORMAT_CHANNELS[format] * TYPE_SIZES[type];
          }
          if (isCube) {
            s *= 6;
          }
          if (isMipmap) {
            var total = 0;
            var w = width;
            while (w >= 1) {
              total += s * w * w;
              w /= 2;
            }
            return total;
          } else {
            return s * width * height;
          }
        }
        function createTextureSet(gl2, extensions, limits, reglPoll, contextState, stats2, config) {
          var mipmapHint = {
            "don't care": GL_DONT_CARE,
            "dont care": GL_DONT_CARE,
            "nice": GL_NICEST,
            "fast": GL_FASTEST
          };
          var wrapModes = {
            "repeat": GL_REPEAT,
            "clamp": GL_CLAMP_TO_EDGE,
            "mirror": GL_MIRRORED_REPEAT
          };
          var magFilters = {
            "nearest": GL_NEAREST,
            "linear": GL_LINEAR
          };
          var minFilters = extend2({
            "mipmap": GL_LINEAR_MIPMAP_LINEAR,
            "nearest mipmap nearest": GL_NEAREST_MIPMAP_NEAREST,
            "linear mipmap nearest": GL_LINEAR_MIPMAP_NEAREST,
            "nearest mipmap linear": GL_NEAREST_MIPMAP_LINEAR,
            "linear mipmap linear": GL_LINEAR_MIPMAP_LINEAR
          }, magFilters);
          var colorSpace = {
            "none": 0,
            "browser": GL_BROWSER_DEFAULT_WEBGL
          };
          var textureTypes = {
            "uint8": GL_UNSIGNED_BYTE$4,
            "rgba4": GL_UNSIGNED_SHORT_4_4_4_4,
            "rgb565": GL_UNSIGNED_SHORT_5_6_5,
            "rgb5 a1": GL_UNSIGNED_SHORT_5_5_5_1
          };
          var textureFormats = {
            "alpha": GL_ALPHA,
            "luminance": GL_LUMINANCE,
            "luminance alpha": GL_LUMINANCE_ALPHA,
            "rgb": GL_RGB,
            "rgba": GL_RGBA$1,
            "rgba4": GL_RGBA4,
            "rgb5 a1": GL_RGB5_A1,
            "rgb565": GL_RGB565
          };
          var compressedTextureFormats = {};
          if (extensions.ext_srgb) {
            textureFormats.srgb = GL_SRGB_EXT;
            textureFormats.srgba = GL_SRGB_ALPHA_EXT;
          }
          if (extensions.oes_texture_float) {
            textureTypes.float32 = textureTypes.float = GL_FLOAT$3;
          }
          if (extensions.oes_texture_half_float) {
            textureTypes["float16"] = textureTypes["half float"] = GL_HALF_FLOAT_OES;
          }
          if (extensions.webgl_depth_texture) {
            extend2(textureFormats, {
              "depth": GL_DEPTH_COMPONENT,
              "depth stencil": GL_DEPTH_STENCIL
            });
            extend2(textureTypes, {
              "uint16": GL_UNSIGNED_SHORT$2,
              "uint32": GL_UNSIGNED_INT$2,
              "depth stencil": GL_UNSIGNED_INT_24_8_WEBGL
            });
          }
          if (extensions.webgl_compressed_texture_s3tc) {
            extend2(compressedTextureFormats, {
              "rgb s3tc dxt1": GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
              "rgba s3tc dxt1": GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
              "rgba s3tc dxt3": GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
              "rgba s3tc dxt5": GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
            });
          }
          if (extensions.webgl_compressed_texture_atc) {
            extend2(compressedTextureFormats, {
              "rgb atc": GL_COMPRESSED_RGB_ATC_WEBGL,
              "rgba atc explicit alpha": GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL,
              "rgba atc interpolated alpha": GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL
            });
          }
          if (extensions.webgl_compressed_texture_pvrtc) {
            extend2(compressedTextureFormats, {
              "rgb pvrtc 4bppv1": GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,
              "rgb pvrtc 2bppv1": GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG,
              "rgba pvrtc 4bppv1": GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,
              "rgba pvrtc 2bppv1": GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
            });
          }
          if (extensions.webgl_compressed_texture_etc1) {
            compressedTextureFormats["rgb etc1"] = GL_COMPRESSED_RGB_ETC1_WEBGL;
          }
          var supportedCompressedFormats = Array.prototype.slice.call(
            gl2.getParameter(GL_COMPRESSED_TEXTURE_FORMATS)
          );
          Object.keys(compressedTextureFormats).forEach(function(name2) {
            var format = compressedTextureFormats[name2];
            if (supportedCompressedFormats.indexOf(format) >= 0) {
              textureFormats[name2] = format;
            }
          });
          var supportedFormats = Object.keys(textureFormats);
          limits.textureFormats = supportedFormats;
          var textureFormatsInvert = [];
          Object.keys(textureFormats).forEach(function(key) {
            var val = textureFormats[key];
            textureFormatsInvert[val] = key;
          });
          var textureTypesInvert = [];
          Object.keys(textureTypes).forEach(function(key) {
            var val = textureTypes[key];
            textureTypesInvert[val] = key;
          });
          var magFiltersInvert = [];
          Object.keys(magFilters).forEach(function(key) {
            var val = magFilters[key];
            magFiltersInvert[val] = key;
          });
          var minFiltersInvert = [];
          Object.keys(minFilters).forEach(function(key) {
            var val = minFilters[key];
            minFiltersInvert[val] = key;
          });
          var wrapModesInvert = [];
          Object.keys(wrapModes).forEach(function(key) {
            var val = wrapModes[key];
            wrapModesInvert[val] = key;
          });
          var colorFormats = supportedFormats.reduce(function(color2, key) {
            var glenum = textureFormats[key];
            if (glenum === GL_LUMINANCE || glenum === GL_ALPHA || glenum === GL_LUMINANCE || glenum === GL_LUMINANCE_ALPHA || glenum === GL_DEPTH_COMPONENT || glenum === GL_DEPTH_STENCIL || extensions.ext_srgb && (glenum === GL_SRGB_EXT || glenum === GL_SRGB_ALPHA_EXT)) {
              color2[glenum] = glenum;
            } else if (glenum === GL_RGB5_A1 || key.indexOf("rgba") >= 0) {
              color2[glenum] = GL_RGBA$1;
            } else {
              color2[glenum] = GL_RGB;
            }
            return color2;
          }, {});
          function TexFlags() {
            this.internalformat = GL_RGBA$1;
            this.format = GL_RGBA$1;
            this.type = GL_UNSIGNED_BYTE$4;
            this.compressed = false;
            this.premultiplyAlpha = false;
            this.flipY = false;
            this.unpackAlignment = 1;
            this.colorSpace = GL_BROWSER_DEFAULT_WEBGL;
            this.width = 0;
            this.height = 0;
            this.channels = 0;
          }
          function copyFlags(result, other) {
            result.internalformat = other.internalformat;
            result.format = other.format;
            result.type = other.type;
            result.compressed = other.compressed;
            result.premultiplyAlpha = other.premultiplyAlpha;
            result.flipY = other.flipY;
            result.unpackAlignment = other.unpackAlignment;
            result.colorSpace = other.colorSpace;
            result.width = other.width;
            result.height = other.height;
            result.channels = other.channels;
          }
          function parseFlags(flags, options) {
            if (typeof options !== "object" || !options) {
              return;
            }
            if ("premultiplyAlpha" in options) {
              flags.premultiplyAlpha = options.premultiplyAlpha;
            }
            if ("flipY" in options) {
              flags.flipY = options.flipY;
            }
            if ("alignment" in options) {
              flags.unpackAlignment = options.alignment;
            }
            if ("colorSpace" in options) {
              flags.colorSpace = colorSpace[options.colorSpace];
            }
            if ("type" in options) {
              var type = options.type;
              flags.type = textureTypes[type];
            }
            var w = flags.width;
            var h = flags.height;
            var c = flags.channels;
            var hasChannels = false;
            if ("shape" in options) {
              w = options.shape[0];
              h = options.shape[1];
              if (options.shape.length === 3) {
                c = options.shape[2];
                hasChannels = true;
              }
            } else {
              if ("radius" in options) {
                w = h = options.radius;
              }
              if ("width" in options) {
                w = options.width;
              }
              if ("height" in options) {
                h = options.height;
              }
              if ("channels" in options) {
                c = options.channels;
                hasChannels = true;
              }
            }
            flags.width = w | 0;
            flags.height = h | 0;
            flags.channels = c | 0;
            var hasFormat = false;
            if ("format" in options) {
              var formatStr = options.format;
              var internalformat = flags.internalformat = textureFormats[formatStr];
              flags.format = colorFormats[internalformat];
              if (formatStr in textureTypes) {
                if (!("type" in options)) {
                  flags.type = textureTypes[formatStr];
                }
              }
              if (formatStr in compressedTextureFormats) {
                flags.compressed = true;
              }
              hasFormat = true;
            }
            if (!hasChannels && hasFormat) {
              flags.channels = FORMAT_CHANNELS[flags.format];
            } else if (hasChannels && !hasFormat) {
              if (flags.channels !== CHANNELS_FORMAT[flags.format]) {
                flags.format = flags.internalformat = CHANNELS_FORMAT[flags.channels];
              }
            } else if (hasFormat && hasChannels) {
            }
          }
          function setFlags(flags) {
            gl2.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL, flags.flipY);
            gl2.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, flags.premultiplyAlpha);
            gl2.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL, flags.colorSpace);
            gl2.pixelStorei(GL_UNPACK_ALIGNMENT, flags.unpackAlignment);
          }
          function TexImage() {
            TexFlags.call(this);
            this.xOffset = 0;
            this.yOffset = 0;
            this.data = null;
            this.needsFree = false;
            this.element = null;
            this.needsCopy = false;
          }
          function parseImage(image, options) {
            var data = null;
            if (isPixelData(options)) {
              data = options;
            } else if (options) {
              parseFlags(image, options);
              if ("x" in options) {
                image.xOffset = options.x | 0;
              }
              if ("y" in options) {
                image.yOffset = options.y | 0;
              }
              if (isPixelData(options.data)) {
                data = options.data;
              }
            }
            if (options.copy) {
              var viewW = contextState.viewportWidth;
              var viewH = contextState.viewportHeight;
              image.width = image.width || viewW - image.xOffset;
              image.height = image.height || viewH - image.yOffset;
              image.needsCopy = true;
            } else if (!data) {
              image.width = image.width || 1;
              image.height = image.height || 1;
              image.channels = image.channels || 4;
            } else if (isTypedArray(data)) {
              image.channels = image.channels || 4;
              image.data = data;
              if (!("type" in options) && image.type === GL_UNSIGNED_BYTE$4) {
                image.type = typedArrayCode$1(data);
              }
            } else if (isNumericArray(data)) {
              image.channels = image.channels || 4;
              convertData(image, data);
              image.alignment = 1;
              image.needsFree = true;
            } else if (isNDArrayLike(data)) {
              var array = data.data;
              if (!Array.isArray(array) && image.type === GL_UNSIGNED_BYTE$4) {
                image.type = typedArrayCode$1(array);
              }
              var shape = data.shape;
              var stride = data.stride;
              var shapeX, shapeY, shapeC, strideX, strideY, strideC;
              if (shape.length === 3) {
                shapeC = shape[2];
                strideC = stride[2];
              } else {
                shapeC = 1;
                strideC = 1;
              }
              shapeX = shape[0];
              shapeY = shape[1];
              strideX = stride[0];
              strideY = stride[1];
              image.alignment = 1;
              image.width = shapeX;
              image.height = shapeY;
              image.channels = shapeC;
              image.format = image.internalformat = CHANNELS_FORMAT[shapeC];
              image.needsFree = true;
              transposeData(image, array, strideX, strideY, strideC, data.offset);
            } else if (isCanvasElement(data) || isOffscreenCanvas(data) || isContext2D(data)) {
              if (isCanvasElement(data) || isOffscreenCanvas(data)) {
                image.element = data;
              } else {
                image.element = data.canvas;
              }
              image.width = image.element.width;
              image.height = image.element.height;
              image.channels = 4;
            } else if (isBitmap(data)) {
              image.element = data;
              image.width = data.width;
              image.height = data.height;
              image.channels = 4;
            } else if (isImageElement(data)) {
              image.element = data;
              image.width = data.naturalWidth;
              image.height = data.naturalHeight;
              image.channels = 4;
            } else if (isVideoElement(data)) {
              image.element = data;
              image.width = data.videoWidth;
              image.height = data.videoHeight;
              image.channels = 4;
            } else if (isRectArray(data)) {
              var w = image.width || data[0].length;
              var h = image.height || data.length;
              var c = image.channels;
              if (isArrayLike(data[0][0])) {
                c = c || data[0][0].length;
              } else {
                c = c || 1;
              }
              var arrayShape2 = flattenUtils.shape(data);
              var n = 1;
              for (var dd = 0; dd < arrayShape2.length; ++dd) {
                n *= arrayShape2[dd];
              }
              var allocData = preConvert(image, n);
              flattenUtils.flatten(data, arrayShape2, "", allocData);
              postConvert(image, allocData);
              image.alignment = 1;
              image.width = w;
              image.height = h;
              image.channels = c;
              image.format = image.internalformat = CHANNELS_FORMAT[c];
              image.needsFree = true;
            }
            if (image.type === GL_FLOAT$3) {
            } else if (image.type === GL_HALF_FLOAT_OES) {
            }
          }
          function setImage(info, target, miplevel) {
            var element = info.element;
            var data = info.data;
            var internalformat = info.internalformat;
            var format = info.format;
            var type = info.type;
            var width = info.width;
            var height = info.height;
            setFlags(info);
            if (element) {
              gl2.texImage2D(target, miplevel, format, format, type, element);
            } else if (info.compressed) {
              gl2.compressedTexImage2D(target, miplevel, internalformat, width, height, 0, data);
            } else if (info.needsCopy) {
              reglPoll();
              gl2.copyTexImage2D(
                target,
                miplevel,
                format,
                info.xOffset,
                info.yOffset,
                width,
                height,
                0
              );
            } else {
              gl2.texImage2D(target, miplevel, format, width, height, 0, format, type, data || null);
            }
          }
          function setSubImage(info, target, x, y, miplevel) {
            var element = info.element;
            var data = info.data;
            var internalformat = info.internalformat;
            var format = info.format;
            var type = info.type;
            var width = info.width;
            var height = info.height;
            setFlags(info);
            if (element) {
              gl2.texSubImage2D(
                target,
                miplevel,
                x,
                y,
                format,
                type,
                element
              );
            } else if (info.compressed) {
              gl2.compressedTexSubImage2D(
                target,
                miplevel,
                x,
                y,
                internalformat,
                width,
                height,
                data
              );
            } else if (info.needsCopy) {
              reglPoll();
              gl2.copyTexSubImage2D(
                target,
                miplevel,
                x,
                y,
                info.xOffset,
                info.yOffset,
                width,
                height
              );
            } else {
              gl2.texSubImage2D(
                target,
                miplevel,
                x,
                y,
                width,
                height,
                format,
                type,
                data
              );
            }
          }
          var imagePool = [];
          function allocImage() {
            return imagePool.pop() || new TexImage();
          }
          function freeImage(image) {
            if (image.needsFree) {
              pool.freeType(image.data);
            }
            TexImage.call(image);
            imagePool.push(image);
          }
          function MipMap() {
            TexFlags.call(this);
            this.genMipmaps = false;
            this.mipmapHint = GL_DONT_CARE;
            this.mipmask = 0;
            this.images = Array(16);
          }
          function parseMipMapFromShape(mipmap, width, height) {
            var img = mipmap.images[0] = allocImage();
            mipmap.mipmask = 1;
            img.width = mipmap.width = width;
            img.height = mipmap.height = height;
            img.channels = mipmap.channels = 4;
          }
          function parseMipMapFromObject(mipmap, options) {
            var imgData = null;
            if (isPixelData(options)) {
              imgData = mipmap.images[0] = allocImage();
              copyFlags(imgData, mipmap);
              parseImage(imgData, options);
              mipmap.mipmask = 1;
            } else {
              parseFlags(mipmap, options);
              if (Array.isArray(options.mipmap)) {
                var mipData = options.mipmap;
                for (var i = 0; i < mipData.length; ++i) {
                  imgData = mipmap.images[i] = allocImage();
                  copyFlags(imgData, mipmap);
                  imgData.width >>= i;
                  imgData.height >>= i;
                  parseImage(imgData, mipData[i]);
                  mipmap.mipmask |= 1 << i;
                }
              } else {
                imgData = mipmap.images[0] = allocImage();
                copyFlags(imgData, mipmap);
                parseImage(imgData, options);
                mipmap.mipmask = 1;
              }
            }
            copyFlags(mipmap, mipmap.images[0]);
            if (mipmap.compressed && (mipmap.internalformat === GL_COMPRESSED_RGB_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT3_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)) {
            }
          }
          function setMipMap(mipmap, target) {
            var images = mipmap.images;
            for (var i = 0; i < images.length; ++i) {
              if (!images[i]) {
                return;
              }
              setImage(images[i], target, i);
            }
          }
          var mipPool = [];
          function allocMipMap() {
            var result = mipPool.pop() || new MipMap();
            TexFlags.call(result);
            result.mipmask = 0;
            for (var i = 0; i < 16; ++i) {
              result.images[i] = null;
            }
            return result;
          }
          function freeMipMap(mipmap) {
            var images = mipmap.images;
            for (var i = 0; i < images.length; ++i) {
              if (images[i]) {
                freeImage(images[i]);
              }
              images[i] = null;
            }
            mipPool.push(mipmap);
          }
          function TexInfo() {
            this.minFilter = GL_NEAREST;
            this.magFilter = GL_NEAREST;
            this.wrapS = GL_CLAMP_TO_EDGE;
            this.wrapT = GL_CLAMP_TO_EDGE;
            this.anisotropic = 1;
            this.genMipmaps = false;
            this.mipmapHint = GL_DONT_CARE;
          }
          function parseTexInfo(info, options) {
            if ("min" in options) {
              var minFilter = options.min;
              info.minFilter = minFilters[minFilter];
              if (MIPMAP_FILTERS.indexOf(info.minFilter) >= 0 && !("faces" in options)) {
                info.genMipmaps = true;
              }
            }
            if ("mag" in options) {
              var magFilter = options.mag;
              info.magFilter = magFilters[magFilter];
            }
            var wrapS = info.wrapS;
            var wrapT = info.wrapT;
            if ("wrap" in options) {
              var wrap = options.wrap;
              if (typeof wrap === "string") {
                wrapS = wrapT = wrapModes[wrap];
              } else if (Array.isArray(wrap)) {
                wrapS = wrapModes[wrap[0]];
                wrapT = wrapModes[wrap[1]];
              }
            } else {
              if ("wrapS" in options) {
                var optWrapS = options.wrapS;
                wrapS = wrapModes[optWrapS];
              }
              if ("wrapT" in options) {
                var optWrapT = options.wrapT;
                wrapT = wrapModes[optWrapT];
              }
            }
            info.wrapS = wrapS;
            info.wrapT = wrapT;
            if ("anisotropic" in options) {
              var anisotropic = options.anisotropic;
              info.anisotropic = options.anisotropic;
            }
            if ("mipmap" in options) {
              var hasMipMap = false;
              switch (typeof options.mipmap) {
                case "string":
                  info.mipmapHint = mipmapHint[options.mipmap];
                  info.genMipmaps = true;
                  hasMipMap = true;
                  break;
                case "boolean":
                  hasMipMap = info.genMipmaps = options.mipmap;
                  break;
                case "object":
                  info.genMipmaps = false;
                  hasMipMap = true;
                  break;
                default:
              }
              if (hasMipMap && !("min" in options)) {
                info.minFilter = GL_NEAREST_MIPMAP_NEAREST;
              }
            }
          }
          function setTexInfo(info, target) {
            gl2.texParameteri(target, GL_TEXTURE_MIN_FILTER, info.minFilter);
            gl2.texParameteri(target, GL_TEXTURE_MAG_FILTER, info.magFilter);
            gl2.texParameteri(target, GL_TEXTURE_WRAP_S, info.wrapS);
            gl2.texParameteri(target, GL_TEXTURE_WRAP_T, info.wrapT);
            if (extensions.ext_texture_filter_anisotropic) {
              gl2.texParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, info.anisotropic);
            }
            if (info.genMipmaps) {
              gl2.hint(GL_GENERATE_MIPMAP_HINT, info.mipmapHint);
              gl2.generateMipmap(target);
            }
          }
          var textureCount = 0;
          var textureSet = {};
          var numTexUnits = limits.maxTextureUnits;
          var textureUnits = Array(numTexUnits).map(function() {
            return null;
          });
          function REGLTexture(target) {
            TexFlags.call(this);
            this.mipmask = 0;
            this.internalformat = GL_RGBA$1;
            this.id = textureCount++;
            this.refCount = 1;
            this.target = target;
            this.texture = gl2.createTexture();
            this.unit = -1;
            this.bindCount = 0;
            this.texInfo = new TexInfo();
            if (config.profile) {
              this.stats = { size: 0 };
            }
          }
          function tempBind(texture) {
            gl2.activeTexture(GL_TEXTURE0$1);
            gl2.bindTexture(texture.target, texture.texture);
          }
          function tempRestore() {
            var prev = textureUnits[0];
            if (prev) {
              gl2.bindTexture(prev.target, prev.texture);
            } else {
              gl2.bindTexture(GL_TEXTURE_2D$1, null);
            }
          }
          function destroy(texture) {
            var handle = texture.texture;
            var unit = texture.unit;
            var target = texture.target;
            if (unit >= 0) {
              gl2.activeTexture(GL_TEXTURE0$1 + unit);
              gl2.bindTexture(target, null);
              textureUnits[unit] = null;
            }
            gl2.deleteTexture(handle);
            texture.texture = null;
            texture.params = null;
            texture.pixels = null;
            texture.refCount = 0;
            delete textureSet[texture.id];
            stats2.textureCount--;
          }
          extend2(REGLTexture.prototype, {
            bind: function() {
              var texture = this;
              texture.bindCount += 1;
              var unit = texture.unit;
              if (unit < 0) {
                for (var i = 0; i < numTexUnits; ++i) {
                  var other = textureUnits[i];
                  if (other) {
                    if (other.bindCount > 0) {
                      continue;
                    }
                    other.unit = -1;
                  }
                  textureUnits[i] = texture;
                  unit = i;
                  break;
                }
                if (unit >= numTexUnits) {
                }
                if (config.profile && stats2.maxTextureUnits < unit + 1) {
                  stats2.maxTextureUnits = unit + 1;
                }
                texture.unit = unit;
                gl2.activeTexture(GL_TEXTURE0$1 + unit);
                gl2.bindTexture(texture.target, texture.texture);
              }
              return unit;
            },
            unbind: function() {
              this.bindCount -= 1;
            },
            decRef: function() {
              if (--this.refCount <= 0) {
                destroy(this);
              }
            }
          });
          function createTexture2D(a, b) {
            var texture = new REGLTexture(GL_TEXTURE_2D$1);
            textureSet[texture.id] = texture;
            stats2.textureCount++;
            function reglTexture2D(a2, b2) {
              var texInfo = texture.texInfo;
              TexInfo.call(texInfo);
              var mipData = allocMipMap();
              if (typeof a2 === "number") {
                if (typeof b2 === "number") {
                  parseMipMapFromShape(mipData, a2 | 0, b2 | 0);
                } else {
                  parseMipMapFromShape(mipData, a2 | 0, a2 | 0);
                }
              } else if (a2) {
                parseTexInfo(texInfo, a2);
                parseMipMapFromObject(mipData, a2);
              } else {
                parseMipMapFromShape(mipData, 1, 1);
              }
              if (texInfo.genMipmaps) {
                mipData.mipmask = (mipData.width << 1) - 1;
              }
              texture.mipmask = mipData.mipmask;
              copyFlags(texture, mipData);
              texture.internalformat = mipData.internalformat;
              reglTexture2D.width = mipData.width;
              reglTexture2D.height = mipData.height;
              tempBind(texture);
              setMipMap(mipData, GL_TEXTURE_2D$1);
              setTexInfo(texInfo, GL_TEXTURE_2D$1);
              tempRestore();
              freeMipMap(mipData);
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  mipData.width,
                  mipData.height,
                  texInfo.genMipmaps,
                  false
                );
              }
              reglTexture2D.format = textureFormatsInvert[texture.internalformat];
              reglTexture2D.type = textureTypesInvert[texture.type];
              reglTexture2D.mag = magFiltersInvert[texInfo.magFilter];
              reglTexture2D.min = minFiltersInvert[texInfo.minFilter];
              reglTexture2D.wrapS = wrapModesInvert[texInfo.wrapS];
              reglTexture2D.wrapT = wrapModesInvert[texInfo.wrapT];
              return reglTexture2D;
            }
            function subimage(image, x_, y_, level_) {
              var x = x_ | 0;
              var y = y_ | 0;
              var level = level_ | 0;
              var imageData = allocImage();
              copyFlags(imageData, texture);
              imageData.width = 0;
              imageData.height = 0;
              parseImage(imageData, image);
              imageData.width = imageData.width || (texture.width >> level) - x;
              imageData.height = imageData.height || (texture.height >> level) - y;
              tempBind(texture);
              setSubImage(imageData, GL_TEXTURE_2D$1, x, y, level);
              tempRestore();
              freeImage(imageData);
              return reglTexture2D;
            }
            function resize(w_, h_) {
              var w = w_ | 0;
              var h = h_ | 0 || w;
              if (w === texture.width && h === texture.height) {
                return reglTexture2D;
              }
              reglTexture2D.width = texture.width = w;
              reglTexture2D.height = texture.height = h;
              tempBind(texture);
              for (var i = 0; texture.mipmask >> i; ++i) {
                var _w = w >> i;
                var _h = h >> i;
                if (!_w || !_h) break;
                gl2.texImage2D(
                  GL_TEXTURE_2D$1,
                  i,
                  texture.format,
                  _w,
                  _h,
                  0,
                  texture.format,
                  texture.type,
                  null
                );
              }
              tempRestore();
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  w,
                  h,
                  false,
                  false
                );
              }
              return reglTexture2D;
            }
            reglTexture2D(a, b);
            reglTexture2D.subimage = subimage;
            reglTexture2D.resize = resize;
            reglTexture2D._reglType = "texture2d";
            reglTexture2D._texture = texture;
            if (config.profile) {
              reglTexture2D.stats = texture.stats;
            }
            reglTexture2D.destroy = function() {
              texture.decRef();
            };
            return reglTexture2D;
          }
          function createTextureCube(a0, a1, a2, a3, a4, a5) {
            var texture = new REGLTexture(GL_TEXTURE_CUBE_MAP$1);
            textureSet[texture.id] = texture;
            stats2.cubeCount++;
            var faces = new Array(6);
            function reglTextureCube(a02, a12, a22, a32, a42, a52) {
              var i;
              var texInfo = texture.texInfo;
              TexInfo.call(texInfo);
              for (i = 0; i < 6; ++i) {
                faces[i] = allocMipMap();
              }
              if (typeof a02 === "number" || !a02) {
                var s = a02 | 0 || 1;
                for (i = 0; i < 6; ++i) {
                  parseMipMapFromShape(faces[i], s, s);
                }
              } else if (typeof a02 === "object") {
                if (a12) {
                  parseMipMapFromObject(faces[0], a02);
                  parseMipMapFromObject(faces[1], a12);
                  parseMipMapFromObject(faces[2], a22);
                  parseMipMapFromObject(faces[3], a32);
                  parseMipMapFromObject(faces[4], a42);
                  parseMipMapFromObject(faces[5], a52);
                } else {
                  parseTexInfo(texInfo, a02);
                  parseFlags(texture, a02);
                  if ("faces" in a02) {
                    var faceInput = a02.faces;
                    for (i = 0; i < 6; ++i) {
                      copyFlags(faces[i], texture);
                      parseMipMapFromObject(faces[i], faceInput[i]);
                    }
                  } else {
                    for (i = 0; i < 6; ++i) {
                      parseMipMapFromObject(faces[i], a02);
                    }
                  }
                }
              } else {
              }
              copyFlags(texture, faces[0]);
              if (texInfo.genMipmaps) {
                texture.mipmask = (faces[0].width << 1) - 1;
              } else {
                texture.mipmask = faces[0].mipmask;
              }
              texture.internalformat = faces[0].internalformat;
              reglTextureCube.width = faces[0].width;
              reglTextureCube.height = faces[0].height;
              tempBind(texture);
              for (i = 0; i < 6; ++i) {
                setMipMap(faces[i], GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i);
              }
              setTexInfo(texInfo, GL_TEXTURE_CUBE_MAP$1);
              tempRestore();
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  reglTextureCube.width,
                  reglTextureCube.height,
                  texInfo.genMipmaps,
                  true
                );
              }
              reglTextureCube.format = textureFormatsInvert[texture.internalformat];
              reglTextureCube.type = textureTypesInvert[texture.type];
              reglTextureCube.mag = magFiltersInvert[texInfo.magFilter];
              reglTextureCube.min = minFiltersInvert[texInfo.minFilter];
              reglTextureCube.wrapS = wrapModesInvert[texInfo.wrapS];
              reglTextureCube.wrapT = wrapModesInvert[texInfo.wrapT];
              for (i = 0; i < 6; ++i) {
                freeMipMap(faces[i]);
              }
              return reglTextureCube;
            }
            function subimage(face, image, x_, y_, level_) {
              var x = x_ | 0;
              var y = y_ | 0;
              var level = level_ | 0;
              var imageData = allocImage();
              copyFlags(imageData, texture);
              imageData.width = 0;
              imageData.height = 0;
              parseImage(imageData, image);
              imageData.width = imageData.width || (texture.width >> level) - x;
              imageData.height = imageData.height || (texture.height >> level) - y;
              tempBind(texture);
              setSubImage(imageData, GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + face, x, y, level);
              tempRestore();
              freeImage(imageData);
              return reglTextureCube;
            }
            function resize(radius_) {
              var radius = radius_ | 0;
              if (radius === texture.width) {
                return;
              }
              reglTextureCube.width = texture.width = radius;
              reglTextureCube.height = texture.height = radius;
              tempBind(texture);
              for (var i = 0; i < 6; ++i) {
                for (var j = 0; texture.mipmask >> j; ++j) {
                  gl2.texImage2D(
                    GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i,
                    j,
                    texture.format,
                    radius >> j,
                    radius >> j,
                    0,
                    texture.format,
                    texture.type,
                    null
                  );
                }
              }
              tempRestore();
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  reglTextureCube.width,
                  reglTextureCube.height,
                  false,
                  true
                );
              }
              return reglTextureCube;
            }
            reglTextureCube(a0, a1, a2, a3, a4, a5);
            reglTextureCube.subimage = subimage;
            reglTextureCube.resize = resize;
            reglTextureCube._reglType = "textureCube";
            reglTextureCube._texture = texture;
            if (config.profile) {
              reglTextureCube.stats = texture.stats;
            }
            reglTextureCube.destroy = function() {
              texture.decRef();
            };
            return reglTextureCube;
          }
          function destroyTextures() {
            for (var i = 0; i < numTexUnits; ++i) {
              gl2.activeTexture(GL_TEXTURE0$1 + i);
              gl2.bindTexture(GL_TEXTURE_2D$1, null);
              textureUnits[i] = null;
            }
            values(textureSet).forEach(destroy);
            stats2.cubeCount = 0;
            stats2.textureCount = 0;
          }
          if (config.profile) {
            stats2.getTotalTextureSize = function() {
              var total = 0;
              Object.keys(textureSet).forEach(function(key) {
                total += textureSet[key].stats.size;
              });
              return total;
            };
          }
          function restoreTextures() {
            for (var i = 0; i < numTexUnits; ++i) {
              var tex = textureUnits[i];
              if (tex) {
                tex.bindCount = 0;
                tex.unit = -1;
                textureUnits[i] = null;
              }
            }
            values(textureSet).forEach(function(texture) {
              texture.texture = gl2.createTexture();
              gl2.bindTexture(texture.target, texture.texture);
              for (var i2 = 0; i2 < 32; ++i2) {
                if ((texture.mipmask & 1 << i2) === 0) {
                  continue;
                }
                if (texture.target === GL_TEXTURE_2D$1) {
                  gl2.texImage2D(
                    GL_TEXTURE_2D$1,
                    i2,
                    texture.internalformat,
                    texture.width >> i2,
                    texture.height >> i2,
                    0,
                    texture.internalformat,
                    texture.type,
                    null
                  );
                } else {
                  for (var j = 0; j < 6; ++j) {
                    gl2.texImage2D(
                      GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + j,
                      i2,
                      texture.internalformat,
                      texture.width >> i2,
                      texture.height >> i2,
                      0,
                      texture.internalformat,
                      texture.type,
                      null
                    );
                  }
                }
              }
              setTexInfo(texture.texInfo, texture.target);
            });
          }
          function refreshTextures() {
            for (var i = 0; i < numTexUnits; ++i) {
              var tex = textureUnits[i];
              if (tex) {
                tex.bindCount = 0;
                tex.unit = -1;
                textureUnits[i] = null;
              }
              gl2.activeTexture(GL_TEXTURE0$1 + i);
              gl2.bindTexture(GL_TEXTURE_2D$1, null);
              gl2.bindTexture(GL_TEXTURE_CUBE_MAP$1, null);
            }
          }
          return {
            create2D: createTexture2D,
            createCube: createTextureCube,
            clear: destroyTextures,
            getTexture: function(wrapper) {
              return null;
            },
            restore: restoreTextures,
            refresh: refreshTextures
          };
        }
        var GL_RENDERBUFFER = 36161;
        var GL_RGBA4$1 = 32854;
        var GL_RGB5_A1$1 = 32855;
        var GL_RGB565$1 = 36194;
        var GL_DEPTH_COMPONENT16 = 33189;
        var GL_STENCIL_INDEX8 = 36168;
        var GL_DEPTH_STENCIL$1 = 34041;
        var GL_SRGB8_ALPHA8_EXT = 35907;
        var GL_RGBA32F_EXT = 34836;
        var GL_RGBA16F_EXT = 34842;
        var GL_RGB16F_EXT = 34843;
        var FORMAT_SIZES = [];
        FORMAT_SIZES[GL_RGBA4$1] = 2;
        FORMAT_SIZES[GL_RGB5_A1$1] = 2;
        FORMAT_SIZES[GL_RGB565$1] = 2;
        FORMAT_SIZES[GL_DEPTH_COMPONENT16] = 2;
        FORMAT_SIZES[GL_STENCIL_INDEX8] = 1;
        FORMAT_SIZES[GL_DEPTH_STENCIL$1] = 4;
        FORMAT_SIZES[GL_SRGB8_ALPHA8_EXT] = 4;
        FORMAT_SIZES[GL_RGBA32F_EXT] = 16;
        FORMAT_SIZES[GL_RGBA16F_EXT] = 8;
        FORMAT_SIZES[GL_RGB16F_EXT] = 6;
        function getRenderbufferSize(format, width, height) {
          return FORMAT_SIZES[format] * width * height;
        }
        var wrapRenderbuffers = function(gl2, extensions, limits, stats2, config) {
          var formatTypes = {
            "rgba4": GL_RGBA4$1,
            "rgb565": GL_RGB565$1,
            "rgb5 a1": GL_RGB5_A1$1,
            "depth": GL_DEPTH_COMPONENT16,
            "stencil": GL_STENCIL_INDEX8,
            "depth stencil": GL_DEPTH_STENCIL$1
          };
          if (extensions.ext_srgb) {
            formatTypes["srgba"] = GL_SRGB8_ALPHA8_EXT;
          }
          if (extensions.ext_color_buffer_half_float) {
            formatTypes["rgba16f"] = GL_RGBA16F_EXT;
            formatTypes["rgb16f"] = GL_RGB16F_EXT;
          }
          if (extensions.webgl_color_buffer_float) {
            formatTypes["rgba32f"] = GL_RGBA32F_EXT;
          }
          var formatTypesInvert = [];
          Object.keys(formatTypes).forEach(function(key) {
            var val = formatTypes[key];
            formatTypesInvert[val] = key;
          });
          var renderbufferCount = 0;
          var renderbufferSet = {};
          function REGLRenderbuffer(renderbuffer) {
            this.id = renderbufferCount++;
            this.refCount = 1;
            this.renderbuffer = renderbuffer;
            this.format = GL_RGBA4$1;
            this.width = 0;
            this.height = 0;
            if (config.profile) {
              this.stats = { size: 0 };
            }
          }
          REGLRenderbuffer.prototype.decRef = function() {
            if (--this.refCount <= 0) {
              destroy(this);
            }
          };
          function destroy(rb) {
            var handle = rb.renderbuffer;
            gl2.bindRenderbuffer(GL_RENDERBUFFER, null);
            gl2.deleteRenderbuffer(handle);
            rb.renderbuffer = null;
            rb.refCount = 0;
            delete renderbufferSet[rb.id];
            stats2.renderbufferCount--;
          }
          function createRenderbuffer(a, b) {
            var renderbuffer = new REGLRenderbuffer(gl2.createRenderbuffer());
            renderbufferSet[renderbuffer.id] = renderbuffer;
            stats2.renderbufferCount++;
            function reglRenderbuffer(a2, b2) {
              var w = 0;
              var h = 0;
              var format = GL_RGBA4$1;
              if (typeof a2 === "object" && a2) {
                var options = a2;
                if ("shape" in options) {
                  var shape = options.shape;
                  w = shape[0] | 0;
                  h = shape[1] | 0;
                } else {
                  if ("radius" in options) {
                    w = h = options.radius | 0;
                  }
                  if ("width" in options) {
                    w = options.width | 0;
                  }
                  if ("height" in options) {
                    h = options.height | 0;
                  }
                }
                if ("format" in options) {
                  format = formatTypes[options.format];
                }
              } else if (typeof a2 === "number") {
                w = a2 | 0;
                if (typeof b2 === "number") {
                  h = b2 | 0;
                } else {
                  h = w;
                }
              } else if (!a2) {
                w = h = 1;
              } else {
              }
              if (w === renderbuffer.width && h === renderbuffer.height && format === renderbuffer.format) {
                return;
              }
              reglRenderbuffer.width = renderbuffer.width = w;
              reglRenderbuffer.height = renderbuffer.height = h;
              renderbuffer.format = format;
              gl2.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer);
              gl2.renderbufferStorage(GL_RENDERBUFFER, format, w, h);
              if (config.profile) {
                renderbuffer.stats.size = getRenderbufferSize(renderbuffer.format, renderbuffer.width, renderbuffer.height);
              }
              reglRenderbuffer.format = formatTypesInvert[renderbuffer.format];
              return reglRenderbuffer;
            }
            function resize(w_, h_) {
              var w = w_ | 0;
              var h = h_ | 0 || w;
              if (w === renderbuffer.width && h === renderbuffer.height) {
                return reglRenderbuffer;
              }
              reglRenderbuffer.width = renderbuffer.width = w;
              reglRenderbuffer.height = renderbuffer.height = h;
              gl2.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer);
              gl2.renderbufferStorage(GL_RENDERBUFFER, renderbuffer.format, w, h);
              if (config.profile) {
                renderbuffer.stats.size = getRenderbufferSize(
                  renderbuffer.format,
                  renderbuffer.width,
                  renderbuffer.height
                );
              }
              return reglRenderbuffer;
            }
            reglRenderbuffer(a, b);
            reglRenderbuffer.resize = resize;
            reglRenderbuffer._reglType = "renderbuffer";
            reglRenderbuffer._renderbuffer = renderbuffer;
            if (config.profile) {
              reglRenderbuffer.stats = renderbuffer.stats;
            }
            reglRenderbuffer.destroy = function() {
              renderbuffer.decRef();
            };
            return reglRenderbuffer;
          }
          if (config.profile) {
            stats2.getTotalRenderbufferSize = function() {
              var total = 0;
              Object.keys(renderbufferSet).forEach(function(key) {
                total += renderbufferSet[key].stats.size;
              });
              return total;
            };
          }
          function restoreRenderbuffers() {
            values(renderbufferSet).forEach(function(rb) {
              rb.renderbuffer = gl2.createRenderbuffer();
              gl2.bindRenderbuffer(GL_RENDERBUFFER, rb.renderbuffer);
              gl2.renderbufferStorage(GL_RENDERBUFFER, rb.format, rb.width, rb.height);
            });
            gl2.bindRenderbuffer(GL_RENDERBUFFER, null);
          }
          return {
            create: createRenderbuffer,
            clear: function() {
              values(renderbufferSet).forEach(destroy);
            },
            restore: restoreRenderbuffers
          };
        };
        var GL_FRAMEBUFFER$1 = 36160;
        var GL_RENDERBUFFER$1 = 36161;
        var GL_TEXTURE_2D$2 = 3553;
        var GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 = 34069;
        var GL_COLOR_ATTACHMENT0$1 = 36064;
        var GL_DEPTH_ATTACHMENT = 36096;
        var GL_STENCIL_ATTACHMENT = 36128;
        var GL_DEPTH_STENCIL_ATTACHMENT = 33306;
        var GL_FRAMEBUFFER_COMPLETE$1 = 36053;
        var GL_HALF_FLOAT_OES$1 = 36193;
        var GL_UNSIGNED_BYTE$5 = 5121;
        var GL_FLOAT$4 = 5126;
        var GL_RGB$1 = 6407;
        var GL_RGBA$2 = 6408;
        var textureFormatChannels = [];
        textureFormatChannels[GL_RGBA$2] = 4;
        textureFormatChannels[GL_RGB$1] = 3;
        var textureTypeSizes = [];
        textureTypeSizes[GL_UNSIGNED_BYTE$5] = 1;
        textureTypeSizes[GL_FLOAT$4] = 4;
        textureTypeSizes[GL_HALF_FLOAT_OES$1] = 2;
        function wrapFBOState(gl2, extensions, limits, textureState, renderbufferState, stats2) {
          var framebufferState = {
            cur: null,
            next: null,
            dirty: false,
            setFBO: null
          };
          var colorTextureFormats = ["rgba"];
          var colorRenderbufferFormats = ["rgba4", "rgb565", "rgb5 a1"];
          if (extensions.ext_srgb) {
            colorRenderbufferFormats.push("srgba");
          }
          if (extensions.ext_color_buffer_half_float) {
            colorRenderbufferFormats.push("rgba16f", "rgb16f");
          }
          if (extensions.webgl_color_buffer_float) {
            colorRenderbufferFormats.push("rgba32f");
          }
          var colorTypes = ["uint8"];
          if (extensions.oes_texture_half_float) {
            colorTypes.push("half float", "float16");
          }
          if (extensions.oes_texture_float) {
            colorTypes.push("float", "float32");
          }
          function FramebufferAttachment(target, texture, renderbuffer) {
            this.target = target;
            this.texture = texture;
            this.renderbuffer = renderbuffer;
            var w = 0;
            var h = 0;
            if (texture) {
              w = texture.width;
              h = texture.height;
            } else if (renderbuffer) {
              w = renderbuffer.width;
              h = renderbuffer.height;
            }
            this.width = w;
            this.height = h;
          }
          function decRef(attachment) {
            if (attachment) {
              if (attachment.texture) {
                attachment.texture._texture.decRef();
              }
              if (attachment.renderbuffer) {
                attachment.renderbuffer._renderbuffer.decRef();
              }
            }
          }
          function incRefAndCheckShape(attachment, width, height) {
            if (!attachment) {
              return;
            }
            if (attachment.texture) {
              var texture = attachment.texture._texture;
              var tw = Math.max(1, texture.width);
              var th = Math.max(1, texture.height);
              texture.refCount += 1;
            } else {
              var renderbuffer = attachment.renderbuffer._renderbuffer;
              renderbuffer.refCount += 1;
            }
          }
          function attach(location2, attachment) {
            if (attachment) {
              if (attachment.texture) {
                gl2.framebufferTexture2D(
                  GL_FRAMEBUFFER$1,
                  location2,
                  attachment.target,
                  attachment.texture._texture.texture,
                  0
                );
              } else {
                gl2.framebufferRenderbuffer(
                  GL_FRAMEBUFFER$1,
                  location2,
                  GL_RENDERBUFFER$1,
                  attachment.renderbuffer._renderbuffer.renderbuffer
                );
              }
            }
          }
          function parseAttachment(attachment) {
            var target = GL_TEXTURE_2D$2;
            var texture = null;
            var renderbuffer = null;
            var data = attachment;
            if (typeof attachment === "object") {
              data = attachment.data;
              if ("target" in attachment) {
                target = attachment.target | 0;
              }
            }
            var type = data._reglType;
            if (type === "texture2d") {
              texture = data;
            } else if (type === "textureCube") {
              texture = data;
            } else if (type === "renderbuffer") {
              renderbuffer = data;
              target = GL_RENDERBUFFER$1;
            } else {
            }
            return new FramebufferAttachment(target, texture, renderbuffer);
          }
          function allocAttachment(width, height, isTexture, format, type) {
            if (isTexture) {
              var texture = textureState.create2D({
                width,
                height,
                format,
                type
              });
              texture._texture.refCount = 0;
              return new FramebufferAttachment(GL_TEXTURE_2D$2, texture, null);
            } else {
              var rb = renderbufferState.create({
                width,
                height,
                format
              });
              rb._renderbuffer.refCount = 0;
              return new FramebufferAttachment(GL_RENDERBUFFER$1, null, rb);
            }
          }
          function unwrapAttachment(attachment) {
            return attachment && (attachment.texture || attachment.renderbuffer);
          }
          function resizeAttachment(attachment, w, h) {
            if (attachment) {
              if (attachment.texture) {
                attachment.texture.resize(w, h);
              } else if (attachment.renderbuffer) {
                attachment.renderbuffer.resize(w, h);
              }
              attachment.width = w;
              attachment.height = h;
            }
          }
          var framebufferCount = 0;
          var framebufferSet = {};
          function REGLFramebuffer() {
            this.id = framebufferCount++;
            framebufferSet[this.id] = this;
            this.framebuffer = gl2.createFramebuffer();
            this.width = 0;
            this.height = 0;
            this.colorAttachments = [];
            this.depthAttachment = null;
            this.stencilAttachment = null;
            this.depthStencilAttachment = null;
          }
          function decFBORefs(framebuffer) {
            framebuffer.colorAttachments.forEach(decRef);
            decRef(framebuffer.depthAttachment);
            decRef(framebuffer.stencilAttachment);
            decRef(framebuffer.depthStencilAttachment);
          }
          function destroy(framebuffer) {
            var handle = framebuffer.framebuffer;
            gl2.deleteFramebuffer(handle);
            framebuffer.framebuffer = null;
            stats2.framebufferCount--;
            delete framebufferSet[framebuffer.id];
          }
          function updateFramebuffer(framebuffer) {
            var i;
            gl2.bindFramebuffer(GL_FRAMEBUFFER$1, framebuffer.framebuffer);
            var colorAttachments = framebuffer.colorAttachments;
            for (i = 0; i < colorAttachments.length; ++i) {
              attach(GL_COLOR_ATTACHMENT0$1 + i, colorAttachments[i]);
            }
            for (i = colorAttachments.length; i < limits.maxColorAttachments; ++i) {
              gl2.framebufferTexture2D(
                GL_FRAMEBUFFER$1,
                GL_COLOR_ATTACHMENT0$1 + i,
                GL_TEXTURE_2D$2,
                null,
                0
              );
            }
            gl2.framebufferTexture2D(
              GL_FRAMEBUFFER$1,
              GL_DEPTH_STENCIL_ATTACHMENT,
              GL_TEXTURE_2D$2,
              null,
              0
            );
            gl2.framebufferTexture2D(
              GL_FRAMEBUFFER$1,
              GL_DEPTH_ATTACHMENT,
              GL_TEXTURE_2D$2,
              null,
              0
            );
            gl2.framebufferTexture2D(
              GL_FRAMEBUFFER$1,
              GL_STENCIL_ATTACHMENT,
              GL_TEXTURE_2D$2,
              null,
              0
            );
            attach(GL_DEPTH_ATTACHMENT, framebuffer.depthAttachment);
            attach(GL_STENCIL_ATTACHMENT, framebuffer.stencilAttachment);
            attach(GL_DEPTH_STENCIL_ATTACHMENT, framebuffer.depthStencilAttachment);
            var status = gl2.checkFramebufferStatus(GL_FRAMEBUFFER$1);
            if (!gl2.isContextLost() && status !== GL_FRAMEBUFFER_COMPLETE$1) {
            }
            gl2.bindFramebuffer(GL_FRAMEBUFFER$1, framebufferState.next ? framebufferState.next.framebuffer : null);
            framebufferState.cur = framebufferState.next;
            gl2.getError();
          }
          function createFBO(a0, a1) {
            var framebuffer = new REGLFramebuffer();
            stats2.framebufferCount++;
            function reglFramebuffer(a, b) {
              var i;
              var width = 0;
              var height = 0;
              var needsDepth = true;
              var needsStencil = true;
              var colorBuffer = null;
              var colorTexture = true;
              var colorFormat = "rgba";
              var colorType = "uint8";
              var colorCount = 1;
              var depthBuffer = null;
              var stencilBuffer = null;
              var depthStencilBuffer = null;
              var depthStencilTexture = false;
              if (typeof a === "number") {
                width = a | 0;
                height = b | 0 || width;
              } else if (!a) {
                width = height = 1;
              } else {
                var options = a;
                if ("shape" in options) {
                  var shape = options.shape;
                  width = shape[0];
                  height = shape[1];
                } else {
                  if ("radius" in options) {
                    width = height = options.radius;
                  }
                  if ("width" in options) {
                    width = options.width;
                  }
                  if ("height" in options) {
                    height = options.height;
                  }
                }
                if ("color" in options || "colors" in options) {
                  colorBuffer = options.color || options.colors;
                  if (Array.isArray(colorBuffer)) {
                  }
                }
                if (!colorBuffer) {
                  if ("colorCount" in options) {
                    colorCount = options.colorCount | 0;
                  }
                  if ("colorTexture" in options) {
                    colorTexture = !!options.colorTexture;
                    colorFormat = "rgba4";
                  }
                  if ("colorType" in options) {
                    colorType = options.colorType;
                    if (!colorTexture) {
                      if (colorType === "half float" || colorType === "float16") {
                        colorFormat = "rgba16f";
                      } else if (colorType === "float" || colorType === "float32") {
                        colorFormat = "rgba32f";
                      }
                    } else {
                    }
                  }
                  if ("colorFormat" in options) {
                    colorFormat = options.colorFormat;
                    if (colorTextureFormats.indexOf(colorFormat) >= 0) {
                      colorTexture = true;
                    } else if (colorRenderbufferFormats.indexOf(colorFormat) >= 0) {
                      colorTexture = false;
                    } else {
                    }
                  }
                }
                if ("depthTexture" in options || "depthStencilTexture" in options) {
                  depthStencilTexture = !!(options.depthTexture || options.depthStencilTexture);
                }
                if ("depth" in options) {
                  if (typeof options.depth === "boolean") {
                    needsDepth = options.depth;
                  } else {
                    depthBuffer = options.depth;
                    needsStencil = false;
                  }
                }
                if ("stencil" in options) {
                  if (typeof options.stencil === "boolean") {
                    needsStencil = options.stencil;
                  } else {
                    stencilBuffer = options.stencil;
                    needsDepth = false;
                  }
                }
                if ("depthStencil" in options) {
                  if (typeof options.depthStencil === "boolean") {
                    needsDepth = needsStencil = options.depthStencil;
                  } else {
                    depthStencilBuffer = options.depthStencil;
                    needsDepth = false;
                    needsStencil = false;
                  }
                }
              }
              var colorAttachments = null;
              var depthAttachment = null;
              var stencilAttachment = null;
              var depthStencilAttachment = null;
              if (Array.isArray(colorBuffer)) {
                colorAttachments = colorBuffer.map(parseAttachment);
              } else if (colorBuffer) {
                colorAttachments = [parseAttachment(colorBuffer)];
              } else {
                colorAttachments = new Array(colorCount);
                for (i = 0; i < colorCount; ++i) {
                  colorAttachments[i] = allocAttachment(
                    width,
                    height,
                    colorTexture,
                    colorFormat,
                    colorType
                  );
                }
              }
              width = width || colorAttachments[0].width;
              height = height || colorAttachments[0].height;
              if (depthBuffer) {
                depthAttachment = parseAttachment(depthBuffer);
              } else if (needsDepth && !needsStencil) {
                depthAttachment = allocAttachment(
                  width,
                  height,
                  depthStencilTexture,
                  "depth",
                  "uint32"
                );
              }
              if (stencilBuffer) {
                stencilAttachment = parseAttachment(stencilBuffer);
              } else if (needsStencil && !needsDepth) {
                stencilAttachment = allocAttachment(
                  width,
                  height,
                  false,
                  "stencil",
                  "uint8"
                );
              }
              if (depthStencilBuffer) {
                depthStencilAttachment = parseAttachment(depthStencilBuffer);
              } else if (!depthBuffer && !stencilBuffer && needsStencil && needsDepth) {
                depthStencilAttachment = allocAttachment(
                  width,
                  height,
                  depthStencilTexture,
                  "depth stencil",
                  "depth stencil"
                );
              }
              var commonColorAttachmentSize = null;
              for (i = 0; i < colorAttachments.length; ++i) {
                incRefAndCheckShape(colorAttachments[i], width, height);
                if (colorAttachments[i] && colorAttachments[i].texture) {
                  var colorAttachmentSize = textureFormatChannels[colorAttachments[i].texture._texture.format] * textureTypeSizes[colorAttachments[i].texture._texture.type];
                  if (commonColorAttachmentSize === null) {
                    commonColorAttachmentSize = colorAttachmentSize;
                  } else {
                  }
                }
              }
              incRefAndCheckShape(depthAttachment, width, height);
              incRefAndCheckShape(stencilAttachment, width, height);
              incRefAndCheckShape(depthStencilAttachment, width, height);
              decFBORefs(framebuffer);
              framebuffer.width = width;
              framebuffer.height = height;
              framebuffer.colorAttachments = colorAttachments;
              framebuffer.depthAttachment = depthAttachment;
              framebuffer.stencilAttachment = stencilAttachment;
              framebuffer.depthStencilAttachment = depthStencilAttachment;
              reglFramebuffer.color = colorAttachments.map(unwrapAttachment);
              reglFramebuffer.depth = unwrapAttachment(depthAttachment);
              reglFramebuffer.stencil = unwrapAttachment(stencilAttachment);
              reglFramebuffer.depthStencil = unwrapAttachment(depthStencilAttachment);
              reglFramebuffer.width = framebuffer.width;
              reglFramebuffer.height = framebuffer.height;
              updateFramebuffer(framebuffer);
              return reglFramebuffer;
            }
            function resize(w_, h_) {
              var w = Math.max(w_ | 0, 1);
              var h = Math.max(h_ | 0 || w, 1);
              if (w === framebuffer.width && h === framebuffer.height) {
                return reglFramebuffer;
              }
              var colorAttachments = framebuffer.colorAttachments;
              for (var i = 0; i < colorAttachments.length; ++i) {
                resizeAttachment(colorAttachments[i], w, h);
              }
              resizeAttachment(framebuffer.depthAttachment, w, h);
              resizeAttachment(framebuffer.stencilAttachment, w, h);
              resizeAttachment(framebuffer.depthStencilAttachment, w, h);
              framebuffer.width = reglFramebuffer.width = w;
              framebuffer.height = reglFramebuffer.height = h;
              updateFramebuffer(framebuffer);
              return reglFramebuffer;
            }
            reglFramebuffer(a0, a1);
            return extend2(reglFramebuffer, {
              resize,
              _reglType: "framebuffer",
              _framebuffer: framebuffer,
              destroy: function() {
                destroy(framebuffer);
                decFBORefs(framebuffer);
              },
              use: function(block) {
                framebufferState.setFBO({
                  framebuffer: reglFramebuffer
                }, block);
              }
            });
          }
          function createCubeFBO(options) {
            var faces = Array(6);
            function reglFramebufferCube(a) {
              var i;
              var params = {
                color: null
              };
              var radius = 0;
              var colorBuffer = null;
              var colorFormat = "rgba";
              var colorType = "uint8";
              var colorCount = 1;
              if (typeof a === "number") {
                radius = a | 0;
              } else if (!a) {
                radius = 1;
              } else {
                var options2 = a;
                if ("shape" in options2) {
                  var shape = options2.shape;
                  radius = shape[0];
                } else {
                  if ("radius" in options2) {
                    radius = options2.radius | 0;
                  }
                  if ("width" in options2) {
                    radius = options2.width | 0;
                    if ("height" in options2) {
                    }
                  } else if ("height" in options2) {
                    radius = options2.height | 0;
                  }
                }
                if ("color" in options2 || "colors" in options2) {
                  colorBuffer = options2.color || options2.colors;
                  if (Array.isArray(colorBuffer)) {
                  }
                }
                if (!colorBuffer) {
                  if ("colorCount" in options2) {
                    colorCount = options2.colorCount | 0;
                  }
                  if ("colorType" in options2) {
                    colorType = options2.colorType;
                  }
                  if ("colorFormat" in options2) {
                    colorFormat = options2.colorFormat;
                  }
                }
                if ("depth" in options2) {
                  params.depth = options2.depth;
                }
                if ("stencil" in options2) {
                  params.stencil = options2.stencil;
                }
                if ("depthStencil" in options2) {
                  params.depthStencil = options2.depthStencil;
                }
              }
              var colorCubes;
              if (colorBuffer) {
                if (Array.isArray(colorBuffer)) {
                  colorCubes = [];
                  for (i = 0; i < colorBuffer.length; ++i) {
                    colorCubes[i] = colorBuffer[i];
                  }
                } else {
                  colorCubes = [colorBuffer];
                }
              } else {
                colorCubes = Array(colorCount);
                var cubeMapParams = {
                  radius,
                  format: colorFormat,
                  type: colorType
                };
                for (i = 0; i < colorCount; ++i) {
                  colorCubes[i] = textureState.createCube(cubeMapParams);
                }
              }
              params.color = Array(colorCubes.length);
              for (i = 0; i < colorCubes.length; ++i) {
                var cube = colorCubes[i];
                radius = radius || cube.width;
                params.color[i] = {
                  target: GL_TEXTURE_CUBE_MAP_POSITIVE_X$2,
                  data: colorCubes[i]
                };
              }
              for (i = 0; i < 6; ++i) {
                for (var j = 0; j < colorCubes.length; ++j) {
                  params.color[j].target = GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 + i;
                }
                if (i > 0) {
                  params.depth = faces[0].depth;
                  params.stencil = faces[0].stencil;
                  params.depthStencil = faces[0].depthStencil;
                }
                if (faces[i]) {
                  faces[i](params);
                } else {
                  faces[i] = createFBO(params);
                }
              }
              return extend2(reglFramebufferCube, {
                width: radius,
                height: radius,
                color: colorCubes
              });
            }
            function resize(radius_) {
              var i;
              var radius = radius_ | 0;
              if (radius === reglFramebufferCube.width) {
                return reglFramebufferCube;
              }
              var colors = reglFramebufferCube.color;
              for (i = 0; i < colors.length; ++i) {
                colors[i].resize(radius);
              }
              for (i = 0; i < 6; ++i) {
                faces[i].resize(radius);
              }
              reglFramebufferCube.width = reglFramebufferCube.height = radius;
              return reglFramebufferCube;
            }
            reglFramebufferCube(options);
            return extend2(reglFramebufferCube, {
              faces,
              resize,
              _reglType: "framebufferCube",
              destroy: function() {
                faces.forEach(function(f) {
                  f.destroy();
                });
              }
            });
          }
          function restoreFramebuffers() {
            framebufferState.cur = null;
            framebufferState.next = null;
            framebufferState.dirty = true;
            values(framebufferSet).forEach(function(fb) {
              fb.framebuffer = gl2.createFramebuffer();
              updateFramebuffer(fb);
            });
          }
          return extend2(framebufferState, {
            getFramebuffer: function(object) {
              if (typeof object === "function" && object._reglType === "framebuffer") {
                var fbo = object._framebuffer;
                if (fbo instanceof REGLFramebuffer) {
                  return fbo;
                }
              }
              return null;
            },
            create: createFBO,
            createCube: createCubeFBO,
            clear: function() {
              values(framebufferSet).forEach(destroy);
            },
            restore: restoreFramebuffers
          });
        }
        var GL_FLOAT$5 = 5126;
        var GL_ARRAY_BUFFER$1 = 34962;
        var GL_ELEMENT_ARRAY_BUFFER$1 = 34963;
        function AttributeRecord() {
          this.state = 0;
          this.x = 0;
          this.y = 0;
          this.z = 0;
          this.w = 0;
          this.buffer = null;
          this.size = 0;
          this.normalized = false;
          this.type = GL_FLOAT$5;
          this.offset = 0;
          this.stride = 0;
          this.divisor = 0;
        }
        function wrapAttributeState(gl2, extensions, limits, stats2, bufferState, elementState, drawState) {
          var NUM_ATTRIBUTES = limits.maxAttributes;
          var attributeBindings = new Array(NUM_ATTRIBUTES);
          for (var i = 0; i < NUM_ATTRIBUTES; ++i) {
            attributeBindings[i] = new AttributeRecord();
          }
          var vaoCount = 0;
          var vaoSet = {};
          var state = {
            Record: AttributeRecord,
            scope: {},
            state: attributeBindings,
            currentVAO: null,
            targetVAO: null,
            restore: extVAO() ? restoreVAO : function() {
            },
            createVAO,
            getVAO,
            destroyBuffer,
            setVAO: extVAO() ? setVAOEXT : setVAOEmulated,
            clear: extVAO() ? destroyVAOEXT : function() {
            }
          };
          function destroyBuffer(buffer) {
            for (var i2 = 0; i2 < attributeBindings.length; ++i2) {
              var record = attributeBindings[i2];
              if (record.buffer === buffer) {
                gl2.disableVertexAttribArray(i2);
                record.buffer = null;
              }
            }
          }
          function extVAO() {
            return extensions.oes_vertex_array_object;
          }
          function extInstanced() {
            return extensions.angle_instanced_arrays;
          }
          function getVAO(vao) {
            if (typeof vao === "function" && vao._vao) {
              return vao._vao;
            }
            return null;
          }
          function setVAOEXT(vao) {
            if (vao === state.currentVAO) {
              return;
            }
            var ext = extVAO();
            if (vao) {
              ext.bindVertexArrayOES(vao.vao);
            } else {
              ext.bindVertexArrayOES(null);
            }
            state.currentVAO = vao;
          }
          function setVAOEmulated(vao) {
            if (vao === state.currentVAO) {
              return;
            }
            if (vao) {
              vao.bindAttrs();
            } else {
              var exti = extInstanced();
              for (var i2 = 0; i2 < attributeBindings.length; ++i2) {
                var binding = attributeBindings[i2];
                if (binding.buffer) {
                  gl2.enableVertexAttribArray(i2);
                  binding.buffer.bind();
                  gl2.vertexAttribPointer(i2, binding.size, binding.type, binding.normalized, binding.stride, binding.offfset);
                  if (exti && binding.divisor) {
                    exti.vertexAttribDivisorANGLE(i2, binding.divisor);
                  }
                } else {
                  gl2.disableVertexAttribArray(i2);
                  gl2.vertexAttrib4f(i2, binding.x, binding.y, binding.z, binding.w);
                }
              }
              if (drawState.elements) {
                gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, drawState.elements.buffer.buffer);
              } else {
                gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null);
              }
            }
            state.currentVAO = vao;
          }
          function destroyVAOEXT() {
            values(vaoSet).forEach(function(vao) {
              vao.destroy();
            });
          }
          function REGLVAO() {
            this.id = ++vaoCount;
            this.attributes = [];
            this.elements = null;
            this.ownsElements = false;
            this.count = 0;
            this.offset = 0;
            this.instances = -1;
            this.primitive = 4;
            var extension = extVAO();
            if (extension) {
              this.vao = extension.createVertexArrayOES();
            } else {
              this.vao = null;
            }
            vaoSet[this.id] = this;
            this.buffers = [];
          }
          REGLVAO.prototype.bindAttrs = function() {
            var exti = extInstanced();
            var attributes = this.attributes;
            for (var i2 = 0; i2 < attributes.length; ++i2) {
              var attr = attributes[i2];
              if (attr.buffer) {
                gl2.enableVertexAttribArray(i2);
                gl2.bindBuffer(GL_ARRAY_BUFFER$1, attr.buffer.buffer);
                gl2.vertexAttribPointer(i2, attr.size, attr.type, attr.normalized, attr.stride, attr.offset);
                if (exti && attr.divisor) {
                  exti.vertexAttribDivisorANGLE(i2, attr.divisor);
                }
              } else {
                gl2.disableVertexAttribArray(i2);
                gl2.vertexAttrib4f(i2, attr.x, attr.y, attr.z, attr.w);
              }
            }
            for (var j = attributes.length; j < NUM_ATTRIBUTES; ++j) {
              gl2.disableVertexAttribArray(j);
            }
            var elements = elementState.getElements(this.elements);
            if (elements) {
              gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, elements.buffer.buffer);
            } else {
              gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null);
            }
          };
          REGLVAO.prototype.refresh = function() {
            var ext = extVAO();
            if (ext) {
              ext.bindVertexArrayOES(this.vao);
              this.bindAttrs();
              state.currentVAO = null;
              ext.bindVertexArrayOES(null);
            }
          };
          REGLVAO.prototype.destroy = function() {
            if (this.vao) {
              var extension = extVAO();
              if (this === state.currentVAO) {
                state.currentVAO = null;
                extension.bindVertexArrayOES(null);
              }
              extension.deleteVertexArrayOES(this.vao);
              this.vao = null;
            }
            if (this.ownsElements) {
              this.elements.destroy();
              this.elements = null;
              this.ownsElements = false;
            }
            if (vaoSet[this.id]) {
              delete vaoSet[this.id];
              stats2.vaoCount -= 1;
            }
          };
          function restoreVAO() {
            var ext = extVAO();
            if (ext) {
              values(vaoSet).forEach(function(vao) {
                vao.refresh();
              });
            }
          }
          function createVAO(_attr) {
            var vao = new REGLVAO();
            stats2.vaoCount += 1;
            function updateVAO(options) {
              var attributes;
              if (Array.isArray(options)) {
                attributes = options;
                if (vao.elements && vao.ownsElements) {
                  vao.elements.destroy();
                }
                vao.elements = null;
                vao.ownsElements = false;
                vao.offset = 0;
                vao.count = 0;
                vao.instances = -1;
                vao.primitive = 4;
              } else {
                if (options.elements) {
                  var elements = options.elements;
                  if (vao.ownsElements) {
                    if (typeof elements === "function" && elements._reglType === "elements") {
                      vao.elements.destroy();
                      vao.ownsElements = false;
                    } else {
                      vao.elements(elements);
                      vao.ownsElements = false;
                    }
                  } else if (elementState.getElements(options.elements)) {
                    vao.elements = options.elements;
                    vao.ownsElements = false;
                  } else {
                    vao.elements = elementState.create(options.elements);
                    vao.ownsElements = true;
                  }
                } else {
                  vao.elements = null;
                  vao.ownsElements = false;
                }
                attributes = options.attributes;
                vao.offset = 0;
                vao.count = -1;
                vao.instances = -1;
                vao.primitive = 4;
                if (vao.elements) {
                  vao.count = vao.elements._elements.vertCount;
                  vao.primitive = vao.elements._elements.primType;
                }
                if ("offset" in options) {
                  vao.offset = options.offset | 0;
                }
                if ("count" in options) {
                  vao.count = options.count | 0;
                }
                if ("instances" in options) {
                  vao.instances = options.instances | 0;
                }
                if ("primitive" in options) {
                  vao.primitive = primTypes[options.primitive];
                }
              }
              var bufUpdated = {};
              var nattributes = vao.attributes;
              nattributes.length = attributes.length;
              for (var i2 = 0; i2 < attributes.length; ++i2) {
                var spec = attributes[i2];
                var rec = nattributes[i2] = new AttributeRecord();
                var data = spec.data || spec;
                if (Array.isArray(data) || isTypedArray(data) || isNDArrayLike(data)) {
                  var buf;
                  if (vao.buffers[i2]) {
                    buf = vao.buffers[i2];
                    if (isTypedArray(data) && buf._buffer.byteLength >= data.byteLength) {
                      buf.subdata(data);
                    } else {
                      buf.destroy();
                      vao.buffers[i2] = null;
                    }
                  }
                  if (!vao.buffers[i2]) {
                    buf = vao.buffers[i2] = bufferState.create(spec, GL_ARRAY_BUFFER$1, false, true);
                  }
                  rec.buffer = bufferState.getBuffer(buf);
                  rec.size = rec.buffer.dimension | 0;
                  rec.normalized = false;
                  rec.type = rec.buffer.dtype;
                  rec.offset = 0;
                  rec.stride = 0;
                  rec.divisor = 0;
                  rec.state = 1;
                  bufUpdated[i2] = 1;
                } else if (bufferState.getBuffer(spec)) {
                  rec.buffer = bufferState.getBuffer(spec);
                  rec.size = rec.buffer.dimension | 0;
                  rec.normalized = false;
                  rec.type = rec.buffer.dtype;
                  rec.offset = 0;
                  rec.stride = 0;
                  rec.divisor = 0;
                  rec.state = 1;
                } else if (bufferState.getBuffer(spec.buffer)) {
                  rec.buffer = bufferState.getBuffer(spec.buffer);
                  rec.size = (+spec.size || rec.buffer.dimension) | 0;
                  rec.normalized = !!spec.normalized || false;
                  if ("type" in spec) {
                    rec.type = glTypes[spec.type];
                  } else {
                    rec.type = rec.buffer.dtype;
                  }
                  rec.offset = (spec.offset || 0) | 0;
                  rec.stride = (spec.stride || 0) | 0;
                  rec.divisor = (spec.divisor || 0) | 0;
                  rec.state = 1;
                } else if ("x" in spec) {
                  rec.x = +spec.x || 0;
                  rec.y = +spec.y || 0;
                  rec.z = +spec.z || 0;
                  rec.w = +spec.w || 0;
                  rec.state = 2;
                } else {
                }
              }
              for (var j = 0; j < vao.buffers.length; ++j) {
                if (!bufUpdated[j] && vao.buffers[j]) {
                  vao.buffers[j].destroy();
                  vao.buffers[j] = null;
                }
              }
              vao.refresh();
              return updateVAO;
            }
            updateVAO.destroy = function() {
              for (var j = 0; j < vao.buffers.length; ++j) {
                if (vao.buffers[j]) {
                  vao.buffers[j].destroy();
                }
              }
              vao.buffers.length = 0;
              if (vao.ownsElements) {
                vao.elements.destroy();
                vao.elements = null;
                vao.ownsElements = false;
              }
              vao.destroy();
            };
            updateVAO._vao = vao;
            updateVAO._reglType = "vao";
            return updateVAO(_attr);
          }
          return state;
        }
        var GL_FRAGMENT_SHADER = 35632;
        var GL_VERTEX_SHADER = 35633;
        var GL_ACTIVE_UNIFORMS = 35718;
        var GL_ACTIVE_ATTRIBUTES = 35721;
        function wrapShaderState(gl2, stringStore, stats2, config) {
          var fragShaders = {};
          var vertShaders = {};
          function ActiveInfo(name2, id, location2, info) {
            this.name = name2;
            this.id = id;
            this.location = location2;
            this.info = info;
          }
          function insertActiveInfo(list, info) {
            for (var i = 0; i < list.length; ++i) {
              if (list[i].id === info.id) {
                list[i].location = info.location;
                return;
              }
            }
            list.push(info);
          }
          function getShader(type, id, command) {
            var cache = type === GL_FRAGMENT_SHADER ? fragShaders : vertShaders;
            var shader = cache[id];
            if (!shader) {
              var source = stringStore.str(id);
              shader = gl2.createShader(type);
              gl2.shaderSource(shader, source);
              gl2.compileShader(shader);
              cache[id] = shader;
            }
            return shader;
          }
          var programCache = {};
          var programList = [];
          var PROGRAM_COUNTER = 0;
          function REGLProgram(fragId, vertId) {
            this.id = PROGRAM_COUNTER++;
            this.fragId = fragId;
            this.vertId = vertId;
            this.program = null;
            this.uniforms = [];
            this.attributes = [];
            this.refCount = 1;
            if (config.profile) {
              this.stats = {
                uniformsCount: 0,
                attributesCount: 0
              };
            }
          }
          function linkProgram(desc, command, attributeLocations) {
            var i, info;
            var fragShader = getShader(GL_FRAGMENT_SHADER, desc.fragId);
            var vertShader = getShader(GL_VERTEX_SHADER, desc.vertId);
            var program = desc.program = gl2.createProgram();
            gl2.attachShader(program, fragShader);
            gl2.attachShader(program, vertShader);
            if (attributeLocations) {
              for (i = 0; i < attributeLocations.length; ++i) {
                var binding = attributeLocations[i];
                gl2.bindAttribLocation(program, binding[0], binding[1]);
              }
            }
            gl2.linkProgram(program);
            var numUniforms = gl2.getProgramParameter(program, GL_ACTIVE_UNIFORMS);
            if (config.profile) {
              desc.stats.uniformsCount = numUniforms;
            }
            var uniforms = desc.uniforms;
            for (i = 0; i < numUniforms; ++i) {
              info = gl2.getActiveUniform(program, i);
              if (info) {
                if (info.size > 1) {
                  for (var j = 0; j < info.size; ++j) {
                    var name2 = info.name.replace("[0]", "[" + j + "]");
                    insertActiveInfo(uniforms, new ActiveInfo(
                      name2,
                      stringStore.id(name2),
                      gl2.getUniformLocation(program, name2),
                      info
                    ));
                  }
                } else {
                  insertActiveInfo(uniforms, new ActiveInfo(
                    info.name,
                    stringStore.id(info.name),
                    gl2.getUniformLocation(program, info.name),
                    info
                  ));
                }
              }
            }
            var numAttributes = gl2.getProgramParameter(program, GL_ACTIVE_ATTRIBUTES);
            if (config.profile) {
              desc.stats.attributesCount = numAttributes;
            }
            var attributes = desc.attributes;
            for (i = 0; i < numAttributes; ++i) {
              info = gl2.getActiveAttrib(program, i);
              if (info) {
                insertActiveInfo(attributes, new ActiveInfo(
                  info.name,
                  stringStore.id(info.name),
                  gl2.getAttribLocation(program, info.name),
                  info
                ));
              }
            }
          }
          if (config.profile) {
            stats2.getMaxUniformsCount = function() {
              var m = 0;
              programList.forEach(function(desc) {
                if (desc.stats.uniformsCount > m) {
                  m = desc.stats.uniformsCount;
                }
              });
              return m;
            };
            stats2.getMaxAttributesCount = function() {
              var m = 0;
              programList.forEach(function(desc) {
                if (desc.stats.attributesCount > m) {
                  m = desc.stats.attributesCount;
                }
              });
              return m;
            };
          }
          function restoreShaders() {
            fragShaders = {};
            vertShaders = {};
            for (var i = 0; i < programList.length; ++i) {
              linkProgram(programList[i], null, programList[i].attributes.map(function(info) {
                return [info.location, info.name];
              }));
            }
          }
          return {
            clear: function() {
              var deleteShader = gl2.deleteShader.bind(gl2);
              values(fragShaders).forEach(deleteShader);
              fragShaders = {};
              values(vertShaders).forEach(deleteShader);
              vertShaders = {};
              programList.forEach(function(desc) {
                gl2.deleteProgram(desc.program);
              });
              programList.length = 0;
              programCache = {};
              stats2.shaderCount = 0;
            },
            program: function(vertId, fragId, command, attribLocations) {
              var cache = programCache[fragId];
              if (!cache) {
                cache = programCache[fragId] = {};
              }
              var prevProgram = cache[vertId];
              if (prevProgram) {
                prevProgram.refCount++;
                if (!attribLocations) {
                  return prevProgram;
                }
              }
              var program = new REGLProgram(fragId, vertId);
              stats2.shaderCount++;
              linkProgram(program, command, attribLocations);
              if (!prevProgram) {
                cache[vertId] = program;
              }
              programList.push(program);
              return extend2(program, {
                destroy: function() {
                  program.refCount--;
                  if (program.refCount <= 0) {
                    gl2.deleteProgram(program.program);
                    var idx = programList.indexOf(program);
                    programList.splice(idx, 1);
                    stats2.shaderCount--;
                  }
                  if (cache[program.vertId].refCount <= 0) {
                    gl2.deleteShader(vertShaders[program.vertId]);
                    delete vertShaders[program.vertId];
                    delete programCache[program.fragId][program.vertId];
                  }
                  if (!Object.keys(programCache[program.fragId]).length) {
                    gl2.deleteShader(fragShaders[program.fragId]);
                    delete fragShaders[program.fragId];
                    delete programCache[program.fragId];
                  }
                }
              });
            },
            restore: restoreShaders,
            shader: getShader,
            frag: -1,
            vert: -1
          };
        }
        var GL_RGBA$3 = 6408;
        var GL_UNSIGNED_BYTE$6 = 5121;
        var GL_PACK_ALIGNMENT = 3333;
        var GL_FLOAT$6 = 5126;
        function wrapReadPixels(gl2, framebufferState, reglPoll, context, glAttributes, extensions, limits) {
          function readPixelsImpl(input) {
            var type;
            if (framebufferState.next === null) {
              type = GL_UNSIGNED_BYTE$6;
            } else {
              type = framebufferState.next.colorAttachments[0].texture._texture.type;
            }
            var x = 0;
            var y = 0;
            var width = context.framebufferWidth;
            var height = context.framebufferHeight;
            var data = null;
            if (isTypedArray(input)) {
              data = input;
            } else if (input) {
              x = input.x | 0;
              y = input.y | 0;
              width = (input.width || context.framebufferWidth - x) | 0;
              height = (input.height || context.framebufferHeight - y) | 0;
              data = input.data || null;
            }
            if (data) {
              if (type === GL_UNSIGNED_BYTE$6) {
              } else if (type === GL_FLOAT$6) {
              }
            }
            reglPoll();
            var size = width * height * 4;
            if (!data) {
              if (type === GL_UNSIGNED_BYTE$6) {
                data = new Uint8Array(size);
              } else if (type === GL_FLOAT$6) {
                data = data || new Float32Array(size);
              }
            }
            gl2.pixelStorei(GL_PACK_ALIGNMENT, 4);
            gl2.readPixels(
              x,
              y,
              width,
              height,
              GL_RGBA$3,
              type,
              data
            );
            return data;
          }
          function readPixelsFBO(options) {
            var result;
            framebufferState.setFBO({
              framebuffer: options.framebuffer
            }, function() {
              result = readPixelsImpl(options);
            });
            return result;
          }
          function readPixels(options) {
            if (!options || !("framebuffer" in options)) {
              return readPixelsImpl(options);
            } else {
              return readPixelsFBO(options);
            }
          }
          return readPixels;
        }
        var hexcase = 0;
        var b64pad = "";
        function hex_sha256(s) {
          return rstr2hex(rstr_sha256(str2rstr_utf8(s)));
        }
        function rstr_sha256(s) {
          return binb2rstr(binb_sha256(rstr2binb(s), s.length * 8));
        }
        function rstr_hmac_sha256(key, data) {
          var bkey = rstr2binb(key);
          if (bkey.length > 16) bkey = binb_sha256(bkey, key.length * 8);
          var ipad = Array(16), opad = Array(16);
          for (var i = 0; i < 16; i++) {
            ipad[i] = bkey[i] ^ 909522486;
            opad[i] = bkey[i] ^ 1549556828;
          }
          var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
          return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256));
        }
        function rstr2hex(input) {
          var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
          var output = "";
          var x;
          for (var i = 0; i < input.length; i++) {
            x = input.charCodeAt(i);
            output += hex_tab.charAt(x >>> 4 & 15) + hex_tab.charAt(x & 15);
          }
          return output;
        }
        function rstr2b64(input) {
          var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
          var output = "";
          var len = input.length;
          for (var i = 0; i < len; i += 3) {
            var triplet = input.charCodeAt(i) << 16 | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0);
            for (var j = 0; j < 4; j++) {
              if (i * 8 + j * 6 > input.length * 8) output += b64pad;
              else output += tab.charAt(triplet >>> 6 * (3 - j) & 63);
            }
          }
          return output;
        }
        function rstr2any(input, encoding) {
          var divisor = encoding.length;
          var remainders = Array();
          var i, q, x, quotient;
          var dividend = Array(Math.ceil(input.length / 2));
          for (i = 0; i < dividend.length; i++) {
            dividend[i] = input.charCodeAt(i * 2) << 8 | input.charCodeAt(i * 2 + 1);
          }
          while (dividend.length > 0) {
            quotient = Array();
            x = 0;
            for (i = 0; i < dividend.length; i++) {
              x = (x << 16) + dividend[i];
              q = Math.floor(x / divisor);
              x -= q * divisor;
              if (quotient.length > 0 || q > 0)
                quotient[quotient.length] = q;
            }
            remainders[remainders.length] = x;
            dividend = quotient;
          }
          var output = "";
          for (i = remainders.length - 1; i >= 0; i--)
            output += encoding.charAt(remainders[i]);
          var full_length = Math.ceil(input.length * 8 / (Math.log(encoding.length) / Math.log(2)));
          for (i = output.length; i < full_length; i++)
            output = encoding[0] + output;
          return output;
        }
        function str2rstr_utf8(input) {
          var output = "";
          var i = -1;
          var x, y;
          while (++i < input.length) {
            x = input.charCodeAt(i);
            y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
            if (55296 <= x && x <= 56319 && 56320 <= y && y <= 57343) {
              x = 65536 + ((x & 1023) << 10) + (y & 1023);
              i++;
            }
            if (x <= 127)
              output += String.fromCharCode(x);
            else if (x <= 2047)
              output += String.fromCharCode(
                192 | x >>> 6 & 31,
                128 | x & 63
              );
            else if (x <= 65535)
              output += String.fromCharCode(
                224 | x >>> 12 & 15,
                128 | x >>> 6 & 63,
                128 | x & 63
              );
            else if (x <= 2097151)
              output += String.fromCharCode(
                240 | x >>> 18 & 7,
                128 | x >>> 12 & 63,
                128 | x >>> 6 & 63,
                128 | x & 63
              );
          }
          return output;
        }
        function rstr2binb(input) {
          var output = Array(input.length >> 2);
          for (var i = 0; i < output.length; i++)
            output[i] = 0;
          for (var i = 0; i < input.length * 8; i += 8)
            output[i >> 5] |= (input.charCodeAt(i / 8) & 255) << 24 - i % 32;
          return output;
        }
        function binb2rstr(input) {
          var output = "";
          for (var i = 0; i < input.length * 32; i += 8)
            output += String.fromCharCode(input[i >> 5] >>> 24 - i % 32 & 255);
          return output;
        }
        function sha256_S(X, n) {
          return X >>> n | X << 32 - n;
        }
        function sha256_R(X, n) {
          return X >>> n;
        }
        function sha256_Ch(x, y, z) {
          return x & y ^ ~x & z;
        }
        function sha256_Maj(x, y, z) {
          return x & y ^ x & z ^ y & z;
        }
        function sha256_Sigma0256(x) {
          return sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22);
        }
        function sha256_Sigma1256(x) {
          return sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25);
        }
        function sha256_Gamma0256(x) {
          return sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3);
        }
        function sha256_Gamma1256(x) {
          return sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10);
        }
        var sha256_K = new Array(
          1116352408,
          1899447441,
          -1245643825,
          -373957723,
          961987163,
          1508970993,
          -1841331548,
          -1424204075,
          -670586216,
          310598401,
          607225278,
          1426881987,
          1925078388,
          -2132889090,
          -1680079193,
          -1046744716,
          -459576895,
          -272742522,
          264347078,
          604807628,
          770255983,
          1249150122,
          1555081692,
          1996064986,
          -1740746414,
          -1473132947,
          -1341970488,
          -1084653625,
          -958395405,
          -710438585,
          113926993,
          338241895,
          666307205,
          773529912,
          1294757372,
          1396182291,
          1695183700,
          1986661051,
          -2117940946,
          -1838011259,
          -1564481375,
          -1474664885,
          -1035236496,
          -949202525,
          -778901479,
          -694614492,
          -200395387,
          275423344,
          430227734,
          506948616,
          659060556,
          883997877,
          958139571,
          1322822218,
          1537002063,
          1747873779,
          1955562222,
          2024104815,
          -2067236844,
          -1933114872,
          -1866530822,
          -1538233109,
          -1090935817,
          -965641998
        );
        function binb_sha256(m, l) {
          var HASH = new Array(
            1779033703,
            -1150833019,
            1013904242,
            -1521486534,
            1359893119,
            -1694144372,
            528734635,
            1541459225
          );
          var W = new Array(64);
          var a, b, c, d, e, f, g, h;
          var i, j, T1, T2;
          m[l >> 5] |= 128 << 24 - l % 32;
          m[(l + 64 >> 9 << 4) + 15] = l;
          for (i = 0; i < m.length; i += 16) {
            a = HASH[0];
            b = HASH[1];
            c = HASH[2];
            d = HASH[3];
            e = HASH[4];
            f = HASH[5];
            g = HASH[6];
            h = HASH[7];
            for (j = 0; j < 64; j++) {
              if (j < 16) W[j] = m[j + i];
              else W[j] = safe_add(safe_add(
                safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]),
                sha256_Gamma0256(W[j - 15])
              ), W[j - 16]);
              T1 = safe_add(safe_add(
                safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)),
                sha256_K[j]
              ), W[j]);
              T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c));
              h = g;
              g = f;
              f = e;
              e = safe_add(d, T1);
              d = c;
              c = b;
              b = a;
              a = safe_add(T1, T2);
            }
            HASH[0] = safe_add(a, HASH[0]);
            HASH[1] = safe_add(b, HASH[1]);
            HASH[2] = safe_add(c, HASH[2]);
            HASH[3] = safe_add(d, HASH[3]);
            HASH[4] = safe_add(e, HASH[4]);
            HASH[5] = safe_add(f, HASH[5]);
            HASH[6] = safe_add(g, HASH[6]);
            HASH[7] = safe_add(h, HASH[7]);
          }
          return HASH;
        }
        function safe_add(x, y) {
          var lsw = (x & 65535) + (y & 65535);
          var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
          return msw << 16 | lsw & 65535;
        }
        function slice(x) {
          return Array.prototype.slice.call(x);
        }
        function join(x) {
          return slice(x).join("");
        }
        function createEnvironment(options) {
          var cache = options && options.cache;
          var varCounter = 0;
          var linkedNames = [];
          var linkedValues = [];
          var isStable = [];
          function link(value, options2) {
            var stable = options2 && options2.stable;
            if (!stable) {
              for (var i = 0; i < linkedValues.length; ++i) {
                if (linkedValues[i] === value && !isStable[i]) {
                  return linkedNames[i];
                }
              }
            }
            var name2 = "g" + varCounter++;
            linkedNames.push(name2);
            linkedValues.push(value);
            isStable.push(stable);
            return name2;
          }
          function block() {
            var code = [];
            function push() {
              code.push.apply(code, slice(arguments));
            }
            var vars = [];
            function def() {
              var name2 = "v" + varCounter++;
              vars.push(name2);
              if (arguments.length > 0) {
                code.push(name2, "=");
                code.push.apply(code, slice(arguments));
                code.push(";");
              }
              return name2;
            }
            return extend2(push, {
              def,
              toString: function() {
                return join([
                  vars.length > 0 ? "var " + vars.join(",") + ";" : "",
                  join(code)
                ]);
              }
            });
          }
          function scope() {
            var entry = block();
            var exit = block();
            var entryToString = entry.toString;
            var exitToString = exit.toString;
            function save(object, prop) {
              exit(object, prop, "=", entry.def(object, prop), ";");
            }
            return extend2(function() {
              entry.apply(entry, slice(arguments));
            }, {
              def: entry.def,
              entry,
              exit,
              save,
              set: function(object, prop, value) {
                save(object, prop);
                entry(object, prop, "=", value, ";");
              },
              toString: function() {
                return entryToString() + exitToString();
              }
            });
          }
          function conditional() {
            var pred = join(arguments);
            var thenBlock = scope();
            var elseBlock = scope();
            var thenToString = thenBlock.toString;
            var elseToString = elseBlock.toString;
            return extend2(thenBlock, {
              then: function() {
                thenBlock.apply(thenBlock, slice(arguments));
                return this;
              },
              else: function() {
                elseBlock.apply(elseBlock, slice(arguments));
                return this;
              },
              toString: function() {
                var elseClause = elseToString();
                if (elseClause) {
                  elseClause = "else{" + elseClause + "}";
                }
                return join([
                  "if(",
                  pred,
                  "){",
                  thenToString(),
                  "}",
                  elseClause
                ]);
              }
            });
          }
          var globalBlock = block();
          var procedures = {};
          function proc(name2, count) {
            var args = [];
            function arg() {
              var name3 = "a" + args.length;
              args.push(name3);
              return name3;
            }
            count = count || 0;
            for (var i = 0; i < count; ++i) {
              arg();
            }
            var body = scope();
            var bodyToString = body.toString;
            var result = procedures[name2] = extend2(body, {
              arg,
              toString: function() {
                return join([
                  "function(",
                  args.join(),
                  "){",
                  bodyToString(),
                  "}"
                ]);
              }
            });
            return result;
          }
          function compile() {
            var code = [
              '"use strict";',
              globalBlock,
              "return {"
            ];
            Object.keys(procedures).forEach(function(name2) {
              code.push('"', name2, '":', procedures[name2].toString(), ",");
            });
            code.push("}");
            var src = join(code).replace(/;/g, ";\n").replace(/}/g, "}\n").replace(/{/g, "{\n");
            var key;
            if (cache) {
              key = hex_sha256(src);
              if (cache[key]) {
                return cache[key].apply(null, linkedValues);
              }
            }
            var proc2 = Function.apply(null, linkedNames.concat(src));
            if (cache) {
              cache[key] = proc2;
            }
            return proc2.apply(null, linkedValues);
          }
          return {
            global: globalBlock,
            link,
            block,
            proc,
            scope,
            cond: conditional,
            compile
          };
        }
        var CUTE_COMPONENTS = "xyzw".split("");
        var GL_UNSIGNED_BYTE$7 = 5121;
        var ATTRIB_STATE_POINTER = 1;
        var ATTRIB_STATE_CONSTANT = 2;
        var DYN_FUNC$1 = 0;
        var DYN_PROP$1 = 1;
        var DYN_CONTEXT$1 = 2;
        var DYN_STATE$1 = 3;
        var DYN_THUNK = 4;
        var DYN_CONSTANT$1 = 5;
        var DYN_ARRAY$1 = 6;
        var S_DITHER = "dither";
        var S_BLEND_ENABLE = "blend.enable";
        var S_BLEND_COLOR = "blend.color";
        var S_BLEND_EQUATION = "blend.equation";
        var S_BLEND_FUNC = "blend.func";
        var S_DEPTH_ENABLE = "depth.enable";
        var S_DEPTH_FUNC = "depth.func";
        var S_DEPTH_RANGE = "depth.range";
        var S_DEPTH_MASK = "depth.mask";
        var S_COLOR_MASK = "colorMask";
        var S_CULL_ENABLE = "cull.enable";
        var S_CULL_FACE = "cull.face";
        var S_FRONT_FACE = "frontFace";
        var S_LINE_WIDTH = "lineWidth";
        var S_POLYGON_OFFSET_ENABLE = "polygonOffset.enable";
        var S_POLYGON_OFFSET_OFFSET = "polygonOffset.offset";
        var S_SAMPLE_ALPHA = "sample.alpha";
        var S_SAMPLE_ENABLE = "sample.enable";
        var S_SAMPLE_COVERAGE = "sample.coverage";
        var S_STENCIL_ENABLE = "stencil.enable";
        var S_STENCIL_MASK = "stencil.mask";
        var S_STENCIL_FUNC = "stencil.func";
        var S_STENCIL_OPFRONT = "stencil.opFront";
        var S_STENCIL_OPBACK = "stencil.opBack";
        var S_SCISSOR_ENABLE = "scissor.enable";
        var S_SCISSOR_BOX = "scissor.box";
        var S_VIEWPORT = "viewport";
        var S_PROFILE = "profile";
        var S_FRAMEBUFFER = "framebuffer";
        var S_VERT = "vert";
        var S_FRAG = "frag";
        var S_ELEMENTS = "elements";
        var S_PRIMITIVE = "primitive";
        var S_COUNT = "count";
        var S_OFFSET = "offset";
        var S_INSTANCES = "instances";
        var S_VAO = "vao";
        var SUFFIX_WIDTH = "Width";
        var SUFFIX_HEIGHT = "Height";
        var S_FRAMEBUFFER_WIDTH = S_FRAMEBUFFER + SUFFIX_WIDTH;
        var S_FRAMEBUFFER_HEIGHT = S_FRAMEBUFFER + SUFFIX_HEIGHT;
        var S_VIEWPORT_WIDTH = S_VIEWPORT + SUFFIX_WIDTH;
        var S_VIEWPORT_HEIGHT = S_VIEWPORT + SUFFIX_HEIGHT;
        var S_DRAWINGBUFFER = "drawingBuffer";
        var S_DRAWINGBUFFER_WIDTH = S_DRAWINGBUFFER + SUFFIX_WIDTH;
        var S_DRAWINGBUFFER_HEIGHT = S_DRAWINGBUFFER + SUFFIX_HEIGHT;
        var NESTED_OPTIONS = [
          S_BLEND_FUNC,
          S_BLEND_EQUATION,
          S_STENCIL_FUNC,
          S_STENCIL_OPFRONT,
          S_STENCIL_OPBACK,
          S_SAMPLE_COVERAGE,
          S_VIEWPORT,
          S_SCISSOR_BOX,
          S_POLYGON_OFFSET_OFFSET
        ];
        var GL_ARRAY_BUFFER$2 = 34962;
        var GL_ELEMENT_ARRAY_BUFFER$2 = 34963;
        var GL_CULL_FACE = 2884;
        var GL_BLEND = 3042;
        var GL_DITHER = 3024;
        var GL_STENCIL_TEST = 2960;
        var GL_DEPTH_TEST = 2929;
        var GL_SCISSOR_TEST = 3089;
        var GL_POLYGON_OFFSET_FILL = 32823;
        var GL_SAMPLE_ALPHA_TO_COVERAGE = 32926;
        var GL_SAMPLE_COVERAGE = 32928;
        var GL_FLOAT$7 = 5126;
        var GL_FLOAT_VEC2 = 35664;
        var GL_FLOAT_VEC3 = 35665;
        var GL_FLOAT_VEC4 = 35666;
        var GL_INT$2 = 5124;
        var GL_INT_VEC2 = 35667;
        var GL_INT_VEC3 = 35668;
        var GL_INT_VEC4 = 35669;
        var GL_BOOL = 35670;
        var GL_BOOL_VEC2 = 35671;
        var GL_BOOL_VEC3 = 35672;
        var GL_BOOL_VEC4 = 35673;
        var GL_FLOAT_MAT2 = 35674;
        var GL_FLOAT_MAT3 = 35675;
        var GL_FLOAT_MAT4 = 35676;
        var GL_SAMPLER_2D = 35678;
        var GL_SAMPLER_CUBE = 35680;
        var GL_TRIANGLES$1 = 4;
        var GL_FRONT = 1028;
        var GL_BACK = 1029;
        var GL_CW = 2304;
        var GL_CCW = 2305;
        var GL_MIN_EXT = 32775;
        var GL_MAX_EXT = 32776;
        var GL_ALWAYS = 519;
        var GL_KEEP = 7680;
        var GL_ZERO = 0;
        var GL_ONE = 1;
        var GL_FUNC_ADD = 32774;
        var GL_LESS = 513;
        var GL_FRAMEBUFFER$2 = 36160;
        var GL_COLOR_ATTACHMENT0$2 = 36064;
        var blendFuncs = {
          "0": 0,
          "1": 1,
          "zero": 0,
          "one": 1,
          "src color": 768,
          "one minus src color": 769,
          "src alpha": 770,
          "one minus src alpha": 771,
          "dst color": 774,
          "one minus dst color": 775,
          "dst alpha": 772,
          "one minus dst alpha": 773,
          "constant color": 32769,
          "one minus constant color": 32770,
          "constant alpha": 32771,
          "one minus constant alpha": 32772,
          "src alpha saturate": 776
        };
        var compareFuncs = {
          "never": 512,
          "less": 513,
          "<": 513,
          "equal": 514,
          "=": 514,
          "==": 514,
          "===": 514,
          "lequal": 515,
          "<=": 515,
          "greater": 516,
          ">": 516,
          "notequal": 517,
          "!=": 517,
          "!==": 517,
          "gequal": 518,
          ">=": 518,
          "always": 519
        };
        var stencilOps = {
          "0": 0,
          "zero": 0,
          "keep": 7680,
          "replace": 7681,
          "increment": 7682,
          "decrement": 7683,
          "increment wrap": 34055,
          "decrement wrap": 34056,
          "invert": 5386
        };
        var orientationType = {
          "cw": GL_CW,
          "ccw": GL_CCW
        };
        function isBufferArgs(x) {
          return Array.isArray(x) || isTypedArray(x) || isNDArrayLike(x);
        }
        function sortState(state) {
          return state.sort(function(a, b) {
            if (a === S_VIEWPORT) {
              return -1;
            } else if (b === S_VIEWPORT) {
              return 1;
            }
            return a < b ? -1 : 1;
          });
        }
        function Declaration(thisDep, contextDep, propDep, append) {
          this.thisDep = thisDep;
          this.contextDep = contextDep;
          this.propDep = propDep;
          this.append = append;
        }
        function isStatic(decl) {
          return decl && !(decl.thisDep || decl.contextDep || decl.propDep);
        }
        function createStaticDecl(append) {
          return new Declaration(false, false, false, append);
        }
        function createDynamicDecl(dyn, append) {
          var type = dyn.type;
          if (type === DYN_FUNC$1) {
            var numArgs = dyn.data.length;
            return new Declaration(
              true,
              numArgs >= 1,
              numArgs >= 2,
              append
            );
          } else if (type === DYN_THUNK) {
            var data = dyn.data;
            return new Declaration(
              data.thisDep,
              data.contextDep,
              data.propDep,
              append
            );
          } else if (type === DYN_CONSTANT$1) {
            return new Declaration(
              false,
              false,
              false,
              append
            );
          } else if (type === DYN_ARRAY$1) {
            var thisDep = false;
            var contextDep = false;
            var propDep = false;
            for (var i = 0; i < dyn.data.length; ++i) {
              var subDyn = dyn.data[i];
              if (subDyn.type === DYN_PROP$1) {
                propDep = true;
              } else if (subDyn.type === DYN_CONTEXT$1) {
                contextDep = true;
              } else if (subDyn.type === DYN_STATE$1) {
                thisDep = true;
              } else if (subDyn.type === DYN_FUNC$1) {
                thisDep = true;
                var subArgs = subDyn.data;
                if (subArgs >= 1) {
                  contextDep = true;
                }
                if (subArgs >= 2) {
                  propDep = true;
                }
              } else if (subDyn.type === DYN_THUNK) {
                thisDep = thisDep || subDyn.data.thisDep;
                contextDep = contextDep || subDyn.data.contextDep;
                propDep = propDep || subDyn.data.propDep;
              }
            }
            return new Declaration(
              thisDep,
              contextDep,
              propDep,
              append
            );
          } else {
            return new Declaration(
              type === DYN_STATE$1,
              type === DYN_CONTEXT$1,
              type === DYN_PROP$1,
              append
            );
          }
        }
        var SCOPE_DECL = new Declaration(false, false, false, function() {
        });
        function reglCore(gl2, stringStore, extensions, limits, bufferState, elementState, textureState, framebufferState, uniformState, attributeState, shaderState, drawState, contextState, timer, cachedCode, config) {
          var AttributeRecord2 = attributeState.Record;
          var blendEquations = {
            "add": 32774,
            "subtract": 32778,
            "reverse subtract": 32779
          };
          if (extensions.ext_blend_minmax) {
            blendEquations.min = GL_MIN_EXT;
            blendEquations.max = GL_MAX_EXT;
          }
          var extInstancing = extensions.angle_instanced_arrays;
          var extDrawBuffers = extensions.webgl_draw_buffers;
          var extVertexArrays = extensions.oes_vertex_array_object;
          var currentState = {
            dirty: true,
            profile: config.profile
          };
          var nextState = {};
          var GL_STATE_NAMES = [];
          var GL_FLAGS = {};
          var GL_VARIABLES = {};
          function propName(name2) {
            return name2.replace(".", "_");
          }
          function stateFlag(sname, cap, init) {
            var name2 = propName(sname);
            GL_STATE_NAMES.push(sname);
            nextState[name2] = currentState[name2] = !!init;
            GL_FLAGS[name2] = cap;
          }
          function stateVariable(sname, func, init) {
            var name2 = propName(sname);
            GL_STATE_NAMES.push(sname);
            if (Array.isArray(init)) {
              currentState[name2] = init.slice();
              nextState[name2] = init.slice();
            } else {
              currentState[name2] = nextState[name2] = init;
            }
            GL_VARIABLES[name2] = func;
          }
          function hasVariableReference(exp) {
            if (!isNaN(exp)) {
              return false;
            }
            return true;
          }
          stateFlag(S_DITHER, GL_DITHER);
          stateFlag(S_BLEND_ENABLE, GL_BLEND);
          stateVariable(S_BLEND_COLOR, "blendColor", [0, 0, 0, 0]);
          stateVariable(
            S_BLEND_EQUATION,
            "blendEquationSeparate",
            [GL_FUNC_ADD, GL_FUNC_ADD]
          );
          stateVariable(
            S_BLEND_FUNC,
            "blendFuncSeparate",
            [GL_ONE, GL_ZERO, GL_ONE, GL_ZERO]
          );
          stateFlag(S_DEPTH_ENABLE, GL_DEPTH_TEST, true);
          stateVariable(S_DEPTH_FUNC, "depthFunc", GL_LESS);
          stateVariable(S_DEPTH_RANGE, "depthRange", [0, 1]);
          stateVariable(S_DEPTH_MASK, "depthMask", true);
          stateVariable(S_COLOR_MASK, S_COLOR_MASK, [true, true, true, true]);
          stateFlag(S_CULL_ENABLE, GL_CULL_FACE);
          stateVariable(S_CULL_FACE, "cullFace", GL_BACK);
          stateVariable(S_FRONT_FACE, S_FRONT_FACE, GL_CCW);
          stateVariable(S_LINE_WIDTH, S_LINE_WIDTH, 1);
          stateFlag(S_POLYGON_OFFSET_ENABLE, GL_POLYGON_OFFSET_FILL);
          stateVariable(S_POLYGON_OFFSET_OFFSET, "polygonOffset", [0, 0]);
          stateFlag(S_SAMPLE_ALPHA, GL_SAMPLE_ALPHA_TO_COVERAGE);
          stateFlag(S_SAMPLE_ENABLE, GL_SAMPLE_COVERAGE);
          stateVariable(S_SAMPLE_COVERAGE, "sampleCoverage", [1, false]);
          stateFlag(S_STENCIL_ENABLE, GL_STENCIL_TEST);
          stateVariable(S_STENCIL_MASK, "stencilMask", -1);
          stateVariable(S_STENCIL_FUNC, "stencilFunc", [GL_ALWAYS, 0, -1]);
          stateVariable(
            S_STENCIL_OPFRONT,
            "stencilOpSeparate",
            [GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP]
          );
          stateVariable(
            S_STENCIL_OPBACK,
            "stencilOpSeparate",
            [GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP]
          );
          stateFlag(S_SCISSOR_ENABLE, GL_SCISSOR_TEST);
          stateVariable(
            S_SCISSOR_BOX,
            "scissor",
            [0, 0, gl2.drawingBufferWidth, gl2.drawingBufferHeight]
          );
          stateVariable(
            S_VIEWPORT,
            S_VIEWPORT,
            [0, 0, gl2.drawingBufferWidth, gl2.drawingBufferHeight]
          );
          var sharedState = {
            gl: gl2,
            context: contextState,
            strings: stringStore,
            next: nextState,
            current: currentState,
            draw: drawState,
            elements: elementState,
            buffer: bufferState,
            shader: shaderState,
            attributes: attributeState.state,
            vao: attributeState,
            uniforms: uniformState,
            framebuffer: framebufferState,
            extensions,
            timer,
            isBufferArgs
          };
          var sharedConstants = {
            primTypes,
            compareFuncs,
            blendFuncs,
            blendEquations,
            stencilOps,
            glTypes,
            orientationType
          };
          if (extDrawBuffers) {
            sharedConstants.backBuffer = [GL_BACK];
            sharedConstants.drawBuffer = loop(limits.maxDrawbuffers, function(i) {
              if (i === 0) {
                return [0];
              }
              return loop(i, function(j) {
                return GL_COLOR_ATTACHMENT0$2 + j;
              });
            });
          }
          var drawCallCounter = 0;
          function createREGLEnvironment() {
            var env = createEnvironment({ cache: cachedCode });
            var link = env.link;
            var global2 = env.global;
            env.id = drawCallCounter++;
            env.batchId = "0";
            var SHARED = link(sharedState);
            var shared = env.shared = {
              props: "a0"
            };
            Object.keys(sharedState).forEach(function(prop) {
              shared[prop] = global2.def(SHARED, ".", prop);
            });
            var nextVars = env.next = {};
            var currentVars = env.current = {};
            Object.keys(GL_VARIABLES).forEach(function(variable) {
              if (Array.isArray(currentState[variable])) {
                nextVars[variable] = global2.def(shared.next, ".", variable);
                currentVars[variable] = global2.def(shared.current, ".", variable);
              }
            });
            var constants = env.constants = {};
            Object.keys(sharedConstants).forEach(function(name2) {
              constants[name2] = global2.def(JSON.stringify(sharedConstants[name2]));
            });
            env.invoke = function(block, x) {
              switch (x.type) {
                case DYN_FUNC$1:
                  var argList = [
                    "this",
                    shared.context,
                    shared.props,
                    env.batchId
                  ];
                  return block.def(
                    link(x.data),
                    ".call(",
                    argList.slice(0, Math.max(x.data.length + 1, 4)),
                    ")"
                  );
                case DYN_PROP$1:
                  return block.def(shared.props, x.data);
                case DYN_CONTEXT$1:
                  return block.def(shared.context, x.data);
                case DYN_STATE$1:
                  return block.def("this", x.data);
                case DYN_THUNK:
                  x.data.append(env, block);
                  return x.data.ref;
                case DYN_CONSTANT$1:
                  return x.data.toString();
                case DYN_ARRAY$1:
                  return x.data.map(function(y) {
                    return env.invoke(block, y);
                  });
              }
            };
            env.attribCache = {};
            var scopeAttribs = {};
            env.scopeAttrib = function(name2) {
              var id = stringStore.id(name2);
              if (id in scopeAttribs) {
                return scopeAttribs[id];
              }
              var binding = attributeState.scope[id];
              if (!binding) {
                binding = attributeState.scope[id] = new AttributeRecord2();
              }
              var result = scopeAttribs[id] = link(binding);
              return result;
            };
            return env;
          }
          function parseProfile(options) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var profileEnable;
            if (S_PROFILE in staticOptions) {
              var value = !!staticOptions[S_PROFILE];
              profileEnable = createStaticDecl(function(env, scope) {
                return value;
              });
              profileEnable.enable = value;
            } else if (S_PROFILE in dynamicOptions) {
              var dyn = dynamicOptions[S_PROFILE];
              profileEnable = createDynamicDecl(dyn, function(env, scope) {
                return env.invoke(scope, dyn);
              });
            }
            return profileEnable;
          }
          function parseFramebuffer(options, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            if (S_FRAMEBUFFER in staticOptions) {
              var framebuffer = staticOptions[S_FRAMEBUFFER];
              if (framebuffer) {
                framebuffer = framebufferState.getFramebuffer(framebuffer);
                return createStaticDecl(function(env2, block) {
                  var FRAMEBUFFER = env2.link(framebuffer);
                  var shared = env2.shared;
                  block.set(
                    shared.framebuffer,
                    ".next",
                    FRAMEBUFFER
                  );
                  var CONTEXT = shared.context;
                  block.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_WIDTH,
                    FRAMEBUFFER + ".width"
                  );
                  block.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_HEIGHT,
                    FRAMEBUFFER + ".height"
                  );
                  return FRAMEBUFFER;
                });
              } else {
                return createStaticDecl(function(env2, scope) {
                  var shared = env2.shared;
                  scope.set(
                    shared.framebuffer,
                    ".next",
                    "null"
                  );
                  var CONTEXT = shared.context;
                  scope.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_WIDTH,
                    CONTEXT + "." + S_DRAWINGBUFFER_WIDTH
                  );
                  scope.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_HEIGHT,
                    CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT
                  );
                  return "null";
                });
              }
            } else if (S_FRAMEBUFFER in dynamicOptions) {
              var dyn = dynamicOptions[S_FRAMEBUFFER];
              return createDynamicDecl(dyn, function(env2, scope) {
                var FRAMEBUFFER_FUNC = env2.invoke(scope, dyn);
                var shared = env2.shared;
                var FRAMEBUFFER_STATE = shared.framebuffer;
                var FRAMEBUFFER = scope.def(
                  FRAMEBUFFER_STATE,
                  ".getFramebuffer(",
                  FRAMEBUFFER_FUNC,
                  ")"
                );
                scope.set(
                  FRAMEBUFFER_STATE,
                  ".next",
                  FRAMEBUFFER
                );
                var CONTEXT = shared.context;
                scope.set(
                  CONTEXT,
                  "." + S_FRAMEBUFFER_WIDTH,
                  FRAMEBUFFER + "?" + FRAMEBUFFER + ".width:" + CONTEXT + "." + S_DRAWINGBUFFER_WIDTH
                );
                scope.set(
                  CONTEXT,
                  "." + S_FRAMEBUFFER_HEIGHT,
                  FRAMEBUFFER + "?" + FRAMEBUFFER + ".height:" + CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT
                );
                return FRAMEBUFFER;
              });
            } else {
              return null;
            }
          }
          function parseViewportScissor(options, framebuffer, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            function parseBox(param) {
              if (param in staticOptions) {
                var box = staticOptions[param];
                var isStatic2 = true;
                var x = box.x | 0;
                var y = box.y | 0;
                var w, h;
                if ("width" in box) {
                  w = box.width | 0;
                } else {
                  isStatic2 = false;
                }
                if ("height" in box) {
                  h = box.height | 0;
                } else {
                  isStatic2 = false;
                }
                return new Declaration(
                  !isStatic2 && framebuffer && framebuffer.thisDep,
                  !isStatic2 && framebuffer && framebuffer.contextDep,
                  !isStatic2 && framebuffer && framebuffer.propDep,
                  function(env2, scope) {
                    var CONTEXT = env2.shared.context;
                    var BOX_W = w;
                    if (!("width" in box)) {
                      BOX_W = scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH, "-", x);
                    }
                    var BOX_H = h;
                    if (!("height" in box)) {
                      BOX_H = scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT, "-", y);
                    }
                    return [x, y, BOX_W, BOX_H];
                  }
                );
              } else if (param in dynamicOptions) {
                var dynBox = dynamicOptions[param];
                var result = createDynamicDecl(dynBox, function(env2, scope) {
                  var BOX = env2.invoke(scope, dynBox);
                  var CONTEXT = env2.shared.context;
                  var BOX_X = scope.def(BOX, ".x|0");
                  var BOX_Y = scope.def(BOX, ".y|0");
                  var BOX_W = scope.def(
                    '"width" in ',
                    BOX,
                    "?",
                    BOX,
                    ".width|0:",
                    "(",
                    CONTEXT,
                    ".",
                    S_FRAMEBUFFER_WIDTH,
                    "-",
                    BOX_X,
                    ")"
                  );
                  var BOX_H = scope.def(
                    '"height" in ',
                    BOX,
                    "?",
                    BOX,
                    ".height|0:",
                    "(",
                    CONTEXT,
                    ".",
                    S_FRAMEBUFFER_HEIGHT,
                    "-",
                    BOX_Y,
                    ")"
                  );
                  return [BOX_X, BOX_Y, BOX_W, BOX_H];
                });
                if (framebuffer) {
                  result.thisDep = result.thisDep || framebuffer.thisDep;
                  result.contextDep = result.contextDep || framebuffer.contextDep;
                  result.propDep = result.propDep || framebuffer.propDep;
                }
                return result;
              } else if (framebuffer) {
                return new Declaration(
                  framebuffer.thisDep,
                  framebuffer.contextDep,
                  framebuffer.propDep,
                  function(env2, scope) {
                    var CONTEXT = env2.shared.context;
                    return [
                      0,
                      0,
                      scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH),
                      scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT)
                    ];
                  }
                );
              } else {
                return null;
              }
            }
            var viewport = parseBox(S_VIEWPORT);
            if (viewport) {
              var prevViewport = viewport;
              viewport = new Declaration(
                viewport.thisDep,
                viewport.contextDep,
                viewport.propDep,
                function(env2, scope) {
                  var VIEWPORT = prevViewport.append(env2, scope);
                  var CONTEXT = env2.shared.context;
                  scope.set(
                    CONTEXT,
                    "." + S_VIEWPORT_WIDTH,
                    VIEWPORT[2]
                  );
                  scope.set(
                    CONTEXT,
                    "." + S_VIEWPORT_HEIGHT,
                    VIEWPORT[3]
                  );
                  return VIEWPORT;
                }
              );
            }
            return {
              viewport,
              scissor_box: parseBox(S_SCISSOR_BOX)
            };
          }
          function parseAttribLocations(options, attributes) {
            var staticOptions = options.static;
            var staticProgram = typeof staticOptions[S_FRAG] === "string" && typeof staticOptions[S_VERT] === "string";
            if (staticProgram) {
              if (Object.keys(attributes.dynamic).length > 0) {
                return null;
              }
              var staticAttributes = attributes.static;
              var sAttributes = Object.keys(staticAttributes);
              if (sAttributes.length > 0 && typeof staticAttributes[sAttributes[0]] === "number") {
                var bindings = [];
                for (var i = 0; i < sAttributes.length; ++i) {
                  bindings.push([staticAttributes[sAttributes[i]] | 0, sAttributes[i]]);
                }
                return bindings;
              }
            }
            return null;
          }
          function parseProgram(options, env, attribLocations) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            function parseShader(name2) {
              if (name2 in staticOptions) {
                var id = stringStore.id(staticOptions[name2]);
                var result = createStaticDecl(function() {
                  return id;
                });
                result.id = id;
                return result;
              } else if (name2 in dynamicOptions) {
                var dyn = dynamicOptions[name2];
                return createDynamicDecl(dyn, function(env2, scope) {
                  var str = env2.invoke(scope, dyn);
                  var id2 = scope.def(env2.shared.strings, ".id(", str, ")");
                  return id2;
                });
              }
              return null;
            }
            var frag = parseShader(S_FRAG);
            var vert = parseShader(S_VERT);
            var program = null;
            var progVar;
            if (isStatic(frag) && isStatic(vert)) {
              program = shaderState.program(vert.id, frag.id, null, attribLocations);
              progVar = createStaticDecl(function(env2, scope) {
                return env2.link(program);
              });
            } else {
              progVar = new Declaration(
                frag && frag.thisDep || vert && vert.thisDep,
                frag && frag.contextDep || vert && vert.contextDep,
                frag && frag.propDep || vert && vert.propDep,
                function(env2, scope) {
                  var SHADER_STATE = env2.shared.shader;
                  var fragId;
                  if (frag) {
                    fragId = frag.append(env2, scope);
                  } else {
                    fragId = scope.def(SHADER_STATE, ".", S_FRAG);
                  }
                  var vertId;
                  if (vert) {
                    vertId = vert.append(env2, scope);
                  } else {
                    vertId = scope.def(SHADER_STATE, ".", S_VERT);
                  }
                  var progDef = SHADER_STATE + ".program(" + vertId + "," + fragId;
                  return scope.def(progDef + ")");
                }
              );
            }
            return {
              frag,
              vert,
              progVar,
              program
            };
          }
          function parseDraw(options, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var staticDraw = {};
            var vaoActive = false;
            function parseVAO() {
              if (S_VAO in staticOptions) {
                var vao2 = staticOptions[S_VAO];
                if (vao2 !== null && attributeState.getVAO(vao2) === null) {
                  vao2 = attributeState.createVAO(vao2);
                }
                vaoActive = true;
                staticDraw.vao = vao2;
                return createStaticDecl(function(env2) {
                  var vaoRef = attributeState.getVAO(vao2);
                  if (vaoRef) {
                    return env2.link(vaoRef);
                  } else {
                    return "null";
                  }
                });
              } else if (S_VAO in dynamicOptions) {
                vaoActive = true;
                var dyn = dynamicOptions[S_VAO];
                return createDynamicDecl(dyn, function(env2, scope) {
                  var vaoRef = env2.invoke(scope, dyn);
                  return scope.def(env2.shared.vao + ".getVAO(" + vaoRef + ")");
                });
              }
              return null;
            }
            var vao = parseVAO();
            var elementsActive = false;
            function parseElements() {
              if (S_ELEMENTS in staticOptions) {
                var elements2 = staticOptions[S_ELEMENTS];
                staticDraw.elements = elements2;
                if (isBufferArgs(elements2)) {
                  var e = staticDraw.elements = elementState.create(elements2, true);
                  elements2 = elementState.getElements(e);
                  elementsActive = true;
                } else if (elements2) {
                  elements2 = elementState.getElements(elements2);
                  elementsActive = true;
                }
                var result = createStaticDecl(function(env2, scope) {
                  if (elements2) {
                    var result2 = env2.link(elements2);
                    env2.ELEMENTS = result2;
                    return result2;
                  }
                  env2.ELEMENTS = null;
                  return null;
                });
                result.value = elements2;
                return result;
              } else if (S_ELEMENTS in dynamicOptions) {
                elementsActive = true;
                var dyn = dynamicOptions[S_ELEMENTS];
                return createDynamicDecl(dyn, function(env2, scope) {
                  var shared = env2.shared;
                  var IS_BUFFER_ARGS = shared.isBufferArgs;
                  var ELEMENT_STATE = shared.elements;
                  var elementDefn = env2.invoke(scope, dyn);
                  var elements3 = scope.def("null");
                  var elementStream = scope.def(IS_BUFFER_ARGS, "(", elementDefn, ")");
                  var ifte = env2.cond(elementStream).then(elements3, "=", ELEMENT_STATE, ".createStream(", elementDefn, ");").else(elements3, "=", ELEMENT_STATE, ".getElements(", elementDefn, ");");
                  scope.entry(ifte);
                  scope.exit(
                    env2.cond(elementStream).then(ELEMENT_STATE, ".destroyStream(", elements3, ");")
                  );
                  env2.ELEMENTS = elements3;
                  return elements3;
                });
              } else if (vaoActive) {
                return new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.elements + ".getElements(" + env2.shared.vao + ".currentVAO.elements):null");
                  }
                );
              }
              return null;
            }
            var elements = parseElements();
            function parsePrimitive() {
              if (S_PRIMITIVE in staticOptions) {
                var primitive2 = staticOptions[S_PRIMITIVE];
                staticDraw.primitive = primitive2;
                return createStaticDecl(function(env2, scope) {
                  return primTypes[primitive2];
                });
              } else if (S_PRIMITIVE in dynamicOptions) {
                var dynPrimitive = dynamicOptions[S_PRIMITIVE];
                return createDynamicDecl(dynPrimitive, function(env2, scope) {
                  var PRIM_TYPES = env2.constants.primTypes;
                  var prim = env2.invoke(scope, dynPrimitive);
                  return scope.def(PRIM_TYPES, "[", prim, "]");
                });
              } else if (elementsActive) {
                if (isStatic(elements)) {
                  if (elements.value) {
                    return createStaticDecl(function(env2, scope) {
                      return scope.def(env2.ELEMENTS, ".primType");
                    });
                  } else {
                    return createStaticDecl(function() {
                      return GL_TRIANGLES$1;
                    });
                  }
                } else {
                  return new Declaration(
                    elements.thisDep,
                    elements.contextDep,
                    elements.propDep,
                    function(env2, scope) {
                      var elements2 = env2.ELEMENTS;
                      return scope.def(elements2, "?", elements2, ".primType:", GL_TRIANGLES$1);
                    }
                  );
                }
              } else if (vaoActive) {
                return new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.primitive:" + GL_TRIANGLES$1);
                  }
                );
              }
              return null;
            }
            function parseParam(param, isOffset) {
              if (param in staticOptions) {
                var value = staticOptions[param] | 0;
                if (isOffset) {
                  staticDraw.offset = value;
                } else {
                  staticDraw.instances = value;
                }
                return createStaticDecl(function(env2, scope) {
                  if (isOffset) {
                    env2.OFFSET = value;
                  }
                  return value;
                });
              } else if (param in dynamicOptions) {
                var dynValue = dynamicOptions[param];
                return createDynamicDecl(dynValue, function(env2, scope) {
                  var result = env2.invoke(scope, dynValue);
                  if (isOffset) {
                    env2.OFFSET = result;
                  }
                  return result;
                });
              } else if (isOffset) {
                if (elementsActive) {
                  return createStaticDecl(function(env2, scope) {
                    env2.OFFSET = 0;
                    return 0;
                  });
                } else if (vaoActive) {
                  return new Declaration(
                    vao.thisDep,
                    vao.contextDep,
                    vao.propDep,
                    function(env2, scope) {
                      return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.offset:0");
                    }
                  );
                }
              } else if (vaoActive) {
                return new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.instances:-1");
                  }
                );
              }
              return null;
            }
            var OFFSET = parseParam(S_OFFSET, true);
            function parseVertCount() {
              if (S_COUNT in staticOptions) {
                var count2 = staticOptions[S_COUNT] | 0;
                staticDraw.count = count2;
                return createStaticDecl(function() {
                  return count2;
                });
              } else if (S_COUNT in dynamicOptions) {
                var dynCount = dynamicOptions[S_COUNT];
                return createDynamicDecl(dynCount, function(env2, scope) {
                  var result2 = env2.invoke(scope, dynCount);
                  return result2;
                });
              } else if (elementsActive) {
                if (isStatic(elements)) {
                  if (elements) {
                    if (OFFSET) {
                      return new Declaration(
                        OFFSET.thisDep,
                        OFFSET.contextDep,
                        OFFSET.propDep,
                        function(env2, scope) {
                          var result2 = scope.def(
                            env2.ELEMENTS,
                            ".vertCount-",
                            env2.OFFSET
                          );
                          return result2;
                        }
                      );
                    } else {
                      return createStaticDecl(function(env2, scope) {
                        return scope.def(env2.ELEMENTS, ".vertCount");
                      });
                    }
                  } else {
                    var result = createStaticDecl(function() {
                      return -1;
                    });
                    return result;
                  }
                } else {
                  var variable = new Declaration(
                    elements.thisDep || OFFSET.thisDep,
                    elements.contextDep || OFFSET.contextDep,
                    elements.propDep || OFFSET.propDep,
                    function(env2, scope) {
                      var elements2 = env2.ELEMENTS;
                      if (env2.OFFSET) {
                        return scope.def(
                          elements2,
                          "?",
                          elements2,
                          ".vertCount-",
                          env2.OFFSET,
                          ":-1"
                        );
                      }
                      return scope.def(elements2, "?", elements2, ".vertCount:-1");
                    }
                  );
                  return variable;
                }
              } else if (vaoActive) {
                var countVariable = new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao, ".currentVAO?", env2.shared.vao, ".currentVAO.count:-1");
                  }
                );
                return countVariable;
              }
              return null;
            }
            var primitive = parsePrimitive();
            var count = parseVertCount();
            var instances = parseParam(S_INSTANCES, false);
            return {
              elements,
              primitive,
              count,
              instances,
              offset: OFFSET,
              vao,
              vaoActive,
              elementsActive,
              // static draw props
              static: staticDraw
            };
          }
          function parseGLState(options, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var STATE = {};
            GL_STATE_NAMES.forEach(function(prop) {
              var param = propName(prop);
              function parseParam(parseStatic, parseDynamic) {
                if (prop in staticOptions) {
                  var value = parseStatic(staticOptions[prop]);
                  STATE[param] = createStaticDecl(function() {
                    return value;
                  });
                } else if (prop in dynamicOptions) {
                  var dyn = dynamicOptions[prop];
                  STATE[param] = createDynamicDecl(dyn, function(env2, scope) {
                    return parseDynamic(env2, scope, env2.invoke(scope, dyn));
                  });
                }
              }
              switch (prop) {
                case S_CULL_ENABLE:
                case S_BLEND_ENABLE:
                case S_DITHER:
                case S_STENCIL_ENABLE:
                case S_DEPTH_ENABLE:
                case S_SCISSOR_ENABLE:
                case S_POLYGON_OFFSET_ENABLE:
                case S_SAMPLE_ALPHA:
                case S_SAMPLE_ENABLE:
                case S_DEPTH_MASK:
                  return parseParam(
                    function(value) {
                      return value;
                    },
                    function(env2, scope, value) {
                      return value;
                    }
                  );
                case S_DEPTH_FUNC:
                  return parseParam(
                    function(value) {
                      return compareFuncs[value];
                    },
                    function(env2, scope, value) {
                      var COMPARE_FUNCS = env2.constants.compareFuncs;
                      return scope.def(COMPARE_FUNCS, "[", value, "]");
                    }
                  );
                case S_DEPTH_RANGE:
                  return parseParam(
                    function(value) {
                      return value;
                    },
                    function(env2, scope, value) {
                      var Z_NEAR = scope.def("+", value, "[0]");
                      var Z_FAR = scope.def("+", value, "[1]");
                      return [Z_NEAR, Z_FAR];
                    }
                  );
                case S_BLEND_FUNC:
                  return parseParam(
                    function(value) {
                      var srcRGB = "srcRGB" in value ? value.srcRGB : value.src;
                      var srcAlpha = "srcAlpha" in value ? value.srcAlpha : value.src;
                      var dstRGB = "dstRGB" in value ? value.dstRGB : value.dst;
                      var dstAlpha = "dstAlpha" in value ? value.dstAlpha : value.dst;
                      return [
                        blendFuncs[srcRGB],
                        blendFuncs[dstRGB],
                        blendFuncs[srcAlpha],
                        blendFuncs[dstAlpha]
                      ];
                    },
                    function(env2, scope, value) {
                      var BLEND_FUNCS = env2.constants.blendFuncs;
                      function read(prefix, suffix) {
                        var func = scope.def(
                          '"',
                          prefix,
                          suffix,
                          '" in ',
                          value,
                          "?",
                          value,
                          ".",
                          prefix,
                          suffix,
                          ":",
                          value,
                          ".",
                          prefix
                        );
                        return func;
                      }
                      var srcRGB = read("src", "RGB");
                      var dstRGB = read("dst", "RGB");
                      var SRC_RGB = scope.def(BLEND_FUNCS, "[", srcRGB, "]");
                      var SRC_ALPHA = scope.def(BLEND_FUNCS, "[", read("src", "Alpha"), "]");
                      var DST_RGB = scope.def(BLEND_FUNCS, "[", dstRGB, "]");
                      var DST_ALPHA = scope.def(BLEND_FUNCS, "[", read("dst", "Alpha"), "]");
                      return [SRC_RGB, DST_RGB, SRC_ALPHA, DST_ALPHA];
                    }
                  );
                case S_BLEND_EQUATION:
                  return parseParam(
                    function(value) {
                      if (typeof value === "string") {
                        return [
                          blendEquations[value],
                          blendEquations[value]
                        ];
                      } else if (typeof value === "object") {
                        return [
                          blendEquations[value.rgb],
                          blendEquations[value.alpha]
                        ];
                      } else {
                      }
                    },
                    function(env2, scope, value) {
                      var BLEND_EQUATIONS = env2.constants.blendEquations;
                      var RGB = scope.def();
                      var ALPHA = scope.def();
                      var ifte = env2.cond("typeof ", value, '==="string"');
                      ifte.then(
                        RGB,
                        "=",
                        ALPHA,
                        "=",
                        BLEND_EQUATIONS,
                        "[",
                        value,
                        "];"
                      );
                      ifte.else(
                        RGB,
                        "=",
                        BLEND_EQUATIONS,
                        "[",
                        value,
                        ".rgb];",
                        ALPHA,
                        "=",
                        BLEND_EQUATIONS,
                        "[",
                        value,
                        ".alpha];"
                      );
                      scope(ifte);
                      return [RGB, ALPHA];
                    }
                  );
                case S_BLEND_COLOR:
                  return parseParam(
                    function(value) {
                      return loop(4, function(i) {
                        return +value[i];
                      });
                    },
                    function(env2, scope, value) {
                      return loop(4, function(i) {
                        return scope.def("+", value, "[", i, "]");
                      });
                    }
                  );
                case S_STENCIL_MASK:
                  return parseParam(
                    function(value) {
                      return value | 0;
                    },
                    function(env2, scope, value) {
                      return scope.def(value, "|0");
                    }
                  );
                case S_STENCIL_FUNC:
                  return parseParam(
                    function(value) {
                      var cmp = value.cmp || "keep";
                      var ref = value.ref || 0;
                      var mask = "mask" in value ? value.mask : -1;
                      return [
                        compareFuncs[cmp],
                        ref,
                        mask
                      ];
                    },
                    function(env2, scope, value) {
                      var COMPARE_FUNCS = env2.constants.compareFuncs;
                      var cmp = scope.def(
                        '"cmp" in ',
                        value,
                        "?",
                        COMPARE_FUNCS,
                        "[",
                        value,
                        ".cmp]",
                        ":",
                        GL_KEEP
                      );
                      var ref = scope.def(value, ".ref|0");
                      var mask = scope.def(
                        '"mask" in ',
                        value,
                        "?",
                        value,
                        ".mask|0:-1"
                      );
                      return [cmp, ref, mask];
                    }
                  );
                case S_STENCIL_OPFRONT:
                case S_STENCIL_OPBACK:
                  return parseParam(
                    function(value) {
                      var fail = value.fail || "keep";
                      var zfail = value.zfail || "keep";
                      var zpass = value.zpass || "keep";
                      return [
                        prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
                        stencilOps[fail],
                        stencilOps[zfail],
                        stencilOps[zpass]
                      ];
                    },
                    function(env2, scope, value) {
                      var STENCIL_OPS = env2.constants.stencilOps;
                      function read(name2) {
                        return scope.def(
                          '"',
                          name2,
                          '" in ',
                          value,
                          "?",
                          STENCIL_OPS,
                          "[",
                          value,
                          ".",
                          name2,
                          "]:",
                          GL_KEEP
                        );
                      }
                      return [
                        prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
                        read("fail"),
                        read("zfail"),
                        read("zpass")
                      ];
                    }
                  );
                case S_POLYGON_OFFSET_OFFSET:
                  return parseParam(
                    function(value) {
                      var factor = value.factor | 0;
                      var units = value.units | 0;
                      return [factor, units];
                    },
                    function(env2, scope, value) {
                      var FACTOR = scope.def(value, ".factor|0");
                      var UNITS = scope.def(value, ".units|0");
                      return [FACTOR, UNITS];
                    }
                  );
                case S_CULL_FACE:
                  return parseParam(
                    function(value) {
                      var face = 0;
                      if (value === "front") {
                        face = GL_FRONT;
                      } else if (value === "back") {
                        face = GL_BACK;
                      }
                      return face;
                    },
                    function(env2, scope, value) {
                      return scope.def(value, '==="front"?', GL_FRONT, ":", GL_BACK);
                    }
                  );
                case S_LINE_WIDTH:
                  return parseParam(
                    function(value) {
                      return value;
                    },
                    function(env2, scope, value) {
                      return value;
                    }
                  );
                case S_FRONT_FACE:
                  return parseParam(
                    function(value) {
                      return orientationType[value];
                    },
                    function(env2, scope, value) {
                      return scope.def(value + '==="cw"?' + GL_CW + ":" + GL_CCW);
                    }
                  );
                case S_COLOR_MASK:
                  return parseParam(
                    function(value) {
                      return value.map(function(v) {
                        return !!v;
                      });
                    },
                    function(env2, scope, value) {
                      return loop(4, function(i) {
                        return "!!" + value + "[" + i + "]";
                      });
                    }
                  );
                case S_SAMPLE_COVERAGE:
                  return parseParam(
                    function(value) {
                      var sampleValue = "value" in value ? value.value : 1;
                      var sampleInvert = !!value.invert;
                      return [sampleValue, sampleInvert];
                    },
                    function(env2, scope, value) {
                      var VALUE = scope.def(
                        '"value" in ',
                        value,
                        "?+",
                        value,
                        ".value:1"
                      );
                      var INVERT = scope.def("!!", value, ".invert");
                      return [VALUE, INVERT];
                    }
                  );
              }
            });
            return STATE;
          }
          function parseUniforms(uniforms, env) {
            var staticUniforms = uniforms.static;
            var dynamicUniforms = uniforms.dynamic;
            var UNIFORMS = {};
            Object.keys(staticUniforms).forEach(function(name2) {
              var value = staticUniforms[name2];
              var result;
              if (typeof value === "number" || typeof value === "boolean") {
                result = createStaticDecl(function() {
                  return value;
                });
              } else if (typeof value === "function") {
                var reglType = value._reglType;
                if (reglType === "texture2d" || reglType === "textureCube") {
                  result = createStaticDecl(function(env2) {
                    return env2.link(value);
                  });
                } else if (reglType === "framebuffer" || reglType === "framebufferCube") {
                  result = createStaticDecl(function(env2) {
                    return env2.link(value.color[0]);
                  });
                } else {
                }
              } else if (isArrayLike(value)) {
                result = createStaticDecl(function(env2) {
                  var ITEM = env2.global.def(
                    "[",
                    loop(value.length, function(i) {
                      return value[i];
                    }),
                    "]"
                  );
                  return ITEM;
                });
              } else {
              }
              result.value = value;
              UNIFORMS[name2] = result;
            });
            Object.keys(dynamicUniforms).forEach(function(key) {
              var dyn = dynamicUniforms[key];
              UNIFORMS[key] = createDynamicDecl(dyn, function(env2, scope) {
                return env2.invoke(scope, dyn);
              });
            });
            return UNIFORMS;
          }
          function parseAttributes(attributes, env) {
            var staticAttributes = attributes.static;
            var dynamicAttributes = attributes.dynamic;
            var attributeDefs = {};
            Object.keys(staticAttributes).forEach(function(attribute) {
              var value = staticAttributes[attribute];
              var id = stringStore.id(attribute);
              var record = new AttributeRecord2();
              if (isBufferArgs(value)) {
                record.state = ATTRIB_STATE_POINTER;
                record.buffer = bufferState.getBuffer(
                  bufferState.create(value, GL_ARRAY_BUFFER$2, false, true)
                );
                record.type = 0;
              } else {
                var buffer = bufferState.getBuffer(value);
                if (buffer) {
                  record.state = ATTRIB_STATE_POINTER;
                  record.buffer = buffer;
                  record.type = 0;
                } else {
                  if ("constant" in value) {
                    var constant = value.constant;
                    record.buffer = "null";
                    record.state = ATTRIB_STATE_CONSTANT;
                    if (typeof constant === "number") {
                      record.x = constant;
                    } else {
                      CUTE_COMPONENTS.forEach(function(c, i) {
                        if (i < constant.length) {
                          record[c] = constant[i];
                        }
                      });
                    }
                  } else {
                    if (isBufferArgs(value.buffer)) {
                      buffer = bufferState.getBuffer(
                        bufferState.create(value.buffer, GL_ARRAY_BUFFER$2, false, true)
                      );
                    } else {
                      buffer = bufferState.getBuffer(value.buffer);
                    }
                    var offset = value.offset | 0;
                    var stride = value.stride | 0;
                    var size = value.size | 0;
                    var normalized = !!value.normalized;
                    var type = 0;
                    if ("type" in value) {
                      type = glTypes[value.type];
                    }
                    var divisor = value.divisor | 0;
                    record.buffer = buffer;
                    record.state = ATTRIB_STATE_POINTER;
                    record.size = size;
                    record.normalized = normalized;
                    record.type = type || buffer.dtype;
                    record.offset = offset;
                    record.stride = stride;
                    record.divisor = divisor;
                  }
                }
              }
              attributeDefs[attribute] = createStaticDecl(function(env2, scope) {
                var cache = env2.attribCache;
                if (id in cache) {
                  return cache[id];
                }
                var result = {
                  isStream: false
                };
                Object.keys(record).forEach(function(key) {
                  result[key] = record[key];
                });
                if (record.buffer) {
                  result.buffer = env2.link(record.buffer);
                  result.type = result.type || result.buffer + ".dtype";
                }
                cache[id] = result;
                return result;
              });
            });
            Object.keys(dynamicAttributes).forEach(function(attribute) {
              var dyn = dynamicAttributes[attribute];
              function appendAttributeCode(env2, block) {
                var VALUE = env2.invoke(block, dyn);
                var shared = env2.shared;
                var constants = env2.constants;
                var IS_BUFFER_ARGS = shared.isBufferArgs;
                var BUFFER_STATE = shared.buffer;
                var result = {
                  isStream: block.def(false)
                };
                var defaultRecord = new AttributeRecord2();
                defaultRecord.state = ATTRIB_STATE_POINTER;
                Object.keys(defaultRecord).forEach(function(key) {
                  result[key] = block.def("" + defaultRecord[key]);
                });
                var BUFFER = result.buffer;
                var TYPE = result.type;
                block(
                  "if(",
                  IS_BUFFER_ARGS,
                  "(",
                  VALUE,
                  ")){",
                  result.isStream,
                  "=true;",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".createStream(",
                  GL_ARRAY_BUFFER$2,
                  ",",
                  VALUE,
                  ");",
                  TYPE,
                  "=",
                  BUFFER,
                  ".dtype;",
                  "}else{",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".getBuffer(",
                  VALUE,
                  ");",
                  "if(",
                  BUFFER,
                  "){",
                  TYPE,
                  "=",
                  BUFFER,
                  ".dtype;",
                  '}else if("constant" in ',
                  VALUE,
                  "){",
                  result.state,
                  "=",
                  ATTRIB_STATE_CONSTANT,
                  ";",
                  "if(typeof " + VALUE + '.constant === "number"){',
                  result[CUTE_COMPONENTS[0]],
                  "=",
                  VALUE,
                  ".constant;",
                  CUTE_COMPONENTS.slice(1).map(function(n) {
                    return result[n];
                  }).join("="),
                  "=0;",
                  "}else{",
                  CUTE_COMPONENTS.map(function(name2, i) {
                    return result[name2] + "=" + VALUE + ".constant.length>" + i + "?" + VALUE + ".constant[" + i + "]:0;";
                  }).join(""),
                  "}}else{",
                  "if(",
                  IS_BUFFER_ARGS,
                  "(",
                  VALUE,
                  ".buffer)){",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".createStream(",
                  GL_ARRAY_BUFFER$2,
                  ",",
                  VALUE,
                  ".buffer);",
                  "}else{",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".getBuffer(",
                  VALUE,
                  ".buffer);",
                  "}",
                  TYPE,
                  '="type" in ',
                  VALUE,
                  "?",
                  constants.glTypes,
                  "[",
                  VALUE,
                  ".type]:",
                  BUFFER,
                  ".dtype;",
                  result.normalized,
                  "=!!",
                  VALUE,
                  ".normalized;"
                );
                function emitReadRecord(name2) {
                  block(result[name2], "=", VALUE, ".", name2, "|0;");
                }
                emitReadRecord("size");
                emitReadRecord("offset");
                emitReadRecord("stride");
                emitReadRecord("divisor");
                block("}}");
                block.exit(
                  "if(",
                  result.isStream,
                  "){",
                  BUFFER_STATE,
                  ".destroyStream(",
                  BUFFER,
                  ");",
                  "}"
                );
                return result;
              }
              attributeDefs[attribute] = createDynamicDecl(dyn, appendAttributeCode);
            });
            return attributeDefs;
          }
          function parseContext(context) {
            var staticContext = context.static;
            var dynamicContext = context.dynamic;
            var result = {};
            Object.keys(staticContext).forEach(function(name2) {
              var value = staticContext[name2];
              result[name2] = createStaticDecl(function(env, scope) {
                if (typeof value === "number" || typeof value === "boolean") {
                  return "" + value;
                } else {
                  return env.link(value);
                }
              });
            });
            Object.keys(dynamicContext).forEach(function(name2) {
              var dyn = dynamicContext[name2];
              result[name2] = createDynamicDecl(dyn, function(env, scope) {
                return env.invoke(scope, dyn);
              });
            });
            return result;
          }
          function parseArguments(options, attributes, uniforms, context, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var attribLocations = parseAttribLocations(options, attributes);
            var framebuffer = parseFramebuffer(options, env);
            var viewportAndScissor = parseViewportScissor(options, framebuffer, env);
            var draw = parseDraw(options, env);
            var state = parseGLState(options, env);
            var shader = parseProgram(options, env, attribLocations);
            function copyBox(name2) {
              var defn = viewportAndScissor[name2];
              if (defn) {
                state[name2] = defn;
              }
            }
            copyBox(S_VIEWPORT);
            copyBox(propName(S_SCISSOR_BOX));
            var dirty = Object.keys(state).length > 0;
            var result = {
              framebuffer,
              draw,
              shader,
              state,
              dirty,
              scopeVAO: null,
              drawVAO: null,
              useVAO: false,
              attributes: {}
            };
            result.profile = parseProfile(options, env);
            result.uniforms = parseUniforms(uniforms, env);
            result.drawVAO = result.scopeVAO = draw.vao;
            if (!result.drawVAO && shader.program && !attribLocations && extensions.angle_instanced_arrays && draw.static.elements) {
              var useVAO = true;
              var staticBindings = shader.program.attributes.map(function(attr) {
                var binding = attributes.static[attr];
                useVAO = useVAO && !!binding;
                return binding;
              });
              if (useVAO && staticBindings.length > 0) {
                var vao = attributeState.getVAO(attributeState.createVAO({
                  attributes: staticBindings,
                  elements: draw.static.elements
                }));
                result.drawVAO = new Declaration(null, null, null, function(env2, scope) {
                  return env2.link(vao);
                });
                result.useVAO = true;
              }
            }
            if (attribLocations) {
              result.useVAO = true;
            } else {
              result.attributes = parseAttributes(attributes, env);
            }
            result.context = parseContext(context, env);
            return result;
          }
          function emitContext(env, scope, context) {
            var shared = env.shared;
            var CONTEXT = shared.context;
            var contextEnter = env.scope();
            Object.keys(context).forEach(function(name2) {
              scope.save(CONTEXT, "." + name2);
              var defn = context[name2];
              var value = defn.append(env, scope);
              if (Array.isArray(value)) {
                contextEnter(CONTEXT, ".", name2, "=[", value.join(), "];");
              } else {
                contextEnter(CONTEXT, ".", name2, "=", value, ";");
              }
            });
            scope(contextEnter);
          }
          function emitPollFramebuffer(env, scope, framebuffer, skipCheck) {
            var shared = env.shared;
            var GL = shared.gl;
            var FRAMEBUFFER_STATE = shared.framebuffer;
            var EXT_DRAW_BUFFERS;
            if (extDrawBuffers) {
              EXT_DRAW_BUFFERS = scope.def(shared.extensions, ".webgl_draw_buffers");
            }
            var constants = env.constants;
            var DRAW_BUFFERS = constants.drawBuffer;
            var BACK_BUFFER = constants.backBuffer;
            var NEXT;
            if (framebuffer) {
              NEXT = framebuffer.append(env, scope);
            } else {
              NEXT = scope.def(FRAMEBUFFER_STATE, ".next");
            }
            if (!skipCheck) {
              scope("if(", NEXT, "!==", FRAMEBUFFER_STATE, ".cur){");
            }
            scope(
              "if(",
              NEXT,
              "){",
              GL,
              ".bindFramebuffer(",
              GL_FRAMEBUFFER$2,
              ",",
              NEXT,
              ".framebuffer);"
            );
            if (extDrawBuffers) {
              scope(
                EXT_DRAW_BUFFERS,
                ".drawBuffersWEBGL(",
                DRAW_BUFFERS,
                "[",
                NEXT,
                ".colorAttachments.length]);"
              );
            }
            scope(
              "}else{",
              GL,
              ".bindFramebuffer(",
              GL_FRAMEBUFFER$2,
              ",null);"
            );
            if (extDrawBuffers) {
              scope(EXT_DRAW_BUFFERS, ".drawBuffersWEBGL(", BACK_BUFFER, ");");
            }
            scope(
              "}",
              FRAMEBUFFER_STATE,
              ".cur=",
              NEXT,
              ";"
            );
            if (!skipCheck) {
              scope("}");
            }
          }
          function emitPollState(env, scope, args) {
            var shared = env.shared;
            var GL = shared.gl;
            var CURRENT_VARS = env.current;
            var NEXT_VARS = env.next;
            var CURRENT_STATE = shared.current;
            var NEXT_STATE = shared.next;
            var block = env.cond(CURRENT_STATE, ".dirty");
            GL_STATE_NAMES.forEach(function(prop) {
              var param = propName(prop);
              if (param in args.state) {
                return;
              }
              var NEXT, CURRENT;
              if (param in NEXT_VARS) {
                NEXT = NEXT_VARS[param];
                CURRENT = CURRENT_VARS[param];
                var parts = loop(currentState[param].length, function(i) {
                  return block.def(NEXT, "[", i, "]");
                });
                block(env.cond(parts.map(function(p, i) {
                  return p + "!==" + CURRENT + "[" + i + "]";
                }).join("||")).then(
                  GL,
                  ".",
                  GL_VARIABLES[param],
                  "(",
                  parts,
                  ");",
                  parts.map(function(p, i) {
                    return CURRENT + "[" + i + "]=" + p;
                  }).join(";"),
                  ";"
                ));
              } else {
                NEXT = block.def(NEXT_STATE, ".", param);
                var ifte = env.cond(NEXT, "!==", CURRENT_STATE, ".", param);
                block(ifte);
                if (param in GL_FLAGS) {
                  ifte(
                    env.cond(NEXT).then(GL, ".enable(", GL_FLAGS[param], ");").else(GL, ".disable(", GL_FLAGS[param], ");"),
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    NEXT,
                    ";"
                  );
                } else {
                  ifte(
                    GL,
                    ".",
                    GL_VARIABLES[param],
                    "(",
                    NEXT,
                    ");",
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    NEXT,
                    ";"
                  );
                }
              }
            });
            if (Object.keys(args.state).length === 0) {
              block(CURRENT_STATE, ".dirty=false;");
            }
            scope(block);
          }
          function emitSetOptions(env, scope, options, filter) {
            var shared = env.shared;
            var CURRENT_VARS = env.current;
            var CURRENT_STATE = shared.current;
            var GL = shared.gl;
            var VALUE;
            sortState(Object.keys(options)).forEach(function(param) {
              var defn = options[param];
              if (filter && !filter(defn)) {
                return;
              }
              var variable = defn.append(env, scope);
              if (GL_FLAGS[param]) {
                var flag = GL_FLAGS[param];
                if (isStatic(defn)) {
                  VALUE = env.link(variable, { stable: true });
                  scope(env.cond(VALUE).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");"));
                  scope(CURRENT_STATE, ".", param, "=", VALUE, ";");
                } else {
                  scope(env.cond(variable).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");"));
                  scope(CURRENT_STATE, ".", param, "=", variable, ";");
                }
              } else if (isArrayLike(variable)) {
                var CURRENT = CURRENT_VARS[param];
                scope(
                  GL,
                  ".",
                  GL_VARIABLES[param],
                  "(",
                  variable,
                  ");",
                  variable.map(function(v, i) {
                    return CURRENT + "[" + i + "]=" + v;
                  }).join(";"),
                  ";"
                );
              } else {
                if (isStatic(defn)) {
                  VALUE = env.link(variable, { stable: true });
                  scope(
                    GL,
                    ".",
                    GL_VARIABLES[param],
                    "(",
                    VALUE,
                    ");",
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    VALUE,
                    ";"
                  );
                } else {
                  scope(
                    GL,
                    ".",
                    GL_VARIABLES[param],
                    "(",
                    variable,
                    ");",
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    variable,
                    ";"
                  );
                }
              }
            });
          }
          function injectExtensions(env, scope) {
            if (extInstancing) {
              env.instancing = scope.def(
                env.shared.extensions,
                ".angle_instanced_arrays"
              );
            }
          }
          function emitProfile(env, scope, args, useScope, incrementCounter) {
            var shared = env.shared;
            var STATS = env.stats;
            var CURRENT_STATE = shared.current;
            var TIMER = shared.timer;
            var profileArg = args.profile;
            function perfCounter() {
              if (typeof performance === "undefined") {
                return "Date.now()";
              } else {
                return "performance.now()";
              }
            }
            var CPU_START, QUERY_COUNTER;
            function emitProfileStart(block) {
              CPU_START = scope.def();
              block(CPU_START, "=", perfCounter(), ";");
              if (typeof incrementCounter === "string") {
                block(STATS, ".count+=", incrementCounter, ";");
              } else {
                block(STATS, ".count++;");
              }
              if (timer) {
                if (useScope) {
                  QUERY_COUNTER = scope.def();
                  block(QUERY_COUNTER, "=", TIMER, ".getNumPendingQueries();");
                } else {
                  block(TIMER, ".beginQuery(", STATS, ");");
                }
              }
            }
            function emitProfileEnd(block) {
              block(STATS, ".cpuTime+=", perfCounter(), "-", CPU_START, ";");
              if (timer) {
                if (useScope) {
                  block(
                    TIMER,
                    ".pushScopeStats(",
                    QUERY_COUNTER,
                    ",",
                    TIMER,
                    ".getNumPendingQueries(),",
                    STATS,
                    ");"
                  );
                } else {
                  block(TIMER, ".endQuery();");
                }
              }
            }
            function scopeProfile(value) {
              var prev = scope.def(CURRENT_STATE, ".profile");
              scope(CURRENT_STATE, ".profile=", value, ";");
              scope.exit(CURRENT_STATE, ".profile=", prev, ";");
            }
            var USE_PROFILE;
            if (profileArg) {
              if (isStatic(profileArg)) {
                if (profileArg.enable) {
                  emitProfileStart(scope);
                  emitProfileEnd(scope.exit);
                  scopeProfile("true");
                } else {
                  scopeProfile("false");
                }
                return;
              }
              USE_PROFILE = profileArg.append(env, scope);
              scopeProfile(USE_PROFILE);
            } else {
              USE_PROFILE = scope.def(CURRENT_STATE, ".profile");
            }
            var start = env.block();
            emitProfileStart(start);
            scope("if(", USE_PROFILE, "){", start, "}");
            var end = env.block();
            emitProfileEnd(end);
            scope.exit("if(", USE_PROFILE, "){", end, "}");
          }
          function emitAttributes(env, scope, args, attributes, filter) {
            var shared = env.shared;
            function typeLength(x) {
              switch (x) {
                case GL_FLOAT_VEC2:
                case GL_INT_VEC2:
                case GL_BOOL_VEC2:
                  return 2;
                case GL_FLOAT_VEC3:
                case GL_INT_VEC3:
                case GL_BOOL_VEC3:
                  return 3;
                case GL_FLOAT_VEC4:
                case GL_INT_VEC4:
                case GL_BOOL_VEC4:
                  return 4;
                default:
                  return 1;
              }
            }
            function emitBindAttribute(ATTRIBUTE, size, record) {
              var GL = shared.gl;
              var LOCATION = scope.def(ATTRIBUTE, ".location");
              var BINDING = scope.def(shared.attributes, "[", LOCATION, "]");
              var STATE = record.state;
              var BUFFER = record.buffer;
              var CONST_COMPONENTS = [
                record.x,
                record.y,
                record.z,
                record.w
              ];
              var COMMON_KEYS = [
                "buffer",
                "normalized",
                "offset",
                "stride"
              ];
              function emitBuffer() {
                scope(
                  "if(!",
                  BINDING,
                  ".buffer){",
                  GL,
                  ".enableVertexAttribArray(",
                  LOCATION,
                  ");}"
                );
                var TYPE = record.type;
                var SIZE;
                if (!record.size) {
                  SIZE = size;
                } else {
                  SIZE = scope.def(record.size, "||", size);
                }
                scope(
                  "if(",
                  BINDING,
                  ".type!==",
                  TYPE,
                  "||",
                  BINDING,
                  ".size!==",
                  SIZE,
                  "||",
                  COMMON_KEYS.map(function(key) {
                    return BINDING + "." + key + "!==" + record[key];
                  }).join("||"),
                  "){",
                  GL,
                  ".bindBuffer(",
                  GL_ARRAY_BUFFER$2,
                  ",",
                  BUFFER,
                  ".buffer);",
                  GL,
                  ".vertexAttribPointer(",
                  [
                    LOCATION,
                    SIZE,
                    TYPE,
                    record.normalized,
                    record.stride,
                    record.offset
                  ],
                  ");",
                  BINDING,
                  ".type=",
                  TYPE,
                  ";",
                  BINDING,
                  ".size=",
                  SIZE,
                  ";",
                  COMMON_KEYS.map(function(key) {
                    return BINDING + "." + key + "=" + record[key] + ";";
                  }).join(""),
                  "}"
                );
                if (extInstancing) {
                  var DIVISOR = record.divisor;
                  scope(
                    "if(",
                    BINDING,
                    ".divisor!==",
                    DIVISOR,
                    "){",
                    env.instancing,
                    ".vertexAttribDivisorANGLE(",
                    [LOCATION, DIVISOR],
                    ");",
                    BINDING,
                    ".divisor=",
                    DIVISOR,
                    ";}"
                  );
                }
              }
              function emitConstant() {
                scope(
                  "if(",
                  BINDING,
                  ".buffer){",
                  GL,
                  ".disableVertexAttribArray(",
                  LOCATION,
                  ");",
                  BINDING,
                  ".buffer=null;",
                  "}if(",
                  CUTE_COMPONENTS.map(function(c, i) {
                    return BINDING + "." + c + "!==" + CONST_COMPONENTS[i];
                  }).join("||"),
                  "){",
                  GL,
                  ".vertexAttrib4f(",
                  LOCATION,
                  ",",
                  CONST_COMPONENTS,
                  ");",
                  CUTE_COMPONENTS.map(function(c, i) {
                    return BINDING + "." + c + "=" + CONST_COMPONENTS[i] + ";";
                  }).join(""),
                  "}"
                );
              }
              if (STATE === ATTRIB_STATE_POINTER) {
                emitBuffer();
              } else if (STATE === ATTRIB_STATE_CONSTANT) {
                emitConstant();
              } else {
                scope("if(", STATE, "===", ATTRIB_STATE_POINTER, "){");
                emitBuffer();
                scope("}else{");
                emitConstant();
                scope("}");
              }
            }
            attributes.forEach(function(attribute) {
              var name2 = attribute.name;
              var arg = args.attributes[name2];
              var record;
              if (arg) {
                if (!filter(arg)) {
                  return;
                }
                record = arg.append(env, scope);
              } else {
                if (!filter(SCOPE_DECL)) {
                  return;
                }
                var scopeAttrib = env.scopeAttrib(name2);
                record = {};
                Object.keys(new AttributeRecord2()).forEach(function(key) {
                  record[key] = scope.def(scopeAttrib, ".", key);
                });
              }
              emitBindAttribute(
                env.link(attribute),
                typeLength(attribute.info.type),
                record
              );
            });
          }
          function emitUniforms(env, scope, args, uniforms, filter, isBatchInnerLoop) {
            var shared = env.shared;
            var GL = shared.gl;
            var infix;
            for (var i = 0; i < uniforms.length; ++i) {
              var uniform = uniforms[i];
              var name2 = uniform.name;
              var type = uniform.info.type;
              var arg = args.uniforms[name2];
              var UNIFORM = env.link(uniform);
              var LOCATION = UNIFORM + ".location";
              var VALUE;
              if (arg) {
                if (!filter(arg)) {
                  continue;
                }
                if (isStatic(arg)) {
                  var value = arg.value;
                  if (type === GL_SAMPLER_2D || type === GL_SAMPLER_CUBE) {
                    var TEX_VALUE = env.link(value._texture || value.color[0]._texture);
                    scope(GL, ".uniform1i(", LOCATION, ",", TEX_VALUE + ".bind());");
                    scope.exit(TEX_VALUE, ".unbind();");
                  } else if (type === GL_FLOAT_MAT2 || type === GL_FLOAT_MAT3 || type === GL_FLOAT_MAT4) {
                    var MAT_VALUE = env.global.def("new Float32Array([" + Array.prototype.slice.call(value) + "])");
                    var dim = 2;
                    if (type === GL_FLOAT_MAT3) {
                      dim = 3;
                    } else if (type === GL_FLOAT_MAT4) {
                      dim = 4;
                    }
                    scope(
                      GL,
                      ".uniformMatrix",
                      dim,
                      "fv(",
                      LOCATION,
                      ",false,",
                      MAT_VALUE,
                      ");"
                    );
                  } else {
                    switch (type) {
                      case GL_FLOAT$7:
                        infix = "1f";
                        break;
                      case GL_FLOAT_VEC2:
                        infix = "2f";
                        break;
                      case GL_FLOAT_VEC3:
                        infix = "3f";
                        break;
                      case GL_FLOAT_VEC4:
                        infix = "4f";
                        break;
                      case GL_BOOL:
                        infix = "1i";
                        break;
                      case GL_INT$2:
                        infix = "1i";
                        break;
                      case GL_BOOL_VEC2:
                        infix = "2i";
                        break;
                      case GL_INT_VEC2:
                        infix = "2i";
                        break;
                      case GL_BOOL_VEC3:
                        infix = "3i";
                        break;
                      case GL_INT_VEC3:
                        infix = "3i";
                        break;
                      case GL_BOOL_VEC4:
                        infix = "4i";
                        break;
                      case GL_INT_VEC4:
                        infix = "4i";
                        break;
                    }
                    scope(
                      GL,
                      ".uniform",
                      infix,
                      "(",
                      LOCATION,
                      ",",
                      isArrayLike(value) ? Array.prototype.slice.call(value) : value,
                      ");"
                    );
                  }
                  continue;
                } else {
                  VALUE = arg.append(env, scope);
                }
              } else {
                if (!filter(SCOPE_DECL)) {
                  continue;
                }
                VALUE = scope.def(shared.uniforms, "[", stringStore.id(name2), "]");
              }
              if (type === GL_SAMPLER_2D) {
                scope(
                  "if(",
                  VALUE,
                  "&&",
                  VALUE,
                  '._reglType==="framebuffer"){',
                  VALUE,
                  "=",
                  VALUE,
                  ".color[0];",
                  "}"
                );
              } else if (type === GL_SAMPLER_CUBE) {
                scope(
                  "if(",
                  VALUE,
                  "&&",
                  VALUE,
                  '._reglType==="framebufferCube"){',
                  VALUE,
                  "=",
                  VALUE,
                  ".color[0];",
                  "}"
                );
              }
              var unroll = 1;
              switch (type) {
                case GL_SAMPLER_2D:
                case GL_SAMPLER_CUBE:
                  var TEX = scope.def(VALUE, "._texture");
                  scope(GL, ".uniform1i(", LOCATION, ",", TEX, ".bind());");
                  scope.exit(TEX, ".unbind();");
                  continue;
                case GL_INT$2:
                case GL_BOOL:
                  infix = "1i";
                  break;
                case GL_INT_VEC2:
                case GL_BOOL_VEC2:
                  infix = "2i";
                  unroll = 2;
                  break;
                case GL_INT_VEC3:
                case GL_BOOL_VEC3:
                  infix = "3i";
                  unroll = 3;
                  break;
                case GL_INT_VEC4:
                case GL_BOOL_VEC4:
                  infix = "4i";
                  unroll = 4;
                  break;
                case GL_FLOAT$7:
                  infix = "1f";
                  break;
                case GL_FLOAT_VEC2:
                  infix = "2f";
                  unroll = 2;
                  break;
                case GL_FLOAT_VEC3:
                  infix = "3f";
                  unroll = 3;
                  break;
                case GL_FLOAT_VEC4:
                  infix = "4f";
                  unroll = 4;
                  break;
                case GL_FLOAT_MAT2:
                  infix = "Matrix2fv";
                  break;
                case GL_FLOAT_MAT3:
                  infix = "Matrix3fv";
                  break;
                case GL_FLOAT_MAT4:
                  infix = "Matrix4fv";
                  break;
              }
              if (infix.charAt(0) === "M") {
                scope(GL, ".uniform", infix, "(", LOCATION, ",");
                var matSize = Math.pow(type - GL_FLOAT_MAT2 + 2, 2);
                var STORAGE = env.global.def("new Float32Array(", matSize, ")");
                if (Array.isArray(VALUE)) {
                  scope(
                    "false,(",
                    loop(matSize, function(i2) {
                      return STORAGE + "[" + i2 + "]=" + VALUE[i2];
                    }),
                    ",",
                    STORAGE,
                    ")"
                  );
                } else {
                  scope(
                    "false,(Array.isArray(",
                    VALUE,
                    ")||",
                    VALUE,
                    " instanceof Float32Array)?",
                    VALUE,
                    ":(",
                    loop(matSize, function(i2) {
                      return STORAGE + "[" + i2 + "]=" + VALUE + "[" + i2 + "]";
                    }),
                    ",",
                    STORAGE,
                    ")"
                  );
                }
                scope(");");
              } else if (unroll > 1) {
                var prev = [];
                var cur = [];
                for (var j = 0; j < unroll; ++j) {
                  if (Array.isArray(VALUE)) {
                    cur.push(VALUE[j]);
                  } else {
                    cur.push(scope.def(VALUE + "[" + j + "]"));
                  }
                  if (isBatchInnerLoop) {
                    prev.push(scope.def());
                  }
                }
                if (isBatchInnerLoop) {
                  scope("if(!", env.batchId, "||", prev.map(function(p, i2) {
                    return p + "!==" + cur[i2];
                  }).join("||"), "){", prev.map(function(p, i2) {
                    return p + "=" + cur[i2] + ";";
                  }).join(""));
                }
                scope(GL, ".uniform", infix, "(", LOCATION, ",", cur.join(","), ");");
                if (isBatchInnerLoop) {
                  scope("}");
                }
              } else {
                if (isBatchInnerLoop) {
                  var prevS = scope.def();
                  scope(
                    "if(!",
                    env.batchId,
                    "||",
                    prevS,
                    "!==",
                    VALUE,
                    "){",
                    prevS,
                    "=",
                    VALUE,
                    ";"
                  );
                }
                scope(GL, ".uniform", infix, "(", LOCATION, ",", VALUE, ");");
                if (isBatchInnerLoop) {
                  scope("}");
                }
              }
            }
          }
          function emitDraw(env, outer, inner, args) {
            var shared = env.shared;
            var GL = shared.gl;
            var DRAW_STATE = shared.draw;
            var drawOptions = args.draw;
            function emitElements() {
              var defn = drawOptions.elements;
              var ELEMENTS2;
              var scope = outer;
              if (defn) {
                if (defn.contextDep && args.contextDynamic || defn.propDep) {
                  scope = inner;
                }
                ELEMENTS2 = defn.append(env, scope);
                if (drawOptions.elementsActive) {
                  scope(
                    "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);"
                  );
                }
              } else {
                ELEMENTS2 = scope.def();
                scope(
                  ELEMENTS2,
                  "=",
                  DRAW_STATE,
                  ".",
                  S_ELEMENTS,
                  ";",
                  "if(",
                  ELEMENTS2,
                  "){",
                  GL,
                  ".bindBuffer(",
                  GL_ELEMENT_ARRAY_BUFFER$2,
                  ",",
                  ELEMENTS2,
                  ".buffer.buffer);}",
                  "else if(",
                  shared.vao,
                  ".currentVAO){",
                  ELEMENTS2,
                  "=",
                  env.shared.elements + ".getElements(" + shared.vao,
                  ".currentVAO.elements);",
                  !extVertexArrays ? "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);" : "",
                  "}"
                );
              }
              return ELEMENTS2;
            }
            function emitCount() {
              var defn = drawOptions.count;
              var COUNT2;
              var scope = outer;
              if (defn) {
                if (defn.contextDep && args.contextDynamic || defn.propDep) {
                  scope = inner;
                }
                COUNT2 = defn.append(env, scope);
              } else {
                COUNT2 = scope.def(DRAW_STATE, ".", S_COUNT);
              }
              return COUNT2;
            }
            var ELEMENTS = emitElements();
            function emitValue(name2) {
              var defn = drawOptions[name2];
              if (defn) {
                if (defn.contextDep && args.contextDynamic || defn.propDep) {
                  return defn.append(env, inner);
                } else {
                  return defn.append(env, outer);
                }
              } else {
                return outer.def(DRAW_STATE, ".", name2);
              }
            }
            var PRIMITIVE = emitValue(S_PRIMITIVE);
            var OFFSET = emitValue(S_OFFSET);
            var COUNT = emitCount();
            if (typeof COUNT === "number") {
              if (COUNT === 0) {
                return;
              }
            } else {
              inner("if(", COUNT, "){");
              inner.exit("}");
            }
            var INSTANCES, EXT_INSTANCING;
            if (extInstancing) {
              INSTANCES = emitValue(S_INSTANCES);
              EXT_INSTANCING = env.instancing;
            }
            var ELEMENT_TYPE = ELEMENTS + ".type";
            var elementsStatic = drawOptions.elements && isStatic(drawOptions.elements) && !drawOptions.vaoActive;
            function emitInstancing() {
              function drawElements() {
                inner(EXT_INSTANCING, ".drawElementsInstancedANGLE(", [
                  PRIMITIVE,
                  COUNT,
                  ELEMENT_TYPE,
                  OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)",
                  INSTANCES
                ], ");");
              }
              function drawArrays() {
                inner(
                  EXT_INSTANCING,
                  ".drawArraysInstancedANGLE(",
                  [PRIMITIVE, OFFSET, COUNT, INSTANCES],
                  ");"
                );
              }
              if (ELEMENTS && ELEMENTS !== "null") {
                if (!elementsStatic) {
                  inner("if(", ELEMENTS, "){");
                  drawElements();
                  inner("}else{");
                  drawArrays();
                  inner("}");
                } else {
                  drawElements();
                }
              } else {
                drawArrays();
              }
            }
            function emitRegular() {
              function drawElements() {
                inner(GL + ".drawElements(" + [
                  PRIMITIVE,
                  COUNT,
                  ELEMENT_TYPE,
                  OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)"
                ] + ");");
              }
              function drawArrays() {
                inner(GL + ".drawArrays(" + [PRIMITIVE, OFFSET, COUNT] + ");");
              }
              if (ELEMENTS && ELEMENTS !== "null") {
                if (!elementsStatic) {
                  inner("if(", ELEMENTS, "){");
                  drawElements();
                  inner("}else{");
                  drawArrays();
                  inner("}");
                } else {
                  drawElements();
                }
              } else {
                drawArrays();
              }
            }
            if (extInstancing && (typeof INSTANCES !== "number" || INSTANCES >= 0)) {
              if (typeof INSTANCES === "string") {
                inner("if(", INSTANCES, ">0){");
                emitInstancing();
                inner("}else if(", INSTANCES, "<0){");
                emitRegular();
                inner("}");
              } else {
                emitInstancing();
              }
            } else {
              emitRegular();
            }
          }
          function createBody(emitBody, parentEnv, args, program, count) {
            var env = createREGLEnvironment();
            var scope = env.proc("body", count);
            if (extInstancing) {
              env.instancing = scope.def(
                env.shared.extensions,
                ".angle_instanced_arrays"
              );
            }
            emitBody(env, scope, args, program);
            return env.compile().body;
          }
          function emitDrawBody(env, draw, args, program) {
            injectExtensions(env, draw);
            if (args.useVAO) {
              if (args.drawVAO) {
                draw(env.shared.vao, ".setVAO(", args.drawVAO.append(env, draw), ");");
              } else {
                draw(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);");
              }
            } else {
              draw(env.shared.vao, ".setVAO(null);");
              emitAttributes(env, draw, args, program.attributes, function() {
                return true;
              });
            }
            emitUniforms(env, draw, args, program.uniforms, function() {
              return true;
            }, false);
            emitDraw(env, draw, draw, args);
          }
          function emitDrawProc(env, args) {
            var draw = env.proc("draw", 1);
            injectExtensions(env, draw);
            emitContext(env, draw, args.context);
            emitPollFramebuffer(env, draw, args.framebuffer);
            emitPollState(env, draw, args);
            emitSetOptions(env, draw, args.state);
            emitProfile(env, draw, args, false, true);
            var program = args.shader.progVar.append(env, draw);
            draw(env.shared.gl, ".useProgram(", program, ".program);");
            if (args.shader.program) {
              emitDrawBody(env, draw, args, args.shader.program);
            } else {
              draw(env.shared.vao, ".setVAO(null);");
              var drawCache = env.global.def("{}");
              var PROG_ID = draw.def(program, ".id");
              var CACHED_PROC = draw.def(drawCache, "[", PROG_ID, "]");
              draw(
                env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0);").else(
                  CACHED_PROC,
                  "=",
                  drawCache,
                  "[",
                  PROG_ID,
                  "]=",
                  env.link(function(program2) {
                    return createBody(emitDrawBody, env, args, program2, 1);
                  }),
                  "(",
                  program,
                  ");",
                  CACHED_PROC,
                  ".call(this,a0);"
                )
              );
            }
            if (Object.keys(args.state).length > 0) {
              draw(env.shared.current, ".dirty=true;");
            }
            if (env.shared.vao) {
              draw(env.shared.vao, ".setVAO(null);");
            }
          }
          function emitBatchDynamicShaderBody(env, scope, args, program) {
            env.batchId = "a1";
            injectExtensions(env, scope);
            function all() {
              return true;
            }
            emitAttributes(env, scope, args, program.attributes, all);
            emitUniforms(env, scope, args, program.uniforms, all, false);
            emitDraw(env, scope, scope, args);
          }
          function emitBatchBody(env, scope, args, program) {
            injectExtensions(env, scope);
            var contextDynamic = args.contextDep;
            var BATCH_ID = scope.def();
            var PROP_LIST = "a0";
            var NUM_PROPS = "a1";
            var PROPS = scope.def();
            env.shared.props = PROPS;
            env.batchId = BATCH_ID;
            var outer = env.scope();
            var inner = env.scope();
            scope(
              outer.entry,
              "for(",
              BATCH_ID,
              "=0;",
              BATCH_ID,
              "<",
              NUM_PROPS,
              ";++",
              BATCH_ID,
              "){",
              PROPS,
              "=",
              PROP_LIST,
              "[",
              BATCH_ID,
              "];",
              inner,
              "}",
              outer.exit
            );
            function isInnerDefn(defn) {
              return defn.contextDep && contextDynamic || defn.propDep;
            }
            function isOuterDefn(defn) {
              return !isInnerDefn(defn);
            }
            if (args.needsContext) {
              emitContext(env, inner, args.context);
            }
            if (args.needsFramebuffer) {
              emitPollFramebuffer(env, inner, args.framebuffer);
            }
            emitSetOptions(env, inner, args.state, isInnerDefn);
            if (args.profile && isInnerDefn(args.profile)) {
              emitProfile(env, inner, args, false, true);
            }
            if (!program) {
              var progCache = env.global.def("{}");
              var PROGRAM = args.shader.progVar.append(env, inner);
              var PROG_ID = inner.def(PROGRAM, ".id");
              var CACHED_PROC = inner.def(progCache, "[", PROG_ID, "]");
              inner(
                env.shared.gl,
                ".useProgram(",
                PROGRAM,
                ".program);",
                "if(!",
                CACHED_PROC,
                "){",
                CACHED_PROC,
                "=",
                progCache,
                "[",
                PROG_ID,
                "]=",
                env.link(function(program2) {
                  return createBody(
                    emitBatchDynamicShaderBody,
                    env,
                    args,
                    program2,
                    2
                  );
                }),
                "(",
                PROGRAM,
                ");}",
                CACHED_PROC,
                ".call(this,a0[",
                BATCH_ID,
                "],",
                BATCH_ID,
                ");"
              );
            } else {
              if (args.useVAO) {
                if (args.drawVAO) {
                  if (isInnerDefn(args.drawVAO)) {
                    inner(env.shared.vao, ".setVAO(", args.drawVAO.append(env, inner), ");");
                  } else {
                    outer(env.shared.vao, ".setVAO(", args.drawVAO.append(env, outer), ");");
                  }
                } else {
                  outer(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);");
                }
              } else {
                outer(env.shared.vao, ".setVAO(null);");
                emitAttributes(env, outer, args, program.attributes, isOuterDefn);
                emitAttributes(env, inner, args, program.attributes, isInnerDefn);
              }
              emitUniforms(env, outer, args, program.uniforms, isOuterDefn, false);
              emitUniforms(env, inner, args, program.uniforms, isInnerDefn, true);
              emitDraw(env, outer, inner, args);
            }
          }
          function emitBatchProc(env, args) {
            var batch = env.proc("batch", 2);
            env.batchId = "0";
            injectExtensions(env, batch);
            var contextDynamic = false;
            var needsContext = true;
            Object.keys(args.context).forEach(function(name2) {
              contextDynamic = contextDynamic || args.context[name2].propDep;
            });
            if (!contextDynamic) {
              emitContext(env, batch, args.context);
              needsContext = false;
            }
            var framebuffer = args.framebuffer;
            var needsFramebuffer = false;
            if (framebuffer) {
              if (framebuffer.propDep) {
                contextDynamic = needsFramebuffer = true;
              } else if (framebuffer.contextDep && contextDynamic) {
                needsFramebuffer = true;
              }
              if (!needsFramebuffer) {
                emitPollFramebuffer(env, batch, framebuffer);
              }
            } else {
              emitPollFramebuffer(env, batch, null);
            }
            if (args.state.viewport && args.state.viewport.propDep) {
              contextDynamic = true;
            }
            function isInnerDefn(defn) {
              return defn.contextDep && contextDynamic || defn.propDep;
            }
            emitPollState(env, batch, args);
            emitSetOptions(env, batch, args.state, function(defn) {
              return !isInnerDefn(defn);
            });
            if (!args.profile || !isInnerDefn(args.profile)) {
              emitProfile(env, batch, args, false, "a1");
            }
            args.contextDep = contextDynamic;
            args.needsContext = needsContext;
            args.needsFramebuffer = needsFramebuffer;
            var progDefn = args.shader.progVar;
            if (progDefn.contextDep && contextDynamic || progDefn.propDep) {
              emitBatchBody(
                env,
                batch,
                args,
                null
              );
            } else {
              var PROGRAM = progDefn.append(env, batch);
              batch(env.shared.gl, ".useProgram(", PROGRAM, ".program);");
              if (args.shader.program) {
                emitBatchBody(
                  env,
                  batch,
                  args,
                  args.shader.program
                );
              } else {
                batch(env.shared.vao, ".setVAO(null);");
                var batchCache = env.global.def("{}");
                var PROG_ID = batch.def(PROGRAM, ".id");
                var CACHED_PROC = batch.def(batchCache, "[", PROG_ID, "]");
                batch(
                  env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0,a1);").else(
                    CACHED_PROC,
                    "=",
                    batchCache,
                    "[",
                    PROG_ID,
                    "]=",
                    env.link(function(program) {
                      return createBody(emitBatchBody, env, args, program, 2);
                    }),
                    "(",
                    PROGRAM,
                    ");",
                    CACHED_PROC,
                    ".call(this,a0,a1);"
                  )
                );
              }
            }
            if (Object.keys(args.state).length > 0) {
              batch(env.shared.current, ".dirty=true;");
            }
            if (env.shared.vao) {
              batch(env.shared.vao, ".setVAO(null);");
            }
          }
          function emitScopeProc(env, args) {
            var scope = env.proc("scope", 3);
            env.batchId = "a2";
            var shared = env.shared;
            var CURRENT_STATE = shared.current;
            emitContext(env, scope, args.context);
            if (args.framebuffer) {
              args.framebuffer.append(env, scope);
            }
            sortState(Object.keys(args.state)).forEach(function(name2) {
              var defn = args.state[name2];
              var value = defn.append(env, scope);
              if (isArrayLike(value)) {
                value.forEach(function(v, i) {
                  if (hasVariableReference(v)) {
                    scope.set(env.next[name2], "[" + i + "]", v);
                  } else {
                    scope.set(env.next[name2], "[" + i + "]", env.link(v, { stable: true }));
                  }
                });
              } else {
                if (isStatic(defn)) {
                  scope.set(shared.next, "." + name2, env.link(value, { stable: true }));
                } else {
                  scope.set(shared.next, "." + name2, value);
                }
              }
            });
            emitProfile(env, scope, args, true, true);
            [S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach(
              function(opt) {
                var variable = args.draw[opt];
                if (!variable) {
                  return;
                }
                var VARIABLE2 = variable.append(env, scope);
                if (hasVariableReference(VARIABLE2)) {
                  scope.set(shared.draw, "." + opt, VARIABLE2);
                } else {
                  scope.set(shared.draw, "." + opt, env.link(VARIABLE2), { stable: true });
                }
              }
            );
            Object.keys(args.uniforms).forEach(function(opt) {
              var value = args.uniforms[opt].append(env, scope);
              if (Array.isArray(value)) {
                value = "[" + value.map(function(v) {
                  if (hasVariableReference(v)) {
                    return v;
                  } else {
                    return env.link(v, { stable: true });
                  }
                }) + "]";
              }
              scope.set(
                shared.uniforms,
                "[" + env.link(stringStore.id(opt), { stable: true }) + "]",
                value
              );
            });
            Object.keys(args.attributes).forEach(function(name2) {
              var record = args.attributes[name2].append(env, scope);
              var scopeAttrib = env.scopeAttrib(name2);
              Object.keys(new AttributeRecord2()).forEach(function(prop) {
                scope.set(scopeAttrib, "." + prop, record[prop]);
              });
            });
            if (args.scopeVAO) {
              var VARIABLE = args.scopeVAO.append(env, scope);
              if (hasVariableReference(VARIABLE)) {
                scope.set(shared.vao, ".targetVAO", VARIABLE);
              } else {
                scope.set(shared.vao, ".targetVAO", env.link(VARIABLE, { stable: true }));
              }
            }
            function saveShader(name2) {
              var shader = args.shader[name2];
              if (shader) {
                var VARIABLE2 = shader.append(env, scope);
                if (hasVariableReference(VARIABLE2)) {
                  scope.set(shared.shader, "." + name2, VARIABLE2);
                } else {
                  scope.set(shared.shader, "." + name2, env.link(VARIABLE2, { stable: true }));
                }
              }
            }
            saveShader(S_VERT);
            saveShader(S_FRAG);
            if (Object.keys(args.state).length > 0) {
              scope(CURRENT_STATE, ".dirty=true;");
              scope.exit(CURRENT_STATE, ".dirty=true;");
            }
            scope("a1(", env.shared.context, ",a0,", env.batchId, ");");
          }
          function isDynamicObject(object) {
            if (typeof object !== "object" || isArrayLike(object)) {
              return;
            }
            var props = Object.keys(object);
            for (var i = 0; i < props.length; ++i) {
              if (dynamic.isDynamic(object[props[i]])) {
                return true;
              }
            }
            return false;
          }
          function splatObject(env, options, name2) {
            var object = options.static[name2];
            if (!object || !isDynamicObject(object)) {
              return;
            }
            var globals = env.global;
            var keys = Object.keys(object);
            var thisDep = false;
            var contextDep = false;
            var propDep = false;
            var objectRef = env.global.def("{}");
            keys.forEach(function(key) {
              var value = object[key];
              if (dynamic.isDynamic(value)) {
                if (typeof value === "function") {
                  value = object[key] = dynamic.unbox(value);
                }
                var deps = createDynamicDecl(value, null);
                thisDep = thisDep || deps.thisDep;
                propDep = propDep || deps.propDep;
                contextDep = contextDep || deps.contextDep;
              } else {
                globals(objectRef, ".", key, "=");
                switch (typeof value) {
                  case "number":
                    globals(value);
                    break;
                  case "string":
                    globals('"', value, '"');
                    break;
                  case "object":
                    if (Array.isArray(value)) {
                      globals("[", value.join(), "]");
                    }
                    break;
                  default:
                    globals(env.link(value));
                    break;
                }
                globals(";");
              }
            });
            function appendBlock(env2, block) {
              keys.forEach(function(key) {
                var value = object[key];
                if (!dynamic.isDynamic(value)) {
                  return;
                }
                var ref = env2.invoke(block, value);
                block(objectRef, ".", key, "=", ref, ";");
              });
            }
            options.dynamic[name2] = new dynamic.DynamicVariable(DYN_THUNK, {
              thisDep,
              contextDep,
              propDep,
              ref: objectRef,
              append: appendBlock
            });
            delete options.static[name2];
          }
          function compileCommand(options, attributes, uniforms, context, stats2) {
            var env = createREGLEnvironment();
            env.stats = env.link(stats2);
            Object.keys(attributes.static).forEach(function(key) {
              splatObject(env, attributes, key);
            });
            NESTED_OPTIONS.forEach(function(name2) {
              splatObject(env, options, name2);
            });
            var args = parseArguments(options, attributes, uniforms, context, env);
            if (args.shader.program) {
              args.shader.program.attributes.sort(function(a, b) {
                return a.name < b.name ? -1 : 1;
              });
              args.shader.program.uniforms.sort(function(a, b) {
                return a.name < b.name ? -1 : 1;
              });
            }
            emitDrawProc(env, args);
            emitScopeProc(env, args);
            emitBatchProc(env, args);
            return extend2(env.compile(), {
              destroy: function() {
                args.shader.program.destroy();
              }
            });
          }
          return {
            next: nextState,
            current: currentState,
            procs: function() {
              var env = createREGLEnvironment();
              var poll = env.proc("poll");
              var refresh = env.proc("refresh");
              var common = env.block();
              poll(common);
              refresh(common);
              var shared = env.shared;
              var GL = shared.gl;
              var NEXT_STATE = shared.next;
              var CURRENT_STATE = shared.current;
              common(CURRENT_STATE, ".dirty=false;");
              emitPollFramebuffer(env, poll);
              emitPollFramebuffer(env, refresh, null, true);
              var INSTANCING;
              if (extInstancing) {
                INSTANCING = env.link(extInstancing);
              }
              if (extensions.oes_vertex_array_object) {
                refresh(env.link(extensions.oes_vertex_array_object), ".bindVertexArrayOES(null);");
              }
              var BINDING = refresh.def(shared.attributes);
              var TEMP_BINDING = refresh.def(0);
              var ifte = env.cond(TEMP_BINDING, ".buffer");
              ifte.then(
                GL,
                ".enableVertexAttribArray(i);",
                GL,
                ".bindBuffer(",
                GL_ARRAY_BUFFER$2,
                ",",
                TEMP_BINDING,
                ".buffer.buffer);",
                GL,
                ".vertexAttribPointer(i,",
                TEMP_BINDING,
                ".size,",
                TEMP_BINDING,
                ".type,",
                TEMP_BINDING,
                ".normalized,",
                TEMP_BINDING,
                ".stride,",
                TEMP_BINDING,
                ".offset);"
              ).else(
                GL,
                ".disableVertexAttribArray(i);",
                GL,
                ".vertexAttrib4f(i,",
                TEMP_BINDING,
                ".x,",
                TEMP_BINDING,
                ".y,",
                TEMP_BINDING,
                ".z,",
                TEMP_BINDING,
                ".w);",
                TEMP_BINDING,
                ".buffer=null;"
              );
              var MAX_ATTRIBUTES = env.link(limits.maxAttributes, { stable: true });
              refresh(
                "for(var i=0;i<",
                MAX_ATTRIBUTES,
                ";++i){",
                TEMP_BINDING,
                "=",
                BINDING,
                "[i];",
                ifte,
                "}"
              );
              if (extInstancing) {
                refresh(
                  "for(var i=0;i<",
                  MAX_ATTRIBUTES,
                  ";++i){",
                  INSTANCING,
                  ".vertexAttribDivisorANGLE(i,",
                  BINDING,
                  "[i].divisor);",
                  "}"
                );
              }
              refresh(
                env.shared.vao,
                ".currentVAO=null;",
                env.shared.vao,
                ".setVAO(",
                env.shared.vao,
                ".targetVAO);"
              );
              Object.keys(GL_FLAGS).forEach(function(flag) {
                var cap = GL_FLAGS[flag];
                var NEXT = common.def(NEXT_STATE, ".", flag);
                var block = env.block();
                block(
                  "if(",
                  NEXT,
                  "){",
                  GL,
                  ".enable(",
                  cap,
                  ")}else{",
                  GL,
                  ".disable(",
                  cap,
                  ")}",
                  CURRENT_STATE,
                  ".",
                  flag,
                  "=",
                  NEXT,
                  ";"
                );
                refresh(block);
                poll(
                  "if(",
                  NEXT,
                  "!==",
                  CURRENT_STATE,
                  ".",
                  flag,
                  "){",
                  block,
                  "}"
                );
              });
              Object.keys(GL_VARIABLES).forEach(function(name2) {
                var func = GL_VARIABLES[name2];
                var init = currentState[name2];
                var NEXT, CURRENT;
                var block = env.block();
                block(GL, ".", func, "(");
                if (isArrayLike(init)) {
                  var n = init.length;
                  NEXT = env.global.def(NEXT_STATE, ".", name2);
                  CURRENT = env.global.def(CURRENT_STATE, ".", name2);
                  block(
                    loop(n, function(i) {
                      return NEXT + "[" + i + "]";
                    }),
                    ");",
                    loop(n, function(i) {
                      return CURRENT + "[" + i + "]=" + NEXT + "[" + i + "];";
                    }).join("")
                  );
                  poll(
                    "if(",
                    loop(n, function(i) {
                      return NEXT + "[" + i + "]!==" + CURRENT + "[" + i + "]";
                    }).join("||"),
                    "){",
                    block,
                    "}"
                  );
                } else {
                  NEXT = common.def(NEXT_STATE, ".", name2);
                  CURRENT = common.def(CURRENT_STATE, ".", name2);
                  block(
                    NEXT,
                    ");",
                    CURRENT_STATE,
                    ".",
                    name2,
                    "=",
                    NEXT,
                    ";"
                  );
                  poll(
                    "if(",
                    NEXT,
                    "!==",
                    CURRENT,
                    "){",
                    block,
                    "}"
                  );
                }
                refresh(block);
              });
              return env.compile();
            }(),
            compile: compileCommand
          };
        }
        function stats() {
          return {
            vaoCount: 0,
            bufferCount: 0,
            elementsCount: 0,
            framebufferCount: 0,
            shaderCount: 0,
            textureCount: 0,
            cubeCount: 0,
            renderbufferCount: 0,
            maxTextureUnits: 0
          };
        }
        var GL_QUERY_RESULT_EXT = 34918;
        var GL_QUERY_RESULT_AVAILABLE_EXT = 34919;
        var GL_TIME_ELAPSED_EXT = 35007;
        var createTimer = function(gl2, extensions) {
          if (!extensions.ext_disjoint_timer_query) {
            return null;
          }
          var queryPool = [];
          function allocQuery() {
            return queryPool.pop() || extensions.ext_disjoint_timer_query.createQueryEXT();
          }
          function freeQuery(query) {
            queryPool.push(query);
          }
          var pendingQueries = [];
          function beginQuery(stats2) {
            var query = allocQuery();
            extensions.ext_disjoint_timer_query.beginQueryEXT(GL_TIME_ELAPSED_EXT, query);
            pendingQueries.push(query);
            pushScopeStats(pendingQueries.length - 1, pendingQueries.length, stats2);
          }
          function endQuery() {
            extensions.ext_disjoint_timer_query.endQueryEXT(GL_TIME_ELAPSED_EXT);
          }
          function PendingStats() {
            this.startQueryIndex = -1;
            this.endQueryIndex = -1;
            this.sum = 0;
            this.stats = null;
          }
          var pendingStatsPool = [];
          function allocPendingStats() {
            return pendingStatsPool.pop() || new PendingStats();
          }
          function freePendingStats(pendingStats2) {
            pendingStatsPool.push(pendingStats2);
          }
          var pendingStats = [];
          function pushScopeStats(start, end, stats2) {
            var ps = allocPendingStats();
            ps.startQueryIndex = start;
            ps.endQueryIndex = end;
            ps.sum = 0;
            ps.stats = stats2;
            pendingStats.push(ps);
          }
          var timeSum = [];
          var queryPtr = [];
          function update() {
            var ptr, i;
            var n = pendingQueries.length;
            if (n === 0) {
              return;
            }
            queryPtr.length = Math.max(queryPtr.length, n + 1);
            timeSum.length = Math.max(timeSum.length, n + 1);
            timeSum[0] = 0;
            queryPtr[0] = 0;
            var queryTime = 0;
            ptr = 0;
            for (i = 0; i < pendingQueries.length; ++i) {
              var query = pendingQueries[i];
              if (extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT)) {
                queryTime += extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_EXT);
                freeQuery(query);
              } else {
                pendingQueries[ptr++] = query;
              }
              timeSum[i + 1] = queryTime;
              queryPtr[i + 1] = ptr;
            }
            pendingQueries.length = ptr;
            ptr = 0;
            for (i = 0; i < pendingStats.length; ++i) {
              var stats2 = pendingStats[i];
              var start = stats2.startQueryIndex;
              var end = stats2.endQueryIndex;
              stats2.sum += timeSum[end] - timeSum[start];
              var startPtr = queryPtr[start];
              var endPtr = queryPtr[end];
              if (endPtr === startPtr) {
                stats2.stats.gpuTime += stats2.sum / 1e6;
                freePendingStats(stats2);
              } else {
                stats2.startQueryIndex = startPtr;
                stats2.endQueryIndex = endPtr;
                pendingStats[ptr++] = stats2;
              }
            }
            pendingStats.length = ptr;
          }
          return {
            beginQuery,
            endQuery,
            pushScopeStats,
            update,
            getNumPendingQueries: function() {
              return pendingQueries.length;
            },
            clear: function() {
              queryPool.push.apply(queryPool, pendingQueries);
              for (var i = 0; i < queryPool.length; i++) {
                extensions.ext_disjoint_timer_query.deleteQueryEXT(queryPool[i]);
              }
              pendingQueries.length = 0;
              queryPool.length = 0;
            },
            restore: function() {
              pendingQueries.length = 0;
              queryPool.length = 0;
            }
          };
        };
        var GL_COLOR_BUFFER_BIT = 16384;
        var GL_DEPTH_BUFFER_BIT = 256;
        var GL_STENCIL_BUFFER_BIT = 1024;
        var GL_ARRAY_BUFFER = 34962;
        var CONTEXT_LOST_EVENT = "webglcontextlost";
        var CONTEXT_RESTORED_EVENT = "webglcontextrestored";
        var DYN_PROP = 1;
        var DYN_CONTEXT = 2;
        var DYN_STATE = 3;
        function find(haystack, needle) {
          for (var i = 0; i < haystack.length; ++i) {
            if (haystack[i] === needle) {
              return i;
            }
          }
          return -1;
        }
        function wrapREGL(args) {
          var config = parseArgs(args);
          if (!config) {
            return null;
          }
          var gl2 = config.gl;
          var glAttributes = gl2.getContextAttributes();
          var contextLost = gl2.isContextLost();
          var extensionState = createExtensionCache(gl2, config);
          if (!extensionState) {
            return null;
          }
          var stringStore = createStringStore();
          var stats$$1 = stats();
          var cachedCode = config.cachedCode || {};
          var extensions = extensionState.extensions;
          var timer = createTimer(gl2, extensions);
          var START_TIME = clock();
          var WIDTH = gl2.drawingBufferWidth;
          var HEIGHT = gl2.drawingBufferHeight;
          var contextState = {
            tick: 0,
            time: 0,
            viewportWidth: WIDTH,
            viewportHeight: HEIGHT,
            framebufferWidth: WIDTH,
            framebufferHeight: HEIGHT,
            drawingBufferWidth: WIDTH,
            drawingBufferHeight: HEIGHT,
            pixelRatio: config.pixelRatio
          };
          var uniformState = {};
          var drawState = {
            elements: null,
            primitive: 4,
            // GL_TRIANGLES
            count: -1,
            offset: 0,
            instances: -1
          };
          var limits = wrapLimits(gl2, extensions);
          var bufferState = wrapBufferState(
            gl2,
            stats$$1,
            config,
            destroyBuffer
          );
          var elementState = wrapElementsState(gl2, extensions, bufferState, stats$$1);
          var attributeState = wrapAttributeState(
            gl2,
            extensions,
            limits,
            stats$$1,
            bufferState,
            elementState,
            drawState
          );
          function destroyBuffer(buffer) {
            return attributeState.destroyBuffer(buffer);
          }
          var shaderState = wrapShaderState(gl2, stringStore, stats$$1, config);
          var textureState = createTextureSet(
            gl2,
            extensions,
            limits,
            function() {
              core.procs.poll();
            },
            contextState,
            stats$$1,
            config
          );
          var renderbufferState = wrapRenderbuffers(gl2, extensions, limits, stats$$1, config);
          var framebufferState = wrapFBOState(
            gl2,
            extensions,
            limits,
            textureState,
            renderbufferState,
            stats$$1
          );
          var core = reglCore(
            gl2,
            stringStore,
            extensions,
            limits,
            bufferState,
            elementState,
            textureState,
            framebufferState,
            uniformState,
            attributeState,
            shaderState,
            drawState,
            contextState,
            timer,
            cachedCode,
            config
          );
          var readPixels = wrapReadPixels(
            gl2,
            framebufferState,
            core.procs.poll,
            contextState,
            glAttributes,
            extensions,
            limits
          );
          var nextState = core.next;
          var canvas = gl2.canvas;
          var rafCallbacks = [];
          var lossCallbacks = [];
          var restoreCallbacks = [];
          var destroyCallbacks = [config.onDestroy];
          var activeRAF = null;
          function handleRAF() {
            if (rafCallbacks.length === 0) {
              if (timer) {
                timer.update();
              }
              activeRAF = null;
              return;
            }
            activeRAF = raf.next(handleRAF);
            poll();
            for (var i = rafCallbacks.length - 1; i >= 0; --i) {
              var cb = rafCallbacks[i];
              if (cb) {
                cb(contextState, null, 0);
              }
            }
            gl2.flush();
            if (timer) {
              timer.update();
            }
          }
          function startRAF() {
            if (!activeRAF && rafCallbacks.length > 0) {
              activeRAF = raf.next(handleRAF);
            }
          }
          function stopRAF() {
            if (activeRAF) {
              raf.cancel(handleRAF);
              activeRAF = null;
            }
          }
          function handleContextLoss(event) {
            event.preventDefault();
            contextLost = true;
            stopRAF();
            lossCallbacks.forEach(function(cb) {
              cb();
            });
          }
          function handleContextRestored(event) {
            gl2.getError();
            contextLost = false;
            extensionState.restore();
            shaderState.restore();
            bufferState.restore();
            textureState.restore();
            renderbufferState.restore();
            framebufferState.restore();
            attributeState.restore();
            if (timer) {
              timer.restore();
            }
            core.procs.refresh();
            startRAF();
            restoreCallbacks.forEach(function(cb) {
              cb();
            });
          }
          if (canvas) {
            canvas.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false);
            canvas.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false);
          }
          function destroy() {
            rafCallbacks.length = 0;
            stopRAF();
            if (canvas) {
              canvas.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss);
              canvas.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored);
            }
            shaderState.clear();
            framebufferState.clear();
            renderbufferState.clear();
            attributeState.clear();
            textureState.clear();
            elementState.clear();
            bufferState.clear();
            if (timer) {
              timer.clear();
            }
            destroyCallbacks.forEach(function(cb) {
              cb();
            });
          }
          function compileProcedure(options) {
            function flattenNestedOptions(options2) {
              var result = extend2({}, options2);
              delete result.uniforms;
              delete result.attributes;
              delete result.context;
              delete result.vao;
              if ("stencil" in result && result.stencil.op) {
                result.stencil.opBack = result.stencil.opFront = result.stencil.op;
                delete result.stencil.op;
              }
              function merge(name2) {
                if (name2 in result) {
                  var child = result[name2];
                  delete result[name2];
                  Object.keys(child).forEach(function(prop) {
                    result[name2 + "." + prop] = child[prop];
                  });
                }
              }
              merge("blend");
              merge("depth");
              merge("cull");
              merge("stencil");
              merge("polygonOffset");
              merge("scissor");
              merge("sample");
              if ("vao" in options2) {
                result.vao = options2.vao;
              }
              return result;
            }
            function separateDynamic(object, useArrays) {
              var staticItems = {};
              var dynamicItems = {};
              Object.keys(object).forEach(function(option) {
                var value = object[option];
                if (dynamic.isDynamic(value)) {
                  dynamicItems[option] = dynamic.unbox(value, option);
                  return;
                } else if (useArrays && Array.isArray(value)) {
                  for (var i = 0; i < value.length; ++i) {
                    if (dynamic.isDynamic(value[i])) {
                      dynamicItems[option] = dynamic.unbox(value, option);
                      return;
                    }
                  }
                }
                staticItems[option] = value;
              });
              return {
                dynamic: dynamicItems,
                static: staticItems
              };
            }
            var context = separateDynamic(options.context || {}, true);
            var uniforms = separateDynamic(options.uniforms || {}, true);
            var attributes = separateDynamic(options.attributes || {}, false);
            var opts = separateDynamic(flattenNestedOptions(options), false);
            var stats$$12 = {
              gpuTime: 0,
              cpuTime: 0,
              count: 0
            };
            var compiled = core.compile(opts, attributes, uniforms, context, stats$$12);
            var draw = compiled.draw;
            var batch = compiled.batch;
            var scope = compiled.scope;
            var EMPTY_ARRAY = [];
            function reserve(count) {
              while (EMPTY_ARRAY.length < count) {
                EMPTY_ARRAY.push(null);
              }
              return EMPTY_ARRAY;
            }
            function REGLCommand(args2, body) {
              var i;
              if (contextLost) {
              }
              if (typeof args2 === "function") {
                return scope.call(this, null, args2, 0);
              } else if (typeof body === "function") {
                if (typeof args2 === "number") {
                  for (i = 0; i < args2; ++i) {
                    scope.call(this, null, body, i);
                  }
                } else if (Array.isArray(args2)) {
                  for (i = 0; i < args2.length; ++i) {
                    scope.call(this, args2[i], body, i);
                  }
                } else {
                  return scope.call(this, args2, body, 0);
                }
              } else if (typeof args2 === "number") {
                if (args2 > 0) {
                  return batch.call(this, reserve(args2 | 0), args2 | 0);
                }
              } else if (Array.isArray(args2)) {
                if (args2.length) {
                  return batch.call(this, args2, args2.length);
                }
              } else {
                return draw.call(this, args2);
              }
            }
            return extend2(REGLCommand, {
              stats: stats$$12,
              destroy: function() {
                compiled.destroy();
              }
            });
          }
          var setFBO = framebufferState.setFBO = compileProcedure({
            framebuffer: dynamic.define.call(null, DYN_PROP, "framebuffer")
          });
          function clearImpl(_, options) {
            var clearFlags = 0;
            core.procs.poll();
            var c = options.color;
            if (c) {
              gl2.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0);
              clearFlags |= GL_COLOR_BUFFER_BIT;
            }
            if ("depth" in options) {
              gl2.clearDepth(+options.depth);
              clearFlags |= GL_DEPTH_BUFFER_BIT;
            }
            if ("stencil" in options) {
              gl2.clearStencil(options.stencil | 0);
              clearFlags |= GL_STENCIL_BUFFER_BIT;
            }
            gl2.clear(clearFlags);
          }
          function clear(options) {
            if ("framebuffer" in options) {
              if (options.framebuffer && options.framebuffer_reglType === "framebufferCube") {
                for (var i = 0; i < 6; ++i) {
                  setFBO(extend2({
                    framebuffer: options.framebuffer.faces[i]
                  }, options), clearImpl);
                }
              } else {
                setFBO(options, clearImpl);
              }
            } else {
              clearImpl(null, options);
            }
          }
          function frame(cb) {
            rafCallbacks.push(cb);
            function cancel() {
              var i = find(rafCallbacks, cb);
              function pendingCancel() {
                var index = find(rafCallbacks, pendingCancel);
                rafCallbacks[index] = rafCallbacks[rafCallbacks.length - 1];
                rafCallbacks.length -= 1;
                if (rafCallbacks.length <= 0) {
                  stopRAF();
                }
              }
              rafCallbacks[i] = pendingCancel;
            }
            startRAF();
            return {
              cancel
            };
          }
          function pollViewport() {
            var viewport = nextState.viewport;
            var scissorBox = nextState.scissor_box;
            viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0;
            contextState.viewportWidth = contextState.framebufferWidth = contextState.drawingBufferWidth = viewport[2] = scissorBox[2] = gl2.drawingBufferWidth;
            contextState.viewportHeight = contextState.framebufferHeight = contextState.drawingBufferHeight = viewport[3] = scissorBox[3] = gl2.drawingBufferHeight;
          }
          function poll() {
            contextState.tick += 1;
            contextState.time = now();
            pollViewport();
            core.procs.poll();
          }
          function refresh() {
            textureState.refresh();
            pollViewport();
            core.procs.refresh();
            if (timer) {
              timer.update();
            }
          }
          function now() {
            return (clock() - START_TIME) / 1e3;
          }
          refresh();
          function addListener(event, callback) {
            var callbacks;
            switch (event) {
              case "frame":
                return frame(callback);
              case "lost":
                callbacks = lossCallbacks;
                break;
              case "restore":
                callbacks = restoreCallbacks;
                break;
              case "destroy":
                callbacks = destroyCallbacks;
                break;
              default:
            }
            callbacks.push(callback);
            return {
              cancel: function() {
                for (var i = 0; i < callbacks.length; ++i) {
                  if (callbacks[i] === callback) {
                    callbacks[i] = callbacks[callbacks.length - 1];
                    callbacks.pop();
                    return;
                  }
                }
              }
            };
          }
          function getCachedCode() {
            return cachedCode;
          }
          function preloadCachedCode(moreCache) {
            Object.entries(moreCache).forEach(function(kv) {
              cachedCode[kv[0]] = kv[1];
            });
          }
          var regl = extend2(compileProcedure, {
            // Clear current FBO
            clear,
            // Short cuts for dynamic variables
            prop: dynamic.define.bind(null, DYN_PROP),
            context: dynamic.define.bind(null, DYN_CONTEXT),
            this: dynamic.define.bind(null, DYN_STATE),
            // executes an empty draw command
            draw: compileProcedure({}),
            // Resources
            buffer: function(options) {
              return bufferState.create(options, GL_ARRAY_BUFFER, false, false);
            },
            elements: function(options) {
              return elementState.create(options, false);
            },
            texture: textureState.create2D,
            cube: textureState.createCube,
            renderbuffer: renderbufferState.create,
            framebuffer: framebufferState.create,
            framebufferCube: framebufferState.createCube,
            vao: attributeState.createVAO,
            // Expose context attributes
            attributes: glAttributes,
            // Frame rendering
            frame,
            on: addListener,
            // System limits
            limits,
            hasExtension: function(name2) {
              return limits.extensions.indexOf(name2.toLowerCase()) >= 0;
            },
            // Read pixels
            read: readPixels,
            // Destroy regl and all associated resources
            destroy,
            // Direct GL state manipulation
            _gl: gl2,
            _refresh: refresh,
            poll: function() {
              poll();
              if (timer) {
                timer.update();
              }
            },
            // Current time
            now,
            // regl Statistics Information
            stats: stats$$1,
            // cache generated code
            getCachedCode,
            preloadCachedCode
          });
          config.onDone(null, regl);
          return regl;
        }
        return wrapREGL;
      });
    }
  });

  // node_modules/gl-util/context.js
  var require_context = __commonJS({
    "node_modules/gl-util/context.js"(exports, module) {
      "use strict";
      var pick = require_pick_by_alias();
      module.exports = function setContext(o) {
        if (!o) o = {};
        else if (typeof o === "string") o = { container: o };
        if (isCanvas(o)) {
          o = { container: o };
        } else if (isElement(o)) {
          o = { container: o };
        } else if (isContext(o)) {
          o = { gl: o };
        } else {
          o = pick(o, {
            container: "container target element el canvas holder parent parentNode wrapper use ref root node",
            gl: "gl context webgl glContext",
            attrs: "attributes attrs contextAttributes",
            pixelRatio: "pixelRatio pxRatio px ratio pxratio pixelratio",
            width: "w width",
            height: "h height"
          }, true);
        }
        if (!o.pixelRatio) o.pixelRatio = window.pixelRatio || 1;
        if (o.gl) {
          return o.gl;
        }
        if (o.canvas) {
          o.container = o.canvas.parentNode;
        }
        if (o.container) {
          if (typeof o.container === "string") {
            var c = document.querySelector(o.container);
            if (!c) throw Error("Element " + o.container + " is not found");
            o.container = c;
          }
          if (isCanvas(o.container)) {
            o.canvas = o.container;
            o.container = o.canvas.parentNode;
          } else if (!o.canvas) {
            o.canvas = createCanvas();
            o.container.appendChild(o.canvas);
            resize(o);
          }
        } else if (!o.canvas) {
          if (typeof document !== "undefined") {
            o.container = document.body || document.documentElement;
            o.canvas = createCanvas();
            o.container.appendChild(o.canvas);
            resize(o);
          } else {
            throw Error("Not DOM environment. Use headless-gl.");
          }
        }
        if (!o.gl) {
          ["webgl", "experimental-webgl", "webgl-experimental"].some(function(c2) {
            try {
              o.gl = o.canvas.getContext(c2, o.attrs);
            } catch (e) {
            }
            return o.gl;
          });
        }
        return o.gl;
      };
      function resize(o) {
        if (o.container) {
          if (o.container == document.body) {
            if (!document.body.style.width) o.canvas.width = o.width || o.pixelRatio * window.innerWidth;
            if (!document.body.style.height) o.canvas.height = o.height || o.pixelRatio * window.innerHeight;
          } else {
            var bounds = o.container.getBoundingClientRect();
            o.canvas.width = o.width || bounds.right - bounds.left;
            o.canvas.height = o.height || bounds.bottom - bounds.top;
          }
        }
      }
      function isCanvas(e) {
        return typeof e.getContext === "function" && "width" in e && "height" in e;
      }
      function isElement(e) {
        return typeof e.nodeName === "string" && typeof e.appendChild === "function" && typeof e.getBoundingClientRect === "function";
      }
      function isContext(e) {
        return typeof e.drawArrays === "function" || typeof e.drawElements === "function";
      }
      function createCanvas() {
        var canvas = document.createElement("canvas");
        canvas.style.position = "absolute";
        canvas.style.top = 0;
        canvas.style.left = 0;
        return canvas;
      }
    }
  });

  // node_modules/font-atlas/index.js
  var require_font_atlas = __commonJS({
    "node_modules/font-atlas/index.js"(exports, module) {
      "use strict";
      var stringifyFont = require_stringify();
      var defaultChars = [32, 126];
      module.exports = atlas;
      function atlas(options) {
        options = options || {};
        var shape = options.shape ? options.shape : options.canvas ? [options.canvas.width, options.canvas.height] : [512, 512];
        var canvas = options.canvas || document.createElement("canvas");
        var font = options.font;
        var step = typeof options.step === "number" ? [options.step, options.step] : options.step || [32, 32];
        var chars = options.chars || defaultChars;
        if (font && typeof font !== "string") font = stringifyFont(font);
        if (!Array.isArray(chars)) {
          chars = String(chars).split("");
        } else if (chars.length === 2 && typeof chars[0] === "number" && typeof chars[1] === "number") {
          var newchars = [];
          for (var i = chars[0], j = 0; i <= chars[1]; i++) {
            newchars[j++] = String.fromCharCode(i);
          }
          chars = newchars;
        }
        shape = shape.slice();
        canvas.width = shape[0];
        canvas.height = shape[1];
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "#000";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.font = font;
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.fillStyle = "#fff";
        var x = step[0] / 2;
        var y = step[1] / 2;
        for (var i = 0; i < chars.length; i++) {
          ctx.fillText(chars[i], x, y);
          if ((x += step[0]) > shape[0] - step[0] / 2) x = step[0] / 2, y += step[1];
        }
        return canvas;
      }
    }
  });

  // node_modules/bit-twiddle/twiddle.js
  var require_twiddle = __commonJS({
    "node_modules/bit-twiddle/twiddle.js"(exports) {
      "use strict";
      "use restrict";
      var INT_BITS = 32;
      exports.INT_BITS = INT_BITS;
      exports.INT_MAX = 2147483647;
      exports.INT_MIN = -1 << INT_BITS - 1;
      exports.sign = function(v) {
        return (v > 0) - (v < 0);
      };
      exports.abs = function(v) {
        var mask = v >> INT_BITS - 1;
        return (v ^ mask) - mask;
      };
      exports.min = function(x, y) {
        return y ^ (x ^ y) & -(x < y);
      };
      exports.max = function(x, y) {
        return x ^ (x ^ y) & -(x < y);
      };
      exports.isPow2 = function(v) {
        return !(v & v - 1) && !!v;
      };
      exports.log2 = function(v) {
        var r, shift;
        r = (v > 65535) << 4;
        v >>>= r;
        shift = (v > 255) << 3;
        v >>>= shift;
        r |= shift;
        shift = (v > 15) << 2;
        v >>>= shift;
        r |= shift;
        shift = (v > 3) << 1;
        v >>>= shift;
        r |= shift;
        return r | v >> 1;
      };
      exports.log10 = function(v) {
        return v >= 1e9 ? 9 : v >= 1e8 ? 8 : v >= 1e7 ? 7 : v >= 1e6 ? 6 : v >= 1e5 ? 5 : v >= 1e4 ? 4 : v >= 1e3 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0;
      };
      exports.popCount = function(v) {
        v = v - (v >>> 1 & 1431655765);
        v = (v & 858993459) + (v >>> 2 & 858993459);
        return (v + (v >>> 4) & 252645135) * 16843009 >>> 24;
      };
      function countTrailingZeros(v) {
        var c = 32;
        v &= -v;
        if (v) c--;
        if (v & 65535) c -= 16;
        if (v & 16711935) c -= 8;
        if (v & 252645135) c -= 4;
        if (v & 858993459) c -= 2;
        if (v & 1431655765) c -= 1;
        return c;
      }
      exports.countTrailingZeros = countTrailingZeros;
      exports.nextPow2 = function(v) {
        v += v === 0;
        --v;
        v |= v >>> 1;
        v |= v >>> 2;
        v |= v >>> 4;
        v |= v >>> 8;
        v |= v >>> 16;
        return v + 1;
      };
      exports.prevPow2 = function(v) {
        v |= v >>> 1;
        v |= v >>> 2;
        v |= v >>> 4;
        v |= v >>> 8;
        v |= v >>> 16;
        return v - (v >>> 1);
      };
      exports.parity = function(v) {
        v ^= v >>> 16;
        v ^= v >>> 8;
        v ^= v >>> 4;
        v &= 15;
        return 27030 >>> v & 1;
      };
      var REVERSE_TABLE = new Array(256);
      (function(tab) {
        for (var i = 0; i < 256; ++i) {
          var v = i, r = i, s = 7;
          for (v >>>= 1; v; v >>>= 1) {
            r <<= 1;
            r |= v & 1;
            --s;
          }
          tab[i] = r << s & 255;
        }
      })(REVERSE_TABLE);
      exports.reverse = function(v) {
        return REVERSE_TABLE[v & 255] << 24 | REVERSE_TABLE[v >>> 8 & 255] << 16 | REVERSE_TABLE[v >>> 16 & 255] << 8 | REVERSE_TABLE[v >>> 24 & 255];
      };
      exports.interleave2 = function(x, y) {
        x &= 65535;
        x = (x | x << 8) & 16711935;
        x = (x | x << 4) & 252645135;
        x = (x | x << 2) & 858993459;
        x = (x | x << 1) & 1431655765;
        y &= 65535;
        y = (y | y << 8) & 16711935;
        y = (y | y << 4) & 252645135;
        y = (y | y << 2) & 858993459;
        y = (y | y << 1) & 1431655765;
        return x | y << 1;
      };
      exports.deinterleave2 = function(v, n) {
        v = v >>> n & 1431655765;
        v = (v | v >>> 1) & 858993459;
        v = (v | v >>> 2) & 252645135;
        v = (v | v >>> 4) & 16711935;
        v = (v | v >>> 16) & 65535;
        return v << 16 >> 16;
      };
      exports.interleave3 = function(x, y, z) {
        x &= 1023;
        x = (x | x << 16) & 4278190335;
        x = (x | x << 8) & 251719695;
        x = (x | x << 4) & 3272356035;
        x = (x | x << 2) & 1227133513;
        y &= 1023;
        y = (y | y << 16) & 4278190335;
        y = (y | y << 8) & 251719695;
        y = (y | y << 4) & 3272356035;
        y = (y | y << 2) & 1227133513;
        x |= y << 1;
        z &= 1023;
        z = (z | z << 16) & 4278190335;
        z = (z | z << 8) & 251719695;
        z = (z | z << 4) & 3272356035;
        z = (z | z << 2) & 1227133513;
        return x | z << 2;
      };
      exports.deinterleave3 = function(v, n) {
        v = v >>> n & 1227133513;
        v = (v | v >>> 2) & 3272356035;
        v = (v | v >>> 4) & 251719695;
        v = (v | v >>> 8) & 4278190335;
        v = (v | v >>> 16) & 1023;
        return v << 22 >> 22;
      };
      exports.nextCombination = function(v) {
        var t = v | v - 1;
        return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1;
      };
    }
  });

  // node_modules/dup/dup.js
  var require_dup = __commonJS({
    "node_modules/dup/dup.js"(exports, module) {
      "use strict";
      function dupe_array(count, value, i) {
        var c = count[i] | 0;
        if (c <= 0) {
          return [];
        }
        var result = new Array(c), j;
        if (i === count.length - 1) {
          for (j = 0; j < c; ++j) {
            result[j] = value;
          }
        } else {
          for (j = 0; j < c; ++j) {
            result[j] = dupe_array(count, value, i + 1);
          }
        }
        return result;
      }
      function dupe_number(count, value) {
        var result, i;
        result = new Array(count);
        for (i = 0; i < count; ++i) {
          result[i] = value;
        }
        return result;
      }
      function dupe(count, value) {
        if (typeof value === "undefined") {
          value = 0;
        }
        switch (typeof count) {
          case "number":
            if (count > 0) {
              return dupe_number(count | 0, value);
            }
            break;
          case "object":
            if (typeof count.length === "number") {
              return dupe_array(count, value, 0);
            }
            break;
        }
        return [];
      }
      module.exports = dupe;
    }
  });

  // node_modules/typedarray-pool/pool.js
  var require_pool = __commonJS({
    "node_modules/typedarray-pool/pool.js"(exports) {
      "use strict";
      var bits = require_twiddle();
      var dup = require_dup();
      var Buffer2 = require_buffer().Buffer;
      if (!window.__TYPEDARRAY_POOL) {
        window.__TYPEDARRAY_POOL = {
          UINT8: dup([32, 0]),
          UINT16: dup([32, 0]),
          UINT32: dup([32, 0]),
          BIGUINT64: dup([32, 0]),
          INT8: dup([32, 0]),
          INT16: dup([32, 0]),
          INT32: dup([32, 0]),
          BIGINT64: dup([32, 0]),
          FLOAT: dup([32, 0]),
          DOUBLE: dup([32, 0]),
          DATA: dup([32, 0]),
          UINT8C: dup([32, 0]),
          BUFFER: dup([32, 0])
        };
      }
      var hasUint8C = typeof Uint8ClampedArray !== "undefined";
      var hasBigUint64 = typeof BigUint64Array !== "undefined";
      var hasBigInt64 = typeof BigInt64Array !== "undefined";
      var POOL = window.__TYPEDARRAY_POOL;
      if (!POOL.UINT8C) {
        POOL.UINT8C = dup([32, 0]);
      }
      if (!POOL.BIGUINT64) {
        POOL.BIGUINT64 = dup([32, 0]);
      }
      if (!POOL.BIGINT64) {
        POOL.BIGINT64 = dup([32, 0]);
      }
      if (!POOL.BUFFER) {
        POOL.BUFFER = dup([32, 0]);
      }
      var DATA = POOL.DATA;
      var BUFFER = POOL.BUFFER;
      exports.free = function free(array) {
        if (Buffer2.isBuffer(array)) {
          BUFFER[bits.log2(array.length)].push(array);
        } else {
          if (Object.prototype.toString.call(array) !== "[object ArrayBuffer]") {
            array = array.buffer;
          }
          if (!array) {
            return;
          }
          var n = array.length || array.byteLength;
          var log_n = bits.log2(n) | 0;
          DATA[log_n].push(array);
        }
      };
      function freeArrayBuffer(buffer) {
        if (!buffer) {
          return;
        }
        var n = buffer.length || buffer.byteLength;
        var log_n = bits.log2(n);
        DATA[log_n].push(buffer);
      }
      function freeTypedArray(array) {
        freeArrayBuffer(array.buffer);
      }
      exports.freeUint8 = exports.freeUint16 = exports.freeUint32 = exports.freeBigUint64 = exports.freeInt8 = exports.freeInt16 = exports.freeInt32 = exports.freeBigInt64 = exports.freeFloat32 = exports.freeFloat = exports.freeFloat64 = exports.freeDouble = exports.freeUint8Clamped = exports.freeDataView = freeTypedArray;
      exports.freeArrayBuffer = freeArrayBuffer;
      exports.freeBuffer = function freeBuffer(array) {
        BUFFER[bits.log2(array.length)].push(array);
      };
      exports.malloc = function malloc(n, dtype) {
        if (dtype === void 0 || dtype === "arraybuffer") {
          return mallocArrayBuffer(n);
        } else {
          switch (dtype) {
            case "uint8":
              return mallocUint8(n);
            case "uint16":
              return mallocUint16(n);
            case "uint32":
              return mallocUint32(n);
            case "int8":
              return mallocInt8(n);
            case "int16":
              return mallocInt16(n);
            case "int32":
              return mallocInt32(n);
            case "float":
            case "float32":
              return mallocFloat(n);
            case "double":
            case "float64":
              return mallocDouble(n);
            case "uint8_clamped":
              return mallocUint8Clamped(n);
            case "bigint64":
              return mallocBigInt64(n);
            case "biguint64":
              return mallocBigUint64(n);
            case "buffer":
              return mallocBuffer(n);
            case "data":
            case "dataview":
              return mallocDataView(n);
            default:
              return null;
          }
        }
        return null;
      };
      function mallocArrayBuffer(n) {
        var n = bits.nextPow2(n);
        var log_n = bits.log2(n);
        var d = DATA[log_n];
        if (d.length > 0) {
          return d.pop();
        }
        return new ArrayBuffer(n);
      }
      exports.mallocArrayBuffer = mallocArrayBuffer;
      function mallocUint8(n) {
        return new Uint8Array(mallocArrayBuffer(n), 0, n);
      }
      exports.mallocUint8 = mallocUint8;
      function mallocUint16(n) {
        return new Uint16Array(mallocArrayBuffer(2 * n), 0, n);
      }
      exports.mallocUint16 = mallocUint16;
      function mallocUint32(n) {
        return new Uint32Array(mallocArrayBuffer(4 * n), 0, n);
      }
      exports.mallocUint32 = mallocUint32;
      function mallocInt8(n) {
        return new Int8Array(mallocArrayBuffer(n), 0, n);
      }
      exports.mallocInt8 = mallocInt8;
      function mallocInt16(n) {
        return new Int16Array(mallocArrayBuffer(2 * n), 0, n);
      }
      exports.mallocInt16 = mallocInt16;
      function mallocInt32(n) {
        return new Int32Array(mallocArrayBuffer(4 * n), 0, n);
      }
      exports.mallocInt32 = mallocInt32;
      function mallocFloat(n) {
        return new Float32Array(mallocArrayBuffer(4 * n), 0, n);
      }
      exports.mallocFloat32 = exports.mallocFloat = mallocFloat;
      function mallocDouble(n) {
        return new Float64Array(mallocArrayBuffer(8 * n), 0, n);
      }
      exports.mallocFloat64 = exports.mallocDouble = mallocDouble;
      function mallocUint8Clamped(n) {
        if (hasUint8C) {
          return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n);
        } else {
          return mallocUint8(n);
        }
      }
      exports.mallocUint8Clamped = mallocUint8Clamped;
      function mallocBigUint64(n) {
        if (hasBigUint64) {
          return new BigUint64Array(mallocArrayBuffer(8 * n), 0, n);
        } else {
          return null;
        }
      }
      exports.mallocBigUint64 = mallocBigUint64;
      function mallocBigInt64(n) {
        if (hasBigInt64) {
          return new BigInt64Array(mallocArrayBuffer(8 * n), 0, n);
        } else {
          return null;
        }
      }
      exports.mallocBigInt64 = mallocBigInt64;
      function mallocDataView(n) {
        return new DataView(mallocArrayBuffer(n), 0, n);
      }
      exports.mallocDataView = mallocDataView;
      function mallocBuffer(n) {
        n = bits.nextPow2(n);
        var log_n = bits.log2(n);
        var cache = BUFFER[log_n];
        if (cache.length > 0) {
          return cache.pop();
        }
        return new Buffer2(n);
      }
      exports.mallocBuffer = mallocBuffer;
      exports.clearCache = function clearCache() {
        for (var i = 0; i < 32; ++i) {
          POOL.UINT8[i].length = 0;
          POOL.UINT16[i].length = 0;
          POOL.UINT32[i].length = 0;
          POOL.INT8[i].length = 0;
          POOL.INT16[i].length = 0;
          POOL.INT32[i].length = 0;
          POOL.FLOAT[i].length = 0;
          POOL.DOUBLE[i].length = 0;
          POOL.BIGUINT64[i].length = 0;
          POOL.BIGINT64[i].length = 0;
          POOL.UINT8C[i].length = 0;
          DATA[i].length = 0;
          BUFFER[i].length = 0;
        }
      };
    }
  });

  // node_modules/is-plain-obj/index.js
  var require_is_plain_obj = __commonJS({
    "node_modules/is-plain-obj/index.js"(exports, module) {
      "use strict";
      var toString = Object.prototype.toString;
      module.exports = function(x) {
        var prototype;
        return toString.call(x) === "[object Object]" && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({}));
      };
    }
  });

  // node_modules/parse-unit/index.js
  var require_parse_unit = __commonJS({
    "node_modules/parse-unit/index.js"(exports, module) {
      module.exports = function parseUnit(str, out) {
        if (!out)
          out = [0, ""];
        str = String(str);
        var num = parseFloat(str, 10);
        out[0] = num;
        out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || "";
        return out;
      };
    }
  });

  // node_modules/to-px/topx.js
  var require_topx = __commonJS({
    "node_modules/to-px/topx.js"(exports, module) {
      "use strict";
      var parseUnit = require_parse_unit();
      module.exports = toPX;
      var PIXELS_PER_INCH = 96;
      function getPropertyInPX(element, prop) {
        var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop));
        return parts[0] * toPX(parts[1], element);
      }
      function getSizeBrutal(unit, element) {
        var testDIV = document.createElement("div");
        testDIV.style["font-size"] = "128" + unit;
        element.appendChild(testDIV);
        var size = getPropertyInPX(testDIV, "font-size") / 128;
        element.removeChild(testDIV);
        return size;
      }
      function toPX(str, element) {
        element = element || document.body;
        str = (str || "px").trim().toLowerCase();
        if (element === window || element === document) {
          element = document.body;
        }
        switch (str) {
          case "%":
            return element.clientHeight / 100;
          case "ch":
          case "ex":
            return getSizeBrutal(str, element);
          case "em":
            return getPropertyInPX(element, "font-size");
          case "rem":
            return getPropertyInPX(document.body, "font-size");
          case "vw":
            return window.innerWidth / 100;
          case "vh":
            return window.innerHeight / 100;
          case "vmin":
            return Math.min(window.innerWidth, window.innerHeight) / 100;
          case "vmax":
            return Math.max(window.innerWidth, window.innerHeight) / 100;
          case "in":
            return PIXELS_PER_INCH;
          case "cm":
            return PIXELS_PER_INCH / 2.54;
          case "mm":
            return PIXELS_PER_INCH / 25.4;
          case "pt":
            return PIXELS_PER_INCH / 72;
          case "pc":
            return PIXELS_PER_INCH / 6;
        }
        return 1;
      }
    }
  });

  // node_modules/detect-kerning/index.js
  var require_detect_kerning = __commonJS({
    "node_modules/detect-kerning/index.js"(exports, module) {
      "use strict";
      module.exports = kerning;
      var canvas = kerning.canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var asciiPairs = createPairs([32, 126]);
      kerning.createPairs = createPairs;
      kerning.ascii = asciiPairs;
      function kerning(family, o) {
        if (Array.isArray(family)) family = family.join(", ");
        var table = {}, pairs, fs = 16, threshold = 0.05;
        if (o) {
          if (o.length === 2 && typeof o[0] === "number") {
            pairs = createPairs(o);
          } else if (Array.isArray(o)) {
            pairs = o;
          } else {
            if (o.o) pairs = createPairs(o.o);
            else if (o.pairs) pairs = o.pairs;
            if (o.fontSize) fs = o.fontSize;
            if (o.threshold != null) threshold = o.threshold;
          }
        }
        if (!pairs) pairs = asciiPairs;
        ctx.font = fs + "px " + family;
        for (var i = 0; i < pairs.length; i++) {
          var pair = pairs[i];
          var width = ctx.measureText(pair[0]).width + ctx.measureText(pair[1]).width;
          var kerningWidth = ctx.measureText(pair).width;
          if (Math.abs(width - kerningWidth) > fs * threshold) {
            var emWidth = (kerningWidth - width) / fs;
            table[pair] = emWidth * 1e3;
          }
        }
        return table;
      }
      function createPairs(range) {
        var pairs = [];
        for (var i = range[0]; i <= range[1]; i++) {
          var leftChar = String.fromCharCode(i);
          for (var j = range[0]; j < range[1]; j++) {
            var rightChar = String.fromCharCode(j);
            var pair = leftChar + rightChar;
            pairs.push(pair);
          }
        }
        return pairs;
      }
    }
  });

  // node_modules/font-measure/index.js
  var require_font_measure = __commonJS({
    "node_modules/font-measure/index.js"(exports, module) {
      "use strict";
      module.exports = measure;
      measure.canvas = document.createElement("canvas");
      measure.cache = {};
      function measure(font, o) {
        if (!o) o = {};
        if (typeof font === "string" || Array.isArray(font)) {
          o.family = font;
        }
        var family = Array.isArray(o.family) ? o.family.join(", ") : o.family;
        if (!family) throw Error("`family` must be defined");
        var fs = o.size || o.fontSize || o.em || 48;
        var weight = o.weight || o.fontWeight || "";
        var style = o.style || o.fontStyle || "";
        var font = [style, weight, fs].join(" ") + "px " + family;
        var origin = o.origin || "top";
        if (measure.cache[family]) {
          if (fs <= measure.cache[family].em) {
            return applyOrigin(measure.cache[family], origin);
          }
        }
        var canvas = o.canvas || measure.canvas;
        var ctx = canvas.getContext("2d");
        var chars = {
          upper: o.upper !== void 0 ? o.upper : "H",
          lower: o.lower !== void 0 ? o.lower : "x",
          descent: o.descent !== void 0 ? o.descent : "p",
          ascent: o.ascent !== void 0 ? o.ascent : "h",
          tittle: o.tittle !== void 0 ? o.tittle : "i",
          overshoot: o.overshoot !== void 0 ? o.overshoot : "O"
        };
        var l = Math.ceil(fs * 1.5);
        canvas.height = l;
        canvas.width = l * 0.5;
        ctx.font = font;
        var char = "H";
        var result = {
          top: 0
        };
        ctx.clearRect(0, 0, l, l);
        ctx.textBaseline = "top";
        ctx.fillStyle = "black";
        ctx.fillText(char, 0, 0);
        var topPx = firstTop(ctx.getImageData(0, 0, l, l));
        ctx.clearRect(0, 0, l, l);
        ctx.textBaseline = "bottom";
        ctx.fillText(char, 0, l);
        var bottomPx = firstTop(ctx.getImageData(0, 0, l, l));
        result.lineHeight = result.bottom = l - bottomPx + topPx;
        ctx.clearRect(0, 0, l, l);
        ctx.textBaseline = "alphabetic";
        ctx.fillText(char, 0, l);
        var baselinePx = firstTop(ctx.getImageData(0, 0, l, l));
        var baseline = l - baselinePx - 1 + topPx;
        result.baseline = result.alphabetic = baseline;
        ctx.clearRect(0, 0, l, l);
        ctx.textBaseline = "middle";
        ctx.fillText(char, 0, l * 0.5);
        var medianPx = firstTop(ctx.getImageData(0, 0, l, l));
        result.median = result.middle = l - medianPx - 1 + topPx - l * 0.5;
        ctx.clearRect(0, 0, l, l);
        ctx.textBaseline = "hanging";
        ctx.fillText(char, 0, l * 0.5);
        var hangingPx = firstTop(ctx.getImageData(0, 0, l, l));
        result.hanging = l - hangingPx - 1 + topPx - l * 0.5;
        ctx.clearRect(0, 0, l, l);
        ctx.textBaseline = "ideographic";
        ctx.fillText(char, 0, l);
        var ideographicPx = firstTop(ctx.getImageData(0, 0, l, l));
        result.ideographic = l - ideographicPx - 1 + topPx;
        if (chars.upper) {
          ctx.clearRect(0, 0, l, l);
          ctx.textBaseline = "top";
          ctx.fillText(chars.upper, 0, 0);
          result.upper = firstTop(ctx.getImageData(0, 0, l, l));
          result.capHeight = result.baseline - result.upper;
        }
        if (chars.lower) {
          ctx.clearRect(0, 0, l, l);
          ctx.textBaseline = "top";
          ctx.fillText(chars.lower, 0, 0);
          result.lower = firstTop(ctx.getImageData(0, 0, l, l));
          result.xHeight = result.baseline - result.lower;
        }
        if (chars.tittle) {
          ctx.clearRect(0, 0, l, l);
          ctx.textBaseline = "top";
          ctx.fillText(chars.tittle, 0, 0);
          result.tittle = firstTop(ctx.getImageData(0, 0, l, l));
        }
        if (chars.ascent) {
          ctx.clearRect(0, 0, l, l);
          ctx.textBaseline = "top";
          ctx.fillText(chars.ascent, 0, 0);
          result.ascent = firstTop(ctx.getImageData(0, 0, l, l));
        }
        if (chars.descent) {
          ctx.clearRect(0, 0, l, l);
          ctx.textBaseline = "top";
          ctx.fillText(chars.descent, 0, 0);
          result.descent = firstBottom(ctx.getImageData(0, 0, l, l));
        }
        if (chars.overshoot) {
          ctx.clearRect(0, 0, l, l);
          ctx.textBaseline = "top";
          ctx.fillText(chars.overshoot, 0, 0);
          var overshootPx = firstBottom(ctx.getImageData(0, 0, l, l));
          result.overshoot = overshootPx - baseline;
        }
        for (var name2 in result) {
          result[name2] /= fs;
        }
        result.em = fs;
        measure.cache[family] = result;
        return applyOrigin(result, origin);
      }
      function applyOrigin(obj, origin) {
        var res = {};
        if (typeof origin === "string") origin = obj[origin];
        for (var name2 in obj) {
          if (name2 === "em") continue;
          res[name2] = obj[name2] - origin;
        }
        return res;
      }
      function firstTop(iData) {
        var l = iData.height;
        var data = iData.data;
        for (var i = 3; i < data.length; i += 4) {
          if (data[i] !== 0) {
            return Math.floor((i - 3) * 0.25 / l);
          }
        }
      }
      function firstBottom(iData) {
        var l = iData.height;
        var data = iData.data;
        for (var i = data.length - 1; i > 0; i -= 4) {
          if (data[i] !== 0) {
            return Math.floor((i - 3) * 0.25 / l);
          }
        }
      }
    }
  });

  // node_modules/gl-text/dist.js
  var require_dist = __commonJS({
    "node_modules/gl-text/dist.js"(exports, module) {
      "use strict";
      var Font = require_css_font();
      var pick = require_pick_by_alias();
      var createRegl = require_regl_unchecked();
      var createGl = require_context();
      var WeakMap2 = require_es6_weak_map();
      var rgba3 = require_color_normalize();
      var fontAtlas = require_font_atlas();
      var pool = require_pool();
      var parseRect = require_parse_rect();
      var isObj = require_is_plain_obj();
      var parseUnit = require_parse_unit();
      var px = require_topx();
      var kerning = require_detect_kerning();
      var extend2 = require_object_assign();
      var metrics = require_font_measure();
      var flatten = require_flatten_vertex_data();
      var ref = require_twiddle();
      var nextPow2 = ref.nextPow2;
      var shaderCache = new WeakMap2();
      var isStretchSupported = false;
      if (document.body) {
        el = document.body.appendChild(document.createElement("div"));
        el.style.font = "italic small-caps bold condensed 16px/2 cursive";
        if (getComputedStyle(el).fontStretch) {
          isStretchSupported = true;
        }
        document.body.removeChild(el);
      }
      var el;
      var GlText = function GlText2(o) {
        if (isRegl(o)) {
          o = { regl: o };
          this.gl = o.regl._gl;
        } else {
          this.gl = createGl(o);
        }
        this.shader = shaderCache.get(this.gl);
        if (!this.shader) {
          this.regl = o.regl || createRegl({ gl: this.gl });
        } else {
          this.regl = this.shader.regl;
        }
        this.charBuffer = this.regl.buffer({ type: "uint8", usage: "stream" });
        this.sizeBuffer = this.regl.buffer({ type: "float", usage: "stream" });
        if (!this.shader) {
          this.shader = this.createShader();
          shaderCache.set(this.gl, this.shader);
        }
        this.batch = [];
        this.fontSize = [];
        this.font = [];
        this.fontAtlas = [];
        this.draw = this.shader.draw.bind(this);
        this.render = function() {
          this.regl._refresh();
          this.draw(this.batch);
        };
        this.canvas = this.gl.canvas;
        this.update(isObj(o) ? o : {});
      };
      GlText.prototype.createShader = function createShader() {
        var regl = this.regl;
        var draw = regl({
          blend: {
            enable: true,
            color: [0, 0, 0, 1],
            func: {
              srcRGB: "src alpha",
              dstRGB: "one minus src alpha",
              srcAlpha: "one minus dst alpha",
              dstAlpha: "one"
            }
          },
          stencil: { enable: false },
          depth: { enable: false },
          count: regl.prop("count"),
          offset: regl.prop("offset"),
          attributes: {
            charOffset: {
              offset: 4,
              stride: 8,
              buffer: regl.this("sizeBuffer")
            },
            width: {
              offset: 0,
              stride: 8,
              buffer: regl.this("sizeBuffer")
            },
            char: regl.this("charBuffer"),
            position: regl.this("position")
          },
          uniforms: {
            atlasSize: function(c, p) {
              return [p.atlas.width, p.atlas.height];
            },
            atlasDim: function(c, p) {
              return [p.atlas.cols, p.atlas.rows];
            },
            atlas: function(c, p) {
              return p.atlas.texture;
            },
            charStep: function(c, p) {
              return p.atlas.step;
            },
            em: function(c, p) {
              return p.atlas.em;
            },
            color: regl.prop("color"),
            opacity: regl.prop("opacity"),
            viewport: regl.this("viewportArray"),
            scale: regl.this("scale"),
            align: regl.prop("align"),
            baseline: regl.prop("baseline"),
            translate: regl.this("translate"),
            positionOffset: regl.prop("positionOffset")
          },
          primitive: "points",
          viewport: regl.this("viewport"),
          vert: "\n			precision highp float;\n			attribute float width, charOffset, char;\n			attribute vec2 position;\n			uniform float fontSize, charStep, em, align, baseline;\n			uniform vec4 viewport;\n			uniform vec4 color;\n			uniform vec2 atlasSize, atlasDim, scale, translate, positionOffset;\n			varying vec2 charCoord, charId;\n			varying float charWidth;\n			varying vec4 fontColor;\n			void main () {\n				vec2 offset = floor(em * (vec2(align + charOffset, baseline)\n					+ vec2(positionOffset.x, -positionOffset.y)))\n					/ (viewport.zw * scale.xy);\n\n				vec2 position = (position + translate) * scale;\n				position += offset * scale;\n\n				charCoord = position * viewport.zw + viewport.xy;\n\n				gl_Position = vec4(position * 2. - 1., 0, 1);\n\n				gl_PointSize = charStep;\n\n				charId.x = mod(char, atlasDim.x);\n				charId.y = floor(char / atlasDim.x);\n\n				charWidth = width * em;\n\n				fontColor = color / 255.;\n			}",
          frag: "\n			precision highp float;\n			uniform float fontSize, charStep, opacity;\n			uniform vec2 atlasSize;\n			uniform vec4 viewport;\n			uniform sampler2D atlas;\n			varying vec4 fontColor;\n			varying vec2 charCoord, charId;\n			varying float charWidth;\n\n			float lightness(vec4 color) {\n				return color.r * 0.299 + color.g * 0.587 + color.b * 0.114;\n			}\n\n			void main () {\n				vec2 uv = gl_FragCoord.xy - charCoord + charStep * .5;\n				float halfCharStep = floor(charStep * .5 + .5);\n\n				// invert y and shift by 1px (FF expecially needs that)\n				uv.y = charStep - uv.y;\n\n				// ignore points outside of character bounding box\n				float halfCharWidth = ceil(charWidth * .5);\n				if (floor(uv.x) > halfCharStep + halfCharWidth ||\n					floor(uv.x) < halfCharStep - halfCharWidth) return;\n\n				uv += charId * charStep;\n				uv = uv / atlasSize;\n\n				vec4 color = fontColor;\n				vec4 mask = texture2D(atlas, uv);\n\n				float maskY = lightness(mask);\n				// float colorY = lightness(color);\n				color.a *= maskY;\n				color.a *= opacity;\n\n				// color.a += .1;\n\n				// antialiasing, see yiq color space y-channel formula\n				// color.rgb += (1. - color.rgb) * (1. - mask.rgb);\n\n				gl_FragColor = color;\n			}"
        });
        var atlas = {};
        return { regl, draw, atlas };
      };
      GlText.prototype.update = function update(o) {
        var this$1 = this;
        if (typeof o === "string") {
          o = { text: o };
        } else if (!o) {
          return;
        }
        o = pick(o, {
          position: "position positions coord coords coordinates",
          font: "font fontFace fontface typeface cssFont css-font family fontFamily",
          fontSize: "fontSize fontsize size font-size",
          text: "text texts chars characters value values symbols",
          align: "align alignment textAlign textbaseline",
          baseline: "baseline textBaseline textbaseline",
          direction: "dir direction textDirection",
          color: "color colour fill fill-color fillColor textColor textcolor",
          kerning: "kerning kern",
          range: "range dataBox",
          viewport: "vp viewport viewBox viewbox viewPort",
          opacity: "opacity alpha transparency visible visibility opaque",
          offset: "offset positionOffset padding shift indent indentation"
        }, true);
        if (o.opacity != null) {
          if (Array.isArray(o.opacity)) {
            this.opacity = o.opacity.map(function(o2) {
              return parseFloat(o2);
            });
          } else {
            this.opacity = parseFloat(o.opacity);
          }
        }
        if (o.viewport != null) {
          this.viewport = parseRect(o.viewport);
          this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height];
        }
        if (this.viewport == null) {
          this.viewport = {
            x: 0,
            y: 0,
            width: this.gl.drawingBufferWidth,
            height: this.gl.drawingBufferHeight
          };
          this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height];
        }
        if (o.kerning != null) {
          this.kerning = o.kerning;
        }
        if (o.offset != null) {
          if (typeof o.offset === "number") {
            o.offset = [o.offset, 0];
          }
          this.positionOffset = flatten(o.offset);
        }
        if (o.direction) {
          this.direction = o.direction;
        }
        if (o.range) {
          this.range = o.range;
          this.scale = [1 / (o.range[2] - o.range[0]), 1 / (o.range[3] - o.range[1])];
          this.translate = [-o.range[0], -o.range[1]];
        }
        if (o.scale) {
          this.scale = o.scale;
        }
        if (o.translate) {
          this.translate = o.translate;
        }
        if (!this.scale) {
          this.scale = [1 / this.viewport.width, 1 / this.viewport.height];
        }
        if (!this.translate) {
          this.translate = [0, 0];
        }
        if (!this.font.length && !o.font) {
          o.font = GlText.baseFontSize + "px sans-serif";
        }
        var newFont = false, newFontSize = false;
        if (o.font) {
          (Array.isArray(o.font) ? o.font : [o.font]).forEach(function(font2, i2) {
            if (typeof font2 === "string") {
              try {
                font2 = Font.parse(font2);
              } catch (e) {
                font2 = Font.parse(GlText.baseFontSize + "px " + font2);
              }
            } else {
              var fontStyle = font2.style;
              var fontWeight = font2.weight;
              var fontStretch = font2.stretch;
              var fontVariant = font2.variant;
              font2 = Font.parse(Font.stringify(font2));
              if (fontStyle) font2.style = fontStyle;
              if (fontWeight) font2.weight = fontWeight;
              if (fontStretch) font2.stretch = fontStretch;
              if (fontVariant) font2.variant = fontVariant;
            }
            var baseString = Font.stringify({
              size: GlText.baseFontSize,
              family: font2.family,
              stretch: isStretchSupported ? font2.stretch : void 0,
              variant: font2.variant,
              weight: font2.weight,
              style: font2.style
            });
            var unit = parseUnit(font2.size);
            var fs = Math.round(unit[0] * px(unit[1]));
            if (fs !== this$1.fontSize[i2]) {
              newFontSize = true;
              this$1.fontSize[i2] = fs;
            }
            if (!this$1.font[i2] || baseString != this$1.font[i2].baseString) {
              newFont = true;
              this$1.font[i2] = GlText.fonts[baseString];
              if (!this$1.font[i2]) {
                var family = font2.family.join(", ");
                var style = [font2.style];
                if (font2.style != font2.variant) {
                  style.push(font2.variant);
                }
                if (font2.variant != font2.weight) {
                  style.push(font2.weight);
                }
                if (isStretchSupported && font2.weight != font2.stretch) {
                  style.push(font2.stretch);
                }
                this$1.font[i2] = {
                  baseString,
                  // typeface
                  family,
                  weight: font2.weight,
                  stretch: font2.stretch,
                  style: font2.style,
                  variant: font2.variant,
                  // widths of characters
                  width: {},
                  // kernin pairs offsets
                  kerning: {},
                  metrics: metrics(family, {
                    origin: "top",
                    fontSize: GlText.baseFontSize,
                    fontStyle: style.join(" ")
                  })
                };
                GlText.fonts[baseString] = this$1.font[i2];
              }
            }
          });
        }
        if (newFont || newFontSize) {
          this.font.forEach(function(font2, i2) {
            var fontString = Font.stringify({
              size: this$1.fontSize[i2],
              family: font2.family,
              stretch: isStretchSupported ? font2.stretch : void 0,
              variant: font2.variant,
              weight: font2.weight,
              style: font2.style
            });
            this$1.fontAtlas[i2] = this$1.shader.atlas[fontString];
            if (!this$1.fontAtlas[i2]) {
              var metrics2 = font2.metrics;
              this$1.shader.atlas[fontString] = this$1.fontAtlas[i2] = {
                fontString,
                // even step is better for rendered characters
                step: Math.ceil(this$1.fontSize[i2] * metrics2.bottom * 0.5) * 2,
                em: this$1.fontSize[i2],
                cols: 0,
                rows: 0,
                height: 0,
                width: 0,
                chars: [],
                ids: {},
                texture: this$1.regl.texture()
              };
            }
            if (o.text == null) {
              o.text = this$1.text;
            }
          });
        }
        if (typeof o.text === "string" && o.position && o.position.length > 2) {
          var textArray = Array(o.position.length * 0.5);
          for (var i = 0; i < textArray.length; i++) {
            textArray[i] = o.text;
          }
          o.text = textArray;
        }
        var newAtlasChars;
        if (o.text != null || newFont) {
          this.textOffsets = [0];
          if (Array.isArray(o.text)) {
            this.count = o.text[0].length;
            this.counts = [this.count];
            for (var i$1 = 1; i$1 < o.text.length; i$1++) {
              this.textOffsets[i$1] = this.textOffsets[i$1 - 1] + o.text[i$1 - 1].length;
              this.count += o.text[i$1].length;
              this.counts.push(o.text[i$1].length);
            }
            this.text = o.text.join("");
          } else {
            this.text = o.text;
            this.count = this.text.length;
            this.counts = [this.count];
          }
          newAtlasChars = [];
          this.font.forEach(function(font2, idx) {
            GlText.atlasContext.font = font2.baseString;
            var atlas2 = this$1.fontAtlas[idx];
            for (var i2 = 0; i2 < this$1.text.length; i2++) {
              var char2 = this$1.text.charAt(i2);
              if (atlas2.ids[char2] == null) {
                atlas2.ids[char2] = atlas2.chars.length;
                atlas2.chars.push(char2);
                newAtlasChars.push(char2);
              }
              if (font2.width[char2] == null) {
                font2.width[char2] = GlText.atlasContext.measureText(char2).width / GlText.baseFontSize;
                if (this$1.kerning) {
                  var pairs = [];
                  for (var baseChar in font2.width) {
                    pairs.push(baseChar + char2, char2 + baseChar);
                  }
                  extend2(font2.kerning, kerning(font2.family, {
                    pairs
                  }));
                }
              }
            }
          });
        }
        if (o.position) {
          if (o.position.length > 2) {
            var flat = !o.position[0].length;
            var positionData = pool.mallocFloat(this.count * 2);
            for (var i$2 = 0, ptr = 0; i$2 < this.counts.length; i$2++) {
              var count = this.counts[i$2];
              if (flat) {
                for (var j = 0; j < count; j++) {
                  positionData[ptr++] = o.position[i$2 * 2];
                  positionData[ptr++] = o.position[i$2 * 2 + 1];
                }
              } else {
                for (var j$1 = 0; j$1 < count; j$1++) {
                  positionData[ptr++] = o.position[i$2][0];
                  positionData[ptr++] = o.position[i$2][1];
                }
              }
            }
            if (this.position.call) {
              this.position({
                type: "float",
                data: positionData
              });
            } else {
              this.position = this.regl.buffer({
                type: "float",
                data: positionData
              });
            }
            pool.freeFloat(positionData);
          } else {
            if (this.position.destroy) {
              this.position.destroy();
            }
            this.position = {
              constant: o.position
            };
          }
        }
        if (o.text || newFont) {
          var charIds = pool.mallocUint8(this.count);
          var sizeData = pool.mallocFloat(this.count * 2);
          this.textWidth = [];
          for (var i$3 = 0, ptr$1 = 0; i$3 < this.counts.length; i$3++) {
            var count$1 = this.counts[i$3];
            var font = this.font[i$3] || this.font[0];
            var atlas = this.fontAtlas[i$3] || this.fontAtlas[0];
            for (var j$2 = 0; j$2 < count$1; j$2++) {
              var char = this.text.charAt(ptr$1);
              var prevChar = this.text.charAt(ptr$1 - 1);
              charIds[ptr$1] = atlas.ids[char];
              sizeData[ptr$1 * 2] = font.width[char];
              if (j$2) {
                var prevWidth = sizeData[ptr$1 * 2 - 2];
                var currWidth = sizeData[ptr$1 * 2];
                var prevOffset = sizeData[ptr$1 * 2 - 1];
                var offset = prevOffset + prevWidth * 0.5 + currWidth * 0.5;
                if (this.kerning) {
                  var kerning$1 = font.kerning[prevChar + char];
                  if (kerning$1) {
                    offset += kerning$1 * 1e-3;
                  }
                }
                sizeData[ptr$1 * 2 + 1] = offset;
              } else {
                sizeData[ptr$1 * 2 + 1] = sizeData[ptr$1 * 2] * 0.5;
              }
              ptr$1++;
            }
            this.textWidth.push(
              !sizeData.length ? 0 : (
                // last offset + half last width
                sizeData[ptr$1 * 2 - 2] * 0.5 + sizeData[ptr$1 * 2 - 1]
              )
            );
          }
          if (!o.align) {
            o.align = this.align;
          }
          this.charBuffer({ data: charIds, type: "uint8", usage: "stream" });
          this.sizeBuffer({ data: sizeData, type: "float", usage: "stream" });
          pool.freeUint8(charIds);
          pool.freeFloat(sizeData);
          if (newAtlasChars.length) {
            this.font.forEach(function(font2, i2) {
              var atlas2 = this$1.fontAtlas[i2];
              var step = atlas2.step;
              var maxCols = Math.floor(GlText.maxAtlasSize / step);
              var cols = Math.min(maxCols, atlas2.chars.length);
              var rows = Math.ceil(atlas2.chars.length / cols);
              var atlasWidth = nextPow2(cols * step);
              var atlasHeight = nextPow2(rows * step);
              atlas2.width = atlasWidth;
              atlas2.height = atlasHeight;
              atlas2.rows = rows;
              atlas2.cols = cols;
              if (!atlas2.em) {
                return;
              }
              atlas2.texture({
                data: fontAtlas({
                  canvas: GlText.atlasCanvas,
                  font: atlas2.fontString,
                  chars: atlas2.chars,
                  shape: [atlasWidth, atlasHeight],
                  step: [step, step]
                })
              });
            });
          }
        }
        if (o.align) {
          this.align = o.align;
          this.alignOffset = this.textWidth.map(function(textWidth, i2) {
            var align = !Array.isArray(this$1.align) ? this$1.align : this$1.align.length > 1 ? this$1.align[i2] : this$1.align[0];
            if (typeof align === "number") {
              return align;
            }
            switch (align) {
              case "right":
              case "end":
                return -textWidth;
              case "center":
              case "centre":
              case "middle":
                return -textWidth * 0.5;
            }
            return 0;
          });
        }
        if (this.baseline == null && o.baseline == null) {
          o.baseline = 0;
        }
        if (o.baseline != null) {
          this.baseline = o.baseline;
          if (!Array.isArray(this.baseline)) {
            this.baseline = [this.baseline];
          }
          this.baselineOffset = this.baseline.map(function(baseline, i2) {
            var m = (this$1.font[i2] || this$1.font[0]).metrics;
            var base = 0;
            base += m.bottom * 0.5;
            if (typeof baseline === "number") {
              base += baseline - m.baseline;
            } else {
              base += -m[baseline];
            }
            base *= -1;
            return base;
          });
        }
        if (o.color != null) {
          if (!o.color) {
            o.color = "transparent";
          }
          if (typeof o.color === "string" || !isNaN(o.color)) {
            this.color = rgba3(o.color, "uint8");
          } else {
            var colorData;
            if (typeof o.color[0] === "number" && o.color.length > this.counts.length) {
              var l = o.color.length;
              colorData = pool.mallocUint8(l);
              var sub = (o.color.subarray || o.color.slice).bind(o.color);
              for (var i$4 = 0; i$4 < l; i$4 += 4) {
                colorData.set(rgba3(sub(i$4, i$4 + 4), "uint8"), i$4);
              }
            } else {
              var l$1 = o.color.length;
              colorData = pool.mallocUint8(l$1 * 4);
              for (var i$5 = 0; i$5 < l$1; i$5++) {
                colorData.set(rgba3(o.color[i$5] || 0, "uint8"), i$5 * 4);
              }
            }
            this.color = colorData;
          }
        }
        if (o.position || o.text || o.color || o.baseline || o.align || o.font || o.offset || o.opacity) {
          var isBatch = this.color.length > 4 || this.baselineOffset.length > 1 || this.align && this.align.length > 1 || this.fontAtlas.length > 1 || this.positionOffset.length > 2;
          if (isBatch) {
            var length = Math.max(
              this.position.length * 0.5 || 0,
              this.color.length * 0.25 || 0,
              this.baselineOffset.length || 0,
              this.alignOffset.length || 0,
              this.font.length || 0,
              this.opacity.length || 0,
              this.positionOffset.length * 0.5 || 0
            );
            this.batch = Array(length);
            for (var i$6 = 0; i$6 < this.batch.length; i$6++) {
              this.batch[i$6] = {
                count: this.counts.length > 1 ? this.counts[i$6] : this.counts[0],
                offset: this.textOffsets.length > 1 ? this.textOffsets[i$6] : this.textOffsets[0],
                color: !this.color ? [0, 0, 0, 255] : this.color.length <= 4 ? this.color : this.color.subarray(i$6 * 4, i$6 * 4 + 4),
                opacity: Array.isArray(this.opacity) ? this.opacity[i$6] : this.opacity,
                baseline: this.baselineOffset[i$6] != null ? this.baselineOffset[i$6] : this.baselineOffset[0],
                align: !this.align ? 0 : this.alignOffset[i$6] != null ? this.alignOffset[i$6] : this.alignOffset[0],
                atlas: this.fontAtlas[i$6] || this.fontAtlas[0],
                positionOffset: this.positionOffset.length > 2 ? this.positionOffset.subarray(i$6 * 2, i$6 * 2 + 2) : this.positionOffset
              };
            }
          } else {
            if (this.count) {
              this.batch = [{
                count: this.count,
                offset: 0,
                color: this.color || [0, 0, 0, 255],
                opacity: Array.isArray(this.opacity) ? this.opacity[0] : this.opacity,
                baseline: this.baselineOffset[0],
                align: this.alignOffset ? this.alignOffset[0] : 0,
                atlas: this.fontAtlas[0],
                positionOffset: this.positionOffset
              }];
            } else {
              this.batch = [];
            }
          }
        }
      };
      GlText.prototype.destroy = function destroy() {
      };
      GlText.prototype.kerning = true;
      GlText.prototype.position = { constant: new Float32Array(2) };
      GlText.prototype.translate = null;
      GlText.prototype.scale = null;
      GlText.prototype.font = null;
      GlText.prototype.text = "";
      GlText.prototype.positionOffset = [0, 0];
      GlText.prototype.opacity = 1;
      GlText.prototype.color = new Uint8Array([0, 0, 0, 255]);
      GlText.prototype.alignOffset = [0, 0];
      GlText.maxAtlasSize = 1024;
      GlText.atlasCanvas = document.createElement("canvas");
      GlText.atlasContext = GlText.atlasCanvas.getContext("2d", { alpha: false });
      GlText.baseFontSize = 64;
      GlText.fonts = {};
      function isRegl(o) {
        return typeof o === "function" && o._gl && o.prop && o.texture && o.buffer;
      }
      module.exports = GlText;
    }
  });

  // node_modules/@plotly/regl/dist/regl.unchecked.js
  var require_regl_unchecked2 = __commonJS({
    "node_modules/@plotly/regl/dist/regl.unchecked.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && false ? define(factory) : global2.createREGL = factory();
      })(exports, function() {
        "use strict";
        var extend2 = function(base, opts) {
          var keys = Object.keys(opts);
          for (var i = 0; i < keys.length; ++i) {
            base[keys[i]] = opts[keys[i]];
          }
          return base;
        };
        var VARIABLE_COUNTER = 0;
        var DYN_FUNC = 0;
        var DYN_CONSTANT = 5;
        var DYN_ARRAY = 6;
        function DynamicVariable(type, data) {
          this.id = VARIABLE_COUNTER++;
          this.type = type;
          this.data = data;
        }
        function escapeStr(str) {
          return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
        }
        function splitParts(str) {
          if (str.length === 0) {
            return [];
          }
          var firstChar = str.charAt(0);
          var lastChar = str.charAt(str.length - 1);
          if (str.length > 1 && firstChar === lastChar && (firstChar === '"' || firstChar === "'")) {
            return ['"' + escapeStr(str.substr(1, str.length - 2)) + '"'];
          }
          var parts = /\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str);
          if (parts) {
            return splitParts(str.substr(0, parts.index)).concat(splitParts(parts[1])).concat(splitParts(str.substr(parts.index + parts[0].length)));
          }
          var subparts = str.split(".");
          if (subparts.length === 1) {
            return ['"' + escapeStr(str) + '"'];
          }
          var result = [];
          for (var i = 0; i < subparts.length; ++i) {
            result = result.concat(splitParts(subparts[i]));
          }
          return result;
        }
        function toAccessorString(str) {
          return "[" + splitParts(str).join("][") + "]";
        }
        function defineDynamic(type, data) {
          return new DynamicVariable(type, toAccessorString(data + ""));
        }
        function isDynamic(x) {
          return typeof x === "function" && !x._reglType || x instanceof DynamicVariable;
        }
        function unbox(x, path) {
          if (typeof x === "function") {
            return new DynamicVariable(DYN_FUNC, x);
          } else if (typeof x === "number" || typeof x === "boolean") {
            return new DynamicVariable(DYN_CONSTANT, x);
          } else if (Array.isArray(x)) {
            return new DynamicVariable(DYN_ARRAY, x.map(function(y, i) {
              return unbox(y, path + "[" + i + "]");
            }));
          } else if (x instanceof DynamicVariable) {
            return x;
          }
        }
        var dynamic = {
          DynamicVariable,
          define: defineDynamic,
          isDynamic,
          unbox,
          accessor: toAccessorString
        };
        var raf = {
          next: typeof requestAnimationFrame === "function" ? function(cb) {
            return requestAnimationFrame(cb);
          } : function(cb) {
            return setTimeout(cb, 16);
          },
          cancel: typeof cancelAnimationFrame === "function" ? function(raf2) {
            return cancelAnimationFrame(raf2);
          } : clearTimeout
        };
        var clock = typeof performance !== "undefined" && performance.now ? function() {
          return performance.now();
        } : function() {
          return +/* @__PURE__ */ new Date();
        };
        function createStringStore() {
          var stringIds = { "": 0 };
          var stringValues = [""];
          return {
            id: function(str) {
              var result = stringIds[str];
              if (result) {
                return result;
              }
              result = stringIds[str] = stringValues.length;
              stringValues.push(str);
              return result;
            },
            str: function(id) {
              return stringValues[id];
            }
          };
        }
        function createCanvas(element, onDone, pixelRatio) {
          var canvas = document.createElement("canvas");
          extend2(canvas.style, {
            border: 0,
            margin: 0,
            padding: 0,
            top: 0,
            left: 0,
            width: "100%",
            height: "100%"
          });
          element.appendChild(canvas);
          if (element === document.body) {
            canvas.style.position = "absolute";
            extend2(element.style, {
              margin: 0,
              padding: 0
            });
          }
          function resize() {
            var w = window.innerWidth;
            var h = window.innerHeight;
            if (element !== document.body) {
              var bounds = canvas.getBoundingClientRect();
              w = bounds.right - bounds.left;
              h = bounds.bottom - bounds.top;
            }
            canvas.width = pixelRatio * w;
            canvas.height = pixelRatio * h;
          }
          var resizeObserver;
          if (element !== document.body && typeof ResizeObserver === "function") {
            resizeObserver = new ResizeObserver(function() {
              setTimeout(resize);
            });
            resizeObserver.observe(element);
          } else {
            window.addEventListener("resize", resize, false);
          }
          function onDestroy() {
            if (resizeObserver) {
              resizeObserver.disconnect();
            } else {
              window.removeEventListener("resize", resize);
            }
            element.removeChild(canvas);
          }
          resize();
          return {
            canvas,
            onDestroy
          };
        }
        function createContext(canvas, contextAttributes) {
          function get(name2) {
            try {
              return canvas.getContext(name2, contextAttributes);
            } catch (e) {
              return null;
            }
          }
          return get("webgl") || get("experimental-webgl") || get("webgl-experimental");
        }
        function isHTMLElement(obj) {
          return typeof obj.nodeName === "string" && typeof obj.appendChild === "function" && typeof obj.getBoundingClientRect === "function";
        }
        function isWebGLContext(obj) {
          return typeof obj.drawArrays === "function" || typeof obj.drawElements === "function";
        }
        function parseExtensions(input) {
          if (typeof input === "string") {
            return input.split();
          }
          return input;
        }
        function getElement(desc) {
          if (typeof desc === "string") {
            return document.querySelector(desc);
          }
          return desc;
        }
        function parseArgs(args_) {
          var args = args_ || {};
          var element, container, canvas, gl2;
          var contextAttributes = {};
          var extensions = [];
          var optionalExtensions = [];
          var pixelRatio = typeof window === "undefined" ? 1 : window.devicePixelRatio;
          var profile = false;
          var cachedCode = {};
          var onDone = function(err) {
            if (err) {
            }
          };
          var onDestroy = function() {
          };
          if (typeof args === "string") {
            element = document.querySelector(args);
          } else if (typeof args === "object") {
            if (isHTMLElement(args)) {
              element = args;
            } else if (isWebGLContext(args)) {
              gl2 = args;
              canvas = gl2.canvas;
            } else {
              if ("gl" in args) {
                gl2 = args.gl;
              } else if ("canvas" in args) {
                canvas = getElement(args.canvas);
              } else if ("container" in args) {
                container = getElement(args.container);
              }
              if ("attributes" in args) {
                contextAttributes = args.attributes;
              }
              if ("extensions" in args) {
                extensions = parseExtensions(args.extensions);
              }
              if ("optionalExtensions" in args) {
                optionalExtensions = parseExtensions(args.optionalExtensions);
              }
              if ("onDone" in args) {
                onDone = args.onDone;
              }
              if ("profile" in args) {
                profile = !!args.profile;
              }
              if ("pixelRatio" in args) {
                pixelRatio = +args.pixelRatio;
              }
              if ("cachedCode" in args) {
                cachedCode = args.cachedCode;
              }
            }
          } else {
          }
          if (element) {
            if (element.nodeName.toLowerCase() === "canvas") {
              canvas = element;
            } else {
              container = element;
            }
          }
          if (!gl2) {
            if (!canvas) {
              var result = createCanvas(container || document.body, onDone, pixelRatio);
              if (!result) {
                return null;
              }
              canvas = result.canvas;
              onDestroy = result.onDestroy;
            }
            if (contextAttributes.premultipliedAlpha === void 0) contextAttributes.premultipliedAlpha = true;
            gl2 = createContext(canvas, contextAttributes);
          }
          if (!gl2) {
            onDestroy();
            onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org");
            return null;
          }
          return {
            gl: gl2,
            canvas,
            container,
            extensions,
            optionalExtensions,
            pixelRatio,
            profile,
            cachedCode,
            onDone,
            onDestroy
          };
        }
        function createExtensionCache(gl2, config) {
          var extensions = {};
          function tryLoadExtension(name_) {
            var name3 = name_.toLowerCase();
            var ext;
            try {
              ext = extensions[name3] = gl2.getExtension(name3);
            } catch (e) {
            }
            return !!ext;
          }
          for (var i = 0; i < config.extensions.length; ++i) {
            var name2 = config.extensions[i];
            if (!tryLoadExtension(name2)) {
              config.onDestroy();
              config.onDone('"' + name2 + '" extension is not supported by the current WebGL context, try upgrading your system or a different browser');
              return null;
            }
          }
          config.optionalExtensions.forEach(tryLoadExtension);
          return {
            extensions,
            restore: function() {
              Object.keys(extensions).forEach(function(name3) {
                if (extensions[name3] && !tryLoadExtension(name3)) {
                  throw new Error("(regl): error restoring extension " + name3);
                }
              });
            }
          };
        }
        function loop(n, f) {
          var result = Array(n);
          for (var i = 0; i < n; ++i) {
            result[i] = f(i);
          }
          return result;
        }
        var GL_BYTE = 5120;
        var GL_UNSIGNED_BYTE$1 = 5121;
        var GL_SHORT = 5122;
        var GL_UNSIGNED_SHORT = 5123;
        var GL_INT = 5124;
        var GL_UNSIGNED_INT = 5125;
        var GL_FLOAT$1 = 5126;
        function nextPow16(v) {
          for (var i = 16; i <= 1 << 28; i *= 16) {
            if (v <= i) {
              return i;
            }
          }
          return 0;
        }
        function log2(v) {
          var r, shift;
          r = (v > 65535) << 4;
          v >>>= r;
          shift = (v > 255) << 3;
          v >>>= shift;
          r |= shift;
          shift = (v > 15) << 2;
          v >>>= shift;
          r |= shift;
          shift = (v > 3) << 1;
          v >>>= shift;
          r |= shift;
          return r | v >> 1;
        }
        function createPool() {
          var bufferPool = loop(8, function() {
            return [];
          });
          function alloc(n) {
            var sz = nextPow16(n);
            var bin = bufferPool[log2(sz) >> 2];
            if (bin.length > 0) {
              return bin.pop();
            }
            return new ArrayBuffer(sz);
          }
          function free(buf) {
            bufferPool[log2(buf.byteLength) >> 2].push(buf);
          }
          function allocType(type, n) {
            var result = null;
            switch (type) {
              case GL_BYTE:
                result = new Int8Array(alloc(n), 0, n);
                break;
              case GL_UNSIGNED_BYTE$1:
                result = new Uint8Array(alloc(n), 0, n);
                break;
              case GL_SHORT:
                result = new Int16Array(alloc(2 * n), 0, n);
                break;
              case GL_UNSIGNED_SHORT:
                result = new Uint16Array(alloc(2 * n), 0, n);
                break;
              case GL_INT:
                result = new Int32Array(alloc(4 * n), 0, n);
                break;
              case GL_UNSIGNED_INT:
                result = new Uint32Array(alloc(4 * n), 0, n);
                break;
              case GL_FLOAT$1:
                result = new Float32Array(alloc(4 * n), 0, n);
                break;
              default:
                return null;
            }
            if (result.length !== n) {
              return result.subarray(0, n);
            }
            return result;
          }
          function freeType(array) {
            free(array.buffer);
          }
          return {
            alloc,
            free,
            allocType,
            freeType
          };
        }
        var pool = createPool();
        pool.zero = createPool();
        var GL_SUBPIXEL_BITS = 3408;
        var GL_RED_BITS = 3410;
        var GL_GREEN_BITS = 3411;
        var GL_BLUE_BITS = 3412;
        var GL_ALPHA_BITS = 3413;
        var GL_DEPTH_BITS = 3414;
        var GL_STENCIL_BITS = 3415;
        var GL_ALIASED_POINT_SIZE_RANGE = 33901;
        var GL_ALIASED_LINE_WIDTH_RANGE = 33902;
        var GL_MAX_TEXTURE_SIZE = 3379;
        var GL_MAX_VIEWPORT_DIMS = 3386;
        var GL_MAX_VERTEX_ATTRIBS = 34921;
        var GL_MAX_VERTEX_UNIFORM_VECTORS = 36347;
        var GL_MAX_VARYING_VECTORS = 36348;
        var GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 35661;
        var GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 35660;
        var GL_MAX_TEXTURE_IMAGE_UNITS = 34930;
        var GL_MAX_FRAGMENT_UNIFORM_VECTORS = 36349;
        var GL_MAX_CUBE_MAP_TEXTURE_SIZE = 34076;
        var GL_MAX_RENDERBUFFER_SIZE = 34024;
        var GL_VENDOR = 7936;
        var GL_RENDERER = 7937;
        var GL_VERSION = 7938;
        var GL_SHADING_LANGUAGE_VERSION = 35724;
        var GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 34047;
        var GL_MAX_COLOR_ATTACHMENTS_WEBGL = 36063;
        var GL_MAX_DRAW_BUFFERS_WEBGL = 34852;
        var GL_TEXTURE_2D = 3553;
        var GL_TEXTURE_CUBE_MAP = 34067;
        var GL_TEXTURE_CUBE_MAP_POSITIVE_X = 34069;
        var GL_TEXTURE0 = 33984;
        var GL_RGBA = 6408;
        var GL_FLOAT = 5126;
        var GL_UNSIGNED_BYTE = 5121;
        var GL_FRAMEBUFFER = 36160;
        var GL_FRAMEBUFFER_COMPLETE = 36053;
        var GL_COLOR_ATTACHMENT0 = 36064;
        var GL_COLOR_BUFFER_BIT$1 = 16384;
        var wrapLimits = function(gl2, extensions) {
          var maxAnisotropic = 1;
          if (extensions.ext_texture_filter_anisotropic) {
            maxAnisotropic = gl2.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT);
          }
          var maxDrawbuffers = 1;
          var maxColorAttachments = 1;
          if (extensions.webgl_draw_buffers) {
            maxDrawbuffers = gl2.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL);
            maxColorAttachments = gl2.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL);
          }
          var readFloat = !!extensions.oes_texture_float;
          if (readFloat) {
            var readFloatTexture = gl2.createTexture();
            gl2.bindTexture(GL_TEXTURE_2D, readFloatTexture);
            gl2.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, null);
            var fbo = gl2.createFramebuffer();
            gl2.bindFramebuffer(GL_FRAMEBUFFER, fbo);
            gl2.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, readFloatTexture, 0);
            gl2.bindTexture(GL_TEXTURE_2D, null);
            if (gl2.checkFramebufferStatus(GL_FRAMEBUFFER) !== GL_FRAMEBUFFER_COMPLETE) readFloat = false;
            else {
              gl2.viewport(0, 0, 1, 1);
              gl2.clearColor(1, 0, 0, 1);
              gl2.clear(GL_COLOR_BUFFER_BIT$1);
              var pixels = pool.allocType(GL_FLOAT, 4);
              gl2.readPixels(0, 0, 1, 1, GL_RGBA, GL_FLOAT, pixels);
              if (gl2.getError()) readFloat = false;
              else {
                gl2.deleteFramebuffer(fbo);
                gl2.deleteTexture(readFloatTexture);
                readFloat = pixels[0] === 1;
              }
              pool.freeType(pixels);
            }
          }
          var isIE = typeof navigator !== "undefined" && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion) || /Edge/.test(navigator.userAgent));
          var npotTextureCube = true;
          if (!isIE) {
            var cubeTexture = gl2.createTexture();
            var data = pool.allocType(GL_UNSIGNED_BYTE, 36);
            gl2.activeTexture(GL_TEXTURE0);
            gl2.bindTexture(GL_TEXTURE_CUBE_MAP, cubeTexture);
            gl2.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, 3, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
            pool.freeType(data);
            gl2.bindTexture(GL_TEXTURE_CUBE_MAP, null);
            gl2.deleteTexture(cubeTexture);
            npotTextureCube = !gl2.getError();
          }
          return {
            // drawing buffer bit depth
            colorBits: [
              gl2.getParameter(GL_RED_BITS),
              gl2.getParameter(GL_GREEN_BITS),
              gl2.getParameter(GL_BLUE_BITS),
              gl2.getParameter(GL_ALPHA_BITS)
            ],
            depthBits: gl2.getParameter(GL_DEPTH_BITS),
            stencilBits: gl2.getParameter(GL_STENCIL_BITS),
            subpixelBits: gl2.getParameter(GL_SUBPIXEL_BITS),
            // supported extensions
            extensions: Object.keys(extensions).filter(function(ext) {
              return !!extensions[ext];
            }),
            // max aniso samples
            maxAnisotropic,
            // max draw buffers
            maxDrawbuffers,
            maxColorAttachments,
            // point and line size ranges
            pointSizeDims: gl2.getParameter(GL_ALIASED_POINT_SIZE_RANGE),
            lineWidthDims: gl2.getParameter(GL_ALIASED_LINE_WIDTH_RANGE),
            maxViewportDims: gl2.getParameter(GL_MAX_VIEWPORT_DIMS),
            maxCombinedTextureUnits: gl2.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS),
            maxCubeMapSize: gl2.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE),
            maxRenderbufferSize: gl2.getParameter(GL_MAX_RENDERBUFFER_SIZE),
            maxTextureUnits: gl2.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS),
            maxTextureSize: gl2.getParameter(GL_MAX_TEXTURE_SIZE),
            maxAttributes: gl2.getParameter(GL_MAX_VERTEX_ATTRIBS),
            maxVertexUniforms: gl2.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS),
            maxVertexTextureUnits: gl2.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS),
            maxVaryingVectors: gl2.getParameter(GL_MAX_VARYING_VECTORS),
            maxFragmentUniforms: gl2.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS),
            // vendor info
            glsl: gl2.getParameter(GL_SHADING_LANGUAGE_VERSION),
            renderer: gl2.getParameter(GL_RENDERER),
            vendor: gl2.getParameter(GL_VENDOR),
            version: gl2.getParameter(GL_VERSION),
            // quirks
            readFloat,
            npotTextureCube
          };
        };
        var isTypedArray = function(x) {
          return x instanceof Uint8Array || x instanceof Uint16Array || x instanceof Uint32Array || x instanceof Int8Array || x instanceof Int16Array || x instanceof Int32Array || x instanceof Float32Array || x instanceof Float64Array || x instanceof Uint8ClampedArray;
        };
        function isNDArrayLike(obj) {
          return !!obj && typeof obj === "object" && Array.isArray(obj.shape) && Array.isArray(obj.stride) && typeof obj.offset === "number" && obj.shape.length === obj.stride.length && (Array.isArray(obj.data) || isTypedArray(obj.data));
        }
        var values = function(obj) {
          return Object.keys(obj).map(function(key) {
            return obj[key];
          });
        };
        var flattenUtils = {
          shape: arrayShape$1,
          flatten: flattenArray
        };
        function flatten1D(array, nx, out) {
          for (var i = 0; i < nx; ++i) {
            out[i] = array[i];
          }
        }
        function flatten2D(array, nx, ny, out) {
          var ptr = 0;
          for (var i = 0; i < nx; ++i) {
            var row = array[i];
            for (var j = 0; j < ny; ++j) {
              out[ptr++] = row[j];
            }
          }
        }
        function flatten3D(array, nx, ny, nz, out, ptr_) {
          var ptr = ptr_;
          for (var i = 0; i < nx; ++i) {
            var row = array[i];
            for (var j = 0; j < ny; ++j) {
              var col = row[j];
              for (var k = 0; k < nz; ++k) {
                out[ptr++] = col[k];
              }
            }
          }
        }
        function flattenRec(array, shape, level, out, ptr) {
          var stride = 1;
          for (var i = level + 1; i < shape.length; ++i) {
            stride *= shape[i];
          }
          var n = shape[level];
          if (shape.length - level === 4) {
            var nx = shape[level + 1];
            var ny = shape[level + 2];
            var nz = shape[level + 3];
            for (i = 0; i < n; ++i) {
              flatten3D(array[i], nx, ny, nz, out, ptr);
              ptr += stride;
            }
          } else {
            for (i = 0; i < n; ++i) {
              flattenRec(array[i], shape, level + 1, out, ptr);
              ptr += stride;
            }
          }
        }
        function flattenArray(array, shape, type, out_) {
          var sz = 1;
          if (shape.length) {
            for (var i = 0; i < shape.length; ++i) {
              sz *= shape[i];
            }
          } else {
            sz = 0;
          }
          var out = out_ || pool.allocType(type, sz);
          switch (shape.length) {
            case 0:
              break;
            case 1:
              flatten1D(array, shape[0], out);
              break;
            case 2:
              flatten2D(array, shape[0], shape[1], out);
              break;
            case 3:
              flatten3D(array, shape[0], shape[1], shape[2], out, 0);
              break;
            default:
              flattenRec(array, shape, 0, out, 0);
          }
          return out;
        }
        function arrayShape$1(array_) {
          var shape = [];
          for (var array = array_; array.length; array = array[0]) {
            shape.push(array.length);
          }
          return shape;
        }
        var arrayTypes = {
          "[object Int8Array]": 5120,
          "[object Int16Array]": 5122,
          "[object Int32Array]": 5124,
          "[object Uint8Array]": 5121,
          "[object Uint8ClampedArray]": 5121,
          "[object Uint16Array]": 5123,
          "[object Uint32Array]": 5125,
          "[object Float32Array]": 5126,
          "[object Float64Array]": 5121,
          "[object ArrayBuffer]": 5121
        };
        var int8 = 5120;
        var int16 = 5122;
        var int32 = 5124;
        var uint8 = 5121;
        var uint16 = 5123;
        var uint32 = 5125;
        var float = 5126;
        var float32 = 5126;
        var glTypes = {
          int8,
          int16,
          int32,
          uint8,
          uint16,
          uint32,
          float,
          float32
        };
        var dynamic$1 = 35048;
        var stream = 35040;
        var usageTypes = {
          dynamic: dynamic$1,
          stream,
          "static": 35044
        };
        var arrayFlatten = flattenUtils.flatten;
        var arrayShape = flattenUtils.shape;
        var GL_STATIC_DRAW = 35044;
        var GL_STREAM_DRAW = 35040;
        var GL_UNSIGNED_BYTE$2 = 5121;
        var GL_FLOAT$2 = 5126;
        var DTYPES_SIZES = [];
        DTYPES_SIZES[5120] = 1;
        DTYPES_SIZES[5122] = 2;
        DTYPES_SIZES[5124] = 4;
        DTYPES_SIZES[5121] = 1;
        DTYPES_SIZES[5123] = 2;
        DTYPES_SIZES[5125] = 4;
        DTYPES_SIZES[5126] = 4;
        function typedArrayCode(data) {
          return arrayTypes[Object.prototype.toString.call(data)] | 0;
        }
        function copyArray(out, inp) {
          for (var i = 0; i < inp.length; ++i) {
            out[i] = inp[i];
          }
        }
        function transpose(result, data, shapeX, shapeY, strideX, strideY, offset) {
          var ptr = 0;
          for (var i = 0; i < shapeX; ++i) {
            for (var j = 0; j < shapeY; ++j) {
              result[ptr++] = data[strideX * i + strideY * j + offset];
            }
          }
        }
        function wrapBufferState(gl2, stats2, config, destroyBuffer) {
          var bufferCount = 0;
          var bufferSet = {};
          function REGLBuffer(type) {
            this.id = bufferCount++;
            this.buffer = gl2.createBuffer();
            this.type = type;
            this.usage = GL_STATIC_DRAW;
            this.byteLength = 0;
            this.dimension = 1;
            this.dtype = GL_UNSIGNED_BYTE$2;
            this.persistentData = null;
            if (config.profile) {
              this.stats = { size: 0 };
            }
          }
          REGLBuffer.prototype.bind = function() {
            gl2.bindBuffer(this.type, this.buffer);
          };
          REGLBuffer.prototype.destroy = function() {
            destroy(this);
          };
          var streamPool = [];
          function createStream(type, data) {
            var buffer = streamPool.pop();
            if (!buffer) {
              buffer = new REGLBuffer(type);
            }
            buffer.bind();
            initBufferFromData(buffer, data, GL_STREAM_DRAW, 0, 1, false);
            return buffer;
          }
          function destroyStream(stream$$1) {
            streamPool.push(stream$$1);
          }
          function initBufferFromTypedArray(buffer, data, usage) {
            buffer.byteLength = data.byteLength;
            gl2.bufferData(buffer.type, data, usage);
          }
          function initBufferFromData(buffer, data, usage, dtype, dimension, persist) {
            var shape;
            buffer.usage = usage;
            if (Array.isArray(data)) {
              buffer.dtype = dtype || GL_FLOAT$2;
              if (data.length > 0) {
                var flatData;
                if (Array.isArray(data[0])) {
                  shape = arrayShape(data);
                  var dim = 1;
                  for (var i = 1; i < shape.length; ++i) {
                    dim *= shape[i];
                  }
                  buffer.dimension = dim;
                  flatData = arrayFlatten(data, shape, buffer.dtype);
                  initBufferFromTypedArray(buffer, flatData, usage);
                  if (persist) {
                    buffer.persistentData = flatData;
                  } else {
                    pool.freeType(flatData);
                  }
                } else if (typeof data[0] === "number") {
                  buffer.dimension = dimension;
                  var typedData = pool.allocType(buffer.dtype, data.length);
                  copyArray(typedData, data);
                  initBufferFromTypedArray(buffer, typedData, usage);
                  if (persist) {
                    buffer.persistentData = typedData;
                  } else {
                    pool.freeType(typedData);
                  }
                } else if (isTypedArray(data[0])) {
                  buffer.dimension = data[0].length;
                  buffer.dtype = dtype || typedArrayCode(data[0]) || GL_FLOAT$2;
                  flatData = arrayFlatten(
                    data,
                    [data.length, data[0].length],
                    buffer.dtype
                  );
                  initBufferFromTypedArray(buffer, flatData, usage);
                  if (persist) {
                    buffer.persistentData = flatData;
                  } else {
                    pool.freeType(flatData);
                  }
                } else {
                }
              }
            } else if (isTypedArray(data)) {
              buffer.dtype = dtype || typedArrayCode(data);
              buffer.dimension = dimension;
              initBufferFromTypedArray(buffer, data, usage);
              if (persist) {
                buffer.persistentData = new Uint8Array(new Uint8Array(data.buffer));
              }
            } else if (isNDArrayLike(data)) {
              shape = data.shape;
              var stride = data.stride;
              var offset = data.offset;
              var shapeX = 0;
              var shapeY = 0;
              var strideX = 0;
              var strideY = 0;
              if (shape.length === 1) {
                shapeX = shape[0];
                shapeY = 1;
                strideX = stride[0];
                strideY = 0;
              } else if (shape.length === 2) {
                shapeX = shape[0];
                shapeY = shape[1];
                strideX = stride[0];
                strideY = stride[1];
              } else {
              }
              buffer.dtype = dtype || typedArrayCode(data.data) || GL_FLOAT$2;
              buffer.dimension = shapeY;
              var transposeData2 = pool.allocType(buffer.dtype, shapeX * shapeY);
              transpose(
                transposeData2,
                data.data,
                shapeX,
                shapeY,
                strideX,
                strideY,
                offset
              );
              initBufferFromTypedArray(buffer, transposeData2, usage);
              if (persist) {
                buffer.persistentData = transposeData2;
              } else {
                pool.freeType(transposeData2);
              }
            } else if (data instanceof ArrayBuffer) {
              buffer.dtype = GL_UNSIGNED_BYTE$2;
              buffer.dimension = dimension;
              initBufferFromTypedArray(buffer, data, usage);
              if (persist) {
                buffer.persistentData = new Uint8Array(new Uint8Array(data));
              }
            } else {
            }
          }
          function destroy(buffer) {
            stats2.bufferCount--;
            destroyBuffer(buffer);
            var handle = buffer.buffer;
            gl2.deleteBuffer(handle);
            buffer.buffer = null;
            delete bufferSet[buffer.id];
          }
          function createBuffer(options, type, deferInit, persistent) {
            stats2.bufferCount++;
            var buffer = new REGLBuffer(type);
            bufferSet[buffer.id] = buffer;
            function reglBuffer(options2) {
              var usage = GL_STATIC_DRAW;
              var data = null;
              var byteLength = 0;
              var dtype = 0;
              var dimension = 1;
              if (Array.isArray(options2) || isTypedArray(options2) || isNDArrayLike(options2) || options2 instanceof ArrayBuffer) {
                data = options2;
              } else if (typeof options2 === "number") {
                byteLength = options2 | 0;
              } else if (options2) {
                if ("data" in options2) {
                  data = options2.data;
                }
                if ("usage" in options2) {
                  usage = usageTypes[options2.usage];
                }
                if ("type" in options2) {
                  dtype = glTypes[options2.type];
                }
                if ("dimension" in options2) {
                  dimension = options2.dimension | 0;
                }
                if ("length" in options2) {
                  byteLength = options2.length | 0;
                }
              }
              buffer.bind();
              if (!data) {
                if (byteLength) gl2.bufferData(buffer.type, byteLength, usage);
                buffer.dtype = dtype || GL_UNSIGNED_BYTE$2;
                buffer.usage = usage;
                buffer.dimension = dimension;
                buffer.byteLength = byteLength;
              } else {
                initBufferFromData(buffer, data, usage, dtype, dimension, persistent);
              }
              if (config.profile) {
                buffer.stats.size = buffer.byteLength * DTYPES_SIZES[buffer.dtype];
              }
              return reglBuffer;
            }
            function setSubData(data, offset) {
              gl2.bufferSubData(buffer.type, offset, data);
            }
            function subdata(data, offset_) {
              var offset = (offset_ || 0) | 0;
              var shape;
              buffer.bind();
              if (isTypedArray(data) || data instanceof ArrayBuffer) {
                setSubData(data, offset);
              } else if (Array.isArray(data)) {
                if (data.length > 0) {
                  if (typeof data[0] === "number") {
                    var converted = pool.allocType(buffer.dtype, data.length);
                    copyArray(converted, data);
                    setSubData(converted, offset);
                    pool.freeType(converted);
                  } else if (Array.isArray(data[0]) || isTypedArray(data[0])) {
                    shape = arrayShape(data);
                    var flatData = arrayFlatten(data, shape, buffer.dtype);
                    setSubData(flatData, offset);
                    pool.freeType(flatData);
                  } else {
                  }
                }
              } else if (isNDArrayLike(data)) {
                shape = data.shape;
                var stride = data.stride;
                var shapeX = 0;
                var shapeY = 0;
                var strideX = 0;
                var strideY = 0;
                if (shape.length === 1) {
                  shapeX = shape[0];
                  shapeY = 1;
                  strideX = stride[0];
                  strideY = 0;
                } else if (shape.length === 2) {
                  shapeX = shape[0];
                  shapeY = shape[1];
                  strideX = stride[0];
                  strideY = stride[1];
                } else {
                }
                var dtype = Array.isArray(data.data) ? buffer.dtype : typedArrayCode(data.data);
                var transposeData2 = pool.allocType(dtype, shapeX * shapeY);
                transpose(
                  transposeData2,
                  data.data,
                  shapeX,
                  shapeY,
                  strideX,
                  strideY,
                  data.offset
                );
                setSubData(transposeData2, offset);
                pool.freeType(transposeData2);
              } else {
              }
              return reglBuffer;
            }
            if (!deferInit) {
              reglBuffer(options);
            }
            reglBuffer._reglType = "buffer";
            reglBuffer._buffer = buffer;
            reglBuffer.subdata = subdata;
            if (config.profile) {
              reglBuffer.stats = buffer.stats;
            }
            reglBuffer.destroy = function() {
              destroy(buffer);
            };
            return reglBuffer;
          }
          function restoreBuffers() {
            values(bufferSet).forEach(function(buffer) {
              buffer.buffer = gl2.createBuffer();
              gl2.bindBuffer(buffer.type, buffer.buffer);
              gl2.bufferData(
                buffer.type,
                buffer.persistentData || buffer.byteLength,
                buffer.usage
              );
            });
          }
          if (config.profile) {
            stats2.getTotalBufferSize = function() {
              var total = 0;
              Object.keys(bufferSet).forEach(function(key) {
                total += bufferSet[key].stats.size;
              });
              return total;
            };
          }
          return {
            create: createBuffer,
            createStream,
            destroyStream,
            clear: function() {
              values(bufferSet).forEach(destroy);
              streamPool.forEach(destroy);
            },
            getBuffer: function(wrapper) {
              if (wrapper && wrapper._buffer instanceof REGLBuffer) {
                return wrapper._buffer;
              }
              return null;
            },
            restore: restoreBuffers,
            _initBuffer: initBufferFromData
          };
        }
        var points = 0;
        var point = 0;
        var lines = 1;
        var line = 1;
        var triangles = 4;
        var triangle = 4;
        var primTypes = {
          points,
          point,
          lines,
          line,
          triangles,
          triangle,
          "line loop": 2,
          "line strip": 3,
          "triangle strip": 5,
          "triangle fan": 6
        };
        var GL_POINTS = 0;
        var GL_LINES = 1;
        var GL_TRIANGLES = 4;
        var GL_BYTE$1 = 5120;
        var GL_UNSIGNED_BYTE$3 = 5121;
        var GL_SHORT$1 = 5122;
        var GL_UNSIGNED_SHORT$1 = 5123;
        var GL_INT$1 = 5124;
        var GL_UNSIGNED_INT$1 = 5125;
        var GL_ELEMENT_ARRAY_BUFFER = 34963;
        var GL_STREAM_DRAW$1 = 35040;
        var GL_STATIC_DRAW$1 = 35044;
        function wrapElementsState(gl2, extensions, bufferState, stats2) {
          var elementSet = {};
          var elementCount = 0;
          var elementTypes = {
            "uint8": GL_UNSIGNED_BYTE$3,
            "uint16": GL_UNSIGNED_SHORT$1
          };
          if (extensions.oes_element_index_uint) {
            elementTypes.uint32 = GL_UNSIGNED_INT$1;
          }
          function REGLElementBuffer(buffer) {
            this.id = elementCount++;
            elementSet[this.id] = this;
            this.buffer = buffer;
            this.primType = GL_TRIANGLES;
            this.vertCount = 0;
            this.type = 0;
          }
          REGLElementBuffer.prototype.bind = function() {
            this.buffer.bind();
          };
          var bufferPool = [];
          function createElementStream(data) {
            var result = bufferPool.pop();
            if (!result) {
              result = new REGLElementBuffer(bufferState.create(
                null,
                GL_ELEMENT_ARRAY_BUFFER,
                true,
                false
              )._buffer);
            }
            initElements(result, data, GL_STREAM_DRAW$1, -1, -1, 0, 0);
            return result;
          }
          function destroyElementStream(elements) {
            bufferPool.push(elements);
          }
          function initElements(elements, data, usage, prim, count, byteLength, type) {
            elements.buffer.bind();
            var dtype;
            if (data) {
              var predictedType = type;
              if (!type && (!isTypedArray(data) || isNDArrayLike(data) && !isTypedArray(data.data))) {
                predictedType = extensions.oes_element_index_uint ? GL_UNSIGNED_INT$1 : GL_UNSIGNED_SHORT$1;
              }
              bufferState._initBuffer(
                elements.buffer,
                data,
                usage,
                predictedType,
                3
              );
            } else {
              gl2.bufferData(GL_ELEMENT_ARRAY_BUFFER, byteLength, usage);
              elements.buffer.dtype = dtype || GL_UNSIGNED_BYTE$3;
              elements.buffer.usage = usage;
              elements.buffer.dimension = 3;
              elements.buffer.byteLength = byteLength;
            }
            dtype = type;
            if (!type) {
              switch (elements.buffer.dtype) {
                case GL_UNSIGNED_BYTE$3:
                case GL_BYTE$1:
                  dtype = GL_UNSIGNED_BYTE$3;
                  break;
                case GL_UNSIGNED_SHORT$1:
                case GL_SHORT$1:
                  dtype = GL_UNSIGNED_SHORT$1;
                  break;
                case GL_UNSIGNED_INT$1:
                case GL_INT$1:
                  dtype = GL_UNSIGNED_INT$1;
                  break;
                default:
              }
              elements.buffer.dtype = dtype;
            }
            elements.type = dtype;
            var vertCount = count;
            if (vertCount < 0) {
              vertCount = elements.buffer.byteLength;
              if (dtype === GL_UNSIGNED_SHORT$1) {
                vertCount >>= 1;
              } else if (dtype === GL_UNSIGNED_INT$1) {
                vertCount >>= 2;
              }
            }
            elements.vertCount = vertCount;
            var primType = prim;
            if (prim < 0) {
              primType = GL_TRIANGLES;
              var dimension = elements.buffer.dimension;
              if (dimension === 1) primType = GL_POINTS;
              if (dimension === 2) primType = GL_LINES;
              if (dimension === 3) primType = GL_TRIANGLES;
            }
            elements.primType = primType;
          }
          function destroyElements(elements) {
            stats2.elementsCount--;
            delete elementSet[elements.id];
            elements.buffer.destroy();
            elements.buffer = null;
          }
          function createElements(options, persistent) {
            var buffer = bufferState.create(null, GL_ELEMENT_ARRAY_BUFFER, true);
            var elements = new REGLElementBuffer(buffer._buffer);
            stats2.elementsCount++;
            function reglElements(options2) {
              if (!options2) {
                buffer();
                elements.primType = GL_TRIANGLES;
                elements.vertCount = 0;
                elements.type = GL_UNSIGNED_BYTE$3;
              } else if (typeof options2 === "number") {
                buffer(options2);
                elements.primType = GL_TRIANGLES;
                elements.vertCount = options2 | 0;
                elements.type = GL_UNSIGNED_BYTE$3;
              } else {
                var data = null;
                var usage = GL_STATIC_DRAW$1;
                var primType = -1;
                var vertCount = -1;
                var byteLength = 0;
                var dtype = 0;
                if (Array.isArray(options2) || isTypedArray(options2) || isNDArrayLike(options2)) {
                  data = options2;
                } else {
                  if ("data" in options2) {
                    data = options2.data;
                  }
                  if ("usage" in options2) {
                    usage = usageTypes[options2.usage];
                  }
                  if ("primitive" in options2) {
                    primType = primTypes[options2.primitive];
                  }
                  if ("count" in options2) {
                    vertCount = options2.count | 0;
                  }
                  if ("type" in options2) {
                    dtype = elementTypes[options2.type];
                  }
                  if ("length" in options2) {
                    byteLength = options2.length | 0;
                  } else {
                    byteLength = vertCount;
                    if (dtype === GL_UNSIGNED_SHORT$1 || dtype === GL_SHORT$1) {
                      byteLength *= 2;
                    } else if (dtype === GL_UNSIGNED_INT$1 || dtype === GL_INT$1) {
                      byteLength *= 4;
                    }
                  }
                }
                initElements(
                  elements,
                  data,
                  usage,
                  primType,
                  vertCount,
                  byteLength,
                  dtype
                );
              }
              return reglElements;
            }
            reglElements(options);
            reglElements._reglType = "elements";
            reglElements._elements = elements;
            reglElements.subdata = function(data, offset) {
              buffer.subdata(data, offset);
              return reglElements;
            };
            reglElements.destroy = function() {
              destroyElements(elements);
            };
            return reglElements;
          }
          return {
            create: createElements,
            createStream: createElementStream,
            destroyStream: destroyElementStream,
            getElements: function(elements) {
              if (typeof elements === "function" && elements._elements instanceof REGLElementBuffer) {
                return elements._elements;
              }
              return null;
            },
            clear: function() {
              values(elementSet).forEach(destroyElements);
            }
          };
        }
        var FLOAT = new Float32Array(1);
        var INT = new Uint32Array(FLOAT.buffer);
        var GL_UNSIGNED_SHORT$3 = 5123;
        function convertToHalfFloat(array) {
          var ushorts = pool.allocType(GL_UNSIGNED_SHORT$3, array.length);
          for (var i = 0; i < array.length; ++i) {
            if (isNaN(array[i])) {
              ushorts[i] = 65535;
            } else if (array[i] === Infinity) {
              ushorts[i] = 31744;
            } else if (array[i] === -Infinity) {
              ushorts[i] = 64512;
            } else {
              FLOAT[0] = array[i];
              var x = INT[0];
              var sgn = x >>> 31 << 15;
              var exp = (x << 1 >>> 24) - 127;
              var frac = x >> 13 & (1 << 10) - 1;
              if (exp < -24) {
                ushorts[i] = sgn;
              } else if (exp < -14) {
                var s = -14 - exp;
                ushorts[i] = sgn + (frac + (1 << 10) >> s);
              } else if (exp > 15) {
                ushorts[i] = sgn + 31744;
              } else {
                ushorts[i] = sgn + (exp + 15 << 10) + frac;
              }
            }
          }
          return ushorts;
        }
        function isArrayLike(s) {
          return Array.isArray(s) || isTypedArray(s);
        }
        var GL_COMPRESSED_TEXTURE_FORMATS = 34467;
        var GL_TEXTURE_2D$1 = 3553;
        var GL_TEXTURE_CUBE_MAP$1 = 34067;
        var GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 = 34069;
        var GL_RGBA$1 = 6408;
        var GL_ALPHA = 6406;
        var GL_RGB = 6407;
        var GL_LUMINANCE = 6409;
        var GL_LUMINANCE_ALPHA = 6410;
        var GL_RGBA4 = 32854;
        var GL_RGB5_A1 = 32855;
        var GL_RGB565 = 36194;
        var GL_UNSIGNED_SHORT_4_4_4_4 = 32819;
        var GL_UNSIGNED_SHORT_5_5_5_1 = 32820;
        var GL_UNSIGNED_SHORT_5_6_5 = 33635;
        var GL_UNSIGNED_INT_24_8_WEBGL = 34042;
        var GL_DEPTH_COMPONENT = 6402;
        var GL_DEPTH_STENCIL = 34041;
        var GL_SRGB_EXT = 35904;
        var GL_SRGB_ALPHA_EXT = 35906;
        var GL_HALF_FLOAT_OES = 36193;
        var GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 33776;
        var GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 33777;
        var GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 33778;
        var GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 33779;
        var GL_COMPRESSED_RGB_ATC_WEBGL = 35986;
        var GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 35987;
        var GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 34798;
        var GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 35840;
        var GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 35841;
        var GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 35842;
        var GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 35843;
        var GL_COMPRESSED_RGB_ETC1_WEBGL = 36196;
        var GL_UNSIGNED_BYTE$4 = 5121;
        var GL_UNSIGNED_SHORT$2 = 5123;
        var GL_UNSIGNED_INT$2 = 5125;
        var GL_FLOAT$3 = 5126;
        var GL_TEXTURE_WRAP_S = 10242;
        var GL_TEXTURE_WRAP_T = 10243;
        var GL_REPEAT = 10497;
        var GL_CLAMP_TO_EDGE = 33071;
        var GL_MIRRORED_REPEAT = 33648;
        var GL_TEXTURE_MAG_FILTER = 10240;
        var GL_TEXTURE_MIN_FILTER = 10241;
        var GL_NEAREST = 9728;
        var GL_LINEAR = 9729;
        var GL_NEAREST_MIPMAP_NEAREST = 9984;
        var GL_LINEAR_MIPMAP_NEAREST = 9985;
        var GL_NEAREST_MIPMAP_LINEAR = 9986;
        var GL_LINEAR_MIPMAP_LINEAR = 9987;
        var GL_GENERATE_MIPMAP_HINT = 33170;
        var GL_DONT_CARE = 4352;
        var GL_FASTEST = 4353;
        var GL_NICEST = 4354;
        var GL_TEXTURE_MAX_ANISOTROPY_EXT = 34046;
        var GL_UNPACK_ALIGNMENT = 3317;
        var GL_UNPACK_FLIP_Y_WEBGL = 37440;
        var GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL = 37441;
        var GL_UNPACK_COLORSPACE_CONVERSION_WEBGL = 37443;
        var GL_BROWSER_DEFAULT_WEBGL = 37444;
        var GL_TEXTURE0$1 = 33984;
        var MIPMAP_FILTERS = [
          GL_NEAREST_MIPMAP_NEAREST,
          GL_NEAREST_MIPMAP_LINEAR,
          GL_LINEAR_MIPMAP_NEAREST,
          GL_LINEAR_MIPMAP_LINEAR
        ];
        var CHANNELS_FORMAT = [
          0,
          GL_LUMINANCE,
          GL_LUMINANCE_ALPHA,
          GL_RGB,
          GL_RGBA$1
        ];
        var FORMAT_CHANNELS = {};
        FORMAT_CHANNELS[GL_LUMINANCE] = FORMAT_CHANNELS[GL_ALPHA] = FORMAT_CHANNELS[GL_DEPTH_COMPONENT] = 1;
        FORMAT_CHANNELS[GL_DEPTH_STENCIL] = FORMAT_CHANNELS[GL_LUMINANCE_ALPHA] = 2;
        FORMAT_CHANNELS[GL_RGB] = FORMAT_CHANNELS[GL_SRGB_EXT] = 3;
        FORMAT_CHANNELS[GL_RGBA$1] = FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT] = 4;
        function objectName(str) {
          return "[object " + str + "]";
        }
        var CANVAS_CLASS = objectName("HTMLCanvasElement");
        var OFFSCREENCANVAS_CLASS = objectName("OffscreenCanvas");
        var CONTEXT2D_CLASS = objectName("CanvasRenderingContext2D");
        var BITMAP_CLASS = objectName("ImageBitmap");
        var IMAGE_CLASS = objectName("HTMLImageElement");
        var VIDEO_CLASS = objectName("HTMLVideoElement");
        var PIXEL_CLASSES = Object.keys(arrayTypes).concat([
          CANVAS_CLASS,
          OFFSCREENCANVAS_CLASS,
          CONTEXT2D_CLASS,
          BITMAP_CLASS,
          IMAGE_CLASS,
          VIDEO_CLASS
        ]);
        var TYPE_SIZES = [];
        TYPE_SIZES[GL_UNSIGNED_BYTE$4] = 1;
        TYPE_SIZES[GL_FLOAT$3] = 4;
        TYPE_SIZES[GL_HALF_FLOAT_OES] = 2;
        TYPE_SIZES[GL_UNSIGNED_SHORT$2] = 2;
        TYPE_SIZES[GL_UNSIGNED_INT$2] = 4;
        var FORMAT_SIZES_SPECIAL = [];
        FORMAT_SIZES_SPECIAL[GL_RGBA4] = 2;
        FORMAT_SIZES_SPECIAL[GL_RGB5_A1] = 2;
        FORMAT_SIZES_SPECIAL[GL_RGB565] = 2;
        FORMAT_SIZES_SPECIAL[GL_DEPTH_STENCIL] = 4;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ATC_WEBGL] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25;
        FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ETC1_WEBGL] = 0.5;
        function isNumericArray(arr) {
          return Array.isArray(arr) && (arr.length === 0 || typeof arr[0] === "number");
        }
        function isRectArray(arr) {
          if (!Array.isArray(arr)) {
            return false;
          }
          var width = arr.length;
          if (width === 0 || !isArrayLike(arr[0])) {
            return false;
          }
          return true;
        }
        function classString(x) {
          return Object.prototype.toString.call(x);
        }
        function isCanvasElement(object) {
          return classString(object) === CANVAS_CLASS;
        }
        function isOffscreenCanvas(object) {
          return classString(object) === OFFSCREENCANVAS_CLASS;
        }
        function isContext2D(object) {
          return classString(object) === CONTEXT2D_CLASS;
        }
        function isBitmap(object) {
          return classString(object) === BITMAP_CLASS;
        }
        function isImageElement(object) {
          return classString(object) === IMAGE_CLASS;
        }
        function isVideoElement(object) {
          return classString(object) === VIDEO_CLASS;
        }
        function isPixelData(object) {
          if (!object) {
            return false;
          }
          var className = classString(object);
          if (PIXEL_CLASSES.indexOf(className) >= 0) {
            return true;
          }
          return isNumericArray(object) || isRectArray(object) || isNDArrayLike(object);
        }
        function typedArrayCode$1(data) {
          return arrayTypes[Object.prototype.toString.call(data)] | 0;
        }
        function convertData(result, data) {
          var n = data.length;
          switch (result.type) {
            case GL_UNSIGNED_BYTE$4:
            case GL_UNSIGNED_SHORT$2:
            case GL_UNSIGNED_INT$2:
            case GL_FLOAT$3:
              var converted = pool.allocType(result.type, n);
              converted.set(data);
              result.data = converted;
              break;
            case GL_HALF_FLOAT_OES:
              result.data = convertToHalfFloat(data);
              break;
            default:
          }
        }
        function preConvert(image, n) {
          return pool.allocType(
            image.type === GL_HALF_FLOAT_OES ? GL_FLOAT$3 : image.type,
            n
          );
        }
        function postConvert(image, data) {
          if (image.type === GL_HALF_FLOAT_OES) {
            image.data = convertToHalfFloat(data);
            pool.freeType(data);
          } else {
            image.data = data;
          }
        }
        function transposeData(image, array, strideX, strideY, strideC, offset) {
          var w = image.width;
          var h = image.height;
          var c = image.channels;
          var n = w * h * c;
          var data = preConvert(image, n);
          var p = 0;
          for (var i = 0; i < h; ++i) {
            for (var j = 0; j < w; ++j) {
              for (var k = 0; k < c; ++k) {
                data[p++] = array[strideX * j + strideY * i + strideC * k + offset];
              }
            }
          }
          postConvert(image, data);
        }
        function getTextureSize(format, type, width, height, isMipmap, isCube) {
          var s;
          if (typeof FORMAT_SIZES_SPECIAL[format] !== "undefined") {
            s = FORMAT_SIZES_SPECIAL[format];
          } else {
            s = FORMAT_CHANNELS[format] * TYPE_SIZES[type];
          }
          if (isCube) {
            s *= 6;
          }
          if (isMipmap) {
            var total = 0;
            var w = width;
            while (w >= 1) {
              total += s * w * w;
              w /= 2;
            }
            return total;
          } else {
            return s * width * height;
          }
        }
        function createTextureSet(gl2, extensions, limits, reglPoll, contextState, stats2, config) {
          var mipmapHint = {
            "don't care": GL_DONT_CARE,
            "dont care": GL_DONT_CARE,
            "nice": GL_NICEST,
            "fast": GL_FASTEST
          };
          var wrapModes = {
            "repeat": GL_REPEAT,
            "clamp": GL_CLAMP_TO_EDGE,
            "mirror": GL_MIRRORED_REPEAT
          };
          var magFilters = {
            "nearest": GL_NEAREST,
            "linear": GL_LINEAR
          };
          var minFilters = extend2({
            "mipmap": GL_LINEAR_MIPMAP_LINEAR,
            "nearest mipmap nearest": GL_NEAREST_MIPMAP_NEAREST,
            "linear mipmap nearest": GL_LINEAR_MIPMAP_NEAREST,
            "nearest mipmap linear": GL_NEAREST_MIPMAP_LINEAR,
            "linear mipmap linear": GL_LINEAR_MIPMAP_LINEAR
          }, magFilters);
          var colorSpace = {
            "none": 0,
            "browser": GL_BROWSER_DEFAULT_WEBGL
          };
          var textureTypes = {
            "uint8": GL_UNSIGNED_BYTE$4,
            "rgba4": GL_UNSIGNED_SHORT_4_4_4_4,
            "rgb565": GL_UNSIGNED_SHORT_5_6_5,
            "rgb5 a1": GL_UNSIGNED_SHORT_5_5_5_1
          };
          var textureFormats = {
            "alpha": GL_ALPHA,
            "luminance": GL_LUMINANCE,
            "luminance alpha": GL_LUMINANCE_ALPHA,
            "rgb": GL_RGB,
            "rgba": GL_RGBA$1,
            "rgba4": GL_RGBA4,
            "rgb5 a1": GL_RGB5_A1,
            "rgb565": GL_RGB565
          };
          var compressedTextureFormats = {};
          if (extensions.ext_srgb) {
            textureFormats.srgb = GL_SRGB_EXT;
            textureFormats.srgba = GL_SRGB_ALPHA_EXT;
          }
          if (extensions.oes_texture_float) {
            textureTypes.float32 = textureTypes.float = GL_FLOAT$3;
          }
          if (extensions.oes_texture_half_float) {
            textureTypes["float16"] = textureTypes["half float"] = GL_HALF_FLOAT_OES;
          }
          if (extensions.webgl_depth_texture) {
            extend2(textureFormats, {
              "depth": GL_DEPTH_COMPONENT,
              "depth stencil": GL_DEPTH_STENCIL
            });
            extend2(textureTypes, {
              "uint16": GL_UNSIGNED_SHORT$2,
              "uint32": GL_UNSIGNED_INT$2,
              "depth stencil": GL_UNSIGNED_INT_24_8_WEBGL
            });
          }
          if (extensions.webgl_compressed_texture_s3tc) {
            extend2(compressedTextureFormats, {
              "rgb s3tc dxt1": GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
              "rgba s3tc dxt1": GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
              "rgba s3tc dxt3": GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
              "rgba s3tc dxt5": GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
            });
          }
          if (extensions.webgl_compressed_texture_atc) {
            extend2(compressedTextureFormats, {
              "rgb atc": GL_COMPRESSED_RGB_ATC_WEBGL,
              "rgba atc explicit alpha": GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL,
              "rgba atc interpolated alpha": GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL
            });
          }
          if (extensions.webgl_compressed_texture_pvrtc) {
            extend2(compressedTextureFormats, {
              "rgb pvrtc 4bppv1": GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,
              "rgb pvrtc 2bppv1": GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG,
              "rgba pvrtc 4bppv1": GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,
              "rgba pvrtc 2bppv1": GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
            });
          }
          if (extensions.webgl_compressed_texture_etc1) {
            compressedTextureFormats["rgb etc1"] = GL_COMPRESSED_RGB_ETC1_WEBGL;
          }
          var supportedCompressedFormats = Array.prototype.slice.call(
            gl2.getParameter(GL_COMPRESSED_TEXTURE_FORMATS)
          );
          Object.keys(compressedTextureFormats).forEach(function(name2) {
            var format = compressedTextureFormats[name2];
            if (supportedCompressedFormats.indexOf(format) >= 0) {
              textureFormats[name2] = format;
            }
          });
          var supportedFormats = Object.keys(textureFormats);
          limits.textureFormats = supportedFormats;
          var textureFormatsInvert = [];
          Object.keys(textureFormats).forEach(function(key) {
            var val = textureFormats[key];
            textureFormatsInvert[val] = key;
          });
          var textureTypesInvert = [];
          Object.keys(textureTypes).forEach(function(key) {
            var val = textureTypes[key];
            textureTypesInvert[val] = key;
          });
          var magFiltersInvert = [];
          Object.keys(magFilters).forEach(function(key) {
            var val = magFilters[key];
            magFiltersInvert[val] = key;
          });
          var minFiltersInvert = [];
          Object.keys(minFilters).forEach(function(key) {
            var val = minFilters[key];
            minFiltersInvert[val] = key;
          });
          var wrapModesInvert = [];
          Object.keys(wrapModes).forEach(function(key) {
            var val = wrapModes[key];
            wrapModesInvert[val] = key;
          });
          var colorFormats = supportedFormats.reduce(function(color2, key) {
            var glenum = textureFormats[key];
            if (glenum === GL_LUMINANCE || glenum === GL_ALPHA || glenum === GL_LUMINANCE || glenum === GL_LUMINANCE_ALPHA || glenum === GL_DEPTH_COMPONENT || glenum === GL_DEPTH_STENCIL || extensions.ext_srgb && (glenum === GL_SRGB_EXT || glenum === GL_SRGB_ALPHA_EXT)) {
              color2[glenum] = glenum;
            } else if (glenum === GL_RGB5_A1 || key.indexOf("rgba") >= 0) {
              color2[glenum] = GL_RGBA$1;
            } else {
              color2[glenum] = GL_RGB;
            }
            return color2;
          }, {});
          function TexFlags() {
            this.internalformat = GL_RGBA$1;
            this.format = GL_RGBA$1;
            this.type = GL_UNSIGNED_BYTE$4;
            this.compressed = false;
            this.premultiplyAlpha = false;
            this.flipY = false;
            this.unpackAlignment = 1;
            this.colorSpace = GL_BROWSER_DEFAULT_WEBGL;
            this.width = 0;
            this.height = 0;
            this.channels = 0;
          }
          function copyFlags(result, other) {
            result.internalformat = other.internalformat;
            result.format = other.format;
            result.type = other.type;
            result.compressed = other.compressed;
            result.premultiplyAlpha = other.premultiplyAlpha;
            result.flipY = other.flipY;
            result.unpackAlignment = other.unpackAlignment;
            result.colorSpace = other.colorSpace;
            result.width = other.width;
            result.height = other.height;
            result.channels = other.channels;
          }
          function parseFlags(flags, options) {
            if (typeof options !== "object" || !options) {
              return;
            }
            if ("premultiplyAlpha" in options) {
              flags.premultiplyAlpha = options.premultiplyAlpha;
            }
            if ("flipY" in options) {
              flags.flipY = options.flipY;
            }
            if ("alignment" in options) {
              flags.unpackAlignment = options.alignment;
            }
            if ("colorSpace" in options) {
              flags.colorSpace = colorSpace[options.colorSpace];
            }
            if ("type" in options) {
              var type = options.type;
              flags.type = textureTypes[type];
            }
            var w = flags.width;
            var h = flags.height;
            var c = flags.channels;
            var hasChannels = false;
            if ("shape" in options) {
              w = options.shape[0];
              h = options.shape[1];
              if (options.shape.length === 3) {
                c = options.shape[2];
                hasChannels = true;
              }
            } else {
              if ("radius" in options) {
                w = h = options.radius;
              }
              if ("width" in options) {
                w = options.width;
              }
              if ("height" in options) {
                h = options.height;
              }
              if ("channels" in options) {
                c = options.channels;
                hasChannels = true;
              }
            }
            flags.width = w | 0;
            flags.height = h | 0;
            flags.channels = c | 0;
            var hasFormat = false;
            if ("format" in options) {
              var formatStr = options.format;
              var internalformat = flags.internalformat = textureFormats[formatStr];
              flags.format = colorFormats[internalformat];
              if (formatStr in textureTypes) {
                if (!("type" in options)) {
                  flags.type = textureTypes[formatStr];
                }
              }
              if (formatStr in compressedTextureFormats) {
                flags.compressed = true;
              }
              hasFormat = true;
            }
            if (!hasChannels && hasFormat) {
              flags.channels = FORMAT_CHANNELS[flags.format];
            } else if (hasChannels && !hasFormat) {
              if (flags.channels !== CHANNELS_FORMAT[flags.format]) {
                flags.format = flags.internalformat = CHANNELS_FORMAT[flags.channels];
              }
            } else if (hasFormat && hasChannels) {
            }
          }
          function setFlags(flags) {
            gl2.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL, flags.flipY);
            gl2.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, flags.premultiplyAlpha);
            gl2.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL, flags.colorSpace);
            gl2.pixelStorei(GL_UNPACK_ALIGNMENT, flags.unpackAlignment);
          }
          function TexImage() {
            TexFlags.call(this);
            this.xOffset = 0;
            this.yOffset = 0;
            this.data = null;
            this.needsFree = false;
            this.element = null;
            this.needsCopy = false;
          }
          function parseImage(image, options) {
            var data = null;
            if (isPixelData(options)) {
              data = options;
            } else if (options) {
              parseFlags(image, options);
              if ("x" in options) {
                image.xOffset = options.x | 0;
              }
              if ("y" in options) {
                image.yOffset = options.y | 0;
              }
              if (isPixelData(options.data)) {
                data = options.data;
              }
            }
            if (options.copy) {
              var viewW = contextState.viewportWidth;
              var viewH = contextState.viewportHeight;
              image.width = image.width || viewW - image.xOffset;
              image.height = image.height || viewH - image.yOffset;
              image.needsCopy = true;
            } else if (!data) {
              image.width = image.width || 1;
              image.height = image.height || 1;
              image.channels = image.channels || 4;
            } else if (isTypedArray(data)) {
              image.channels = image.channels || 4;
              image.data = data;
              if (!("type" in options) && image.type === GL_UNSIGNED_BYTE$4) {
                image.type = typedArrayCode$1(data);
              }
            } else if (isNumericArray(data)) {
              image.channels = image.channels || 4;
              convertData(image, data);
              image.alignment = 1;
              image.needsFree = true;
            } else if (isNDArrayLike(data)) {
              var array = data.data;
              if (!Array.isArray(array) && image.type === GL_UNSIGNED_BYTE$4) {
                image.type = typedArrayCode$1(array);
              }
              var shape = data.shape;
              var stride = data.stride;
              var shapeX, shapeY, shapeC, strideX, strideY, strideC;
              if (shape.length === 3) {
                shapeC = shape[2];
                strideC = stride[2];
              } else {
                shapeC = 1;
                strideC = 1;
              }
              shapeX = shape[0];
              shapeY = shape[1];
              strideX = stride[0];
              strideY = stride[1];
              image.alignment = 1;
              image.width = shapeX;
              image.height = shapeY;
              image.channels = shapeC;
              image.format = image.internalformat = CHANNELS_FORMAT[shapeC];
              image.needsFree = true;
              transposeData(image, array, strideX, strideY, strideC, data.offset);
            } else if (isCanvasElement(data) || isOffscreenCanvas(data) || isContext2D(data)) {
              if (isCanvasElement(data) || isOffscreenCanvas(data)) {
                image.element = data;
              } else {
                image.element = data.canvas;
              }
              image.width = image.element.width;
              image.height = image.element.height;
              image.channels = 4;
            } else if (isBitmap(data)) {
              image.element = data;
              image.width = data.width;
              image.height = data.height;
              image.channels = 4;
            } else if (isImageElement(data)) {
              image.element = data;
              image.width = data.naturalWidth;
              image.height = data.naturalHeight;
              image.channels = 4;
            } else if (isVideoElement(data)) {
              image.element = data;
              image.width = data.videoWidth;
              image.height = data.videoHeight;
              image.channels = 4;
            } else if (isRectArray(data)) {
              var w = image.width || data[0].length;
              var h = image.height || data.length;
              var c = image.channels;
              if (isArrayLike(data[0][0])) {
                c = c || data[0][0].length;
              } else {
                c = c || 1;
              }
              var arrayShape2 = flattenUtils.shape(data);
              var n = 1;
              for (var dd = 0; dd < arrayShape2.length; ++dd) {
                n *= arrayShape2[dd];
              }
              var allocData = preConvert(image, n);
              flattenUtils.flatten(data, arrayShape2, "", allocData);
              postConvert(image, allocData);
              image.alignment = 1;
              image.width = w;
              image.height = h;
              image.channels = c;
              image.format = image.internalformat = CHANNELS_FORMAT[c];
              image.needsFree = true;
            }
            if (image.type === GL_FLOAT$3) {
            } else if (image.type === GL_HALF_FLOAT_OES) {
            }
          }
          function setImage(info, target, miplevel) {
            var element = info.element;
            var data = info.data;
            var internalformat = info.internalformat;
            var format = info.format;
            var type = info.type;
            var width = info.width;
            var height = info.height;
            setFlags(info);
            if (element) {
              gl2.texImage2D(target, miplevel, format, format, type, element);
            } else if (info.compressed) {
              gl2.compressedTexImage2D(target, miplevel, internalformat, width, height, 0, data);
            } else if (info.needsCopy) {
              reglPoll();
              gl2.copyTexImage2D(
                target,
                miplevel,
                format,
                info.xOffset,
                info.yOffset,
                width,
                height,
                0
              );
            } else {
              gl2.texImage2D(target, miplevel, format, width, height, 0, format, type, data || null);
            }
          }
          function setSubImage(info, target, x, y, miplevel) {
            var element = info.element;
            var data = info.data;
            var internalformat = info.internalformat;
            var format = info.format;
            var type = info.type;
            var width = info.width;
            var height = info.height;
            setFlags(info);
            if (element) {
              gl2.texSubImage2D(
                target,
                miplevel,
                x,
                y,
                format,
                type,
                element
              );
            } else if (info.compressed) {
              gl2.compressedTexSubImage2D(
                target,
                miplevel,
                x,
                y,
                internalformat,
                width,
                height,
                data
              );
            } else if (info.needsCopy) {
              reglPoll();
              gl2.copyTexSubImage2D(
                target,
                miplevel,
                x,
                y,
                info.xOffset,
                info.yOffset,
                width,
                height
              );
            } else {
              gl2.texSubImage2D(
                target,
                miplevel,
                x,
                y,
                width,
                height,
                format,
                type,
                data
              );
            }
          }
          var imagePool = [];
          function allocImage() {
            return imagePool.pop() || new TexImage();
          }
          function freeImage(image) {
            if (image.needsFree) {
              pool.freeType(image.data);
            }
            TexImage.call(image);
            imagePool.push(image);
          }
          function MipMap() {
            TexFlags.call(this);
            this.genMipmaps = false;
            this.mipmapHint = GL_DONT_CARE;
            this.mipmask = 0;
            this.images = Array(16);
          }
          function parseMipMapFromShape(mipmap, width, height) {
            var img = mipmap.images[0] = allocImage();
            mipmap.mipmask = 1;
            img.width = mipmap.width = width;
            img.height = mipmap.height = height;
            img.channels = mipmap.channels = 4;
          }
          function parseMipMapFromObject(mipmap, options) {
            var imgData = null;
            if (isPixelData(options)) {
              imgData = mipmap.images[0] = allocImage();
              copyFlags(imgData, mipmap);
              parseImage(imgData, options);
              mipmap.mipmask = 1;
            } else {
              parseFlags(mipmap, options);
              if (Array.isArray(options.mipmap)) {
                var mipData = options.mipmap;
                for (var i = 0; i < mipData.length; ++i) {
                  imgData = mipmap.images[i] = allocImage();
                  copyFlags(imgData, mipmap);
                  imgData.width >>= i;
                  imgData.height >>= i;
                  parseImage(imgData, mipData[i]);
                  mipmap.mipmask |= 1 << i;
                }
              } else {
                imgData = mipmap.images[0] = allocImage();
                copyFlags(imgData, mipmap);
                parseImage(imgData, options);
                mipmap.mipmask = 1;
              }
            }
            copyFlags(mipmap, mipmap.images[0]);
            if (mipmap.compressed && (mipmap.internalformat === GL_COMPRESSED_RGB_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT3_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)) {
            }
          }
          function setMipMap(mipmap, target) {
            var images = mipmap.images;
            for (var i = 0; i < images.length; ++i) {
              if (!images[i]) {
                return;
              }
              setImage(images[i], target, i);
            }
          }
          var mipPool = [];
          function allocMipMap() {
            var result = mipPool.pop() || new MipMap();
            TexFlags.call(result);
            result.mipmask = 0;
            for (var i = 0; i < 16; ++i) {
              result.images[i] = null;
            }
            return result;
          }
          function freeMipMap(mipmap) {
            var images = mipmap.images;
            for (var i = 0; i < images.length; ++i) {
              if (images[i]) {
                freeImage(images[i]);
              }
              images[i] = null;
            }
            mipPool.push(mipmap);
          }
          function TexInfo() {
            this.minFilter = GL_NEAREST;
            this.magFilter = GL_NEAREST;
            this.wrapS = GL_CLAMP_TO_EDGE;
            this.wrapT = GL_CLAMP_TO_EDGE;
            this.anisotropic = 1;
            this.genMipmaps = false;
            this.mipmapHint = GL_DONT_CARE;
          }
          function parseTexInfo(info, options) {
            if ("min" in options) {
              var minFilter = options.min;
              info.minFilter = minFilters[minFilter];
              if (MIPMAP_FILTERS.indexOf(info.minFilter) >= 0 && !("faces" in options)) {
                info.genMipmaps = true;
              }
            }
            if ("mag" in options) {
              var magFilter = options.mag;
              info.magFilter = magFilters[magFilter];
            }
            var wrapS = info.wrapS;
            var wrapT = info.wrapT;
            if ("wrap" in options) {
              var wrap = options.wrap;
              if (typeof wrap === "string") {
                wrapS = wrapT = wrapModes[wrap];
              } else if (Array.isArray(wrap)) {
                wrapS = wrapModes[wrap[0]];
                wrapT = wrapModes[wrap[1]];
              }
            } else {
              if ("wrapS" in options) {
                var optWrapS = options.wrapS;
                wrapS = wrapModes[optWrapS];
              }
              if ("wrapT" in options) {
                var optWrapT = options.wrapT;
                wrapT = wrapModes[optWrapT];
              }
            }
            info.wrapS = wrapS;
            info.wrapT = wrapT;
            if ("anisotropic" in options) {
              var anisotropic = options.anisotropic;
              info.anisotropic = options.anisotropic;
            }
            if ("mipmap" in options) {
              var hasMipMap = false;
              switch (typeof options.mipmap) {
                case "string":
                  info.mipmapHint = mipmapHint[options.mipmap];
                  info.genMipmaps = true;
                  hasMipMap = true;
                  break;
                case "boolean":
                  hasMipMap = info.genMipmaps = options.mipmap;
                  break;
                case "object":
                  info.genMipmaps = false;
                  hasMipMap = true;
                  break;
                default:
              }
              if (hasMipMap && !("min" in options)) {
                info.minFilter = GL_NEAREST_MIPMAP_NEAREST;
              }
            }
          }
          function setTexInfo(info, target) {
            gl2.texParameteri(target, GL_TEXTURE_MIN_FILTER, info.minFilter);
            gl2.texParameteri(target, GL_TEXTURE_MAG_FILTER, info.magFilter);
            gl2.texParameteri(target, GL_TEXTURE_WRAP_S, info.wrapS);
            gl2.texParameteri(target, GL_TEXTURE_WRAP_T, info.wrapT);
            if (extensions.ext_texture_filter_anisotropic) {
              gl2.texParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, info.anisotropic);
            }
            if (info.genMipmaps) {
              gl2.hint(GL_GENERATE_MIPMAP_HINT, info.mipmapHint);
              gl2.generateMipmap(target);
            }
          }
          var textureCount = 0;
          var textureSet = {};
          var numTexUnits = limits.maxTextureUnits;
          var textureUnits = Array(numTexUnits).map(function() {
            return null;
          });
          function REGLTexture(target) {
            TexFlags.call(this);
            this.mipmask = 0;
            this.internalformat = GL_RGBA$1;
            this.id = textureCount++;
            this.refCount = 1;
            this.target = target;
            this.texture = gl2.createTexture();
            this.unit = -1;
            this.bindCount = 0;
            this.texInfo = new TexInfo();
            if (config.profile) {
              this.stats = { size: 0 };
            }
          }
          function tempBind(texture) {
            gl2.activeTexture(GL_TEXTURE0$1);
            gl2.bindTexture(texture.target, texture.texture);
          }
          function tempRestore() {
            var prev = textureUnits[0];
            if (prev) {
              gl2.bindTexture(prev.target, prev.texture);
            } else {
              gl2.bindTexture(GL_TEXTURE_2D$1, null);
            }
          }
          function destroy(texture) {
            var handle = texture.texture;
            var unit = texture.unit;
            var target = texture.target;
            if (unit >= 0) {
              gl2.activeTexture(GL_TEXTURE0$1 + unit);
              gl2.bindTexture(target, null);
              textureUnits[unit] = null;
            }
            gl2.deleteTexture(handle);
            texture.texture = null;
            texture.params = null;
            texture.pixels = null;
            texture.refCount = 0;
            delete textureSet[texture.id];
            stats2.textureCount--;
          }
          extend2(REGLTexture.prototype, {
            bind: function() {
              var texture = this;
              texture.bindCount += 1;
              var unit = texture.unit;
              if (unit < 0) {
                for (var i = 0; i < numTexUnits; ++i) {
                  var other = textureUnits[i];
                  if (other) {
                    if (other.bindCount > 0) {
                      continue;
                    }
                    other.unit = -1;
                  }
                  textureUnits[i] = texture;
                  unit = i;
                  break;
                }
                if (unit >= numTexUnits) {
                }
                if (config.profile && stats2.maxTextureUnits < unit + 1) {
                  stats2.maxTextureUnits = unit + 1;
                }
                texture.unit = unit;
                gl2.activeTexture(GL_TEXTURE0$1 + unit);
                gl2.bindTexture(texture.target, texture.texture);
              }
              return unit;
            },
            unbind: function() {
              this.bindCount -= 1;
            },
            decRef: function() {
              if (--this.refCount <= 0) {
                destroy(this);
              }
            }
          });
          function createTexture2D(a, b) {
            var texture = new REGLTexture(GL_TEXTURE_2D$1);
            textureSet[texture.id] = texture;
            stats2.textureCount++;
            function reglTexture2D(a2, b2) {
              var texInfo = texture.texInfo;
              TexInfo.call(texInfo);
              var mipData = allocMipMap();
              if (typeof a2 === "number") {
                if (typeof b2 === "number") {
                  parseMipMapFromShape(mipData, a2 | 0, b2 | 0);
                } else {
                  parseMipMapFromShape(mipData, a2 | 0, a2 | 0);
                }
              } else if (a2) {
                parseTexInfo(texInfo, a2);
                parseMipMapFromObject(mipData, a2);
              } else {
                parseMipMapFromShape(mipData, 1, 1);
              }
              if (texInfo.genMipmaps) {
                mipData.mipmask = (mipData.width << 1) - 1;
              }
              texture.mipmask = mipData.mipmask;
              copyFlags(texture, mipData);
              texture.internalformat = mipData.internalformat;
              reglTexture2D.width = mipData.width;
              reglTexture2D.height = mipData.height;
              tempBind(texture);
              setMipMap(mipData, GL_TEXTURE_2D$1);
              setTexInfo(texInfo, GL_TEXTURE_2D$1);
              tempRestore();
              freeMipMap(mipData);
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  mipData.width,
                  mipData.height,
                  texInfo.genMipmaps,
                  false
                );
              }
              reglTexture2D.format = textureFormatsInvert[texture.internalformat];
              reglTexture2D.type = textureTypesInvert[texture.type];
              reglTexture2D.mag = magFiltersInvert[texInfo.magFilter];
              reglTexture2D.min = minFiltersInvert[texInfo.minFilter];
              reglTexture2D.wrapS = wrapModesInvert[texInfo.wrapS];
              reglTexture2D.wrapT = wrapModesInvert[texInfo.wrapT];
              return reglTexture2D;
            }
            function subimage(image, x_, y_, level_) {
              var x = x_ | 0;
              var y = y_ | 0;
              var level = level_ | 0;
              var imageData = allocImage();
              copyFlags(imageData, texture);
              imageData.width = 0;
              imageData.height = 0;
              parseImage(imageData, image);
              imageData.width = imageData.width || (texture.width >> level) - x;
              imageData.height = imageData.height || (texture.height >> level) - y;
              tempBind(texture);
              setSubImage(imageData, GL_TEXTURE_2D$1, x, y, level);
              tempRestore();
              freeImage(imageData);
              return reglTexture2D;
            }
            function resize(w_, h_) {
              var w = w_ | 0;
              var h = h_ | 0 || w;
              if (w === texture.width && h === texture.height) {
                return reglTexture2D;
              }
              reglTexture2D.width = texture.width = w;
              reglTexture2D.height = texture.height = h;
              tempBind(texture);
              for (var i = 0; texture.mipmask >> i; ++i) {
                var _w = w >> i;
                var _h = h >> i;
                if (!_w || !_h) break;
                gl2.texImage2D(
                  GL_TEXTURE_2D$1,
                  i,
                  texture.format,
                  _w,
                  _h,
                  0,
                  texture.format,
                  texture.type,
                  null
                );
              }
              tempRestore();
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  w,
                  h,
                  false,
                  false
                );
              }
              return reglTexture2D;
            }
            reglTexture2D(a, b);
            reglTexture2D.subimage = subimage;
            reglTexture2D.resize = resize;
            reglTexture2D._reglType = "texture2d";
            reglTexture2D._texture = texture;
            if (config.profile) {
              reglTexture2D.stats = texture.stats;
            }
            reglTexture2D.destroy = function() {
              texture.decRef();
            };
            return reglTexture2D;
          }
          function createTextureCube(a0, a1, a2, a3, a4, a5) {
            var texture = new REGLTexture(GL_TEXTURE_CUBE_MAP$1);
            textureSet[texture.id] = texture;
            stats2.cubeCount++;
            var faces = new Array(6);
            function reglTextureCube(a02, a12, a22, a32, a42, a52) {
              var i;
              var texInfo = texture.texInfo;
              TexInfo.call(texInfo);
              for (i = 0; i < 6; ++i) {
                faces[i] = allocMipMap();
              }
              if (typeof a02 === "number" || !a02) {
                var s = a02 | 0 || 1;
                for (i = 0; i < 6; ++i) {
                  parseMipMapFromShape(faces[i], s, s);
                }
              } else if (typeof a02 === "object") {
                if (a12) {
                  parseMipMapFromObject(faces[0], a02);
                  parseMipMapFromObject(faces[1], a12);
                  parseMipMapFromObject(faces[2], a22);
                  parseMipMapFromObject(faces[3], a32);
                  parseMipMapFromObject(faces[4], a42);
                  parseMipMapFromObject(faces[5], a52);
                } else {
                  parseTexInfo(texInfo, a02);
                  parseFlags(texture, a02);
                  if ("faces" in a02) {
                    var faceInput = a02.faces;
                    for (i = 0; i < 6; ++i) {
                      copyFlags(faces[i], texture);
                      parseMipMapFromObject(faces[i], faceInput[i]);
                    }
                  } else {
                    for (i = 0; i < 6; ++i) {
                      parseMipMapFromObject(faces[i], a02);
                    }
                  }
                }
              } else {
              }
              copyFlags(texture, faces[0]);
              if (texInfo.genMipmaps) {
                texture.mipmask = (faces[0].width << 1) - 1;
              } else {
                texture.mipmask = faces[0].mipmask;
              }
              texture.internalformat = faces[0].internalformat;
              reglTextureCube.width = faces[0].width;
              reglTextureCube.height = faces[0].height;
              tempBind(texture);
              for (i = 0; i < 6; ++i) {
                setMipMap(faces[i], GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i);
              }
              setTexInfo(texInfo, GL_TEXTURE_CUBE_MAP$1);
              tempRestore();
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  reglTextureCube.width,
                  reglTextureCube.height,
                  texInfo.genMipmaps,
                  true
                );
              }
              reglTextureCube.format = textureFormatsInvert[texture.internalformat];
              reglTextureCube.type = textureTypesInvert[texture.type];
              reglTextureCube.mag = magFiltersInvert[texInfo.magFilter];
              reglTextureCube.min = minFiltersInvert[texInfo.minFilter];
              reglTextureCube.wrapS = wrapModesInvert[texInfo.wrapS];
              reglTextureCube.wrapT = wrapModesInvert[texInfo.wrapT];
              for (i = 0; i < 6; ++i) {
                freeMipMap(faces[i]);
              }
              return reglTextureCube;
            }
            function subimage(face, image, x_, y_, level_) {
              var x = x_ | 0;
              var y = y_ | 0;
              var level = level_ | 0;
              var imageData = allocImage();
              copyFlags(imageData, texture);
              imageData.width = 0;
              imageData.height = 0;
              parseImage(imageData, image);
              imageData.width = imageData.width || (texture.width >> level) - x;
              imageData.height = imageData.height || (texture.height >> level) - y;
              tempBind(texture);
              setSubImage(imageData, GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + face, x, y, level);
              tempRestore();
              freeImage(imageData);
              return reglTextureCube;
            }
            function resize(radius_) {
              var radius = radius_ | 0;
              if (radius === texture.width) {
                return;
              }
              reglTextureCube.width = texture.width = radius;
              reglTextureCube.height = texture.height = radius;
              tempBind(texture);
              for (var i = 0; i < 6; ++i) {
                for (var j = 0; texture.mipmask >> j; ++j) {
                  gl2.texImage2D(
                    GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i,
                    j,
                    texture.format,
                    radius >> j,
                    radius >> j,
                    0,
                    texture.format,
                    texture.type,
                    null
                  );
                }
              }
              tempRestore();
              if (config.profile) {
                texture.stats.size = getTextureSize(
                  texture.internalformat,
                  texture.type,
                  reglTextureCube.width,
                  reglTextureCube.height,
                  false,
                  true
                );
              }
              return reglTextureCube;
            }
            reglTextureCube(a0, a1, a2, a3, a4, a5);
            reglTextureCube.subimage = subimage;
            reglTextureCube.resize = resize;
            reglTextureCube._reglType = "textureCube";
            reglTextureCube._texture = texture;
            if (config.profile) {
              reglTextureCube.stats = texture.stats;
            }
            reglTextureCube.destroy = function() {
              texture.decRef();
            };
            return reglTextureCube;
          }
          function destroyTextures() {
            for (var i = 0; i < numTexUnits; ++i) {
              gl2.activeTexture(GL_TEXTURE0$1 + i);
              gl2.bindTexture(GL_TEXTURE_2D$1, null);
              textureUnits[i] = null;
            }
            values(textureSet).forEach(destroy);
            stats2.cubeCount = 0;
            stats2.textureCount = 0;
          }
          if (config.profile) {
            stats2.getTotalTextureSize = function() {
              var total = 0;
              Object.keys(textureSet).forEach(function(key) {
                total += textureSet[key].stats.size;
              });
              return total;
            };
          }
          function restoreTextures() {
            for (var i = 0; i < numTexUnits; ++i) {
              var tex = textureUnits[i];
              if (tex) {
                tex.bindCount = 0;
                tex.unit = -1;
                textureUnits[i] = null;
              }
            }
            values(textureSet).forEach(function(texture) {
              texture.texture = gl2.createTexture();
              gl2.bindTexture(texture.target, texture.texture);
              for (var i2 = 0; i2 < 32; ++i2) {
                if ((texture.mipmask & 1 << i2) === 0) {
                  continue;
                }
                if (texture.target === GL_TEXTURE_2D$1) {
                  gl2.texImage2D(
                    GL_TEXTURE_2D$1,
                    i2,
                    texture.internalformat,
                    texture.width >> i2,
                    texture.height >> i2,
                    0,
                    texture.internalformat,
                    texture.type,
                    null
                  );
                } else {
                  for (var j = 0; j < 6; ++j) {
                    gl2.texImage2D(
                      GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + j,
                      i2,
                      texture.internalformat,
                      texture.width >> i2,
                      texture.height >> i2,
                      0,
                      texture.internalformat,
                      texture.type,
                      null
                    );
                  }
                }
              }
              setTexInfo(texture.texInfo, texture.target);
            });
          }
          function refreshTextures() {
            for (var i = 0; i < numTexUnits; ++i) {
              var tex = textureUnits[i];
              if (tex) {
                tex.bindCount = 0;
                tex.unit = -1;
                textureUnits[i] = null;
              }
              gl2.activeTexture(GL_TEXTURE0$1 + i);
              gl2.bindTexture(GL_TEXTURE_2D$1, null);
              gl2.bindTexture(GL_TEXTURE_CUBE_MAP$1, null);
            }
          }
          return {
            create2D: createTexture2D,
            createCube: createTextureCube,
            clear: destroyTextures,
            getTexture: function(wrapper) {
              return null;
            },
            restore: restoreTextures,
            refresh: refreshTextures
          };
        }
        var GL_RENDERBUFFER = 36161;
        var GL_RGBA4$1 = 32854;
        var GL_RGB5_A1$1 = 32855;
        var GL_RGB565$1 = 36194;
        var GL_DEPTH_COMPONENT16 = 33189;
        var GL_STENCIL_INDEX8 = 36168;
        var GL_DEPTH_STENCIL$1 = 34041;
        var GL_SRGB8_ALPHA8_EXT = 35907;
        var GL_RGBA32F_EXT = 34836;
        var GL_RGBA16F_EXT = 34842;
        var GL_RGB16F_EXT = 34843;
        var FORMAT_SIZES = [];
        FORMAT_SIZES[GL_RGBA4$1] = 2;
        FORMAT_SIZES[GL_RGB5_A1$1] = 2;
        FORMAT_SIZES[GL_RGB565$1] = 2;
        FORMAT_SIZES[GL_DEPTH_COMPONENT16] = 2;
        FORMAT_SIZES[GL_STENCIL_INDEX8] = 1;
        FORMAT_SIZES[GL_DEPTH_STENCIL$1] = 4;
        FORMAT_SIZES[GL_SRGB8_ALPHA8_EXT] = 4;
        FORMAT_SIZES[GL_RGBA32F_EXT] = 16;
        FORMAT_SIZES[GL_RGBA16F_EXT] = 8;
        FORMAT_SIZES[GL_RGB16F_EXT] = 6;
        function getRenderbufferSize(format, width, height) {
          return FORMAT_SIZES[format] * width * height;
        }
        var wrapRenderbuffers = function(gl2, extensions, limits, stats2, config) {
          var formatTypes = {
            "rgba4": GL_RGBA4$1,
            "rgb565": GL_RGB565$1,
            "rgb5 a1": GL_RGB5_A1$1,
            "depth": GL_DEPTH_COMPONENT16,
            "stencil": GL_STENCIL_INDEX8,
            "depth stencil": GL_DEPTH_STENCIL$1
          };
          if (extensions.ext_srgb) {
            formatTypes["srgba"] = GL_SRGB8_ALPHA8_EXT;
          }
          if (extensions.ext_color_buffer_half_float) {
            formatTypes["rgba16f"] = GL_RGBA16F_EXT;
            formatTypes["rgb16f"] = GL_RGB16F_EXT;
          }
          if (extensions.webgl_color_buffer_float) {
            formatTypes["rgba32f"] = GL_RGBA32F_EXT;
          }
          var formatTypesInvert = [];
          Object.keys(formatTypes).forEach(function(key) {
            var val = formatTypes[key];
            formatTypesInvert[val] = key;
          });
          var renderbufferCount = 0;
          var renderbufferSet = {};
          function REGLRenderbuffer(renderbuffer) {
            this.id = renderbufferCount++;
            this.refCount = 1;
            this.renderbuffer = renderbuffer;
            this.format = GL_RGBA4$1;
            this.width = 0;
            this.height = 0;
            if (config.profile) {
              this.stats = { size: 0 };
            }
          }
          REGLRenderbuffer.prototype.decRef = function() {
            if (--this.refCount <= 0) {
              destroy(this);
            }
          };
          function destroy(rb) {
            var handle = rb.renderbuffer;
            gl2.bindRenderbuffer(GL_RENDERBUFFER, null);
            gl2.deleteRenderbuffer(handle);
            rb.renderbuffer = null;
            rb.refCount = 0;
            delete renderbufferSet[rb.id];
            stats2.renderbufferCount--;
          }
          function createRenderbuffer(a, b) {
            var renderbuffer = new REGLRenderbuffer(gl2.createRenderbuffer());
            renderbufferSet[renderbuffer.id] = renderbuffer;
            stats2.renderbufferCount++;
            function reglRenderbuffer(a2, b2) {
              var w = 0;
              var h = 0;
              var format = GL_RGBA4$1;
              if (typeof a2 === "object" && a2) {
                var options = a2;
                if ("shape" in options) {
                  var shape = options.shape;
                  w = shape[0] | 0;
                  h = shape[1] | 0;
                } else {
                  if ("radius" in options) {
                    w = h = options.radius | 0;
                  }
                  if ("width" in options) {
                    w = options.width | 0;
                  }
                  if ("height" in options) {
                    h = options.height | 0;
                  }
                }
                if ("format" in options) {
                  format = formatTypes[options.format];
                }
              } else if (typeof a2 === "number") {
                w = a2 | 0;
                if (typeof b2 === "number") {
                  h = b2 | 0;
                } else {
                  h = w;
                }
              } else if (!a2) {
                w = h = 1;
              } else {
              }
              if (w === renderbuffer.width && h === renderbuffer.height && format === renderbuffer.format) {
                return;
              }
              reglRenderbuffer.width = renderbuffer.width = w;
              reglRenderbuffer.height = renderbuffer.height = h;
              renderbuffer.format = format;
              gl2.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer);
              gl2.renderbufferStorage(GL_RENDERBUFFER, format, w, h);
              if (config.profile) {
                renderbuffer.stats.size = getRenderbufferSize(renderbuffer.format, renderbuffer.width, renderbuffer.height);
              }
              reglRenderbuffer.format = formatTypesInvert[renderbuffer.format];
              return reglRenderbuffer;
            }
            function resize(w_, h_) {
              var w = w_ | 0;
              var h = h_ | 0 || w;
              if (w === renderbuffer.width && h === renderbuffer.height) {
                return reglRenderbuffer;
              }
              reglRenderbuffer.width = renderbuffer.width = w;
              reglRenderbuffer.height = renderbuffer.height = h;
              gl2.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer);
              gl2.renderbufferStorage(GL_RENDERBUFFER, renderbuffer.format, w, h);
              if (config.profile) {
                renderbuffer.stats.size = getRenderbufferSize(
                  renderbuffer.format,
                  renderbuffer.width,
                  renderbuffer.height
                );
              }
              return reglRenderbuffer;
            }
            reglRenderbuffer(a, b);
            reglRenderbuffer.resize = resize;
            reglRenderbuffer._reglType = "renderbuffer";
            reglRenderbuffer._renderbuffer = renderbuffer;
            if (config.profile) {
              reglRenderbuffer.stats = renderbuffer.stats;
            }
            reglRenderbuffer.destroy = function() {
              renderbuffer.decRef();
            };
            return reglRenderbuffer;
          }
          if (config.profile) {
            stats2.getTotalRenderbufferSize = function() {
              var total = 0;
              Object.keys(renderbufferSet).forEach(function(key) {
                total += renderbufferSet[key].stats.size;
              });
              return total;
            };
          }
          function restoreRenderbuffers() {
            values(renderbufferSet).forEach(function(rb) {
              rb.renderbuffer = gl2.createRenderbuffer();
              gl2.bindRenderbuffer(GL_RENDERBUFFER, rb.renderbuffer);
              gl2.renderbufferStorage(GL_RENDERBUFFER, rb.format, rb.width, rb.height);
            });
            gl2.bindRenderbuffer(GL_RENDERBUFFER, null);
          }
          return {
            create: createRenderbuffer,
            clear: function() {
              values(renderbufferSet).forEach(destroy);
            },
            restore: restoreRenderbuffers
          };
        };
        var GL_FRAMEBUFFER$1 = 36160;
        var GL_RENDERBUFFER$1 = 36161;
        var GL_TEXTURE_2D$2 = 3553;
        var GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 = 34069;
        var GL_COLOR_ATTACHMENT0$1 = 36064;
        var GL_DEPTH_ATTACHMENT = 36096;
        var GL_STENCIL_ATTACHMENT = 36128;
        var GL_DEPTH_STENCIL_ATTACHMENT = 33306;
        var GL_FRAMEBUFFER_COMPLETE$1 = 36053;
        var GL_HALF_FLOAT_OES$1 = 36193;
        var GL_UNSIGNED_BYTE$5 = 5121;
        var GL_FLOAT$4 = 5126;
        var GL_RGB$1 = 6407;
        var GL_RGBA$2 = 6408;
        var textureFormatChannels = [];
        textureFormatChannels[GL_RGBA$2] = 4;
        textureFormatChannels[GL_RGB$1] = 3;
        var textureTypeSizes = [];
        textureTypeSizes[GL_UNSIGNED_BYTE$5] = 1;
        textureTypeSizes[GL_FLOAT$4] = 4;
        textureTypeSizes[GL_HALF_FLOAT_OES$1] = 2;
        function wrapFBOState(gl2, extensions, limits, textureState, renderbufferState, stats2) {
          var framebufferState = {
            cur: null,
            next: null,
            dirty: false,
            setFBO: null
          };
          var colorTextureFormats = ["rgba"];
          var colorRenderbufferFormats = ["rgba4", "rgb565", "rgb5 a1"];
          if (extensions.ext_srgb) {
            colorRenderbufferFormats.push("srgba");
          }
          if (extensions.ext_color_buffer_half_float) {
            colorRenderbufferFormats.push("rgba16f", "rgb16f");
          }
          if (extensions.webgl_color_buffer_float) {
            colorRenderbufferFormats.push("rgba32f");
          }
          var colorTypes = ["uint8"];
          if (extensions.oes_texture_half_float) {
            colorTypes.push("half float", "float16");
          }
          if (extensions.oes_texture_float) {
            colorTypes.push("float", "float32");
          }
          function FramebufferAttachment(target, texture, renderbuffer) {
            this.target = target;
            this.texture = texture;
            this.renderbuffer = renderbuffer;
            var w = 0;
            var h = 0;
            if (texture) {
              w = texture.width;
              h = texture.height;
            } else if (renderbuffer) {
              w = renderbuffer.width;
              h = renderbuffer.height;
            }
            this.width = w;
            this.height = h;
          }
          function decRef(attachment) {
            if (attachment) {
              if (attachment.texture) {
                attachment.texture._texture.decRef();
              }
              if (attachment.renderbuffer) {
                attachment.renderbuffer._renderbuffer.decRef();
              }
            }
          }
          function incRefAndCheckShape(attachment, width, height) {
            if (!attachment) {
              return;
            }
            if (attachment.texture) {
              var texture = attachment.texture._texture;
              var tw = Math.max(1, texture.width);
              var th = Math.max(1, texture.height);
              texture.refCount += 1;
            } else {
              var renderbuffer = attachment.renderbuffer._renderbuffer;
              renderbuffer.refCount += 1;
            }
          }
          function attach(location2, attachment) {
            if (attachment) {
              if (attachment.texture) {
                gl2.framebufferTexture2D(
                  GL_FRAMEBUFFER$1,
                  location2,
                  attachment.target,
                  attachment.texture._texture.texture,
                  0
                );
              } else {
                gl2.framebufferRenderbuffer(
                  GL_FRAMEBUFFER$1,
                  location2,
                  GL_RENDERBUFFER$1,
                  attachment.renderbuffer._renderbuffer.renderbuffer
                );
              }
            }
          }
          function parseAttachment(attachment) {
            var target = GL_TEXTURE_2D$2;
            var texture = null;
            var renderbuffer = null;
            var data = attachment;
            if (typeof attachment === "object") {
              data = attachment.data;
              if ("target" in attachment) {
                target = attachment.target | 0;
              }
            }
            var type = data._reglType;
            if (type === "texture2d") {
              texture = data;
            } else if (type === "textureCube") {
              texture = data;
            } else if (type === "renderbuffer") {
              renderbuffer = data;
              target = GL_RENDERBUFFER$1;
            } else {
            }
            return new FramebufferAttachment(target, texture, renderbuffer);
          }
          function allocAttachment(width, height, isTexture, format, type) {
            if (isTexture) {
              var texture = textureState.create2D({
                width,
                height,
                format,
                type
              });
              texture._texture.refCount = 0;
              return new FramebufferAttachment(GL_TEXTURE_2D$2, texture, null);
            } else {
              var rb = renderbufferState.create({
                width,
                height,
                format
              });
              rb._renderbuffer.refCount = 0;
              return new FramebufferAttachment(GL_RENDERBUFFER$1, null, rb);
            }
          }
          function unwrapAttachment(attachment) {
            return attachment && (attachment.texture || attachment.renderbuffer);
          }
          function resizeAttachment(attachment, w, h) {
            if (attachment) {
              if (attachment.texture) {
                attachment.texture.resize(w, h);
              } else if (attachment.renderbuffer) {
                attachment.renderbuffer.resize(w, h);
              }
              attachment.width = w;
              attachment.height = h;
            }
          }
          var framebufferCount = 0;
          var framebufferSet = {};
          function REGLFramebuffer() {
            this.id = framebufferCount++;
            framebufferSet[this.id] = this;
            this.framebuffer = gl2.createFramebuffer();
            this.width = 0;
            this.height = 0;
            this.colorAttachments = [];
            this.depthAttachment = null;
            this.stencilAttachment = null;
            this.depthStencilAttachment = null;
          }
          function decFBORefs(framebuffer) {
            framebuffer.colorAttachments.forEach(decRef);
            decRef(framebuffer.depthAttachment);
            decRef(framebuffer.stencilAttachment);
            decRef(framebuffer.depthStencilAttachment);
          }
          function destroy(framebuffer) {
            var handle = framebuffer.framebuffer;
            gl2.deleteFramebuffer(handle);
            framebuffer.framebuffer = null;
            stats2.framebufferCount--;
            delete framebufferSet[framebuffer.id];
          }
          function updateFramebuffer(framebuffer) {
            var i;
            gl2.bindFramebuffer(GL_FRAMEBUFFER$1, framebuffer.framebuffer);
            var colorAttachments = framebuffer.colorAttachments;
            for (i = 0; i < colorAttachments.length; ++i) {
              attach(GL_COLOR_ATTACHMENT0$1 + i, colorAttachments[i]);
            }
            for (i = colorAttachments.length; i < limits.maxColorAttachments; ++i) {
              gl2.framebufferTexture2D(
                GL_FRAMEBUFFER$1,
                GL_COLOR_ATTACHMENT0$1 + i,
                GL_TEXTURE_2D$2,
                null,
                0
              );
            }
            gl2.framebufferTexture2D(
              GL_FRAMEBUFFER$1,
              GL_DEPTH_STENCIL_ATTACHMENT,
              GL_TEXTURE_2D$2,
              null,
              0
            );
            gl2.framebufferTexture2D(
              GL_FRAMEBUFFER$1,
              GL_DEPTH_ATTACHMENT,
              GL_TEXTURE_2D$2,
              null,
              0
            );
            gl2.framebufferTexture2D(
              GL_FRAMEBUFFER$1,
              GL_STENCIL_ATTACHMENT,
              GL_TEXTURE_2D$2,
              null,
              0
            );
            attach(GL_DEPTH_ATTACHMENT, framebuffer.depthAttachment);
            attach(GL_STENCIL_ATTACHMENT, framebuffer.stencilAttachment);
            attach(GL_DEPTH_STENCIL_ATTACHMENT, framebuffer.depthStencilAttachment);
            var status = gl2.checkFramebufferStatus(GL_FRAMEBUFFER$1);
            if (!gl2.isContextLost() && status !== GL_FRAMEBUFFER_COMPLETE$1) {
            }
            gl2.bindFramebuffer(GL_FRAMEBUFFER$1, framebufferState.next ? framebufferState.next.framebuffer : null);
            framebufferState.cur = framebufferState.next;
            gl2.getError();
          }
          function createFBO(a0, a1) {
            var framebuffer = new REGLFramebuffer();
            stats2.framebufferCount++;
            function reglFramebuffer(a, b) {
              var i;
              var width = 0;
              var height = 0;
              var needsDepth = true;
              var needsStencil = true;
              var colorBuffer = null;
              var colorTexture = true;
              var colorFormat = "rgba";
              var colorType = "uint8";
              var colorCount = 1;
              var depthBuffer = null;
              var stencilBuffer = null;
              var depthStencilBuffer = null;
              var depthStencilTexture = false;
              if (typeof a === "number") {
                width = a | 0;
                height = b | 0 || width;
              } else if (!a) {
                width = height = 1;
              } else {
                var options = a;
                if ("shape" in options) {
                  var shape = options.shape;
                  width = shape[0];
                  height = shape[1];
                } else {
                  if ("radius" in options) {
                    width = height = options.radius;
                  }
                  if ("width" in options) {
                    width = options.width;
                  }
                  if ("height" in options) {
                    height = options.height;
                  }
                }
                if ("color" in options || "colors" in options) {
                  colorBuffer = options.color || options.colors;
                  if (Array.isArray(colorBuffer)) {
                  }
                }
                if (!colorBuffer) {
                  if ("colorCount" in options) {
                    colorCount = options.colorCount | 0;
                  }
                  if ("colorTexture" in options) {
                    colorTexture = !!options.colorTexture;
                    colorFormat = "rgba4";
                  }
                  if ("colorType" in options) {
                    colorType = options.colorType;
                    if (!colorTexture) {
                      if (colorType === "half float" || colorType === "float16") {
                        colorFormat = "rgba16f";
                      } else if (colorType === "float" || colorType === "float32") {
                        colorFormat = "rgba32f";
                      }
                    } else {
                    }
                  }
                  if ("colorFormat" in options) {
                    colorFormat = options.colorFormat;
                    if (colorTextureFormats.indexOf(colorFormat) >= 0) {
                      colorTexture = true;
                    } else if (colorRenderbufferFormats.indexOf(colorFormat) >= 0) {
                      colorTexture = false;
                    } else {
                    }
                  }
                }
                if ("depthTexture" in options || "depthStencilTexture" in options) {
                  depthStencilTexture = !!(options.depthTexture || options.depthStencilTexture);
                }
                if ("depth" in options) {
                  if (typeof options.depth === "boolean") {
                    needsDepth = options.depth;
                  } else {
                    depthBuffer = options.depth;
                    needsStencil = false;
                  }
                }
                if ("stencil" in options) {
                  if (typeof options.stencil === "boolean") {
                    needsStencil = options.stencil;
                  } else {
                    stencilBuffer = options.stencil;
                    needsDepth = false;
                  }
                }
                if ("depthStencil" in options) {
                  if (typeof options.depthStencil === "boolean") {
                    needsDepth = needsStencil = options.depthStencil;
                  } else {
                    depthStencilBuffer = options.depthStencil;
                    needsDepth = false;
                    needsStencil = false;
                  }
                }
              }
              var colorAttachments = null;
              var depthAttachment = null;
              var stencilAttachment = null;
              var depthStencilAttachment = null;
              if (Array.isArray(colorBuffer)) {
                colorAttachments = colorBuffer.map(parseAttachment);
              } else if (colorBuffer) {
                colorAttachments = [parseAttachment(colorBuffer)];
              } else {
                colorAttachments = new Array(colorCount);
                for (i = 0; i < colorCount; ++i) {
                  colorAttachments[i] = allocAttachment(
                    width,
                    height,
                    colorTexture,
                    colorFormat,
                    colorType
                  );
                }
              }
              width = width || colorAttachments[0].width;
              height = height || colorAttachments[0].height;
              if (depthBuffer) {
                depthAttachment = parseAttachment(depthBuffer);
              } else if (needsDepth && !needsStencil) {
                depthAttachment = allocAttachment(
                  width,
                  height,
                  depthStencilTexture,
                  "depth",
                  "uint32"
                );
              }
              if (stencilBuffer) {
                stencilAttachment = parseAttachment(stencilBuffer);
              } else if (needsStencil && !needsDepth) {
                stencilAttachment = allocAttachment(
                  width,
                  height,
                  false,
                  "stencil",
                  "uint8"
                );
              }
              if (depthStencilBuffer) {
                depthStencilAttachment = parseAttachment(depthStencilBuffer);
              } else if (!depthBuffer && !stencilBuffer && needsStencil && needsDepth) {
                depthStencilAttachment = allocAttachment(
                  width,
                  height,
                  depthStencilTexture,
                  "depth stencil",
                  "depth stencil"
                );
              }
              var commonColorAttachmentSize = null;
              for (i = 0; i < colorAttachments.length; ++i) {
                incRefAndCheckShape(colorAttachments[i], width, height);
                if (colorAttachments[i] && colorAttachments[i].texture) {
                  var colorAttachmentSize = textureFormatChannels[colorAttachments[i].texture._texture.format] * textureTypeSizes[colorAttachments[i].texture._texture.type];
                  if (commonColorAttachmentSize === null) {
                    commonColorAttachmentSize = colorAttachmentSize;
                  } else {
                  }
                }
              }
              incRefAndCheckShape(depthAttachment, width, height);
              incRefAndCheckShape(stencilAttachment, width, height);
              incRefAndCheckShape(depthStencilAttachment, width, height);
              decFBORefs(framebuffer);
              framebuffer.width = width;
              framebuffer.height = height;
              framebuffer.colorAttachments = colorAttachments;
              framebuffer.depthAttachment = depthAttachment;
              framebuffer.stencilAttachment = stencilAttachment;
              framebuffer.depthStencilAttachment = depthStencilAttachment;
              reglFramebuffer.color = colorAttachments.map(unwrapAttachment);
              reglFramebuffer.depth = unwrapAttachment(depthAttachment);
              reglFramebuffer.stencil = unwrapAttachment(stencilAttachment);
              reglFramebuffer.depthStencil = unwrapAttachment(depthStencilAttachment);
              reglFramebuffer.width = framebuffer.width;
              reglFramebuffer.height = framebuffer.height;
              updateFramebuffer(framebuffer);
              return reglFramebuffer;
            }
            function resize(w_, h_) {
              var w = Math.max(w_ | 0, 1);
              var h = Math.max(h_ | 0 || w, 1);
              if (w === framebuffer.width && h === framebuffer.height) {
                return reglFramebuffer;
              }
              var colorAttachments = framebuffer.colorAttachments;
              for (var i = 0; i < colorAttachments.length; ++i) {
                resizeAttachment(colorAttachments[i], w, h);
              }
              resizeAttachment(framebuffer.depthAttachment, w, h);
              resizeAttachment(framebuffer.stencilAttachment, w, h);
              resizeAttachment(framebuffer.depthStencilAttachment, w, h);
              framebuffer.width = reglFramebuffer.width = w;
              framebuffer.height = reglFramebuffer.height = h;
              updateFramebuffer(framebuffer);
              return reglFramebuffer;
            }
            reglFramebuffer(a0, a1);
            return extend2(reglFramebuffer, {
              resize,
              _reglType: "framebuffer",
              _framebuffer: framebuffer,
              destroy: function() {
                destroy(framebuffer);
                decFBORefs(framebuffer);
              },
              use: function(block) {
                framebufferState.setFBO({
                  framebuffer: reglFramebuffer
                }, block);
              }
            });
          }
          function createCubeFBO(options) {
            var faces = Array(6);
            function reglFramebufferCube(a) {
              var i;
              var params = {
                color: null
              };
              var radius = 0;
              var colorBuffer = null;
              var colorFormat = "rgba";
              var colorType = "uint8";
              var colorCount = 1;
              if (typeof a === "number") {
                radius = a | 0;
              } else if (!a) {
                radius = 1;
              } else {
                var options2 = a;
                if ("shape" in options2) {
                  var shape = options2.shape;
                  radius = shape[0];
                } else {
                  if ("radius" in options2) {
                    radius = options2.radius | 0;
                  }
                  if ("width" in options2) {
                    radius = options2.width | 0;
                    if ("height" in options2) {
                    }
                  } else if ("height" in options2) {
                    radius = options2.height | 0;
                  }
                }
                if ("color" in options2 || "colors" in options2) {
                  colorBuffer = options2.color || options2.colors;
                  if (Array.isArray(colorBuffer)) {
                  }
                }
                if (!colorBuffer) {
                  if ("colorCount" in options2) {
                    colorCount = options2.colorCount | 0;
                  }
                  if ("colorType" in options2) {
                    colorType = options2.colorType;
                  }
                  if ("colorFormat" in options2) {
                    colorFormat = options2.colorFormat;
                  }
                }
                if ("depth" in options2) {
                  params.depth = options2.depth;
                }
                if ("stencil" in options2) {
                  params.stencil = options2.stencil;
                }
                if ("depthStencil" in options2) {
                  params.depthStencil = options2.depthStencil;
                }
              }
              var colorCubes;
              if (colorBuffer) {
                if (Array.isArray(colorBuffer)) {
                  colorCubes = [];
                  for (i = 0; i < colorBuffer.length; ++i) {
                    colorCubes[i] = colorBuffer[i];
                  }
                } else {
                  colorCubes = [colorBuffer];
                }
              } else {
                colorCubes = Array(colorCount);
                var cubeMapParams = {
                  radius,
                  format: colorFormat,
                  type: colorType
                };
                for (i = 0; i < colorCount; ++i) {
                  colorCubes[i] = textureState.createCube(cubeMapParams);
                }
              }
              params.color = Array(colorCubes.length);
              for (i = 0; i < colorCubes.length; ++i) {
                var cube = colorCubes[i];
                radius = radius || cube.width;
                params.color[i] = {
                  target: GL_TEXTURE_CUBE_MAP_POSITIVE_X$2,
                  data: colorCubes[i]
                };
              }
              for (i = 0; i < 6; ++i) {
                for (var j = 0; j < colorCubes.length; ++j) {
                  params.color[j].target = GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 + i;
                }
                if (i > 0) {
                  params.depth = faces[0].depth;
                  params.stencil = faces[0].stencil;
                  params.depthStencil = faces[0].depthStencil;
                }
                if (faces[i]) {
                  faces[i](params);
                } else {
                  faces[i] = createFBO(params);
                }
              }
              return extend2(reglFramebufferCube, {
                width: radius,
                height: radius,
                color: colorCubes
              });
            }
            function resize(radius_) {
              var i;
              var radius = radius_ | 0;
              if (radius === reglFramebufferCube.width) {
                return reglFramebufferCube;
              }
              var colors = reglFramebufferCube.color;
              for (i = 0; i < colors.length; ++i) {
                colors[i].resize(radius);
              }
              for (i = 0; i < 6; ++i) {
                faces[i].resize(radius);
              }
              reglFramebufferCube.width = reglFramebufferCube.height = radius;
              return reglFramebufferCube;
            }
            reglFramebufferCube(options);
            return extend2(reglFramebufferCube, {
              faces,
              resize,
              _reglType: "framebufferCube",
              destroy: function() {
                faces.forEach(function(f) {
                  f.destroy();
                });
              }
            });
          }
          function restoreFramebuffers() {
            framebufferState.cur = null;
            framebufferState.next = null;
            framebufferState.dirty = true;
            values(framebufferSet).forEach(function(fb) {
              fb.framebuffer = gl2.createFramebuffer();
              updateFramebuffer(fb);
            });
          }
          return extend2(framebufferState, {
            getFramebuffer: function(object) {
              if (typeof object === "function" && object._reglType === "framebuffer") {
                var fbo = object._framebuffer;
                if (fbo instanceof REGLFramebuffer) {
                  return fbo;
                }
              }
              return null;
            },
            create: createFBO,
            createCube: createCubeFBO,
            clear: function() {
              values(framebufferSet).forEach(destroy);
            },
            restore: restoreFramebuffers
          });
        }
        var GL_FLOAT$5 = 5126;
        var GL_ARRAY_BUFFER$1 = 34962;
        var GL_ELEMENT_ARRAY_BUFFER$1 = 34963;
        function AttributeRecord() {
          this.state = 0;
          this.x = 0;
          this.y = 0;
          this.z = 0;
          this.w = 0;
          this.buffer = null;
          this.size = 0;
          this.normalized = false;
          this.type = GL_FLOAT$5;
          this.offset = 0;
          this.stride = 0;
          this.divisor = 0;
        }
        function wrapAttributeState(gl2, extensions, limits, stats2, bufferState, elementState, drawState) {
          var NUM_ATTRIBUTES = limits.maxAttributes;
          var attributeBindings = new Array(NUM_ATTRIBUTES);
          for (var i = 0; i < NUM_ATTRIBUTES; ++i) {
            attributeBindings[i] = new AttributeRecord();
          }
          var vaoCount = 0;
          var vaoSet = {};
          var state = {
            Record: AttributeRecord,
            scope: {},
            state: attributeBindings,
            currentVAO: null,
            targetVAO: null,
            restore: extVAO() ? restoreVAO : function() {
            },
            createVAO,
            getVAO,
            destroyBuffer,
            setVAO: extVAO() ? setVAOEXT : setVAOEmulated,
            clear: extVAO() ? destroyVAOEXT : function() {
            }
          };
          function destroyBuffer(buffer) {
            for (var i2 = 0; i2 < attributeBindings.length; ++i2) {
              var record = attributeBindings[i2];
              if (record.buffer === buffer) {
                gl2.disableVertexAttribArray(i2);
                record.buffer = null;
              }
            }
          }
          function extVAO() {
            return extensions.oes_vertex_array_object;
          }
          function extInstanced() {
            return extensions.angle_instanced_arrays;
          }
          function getVAO(vao) {
            if (typeof vao === "function" && vao._vao) {
              return vao._vao;
            }
            return null;
          }
          function setVAOEXT(vao) {
            if (vao === state.currentVAO) {
              return;
            }
            var ext = extVAO();
            if (vao) {
              ext.bindVertexArrayOES(vao.vao);
            } else {
              ext.bindVertexArrayOES(null);
            }
            state.currentVAO = vao;
          }
          function setVAOEmulated(vao) {
            if (vao === state.currentVAO) {
              return;
            }
            if (vao) {
              vao.bindAttrs();
            } else {
              var exti = extInstanced();
              for (var i2 = 0; i2 < attributeBindings.length; ++i2) {
                var binding = attributeBindings[i2];
                if (binding.buffer) {
                  gl2.enableVertexAttribArray(i2);
                  binding.buffer.bind();
                  gl2.vertexAttribPointer(i2, binding.size, binding.type, binding.normalized, binding.stride, binding.offfset);
                  if (exti && binding.divisor) {
                    exti.vertexAttribDivisorANGLE(i2, binding.divisor);
                  }
                } else {
                  gl2.disableVertexAttribArray(i2);
                  gl2.vertexAttrib4f(i2, binding.x, binding.y, binding.z, binding.w);
                }
              }
              if (drawState.elements) {
                gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, drawState.elements.buffer.buffer);
              } else {
                gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null);
              }
            }
            state.currentVAO = vao;
          }
          function destroyVAOEXT() {
            values(vaoSet).forEach(function(vao) {
              vao.destroy();
            });
          }
          function REGLVAO() {
            this.id = ++vaoCount;
            this.attributes = [];
            this.elements = null;
            this.ownsElements = false;
            this.count = 0;
            this.offset = 0;
            this.instances = -1;
            this.primitive = 4;
            var extension = extVAO();
            if (extension) {
              this.vao = extension.createVertexArrayOES();
            } else {
              this.vao = null;
            }
            vaoSet[this.id] = this;
            this.buffers = [];
          }
          REGLVAO.prototype.bindAttrs = function() {
            var exti = extInstanced();
            var attributes = this.attributes;
            for (var i2 = 0; i2 < attributes.length; ++i2) {
              var attr = attributes[i2];
              if (attr.buffer) {
                gl2.enableVertexAttribArray(i2);
                gl2.bindBuffer(GL_ARRAY_BUFFER$1, attr.buffer.buffer);
                gl2.vertexAttribPointer(i2, attr.size, attr.type, attr.normalized, attr.stride, attr.offset);
                if (exti && attr.divisor) {
                  exti.vertexAttribDivisorANGLE(i2, attr.divisor);
                }
              } else {
                gl2.disableVertexAttribArray(i2);
                gl2.vertexAttrib4f(i2, attr.x, attr.y, attr.z, attr.w);
              }
            }
            for (var j = attributes.length; j < NUM_ATTRIBUTES; ++j) {
              gl2.disableVertexAttribArray(j);
            }
            var elements = elementState.getElements(this.elements);
            if (elements) {
              gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, elements.buffer.buffer);
            } else {
              gl2.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null);
            }
          };
          REGLVAO.prototype.refresh = function() {
            var ext = extVAO();
            if (ext) {
              ext.bindVertexArrayOES(this.vao);
              this.bindAttrs();
              state.currentVAO = null;
              ext.bindVertexArrayOES(null);
            }
          };
          REGLVAO.prototype.destroy = function() {
            if (this.vao) {
              var extension = extVAO();
              if (this === state.currentVAO) {
                state.currentVAO = null;
                extension.bindVertexArrayOES(null);
              }
              extension.deleteVertexArrayOES(this.vao);
              this.vao = null;
            }
            if (this.ownsElements) {
              this.elements.destroy();
              this.elements = null;
              this.ownsElements = false;
            }
            if (vaoSet[this.id]) {
              delete vaoSet[this.id];
              stats2.vaoCount -= 1;
            }
          };
          function restoreVAO() {
            var ext = extVAO();
            if (ext) {
              values(vaoSet).forEach(function(vao) {
                vao.refresh();
              });
            }
          }
          function createVAO(_attr) {
            var vao = new REGLVAO();
            stats2.vaoCount += 1;
            function updateVAO(options) {
              var attributes;
              if (Array.isArray(options)) {
                attributes = options;
                if (vao.elements && vao.ownsElements) {
                  vao.elements.destroy();
                }
                vao.elements = null;
                vao.ownsElements = false;
                vao.offset = 0;
                vao.count = 0;
                vao.instances = -1;
                vao.primitive = 4;
              } else {
                if (options.elements) {
                  var elements = options.elements;
                  if (vao.ownsElements) {
                    if (typeof elements === "function" && elements._reglType === "elements") {
                      vao.elements.destroy();
                      vao.ownsElements = false;
                    } else {
                      vao.elements(elements);
                      vao.ownsElements = false;
                    }
                  } else if (elementState.getElements(options.elements)) {
                    vao.elements = options.elements;
                    vao.ownsElements = false;
                  } else {
                    vao.elements = elementState.create(options.elements);
                    vao.ownsElements = true;
                  }
                } else {
                  vao.elements = null;
                  vao.ownsElements = false;
                }
                attributes = options.attributes;
                vao.offset = 0;
                vao.count = -1;
                vao.instances = -1;
                vao.primitive = 4;
                if (vao.elements) {
                  vao.count = vao.elements._elements.vertCount;
                  vao.primitive = vao.elements._elements.primType;
                }
                if ("offset" in options) {
                  vao.offset = options.offset | 0;
                }
                if ("count" in options) {
                  vao.count = options.count | 0;
                }
                if ("instances" in options) {
                  vao.instances = options.instances | 0;
                }
                if ("primitive" in options) {
                  vao.primitive = primTypes[options.primitive];
                }
              }
              var bufUpdated = {};
              var nattributes = vao.attributes;
              nattributes.length = attributes.length;
              for (var i2 = 0; i2 < attributes.length; ++i2) {
                var spec = attributes[i2];
                var rec = nattributes[i2] = new AttributeRecord();
                var data = spec.data || spec;
                if (Array.isArray(data) || isTypedArray(data) || isNDArrayLike(data)) {
                  var buf;
                  if (vao.buffers[i2]) {
                    buf = vao.buffers[i2];
                    if (isTypedArray(data) && buf._buffer.byteLength >= data.byteLength) {
                      buf.subdata(data);
                    } else {
                      buf.destroy();
                      vao.buffers[i2] = null;
                    }
                  }
                  if (!vao.buffers[i2]) {
                    buf = vao.buffers[i2] = bufferState.create(spec, GL_ARRAY_BUFFER$1, false, true);
                  }
                  rec.buffer = bufferState.getBuffer(buf);
                  rec.size = rec.buffer.dimension | 0;
                  rec.normalized = false;
                  rec.type = rec.buffer.dtype;
                  rec.offset = 0;
                  rec.stride = 0;
                  rec.divisor = 0;
                  rec.state = 1;
                  bufUpdated[i2] = 1;
                } else if (bufferState.getBuffer(spec)) {
                  rec.buffer = bufferState.getBuffer(spec);
                  rec.size = rec.buffer.dimension | 0;
                  rec.normalized = false;
                  rec.type = rec.buffer.dtype;
                  rec.offset = 0;
                  rec.stride = 0;
                  rec.divisor = 0;
                  rec.state = 1;
                } else if (bufferState.getBuffer(spec.buffer)) {
                  rec.buffer = bufferState.getBuffer(spec.buffer);
                  rec.size = (+spec.size || rec.buffer.dimension) | 0;
                  rec.normalized = !!spec.normalized || false;
                  if ("type" in spec) {
                    rec.type = glTypes[spec.type];
                  } else {
                    rec.type = rec.buffer.dtype;
                  }
                  rec.offset = (spec.offset || 0) | 0;
                  rec.stride = (spec.stride || 0) | 0;
                  rec.divisor = (spec.divisor || 0) | 0;
                  rec.state = 1;
                } else if ("x" in spec) {
                  rec.x = +spec.x || 0;
                  rec.y = +spec.y || 0;
                  rec.z = +spec.z || 0;
                  rec.w = +spec.w || 0;
                  rec.state = 2;
                } else {
                }
              }
              for (var j = 0; j < vao.buffers.length; ++j) {
                if (!bufUpdated[j] && vao.buffers[j]) {
                  vao.buffers[j].destroy();
                  vao.buffers[j] = null;
                }
              }
              vao.refresh();
              return updateVAO;
            }
            updateVAO.destroy = function() {
              for (var j = 0; j < vao.buffers.length; ++j) {
                if (vao.buffers[j]) {
                  vao.buffers[j].destroy();
                }
              }
              vao.buffers.length = 0;
              if (vao.ownsElements) {
                vao.elements.destroy();
                vao.elements = null;
                vao.ownsElements = false;
              }
              vao.destroy();
            };
            updateVAO._vao = vao;
            updateVAO._reglType = "vao";
            return updateVAO(_attr);
          }
          return state;
        }
        var GL_FRAGMENT_SHADER = 35632;
        var GL_VERTEX_SHADER = 35633;
        var GL_ACTIVE_UNIFORMS = 35718;
        var GL_ACTIVE_ATTRIBUTES = 35721;
        function wrapShaderState(gl2, stringStore, stats2, config) {
          var fragShaders = {};
          var vertShaders = {};
          function ActiveInfo(name2, id, location2, info) {
            this.name = name2;
            this.id = id;
            this.location = location2;
            this.info = info;
          }
          function insertActiveInfo(list, info) {
            for (var i = 0; i < list.length; ++i) {
              if (list[i].id === info.id) {
                list[i].location = info.location;
                return;
              }
            }
            list.push(info);
          }
          function getShader(type, id, command) {
            var cache = type === GL_FRAGMENT_SHADER ? fragShaders : vertShaders;
            var shader = cache[id];
            if (!shader) {
              var source = stringStore.str(id);
              shader = gl2.createShader(type);
              gl2.shaderSource(shader, source);
              gl2.compileShader(shader);
              cache[id] = shader;
            }
            return shader;
          }
          var programCache = {};
          var programList = [];
          var PROGRAM_COUNTER = 0;
          function REGLProgram(fragId, vertId) {
            this.id = PROGRAM_COUNTER++;
            this.fragId = fragId;
            this.vertId = vertId;
            this.program = null;
            this.uniforms = [];
            this.attributes = [];
            this.refCount = 1;
            if (config.profile) {
              this.stats = {
                uniformsCount: 0,
                attributesCount: 0
              };
            }
          }
          function linkProgram(desc, command, attributeLocations) {
            var i, info;
            var fragShader = getShader(GL_FRAGMENT_SHADER, desc.fragId);
            var vertShader = getShader(GL_VERTEX_SHADER, desc.vertId);
            var program = desc.program = gl2.createProgram();
            gl2.attachShader(program, fragShader);
            gl2.attachShader(program, vertShader);
            if (attributeLocations) {
              for (i = 0; i < attributeLocations.length; ++i) {
                var binding = attributeLocations[i];
                gl2.bindAttribLocation(program, binding[0], binding[1]);
              }
            }
            gl2.linkProgram(program);
            var numUniforms = gl2.getProgramParameter(program, GL_ACTIVE_UNIFORMS);
            if (config.profile) {
              desc.stats.uniformsCount = numUniforms;
            }
            var uniforms = desc.uniforms;
            for (i = 0; i < numUniforms; ++i) {
              info = gl2.getActiveUniform(program, i);
              if (info) {
                if (info.size > 1) {
                  for (var j = 0; j < info.size; ++j) {
                    var name2 = info.name.replace("[0]", "[" + j + "]");
                    insertActiveInfo(uniforms, new ActiveInfo(
                      name2,
                      stringStore.id(name2),
                      gl2.getUniformLocation(program, name2),
                      info
                    ));
                  }
                } else {
                  insertActiveInfo(uniforms, new ActiveInfo(
                    info.name,
                    stringStore.id(info.name),
                    gl2.getUniformLocation(program, info.name),
                    info
                  ));
                }
              }
            }
            var numAttributes = gl2.getProgramParameter(program, GL_ACTIVE_ATTRIBUTES);
            if (config.profile) {
              desc.stats.attributesCount = numAttributes;
            }
            var attributes = desc.attributes;
            for (i = 0; i < numAttributes; ++i) {
              info = gl2.getActiveAttrib(program, i);
              if (info) {
                insertActiveInfo(attributes, new ActiveInfo(
                  info.name,
                  stringStore.id(info.name),
                  gl2.getAttribLocation(program, info.name),
                  info
                ));
              }
            }
          }
          if (config.profile) {
            stats2.getMaxUniformsCount = function() {
              var m = 0;
              programList.forEach(function(desc) {
                if (desc.stats.uniformsCount > m) {
                  m = desc.stats.uniformsCount;
                }
              });
              return m;
            };
            stats2.getMaxAttributesCount = function() {
              var m = 0;
              programList.forEach(function(desc) {
                if (desc.stats.attributesCount > m) {
                  m = desc.stats.attributesCount;
                }
              });
              return m;
            };
          }
          function restoreShaders() {
            fragShaders = {};
            vertShaders = {};
            for (var i = 0; i < programList.length; ++i) {
              linkProgram(programList[i], null, programList[i].attributes.map(function(info) {
                return [info.location, info.name];
              }));
            }
          }
          return {
            clear: function() {
              var deleteShader = gl2.deleteShader.bind(gl2);
              values(fragShaders).forEach(deleteShader);
              fragShaders = {};
              values(vertShaders).forEach(deleteShader);
              vertShaders = {};
              programList.forEach(function(desc) {
                gl2.deleteProgram(desc.program);
              });
              programList.length = 0;
              programCache = {};
              stats2.shaderCount = 0;
            },
            program: function(vertId, fragId, command, attribLocations) {
              var cache = programCache[fragId];
              if (!cache) {
                cache = programCache[fragId] = {};
              }
              var prevProgram = cache[vertId];
              if (prevProgram) {
                prevProgram.refCount++;
                if (!attribLocations) {
                  return prevProgram;
                }
              }
              var program = new REGLProgram(fragId, vertId);
              stats2.shaderCount++;
              linkProgram(program, command, attribLocations);
              if (!prevProgram) {
                cache[vertId] = program;
              }
              programList.push(program);
              return extend2(program, {
                destroy: function() {
                  program.refCount--;
                  if (program.refCount <= 0) {
                    gl2.deleteProgram(program.program);
                    var idx = programList.indexOf(program);
                    programList.splice(idx, 1);
                    stats2.shaderCount--;
                  }
                  if (cache[program.vertId].refCount <= 0) {
                    gl2.deleteShader(vertShaders[program.vertId]);
                    delete vertShaders[program.vertId];
                    delete programCache[program.fragId][program.vertId];
                  }
                  if (!Object.keys(programCache[program.fragId]).length) {
                    gl2.deleteShader(fragShaders[program.fragId]);
                    delete fragShaders[program.fragId];
                    delete programCache[program.fragId];
                  }
                }
              });
            },
            restore: restoreShaders,
            shader: getShader,
            frag: -1,
            vert: -1
          };
        }
        var GL_RGBA$3 = 6408;
        var GL_UNSIGNED_BYTE$6 = 5121;
        var GL_PACK_ALIGNMENT = 3333;
        var GL_FLOAT$6 = 5126;
        function wrapReadPixels(gl2, framebufferState, reglPoll, context, glAttributes, extensions, limits) {
          function readPixelsImpl(input) {
            var type;
            if (framebufferState.next === null) {
              type = GL_UNSIGNED_BYTE$6;
            } else {
              type = framebufferState.next.colorAttachments[0].texture._texture.type;
            }
            var x = 0;
            var y = 0;
            var width = context.framebufferWidth;
            var height = context.framebufferHeight;
            var data = null;
            if (isTypedArray(input)) {
              data = input;
            } else if (input) {
              x = input.x | 0;
              y = input.y | 0;
              width = (input.width || context.framebufferWidth - x) | 0;
              height = (input.height || context.framebufferHeight - y) | 0;
              data = input.data || null;
            }
            if (data) {
              if (type === GL_UNSIGNED_BYTE$6) {
              } else if (type === GL_FLOAT$6) {
              }
            }
            reglPoll();
            var size = width * height * 4;
            if (!data) {
              if (type === GL_UNSIGNED_BYTE$6) {
                data = new Uint8Array(size);
              } else if (type === GL_FLOAT$6) {
                data = data || new Float32Array(size);
              }
            }
            gl2.pixelStorei(GL_PACK_ALIGNMENT, 4);
            gl2.readPixels(
              x,
              y,
              width,
              height,
              GL_RGBA$3,
              type,
              data
            );
            return data;
          }
          function readPixelsFBO(options) {
            var result;
            framebufferState.setFBO({
              framebuffer: options.framebuffer
            }, function() {
              result = readPixelsImpl(options);
            });
            return result;
          }
          function readPixels(options) {
            if (!options || !("framebuffer" in options)) {
              return readPixelsImpl(options);
            } else {
              return readPixelsFBO(options);
            }
          }
          return readPixels;
        }
        var hexcase = 0;
        var b64pad = "";
        function hex_sha256(s) {
          return rstr2hex(rstr_sha256(str2rstr_utf8(s)));
        }
        function rstr_sha256(s) {
          return binb2rstr(binb_sha256(rstr2binb(s), s.length * 8));
        }
        function rstr_hmac_sha256(key, data) {
          var bkey = rstr2binb(key);
          if (bkey.length > 16) bkey = binb_sha256(bkey, key.length * 8);
          var ipad = Array(16), opad = Array(16);
          for (var i = 0; i < 16; i++) {
            ipad[i] = bkey[i] ^ 909522486;
            opad[i] = bkey[i] ^ 1549556828;
          }
          var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
          return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256));
        }
        function rstr2hex(input) {
          var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
          var output = "";
          var x;
          for (var i = 0; i < input.length; i++) {
            x = input.charCodeAt(i);
            output += hex_tab.charAt(x >>> 4 & 15) + hex_tab.charAt(x & 15);
          }
          return output;
        }
        function rstr2b64(input) {
          var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
          var output = "";
          var len = input.length;
          for (var i = 0; i < len; i += 3) {
            var triplet = input.charCodeAt(i) << 16 | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0);
            for (var j = 0; j < 4; j++) {
              if (i * 8 + j * 6 > input.length * 8) output += b64pad;
              else output += tab.charAt(triplet >>> 6 * (3 - j) & 63);
            }
          }
          return output;
        }
        function rstr2any(input, encoding) {
          var divisor = encoding.length;
          var remainders = Array();
          var i, q, x, quotient;
          var dividend = Array(Math.ceil(input.length / 2));
          for (i = 0; i < dividend.length; i++) {
            dividend[i] = input.charCodeAt(i * 2) << 8 | input.charCodeAt(i * 2 + 1);
          }
          while (dividend.length > 0) {
            quotient = Array();
            x = 0;
            for (i = 0; i < dividend.length; i++) {
              x = (x << 16) + dividend[i];
              q = Math.floor(x / divisor);
              x -= q * divisor;
              if (quotient.length > 0 || q > 0)
                quotient[quotient.length] = q;
            }
            remainders[remainders.length] = x;
            dividend = quotient;
          }
          var output = "";
          for (i = remainders.length - 1; i >= 0; i--)
            output += encoding.charAt(remainders[i]);
          var full_length = Math.ceil(input.length * 8 / (Math.log(encoding.length) / Math.log(2)));
          for (i = output.length; i < full_length; i++)
            output = encoding[0] + output;
          return output;
        }
        function str2rstr_utf8(input) {
          var output = "";
          var i = -1;
          var x, y;
          while (++i < input.length) {
            x = input.charCodeAt(i);
            y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
            if (55296 <= x && x <= 56319 && 56320 <= y && y <= 57343) {
              x = 65536 + ((x & 1023) << 10) + (y & 1023);
              i++;
            }
            if (x <= 127)
              output += String.fromCharCode(x);
            else if (x <= 2047)
              output += String.fromCharCode(
                192 | x >>> 6 & 31,
                128 | x & 63
              );
            else if (x <= 65535)
              output += String.fromCharCode(
                224 | x >>> 12 & 15,
                128 | x >>> 6 & 63,
                128 | x & 63
              );
            else if (x <= 2097151)
              output += String.fromCharCode(
                240 | x >>> 18 & 7,
                128 | x >>> 12 & 63,
                128 | x >>> 6 & 63,
                128 | x & 63
              );
          }
          return output;
        }
        function rstr2binb(input) {
          var output = Array(input.length >> 2);
          for (var i = 0; i < output.length; i++)
            output[i] = 0;
          for (var i = 0; i < input.length * 8; i += 8)
            output[i >> 5] |= (input.charCodeAt(i / 8) & 255) << 24 - i % 32;
          return output;
        }
        function binb2rstr(input) {
          var output = "";
          for (var i = 0; i < input.length * 32; i += 8)
            output += String.fromCharCode(input[i >> 5] >>> 24 - i % 32 & 255);
          return output;
        }
        function sha256_S(X, n) {
          return X >>> n | X << 32 - n;
        }
        function sha256_R(X, n) {
          return X >>> n;
        }
        function sha256_Ch(x, y, z) {
          return x & y ^ ~x & z;
        }
        function sha256_Maj(x, y, z) {
          return x & y ^ x & z ^ y & z;
        }
        function sha256_Sigma0256(x) {
          return sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22);
        }
        function sha256_Sigma1256(x) {
          return sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25);
        }
        function sha256_Gamma0256(x) {
          return sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3);
        }
        function sha256_Gamma1256(x) {
          return sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10);
        }
        var sha256_K = new Array(
          1116352408,
          1899447441,
          -1245643825,
          -373957723,
          961987163,
          1508970993,
          -1841331548,
          -1424204075,
          -670586216,
          310598401,
          607225278,
          1426881987,
          1925078388,
          -2132889090,
          -1680079193,
          -1046744716,
          -459576895,
          -272742522,
          264347078,
          604807628,
          770255983,
          1249150122,
          1555081692,
          1996064986,
          -1740746414,
          -1473132947,
          -1341970488,
          -1084653625,
          -958395405,
          -710438585,
          113926993,
          338241895,
          666307205,
          773529912,
          1294757372,
          1396182291,
          1695183700,
          1986661051,
          -2117940946,
          -1838011259,
          -1564481375,
          -1474664885,
          -1035236496,
          -949202525,
          -778901479,
          -694614492,
          -200395387,
          275423344,
          430227734,
          506948616,
          659060556,
          883997877,
          958139571,
          1322822218,
          1537002063,
          1747873779,
          1955562222,
          2024104815,
          -2067236844,
          -1933114872,
          -1866530822,
          -1538233109,
          -1090935817,
          -965641998
        );
        function binb_sha256(m, l) {
          var HASH = new Array(
            1779033703,
            -1150833019,
            1013904242,
            -1521486534,
            1359893119,
            -1694144372,
            528734635,
            1541459225
          );
          var W = new Array(64);
          var a, b, c, d, e, f, g, h;
          var i, j, T1, T2;
          m[l >> 5] |= 128 << 24 - l % 32;
          m[(l + 64 >> 9 << 4) + 15] = l;
          for (i = 0; i < m.length; i += 16) {
            a = HASH[0];
            b = HASH[1];
            c = HASH[2];
            d = HASH[3];
            e = HASH[4];
            f = HASH[5];
            g = HASH[6];
            h = HASH[7];
            for (j = 0; j < 64; j++) {
              if (j < 16) W[j] = m[j + i];
              else W[j] = safe_add(safe_add(
                safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]),
                sha256_Gamma0256(W[j - 15])
              ), W[j - 16]);
              T1 = safe_add(safe_add(
                safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)),
                sha256_K[j]
              ), W[j]);
              T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c));
              h = g;
              g = f;
              f = e;
              e = safe_add(d, T1);
              d = c;
              c = b;
              b = a;
              a = safe_add(T1, T2);
            }
            HASH[0] = safe_add(a, HASH[0]);
            HASH[1] = safe_add(b, HASH[1]);
            HASH[2] = safe_add(c, HASH[2]);
            HASH[3] = safe_add(d, HASH[3]);
            HASH[4] = safe_add(e, HASH[4]);
            HASH[5] = safe_add(f, HASH[5]);
            HASH[6] = safe_add(g, HASH[6]);
            HASH[7] = safe_add(h, HASH[7]);
          }
          return HASH;
        }
        function safe_add(x, y) {
          var lsw = (x & 65535) + (y & 65535);
          var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
          return msw << 16 | lsw & 65535;
        }
        function slice(x) {
          return Array.prototype.slice.call(x);
        }
        function join(x) {
          return slice(x).join("");
        }
        function createEnvironment(options) {
          var cache = options && options.cache;
          var varCounter = 0;
          var linkedNames = [];
          var linkedValues = [];
          var isStable = [];
          function link(value, options2) {
            var stable = options2 && options2.stable;
            if (!stable) {
              for (var i = 0; i < linkedValues.length; ++i) {
                if (linkedValues[i] === value && !isStable[i]) {
                  return linkedNames[i];
                }
              }
            }
            var name2 = "g" + varCounter++;
            linkedNames.push(name2);
            linkedValues.push(value);
            isStable.push(stable);
            return name2;
          }
          function block() {
            var code = [];
            function push() {
              code.push.apply(code, slice(arguments));
            }
            var vars = [];
            function def() {
              var name2 = "v" + varCounter++;
              vars.push(name2);
              if (arguments.length > 0) {
                code.push(name2, "=");
                code.push.apply(code, slice(arguments));
                code.push(";");
              }
              return name2;
            }
            return extend2(push, {
              def,
              toString: function() {
                return join([
                  vars.length > 0 ? "var " + vars.join(",") + ";" : "",
                  join(code)
                ]);
              }
            });
          }
          function scope() {
            var entry = block();
            var exit = block();
            var entryToString = entry.toString;
            var exitToString = exit.toString;
            function save(object, prop) {
              exit(object, prop, "=", entry.def(object, prop), ";");
            }
            return extend2(function() {
              entry.apply(entry, slice(arguments));
            }, {
              def: entry.def,
              entry,
              exit,
              save,
              set: function(object, prop, value) {
                save(object, prop);
                entry(object, prop, "=", value, ";");
              },
              toString: function() {
                return entryToString() + exitToString();
              }
            });
          }
          function conditional() {
            var pred = join(arguments);
            var thenBlock = scope();
            var elseBlock = scope();
            var thenToString = thenBlock.toString;
            var elseToString = elseBlock.toString;
            return extend2(thenBlock, {
              then: function() {
                thenBlock.apply(thenBlock, slice(arguments));
                return this;
              },
              else: function() {
                elseBlock.apply(elseBlock, slice(arguments));
                return this;
              },
              toString: function() {
                var elseClause = elseToString();
                if (elseClause) {
                  elseClause = "else{" + elseClause + "}";
                }
                return join([
                  "if(",
                  pred,
                  "){",
                  thenToString(),
                  "}",
                  elseClause
                ]);
              }
            });
          }
          var globalBlock = block();
          var procedures = {};
          function proc(name2, count) {
            var args = [];
            function arg() {
              var name3 = "a" + args.length;
              args.push(name3);
              return name3;
            }
            count = count || 0;
            for (var i = 0; i < count; ++i) {
              arg();
            }
            var body = scope();
            var bodyToString = body.toString;
            var result = procedures[name2] = extend2(body, {
              arg,
              toString: function() {
                return join([
                  "function(",
                  args.join(),
                  "){",
                  bodyToString(),
                  "}"
                ]);
              }
            });
            return result;
          }
          function compile() {
            var code = [
              '"use strict";',
              globalBlock,
              "return {"
            ];
            Object.keys(procedures).forEach(function(name2) {
              code.push('"', name2, '":', procedures[name2].toString(), ",");
            });
            code.push("}");
            var src = join(code).replace(/;/g, ";\n").replace(/}/g, "}\n").replace(/{/g, "{\n");
            var key;
            if (cache) {
              key = hex_sha256(src);
              if (cache[key]) {
                return cache[key].apply(null, linkedValues);
              }
            }
            var proc2 = Function.apply(null, linkedNames.concat(src));
            if (cache) {
              cache[key] = proc2;
            }
            return proc2.apply(null, linkedValues);
          }
          return {
            global: globalBlock,
            link,
            block,
            proc,
            scope,
            cond: conditional,
            compile
          };
        }
        var CUTE_COMPONENTS = "xyzw".split("");
        var GL_UNSIGNED_BYTE$7 = 5121;
        var ATTRIB_STATE_POINTER = 1;
        var ATTRIB_STATE_CONSTANT = 2;
        var DYN_FUNC$1 = 0;
        var DYN_PROP$1 = 1;
        var DYN_CONTEXT$1 = 2;
        var DYN_STATE$1 = 3;
        var DYN_THUNK = 4;
        var DYN_CONSTANT$1 = 5;
        var DYN_ARRAY$1 = 6;
        var S_DITHER = "dither";
        var S_BLEND_ENABLE = "blend.enable";
        var S_BLEND_COLOR = "blend.color";
        var S_BLEND_EQUATION = "blend.equation";
        var S_BLEND_FUNC = "blend.func";
        var S_DEPTH_ENABLE = "depth.enable";
        var S_DEPTH_FUNC = "depth.func";
        var S_DEPTH_RANGE = "depth.range";
        var S_DEPTH_MASK = "depth.mask";
        var S_COLOR_MASK = "colorMask";
        var S_CULL_ENABLE = "cull.enable";
        var S_CULL_FACE = "cull.face";
        var S_FRONT_FACE = "frontFace";
        var S_LINE_WIDTH = "lineWidth";
        var S_POLYGON_OFFSET_ENABLE = "polygonOffset.enable";
        var S_POLYGON_OFFSET_OFFSET = "polygonOffset.offset";
        var S_SAMPLE_ALPHA = "sample.alpha";
        var S_SAMPLE_ENABLE = "sample.enable";
        var S_SAMPLE_COVERAGE = "sample.coverage";
        var S_STENCIL_ENABLE = "stencil.enable";
        var S_STENCIL_MASK = "stencil.mask";
        var S_STENCIL_FUNC = "stencil.func";
        var S_STENCIL_OPFRONT = "stencil.opFront";
        var S_STENCIL_OPBACK = "stencil.opBack";
        var S_SCISSOR_ENABLE = "scissor.enable";
        var S_SCISSOR_BOX = "scissor.box";
        var S_VIEWPORT = "viewport";
        var S_PROFILE = "profile";
        var S_FRAMEBUFFER = "framebuffer";
        var S_VERT = "vert";
        var S_FRAG = "frag";
        var S_ELEMENTS = "elements";
        var S_PRIMITIVE = "primitive";
        var S_COUNT = "count";
        var S_OFFSET = "offset";
        var S_INSTANCES = "instances";
        var S_VAO = "vao";
        var SUFFIX_WIDTH = "Width";
        var SUFFIX_HEIGHT = "Height";
        var S_FRAMEBUFFER_WIDTH = S_FRAMEBUFFER + SUFFIX_WIDTH;
        var S_FRAMEBUFFER_HEIGHT = S_FRAMEBUFFER + SUFFIX_HEIGHT;
        var S_VIEWPORT_WIDTH = S_VIEWPORT + SUFFIX_WIDTH;
        var S_VIEWPORT_HEIGHT = S_VIEWPORT + SUFFIX_HEIGHT;
        var S_DRAWINGBUFFER = "drawingBuffer";
        var S_DRAWINGBUFFER_WIDTH = S_DRAWINGBUFFER + SUFFIX_WIDTH;
        var S_DRAWINGBUFFER_HEIGHT = S_DRAWINGBUFFER + SUFFIX_HEIGHT;
        var NESTED_OPTIONS = [
          S_BLEND_FUNC,
          S_BLEND_EQUATION,
          S_STENCIL_FUNC,
          S_STENCIL_OPFRONT,
          S_STENCIL_OPBACK,
          S_SAMPLE_COVERAGE,
          S_VIEWPORT,
          S_SCISSOR_BOX,
          S_POLYGON_OFFSET_OFFSET
        ];
        var GL_ARRAY_BUFFER$2 = 34962;
        var GL_ELEMENT_ARRAY_BUFFER$2 = 34963;
        var GL_CULL_FACE = 2884;
        var GL_BLEND = 3042;
        var GL_DITHER = 3024;
        var GL_STENCIL_TEST = 2960;
        var GL_DEPTH_TEST = 2929;
        var GL_SCISSOR_TEST = 3089;
        var GL_POLYGON_OFFSET_FILL = 32823;
        var GL_SAMPLE_ALPHA_TO_COVERAGE = 32926;
        var GL_SAMPLE_COVERAGE = 32928;
        var GL_FLOAT$7 = 5126;
        var GL_FLOAT_VEC2 = 35664;
        var GL_FLOAT_VEC3 = 35665;
        var GL_FLOAT_VEC4 = 35666;
        var GL_INT$2 = 5124;
        var GL_INT_VEC2 = 35667;
        var GL_INT_VEC3 = 35668;
        var GL_INT_VEC4 = 35669;
        var GL_BOOL = 35670;
        var GL_BOOL_VEC2 = 35671;
        var GL_BOOL_VEC3 = 35672;
        var GL_BOOL_VEC4 = 35673;
        var GL_FLOAT_MAT2 = 35674;
        var GL_FLOAT_MAT3 = 35675;
        var GL_FLOAT_MAT4 = 35676;
        var GL_SAMPLER_2D = 35678;
        var GL_SAMPLER_CUBE = 35680;
        var GL_TRIANGLES$1 = 4;
        var GL_FRONT = 1028;
        var GL_BACK = 1029;
        var GL_CW = 2304;
        var GL_CCW = 2305;
        var GL_MIN_EXT = 32775;
        var GL_MAX_EXT = 32776;
        var GL_ALWAYS = 519;
        var GL_KEEP = 7680;
        var GL_ZERO = 0;
        var GL_ONE = 1;
        var GL_FUNC_ADD = 32774;
        var GL_LESS = 513;
        var GL_FRAMEBUFFER$2 = 36160;
        var GL_COLOR_ATTACHMENT0$2 = 36064;
        var blendFuncs = {
          "0": 0,
          "1": 1,
          "zero": 0,
          "one": 1,
          "src color": 768,
          "one minus src color": 769,
          "src alpha": 770,
          "one minus src alpha": 771,
          "dst color": 774,
          "one minus dst color": 775,
          "dst alpha": 772,
          "one minus dst alpha": 773,
          "constant color": 32769,
          "one minus constant color": 32770,
          "constant alpha": 32771,
          "one minus constant alpha": 32772,
          "src alpha saturate": 776
        };
        var compareFuncs = {
          "never": 512,
          "less": 513,
          "<": 513,
          "equal": 514,
          "=": 514,
          "==": 514,
          "===": 514,
          "lequal": 515,
          "<=": 515,
          "greater": 516,
          ">": 516,
          "notequal": 517,
          "!=": 517,
          "!==": 517,
          "gequal": 518,
          ">=": 518,
          "always": 519
        };
        var stencilOps = {
          "0": 0,
          "zero": 0,
          "keep": 7680,
          "replace": 7681,
          "increment": 7682,
          "decrement": 7683,
          "increment wrap": 34055,
          "decrement wrap": 34056,
          "invert": 5386
        };
        var orientationType = {
          "cw": GL_CW,
          "ccw": GL_CCW
        };
        function isBufferArgs(x) {
          return Array.isArray(x) || isTypedArray(x) || isNDArrayLike(x);
        }
        function sortState(state) {
          return state.sort(function(a, b) {
            if (a === S_VIEWPORT) {
              return -1;
            } else if (b === S_VIEWPORT) {
              return 1;
            }
            return a < b ? -1 : 1;
          });
        }
        function Declaration(thisDep, contextDep, propDep, append) {
          this.thisDep = thisDep;
          this.contextDep = contextDep;
          this.propDep = propDep;
          this.append = append;
        }
        function isStatic(decl) {
          return decl && !(decl.thisDep || decl.contextDep || decl.propDep);
        }
        function createStaticDecl(append) {
          return new Declaration(false, false, false, append);
        }
        function createDynamicDecl(dyn, append) {
          var type = dyn.type;
          if (type === DYN_FUNC$1) {
            var numArgs = dyn.data.length;
            return new Declaration(
              true,
              numArgs >= 1,
              numArgs >= 2,
              append
            );
          } else if (type === DYN_THUNK) {
            var data = dyn.data;
            return new Declaration(
              data.thisDep,
              data.contextDep,
              data.propDep,
              append
            );
          } else if (type === DYN_CONSTANT$1) {
            return new Declaration(
              false,
              false,
              false,
              append
            );
          } else if (type === DYN_ARRAY$1) {
            var thisDep = false;
            var contextDep = false;
            var propDep = false;
            for (var i = 0; i < dyn.data.length; ++i) {
              var subDyn = dyn.data[i];
              if (subDyn.type === DYN_PROP$1) {
                propDep = true;
              } else if (subDyn.type === DYN_CONTEXT$1) {
                contextDep = true;
              } else if (subDyn.type === DYN_STATE$1) {
                thisDep = true;
              } else if (subDyn.type === DYN_FUNC$1) {
                thisDep = true;
                var subArgs = subDyn.data;
                if (subArgs >= 1) {
                  contextDep = true;
                }
                if (subArgs >= 2) {
                  propDep = true;
                }
              } else if (subDyn.type === DYN_THUNK) {
                thisDep = thisDep || subDyn.data.thisDep;
                contextDep = contextDep || subDyn.data.contextDep;
                propDep = propDep || subDyn.data.propDep;
              }
            }
            return new Declaration(
              thisDep,
              contextDep,
              propDep,
              append
            );
          } else {
            return new Declaration(
              type === DYN_STATE$1,
              type === DYN_CONTEXT$1,
              type === DYN_PROP$1,
              append
            );
          }
        }
        var SCOPE_DECL = new Declaration(false, false, false, function() {
        });
        function reglCore(gl2, stringStore, extensions, limits, bufferState, elementState, textureState, framebufferState, uniformState, attributeState, shaderState, drawState, contextState, timer, cachedCode, config) {
          var AttributeRecord2 = attributeState.Record;
          var blendEquations = {
            "add": 32774,
            "subtract": 32778,
            "reverse subtract": 32779
          };
          if (extensions.ext_blend_minmax) {
            blendEquations.min = GL_MIN_EXT;
            blendEquations.max = GL_MAX_EXT;
          }
          var extInstancing = extensions.angle_instanced_arrays;
          var extDrawBuffers = extensions.webgl_draw_buffers;
          var extVertexArrays = extensions.oes_vertex_array_object;
          var currentState = {
            dirty: true,
            profile: config.profile
          };
          var nextState = {};
          var GL_STATE_NAMES = [];
          var GL_FLAGS = {};
          var GL_VARIABLES = {};
          function propName(name2) {
            return name2.replace(".", "_");
          }
          function stateFlag(sname, cap, init) {
            var name2 = propName(sname);
            GL_STATE_NAMES.push(sname);
            nextState[name2] = currentState[name2] = !!init;
            GL_FLAGS[name2] = cap;
          }
          function stateVariable(sname, func, init) {
            var name2 = propName(sname);
            GL_STATE_NAMES.push(sname);
            if (Array.isArray(init)) {
              currentState[name2] = init.slice();
              nextState[name2] = init.slice();
            } else {
              currentState[name2] = nextState[name2] = init;
            }
            GL_VARIABLES[name2] = func;
          }
          function hasVariableReference(exp) {
            if (!isNaN(exp)) {
              return false;
            }
            return true;
          }
          stateFlag(S_DITHER, GL_DITHER);
          stateFlag(S_BLEND_ENABLE, GL_BLEND);
          stateVariable(S_BLEND_COLOR, "blendColor", [0, 0, 0, 0]);
          stateVariable(
            S_BLEND_EQUATION,
            "blendEquationSeparate",
            [GL_FUNC_ADD, GL_FUNC_ADD]
          );
          stateVariable(
            S_BLEND_FUNC,
            "blendFuncSeparate",
            [GL_ONE, GL_ZERO, GL_ONE, GL_ZERO]
          );
          stateFlag(S_DEPTH_ENABLE, GL_DEPTH_TEST, true);
          stateVariable(S_DEPTH_FUNC, "depthFunc", GL_LESS);
          stateVariable(S_DEPTH_RANGE, "depthRange", [0, 1]);
          stateVariable(S_DEPTH_MASK, "depthMask", true);
          stateVariable(S_COLOR_MASK, S_COLOR_MASK, [true, true, true, true]);
          stateFlag(S_CULL_ENABLE, GL_CULL_FACE);
          stateVariable(S_CULL_FACE, "cullFace", GL_BACK);
          stateVariable(S_FRONT_FACE, S_FRONT_FACE, GL_CCW);
          stateVariable(S_LINE_WIDTH, S_LINE_WIDTH, 1);
          stateFlag(S_POLYGON_OFFSET_ENABLE, GL_POLYGON_OFFSET_FILL);
          stateVariable(S_POLYGON_OFFSET_OFFSET, "polygonOffset", [0, 0]);
          stateFlag(S_SAMPLE_ALPHA, GL_SAMPLE_ALPHA_TO_COVERAGE);
          stateFlag(S_SAMPLE_ENABLE, GL_SAMPLE_COVERAGE);
          stateVariable(S_SAMPLE_COVERAGE, "sampleCoverage", [1, false]);
          stateFlag(S_STENCIL_ENABLE, GL_STENCIL_TEST);
          stateVariable(S_STENCIL_MASK, "stencilMask", -1);
          stateVariable(S_STENCIL_FUNC, "stencilFunc", [GL_ALWAYS, 0, -1]);
          stateVariable(
            S_STENCIL_OPFRONT,
            "stencilOpSeparate",
            [GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP]
          );
          stateVariable(
            S_STENCIL_OPBACK,
            "stencilOpSeparate",
            [GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP]
          );
          stateFlag(S_SCISSOR_ENABLE, GL_SCISSOR_TEST);
          stateVariable(
            S_SCISSOR_BOX,
            "scissor",
            [0, 0, gl2.drawingBufferWidth, gl2.drawingBufferHeight]
          );
          stateVariable(
            S_VIEWPORT,
            S_VIEWPORT,
            [0, 0, gl2.drawingBufferWidth, gl2.drawingBufferHeight]
          );
          var sharedState = {
            gl: gl2,
            context: contextState,
            strings: stringStore,
            next: nextState,
            current: currentState,
            draw: drawState,
            elements: elementState,
            buffer: bufferState,
            shader: shaderState,
            attributes: attributeState.state,
            vao: attributeState,
            uniforms: uniformState,
            framebuffer: framebufferState,
            extensions,
            timer,
            isBufferArgs
          };
          var sharedConstants = {
            primTypes,
            compareFuncs,
            blendFuncs,
            blendEquations,
            stencilOps,
            glTypes,
            orientationType
          };
          if (extDrawBuffers) {
            sharedConstants.backBuffer = [GL_BACK];
            sharedConstants.drawBuffer = loop(limits.maxDrawbuffers, function(i) {
              if (i === 0) {
                return [0];
              }
              return loop(i, function(j) {
                return GL_COLOR_ATTACHMENT0$2 + j;
              });
            });
          }
          var drawCallCounter = 0;
          function createREGLEnvironment() {
            var env = createEnvironment({ cache: cachedCode });
            var link = env.link;
            var global2 = env.global;
            env.id = drawCallCounter++;
            env.batchId = "0";
            var SHARED = link(sharedState);
            var shared = env.shared = {
              props: "a0"
            };
            Object.keys(sharedState).forEach(function(prop) {
              shared[prop] = global2.def(SHARED, ".", prop);
            });
            var nextVars = env.next = {};
            var currentVars = env.current = {};
            Object.keys(GL_VARIABLES).forEach(function(variable) {
              if (Array.isArray(currentState[variable])) {
                nextVars[variable] = global2.def(shared.next, ".", variable);
                currentVars[variable] = global2.def(shared.current, ".", variable);
              }
            });
            var constants = env.constants = {};
            Object.keys(sharedConstants).forEach(function(name2) {
              constants[name2] = global2.def(JSON.stringify(sharedConstants[name2]));
            });
            env.invoke = function(block, x) {
              switch (x.type) {
                case DYN_FUNC$1:
                  var argList = [
                    "this",
                    shared.context,
                    shared.props,
                    env.batchId
                  ];
                  return block.def(
                    link(x.data),
                    ".call(",
                    argList.slice(0, Math.max(x.data.length + 1, 4)),
                    ")"
                  );
                case DYN_PROP$1:
                  return block.def(shared.props, x.data);
                case DYN_CONTEXT$1:
                  return block.def(shared.context, x.data);
                case DYN_STATE$1:
                  return block.def("this", x.data);
                case DYN_THUNK:
                  x.data.append(env, block);
                  return x.data.ref;
                case DYN_CONSTANT$1:
                  return x.data.toString();
                case DYN_ARRAY$1:
                  return x.data.map(function(y) {
                    return env.invoke(block, y);
                  });
              }
            };
            env.attribCache = {};
            var scopeAttribs = {};
            env.scopeAttrib = function(name2) {
              var id = stringStore.id(name2);
              if (id in scopeAttribs) {
                return scopeAttribs[id];
              }
              var binding = attributeState.scope[id];
              if (!binding) {
                binding = attributeState.scope[id] = new AttributeRecord2();
              }
              var result = scopeAttribs[id] = link(binding);
              return result;
            };
            return env;
          }
          function parseProfile(options) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var profileEnable;
            if (S_PROFILE in staticOptions) {
              var value = !!staticOptions[S_PROFILE];
              profileEnable = createStaticDecl(function(env, scope) {
                return value;
              });
              profileEnable.enable = value;
            } else if (S_PROFILE in dynamicOptions) {
              var dyn = dynamicOptions[S_PROFILE];
              profileEnable = createDynamicDecl(dyn, function(env, scope) {
                return env.invoke(scope, dyn);
              });
            }
            return profileEnable;
          }
          function parseFramebuffer(options, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            if (S_FRAMEBUFFER in staticOptions) {
              var framebuffer = staticOptions[S_FRAMEBUFFER];
              if (framebuffer) {
                framebuffer = framebufferState.getFramebuffer(framebuffer);
                return createStaticDecl(function(env2, block) {
                  var FRAMEBUFFER = env2.link(framebuffer);
                  var shared = env2.shared;
                  block.set(
                    shared.framebuffer,
                    ".next",
                    FRAMEBUFFER
                  );
                  var CONTEXT = shared.context;
                  block.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_WIDTH,
                    FRAMEBUFFER + ".width"
                  );
                  block.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_HEIGHT,
                    FRAMEBUFFER + ".height"
                  );
                  return FRAMEBUFFER;
                });
              } else {
                return createStaticDecl(function(env2, scope) {
                  var shared = env2.shared;
                  scope.set(
                    shared.framebuffer,
                    ".next",
                    "null"
                  );
                  var CONTEXT = shared.context;
                  scope.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_WIDTH,
                    CONTEXT + "." + S_DRAWINGBUFFER_WIDTH
                  );
                  scope.set(
                    CONTEXT,
                    "." + S_FRAMEBUFFER_HEIGHT,
                    CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT
                  );
                  return "null";
                });
              }
            } else if (S_FRAMEBUFFER in dynamicOptions) {
              var dyn = dynamicOptions[S_FRAMEBUFFER];
              return createDynamicDecl(dyn, function(env2, scope) {
                var FRAMEBUFFER_FUNC = env2.invoke(scope, dyn);
                var shared = env2.shared;
                var FRAMEBUFFER_STATE = shared.framebuffer;
                var FRAMEBUFFER = scope.def(
                  FRAMEBUFFER_STATE,
                  ".getFramebuffer(",
                  FRAMEBUFFER_FUNC,
                  ")"
                );
                scope.set(
                  FRAMEBUFFER_STATE,
                  ".next",
                  FRAMEBUFFER
                );
                var CONTEXT = shared.context;
                scope.set(
                  CONTEXT,
                  "." + S_FRAMEBUFFER_WIDTH,
                  FRAMEBUFFER + "?" + FRAMEBUFFER + ".width:" + CONTEXT + "." + S_DRAWINGBUFFER_WIDTH
                );
                scope.set(
                  CONTEXT,
                  "." + S_FRAMEBUFFER_HEIGHT,
                  FRAMEBUFFER + "?" + FRAMEBUFFER + ".height:" + CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT
                );
                return FRAMEBUFFER;
              });
            } else {
              return null;
            }
          }
          function parseViewportScissor(options, framebuffer, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            function parseBox(param) {
              if (param in staticOptions) {
                var box = staticOptions[param];
                var isStatic2 = true;
                var x = box.x | 0;
                var y = box.y | 0;
                var w, h;
                if ("width" in box) {
                  w = box.width | 0;
                } else {
                  isStatic2 = false;
                }
                if ("height" in box) {
                  h = box.height | 0;
                } else {
                  isStatic2 = false;
                }
                return new Declaration(
                  !isStatic2 && framebuffer && framebuffer.thisDep,
                  !isStatic2 && framebuffer && framebuffer.contextDep,
                  !isStatic2 && framebuffer && framebuffer.propDep,
                  function(env2, scope) {
                    var CONTEXT = env2.shared.context;
                    var BOX_W = w;
                    if (!("width" in box)) {
                      BOX_W = scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH, "-", x);
                    }
                    var BOX_H = h;
                    if (!("height" in box)) {
                      BOX_H = scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT, "-", y);
                    }
                    return [x, y, BOX_W, BOX_H];
                  }
                );
              } else if (param in dynamicOptions) {
                var dynBox = dynamicOptions[param];
                var result = createDynamicDecl(dynBox, function(env2, scope) {
                  var BOX = env2.invoke(scope, dynBox);
                  var CONTEXT = env2.shared.context;
                  var BOX_X = scope.def(BOX, ".x|0");
                  var BOX_Y = scope.def(BOX, ".y|0");
                  var BOX_W = scope.def(
                    '"width" in ',
                    BOX,
                    "?",
                    BOX,
                    ".width|0:",
                    "(",
                    CONTEXT,
                    ".",
                    S_FRAMEBUFFER_WIDTH,
                    "-",
                    BOX_X,
                    ")"
                  );
                  var BOX_H = scope.def(
                    '"height" in ',
                    BOX,
                    "?",
                    BOX,
                    ".height|0:",
                    "(",
                    CONTEXT,
                    ".",
                    S_FRAMEBUFFER_HEIGHT,
                    "-",
                    BOX_Y,
                    ")"
                  );
                  return [BOX_X, BOX_Y, BOX_W, BOX_H];
                });
                if (framebuffer) {
                  result.thisDep = result.thisDep || framebuffer.thisDep;
                  result.contextDep = result.contextDep || framebuffer.contextDep;
                  result.propDep = result.propDep || framebuffer.propDep;
                }
                return result;
              } else if (framebuffer) {
                return new Declaration(
                  framebuffer.thisDep,
                  framebuffer.contextDep,
                  framebuffer.propDep,
                  function(env2, scope) {
                    var CONTEXT = env2.shared.context;
                    return [
                      0,
                      0,
                      scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH),
                      scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT)
                    ];
                  }
                );
              } else {
                return null;
              }
            }
            var viewport = parseBox(S_VIEWPORT);
            if (viewport) {
              var prevViewport = viewport;
              viewport = new Declaration(
                viewport.thisDep,
                viewport.contextDep,
                viewport.propDep,
                function(env2, scope) {
                  var VIEWPORT = prevViewport.append(env2, scope);
                  var CONTEXT = env2.shared.context;
                  scope.set(
                    CONTEXT,
                    "." + S_VIEWPORT_WIDTH,
                    VIEWPORT[2]
                  );
                  scope.set(
                    CONTEXT,
                    "." + S_VIEWPORT_HEIGHT,
                    VIEWPORT[3]
                  );
                  return VIEWPORT;
                }
              );
            }
            return {
              viewport,
              scissor_box: parseBox(S_SCISSOR_BOX)
            };
          }
          function parseAttribLocations(options, attributes) {
            var staticOptions = options.static;
            var staticProgram = typeof staticOptions[S_FRAG] === "string" && typeof staticOptions[S_VERT] === "string";
            if (staticProgram) {
              if (Object.keys(attributes.dynamic).length > 0) {
                return null;
              }
              var staticAttributes = attributes.static;
              var sAttributes = Object.keys(staticAttributes);
              if (sAttributes.length > 0 && typeof staticAttributes[sAttributes[0]] === "number") {
                var bindings = [];
                for (var i = 0; i < sAttributes.length; ++i) {
                  bindings.push([staticAttributes[sAttributes[i]] | 0, sAttributes[i]]);
                }
                return bindings;
              }
            }
            return null;
          }
          function parseProgram(options, env, attribLocations) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            function parseShader(name2) {
              if (name2 in staticOptions) {
                var id = stringStore.id(staticOptions[name2]);
                var result = createStaticDecl(function() {
                  return id;
                });
                result.id = id;
                return result;
              } else if (name2 in dynamicOptions) {
                var dyn = dynamicOptions[name2];
                return createDynamicDecl(dyn, function(env2, scope) {
                  var str = env2.invoke(scope, dyn);
                  var id2 = scope.def(env2.shared.strings, ".id(", str, ")");
                  return id2;
                });
              }
              return null;
            }
            var frag = parseShader(S_FRAG);
            var vert = parseShader(S_VERT);
            var program = null;
            var progVar;
            if (isStatic(frag) && isStatic(vert)) {
              program = shaderState.program(vert.id, frag.id, null, attribLocations);
              progVar = createStaticDecl(function(env2, scope) {
                return env2.link(program);
              });
            } else {
              progVar = new Declaration(
                frag && frag.thisDep || vert && vert.thisDep,
                frag && frag.contextDep || vert && vert.contextDep,
                frag && frag.propDep || vert && vert.propDep,
                function(env2, scope) {
                  var SHADER_STATE = env2.shared.shader;
                  var fragId;
                  if (frag) {
                    fragId = frag.append(env2, scope);
                  } else {
                    fragId = scope.def(SHADER_STATE, ".", S_FRAG);
                  }
                  var vertId;
                  if (vert) {
                    vertId = vert.append(env2, scope);
                  } else {
                    vertId = scope.def(SHADER_STATE, ".", S_VERT);
                  }
                  var progDef = SHADER_STATE + ".program(" + vertId + "," + fragId;
                  return scope.def(progDef + ")");
                }
              );
            }
            return {
              frag,
              vert,
              progVar,
              program
            };
          }
          function parseDraw(options, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var staticDraw = {};
            var vaoActive = false;
            function parseVAO() {
              if (S_VAO in staticOptions) {
                var vao2 = staticOptions[S_VAO];
                if (vao2 !== null && attributeState.getVAO(vao2) === null) {
                  vao2 = attributeState.createVAO(vao2);
                }
                vaoActive = true;
                staticDraw.vao = vao2;
                return createStaticDecl(function(env2) {
                  var vaoRef = attributeState.getVAO(vao2);
                  if (vaoRef) {
                    return env2.link(vaoRef);
                  } else {
                    return "null";
                  }
                });
              } else if (S_VAO in dynamicOptions) {
                vaoActive = true;
                var dyn = dynamicOptions[S_VAO];
                return createDynamicDecl(dyn, function(env2, scope) {
                  var vaoRef = env2.invoke(scope, dyn);
                  return scope.def(env2.shared.vao + ".getVAO(" + vaoRef + ")");
                });
              }
              return null;
            }
            var vao = parseVAO();
            var elementsActive = false;
            function parseElements() {
              if (S_ELEMENTS in staticOptions) {
                var elements2 = staticOptions[S_ELEMENTS];
                staticDraw.elements = elements2;
                if (isBufferArgs(elements2)) {
                  var e = staticDraw.elements = elementState.create(elements2, true);
                  elements2 = elementState.getElements(e);
                  elementsActive = true;
                } else if (elements2) {
                  elements2 = elementState.getElements(elements2);
                  elementsActive = true;
                }
                var result = createStaticDecl(function(env2, scope) {
                  if (elements2) {
                    var result2 = env2.link(elements2);
                    env2.ELEMENTS = result2;
                    return result2;
                  }
                  env2.ELEMENTS = null;
                  return null;
                });
                result.value = elements2;
                return result;
              } else if (S_ELEMENTS in dynamicOptions) {
                elementsActive = true;
                var dyn = dynamicOptions[S_ELEMENTS];
                return createDynamicDecl(dyn, function(env2, scope) {
                  var shared = env2.shared;
                  var IS_BUFFER_ARGS = shared.isBufferArgs;
                  var ELEMENT_STATE = shared.elements;
                  var elementDefn = env2.invoke(scope, dyn);
                  var elements3 = scope.def("null");
                  var elementStream = scope.def(IS_BUFFER_ARGS, "(", elementDefn, ")");
                  var ifte = env2.cond(elementStream).then(elements3, "=", ELEMENT_STATE, ".createStream(", elementDefn, ");").else(elements3, "=", ELEMENT_STATE, ".getElements(", elementDefn, ");");
                  scope.entry(ifte);
                  scope.exit(
                    env2.cond(elementStream).then(ELEMENT_STATE, ".destroyStream(", elements3, ");")
                  );
                  env2.ELEMENTS = elements3;
                  return elements3;
                });
              } else if (vaoActive) {
                return new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.elements + ".getElements(" + env2.shared.vao + ".currentVAO.elements):null");
                  }
                );
              }
              return null;
            }
            var elements = parseElements();
            function parsePrimitive() {
              if (S_PRIMITIVE in staticOptions) {
                var primitive2 = staticOptions[S_PRIMITIVE];
                staticDraw.primitive = primitive2;
                return createStaticDecl(function(env2, scope) {
                  return primTypes[primitive2];
                });
              } else if (S_PRIMITIVE in dynamicOptions) {
                var dynPrimitive = dynamicOptions[S_PRIMITIVE];
                return createDynamicDecl(dynPrimitive, function(env2, scope) {
                  var PRIM_TYPES = env2.constants.primTypes;
                  var prim = env2.invoke(scope, dynPrimitive);
                  return scope.def(PRIM_TYPES, "[", prim, "]");
                });
              } else if (elementsActive) {
                if (isStatic(elements)) {
                  if (elements.value) {
                    return createStaticDecl(function(env2, scope) {
                      return scope.def(env2.ELEMENTS, ".primType");
                    });
                  } else {
                    return createStaticDecl(function() {
                      return GL_TRIANGLES$1;
                    });
                  }
                } else {
                  return new Declaration(
                    elements.thisDep,
                    elements.contextDep,
                    elements.propDep,
                    function(env2, scope) {
                      var elements2 = env2.ELEMENTS;
                      return scope.def(elements2, "?", elements2, ".primType:", GL_TRIANGLES$1);
                    }
                  );
                }
              } else if (vaoActive) {
                return new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.primitive:" + GL_TRIANGLES$1);
                  }
                );
              }
              return null;
            }
            function parseParam(param, isOffset) {
              if (param in staticOptions) {
                var value = staticOptions[param] | 0;
                if (isOffset) {
                  staticDraw.offset = value;
                } else {
                  staticDraw.instances = value;
                }
                return createStaticDecl(function(env2, scope) {
                  if (isOffset) {
                    env2.OFFSET = value;
                  }
                  return value;
                });
              } else if (param in dynamicOptions) {
                var dynValue = dynamicOptions[param];
                return createDynamicDecl(dynValue, function(env2, scope) {
                  var result = env2.invoke(scope, dynValue);
                  if (isOffset) {
                    env2.OFFSET = result;
                  }
                  return result;
                });
              } else if (isOffset) {
                if (elementsActive) {
                  return createStaticDecl(function(env2, scope) {
                    env2.OFFSET = 0;
                    return 0;
                  });
                } else if (vaoActive) {
                  return new Declaration(
                    vao.thisDep,
                    vao.contextDep,
                    vao.propDep,
                    function(env2, scope) {
                      return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.offset:0");
                    }
                  );
                }
              } else if (vaoActive) {
                return new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.instances:-1");
                  }
                );
              }
              return null;
            }
            var OFFSET = parseParam(S_OFFSET, true);
            function parseVertCount() {
              if (S_COUNT in staticOptions) {
                var count2 = staticOptions[S_COUNT] | 0;
                staticDraw.count = count2;
                return createStaticDecl(function() {
                  return count2;
                });
              } else if (S_COUNT in dynamicOptions) {
                var dynCount = dynamicOptions[S_COUNT];
                return createDynamicDecl(dynCount, function(env2, scope) {
                  var result2 = env2.invoke(scope, dynCount);
                  return result2;
                });
              } else if (elementsActive) {
                if (isStatic(elements)) {
                  if (elements) {
                    if (OFFSET) {
                      return new Declaration(
                        OFFSET.thisDep,
                        OFFSET.contextDep,
                        OFFSET.propDep,
                        function(env2, scope) {
                          var result2 = scope.def(
                            env2.ELEMENTS,
                            ".vertCount-",
                            env2.OFFSET
                          );
                          return result2;
                        }
                      );
                    } else {
                      return createStaticDecl(function(env2, scope) {
                        return scope.def(env2.ELEMENTS, ".vertCount");
                      });
                    }
                  } else {
                    var result = createStaticDecl(function() {
                      return -1;
                    });
                    return result;
                  }
                } else {
                  var variable = new Declaration(
                    elements.thisDep || OFFSET.thisDep,
                    elements.contextDep || OFFSET.contextDep,
                    elements.propDep || OFFSET.propDep,
                    function(env2, scope) {
                      var elements2 = env2.ELEMENTS;
                      if (env2.OFFSET) {
                        return scope.def(
                          elements2,
                          "?",
                          elements2,
                          ".vertCount-",
                          env2.OFFSET,
                          ":-1"
                        );
                      }
                      return scope.def(elements2, "?", elements2, ".vertCount:-1");
                    }
                  );
                  return variable;
                }
              } else if (vaoActive) {
                var countVariable = new Declaration(
                  vao.thisDep,
                  vao.contextDep,
                  vao.propDep,
                  function(env2, scope) {
                    return scope.def(env2.shared.vao, ".currentVAO?", env2.shared.vao, ".currentVAO.count:-1");
                  }
                );
                return countVariable;
              }
              return null;
            }
            var primitive = parsePrimitive();
            var count = parseVertCount();
            var instances = parseParam(S_INSTANCES, false);
            return {
              elements,
              primitive,
              count,
              instances,
              offset: OFFSET,
              vao,
              vaoActive,
              elementsActive,
              // static draw props
              static: staticDraw
            };
          }
          function parseGLState(options, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var STATE = {};
            GL_STATE_NAMES.forEach(function(prop) {
              var param = propName(prop);
              function parseParam(parseStatic, parseDynamic) {
                if (prop in staticOptions) {
                  var value = parseStatic(staticOptions[prop]);
                  STATE[param] = createStaticDecl(function() {
                    return value;
                  });
                } else if (prop in dynamicOptions) {
                  var dyn = dynamicOptions[prop];
                  STATE[param] = createDynamicDecl(dyn, function(env2, scope) {
                    return parseDynamic(env2, scope, env2.invoke(scope, dyn));
                  });
                }
              }
              switch (prop) {
                case S_CULL_ENABLE:
                case S_BLEND_ENABLE:
                case S_DITHER:
                case S_STENCIL_ENABLE:
                case S_DEPTH_ENABLE:
                case S_SCISSOR_ENABLE:
                case S_POLYGON_OFFSET_ENABLE:
                case S_SAMPLE_ALPHA:
                case S_SAMPLE_ENABLE:
                case S_DEPTH_MASK:
                  return parseParam(
                    function(value) {
                      return value;
                    },
                    function(env2, scope, value) {
                      return value;
                    }
                  );
                case S_DEPTH_FUNC:
                  return parseParam(
                    function(value) {
                      return compareFuncs[value];
                    },
                    function(env2, scope, value) {
                      var COMPARE_FUNCS = env2.constants.compareFuncs;
                      return scope.def(COMPARE_FUNCS, "[", value, "]");
                    }
                  );
                case S_DEPTH_RANGE:
                  return parseParam(
                    function(value) {
                      return value;
                    },
                    function(env2, scope, value) {
                      var Z_NEAR = scope.def("+", value, "[0]");
                      var Z_FAR = scope.def("+", value, "[1]");
                      return [Z_NEAR, Z_FAR];
                    }
                  );
                case S_BLEND_FUNC:
                  return parseParam(
                    function(value) {
                      var srcRGB = "srcRGB" in value ? value.srcRGB : value.src;
                      var srcAlpha = "srcAlpha" in value ? value.srcAlpha : value.src;
                      var dstRGB = "dstRGB" in value ? value.dstRGB : value.dst;
                      var dstAlpha = "dstAlpha" in value ? value.dstAlpha : value.dst;
                      return [
                        blendFuncs[srcRGB],
                        blendFuncs[dstRGB],
                        blendFuncs[srcAlpha],
                        blendFuncs[dstAlpha]
                      ];
                    },
                    function(env2, scope, value) {
                      var BLEND_FUNCS = env2.constants.blendFuncs;
                      function read(prefix, suffix) {
                        var func = scope.def(
                          '"',
                          prefix,
                          suffix,
                          '" in ',
                          value,
                          "?",
                          value,
                          ".",
                          prefix,
                          suffix,
                          ":",
                          value,
                          ".",
                          prefix
                        );
                        return func;
                      }
                      var srcRGB = read("src", "RGB");
                      var dstRGB = read("dst", "RGB");
                      var SRC_RGB = scope.def(BLEND_FUNCS, "[", srcRGB, "]");
                      var SRC_ALPHA = scope.def(BLEND_FUNCS, "[", read("src", "Alpha"), "]");
                      var DST_RGB = scope.def(BLEND_FUNCS, "[", dstRGB, "]");
                      var DST_ALPHA = scope.def(BLEND_FUNCS, "[", read("dst", "Alpha"), "]");
                      return [SRC_RGB, DST_RGB, SRC_ALPHA, DST_ALPHA];
                    }
                  );
                case S_BLEND_EQUATION:
                  return parseParam(
                    function(value) {
                      if (typeof value === "string") {
                        return [
                          blendEquations[value],
                          blendEquations[value]
                        ];
                      } else if (typeof value === "object") {
                        return [
                          blendEquations[value.rgb],
                          blendEquations[value.alpha]
                        ];
                      } else {
                      }
                    },
                    function(env2, scope, value) {
                      var BLEND_EQUATIONS = env2.constants.blendEquations;
                      var RGB = scope.def();
                      var ALPHA = scope.def();
                      var ifte = env2.cond("typeof ", value, '==="string"');
                      ifte.then(
                        RGB,
                        "=",
                        ALPHA,
                        "=",
                        BLEND_EQUATIONS,
                        "[",
                        value,
                        "];"
                      );
                      ifte.else(
                        RGB,
                        "=",
                        BLEND_EQUATIONS,
                        "[",
                        value,
                        ".rgb];",
                        ALPHA,
                        "=",
                        BLEND_EQUATIONS,
                        "[",
                        value,
                        ".alpha];"
                      );
                      scope(ifte);
                      return [RGB, ALPHA];
                    }
                  );
                case S_BLEND_COLOR:
                  return parseParam(
                    function(value) {
                      return loop(4, function(i) {
                        return +value[i];
                      });
                    },
                    function(env2, scope, value) {
                      return loop(4, function(i) {
                        return scope.def("+", value, "[", i, "]");
                      });
                    }
                  );
                case S_STENCIL_MASK:
                  return parseParam(
                    function(value) {
                      return value | 0;
                    },
                    function(env2, scope, value) {
                      return scope.def(value, "|0");
                    }
                  );
                case S_STENCIL_FUNC:
                  return parseParam(
                    function(value) {
                      var cmp = value.cmp || "keep";
                      var ref = value.ref || 0;
                      var mask = "mask" in value ? value.mask : -1;
                      return [
                        compareFuncs[cmp],
                        ref,
                        mask
                      ];
                    },
                    function(env2, scope, value) {
                      var COMPARE_FUNCS = env2.constants.compareFuncs;
                      var cmp = scope.def(
                        '"cmp" in ',
                        value,
                        "?",
                        COMPARE_FUNCS,
                        "[",
                        value,
                        ".cmp]",
                        ":",
                        GL_KEEP
                      );
                      var ref = scope.def(value, ".ref|0");
                      var mask = scope.def(
                        '"mask" in ',
                        value,
                        "?",
                        value,
                        ".mask|0:-1"
                      );
                      return [cmp, ref, mask];
                    }
                  );
                case S_STENCIL_OPFRONT:
                case S_STENCIL_OPBACK:
                  return parseParam(
                    function(value) {
                      var fail = value.fail || "keep";
                      var zfail = value.zfail || "keep";
                      var zpass = value.zpass || "keep";
                      return [
                        prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
                        stencilOps[fail],
                        stencilOps[zfail],
                        stencilOps[zpass]
                      ];
                    },
                    function(env2, scope, value) {
                      var STENCIL_OPS = env2.constants.stencilOps;
                      function read(name2) {
                        return scope.def(
                          '"',
                          name2,
                          '" in ',
                          value,
                          "?",
                          STENCIL_OPS,
                          "[",
                          value,
                          ".",
                          name2,
                          "]:",
                          GL_KEEP
                        );
                      }
                      return [
                        prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT,
                        read("fail"),
                        read("zfail"),
                        read("zpass")
                      ];
                    }
                  );
                case S_POLYGON_OFFSET_OFFSET:
                  return parseParam(
                    function(value) {
                      var factor = value.factor | 0;
                      var units = value.units | 0;
                      return [factor, units];
                    },
                    function(env2, scope, value) {
                      var FACTOR = scope.def(value, ".factor|0");
                      var UNITS = scope.def(value, ".units|0");
                      return [FACTOR, UNITS];
                    }
                  );
                case S_CULL_FACE:
                  return parseParam(
                    function(value) {
                      var face = 0;
                      if (value === "front") {
                        face = GL_FRONT;
                      } else if (value === "back") {
                        face = GL_BACK;
                      }
                      return face;
                    },
                    function(env2, scope, value) {
                      return scope.def(value, '==="front"?', GL_FRONT, ":", GL_BACK);
                    }
                  );
                case S_LINE_WIDTH:
                  return parseParam(
                    function(value) {
                      return value;
                    },
                    function(env2, scope, value) {
                      return value;
                    }
                  );
                case S_FRONT_FACE:
                  return parseParam(
                    function(value) {
                      return orientationType[value];
                    },
                    function(env2, scope, value) {
                      return scope.def(value + '==="cw"?' + GL_CW + ":" + GL_CCW);
                    }
                  );
                case S_COLOR_MASK:
                  return parseParam(
                    function(value) {
                      return value.map(function(v) {
                        return !!v;
                      });
                    },
                    function(env2, scope, value) {
                      return loop(4, function(i) {
                        return "!!" + value + "[" + i + "]";
                      });
                    }
                  );
                case S_SAMPLE_COVERAGE:
                  return parseParam(
                    function(value) {
                      var sampleValue = "value" in value ? value.value : 1;
                      var sampleInvert = !!value.invert;
                      return [sampleValue, sampleInvert];
                    },
                    function(env2, scope, value) {
                      var VALUE = scope.def(
                        '"value" in ',
                        value,
                        "?+",
                        value,
                        ".value:1"
                      );
                      var INVERT = scope.def("!!", value, ".invert");
                      return [VALUE, INVERT];
                    }
                  );
              }
            });
            return STATE;
          }
          function parseUniforms(uniforms, env) {
            var staticUniforms = uniforms.static;
            var dynamicUniforms = uniforms.dynamic;
            var UNIFORMS = {};
            Object.keys(staticUniforms).forEach(function(name2) {
              var value = staticUniforms[name2];
              var result;
              if (typeof value === "number" || typeof value === "boolean") {
                result = createStaticDecl(function() {
                  return value;
                });
              } else if (typeof value === "function") {
                var reglType = value._reglType;
                if (reglType === "texture2d" || reglType === "textureCube") {
                  result = createStaticDecl(function(env2) {
                    return env2.link(value);
                  });
                } else if (reglType === "framebuffer" || reglType === "framebufferCube") {
                  result = createStaticDecl(function(env2) {
                    return env2.link(value.color[0]);
                  });
                } else {
                }
              } else if (isArrayLike(value)) {
                result = createStaticDecl(function(env2) {
                  var ITEM = env2.global.def(
                    "[",
                    loop(value.length, function(i) {
                      return value[i];
                    }),
                    "]"
                  );
                  return ITEM;
                });
              } else {
              }
              result.value = value;
              UNIFORMS[name2] = result;
            });
            Object.keys(dynamicUniforms).forEach(function(key) {
              var dyn = dynamicUniforms[key];
              UNIFORMS[key] = createDynamicDecl(dyn, function(env2, scope) {
                return env2.invoke(scope, dyn);
              });
            });
            return UNIFORMS;
          }
          function parseAttributes(attributes, env) {
            var staticAttributes = attributes.static;
            var dynamicAttributes = attributes.dynamic;
            var attributeDefs = {};
            Object.keys(staticAttributes).forEach(function(attribute) {
              var value = staticAttributes[attribute];
              var id = stringStore.id(attribute);
              var record = new AttributeRecord2();
              if (isBufferArgs(value)) {
                record.state = ATTRIB_STATE_POINTER;
                record.buffer = bufferState.getBuffer(
                  bufferState.create(value, GL_ARRAY_BUFFER$2, false, true)
                );
                record.type = 0;
              } else {
                var buffer = bufferState.getBuffer(value);
                if (buffer) {
                  record.state = ATTRIB_STATE_POINTER;
                  record.buffer = buffer;
                  record.type = 0;
                } else {
                  if ("constant" in value) {
                    var constant = value.constant;
                    record.buffer = "null";
                    record.state = ATTRIB_STATE_CONSTANT;
                    if (typeof constant === "number") {
                      record.x = constant;
                    } else {
                      CUTE_COMPONENTS.forEach(function(c, i) {
                        if (i < constant.length) {
                          record[c] = constant[i];
                        }
                      });
                    }
                  } else {
                    if (isBufferArgs(value.buffer)) {
                      buffer = bufferState.getBuffer(
                        bufferState.create(value.buffer, GL_ARRAY_BUFFER$2, false, true)
                      );
                    } else {
                      buffer = bufferState.getBuffer(value.buffer);
                    }
                    var offset = value.offset | 0;
                    var stride = value.stride | 0;
                    var size = value.size | 0;
                    var normalized = !!value.normalized;
                    var type = 0;
                    if ("type" in value) {
                      type = glTypes[value.type];
                    }
                    var divisor = value.divisor | 0;
                    record.buffer = buffer;
                    record.state = ATTRIB_STATE_POINTER;
                    record.size = size;
                    record.normalized = normalized;
                    record.type = type || buffer.dtype;
                    record.offset = offset;
                    record.stride = stride;
                    record.divisor = divisor;
                  }
                }
              }
              attributeDefs[attribute] = createStaticDecl(function(env2, scope) {
                var cache = env2.attribCache;
                if (id in cache) {
                  return cache[id];
                }
                var result = {
                  isStream: false
                };
                Object.keys(record).forEach(function(key) {
                  result[key] = record[key];
                });
                if (record.buffer) {
                  result.buffer = env2.link(record.buffer);
                  result.type = result.type || result.buffer + ".dtype";
                }
                cache[id] = result;
                return result;
              });
            });
            Object.keys(dynamicAttributes).forEach(function(attribute) {
              var dyn = dynamicAttributes[attribute];
              function appendAttributeCode(env2, block) {
                var VALUE = env2.invoke(block, dyn);
                var shared = env2.shared;
                var constants = env2.constants;
                var IS_BUFFER_ARGS = shared.isBufferArgs;
                var BUFFER_STATE = shared.buffer;
                var result = {
                  isStream: block.def(false)
                };
                var defaultRecord = new AttributeRecord2();
                defaultRecord.state = ATTRIB_STATE_POINTER;
                Object.keys(defaultRecord).forEach(function(key) {
                  result[key] = block.def("" + defaultRecord[key]);
                });
                var BUFFER = result.buffer;
                var TYPE = result.type;
                block(
                  "if(",
                  IS_BUFFER_ARGS,
                  "(",
                  VALUE,
                  ")){",
                  result.isStream,
                  "=true;",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".createStream(",
                  GL_ARRAY_BUFFER$2,
                  ",",
                  VALUE,
                  ");",
                  TYPE,
                  "=",
                  BUFFER,
                  ".dtype;",
                  "}else{",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".getBuffer(",
                  VALUE,
                  ");",
                  "if(",
                  BUFFER,
                  "){",
                  TYPE,
                  "=",
                  BUFFER,
                  ".dtype;",
                  '}else if("constant" in ',
                  VALUE,
                  "){",
                  result.state,
                  "=",
                  ATTRIB_STATE_CONSTANT,
                  ";",
                  "if(typeof " + VALUE + '.constant === "number"){',
                  result[CUTE_COMPONENTS[0]],
                  "=",
                  VALUE,
                  ".constant;",
                  CUTE_COMPONENTS.slice(1).map(function(n) {
                    return result[n];
                  }).join("="),
                  "=0;",
                  "}else{",
                  CUTE_COMPONENTS.map(function(name2, i) {
                    return result[name2] + "=" + VALUE + ".constant.length>" + i + "?" + VALUE + ".constant[" + i + "]:0;";
                  }).join(""),
                  "}}else{",
                  "if(",
                  IS_BUFFER_ARGS,
                  "(",
                  VALUE,
                  ".buffer)){",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".createStream(",
                  GL_ARRAY_BUFFER$2,
                  ",",
                  VALUE,
                  ".buffer);",
                  "}else{",
                  BUFFER,
                  "=",
                  BUFFER_STATE,
                  ".getBuffer(",
                  VALUE,
                  ".buffer);",
                  "}",
                  TYPE,
                  '="type" in ',
                  VALUE,
                  "?",
                  constants.glTypes,
                  "[",
                  VALUE,
                  ".type]:",
                  BUFFER,
                  ".dtype;",
                  result.normalized,
                  "=!!",
                  VALUE,
                  ".normalized;"
                );
                function emitReadRecord(name2) {
                  block(result[name2], "=", VALUE, ".", name2, "|0;");
                }
                emitReadRecord("size");
                emitReadRecord("offset");
                emitReadRecord("stride");
                emitReadRecord("divisor");
                block("}}");
                block.exit(
                  "if(",
                  result.isStream,
                  "){",
                  BUFFER_STATE,
                  ".destroyStream(",
                  BUFFER,
                  ");",
                  "}"
                );
                return result;
              }
              attributeDefs[attribute] = createDynamicDecl(dyn, appendAttributeCode);
            });
            return attributeDefs;
          }
          function parseContext(context) {
            var staticContext = context.static;
            var dynamicContext = context.dynamic;
            var result = {};
            Object.keys(staticContext).forEach(function(name2) {
              var value = staticContext[name2];
              result[name2] = createStaticDecl(function(env, scope) {
                if (typeof value === "number" || typeof value === "boolean") {
                  return "" + value;
                } else {
                  return env.link(value);
                }
              });
            });
            Object.keys(dynamicContext).forEach(function(name2) {
              var dyn = dynamicContext[name2];
              result[name2] = createDynamicDecl(dyn, function(env, scope) {
                return env.invoke(scope, dyn);
              });
            });
            return result;
          }
          function parseArguments(options, attributes, uniforms, context, env) {
            var staticOptions = options.static;
            var dynamicOptions = options.dynamic;
            var attribLocations = parseAttribLocations(options, attributes);
            var framebuffer = parseFramebuffer(options, env);
            var viewportAndScissor = parseViewportScissor(options, framebuffer, env);
            var draw = parseDraw(options, env);
            var state = parseGLState(options, env);
            var shader = parseProgram(options, env, attribLocations);
            function copyBox(name2) {
              var defn = viewportAndScissor[name2];
              if (defn) {
                state[name2] = defn;
              }
            }
            copyBox(S_VIEWPORT);
            copyBox(propName(S_SCISSOR_BOX));
            var dirty = Object.keys(state).length > 0;
            var result = {
              framebuffer,
              draw,
              shader,
              state,
              dirty,
              scopeVAO: null,
              drawVAO: null,
              useVAO: false,
              attributes: {}
            };
            result.profile = parseProfile(options, env);
            result.uniforms = parseUniforms(uniforms, env);
            result.drawVAO = result.scopeVAO = draw.vao;
            if (!result.drawVAO && shader.program && !attribLocations && extensions.angle_instanced_arrays && draw.static.elements) {
              var useVAO = true;
              var staticBindings = shader.program.attributes.map(function(attr) {
                var binding = attributes.static[attr];
                useVAO = useVAO && !!binding;
                return binding;
              });
              if (useVAO && staticBindings.length > 0) {
                var vao = attributeState.getVAO(attributeState.createVAO({
                  attributes: staticBindings,
                  elements: draw.static.elements
                }));
                result.drawVAO = new Declaration(null, null, null, function(env2, scope) {
                  return env2.link(vao);
                });
                result.useVAO = true;
              }
            }
            if (attribLocations) {
              result.useVAO = true;
            } else {
              result.attributes = parseAttributes(attributes, env);
            }
            result.context = parseContext(context, env);
            return result;
          }
          function emitContext(env, scope, context) {
            var shared = env.shared;
            var CONTEXT = shared.context;
            var contextEnter = env.scope();
            Object.keys(context).forEach(function(name2) {
              scope.save(CONTEXT, "." + name2);
              var defn = context[name2];
              var value = defn.append(env, scope);
              if (Array.isArray(value)) {
                contextEnter(CONTEXT, ".", name2, "=[", value.join(), "];");
              } else {
                contextEnter(CONTEXT, ".", name2, "=", value, ";");
              }
            });
            scope(contextEnter);
          }
          function emitPollFramebuffer(env, scope, framebuffer, skipCheck) {
            var shared = env.shared;
            var GL = shared.gl;
            var FRAMEBUFFER_STATE = shared.framebuffer;
            var EXT_DRAW_BUFFERS;
            if (extDrawBuffers) {
              EXT_DRAW_BUFFERS = scope.def(shared.extensions, ".webgl_draw_buffers");
            }
            var constants = env.constants;
            var DRAW_BUFFERS = constants.drawBuffer;
            var BACK_BUFFER = constants.backBuffer;
            var NEXT;
            if (framebuffer) {
              NEXT = framebuffer.append(env, scope);
            } else {
              NEXT = scope.def(FRAMEBUFFER_STATE, ".next");
            }
            if (!skipCheck) {
              scope("if(", NEXT, "!==", FRAMEBUFFER_STATE, ".cur){");
            }
            scope(
              "if(",
              NEXT,
              "){",
              GL,
              ".bindFramebuffer(",
              GL_FRAMEBUFFER$2,
              ",",
              NEXT,
              ".framebuffer);"
            );
            if (extDrawBuffers) {
              scope(
                EXT_DRAW_BUFFERS,
                ".drawBuffersWEBGL(",
                DRAW_BUFFERS,
                "[",
                NEXT,
                ".colorAttachments.length]);"
              );
            }
            scope(
              "}else{",
              GL,
              ".bindFramebuffer(",
              GL_FRAMEBUFFER$2,
              ",null);"
            );
            if (extDrawBuffers) {
              scope(EXT_DRAW_BUFFERS, ".drawBuffersWEBGL(", BACK_BUFFER, ");");
            }
            scope(
              "}",
              FRAMEBUFFER_STATE,
              ".cur=",
              NEXT,
              ";"
            );
            if (!skipCheck) {
              scope("}");
            }
          }
          function emitPollState(env, scope, args) {
            var shared = env.shared;
            var GL = shared.gl;
            var CURRENT_VARS = env.current;
            var NEXT_VARS = env.next;
            var CURRENT_STATE = shared.current;
            var NEXT_STATE = shared.next;
            var block = env.cond(CURRENT_STATE, ".dirty");
            GL_STATE_NAMES.forEach(function(prop) {
              var param = propName(prop);
              if (param in args.state) {
                return;
              }
              var NEXT, CURRENT;
              if (param in NEXT_VARS) {
                NEXT = NEXT_VARS[param];
                CURRENT = CURRENT_VARS[param];
                var parts = loop(currentState[param].length, function(i) {
                  return block.def(NEXT, "[", i, "]");
                });
                block(env.cond(parts.map(function(p, i) {
                  return p + "!==" + CURRENT + "[" + i + "]";
                }).join("||")).then(
                  GL,
                  ".",
                  GL_VARIABLES[param],
                  "(",
                  parts,
                  ");",
                  parts.map(function(p, i) {
                    return CURRENT + "[" + i + "]=" + p;
                  }).join(";"),
                  ";"
                ));
              } else {
                NEXT = block.def(NEXT_STATE, ".", param);
                var ifte = env.cond(NEXT, "!==", CURRENT_STATE, ".", param);
                block(ifte);
                if (param in GL_FLAGS) {
                  ifte(
                    env.cond(NEXT).then(GL, ".enable(", GL_FLAGS[param], ");").else(GL, ".disable(", GL_FLAGS[param], ");"),
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    NEXT,
                    ";"
                  );
                } else {
                  ifte(
                    GL,
                    ".",
                    GL_VARIABLES[param],
                    "(",
                    NEXT,
                    ");",
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    NEXT,
                    ";"
                  );
                }
              }
            });
            if (Object.keys(args.state).length === 0) {
              block(CURRENT_STATE, ".dirty=false;");
            }
            scope(block);
          }
          function emitSetOptions(env, scope, options, filter) {
            var shared = env.shared;
            var CURRENT_VARS = env.current;
            var CURRENT_STATE = shared.current;
            var GL = shared.gl;
            var VALUE;
            sortState(Object.keys(options)).forEach(function(param) {
              var defn = options[param];
              if (filter && !filter(defn)) {
                return;
              }
              var variable = defn.append(env, scope);
              if (GL_FLAGS[param]) {
                var flag = GL_FLAGS[param];
                if (isStatic(defn)) {
                  VALUE = env.link(variable, { stable: true });
                  scope(env.cond(VALUE).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");"));
                  scope(CURRENT_STATE, ".", param, "=", VALUE, ";");
                } else {
                  scope(env.cond(variable).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");"));
                  scope(CURRENT_STATE, ".", param, "=", variable, ";");
                }
              } else if (isArrayLike(variable)) {
                var CURRENT = CURRENT_VARS[param];
                scope(
                  GL,
                  ".",
                  GL_VARIABLES[param],
                  "(",
                  variable,
                  ");",
                  variable.map(function(v, i) {
                    return CURRENT + "[" + i + "]=" + v;
                  }).join(";"),
                  ";"
                );
              } else {
                if (isStatic(defn)) {
                  VALUE = env.link(variable, { stable: true });
                  scope(
                    GL,
                    ".",
                    GL_VARIABLES[param],
                    "(",
                    VALUE,
                    ");",
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    VALUE,
                    ";"
                  );
                } else {
                  scope(
                    GL,
                    ".",
                    GL_VARIABLES[param],
                    "(",
                    variable,
                    ");",
                    CURRENT_STATE,
                    ".",
                    param,
                    "=",
                    variable,
                    ";"
                  );
                }
              }
            });
          }
          function injectExtensions(env, scope) {
            if (extInstancing) {
              env.instancing = scope.def(
                env.shared.extensions,
                ".angle_instanced_arrays"
              );
            }
          }
          function emitProfile(env, scope, args, useScope, incrementCounter) {
            var shared = env.shared;
            var STATS = env.stats;
            var CURRENT_STATE = shared.current;
            var TIMER = shared.timer;
            var profileArg = args.profile;
            function perfCounter() {
              if (typeof performance === "undefined") {
                return "Date.now()";
              } else {
                return "performance.now()";
              }
            }
            var CPU_START, QUERY_COUNTER;
            function emitProfileStart(block) {
              CPU_START = scope.def();
              block(CPU_START, "=", perfCounter(), ";");
              if (typeof incrementCounter === "string") {
                block(STATS, ".count+=", incrementCounter, ";");
              } else {
                block(STATS, ".count++;");
              }
              if (timer) {
                if (useScope) {
                  QUERY_COUNTER = scope.def();
                  block(QUERY_COUNTER, "=", TIMER, ".getNumPendingQueries();");
                } else {
                  block(TIMER, ".beginQuery(", STATS, ");");
                }
              }
            }
            function emitProfileEnd(block) {
              block(STATS, ".cpuTime+=", perfCounter(), "-", CPU_START, ";");
              if (timer) {
                if (useScope) {
                  block(
                    TIMER,
                    ".pushScopeStats(",
                    QUERY_COUNTER,
                    ",",
                    TIMER,
                    ".getNumPendingQueries(),",
                    STATS,
                    ");"
                  );
                } else {
                  block(TIMER, ".endQuery();");
                }
              }
            }
            function scopeProfile(value) {
              var prev = scope.def(CURRENT_STATE, ".profile");
              scope(CURRENT_STATE, ".profile=", value, ";");
              scope.exit(CURRENT_STATE, ".profile=", prev, ";");
            }
            var USE_PROFILE;
            if (profileArg) {
              if (isStatic(profileArg)) {
                if (profileArg.enable) {
                  emitProfileStart(scope);
                  emitProfileEnd(scope.exit);
                  scopeProfile("true");
                } else {
                  scopeProfile("false");
                }
                return;
              }
              USE_PROFILE = profileArg.append(env, scope);
              scopeProfile(USE_PROFILE);
            } else {
              USE_PROFILE = scope.def(CURRENT_STATE, ".profile");
            }
            var start = env.block();
            emitProfileStart(start);
            scope("if(", USE_PROFILE, "){", start, "}");
            var end = env.block();
            emitProfileEnd(end);
            scope.exit("if(", USE_PROFILE, "){", end, "}");
          }
          function emitAttributes(env, scope, args, attributes, filter) {
            var shared = env.shared;
            function typeLength(x) {
              switch (x) {
                case GL_FLOAT_VEC2:
                case GL_INT_VEC2:
                case GL_BOOL_VEC2:
                  return 2;
                case GL_FLOAT_VEC3:
                case GL_INT_VEC3:
                case GL_BOOL_VEC3:
                  return 3;
                case GL_FLOAT_VEC4:
                case GL_INT_VEC4:
                case GL_BOOL_VEC4:
                  return 4;
                default:
                  return 1;
              }
            }
            function emitBindAttribute(ATTRIBUTE, size, record) {
              var GL = shared.gl;
              var LOCATION = scope.def(ATTRIBUTE, ".location");
              var BINDING = scope.def(shared.attributes, "[", LOCATION, "]");
              var STATE = record.state;
              var BUFFER = record.buffer;
              var CONST_COMPONENTS = [
                record.x,
                record.y,
                record.z,
                record.w
              ];
              var COMMON_KEYS = [
                "buffer",
                "normalized",
                "offset",
                "stride"
              ];
              function emitBuffer() {
                scope(
                  "if(!",
                  BINDING,
                  ".buffer){",
                  GL,
                  ".enableVertexAttribArray(",
                  LOCATION,
                  ");}"
                );
                var TYPE = record.type;
                var SIZE;
                if (!record.size) {
                  SIZE = size;
                } else {
                  SIZE = scope.def(record.size, "||", size);
                }
                scope(
                  "if(",
                  BINDING,
                  ".type!==",
                  TYPE,
                  "||",
                  BINDING,
                  ".size!==",
                  SIZE,
                  "||",
                  COMMON_KEYS.map(function(key) {
                    return BINDING + "." + key + "!==" + record[key];
                  }).join("||"),
                  "){",
                  GL,
                  ".bindBuffer(",
                  GL_ARRAY_BUFFER$2,
                  ",",
                  BUFFER,
                  ".buffer);",
                  GL,
                  ".vertexAttribPointer(",
                  [
                    LOCATION,
                    SIZE,
                    TYPE,
                    record.normalized,
                    record.stride,
                    record.offset
                  ],
                  ");",
                  BINDING,
                  ".type=",
                  TYPE,
                  ";",
                  BINDING,
                  ".size=",
                  SIZE,
                  ";",
                  COMMON_KEYS.map(function(key) {
                    return BINDING + "." + key + "=" + record[key] + ";";
                  }).join(""),
                  "}"
                );
                if (extInstancing) {
                  var DIVISOR = record.divisor;
                  scope(
                    "if(",
                    BINDING,
                    ".divisor!==",
                    DIVISOR,
                    "){",
                    env.instancing,
                    ".vertexAttribDivisorANGLE(",
                    [LOCATION, DIVISOR],
                    ");",
                    BINDING,
                    ".divisor=",
                    DIVISOR,
                    ";}"
                  );
                }
              }
              function emitConstant() {
                scope(
                  "if(",
                  BINDING,
                  ".buffer){",
                  GL,
                  ".disableVertexAttribArray(",
                  LOCATION,
                  ");",
                  BINDING,
                  ".buffer=null;",
                  "}if(",
                  CUTE_COMPONENTS.map(function(c, i) {
                    return BINDING + "." + c + "!==" + CONST_COMPONENTS[i];
                  }).join("||"),
                  "){",
                  GL,
                  ".vertexAttrib4f(",
                  LOCATION,
                  ",",
                  CONST_COMPONENTS,
                  ");",
                  CUTE_COMPONENTS.map(function(c, i) {
                    return BINDING + "." + c + "=" + CONST_COMPONENTS[i] + ";";
                  }).join(""),
                  "}"
                );
              }
              if (STATE === ATTRIB_STATE_POINTER) {
                emitBuffer();
              } else if (STATE === ATTRIB_STATE_CONSTANT) {
                emitConstant();
              } else {
                scope("if(", STATE, "===", ATTRIB_STATE_POINTER, "){");
                emitBuffer();
                scope("}else{");
                emitConstant();
                scope("}");
              }
            }
            attributes.forEach(function(attribute) {
              var name2 = attribute.name;
              var arg = args.attributes[name2];
              var record;
              if (arg) {
                if (!filter(arg)) {
                  return;
                }
                record = arg.append(env, scope);
              } else {
                if (!filter(SCOPE_DECL)) {
                  return;
                }
                var scopeAttrib = env.scopeAttrib(name2);
                record = {};
                Object.keys(new AttributeRecord2()).forEach(function(key) {
                  record[key] = scope.def(scopeAttrib, ".", key);
                });
              }
              emitBindAttribute(
                env.link(attribute),
                typeLength(attribute.info.type),
                record
              );
            });
          }
          function emitUniforms(env, scope, args, uniforms, filter, isBatchInnerLoop) {
            var shared = env.shared;
            var GL = shared.gl;
            var infix;
            for (var i = 0; i < uniforms.length; ++i) {
              var uniform = uniforms[i];
              var name2 = uniform.name;
              var type = uniform.info.type;
              var arg = args.uniforms[name2];
              var UNIFORM = env.link(uniform);
              var LOCATION = UNIFORM + ".location";
              var VALUE;
              if (arg) {
                if (!filter(arg)) {
                  continue;
                }
                if (isStatic(arg)) {
                  var value = arg.value;
                  if (type === GL_SAMPLER_2D || type === GL_SAMPLER_CUBE) {
                    var TEX_VALUE = env.link(value._texture || value.color[0]._texture);
                    scope(GL, ".uniform1i(", LOCATION, ",", TEX_VALUE + ".bind());");
                    scope.exit(TEX_VALUE, ".unbind();");
                  } else if (type === GL_FLOAT_MAT2 || type === GL_FLOAT_MAT3 || type === GL_FLOAT_MAT4) {
                    var MAT_VALUE = env.global.def("new Float32Array([" + Array.prototype.slice.call(value) + "])");
                    var dim = 2;
                    if (type === GL_FLOAT_MAT3) {
                      dim = 3;
                    } else if (type === GL_FLOAT_MAT4) {
                      dim = 4;
                    }
                    scope(
                      GL,
                      ".uniformMatrix",
                      dim,
                      "fv(",
                      LOCATION,
                      ",false,",
                      MAT_VALUE,
                      ");"
                    );
                  } else {
                    switch (type) {
                      case GL_FLOAT$7:
                        infix = "1f";
                        break;
                      case GL_FLOAT_VEC2:
                        infix = "2f";
                        break;
                      case GL_FLOAT_VEC3:
                        infix = "3f";
                        break;
                      case GL_FLOAT_VEC4:
                        infix = "4f";
                        break;
                      case GL_BOOL:
                        infix = "1i";
                        break;
                      case GL_INT$2:
                        infix = "1i";
                        break;
                      case GL_BOOL_VEC2:
                        infix = "2i";
                        break;
                      case GL_INT_VEC2:
                        infix = "2i";
                        break;
                      case GL_BOOL_VEC3:
                        infix = "3i";
                        break;
                      case GL_INT_VEC3:
                        infix = "3i";
                        break;
                      case GL_BOOL_VEC4:
                        infix = "4i";
                        break;
                      case GL_INT_VEC4:
                        infix = "4i";
                        break;
                    }
                    scope(
                      GL,
                      ".uniform",
                      infix,
                      "(",
                      LOCATION,
                      ",",
                      isArrayLike(value) ? Array.prototype.slice.call(value) : value,
                      ");"
                    );
                  }
                  continue;
                } else {
                  VALUE = arg.append(env, scope);
                }
              } else {
                if (!filter(SCOPE_DECL)) {
                  continue;
                }
                VALUE = scope.def(shared.uniforms, "[", stringStore.id(name2), "]");
              }
              if (type === GL_SAMPLER_2D) {
                scope(
                  "if(",
                  VALUE,
                  "&&",
                  VALUE,
                  '._reglType==="framebuffer"){',
                  VALUE,
                  "=",
                  VALUE,
                  ".color[0];",
                  "}"
                );
              } else if (type === GL_SAMPLER_CUBE) {
                scope(
                  "if(",
                  VALUE,
                  "&&",
                  VALUE,
                  '._reglType==="framebufferCube"){',
                  VALUE,
                  "=",
                  VALUE,
                  ".color[0];",
                  "}"
                );
              }
              var unroll = 1;
              switch (type) {
                case GL_SAMPLER_2D:
                case GL_SAMPLER_CUBE:
                  var TEX = scope.def(VALUE, "._texture");
                  scope(GL, ".uniform1i(", LOCATION, ",", TEX, ".bind());");
                  scope.exit(TEX, ".unbind();");
                  continue;
                case GL_INT$2:
                case GL_BOOL:
                  infix = "1i";
                  break;
                case GL_INT_VEC2:
                case GL_BOOL_VEC2:
                  infix = "2i";
                  unroll = 2;
                  break;
                case GL_INT_VEC3:
                case GL_BOOL_VEC3:
                  infix = "3i";
                  unroll = 3;
                  break;
                case GL_INT_VEC4:
                case GL_BOOL_VEC4:
                  infix = "4i";
                  unroll = 4;
                  break;
                case GL_FLOAT$7:
                  infix = "1f";
                  break;
                case GL_FLOAT_VEC2:
                  infix = "2f";
                  unroll = 2;
                  break;
                case GL_FLOAT_VEC3:
                  infix = "3f";
                  unroll = 3;
                  break;
                case GL_FLOAT_VEC4:
                  infix = "4f";
                  unroll = 4;
                  break;
                case GL_FLOAT_MAT2:
                  infix = "Matrix2fv";
                  break;
                case GL_FLOAT_MAT3:
                  infix = "Matrix3fv";
                  break;
                case GL_FLOAT_MAT4:
                  infix = "Matrix4fv";
                  break;
              }
              if (infix.charAt(0) === "M") {
                scope(GL, ".uniform", infix, "(", LOCATION, ",");
                var matSize = Math.pow(type - GL_FLOAT_MAT2 + 2, 2);
                var STORAGE = env.global.def("new Float32Array(", matSize, ")");
                if (Array.isArray(VALUE)) {
                  scope(
                    "false,(",
                    loop(matSize, function(i2) {
                      return STORAGE + "[" + i2 + "]=" + VALUE[i2];
                    }),
                    ",",
                    STORAGE,
                    ")"
                  );
                } else {
                  scope(
                    "false,(Array.isArray(",
                    VALUE,
                    ")||",
                    VALUE,
                    " instanceof Float32Array)?",
                    VALUE,
                    ":(",
                    loop(matSize, function(i2) {
                      return STORAGE + "[" + i2 + "]=" + VALUE + "[" + i2 + "]";
                    }),
                    ",",
                    STORAGE,
                    ")"
                  );
                }
                scope(");");
              } else if (unroll > 1) {
                var prev = [];
                var cur = [];
                for (var j = 0; j < unroll; ++j) {
                  if (Array.isArray(VALUE)) {
                    cur.push(VALUE[j]);
                  } else {
                    cur.push(scope.def(VALUE + "[" + j + "]"));
                  }
                  if (isBatchInnerLoop) {
                    prev.push(scope.def());
                  }
                }
                if (isBatchInnerLoop) {
                  scope("if(!", env.batchId, "||", prev.map(function(p, i2) {
                    return p + "!==" + cur[i2];
                  }).join("||"), "){", prev.map(function(p, i2) {
                    return p + "=" + cur[i2] + ";";
                  }).join(""));
                }
                scope(GL, ".uniform", infix, "(", LOCATION, ",", cur.join(","), ");");
                if (isBatchInnerLoop) {
                  scope("}");
                }
              } else {
                if (isBatchInnerLoop) {
                  var prevS = scope.def();
                  scope(
                    "if(!",
                    env.batchId,
                    "||",
                    prevS,
                    "!==",
                    VALUE,
                    "){",
                    prevS,
                    "=",
                    VALUE,
                    ";"
                  );
                }
                scope(GL, ".uniform", infix, "(", LOCATION, ",", VALUE, ");");
                if (isBatchInnerLoop) {
                  scope("}");
                }
              }
            }
          }
          function emitDraw(env, outer, inner, args) {
            var shared = env.shared;
            var GL = shared.gl;
            var DRAW_STATE = shared.draw;
            var drawOptions = args.draw;
            function emitElements() {
              var defn = drawOptions.elements;
              var ELEMENTS2;
              var scope = outer;
              if (defn) {
                if (defn.contextDep && args.contextDynamic || defn.propDep) {
                  scope = inner;
                }
                ELEMENTS2 = defn.append(env, scope);
                if (drawOptions.elementsActive) {
                  scope(
                    "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);"
                  );
                }
              } else {
                ELEMENTS2 = scope.def();
                scope(
                  ELEMENTS2,
                  "=",
                  DRAW_STATE,
                  ".",
                  S_ELEMENTS,
                  ";",
                  "if(",
                  ELEMENTS2,
                  "){",
                  GL,
                  ".bindBuffer(",
                  GL_ELEMENT_ARRAY_BUFFER$2,
                  ",",
                  ELEMENTS2,
                  ".buffer.buffer);}",
                  "else if(",
                  shared.vao,
                  ".currentVAO){",
                  ELEMENTS2,
                  "=",
                  env.shared.elements + ".getElements(" + shared.vao,
                  ".currentVAO.elements);",
                  !extVertexArrays ? "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);" : "",
                  "}"
                );
              }
              return ELEMENTS2;
            }
            function emitCount() {
              var defn = drawOptions.count;
              var COUNT2;
              var scope = outer;
              if (defn) {
                if (defn.contextDep && args.contextDynamic || defn.propDep) {
                  scope = inner;
                }
                COUNT2 = defn.append(env, scope);
              } else {
                COUNT2 = scope.def(DRAW_STATE, ".", S_COUNT);
              }
              return COUNT2;
            }
            var ELEMENTS = emitElements();
            function emitValue(name2) {
              var defn = drawOptions[name2];
              if (defn) {
                if (defn.contextDep && args.contextDynamic || defn.propDep) {
                  return defn.append(env, inner);
                } else {
                  return defn.append(env, outer);
                }
              } else {
                return outer.def(DRAW_STATE, ".", name2);
              }
            }
            var PRIMITIVE = emitValue(S_PRIMITIVE);
            var OFFSET = emitValue(S_OFFSET);
            var COUNT = emitCount();
            if (typeof COUNT === "number") {
              if (COUNT === 0) {
                return;
              }
            } else {
              inner("if(", COUNT, "){");
              inner.exit("}");
            }
            var INSTANCES, EXT_INSTANCING;
            if (extInstancing) {
              INSTANCES = emitValue(S_INSTANCES);
              EXT_INSTANCING = env.instancing;
            }
            var ELEMENT_TYPE = ELEMENTS + ".type";
            var elementsStatic = drawOptions.elements && isStatic(drawOptions.elements) && !drawOptions.vaoActive;
            function emitInstancing() {
              function drawElements() {
                inner(EXT_INSTANCING, ".drawElementsInstancedANGLE(", [
                  PRIMITIVE,
                  COUNT,
                  ELEMENT_TYPE,
                  OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)",
                  INSTANCES
                ], ");");
              }
              function drawArrays() {
                inner(
                  EXT_INSTANCING,
                  ".drawArraysInstancedANGLE(",
                  [PRIMITIVE, OFFSET, COUNT, INSTANCES],
                  ");"
                );
              }
              if (ELEMENTS && ELEMENTS !== "null") {
                if (!elementsStatic) {
                  inner("if(", ELEMENTS, "){");
                  drawElements();
                  inner("}else{");
                  drawArrays();
                  inner("}");
                } else {
                  drawElements();
                }
              } else {
                drawArrays();
              }
            }
            function emitRegular() {
              function drawElements() {
                inner(GL + ".drawElements(" + [
                  PRIMITIVE,
                  COUNT,
                  ELEMENT_TYPE,
                  OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)"
                ] + ");");
              }
              function drawArrays() {
                inner(GL + ".drawArrays(" + [PRIMITIVE, OFFSET, COUNT] + ");");
              }
              if (ELEMENTS && ELEMENTS !== "null") {
                if (!elementsStatic) {
                  inner("if(", ELEMENTS, "){");
                  drawElements();
                  inner("}else{");
                  drawArrays();
                  inner("}");
                } else {
                  drawElements();
                }
              } else {
                drawArrays();
              }
            }
            if (extInstancing && (typeof INSTANCES !== "number" || INSTANCES >= 0)) {
              if (typeof INSTANCES === "string") {
                inner("if(", INSTANCES, ">0){");
                emitInstancing();
                inner("}else if(", INSTANCES, "<0){");
                emitRegular();
                inner("}");
              } else {
                emitInstancing();
              }
            } else {
              emitRegular();
            }
          }
          function createBody(emitBody, parentEnv, args, program, count) {
            var env = createREGLEnvironment();
            var scope = env.proc("body", count);
            if (extInstancing) {
              env.instancing = scope.def(
                env.shared.extensions,
                ".angle_instanced_arrays"
              );
            }
            emitBody(env, scope, args, program);
            return env.compile().body;
          }
          function emitDrawBody(env, draw, args, program) {
            injectExtensions(env, draw);
            if (args.useVAO) {
              if (args.drawVAO) {
                draw(env.shared.vao, ".setVAO(", args.drawVAO.append(env, draw), ");");
              } else {
                draw(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);");
              }
            } else {
              draw(env.shared.vao, ".setVAO(null);");
              emitAttributes(env, draw, args, program.attributes, function() {
                return true;
              });
            }
            emitUniforms(env, draw, args, program.uniforms, function() {
              return true;
            }, false);
            emitDraw(env, draw, draw, args);
          }
          function emitDrawProc(env, args) {
            var draw = env.proc("draw", 1);
            injectExtensions(env, draw);
            emitContext(env, draw, args.context);
            emitPollFramebuffer(env, draw, args.framebuffer);
            emitPollState(env, draw, args);
            emitSetOptions(env, draw, args.state);
            emitProfile(env, draw, args, false, true);
            var program = args.shader.progVar.append(env, draw);
            draw(env.shared.gl, ".useProgram(", program, ".program);");
            if (args.shader.program) {
              emitDrawBody(env, draw, args, args.shader.program);
            } else {
              draw(env.shared.vao, ".setVAO(null);");
              var drawCache = env.global.def("{}");
              var PROG_ID = draw.def(program, ".id");
              var CACHED_PROC = draw.def(drawCache, "[", PROG_ID, "]");
              draw(
                env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0);").else(
                  CACHED_PROC,
                  "=",
                  drawCache,
                  "[",
                  PROG_ID,
                  "]=",
                  env.link(function(program2) {
                    return createBody(emitDrawBody, env, args, program2, 1);
                  }),
                  "(",
                  program,
                  ");",
                  CACHED_PROC,
                  ".call(this,a0);"
                )
              );
            }
            if (Object.keys(args.state).length > 0) {
              draw(env.shared.current, ".dirty=true;");
            }
            if (env.shared.vao) {
              draw(env.shared.vao, ".setVAO(null);");
            }
          }
          function emitBatchDynamicShaderBody(env, scope, args, program) {
            env.batchId = "a1";
            injectExtensions(env, scope);
            function all() {
              return true;
            }
            emitAttributes(env, scope, args, program.attributes, all);
            emitUniforms(env, scope, args, program.uniforms, all, false);
            emitDraw(env, scope, scope, args);
          }
          function emitBatchBody(env, scope, args, program) {
            injectExtensions(env, scope);
            var contextDynamic = args.contextDep;
            var BATCH_ID = scope.def();
            var PROP_LIST = "a0";
            var NUM_PROPS = "a1";
            var PROPS = scope.def();
            env.shared.props = PROPS;
            env.batchId = BATCH_ID;
            var outer = env.scope();
            var inner = env.scope();
            scope(
              outer.entry,
              "for(",
              BATCH_ID,
              "=0;",
              BATCH_ID,
              "<",
              NUM_PROPS,
              ";++",
              BATCH_ID,
              "){",
              PROPS,
              "=",
              PROP_LIST,
              "[",
              BATCH_ID,
              "];",
              inner,
              "}",
              outer.exit
            );
            function isInnerDefn(defn) {
              return defn.contextDep && contextDynamic || defn.propDep;
            }
            function isOuterDefn(defn) {
              return !isInnerDefn(defn);
            }
            if (args.needsContext) {
              emitContext(env, inner, args.context);
            }
            if (args.needsFramebuffer) {
              emitPollFramebuffer(env, inner, args.framebuffer);
            }
            emitSetOptions(env, inner, args.state, isInnerDefn);
            if (args.profile && isInnerDefn(args.profile)) {
              emitProfile(env, inner, args, false, true);
            }
            if (!program) {
              var progCache = env.global.def("{}");
              var PROGRAM = args.shader.progVar.append(env, inner);
              var PROG_ID = inner.def(PROGRAM, ".id");
              var CACHED_PROC = inner.def(progCache, "[", PROG_ID, "]");
              inner(
                env.shared.gl,
                ".useProgram(",
                PROGRAM,
                ".program);",
                "if(!",
                CACHED_PROC,
                "){",
                CACHED_PROC,
                "=",
                progCache,
                "[",
                PROG_ID,
                "]=",
                env.link(function(program2) {
                  return createBody(
                    emitBatchDynamicShaderBody,
                    env,
                    args,
                    program2,
                    2
                  );
                }),
                "(",
                PROGRAM,
                ");}",
                CACHED_PROC,
                ".call(this,a0[",
                BATCH_ID,
                "],",
                BATCH_ID,
                ");"
              );
            } else {
              if (args.useVAO) {
                if (args.drawVAO) {
                  if (isInnerDefn(args.drawVAO)) {
                    inner(env.shared.vao, ".setVAO(", args.drawVAO.append(env, inner), ");");
                  } else {
                    outer(env.shared.vao, ".setVAO(", args.drawVAO.append(env, outer), ");");
                  }
                } else {
                  outer(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);");
                }
              } else {
                outer(env.shared.vao, ".setVAO(null);");
                emitAttributes(env, outer, args, program.attributes, isOuterDefn);
                emitAttributes(env, inner, args, program.attributes, isInnerDefn);
              }
              emitUniforms(env, outer, args, program.uniforms, isOuterDefn, false);
              emitUniforms(env, inner, args, program.uniforms, isInnerDefn, true);
              emitDraw(env, outer, inner, args);
            }
          }
          function emitBatchProc(env, args) {
            var batch = env.proc("batch", 2);
            env.batchId = "0";
            injectExtensions(env, batch);
            var contextDynamic = false;
            var needsContext = true;
            Object.keys(args.context).forEach(function(name2) {
              contextDynamic = contextDynamic || args.context[name2].propDep;
            });
            if (!contextDynamic) {
              emitContext(env, batch, args.context);
              needsContext = false;
            }
            var framebuffer = args.framebuffer;
            var needsFramebuffer = false;
            if (framebuffer) {
              if (framebuffer.propDep) {
                contextDynamic = needsFramebuffer = true;
              } else if (framebuffer.contextDep && contextDynamic) {
                needsFramebuffer = true;
              }
              if (!needsFramebuffer) {
                emitPollFramebuffer(env, batch, framebuffer);
              }
            } else {
              emitPollFramebuffer(env, batch, null);
            }
            if (args.state.viewport && args.state.viewport.propDep) {
              contextDynamic = true;
            }
            function isInnerDefn(defn) {
              return defn.contextDep && contextDynamic || defn.propDep;
            }
            emitPollState(env, batch, args);
            emitSetOptions(env, batch, args.state, function(defn) {
              return !isInnerDefn(defn);
            });
            if (!args.profile || !isInnerDefn(args.profile)) {
              emitProfile(env, batch, args, false, "a1");
            }
            args.contextDep = contextDynamic;
            args.needsContext = needsContext;
            args.needsFramebuffer = needsFramebuffer;
            var progDefn = args.shader.progVar;
            if (progDefn.contextDep && contextDynamic || progDefn.propDep) {
              emitBatchBody(
                env,
                batch,
                args,
                null
              );
            } else {
              var PROGRAM = progDefn.append(env, batch);
              batch(env.shared.gl, ".useProgram(", PROGRAM, ".program);");
              if (args.shader.program) {
                emitBatchBody(
                  env,
                  batch,
                  args,
                  args.shader.program
                );
              } else {
                batch(env.shared.vao, ".setVAO(null);");
                var batchCache = env.global.def("{}");
                var PROG_ID = batch.def(PROGRAM, ".id");
                var CACHED_PROC = batch.def(batchCache, "[", PROG_ID, "]");
                batch(
                  env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0,a1);").else(
                    CACHED_PROC,
                    "=",
                    batchCache,
                    "[",
                    PROG_ID,
                    "]=",
                    env.link(function(program) {
                      return createBody(emitBatchBody, env, args, program, 2);
                    }),
                    "(",
                    PROGRAM,
                    ");",
                    CACHED_PROC,
                    ".call(this,a0,a1);"
                  )
                );
              }
            }
            if (Object.keys(args.state).length > 0) {
              batch(env.shared.current, ".dirty=true;");
            }
            if (env.shared.vao) {
              batch(env.shared.vao, ".setVAO(null);");
            }
          }
          function emitScopeProc(env, args) {
            var scope = env.proc("scope", 3);
            env.batchId = "a2";
            var shared = env.shared;
            var CURRENT_STATE = shared.current;
            emitContext(env, scope, args.context);
            if (args.framebuffer) {
              args.framebuffer.append(env, scope);
            }
            sortState(Object.keys(args.state)).forEach(function(name2) {
              var defn = args.state[name2];
              var value = defn.append(env, scope);
              if (isArrayLike(value)) {
                value.forEach(function(v, i) {
                  if (hasVariableReference(v)) {
                    scope.set(env.next[name2], "[" + i + "]", v);
                  } else {
                    scope.set(env.next[name2], "[" + i + "]", env.link(v, { stable: true }));
                  }
                });
              } else {
                if (isStatic(defn)) {
                  scope.set(shared.next, "." + name2, env.link(value, { stable: true }));
                } else {
                  scope.set(shared.next, "." + name2, value);
                }
              }
            });
            emitProfile(env, scope, args, true, true);
            [S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach(
              function(opt) {
                var variable = args.draw[opt];
                if (!variable) {
                  return;
                }
                var VARIABLE2 = variable.append(env, scope);
                if (hasVariableReference(VARIABLE2)) {
                  scope.set(shared.draw, "." + opt, VARIABLE2);
                } else {
                  scope.set(shared.draw, "." + opt, env.link(VARIABLE2), { stable: true });
                }
              }
            );
            Object.keys(args.uniforms).forEach(function(opt) {
              var value = args.uniforms[opt].append(env, scope);
              if (Array.isArray(value)) {
                value = "[" + value.map(function(v) {
                  if (hasVariableReference(v)) {
                    return v;
                  } else {
                    return env.link(v, { stable: true });
                  }
                }) + "]";
              }
              scope.set(
                shared.uniforms,
                "[" + env.link(stringStore.id(opt), { stable: true }) + "]",
                value
              );
            });
            Object.keys(args.attributes).forEach(function(name2) {
              var record = args.attributes[name2].append(env, scope);
              var scopeAttrib = env.scopeAttrib(name2);
              Object.keys(new AttributeRecord2()).forEach(function(prop) {
                scope.set(scopeAttrib, "." + prop, record[prop]);
              });
            });
            if (args.scopeVAO) {
              var VARIABLE = args.scopeVAO.append(env, scope);
              if (hasVariableReference(VARIABLE)) {
                scope.set(shared.vao, ".targetVAO", VARIABLE);
              } else {
                scope.set(shared.vao, ".targetVAO", env.link(VARIABLE, { stable: true }));
              }
            }
            function saveShader(name2) {
              var shader = args.shader[name2];
              if (shader) {
                var VARIABLE2 = shader.append(env, scope);
                if (hasVariableReference(VARIABLE2)) {
                  scope.set(shared.shader, "." + name2, VARIABLE2);
                } else {
                  scope.set(shared.shader, "." + name2, env.link(VARIABLE2, { stable: true }));
                }
              }
            }
            saveShader(S_VERT);
            saveShader(S_FRAG);
            if (Object.keys(args.state).length > 0) {
              scope(CURRENT_STATE, ".dirty=true;");
              scope.exit(CURRENT_STATE, ".dirty=true;");
            }
            scope("a1(", env.shared.context, ",a0,", env.batchId, ");");
          }
          function isDynamicObject(object) {
            if (typeof object !== "object" || isArrayLike(object)) {
              return;
            }
            var props = Object.keys(object);
            for (var i = 0; i < props.length; ++i) {
              if (dynamic.isDynamic(object[props[i]])) {
                return true;
              }
            }
            return false;
          }
          function splatObject(env, options, name2) {
            var object = options.static[name2];
            if (!object || !isDynamicObject(object)) {
              return;
            }
            var globals = env.global;
            var keys = Object.keys(object);
            var thisDep = false;
            var contextDep = false;
            var propDep = false;
            var objectRef = env.global.def("{}");
            keys.forEach(function(key) {
              var value = object[key];
              if (dynamic.isDynamic(value)) {
                if (typeof value === "function") {
                  value = object[key] = dynamic.unbox(value);
                }
                var deps = createDynamicDecl(value, null);
                thisDep = thisDep || deps.thisDep;
                propDep = propDep || deps.propDep;
                contextDep = contextDep || deps.contextDep;
              } else {
                globals(objectRef, ".", key, "=");
                switch (typeof value) {
                  case "number":
                    globals(value);
                    break;
                  case "string":
                    globals('"', value, '"');
                    break;
                  case "object":
                    if (Array.isArray(value)) {
                      globals("[", value.join(), "]");
                    }
                    break;
                  default:
                    globals(env.link(value));
                    break;
                }
                globals(";");
              }
            });
            function appendBlock(env2, block) {
              keys.forEach(function(key) {
                var value = object[key];
                if (!dynamic.isDynamic(value)) {
                  return;
                }
                var ref = env2.invoke(block, value);
                block(objectRef, ".", key, "=", ref, ";");
              });
            }
            options.dynamic[name2] = new dynamic.DynamicVariable(DYN_THUNK, {
              thisDep,
              contextDep,
              propDep,
              ref: objectRef,
              append: appendBlock
            });
            delete options.static[name2];
          }
          function compileCommand(options, attributes, uniforms, context, stats2) {
            var env = createREGLEnvironment();
            env.stats = env.link(stats2);
            Object.keys(attributes.static).forEach(function(key) {
              splatObject(env, attributes, key);
            });
            NESTED_OPTIONS.forEach(function(name2) {
              splatObject(env, options, name2);
            });
            var args = parseArguments(options, attributes, uniforms, context, env);
            if (args.shader.program) {
              args.shader.program.attributes.sort(function(a, b) {
                return a.name < b.name ? -1 : 1;
              });
              args.shader.program.uniforms.sort(function(a, b) {
                return a.name < b.name ? -1 : 1;
              });
            }
            emitDrawProc(env, args);
            emitScopeProc(env, args);
            emitBatchProc(env, args);
            return extend2(env.compile(), {
              destroy: function() {
                args.shader.program.destroy();
              }
            });
          }
          return {
            next: nextState,
            current: currentState,
            procs: function() {
              var env = createREGLEnvironment();
              var poll = env.proc("poll");
              var refresh = env.proc("refresh");
              var common = env.block();
              poll(common);
              refresh(common);
              var shared = env.shared;
              var GL = shared.gl;
              var NEXT_STATE = shared.next;
              var CURRENT_STATE = shared.current;
              common(CURRENT_STATE, ".dirty=false;");
              emitPollFramebuffer(env, poll);
              emitPollFramebuffer(env, refresh, null, true);
              var INSTANCING;
              if (extInstancing) {
                INSTANCING = env.link(extInstancing);
              }
              if (extensions.oes_vertex_array_object) {
                refresh(env.link(extensions.oes_vertex_array_object), ".bindVertexArrayOES(null);");
              }
              var BINDING = refresh.def(shared.attributes);
              var TEMP_BINDING = refresh.def(0);
              var ifte = env.cond(TEMP_BINDING, ".buffer");
              ifte.then(
                GL,
                ".enableVertexAttribArray(i);",
                GL,
                ".bindBuffer(",
                GL_ARRAY_BUFFER$2,
                ",",
                TEMP_BINDING,
                ".buffer.buffer);",
                GL,
                ".vertexAttribPointer(i,",
                TEMP_BINDING,
                ".size,",
                TEMP_BINDING,
                ".type,",
                TEMP_BINDING,
                ".normalized,",
                TEMP_BINDING,
                ".stride,",
                TEMP_BINDING,
                ".offset);"
              ).else(
                GL,
                ".disableVertexAttribArray(i);",
                GL,
                ".vertexAttrib4f(i,",
                TEMP_BINDING,
                ".x,",
                TEMP_BINDING,
                ".y,",
                TEMP_BINDING,
                ".z,",
                TEMP_BINDING,
                ".w);",
                TEMP_BINDING,
                ".buffer=null;"
              );
              var MAX_ATTRIBUTES = env.link(limits.maxAttributes, { stable: true });
              refresh(
                "for(var i=0;i<",
                MAX_ATTRIBUTES,
                ";++i){",
                TEMP_BINDING,
                "=",
                BINDING,
                "[i];",
                ifte,
                "}"
              );
              if (extInstancing) {
                refresh(
                  "for(var i=0;i<",
                  MAX_ATTRIBUTES,
                  ";++i){",
                  INSTANCING,
                  ".vertexAttribDivisorANGLE(i,",
                  BINDING,
                  "[i].divisor);",
                  "}"
                );
              }
              refresh(
                env.shared.vao,
                ".currentVAO=null;",
                env.shared.vao,
                ".setVAO(",
                env.shared.vao,
                ".targetVAO);"
              );
              Object.keys(GL_FLAGS).forEach(function(flag) {
                var cap = GL_FLAGS[flag];
                var NEXT = common.def(NEXT_STATE, ".", flag);
                var block = env.block();
                block(
                  "if(",
                  NEXT,
                  "){",
                  GL,
                  ".enable(",
                  cap,
                  ")}else{",
                  GL,
                  ".disable(",
                  cap,
                  ")}",
                  CURRENT_STATE,
                  ".",
                  flag,
                  "=",
                  NEXT,
                  ";"
                );
                refresh(block);
                poll(
                  "if(",
                  NEXT,
                  "!==",
                  CURRENT_STATE,
                  ".",
                  flag,
                  "){",
                  block,
                  "}"
                );
              });
              Object.keys(GL_VARIABLES).forEach(function(name2) {
                var func = GL_VARIABLES[name2];
                var init = currentState[name2];
                var NEXT, CURRENT;
                var block = env.block();
                block(GL, ".", func, "(");
                if (isArrayLike(init)) {
                  var n = init.length;
                  NEXT = env.global.def(NEXT_STATE, ".", name2);
                  CURRENT = env.global.def(CURRENT_STATE, ".", name2);
                  block(
                    loop(n, function(i) {
                      return NEXT + "[" + i + "]";
                    }),
                    ");",
                    loop(n, function(i) {
                      return CURRENT + "[" + i + "]=" + NEXT + "[" + i + "];";
                    }).join("")
                  );
                  poll(
                    "if(",
                    loop(n, function(i) {
                      return NEXT + "[" + i + "]!==" + CURRENT + "[" + i + "]";
                    }).join("||"),
                    "){",
                    block,
                    "}"
                  );
                } else {
                  NEXT = common.def(NEXT_STATE, ".", name2);
                  CURRENT = common.def(CURRENT_STATE, ".", name2);
                  block(
                    NEXT,
                    ");",
                    CURRENT_STATE,
                    ".",
                    name2,
                    "=",
                    NEXT,
                    ";"
                  );
                  poll(
                    "if(",
                    NEXT,
                    "!==",
                    CURRENT,
                    "){",
                    block,
                    "}"
                  );
                }
                refresh(block);
              });
              return env.compile();
            }(),
            compile: compileCommand
          };
        }
        function stats() {
          return {
            vaoCount: 0,
            bufferCount: 0,
            elementsCount: 0,
            framebufferCount: 0,
            shaderCount: 0,
            textureCount: 0,
            cubeCount: 0,
            renderbufferCount: 0,
            maxTextureUnits: 0
          };
        }
        var GL_QUERY_RESULT_EXT = 34918;
        var GL_QUERY_RESULT_AVAILABLE_EXT = 34919;
        var GL_TIME_ELAPSED_EXT = 35007;
        var createTimer = function(gl2, extensions) {
          if (!extensions.ext_disjoint_timer_query) {
            return null;
          }
          var queryPool = [];
          function allocQuery() {
            return queryPool.pop() || extensions.ext_disjoint_timer_query.createQueryEXT();
          }
          function freeQuery(query) {
            queryPool.push(query);
          }
          var pendingQueries = [];
          function beginQuery(stats2) {
            var query = allocQuery();
            extensions.ext_disjoint_timer_query.beginQueryEXT(GL_TIME_ELAPSED_EXT, query);
            pendingQueries.push(query);
            pushScopeStats(pendingQueries.length - 1, pendingQueries.length, stats2);
          }
          function endQuery() {
            extensions.ext_disjoint_timer_query.endQueryEXT(GL_TIME_ELAPSED_EXT);
          }
          function PendingStats() {
            this.startQueryIndex = -1;
            this.endQueryIndex = -1;
            this.sum = 0;
            this.stats = null;
          }
          var pendingStatsPool = [];
          function allocPendingStats() {
            return pendingStatsPool.pop() || new PendingStats();
          }
          function freePendingStats(pendingStats2) {
            pendingStatsPool.push(pendingStats2);
          }
          var pendingStats = [];
          function pushScopeStats(start, end, stats2) {
            var ps = allocPendingStats();
            ps.startQueryIndex = start;
            ps.endQueryIndex = end;
            ps.sum = 0;
            ps.stats = stats2;
            pendingStats.push(ps);
          }
          var timeSum = [];
          var queryPtr = [];
          function update() {
            var ptr, i;
            var n = pendingQueries.length;
            if (n === 0) {
              return;
            }
            queryPtr.length = Math.max(queryPtr.length, n + 1);
            timeSum.length = Math.max(timeSum.length, n + 1);
            timeSum[0] = 0;
            queryPtr[0] = 0;
            var queryTime = 0;
            ptr = 0;
            for (i = 0; i < pendingQueries.length; ++i) {
              var query = pendingQueries[i];
              if (extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT)) {
                queryTime += extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_EXT);
                freeQuery(query);
              } else {
                pendingQueries[ptr++] = query;
              }
              timeSum[i + 1] = queryTime;
              queryPtr[i + 1] = ptr;
            }
            pendingQueries.length = ptr;
            ptr = 0;
            for (i = 0; i < pendingStats.length; ++i) {
              var stats2 = pendingStats[i];
              var start = stats2.startQueryIndex;
              var end = stats2.endQueryIndex;
              stats2.sum += timeSum[end] - timeSum[start];
              var startPtr = queryPtr[start];
              var endPtr = queryPtr[end];
              if (endPtr === startPtr) {
                stats2.stats.gpuTime += stats2.sum / 1e6;
                freePendingStats(stats2);
              } else {
                stats2.startQueryIndex = startPtr;
                stats2.endQueryIndex = endPtr;
                pendingStats[ptr++] = stats2;
              }
            }
            pendingStats.length = ptr;
          }
          return {
            beginQuery,
            endQuery,
            pushScopeStats,
            update,
            getNumPendingQueries: function() {
              return pendingQueries.length;
            },
            clear: function() {
              queryPool.push.apply(queryPool, pendingQueries);
              for (var i = 0; i < queryPool.length; i++) {
                extensions.ext_disjoint_timer_query.deleteQueryEXT(queryPool[i]);
              }
              pendingQueries.length = 0;
              queryPool.length = 0;
            },
            restore: function() {
              pendingQueries.length = 0;
              queryPool.length = 0;
            }
          };
        };
        var GL_COLOR_BUFFER_BIT = 16384;
        var GL_DEPTH_BUFFER_BIT = 256;
        var GL_STENCIL_BUFFER_BIT = 1024;
        var GL_ARRAY_BUFFER = 34962;
        var CONTEXT_LOST_EVENT = "webglcontextlost";
        var CONTEXT_RESTORED_EVENT = "webglcontextrestored";
        var DYN_PROP = 1;
        var DYN_CONTEXT = 2;
        var DYN_STATE = 3;
        function find(haystack, needle) {
          for (var i = 0; i < haystack.length; ++i) {
            if (haystack[i] === needle) {
              return i;
            }
          }
          return -1;
        }
        function wrapREGL(args) {
          var config = parseArgs(args);
          if (!config) {
            return null;
          }
          var gl2 = config.gl;
          var glAttributes = gl2.getContextAttributes();
          var contextLost = gl2.isContextLost();
          var extensionState = createExtensionCache(gl2, config);
          if (!extensionState) {
            return null;
          }
          var stringStore = createStringStore();
          var stats$$1 = stats();
          var cachedCode = config.cachedCode || {};
          var extensions = extensionState.extensions;
          var timer = createTimer(gl2, extensions);
          var START_TIME = clock();
          var WIDTH = gl2.drawingBufferWidth;
          var HEIGHT = gl2.drawingBufferHeight;
          var contextState = {
            tick: 0,
            time: 0,
            viewportWidth: WIDTH,
            viewportHeight: HEIGHT,
            framebufferWidth: WIDTH,
            framebufferHeight: HEIGHT,
            drawingBufferWidth: WIDTH,
            drawingBufferHeight: HEIGHT,
            pixelRatio: config.pixelRatio
          };
          var uniformState = {};
          var drawState = {
            elements: null,
            primitive: 4,
            // GL_TRIANGLES
            count: -1,
            offset: 0,
            instances: -1
          };
          var limits = wrapLimits(gl2, extensions);
          var bufferState = wrapBufferState(
            gl2,
            stats$$1,
            config,
            destroyBuffer
          );
          var elementState = wrapElementsState(gl2, extensions, bufferState, stats$$1);
          var attributeState = wrapAttributeState(
            gl2,
            extensions,
            limits,
            stats$$1,
            bufferState,
            elementState,
            drawState
          );
          function destroyBuffer(buffer) {
            return attributeState.destroyBuffer(buffer);
          }
          var shaderState = wrapShaderState(gl2, stringStore, stats$$1, config);
          var textureState = createTextureSet(
            gl2,
            extensions,
            limits,
            function() {
              core.procs.poll();
            },
            contextState,
            stats$$1,
            config
          );
          var renderbufferState = wrapRenderbuffers(gl2, extensions, limits, stats$$1, config);
          var framebufferState = wrapFBOState(
            gl2,
            extensions,
            limits,
            textureState,
            renderbufferState,
            stats$$1
          );
          var core = reglCore(
            gl2,
            stringStore,
            extensions,
            limits,
            bufferState,
            elementState,
            textureState,
            framebufferState,
            uniformState,
            attributeState,
            shaderState,
            drawState,
            contextState,
            timer,
            cachedCode,
            config
          );
          var readPixels = wrapReadPixels(
            gl2,
            framebufferState,
            core.procs.poll,
            contextState,
            glAttributes,
            extensions,
            limits
          );
          var nextState = core.next;
          var canvas = gl2.canvas;
          var rafCallbacks = [];
          var lossCallbacks = [];
          var restoreCallbacks = [];
          var destroyCallbacks = [config.onDestroy];
          var activeRAF = null;
          function handleRAF() {
            if (rafCallbacks.length === 0) {
              if (timer) {
                timer.update();
              }
              activeRAF = null;
              return;
            }
            activeRAF = raf.next(handleRAF);
            poll();
            for (var i = rafCallbacks.length - 1; i >= 0; --i) {
              var cb = rafCallbacks[i];
              if (cb) {
                cb(contextState, null, 0);
              }
            }
            gl2.flush();
            if (timer) {
              timer.update();
            }
          }
          function startRAF() {
            if (!activeRAF && rafCallbacks.length > 0) {
              activeRAF = raf.next(handleRAF);
            }
          }
          function stopRAF() {
            if (activeRAF) {
              raf.cancel(handleRAF);
              activeRAF = null;
            }
          }
          function handleContextLoss(event) {
            event.preventDefault();
            contextLost = true;
            stopRAF();
            lossCallbacks.forEach(function(cb) {
              cb();
            });
          }
          function handleContextRestored(event) {
            gl2.getError();
            contextLost = false;
            extensionState.restore();
            shaderState.restore();
            bufferState.restore();
            textureState.restore();
            renderbufferState.restore();
            framebufferState.restore();
            attributeState.restore();
            if (timer) {
              timer.restore();
            }
            core.procs.refresh();
            startRAF();
            restoreCallbacks.forEach(function(cb) {
              cb();
            });
          }
          if (canvas) {
            canvas.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false);
            canvas.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false);
          }
          function destroy() {
            rafCallbacks.length = 0;
            stopRAF();
            if (canvas) {
              canvas.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss);
              canvas.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored);
            }
            shaderState.clear();
            framebufferState.clear();
            renderbufferState.clear();
            attributeState.clear();
            textureState.clear();
            elementState.clear();
            bufferState.clear();
            if (timer) {
              timer.clear();
            }
            destroyCallbacks.forEach(function(cb) {
              cb();
            });
          }
          function compileProcedure(options) {
            function flattenNestedOptions(options2) {
              var result = extend2({}, options2);
              delete result.uniforms;
              delete result.attributes;
              delete result.context;
              delete result.vao;
              if ("stencil" in result && result.stencil.op) {
                result.stencil.opBack = result.stencil.opFront = result.stencil.op;
                delete result.stencil.op;
              }
              function merge(name2) {
                if (name2 in result) {
                  var child = result[name2];
                  delete result[name2];
                  Object.keys(child).forEach(function(prop) {
                    result[name2 + "." + prop] = child[prop];
                  });
                }
              }
              merge("blend");
              merge("depth");
              merge("cull");
              merge("stencil");
              merge("polygonOffset");
              merge("scissor");
              merge("sample");
              if ("vao" in options2) {
                result.vao = options2.vao;
              }
              return result;
            }
            function separateDynamic(object, useArrays) {
              var staticItems = {};
              var dynamicItems = {};
              Object.keys(object).forEach(function(option) {
                var value = object[option];
                if (dynamic.isDynamic(value)) {
                  dynamicItems[option] = dynamic.unbox(value, option);
                  return;
                } else if (useArrays && Array.isArray(value)) {
                  for (var i = 0; i < value.length; ++i) {
                    if (dynamic.isDynamic(value[i])) {
                      dynamicItems[option] = dynamic.unbox(value, option);
                      return;
                    }
                  }
                }
                staticItems[option] = value;
              });
              return {
                dynamic: dynamicItems,
                static: staticItems
              };
            }
            var context = separateDynamic(options.context || {}, true);
            var uniforms = separateDynamic(options.uniforms || {}, true);
            var attributes = separateDynamic(options.attributes || {}, false);
            var opts = separateDynamic(flattenNestedOptions(options), false);
            var stats$$12 = {
              gpuTime: 0,
              cpuTime: 0,
              count: 0
            };
            var compiled = core.compile(opts, attributes, uniforms, context, stats$$12);
            var draw = compiled.draw;
            var batch = compiled.batch;
            var scope = compiled.scope;
            var EMPTY_ARRAY = [];
            function reserve(count) {
              while (EMPTY_ARRAY.length < count) {
                EMPTY_ARRAY.push(null);
              }
              return EMPTY_ARRAY;
            }
            function REGLCommand(args2, body) {
              var i;
              if (contextLost) {
              }
              if (typeof args2 === "function") {
                return scope.call(this, null, args2, 0);
              } else if (typeof body === "function") {
                if (typeof args2 === "number") {
                  for (i = 0; i < args2; ++i) {
                    scope.call(this, null, body, i);
                  }
                } else if (Array.isArray(args2)) {
                  for (i = 0; i < args2.length; ++i) {
                    scope.call(this, args2[i], body, i);
                  }
                } else {
                  return scope.call(this, args2, body, 0);
                }
              } else if (typeof args2 === "number") {
                if (args2 > 0) {
                  return batch.call(this, reserve(args2 | 0), args2 | 0);
                }
              } else if (Array.isArray(args2)) {
                if (args2.length) {
                  return batch.call(this, args2, args2.length);
                }
              } else {
                return draw.call(this, args2);
              }
            }
            return extend2(REGLCommand, {
              stats: stats$$12,
              destroy: function() {
                compiled.destroy();
              }
            });
          }
          var setFBO = framebufferState.setFBO = compileProcedure({
            framebuffer: dynamic.define.call(null, DYN_PROP, "framebuffer")
          });
          function clearImpl(_, options) {
            var clearFlags = 0;
            core.procs.poll();
            var c = options.color;
            if (c) {
              gl2.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0);
              clearFlags |= GL_COLOR_BUFFER_BIT;
            }
            if ("depth" in options) {
              gl2.clearDepth(+options.depth);
              clearFlags |= GL_DEPTH_BUFFER_BIT;
            }
            if ("stencil" in options) {
              gl2.clearStencil(options.stencil | 0);
              clearFlags |= GL_STENCIL_BUFFER_BIT;
            }
            gl2.clear(clearFlags);
          }
          function clear(options) {
            if ("framebuffer" in options) {
              if (options.framebuffer && options.framebuffer_reglType === "framebufferCube") {
                for (var i = 0; i < 6; ++i) {
                  setFBO(extend2({
                    framebuffer: options.framebuffer.faces[i]
                  }, options), clearImpl);
                }
              } else {
                setFBO(options, clearImpl);
              }
            } else {
              clearImpl(null, options);
            }
          }
          function frame(cb) {
            rafCallbacks.push(cb);
            function cancel() {
              var i = find(rafCallbacks, cb);
              function pendingCancel() {
                var index = find(rafCallbacks, pendingCancel);
                rafCallbacks[index] = rafCallbacks[rafCallbacks.length - 1];
                rafCallbacks.length -= 1;
                if (rafCallbacks.length <= 0) {
                  stopRAF();
                }
              }
              rafCallbacks[i] = pendingCancel;
            }
            startRAF();
            return {
              cancel
            };
          }
          function pollViewport() {
            var viewport = nextState.viewport;
            var scissorBox = nextState.scissor_box;
            viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0;
            contextState.viewportWidth = contextState.framebufferWidth = contextState.drawingBufferWidth = viewport[2] = scissorBox[2] = gl2.drawingBufferWidth;
            contextState.viewportHeight = contextState.framebufferHeight = contextState.drawingBufferHeight = viewport[3] = scissorBox[3] = gl2.drawingBufferHeight;
          }
          function poll() {
            contextState.tick += 1;
            contextState.time = now();
            pollViewport();
            core.procs.poll();
          }
          function refresh() {
            textureState.refresh();
            pollViewport();
            core.procs.refresh();
            if (timer) {
              timer.update();
            }
          }
          function now() {
            return (clock() - START_TIME) / 1e3;
          }
          refresh();
          function addListener(event, callback) {
            var callbacks;
            switch (event) {
              case "frame":
                return frame(callback);
              case "lost":
                callbacks = lossCallbacks;
                break;
              case "restore":
                callbacks = restoreCallbacks;
                break;
              case "destroy":
                callbacks = destroyCallbacks;
                break;
              default:
            }
            callbacks.push(callback);
            return {
              cancel: function() {
                for (var i = 0; i < callbacks.length; ++i) {
                  if (callbacks[i] === callback) {
                    callbacks[i] = callbacks[callbacks.length - 1];
                    callbacks.pop();
                    return;
                  }
                }
              }
            };
          }
          function getCachedCode() {
            return cachedCode;
          }
          function preloadCachedCode(moreCache) {
            Object.entries(moreCache).forEach(function(kv) {
              cachedCode[kv[0]] = kv[1];
            });
          }
          var regl = extend2(compileProcedure, {
            // Clear current FBO
            clear,
            // Short cuts for dynamic variables
            prop: dynamic.define.bind(null, DYN_PROP),
            context: dynamic.define.bind(null, DYN_CONTEXT),
            this: dynamic.define.bind(null, DYN_STATE),
            // executes an empty draw command
            draw: compileProcedure({}),
            // Resources
            buffer: function(options) {
              return bufferState.create(options, GL_ARRAY_BUFFER, false, false);
            },
            elements: function(options) {
              return elementState.create(options, false);
            },
            texture: textureState.create2D,
            cube: textureState.createCube,
            renderbuffer: renderbufferState.create,
            framebuffer: framebufferState.create,
            framebufferCube: framebufferState.createCube,
            vao: attributeState.createVAO,
            // Expose context attributes
            attributes: glAttributes,
            // Frame rendering
            frame,
            on: addListener,
            // System limits
            limits,
            hasExtension: function(name2) {
              return limits.extensions.indexOf(name2.toLowerCase()) >= 0;
            },
            // Read pixels
            read: readPixels,
            // Destroy regl and all associated resources
            destroy,
            // Direct GL state manipulation
            _gl: gl2,
            _refresh: refresh,
            poll: function() {
              poll();
              if (timer) {
                timer.update();
              }
            },
            // Current time
            now,
            // regl Statistics Information
            stats: stats$$1,
            // cache generated code
            getCachedCode,
            preloadCachedCode
          });
          config.onDone(null, regl);
          return regl;
        }
        return wrapREGL;
      });
    }
  });

  // src/lib/prepare_regl.js
  var require_prepare_regl = __commonJS({
    "src/lib/prepare_regl.js"(exports, module) {
      "use strict";
      var showNoWebGlMsg = require_show_no_webgl_msg();
      var createRegl = require_regl_unchecked2();
      module.exports = function prepareRegl(gd, extensions, reglPrecompiled) {
        var fullLayout = gd._fullLayout;
        var success = true;
        fullLayout._glcanvas.each(function(d) {
          if (d.regl) {
            d.regl.preloadCachedCode(reglPrecompiled);
            return;
          }
          if (d.pick && !fullLayout._has("parcoords")) return;
          try {
            d.regl = createRegl({
              canvas: this,
              attributes: {
                antialias: !d.pick,
                preserveDrawingBuffer: true
              },
              pixelRatio: gd._context.plotGlPixelRatio || window.devicePixelRatio,
              extensions: extensions || [],
              cachedCode: reglPrecompiled || {}
            });
          } catch (e) {
            success = false;
          }
          if (!d.regl) success = false;
          if (success) {
            this.addEventListener("webglcontextlost", function(event) {
              if (gd && gd.emit) {
                gd.emit("plotly_webglcontextlost", {
                  event,
                  layer: d.key
                });
              }
            }, false);
          }
        });
        if (!success) {
          showNoWebGlMsg({ container: fullLayout._glcontainer.node() });
        }
        return success;
      };
    }
  });

  // src/traces/scattergl/plot.js
  var require_plot19 = __commonJS({
    "src/traces/scattergl/plot.js"(exports, module) {
      "use strict";
      var createScatter = require_bundle();
      var createLine = require_regl_line2d();
      var createError = require_regl_error2d();
      var Text = require_dist();
      var Lib = require_lib();
      var selectMode = require_helpers5().selectMode;
      var prepareRegl = require_prepare_regl();
      var subTypes = require_subtypes();
      var linkTraces = require_link_traces();
      var styleTextSelection = require_edit_style().styleTextSelection;
      var reglPrecompiled = {};
      function getViewport(fullLayout, xaxis, yaxis, plotGlPixelRatio) {
        var gs = fullLayout._size;
        var width = fullLayout.width * plotGlPixelRatio;
        var height = fullLayout.height * plotGlPixelRatio;
        var l = gs.l * plotGlPixelRatio;
        var b = gs.b * plotGlPixelRatio;
        var r = gs.r * plotGlPixelRatio;
        var t = gs.t * plotGlPixelRatio;
        var w = gs.w * plotGlPixelRatio;
        var h = gs.h * plotGlPixelRatio;
        return [
          l + xaxis.domain[0] * w,
          b + yaxis.domain[0] * h,
          width - r - (1 - xaxis.domain[1]) * w,
          height - t - (1 - yaxis.domain[1]) * h
        ];
      }
      var exports = module.exports = function plot(gd, subplot, cdata) {
        if (!cdata.length) return;
        var fullLayout = gd._fullLayout;
        var scene = subplot._scene;
        var xaxis = subplot.xaxis;
        var yaxis = subplot.yaxis;
        var i, j;
        if (!scene) return;
        var success = prepareRegl(gd, ["ANGLE_instanced_arrays", "OES_element_index_uint"], reglPrecompiled);
        if (!success) {
          scene.init();
          return;
        }
        var count = scene.count;
        var regl = fullLayout._glcanvas.data()[0].regl;
        linkTraces(gd, subplot, cdata);
        if (scene.dirty) {
          if ((scene.line2d || scene.error2d) && !(scene.scatter2d || scene.fill2d || scene.glText)) {
            regl.clear({ color: true, depth: true });
          }
          if (scene.error2d === true) {
            scene.error2d = createError(regl);
          }
          if (scene.line2d === true) {
            scene.line2d = createLine(regl);
          }
          if (scene.scatter2d === true) {
            scene.scatter2d = createScatter(regl);
          }
          if (scene.fill2d === true) {
            scene.fill2d = createLine(regl);
          }
          if (scene.glText === true) {
            scene.glText = new Array(count);
            for (i = 0; i < count; i++) {
              scene.glText[i] = new Text(regl);
            }
          }
          if (scene.glText) {
            if (count > scene.glText.length) {
              var textsToAdd = count - scene.glText.length;
              for (i = 0; i < textsToAdd; i++) {
                scene.glText.push(new Text(regl));
              }
            } else if (count < scene.glText.length) {
              var textsToRemove = scene.glText.length - count;
              var removedTexts = scene.glText.splice(count, textsToRemove);
              removedTexts.forEach(function(text) {
                text.destroy();
              });
            }
            for (i = 0; i < count; i++) {
              scene.glText[i].update(scene.textOptions[i]);
            }
          }
          if (scene.line2d) {
            scene.line2d.update(scene.lineOptions);
            scene.lineOptions = scene.lineOptions.map(function(lineOptions) {
              if (lineOptions && lineOptions.positions) {
                var srcPos = lineOptions.positions;
                var firstptdef = 0;
                while (firstptdef < srcPos.length && (isNaN(srcPos[firstptdef]) || isNaN(srcPos[firstptdef + 1]))) {
                  firstptdef += 2;
                }
                var lastptdef = srcPos.length - 2;
                while (lastptdef > firstptdef && (isNaN(srcPos[lastptdef]) || isNaN(srcPos[lastptdef + 1]))) {
                  lastptdef -= 2;
                }
                lineOptions.positions = srcPos.slice(firstptdef, lastptdef + 2);
              }
              return lineOptions;
            });
            scene.line2d.update(scene.lineOptions);
          }
          if (scene.error2d) {
            var errorBatch = (scene.errorXOptions || []).concat(scene.errorYOptions || []);
            scene.error2d.update(errorBatch);
          }
          if (scene.scatter2d) {
            scene.scatter2d.update(scene.markerOptions);
          }
          scene.fillOrder = Lib.repeat(null, count);
          if (scene.fill2d) {
            scene.fillOptions = scene.fillOptions.map(function(fillOptions, i2) {
              var cdscatter = cdata[i2];
              if (!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
              var cd = cdscatter[0];
              var trace2 = cd.trace;
              var stash2 = cd.t;
              var lineOptions = scene.lineOptions[i2];
              var last, j2;
              var fillData = [];
              if (trace2._ownfill) fillData.push(i2);
              if (trace2._nexttrace) fillData.push(i2 + 1);
              if (fillData.length) scene.fillOrder[i2] = fillData;
              var pos = [];
              var srcPos = lineOptions && lineOptions.positions || stash2.positions;
              var firstptdef, lastptdef;
              if (trace2.fill === "tozeroy") {
                firstptdef = 0;
                while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef + 1])) {
                  firstptdef += 2;
                }
                lastptdef = srcPos.length - 2;
                while (lastptdef > firstptdef && isNaN(srcPos[lastptdef + 1])) {
                  lastptdef -= 2;
                }
                if (srcPos[firstptdef + 1] !== 0) {
                  pos = [srcPos[firstptdef], 0];
                }
                pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
                if (srcPos[lastptdef + 1] !== 0) {
                  pos = pos.concat([srcPos[lastptdef], 0]);
                }
              } else if (trace2.fill === "tozerox") {
                firstptdef = 0;
                while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef])) {
                  firstptdef += 2;
                }
                lastptdef = srcPos.length - 2;
                while (lastptdef > firstptdef && isNaN(srcPos[lastptdef])) {
                  lastptdef -= 2;
                }
                if (srcPos[firstptdef] !== 0) {
                  pos = [0, srcPos[firstptdef + 1]];
                }
                pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2));
                if (srcPos[lastptdef] !== 0) {
                  pos = pos.concat([0, srcPos[lastptdef + 1]]);
                }
              } else if (trace2.fill === "toself" || trace2.fill === "tonext") {
                pos = [];
                last = 0;
                fillOptions.splitNull = true;
                for (j2 = 0; j2 < srcPos.length; j2 += 2) {
                  if (isNaN(srcPos[j2]) || isNaN(srcPos[j2 + 1])) {
                    pos = pos.concat(srcPos.slice(last, j2));
                    pos.push(srcPos[last], srcPos[last + 1]);
                    pos.push(null, null);
                    last = j2 + 2;
                  }
                }
                pos = pos.concat(srcPos.slice(last));
                if (last) {
                  pos.push(srcPos[last], srcPos[last + 1]);
                }
              } else {
                var nextTrace = trace2._nexttrace;
                if (nextTrace) {
                  var nextOptions = scene.lineOptions[i2 + 1];
                  if (nextOptions) {
                    var nextPos = nextOptions.positions;
                    if (trace2.fill === "tonexty") {
                      pos = srcPos.slice();
                      for (i2 = Math.floor(nextPos.length / 2); i2--; ) {
                        var xx = nextPos[i2 * 2];
                        var yy = nextPos[i2 * 2 + 1];
                        if (isNaN(xx) || isNaN(yy)) continue;
                        pos.push(xx, yy);
                      }
                      fillOptions.fill = nextTrace.fillcolor;
                    }
                  }
                }
              }
              if (trace2._prevtrace && trace2._prevtrace.fill === "tonext") {
                var prevLinePos = scene.lineOptions[i2 - 1].positions;
                var offset = pos.length / 2;
                last = offset;
                var hole = [last];
                for (j2 = 0; j2 < prevLinePos.length; j2 += 2) {
                  if (isNaN(prevLinePos[j2]) || isNaN(prevLinePos[j2 + 1])) {
                    hole.push(j2 / 2 + offset + 1);
                    last = j2 + 2;
                  }
                }
                pos = pos.concat(prevLinePos);
                fillOptions.hole = hole;
              }
              fillOptions.fillmode = trace2.fill;
              fillOptions.opacity = trace2.opacity;
              fillOptions.positions = pos;
              return fillOptions;
            });
            scene.fill2d.update(scene.fillOptions);
          }
        }
        var dragmode = fullLayout.dragmode;
        var isSelectMode = selectMode(dragmode);
        var clickSelectEnabled = fullLayout.clickmode.indexOf("select") > -1;
        for (const [cd0] of cdata) {
          if (!cd0) continue;
          var trace = cd0.trace;
          var stash = cd0.t;
          var index = stash.index;
          var len = trace._length;
          var x = stash.x;
          var y = stash.y;
          if (trace.selectedpoints || isSelectMode || clickSelectEnabled) {
            if (!isSelectMode) isSelectMode = true;
            if (trace.selectedpoints) {
              var selPts = scene.selectBatch[index] = Lib.selIndices2selPoints(trace);
              var selDict = {};
              for (j = 0; j < selPts.length; j++) {
                selDict[selPts[j]] = 1;
              }
              var unselPts = [];
              for (j = 0; j < len; j++) {
                if (!selDict[j]) unselPts.push(j);
              }
              scene.unselectBatch[index] = unselPts;
            }
            var xpx = stash.xpx = new Array(len);
            var ypx = stash.ypx = new Array(len);
            for (j = 0; j < len; j++) {
              xpx[j] = xaxis.c2p(x[j]);
              ypx[j] = yaxis.c2p(y[j]);
            }
          } else {
            stash.xpx = stash.ypx = null;
          }
        }
        if (isSelectMode) {
          if (!scene.select2d) {
            scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl);
          }
          if (scene.scatter2d) {
            var unselOpts = new Array(count);
            for (i = 0; i < count; i++) {
              unselOpts[i] = scene.selectBatch[i].length || scene.unselectBatch[i].length ? scene.markerUnselectedOptions[i] : {};
            }
            scene.scatter2d.update(unselOpts);
          }
          if (scene.select2d) {
            scene.select2d.update(scene.markerOptions);
            scene.select2d.update(scene.markerSelectedOptions);
          }
          if (scene.glText) {
            cdata.forEach(function(cdscatter) {
              var trace2 = ((cdscatter || [])[0] || {}).trace || {};
              if (subTypes.hasText(trace2)) {
                styleTextSelection(cdscatter);
              }
            });
          }
        } else {
          if (scene.scatter2d) {
            scene.scatter2d.update(scene.markerOptions);
          }
        }
        var vpRange0 = {
          viewport: getViewport(fullLayout, xaxis, yaxis, gd._context.plotGlPixelRatio),
          // TODO do we need those fallbacks?
          range: [
            (xaxis._rl || xaxis.range)[0],
            (yaxis._rl || yaxis.range)[0],
            (xaxis._rl || xaxis.range)[1],
            (yaxis._rl || yaxis.range)[1]
          ]
        };
        var vpRange = Lib.repeat(vpRange0, scene.count);
        if (scene.fill2d) {
          scene.fill2d.update(vpRange);
        }
        if (scene.line2d) {
          scene.line2d.update(vpRange);
        }
        if (scene.error2d) {
          scene.error2d.update(vpRange.concat(vpRange));
        }
        if (scene.scatter2d) {
          scene.scatter2d.update(vpRange);
        }
        if (scene.select2d) {
          scene.select2d.update(vpRange);
        }
        if (scene.glText) {
          scene.glText.forEach(function(text) {
            text.update(vpRange0);
          });
        }
      };
      exports.reglPrecompiled = reglPrecompiled;
    }
  });

  // src/traces/scattergl/index.js
  var require_scattergl = __commonJS({
    "src/traces/scattergl/index.js"(exports, module) {
      "use strict";
      var index = require_base_index();
      index.plot = require_plot19();
      module.exports = index;
    }
  });

  // lib/scattergl.js
  var require_scattergl2 = __commonJS({
    "lib/scattergl.js"(exports, module) {
      "use strict";
      module.exports = require_scattergl();
    }
  });

  // src/traces/splom/attributes.js
  var require_attributes51 = __commonJS({
    "src/traces/splom/attributes.js"(exports, module) {
      "use strict";
      var scatterAttrs = require_attributes12();
      var colorScaleAttrs = require_attributes8();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var scatterGlAttrs = require_attributes50();
      var cartesianIdRegex = require_constants2().idRegex;
      var templatedArray = require_plot_template().templatedArray;
      var extendFlat = require_extend().extendFlat;
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      var markerLineAttrs = extendFlat(colorScaleAttrs("marker.line", { editTypeOverride: "calc" }), {
        width: extendFlat({}, scatterMarkerLineAttrs.width, { editType: "calc" }),
        editType: "calc"
      });
      var markerAttrs = extendFlat(colorScaleAttrs("marker"), {
        symbol: scatterMarkerAttrs.symbol,
        angle: scatterMarkerAttrs.angle,
        size: extendFlat({}, scatterMarkerAttrs.size, { editType: "markerSize" }),
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        opacity: scatterMarkerAttrs.opacity,
        colorbar: scatterMarkerAttrs.colorbar,
        line: markerLineAttrs,
        editType: "calc"
      });
      markerAttrs.color.editType = markerAttrs.cmin.editType = markerAttrs.cmax.editType = "style";
      function makeAxesValObject(axLetter) {
        return {
          valType: "info_array",
          freeLength: true,
          editType: "calc",
          items: {
            valType: "subplotid",
            regex: cartesianIdRegex[axLetter],
            editType: "plot"
          }
        };
      }
      module.exports = {
        dimensions: templatedArray("dimension", {
          visible: {
            valType: "boolean",
            dflt: true,
            editType: "calc"
          },
          label: {
            valType: "string",
            editType: "calc"
          },
          values: {
            valType: "data_array",
            editType: "calc+clearAxisTypes"
          },
          axis: {
            type: {
              valType: "enumerated",
              values: ["linear", "log", "date", "category"],
              editType: "calc+clearAxisTypes"
            },
            // TODO make 'true' the default in v3?
            matches: {
              valType: "boolean",
              dflt: false,
              editType: "calc"
            },
            editType: "calc+clearAxisTypes"
          },
          // TODO should add an attribute to pin down x only vars and y only vars
          // like https://seaborn.pydata.org/generated/seaborn.pairplot.html
          // x_vars and y_vars
          // maybe more axis defaulting option e.g. `showgrid: false`
          editType: "calc+clearAxisTypes"
        }),
        // mode: {}, (only 'markers' for now)
        text: extendFlat({}, scatterGlAttrs.text, {}),
        hovertext: extendFlat({}, scatterGlAttrs.hovertext, {}),
        hovertemplate: hovertemplateAttrs(),
        hovertemplatefallback: templatefallbackAttrs(),
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        marker: markerAttrs,
        xaxes: makeAxesValObject("x"),
        yaxes: makeAxesValObject("y"),
        diagonal: {
          visible: {
            valType: "boolean",
            dflt: true,
            editType: "calc"
          },
          // type: 'scattergl' | 'histogram' | 'box' | 'violin'
          // ...
          // more options
          editType: "calc"
        },
        showupperhalf: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        },
        showlowerhalf: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        },
        selected: {
          marker: scatterGlAttrs.selected.marker,
          editType: "calc"
        },
        unselected: {
          marker: scatterGlAttrs.unselected.marker,
          editType: "calc"
        },
        opacity: scatterGlAttrs.opacity
      };
    }
  });

  // src/traces/parcoords/merge_length.js
  var require_merge_length = __commonJS({
    "src/traces/parcoords/merge_length.js"(exports, module) {
      "use strict";
      module.exports = function(traceOut, dimensions, dataAttr, len) {
        if (!len) len = Infinity;
        var i, dimi;
        for (i = 0; i < dimensions.length; i++) {
          dimi = dimensions[i];
          if (dimi.visible) len = Math.min(len, dimi[dataAttr].length);
        }
        if (len === Infinity) len = 0;
        traceOut._length = len;
        for (i = 0; i < dimensions.length; i++) {
          dimi = dimensions[i];
          if (dimi.visible) dimi._length = len;
        }
        return len;
      };
    }
  });

  // src/traces/splom/defaults.js
  var require_defaults47 = __commonJS({
    "src/traces/splom/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes51();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var mergeLength = require_merge_length();
      var isOpenSymbol = require_helpers16().isOpenSymbol;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
          name: "dimensions",
          handleItemDefaults: dimensionDefaults
        });
        var showDiag = coerce("diagonal.visible");
        var showUpper = coerce("showupperhalf");
        var showLower = coerce("showlowerhalf");
        var dimLength = mergeLength(traceOut, dimensions, "values");
        if (!dimLength || !showDiag && !showUpper && !showLower) {
          traceOut.visible = false;
          return;
        }
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("xhoverformat");
        coerce("yhoverformat");
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
          noAngleRef: true,
          noLineDash: true,
          noStandOff: true
        });
        var isOpen = isOpenSymbol(traceOut.marker.symbol);
        var isBubble = subTypes.isBubble(traceOut);
        coerce("marker.line.width", isOpen || isBubble ? 1 : 0);
        handleAxisDefaults(traceIn, traceOut, layout, coerce);
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
      function dimensionDefaults(dimIn, dimOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(dimIn, dimOut, attributes.dimensions, attr, dflt);
        }
        coerce("label");
        var values = coerce("values");
        if (!(values && values.length)) dimOut.visible = false;
        else coerce("visible");
        coerce("axis.type");
        coerce("axis.matches");
      }
      function handleAxisDefaults(traceIn, traceOut, layout, coerce) {
        var dimensions = traceOut.dimensions;
        var dimLength = dimensions.length;
        var showUpper = traceOut.showupperhalf;
        var showLower = traceOut.showlowerhalf;
        var showDiag = traceOut.diagonal.visible;
        var i, j;
        var xAxesDflt = new Array(dimLength);
        var yAxesDflt = new Array(dimLength);
        for (i = 0; i < dimLength; i++) {
          var suffix = i ? i + 1 : "";
          xAxesDflt[i] = "x" + suffix;
          yAxesDflt[i] = "y" + suffix;
        }
        var xaxes = coerce("xaxes", xAxesDflt);
        var yaxes = coerce("yaxes", yAxesDflt);
        var diag = traceOut._diag = new Array(dimLength);
        traceOut._xaxes = {};
        traceOut._yaxes = {};
        var xList = [];
        var yList = [];
        function fillAxisStashes(axId, counterAxId, dim2, list) {
          if (!axId) return;
          var axLetter = axId.charAt(0);
          var stash = layout._splomAxes[axLetter];
          traceOut["_" + axLetter + "axes"][axId] = 1;
          list.push(axId);
          if (!(axId in stash)) {
            var s = stash[axId] = {};
            if (dim2) {
              s.label = dim2.label || "";
              if (dim2.visible && dim2.axis) {
                if (dim2.axis.type) s.type = dim2.axis.type;
                if (dim2.axis.matches) s.matches = counterAxId;
              }
            }
          }
        }
        var mustShiftX = !showDiag && !showLower;
        var mustShiftY = !showDiag && !showUpper;
        traceOut._axesDim = {};
        for (i = 0; i < dimLength; i++) {
          var dim = dimensions[i];
          var i0 = i === 0;
          var iN = i === dimLength - 1;
          var xaId = i0 && mustShiftX || iN && mustShiftY ? void 0 : xaxes[i];
          var yaId = i0 && mustShiftY || iN && mustShiftX ? void 0 : yaxes[i];
          fillAxisStashes(xaId, yaId, dim, xList);
          fillAxisStashes(yaId, xaId, dim, yList);
          diag[i] = [xaId, yaId];
          traceOut._axesDim[xaId] = i;
          traceOut._axesDim[yaId] = i;
        }
        for (i = 0; i < xList.length; i++) {
          for (j = 0; j < yList.length; j++) {
            var id = xList[i] + yList[j];
            if (i > j && showUpper) {
              layout._splomSubplots[id] = 1;
            } else if (i < j && showLower) {
              layout._splomSubplots[id] = 1;
            } else if (i === j && (showDiag || !showLower || !showUpper)) {
              layout._splomSubplots[id] = 1;
            }
          }
        }
        if (!showLower || !showDiag && showUpper && showLower) {
          layout._splomGridDflt.xside = "bottom";
          layout._splomGridDflt.yside = "left";
        }
      }
    }
  });

  // src/traces/splom/scene_update.js
  var require_scene_update2 = __commonJS({
    "src/traces/splom/scene_update.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function sceneUpdate(gd, trace) {
        var fullLayout = gd._fullLayout;
        var uid = trace.uid;
        var splomScenes = fullLayout._splomScenes;
        if (!splomScenes) splomScenes = fullLayout._splomScenes = {};
        var reset = {
          dirty: true,
          selectBatch: [],
          unselectBatch: []
        };
        var first = {
          matrix: false,
          selectBatch: [],
          unselectBatch: []
        };
        var scene = splomScenes[trace.uid];
        if (!scene) {
          scene = splomScenes[uid] = Lib.extendFlat({}, reset, first);
          scene.draw = function draw() {
            if (scene.matrix && scene.matrix.draw) {
              if (scene.selectBatch.length || scene.unselectBatch.length) {
                scene.matrix.draw(scene.unselectBatch, scene.selectBatch);
              } else {
                scene.matrix.draw();
              }
            }
            scene.dirty = false;
          };
          scene.destroy = function destroy() {
            if (scene.matrix && scene.matrix.destroy) {
              scene.matrix.destroy();
            }
            scene.matrixOptions = null;
            scene.selectBatch = null;
            scene.unselectBatch = null;
            scene = null;
          };
        }
        if (!scene.dirty) {
          Lib.extendFlat(scene, reset);
        }
        return scene;
      };
    }
  });

  // src/traces/splom/calc.js
  var require_calc30 = __commonJS({
    "src/traces/splom/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var AxisIDs = require_axis_ids();
      var calcMarkerSize = require_calc3().calcMarkerSize;
      var calcAxisExpansion = require_calc3().calcAxisExpansion;
      var calcColorscale = require_colorscale_calc();
      var convertMarkerSelection = require_convert10().markerSelection;
      var convertMarkerStyle = require_convert10().markerStyle;
      var sceneUpdate = require_scene_update2();
      var BADNUM = require_numerical().BADNUM;
      var TOO_MANY_POINTS = require_constants23().TOO_MANY_POINTS;
      module.exports = function calc(gd, trace) {
        var dimensions = trace.dimensions;
        var commonLength = trace._length;
        var opts = {};
        var cdata = opts.cdata = [];
        var ldata = opts.data = [];
        var visibleDims = trace._visibleDims = [];
        var i, k, dim, xa, ya;
        function makeCalcdata(ax, dim2) {
          var ccol = ax.makeCalcdata({
            v: dim2.values,
            vcalendar: trace.calendar
          }, "v");
          for (var j = 0; j < ccol.length; j++) {
            ccol[j] = ccol[j] === BADNUM ? NaN : ccol[j];
          }
          cdata.push(ccol);
          ldata.push(ax.type === "log" ? Lib.simpleMap(ccol, ax.c2l) : ccol);
        }
        for (i = 0; i < dimensions.length; i++) {
          dim = dimensions[i];
          if (dim.visible) {
            xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
            ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
            if (xa && ya && xa.type !== ya.type) {
              Lib.log("Skipping splom dimension " + i + " with conflicting axis types");
              continue;
            }
            if (xa) {
              makeCalcdata(xa, dim);
              if (ya && ya.type === "category") {
                ya._categories = xa._categories.slice();
              }
            } else {
              makeCalcdata(ya, dim);
            }
            visibleDims.push(i);
          }
        }
        calcColorscale(gd, trace);
        Lib.extendFlat(opts, convertMarkerStyle(gd, trace));
        var visibleLength = cdata.length;
        var hasTooManyPoints = visibleLength * commonLength > TOO_MANY_POINTS;
        var ppad;
        if (hasTooManyPoints) {
          ppad = opts.sizeAvg || Math.max(opts.size, 3);
        } else {
          ppad = calcMarkerSize(trace, commonLength);
        }
        for (k = 0; k < visibleDims.length; k++) {
          i = visibleDims[k];
          dim = dimensions[i];
          xa = AxisIDs.getFromId(gd, trace._diag[i][0]) || {};
          ya = AxisIDs.getFromId(gd, trace._diag[i][1]) || {};
          calcAxisExpansion(gd, trace, xa, ya, cdata[k], cdata[k], ppad);
        }
        var scene = sceneUpdate(gd, trace);
        if (!scene.matrix) scene.matrix = true;
        scene.matrixOptions = opts;
        scene.selectedOptions = convertMarkerSelection(gd, trace, trace.selected);
        scene.unselectedOptions = convertMarkerSelection(gd, trace, trace.unselected);
        return [{ x: false, y: false, t: {}, trace }];
      };
    }
  });

  // node_modules/performance-now/lib/performance-now.js
  var require_performance_now = __commonJS({
    "node_modules/performance-now/lib/performance-now.js"(exports, module) {
      (function() {
        var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
        if (typeof performance !== "undefined" && performance !== null && performance.now) {
          module.exports = function() {
            return performance.now();
          };
        } else if (typeof process !== "undefined" && process !== null && process.hrtime) {
          module.exports = function() {
            return (getNanoSeconds() - nodeLoadTime) / 1e6;
          };
          hrtime = process.hrtime;
          getNanoSeconds = function() {
            var hr;
            hr = hrtime();
            return hr[0] * 1e9 + hr[1];
          };
          moduleLoadTime = getNanoSeconds();
          upTime = process.uptime() * 1e9;
          nodeLoadTime = moduleLoadTime - upTime;
        } else if (Date.now) {
          module.exports = function() {
            return Date.now() - loadTime;
          };
          loadTime = Date.now();
        } else {
          module.exports = function() {
            return (/* @__PURE__ */ new Date()).getTime() - loadTime;
          };
          loadTime = (/* @__PURE__ */ new Date()).getTime();
        }
      }).call(exports);
    }
  });

  // node_modules/raf/index.js
  var require_raf = __commonJS({
    "node_modules/raf/index.js"(exports, module) {
      var now = require_performance_now();
      var root = typeof window === "undefined" ? window : window;
      var vendors = ["moz", "webkit"];
      var suffix = "AnimationFrame";
      var raf = root["request" + suffix];
      var caf = root["cancel" + suffix] || root["cancelRequest" + suffix];
      for (i = 0; !raf && i < vendors.length; i++) {
        raf = root[vendors[i] + "Request" + suffix];
        caf = root[vendors[i] + "Cancel" + suffix] || root[vendors[i] + "CancelRequest" + suffix];
      }
      var i;
      if (!raf || !caf) {
        last = 0, id = 0, queue = [], frameDuration = 1e3 / 60;
        raf = function(callback) {
          if (queue.length === 0) {
            var _now = now(), next = Math.max(0, frameDuration - (_now - last));
            last = next + _now;
            setTimeout(function() {
              var cp = queue.slice(0);
              queue.length = 0;
              for (var i2 = 0; i2 < cp.length; i2++) {
                if (!cp[i2].cancelled) {
                  try {
                    cp[i2].callback(last);
                  } catch (e) {
                    setTimeout(function() {
                      throw e;
                    }, 0);
                  }
                }
              }
            }, Math.round(next));
          }
          queue.push({
            handle: ++id,
            callback,
            cancelled: false
          });
          return id;
        };
        caf = function(handle) {
          for (var i2 = 0; i2 < queue.length; i2++) {
            if (queue[i2].handle === handle) {
              queue[i2].cancelled = true;
            }
          }
        };
      }
      var last;
      var id;
      var queue;
      var frameDuration;
      module.exports = function(fn) {
        return raf.call(root, fn);
      };
      module.exports.cancel = function() {
        caf.apply(root, arguments);
      };
      module.exports.polyfill = function(object) {
        if (!object) {
          object = root;
        }
        object.requestAnimationFrame = raf;
        object.cancelAnimationFrame = caf;
      };
    }
  });

  // node_modules/array-range/index.js
  var require_array_range = __commonJS({
    "node_modules/array-range/index.js"(exports, module) {
      module.exports = function newArray(start, end) {
        var n0 = typeof start === "number", n1 = typeof end === "number";
        if (n0 && !n1) {
          end = start;
          start = 0;
        } else if (!n0 && !n1) {
          start = 0;
          end = 0;
        }
        start = start | 0;
        end = end | 0;
        var len = end - start;
        if (len < 0)
          throw new Error("array length must be positive");
        var a = new Array(len);
        for (var i = 0, c = start; i < len; i++, c++)
          a[i] = c;
        return a;
      };
    }
  });

  // node_modules/regl-splom/index.js
  var require_regl_splom = __commonJS({
    "node_modules/regl-splom/index.js"(exports, module) {
      "use strict";
      var createScatter = require_bundle();
      var pick = require_pick_by_alias();
      var getBounds = require_array_bounds();
      var raf = require_raf();
      var arrRange = require_array_range();
      var rect = require_parse_rect();
      var flatten = require_flatten_vertex_data();
      module.exports = SPLOM;
      function SPLOM(regl, options) {
        if (!(this instanceof SPLOM)) return new SPLOM(regl, options);
        this.traces = [];
        this.passes = {};
        this.regl = regl;
        this.scatter = createScatter(regl);
        this.canvas = this.scatter.canvas;
      }
      SPLOM.prototype.render = function(...args) {
        if (args.length) {
          this.update(...args);
        }
        if (this.regl.attributes.preserveDrawingBuffer) return this.draw();
        if (this.dirty) {
          if (this.planned == null) {
            this.planned = raf(() => {
              this.draw();
              this.dirty = true;
              this.planned = null;
            });
          }
        } else {
          this.draw();
          this.dirty = true;
          raf(() => {
            this.dirty = false;
          });
        }
        return this;
      };
      SPLOM.prototype.update = function(...args) {
        if (!args.length) return;
        for (let i = 0; i < args.length; i++) {
          this.updateItem(i, args[i]);
        }
        this.traces = this.traces.filter(Boolean);
        let passes = [];
        let offset = 0;
        for (let i = 0; i < this.traces.length; i++) {
          let trace = this.traces[i];
          let tracePasses = this.traces[i].passes;
          for (let j = 0; j < tracePasses.length; j++) {
            passes.push(this.passes[tracePasses[j]]);
          }
          trace.passOffset = offset;
          offset += trace.passes.length;
        }
        this.scatter.update(...passes);
        return this;
      };
      SPLOM.prototype.updateItem = function(i, options) {
        let { regl } = this;
        if (options === null) {
          this.traces[i] = null;
          return this;
        }
        if (!options) return this;
        let o = pick(options, {
          data: "data items columns rows values dimensions samples x",
          snap: "snap cluster",
          size: "sizes size radius",
          color: "colors color fill fill-color fillColor",
          opacity: "opacity alpha transparency opaque",
          borderSize: "borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline",
          borderColor: "borderColors borderColor bordercolor stroke stroke-color strokeColor",
          marker: "markers marker shape",
          range: "range ranges databox dataBox",
          viewport: "viewport viewBox viewbox",
          domain: "domain domains area areas",
          padding: "pad padding paddings pads margin margins",
          transpose: "transpose transposed",
          diagonal: "diagonal diag showDiagonal",
          upper: "upper up top upperhalf upperHalf showupperhalf showUpper showUpperHalf",
          lower: "lower low bottom lowerhalf lowerHalf showlowerhalf showLowerHalf showLower"
        });
        let trace = this.traces[i] || (this.traces[i] = {
          id: i,
          buffer: regl.buffer({
            usage: "dynamic",
            type: "float",
            data: new Uint8Array()
          }),
          color: "black",
          marker: null,
          size: 12,
          borderColor: "transparent",
          borderSize: 1,
          viewport: rect([regl._gl.drawingBufferWidth, regl._gl.drawingBufferHeight]),
          padding: [0, 0, 0, 0],
          opacity: 1,
          diagonal: true,
          upper: true,
          lower: true
        });
        if (o.color != null) {
          trace.color = o.color;
        }
        if (o.size != null) {
          trace.size = o.size;
        }
        if (o.marker != null) {
          trace.marker = o.marker;
        }
        if (o.borderColor != null) {
          trace.borderColor = o.borderColor;
        }
        if (o.borderSize != null) {
          trace.borderSize = o.borderSize;
        }
        if (o.opacity != null) {
          trace.opacity = o.opacity;
        }
        if (o.viewport) {
          trace.viewport = rect(o.viewport);
        }
        if (o.diagonal != null) trace.diagonal = o.diagonal;
        if (o.upper != null) trace.upper = o.upper;
        if (o.lower != null) trace.lower = o.lower;
        if (o.data) {
          trace.buffer(flatten(o.data));
          trace.columns = o.data.length;
          trace.count = o.data[0].length;
          trace.bounds = [];
          for (let i2 = 0; i2 < trace.columns; i2++) {
            trace.bounds[i2] = getBounds(o.data[i2], 1);
          }
        }
        let multirange;
        if (o.range) {
          trace.range = o.range;
          multirange = trace.range && typeof trace.range[0] !== "number";
        }
        if (o.domain) {
          trace.domain = o.domain;
        }
        let multipadding = false;
        if (o.padding != null) {
          if (Array.isArray(o.padding) && o.padding.length === trace.columns && typeof o.padding[o.padding.length - 1] === "number") {
            trace.padding = o.padding.map(getPad);
            multipadding = true;
          } else {
            trace.padding = getPad(o.padding);
          }
        }
        let m = trace.columns;
        let n = trace.count;
        let w = trace.viewport.width;
        let h = trace.viewport.height;
        let left = trace.viewport.x;
        let top = trace.viewport.y;
        let iw = w / m;
        let ih = h / m;
        trace.passes = [];
        for (let i2 = 0; i2 < m; i2++) {
          for (let j = 0; j < m; j++) {
            if (!trace.diagonal && j === i2) continue;
            if (!trace.upper && i2 > j) continue;
            if (!trace.lower && i2 < j) continue;
            let key = passId(trace.id, i2, j);
            let pass = this.passes[key] || (this.passes[key] = {});
            if (o.data) {
              if (o.transpose) {
                pass.positions = {
                  x: { buffer: trace.buffer, offset: j, count: n, stride: m },
                  y: { buffer: trace.buffer, offset: i2, count: n, stride: m }
                };
              } else {
                pass.positions = {
                  x: { buffer: trace.buffer, offset: j * n, count: n },
                  y: { buffer: trace.buffer, offset: i2 * n, count: n }
                };
              }
              pass.bounds = getBox(trace.bounds, i2, j);
            }
            if (o.domain || o.viewport || o.data) {
              let pad = multipadding ? getBox(trace.padding, i2, j) : trace.padding;
              if (trace.domain) {
                let [lox, loy, hix, hiy] = getBox(trace.domain, i2, j);
                pass.viewport = [
                  left + lox * w + pad[0],
                  top + loy * h + pad[1],
                  left + hix * w - pad[2],
                  top + hiy * h - pad[3]
                ];
              } else {
                pass.viewport = [
                  left + j * iw + iw * pad[0],
                  top + i2 * ih + ih * pad[1],
                  left + (j + 1) * iw - iw * pad[2],
                  top + (i2 + 1) * ih - ih * pad[3]
                ];
              }
            }
            if (o.color) pass.color = trace.color;
            if (o.size) pass.size = trace.size;
            if (o.marker) pass.marker = trace.marker;
            if (o.borderSize) pass.borderSize = trace.borderSize;
            if (o.borderColor) pass.borderColor = trace.borderColor;
            if (o.opacity) pass.opacity = trace.opacity;
            if (o.range) {
              pass.range = multirange ? getBox(trace.range, i2, j) : trace.range || pass.bounds;
            }
            trace.passes.push(key);
          }
        }
        return this;
      };
      SPLOM.prototype.draw = function(...args) {
        if (!args.length) {
          this.scatter.draw();
        } else {
          let idx = [];
          for (let i = 0; i < args.length; i++) {
            if (typeof args[i] === "number") {
              let { passes, passOffset } = this.traces[args[i]];
              idx.push(...arrRange(passOffset, passOffset + passes.length));
            } else if (args[i].length) {
              let els = args[i];
              let { passes, passOffset } = this.traces[i];
              passes = passes.map((passId2, i2) => {
                idx[passOffset + i2] = els;
              });
            }
          }
          this.scatter.draw(...idx);
        }
        return this;
      };
      SPLOM.prototype.destroy = function() {
        this.traces.forEach((trace) => {
          if (trace.buffer && trace.buffer.destroy) trace.buffer.destroy();
        });
        this.traces = null;
        this.passes = null;
        this.scatter.destroy();
        return this;
      };
      function passId(trace, i, j) {
        let id = trace.id != null ? trace.id : trace;
        let n = i;
        let m = j;
        let key = id << 16 | (n & 255) << 8 | m & 255;
        return key;
      }
      function getBox(items, i, j) {
        let ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy;
        let iitem = items[i], jitem = items[j];
        if (iitem.length > 2) {
          ilox = iitem[0];
          ihix = iitem[2];
          iloy = iitem[1];
          ihiy = iitem[3];
        } else if (iitem.length) {
          ilox = iloy = iitem[0];
          ihix = ihiy = iitem[1];
        } else {
          ilox = iitem.x;
          iloy = iitem.y;
          ihix = iitem.x + iitem.width;
          ihiy = iitem.y + iitem.height;
        }
        if (jitem.length > 2) {
          jlox = jitem[0];
          jhix = jitem[2];
          jloy = jitem[1];
          jhiy = jitem[3];
        } else if (jitem.length) {
          jlox = jloy = jitem[0];
          jhix = jhiy = jitem[1];
        } else {
          jlox = jitem.x;
          jloy = jitem.y;
          jhix = jitem.x + jitem.width;
          jhiy = jitem.y + jitem.height;
        }
        return [jlox, iloy, jhix, ihiy];
      }
      function getPad(arg) {
        if (typeof arg === "number") return [arg, arg, arg, arg];
        else if (arg.length === 2) return [arg[0], arg[1], arg[0], arg[1]];
        else {
          let box = rect(arg);
          return [box.x, box.y, box.x + box.width, box.y + box.height];
        }
      }
    }
  });

  // src/traces/splom/plot.js
  var require_plot20 = __commonJS({
    "src/traces/splom/plot.js"(exports, module) {
      "use strict";
      var createMatrix = require_regl_splom();
      var Lib = require_lib();
      var AxisIDs = require_axis_ids();
      var selectMode = require_helpers5().selectMode;
      module.exports = function plot(gd, _, splomCalcData) {
        if (!splomCalcData.length) return;
        for (var i = 0; i < splomCalcData.length; i++) {
          plotOne(gd, splomCalcData[i][0]);
        }
      };
      function plotOne(gd, cd0) {
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        var trace = cd0.trace;
        var stash = cd0.t;
        var scene = fullLayout._splomScenes[trace.uid];
        var matrixOpts = scene.matrixOptions;
        var cdata = matrixOpts.cdata;
        var regl = fullLayout._glcanvas.data()[0].regl;
        var dragmode = fullLayout.dragmode;
        var xa, ya;
        var i, j, k;
        if (cdata.length === 0) return;
        matrixOpts.lower = trace.showupperhalf;
        matrixOpts.upper = trace.showlowerhalf;
        matrixOpts.diagonal = trace.diagonal.visible;
        var visibleDims = trace._visibleDims;
        var visibleLength = cdata.length;
        var viewOpts = scene.viewOpts = {};
        viewOpts.ranges = new Array(visibleLength);
        viewOpts.domains = new Array(visibleLength);
        for (k = 0; k < visibleDims.length; k++) {
          i = visibleDims[k];
          var rng = viewOpts.ranges[k] = new Array(4);
          var dmn = viewOpts.domains[k] = new Array(4);
          xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
          if (xa) {
            rng[0] = xa._rl[0];
            rng[2] = xa._rl[1];
            dmn[0] = xa.domain[0];
            dmn[2] = xa.domain[1];
          }
          ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
          if (ya) {
            rng[1] = ya._rl[0];
            rng[3] = ya._rl[1];
            dmn[1] = ya.domain[0];
            dmn[3] = ya.domain[1];
          }
        }
        var plotGlPixelRatio = gd._context.plotGlPixelRatio;
        var l = gs.l * plotGlPixelRatio;
        var b = gs.b * plotGlPixelRatio;
        var w = gs.w * plotGlPixelRatio;
        var h = gs.h * plotGlPixelRatio;
        viewOpts.viewport = [l, b, w + l, h + b];
        if (scene.matrix === true) {
          scene.matrix = createMatrix(regl);
        }
        var clickSelectEnabled = fullLayout.clickmode.indexOf("select") > -1;
        var isSelectMode = selectMode(dragmode) || !!trace.selectedpoints || clickSelectEnabled;
        var needsBaseUpdate = true;
        if (isSelectMode) {
          var commonLength = trace._length;
          if (trace.selectedpoints) {
            scene.selectBatch = trace.selectedpoints;
            var selPts = trace.selectedpoints;
            var selDict = {};
            for (i = 0; i < selPts.length; i++) {
              selDict[selPts[i]] = true;
            }
            var unselPts = [];
            for (i = 0; i < commonLength; i++) {
              if (!selDict[i]) unselPts.push(i);
            }
            scene.unselectBatch = unselPts;
          }
          var xpx = stash.xpx = new Array(visibleLength);
          var ypx = stash.ypx = new Array(visibleLength);
          for (k = 0; k < visibleDims.length; k++) {
            i = visibleDims[k];
            xa = AxisIDs.getFromId(gd, trace._diag[i][0]);
            if (xa) {
              xpx[k] = new Array(commonLength);
              for (j = 0; j < commonLength; j++) {
                xpx[k][j] = xa.c2p(cdata[k][j]);
              }
            }
            ya = AxisIDs.getFromId(gd, trace._diag[i][1]);
            if (ya) {
              ypx[k] = new Array(commonLength);
              for (j = 0; j < commonLength; j++) {
                ypx[k][j] = ya.c2p(cdata[k][j]);
              }
            }
          }
          if (scene.selectBatch.length || scene.unselectBatch.length) {
            var unselOpts = Lib.extendFlat({}, matrixOpts, scene.unselectedOptions, viewOpts);
            var selOpts = Lib.extendFlat({}, matrixOpts, scene.selectedOptions, viewOpts);
            scene.matrix.update(unselOpts, selOpts);
            needsBaseUpdate = false;
          }
        } else {
          stash.xpx = stash.ypx = null;
        }
        if (needsBaseUpdate) {
          var opts = Lib.extendFlat({}, matrixOpts, viewOpts);
          scene.matrix.update(opts, null);
        }
      }
    }
  });

  // src/traces/splom/helpers.js
  var require_helpers17 = __commonJS({
    "src/traces/splom/helpers.js"(exports) {
      "use strict";
      exports.getDimIndex = function getDimIndex(trace, ax) {
        var axId = ax._id;
        var axLetter = axId.charAt(0);
        var ind = { x: 0, y: 1 }[axLetter];
        var visibleDims = trace._visibleDims;
        for (var k = 0; k < visibleDims.length; k++) {
          var i = visibleDims[k];
          if (trace._diag[i][ind] === axId) return k;
        }
        return false;
      };
    }
  });

  // src/traces/splom/hover.js
  var require_hover17 = __commonJS({
    "src/traces/splom/hover.js"(exports, module) {
      "use strict";
      var helpers = require_helpers17();
      var calcHover = require_hover16().calcHover;
      var getFromId = require_axes().getFromId;
      var extendFlat = require_extend().extendFlat;
      function hoverPoints(pointData, xval, yval, hovermode, opts) {
        if (!opts) opts = {};
        var hovermodeHasX = (hovermode || "").charAt(0) === "x";
        var hovermodeHasY = (hovermode || "").charAt(0) === "y";
        var points = _hoverPoints(pointData, xval, yval);
        if ((hovermodeHasX || hovermodeHasY) && opts.hoversubplots === "axis" && points[0]) {
          var subplotsWith = (hovermodeHasX ? pointData.xa : pointData.ya)._subplotsWith;
          var gd = opts.gd;
          var _pointData = extendFlat({}, pointData);
          for (var i = 0; i < subplotsWith.length; i++) {
            var spId = subplotsWith[i];
            if (spId === pointData.xa._id + pointData.ya._id) continue;
            if (hovermodeHasY) {
              _pointData.xa = getFromId(gd, spId, "x");
            } else {
              _pointData.ya = getFromId(gd, spId, "y");
            }
            var axisHoversubplots = hovermodeHasX || hovermodeHasY;
            var newPoints = _hoverPoints(_pointData, xval, yval, axisHoversubplots);
            points = points.concat(newPoints);
          }
        }
        return points;
      }
      function _hoverPoints(pointData, xval, yval, axisHoversubplots) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var scene = pointData.scene;
        var cdata = scene.matrixOptions.cdata;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var xpx = xa.c2p(xval);
        var ypx = ya.c2p(yval);
        var maxDistance = pointData.distance;
        var xi = helpers.getDimIndex(trace, xa);
        var yi = helpers.getDimIndex(trace, ya);
        if (xi === false || yi === false) return [pointData];
        var x = cdata[xi];
        var y = cdata[yi];
        var id, dxy;
        var minDist = maxDistance;
        for (var i = 0; i < x.length; i++) {
          if (axisHoversubplots && i !== pointData.index) continue;
          var ptx = x[i];
          var pty = y[i];
          var dx = xa.c2p(ptx) - xpx;
          var dy = ya.c2p(pty) - ypx;
          var dist = Math.sqrt(dx * dx + dy * dy);
          if (axisHoversubplots || dist < minDist) {
            minDist = dxy = dist;
            id = i;
          }
        }
        pointData.index = id;
        pointData.distance = minDist;
        pointData.dxy = dxy;
        if (id === void 0) return [pointData];
        return [calcHover(pointData, x, y, trace)];
      }
      module.exports = {
        hoverPoints
      };
    }
  });

  // src/traces/splom/select.js
  var require_select8 = __commonJS({
    "src/traces/splom/select.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var pushUnique = Lib.pushUnique;
      var subTypes = require_subtypes();
      var helpers = require_helpers17();
      module.exports = function select(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var trace = cd[0].trace;
        var stash = cd[0].t;
        var scene = searchInfo.scene;
        var cdata = scene.matrixOptions.cdata;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        if (!scene) return selection;
        var hasOnlyLines = !subTypes.hasMarkers(trace) && !subTypes.hasText(trace);
        if (trace.visible !== true || hasOnlyLines) return selection;
        var xi = helpers.getDimIndex(trace, xa);
        var yi = helpers.getDimIndex(trace, ya);
        if (xi === false || yi === false) return selection;
        var xpx = stash.xpx[xi];
        var ypx = stash.ypx[yi];
        var x = cdata[xi];
        var y = cdata[yi];
        var els = (searchInfo.scene.selectBatch || []).slice();
        var unels = [];
        if (selectionTester !== false && !selectionTester.degenerate) {
          for (var i = 0; i < x.length; i++) {
            if (selectionTester.contains([xpx[i], ypx[i]], null, i, searchInfo)) {
              selection.push({
                pointNumber: i,
                x: x[i],
                y: y[i]
              });
              pushUnique(els, i);
            } else if (els.indexOf(i) !== -1) {
              pushUnique(els, i);
            } else {
              unels.push(i);
            }
          }
        }
        var matrixOpts = scene.matrixOptions;
        if (!els.length && !unels.length) {
          scene.matrix.update(matrixOpts, null);
        } else if (!scene.selectBatch.length && !scene.unselectBatch.length) {
          scene.matrix.update(
            scene.unselectedOptions,
            Lib.extendFlat({}, matrixOpts, scene.selectedOptions, scene.viewOpts)
          );
        }
        scene.selectBatch = els;
        scene.unselectBatch = unels;
        return selection;
      };
    }
  });

  // src/traces/splom/edit_style.js
  var require_edit_style2 = __commonJS({
    "src/traces/splom/edit_style.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var calcColorscale = require_colorscale_calc();
      var convertMarkerStyle = require_convert10().markerStyle;
      module.exports = function editStyle(gd, cd0) {
        var trace = cd0.trace;
        var scene = gd._fullLayout._splomScenes[trace.uid];
        if (scene) {
          calcColorscale(gd, trace);
          Lib.extendFlat(scene.matrixOptions, convertMarkerStyle(gd, trace));
          var opts = Lib.extendFlat({}, scene.matrixOptions, scene.viewOpts);
          scene.matrix.update(opts, null);
        }
      };
    }
  });

  // src/traces/splom/base_index.js
  var require_base_index2 = __commonJS({
    "src/traces/splom/base_index.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Grid = require_grid();
      module.exports = {
        moduleType: "trace",
        name: "splom",
        categories: ["gl", "regl", "cartesian", "symbols", "showLegend", "scatter-like"],
        attributes: require_attributes51(),
        supplyDefaults: require_defaults47(),
        colorbar: require_marker_colorbar(),
        calc: require_calc30(),
        plot: require_plot20(),
        hoverPoints: require_hover17().hoverPoints,
        selectPoints: require_select8(),
        editStyle: require_edit_style2(),
        meta: {}
      };
      Registry.register(Grid);
    }
  });

  // src/traces/splom/base_plot.js
  var require_base_plot6 = __commonJS({
    "src/traces/splom/base_plot.js"(exports, module) {
      "use strict";
      var createLine = require_regl_line2d();
      var Registry = require_registry();
      var prepareRegl = require_prepare_regl();
      var getModuleCalcData = require_get_data().getModuleCalcData;
      var Cartesian = require_cartesian();
      var getFromId = require_axis_ids().getFromId;
      var shouldShowZeroLine = require_axes().shouldShowZeroLine;
      var SPLOM = "splom";
      var reglPrecompiled = {};
      function plot(gd) {
        var fullLayout = gd._fullLayout;
        var _module = Registry.getModule(SPLOM);
        var splomCalcData = getModuleCalcData(gd.calcdata, _module)[0];
        var success = prepareRegl(gd, ["ANGLE_instanced_arrays", "OES_element_index_uint"], reglPrecompiled);
        if (!success) return;
        if (fullLayout._hasOnlyLargeSploms) {
          updateGrid(gd);
        }
        _module.plot(gd, {}, splomCalcData);
      }
      function drag(gd) {
        var cd = gd.calcdata;
        var fullLayout = gd._fullLayout;
        if (fullLayout._hasOnlyLargeSploms) {
          updateGrid(gd);
        }
        for (var i = 0; i < cd.length; i++) {
          var cd0 = cd[i][0];
          var trace = cd0.trace;
          var scene = fullLayout._splomScenes[trace.uid];
          if (trace.type === "splom" && scene && scene.matrix) {
            dragOne(gd, trace, scene);
          }
        }
      }
      function dragOne(gd, trace, scene) {
        var visibleLength = scene.matrixOptions.data.length;
        var visibleDims = trace._visibleDims;
        var ranges = scene.viewOpts.ranges = new Array(visibleLength);
        for (var k = 0; k < visibleDims.length; k++) {
          var i = visibleDims[k];
          var rng = ranges[k] = new Array(4);
          var xa = getFromId(gd, trace._diag[i][0]);
          if (xa) {
            rng[0] = xa.r2l(xa.range[0]);
            rng[2] = xa.r2l(xa.range[1]);
          }
          var ya = getFromId(gd, trace._diag[i][1]);
          if (ya) {
            rng[1] = ya.r2l(ya.range[0]);
            rng[3] = ya.r2l(ya.range[1]);
          }
        }
        if (scene.selectBatch.length || scene.unselectBatch.length) {
          scene.matrix.update({ ranges }, { ranges });
        } else {
          scene.matrix.update({ ranges });
        }
      }
      function updateGrid(gd) {
        var fullLayout = gd._fullLayout;
        var regl = fullLayout._glcanvas.data()[0].regl;
        var splomGrid = fullLayout._splomGrid;
        if (!splomGrid) {
          splomGrid = fullLayout._splomGrid = createLine(regl);
        }
        splomGrid.update(makeGridData(gd));
      }
      function makeGridData(gd) {
        var plotGlPixelRatio = gd._context.plotGlPixelRatio;
        var fullLayout = gd._fullLayout;
        var gs = fullLayout._size;
        var fullView = [
          0,
          0,
          fullLayout.width * plotGlPixelRatio,
          fullLayout.height * plotGlPixelRatio
        ];
        var lookup = {};
        var k;
        function push(prefix, ax, x0, x1, y0, y1) {
          x0 *= plotGlPixelRatio;
          x1 *= plotGlPixelRatio;
          y0 *= plotGlPixelRatio;
          y1 *= plotGlPixelRatio;
          var lcolor = ax[prefix + "color"];
          var lwidth = ax[prefix + "width"];
          var key = String(lcolor + lwidth);
          if (key in lookup) {
            lookup[key].data.push(NaN, NaN, x0, x1, y0, y1);
          } else {
            lookup[key] = {
              data: [x0, x1, y0, y1],
              join: "rect",
              thickness: lwidth * plotGlPixelRatio,
              color: lcolor,
              viewport: fullView,
              range: fullView,
              overlay: false
            };
          }
        }
        for (k in fullLayout._splomSubplots) {
          var sp = fullLayout._plots[k];
          var xa = sp.xaxis;
          var ya = sp.yaxis;
          var xVals = xa._gridVals;
          var yVals = ya._gridVals;
          var xOffset = xa._offset;
          var xLength = xa._length;
          var yLength = ya._length;
          var yOffset = gs.b + ya.domain[0] * gs.h;
          var ym = -ya._m;
          var yb = -ym * ya.r2l(ya.range[0], ya.calendar);
          var x, y;
          if (xa.showgrid) {
            for (k = 0; k < xVals.length; k++) {
              x = xOffset + xa.l2p(xVals[k].x);
              push("grid", xa, x, yOffset, x, yOffset + yLength);
            }
          }
          if (ya.showgrid) {
            for (k = 0; k < yVals.length; k++) {
              y = yOffset + yb + ym * yVals[k].x;
              push("grid", ya, xOffset, y, xOffset + xLength, y);
            }
          }
          if (shouldShowZeroLine(gd, xa, ya)) {
            x = xOffset + xa.l2p(0);
            push("zeroline", xa, x, yOffset, x, yOffset + yLength);
          }
          if (shouldShowZeroLine(gd, ya, xa)) {
            y = yOffset + yb + 0;
            push("zeroline", ya, xOffset, y, xOffset + xLength, y);
          }
        }
        var gridBatches = [];
        for (k in lookup) {
          gridBatches.push(lookup[k]);
        }
        return gridBatches;
      }
      function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var lookup = {};
        var i;
        if (oldFullLayout._splomScenes) {
          for (i = 0; i < newFullData.length; i++) {
            var newTrace = newFullData[i];
            if (newTrace.type === "splom") {
              lookup[newTrace.uid] = 1;
            }
          }
          for (i = 0; i < oldFullData.length; i++) {
            var oldTrace = oldFullData[i];
            if (!lookup[oldTrace.uid]) {
              var scene = oldFullLayout._splomScenes[oldTrace.uid];
              if (scene && scene.destroy) scene.destroy();
              oldFullLayout._splomScenes[oldTrace.uid] = null;
              delete oldFullLayout._splomScenes[oldTrace.uid];
            }
          }
        }
        if (Object.keys(oldFullLayout._splomScenes || {}).length === 0) {
          delete oldFullLayout._splomScenes;
        }
        if (oldFullLayout._splomGrid && (!newFullLayout._hasOnlyLargeSploms && oldFullLayout._hasOnlyLargeSploms)) {
          oldFullLayout._splomGrid.destroy();
          oldFullLayout._splomGrid = null;
          delete oldFullLayout._splomGrid;
        }
        Cartesian.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
      }
      module.exports = {
        name: SPLOM,
        attr: Cartesian.attr,
        attrRegex: Cartesian.attrRegex,
        layoutAttributes: Cartesian.layoutAttributes,
        supplyLayoutDefaults: Cartesian.supplyLayoutDefaults,
        drawFramework: Cartesian.drawFramework,
        plot,
        drag,
        updateGrid,
        clean,
        updateFx: Cartesian.updateFx,
        toSVG: Cartesian.toSVG,
        reglPrecompiled
      };
    }
  });

  // src/traces/splom/index.js
  var require_splom = __commonJS({
    "src/traces/splom/index.js"(exports, module) {
      "use strict";
      var index = require_base_index2();
      index.basePlotModule = require_base_plot6(), module.exports = index;
    }
  });

  // lib/splom.js
  var require_splom2 = __commonJS({
    "lib/splom.js"(exports, module) {
      "use strict";
      module.exports = require_splom();
    }
  });

  // src/traces/parcoords/attributes.js
  var require_attributes52 = __commonJS({
    "src/traces/parcoords/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var axesAttrs = require_layout_attributes4();
      var fontAttrs = require_font_attributes();
      var domainAttrs = require_domain().attributes;
      var extendFlat = require_extend().extendFlat;
      var templatedArray = require_plot_template().templatedArray;
      module.exports = {
        domain: domainAttrs({ name: "parcoords", trace: true, editType: "plot" }),
        labelangle: {
          valType: "angle",
          dflt: 0,
          editType: "plot"
        },
        labelside: {
          valType: "enumerated",
          values: ["top", "bottom"],
          dflt: "top",
          editType: "plot"
        },
        labelfont: fontAttrs({
          editType: "plot"
        }),
        tickfont: fontAttrs({
          autoShadowDflt: true,
          editType: "plot"
        }),
        rangefont: fontAttrs({
          editType: "plot"
        }),
        dimensions: templatedArray("dimension", {
          label: {
            valType: "string",
            editType: "plot"
          },
          // TODO: better way to determine ordinal vs continuous axes,
          // so users can use tickvals/ticktext with a continuous axis.
          tickvals: extendFlat({}, axesAttrs.tickvals, {
            editType: "plot"
          }),
          ticktext: extendFlat({}, axesAttrs.ticktext, {
            editType: "plot"
          }),
          tickformat: extendFlat({}, axesAttrs.tickformat, {
            editType: "plot"
          }),
          visible: {
            valType: "boolean",
            dflt: true,
            editType: "plot"
          },
          range: {
            valType: "info_array",
            items: [
              { valType: "number", editType: "plot" },
              { valType: "number", editType: "plot" }
            ],
            editType: "plot"
          },
          constraintrange: {
            valType: "info_array",
            freeLength: true,
            dimensions: "1-2",
            items: [
              { valType: "any", editType: "plot" },
              { valType: "any", editType: "plot" }
            ],
            editType: "plot"
          },
          multiselect: {
            valType: "boolean",
            dflt: true,
            editType: "plot"
          },
          values: {
            valType: "data_array",
            editType: "calc"
          },
          editType: "calc"
        }),
        line: extendFlat(
          { editType: "calc" },
          colorScaleAttrs("line", {
            // the default autocolorscale isn't quite usable for parcoords due to context ambiguity around 0 (grey, off-white)
            // autocolorscale therefore defaults to false too, to avoid being overridden by the blue-white-red autocolor palette
            colorscaleDflt: "Viridis",
            autoColorDflt: false,
            editTypeOverride: "calc"
          })
        ),
        unselected: {
          line: {
            color: {
              valType: "color",
              dflt: "#7f7f7f",
              editType: "plot"
            },
            opacity: {
              valType: "number",
              min: 0,
              max: 1,
              dflt: "auto",
              editType: "plot"
            },
            editType: "plot"
          },
          editType: "plot"
        }
      };
    }
  });

  // src/traces/parcoords/constants.js
  var require_constants24 = __commonJS({
    "src/traces/parcoords/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        maxDimensionCount: 60,
        // this cannot be increased without WebGL code refactoring
        overdrag: 45,
        verticalPadding: 2,
        // otherwise, horizontal lines on top or bottom are of lower width
        tickDistance: 50,
        canvasPixelRatio: 1,
        blockLineCount: 5e3,
        layers: ["contextLineLayer", "focusLineLayer", "pickLineLayer"],
        axisTitleOffset: 28,
        axisExtentOffset: 10,
        bar: {
          width: 4,
          // Visible width of the filter bar
          captureWidth: 10,
          // Mouse-sensitive width for interaction (Fitts law)
          fillColor: "magenta",
          // Color of the filter bar fill
          fillOpacity: 1,
          // Filter bar fill opacity
          snapDuration: 150,
          // tween duration in ms for brush snap for ordinal axes
          snapRatio: 0.25,
          // ratio of bar extension relative to the distance between two adjacent ordinal values
          snapClose: 0.01,
          // fraction of inter-value distance to snap to the closer one, even if you're not over it
          strokeOpacity: 1,
          // Filter bar side stroke opacity
          strokeWidth: 1,
          // Filter bar side stroke width in pixels
          handleHeight: 8,
          // Height of the filter bar vertical resize areas on top and bottom
          handleOpacity: 1,
          // Opacity of the filter bar vertical resize areas on top and bottom
          handleOverlap: 0
          // A larger than 0 value causes overlaps with the filter bar, represented as pixels
        },
        cn: {
          axisExtentText: "axis-extent-text",
          parcoordsLineLayers: "parcoords-line-layers",
          parcoordsLineLayer: "parcoords-lines",
          parcoords: "parcoords",
          parcoordsControlView: "parcoords-control-view",
          yAxis: "y-axis",
          axisOverlays: "axis-overlays",
          axis: "axis",
          axisHeading: "axis-heading",
          axisTitle: "axis-title",
          axisExtent: "axis-extent",
          axisExtentTop: "axis-extent-top",
          axisExtentTopText: "axis-extent-top-text",
          axisExtentBottom: "axis-extent-bottom",
          axisExtentBottomText: "axis-extent-bottom-text",
          axisBrush: "axis-brush"
        },
        id: {
          filterBarPattern: "filter-bar-pattern"
        }
      };
    }
  });

  // src/lib/gup.js
  var require_gup = __commonJS({
    "src/lib/gup.js"(exports, module) {
      "use strict";
      var identity2 = require_identity2();
      function wrap(d) {
        return [d];
      }
      module.exports = {
        // The D3 data binding concept and the General Update Pattern promotes the idea of
        // traversing into the scenegraph by using the `.data(fun, keyFun)` call.
        // The `fun` is most often a `repeat`, ie. the elements beneath a `<g>` element need
        // access to the same data, or a `descend`, which fans a scenegraph node into a bunch of
        // of elements, e.g. points, lines, rows, requiring an array as input.
        // The role of the `keyFun` is to identify what elements are being entered/exited/updated,
        // otherwise D3 reverts to using a plain index which would screw up `transition`s.
        keyFun: function(d) {
          return d.key;
        },
        repeat: wrap,
        descend: identity2,
        // Plotly.js uses a convention of storing the actual contents of the `calcData` as the
        // element zero of a container array. These helpers are just used for clarity as a
        // newcomer to the codebase may not know what the `[0]` is, and whether there can be further
        // elements (not atm).
        wrap,
        unwrap: function(d) {
          return d[0];
        }
      };
    }
  });

  // src/traces/parcoords/axisbrush.js
  var require_axisbrush = __commonJS({
    "src/traces/parcoords/axisbrush.js"(exports, module) {
      "use strict";
      var c = require_constants24();
      var d3 = require_d3();
      var keyFun = require_gup().keyFun;
      var repeat = require_gup().repeat;
      var sortAsc = require_lib().sorterAsc;
      var strTranslate = require_lib().strTranslate;
      var snapRatio = c.bar.snapRatio;
      function snapOvershoot(v, vAdjacent) {
        return v * (1 - snapRatio) + vAdjacent * snapRatio;
      }
      var snapClose = c.bar.snapClose;
      function closeToCovering(v, vAdjacent) {
        return v * (1 - snapClose) + vAdjacent * snapClose;
      }
      function ordinalScaleSnap(isHigh, a, v, existingRanges) {
        if (overlappingExisting(v, existingRanges)) return v;
        var dir = isHigh ? -1 : 1;
        var first = 0;
        var last = a.length - 1;
        if (dir < 0) {
          var tmp = first;
          first = last;
          last = tmp;
        }
        var aHere = a[first];
        var aPrev = aHere;
        for (var i = first; dir * i < dir * last; i += dir) {
          var nextI = i + dir;
          var aNext = a[nextI];
          if (dir * v < dir * closeToCovering(aHere, aNext)) return snapOvershoot(aHere, aPrev);
          if (dir * v < dir * aNext || nextI === last) return snapOvershoot(aNext, aHere);
          aPrev = aHere;
          aHere = aNext;
        }
      }
      function overlappingExisting(v, existingRanges) {
        for (var i = 0; i < existingRanges.length; i++) {
          if (v >= existingRanges[i][0] && v <= existingRanges[i][1]) return true;
        }
        return false;
      }
      function barHorizontalSetup(selection) {
        selection.attr("x", -c.bar.captureWidth / 2).attr("width", c.bar.captureWidth);
      }
      function backgroundBarHorizontalSetup(selection) {
        selection.attr("visibility", "visible").style("visibility", "visible").attr("fill", "yellow").attr("opacity", 0);
      }
      function setHighlight(d) {
        if (!d.brush.filterSpecified) {
          return "0," + d.height;
        }
        var pixelRanges = unitToPx(d.brush.filter.getConsolidated(), d.height);
        var dashArray = [0];
        var p, sectionHeight, iNext;
        var currentGap = pixelRanges.length ? pixelRanges[0][0] : null;
        for (var i = 0; i < pixelRanges.length; i++) {
          p = pixelRanges[i];
          sectionHeight = p[1] - p[0];
          dashArray.push(currentGap);
          dashArray.push(sectionHeight);
          iNext = i + 1;
          if (iNext < pixelRanges.length) {
            currentGap = pixelRanges[iNext][0] - p[1];
          }
        }
        dashArray.push(d.height);
        return dashArray;
      }
      function unitToPx(unitRanges, height) {
        return unitRanges.map(function(pr) {
          return pr.map(function(v) {
            return Math.max(0, v * height);
          }).sort(sortAsc);
        });
      }
      function getRegion(fPix, y) {
        var pad = c.bar.handleHeight;
        if (y > fPix[1] + pad || y < fPix[0] - pad) return;
        if (y >= 0.9 * fPix[1] + 0.1 * fPix[0]) return "n";
        if (y <= 0.9 * fPix[0] + 0.1 * fPix[1]) return "s";
        return "ns";
      }
      function clearCursor() {
        d3.select(document.body).style("cursor", null);
      }
      function styleHighlight(selection) {
        selection.attr("stroke-dasharray", setHighlight);
      }
      function renderHighlight(root, tweenCallback) {
        var bar = d3.select(root).selectAll(".highlight, .highlight-shadow");
        var barToStyle = tweenCallback ? bar.transition().duration(c.bar.snapDuration).each("end", tweenCallback) : bar;
        styleHighlight(barToStyle);
      }
      function getInterval(d, y) {
        var b = d.brush;
        var active = b.filterSpecified;
        var closestInterval = NaN;
        var out = {};
        var i;
        if (active) {
          var height = d.height;
          var intervals = b.filter.getConsolidated();
          var pixIntervals = unitToPx(intervals, height);
          var hoveredInterval = NaN;
          var previousInterval = NaN;
          var nextInterval = NaN;
          for (i = 0; i <= pixIntervals.length; i++) {
            var p = pixIntervals[i];
            if (p && p[0] <= y && y <= p[1]) {
              hoveredInterval = i;
              break;
            } else {
              previousInterval = i ? i - 1 : NaN;
              if (p && p[0] > y) {
                nextInterval = i;
                break;
              }
            }
          }
          closestInterval = hoveredInterval;
          if (isNaN(closestInterval)) {
            if (isNaN(previousInterval) || isNaN(nextInterval)) {
              closestInterval = isNaN(previousInterval) ? nextInterval : previousInterval;
            } else {
              closestInterval = y - pixIntervals[previousInterval][1] < pixIntervals[nextInterval][0] - y ? previousInterval : nextInterval;
            }
          }
          if (!isNaN(closestInterval)) {
            var fPix = pixIntervals[closestInterval];
            var region = getRegion(fPix, y);
            if (region) {
              out.interval = intervals[closestInterval];
              out.intervalPix = fPix;
              out.region = region;
            }
          }
        }
        if (d.ordinal && !out.region) {
          var a = d.unitTickvals;
          var unitLocation = d.unitToPaddedPx.invert(y);
          for (i = 0; i < a.length; i++) {
            var rangei = [
              a[Math.max(i - 1, 0)] * 0.25 + a[i] * 0.75,
              a[Math.min(i + 1, a.length - 1)] * 0.25 + a[i] * 0.75
            ];
            if (unitLocation >= rangei[0] && unitLocation <= rangei[1]) {
              out.clickableOrdinalRange = rangei;
              break;
            }
          }
        }
        return out;
      }
      function dragstart(lThis, d) {
        d3.event.sourceEvent.stopPropagation();
        var y = d.height - d3.mouse(lThis)[1] - 2 * c.verticalPadding;
        var unitLocation = d.unitToPaddedPx.invert(y);
        var b = d.brush;
        var interval = getInterval(d, y);
        var unitRange = interval.interval;
        var s = b.svgBrush;
        s.wasDragged = false;
        s.grabbingBar = interval.region === "ns";
        if (s.grabbingBar) {
          var pixelRange = unitRange.map(d.unitToPaddedPx);
          s.grabPoint = y - pixelRange[0] - c.verticalPadding;
          s.barLength = pixelRange[1] - pixelRange[0];
        }
        s.clickableOrdinalRange = interval.clickableOrdinalRange;
        s.stayingIntervals = d.multiselect && b.filterSpecified ? b.filter.getConsolidated() : [];
        if (unitRange) {
          s.stayingIntervals = s.stayingIntervals.filter(function(int2) {
            return int2[0] !== unitRange[0] && int2[1] !== unitRange[1];
          });
        }
        s.startExtent = interval.region ? unitRange[interval.region === "s" ? 1 : 0] : unitLocation;
        d.parent.inBrushDrag = true;
        s.brushStartCallback();
      }
      function drag(lThis, d) {
        d3.event.sourceEvent.stopPropagation();
        var y = d.height - d3.mouse(lThis)[1] - 2 * c.verticalPadding;
        var s = d.brush.svgBrush;
        s.wasDragged = true;
        s._dragging = true;
        if (s.grabbingBar) {
          s.newExtent = [y - s.grabPoint, y + s.barLength - s.grabPoint].map(d.unitToPaddedPx.invert);
        } else {
          s.newExtent = [s.startExtent, d.unitToPaddedPx.invert(y)].sort(sortAsc);
        }
        d.brush.filterSpecified = true;
        s.extent = s.stayingIntervals.concat([s.newExtent]);
        s.brushCallback(d);
        renderHighlight(lThis.parentNode);
      }
      function dragend(lThis, d) {
        var brush = d.brush;
        var filter = brush.filter;
        var s = brush.svgBrush;
        if (!s._dragging) {
          mousemove(lThis, d);
          drag(lThis, d);
          d.brush.svgBrush.wasDragged = false;
        }
        s._dragging = false;
        var e = d3.event;
        e.sourceEvent.stopPropagation();
        var grabbingBar = s.grabbingBar;
        s.grabbingBar = false;
        s.grabLocation = void 0;
        d.parent.inBrushDrag = false;
        clearCursor();
        if (!s.wasDragged) {
          s.wasDragged = void 0;
          if (s.clickableOrdinalRange) {
            if (brush.filterSpecified && d.multiselect) {
              s.extent.push(s.clickableOrdinalRange);
            } else {
              s.extent = [s.clickableOrdinalRange];
              brush.filterSpecified = true;
            }
          } else if (grabbingBar) {
            s.extent = s.stayingIntervals;
            if (s.extent.length === 0) {
              brushClear(brush);
            }
          } else {
            brushClear(brush);
          }
          s.brushCallback(d);
          renderHighlight(lThis.parentNode);
          s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
          return;
        }
        var mergeIntervals = function() {
          filter.set(filter.getConsolidated());
        };
        if (d.ordinal) {
          var a = d.unitTickvals;
          if (a[a.length - 1] < a[0]) a.reverse();
          s.newExtent = [
            ordinalScaleSnap(0, a, s.newExtent[0], s.stayingIntervals),
            ordinalScaleSnap(1, a, s.newExtent[1], s.stayingIntervals)
          ];
          var hasNewExtent = s.newExtent[1] > s.newExtent[0];
          s.extent = s.stayingIntervals.concat(hasNewExtent ? [s.newExtent] : []);
          if (!s.extent.length) {
            brushClear(brush);
          }
          s.brushCallback(d);
          if (hasNewExtent) {
            renderHighlight(lThis.parentNode, mergeIntervals);
          } else {
            mergeIntervals();
            renderHighlight(lThis.parentNode);
          }
        } else {
          mergeIntervals();
        }
        s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []);
      }
      function mousemove(lThis, d) {
        var y = d.height - d3.mouse(lThis)[1] - 2 * c.verticalPadding;
        var interval = getInterval(d, y);
        var cursor = "crosshair";
        if (interval.clickableOrdinalRange) cursor = "pointer";
        else if (interval.region) cursor = interval.region + "-resize";
        d3.select(document.body).style("cursor", cursor);
      }
      function attachDragBehavior(selection) {
        selection.on("mousemove", function(d) {
          d3.event.preventDefault();
          if (!d.parent.inBrushDrag) mousemove(this, d);
        }).on("mouseleave", function(d) {
          if (!d.parent.inBrushDrag) clearCursor();
        }).call(
          d3.behavior.drag().on("dragstart", function(d) {
            dragstart(this, d);
          }).on("drag", function(d) {
            drag(this, d);
          }).on("dragend", function(d) {
            dragend(this, d);
          })
        );
      }
      function startAsc(a, b) {
        return a[0] - b[0];
      }
      function renderAxisBrush(axisBrush, paperColor, gd) {
        var isStatic = gd._context.staticPlot;
        var background = axisBrush.selectAll(".background").data(repeat);
        background.enter().append("rect").classed("background", true).call(barHorizontalSetup).call(backgroundBarHorizontalSetup).style("pointer-events", isStatic ? "none" : "auto").attr("transform", strTranslate(0, c.verticalPadding));
        background.call(attachDragBehavior).attr("height", function(d) {
          return d.height - c.verticalPadding;
        });
        var highlightShadow = axisBrush.selectAll(".highlight-shadow").data(repeat);
        highlightShadow.enter().append("line").classed("highlight-shadow", true).attr("x", -c.bar.width / 2).attr("stroke-width", c.bar.width + c.bar.strokeWidth).attr("stroke", paperColor).attr("opacity", c.bar.strokeOpacity).attr("stroke-linecap", "butt");
        highlightShadow.attr("y1", function(d) {
          return d.height;
        }).call(styleHighlight);
        var highlight = axisBrush.selectAll(".highlight").data(repeat);
        highlight.enter().append("line").classed("highlight", true).attr("x", -c.bar.width / 2).attr("stroke-width", c.bar.width - c.bar.strokeWidth).attr("stroke", c.bar.fillColor).attr("opacity", c.bar.fillOpacity).attr("stroke-linecap", "butt");
        highlight.attr("y1", function(d) {
          return d.height;
        }).call(styleHighlight);
      }
      function ensureAxisBrush(axisOverlays, paperColor, gd) {
        var axisBrush = axisOverlays.selectAll("." + c.cn.axisBrush).data(repeat, keyFun);
        axisBrush.enter().append("g").classed(c.cn.axisBrush, true);
        renderAxisBrush(axisBrush, paperColor, gd);
      }
      function getBrushExtent(brush) {
        return brush.svgBrush.extent.map(function(e) {
          return e.slice();
        });
      }
      function brushClear(brush) {
        brush.filterSpecified = false;
        brush.svgBrush.extent = [[-Infinity, Infinity]];
      }
      function axisBrushMoved(callback) {
        return function axisBrushMoved2(dimension) {
          var brush = dimension.brush;
          var extent = getBrushExtent(brush);
          var newExtent = extent.slice();
          brush.filter.set(newExtent);
          callback();
        };
      }
      function dedupeRealRanges(intervals) {
        var queue = intervals.slice();
        var result = [];
        var currentInterval;
        var current = queue.shift();
        while (current) {
          currentInterval = current.slice();
          while ((current = queue.shift()) && current[0] <= /* right-open interval would need `<` */
          currentInterval[1]) {
            currentInterval[1] = Math.max(currentInterval[1], current[1]);
          }
          result.push(currentInterval);
        }
        if (result.length === 1 && result[0][0] > result[0][1]) {
          result = [];
        }
        return result;
      }
      function makeFilter() {
        var filter = [];
        var consolidated;
        var bounds;
        return {
          set: function(a) {
            filter = a.map(function(d) {
              return d.slice().sort(sortAsc);
            }).sort(startAsc);
            if (filter.length === 1 && filter[0][0] === -Infinity && filter[0][1] === Infinity) {
              filter = [[0, -1]];
            }
            consolidated = dedupeRealRanges(filter);
            bounds = filter.reduce(function(p, n) {
              return [Math.min(p[0], n[0]), Math.max(p[1], n[1])];
            }, [Infinity, -Infinity]);
          },
          get: function() {
            return filter.slice();
          },
          getConsolidated: function() {
            return consolidated;
          },
          getBounds: function() {
            return bounds;
          }
        };
      }
      function makeBrush(state, rangeSpecified, initialRange, brushStartCallback, brushCallback, brushEndCallback) {
        var filter = makeFilter();
        filter.set(initialRange);
        return {
          filter,
          filterSpecified: rangeSpecified,
          // there's a difference between not filtering and filtering a non-proper subset
          svgBrush: {
            extent: [],
            // this is where the svgBrush writes contents into
            brushStartCallback,
            brushCallback: axisBrushMoved(brushCallback),
            brushEndCallback
          }
        };
      }
      function cleanRanges(ranges, dimension) {
        if (Array.isArray(ranges[0])) {
          ranges = ranges.map(function(ri) {
            return ri.sort(sortAsc);
          });
          if (!dimension.multiselect) ranges = [ranges[0]];
          else ranges = dedupeRealRanges(ranges.sort(startAsc));
        } else ranges = [ranges.sort(sortAsc)];
        if (dimension.tickvals) {
          var sortedTickVals = dimension.tickvals.slice().sort(sortAsc);
          ranges = ranges.map(function(ri) {
            var rSnapped = [
              ordinalScaleSnap(0, sortedTickVals, ri[0], []),
              ordinalScaleSnap(1, sortedTickVals, ri[1], [])
            ];
            if (rSnapped[1] > rSnapped[0]) return rSnapped;
          }).filter(function(ri) {
            return ri;
          });
          if (!ranges.length) return;
        }
        return ranges.length > 1 ? ranges : ranges[0];
      }
      module.exports = {
        makeBrush,
        ensureAxisBrush,
        cleanRanges
      };
    }
  });

  // src/traces/parcoords/defaults.js
  var require_defaults48 = __commonJS({
    "src/traces/parcoords/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleDefaults = require_defaults2();
      var handleDomainDefaults = require_domain().defaults;
      var handleArrayContainerDefaults = require_array_container_defaults();
      var Axes = require_axes();
      var attributes = require_attributes52();
      var axisBrush = require_axisbrush();
      var maxDimensionCount = require_constants24().maxDimensionCount;
      var mergeLength = require_merge_length();
      function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
        var lineColor = coerce("line.color", defaultColor);
        if (hasColorscale(traceIn, "line") && Lib.isArrayOrTypedArray(lineColor)) {
          if (lineColor.length) {
            coerce("line.colorscale");
            colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "line.", cLetter: "c" });
            return lineColor.length;
          } else {
            traceOut.line.color = defaultColor;
          }
        }
        return Infinity;
      }
      function dimensionDefaults(dimensionIn, dimensionOut, parentOut, opts) {
        function coerce(attr, dflt) {
          return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
        }
        var values = coerce("values");
        var visible = coerce("visible");
        if (!(values && values.length)) {
          visible = dimensionOut.visible = false;
        }
        if (visible) {
          coerce("label");
          coerce("tickvals");
          coerce("ticktext");
          coerce("tickformat");
          var range = coerce("range");
          dimensionOut._ax = {
            _id: "y",
            type: "linear",
            showexponent: "all",
            exponentformat: "B",
            range
          };
          Axes.setConvert(dimensionOut._ax, opts.layout);
          coerce("multiselect");
          var constraintRange = coerce("constraintrange");
          if (constraintRange) {
            dimensionOut.constraintrange = axisBrush.cleanRanges(constraintRange, dimensionOut);
          }
        }
      }
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var dimensionsIn = traceIn.dimensions;
        if (Array.isArray(dimensionsIn) && dimensionsIn.length > maxDimensionCount) {
          Lib.log("parcoords traces support up to " + maxDimensionCount + " dimensions at the moment");
          dimensionsIn.splice(maxDimensionCount);
        }
        var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
          name: "dimensions",
          layout,
          handleItemDefaults: dimensionDefaults
        });
        var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleDomainDefaults(traceOut, layout, coerce);
        if (!Array.isArray(dimensions) || !dimensions.length) {
          traceOut.visible = false;
        }
        mergeLength(traceOut, dimensions, "values", len);
        var fontDflt = Lib.extendFlat({}, layout.font, {
          size: Math.round(layout.font.size / 1.2)
        });
        Lib.coerceFont(coerce, "labelfont", fontDflt);
        Lib.coerceFont(coerce, "tickfont", fontDflt, { autoShadowDflt: true });
        Lib.coerceFont(coerce, "rangefont", fontDflt);
        coerce("labelangle");
        coerce("labelside");
        coerce("unselected.line.color");
        coerce("unselected.line.opacity");
      };
    }
  });

  // src/traces/parcoords/calc.js
  var require_calc31 = __commonJS({
    "src/traces/parcoords/calc.js"(exports, module) {
      "use strict";
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var Colorscale = require_colorscale();
      var wrap = require_gup().wrap;
      module.exports = function calc(gd, trace) {
        var lineColor;
        var cscale;
        if (Colorscale.hasColorscale(trace, "line") && isArrayOrTypedArray(trace.line.color)) {
          lineColor = trace.line.color;
          cscale = Colorscale.extractOpts(trace.line).colorscale;
          Colorscale.calc(gd, trace, {
            vals: lineColor,
            containerStr: "line",
            cLetter: "c"
          });
        } else {
          lineColor = constHalf(trace._length);
          cscale = [[0, trace.line.color], [1, trace.line.color]];
        }
        return wrap({ lineColor, cscale });
      };
      function constHalf(len) {
        var out = new Array(len);
        for (var i = 0; i < len; i++) {
          out[i] = 0.5;
        }
        return out;
      }
    }
  });

  // node_modules/color-parse/index.js
  function parse(cstr) {
    var _a, _b;
    var m, parts = [], alpha = 1, space;
    if (typeof cstr === "number") {
      return { space: "rgb", values: [cstr >>> 16, (cstr & 65280) >>> 8, cstr & 255], alpha: 1 };
    }
    if (typeof cstr === "number") return { space: "rgb", values: [cstr >>> 16, (cstr & 65280) >>> 8, cstr & 255], alpha: 1 };
    cstr = String(cstr).toLowerCase();
    if (import_color_name.default[cstr]) {
      parts = import_color_name.default[cstr].slice();
      space = "rgb";
    } else if (cstr === "transparent") {
      alpha = 0;
      space = "rgb";
      parts = [0, 0, 0];
    } else if (cstr[0] === "#") {
      var base = cstr.slice(1);
      var size = base.length;
      var isShort = size <= 4;
      alpha = 1;
      if (isShort) {
        parts = [
          parseInt(base[0] + base[0], 16),
          parseInt(base[1] + base[1], 16),
          parseInt(base[2] + base[2], 16)
        ];
        if (size === 4) {
          alpha = parseInt(base[3] + base[3], 16) / 255;
        }
      } else {
        parts = [
          parseInt(base[0] + base[1], 16),
          parseInt(base[2] + base[3], 16),
          parseInt(base[4] + base[5], 16)
        ];
        if (size === 8) {
          alpha = parseInt(base[6] + base[7], 16) / 255;
        }
      }
      if (!parts[0]) parts[0] = 0;
      if (!parts[1]) parts[1] = 0;
      if (!parts[2]) parts[2] = 0;
      space = "rgb";
    } else if (m = /^((?:rgba?|hs[lvb]a?|hwba?|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms|oklch|oklab|color))\s*\(([^\)]*)\)/.exec(cstr)) {
      var name2 = m[1];
      space = name2.replace(/a$/, "");
      var dims = space === "cmyk" ? 4 : space === "gray" ? 1 : 3;
      parts = m[2].trim().split(/\s*[,\/]\s*|\s+/);
      if (space === "color") space = parts.shift();
      parts = parts.map(function(x, i) {
        if (x[x.length - 1] === "%") {
          x = parseFloat(x) / 100;
          if (i === 3) return x;
          if (space === "rgb") return x * 255;
          if (space[0] === "h") return x * 100;
          if (space[0] === "l" && !i) return x * 100;
          if (space === "lab") return x * 125;
          if (space === "lch") return i < 2 ? x * 150 : x * 360;
          if (space[0] === "o" && !i) return x;
          if (space === "oklab") return x * 0.4;
          if (space === "oklch") return i < 2 ? x * 0.4 : x * 360;
          return x;
        }
        if (space[i] === "h" || i === 2 && space[space.length - 1] === "h") {
          if (baseHues[x] !== void 0) return baseHues[x];
          if (x.endsWith("deg")) return parseFloat(x);
          if (x.endsWith("turn")) return parseFloat(x) * 360;
          if (x.endsWith("grad")) return parseFloat(x) * 360 / 400;
          if (x.endsWith("rad")) return parseFloat(x) * 180 / Math.PI;
        }
        if (x === "none") return 0;
        return parseFloat(x);
      });
      alpha = parts.length > dims ? parts.pop() : 1;
    } else if (/[0-9](?:\s|\/|,)/.test(cstr)) {
      parts = cstr.match(/([0-9]+)/g).map(function(value) {
        return parseFloat(value);
      });
      space = ((_b = (_a = cstr.match(/([a-z])/ig)) == null ? void 0 : _a.join("")) == null ? void 0 : _b.toLowerCase()) || "rgb";
    }
    return {
      space,
      values: parts,
      alpha
    };
  }
  var import_color_name, color_parse_default, baseHues;
  var init_color_parse = __esm({
    "node_modules/color-parse/index.js"() {
      import_color_name = __toESM(require_color_name(), 1);
      color_parse_default = parse;
      baseHues = {
        red: 0,
        orange: 60,
        yellow: 120,
        green: 180,
        blue: 240,
        purple: 300
      };
    }
  });

  // node_modules/color-space/rgb.js
  var rgb_default2;
  var init_rgb2 = __esm({
    "node_modules/color-space/rgb.js"() {
      rgb_default2 = {
        name: "rgb",
        min: [0, 0, 0],
        max: [255, 255, 255],
        channel: ["red", "green", "blue"],
        alias: ["RGB"]
      };
    }
  });

  // node_modules/color-space/hsl.js
  var hsl_default2;
  var init_hsl2 = __esm({
    "node_modules/color-space/hsl.js"() {
      init_rgb2();
      hsl_default2 = {
        name: "hsl",
        min: [0, 0, 0],
        max: [360, 100, 100],
        channel: ["hue", "saturation", "lightness"],
        alias: ["HSL"],
        rgb: function(hsl3) {
          var h = hsl3[0] / 360, s = hsl3[1] / 100, l = hsl3[2] / 100, t12, t22, t32, rgb2, val, i = 0;
          if (s === 0) return val = l * 255, [val, val, val];
          t22 = l < 0.5 ? l * (1 + s) : l + s - l * s;
          t12 = 2 * l - t22;
          rgb2 = [0, 0, 0];
          for (; i < 3; ) {
            t32 = h + 1 / 3 * -(i - 1);
            t32 < 0 ? t32++ : t32 > 1 && t32--;
            val = 6 * t32 < 1 ? t12 + (t22 - t12) * 6 * t32 : 2 * t32 < 1 ? t22 : 3 * t32 < 2 ? t12 + (t22 - t12) * (2 / 3 - t32) * 6 : t12;
            rgb2[i++] = val * 255;
          }
          return rgb2;
        }
      };
      rgb_default2.hsl = function(rgb2) {
        var r = rgb2[0] / 255, g = rgb2[1] / 255, b = rgb2[2] / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), delta = max - min, h, s, l;
        if (max === min) {
          h = 0;
        } else if (r === max) {
          h = (g - b) / delta;
        } else if (g === max) {
          h = 2 + (b - r) / delta;
        } else if (b === max) {
          h = 4 + (r - g) / delta;
        }
        h = Math.min(h * 60, 360);
        if (h < 0) {
          h += 360;
        }
        l = (min + max) / 2;
        if (max === min) {
          s = 0;
        } else if (l <= 0.5) {
          s = delta / (max + min);
        } else {
          s = delta / (2 - max - min);
        }
        return [h, s * 100, l * 100];
      };
    }
  });

  // node_modules/color-rgba/index.js
  var color_rgba_exports = {};
  __export(color_rgba_exports, {
    default: () => rgba2
  });
  function rgba2(color2) {
    if (Array.isArray(color2) && color2.raw) color2 = String.raw(...arguments);
    if (color2 instanceof Number) color2 = +color2;
    var values, i, l;
    var parsed = color_parse_default(color2);
    if (!parsed.space) return [];
    const min = parsed.space[0] === "h" ? hsl_default2.min : rgb_default2.min;
    const max = parsed.space[0] === "h" ? hsl_default2.max : rgb_default2.max;
    values = Array(3);
    values[0] = Math.min(Math.max(parsed.values[0], min[0]), max[0]);
    values[1] = Math.min(Math.max(parsed.values[1], min[1]), max[1]);
    values[2] = Math.min(Math.max(parsed.values[2], min[2]), max[2]);
    if (parsed.space[0] === "h") {
      values = hsl_default2.rgb(values);
    }
    values.push(Math.min(Math.max(parsed.alpha, 0), 1));
    return values;
  }
  var init_color_rgba = __esm({
    "node_modules/color-rgba/index.js"() {
      init_color_parse();
      init_rgb2();
      init_hsl2();
    }
  });

  // src/traces/parcoords/helpers.js
  var require_helpers18 = __commonJS({
    "src/traces/parcoords/helpers.js"(exports) {
      "use strict";
      var isTypedArray = require_lib().isTypedArray;
      exports.convertTypedArray = function(a) {
        return isTypedArray(a) ? Array.prototype.slice.call(a) : a;
      };
      exports.isOrdinal = function(dimension) {
        return !!dimension.tickvals;
      };
      exports.isVisible = function(dimension) {
        return dimension.visible || !("visible" in dimension);
      };
    }
  });

  // src/traces/parcoords/lines.js
  var require_lines = __commonJS({
    "src/traces/parcoords/lines.js"(exports, module) {
      "use strict";
      var vertexShaderSource = [
        "precision highp float;",
        "",
        "varying vec4 fragColor;",
        "",
        "attribute vec4 p01_04, p05_08, p09_12, p13_16,",
        "               p17_20, p21_24, p25_28, p29_32,",
        "               p33_36, p37_40, p41_44, p45_48,",
        "               p49_52, p53_56, p57_60, colors;",
        "",
        "uniform mat4 dim0A, dim1A, dim0B, dim1B, dim0C, dim1C, dim0D, dim1D,",
        "             loA, hiA, loB, hiB, loC, hiC, loD, hiD;",
        "",
        "uniform vec2 resolution, viewBoxPos, viewBoxSize;",
        "uniform float maskHeight;",
        "uniform float drwLayer; // 0: context, 1: focus, 2: pick",
        "uniform vec4 contextColor;",
        "uniform sampler2D maskTexture, palette;",
        "",
        "bool isPick    = (drwLayer > 1.5);",
        "bool isContext = (drwLayer < 0.5);",
        "",
        "const vec4 ZEROS = vec4(0.0, 0.0, 0.0, 0.0);",
        "const vec4 UNITS = vec4(1.0, 1.0, 1.0, 1.0);",
        "",
        "float val(mat4 p, mat4 v) {",
        "    return dot(matrixCompMult(p, v) * UNITS, UNITS);",
        "}",
        "",
        "float axisY(float ratio, mat4 A, mat4 B, mat4 C, mat4 D) {",
        "    float y1 = val(A, dim0A) + val(B, dim0B) + val(C, dim0C) + val(D, dim0D);",
        "    float y2 = val(A, dim1A) + val(B, dim1B) + val(C, dim1C) + val(D, dim1D);",
        "    return y1 * (1.0 - ratio) + y2 * ratio;",
        "}",
        "",
        "int iMod(int a, int b) {",
        "    return a - b * (a / b);",
        "}",
        "",
        "bool fOutside(float p, float lo, float hi) {",
        "    return (lo < hi) && (lo > p || p > hi);",
        "}",
        "",
        "bool vOutside(vec4 p, vec4 lo, vec4 hi) {",
        "    return (",
        "        fOutside(p[0], lo[0], hi[0]) ||",
        "        fOutside(p[1], lo[1], hi[1]) ||",
        "        fOutside(p[2], lo[2], hi[2]) ||",
        "        fOutside(p[3], lo[3], hi[3])",
        "    );",
        "}",
        "",
        "bool mOutside(mat4 p, mat4 lo, mat4 hi) {",
        "    return (",
        "        vOutside(p[0], lo[0], hi[0]) ||",
        "        vOutside(p[1], lo[1], hi[1]) ||",
        "        vOutside(p[2], lo[2], hi[2]) ||",
        "        vOutside(p[3], lo[3], hi[3])",
        "    );",
        "}",
        "",
        "bool outsideBoundingBox(mat4 A, mat4 B, mat4 C, mat4 D) {",
        "    return mOutside(A, loA, hiA) ||",
        "           mOutside(B, loB, hiB) ||",
        "           mOutside(C, loC, hiC) ||",
        "           mOutside(D, loD, hiD);",
        "}",
        "",
        "bool outsideRasterMask(mat4 A, mat4 B, mat4 C, mat4 D) {",
        "    mat4 pnts[4];",
        "    pnts[0] = A;",
        "    pnts[1] = B;",
        "    pnts[2] = C;",
        "    pnts[3] = D;",
        "",
        "    for(int i = 0; i < 4; ++i) {",
        "        for(int j = 0; j < 4; ++j) {",
        "            for(int k = 0; k < 4; ++k) {",
        "                if(0 == iMod(",
        "                    int(255.0 * texture2D(maskTexture,",
        "                        vec2(",
        "                            (float(i * 2 + j / 2) + 0.5) / 8.0,",
        "                            (pnts[i][j][k] * (maskHeight - 1.0) + 1.0) / maskHeight",
        "                        ))[3]",
        "                    ) / int(pow(2.0, float(iMod(j * 4 + k, 8)))),",
        "                    2",
        "                )) return true;",
        "            }",
        "        }",
        "    }",
        "    return false;",
        "}",
        "",
        "vec4 position(bool isContext, float v, mat4 A, mat4 B, mat4 C, mat4 D) {",
        "    float x = 0.5 * sign(v) + 0.5;",
        "    float y = axisY(x, A, B, C, D);",
        "    float z = 1.0 - abs(v);",
        "",
        "    z += isContext ? 0.0 : 2.0 * float(",
        "        outsideBoundingBox(A, B, C, D) ||",
        "        outsideRasterMask(A, B, C, D)",
        "    );",
        "",
        "    return vec4(",
        "        2.0 * (vec2(x, y) * viewBoxSize + viewBoxPos) / resolution - 1.0,",
        "        z,",
        "        1.0",
        "    );",
        "}",
        "",
        "void main() {",
        "    mat4 A = mat4(p01_04, p05_08, p09_12, p13_16);",
        "    mat4 B = mat4(p17_20, p21_24, p25_28, p29_32);",
        "    mat4 C = mat4(p33_36, p37_40, p41_44, p45_48);",
        "    mat4 D = mat4(p49_52, p53_56, p57_60, ZEROS);",
        "",
        "    float v = colors[3];",
        "",
        "    gl_Position = position(isContext, v, A, B, C, D);",
        "",
        "    fragColor =",
        "        isContext ? vec4(contextColor) :",
        "        isPick ? vec4(colors.rgb, 1.0) : texture2D(palette, vec2(abs(v), 0.5));",
        "}"
      ].join("\n");
      var fragmentShaderSource = [
        "precision highp float;",
        "",
        "varying vec4 fragColor;",
        "",
        "void main() {",
        "    gl_FragColor = fragColor;",
        "}"
      ].join("\n");
      var maxDim = require_constants24().maxDimensionCount;
      var Lib = require_lib();
      var depthLimitEpsilon = 1e-6;
      var maskHeight = 2048;
      var dummyPixel = new Uint8Array(4);
      var dataPixel = new Uint8Array(4);
      var paletteTextureConfig = {
        shape: [256, 1],
        format: "rgba",
        type: "uint8",
        mag: "nearest",
        min: "nearest"
      };
      function ensureDraw(regl) {
        regl.read({
          x: 0,
          y: 0,
          width: 1,
          height: 1,
          data: dummyPixel
        });
      }
      function clear(regl, x, y, width, height) {
        var gl2 = regl._gl;
        gl2.enable(gl2.SCISSOR_TEST);
        gl2.scissor(x, y, width, height);
        regl.clear({ color: [0, 0, 0, 0], depth: 1 });
      }
      function renderBlock(regl, glAes, renderState, blockLineCount, sampleCount, item) {
        var rafKey = item.key;
        function render(blockNumber) {
          var count = Math.min(blockLineCount, sampleCount - blockNumber * blockLineCount);
          if (blockNumber === 0) {
            window.cancelAnimationFrame(renderState.currentRafs[rafKey]);
            delete renderState.currentRafs[rafKey];
            clear(regl, item.scissorX, item.scissorY, item.scissorWidth, item.viewBoxSize[1]);
          }
          if (renderState.clearOnly) {
            return;
          }
          item.count = 2 * count;
          item.offset = 2 * blockNumber * blockLineCount;
          glAes(item);
          if (blockNumber * blockLineCount + count < sampleCount) {
            renderState.currentRafs[rafKey] = window.requestAnimationFrame(function() {
              render(blockNumber + 1);
            });
          }
          renderState.drawCompleted = false;
        }
        if (!renderState.drawCompleted) {
          ensureDraw(regl);
          renderState.drawCompleted = true;
        }
        render(0);
      }
      function adjustDepth(d) {
        return Math.max(depthLimitEpsilon, Math.min(1 - depthLimitEpsilon, d));
      }
      function palette(unitToColor, opacity) {
        var result = new Array(256);
        for (var i = 0; i < 256; i++) {
          result[i] = unitToColor(i / 255).concat(opacity);
        }
        return result;
      }
      function calcPickColor(i, rgbIndex) {
        return (i >>> 8 * rgbIndex) % 256 / 255;
      }
      function makePoints(sampleCount, dims, color2) {
        var points = new Array(sampleCount * (maxDim + 4));
        var n = 0;
        for (var i = 0; i < sampleCount; i++) {
          for (var k = 0; k < maxDim; k++) {
            points[n++] = k < dims.length ? dims[k].paddedUnitValues[i] : 0.5;
          }
          points[n++] = calcPickColor(i, 2);
          points[n++] = calcPickColor(i, 1);
          points[n++] = calcPickColor(i, 0);
          points[n++] = adjustDepth(color2[i]);
        }
        return points;
      }
      function makeVecAttr(vecIndex, sampleCount, points) {
        var pointPairs = new Array(sampleCount * 8);
        var n = 0;
        for (var i = 0; i < sampleCount; i++) {
          for (var j = 0; j < 2; j++) {
            for (var k = 0; k < 4; k++) {
              var q = vecIndex * 4 + k;
              var v = points[i * 64 + q];
              if (q === 63 && j === 0) {
                v *= -1;
              }
              pointPairs[n++] = v;
            }
          }
        }
        return pointPairs;
      }
      function pad2(num) {
        var s = "0" + num;
        return s.slice(-2);
      }
      function getAttrName(i) {
        return i < maxDim ? "p" + pad2(i + 1) + "_" + pad2(i + 4) : "colors";
      }
      function setAttributes(attributes, sampleCount, points) {
        for (var i = 0; i <= maxDim; i += 4) {
          attributes[getAttrName(i)](makeVecAttr(i / 4, sampleCount, points));
        }
      }
      function emptyAttributes(regl) {
        var attributes = {};
        for (var i = 0; i <= maxDim; i += 4) {
          attributes[getAttrName(i)] = regl.buffer({ usage: "dynamic", type: "float", data: new Uint8Array(0) });
        }
        return attributes;
      }
      function makeItem(model, leftmost, rightmost, itemNumber, i0, i1, x, y, panelSizeX, panelSizeY, crossfilterDimensionIndex, drwLayer, constraints, plotGlPixelRatio) {
        var dims = [[], []];
        for (var k = 0; k < 64; k++) {
          dims[0][k] = k === i0 ? 1 : 0;
          dims[1][k] = k === i1 ? 1 : 0;
        }
        x *= plotGlPixelRatio;
        y *= plotGlPixelRatio;
        panelSizeX *= plotGlPixelRatio;
        panelSizeY *= plotGlPixelRatio;
        var overdrag = model.lines.canvasOverdrag * plotGlPixelRatio;
        var domain = model.domain;
        var canvasWidth = model.canvasWidth * plotGlPixelRatio;
        var canvasHeight = model.canvasHeight * plotGlPixelRatio;
        var padL = model.pad.l * plotGlPixelRatio;
        var padB = model.pad.b * plotGlPixelRatio;
        var layoutHeight = model.layoutHeight * plotGlPixelRatio;
        var layoutWidth = model.layoutWidth * plotGlPixelRatio;
        var deselectedLinesColor = model.deselectedLines.color;
        var deselectedLinesOpacity = model.deselectedLines.opacity;
        var itemModel = Lib.extendFlat({
          key: crossfilterDimensionIndex,
          resolution: [canvasWidth, canvasHeight],
          viewBoxPos: [x + overdrag, y],
          viewBoxSize: [panelSizeX, panelSizeY],
          i0,
          i1,
          dim0A: dims[0].slice(0, 16),
          dim0B: dims[0].slice(16, 32),
          dim0C: dims[0].slice(32, 48),
          dim0D: dims[0].slice(48, 64),
          dim1A: dims[1].slice(0, 16),
          dim1B: dims[1].slice(16, 32),
          dim1C: dims[1].slice(32, 48),
          dim1D: dims[1].slice(48, 64),
          drwLayer,
          contextColor: [
            deselectedLinesColor[0] / 255,
            deselectedLinesColor[1] / 255,
            deselectedLinesColor[2] / 255,
            deselectedLinesOpacity !== "auto" ? deselectedLinesColor[3] * deselectedLinesOpacity : Math.max(1 / 255, Math.pow(1 / model.lines.color.length, 1 / 3))
          ],
          scissorX: (itemNumber === leftmost ? 0 : x + overdrag) + (padL - overdrag) + layoutWidth * domain.x[0],
          scissorWidth: (itemNumber === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (itemNumber === leftmost ? x + overdrag : 0),
          scissorY: y + padB + layoutHeight * domain.y[0],
          scissorHeight: panelSizeY,
          viewportX: padL - overdrag + layoutWidth * domain.x[0],
          viewportY: padB + layoutHeight * domain.y[0],
          viewportWidth: canvasWidth,
          viewportHeight: canvasHeight
        }, constraints);
        return itemModel;
      }
      function expandedPixelRange(bounds) {
        var dh = maskHeight - 1;
        var a = Math.max(0, Math.floor(bounds[0] * dh), 0);
        var b = Math.min(dh, Math.ceil(bounds[1] * dh), dh);
        return [
          Math.min(a, b),
          Math.max(a, b)
        ];
      }
      module.exports = function(canvasGL, d) {
        var isContext = d.context;
        var isPick = d.pick;
        var regl = d.regl;
        var gl2 = regl._gl;
        var supportedLineWidth = gl2.getParameter(gl2.ALIASED_LINE_WIDTH_RANGE);
        var plotGlPixelRatio = Math.max(
          supportedLineWidth[0],
          Math.min(
            supportedLineWidth[1],
            d.viewModel.plotGlPixelRatio
          )
        );
        var renderState = {
          currentRafs: {},
          drawCompleted: true,
          clearOnly: false
        };
        var model;
        var vm;
        var initialDims;
        var sampleCount;
        var attributes = emptyAttributes(regl);
        var maskTexture;
        var paletteTexture = regl.texture(paletteTextureConfig);
        var prevAxisOrder = [];
        update(d);
        var glAes = regl({
          profile: false,
          blend: {
            enable: isContext,
            func: {
              srcRGB: "src alpha",
              dstRGB: "one minus src alpha",
              srcAlpha: 1,
              dstAlpha: 1
              // 'one minus src alpha'
            },
            equation: {
              rgb: "add",
              alpha: "add"
            },
            color: [0, 0, 0, 0]
          },
          depth: {
            enable: !isContext,
            mask: true,
            func: "less",
            range: [0, 1]
          },
          // for polygons
          cull: {
            enable: true,
            face: "back"
          },
          scissor: {
            enable: true,
            box: {
              x: regl.prop("scissorX"),
              y: regl.prop("scissorY"),
              width: regl.prop("scissorWidth"),
              height: regl.prop("scissorHeight")
            }
          },
          viewport: {
            x: regl.prop("viewportX"),
            y: regl.prop("viewportY"),
            width: regl.prop("viewportWidth"),
            height: regl.prop("viewportHeight")
          },
          dither: false,
          vert: vertexShaderSource,
          frag: fragmentShaderSource,
          primitive: "lines",
          lineWidth: plotGlPixelRatio,
          attributes,
          uniforms: {
            resolution: regl.prop("resolution"),
            viewBoxPos: regl.prop("viewBoxPos"),
            viewBoxSize: regl.prop("viewBoxSize"),
            dim0A: regl.prop("dim0A"),
            dim1A: regl.prop("dim1A"),
            dim0B: regl.prop("dim0B"),
            dim1B: regl.prop("dim1B"),
            dim0C: regl.prop("dim0C"),
            dim1C: regl.prop("dim1C"),
            dim0D: regl.prop("dim0D"),
            dim1D: regl.prop("dim1D"),
            loA: regl.prop("loA"),
            hiA: regl.prop("hiA"),
            loB: regl.prop("loB"),
            hiB: regl.prop("hiB"),
            loC: regl.prop("loC"),
            hiC: regl.prop("hiC"),
            loD: regl.prop("loD"),
            hiD: regl.prop("hiD"),
            palette: paletteTexture,
            contextColor: regl.prop("contextColor"),
            maskTexture: regl.prop("maskTexture"),
            drwLayer: regl.prop("drwLayer"),
            maskHeight: regl.prop("maskHeight")
          },
          offset: regl.prop("offset"),
          count: regl.prop("count")
        });
        function update(dNew) {
          model = dNew.model;
          vm = dNew.viewModel;
          initialDims = vm.dimensions.slice();
          sampleCount = initialDims[0] ? initialDims[0].values.length : 0;
          var lines = model.lines;
          var color2 = isPick ? lines.color.map(function(_, i) {
            return i / lines.color.length;
          }) : lines.color;
          var points = makePoints(sampleCount, initialDims, color2);
          setAttributes(attributes, sampleCount, points);
          if (!isContext && !isPick) {
            paletteTexture = regl.texture(Lib.extendFlat({
              data: palette(model.unitToColor, 255)
            }, paletteTextureConfig));
          }
        }
        function makeConstraints(isContext2) {
          var i, j, k;
          var limits = [[], []];
          for (k = 0; k < 64; k++) {
            var p = !isContext2 && k < initialDims.length ? initialDims[k].brush.filter.getBounds() : [-Infinity, Infinity];
            limits[0][k] = p[0];
            limits[1][k] = p[1];
          }
          var len = maskHeight * 8;
          var mask = new Array(len);
          for (i = 0; i < len; i++) {
            mask[i] = 255;
          }
          if (!isContext2) {
            for (i = 0; i < initialDims.length; i++) {
              var u = i % 8;
              var v = (i - u) / 8;
              var bitMask = Math.pow(2, u);
              var dim = initialDims[i];
              var ranges = dim.brush.filter.get();
              if (ranges.length < 2) continue;
              var prevEnd = expandedPixelRange(ranges[0])[1];
              for (j = 1; j < ranges.length; j++) {
                var nextRange = expandedPixelRange(ranges[j]);
                for (k = prevEnd + 1; k < nextRange[0]; k++) {
                  mask[k * 8 + v] &= ~bitMask;
                }
                prevEnd = Math.max(prevEnd, nextRange[1]);
              }
            }
          }
          var textureData = {
            // 8 units x 8 bits = 64 bits, just sufficient for the almost 64 dimensions we support
            shape: [8, maskHeight],
            format: "alpha",
            type: "uint8",
            mag: "nearest",
            min: "nearest",
            data: mask
          };
          if (maskTexture) maskTexture(textureData);
          else maskTexture = regl.texture(textureData);
          return {
            maskTexture,
            maskHeight,
            loA: limits[0].slice(0, 16),
            loB: limits[0].slice(16, 32),
            loC: limits[0].slice(32, 48),
            loD: limits[0].slice(48, 64),
            hiA: limits[1].slice(0, 16),
            hiB: limits[1].slice(16, 32),
            hiC: limits[1].slice(32, 48),
            hiD: limits[1].slice(48, 64)
          };
        }
        function renderGLParcoords(panels, setChanged, clearOnly) {
          var panelCount = panels.length;
          var i;
          var leftmost;
          var rightmost;
          var lowestX = Infinity;
          var highestX = -Infinity;
          for (i = 0; i < panelCount; i++) {
            if (panels[i].dim0.canvasX < lowestX) {
              lowestX = panels[i].dim0.canvasX;
              leftmost = i;
            }
            if (panels[i].dim1.canvasX > highestX) {
              highestX = panels[i].dim1.canvasX;
              rightmost = i;
            }
          }
          if (panelCount === 0) {
            clear(regl, 0, 0, model.canvasWidth, model.canvasHeight);
          }
          var constraints = makeConstraints(isContext);
          for (i = 0; i < panelCount; i++) {
            var p = panels[i];
            var i0 = p.dim0.crossfilterDimensionIndex;
            var i1 = p.dim1.crossfilterDimensionIndex;
            var x = p.canvasX;
            var y = p.canvasY;
            var nextX = x + p.panelSizeX;
            var plotGlPixelRatio2 = p.plotGlPixelRatio;
            if (setChanged || !prevAxisOrder[i0] || prevAxisOrder[i0][0] !== x || prevAxisOrder[i0][1] !== nextX) {
              prevAxisOrder[i0] = [x, nextX];
              var item = makeItem(
                model,
                leftmost,
                rightmost,
                i,
                i0,
                i1,
                x,
                y,
                p.panelSizeX,
                p.panelSizeY,
                p.dim0.crossfilterDimensionIndex,
                isContext ? 0 : isPick ? 2 : 1,
                constraints,
                plotGlPixelRatio2
              );
              renderState.clearOnly = clearOnly;
              var blockLineCount = setChanged ? model.lines.blockLineCount : sampleCount;
              renderBlock(
                regl,
                glAes,
                renderState,
                blockLineCount,
                sampleCount,
                item
              );
            }
          }
        }
        function readPixel(canvasX, canvasY) {
          regl.read({
            x: canvasX,
            y: canvasY,
            width: 1,
            height: 1,
            data: dataPixel
          });
          return dataPixel;
        }
        function readPixels(canvasX, canvasY, width, height) {
          var pixelArray = new Uint8Array(4 * width * height);
          regl.read({
            x: canvasX,
            y: canvasY,
            width,
            height,
            data: pixelArray
          });
          return pixelArray;
        }
        function destroy() {
          canvasGL.style["pointer-events"] = "none";
          paletteTexture.destroy();
          if (maskTexture) maskTexture.destroy();
          for (var k in attributes) attributes[k].destroy();
        }
        return {
          render: renderGLParcoords,
          readPixel,
          readPixels,
          destroy,
          update
        };
      };
    }
  });

  // src/traces/parcoords/parcoords.js
  var require_parcoords = __commonJS({
    "src/traces/parcoords/parcoords.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var numberFormat = Lib.numberFormat;
      var rgba3 = (init_color_rgba(), __toCommonJS(color_rgba_exports)).default;
      var Axes = require_axes();
      var strRotate = Lib.strRotate;
      var strTranslate = Lib.strTranslate;
      var svgTextUtils = require_svg_text_utils();
      var Drawing = require_drawing();
      var Colorscale = require_colorscale();
      var gup = require_gup();
      var keyFun = gup.keyFun;
      var repeat = gup.repeat;
      var unwrap = gup.unwrap;
      var helpers = require_helpers18();
      var c = require_constants24();
      var brush = require_axisbrush();
      var lineLayerMaker = require_lines();
      function findExtreme(fn, values, len) {
        return Lib.aggNums(fn, null, values, len);
      }
      function findExtremes(values, len) {
        return fixExtremes(
          findExtreme(Math.min, values, len),
          findExtreme(Math.max, values, len)
        );
      }
      function dimensionExtent(dimension) {
        var range = dimension.range;
        return range ? fixExtremes(range[0], range[1]) : findExtremes(dimension.values, dimension._length);
      }
      function fixExtremes(lo, hi) {
        if (isNaN(lo) || !isFinite(lo)) {
          lo = 0;
        }
        if (isNaN(hi) || !isFinite(hi)) {
          hi = 0;
        }
        if (lo === hi) {
          if (lo === 0) {
            lo -= 1;
            hi += 1;
          } else {
            lo *= 0.9;
            hi *= 1.1;
          }
        }
        return [lo, hi];
      }
      function toText(formatter, texts) {
        if (texts) {
          return function(v, i) {
            var text = texts[i];
            if (text === null || text === void 0) return formatter(v);
            return text;
          };
        }
        return formatter;
      }
      function domainScale(height, padding, dimension, tickvals, ticktext) {
        var extent = dimensionExtent(dimension);
        if (tickvals) {
          return d3.scale.ordinal().domain(tickvals.map(toText(numberFormat(dimension.tickformat), ticktext))).range(
            tickvals.map(function(d) {
              var unitVal = (d - extent[0]) / (extent[1] - extent[0]);
              return height - padding + unitVal * (2 * padding - height);
            })
          );
        }
        return d3.scale.linear().domain(extent).range([height - padding, padding]);
      }
      function unitToPaddedPx(height, padding) {
        return d3.scale.linear().range([padding, height - padding]);
      }
      function domainToPaddedUnitScale(dimension, padFraction) {
        return d3.scale.linear().domain(dimensionExtent(dimension)).range([padFraction, 1 - padFraction]);
      }
      function ordinalScale(dimension) {
        if (!dimension.tickvals) return;
        var extent = dimensionExtent(dimension);
        return d3.scale.ordinal().domain(dimension.tickvals).range(dimension.tickvals.map(function(d) {
          return (d - extent[0]) / (extent[1] - extent[0]);
        }));
      }
      function unitToColorScale(cscale) {
        var colorStops = cscale.map(function(d) {
          return d[0];
        });
        var colorTuples = cscale.map(function(d) {
          var RGBA = rgba3(d[1]);
          return d3.rgb("rgb(" + RGBA[0] + "," + RGBA[1] + "," + RGBA[2] + ")");
        });
        var prop = function(n) {
          return function(o) {
            return o[n];
          };
        };
        var polylinearUnitScales = "rgb".split("").map(function(key) {
          return d3.scale.linear().clamp(true).domain(colorStops).range(colorTuples.map(prop(key)));
        });
        return function(d) {
          return polylinearUnitScales.map(function(s) {
            return s(d);
          });
        };
      }
      function someFiltersActive(view) {
        return view.dimensions.some(function(p) {
          return p.brush.filterSpecified;
        });
      }
      function model(layout, d, i) {
        var cd0 = unwrap(d);
        var trace = cd0.trace;
        var lineColor = helpers.convertTypedArray(cd0.lineColor);
        var line = trace.line;
        var deselectedLines = {
          color: rgba3(trace.unselected.line.color),
          opacity: trace.unselected.line.opacity
        };
        var cOpts = Colorscale.extractOpts(line);
        var cscale = cOpts.reversescale ? Colorscale.flipScale(cd0.cscale) : cd0.cscale;
        var domain = trace.domain;
        var dimensions = trace.dimensions;
        var width = layout.width;
        var labelAngle = trace.labelangle;
        var labelSide = trace.labelside;
        var labelFont = trace.labelfont;
        var tickFont = trace.tickfont;
        var rangeFont = trace.rangefont;
        var lines = Lib.extendDeepNoArrays({}, line, {
          color: lineColor.map(d3.scale.linear().domain(
            dimensionExtent({
              values: lineColor,
              range: [cOpts.min, cOpts.max],
              _length: trace._length
            })
          )),
          blockLineCount: c.blockLineCount,
          canvasOverdrag: c.overdrag * c.canvasPixelRatio
        });
        var groupWidth = Math.floor(width * (domain.x[1] - domain.x[0]));
        var groupHeight = Math.floor(layout.height * (domain.y[1] - domain.y[0]));
        var pad = layout.margin || { l: 80, r: 80, t: 100, b: 80 };
        var rowContentWidth = groupWidth;
        var rowHeight = groupHeight;
        return {
          key: i,
          colCount: dimensions.filter(helpers.isVisible).length,
          dimensions,
          tickDistance: c.tickDistance,
          unitToColor: unitToColorScale(cscale),
          lines,
          deselectedLines,
          labelAngle,
          labelSide,
          labelFont,
          tickFont,
          rangeFont,
          layoutWidth: width,
          layoutHeight: layout.height,
          domain,
          translateX: domain.x[0] * width,
          translateY: layout.height - domain.y[1] * layout.height,
          pad,
          canvasWidth: rowContentWidth * c.canvasPixelRatio + 2 * lines.canvasOverdrag,
          canvasHeight: rowHeight * c.canvasPixelRatio,
          width: rowContentWidth,
          height: rowHeight,
          canvasPixelRatio: c.canvasPixelRatio
        };
      }
      function viewModel(state, callbacks, model2) {
        var width = model2.width;
        var height = model2.height;
        var dimensions = model2.dimensions;
        var canvasPixelRatio = model2.canvasPixelRatio;
        var xScale = function(d) {
          return width * d / Math.max(1, model2.colCount - 1);
        };
        var unitPad = c.verticalPadding / height;
        var _unitToPaddedPx = unitToPaddedPx(height, c.verticalPadding);
        var vm = {
          key: model2.key,
          xScale,
          model: model2,
          inBrushDrag: false
          // consider factoring it out and putting it in a centralized global-ish gesture state object
        };
        var uniqueKeys = {};
        vm.dimensions = dimensions.filter(helpers.isVisible).map(function(dimension, i) {
          var domainToPaddedUnit = domainToPaddedUnitScale(dimension, unitPad);
          var foundKey = uniqueKeys[dimension.label];
          uniqueKeys[dimension.label] = (foundKey || 0) + 1;
          var key = dimension.label + (foundKey ? "__" + foundKey : "");
          var specifiedConstraint = dimension.constraintrange;
          var filterRangeSpecified = specifiedConstraint && specifiedConstraint.length;
          if (filterRangeSpecified && !isArrayOrTypedArray(specifiedConstraint[0])) {
            specifiedConstraint = [specifiedConstraint];
          }
          var filterRange = filterRangeSpecified ? specifiedConstraint.map(function(d) {
            return d.map(domainToPaddedUnit);
          }) : [[-Infinity, Infinity]];
          var brushMove = function() {
            var p = vm;
            p.focusLayer && p.focusLayer.render(p.panels, true);
            var filtersActive = someFiltersActive(p);
            if (!state.contextShown() && filtersActive) {
              p.contextLayer && p.contextLayer.render(p.panels, true);
              state.contextShown(true);
            } else if (state.contextShown() && !filtersActive) {
              p.contextLayer && p.contextLayer.render(p.panels, true, true);
              state.contextShown(false);
            }
          };
          var truncatedValues = dimension.values;
          if (truncatedValues.length > dimension._length) {
            truncatedValues = truncatedValues.slice(0, dimension._length);
          }
          var tickvals = dimension.tickvals;
          var ticktext;
          function makeTickItem(v, i2) {
            return { val: v, text: ticktext[i2] };
          }
          function sortTickItem(a, b) {
            return a.val - b.val;
          }
          if (isArrayOrTypedArray(tickvals) && tickvals.length) {
            if (Lib.isTypedArray(tickvals)) tickvals = Array.from(tickvals);
            ticktext = dimension.ticktext;
            if (!isArrayOrTypedArray(ticktext) || !ticktext.length) {
              ticktext = tickvals.map(numberFormat(dimension.tickformat));
            } else if (ticktext.length > tickvals.length) {
              ticktext = ticktext.slice(0, tickvals.length);
            } else if (tickvals.length > ticktext.length) {
              tickvals = tickvals.slice(0, ticktext.length);
            }
            for (var j = 1; j < tickvals.length; j++) {
              if (tickvals[j] < tickvals[j - 1]) {
                var tickItems = tickvals.map(makeTickItem).sort(sortTickItem);
                for (var k = 0; k < tickvals.length; k++) {
                  tickvals[k] = tickItems[k].val;
                  ticktext[k] = tickItems[k].text;
                }
                break;
              }
            }
          } else tickvals = void 0;
          truncatedValues = helpers.convertTypedArray(truncatedValues);
          return {
            key,
            label: dimension.label,
            tickFormat: dimension.tickformat,
            tickvals,
            ticktext,
            ordinal: helpers.isOrdinal(dimension),
            multiselect: dimension.multiselect,
            xIndex: i,
            crossfilterDimensionIndex: i,
            visibleIndex: dimension._index,
            height,
            values: truncatedValues,
            paddedUnitValues: truncatedValues.map(domainToPaddedUnit),
            unitTickvals: tickvals && tickvals.map(domainToPaddedUnit),
            xScale,
            x: xScale(i),
            canvasX: xScale(i) * canvasPixelRatio,
            unitToPaddedPx: _unitToPaddedPx,
            domainScale: domainScale(height, c.verticalPadding, dimension, tickvals, ticktext),
            ordinalScale: ordinalScale(dimension),
            parent: vm,
            model: model2,
            brush: brush.makeBrush(
              state,
              filterRangeSpecified,
              filterRange,
              function() {
                state.linePickActive(false);
              },
              brushMove,
              function(f) {
                vm.focusLayer.render(vm.panels, true);
                vm.pickLayer && vm.pickLayer.render(vm.panels, true);
                state.linePickActive(true);
                if (callbacks && callbacks.filterChanged) {
                  var invScale = domainToPaddedUnit.invert;
                  var newRanges = f.map(function(r) {
                    return r.map(invScale).sort(Lib.sorterAsc);
                  }).sort(function(a, b) {
                    return a[0] - b[0];
                  });
                  callbacks.filterChanged(vm.key, dimension._index, newRanges);
                }
              }
            )
          };
        });
        return vm;
      }
      function styleExtentTexts(selection) {
        selection.classed(c.cn.axisExtentText, true).attr("text-anchor", "middle").style("cursor", "default");
      }
      function parcoordsInteractionState() {
        var linePickActive = true;
        var contextShown = false;
        return {
          linePickActive: function(val) {
            return arguments.length ? linePickActive = !!val : linePickActive;
          },
          contextShown: function(val) {
            return arguments.length ? contextShown = !!val : contextShown;
          }
        };
      }
      function calcTilt(angle, position) {
        var dir = position === "top" ? 1 : -1;
        var radians2 = angle * Math.PI / 180;
        var dx = Math.sin(radians2);
        var dy = Math.cos(radians2);
        return {
          dir,
          dx,
          dy,
          degrees: angle
        };
      }
      function updatePanelLayout(yAxis, vm, plotGlPixelRatio) {
        var panels = vm.panels || (vm.panels = []);
        var data = yAxis.data();
        for (var i = 0; i < data.length - 1; i++) {
          var p = panels[i] || (panels[i] = {});
          var dim0 = data[i];
          var dim1 = data[i + 1];
          p.dim0 = dim0;
          p.dim1 = dim1;
          p.canvasX = dim0.canvasX;
          p.panelSizeX = dim1.canvasX - dim0.canvasX;
          p.panelSizeY = vm.model.canvasHeight;
          p.y = 0;
          p.canvasY = 0;
          p.plotGlPixelRatio = plotGlPixelRatio;
        }
      }
      function calcAllTicks(cd) {
        for (var i = 0; i < cd.length; i++) {
          for (var j = 0; j < cd[i].length; j++) {
            var trace = cd[i][j].trace;
            var dimensions = trace.dimensions;
            for (var k = 0; k < dimensions.length; k++) {
              var values = dimensions[k].values;
              var dim = dimensions[k]._ax;
              if (dim) {
                if (!dim.range) {
                  dim.range = findExtremes(values, trace._length);
                } else {
                  dim.range = fixExtremes(dim.range[0], dim.range[1]);
                }
                if (!dim.dtick) {
                  dim.dtick = 0.01 * (Math.abs(dim.range[1] - dim.range[0]) || 1);
                }
                dim.tickformat = dimensions[k].tickformat;
                Axes.calcTicks(dim);
                dim.cleanRange();
              }
            }
          }
        }
      }
      function linearFormat(dim, v) {
        return Axes.tickText(dim._ax, v, false).text;
      }
      function extremeText(d, isTop) {
        if (d.ordinal) return "";
        var domain = d.domainScale.domain();
        var v = domain[isTop ? domain.length - 1 : 0];
        return linearFormat(d.model.dimensions[d.visibleIndex], v);
      }
      module.exports = function parcoords(gd, cdModule, layout, callbacks) {
        var isStatic = gd._context.staticPlot;
        var fullLayout = gd._fullLayout;
        var svg = fullLayout._toppaper;
        var glContainer = fullLayout._glcontainer;
        var plotGlPixelRatio = gd._context.plotGlPixelRatio;
        var paperColor = gd._fullLayout.paper_bgcolor;
        calcAllTicks(cdModule);
        var state = parcoordsInteractionState();
        var vm = cdModule.filter(function(d) {
          return unwrap(d).trace.visible;
        }).map(model.bind(0, layout)).map(viewModel.bind(0, state, callbacks));
        glContainer.each(function(d, i) {
          return Lib.extendFlat(d, vm[i]);
        });
        var glLayers = glContainer.selectAll(".gl-canvas").each(function(d) {
          d.viewModel = vm[0];
          d.viewModel.plotGlPixelRatio = plotGlPixelRatio;
          d.viewModel.paperColor = paperColor;
          d.model = d.viewModel ? d.viewModel.model : null;
        });
        var lastHovered = null;
        var pickLayer = glLayers.filter(function(d) {
          return d.pick;
        });
        pickLayer.style("pointer-events", isStatic ? "none" : "auto").on("mousemove", function(d) {
          if (state.linePickActive() && d.lineLayer && callbacks && callbacks.hover) {
            var event = d3.event;
            var cw = this.width;
            var ch = this.height;
            var pointer = d3.mouse(this);
            var x = pointer[0];
            var y = pointer[1];
            if (x < 0 || y < 0 || x >= cw || y >= ch) {
              return;
            }
            var pixel = d.lineLayer.readPixel(x, ch - 1 - y);
            var found = pixel[3] !== 0;
            var curveNumber = found ? pixel[2] + 256 * (pixel[1] + 256 * pixel[0]) : null;
            var eventData = {
              x,
              y,
              clientX: event.clientX,
              clientY: event.clientY,
              dataIndex: d.model.key,
              curveNumber
            };
            if (curveNumber !== lastHovered) {
              if (found) {
                callbacks.hover(eventData);
              } else if (callbacks.unhover) {
                callbacks.unhover(eventData);
              }
              lastHovered = curveNumber;
            }
          }
        });
        glLayers.style("opacity", function(d) {
          return d.pick ? 0 : 1;
        });
        svg.style("background", "rgba(255, 255, 255, 0)");
        var controlOverlay = svg.selectAll("." + c.cn.parcoords).data(vm, keyFun);
        controlOverlay.exit().remove();
        controlOverlay.enter().append("g").classed(c.cn.parcoords, true).style("shape-rendering", "crispEdges").style("pointer-events", "none");
        controlOverlay.attr("transform", function(d) {
          return strTranslate(d.model.translateX, d.model.translateY);
        });
        var parcoordsControlView = controlOverlay.selectAll("." + c.cn.parcoordsControlView).data(repeat, keyFun);
        parcoordsControlView.enter().append("g").classed(c.cn.parcoordsControlView, true);
        parcoordsControlView.attr("transform", function(d) {
          return strTranslate(d.model.pad.l, d.model.pad.t);
        });
        var yAxis = parcoordsControlView.selectAll("." + c.cn.yAxis).data(function(p) {
          return p.dimensions;
        }, keyFun);
        yAxis.enter().append("g").classed(c.cn.yAxis, true);
        parcoordsControlView.each(function(p) {
          updatePanelLayout(yAxis, p, plotGlPixelRatio);
        });
        glLayers.each(function(d) {
          if (d.viewModel) {
            if (!d.lineLayer || callbacks) {
              d.lineLayer = lineLayerMaker(this, d);
            } else d.lineLayer.update(d);
            if (d.key || d.key === 0) d.viewModel[d.key] = d.lineLayer;
            var setChanged = !d.context || // don't update background
            callbacks;
            d.lineLayer.render(d.viewModel.panels, setChanged);
          }
        });
        yAxis.attr("transform", function(d) {
          return strTranslate(d.xScale(d.xIndex), 0);
        });
        yAxis.call(
          d3.behavior.drag().origin(function(d) {
            return d;
          }).on("drag", function(d) {
            var p = d.parent;
            state.linePickActive(false);
            d.x = Math.max(-c.overdrag, Math.min(d.model.width + c.overdrag, d3.event.x));
            d.canvasX = d.x * d.model.canvasPixelRatio;
            yAxis.sort(function(a, b) {
              return a.x - b.x;
            }).each(function(e, i) {
              e.xIndex = i;
              e.x = d === e ? e.x : e.xScale(e.xIndex);
              e.canvasX = e.x * e.model.canvasPixelRatio;
            });
            updatePanelLayout(yAxis, p, plotGlPixelRatio);
            yAxis.filter(function(e) {
              return Math.abs(d.xIndex - e.xIndex) !== 0;
            }).attr("transform", function(d2) {
              return strTranslate(d2.xScale(d2.xIndex), 0);
            });
            d3.select(this).attr("transform", strTranslate(d.x, 0));
            yAxis.each(function(e, i0, i1) {
              if (i1 === d.parent.key) p.dimensions[i0] = e;
            });
            p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
            p.focusLayer.render && p.focusLayer.render(p.panels);
          }).on("dragend", function(d) {
            var p = d.parent;
            d.x = d.xScale(d.xIndex);
            d.canvasX = d.x * d.model.canvasPixelRatio;
            updatePanelLayout(yAxis, p, plotGlPixelRatio);
            d3.select(this).attr("transform", function(d2) {
              return strTranslate(d2.x, 0);
            });
            p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p));
            p.focusLayer && p.focusLayer.render(p.panels);
            p.pickLayer && p.pickLayer.render(p.panels, true);
            state.linePickActive(true);
            if (callbacks && callbacks.axesMoved) {
              callbacks.axesMoved(p.key, p.dimensions.map(function(e) {
                return e.crossfilterDimensionIndex;
              }));
            }
          })
        );
        yAxis.exit().remove();
        var axisOverlays = yAxis.selectAll("." + c.cn.axisOverlays).data(repeat, keyFun);
        axisOverlays.enter().append("g").classed(c.cn.axisOverlays, true);
        axisOverlays.selectAll("." + c.cn.axis).remove();
        var axis = axisOverlays.selectAll("." + c.cn.axis).data(repeat, keyFun);
        axis.enter().append("g").classed(c.cn.axis, true);
        axis.each(function(d) {
          var wantedTickCount = d.model.height / d.model.tickDistance;
          var scale = d.domainScale;
          var sdom = scale.domain();
          d3.select(this).call(d3.svg.axis().orient("left").tickSize(4).outerTickSize(2).ticks(wantedTickCount, d.tickFormat).tickValues(d.ordinal ? (
            // and this works for ordinal scales
            sdom
          ) : null).tickFormat(function(v) {
            return helpers.isOrdinal(d) ? v : linearFormat(d.model.dimensions[d.visibleIndex], v);
          }).scale(scale));
          Drawing.font(axis.selectAll("text"), d.model.tickFont);
        });
        axis.selectAll(".domain, .tick>line").attr("fill", "none").attr("stroke", "black").attr("stroke-opacity", 0.25).attr("stroke-width", "1px");
        axis.selectAll("text").style("cursor", "default");
        var axisHeading = axisOverlays.selectAll("." + c.cn.axisHeading).data(repeat, keyFun);
        axisHeading.enter().append("g").classed(c.cn.axisHeading, true);
        var axisTitle = axisHeading.selectAll("." + c.cn.axisTitle).data(repeat, keyFun);
        axisTitle.enter().append("text").classed(c.cn.axisTitle, true).attr("text-anchor", "middle").style("cursor", "ew-resize").style("pointer-events", isStatic ? "none" : "auto");
        axisTitle.text(function(d) {
          return d.label;
        }).each(function(d) {
          var e = d3.select(this);
          Drawing.font(e, d.model.labelFont);
          svgTextUtils.convertToTspans(e, gd);
        }).attr("transform", function(d) {
          var tilt = calcTilt(d.model.labelAngle, d.model.labelSide);
          var r = c.axisTitleOffset;
          return (tilt.dir > 0 ? "" : strTranslate(0, 2 * r + d.model.height)) + strRotate(tilt.degrees) + strTranslate(-r * tilt.dx, -r * tilt.dy);
        }).attr("text-anchor", function(d) {
          var tilt = calcTilt(d.model.labelAngle, d.model.labelSide);
          var adx = Math.abs(tilt.dx);
          var ady = Math.abs(tilt.dy);
          if (2 * adx > ady) {
            return tilt.dir * tilt.dx < 0 ? "start" : "end";
          } else {
            return "middle";
          }
        });
        var axisExtent = axisOverlays.selectAll("." + c.cn.axisExtent).data(repeat, keyFun);
        axisExtent.enter().append("g").classed(c.cn.axisExtent, true);
        var axisExtentTop = axisExtent.selectAll("." + c.cn.axisExtentTop).data(repeat, keyFun);
        axisExtentTop.enter().append("g").classed(c.cn.axisExtentTop, true);
        axisExtentTop.attr("transform", strTranslate(0, -c.axisExtentOffset));
        var axisExtentTopText = axisExtentTop.selectAll("." + c.cn.axisExtentTopText).data(repeat, keyFun);
        axisExtentTopText.enter().append("text").classed(c.cn.axisExtentTopText, true).call(styleExtentTexts);
        axisExtentTopText.text(function(d) {
          return extremeText(d, true);
        }).each(function(d) {
          Drawing.font(d3.select(this), d.model.rangeFont);
        });
        var axisExtentBottom = axisExtent.selectAll("." + c.cn.axisExtentBottom).data(repeat, keyFun);
        axisExtentBottom.enter().append("g").classed(c.cn.axisExtentBottom, true);
        axisExtentBottom.attr("transform", function(d) {
          return strTranslate(0, d.model.height + c.axisExtentOffset);
        });
        var axisExtentBottomText = axisExtentBottom.selectAll("." + c.cn.axisExtentBottomText).data(repeat, keyFun);
        axisExtentBottomText.enter().append("text").classed(c.cn.axisExtentBottomText, true).attr("dy", "0.75em").call(styleExtentTexts);
        axisExtentBottomText.text(function(d) {
          return extremeText(d, false);
        }).each(function(d) {
          Drawing.font(d3.select(this), d.model.rangeFont);
        });
        brush.ensureAxisBrush(axisOverlays, paperColor, gd);
      };
    }
  });

  // src/traces/parcoords/plot.js
  var require_plot21 = __commonJS({
    "src/traces/parcoords/plot.js"(exports, module) {
      "use strict";
      var parcoords = require_parcoords();
      var prepareRegl = require_prepare_regl();
      var isVisible = require_helpers18().isVisible;
      var reglPrecompiled = {};
      function newIndex(visibleIndices, orig, dim) {
        var origIndex = orig.indexOf(dim);
        var currentIndex = visibleIndices.indexOf(origIndex);
        if (currentIndex === -1) {
          currentIndex += orig.length;
        }
        return currentIndex;
      }
      function sorter(visibleIndices, orig) {
        return function sorter2(d1, d2) {
          return newIndex(visibleIndices, orig, d1) - newIndex(visibleIndices, orig, d2);
        };
      }
      var exports = module.exports = function plot(gd, cdModule) {
        var fullLayout = gd._fullLayout;
        var success = prepareRegl(gd, [], reglPrecompiled);
        if (!success) return;
        var currentDims = {};
        var initialDims = {};
        var fullIndices = {};
        var inputIndices = {};
        var size = fullLayout._size;
        cdModule.forEach(function(d, i) {
          var trace = d[0].trace;
          fullIndices[i] = trace.index;
          var iIn = inputIndices[i] = trace.index;
          currentDims[i] = gd.data[iIn].dimensions;
          initialDims[i] = gd.data[iIn].dimensions.slice();
        });
        var filterChanged = function(i, initialDimIndex, newRanges) {
          var dim = initialDims[i][initialDimIndex];
          var newConstraints = newRanges.map(function(r) {
            return r.slice();
          });
          var aStr = "dimensions[" + initialDimIndex + "].constraintrange";
          var preGUI = fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid];
          if (preGUI[aStr] === void 0) {
            var initialVal = dim.constraintrange;
            preGUI[aStr] = initialVal || null;
          }
          var fullDimension = gd._fullData[fullIndices[i]].dimensions[initialDimIndex];
          if (!newConstraints.length) {
            delete dim.constraintrange;
            delete fullDimension.constraintrange;
            newConstraints = null;
          } else {
            if (newConstraints.length === 1) newConstraints = newConstraints[0];
            dim.constraintrange = newConstraints;
            fullDimension.constraintrange = newConstraints.slice();
            newConstraints = [newConstraints];
          }
          var restyleData = {};
          restyleData[aStr] = newConstraints;
          gd.emit("plotly_restyle", [restyleData, [inputIndices[i]]]);
        };
        var hover = function(eventData) {
          gd.emit("plotly_hover", eventData);
        };
        var unhover = function(eventData) {
          gd.emit("plotly_unhover", eventData);
        };
        var axesMoved = function(i, visibleIndices) {
          var orig = sorter(visibleIndices, initialDims[i].filter(isVisible));
          currentDims[i].sort(orig);
          initialDims[i].filter(function(d) {
            return !isVisible(d);
          }).sort(function(d) {
            return initialDims[i].indexOf(d);
          }).forEach(function(d) {
            currentDims[i].splice(currentDims[i].indexOf(d), 1);
            currentDims[i].splice(initialDims[i].indexOf(d), 0, d);
          });
          gd.emit("plotly_restyle", [{ dimensions: [currentDims[i]] }, [inputIndices[i]]]);
        };
        parcoords(
          gd,
          cdModule,
          {
            // layout
            width: size.w,
            height: size.h,
            margin: {
              t: size.t,
              r: size.r,
              b: size.b,
              l: size.l
            }
          },
          {
            // callbacks
            filterChanged,
            hover,
            unhover,
            axesMoved
          }
        );
      };
      exports.reglPrecompiled = reglPrecompiled;
    }
  });

  // src/traces/parcoords/base_plot.js
  var require_base_plot7 = __commonJS({
    "src/traces/parcoords/base_plot.js"(exports) {
      "use strict";
      var d3 = require_d3();
      var getModuleCalcData = require_get_data().getModuleCalcData;
      var parcoordsPlot = require_plot21();
      var xmlnsNamespaces = require_xmlns_namespaces();
      exports.name = "parcoords";
      exports.plot = function(gd) {
        var calcData = getModuleCalcData(gd.calcdata, "parcoords")[0];
        if (calcData.length) parcoordsPlot(gd, calcData);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var hadParcoords = oldFullLayout._has && oldFullLayout._has("parcoords");
        var hasParcoords = newFullLayout._has && newFullLayout._has("parcoords");
        if (hadParcoords && !hasParcoords) {
          oldFullLayout._paperdiv.selectAll(".parcoords").remove();
          oldFullLayout._glimages.selectAll("*").remove();
        }
      };
      exports.toSVG = function(gd) {
        var imageRoot = gd._fullLayout._glimages;
        var root = d3.select(gd).selectAll(".svg-container");
        var canvases = root.filter(function(d, i) {
          return i === root.size() - 1;
        }).selectAll(".gl-canvas-context, .gl-canvas-focus");
        function canvasToImage() {
          var canvas = this;
          var imageData = canvas.toDataURL("image/png");
          var image = imageRoot.append("svg:image");
          image.attr({
            xmlns: xmlnsNamespaces.svg,
            "xlink:href": imageData,
            preserveAspectRatio: "none",
            x: 0,
            y: 0,
            width: canvas.style.width,
            height: canvas.style.height
          });
        }
        canvases.each(canvasToImage);
        window.setTimeout(function() {
          d3.selectAll("#filterBarPattern").attr("id", "filterBarPattern");
        }, 60);
      };
    }
  });

  // src/traces/parcoords/base_index.js
  var require_base_index3 = __commonJS({
    "src/traces/parcoords/base_index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes52(),
        supplyDefaults: require_defaults48(),
        calc: require_calc31(),
        colorbar: {
          container: "line",
          min: "cmin",
          max: "cmax"
        },
        moduleType: "trace",
        name: "parcoords",
        basePlotModule: require_base_plot7(),
        categories: ["gl", "regl", "noOpacity", "noHover"],
        meta: {}
      };
    }
  });

  // src/traces/parcoords/index.js
  var require_parcoords2 = __commonJS({
    "src/traces/parcoords/index.js"(exports, module) {
      "use strict";
      var index = require_base_index3();
      index.plot = require_plot21();
      module.exports = index;
    }
  });

  // lib/parcoords.js
  var require_parcoords3 = __commonJS({
    "lib/parcoords.js"(exports, module) {
      "use strict";
      module.exports = require_parcoords2();
    }
  });

  // src/traces/parcats/attributes.js
  var require_attributes53 = __commonJS({
    "src/traces/parcats/attributes.js"(exports, module) {
      "use strict";
      var extendFlat = require_extend().extendFlat;
      var baseAttrs = require_attributes2();
      var fontAttrs = require_font_attributes();
      var colorScaleAttrs = require_attributes8();
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var domainAttrs = require_domain().attributes;
      var line = extendFlat({ editType: "calc" }, colorScaleAttrs("line", { editTypeOverride: "calc" }), {
        shape: {
          valType: "enumerated",
          values: ["linear", "hspline"],
          dflt: "linear",
          editType: "plot"
        },
        hovertemplate: hovertemplateAttrs(
          {
            editType: "plot",
            arrayOk: false
          },
          {
            keys: ["count", "probability"]
          }
        ),
        hovertemplatefallback: templatefallbackAttrs({ editType: "plot" })
      });
      module.exports = {
        domain: domainAttrs({ name: "parcats", trace: true, editType: "calc" }),
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["count", "probability"],
          editType: "plot",
          arrayOk: false
        }),
        hoveron: {
          valType: "enumerated",
          values: ["category", "color", "dimension"],
          dflt: "category",
          editType: "plot"
        },
        hovertemplate: hovertemplateAttrs(
          {
            editType: "plot",
            arrayOk: false
          },
          {
            keys: ["count", "probability", "category", "categorycount", "colorcount", "bandcolorcount"]
          }
        ),
        hovertemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        arrangement: {
          valType: "enumerated",
          values: ["perpendicular", "freeform", "fixed"],
          dflt: "perpendicular",
          editType: "plot"
        },
        bundlecolors: {
          valType: "boolean",
          dflt: true,
          editType: "plot"
        },
        sortpaths: {
          valType: "enumerated",
          values: ["forward", "backward"],
          dflt: "forward",
          editType: "plot"
        },
        labelfont: fontAttrs({
          editType: "calc"
        }),
        tickfont: fontAttrs({
          autoShadowDflt: true,
          editType: "calc"
        }),
        dimensions: {
          _isLinkedToArray: "dimension",
          label: {
            valType: "string",
            editType: "calc"
          },
          categoryorder: {
            valType: "enumerated",
            values: ["trace", "category ascending", "category descending", "array"],
            dflt: "trace",
            editType: "calc"
          },
          categoryarray: {
            valType: "data_array",
            editType: "calc"
          },
          ticktext: {
            valType: "data_array",
            editType: "calc"
          },
          values: {
            valType: "data_array",
            dflt: [],
            editType: "calc"
          },
          displayindex: {
            valType: "integer",
            editType: "calc"
          },
          editType: "calc",
          visible: {
            valType: "boolean",
            dflt: true,
            editType: "calc"
          }
        },
        line,
        counts: {
          valType: "number",
          min: 0,
          dflt: 1,
          arrayOk: true,
          editType: "calc"
        },
        // Hide unsupported top-level properties from plot-schema
        customdata: void 0,
        hoverlabel: void 0,
        ids: void 0,
        legend: void 0,
        legendgroup: void 0,
        legendrank: void 0,
        opacity: void 0,
        selectedpoints: void 0,
        showlegend: void 0
      };
    }
  });

  // src/traces/parcats/defaults.js
  var require_defaults49 = __commonJS({
    "src/traces/parcats/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleDefaults = require_defaults2();
      var handleDomainDefaults = require_domain().defaults;
      var handleArrayContainerDefaults = require_array_container_defaults();
      var attributes = require_attributes53();
      var mergeLength = require_merge_length();
      var isTypedArraySpec = require_array().isTypedArraySpec;
      function handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
        coerce("line.shape");
        coerce("line.hovertemplate");
        coerce("line.hovertemplatefallback");
        var lineColor = coerce("line.color", layout.colorway[0]);
        if (hasColorscale(traceIn, "line") && Lib.isArrayOrTypedArray(lineColor)) {
          if (lineColor.length) {
            coerce("line.colorscale");
            colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "line.", cLetter: "c" });
            return lineColor.length;
          } else {
            traceOut.line.color = defaultColor;
          }
        }
        return Infinity;
      }
      function dimensionDefaults(dimensionIn, dimensionOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(dimensionIn, dimensionOut, attributes.dimensions, attr, dflt);
        }
        var values = coerce("values");
        var visible = coerce("visible");
        if (!(values && values.length)) {
          visible = dimensionOut.visible = false;
        }
        if (visible) {
          coerce("label");
          coerce("displayindex", dimensionOut._index);
          var arrayIn = dimensionIn.categoryarray;
          var isValidArray = Lib.isArrayOrTypedArray(arrayIn) && arrayIn.length > 0 || isTypedArraySpec(arrayIn);
          var orderDefault;
          if (isValidArray) orderDefault = "array";
          var order = coerce("categoryorder", orderDefault);
          if (order === "array") {
            coerce("categoryarray");
            coerce("ticktext");
          } else {
            delete dimensionIn.categoryarray;
            delete dimensionIn.ticktext;
          }
          if (!isValidArray && order === "array") {
            dimensionOut.categoryorder = "trace";
          }
        }
      }
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var dimensions = handleArrayContainerDefaults(traceIn, traceOut, {
          name: "dimensions",
          handleItemDefaults: dimensionDefaults
        });
        var len = handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleDomainDefaults(traceOut, layout, coerce);
        if (!Array.isArray(dimensions) || !dimensions.length) {
          traceOut.visible = false;
        }
        mergeLength(traceOut, dimensions, "values", len);
        coerce("hoveron");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("arrangement");
        coerce("bundlecolors");
        coerce("sortpaths");
        coerce("counts");
        var layoutFont = layout.font;
        Lib.coerceFont(coerce, "labelfont", layoutFont, {
          overrideDflt: {
            size: Math.round(layoutFont.size)
          }
        });
        Lib.coerceFont(coerce, "tickfont", layoutFont, {
          autoShadowDflt: true,
          overrideDflt: {
            size: Math.round(layoutFont.size / 1.2)
          }
        });
      };
    }
  });

  // src/traces/parcats/calc.js
  var require_calc32 = __commonJS({
    "src/traces/parcats/calc.js"(exports, module) {
      "use strict";
      var wrap = require_gup().wrap;
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleCalc = require_calc();
      var filterUnique = require_filter_unique();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var isNumeric = require_fast_isnumeric();
      module.exports = function calc(gd, trace) {
        var visibleDims = Lib.filterVisible(trace.dimensions);
        if (visibleDims.length === 0) return [];
        var uniqueInfoDims = visibleDims.map(function(dim) {
          var categoryValues;
          if (dim.categoryorder === "trace") {
            categoryValues = null;
          } else if (dim.categoryorder === "array") {
            categoryValues = dim.categoryarray;
          } else {
            categoryValues = filterUnique(dim.values);
            var allNumeric = true;
            for (var i = 0; i < categoryValues.length; i++) {
              if (!isNumeric(categoryValues[i])) {
                allNumeric = false;
                break;
              }
            }
            categoryValues.sort(allNumeric ? Lib.sorterAsc : void 0);
            if (dim.categoryorder === "category descending") {
              categoryValues = categoryValues.reverse();
            }
          }
          return getUniqueInfo(dim.values, categoryValues);
        });
        var counts, count, totalCount;
        if (Lib.isArrayOrTypedArray(trace.counts)) {
          counts = trace.counts;
        } else {
          counts = [trace.counts];
        }
        validateDimensionDisplayInds(visibleDims);
        visibleDims.forEach(function(dim, dimInd) {
          validateCategoryProperties(dim, uniqueInfoDims[dimInd]);
        });
        var line = trace.line;
        var markerColorscale;
        if (line) {
          if (hasColorscale(trace, "line")) {
            colorscaleCalc(gd, trace, {
              vals: trace.line.color,
              containerStr: "line",
              cLetter: "c"
            });
          }
          markerColorscale = Drawing.tryColorscale(line);
        } else {
          markerColorscale = Lib.identity;
        }
        function getMarkerColorInfo(index) {
          var value, rawColor;
          if (Lib.isArrayOrTypedArray(line.color)) {
            value = line.color[index % line.color.length];
            rawColor = value;
          } else {
            value = line.color;
          }
          return { color: markerColorscale(value), rawColor };
        }
        var numValues = visibleDims[0].values.length;
        var pathModels = {};
        var categoryIndsDims = uniqueInfoDims.map(function(di) {
          return di.inds;
        });
        totalCount = 0;
        var valueInd;
        var d;
        for (valueInd = 0; valueInd < numValues; valueInd++) {
          var categoryIndsPath = [];
          for (d = 0; d < categoryIndsDims.length; d++) {
            categoryIndsPath.push(categoryIndsDims[d][valueInd]);
          }
          count = counts[valueInd % counts.length];
          totalCount += count;
          var pathColorInfo = getMarkerColorInfo(valueInd);
          var pathKey = categoryIndsPath + "-" + pathColorInfo.rawColor;
          if (pathModels[pathKey] === void 0) {
            pathModels[pathKey] = createPathModel(
              categoryIndsPath,
              pathColorInfo.color,
              pathColorInfo.rawColor
            );
          }
          updatePathModel(pathModels[pathKey], valueInd, count);
        }
        var dimensionModels = visibleDims.map(function(di, i) {
          return createDimensionModel(i, di._index, di._displayindex, di.label, totalCount);
        });
        for (valueInd = 0; valueInd < numValues; valueInd++) {
          count = counts[valueInd % counts.length];
          for (d = 0; d < dimensionModels.length; d++) {
            var containerInd = dimensionModels[d].containerInd;
            var catInd = uniqueInfoDims[d].inds[valueInd];
            var cats = dimensionModels[d].categories;
            if (cats[catInd] === void 0) {
              var catValue = trace.dimensions[containerInd]._categoryarray[catInd];
              var catLabel = trace.dimensions[containerInd]._ticktext[catInd];
              cats[catInd] = createCategoryModel(d, catInd, catValue, catLabel);
            }
            updateCategoryModel(cats[catInd], valueInd, count);
          }
        }
        return wrap(createParcatsModel(dimensionModels, pathModels, totalCount));
      };
      function createParcatsModel(dimensions, paths, count) {
        var maxCats = dimensions.map(function(d) {
          return d.categories.length;
        }).reduce(function(v1, v2) {
          return Math.max(v1, v2);
        });
        return { dimensions, paths, trace: void 0, maxCats, count };
      }
      function createDimensionModel(dimensionInd, containerInd, displayInd, dimensionLabel, count) {
        return {
          dimensionInd,
          containerInd,
          displayInd,
          dimensionLabel,
          count,
          categories: [],
          dragX: null
        };
      }
      function createCategoryModel(dimensionInd, categoryInd, categoryValue, categoryLabel) {
        return {
          dimensionInd,
          categoryInd,
          categoryValue,
          displayInd: categoryInd,
          categoryLabel,
          valueInds: [],
          count: 0,
          dragY: null
        };
      }
      function updateCategoryModel(categoryModel, valueInd, count) {
        categoryModel.valueInds.push(valueInd);
        categoryModel.count += count;
      }
      function createPathModel(categoryInds, color2, rawColor) {
        return {
          categoryInds,
          color: color2,
          rawColor,
          valueInds: [],
          count: 0
        };
      }
      function updatePathModel(pathModel, valueInd, count) {
        pathModel.valueInds.push(valueInd);
        pathModel.count += count;
      }
      function getUniqueInfo(values, uniqueValues) {
        if (uniqueValues === void 0 || uniqueValues === null) {
          uniqueValues = [];
        } else {
          uniqueValues = uniqueValues.map(function(e) {
            return e;
          });
        }
        var uniqueValueCounts = {};
        var uniqueValueInds = {};
        var inds = [];
        uniqueValues.forEach(function(uniqueVal, valInd) {
          uniqueValueCounts[uniqueVal] = 0;
          uniqueValueInds[uniqueVal] = valInd;
        });
        for (var i = 0; i < values.length; i++) {
          var item = values[i];
          var itemInd;
          if (uniqueValueCounts[item] === void 0) {
            uniqueValueCounts[item] = 1;
            itemInd = uniqueValues.push(item) - 1;
            uniqueValueInds[item] = itemInd;
          } else {
            uniqueValueCounts[item]++;
            itemInd = uniqueValueInds[item];
          }
          inds.push(itemInd);
        }
        var uniqueCounts = uniqueValues.map(function(v) {
          return uniqueValueCounts[v];
        });
        return {
          uniqueValues,
          uniqueCounts,
          inds
        };
      }
      function validateDimensionDisplayInds(visibleDims) {
        var displayInds = visibleDims.map(function(d) {
          return d.displayindex;
        });
        var i;
        if (isRangePermutation(displayInds)) {
          for (i = 0; i < visibleDims.length; i++) {
            visibleDims[i]._displayindex = visibleDims[i].displayindex;
          }
        } else {
          for (i = 0; i < visibleDims.length; i++) {
            visibleDims[i]._displayindex = i;
          }
        }
      }
      function validateCategoryProperties(dim, uniqueInfoDim) {
        dim._categoryarray = uniqueInfoDim.uniqueValues;
        if (dim.ticktext === null || dim.ticktext === void 0) {
          dim._ticktext = [];
        } else {
          dim._ticktext = dim.ticktext.slice();
        }
        for (var i = dim._ticktext.length; i < uniqueInfoDim.uniqueValues.length; i++) {
          dim._ticktext.push(uniqueInfoDim.uniqueValues[i]);
        }
      }
      function isRangePermutation(inds) {
        var indsSpecified = new Array(inds.length);
        for (var i = 0; i < inds.length; i++) {
          if (inds[i] < 0 || inds[i] >= inds.length) {
            return false;
          }
          if (indsSpecified[inds[i]] !== void 0) {
            return false;
          }
          indsSpecified[inds[i]] = true;
        }
        return true;
      }
    }
  });

  // src/traces/parcats/parcats.js
  var require_parcats = __commonJS({
    "src/traces/parcats/parcats.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var interpolateNumber = (init_src2(), __toCommonJS(src_exports)).interpolateNumber;
      var Plotly = require_plot_api();
      var Fx = require_fx();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var Drawing = require_drawing();
      var tinycolor = require_tinycolor();
      var svgTextUtils = require_svg_text_utils();
      function performPlot(parcatsModels, graphDiv, layout, svg) {
        var isStatic = graphDiv._context.staticPlot;
        var viewModels = parcatsModels.map(createParcatsViewModel.bind(0, graphDiv, layout));
        var layerSelection = svg.selectAll("g.parcatslayer").data([null]);
        layerSelection.enter().append("g").attr("class", "parcatslayer").style("pointer-events", isStatic ? "none" : "all");
        var traceSelection = layerSelection.selectAll("g.trace.parcats").data(viewModels, key);
        var traceEnter = traceSelection.enter().append("g").attr("class", "trace parcats");
        traceSelection.attr("transform", function(d) {
          return strTranslate(d.x, d.y);
        });
        traceEnter.append("g").attr("class", "paths");
        var pathsSelection = traceSelection.select("g.paths");
        var pathSelection = pathsSelection.selectAll("path.path").data(function(d) {
          return d.paths;
        }, key);
        pathSelection.attr("fill", function(d) {
          return d.model.color;
        });
        var pathSelectionEnter = pathSelection.enter().append("path").attr("class", "path").attr("stroke-opacity", 0).attr("fill", function(d) {
          return d.model.color;
        }).attr("fill-opacity", 0);
        stylePathsNoHover(pathSelectionEnter);
        pathSelection.attr("d", function(d) {
          return d.svgD;
        });
        if (!pathSelectionEnter.empty()) {
          pathSelection.sort(compareRawColor);
        }
        pathSelection.exit().remove();
        pathSelection.on("mouseover", mouseoverPath).on("mouseout", mouseoutPath).on("click", clickPath);
        traceEnter.append("g").attr("class", "dimensions");
        var dimensionsSelection = traceSelection.select("g.dimensions");
        var dimensionSelection = dimensionsSelection.selectAll("g.dimension").data(function(d) {
          return d.dimensions;
        }, key);
        dimensionSelection.enter().append("g").attr("class", "dimension");
        dimensionSelection.attr("transform", function(d) {
          return strTranslate(d.x, 0);
        });
        dimensionSelection.exit().remove();
        var categorySelection = dimensionSelection.selectAll("g.category").data(function(d) {
          return d.categories;
        }, key);
        var categoryGroupEnterSelection = categorySelection.enter().append("g").attr("class", "category");
        categorySelection.attr("transform", function(d) {
          return strTranslate(0, d.y);
        });
        categoryGroupEnterSelection.append("rect").attr("class", "catrect").attr("pointer-events", "none");
        categorySelection.select("rect.catrect").attr("fill", "none").attr("width", function(d) {
          return d.width;
        }).attr("height", function(d) {
          return d.height;
        });
        styleCategoriesNoHover(categoryGroupEnterSelection);
        var bandSelection = categorySelection.selectAll("rect.bandrect").data(
          /** @param {CategoryViewModel} catViewModel*/
          function(catViewModel) {
            return catViewModel.bands;
          },
          key
        );
        bandSelection.each(function() {
          Lib.raiseToTop(this);
        });
        bandSelection.attr("fill", function(d) {
          return d.color;
        });
        var bandsSelectionEnter = bandSelection.enter().append("rect").attr("class", "bandrect").attr("stroke-opacity", 0).attr("fill", function(d) {
          return d.color;
        }).attr("fill-opacity", 0);
        bandSelection.attr("fill", function(d) {
          return d.color;
        }).attr("width", function(d) {
          return d.width;
        }).attr("height", function(d) {
          return d.height;
        }).attr("y", function(d) {
          return d.y;
        }).attr(
          "cursor",
          /** @param {CategoryBandViewModel} bandModel*/
          function(bandModel) {
            if (bandModel.parcatsViewModel.arrangement === "fixed") {
              return "default";
            } else if (bandModel.parcatsViewModel.arrangement === "perpendicular") {
              return "ns-resize";
            } else {
              return "move";
            }
          }
        );
        styleBandsNoHover(bandsSelectionEnter);
        bandSelection.exit().remove();
        categoryGroupEnterSelection.append("text").attr("class", "catlabel").attr("pointer-events", "none");
        categorySelection.select("text.catlabel").attr(
          "text-anchor",
          function(d) {
            if (catInRightDim(d)) {
              return "start";
            } else {
              return "end";
            }
          }
        ).attr("alignment-baseline", "middle").style("fill", "rgb(0, 0, 0)").attr(
          "x",
          function(d) {
            if (catInRightDim(d)) {
              return d.width + 5;
            } else {
              return -5;
            }
          }
        ).attr("y", function(d) {
          return d.height / 2;
        }).text(function(d) {
          return d.model.categoryLabel;
        }).each(
          /** @param {CategoryViewModel} catModel*/
          function(catModel) {
            Drawing.font(d3.select(this), catModel.parcatsViewModel.categorylabelfont);
            svgTextUtils.convertToTspans(d3.select(this), graphDiv);
          }
        );
        categoryGroupEnterSelection.append("text").attr("class", "dimlabel");
        categorySelection.select("text.dimlabel").attr("text-anchor", "middle").attr("alignment-baseline", "baseline").attr(
          "cursor",
          /** @param {CategoryViewModel} catModel*/
          function(catModel) {
            if (catModel.parcatsViewModel.arrangement === "fixed") {
              return "default";
            } else {
              return "ew-resize";
            }
          }
        ).attr("x", function(d) {
          return d.width / 2;
        }).attr("y", -5).text(function(d, i) {
          if (i === 0) {
            return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
          } else {
            return null;
          }
        }).each(
          /** @param {CategoryViewModel} catModel*/
          function(catModel) {
            Drawing.font(d3.select(this), catModel.parcatsViewModel.labelfont);
          }
        );
        categorySelection.selectAll("rect.bandrect").on("mouseover", mouseoverCategoryBand).on("mouseout", mouseoutCategory);
        categorySelection.exit().remove();
        dimensionSelection.call(d3.behavior.drag().origin(function(d) {
          return { x: d.x, y: 0 };
        }).on("dragstart", dragDimensionStart).on("drag", dragDimension).on("dragend", dragDimensionEnd));
        traceSelection.each(function(d) {
          d.traceSelection = d3.select(this);
          d.pathSelection = d3.select(this).selectAll("g.paths").selectAll("path.path");
          d.dimensionSelection = d3.select(this).selectAll("g.dimensions").selectAll("g.dimension");
        });
        traceSelection.exit().remove();
      }
      module.exports = function(graphDiv, svg, parcatsModels, layout) {
        performPlot(parcatsModels, graphDiv, layout, svg);
      };
      function key(d) {
        return d.key;
      }
      function catInRightDim(d) {
        var numDims = d.parcatsViewModel.dimensions.length;
        var leftDimInd = d.parcatsViewModel.dimensions[numDims - 1].model.dimensionInd;
        return d.model.dimensionInd === leftDimInd;
      }
      function compareRawColor(a, b) {
        if (a.model.rawColor > b.model.rawColor) {
          return 1;
        } else if (a.model.rawColor < b.model.rawColor) {
          return -1;
        } else {
          return 0;
        }
      }
      function mouseoverPath(d) {
        if (!d.parcatsViewModel.dragDimension) {
          if (d.parcatsViewModel.hoverinfoItems.indexOf("skip") === -1) {
            Lib.raiseToTop(this);
            stylePathsHover(d3.select(this));
            var points = buildPointsArrayForPath(d);
            var constraints = buildConstraintsForPath(d);
            d.parcatsViewModel.graphDiv.emit("plotly_hover", {
              points,
              event: d3.event,
              constraints
            });
            if (d.parcatsViewModel.hoverinfoItems.indexOf("none") === -1) {
              var hoverX = d3.mouse(this)[0];
              var gd = d.parcatsViewModel.graphDiv;
              var trace = d.parcatsViewModel.trace;
              var fullLayout = gd._fullLayout;
              var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
              var graphDivBBox = d.parcatsViewModel.graphDiv.getBoundingClientRect();
              var pathCenterX, pathCenterY, dimInd;
              for (dimInd = 0; dimInd < d.leftXs.length - 1; dimInd++) {
                if (d.leftXs[dimInd] + d.dimWidths[dimInd] - 2 <= hoverX && hoverX <= d.leftXs[dimInd + 1] + 2) {
                  var leftDim = d.parcatsViewModel.dimensions[dimInd];
                  var rightDim = d.parcatsViewModel.dimensions[dimInd + 1];
                  pathCenterX = (leftDim.x + leftDim.width + rightDim.x) / 2;
                  pathCenterY = (d.topYs[dimInd] + d.topYs[dimInd + 1] + d.height) / 2;
                  break;
                }
              }
              var hoverCenterX = d.parcatsViewModel.x + pathCenterX;
              var hoverCenterY = d.parcatsViewModel.y + pathCenterY;
              var textColor = tinycolor.mostReadable(d.model.color, ["black", "white"]);
              var count = d.model.count;
              var prob = count / d.parcatsViewModel.model.count;
              var labels = {
                countLabel: count,
                probabilityLabel: prob.toFixed(3)
              };
              var hovertextParts = [];
              if (d.parcatsViewModel.hoverinfoItems.indexOf("count") !== -1) {
                hovertextParts.push(["Count:", labels.countLabel].join(" "));
              }
              if (d.parcatsViewModel.hoverinfoItems.indexOf("probability") !== -1) {
                hovertextParts.push(["P:", labels.probabilityLabel].join(" "));
              }
              var hovertext = hovertextParts.join("<br>");
              var mouseX = d3.mouse(gd)[0];
              Fx.loneHover({
                trace,
                x: hoverCenterX - rootBBox.left + graphDivBBox.left,
                y: hoverCenterY - rootBBox.top + graphDivBBox.top,
                text: hovertext,
                color: d.model.color,
                borderColor: "black",
                fontFamily: 'Monaco, "Courier New", monospace',
                fontSize: 10,
                fontColor: textColor,
                idealAlign: mouseX < hoverCenterX ? "right" : "left",
                hovertemplate: (trace.line || {}).hovertemplate,
                hovertemplateLabels: labels,
                eventData: [{
                  data: trace._input,
                  fullData: trace,
                  count,
                  probability: prob
                }]
              }, {
                container: fullLayout._hoverlayer.node(),
                outerContainer: fullLayout._paper.node(),
                gd
              });
            }
          }
        }
      }
      function mouseoutPath(d) {
        if (!d.parcatsViewModel.dragDimension) {
          stylePathsNoHover(d3.select(this));
          Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
          d.parcatsViewModel.pathSelection.sort(compareRawColor);
          if (d.parcatsViewModel.hoverinfoItems.indexOf("skip") === -1) {
            var points = buildPointsArrayForPath(d);
            var constraints = buildConstraintsForPath(d);
            d.parcatsViewModel.graphDiv.emit("plotly_unhover", {
              points,
              event: d3.event,
              constraints
            });
          }
        }
      }
      function buildPointsArrayForPath(d) {
        var points = [];
        var curveNumber = getTraceIndex(d.parcatsViewModel);
        for (var i = 0; i < d.model.valueInds.length; i++) {
          var pointNumber = d.model.valueInds[i];
          points.push({
            curveNumber,
            pointNumber
          });
        }
        return points;
      }
      function buildConstraintsForPath(d) {
        var constraints = {};
        var dimensions = d.parcatsViewModel.model.dimensions;
        for (var i = 0; i < dimensions.length; i++) {
          var dimension = dimensions[i];
          var category = dimension.categories[d.model.categoryInds[i]];
          constraints[dimension.containerInd] = category.categoryValue;
        }
        if (d.model.rawColor !== void 0) {
          constraints.color = d.model.rawColor;
        }
        return constraints;
      }
      function clickPath(d) {
        if (d.parcatsViewModel.hoverinfoItems.indexOf("skip") === -1) {
          var points = buildPointsArrayForPath(d);
          var constraints = buildConstraintsForPath(d);
          d.parcatsViewModel.graphDiv.emit("plotly_click", {
            points,
            event: d3.event,
            constraints
          });
        }
      }
      function stylePathsNoHover(pathSelection) {
        pathSelection.attr("fill", function(d) {
          return d.model.color;
        }).attr("fill-opacity", 0.6).attr("stroke", "lightgray").attr("stroke-width", 0.2).attr("stroke-opacity", 1);
      }
      function stylePathsHover(pathSelection) {
        pathSelection.attr("fill-opacity", 0.8).attr("stroke", function(d) {
          return tinycolor.mostReadable(d.model.color, ["black", "white"]);
        }).attr("stroke-width", 0.3);
      }
      function styleCategoryHover(categorySelection) {
        categorySelection.select("rect.catrect").attr("stroke", "black").attr("stroke-width", 2.5);
      }
      function styleCategoriesNoHover(categorySelection) {
        categorySelection.select("rect.catrect").attr("stroke", "black").attr("stroke-width", 1).attr("stroke-opacity", 1);
      }
      function styleBandsHover(bandsSelection) {
        bandsSelection.attr("stroke", "black").attr("stroke-width", 1.5);
      }
      function styleBandsNoHover(bandsSelection) {
        bandsSelection.attr("stroke", "black").attr("stroke-width", 0.2).attr("stroke-opacity", 1).attr("fill-opacity", 1);
      }
      function selectPathsThroughCategoryBandColor(catBandViewModel) {
        var allPaths = catBandViewModel.parcatsViewModel.pathSelection;
        var dimInd = catBandViewModel.categoryViewModel.model.dimensionInd;
        var catInd = catBandViewModel.categoryViewModel.model.categoryInd;
        return allPaths.filter(
          /** @param {PathViewModel} pathViewModel */
          function(pathViewModel) {
            return pathViewModel.model.categoryInds[dimInd] === catInd && pathViewModel.model.color === catBandViewModel.color;
          }
        );
      }
      function styleForCategoryHovermode(bandElement) {
        var bandSel = d3.select(bandElement.parentNode).selectAll("rect.bandrect");
        bandSel.each(function(bvm) {
          var paths = selectPathsThroughCategoryBandColor(bvm);
          stylePathsHover(paths);
          paths.each(function() {
            Lib.raiseToTop(this);
          });
        });
        styleCategoryHover(d3.select(bandElement.parentNode));
      }
      function styleForColorHovermode(bandElement) {
        var bandViewModel = d3.select(bandElement).datum();
        var catPaths = selectPathsThroughCategoryBandColor(bandViewModel);
        stylePathsHover(catPaths);
        catPaths.each(function() {
          Lib.raiseToTop(this);
        });
        d3.select(bandElement.parentNode).selectAll("rect.bandrect").filter(function(b) {
          return b.color === bandViewModel.color;
        }).each(function() {
          Lib.raiseToTop(this);
          styleBandsHover(d3.select(this));
        });
      }
      function emitPointsEventCategoryHovermode(bandElement, eventName, event) {
        var bandViewModel = d3.select(bandElement).datum();
        var categoryModel = bandViewModel.categoryViewModel.model;
        var gd = bandViewModel.parcatsViewModel.graphDiv;
        var bandSel = d3.select(bandElement.parentNode).selectAll("rect.bandrect");
        var points = [];
        bandSel.each(function(bvm) {
          var paths = selectPathsThroughCategoryBandColor(bvm);
          paths.each(function(pathViewModel) {
            Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
          });
        });
        var constraints = {};
        constraints[categoryModel.dimensionInd] = categoryModel.categoryValue;
        gd.emit(eventName, {
          points,
          event,
          constraints
        });
      }
      function emitPointsEventColorHovermode(bandElement, eventName, event) {
        var bandViewModel = d3.select(bandElement).datum();
        var categoryModel = bandViewModel.categoryViewModel.model;
        var gd = bandViewModel.parcatsViewModel.graphDiv;
        var paths = selectPathsThroughCategoryBandColor(bandViewModel);
        var points = [];
        paths.each(function(pathViewModel) {
          Array.prototype.push.apply(points, buildPointsArrayForPath(pathViewModel));
        });
        var constraints = {};
        constraints[categoryModel.dimensionInd] = categoryModel.categoryValue;
        if (bandViewModel.rawColor !== void 0) {
          constraints.color = bandViewModel.rawColor;
        }
        gd.emit(eventName, {
          points,
          event,
          constraints
        });
      }
      function createHoverLabelForCategoryHovermode(gd, rootBBox, bandElement) {
        gd._fullLayout._calcInverseTransform(gd);
        var scaleX = gd._fullLayout._invScaleX;
        var scaleY = gd._fullLayout._invScaleY;
        var rectSelection = d3.select(bandElement.parentNode).select("rect.catrect");
        var rectBoundingBox = rectSelection.node().getBoundingClientRect();
        var catViewModel = rectSelection.datum();
        var parcatsViewModel = catViewModel.parcatsViewModel;
        var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];
        var trace = parcatsViewModel.trace;
        var hoverCenterY = rectBoundingBox.top + rectBoundingBox.height / 2;
        var hoverCenterX, hoverLabelIdealAlign;
        if (parcatsViewModel.dimensions.length > 1 && dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {
          hoverCenterX = rectBoundingBox.left;
          hoverLabelIdealAlign = "left";
        } else {
          hoverCenterX = rectBoundingBox.left + rectBoundingBox.width;
          hoverLabelIdealAlign = "right";
        }
        var count = catViewModel.model.count;
        var catLabel = catViewModel.model.categoryLabel;
        var prob = count / catViewModel.parcatsViewModel.model.count;
        var labels = {
          countLabel: count,
          categoryLabel: catLabel,
          probabilityLabel: prob.toFixed(3)
        };
        var hoverinfoParts = [];
        if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf("count") !== -1) {
          hoverinfoParts.push(["Count:", labels.countLabel].join(" "));
        }
        if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf("probability") !== -1) {
          hoverinfoParts.push(["P(" + labels.categoryLabel + "):", labels.probabilityLabel].join(" "));
        }
        var hovertext = hoverinfoParts.join("<br>");
        return {
          trace,
          x: scaleX * (hoverCenterX - rootBBox.left),
          y: scaleY * (hoverCenterY - rootBBox.top),
          text: hovertext,
          color: "lightgray",
          borderColor: "black",
          fontFamily: 'Monaco, "Courier New", monospace',
          fontSize: 12,
          fontColor: "black",
          idealAlign: hoverLabelIdealAlign,
          hovertemplate: trace.hovertemplate,
          hovertemplateLabels: labels,
          eventData: [{
            data: trace._input,
            fullData: trace,
            count,
            category: catLabel,
            probability: prob
          }]
        };
      }
      function createHoverLabelForDimensionHovermode(gd, rootBBox, bandElement) {
        var allHoverlabels = [];
        d3.select(bandElement.parentNode.parentNode).selectAll("g.category").select("rect.catrect").each(function() {
          var bandNode = this;
          allHoverlabels.push(createHoverLabelForCategoryHovermode(gd, rootBBox, bandNode));
        });
        return allHoverlabels;
      }
      function createHoverLabelForColorHovermode(gd, rootBBox, bandElement) {
        gd._fullLayout._calcInverseTransform(gd);
        var scaleX = gd._fullLayout._invScaleX;
        var scaleY = gd._fullLayout._invScaleY;
        var bandBoundingBox = bandElement.getBoundingClientRect();
        var bandViewModel = d3.select(bandElement).datum();
        var catViewModel = bandViewModel.categoryViewModel;
        var parcatsViewModel = catViewModel.parcatsViewModel;
        var dimensionModel = parcatsViewModel.model.dimensions[catViewModel.model.dimensionInd];
        var trace = parcatsViewModel.trace;
        var hoverCenterY = bandBoundingBox.y + bandBoundingBox.height / 2;
        var hoverCenterX, hoverLabelIdealAlign;
        if (parcatsViewModel.dimensions.length > 1 && dimensionModel.displayInd === parcatsViewModel.dimensions.length - 1) {
          hoverCenterX = bandBoundingBox.left;
          hoverLabelIdealAlign = "left";
        } else {
          hoverCenterX = bandBoundingBox.left + bandBoundingBox.width;
          hoverLabelIdealAlign = "right";
        }
        var catLabel = catViewModel.model.categoryLabel;
        var totalCount = bandViewModel.parcatsViewModel.model.count;
        var bandColorCount = 0;
        bandViewModel.categoryViewModel.bands.forEach(function(b) {
          if (b.color === bandViewModel.color) {
            bandColorCount += b.count;
          }
        });
        var catCount = catViewModel.model.count;
        var colorCount = 0;
        parcatsViewModel.pathSelection.each(
          /** @param {PathViewModel} pathViewModel */
          function(pathViewModel) {
            if (pathViewModel.model.color === bandViewModel.color) {
              colorCount += pathViewModel.model.count;
            }
          }
        );
        var pColorAndCat = bandColorCount / totalCount;
        var pCatGivenColor = bandColorCount / colorCount;
        var pColorGivenCat = bandColorCount / catCount;
        var labels = {
          countLabel: bandColorCount,
          categoryLabel: catLabel,
          probabilityLabel: pColorAndCat.toFixed(3)
        };
        var hoverinfoParts = [];
        if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf("count") !== -1) {
          hoverinfoParts.push(["Count:", labels.countLabel].join(" "));
        }
        if (catViewModel.parcatsViewModel.hoverinfoItems.indexOf("probability") !== -1) {
          hoverinfoParts.push("P(color \u2229 " + catLabel + "): " + labels.probabilityLabel);
          hoverinfoParts.push("P(" + catLabel + " | color): " + pCatGivenColor.toFixed(3));
          hoverinfoParts.push("P(color | " + catLabel + "): " + pColorGivenCat.toFixed(3));
        }
        var hovertext = hoverinfoParts.join("<br>");
        var textColor = tinycolor.mostReadable(bandViewModel.color, ["black", "white"]);
        return {
          trace,
          x: scaleX * (hoverCenterX - rootBBox.left),
          y: scaleY * (hoverCenterY - rootBBox.top),
          // name: 'NAME',
          text: hovertext,
          color: bandViewModel.color,
          borderColor: "black",
          fontFamily: 'Monaco, "Courier New", monospace',
          fontColor: textColor,
          fontSize: 10,
          idealAlign: hoverLabelIdealAlign,
          hovertemplate: trace.hovertemplate,
          hovertemplateLabels: labels,
          eventData: [{
            data: trace._input,
            fullData: trace,
            category: catLabel,
            count: totalCount,
            probability: pColorAndCat,
            categorycount: catCount,
            colorcount: colorCount,
            bandcolorcount: bandColorCount
          }]
        };
      }
      function mouseoverCategoryBand(bandViewModel) {
        if (!bandViewModel.parcatsViewModel.dragDimension) {
          if (bandViewModel.parcatsViewModel.hoverinfoItems.indexOf("skip") === -1) {
            var mouseY = d3.mouse(this)[1];
            if (mouseY < -1) {
              return;
            }
            var gd = bandViewModel.parcatsViewModel.graphDiv;
            var fullLayout = gd._fullLayout;
            var rootBBox = fullLayout._paperdiv.node().getBoundingClientRect();
            var hoveron = bandViewModel.parcatsViewModel.hoveron;
            var bandElement = this;
            if (hoveron === "color") {
              styleForColorHovermode(bandElement);
              emitPointsEventColorHovermode(bandElement, "plotly_hover", d3.event);
            } else {
              styleForCategoryHovermode(bandElement);
              emitPointsEventCategoryHovermode(bandElement, "plotly_hover", d3.event);
            }
            if (bandViewModel.parcatsViewModel.hoverinfoItems.indexOf("none") === -1) {
              var hoverItems;
              if (hoveron === "category") {
                hoverItems = createHoverLabelForCategoryHovermode(gd, rootBBox, bandElement);
              } else if (hoveron === "color") {
                hoverItems = createHoverLabelForColorHovermode(gd, rootBBox, bandElement);
              } else if (hoveron === "dimension") {
                hoverItems = createHoverLabelForDimensionHovermode(gd, rootBBox, bandElement);
              }
              if (hoverItems) {
                Fx.loneHover(hoverItems, {
                  container: fullLayout._hoverlayer.node(),
                  outerContainer: fullLayout._paper.node(),
                  gd
                });
              }
            }
          }
        }
      }
      function mouseoutCategory(bandViewModel) {
        var parcatsViewModel = bandViewModel.parcatsViewModel;
        if (!parcatsViewModel.dragDimension) {
          stylePathsNoHover(parcatsViewModel.pathSelection);
          styleCategoriesNoHover(parcatsViewModel.dimensionSelection.selectAll("g.category"));
          styleBandsNoHover(parcatsViewModel.dimensionSelection.selectAll("g.category").selectAll("rect.bandrect"));
          Fx.loneUnhover(parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
          parcatsViewModel.pathSelection.sort(compareRawColor);
          if (parcatsViewModel.hoverinfoItems.indexOf("skip") === -1) {
            var hoveron = bandViewModel.parcatsViewModel.hoveron;
            var bandElement = this;
            if (hoveron === "color") {
              emitPointsEventColorHovermode(bandElement, "plotly_unhover", d3.event);
            } else {
              emitPointsEventCategoryHovermode(bandElement, "plotly_unhover", d3.event);
            }
          }
        }
      }
      function dragDimensionStart(d) {
        if (d.parcatsViewModel.arrangement === "fixed") {
          return;
        }
        d.dragDimensionDisplayInd = d.model.displayInd;
        d.initialDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function(d2) {
          return d2.displayInd;
        });
        d.dragHasMoved = false;
        d.dragCategoryDisplayInd = null;
        d3.select(this).selectAll("g.category").select("rect.catrect").each(
          /** @param {CategoryViewModel} catViewModel */
          function(catViewModel) {
            var catMouseX = d3.mouse(this)[0];
            var catMouseY = d3.mouse(this)[1];
            if (-2 <= catMouseX && catMouseX <= catViewModel.width + 2 && -2 <= catMouseY && catMouseY <= catViewModel.height + 2) {
              d.dragCategoryDisplayInd = catViewModel.model.displayInd;
              d.initialDragCategoryDisplayInds = d.model.categories.map(function(c) {
                return c.displayInd;
              });
              catViewModel.model.dragY = catViewModel.y;
              Lib.raiseToTop(this.parentNode);
              d3.select(this.parentNode).selectAll("rect.bandrect").each(function(bandViewModel) {
                if (bandViewModel.y < catMouseY && catMouseY <= bandViewModel.y + bandViewModel.height) {
                  d.potentialClickBand = this;
                }
              });
            }
          }
        );
        d.parcatsViewModel.dragDimension = d;
        Fx.loneUnhover(d.parcatsViewModel.graphDiv._fullLayout._hoverlayer.node());
      }
      function dragDimension(d) {
        if (d.parcatsViewModel.arrangement === "fixed") {
          return;
        }
        d.dragHasMoved = true;
        if (d.dragDimensionDisplayInd === null) {
          return;
        }
        var dragDimInd = d.dragDimensionDisplayInd;
        var prevDimInd = dragDimInd - 1;
        var nextDimInd = dragDimInd + 1;
        var dragDimension2 = d.parcatsViewModel.dimensions[dragDimInd];
        if (d.dragCategoryDisplayInd !== null) {
          var dragCategory = dragDimension2.categories[d.dragCategoryDisplayInd];
          dragCategory.model.dragY += d3.event.dy;
          var categoryY = dragCategory.model.dragY;
          var catDisplayInd = dragCategory.model.displayInd;
          var dimCategoryViews = dragDimension2.categories;
          var catAbove = dimCategoryViews[catDisplayInd - 1];
          var catBelow = dimCategoryViews[catDisplayInd + 1];
          if (catAbove !== void 0) {
            if (categoryY < catAbove.y + catAbove.height / 2) {
              dragCategory.model.displayInd = catAbove.model.displayInd;
              catAbove.model.displayInd = catDisplayInd;
            }
          }
          if (catBelow !== void 0) {
            if (categoryY + dragCategory.height > catBelow.y + catBelow.height / 2) {
              dragCategory.model.displayInd = catBelow.model.displayInd;
              catBelow.model.displayInd = catDisplayInd;
            }
          }
          d.dragCategoryDisplayInd = dragCategory.model.displayInd;
        }
        if (d.dragCategoryDisplayInd === null || d.parcatsViewModel.arrangement === "freeform") {
          dragDimension2.model.dragX = d3.event.x;
          var prevDimension = d.parcatsViewModel.dimensions[prevDimInd];
          var nextDimension = d.parcatsViewModel.dimensions[nextDimInd];
          if (prevDimension !== void 0) {
            if (dragDimension2.model.dragX < prevDimension.x + prevDimension.width) {
              dragDimension2.model.displayInd = prevDimension.model.displayInd;
              prevDimension.model.displayInd = dragDimInd;
            }
          }
          if (nextDimension !== void 0) {
            if (dragDimension2.model.dragX + dragDimension2.width > nextDimension.x) {
              dragDimension2.model.displayInd = nextDimension.model.displayInd;
              nextDimension.model.displayInd = d.dragDimensionDisplayInd;
            }
          }
          d.dragDimensionDisplayInd = dragDimension2.model.displayInd;
        }
        updateDimensionViewModels(d.parcatsViewModel);
        updatePathViewModels(d.parcatsViewModel);
        updateSvgCategories(d.parcatsViewModel);
        updateSvgPaths(d.parcatsViewModel);
      }
      function dragDimensionEnd(d) {
        if (d.parcatsViewModel.arrangement === "fixed") {
          return;
        }
        if (d.dragDimensionDisplayInd === null) {
          return;
        }
        d3.select(this).selectAll("text").attr("font-weight", "normal");
        var restyleData = {};
        var traceInd = getTraceIndex(d.parcatsViewModel);
        var finalDragDimensionDisplayInds = d.parcatsViewModel.model.dimensions.map(function(d2) {
          return d2.displayInd;
        });
        var anyDimsReordered = d.initialDragDimensionDisplayInds.some(function(initDimDisplay, dimInd) {
          return initDimDisplay !== finalDragDimensionDisplayInds[dimInd];
        });
        if (anyDimsReordered) {
          finalDragDimensionDisplayInds.forEach(function(finalDimDisplay, dimInd) {
            var containerInd = d.parcatsViewModel.model.dimensions[dimInd].containerInd;
            restyleData["dimensions[" + containerInd + "].displayindex"] = finalDimDisplay;
          });
        }
        var anyCatsReordered = false;
        if (d.dragCategoryDisplayInd !== null) {
          var finalDragCategoryDisplayInds = d.model.categories.map(function(c) {
            return c.displayInd;
          });
          anyCatsReordered = d.initialDragCategoryDisplayInds.some(function(initCatDisplay, catInd) {
            return initCatDisplay !== finalDragCategoryDisplayInds[catInd];
          });
          if (anyCatsReordered) {
            var sortedCategoryModels = d.model.categories.slice().sort(
              function(a, b) {
                return a.displayInd - b.displayInd;
              }
            );
            var newCategoryArray = sortedCategoryModels.map(function(v) {
              return v.categoryValue;
            });
            var newCategoryLabels = sortedCategoryModels.map(function(v) {
              return v.categoryLabel;
            });
            restyleData["dimensions[" + d.model.containerInd + "].categoryarray"] = [newCategoryArray];
            restyleData["dimensions[" + d.model.containerInd + "].ticktext"] = [newCategoryLabels];
            restyleData["dimensions[" + d.model.containerInd + "].categoryorder"] = "array";
          }
        }
        if (d.parcatsViewModel.hoverinfoItems.indexOf("skip") === -1) {
          if (!d.dragHasMoved && d.potentialClickBand) {
            if (d.parcatsViewModel.hoveron === "color") {
              emitPointsEventColorHovermode(d.potentialClickBand, "plotly_click", d3.event.sourceEvent);
            } else {
              emitPointsEventCategoryHovermode(d.potentialClickBand, "plotly_click", d3.event.sourceEvent);
            }
          }
        }
        d.model.dragX = null;
        if (d.dragCategoryDisplayInd !== null) {
          var dragCategory = d.parcatsViewModel.dimensions[d.dragDimensionDisplayInd].categories[d.dragCategoryDisplayInd];
          dragCategory.model.dragY = null;
          d.dragCategoryDisplayInd = null;
        }
        d.dragDimensionDisplayInd = null;
        d.parcatsViewModel.dragDimension = null;
        d.dragHasMoved = null;
        d.potentialClickBand = null;
        updateDimensionViewModels(d.parcatsViewModel);
        updatePathViewModels(d.parcatsViewModel);
        var transition = d3.transition().duration(300).ease("cubic-in-out");
        transition.each(function() {
          updateSvgCategories(d.parcatsViewModel, true);
          updateSvgPaths(d.parcatsViewModel, true);
        }).each("end", function() {
          if (anyDimsReordered || anyCatsReordered) {
            Plotly.restyle(d.parcatsViewModel.graphDiv, restyleData, [traceInd]);
          }
        });
      }
      function getTraceIndex(parcatsViewModel) {
        var traceInd;
        var allTraces = parcatsViewModel.graphDiv._fullData;
        for (var i = 0; i < allTraces.length; i++) {
          if (parcatsViewModel.key === allTraces[i].uid) {
            traceInd = i;
            break;
          }
        }
        return traceInd;
      }
      function updateSvgPaths(parcatsViewModel, hasTransition) {
        if (hasTransition === void 0) {
          hasTransition = false;
        }
        function transition(selection) {
          return hasTransition ? selection.transition() : selection;
        }
        parcatsViewModel.pathSelection.data(function(d) {
          return d.paths;
        }, key);
        transition(parcatsViewModel.pathSelection).attr("d", function(d) {
          return d.svgD;
        });
      }
      function updateSvgCategories(parcatsViewModel, hasTransition) {
        if (hasTransition === void 0) {
          hasTransition = false;
        }
        function transition(selection) {
          return hasTransition ? selection.transition() : selection;
        }
        parcatsViewModel.dimensionSelection.data(function(d) {
          return d.dimensions;
        }, key);
        var categorySelection = parcatsViewModel.dimensionSelection.selectAll("g.category").data(function(d) {
          return d.categories;
        }, key);
        transition(parcatsViewModel.dimensionSelection).attr("transform", function(d) {
          return strTranslate(d.x, 0);
        });
        transition(categorySelection).attr("transform", function(d) {
          return strTranslate(0, d.y);
        });
        var dimLabelSelection = categorySelection.select(".dimlabel");
        dimLabelSelection.text(function(d, i) {
          if (i === 0) {
            return d.parcatsViewModel.model.dimensions[d.model.dimensionInd].dimensionLabel;
          } else {
            return null;
          }
        });
        var catLabelSelection = categorySelection.select(".catlabel");
        catLabelSelection.attr(
          "text-anchor",
          function(d) {
            if (catInRightDim(d)) {
              return "start";
            } else {
              return "end";
            }
          }
        ).attr(
          "x",
          function(d) {
            if (catInRightDim(d)) {
              return d.width + 5;
            } else {
              return -5;
            }
          }
        ).each(function(d) {
          var newX;
          var newAnchor;
          if (catInRightDim(d)) {
            newX = d.width + 5;
            newAnchor = "start";
          } else {
            newX = -5;
            newAnchor = "end";
          }
          d3.select(this).selectAll("tspan").attr("x", newX).attr("text-anchor", newAnchor);
        });
        var bandSelection = categorySelection.selectAll("rect.bandrect").data(
          /** @param {CategoryViewModel} catViewModel*/
          function(catViewModel) {
            return catViewModel.bands;
          },
          key
        );
        var bandsSelectionEnter = bandSelection.enter().append("rect").attr("class", "bandrect").attr("cursor", "move").attr("stroke-opacity", 0).attr("fill", function(d) {
          return d.color;
        }).attr("fill-opacity", 0);
        bandSelection.attr("fill", function(d) {
          return d.color;
        }).attr("width", function(d) {
          return d.width;
        }).attr("height", function(d) {
          return d.height;
        }).attr("y", function(d) {
          return d.y;
        });
        styleBandsNoHover(bandsSelectionEnter);
        bandSelection.each(function() {
          Lib.raiseToTop(this);
        });
        bandSelection.exit().remove();
      }
      function createParcatsViewModel(graphDiv, layout, wrappedParcatsModel) {
        var parcatsModel = wrappedParcatsModel[0];
        var margin = layout.margin || { l: 80, r: 80, t: 100, b: 80 };
        var trace = parcatsModel.trace;
        var domain = trace.domain;
        var figureWidth = layout.width;
        var figureHeight = layout.height;
        var traceWidth = Math.floor(figureWidth * (domain.x[1] - domain.x[0]));
        var traceHeight = Math.floor(figureHeight * (domain.y[1] - domain.y[0]));
        var traceX = domain.x[0] * figureWidth + margin.l;
        var traceY = layout.height - domain.y[1] * layout.height + margin.t;
        var pathShape = trace.line.shape;
        var hoverinfoItems;
        if (trace.hoverinfo === "all") {
          hoverinfoItems = ["count", "probability"];
        } else {
          hoverinfoItems = (trace.hoverinfo || "").split("+");
        }
        var parcatsViewModel = {
          trace,
          key: trace.uid,
          model: parcatsModel,
          x: traceX,
          y: traceY,
          width: traceWidth,
          height: traceHeight,
          hoveron: trace.hoveron,
          hoverinfoItems,
          arrangement: trace.arrangement,
          bundlecolors: trace.bundlecolors,
          sortpaths: trace.sortpaths,
          labelfont: trace.labelfont,
          categorylabelfont: trace.tickfont,
          pathShape,
          dragDimension: null,
          margin,
          paths: [],
          dimensions: [],
          graphDiv,
          traceSelection: null,
          pathSelection: null,
          dimensionSelection: null
        };
        if (parcatsModel.dimensions) {
          updateDimensionViewModels(parcatsViewModel);
          updatePathViewModels(parcatsViewModel);
        }
        return parcatsViewModel;
      }
      function buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, curvature) {
        var xRefPoints1 = [];
        var xRefPoints2 = [];
        var refInterpolator;
        var d;
        for (d = 0; d < dimWidths.length - 1; d++) {
          refInterpolator = interpolateNumber(dimWidths[d] + leftXPositions[d], leftXPositions[d + 1]);
          xRefPoints1.push(refInterpolator(curvature));
          xRefPoints2.push(refInterpolator(1 - curvature));
        }
        var svgD = "M " + leftXPositions[0] + "," + pathYs[0];
        svgD += "l" + dimWidths[0] + ",0 ";
        for (d = 1; d < dimWidths.length; d++) {
          svgD += "C" + xRefPoints1[d - 1] + "," + pathYs[d - 1] + " " + xRefPoints2[d - 1] + "," + pathYs[d] + " " + leftXPositions[d] + "," + pathYs[d];
          svgD += "l" + dimWidths[d] + ",0 ";
        }
        svgD += "l0," + pathHeight + " ";
        svgD += "l -" + dimWidths[dimWidths.length - 1] + ",0 ";
        for (d = dimWidths.length - 2; d >= 0; d--) {
          svgD += "C" + xRefPoints2[d] + "," + (pathYs[d + 1] + pathHeight) + " " + xRefPoints1[d] + "," + (pathYs[d] + pathHeight) + " " + (leftXPositions[d] + dimWidths[d]) + "," + (pathYs[d] + pathHeight);
          svgD += "l-" + dimWidths[d] + ",0 ";
        }
        svgD += "Z";
        return svgD;
      }
      function updatePathViewModels(parcatsViewModel) {
        var dimensionViewModels = parcatsViewModel.dimensions;
        var parcatsModel = parcatsViewModel.model;
        var nextYPositions = dimensionViewModels.map(
          function(d2) {
            return d2.categories.map(
              function(c) {
                return c.y;
              }
            );
          }
        );
        var catToDisplayIndPerDim = parcatsViewModel.model.dimensions.map(
          function(d2) {
            return d2.categories.map(function(c) {
              return c.displayInd;
            });
          }
        );
        var dimToDisplayInd = parcatsViewModel.model.dimensions.map(function(d2) {
          return d2.displayInd;
        });
        var displayToDimInd = parcatsViewModel.dimensions.map(function(d2) {
          return d2.model.dimensionInd;
        });
        var leftXPositions = dimensionViewModels.map(
          function(d2) {
            return d2.x;
          }
        );
        var dimWidths = dimensionViewModels.map(function(d2) {
          return d2.width;
        });
        var pathModels = [];
        for (var p in parcatsModel.paths) {
          if (parcatsModel.paths.hasOwnProperty(p)) {
            pathModels.push(parcatsModel.paths[p]);
          }
        }
        function pathDisplayCategoryInds(pathModel2) {
          var dimensionInds = pathModel2.categoryInds.map(function(catInd2, dimInd) {
            return catToDisplayIndPerDim[dimInd][catInd2];
          });
          var displayInds = displayToDimInd.map(function(dimInd) {
            return dimensionInds[dimInd];
          });
          return displayInds;
        }
        pathModels.sort(function(v1, v2) {
          var sortArray1 = pathDisplayCategoryInds(v1);
          var sortArray2 = pathDisplayCategoryInds(v2);
          if (parcatsViewModel.sortpaths === "backward") {
            sortArray1.reverse();
            sortArray2.reverse();
          }
          sortArray1.push(v1.valueInds[0]);
          sortArray2.push(v2.valueInds[0]);
          if (parcatsViewModel.bundlecolors) {
            sortArray1.unshift(v1.rawColor);
            sortArray2.unshift(v2.rawColor);
          }
          if (sortArray1 < sortArray2) {
            return -1;
          }
          if (sortArray1 > sortArray2) {
            return 1;
          }
          return 0;
        });
        var pathViewModels = new Array(pathModels.length);
        var totalCount = dimensionViewModels[0].model.count;
        var totalHeight = dimensionViewModels[0].categories.map(function(c) {
          return c.height;
        }).reduce(function(v1, v2) {
          return v1 + v2;
        });
        for (var pathNumber = 0; pathNumber < pathModels.length; pathNumber++) {
          var pathModel = pathModels[pathNumber];
          var pathHeight;
          if (totalCount > 0) {
            pathHeight = totalHeight * (pathModel.count / totalCount);
          } else {
            pathHeight = 0;
          }
          var pathYs = new Array(nextYPositions.length);
          for (var d = 0; d < pathModel.categoryInds.length; d++) {
            var catInd = pathModel.categoryInds[d];
            var catDisplayInd = catToDisplayIndPerDim[d][catInd];
            var dimDisplayInd = dimToDisplayInd[d];
            pathYs[dimDisplayInd] = nextYPositions[dimDisplayInd][catDisplayInd];
            nextYPositions[dimDisplayInd][catDisplayInd] += pathHeight;
            var catViewModle = parcatsViewModel.dimensions[dimDisplayInd].categories[catDisplayInd];
            var numBands = catViewModle.bands.length;
            var lastCatBand = catViewModle.bands[numBands - 1];
            if (lastCatBand === void 0 || pathModel.rawColor !== lastCatBand.rawColor) {
              var bandY = lastCatBand === void 0 ? 0 : lastCatBand.y + lastCatBand.height;
              catViewModle.bands.push({
                key: bandY,
                color: pathModel.color,
                rawColor: pathModel.rawColor,
                height: pathHeight,
                width: catViewModle.width,
                count: pathModel.count,
                y: bandY,
                categoryViewModel: catViewModle,
                parcatsViewModel
              });
            } else {
              var currentBand = catViewModle.bands[numBands - 1];
              currentBand.height += pathHeight;
              currentBand.count += pathModel.count;
            }
          }
          var svgD;
          if (parcatsViewModel.pathShape === "hspline") {
            svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0.5);
          } else {
            svgD = buildSvgPath(leftXPositions, pathYs, dimWidths, pathHeight, 0);
          }
          pathViewModels[pathNumber] = {
            key: pathModel.valueInds[0],
            model: pathModel,
            height: pathHeight,
            leftXs: leftXPositions,
            topYs: pathYs,
            dimWidths,
            svgD,
            parcatsViewModel
          };
        }
        parcatsViewModel.paths = pathViewModels;
      }
      function updateDimensionViewModels(parcatsViewModel) {
        var dimensionsIndInfo = parcatsViewModel.model.dimensions.map(function(d) {
          return { displayInd: d.displayInd, dimensionInd: d.dimensionInd };
        });
        dimensionsIndInfo.sort(function(a, b) {
          return a.displayInd - b.displayInd;
        });
        var dimensions = [];
        for (var displayInd in dimensionsIndInfo) {
          var dimensionInd = dimensionsIndInfo[displayInd].dimensionInd;
          var dimModel = parcatsViewModel.model.dimensions[dimensionInd];
          dimensions.push(createDimensionViewModel(parcatsViewModel, dimModel));
        }
        parcatsViewModel.dimensions = dimensions;
      }
      function createDimensionViewModel(parcatsViewModel, dimensionModel) {
        var categoryLabelPad = 40;
        var dimWidth = 16;
        var numDimensions = parcatsViewModel.model.dimensions.length;
        var displayInd = dimensionModel.displayInd;
        var dimDx;
        var dimX0;
        var dimX;
        if (numDimensions > 1) {
          dimDx = (parcatsViewModel.width - 2 * categoryLabelPad - dimWidth) / (numDimensions - 1);
        } else {
          dimDx = 0;
        }
        dimX0 = categoryLabelPad;
        dimX = dimX0 + dimDx * displayInd;
        var categories = [];
        var maxCats = parcatsViewModel.model.maxCats;
        var numCats = dimensionModel.categories.length;
        var catSpacing = 8;
        var totalCount = dimensionModel.count;
        var totalHeight = parcatsViewModel.height - catSpacing * (maxCats - 1);
        var nextCatHeight;
        var nextCatModel;
        var nextCat;
        var catInd;
        var catDisplayInd;
        var nextCatY = (maxCats - numCats) * catSpacing / 2;
        var categoryIndInfo = dimensionModel.categories.map(function(c) {
          return { displayInd: c.displayInd, categoryInd: c.categoryInd };
        });
        categoryIndInfo.sort(function(a, b) {
          return a.displayInd - b.displayInd;
        });
        for (catDisplayInd = 0; catDisplayInd < numCats; catDisplayInd++) {
          catInd = categoryIndInfo[catDisplayInd].categoryInd;
          nextCatModel = dimensionModel.categories[catInd];
          if (totalCount > 0) {
            nextCatHeight = nextCatModel.count / totalCount * totalHeight;
          } else {
            nextCatHeight = 0;
          }
          nextCat = {
            key: nextCatModel.valueInds[0],
            model: nextCatModel,
            width: dimWidth,
            height: nextCatHeight,
            y: nextCatModel.dragY !== null ? nextCatModel.dragY : nextCatY,
            bands: [],
            parcatsViewModel
          };
          nextCatY = nextCatY + nextCatHeight + catSpacing;
          categories.push(nextCat);
        }
        return {
          key: dimensionModel.dimensionInd,
          x: dimensionModel.dragX !== null ? dimensionModel.dragX : dimX,
          y: 0,
          width: dimWidth,
          model: dimensionModel,
          categories,
          parcatsViewModel,
          dragCategoryDisplayInd: null,
          dragDimensionDisplayInd: null,
          initialDragDimensionDisplayInds: null,
          initialDragCategoryDisplayInds: null,
          dragHasMoved: null,
          potentialClickBand: null
        };
      }
    }
  });

  // src/traces/parcats/plot.js
  var require_plot22 = __commonJS({
    "src/traces/parcats/plot.js"(exports, module) {
      "use strict";
      var parcats = require_parcats();
      module.exports = function plot(graphDiv, parcatsModels, transitionOpts, makeOnCompleteCallback) {
        var fullLayout = graphDiv._fullLayout;
        var svg = fullLayout._paper;
        var size = fullLayout._size;
        parcats(
          graphDiv,
          svg,
          parcatsModels,
          {
            width: size.w,
            height: size.h,
            margin: {
              t: size.t,
              r: size.r,
              b: size.b,
              l: size.l
            }
          },
          transitionOpts,
          makeOnCompleteCallback
        );
      };
    }
  });

  // src/traces/parcats/base_plot.js
  var require_base_plot8 = __commonJS({
    "src/traces/parcats/base_plot.js"(exports) {
      "use strict";
      var getModuleCalcData = require_get_data().getModuleCalcData;
      var parcatsPlot = require_plot22();
      var PARCATS = "parcats";
      exports.name = PARCATS;
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        var cdModuleAndOthers = getModuleCalcData(gd.calcdata, PARCATS);
        if (cdModuleAndOthers.length) {
          var calcData = cdModuleAndOthers[0];
          parcatsPlot(gd, calcData, transitionOpts, makeOnCompleteCallback);
        }
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var hadTable = oldFullLayout._has && oldFullLayout._has("parcats");
        var hasTable = newFullLayout._has && newFullLayout._has("parcats");
        if (hadTable && !hasTable) {
          oldFullLayout._paperdiv.selectAll(".parcats").remove();
        }
      };
    }
  });

  // src/traces/parcats/index.js
  var require_parcats2 = __commonJS({
    "src/traces/parcats/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes53(),
        supplyDefaults: require_defaults49(),
        calc: require_calc32(),
        plot: require_plot22(),
        colorbar: {
          container: "line",
          min: "cmin",
          max: "cmax"
        },
        moduleType: "trace",
        name: "parcats",
        basePlotModule: require_base_plot8(),
        categories: ["noOpacity"],
        meta: {}
      };
    }
  });

  // lib/parcats.js
  var require_parcats3 = __commonJS({
    "lib/parcats.js"(exports, module) {
      "use strict";
      module.exports = require_parcats2();
    }
  });

  // src/plots/mapbox/constants.js
  var require_constants25 = __commonJS({
    "src/plots/mapbox/constants.js"(exports, module) {
      "use strict";
      var sortObjectKeys = require_sort_object_keys();
      var requiredVersion = "1.13.4";
      var OSM = '\xA9 <a target="_blank" href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
      var carto = [
        '\xA9 <a target="_blank" href="https://carto.com/">Carto</a>',
        OSM
      ].join(" ");
      var stamenTerrainOrToner = [
        'Map tiles by <a target="_blank" href="https://stamen.com">Stamen Design</a>',
        'under <a target="_blank" href="https://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>',
        "|",
        'Data by <a target="_blank" href="https://openstreetmap.org">OpenStreetMap</a> contributors',
        'under <a target="_blank" href="https://www.openstreetmap.org/copyright">ODbL</a>'
      ].join(" ");
      var stamenWaterColor = [
        'Map tiles by <a target="_blank" href="https://stamen.com">Stamen Design</a>',
        'under <a target="_blank" href="https://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>',
        "|",
        'Data by <a target="_blank" href="https://openstreetmap.org">OpenStreetMap</a> contributors',
        'under <a target="_blank" href="https://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>'
      ].join(" ");
      var stylesNonMapbox = {
        "open-street-map": {
          id: "osm",
          version: 8,
          sources: {
            "plotly-osm-tiles": {
              type: "raster",
              attribution: OSM,
              tiles: [
                "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png",
                "https://b.tile.openstreetmap.org/{z}/{x}/{y}.png"
              ],
              tileSize: 256
            }
          },
          layers: [{
            id: "plotly-osm-tiles",
            type: "raster",
            source: "plotly-osm-tiles",
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "white-bg": {
          id: "white-bg",
          version: 8,
          sources: {},
          layers: [{
            id: "white-bg",
            type: "background",
            paint: { "background-color": "#FFFFFF" },
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "carto-positron": {
          id: "carto-positron",
          version: 8,
          sources: {
            "plotly-carto-positron": {
              type: "raster",
              attribution: carto,
              tiles: ["https://cartodb-basemaps-c.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png"],
              tileSize: 256
            }
          },
          layers: [{
            id: "plotly-carto-positron",
            type: "raster",
            source: "plotly-carto-positron",
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "carto-darkmatter": {
          id: "carto-darkmatter",
          version: 8,
          sources: {
            "plotly-carto-darkmatter": {
              type: "raster",
              attribution: carto,
              tiles: ["https://cartodb-basemaps-c.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png"],
              tileSize: 256
            }
          },
          layers: [{
            id: "plotly-carto-darkmatter",
            type: "raster",
            source: "plotly-carto-darkmatter",
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "stamen-terrain": {
          id: "stamen-terrain",
          version: 8,
          sources: {
            "plotly-stamen-terrain": {
              type: "raster",
              attribution: stamenTerrainOrToner,
              tiles: ["https://tiles.stadiamaps.com/tiles/stamen_terrain/{z}/{x}/{y}.png?api_key="],
              tileSize: 256
            }
          },
          layers: [{
            id: "plotly-stamen-terrain",
            type: "raster",
            source: "plotly-stamen-terrain",
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "stamen-toner": {
          id: "stamen-toner",
          version: 8,
          sources: {
            "plotly-stamen-toner": {
              type: "raster",
              attribution: stamenTerrainOrToner,
              tiles: ["https://tiles.stadiamaps.com/tiles/stamen_toner/{z}/{x}/{y}.png?api_key="],
              tileSize: 256
            }
          },
          layers: [{
            id: "plotly-stamen-toner",
            type: "raster",
            source: "plotly-stamen-toner",
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "stamen-watercolor": {
          id: "stamen-watercolor",
          version: 8,
          sources: {
            "plotly-stamen-watercolor": {
              type: "raster",
              attribution: stamenWaterColor,
              tiles: ["https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg?api_key="],
              tileSize: 256
            }
          },
          layers: [{
            id: "plotly-stamen-watercolor",
            type: "raster",
            source: "plotly-stamen-watercolor",
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        }
      };
      var styleValuesNonMapbox = sortObjectKeys(stylesNonMapbox);
      module.exports = {
        requiredVersion,
        styleUrlPrefix: "mapbox://styles/mapbox/",
        styleUrlSuffix: "v9",
        styleValuesMapbox: ["basic", "streets", "outdoors", "light", "dark", "satellite", "satellite-streets"],
        styleValueDflt: "basic",
        stylesNonMapbox,
        styleValuesNonMapbox,
        traceLayerPrefix: "plotly-trace-layer-",
        layoutLayerPrefix: "plotly-layout-layer-",
        wrongVersionErrorMsg: [
          "Your custom plotly.js bundle is not using the correct mapbox-gl version",
          "Please install @plotly/mapbox-gl@" + requiredVersion + "."
        ].join("\n"),
        noAccessTokenErrorMsg: [
          "Missing Mapbox access token.",
          "Mapbox trace type require a Mapbox access token to be registered.",
          "For example:",
          "  Plotly.newPlot(gd, data, layout, { mapboxAccessToken: 'my-access-token' });",
          "More info here: https://www.mapbox.com/help/define-access-token/"
        ].join("\n"),
        missingStyleErrorMsg: [
          "No valid mapbox style found, please set `mapbox.style` to one of:",
          styleValuesNonMapbox.join(", "),
          "or register a Mapbox access token to use a Mapbox-served style."
        ].join("\n"),
        multipleTokensErrorMsg: [
          "Set multiple mapbox access token across different mapbox subplot,",
          "using first token found as mapbox-gl does not allow multipleaccess tokens on the same page."
        ].join("\n"),
        mapOnErrorMsg: "Mapbox error.",
        // Mapbox logo for static export
        mapboxLogo: {
          path0: "m 10.5,1.24 c -5.11,0 -9.25,4.15 -9.25,9.25 0,5.1 4.15,9.25 9.25,9.25 5.1,0 9.25,-4.15 9.25,-9.25 0,-5.11 -4.14,-9.25 -9.25,-9.25 z m 4.39,11.53 c -1.93,1.93 -4.78,2.31 -6.7,2.31 -0.7,0 -1.41,-0.05 -2.1,-0.16 0,0 -1.02,-5.64 2.14,-8.81 0.83,-0.83 1.95,-1.28 3.13,-1.28 1.27,0 2.49,0.51 3.39,1.42 1.84,1.84 1.89,4.75 0.14,6.52 z",
          path1: "M 10.5,-0.01 C 4.7,-0.01 0,4.7 0,10.49 c 0,5.79 4.7,10.5 10.5,10.5 5.8,0 10.5,-4.7 10.5,-10.5 C 20.99,4.7 16.3,-0.01 10.5,-0.01 Z m 0,19.75 c -5.11,0 -9.25,-4.15 -9.25,-9.25 0,-5.1 4.14,-9.26 9.25,-9.26 5.11,0 9.25,4.15 9.25,9.25 0,5.13 -4.14,9.26 -9.25,9.26 z",
          path2: "M 14.74,6.25 C 12.9,4.41 9.98,4.35 8.23,6.1 5.07,9.27 6.09,14.91 6.09,14.91 c 0,0 5.64,1.02 8.81,-2.14 C 16.64,11 16.59,8.09 14.74,6.25 Z m -2.27,4.09 -0.91,1.87 -0.9,-1.87 -1.86,-0.91 1.86,-0.9 0.9,-1.87 0.91,1.87 1.86,0.9 z",
          polygon: "11.56,12.21 10.66,10.34 8.8,9.43 10.66,8.53 11.56,6.66 12.47,8.53 14.33,9.43 12.47,10.34"
        },
        // a subset of node_modules/mapbox-gl/dist/mapbox-gl.css
        styleRules: {
          map: "overflow:hidden;position:relative;",
          "missing-css": "display:none;",
          canary: "background-color:salmon;",
          // Reusing CSS directives from: https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.css
          "ctrl-bottom-left": "position: absolute; pointer-events: none; z-index: 2; bottom: 0; left: 0;",
          "ctrl-bottom-right": "position: absolute; pointer-events: none; z-index: 2; right: 0; bottom: 0;",
          ctrl: "clear: both; pointer-events: auto; transform: translate(0, 0);",
          // Compact ctrl
          "ctrl-attrib.mapboxgl-compact .mapboxgl-ctrl-attrib-inner": "display: none;",
          "ctrl-attrib.mapboxgl-compact:hover .mapboxgl-ctrl-attrib-inner": "display: block; margin-top:2px",
          "ctrl-attrib.mapboxgl-compact:hover": "padding: 2px 24px 2px 4px; visibility: visible; margin-top: 6px;",
          "ctrl-attrib.mapboxgl-compact::after": `content: ""; cursor: pointer; position: absolute; background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"%3E %3Cpath fill="%23333333" fill-rule="evenodd" d="M4,10a6,6 0 1,0 12,0a6,6 0 1,0 -12,0 M9,7a1,1 0 1,0 2,0a1,1 0 1,0 -2,0 M9,10a1,1 0 1,1 2,0l0,3a1,1 0 1,1 -2,0"/%3E %3C/svg%3E'); background-color: rgba(255, 255, 255, 0.5); width: 24px; height: 24px; box-sizing: border-box; border-radius: 12px;`,
          "ctrl-attrib.mapboxgl-compact": "min-height: 20px; padding: 0; margin: 10px; position: relative; background-color: #fff; border-radius: 3px 12px 12px 3px;",
          "ctrl-bottom-right > .mapboxgl-ctrl-attrib.mapboxgl-compact::after": "bottom: 0; right: 0",
          "ctrl-bottom-left > .mapboxgl-ctrl-attrib.mapboxgl-compact::after": "bottom: 0; left: 0",
          "ctrl-bottom-left .mapboxgl-ctrl": "margin: 0 0 10px 10px; float: left;",
          "ctrl-bottom-right .mapboxgl-ctrl": "margin: 0 10px 10px 0; float: right;",
          "ctrl-attrib": "color: rgba(0, 0, 0, 0.75); text-decoration: none; font-size: 12px",
          "ctrl-attrib a": "color: rgba(0, 0, 0, 0.75); text-decoration: none; font-size: 12px",
          "ctrl-attrib a:hover": "color: inherit; text-decoration: underline;",
          "ctrl-attrib .mapbox-improve-map": "font-weight: bold; margin-left: 2px;",
          "attrib-empty": "display: none;",
          // Compact Mapbox logo without text
          "ctrl-logo": `display:block; width: 21px; height: 21px; background-image: url('data:image/svg+xml;charset=utf-8,%3C?xml version="1.0" encoding="utf-8"?%3E %3Csvg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 21 21" style="enable-background:new 0 0 21 21;" xml:space="preserve"%3E%3Cg transform="translate(0,0.01)"%3E%3Cpath d="m 10.5,1.24 c -5.11,0 -9.25,4.15 -9.25,9.25 0,5.1 4.15,9.25 9.25,9.25 5.1,0 9.25,-4.15 9.25,-9.25 0,-5.11 -4.14,-9.25 -9.25,-9.25 z m 4.39,11.53 c -1.93,1.93 -4.78,2.31 -6.7,2.31 -0.7,0 -1.41,-0.05 -2.1,-0.16 0,0 -1.02,-5.64 2.14,-8.81 0.83,-0.83 1.95,-1.28 3.13,-1.28 1.27,0 2.49,0.51 3.39,1.42 1.84,1.84 1.89,4.75 0.14,6.52 z" style="opacity:0.9;fill:%23ffffff;enable-background:new" class="st0"/%3E%3Cpath d="M 10.5,-0.01 C 4.7,-0.01 0,4.7 0,10.49 c 0,5.79 4.7,10.5 10.5,10.5 5.8,0 10.5,-4.7 10.5,-10.5 C 20.99,4.7 16.3,-0.01 10.5,-0.01 Z m 0,19.75 c -5.11,0 -9.25,-4.15 -9.25,-9.25 0,-5.1 4.14,-9.26 9.25,-9.26 5.11,0 9.25,4.15 9.25,9.25 0,5.13 -4.14,9.26 -9.25,9.26 z" style="opacity:0.35;enable-background:new" class="st1"/%3E%3Cpath d="M 14.74,6.25 C 12.9,4.41 9.98,4.35 8.23,6.1 5.07,9.27 6.09,14.91 6.09,14.91 c 0,0 5.64,1.02 8.81,-2.14 C 16.64,11 16.59,8.09 14.74,6.25 Z m -2.27,4.09 -0.91,1.87 -0.9,-1.87 -1.86,-0.91 1.86,-0.9 0.9,-1.87 0.91,1.87 1.86,0.9 z" style="opacity:0.35;enable-background:new" class="st1"/%3E%3Cpolygon points="11.56,12.21 10.66,10.34 8.8,9.43 10.66,8.53 11.56,6.66 12.47,8.53 14.33,9.43 12.47,10.34 " style="opacity:0.9;fill:%23ffffff;enable-background:new" class="st0"/%3E%3C/g%3E%3C/svg%3E')`
          // Mapbox logo WITH text below (commented out for now)
          // 'ctrl-logo': 'width: 85px; height: 21px; margin: 0 0 -3px -3px; display: block; background-repeat: no-repeat; cursor: pointer; background-image: url(\'data:image/svg+xml;charset=utf-8,%3C?xml version="1.0" encoding="utf-8"?%3E%3Csvg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 84.49 21" style="enable-background:new 0 0 84.49 21;" xml:space="preserve"%3E%3Cg%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M83.25,14.26c0,0.12-0.09,0.21-0.21,0.21h-1.61c-0.13,0-0.24-0.06-0.3-0.17l-1.44-2.39l-1.44,2.39 c-0.06,0.11-0.18,0.17-0.3,0.17h-1.61c-0.04,0-0.08-0.01-0.12-0.03c-0.09-0.06-0.13-0.19-0.06-0.28l0,0l2.43-3.68L76.2,6.84 c-0.02-0.03-0.03-0.07-0.03-0.12c0-0.12,0.09-0.21,0.21-0.21h1.61c0.13,0,0.24,0.06,0.3,0.17l1.41,2.36l1.4-2.35 c0.06-0.11,0.18-0.17,0.3-0.17H83c0.04,0,0.08,0.01,0.12,0.03c0.09,0.06,0.13,0.19,0.06,0.28l0,0l-2.37,3.63l2.43,3.67 C83.24,14.18,83.25,14.22,83.25,14.26z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M66.24,9.59c-0.39-1.88-1.96-3.28-3.84-3.28c-1.03,0-2.03,0.42-2.73,1.18V3.51c0-0.13-0.1-0.23-0.23-0.23h-1.4 c-0.13,0-0.23,0.11-0.23,0.23v10.72c0,0.13,0.1,0.23,0.23,0.23h1.4c0.13,0,0.23-0.11,0.23-0.23V13.5c0.71,0.75,1.7,1.18,2.73,1.18 c1.88,0,3.45-1.41,3.84-3.29C66.37,10.79,66.37,10.18,66.24,9.59L66.24,9.59z M62.08,13c-1.32,0-2.39-1.11-2.41-2.48v-0.06 c0.02-1.38,1.09-2.48,2.41-2.48s2.42,1.12,2.42,2.51S63.41,13,62.08,13z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M71.67,6.32c-1.98-0.01-3.72,1.35-4.16,3.29c-0.13,0.59-0.13,1.19,0,1.77c0.44,1.94,2.17,3.32,4.17,3.3 c2.35,0,4.26-1.87,4.26-4.19S74.04,6.32,71.67,6.32z M71.65,13.01c-1.33,0-2.42-1.12-2.42-2.51s1.08-2.52,2.42-2.52 c1.33,0,2.42,1.12,2.42,2.51S72.99,13,71.65,13.01L71.65,13.01z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M62.08,7.98c-1.32,0-2.39,1.11-2.41,2.48v0.06C59.68,11.9,60.75,13,62.08,13s2.42-1.12,2.42-2.51 S63.41,7.98,62.08,7.98z M62.08,11.76c-0.63,0-1.14-0.56-1.17-1.25v-0.04c0.01-0.69,0.54-1.25,1.17-1.25 c0.63,0,1.17,0.57,1.17,1.27C63.24,11.2,62.73,11.76,62.08,11.76z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M71.65,7.98c-1.33,0-2.42,1.12-2.42,2.51S70.32,13,71.65,13s2.42-1.12,2.42-2.51S72.99,7.98,71.65,7.98z M71.65,11.76c-0.64,0-1.17-0.57-1.17-1.27c0-0.7,0.53-1.26,1.17-1.26s1.17,0.57,1.17,1.27C72.82,11.21,72.29,11.76,71.65,11.76z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M45.74,6.53h-1.4c-0.13,0-0.23,0.11-0.23,0.23v0.73c-0.71-0.75-1.7-1.18-2.73-1.18 c-2.17,0-3.94,1.87-3.94,4.19s1.77,4.19,3.94,4.19c1.04,0,2.03-0.43,2.73-1.19v0.73c0,0.13,0.1,0.23,0.23,0.23h1.4 c0.13,0,0.23-0.11,0.23-0.23V6.74c0-0.12-0.09-0.22-0.22-0.22C45.75,6.53,45.75,6.53,45.74,6.53z M44.12,10.53 C44.11,11.9,43.03,13,41.71,13s-2.42-1.12-2.42-2.51s1.08-2.52,2.4-2.52c1.33,0,2.39,1.11,2.41,2.48L44.12,10.53z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M41.71,7.98c-1.33,0-2.42,1.12-2.42,2.51S40.37,13,41.71,13s2.39-1.11,2.41-2.48v-0.06 C44.1,9.09,43.03,7.98,41.71,7.98z M40.55,10.49c0-0.7,0.52-1.27,1.17-1.27c0.64,0,1.14,0.56,1.17,1.25v0.04 c-0.01,0.68-0.53,1.24-1.17,1.24C41.08,11.75,40.55,11.19,40.55,10.49z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M52.41,6.32c-1.03,0-2.03,0.42-2.73,1.18V6.75c0-0.13-0.1-0.23-0.23-0.23h-1.4c-0.13,0-0.23,0.11-0.23,0.23 v10.72c0,0.13,0.1,0.23,0.23,0.23h1.4c0.13,0,0.23-0.1,0.23-0.23V13.5c0.71,0.75,1.7,1.18,2.74,1.18c2.17,0,3.94-1.87,3.94-4.19 S54.58,6.32,52.41,6.32z M52.08,13.01c-1.32,0-2.39-1.11-2.42-2.48v-0.07c0.02-1.38,1.09-2.49,2.4-2.49c1.32,0,2.41,1.12,2.41,2.51 S53.4,13,52.08,13.01L52.08,13.01z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M52.08,7.98c-1.32,0-2.39,1.11-2.42,2.48v0.06c0.03,1.38,1.1,2.48,2.42,2.48s2.41-1.12,2.41-2.51 S53.4,7.98,52.08,7.98z M52.08,11.76c-0.63,0-1.14-0.56-1.17-1.25v-0.04c0.01-0.69,0.54-1.25,1.17-1.25c0.63,0,1.17,0.58,1.17,1.27 S52.72,11.76,52.08,11.76z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M36.08,14.24c0,0.13-0.1,0.23-0.23,0.23h-1.41c-0.13,0-0.23-0.11-0.23-0.23V9.68c0-0.98-0.74-1.71-1.62-1.71 c-0.8,0-1.46,0.7-1.59,1.62l0.01,4.66c0,0.13-0.11,0.23-0.23,0.23h-1.41c-0.13,0-0.23-0.11-0.23-0.23V9.68 c0-0.98-0.74-1.71-1.62-1.71c-0.85,0-1.54,0.79-1.6,1.8v4.48c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23V6.74 c0.01-0.13,0.1-0.22,0.23-0.22h1.4c0.13,0,0.22,0.11,0.23,0.22V7.4c0.5-0.68,1.3-1.09,2.16-1.1h0.03c1.09,0,2.09,0.6,2.6,1.55 c0.45-0.95,1.4-1.55,2.44-1.56c1.62,0,2.93,1.25,2.9,2.78L36.08,14.24z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M84.34,13.59l-0.07-0.13l-1.96-2.99l1.94-2.95c0.44-0.67,0.26-1.56-0.41-2.02c-0.02,0-0.03,0-0.04-0.01 c-0.23-0.15-0.5-0.22-0.78-0.22h-1.61c-0.56,0-1.08,0.29-1.37,0.78L79.72,6.6l-0.34-0.56C79.09,5.56,78.57,5.27,78,5.27h-1.6 c-0.6,0-1.13,0.37-1.35,0.92c-2.19-1.66-5.28-1.47-7.26,0.45c-0.35,0.34-0.65,0.72-0.89,1.14c-0.9-1.62-2.58-2.72-4.5-2.72 c-0.5,0-1.01,0.07-1.48,0.23V3.51c0-0.82-0.66-1.48-1.47-1.48h-1.4c-0.81,0-1.47,0.66-1.47,1.47v3.75 c-0.95-1.36-2.5-2.18-4.17-2.19c-0.74,0-1.46,0.16-2.12,0.47c-0.24-0.17-0.54-0.26-0.84-0.26h-1.4c-0.45,0-0.87,0.21-1.15,0.56 c-0.02-0.03-0.04-0.05-0.07-0.08c-0.28-0.3-0.68-0.47-1.09-0.47h-1.39c-0.3,0-0.6,0.09-0.84,0.26c-0.67-0.3-1.39-0.46-2.12-0.46 c-1.83,0-3.43,1-4.37,2.5c-0.2-0.46-0.48-0.89-0.83-1.25c-0.8-0.81-1.89-1.25-3.02-1.25h-0.01c-0.89,0.01-1.75,0.33-2.46,0.88 c-0.74-0.57-1.64-0.88-2.57-0.88H28.1c-0.29,0-0.58,0.03-0.86,0.11c-0.28,0.06-0.56,0.16-0.82,0.28c-0.21-0.12-0.45-0.18-0.7-0.18 h-1.4c-0.82,0-1.47,0.66-1.47,1.47v7.5c0,0.82,0.66,1.47,1.47,1.47h1.4c0.82,0,1.48-0.66,1.48-1.48l0,0V9.79 c0.03-0.36,0.23-0.59,0.36-0.59c0.18,0,0.38,0.18,0.38,0.47v4.57c0,0.82,0.66,1.47,1.47,1.47h1.41c0.82,0,1.47-0.66,1.47-1.47 l-0.01-4.57c0.06-0.32,0.25-0.47,0.35-0.47c0.18,0,0.38,0.18,0.38,0.47v4.57c0,0.82,0.66,1.47,1.47,1.47h1.41 c0.82,0,1.47-0.66,1.47-1.47v-0.38c0.96,1.29,2.46,2.06,4.06,2.06c0.74,0,1.46-0.16,2.12-0.47c0.24,0.17,0.54,0.26,0.84,0.26h1.39 c0.3,0,0.6-0.09,0.84-0.26v2.01c0,0.82,0.66,1.47,1.47,1.47h1.4c0.82,0,1.47-0.66,1.47-1.47v-1.77c0.48,0.15,0.99,0.23,1.49,0.22 c1.7,0,3.22-0.87,4.17-2.2v0.52c0,0.82,0.66,1.47,1.47,1.47h1.4c0.3,0,0.6-0.09,0.84-0.26c0.66,0.31,1.39,0.47,2.12,0.47 c1.92,0,3.6-1.1,4.49-2.73c1.54,2.65,4.95,3.53,7.58,1.98c0.18-0.11,0.36-0.22,0.53-0.36c0.22,0.55,0.76,0.91,1.35,0.9H78 c0.56,0,1.08-0.29,1.37-0.78l0.37-0.61l0.37,0.61c0.29,0.48,0.81,0.78,1.38,0.78h1.6c0.81,0,1.46-0.66,1.45-1.46 C84.49,14.02,84.44,13.8,84.34,13.59L84.34,13.59z M35.86,14.47h-1.41c-0.13,0-0.23-0.11-0.23-0.23V9.68 c0-0.98-0.74-1.71-1.62-1.71c-0.8,0-1.46,0.7-1.59,1.62l0.01,4.66c0,0.13-0.1,0.23-0.23,0.23h-1.41c-0.13,0-0.23-0.11-0.23-0.23 V9.68c0-0.98-0.74-1.71-1.62-1.71c-0.85,0-1.54,0.79-1.6,1.8v4.48c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23 V6.74c0.01-0.13,0.11-0.22,0.23-0.22h1.4c0.13,0,0.22,0.11,0.23,0.22V7.4c0.5-0.68,1.3-1.09,2.16-1.1h0.03 c1.09,0,2.09,0.6,2.6,1.55c0.45-0.95,1.4-1.55,2.44-1.56c1.62,0,2.93,1.25,2.9,2.78l0.01,5.16C36.09,14.36,35.98,14.46,35.86,14.47 L35.86,14.47z M45.97,14.24c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23V13.5c-0.7,0.76-1.69,1.18-2.72,1.18 c-2.17,0-3.94-1.87-3.94-4.19s1.77-4.19,3.94-4.19c1.03,0,2.02,0.43,2.73,1.18V6.74c0-0.13,0.1-0.23,0.23-0.23h1.4 c0.12-0.01,0.22,0.08,0.23,0.21c0,0.01,0,0.01,0,0.02v7.51h-0.01V14.24z M52.41,14.67c-1.03,0-2.02-0.43-2.73-1.18v3.97 c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.1-0.23-0.23V6.75c0-0.13,0.1-0.22,0.23-0.22h1.4c0.13,0,0.23,0.11,0.23,0.23v0.73 c0.71-0.76,1.7-1.18,2.73-1.18c2.17,0,3.94,1.86,3.94,4.18S54.58,14.67,52.41,14.67z M66.24,11.39c-0.39,1.87-1.96,3.29-3.84,3.29 c-1.03,0-2.02-0.43-2.73-1.18v0.73c0,0.13-0.1,0.23-0.23,0.23h-1.4c-0.13,0-0.23-0.11-0.23-0.23V3.51c0-0.13,0.1-0.23,0.23-0.23 h1.4c0.13,0,0.23,0.11,0.23,0.23v3.97c0.71-0.75,1.7-1.18,2.73-1.17c1.88,0,3.45,1.4,3.84,3.28C66.37,10.19,66.37,10.8,66.24,11.39 L66.24,11.39L66.24,11.39z M71.67,14.68c-2,0.01-3.73-1.35-4.17-3.3c-0.13-0.59-0.13-1.19,0-1.77c0.44-1.94,2.17-3.31,4.17-3.3 c2.36,0,4.26,1.87,4.26,4.19S74.03,14.68,71.67,14.68L71.67,14.68z M83.04,14.47h-1.61c-0.13,0-0.24-0.06-0.3-0.17l-1.44-2.39 l-1.44,2.39c-0.06,0.11-0.18,0.17-0.3,0.17h-1.61c-0.04,0-0.08-0.01-0.12-0.03c-0.09-0.06-0.13-0.19-0.06-0.28l0,0l2.43-3.68 L76.2,6.84c-0.02-0.03-0.03-0.07-0.03-0.12c0-0.12,0.09-0.21,0.21-0.21h1.61c0.13,0,0.24,0.06,0.3,0.17l1.41,2.36l1.41-2.36 c0.06-0.11,0.18-0.17,0.3-0.17h1.61c0.04,0,0.08,0.01,0.12,0.03c0.09,0.06,0.13,0.19,0.06,0.28l0,0l-2.38,3.64l2.43,3.67 c0.02,0.03,0.03,0.07,0.03,0.12C83.25,14.38,83.16,14.47,83.04,14.47L83.04,14.47L83.04,14.47z"/%3E %3Cpath class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" d="M10.5,1.24c-5.11,0-9.25,4.15-9.25,9.25s4.15,9.25,9.25,9.25s9.25-4.15,9.25-9.25 C19.75,5.38,15.61,1.24,10.5,1.24z M14.89,12.77c-1.93,1.93-4.78,2.31-6.7,2.31c-0.7,0-1.41-0.05-2.1-0.16c0,0-1.02-5.64,2.14-8.81 c0.83-0.83,1.95-1.28,3.13-1.28c1.27,0,2.49,0.51,3.39,1.42C16.59,8.09,16.64,11,14.89,12.77z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M10.5-0.01C4.7-0.01,0,4.7,0,10.49s4.7,10.5,10.5,10.5S21,16.29,21,10.49C20.99,4.7,16.3-0.01,10.5-0.01z M10.5,19.74c-5.11,0-9.25-4.15-9.25-9.25s4.14-9.26,9.25-9.26s9.25,4.15,9.25,9.25C19.75,15.61,15.61,19.74,10.5,19.74z"/%3E %3Cpath class="st1" style="opacity:0.35; enable-background:new;" d="M14.74,6.25C12.9,4.41,9.98,4.35,8.23,6.1c-3.16,3.17-2.14,8.81-2.14,8.81s5.64,1.02,8.81-2.14 C16.64,11,16.59,8.09,14.74,6.25z M12.47,10.34l-0.91,1.87l-0.9-1.87L8.8,9.43l1.86-0.9l0.9-1.87l0.91,1.87l1.86,0.9L12.47,10.34z"/%3E %3Cpolygon class="st0" style="opacity:0.9; fill: %23FFFFFF; enable-background: new;" points="14.33,9.43 12.47,10.34 11.56,12.21 10.66,10.34 8.8,9.43 10.66,8.53 11.56,6.66 12.47,8.53 "/%3E%3C/g%3E%3C/svg%3E\');'
        }
      };
    }
  });

  // src/plots/mapbox/layout_attributes.js
  var require_layout_attributes19 = __commonJS({
    "src/plots/mapbox/layout_attributes.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var defaultLine = require_color().defaultLine;
      var domainAttrs = require_domain().attributes;
      var fontAttrs = require_font_attributes();
      var textposition = require_attributes12().textposition;
      var overrideAll = require_edit_types().overrideAll;
      var templatedArray = require_plot_template().templatedArray;
      var constants = require_constants25();
      var fontAttr = fontAttrs({
        noFontVariant: true,
        noFontShadow: true,
        noFontLineposition: true,
        noFontTextcase: true
      });
      fontAttr.family.dflt = "Open Sans Regular, Arial Unicode MS Regular";
      var attrs = module.exports = overrideAll({
        _arrayAttrRegexps: [Lib.counterRegex("mapbox", ".layers", true)],
        domain: domainAttrs({ name: "mapbox" }),
        accesstoken: {
          valType: "string",
          noBlank: true,
          strict: true
        },
        style: {
          valType: "any",
          values: constants.styleValuesMapbox.concat(constants.styleValuesNonMapbox),
          dflt: constants.styleValueDflt
        },
        center: {
          lon: {
            valType: "number",
            dflt: 0
          },
          lat: {
            valType: "number",
            dflt: 0
          }
        },
        zoom: {
          valType: "number",
          dflt: 1
        },
        bearing: {
          valType: "number",
          dflt: 0
        },
        pitch: {
          valType: "number",
          dflt: 0
        },
        bounds: {
          west: {
            valType: "number"
          },
          east: {
            valType: "number"
          },
          south: {
            valType: "number"
          },
          north: {
            valType: "number"
          }
        },
        layers: templatedArray("layer", {
          visible: {
            valType: "boolean",
            dflt: true
          },
          sourcetype: {
            valType: "enumerated",
            values: ["geojson", "vector", "raster", "image"],
            dflt: "geojson"
          },
          source: {
            valType: "any"
          },
          sourcelayer: {
            valType: "string",
            dflt: ""
          },
          sourceattribution: {
            valType: "string"
          },
          type: {
            valType: "enumerated",
            values: ["circle", "line", "fill", "symbol", "raster"],
            dflt: "circle"
          },
          coordinates: {
            valType: "any"
          },
          // attributes shared between all types
          below: {
            valType: "string"
          },
          color: {
            valType: "color",
            dflt: defaultLine
          },
          opacity: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 1
          },
          minzoom: {
            valType: "number",
            min: 0,
            max: 24,
            dflt: 0
          },
          maxzoom: {
            valType: "number",
            min: 0,
            max: 24,
            dflt: 24
          },
          // type-specific style attributes
          circle: {
            radius: {
              valType: "number",
              dflt: 15
            }
          },
          line: {
            width: {
              valType: "number",
              dflt: 2
            },
            dash: {
              valType: "data_array"
            }
          },
          fill: {
            outlinecolor: {
              valType: "color",
              dflt: defaultLine
            }
          },
          symbol: {
            icon: {
              valType: "string",
              dflt: "marker"
            },
            iconsize: {
              valType: "number",
              dflt: 10
            },
            text: {
              valType: "string",
              dflt: ""
            },
            placement: {
              valType: "enumerated",
              values: ["point", "line", "line-center"],
              dflt: "point"
            },
            textfont: fontAttr,
            textposition: Lib.extendFlat({}, textposition, { arrayOk: false })
          }
        })
      }, "plot", "from-root");
      attrs.uirevision = {
        valType: "any",
        editType: "none"
      };
    }
  });

  // src/traces/scattermapbox/attributes.js
  var require_attributes54 = __commonJS({
    "src/traces/scattermapbox/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterGeoAttrs = require_attributes48();
      var scatterAttrs = require_attributes12();
      var mapboxAttrs = require_layout_attributes19();
      var baseAttrs = require_attributes2();
      var colorScaleAttrs = require_attributes8();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var mapboxLayoutAtributes = require_layout_attributes19();
      var lineAttrs = scatterGeoAttrs.line;
      var markerAttrs = scatterGeoAttrs.marker;
      module.exports = overrideAll(
        {
          lon: scatterGeoAttrs.lon,
          lat: scatterGeoAttrs.lat,
          cluster: {
            enabled: {
              valType: "boolean"
            },
            maxzoom: extendFlat({}, mapboxLayoutAtributes.layers.maxzoom, {}),
            step: {
              valType: "number",
              arrayOk: true,
              dflt: -1,
              min: -1
            },
            size: {
              valType: "number",
              arrayOk: true,
              dflt: 20,
              min: 0
            },
            color: {
              valType: "color",
              arrayOk: true
            },
            opacity: extendFlat({}, markerAttrs.opacity, {
              dflt: 1
            })
          },
          // locations
          // locationmode
          mode: extendFlat({}, scatterAttrs.mode, {
            dflt: "markers"
          }),
          text: extendFlat({}, scatterAttrs.text, {}),
          texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["lat", "lon", "text"] }),
          texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
          hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
          line: {
            color: lineAttrs.color,
            width: lineAttrs.width
            // TODO
            // dash: dash
          },
          connectgaps: scatterAttrs.connectgaps,
          marker: extendFlat(
            {
              symbol: {
                valType: "string",
                dflt: "circle",
                arrayOk: true
              },
              angle: {
                valType: "number",
                dflt: "auto",
                arrayOk: true
              },
              allowoverlap: {
                valType: "boolean",
                dflt: false
              },
              opacity: markerAttrs.opacity,
              size: markerAttrs.size,
              sizeref: markerAttrs.sizeref,
              sizemin: markerAttrs.sizemin,
              sizemode: markerAttrs.sizemode
            },
            colorScaleAttrs("marker")
            // line
          ),
          fill: scatterGeoAttrs.fill,
          fillcolor: makeFillcolorAttr(),
          textfont: mapboxAttrs.layers.symbol.textfont,
          textposition: mapboxAttrs.layers.symbol.textposition,
          below: {
            valType: "string"
          },
          selected: {
            marker: scatterAttrs.selected.marker
          },
          unselected: {
            marker: scatterAttrs.unselected.marker
          },
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
            flags: ["lon", "lat", "text", "name"]
          }),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs()
        },
        "calc",
        "nested"
      );
    }
  });

  // src/traces/scattermapbox/constants.js
  var require_constants26 = __commonJS({
    "src/traces/scattermapbox/constants.js"(exports, module) {
      "use strict";
      var supportedFonts = [
        "Metropolis Black Italic",
        "Metropolis Black",
        "Metropolis Bold Italic",
        "Metropolis Bold",
        "Metropolis Extra Bold Italic",
        "Metropolis Extra Bold",
        "Metropolis Extra Light Italic",
        "Metropolis Extra Light",
        "Metropolis Light Italic",
        "Metropolis Light",
        "Metropolis Medium Italic",
        "Metropolis Medium",
        "Metropolis Regular Italic",
        "Metropolis Regular",
        "Metropolis Semi Bold Italic",
        "Metropolis Semi Bold",
        "Metropolis Thin Italic",
        "Metropolis Thin",
        "Open Sans Bold Italic",
        "Open Sans Bold",
        "Open Sans Extrabold Italic",
        "Open Sans Extrabold",
        "Open Sans Italic",
        "Open Sans Light Italic",
        "Open Sans Light",
        "Open Sans Regular",
        "Open Sans Semibold Italic",
        "Open Sans Semibold",
        "Klokantech Noto Sans Bold",
        "Klokantech Noto Sans CJK Bold",
        "Klokantech Noto Sans CJK Regular",
        "Klokantech Noto Sans Italic",
        "Klokantech Noto Sans Regular"
      ];
      module.exports = {
        isSupportedFont: function(a) {
          return supportedFonts.indexOf(a) !== -1;
        }
      };
    }
  });

  // src/traces/scattermapbox/defaults.js
  var require_defaults50 = __commonJS({
    "src/traces/scattermapbox/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var attributes = require_attributes54();
      var isSupportedFont = require_constants26().isSupportedFont;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        function coerce2(attr, dflt) {
          return Lib.coerce2(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleLonLatDefaults(traceIn, traceOut, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        coerce("text");
        coerce("texttemplate");
        coerce("texttemplatefallback");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("mode");
        coerce("below");
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { noLine: true, noAngle: true });
          coerce("marker.allowoverlap");
          coerce("marker.angle");
          var marker = traceOut.marker;
          if (marker.symbol !== "circle") {
            if (Lib.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0];
            if (Lib.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0];
          }
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, { noDash: true });
          coerce("connectgaps");
        }
        var clusterMaxzoom = coerce2("cluster.maxzoom");
        var clusterStep = coerce2("cluster.step");
        var clusterColor = coerce2("cluster.color", traceOut.marker && traceOut.marker.color || defaultColor);
        var clusterSize = coerce2("cluster.size");
        var clusterOpacity = coerce2("cluster.opacity");
        var clusterEnabledDflt = clusterMaxzoom !== false || clusterStep !== false || clusterColor !== false || clusterSize !== false || clusterOpacity !== false;
        var clusterEnabled = coerce("cluster.enabled", clusterEnabledDflt);
        if (clusterEnabled || subTypes.hasText(traceOut)) {
          var layoutFontFamily = layout.font.family;
          handleTextDefaults(traceIn, traceOut, layout, coerce, {
            noSelect: true,
            noFontVariant: true,
            noFontShadow: true,
            noFontLineposition: true,
            noFontTextcase: true,
            font: {
              family: isSupportedFont(layoutFontFamily) ? layoutFontFamily : "Open Sans Regular",
              weight: layout.font.weight,
              style: layout.font.style,
              size: layout.font.size,
              color: layout.font.color
            }
          });
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        }
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
      function handleLonLatDefaults(traceIn, traceOut, coerce) {
        var lon = coerce("lon") || [];
        var lat = coerce("lat") || [];
        var len = Math.min(lon.length, lat.length);
        traceOut._length = len;
        return len;
      }
    }
  });

  // src/traces/scattermapbox/format_labels.js
  var require_format_labels5 = __commonJS({
    "src/traces/scattermapbox/format_labels.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var labels = {};
        var subplot = fullLayout[trace.subplot]._subplot;
        var ax = subplot.mockAxis;
        var lonlat = cdi.lonlat;
        labels.lonLabel = Axes.tickText(ax, ax.c2l(lonlat[0]), true).text;
        labels.latLabel = Axes.tickText(ax, ax.c2l(lonlat[1]), true).text;
        return labels;
      };
    }
  });

  // src/plots/mapbox/convert_text_opts.js
  var require_convert_text_opts = __commonJS({
    "src/plots/mapbox/convert_text_opts.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function convertTextOpts(textposition, iconSize) {
        var parts = textposition.split(" ");
        var vPos = parts[0];
        var hPos = parts[1];
        var factor = Lib.isArrayOrTypedArray(iconSize) ? Lib.mean(iconSize) : iconSize;
        var xInc = 0.5 + factor / 100;
        var yInc = 1.5 + factor / 100;
        var anchorVals = ["", ""];
        var offset = [0, 0];
        switch (vPos) {
          case "top":
            anchorVals[0] = "top";
            offset[1] = -yInc;
            break;
          case "bottom":
            anchorVals[0] = "bottom";
            offset[1] = yInc;
            break;
        }
        switch (hPos) {
          case "left":
            anchorVals[1] = "right";
            offset[0] = -xInc;
            break;
          case "right":
            anchorVals[1] = "left";
            offset[0] = xInc;
            break;
        }
        var anchor;
        if (anchorVals[0] && anchorVals[1]) anchor = anchorVals.join("-");
        else if (anchorVals[0]) anchor = anchorVals[0];
        else if (anchorVals[1]) anchor = anchorVals[1];
        else anchor = "center";
        return { anchor, offset };
      };
    }
  });

  // src/traces/scattermapbox/convert.js
  var require_convert11 = __commonJS({
    "src/traces/scattermapbox/convert.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var BADNUM = require_numerical().BADNUM;
      var geoJsonUtils = require_geojson_utils();
      var Colorscale = require_colorscale();
      var Drawing = require_drawing();
      var makeBubbleSizeFn = require_make_bubble_size_func();
      var subTypes = require_subtypes();
      var isSupportedFont = require_constants26().isSupportedFont;
      var convertTextOpts = require_convert_text_opts();
      var appendArrayPointValue = require_helpers2().appendArrayPointValue;
      var NEWLINES = require_svg_text_utils().NEWLINES;
      var BR_TAG_ALL = require_svg_text_utils().BR_TAG_ALL;
      module.exports = function convert(gd, calcTrace) {
        var trace = calcTrace[0].trace;
        var isVisible = trace.visible === true && trace._length !== 0;
        var hasFill = trace.fill !== "none";
        var hasLines = subTypes.hasLines(trace);
        var hasMarkers = subTypes.hasMarkers(trace);
        var hasText = subTypes.hasText(trace);
        var hasCircles = hasMarkers && trace.marker.symbol === "circle";
        var hasSymbols = hasMarkers && trace.marker.symbol !== "circle";
        var hasCluster = trace.cluster && trace.cluster.enabled;
        var fill = initContainer("fill");
        var line = initContainer("line");
        var circle = initContainer("circle");
        var symbol = initContainer("symbol");
        var opts = {
          fill,
          line,
          circle,
          symbol
        };
        if (!isVisible) return opts;
        var lineCoords;
        if (hasFill || hasLines) {
          lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
        }
        if (hasFill) {
          fill.geojson = geoJsonUtils.makePolygon(lineCoords);
          fill.layout.visibility = "visible";
          Lib.extendFlat(fill.paint, {
            "fill-color": trace.fillcolor
          });
        }
        if (hasLines) {
          line.geojson = geoJsonUtils.makeLine(lineCoords);
          line.layout.visibility = "visible";
          Lib.extendFlat(line.paint, {
            "line-width": trace.line.width,
            "line-color": trace.line.color,
            "line-opacity": trace.opacity
          });
        }
        if (hasCircles) {
          var circleOpts = makeCircleOpts(calcTrace);
          circle.geojson = circleOpts.geojson;
          circle.layout.visibility = "visible";
          if (hasCluster) {
            circle.filter = ["!", ["has", "point_count"]];
            opts.cluster = {
              type: "circle",
              filter: ["has", "point_count"],
              layout: { visibility: "visible" },
              paint: {
                "circle-color": arrayifyAttribute(trace.cluster.color, trace.cluster.step),
                "circle-radius": arrayifyAttribute(trace.cluster.size, trace.cluster.step),
                "circle-opacity": arrayifyAttribute(trace.cluster.opacity, trace.cluster.step)
              }
            };
            opts.clusterCount = {
              type: "symbol",
              filter: ["has", "point_count"],
              paint: {},
              layout: {
                "text-field": "{point_count_abbreviated}",
                "text-font": getTextFont(trace),
                "text-size": 12
              }
            };
          }
          Lib.extendFlat(circle.paint, {
            "circle-color": circleOpts.mcc,
            "circle-radius": circleOpts.mrc,
            "circle-opacity": circleOpts.mo
          });
        }
        if (hasCircles && hasCluster) {
          circle.filter = ["!", ["has", "point_count"]];
        }
        if (hasSymbols || hasText) {
          symbol.geojson = makeSymbolGeoJSON(calcTrace, gd);
          Lib.extendFlat(symbol.layout, {
            visibility: "visible",
            "icon-image": "{symbol}-15",
            "text-field": "{text}"
          });
          if (hasSymbols) {
            Lib.extendFlat(symbol.layout, {
              "icon-size": trace.marker.size / 10
            });
            if ("angle" in trace.marker && trace.marker.angle !== "auto") {
              Lib.extendFlat(symbol.layout, {
                // unfortunately cant use {angle} do to this issue:
                // https://github.com/mapbox/mapbox-gl-js/issues/873
                "icon-rotate": {
                  type: "identity",
                  property: "angle"
                },
                "icon-rotation-alignment": "map"
              });
            }
            symbol.layout["icon-allow-overlap"] = trace.marker.allowoverlap;
            Lib.extendFlat(symbol.paint, {
              "icon-opacity": trace.opacity * trace.marker.opacity,
              // TODO does not work ??
              "icon-color": trace.marker.color
            });
          }
          if (hasText) {
            var iconSize = (trace.marker || {}).size;
            var textOpts = convertTextOpts(trace.textposition, iconSize);
            Lib.extendFlat(symbol.layout, {
              "text-size": trace.textfont.size,
              "text-anchor": textOpts.anchor,
              "text-offset": textOpts.offset,
              "text-font": getTextFont(trace)
            });
            Lib.extendFlat(symbol.paint, {
              "text-color": trace.textfont.color,
              "text-opacity": trace.opacity
            });
          }
        }
        return opts;
      };
      function initContainer(type) {
        return {
          type,
          geojson: geoJsonUtils.makeBlank(),
          layout: { visibility: "none" },
          filter: null,
          paint: {}
        };
      }
      function makeCircleOpts(calcTrace) {
        var trace = calcTrace[0].trace;
        var marker = trace.marker;
        var selectedpoints = trace.selectedpoints;
        var arrayColor = Lib.isArrayOrTypedArray(marker.color);
        var arraySize = Lib.isArrayOrTypedArray(marker.size);
        var arrayOpacity = Lib.isArrayOrTypedArray(marker.opacity);
        var i;
        function addTraceOpacity(o) {
          return trace.opacity * o;
        }
        function size2radius(s) {
          return s / 2;
        }
        var colorFn;
        if (arrayColor) {
          if (Colorscale.hasColorscale(trace, "marker")) {
            colorFn = Colorscale.makeColorScaleFuncFromTrace(marker);
          } else {
            colorFn = Lib.identity;
          }
        }
        var sizeFn;
        if (arraySize) {
          sizeFn = makeBubbleSizeFn(trace);
        }
        var opacityFn;
        if (arrayOpacity) {
          opacityFn = function(mo) {
            var mo2 = isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
            return addTraceOpacity(mo2);
          };
        }
        var features = [];
        for (i = 0; i < calcTrace.length; i++) {
          var calcPt = calcTrace[i];
          var lonlat = calcPt.lonlat;
          if (isBADNUM(lonlat)) continue;
          var props = {};
          if (colorFn) props.mcc = calcPt.mcc = colorFn(calcPt.mc);
          if (sizeFn) props.mrc = calcPt.mrc = sizeFn(calcPt.ms);
          if (opacityFn) props.mo = opacityFn(calcPt.mo);
          if (selectedpoints) props.selected = calcPt.selected || 0;
          features.push({
            type: "Feature",
            id: i + 1,
            geometry: { type: "Point", coordinates: lonlat },
            properties: props
          });
        }
        var fns;
        if (selectedpoints) {
          fns = Drawing.makeSelectedPointStyleFns(trace);
          for (i = 0; i < features.length; i++) {
            var d = features[i].properties;
            if (fns.selectedOpacityFn) {
              d.mo = addTraceOpacity(fns.selectedOpacityFn(d));
            }
            if (fns.selectedColorFn) {
              d.mcc = fns.selectedColorFn(d);
            }
            if (fns.selectedSizeFn) {
              d.mrc = fns.selectedSizeFn(d);
            }
          }
        }
        return {
          geojson: { type: "FeatureCollection", features },
          mcc: arrayColor || fns && fns.selectedColorFn ? { type: "identity", property: "mcc" } : marker.color,
          mrc: arraySize || fns && fns.selectedSizeFn ? { type: "identity", property: "mrc" } : size2radius(marker.size),
          mo: arrayOpacity || fns && fns.selectedOpacityFn ? { type: "identity", property: "mo" } : addTraceOpacity(marker.opacity)
        };
      }
      function makeSymbolGeoJSON(calcTrace, gd) {
        var fullLayout = gd._fullLayout;
        var trace = calcTrace[0].trace;
        var marker = trace.marker || {};
        var symbol = marker.symbol;
        var angle = marker.angle;
        var fillSymbol = symbol !== "circle" ? getFillFunc(symbol) : blankFillFunc;
        var fillAngle = angle !== "auto" ? getFillFunc(angle, true) : blankFillFunc;
        var fillText = subTypes.hasText(trace) ? getFillFunc(trace.text) : blankFillFunc;
        var features = [];
        for (var i = 0; i < calcTrace.length; i++) {
          var calcPt = calcTrace[i];
          if (isBADNUM(calcPt.lonlat)) continue;
          var texttemplate = trace.texttemplate;
          var text;
          if (texttemplate) {
            var tt = Array.isArray(texttemplate) ? texttemplate[i] || "" : texttemplate;
            var labels = trace._module.formatLabels(calcPt, trace, fullLayout);
            var pointValues = {};
            appendArrayPointValue(pointValues, trace, calcPt.i);
            text = Lib.texttemplateString({
              data: [pointValues, calcPt, trace._meta],
              fallback: trace.texttemplatefallback,
              labels,
              locale: fullLayout._d3locale,
              template: tt
            });
          } else {
            text = fillText(i);
          }
          if (text) {
            text = text.replace(NEWLINES, "").replace(BR_TAG_ALL, "\n");
          }
          features.push({
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: calcPt.lonlat
            },
            properties: {
              symbol: fillSymbol(i),
              angle: fillAngle(i),
              text
            }
          });
        }
        return {
          type: "FeatureCollection",
          features
        };
      }
      function getFillFunc(attr, numeric) {
        if (Lib.isArrayOrTypedArray(attr)) {
          if (numeric) {
            return function(i) {
              return isNumeric(attr[i]) ? +attr[i] : 0;
            };
          }
          return function(i) {
            return attr[i];
          };
        } else if (attr) {
          return function() {
            return attr;
          };
        } else {
          return blankFillFunc;
        }
      }
      function blankFillFunc() {
        return "";
      }
      function isBADNUM(lonlat) {
        return lonlat[0] === BADNUM;
      }
      function arrayifyAttribute(values, step) {
        var newAttribute;
        if (Lib.isArrayOrTypedArray(values) && Lib.isArrayOrTypedArray(step)) {
          newAttribute = ["step", ["get", "point_count"], values[0]];
          for (var idx = 1; idx < values.length; idx++) {
            newAttribute.push(step[idx - 1], values[idx]);
          }
        } else {
          newAttribute = values;
        }
        return newAttribute;
      }
      function getTextFont(trace) {
        var font = trace.textfont;
        var family = font.family;
        var style = font.style;
        var weight = font.weight;
        var parts = family.split(" ");
        var isItalic = parts[parts.length - 1] === "Italic";
        if (isItalic) parts.pop();
        isItalic = isItalic || style === "italic";
        var str = parts.join(" ");
        if (weight === "bold" && parts.indexOf("Bold") === -1) {
          str += " Bold";
        } else if (weight <= 1e3) {
          if (parts[0] === "Metropolis") {
            str = "Metropolis";
            if (weight > 850) str += " Black";
            else if (weight > 750) str += " Extra Bold";
            else if (weight > 650) str += " Bold";
            else if (weight > 550) str += " Semi Bold";
            else if (weight > 450) str += " Medium";
            else if (weight > 350) str += " Regular";
            else if (weight > 250) str += " Light";
            else if (weight > 150) str += " Extra Light";
            else str += " Thin";
          } else if (parts.slice(0, 2).join(" ") === "Open Sans") {
            str = "Open Sans";
            if (weight > 750) str += " Extrabold";
            else if (weight > 650) str += " Bold";
            else if (weight > 550) str += " Semibold";
            else if (weight > 350) str += " Regular";
            else str += " Light";
          } else if (parts.slice(0, 3).join(" ") === "Klokantech Noto Sans") {
            str = "Klokantech Noto Sans";
            if (parts[3] === "CJK") str += " CJK";
            str += weight > 500 ? " Bold" : " Regular";
          }
        }
        if (isItalic) str += " Italic";
        if (str === "Open Sans Regular Italic") str = "Open Sans Italic";
        else if (str === "Open Sans Regular Bold") str = "Open Sans Bold";
        else if (str === "Open Sans Regular Bold Italic") str = "Open Sans Bold Italic";
        else if (str === "Klokantech Noto Sans Regular Italic") str = "Klokantech Noto Sans Italic";
        if (!isSupportedFont(str)) {
          str = family;
        }
        var textFont = str.split(", ");
        return textFont;
      }
    }
  });

  // src/traces/scattermapbox/plot.js
  var require_plot23 = __commonJS({
    "src/traces/scattermapbox/plot.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var convert = require_convert11();
      var LAYER_PREFIX = require_constants25().traceLayerPrefix;
      var ORDER = {
        cluster: ["cluster", "clusterCount", "circle"],
        nonCluster: ["fill", "line", "circle", "symbol"]
      };
      function ScatterMapbox(subplot, uid, clusterEnabled, isHidden) {
        this.type = "scattermapbox";
        this.subplot = subplot;
        this.uid = uid;
        this.clusterEnabled = clusterEnabled;
        this.isHidden = isHidden;
        this.sourceIds = {
          fill: "source-" + uid + "-fill",
          line: "source-" + uid + "-line",
          circle: "source-" + uid + "-circle",
          symbol: "source-" + uid + "-symbol",
          cluster: "source-" + uid + "-circle",
          clusterCount: "source-" + uid + "-circle"
        };
        this.layerIds = {
          fill: LAYER_PREFIX + uid + "-fill",
          line: LAYER_PREFIX + uid + "-line",
          circle: LAYER_PREFIX + uid + "-circle",
          symbol: LAYER_PREFIX + uid + "-symbol",
          cluster: LAYER_PREFIX + uid + "-cluster",
          clusterCount: LAYER_PREFIX + uid + "-cluster-count"
        };
        this.below = null;
      }
      var proto = ScatterMapbox.prototype;
      proto.addSource = function(k, opts, cluster) {
        var sourceOpts = {
          type: "geojson",
          data: opts.geojson
        };
        if (cluster && cluster.enabled) {
          Lib.extendFlat(sourceOpts, {
            cluster: true,
            clusterMaxZoom: cluster.maxzoom
          });
        }
        var isSourceExists = this.subplot.map.getSource(this.sourceIds[k]);
        if (isSourceExists) {
          isSourceExists.setData(opts.geojson);
        } else {
          this.subplot.map.addSource(this.sourceIds[k], sourceOpts);
        }
      };
      proto.setSourceData = function(k, opts) {
        this.subplot.map.getSource(this.sourceIds[k]).setData(opts.geojson);
      };
      proto.addLayer = function(k, opts, below) {
        var source = {
          type: opts.type,
          id: this.layerIds[k],
          source: this.sourceIds[k],
          layout: opts.layout,
          paint: opts.paint
        };
        if (opts.filter) {
          source.filter = opts.filter;
        }
        var currentLayerId = this.layerIds[k];
        var layerExist;
        var layers = this.subplot.getMapLayers();
        for (var i = 0; i < layers.length; i++) {
          if (layers[i].id === currentLayerId) {
            layerExist = true;
            break;
          }
        }
        if (layerExist) {
          this.subplot.setOptions(currentLayerId, "setLayoutProperty", source.layout);
          if (source.layout.visibility === "visible") {
            this.subplot.setOptions(currentLayerId, "setPaintProperty", source.paint);
          }
        } else {
          this.subplot.addLayer(source, below);
        }
      };
      proto.update = function update(calcTrace) {
        var trace = calcTrace[0].trace;
        var subplot = this.subplot;
        var map = subplot.map;
        var optsAll = convert(subplot.gd, calcTrace);
        var below = subplot.belowLookup["trace-" + this.uid];
        var hasCluster = !!(trace.cluster && trace.cluster.enabled);
        var hadCluster = !!this.clusterEnabled;
        var lThis = this;
        function addCluster(noSource) {
          if (!noSource) lThis.addSource("circle", optsAll.circle, trace.cluster);
          var order = ORDER.cluster;
          for (var i = 0; i < order.length; i++) {
            var k = order[i];
            var opts = optsAll[k];
            lThis.addLayer(k, opts, below);
          }
        }
        function removeCluster(noSource) {
          var order = ORDER.cluster;
          for (var i = order.length - 1; i >= 0; i--) {
            var k = order[i];
            map.removeLayer(lThis.layerIds[k]);
          }
          if (!noSource) map.removeSource(lThis.sourceIds.circle);
        }
        function addNonCluster(noSource) {
          var order = ORDER.nonCluster;
          for (var i = 0; i < order.length; i++) {
            var k = order[i];
            var opts = optsAll[k];
            if (!noSource) lThis.addSource(k, opts);
            lThis.addLayer(k, opts, below);
          }
        }
        function removeNonCluster(noSource) {
          var order = ORDER.nonCluster;
          for (var i = order.length - 1; i >= 0; i--) {
            var k = order[i];
            map.removeLayer(lThis.layerIds[k]);
            if (!noSource) map.removeSource(lThis.sourceIds[k]);
          }
        }
        function remove(noSource) {
          if (hadCluster) removeCluster(noSource);
          else removeNonCluster(noSource);
        }
        function add(noSource) {
          if (hasCluster) addCluster(noSource);
          else addNonCluster(noSource);
        }
        function repaint() {
          var order = hasCluster ? ORDER.cluster : ORDER.nonCluster;
          for (var i = 0; i < order.length; i++) {
            var k = order[i];
            var opts = optsAll[k];
            if (!opts) continue;
            subplot.setOptions(lThis.layerIds[k], "setLayoutProperty", opts.layout);
            if (opts.layout.visibility === "visible") {
              if (k !== "cluster") {
                lThis.setSourceData(k, opts);
              }
              subplot.setOptions(lThis.layerIds[k], "setPaintProperty", opts.paint);
            }
          }
        }
        var wasHidden = this.isHidden;
        var isHidden = trace.visible !== true;
        if (isHidden) {
          if (!wasHidden) remove();
        } else if (wasHidden) {
          if (!isHidden) add();
        } else if (hadCluster !== hasCluster) {
          remove();
          add();
        } else if (this.below !== below) {
          remove(true);
          add(true);
          repaint();
        } else {
          repaint();
        }
        this.clusterEnabled = hasCluster;
        this.isHidden = isHidden;
        this.below = below;
        calcTrace[0].trace._glTrace = this;
      };
      proto.dispose = function dispose() {
        var map = this.subplot.map;
        var order = this.clusterEnabled ? ORDER.cluster : ORDER.nonCluster;
        for (var i = order.length - 1; i >= 0; i--) {
          var k = order[i];
          map.removeLayer(this.layerIds[k]);
          map.removeSource(this.sourceIds[k]);
        }
      };
      module.exports = function createScatterMapbox(subplot, calcTrace) {
        var trace = calcTrace[0].trace;
        var hasCluster = trace.cluster && trace.cluster.enabled;
        var isHidden = trace.visible !== true;
        var scatterMapbox = new ScatterMapbox(
          subplot,
          trace.uid,
          hasCluster,
          isHidden
        );
        var optsAll = convert(subplot.gd, calcTrace);
        var below = scatterMapbox.below = subplot.belowLookup["trace-" + trace.uid];
        var i, k, opts;
        if (hasCluster) {
          scatterMapbox.addSource("circle", optsAll.circle, trace.cluster);
          for (i = 0; i < ORDER.cluster.length; i++) {
            k = ORDER.cluster[i];
            opts = optsAll[k];
            scatterMapbox.addLayer(k, opts, below);
          }
        } else {
          for (i = 0; i < ORDER.nonCluster.length; i++) {
            k = ORDER.nonCluster[i];
            opts = optsAll[k];
            scatterMapbox.addSource(k, opts, trace.cluster);
            scatterMapbox.addLayer(k, opts, below);
          }
        }
        calcTrace[0].trace._glTrace = scatterMapbox;
        return scatterMapbox;
      };
    }
  });

  // src/traces/scattermapbox/hover.js
  var require_hover18 = __commonJS({
    "src/traces/scattermapbox/hover.js"(exports, module) {
      "use strict";
      var Fx = require_fx();
      var Lib = require_lib();
      var getTraceColor = require_get_trace_color();
      var fillText = Lib.fillText;
      var BADNUM = require_numerical().BADNUM;
      var LAYER_PREFIX = require_constants25().traceLayerPrefix;
      function hoverPoints(pointData, xval, yval) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var subplot = pointData.subplot;
        var clusteredPointsIds = [];
        var layer = LAYER_PREFIX + trace.uid + "-circle";
        var hasCluster = trace.cluster && trace.cluster.enabled;
        if (hasCluster) {
          var elems = subplot.map.queryRenderedFeatures(null, { layers: [layer] });
          clusteredPointsIds = elems.map(function(elem) {
            return elem.id;
          });
        }
        var winding = xval >= 0 ? Math.floor((xval + 180) / 360) : Math.ceil((xval - 180) / 360);
        var lonShift = winding * 360;
        var xval2 = xval - lonShift;
        function distFn(d) {
          var lonlat2 = d.lonlat;
          if (lonlat2[0] === BADNUM) return Infinity;
          if (hasCluster && clusteredPointsIds.indexOf(d.i + 1) === -1) return Infinity;
          var lon = Lib.modHalf(lonlat2[0], 360);
          var lat = lonlat2[1];
          var pt = subplot.project([lon, lat]);
          var dx = pt.x - xa.c2p([xval2, lat]);
          var dy = pt.y - ya.c2p([lon, yval]);
          var rad2 = Math.max(3, d.mrc || 0);
          return Math.max(Math.sqrt(dx * dx + dy * dy) - rad2, 1 - 3 / rad2);
        }
        Fx.getClosest(cd, distFn, pointData);
        if (pointData.index === false) return;
        var di = cd[pointData.index];
        var lonlat = di.lonlat;
        var lonlatShifted = [Lib.modHalf(lonlat[0], 360) + lonShift, lonlat[1]];
        var xc = xa.c2p(lonlatShifted);
        var yc = ya.c2p(lonlatShifted);
        var rad = di.mrc || 1;
        pointData.x0 = xc - rad;
        pointData.x1 = xc + rad;
        pointData.y0 = yc - rad;
        pointData.y1 = yc + rad;
        var fullLayout = {};
        fullLayout[trace.subplot] = { _subplot: subplot };
        var labels = trace._module.formatLabels(di, trace, fullLayout);
        pointData.lonLabel = labels.lonLabel;
        pointData.latLabel = labels.latLabel;
        pointData.color = getTraceColor(trace, di);
        pointData.extraText = getExtraText(trace, di, cd[0].t.labels);
        pointData.hovertemplate = trace.hovertemplate;
        return [pointData];
      }
      function getExtraText(trace, di, labels) {
        if (trace.hovertemplate) return;
        var hoverinfo = di.hi || trace.hoverinfo;
        var parts = hoverinfo.split("+");
        var isAll = parts.indexOf("all") !== -1;
        var hasLon = parts.indexOf("lon") !== -1;
        var hasLat = parts.indexOf("lat") !== -1;
        var lonlat = di.lonlat;
        var text = [];
        function format(v) {
          return v + "\xB0";
        }
        if (isAll || hasLon && hasLat) {
          text.push("(" + format(lonlat[1]) + ", " + format(lonlat[0]) + ")");
        } else if (hasLon) {
          text.push(labels.lon + format(lonlat[0]));
        } else if (hasLat) {
          text.push(labels.lat + format(lonlat[1]));
        }
        if (isAll || parts.indexOf("text") !== -1) {
          fillText(di, trace, text);
        }
        return text.join("<br>");
      }
      module.exports = {
        hoverPoints,
        getExtraText
      };
    }
  });

  // src/traces/scattermapbox/event_data.js
  var require_event_data11 = __commonJS({
    "src/traces/scattermapbox/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        out.lon = pt.lon;
        out.lat = pt.lat;
        return out;
      };
    }
  });

  // src/traces/scattermapbox/select.js
  var require_select9 = __commonJS({
    "src/traces/scattermapbox/select.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subtypes = require_subtypes();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var trace = cd[0].trace;
        var i;
        if (!subtypes.hasMarkers(trace)) return [];
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            var di = cd[i];
            var lonlat = di.lonlat;
            if (lonlat[0] !== BADNUM) {
              var lonlat2 = [Lib.modHalf(lonlat[0], 360), lonlat[1]];
              var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)];
              if (selectionTester.contains(xy, null, i, searchInfo)) {
                selection.push({
                  pointNumber: i,
                  lon: lonlat[0],
                  lat: lonlat[1]
                });
                di.selected = 1;
              } else {
                di.selected = 0;
              }
            }
          }
        }
        return selection;
      };
    }
  });

  // node_modules/@plotly/mapbox-gl/dist/mapbox-gl-unminified.js
  var require_mapbox_gl_unminified = __commonJS({
    "node_modules/@plotly/mapbox-gl/dist/mapbox-gl-unminified.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && false ? define(factory) : (global2 = global2 || self, global2.mapboxgl = factory());
      })(exports, function() {
        "use strict";
        var shared, worker, mapboxgl;
        function define2(_, chunk) {
          if (!shared) {
            shared = chunk;
          } else if (!worker) {
            worker = chunk;
          } else {
            var workerBundleString = "var sharedChunk = {}; (" + shared + ")(sharedChunk); (" + worker + ")(sharedChunk);";
            var sharedChunk = {};
            shared(sharedChunk);
            mapboxgl = chunk(sharedChunk);
            if (typeof window !== "undefined") {
              mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: "text/javascript" }));
            }
          }
        }
        define2(["exports"], function(exports2) {
          "use strict";
          function createCommonjsModule(fn, module2) {
            return module2 = { exports: {} }, fn(module2, module2.exports), module2.exports;
          }
          var version = "1.13.4";
          var unitbezier = UnitBezier;
          function UnitBezier(p1x, p1y, p2x, p2y) {
            this.cx = 3 * p1x;
            this.bx = 3 * (p2x - p1x) - this.cx;
            this.ax = 1 - this.cx - this.bx;
            this.cy = 3 * p1y;
            this.by = 3 * (p2y - p1y) - this.cy;
            this.ay = 1 - this.cy - this.by;
            this.p1x = p1x;
            this.p1y = p2y;
            this.p2x = p2x;
            this.p2y = p2y;
          }
          UnitBezier.prototype.sampleCurveX = function(t) {
            return ((this.ax * t + this.bx) * t + this.cx) * t;
          };
          UnitBezier.prototype.sampleCurveY = function(t) {
            return ((this.ay * t + this.by) * t + this.cy) * t;
          };
          UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
            return (3 * this.ax * t + 2 * this.bx) * t + this.cx;
          };
          UnitBezier.prototype.solveCurveX = function(x, epsilon) {
            if (typeof epsilon === "undefined") {
              epsilon = 1e-6;
            }
            var t03, t13, t23, x2, i;
            for (t23 = x, i = 0; i < 8; i++) {
              x2 = this.sampleCurveX(t23) - x;
              if (Math.abs(x2) < epsilon) {
                return t23;
              }
              var d2 = this.sampleCurveDerivativeX(t23);
              if (Math.abs(d2) < 1e-6) {
                break;
              }
              t23 = t23 - x2 / d2;
            }
            t03 = 0;
            t13 = 1;
            t23 = x;
            if (t23 < t03) {
              return t03;
            }
            if (t23 > t13) {
              return t13;
            }
            while (t03 < t13) {
              x2 = this.sampleCurveX(t23);
              if (Math.abs(x2 - x) < epsilon) {
                return t23;
              }
              if (x > x2) {
                t03 = t23;
              } else {
                t13 = t23;
              }
              t23 = (t13 - t03) * 0.5 + t03;
            }
            return t23;
          };
          UnitBezier.prototype.solve = function(x, epsilon) {
            return this.sampleCurveY(this.solveCurveX(x, epsilon));
          };
          var pointGeometry = Point;
          function Point(x, y) {
            this.x = x;
            this.y = y;
          }
          Point.prototype = {
            clone: function() {
              return new Point(this.x, this.y);
            },
            add: function(p) {
              return this.clone()._add(p);
            },
            sub: function(p) {
              return this.clone()._sub(p);
            },
            multByPoint: function(p) {
              return this.clone()._multByPoint(p);
            },
            divByPoint: function(p) {
              return this.clone()._divByPoint(p);
            },
            mult: function(k) {
              return this.clone()._mult(k);
            },
            div: function(k) {
              return this.clone()._div(k);
            },
            rotate: function(a) {
              return this.clone()._rotate(a);
            },
            rotateAround: function(a, p) {
              return this.clone()._rotateAround(a, p);
            },
            matMult: function(m) {
              return this.clone()._matMult(m);
            },
            unit: function() {
              return this.clone()._unit();
            },
            perp: function() {
              return this.clone()._perp();
            },
            round: function() {
              return this.clone()._round();
            },
            mag: function() {
              return Math.sqrt(this.x * this.x + this.y * this.y);
            },
            equals: function(other) {
              return this.x === other.x && this.y === other.y;
            },
            dist: function(p) {
              return Math.sqrt(this.distSqr(p));
            },
            distSqr: function(p) {
              var dx = p.x - this.x, dy = p.y - this.y;
              return dx * dx + dy * dy;
            },
            angle: function() {
              return Math.atan2(this.y, this.x);
            },
            angleTo: function(b) {
              return Math.atan2(this.y - b.y, this.x - b.x);
            },
            angleWith: function(b) {
              return this.angleWithSep(b.x, b.y);
            },
            angleWithSep: function(x, y) {
              return Math.atan2(this.x * y - this.y * x, this.x * x + this.y * y);
            },
            _matMult: function(m) {
              var x = m[0] * this.x + m[1] * this.y, y = m[2] * this.x + m[3] * this.y;
              this.x = x;
              this.y = y;
              return this;
            },
            _add: function(p) {
              this.x += p.x;
              this.y += p.y;
              return this;
            },
            _sub: function(p) {
              this.x -= p.x;
              this.y -= p.y;
              return this;
            },
            _mult: function(k) {
              this.x *= k;
              this.y *= k;
              return this;
            },
            _div: function(k) {
              this.x /= k;
              this.y /= k;
              return this;
            },
            _multByPoint: function(p) {
              this.x *= p.x;
              this.y *= p.y;
              return this;
            },
            _divByPoint: function(p) {
              this.x /= p.x;
              this.y /= p.y;
              return this;
            },
            _unit: function() {
              this._div(this.mag());
              return this;
            },
            _perp: function() {
              var y = this.y;
              this.y = this.x;
              this.x = -y;
              return this;
            },
            _rotate: function(angle) {
              var cos = Math.cos(angle), sin = Math.sin(angle), x = cos * this.x - sin * this.y, y = sin * this.x + cos * this.y;
              this.x = x;
              this.y = y;
              return this;
            },
            _rotateAround: function(angle, p) {
              var cos = Math.cos(angle), sin = Math.sin(angle), x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y), y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);
              this.x = x;
              this.y = y;
              return this;
            },
            _round: function() {
              this.x = Math.round(this.x);
              this.y = Math.round(this.y);
              return this;
            }
          };
          Point.convert = function(a) {
            if (a instanceof Point) {
              return a;
            }
            if (Array.isArray(a)) {
              return new Point(a[0], a[1]);
            }
            return a;
          };
          var window$1 = typeof self !== "undefined" ? self : {};
          function deepEqual(a, b) {
            if (Array.isArray(a)) {
              if (!Array.isArray(b) || a.length !== b.length) {
                return false;
              }
              for (var i = 0; i < a.length; i++) {
                if (!deepEqual(a[i], b[i])) {
                  return false;
                }
              }
              return true;
            }
            if (typeof a === "object" && a !== null && b !== null) {
              if (!(typeof b === "object")) {
                return false;
              }
              var keys = Object.keys(a);
              if (keys.length !== Object.keys(b).length) {
                return false;
              }
              for (var key in a) {
                if (!deepEqual(a[key], b[key])) {
                  return false;
                }
              }
              return true;
            }
            return a === b;
          }
          var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
          function easeCubicInOut(t) {
            if (t <= 0) {
              return 0;
            }
            if (t >= 1) {
              return 1;
            }
            var t23 = t * t, t33 = t23 * t;
            return 4 * (t < 0.5 ? t33 : 3 * (t - t23) + t33 - 0.75);
          }
          function bezier(p1x, p1y, p2x, p2y) {
            var bezier2 = new unitbezier(p1x, p1y, p2x, p2y);
            return function(t) {
              return bezier2.solve(t);
            };
          }
          var ease = bezier(0.25, 0.1, 0.25, 1);
          function clamp(n, min, max) {
            return Math.min(max, Math.max(min, n));
          }
          function wrap(n, min, max) {
            var d = max - min;
            var w = ((n - min) % d + d) % d + min;
            return w === min ? max : w;
          }
          function asyncAll(array2, fn, callback) {
            if (!array2.length) {
              return callback(null, []);
            }
            var remaining = array2.length;
            var results = new Array(array2.length);
            var error2 = null;
            array2.forEach(function(item, i) {
              fn(item, function(err, result) {
                if (err) {
                  error2 = err;
                }
                results[i] = result;
                if (--remaining === 0) {
                  callback(error2, results);
                }
              });
            });
          }
          function values(obj) {
            var result = [];
            for (var k in obj) {
              result.push(obj[k]);
            }
            return result;
          }
          function keysDifference(obj, other) {
            var difference = [];
            for (var i in obj) {
              if (!(i in other)) {
                difference.push(i);
              }
            }
            return difference;
          }
          function extend2(dest) {
            var sources2 = [], len = arguments.length - 1;
            while (len-- > 0)
              sources2[len] = arguments[len + 1];
            for (var i = 0, list = sources2; i < list.length; i += 1) {
              var src = list[i];
              for (var k in src) {
                dest[k] = src[k];
              }
            }
            return dest;
          }
          function pick(src, properties2) {
            var result = {};
            for (var i = 0; i < properties2.length; i++) {
              var k = properties2[i];
              if (k in src) {
                result[k] = src[k];
              }
            }
            return result;
          }
          var id = 1;
          function uniqueId() {
            return id++;
          }
          function uuid() {
            function b(a) {
              return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : ([1e7] + -[1e3] + -4e3 + -8e3 + -1e11).replace(/[018]/g, b);
            }
            return b();
          }
          function nextPowerOfTwo(value) {
            if (value <= 1) {
              return 1;
            }
            return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
          }
          function validateUuid(str) {
            return str ? /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(str) : false;
          }
          function bindAll(fns, context) {
            fns.forEach(function(fn) {
              if (!context[fn]) {
                return;
              }
              context[fn] = context[fn].bind(context);
            });
          }
          function endsWith(string, suffix) {
            return string.indexOf(suffix, string.length - suffix.length) !== -1;
          }
          function mapObject(input, iterator, context) {
            var output = {};
            for (var key in input) {
              output[key] = iterator.call(context || this, input[key], key, input);
            }
            return output;
          }
          function filterObject(input, iterator, context) {
            var output = {};
            for (var key in input) {
              if (iterator.call(context || this, input[key], key, input)) {
                output[key] = input[key];
              }
            }
            return output;
          }
          function clone(input) {
            if (Array.isArray(input)) {
              return input.map(clone);
            } else if (typeof input === "object" && input) {
              return mapObject(input, clone);
            } else {
              return input;
            }
          }
          function arraysIntersect(a, b) {
            for (var l = 0; l < a.length; l++) {
              if (b.indexOf(a[l]) >= 0) {
                return true;
              }
            }
            return false;
          }
          var warnOnceHistory = {};
          function warnOnce(message) {
            if (!warnOnceHistory[message]) {
              if (typeof console !== "undefined") {
                console.warn(message);
              }
              warnOnceHistory[message] = true;
            }
          }
          function isCounterClockwise(a, b, c) {
            return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
          }
          function calculateSignedArea(ring) {
            var sum = 0;
            for (var i = 0, len = ring.length, j = len - 1, p1 = void 0, p2 = void 0; i < len; j = i++) {
              p1 = ring[i];
              p2 = ring[j];
              sum += (p2.x - p1.x) * (p1.y + p2.y);
            }
            return sum;
          }
          function sphericalToCartesian(ref) {
            var r = ref[0];
            var azimuthal = ref[1];
            var polar = ref[2];
            azimuthal += 90;
            azimuthal *= Math.PI / 180;
            polar *= Math.PI / 180;
            return {
              x: r * Math.cos(azimuthal) * Math.sin(polar),
              y: r * Math.sin(azimuthal) * Math.sin(polar),
              z: r * Math.cos(polar)
            };
          }
          function isWorker() {
            return typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope;
          }
          function parseCacheControl(cacheControl) {
            var re = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g;
            var header = {};
            cacheControl.replace(re, function($0, $1, $2, $3) {
              var value = $2 || $3;
              header[$1] = value ? value.toLowerCase() : true;
              return "";
            });
            if (header["max-age"]) {
              var maxAge = parseInt(header["max-age"], 10);
              if (isNaN(maxAge)) {
                delete header["max-age"];
              } else {
                header["max-age"] = maxAge;
              }
            }
            return header;
          }
          var _isSafari = null;
          function isSafari(scope) {
            if (_isSafari == null) {
              var userAgent = scope.navigator ? scope.navigator.userAgent : null;
              _isSafari = !!scope.safari || !!(userAgent && (/\b(iPad|iPhone|iPod)\b/.test(userAgent) || !!userAgent.match("Safari") && !userAgent.match("Chrome")));
            }
            return _isSafari;
          }
          function storageAvailable(type) {
            try {
              var storage = window$1[type];
              storage.setItem("_mapbox_test_", 1);
              storage.removeItem("_mapbox_test_");
              return true;
            } catch (e) {
              return false;
            }
          }
          function b64EncodeUnicode(str) {
            return window$1.btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
              return String.fromCharCode(Number("0x" + p1));
            }));
          }
          function b64DecodeUnicode(str) {
            return decodeURIComponent(window$1.atob(str).split("").map(function(c) {
              return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
            }).join(""));
          }
          var now = window$1.performance && window$1.performance.now ? window$1.performance.now.bind(window$1.performance) : Date.now.bind(Date);
          var raf = window$1.requestAnimationFrame || window$1.mozRequestAnimationFrame || window$1.webkitRequestAnimationFrame || window$1.msRequestAnimationFrame;
          var cancel = window$1.cancelAnimationFrame || window$1.mozCancelAnimationFrame || window$1.webkitCancelAnimationFrame || window$1.msCancelAnimationFrame;
          var linkEl;
          var reducedMotionQuery;
          var exported = {
            now,
            frame: function frame(fn) {
              var frame2 = raf(fn);
              return {
                cancel: function() {
                  return cancel(frame2);
                }
              };
            },
            getImageData: function getImageData(img, padding) {
              if (padding === void 0)
                padding = 0;
              var canvas = window$1.document.createElement("canvas");
              var context = canvas.getContext("2d");
              if (!context) {
                throw new Error("failed to create canvas 2d context");
              }
              canvas.width = img.width;
              canvas.height = img.height;
              context.drawImage(img, 0, 0, img.width, img.height);
              return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding);
            },
            resolveURL: function resolveURL(path) {
              if (!linkEl) {
                linkEl = window$1.document.createElement("a");
              }
              linkEl.href = path;
              return linkEl.href;
            },
            hardwareConcurrency: window$1.navigator && window$1.navigator.hardwareConcurrency || 4,
            get devicePixelRatio() {
              return window$1.devicePixelRatio;
            },
            get prefersReducedMotion() {
              if (!window$1.matchMedia) {
                return false;
              }
              if (reducedMotionQuery == null) {
                reducedMotionQuery = window$1.matchMedia("(prefers-reduced-motion: reduce)");
              }
              return reducedMotionQuery.matches;
            }
          };
          var config = {
            API_URL: "https://api.mapbox.com",
            get EVENTS_URL() {
              if (!this.API_URL) {
                return null;
              }
              if (this.API_URL.indexOf("https://api.mapbox.cn") === 0) {
                return "https://events.mapbox.cn/events/v2";
              } else if (this.API_URL.indexOf("https://api.mapbox.com") === 0) {
                return "https://events.mapbox.com/events/v2";
              } else {
                return null;
              }
            },
            FEEDBACK_URL: "https://apps.mapbox.com/feedback",
            REQUIRE_ACCESS_TOKEN: true,
            ACCESS_TOKEN: null,
            MAX_PARALLEL_IMAGE_REQUESTS: 16
          };
          var exported$1 = {
            supported: false,
            testSupport
          };
          var glForTesting;
          var webpCheckComplete = false;
          var webpImgTest;
          var webpImgTestOnloadComplete = false;
          if (window$1.document) {
            webpImgTest = window$1.document.createElement("img");
            webpImgTest.onload = function() {
              if (glForTesting) {
                testWebpTextureUpload(glForTesting);
              }
              glForTesting = null;
              webpImgTestOnloadComplete = true;
            };
            webpImgTest.onerror = function() {
              webpCheckComplete = true;
              glForTesting = null;
            };
            webpImgTest.src = "data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=";
          }
          function testSupport(gl2) {
            if (webpCheckComplete || !webpImgTest) {
              return;
            }
            if (webpImgTestOnloadComplete) {
              testWebpTextureUpload(gl2);
            } else {
              glForTesting = gl2;
            }
          }
          function testWebpTextureUpload(gl2) {
            var texture = gl2.createTexture();
            gl2.bindTexture(gl2.TEXTURE_2D, texture);
            try {
              gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, webpImgTest);
              if (gl2.isContextLost()) {
                return;
              }
              exported$1.supported = true;
            } catch (e) {
            }
            gl2.deleteTexture(texture);
            webpCheckComplete = true;
          }
          var SKU_ID = "01";
          function createSkuToken() {
            var TOKEN_VERSION = "1";
            var base62chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var sessionRandomizer = "";
            for (var i = 0; i < 10; i++) {
              sessionRandomizer += base62chars[Math.floor(Math.random() * 62)];
            }
            var expiration = 12 * 60 * 60 * 1e3;
            var token = [
              TOKEN_VERSION,
              SKU_ID,
              sessionRandomizer
            ].join("");
            var tokenExpiresAt = Date.now() + expiration;
            return {
              token,
              tokenExpiresAt
            };
          }
          var RequestManager = function RequestManager2(transformRequestFn, customAccessToken) {
            this._transformRequestFn = transformRequestFn;
            this._customAccessToken = customAccessToken;
            this._createSkuToken();
          };
          RequestManager.prototype._createSkuToken = function _createSkuToken() {
            var skuToken = createSkuToken();
            this._skuToken = skuToken.token;
            this._skuTokenExpiresAt = skuToken.tokenExpiresAt;
          };
          RequestManager.prototype._isSkuTokenExpired = function _isSkuTokenExpired() {
            return Date.now() > this._skuTokenExpiresAt;
          };
          RequestManager.prototype.transformRequest = function transformRequest(url, type) {
            if (this._transformRequestFn) {
              return this._transformRequestFn(url, type) || { url };
            }
            return { url };
          };
          RequestManager.prototype.normalizeStyleURL = function normalizeStyleURL(url, accessToken) {
            if (!isMapboxURL(url)) {
              return url;
            }
            var urlObject = parseUrl(url);
            urlObject.path = "/styles/v1" + urlObject.path;
            return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
          };
          RequestManager.prototype.normalizeGlyphsURL = function normalizeGlyphsURL(url, accessToken) {
            if (!isMapboxURL(url)) {
              return url;
            }
            var urlObject = parseUrl(url);
            urlObject.path = "/fonts/v1" + urlObject.path;
            return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
          };
          RequestManager.prototype.normalizeSourceURL = function normalizeSourceURL(url, accessToken) {
            if (!isMapboxURL(url)) {
              return url;
            }
            var urlObject = parseUrl(url);
            urlObject.path = "/v4/" + urlObject.authority + ".json";
            urlObject.params.push("secure");
            return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
          };
          RequestManager.prototype.normalizeSpriteURL = function normalizeSpriteURL(url, format, extension, accessToken) {
            var urlObject = parseUrl(url);
            if (!isMapboxURL(url)) {
              urlObject.path += "" + format + extension;
              return formatUrl(urlObject);
            }
            urlObject.path = "/styles/v1" + urlObject.path + "/sprite" + format + extension;
            return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);
          };
          RequestManager.prototype.normalizeTileURL = function normalizeTileURL(tileURL, tileSize) {
            if (this._isSkuTokenExpired()) {
              this._createSkuToken();
            }
            if (tileURL && !isMapboxURL(tileURL)) {
              return tileURL;
            }
            var urlObject = parseUrl(tileURL);
            var imageExtensionRe = /(\.(png|jpg)\d*)(?=$)/;
            var tileURLAPIPrefixRe = /^.+\/v4\//;
            var suffix = exported.devicePixelRatio >= 2 || tileSize === 512 ? "@2x" : "";
            var extension = exported$1.supported ? ".webp" : "$1";
            urlObject.path = urlObject.path.replace(imageExtensionRe, "" + suffix + extension);
            urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, "/");
            urlObject.path = "/v4" + urlObject.path;
            var accessToken = this._customAccessToken || getAccessToken(urlObject.params) || config.ACCESS_TOKEN;
            if (config.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) {
              urlObject.params.push("sku=" + this._skuToken);
            }
            return this._makeAPIURL(urlObject, accessToken);
          };
          RequestManager.prototype.canonicalizeTileURL = function canonicalizeTileURL(url, removeAccessToken) {
            var version2 = "/v4/";
            var extensionRe = /\.[\w]+$/;
            var urlObject = parseUrl(url);
            if (!urlObject.path.match(/(^\/v4\/)/) || !urlObject.path.match(extensionRe)) {
              return url;
            }
            var result = "mapbox://tiles/";
            result += urlObject.path.replace(version2, "");
            var params = urlObject.params;
            if (removeAccessToken) {
              params = params.filter(function(p) {
                return !p.match(/^access_token=/);
              });
            }
            if (params.length) {
              result += "?" + params.join("&");
            }
            return result;
          };
          RequestManager.prototype.canonicalizeTileset = function canonicalizeTileset(tileJSON, sourceURL) {
            var removeAccessToken = sourceURL ? isMapboxURL(sourceURL) : false;
            var canonical = [];
            for (var i = 0, list = tileJSON.tiles || []; i < list.length; i += 1) {
              var url = list[i];
              if (isMapboxHTTPURL(url)) {
                canonical.push(this.canonicalizeTileURL(url, removeAccessToken));
              } else {
                canonical.push(url);
              }
            }
            return canonical;
          };
          RequestManager.prototype._makeAPIURL = function _makeAPIURL(urlObject, accessToken) {
            var help = "See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes";
            var apiUrlObject = parseUrl(config.API_URL);
            urlObject.protocol = apiUrlObject.protocol;
            urlObject.authority = apiUrlObject.authority;
            if (urlObject.protocol === "http") {
              var i = urlObject.params.indexOf("secure");
              if (i >= 0) {
                urlObject.params.splice(i, 1);
              }
            }
            if (apiUrlObject.path !== "/") {
              urlObject.path = "" + apiUrlObject.path + urlObject.path;
            }
            if (!config.REQUIRE_ACCESS_TOKEN) {
              return formatUrl(urlObject);
            }
            accessToken = accessToken || config.ACCESS_TOKEN;
            if (!accessToken) {
              throw new Error("An API access token is required to use Mapbox GL. " + help);
            }
            if (accessToken[0] === "s") {
              throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). " + help);
            }
            urlObject.params = urlObject.params.filter(function(d) {
              return d.indexOf("access_token") === -1;
            });
            urlObject.params.push("access_token=" + accessToken);
            return formatUrl(urlObject);
          };
          function isMapboxURL(url) {
            return url.indexOf("mapbox:") === 0;
          }
          var mapboxHTTPURLRe = /^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i;
          function isMapboxHTTPURL(url) {
            return mapboxHTTPURLRe.test(url);
          }
          function hasCacheDefeatingSku(url) {
            return url.indexOf("sku=") > 0 && isMapboxHTTPURL(url);
          }
          function getAccessToken(params) {
            for (var i = 0, list = params; i < list.length; i += 1) {
              var param = list[i];
              var match = param.match(/^access_token=(.*)$/);
              if (match) {
                return match[1];
              }
            }
            return null;
          }
          var urlRe = /^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;
          function parseUrl(url) {
            var parts = url.match(urlRe);
            if (!parts) {
              throw new Error("Unable to parse URL object");
            }
            return {
              protocol: parts[1],
              authority: parts[2],
              path: parts[3] || "/",
              params: parts[4] ? parts[4].split("&") : []
            };
          }
          function formatUrl(obj) {
            var params = obj.params.length ? "?" + obj.params.join("&") : "";
            return obj.protocol + "://" + obj.authority + obj.path + params;
          }
          var telemEventKey = "mapbox.eventData";
          function parseAccessToken(accessToken) {
            if (!accessToken) {
              return null;
            }
            var parts = accessToken.split(".");
            if (!parts || parts.length !== 3) {
              return null;
            }
            try {
              var jsonData = JSON.parse(b64DecodeUnicode(parts[1]));
              return jsonData;
            } catch (e) {
              return null;
            }
          }
          var TelemetryEvent = function TelemetryEvent2(type) {
            this.type = type;
            this.anonId = null;
            this.eventData = {};
            this.queue = [];
            this.pendingRequest = null;
          };
          TelemetryEvent.prototype.getStorageKey = function getStorageKey(domain) {
            var tokenData = parseAccessToken(config.ACCESS_TOKEN);
            var u = "";
            if (tokenData && tokenData["u"]) {
              u = b64EncodeUnicode(tokenData["u"]);
            } else {
              u = config.ACCESS_TOKEN || "";
            }
            return domain ? telemEventKey + "." + domain + ":" + u : telemEventKey + ":" + u;
          };
          TelemetryEvent.prototype.fetchEventData = function fetchEventData() {
            var isLocalStorageAvailable = storageAvailable("localStorage");
            var storageKey = this.getStorageKey();
            var uuidKey = this.getStorageKey("uuid");
            if (isLocalStorageAvailable) {
              try {
                var data = window$1.localStorage.getItem(storageKey);
                if (data) {
                  this.eventData = JSON.parse(data);
                }
                var uuid2 = window$1.localStorage.getItem(uuidKey);
                if (uuid2) {
                  this.anonId = uuid2;
                }
              } catch (e) {
                warnOnce("Unable to read from LocalStorage");
              }
            }
          };
          TelemetryEvent.prototype.saveEventData = function saveEventData() {
            var isLocalStorageAvailable = storageAvailable("localStorage");
            var storageKey = this.getStorageKey();
            var uuidKey = this.getStorageKey("uuid");
            if (isLocalStorageAvailable) {
              try {
                window$1.localStorage.setItem(uuidKey, this.anonId);
                if (Object.keys(this.eventData).length >= 1) {
                  window$1.localStorage.setItem(storageKey, JSON.stringify(this.eventData));
                }
              } catch (e) {
                warnOnce("Unable to write to LocalStorage");
              }
            }
          };
          TelemetryEvent.prototype.processRequests = function processRequests(_) {
          };
          TelemetryEvent.prototype.postEvent = function postEvent(timestamp, additionalPayload, callback, customAccessToken) {
            var this$1 = this;
            if (!config.EVENTS_URL) {
              return;
            }
            var eventsUrlObject = parseUrl(config.EVENTS_URL);
            eventsUrlObject.params.push("access_token=" + (customAccessToken || config.ACCESS_TOKEN || ""));
            var payload = {
              event: this.type,
              created: new Date(timestamp).toISOString(),
              sdkIdentifier: "mapbox-gl-js",
              sdkVersion: version,
              skuId: SKU_ID,
              userId: this.anonId
            };
            var finalPayload = additionalPayload ? extend2(payload, additionalPayload) : payload;
            var request = {
              url: formatUrl(eventsUrlObject),
              headers: { "Content-Type": "text/plain" },
              body: JSON.stringify([finalPayload])
            };
            this.pendingRequest = postData(request, function(error2) {
              this$1.pendingRequest = null;
              callback(error2);
              this$1.saveEventData();
              this$1.processRequests(customAccessToken);
            });
          };
          TelemetryEvent.prototype.queueRequest = function queueRequest(event, customAccessToken) {
            this.queue.push(event);
            this.processRequests(customAccessToken);
          };
          var MapLoadEvent = function(TelemetryEvent2) {
            function MapLoadEvent2() {
              TelemetryEvent2.call(this, "map.load");
              this.success = {};
              this.skuToken = "";
            }
            if (TelemetryEvent2)
              MapLoadEvent2.__proto__ = TelemetryEvent2;
            MapLoadEvent2.prototype = Object.create(TelemetryEvent2 && TelemetryEvent2.prototype);
            MapLoadEvent2.prototype.constructor = MapLoadEvent2;
            MapLoadEvent2.prototype.postMapLoadEvent = function postMapLoadEvent2(tileUrls, mapId, skuToken, customAccessToken) {
              this.skuToken = skuToken;
              if (config.EVENTS_URL && customAccessToken || config.ACCESS_TOKEN && Array.isArray(tileUrls) && tileUrls.some(function(url) {
                return isMapboxURL(url) || isMapboxHTTPURL(url);
              })) {
                this.queueRequest({
                  id: mapId,
                  timestamp: Date.now()
                }, customAccessToken);
              }
            };
            MapLoadEvent2.prototype.processRequests = function processRequests(customAccessToken) {
              var this$1 = this;
              if (this.pendingRequest || this.queue.length === 0) {
                return;
              }
              var ref = this.queue.shift();
              var id2 = ref.id;
              var timestamp = ref.timestamp;
              if (id2 && this.success[id2]) {
                return;
              }
              if (!this.anonId) {
                this.fetchEventData();
              }
              if (!validateUuid(this.anonId)) {
                this.anonId = uuid();
              }
              this.postEvent(timestamp, { skuToken: this.skuToken }, function(err) {
                if (!err) {
                  if (id2) {
                    this$1.success[id2] = true;
                  }
                }
              }, customAccessToken);
            };
            return MapLoadEvent2;
          }(TelemetryEvent);
          var TurnstileEvent = function(TelemetryEvent2) {
            function TurnstileEvent2(customAccessToken) {
              TelemetryEvent2.call(this, "appUserTurnstile");
              this._customAccessToken = customAccessToken;
            }
            if (TelemetryEvent2)
              TurnstileEvent2.__proto__ = TelemetryEvent2;
            TurnstileEvent2.prototype = Object.create(TelemetryEvent2 && TelemetryEvent2.prototype);
            TurnstileEvent2.prototype.constructor = TurnstileEvent2;
            TurnstileEvent2.prototype.postTurnstileEvent = function postTurnstileEvent2(tileUrls, customAccessToken) {
              if (config.EVENTS_URL && config.ACCESS_TOKEN && Array.isArray(tileUrls) && tileUrls.some(function(url) {
                return isMapboxURL(url) || isMapboxHTTPURL(url);
              })) {
                this.queueRequest(Date.now(), customAccessToken);
              }
            };
            TurnstileEvent2.prototype.processRequests = function processRequests(customAccessToken) {
              var this$1 = this;
              if (this.pendingRequest || this.queue.length === 0) {
                return;
              }
              if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) {
                this.fetchEventData();
              }
              var tokenData = parseAccessToken(config.ACCESS_TOKEN);
              var tokenU = tokenData ? tokenData["u"] : config.ACCESS_TOKEN;
              var dueForEvent = tokenU !== this.eventData.tokenU;
              if (!validateUuid(this.anonId)) {
                this.anonId = uuid();
                dueForEvent = true;
              }
              var nextUpdate = this.queue.shift();
              if (this.eventData.lastSuccess) {
                var lastUpdate = new Date(this.eventData.lastSuccess);
                var nextDate = new Date(nextUpdate);
                var daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1e3);
                dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate();
              } else {
                dueForEvent = true;
              }
              if (!dueForEvent) {
                return this.processRequests();
              }
              this.postEvent(nextUpdate, { "enabled.telemetry": false }, function(err) {
                if (!err) {
                  this$1.eventData.lastSuccess = nextUpdate;
                  this$1.eventData.tokenU = tokenU;
                }
              }, customAccessToken);
            };
            return TurnstileEvent2;
          }(TelemetryEvent);
          var turnstileEvent_ = new TurnstileEvent();
          var postTurnstileEvent = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_);
          var mapLoadEvent_ = new MapLoadEvent();
          var postMapLoadEvent = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_);
          var CACHE_NAME = "mapbox-tiles";
          var cacheLimit = 500;
          var cacheCheckThreshold = 50;
          var MIN_TIME_UNTIL_EXPIRY = 1e3 * 60 * 7;
          var sharedCache;
          function cacheOpen() {
            if (window$1.caches && !sharedCache) {
              sharedCache = window$1.caches.open(CACHE_NAME);
            }
          }
          var responseConstructorSupportsReadableStream;
          function prepareBody(response, callback) {
            if (responseConstructorSupportsReadableStream === void 0) {
              try {
                new Response(new ReadableStream());
                responseConstructorSupportsReadableStream = true;
              } catch (e) {
                responseConstructorSupportsReadableStream = false;
              }
            }
            if (responseConstructorSupportsReadableStream) {
              callback(response.body);
            } else {
              response.blob().then(callback);
            }
          }
          function cachePut(request, response, requestTime) {
            cacheOpen();
            if (!sharedCache) {
              return;
            }
            var options = {
              status: response.status,
              statusText: response.statusText,
              headers: new window$1.Headers()
            };
            response.headers.forEach(function(v, k) {
              return options.headers.set(k, v);
            });
            var cacheControl = parseCacheControl(response.headers.get("Cache-Control") || "");
            if (cacheControl["no-store"]) {
              return;
            }
            if (cacheControl["max-age"]) {
              options.headers.set("Expires", new Date(requestTime + cacheControl["max-age"] * 1e3).toUTCString());
            }
            var timeUntilExpiry = new Date(options.headers.get("Expires")).getTime() - requestTime;
            if (timeUntilExpiry < MIN_TIME_UNTIL_EXPIRY) {
              return;
            }
            prepareBody(response, function(body) {
              var clonedResponse = new window$1.Response(body, options);
              cacheOpen();
              if (!sharedCache) {
                return;
              }
              sharedCache.then(function(cache) {
                return cache.put(stripQueryParameters(request.url), clonedResponse);
              }).catch(function(e) {
                return warnOnce(e.message);
              });
            });
          }
          function stripQueryParameters(url) {
            var start = url.indexOf("?");
            return start < 0 ? url : url.slice(0, start);
          }
          function cacheGet(request, callback) {
            cacheOpen();
            if (!sharedCache) {
              return callback(null);
            }
            var strippedURL = stripQueryParameters(request.url);
            sharedCache.then(function(cache) {
              cache.match(strippedURL).then(function(response) {
                var fresh = isFresh(response);
                cache.delete(strippedURL);
                if (fresh) {
                  cache.put(strippedURL, response.clone());
                }
                callback(null, response, fresh);
              }).catch(callback);
            }).catch(callback);
          }
          function isFresh(response) {
            if (!response) {
              return false;
            }
            var expires = new Date(response.headers.get("Expires") || 0);
            var cacheControl = parseCacheControl(response.headers.get("Cache-Control") || "");
            return expires > Date.now() && !cacheControl["no-cache"];
          }
          var globalEntryCounter = Infinity;
          function cacheEntryPossiblyAdded(dispatcher) {
            globalEntryCounter++;
            if (globalEntryCounter > cacheCheckThreshold) {
              dispatcher.getActor().send("enforceCacheSizeLimit", cacheLimit);
              globalEntryCounter = 0;
            }
          }
          function enforceCacheSizeLimit(limit) {
            cacheOpen();
            if (!sharedCache) {
              return;
            }
            sharedCache.then(function(cache) {
              cache.keys().then(function(keys) {
                for (var i = 0; i < keys.length - limit; i++) {
                  cache.delete(keys[i]);
                }
              });
            });
          }
          function clearTileCache(callback) {
            var promise = window$1.caches.delete(CACHE_NAME);
            if (callback) {
              promise.catch(callback).then(function() {
                return callback();
              });
            }
          }
          function setCacheLimits(limit, checkThreshold) {
            cacheLimit = limit;
            cacheCheckThreshold = checkThreshold;
          }
          var supportsOffscreenCanvas;
          function offscreenCanvasSupported() {
            if (supportsOffscreenCanvas == null) {
              supportsOffscreenCanvas = window$1.OffscreenCanvas && new window$1.OffscreenCanvas(1, 1).getContext("2d") && typeof window$1.createImageBitmap === "function";
            }
            return supportsOffscreenCanvas;
          }
          var ResourceType = {
            Unknown: "Unknown",
            Style: "Style",
            Source: "Source",
            Tile: "Tile",
            Glyphs: "Glyphs",
            SpriteImage: "SpriteImage",
            SpriteJSON: "SpriteJSON",
            Image: "Image"
          };
          if (typeof Object.freeze == "function") {
            Object.freeze(ResourceType);
          }
          var AJAXError = function(Error2) {
            function AJAXError2(message, status2, url) {
              if (status2 === 401 && isMapboxHTTPURL(url)) {
                message += ": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes";
              }
              Error2.call(this, message);
              this.status = status2;
              this.url = url;
              this.name = this.constructor.name;
              this.message = message;
            }
            if (Error2)
              AJAXError2.__proto__ = Error2;
            AJAXError2.prototype = Object.create(Error2 && Error2.prototype);
            AJAXError2.prototype.constructor = AJAXError2;
            AJAXError2.prototype.toString = function toString2() {
              return this.name + ": " + this.message + " (" + this.status + "): " + this.url;
            };
            return AJAXError2;
          }(Error);
          var getReferrer = isWorker() ? function() {
            return self.worker && self.worker.referrer;
          } : function() {
            return (window$1.location.protocol === "blob:" ? window$1.parent : window$1).location.href;
          };
          var isFileURL = function(url) {
            return /^file:/.test(url) || /^file:/.test(getReferrer()) && !/^\w+:/.test(url);
          };
          function makeFetchRequest(requestParameters, callback) {
            var controller = new window$1.AbortController();
            var request = new window$1.Request(requestParameters.url, {
              method: requestParameters.method || "GET",
              body: requestParameters.body,
              credentials: requestParameters.credentials,
              headers: requestParameters.headers,
              referrer: getReferrer(),
              signal: controller.signal
            });
            var complete = false;
            var aborted = false;
            var cacheIgnoringSearch = hasCacheDefeatingSku(request.url);
            if (requestParameters.type === "json") {
              request.headers.set("Accept", "application/json");
            }
            var validateOrFetch = function(err, cachedResponse, responseIsFresh) {
              if (aborted) {
                return;
              }
              if (err) {
                if (err.message !== "SecurityError") {
                  warnOnce(err);
                }
              }
              if (cachedResponse && responseIsFresh) {
                return finishRequest(cachedResponse);
              }
              var requestTime = Date.now();
              window$1.fetch(request).then(function(response) {
                if (response.ok) {
                  var cacheableResponse = cacheIgnoringSearch ? response.clone() : null;
                  return finishRequest(response, cacheableResponse, requestTime);
                } else {
                  return callback(new AJAXError(response.statusText, response.status, requestParameters.url));
                }
              }).catch(function(error2) {
                if (error2.code === 20) {
                  return;
                }
                callback(new Error(error2.message));
              });
            };
            var finishRequest = function(response, cacheableResponse, requestTime) {
              (requestParameters.type === "arrayBuffer" ? response.arrayBuffer() : requestParameters.type === "json" ? response.json() : response.text()).then(function(result) {
                if (aborted) {
                  return;
                }
                if (cacheableResponse && requestTime) {
                  cachePut(request, cacheableResponse, requestTime);
                }
                complete = true;
                callback(null, result, response.headers.get("Cache-Control"), response.headers.get("Expires"));
              }).catch(function(err) {
                if (!aborted) {
                  callback(new Error(err.message));
                }
              });
            };
            if (cacheIgnoringSearch) {
              cacheGet(request, validateOrFetch);
            } else {
              validateOrFetch(null, null);
            }
            return {
              cancel: function() {
                aborted = true;
                if (!complete) {
                  controller.abort();
                }
              }
            };
          }
          function makeXMLHttpRequest(requestParameters, callback) {
            var xhr = new window$1.XMLHttpRequest();
            xhr.open(requestParameters.method || "GET", requestParameters.url, true);
            if (requestParameters.type === "arrayBuffer") {
              xhr.responseType = "arraybuffer";
            }
            for (var k in requestParameters.headers) {
              xhr.setRequestHeader(k, requestParameters.headers[k]);
            }
            if (requestParameters.type === "json") {
              xhr.responseType = "text";
              xhr.setRequestHeader("Accept", "application/json");
            }
            xhr.withCredentials = requestParameters.credentials === "include";
            xhr.onerror = function() {
              callback(new Error(xhr.statusText));
            };
            xhr.onload = function() {
              if ((xhr.status >= 200 && xhr.status < 300 || xhr.status === 0) && xhr.response !== null) {
                var data = xhr.response;
                if (requestParameters.type === "json") {
                  try {
                    data = JSON.parse(xhr.response);
                  } catch (err) {
                    return callback(err);
                  }
                }
                callback(null, data, xhr.getResponseHeader("Cache-Control"), xhr.getResponseHeader("Expires"));
              } else {
                callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));
              }
            };
            xhr.send(requestParameters.body);
            return {
              cancel: function() {
                return xhr.abort();
              }
            };
          }
          var makeRequest = function(requestParameters, callback) {
            if (!isFileURL(requestParameters.url)) {
              if (window$1.fetch && window$1.Request && window$1.AbortController && window$1.Request.prototype.hasOwnProperty("signal")) {
                return makeFetchRequest(requestParameters, callback);
              }
              if (isWorker() && self.worker && self.worker.actor) {
                var queueOnMainThread = true;
                return self.worker.actor.send("getResource", requestParameters, callback, void 0, queueOnMainThread);
              }
            }
            return makeXMLHttpRequest(requestParameters, callback);
          };
          var getJSON = function(requestParameters, callback) {
            return makeRequest(extend2(requestParameters, { type: "json" }), callback);
          };
          var getArrayBuffer = function(requestParameters, callback) {
            return makeRequest(extend2(requestParameters, { type: "arrayBuffer" }), callback);
          };
          var postData = function(requestParameters, callback) {
            return makeRequest(extend2(requestParameters, { method: "POST" }), callback);
          };
          function sameOrigin(url) {
            var a = window$1.document.createElement("a");
            a.href = url;
            return a.protocol === window$1.document.location.protocol && a.host === window$1.document.location.host;
          }
          var transparentPngUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";
          function arrayBufferToImage(data, callback, cacheControl, expires) {
            var img = new window$1.Image();
            var URL2 = window$1.URL;
            img.onload = function() {
              callback(null, img);
              URL2.revokeObjectURL(img.src);
              img.onload = null;
              window$1.requestAnimationFrame(function() {
                img.src = transparentPngUrl;
              });
            };
            img.onerror = function() {
              return callback(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));
            };
            var blob = new window$1.Blob([new Uint8Array(data)], { type: "image/png" });
            img.cacheControl = cacheControl;
            img.expires = expires;
            img.src = data.byteLength ? URL2.createObjectURL(blob) : transparentPngUrl;
          }
          function arrayBufferToImageBitmap(data, callback) {
            var blob = new window$1.Blob([new Uint8Array(data)], { type: "image/png" });
            window$1.createImageBitmap(blob).then(function(imgBitmap) {
              callback(null, imgBitmap);
            }).catch(function(e) {
              callback(new Error("Could not load image because of " + e.message + ". Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));
            });
          }
          var imageQueue, numImageRequests;
          var resetImageRequestQueue = function() {
            imageQueue = [];
            numImageRequests = 0;
          };
          resetImageRequestQueue();
          var getImage = function(requestParameters, callback) {
            if (exported$1.supported) {
              if (!requestParameters.headers) {
                requestParameters.headers = {};
              }
              requestParameters.headers.accept = "image/webp,*/*";
            }
            if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) {
              var queued = {
                requestParameters,
                callback,
                cancelled: false,
                cancel: function cancel2() {
                  this.cancelled = true;
                }
              };
              imageQueue.push(queued);
              return queued;
            }
            numImageRequests++;
            var advanced = false;
            var advanceImageRequestQueue = function() {
              if (advanced) {
                return;
              }
              advanced = true;
              numImageRequests--;
              while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) {
                var request2 = imageQueue.shift();
                var requestParameters2 = request2.requestParameters;
                var callback2 = request2.callback;
                var cancelled = request2.cancelled;
                if (!cancelled) {
                  request2.cancel = getImage(requestParameters2, callback2).cancel;
                }
              }
            };
            var request = getArrayBuffer(requestParameters, function(err, data, cacheControl, expires) {
              advanceImageRequestQueue();
              if (err) {
                callback(err);
              } else if (data) {
                if (offscreenCanvasSupported()) {
                  arrayBufferToImageBitmap(data, callback);
                } else {
                  arrayBufferToImage(data, callback, cacheControl, expires);
                }
              }
            });
            return {
              cancel: function() {
                request.cancel();
                advanceImageRequestQueue();
              }
            };
          };
          var getVideo = function(urls, callback) {
            var video = window$1.document.createElement("video");
            video.muted = true;
            video.onloadstart = function() {
              callback(null, video);
            };
            for (var i = 0; i < urls.length; i++) {
              var s = window$1.document.createElement("source");
              if (!sameOrigin(urls[i])) {
                video.crossOrigin = "Anonymous";
              }
              s.src = urls[i];
              video.appendChild(s);
            }
            return {
              cancel: function() {
              }
            };
          };
          function _addEventListener(type, listener, listenerList) {
            var listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1;
            if (!listenerExists) {
              listenerList[type] = listenerList[type] || [];
              listenerList[type].push(listener);
            }
          }
          function _removeEventListener(type, listener, listenerList) {
            if (listenerList && listenerList[type]) {
              var index = listenerList[type].indexOf(listener);
              if (index !== -1) {
                listenerList[type].splice(index, 1);
              }
            }
          }
          var Event = function Event2(type, data) {
            if (data === void 0)
              data = {};
            extend2(this, data);
            this.type = type;
          };
          var ErrorEvent = function(Event2) {
            function ErrorEvent2(error2, data) {
              if (data === void 0)
                data = {};
              Event2.call(this, "error", extend2({ error: error2 }, data));
            }
            if (Event2)
              ErrorEvent2.__proto__ = Event2;
            ErrorEvent2.prototype = Object.create(Event2 && Event2.prototype);
            ErrorEvent2.prototype.constructor = ErrorEvent2;
            return ErrorEvent2;
          }(Event);
          var Evented = function Evented2() {
          };
          Evented.prototype.on = function on(type, listener) {
            this._listeners = this._listeners || {};
            _addEventListener(type, listener, this._listeners);
            return this;
          };
          Evented.prototype.off = function off(type, listener) {
            _removeEventListener(type, listener, this._listeners);
            _removeEventListener(type, listener, this._oneTimeListeners);
            return this;
          };
          Evented.prototype.once = function once(type, listener) {
            this._oneTimeListeners = this._oneTimeListeners || {};
            _addEventListener(type, listener, this._oneTimeListeners);
            return this;
          };
          Evented.prototype.fire = function fire(event, properties2) {
            if (typeof event === "string") {
              event = new Event(event, properties2 || {});
            }
            var type = event.type;
            if (this.listens(type)) {
              event.target = this;
              var listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : [];
              for (var i = 0, list = listeners; i < list.length; i += 1) {
                var listener = list[i];
                listener.call(this, event);
              }
              var oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : [];
              for (var i$1 = 0, list$1 = oneTimeListeners; i$1 < list$1.length; i$1 += 1) {
                var listener$1 = list$1[i$1];
                _removeEventListener(type, listener$1, this._oneTimeListeners);
                listener$1.call(this, event);
              }
              var parent = this._eventedParent;
              if (parent) {
                extend2(event, typeof this._eventedParentData === "function" ? this._eventedParentData() : this._eventedParentData);
                parent.fire(event);
              }
            } else if (event instanceof ErrorEvent) {
              console.error(event.error);
            }
            return this;
          };
          Evented.prototype.listens = function listens(type) {
            return this._listeners && this._listeners[type] && this._listeners[type].length > 0 || this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0 || this._eventedParent && this._eventedParent.listens(type);
          };
          Evented.prototype.setEventedParent = function setEventedParent(parent, data) {
            this._eventedParent = parent;
            this._eventedParentData = data;
            return this;
          };
          var $version = 8;
          var $root = {
            version: {
              required: true,
              type: "enum",
              values: [
                8
              ]
            },
            name: {
              type: "string"
            },
            metadata: {
              type: "*"
            },
            center: {
              type: "array",
              value: "number"
            },
            zoom: {
              type: "number"
            },
            bearing: {
              type: "number",
              "default": 0,
              period: 360,
              units: "degrees"
            },
            pitch: {
              type: "number",
              "default": 0,
              units: "degrees"
            },
            light: {
              type: "light"
            },
            sources: {
              required: true,
              type: "sources"
            },
            sprite: {
              type: "string"
            },
            glyphs: {
              type: "string"
            },
            transition: {
              type: "transition"
            },
            layers: {
              required: true,
              type: "array",
              value: "layer"
            }
          };
          var sources = {
            "*": {
              type: "source"
            }
          };
          var source = [
            "source_vector",
            "source_raster",
            "source_raster_dem",
            "source_geojson",
            "source_video",
            "source_image"
          ];
          var source_vector = {
            type: {
              required: true,
              type: "enum",
              values: {
                vector: {}
              }
            },
            url: {
              type: "string"
            },
            tiles: {
              type: "array",
              value: "string"
            },
            bounds: {
              type: "array",
              value: "number",
              length: 4,
              "default": [
                -180,
                -85.051129,
                180,
                85.051129
              ]
            },
            scheme: {
              type: "enum",
              values: {
                xyz: {},
                tms: {}
              },
              "default": "xyz"
            },
            minzoom: {
              type: "number",
              "default": 0
            },
            maxzoom: {
              type: "number",
              "default": 22
            },
            attribution: {
              type: "string"
            },
            promoteId: {
              type: "promoteId"
            },
            volatile: {
              type: "boolean",
              "default": false
            },
            "*": {
              type: "*"
            }
          };
          var source_raster = {
            type: {
              required: true,
              type: "enum",
              values: {
                raster: {}
              }
            },
            url: {
              type: "string"
            },
            tiles: {
              type: "array",
              value: "string"
            },
            bounds: {
              type: "array",
              value: "number",
              length: 4,
              "default": [
                -180,
                -85.051129,
                180,
                85.051129
              ]
            },
            minzoom: {
              type: "number",
              "default": 0
            },
            maxzoom: {
              type: "number",
              "default": 22
            },
            tileSize: {
              type: "number",
              "default": 512,
              units: "pixels"
            },
            scheme: {
              type: "enum",
              values: {
                xyz: {},
                tms: {}
              },
              "default": "xyz"
            },
            attribution: {
              type: "string"
            },
            volatile: {
              type: "boolean",
              "default": false
            },
            "*": {
              type: "*"
            }
          };
          var source_raster_dem = {
            type: {
              required: true,
              type: "enum",
              values: {
                "raster-dem": {}
              }
            },
            url: {
              type: "string"
            },
            tiles: {
              type: "array",
              value: "string"
            },
            bounds: {
              type: "array",
              value: "number",
              length: 4,
              "default": [
                -180,
                -85.051129,
                180,
                85.051129
              ]
            },
            minzoom: {
              type: "number",
              "default": 0
            },
            maxzoom: {
              type: "number",
              "default": 22
            },
            tileSize: {
              type: "number",
              "default": 512,
              units: "pixels"
            },
            attribution: {
              type: "string"
            },
            encoding: {
              type: "enum",
              values: {
                terrarium: {},
                mapbox: {}
              },
              "default": "mapbox"
            },
            volatile: {
              type: "boolean",
              "default": false
            },
            "*": {
              type: "*"
            }
          };
          var source_geojson = {
            type: {
              required: true,
              type: "enum",
              values: {
                geojson: {}
              }
            },
            data: {
              type: "*"
            },
            maxzoom: {
              type: "number",
              "default": 18
            },
            attribution: {
              type: "string"
            },
            buffer: {
              type: "number",
              "default": 128,
              maximum: 512,
              minimum: 0
            },
            filter: {
              type: "*"
            },
            tolerance: {
              type: "number",
              "default": 0.375
            },
            cluster: {
              type: "boolean",
              "default": false
            },
            clusterRadius: {
              type: "number",
              "default": 50,
              minimum: 0
            },
            clusterMaxZoom: {
              type: "number"
            },
            clusterMinPoints: {
              type: "number"
            },
            clusterProperties: {
              type: "*"
            },
            lineMetrics: {
              type: "boolean",
              "default": false
            },
            generateId: {
              type: "boolean",
              "default": false
            },
            promoteId: {
              type: "promoteId"
            }
          };
          var source_video = {
            type: {
              required: true,
              type: "enum",
              values: {
                video: {}
              }
            },
            urls: {
              required: true,
              type: "array",
              value: "string"
            },
            coordinates: {
              required: true,
              type: "array",
              length: 4,
              value: {
                type: "array",
                length: 2,
                value: "number"
              }
            }
          };
          var source_image = {
            type: {
              required: true,
              type: "enum",
              values: {
                image: {}
              }
            },
            url: {
              required: true,
              type: "string"
            },
            coordinates: {
              required: true,
              type: "array",
              length: 4,
              value: {
                type: "array",
                length: 2,
                value: "number"
              }
            }
          };
          var layer = {
            id: {
              type: "string",
              required: true
            },
            type: {
              type: "enum",
              values: {
                fill: {},
                line: {},
                symbol: {},
                circle: {},
                heatmap: {},
                "fill-extrusion": {},
                raster: {},
                hillshade: {},
                background: {}
              },
              required: true
            },
            metadata: {
              type: "*"
            },
            source: {
              type: "string"
            },
            "source-layer": {
              type: "string"
            },
            minzoom: {
              type: "number",
              minimum: 0,
              maximum: 24
            },
            maxzoom: {
              type: "number",
              minimum: 0,
              maximum: 24
            },
            filter: {
              type: "filter"
            },
            layout: {
              type: "layout"
            },
            paint: {
              type: "paint"
            }
          };
          var layout = [
            "layout_fill",
            "layout_line",
            "layout_circle",
            "layout_heatmap",
            "layout_fill-extrusion",
            "layout_symbol",
            "layout_raster",
            "layout_hillshade",
            "layout_background"
          ];
          var layout_background = {
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var layout_fill = {
            "fill-sort-key": {
              type: "number",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var layout_circle = {
            "circle-sort-key": {
              type: "number",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var layout_heatmap = {
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var layout_line = {
            "line-cap": {
              type: "enum",
              values: {
                butt: {},
                round: {},
                square: {}
              },
              "default": "butt",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "line-join": {
              type: "enum",
              values: {
                bevel: {},
                round: {},
                miter: {}
              },
              "default": "miter",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "line-miter-limit": {
              type: "number",
              "default": 2,
              requires: [
                {
                  "line-join": "miter"
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "line-round-limit": {
              type: "number",
              "default": 1.05,
              requires: [
                {
                  "line-join": "round"
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "line-sort-key": {
              type: "number",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var layout_symbol = {
            "symbol-placement": {
              type: "enum",
              values: {
                point: {},
                line: {},
                "line-center": {}
              },
              "default": "point",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "symbol-spacing": {
              type: "number",
              "default": 250,
              minimum: 1,
              units: "pixels",
              requires: [
                {
                  "symbol-placement": "line"
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "symbol-avoid-edges": {
              type: "boolean",
              "default": false,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "symbol-sort-key": {
              type: "number",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "symbol-z-order": {
              type: "enum",
              values: {
                auto: {},
                "viewport-y": {},
                source: {}
              },
              "default": "auto",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-allow-overlap": {
              type: "boolean",
              "default": false,
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-ignore-placement": {
              type: "boolean",
              "default": false,
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-optional": {
              type: "boolean",
              "default": false,
              requires: [
                "icon-image",
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-rotation-alignment": {
              type: "enum",
              values: {
                map: {},
                viewport: {},
                auto: {}
              },
              "default": "auto",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-size": {
              type: "number",
              "default": 1,
              minimum: 0,
              units: "factor of the original icon size",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-text-fit": {
              type: "enum",
              values: {
                none: {},
                width: {},
                height: {},
                both: {}
              },
              "default": "none",
              requires: [
                "icon-image",
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-text-fit-padding": {
              type: "array",
              value: "number",
              length: 4,
              "default": [
                0,
                0,
                0,
                0
              ],
              units: "pixels",
              requires: [
                "icon-image",
                "text-field",
                {
                  "icon-text-fit": [
                    "both",
                    "width",
                    "height"
                  ]
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-image": {
              type: "resolvedImage",
              tokens: true,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-rotate": {
              type: "number",
              "default": 0,
              period: 360,
              units: "degrees",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-padding": {
              type: "number",
              "default": 2,
              minimum: 0,
              units: "pixels",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-keep-upright": {
              type: "boolean",
              "default": false,
              requires: [
                "icon-image",
                {
                  "icon-rotation-alignment": "map"
                },
                {
                  "symbol-placement": [
                    "line",
                    "line-center"
                  ]
                }
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-offset": {
              type: "array",
              value: "number",
              length: 2,
              "default": [
                0,
                0
              ],
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-anchor": {
              type: "enum",
              values: {
                center: {},
                left: {},
                right: {},
                top: {},
                bottom: {},
                "top-left": {},
                "top-right": {},
                "bottom-left": {},
                "bottom-right": {}
              },
              "default": "center",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-pitch-alignment": {
              type: "enum",
              values: {
                map: {},
                viewport: {},
                auto: {}
              },
              "default": "auto",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-pitch-alignment": {
              type: "enum",
              values: {
                map: {},
                viewport: {},
                auto: {}
              },
              "default": "auto",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-rotation-alignment": {
              type: "enum",
              values: {
                map: {},
                viewport: {},
                auto: {}
              },
              "default": "auto",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-field": {
              type: "formatted",
              "default": "",
              tokens: true,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-font": {
              type: "array",
              value: "string",
              "default": [
                "Open Sans Regular",
                "Arial Unicode MS Regular"
              ],
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-size": {
              type: "number",
              "default": 16,
              minimum: 0,
              units: "pixels",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-max-width": {
              type: "number",
              "default": 10,
              minimum: 0,
              units: "ems",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-line-height": {
              type: "number",
              "default": 1.2,
              units: "ems",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-letter-spacing": {
              type: "number",
              "default": 0,
              units: "ems",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-justify": {
              type: "enum",
              values: {
                auto: {},
                left: {},
                center: {},
                right: {}
              },
              "default": "center",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-radial-offset": {
              type: "number",
              units: "ems",
              "default": 0,
              requires: [
                "text-field"
              ],
              "property-type": "data-driven",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              }
            },
            "text-variable-anchor": {
              type: "array",
              value: "enum",
              values: {
                center: {},
                left: {},
                right: {},
                top: {},
                bottom: {},
                "top-left": {},
                "top-right": {},
                "bottom-left": {},
                "bottom-right": {}
              },
              requires: [
                "text-field",
                {
                  "symbol-placement": [
                    "point"
                  ]
                }
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-anchor": {
              type: "enum",
              values: {
                center: {},
                left: {},
                right: {},
                top: {},
                bottom: {},
                "top-left": {},
                "top-right": {},
                "bottom-left": {},
                "bottom-right": {}
              },
              "default": "center",
              requires: [
                "text-field",
                {
                  "!": "text-variable-anchor"
                }
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-max-angle": {
              type: "number",
              "default": 45,
              units: "degrees",
              requires: [
                "text-field",
                {
                  "symbol-placement": [
                    "line",
                    "line-center"
                  ]
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-writing-mode": {
              type: "array",
              value: "enum",
              values: {
                horizontal: {},
                vertical: {}
              },
              requires: [
                "text-field",
                {
                  "symbol-placement": [
                    "point"
                  ]
                }
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-rotate": {
              type: "number",
              "default": 0,
              period: 360,
              units: "degrees",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-padding": {
              type: "number",
              "default": 2,
              minimum: 0,
              units: "pixels",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-keep-upright": {
              type: "boolean",
              "default": true,
              requires: [
                "text-field",
                {
                  "text-rotation-alignment": "map"
                },
                {
                  "symbol-placement": [
                    "line",
                    "line-center"
                  ]
                }
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-transform": {
              type: "enum",
              values: {
                none: {},
                uppercase: {},
                lowercase: {}
              },
              "default": "none",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-offset": {
              type: "array",
              value: "number",
              units: "ems",
              length: 2,
              "default": [
                0,
                0
              ],
              requires: [
                "text-field",
                {
                  "!": "text-radial-offset"
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "data-driven"
            },
            "text-allow-overlap": {
              type: "boolean",
              "default": false,
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-ignore-placement": {
              type: "boolean",
              "default": false,
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-optional": {
              type: "boolean",
              "default": false,
              requires: [
                "text-field",
                "icon-image"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var layout_raster = {
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var layout_hillshade = {
            visibility: {
              type: "enum",
              values: {
                visible: {},
                none: {}
              },
              "default": "visible",
              "property-type": "constant"
            }
          };
          var filter = {
            type: "array",
            value: "*"
          };
          var filter_operator = {
            type: "enum",
            values: {
              "==": {},
              "!=": {},
              ">": {},
              ">=": {},
              "<": {},
              "<=": {},
              "in": {},
              "!in": {},
              all: {},
              any: {},
              none: {},
              has: {},
              "!has": {},
              within: {}
            }
          };
          var geometry_type = {
            type: "enum",
            values: {
              Point: {},
              LineString: {},
              Polygon: {}
            }
          };
          var function_stop = {
            type: "array",
            minimum: 0,
            maximum: 24,
            value: [
              "number",
              "color"
            ],
            length: 2
          };
          var expression = {
            type: "array",
            value: "*",
            minimum: 1
          };
          var light = {
            anchor: {
              type: "enum",
              "default": "viewport",
              values: {
                map: {},
                viewport: {}
              },
              "property-type": "data-constant",
              transition: false,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              }
            },
            position: {
              type: "array",
              "default": [
                1.15,
                210,
                30
              ],
              length: 3,
              value: "number",
              "property-type": "data-constant",
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              }
            },
            color: {
              type: "color",
              "property-type": "data-constant",
              "default": "#ffffff",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              transition: true
            },
            intensity: {
              type: "number",
              "property-type": "data-constant",
              "default": 0.5,
              minimum: 0,
              maximum: 1,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              transition: true
            }
          };
          var paint = [
            "paint_fill",
            "paint_line",
            "paint_circle",
            "paint_heatmap",
            "paint_fill-extrusion",
            "paint_symbol",
            "paint_raster",
            "paint_hillshade",
            "paint_background"
          ];
          var paint_fill = {
            "fill-antialias": {
              type: "boolean",
              "default": true,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "fill-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "fill-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              requires: [
                {
                  "!": "fill-pattern"
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "fill-outline-color": {
              type: "color",
              transition: true,
              requires: [
                {
                  "!": "fill-pattern"
                },
                {
                  "fill-antialias": true
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "fill-translate": {
              type: "array",
              value: "number",
              length: 2,
              "default": [
                0,
                0
              ],
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "fill-translate-anchor": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "map",
              requires: [
                "fill-translate"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "fill-pattern": {
              type: "resolvedImage",
              transition: true,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "cross-faded-data-driven"
            }
          };
          var paint_line = {
            "line-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "line-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              requires: [
                {
                  "!": "line-pattern"
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "line-translate": {
              type: "array",
              value: "number",
              length: 2,
              "default": [
                0,
                0
              ],
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "line-translate-anchor": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "map",
              requires: [
                "line-translate"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "line-width": {
              type: "number",
              "default": 1,
              minimum: 0,
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "line-gap-width": {
              type: "number",
              "default": 0,
              minimum: 0,
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "line-offset": {
              type: "number",
              "default": 0,
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "line-blur": {
              type: "number",
              "default": 0,
              minimum: 0,
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "line-dasharray": {
              type: "array",
              value: "number",
              minimum: 0,
              transition: true,
              units: "line widths",
              requires: [
                {
                  "!": "line-pattern"
                }
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "cross-faded"
            },
            "line-pattern": {
              type: "resolvedImage",
              transition: true,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom",
                  "feature"
                ]
              },
              "property-type": "cross-faded-data-driven"
            },
            "line-gradient": {
              type: "color",
              transition: false,
              requires: [
                {
                  "!": "line-dasharray"
                },
                {
                  "!": "line-pattern"
                },
                {
                  source: "geojson",
                  has: {
                    lineMetrics: true
                  }
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "line-progress"
                ]
              },
              "property-type": "color-ramp"
            }
          };
          var paint_circle = {
            "circle-radius": {
              type: "number",
              "default": 5,
              minimum: 0,
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "circle-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "circle-blur": {
              type: "number",
              "default": 0,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "circle-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "circle-translate": {
              type: "array",
              value: "number",
              length: 2,
              "default": [
                0,
                0
              ],
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "circle-translate-anchor": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "map",
              requires: [
                "circle-translate"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "circle-pitch-scale": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "map",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "circle-pitch-alignment": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "viewport",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "circle-stroke-width": {
              type: "number",
              "default": 0,
              minimum: 0,
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "circle-stroke-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "circle-stroke-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            }
          };
          var paint_heatmap = {
            "heatmap-radius": {
              type: "number",
              "default": 30,
              minimum: 1,
              transition: true,
              units: "pixels",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "heatmap-weight": {
              type: "number",
              "default": 1,
              minimum: 0,
              transition: false,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "heatmap-intensity": {
              type: "number",
              "default": 1,
              minimum: 0,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "heatmap-color": {
              type: "color",
              "default": [
                "interpolate",
                [
                  "linear"
                ],
                [
                  "heatmap-density"
                ],
                0,
                "rgba(0, 0, 255, 0)",
                0.1,
                "royalblue",
                0.3,
                "cyan",
                0.5,
                "lime",
                0.7,
                "yellow",
                1,
                "red"
              ],
              transition: false,
              expression: {
                interpolated: true,
                parameters: [
                  "heatmap-density"
                ]
              },
              "property-type": "color-ramp"
            },
            "heatmap-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            }
          };
          var paint_symbol = {
            "icon-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-halo-color": {
              type: "color",
              "default": "rgba(0, 0, 0, 0)",
              transition: true,
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-halo-width": {
              type: "number",
              "default": 0,
              minimum: 0,
              transition: true,
              units: "pixels",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-halo-blur": {
              type: "number",
              "default": 0,
              minimum: 0,
              transition: true,
              units: "pixels",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "icon-translate": {
              type: "array",
              value: "number",
              length: 2,
              "default": [
                0,
                0
              ],
              transition: true,
              units: "pixels",
              requires: [
                "icon-image"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "icon-translate-anchor": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "map",
              requires: [
                "icon-image",
                "icon-translate"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "text-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              overridable: true,
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "text-halo-color": {
              type: "color",
              "default": "rgba(0, 0, 0, 0)",
              transition: true,
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "text-halo-width": {
              type: "number",
              "default": 0,
              minimum: 0,
              transition: true,
              units: "pixels",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "text-halo-blur": {
              type: "number",
              "default": 0,
              minimum: 0,
              transition: true,
              units: "pixels",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom",
                  "feature",
                  "feature-state"
                ]
              },
              "property-type": "data-driven"
            },
            "text-translate": {
              type: "array",
              value: "number",
              length: 2,
              "default": [
                0,
                0
              ],
              transition: true,
              units: "pixels",
              requires: [
                "text-field"
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "text-translate-anchor": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "map",
              requires: [
                "text-field",
                "text-translate"
              ],
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            }
          };
          var paint_raster = {
            "raster-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "raster-hue-rotate": {
              type: "number",
              "default": 0,
              period: 360,
              transition: true,
              units: "degrees",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "raster-brightness-min": {
              type: "number",
              "default": 0,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "raster-brightness-max": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "raster-saturation": {
              type: "number",
              "default": 0,
              minimum: -1,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "raster-contrast": {
              type: "number",
              "default": 0,
              minimum: -1,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "raster-resampling": {
              type: "enum",
              values: {
                linear: {},
                nearest: {}
              },
              "default": "linear",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "raster-fade-duration": {
              type: "number",
              "default": 300,
              minimum: 0,
              transition: false,
              units: "milliseconds",
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            }
          };
          var paint_hillshade = {
            "hillshade-illumination-direction": {
              type: "number",
              "default": 335,
              minimum: 0,
              maximum: 359,
              transition: false,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "hillshade-illumination-anchor": {
              type: "enum",
              values: {
                map: {},
                viewport: {}
              },
              "default": "viewport",
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "hillshade-exaggeration": {
              type: "number",
              "default": 0.5,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "hillshade-shadow-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "hillshade-highlight-color": {
              type: "color",
              "default": "#FFFFFF",
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "hillshade-accent-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            }
          };
          var paint_background = {
            "background-color": {
              type: "color",
              "default": "#000000",
              transition: true,
              requires: [
                {
                  "!": "background-pattern"
                }
              ],
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            },
            "background-pattern": {
              type: "resolvedImage",
              transition: true,
              expression: {
                interpolated: false,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "cross-faded"
            },
            "background-opacity": {
              type: "number",
              "default": 1,
              minimum: 0,
              maximum: 1,
              transition: true,
              expression: {
                interpolated: true,
                parameters: [
                  "zoom"
                ]
              },
              "property-type": "data-constant"
            }
          };
          var transition = {
            duration: {
              type: "number",
              "default": 300,
              minimum: 0,
              units: "milliseconds"
            },
            delay: {
              type: "number",
              "default": 0,
              minimum: 0,
              units: "milliseconds"
            }
          };
          var promoteId = {
            "*": {
              type: "string"
            }
          };
          var spec = {
            $version,
            $root,
            sources,
            source,
            source_vector,
            source_raster,
            source_raster_dem,
            source_geojson,
            source_video,
            source_image,
            layer,
            layout,
            layout_background,
            layout_fill,
            layout_circle,
            layout_heatmap,
            "layout_fill-extrusion": {
              visibility: {
                type: "enum",
                values: {
                  visible: {},
                  none: {}
                },
                "default": "visible",
                "property-type": "constant"
              }
            },
            layout_line,
            layout_symbol,
            layout_raster,
            layout_hillshade,
            filter,
            filter_operator,
            geometry_type,
            "function": {
              expression: {
                type: "expression"
              },
              stops: {
                type: "array",
                value: "function_stop"
              },
              base: {
                type: "number",
                "default": 1,
                minimum: 0
              },
              property: {
                type: "string",
                "default": "$zoom"
              },
              type: {
                type: "enum",
                values: {
                  identity: {},
                  exponential: {},
                  interval: {},
                  categorical: {}
                },
                "default": "exponential"
              },
              colorSpace: {
                type: "enum",
                values: {
                  rgb: {},
                  lab: {},
                  hcl: {}
                },
                "default": "rgb"
              },
              "default": {
                type: "*",
                required: false
              }
            },
            function_stop,
            expression,
            light,
            paint,
            paint_fill,
            "paint_fill-extrusion": {
              "fill-extrusion-opacity": {
                type: "number",
                "default": 1,
                minimum: 0,
                maximum: 1,
                transition: true,
                expression: {
                  interpolated: true,
                  parameters: [
                    "zoom"
                  ]
                },
                "property-type": "data-constant"
              },
              "fill-extrusion-color": {
                type: "color",
                "default": "#000000",
                transition: true,
                requires: [
                  {
                    "!": "fill-extrusion-pattern"
                  }
                ],
                expression: {
                  interpolated: true,
                  parameters: [
                    "zoom",
                    "feature",
                    "feature-state"
                  ]
                },
                "property-type": "data-driven"
              },
              "fill-extrusion-translate": {
                type: "array",
                value: "number",
                length: 2,
                "default": [
                  0,
                  0
                ],
                transition: true,
                units: "pixels",
                expression: {
                  interpolated: true,
                  parameters: [
                    "zoom"
                  ]
                },
                "property-type": "data-constant"
              },
              "fill-extrusion-translate-anchor": {
                type: "enum",
                values: {
                  map: {},
                  viewport: {}
                },
                "default": "map",
                requires: [
                  "fill-extrusion-translate"
                ],
                expression: {
                  interpolated: false,
                  parameters: [
                    "zoom"
                  ]
                },
                "property-type": "data-constant"
              },
              "fill-extrusion-pattern": {
                type: "resolvedImage",
                transition: true,
                expression: {
                  interpolated: false,
                  parameters: [
                    "zoom",
                    "feature"
                  ]
                },
                "property-type": "cross-faded-data-driven"
              },
              "fill-extrusion-height": {
                type: "number",
                "default": 0,
                minimum: 0,
                units: "meters",
                transition: true,
                expression: {
                  interpolated: true,
                  parameters: [
                    "zoom",
                    "feature",
                    "feature-state"
                  ]
                },
                "property-type": "data-driven"
              },
              "fill-extrusion-base": {
                type: "number",
                "default": 0,
                minimum: 0,
                units: "meters",
                transition: true,
                requires: [
                  "fill-extrusion-height"
                ],
                expression: {
                  interpolated: true,
                  parameters: [
                    "zoom",
                    "feature",
                    "feature-state"
                  ]
                },
                "property-type": "data-driven"
              },
              "fill-extrusion-vertical-gradient": {
                type: "boolean",
                "default": true,
                transition: false,
                expression: {
                  interpolated: false,
                  parameters: [
                    "zoom"
                  ]
                },
                "property-type": "data-constant"
              }
            },
            paint_line,
            paint_circle,
            paint_heatmap,
            paint_symbol,
            paint_raster,
            paint_hillshade,
            paint_background,
            transition,
            "property-type": {
              "data-driven": {
                type: "property-type"
              },
              "cross-faded": {
                type: "property-type"
              },
              "cross-faded-data-driven": {
                type: "property-type"
              },
              "color-ramp": {
                type: "property-type"
              },
              "data-constant": {
                type: "property-type"
              },
              constant: {
                type: "property-type"
              }
            },
            promoteId
          };
          var ValidationError = function ValidationError2(key, value, message, identifier) {
            this.message = (key ? key + ": " : "") + message;
            if (identifier) {
              this.identifier = identifier;
            }
            if (value !== null && value !== void 0 && value.__line__) {
              this.line = value.__line__;
            }
          };
          function validateConstants(options) {
            var key = options.key;
            var constants = options.value;
            if (constants) {
              return [new ValidationError(key, constants, "constants have been deprecated as of v8")];
            } else {
              return [];
            }
          }
          function extend$1(output) {
            var inputs = [], len = arguments.length - 1;
            while (len-- > 0)
              inputs[len] = arguments[len + 1];
            for (var i = 0, list = inputs; i < list.length; i += 1) {
              var input = list[i];
              for (var k in input) {
                output[k] = input[k];
              }
            }
            return output;
          }
          function unbundle(value) {
            if (value instanceof Number || value instanceof String || value instanceof Boolean) {
              return value.valueOf();
            } else {
              return value;
            }
          }
          function deepUnbundle(value) {
            if (Array.isArray(value)) {
              return value.map(deepUnbundle);
            } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) {
              var unbundledValue = {};
              for (var key in value) {
                unbundledValue[key] = deepUnbundle(value[key]);
              }
              return unbundledValue;
            }
            return unbundle(value);
          }
          var ParsingError = function(Error2) {
            function ParsingError2(key, message) {
              Error2.call(this, message);
              this.message = message;
              this.key = key;
            }
            if (Error2)
              ParsingError2.__proto__ = Error2;
            ParsingError2.prototype = Object.create(Error2 && Error2.prototype);
            ParsingError2.prototype.constructor = ParsingError2;
            return ParsingError2;
          }(Error);
          var Scope = function Scope2(parent, bindings) {
            if (bindings === void 0)
              bindings = [];
            this.parent = parent;
            this.bindings = {};
            for (var i = 0, list = bindings; i < list.length; i += 1) {
              var ref = list[i];
              var name3 = ref[0];
              var expression2 = ref[1];
              this.bindings[name3] = expression2;
            }
          };
          Scope.prototype.concat = function concat(bindings) {
            return new Scope(this, bindings);
          };
          Scope.prototype.get = function get2(name3) {
            if (this.bindings[name3]) {
              return this.bindings[name3];
            }
            if (this.parent) {
              return this.parent.get(name3);
            }
            throw new Error(name3 + " not found in scope.");
          };
          Scope.prototype.has = function has2(name3) {
            if (this.bindings[name3]) {
              return true;
            }
            return this.parent ? this.parent.has(name3) : false;
          };
          var NullType = { kind: "null" };
          var NumberType = { kind: "number" };
          var StringType = { kind: "string" };
          var BooleanType = { kind: "boolean" };
          var ColorType = { kind: "color" };
          var ObjectType = { kind: "object" };
          var ValueType = { kind: "value" };
          var ErrorType = { kind: "error" };
          var CollatorType = { kind: "collator" };
          var FormattedType = { kind: "formatted" };
          var ResolvedImageType = { kind: "resolvedImage" };
          function array(itemType, N) {
            return {
              kind: "array",
              itemType,
              N
            };
          }
          function toString(type) {
            if (type.kind === "array") {
              var itemType = toString(type.itemType);
              return typeof type.N === "number" ? "array<" + itemType + ", " + type.N + ">" : type.itemType.kind === "value" ? "array" : "array<" + itemType + ">";
            } else {
              return type.kind;
            }
          }
          var valueMemberTypes = [
            NullType,
            NumberType,
            StringType,
            BooleanType,
            ColorType,
            FormattedType,
            ObjectType,
            array(ValueType),
            ResolvedImageType
          ];
          function checkSubtype(expected, t) {
            if (t.kind === "error") {
              return null;
            } else if (expected.kind === "array") {
              if (t.kind === "array" && (t.N === 0 && t.itemType.kind === "value" || !checkSubtype(expected.itemType, t.itemType)) && (typeof expected.N !== "number" || expected.N === t.N)) {
                return null;
              }
            } else if (expected.kind === t.kind) {
              return null;
            } else if (expected.kind === "value") {
              for (var i = 0, list = valueMemberTypes; i < list.length; i += 1) {
                var memberType = list[i];
                if (!checkSubtype(memberType, t)) {
                  return null;
                }
              }
            }
            return "Expected " + toString(expected) + " but found " + toString(t) + " instead.";
          }
          function isValidType(provided, allowedTypes) {
            return allowedTypes.some(function(t) {
              return t.kind === provided.kind;
            });
          }
          function isValidNativeType(provided, allowedTypes) {
            return allowedTypes.some(function(t) {
              if (t === "null") {
                return provided === null;
              } else if (t === "array") {
                return Array.isArray(provided);
              } else if (t === "object") {
                return provided && !Array.isArray(provided) && typeof provided === "object";
              } else {
                return t === typeof provided;
              }
            });
          }
          var csscolorparser = createCommonjsModule(function(module2, exports3) {
            var kCSSColorTable = {
              "transparent": [
                0,
                0,
                0,
                0
              ],
              "aliceblue": [
                240,
                248,
                255,
                1
              ],
              "antiquewhite": [
                250,
                235,
                215,
                1
              ],
              "aqua": [
                0,
                255,
                255,
                1
              ],
              "aquamarine": [
                127,
                255,
                212,
                1
              ],
              "azure": [
                240,
                255,
                255,
                1
              ],
              "beige": [
                245,
                245,
                220,
                1
              ],
              "bisque": [
                255,
                228,
                196,
                1
              ],
              "black": [
                0,
                0,
                0,
                1
              ],
              "blanchedalmond": [
                255,
                235,
                205,
                1
              ],
              "blue": [
                0,
                0,
                255,
                1
              ],
              "blueviolet": [
                138,
                43,
                226,
                1
              ],
              "brown": [
                165,
                42,
                42,
                1
              ],
              "burlywood": [
                222,
                184,
                135,
                1
              ],
              "cadetblue": [
                95,
                158,
                160,
                1
              ],
              "chartreuse": [
                127,
                255,
                0,
                1
              ],
              "chocolate": [
                210,
                105,
                30,
                1
              ],
              "coral": [
                255,
                127,
                80,
                1
              ],
              "cornflowerblue": [
                100,
                149,
                237,
                1
              ],
              "cornsilk": [
                255,
                248,
                220,
                1
              ],
              "crimson": [
                220,
                20,
                60,
                1
              ],
              "cyan": [
                0,
                255,
                255,
                1
              ],
              "darkblue": [
                0,
                0,
                139,
                1
              ],
              "darkcyan": [
                0,
                139,
                139,
                1
              ],
              "darkgoldenrod": [
                184,
                134,
                11,
                1
              ],
              "darkgray": [
                169,
                169,
                169,
                1
              ],
              "darkgreen": [
                0,
                100,
                0,
                1
              ],
              "darkgrey": [
                169,
                169,
                169,
                1
              ],
              "darkkhaki": [
                189,
                183,
                107,
                1
              ],
              "darkmagenta": [
                139,
                0,
                139,
                1
              ],
              "darkolivegreen": [
                85,
                107,
                47,
                1
              ],
              "darkorange": [
                255,
                140,
                0,
                1
              ],
              "darkorchid": [
                153,
                50,
                204,
                1
              ],
              "darkred": [
                139,
                0,
                0,
                1
              ],
              "darksalmon": [
                233,
                150,
                122,
                1
              ],
              "darkseagreen": [
                143,
                188,
                143,
                1
              ],
              "darkslateblue": [
                72,
                61,
                139,
                1
              ],
              "darkslategray": [
                47,
                79,
                79,
                1
              ],
              "darkslategrey": [
                47,
                79,
                79,
                1
              ],
              "darkturquoise": [
                0,
                206,
                209,
                1
              ],
              "darkviolet": [
                148,
                0,
                211,
                1
              ],
              "deeppink": [
                255,
                20,
                147,
                1
              ],
              "deepskyblue": [
                0,
                191,
                255,
                1
              ],
              "dimgray": [
                105,
                105,
                105,
                1
              ],
              "dimgrey": [
                105,
                105,
                105,
                1
              ],
              "dodgerblue": [
                30,
                144,
                255,
                1
              ],
              "firebrick": [
                178,
                34,
                34,
                1
              ],
              "floralwhite": [
                255,
                250,
                240,
                1
              ],
              "forestgreen": [
                34,
                139,
                34,
                1
              ],
              "fuchsia": [
                255,
                0,
                255,
                1
              ],
              "gainsboro": [
                220,
                220,
                220,
                1
              ],
              "ghostwhite": [
                248,
                248,
                255,
                1
              ],
              "gold": [
                255,
                215,
                0,
                1
              ],
              "goldenrod": [
                218,
                165,
                32,
                1
              ],
              "gray": [
                128,
                128,
                128,
                1
              ],
              "green": [
                0,
                128,
                0,
                1
              ],
              "greenyellow": [
                173,
                255,
                47,
                1
              ],
              "grey": [
                128,
                128,
                128,
                1
              ],
              "honeydew": [
                240,
                255,
                240,
                1
              ],
              "hotpink": [
                255,
                105,
                180,
                1
              ],
              "indianred": [
                205,
                92,
                92,
                1
              ],
              "indigo": [
                75,
                0,
                130,
                1
              ],
              "ivory": [
                255,
                255,
                240,
                1
              ],
              "khaki": [
                240,
                230,
                140,
                1
              ],
              "lavender": [
                230,
                230,
                250,
                1
              ],
              "lavenderblush": [
                255,
                240,
                245,
                1
              ],
              "lawngreen": [
                124,
                252,
                0,
                1
              ],
              "lemonchiffon": [
                255,
                250,
                205,
                1
              ],
              "lightblue": [
                173,
                216,
                230,
                1
              ],
              "lightcoral": [
                240,
                128,
                128,
                1
              ],
              "lightcyan": [
                224,
                255,
                255,
                1
              ],
              "lightgoldenrodyellow": [
                250,
                250,
                210,
                1
              ],
              "lightgray": [
                211,
                211,
                211,
                1
              ],
              "lightgreen": [
                144,
                238,
                144,
                1
              ],
              "lightgrey": [
                211,
                211,
                211,
                1
              ],
              "lightpink": [
                255,
                182,
                193,
                1
              ],
              "lightsalmon": [
                255,
                160,
                122,
                1
              ],
              "lightseagreen": [
                32,
                178,
                170,
                1
              ],
              "lightskyblue": [
                135,
                206,
                250,
                1
              ],
              "lightslategray": [
                119,
                136,
                153,
                1
              ],
              "lightslategrey": [
                119,
                136,
                153,
                1
              ],
              "lightsteelblue": [
                176,
                196,
                222,
                1
              ],
              "lightyellow": [
                255,
                255,
                224,
                1
              ],
              "lime": [
                0,
                255,
                0,
                1
              ],
              "limegreen": [
                50,
                205,
                50,
                1
              ],
              "linen": [
                250,
                240,
                230,
                1
              ],
              "magenta": [
                255,
                0,
                255,
                1
              ],
              "maroon": [
                128,
                0,
                0,
                1
              ],
              "mediumaquamarine": [
                102,
                205,
                170,
                1
              ],
              "mediumblue": [
                0,
                0,
                205,
                1
              ],
              "mediumorchid": [
                186,
                85,
                211,
                1
              ],
              "mediumpurple": [
                147,
                112,
                219,
                1
              ],
              "mediumseagreen": [
                60,
                179,
                113,
                1
              ],
              "mediumslateblue": [
                123,
                104,
                238,
                1
              ],
              "mediumspringgreen": [
                0,
                250,
                154,
                1
              ],
              "mediumturquoise": [
                72,
                209,
                204,
                1
              ],
              "mediumvioletred": [
                199,
                21,
                133,
                1
              ],
              "midnightblue": [
                25,
                25,
                112,
                1
              ],
              "mintcream": [
                245,
                255,
                250,
                1
              ],
              "mistyrose": [
                255,
                228,
                225,
                1
              ],
              "moccasin": [
                255,
                228,
                181,
                1
              ],
              "navajowhite": [
                255,
                222,
                173,
                1
              ],
              "navy": [
                0,
                0,
                128,
                1
              ],
              "oldlace": [
                253,
                245,
                230,
                1
              ],
              "olive": [
                128,
                128,
                0,
                1
              ],
              "olivedrab": [
                107,
                142,
                35,
                1
              ],
              "orange": [
                255,
                165,
                0,
                1
              ],
              "orangered": [
                255,
                69,
                0,
                1
              ],
              "orchid": [
                218,
                112,
                214,
                1
              ],
              "palegoldenrod": [
                238,
                232,
                170,
                1
              ],
              "palegreen": [
                152,
                251,
                152,
                1
              ],
              "paleturquoise": [
                175,
                238,
                238,
                1
              ],
              "palevioletred": [
                219,
                112,
                147,
                1
              ],
              "papayawhip": [
                255,
                239,
                213,
                1
              ],
              "peachpuff": [
                255,
                218,
                185,
                1
              ],
              "peru": [
                205,
                133,
                63,
                1
              ],
              "pink": [
                255,
                192,
                203,
                1
              ],
              "plum": [
                221,
                160,
                221,
                1
              ],
              "powderblue": [
                176,
                224,
                230,
                1
              ],
              "purple": [
                128,
                0,
                128,
                1
              ],
              "rebeccapurple": [
                102,
                51,
                153,
                1
              ],
              "red": [
                255,
                0,
                0,
                1
              ],
              "rosybrown": [
                188,
                143,
                143,
                1
              ],
              "royalblue": [
                65,
                105,
                225,
                1
              ],
              "saddlebrown": [
                139,
                69,
                19,
                1
              ],
              "salmon": [
                250,
                128,
                114,
                1
              ],
              "sandybrown": [
                244,
                164,
                96,
                1
              ],
              "seagreen": [
                46,
                139,
                87,
                1
              ],
              "seashell": [
                255,
                245,
                238,
                1
              ],
              "sienna": [
                160,
                82,
                45,
                1
              ],
              "silver": [
                192,
                192,
                192,
                1
              ],
              "skyblue": [
                135,
                206,
                235,
                1
              ],
              "slateblue": [
                106,
                90,
                205,
                1
              ],
              "slategray": [
                112,
                128,
                144,
                1
              ],
              "slategrey": [
                112,
                128,
                144,
                1
              ],
              "snow": [
                255,
                250,
                250,
                1
              ],
              "springgreen": [
                0,
                255,
                127,
                1
              ],
              "steelblue": [
                70,
                130,
                180,
                1
              ],
              "tan": [
                210,
                180,
                140,
                1
              ],
              "teal": [
                0,
                128,
                128,
                1
              ],
              "thistle": [
                216,
                191,
                216,
                1
              ],
              "tomato": [
                255,
                99,
                71,
                1
              ],
              "turquoise": [
                64,
                224,
                208,
                1
              ],
              "violet": [
                238,
                130,
                238,
                1
              ],
              "wheat": [
                245,
                222,
                179,
                1
              ],
              "white": [
                255,
                255,
                255,
                1
              ],
              "whitesmoke": [
                245,
                245,
                245,
                1
              ],
              "yellow": [
                255,
                255,
                0,
                1
              ],
              "yellowgreen": [
                154,
                205,
                50,
                1
              ]
            };
            function clamp_css_byte(i) {
              i = Math.round(i);
              return i < 0 ? 0 : i > 255 ? 255 : i;
            }
            function clamp_css_float(f) {
              return f < 0 ? 0 : f > 1 ? 1 : f;
            }
            function parse_css_int(str) {
              if (str[str.length - 1] === "%") {
                return clamp_css_byte(parseFloat(str) / 100 * 255);
              }
              return clamp_css_byte(parseInt(str));
            }
            function parse_css_float(str) {
              if (str[str.length - 1] === "%") {
                return clamp_css_float(parseFloat(str) / 100);
              }
              return clamp_css_float(parseFloat(str));
            }
            function css_hue_to_rgb(m1, m2, h) {
              if (h < 0) {
                h += 1;
              } else if (h > 1) {
                h -= 1;
              }
              if (h * 6 < 1) {
                return m1 + (m2 - m1) * h * 6;
              }
              if (h * 2 < 1) {
                return m2;
              }
              if (h * 3 < 2) {
                return m1 + (m2 - m1) * (2 / 3 - h) * 6;
              }
              return m1;
            }
            function parseCSSColor(css_str) {
              var str = css_str.replace(/ /g, "").toLowerCase();
              if (str in kCSSColorTable) {
                return kCSSColorTable[str].slice();
              }
              if (str[0] === "#") {
                if (str.length === 4) {
                  var iv = parseInt(str.substr(1), 16);
                  if (!(iv >= 0 && iv <= 4095)) {
                    return null;
                  }
                  return [
                    (iv & 3840) >> 4 | (iv & 3840) >> 8,
                    iv & 240 | (iv & 240) >> 4,
                    iv & 15 | (iv & 15) << 4,
                    1
                  ];
                } else if (str.length === 7) {
                  var iv = parseInt(str.substr(1), 16);
                  if (!(iv >= 0 && iv <= 16777215)) {
                    return null;
                  }
                  return [
                    (iv & 16711680) >> 16,
                    (iv & 65280) >> 8,
                    iv & 255,
                    1
                  ];
                }
                return null;
              }
              var op = str.indexOf("("), ep = str.indexOf(")");
              if (op !== -1 && ep + 1 === str.length) {
                var fname = str.substr(0, op);
                var params = str.substr(op + 1, ep - (op + 1)).split(",");
                var alpha = 1;
                switch (fname) {
                  case "rgba":
                    if (params.length !== 4) {
                      return null;
                    }
                    alpha = parse_css_float(params.pop());
                  case "rgb":
                    if (params.length !== 3) {
                      return null;
                    }
                    return [
                      parse_css_int(params[0]),
                      parse_css_int(params[1]),
                      parse_css_int(params[2]),
                      alpha
                    ];
                  case "hsla":
                    if (params.length !== 4) {
                      return null;
                    }
                    alpha = parse_css_float(params.pop());
                  case "hsl":
                    if (params.length !== 3) {
                      return null;
                    }
                    var h = (parseFloat(params[0]) % 360 + 360) % 360 / 360;
                    var s = parse_css_float(params[1]);
                    var l = parse_css_float(params[2]);
                    var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
                    var m1 = l * 2 - m2;
                    return [
                      clamp_css_byte(css_hue_to_rgb(m1, m2, h + 1 / 3) * 255),
                      clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),
                      clamp_css_byte(css_hue_to_rgb(m1, m2, h - 1 / 3) * 255),
                      alpha
                    ];
                  default:
                    return null;
                }
              }
              return null;
            }
            try {
              exports3.parseCSSColor = parseCSSColor;
            } catch (e) {
            }
          });
          var csscolorparser_1 = csscolorparser.parseCSSColor;
          var Color2 = function Color3(r, g, b, a) {
            if (a === void 0)
              a = 1;
            this.r = r;
            this.g = g;
            this.b = b;
            this.a = a;
          };
          Color2.parse = function parse2(input) {
            if (!input) {
              return void 0;
            }
            if (input instanceof Color2) {
              return input;
            }
            if (typeof input !== "string") {
              return void 0;
            }
            var rgba4 = csscolorparser_1(input);
            if (!rgba4) {
              return void 0;
            }
            return new Color2(rgba4[0] / 255 * rgba4[3], rgba4[1] / 255 * rgba4[3], rgba4[2] / 255 * rgba4[3], rgba4[3]);
          };
          Color2.prototype.toString = function toString2() {
            var ref = this.toArray();
            var r = ref[0];
            var g = ref[1];
            var b = ref[2];
            var a = ref[3];
            return "rgba(" + Math.round(r) + "," + Math.round(g) + "," + Math.round(b) + "," + a + ")";
          };
          Color2.prototype.toArray = function toArray() {
            var ref = this;
            var r = ref.r;
            var g = ref.g;
            var b = ref.b;
            var a = ref.a;
            return a === 0 ? [
              0,
              0,
              0,
              0
            ] : [
              r * 255 / a,
              g * 255 / a,
              b * 255 / a,
              a
            ];
          };
          Color2.black = new Color2(0, 0, 0, 1);
          Color2.white = new Color2(1, 1, 1, 1);
          Color2.transparent = new Color2(0, 0, 0, 0);
          Color2.red = new Color2(1, 0, 0, 1);
          var Collator = function Collator2(caseSensitive, diacriticSensitive, locale) {
            if (caseSensitive) {
              this.sensitivity = diacriticSensitive ? "variant" : "case";
            } else {
              this.sensitivity = diacriticSensitive ? "accent" : "base";
            }
            this.locale = locale;
            this.collator = new Intl.Collator(this.locale ? this.locale : [], {
              sensitivity: this.sensitivity,
              usage: "search"
            });
          };
          Collator.prototype.compare = function compare2(lhs, rhs) {
            return this.collator.compare(lhs, rhs);
          };
          Collator.prototype.resolvedLocale = function resolvedLocale() {
            return new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale;
          };
          var FormattedSection = function FormattedSection2(text, image, scale2, fontStack, textColor) {
            this.text = text;
            this.image = image;
            this.scale = scale2;
            this.fontStack = fontStack;
            this.textColor = textColor;
          };
          var Formatted = function Formatted2(sections) {
            this.sections = sections;
          };
          Formatted.fromString = function fromString(unformatted) {
            return new Formatted([new FormattedSection(unformatted, null, null, null, null)]);
          };
          Formatted.prototype.isEmpty = function isEmpty2() {
            if (this.sections.length === 0) {
              return true;
            }
            return !this.sections.some(function(section) {
              return section.text.length !== 0 || section.image && section.image.name.length !== 0;
            });
          };
          Formatted.factory = function factory(text) {
            if (text instanceof Formatted) {
              return text;
            } else {
              return Formatted.fromString(text);
            }
          };
          Formatted.prototype.toString = function toString2() {
            if (this.sections.length === 0) {
              return "";
            }
            return this.sections.map(function(section) {
              return section.text;
            }).join("");
          };
          Formatted.prototype.serialize = function serialize2() {
            var serialized = ["format"];
            for (var i = 0, list = this.sections; i < list.length; i += 1) {
              var section = list[i];
              if (section.image) {
                serialized.push([
                  "image",
                  section.image.name
                ]);
                continue;
              }
              serialized.push(section.text);
              var options = {};
              if (section.fontStack) {
                options["text-font"] = [
                  "literal",
                  section.fontStack.split(",")
                ];
              }
              if (section.scale) {
                options["font-scale"] = section.scale;
              }
              if (section.textColor) {
                options["text-color"] = ["rgba"].concat(section.textColor.toArray());
              }
              serialized.push(options);
            }
            return serialized;
          };
          var ResolvedImage = function ResolvedImage2(options) {
            this.name = options.name;
            this.available = options.available;
          };
          ResolvedImage.prototype.toString = function toString2() {
            return this.name;
          };
          ResolvedImage.fromString = function fromString(name3) {
            if (!name3) {
              return null;
            }
            return new ResolvedImage({
              name: name3,
              available: false
            });
          };
          ResolvedImage.prototype.serialize = function serialize2() {
            return [
              "image",
              this.name
            ];
          };
          function validateRGBA(r, g, b, a) {
            if (!(typeof r === "number" && r >= 0 && r <= 255 && typeof g === "number" && g >= 0 && g <= 255 && typeof b === "number" && b >= 0 && b <= 255)) {
              var value = typeof a === "number" ? [
                r,
                g,
                b,
                a
              ] : [
                r,
                g,
                b
              ];
              return "Invalid rgba value [" + value.join(", ") + "]: 'r', 'g', and 'b' must be between 0 and 255.";
            }
            if (!(typeof a === "undefined" || typeof a === "number" && a >= 0 && a <= 1)) {
              return "Invalid rgba value [" + [
                r,
                g,
                b,
                a
              ].join(", ") + "]: 'a' must be between 0 and 1.";
            }
            return null;
          }
          function isValue(mixed) {
            if (mixed === null) {
              return true;
            } else if (typeof mixed === "string") {
              return true;
            } else if (typeof mixed === "boolean") {
              return true;
            } else if (typeof mixed === "number") {
              return true;
            } else if (mixed instanceof Color2) {
              return true;
            } else if (mixed instanceof Collator) {
              return true;
            } else if (mixed instanceof Formatted) {
              return true;
            } else if (mixed instanceof ResolvedImage) {
              return true;
            } else if (Array.isArray(mixed)) {
              for (var i = 0, list = mixed; i < list.length; i += 1) {
                var item = list[i];
                if (!isValue(item)) {
                  return false;
                }
              }
              return true;
            } else if (typeof mixed === "object") {
              for (var key in mixed) {
                if (!isValue(mixed[key])) {
                  return false;
                }
              }
              return true;
            } else {
              return false;
            }
          }
          function typeOf(value) {
            if (value === null) {
              return NullType;
            } else if (typeof value === "string") {
              return StringType;
            } else if (typeof value === "boolean") {
              return BooleanType;
            } else if (typeof value === "number") {
              return NumberType;
            } else if (value instanceof Color2) {
              return ColorType;
            } else if (value instanceof Collator) {
              return CollatorType;
            } else if (value instanceof Formatted) {
              return FormattedType;
            } else if (value instanceof ResolvedImage) {
              return ResolvedImageType;
            } else if (Array.isArray(value)) {
              var length = value.length;
              var itemType;
              for (var i = 0, list = value; i < list.length; i += 1) {
                var item = list[i];
                var t = typeOf(item);
                if (!itemType) {
                  itemType = t;
                } else if (itemType === t) {
                  continue;
                } else {
                  itemType = ValueType;
                  break;
                }
              }
              return array(itemType || ValueType, length);
            } else {
              return ObjectType;
            }
          }
          function toString$1(value) {
            var type = typeof value;
            if (value === null) {
              return "";
            } else if (type === "string" || type === "number" || type === "boolean") {
              return String(value);
            } else if (value instanceof Color2 || value instanceof Formatted || value instanceof ResolvedImage) {
              return value.toString();
            } else {
              return JSON.stringify(value);
            }
          }
          var Literal = function Literal2(type, value) {
            this.type = type;
            this.value = value;
          };
          Literal.parse = function parse2(args, context) {
            if (args.length !== 2) {
              return context.error("'literal' expression requires exactly one argument, but found " + (args.length - 1) + " instead.");
            }
            if (!isValue(args[1])) {
              return context.error("invalid value");
            }
            var value = args[1];
            var type = typeOf(value);
            var expected = context.expectedType;
            if (type.kind === "array" && type.N === 0 && expected && expected.kind === "array" && (typeof expected.N !== "number" || expected.N === 0)) {
              type = expected;
            }
            return new Literal(type, value);
          };
          Literal.prototype.evaluate = function evaluate() {
            return this.value;
          };
          Literal.prototype.eachChild = function eachChild() {
          };
          Literal.prototype.outputDefined = function outputDefined() {
            return true;
          };
          Literal.prototype.serialize = function serialize2() {
            if (this.type.kind === "array" || this.type.kind === "object") {
              return [
                "literal",
                this.value
              ];
            } else if (this.value instanceof Color2) {
              return ["rgba"].concat(this.value.toArray());
            } else if (this.value instanceof Formatted) {
              return this.value.serialize();
            } else {
              return this.value;
            }
          };
          var RuntimeError = function RuntimeError2(message) {
            this.name = "ExpressionEvaluationError";
            this.message = message;
          };
          RuntimeError.prototype.toJSON = function toJSON() {
            return this.message;
          };
          var types = {
            string: StringType,
            number: NumberType,
            boolean: BooleanType,
            object: ObjectType
          };
          var Assertion = function Assertion2(type, args) {
            this.type = type;
            this.args = args;
          };
          Assertion.parse = function parse2(args, context) {
            if (args.length < 2) {
              return context.error("Expected at least one argument.");
            }
            var i = 1;
            var type;
            var name3 = args[0];
            if (name3 === "array") {
              var itemType;
              if (args.length > 2) {
                var type$1 = args[1];
                if (typeof type$1 !== "string" || !(type$1 in types) || type$1 === "object") {
                  return context.error('The item type argument of "array" must be one of string, number, boolean', 1);
                }
                itemType = types[type$1];
                i++;
              } else {
                itemType = ValueType;
              }
              var N;
              if (args.length > 3) {
                if (args[2] !== null && (typeof args[2] !== "number" || args[2] < 0 || args[2] !== Math.floor(args[2]))) {
                  return context.error('The length argument to "array" must be a positive integer literal', 2);
                }
                N = args[2];
                i++;
              }
              type = array(itemType, N);
            } else {
              type = types[name3];
            }
            var parsed = [];
            for (; i < args.length; i++) {
              var input = context.parse(args[i], i, ValueType);
              if (!input) {
                return null;
              }
              parsed.push(input);
            }
            return new Assertion(type, parsed);
          };
          Assertion.prototype.evaluate = function evaluate(ctx) {
            for (var i = 0; i < this.args.length; i++) {
              var value = this.args[i].evaluate(ctx);
              var error2 = checkSubtype(this.type, typeOf(value));
              if (!error2) {
                return value;
              } else if (i === this.args.length - 1) {
                throw new RuntimeError("Expected value to be of type " + toString(this.type) + ", but found " + toString(typeOf(value)) + " instead.");
              }
            }
            return null;
          };
          Assertion.prototype.eachChild = function eachChild(fn) {
            this.args.forEach(fn);
          };
          Assertion.prototype.outputDefined = function outputDefined() {
            return this.args.every(function(arg) {
              return arg.outputDefined();
            });
          };
          Assertion.prototype.serialize = function serialize2() {
            var type = this.type;
            var serialized = [type.kind];
            if (type.kind === "array") {
              var itemType = type.itemType;
              if (itemType.kind === "string" || itemType.kind === "number" || itemType.kind === "boolean") {
                serialized.push(itemType.kind);
                var N = type.N;
                if (typeof N === "number" || this.args.length > 1) {
                  serialized.push(N);
                }
              }
            }
            return serialized.concat(this.args.map(function(arg) {
              return arg.serialize();
            }));
          };
          var FormatExpression = function FormatExpression2(sections) {
            this.type = FormattedType;
            this.sections = sections;
          };
          FormatExpression.parse = function parse2(args, context) {
            if (args.length < 2) {
              return context.error("Expected at least one argument.");
            }
            var firstArg = args[1];
            if (!Array.isArray(firstArg) && typeof firstArg === "object") {
              return context.error("First argument must be an image or text section.");
            }
            var sections = [];
            var nextTokenMayBeObject = false;
            for (var i = 1; i <= args.length - 1; ++i) {
              var arg = args[i];
              if (nextTokenMayBeObject && typeof arg === "object" && !Array.isArray(arg)) {
                nextTokenMayBeObject = false;
                var scale2 = null;
                if (arg["font-scale"]) {
                  scale2 = context.parse(arg["font-scale"], 1, NumberType);
                  if (!scale2) {
                    return null;
                  }
                }
                var font = null;
                if (arg["text-font"]) {
                  font = context.parse(arg["text-font"], 1, array(StringType));
                  if (!font) {
                    return null;
                  }
                }
                var textColor = null;
                if (arg["text-color"]) {
                  textColor = context.parse(arg["text-color"], 1, ColorType);
                  if (!textColor) {
                    return null;
                  }
                }
                var lastExpression = sections[sections.length - 1];
                lastExpression.scale = scale2;
                lastExpression.font = font;
                lastExpression.textColor = textColor;
              } else {
                var content = context.parse(args[i], 1, ValueType);
                if (!content) {
                  return null;
                }
                var kind = content.type.kind;
                if (kind !== "string" && kind !== "value" && kind !== "null" && kind !== "resolvedImage") {
                  return context.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");
                }
                nextTokenMayBeObject = true;
                sections.push({
                  content,
                  scale: null,
                  font: null,
                  textColor: null
                });
              }
            }
            return new FormatExpression(sections);
          };
          FormatExpression.prototype.evaluate = function evaluate(ctx) {
            var evaluateSection = function(section) {
              var evaluatedContent = section.content.evaluate(ctx);
              if (typeOf(evaluatedContent) === ResolvedImageType) {
                return new FormattedSection("", evaluatedContent, null, null, null);
              }
              return new FormattedSection(toString$1(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(",") : null, section.textColor ? section.textColor.evaluate(ctx) : null);
            };
            return new Formatted(this.sections.map(evaluateSection));
          };
          FormatExpression.prototype.eachChild = function eachChild(fn) {
            for (var i = 0, list = this.sections; i < list.length; i += 1) {
              var section = list[i];
              fn(section.content);
              if (section.scale) {
                fn(section.scale);
              }
              if (section.font) {
                fn(section.font);
              }
              if (section.textColor) {
                fn(section.textColor);
              }
            }
          };
          FormatExpression.prototype.outputDefined = function outputDefined() {
            return false;
          };
          FormatExpression.prototype.serialize = function serialize2() {
            var serialized = ["format"];
            for (var i = 0, list = this.sections; i < list.length; i += 1) {
              var section = list[i];
              serialized.push(section.content.serialize());
              var options = {};
              if (section.scale) {
                options["font-scale"] = section.scale.serialize();
              }
              if (section.font) {
                options["text-font"] = section.font.serialize();
              }
              if (section.textColor) {
                options["text-color"] = section.textColor.serialize();
              }
              serialized.push(options);
            }
            return serialized;
          };
          var ImageExpression = function ImageExpression2(input) {
            this.type = ResolvedImageType;
            this.input = input;
          };
          ImageExpression.parse = function parse2(args, context) {
            if (args.length !== 2) {
              return context.error("Expected two arguments.");
            }
            var name3 = context.parse(args[1], 1, StringType);
            if (!name3) {
              return context.error("No image name provided.");
            }
            return new ImageExpression(name3);
          };
          ImageExpression.prototype.evaluate = function evaluate(ctx) {
            var evaluatedImageName = this.input.evaluate(ctx);
            var value = ResolvedImage.fromString(evaluatedImageName);
            if (value && ctx.availableImages) {
              value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1;
            }
            return value;
          };
          ImageExpression.prototype.eachChild = function eachChild(fn) {
            fn(this.input);
          };
          ImageExpression.prototype.outputDefined = function outputDefined() {
            return false;
          };
          ImageExpression.prototype.serialize = function serialize2() {
            return [
              "image",
              this.input.serialize()
            ];
          };
          var types$1 = {
            "to-boolean": BooleanType,
            "to-color": ColorType,
            "to-number": NumberType,
            "to-string": StringType
          };
          var Coercion = function Coercion2(type, args) {
            this.type = type;
            this.args = args;
          };
          Coercion.parse = function parse2(args, context) {
            if (args.length < 2) {
              return context.error("Expected at least one argument.");
            }
            var name3 = args[0];
            if ((name3 === "to-boolean" || name3 === "to-string") && args.length !== 2) {
              return context.error("Expected one argument.");
            }
            var type = types$1[name3];
            var parsed = [];
            for (var i = 1; i < args.length; i++) {
              var input = context.parse(args[i], i, ValueType);
              if (!input) {
                return null;
              }
              parsed.push(input);
            }
            return new Coercion(type, parsed);
          };
          Coercion.prototype.evaluate = function evaluate(ctx) {
            if (this.type.kind === "boolean") {
              return Boolean(this.args[0].evaluate(ctx));
            } else if (this.type.kind === "color") {
              var input;
              var error2;
              for (var i = 0, list = this.args; i < list.length; i += 1) {
                var arg = list[i];
                input = arg.evaluate(ctx);
                error2 = null;
                if (input instanceof Color2) {
                  return input;
                } else if (typeof input === "string") {
                  var c = ctx.parseColor(input);
                  if (c) {
                    return c;
                  }
                } else if (Array.isArray(input)) {
                  if (input.length < 3 || input.length > 4) {
                    error2 = "Invalid rbga value " + JSON.stringify(input) + ": expected an array containing either three or four numeric values.";
                  } else {
                    error2 = validateRGBA(input[0], input[1], input[2], input[3]);
                  }
                  if (!error2) {
                    return new Color2(input[0] / 255, input[1] / 255, input[2] / 255, input[3]);
                  }
                }
              }
              throw new RuntimeError(error2 || "Could not parse color from value '" + (typeof input === "string" ? input : String(JSON.stringify(input))) + "'");
            } else if (this.type.kind === "number") {
              var value = null;
              for (var i$1 = 0, list$1 = this.args; i$1 < list$1.length; i$1 += 1) {
                var arg$1 = list$1[i$1];
                value = arg$1.evaluate(ctx);
                if (value === null) {
                  return 0;
                }
                var num = Number(value);
                if (isNaN(num)) {
                  continue;
                }
                return num;
              }
              throw new RuntimeError("Could not convert " + JSON.stringify(value) + " to number.");
            } else if (this.type.kind === "formatted") {
              return Formatted.fromString(toString$1(this.args[0].evaluate(ctx)));
            } else if (this.type.kind === "resolvedImage") {
              return ResolvedImage.fromString(toString$1(this.args[0].evaluate(ctx)));
            } else {
              return toString$1(this.args[0].evaluate(ctx));
            }
          };
          Coercion.prototype.eachChild = function eachChild(fn) {
            this.args.forEach(fn);
          };
          Coercion.prototype.outputDefined = function outputDefined() {
            return this.args.every(function(arg) {
              return arg.outputDefined();
            });
          };
          Coercion.prototype.serialize = function serialize2() {
            if (this.type.kind === "formatted") {
              return new FormatExpression([{
                content: this.args[0],
                scale: null,
                font: null,
                textColor: null
              }]).serialize();
            }
            if (this.type.kind === "resolvedImage") {
              return new ImageExpression(this.args[0]).serialize();
            }
            var serialized = ["to-" + this.type.kind];
            this.eachChild(function(child) {
              serialized.push(child.serialize());
            });
            return serialized;
          };
          var geometryTypes = [
            "Unknown",
            "Point",
            "LineString",
            "Polygon"
          ];
          var EvaluationContext = function EvaluationContext2() {
            this.globals = null;
            this.feature = null;
            this.featureState = null;
            this.formattedSection = null;
            this._parseColorCache = {};
            this.availableImages = null;
            this.canonical = null;
          };
          EvaluationContext.prototype.id = function id2() {
            return this.feature && "id" in this.feature ? this.feature.id : null;
          };
          EvaluationContext.prototype.geometryType = function geometryType() {
            return this.feature ? typeof this.feature.type === "number" ? geometryTypes[this.feature.type] : this.feature.type : null;
          };
          EvaluationContext.prototype.geometry = function geometry() {
            return this.feature && "geometry" in this.feature ? this.feature.geometry : null;
          };
          EvaluationContext.prototype.canonicalID = function canonicalID() {
            return this.canonical;
          };
          EvaluationContext.prototype.properties = function properties2() {
            return this.feature && this.feature.properties || {};
          };
          EvaluationContext.prototype.parseColor = function parseColor(input) {
            var cached = this._parseColorCache[input];
            if (!cached) {
              cached = this._parseColorCache[input] = Color2.parse(input);
            }
            return cached;
          };
          var CompoundExpression = function CompoundExpression2(name3, type, evaluate, args) {
            this.name = name3;
            this.type = type;
            this._evaluate = evaluate;
            this.args = args;
          };
          CompoundExpression.prototype.evaluate = function evaluate(ctx) {
            return this._evaluate(ctx, this.args);
          };
          CompoundExpression.prototype.eachChild = function eachChild(fn) {
            this.args.forEach(fn);
          };
          CompoundExpression.prototype.outputDefined = function outputDefined() {
            return false;
          };
          CompoundExpression.prototype.serialize = function serialize2() {
            return [this.name].concat(this.args.map(function(arg) {
              return arg.serialize();
            }));
          };
          CompoundExpression.parse = function parse2(args, context) {
            var ref$1;
            var op = args[0];
            var definition = CompoundExpression.definitions[op];
            if (!definition) {
              return context.error('Unknown expression "' + op + '". If you wanted a literal array, use ["literal", [...]].', 0);
            }
            var type = Array.isArray(definition) ? definition[0] : definition.type;
            var availableOverloads = Array.isArray(definition) ? [[
              definition[1],
              definition[2]
            ]] : definition.overloads;
            var overloads = availableOverloads.filter(function(ref2) {
              var signature = ref2[0];
              return !Array.isArray(signature) || signature.length === args.length - 1;
            });
            var signatureContext = null;
            for (var i$3 = 0, list = overloads; i$3 < list.length; i$3 += 1) {
              var ref = list[i$3];
              var params = ref[0];
              var evaluate = ref[1];
              signatureContext = new ParsingContext(context.registry, context.path, null, context.scope);
              var parsedArgs = [];
              var argParseFailed = false;
              for (var i = 1; i < args.length; i++) {
                var arg = args[i];
                var expectedType = Array.isArray(params) ? params[i - 1] : params.type;
                var parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);
                if (!parsed) {
                  argParseFailed = true;
                  break;
                }
                parsedArgs.push(parsed);
              }
              if (argParseFailed) {
                continue;
              }
              if (Array.isArray(params)) {
                if (params.length !== parsedArgs.length) {
                  signatureContext.error("Expected " + params.length + " arguments, but found " + parsedArgs.length + " instead.");
                  continue;
                }
              }
              for (var i$1 = 0; i$1 < parsedArgs.length; i$1++) {
                var expected = Array.isArray(params) ? params[i$1] : params.type;
                var arg$1 = parsedArgs[i$1];
                signatureContext.concat(i$1 + 1).checkSubtype(expected, arg$1.type);
              }
              if (signatureContext.errors.length === 0) {
                return new CompoundExpression(op, type, evaluate, parsedArgs);
              }
            }
            if (overloads.length === 1) {
              (ref$1 = context.errors).push.apply(ref$1, signatureContext.errors);
            } else {
              var expected$1 = overloads.length ? overloads : availableOverloads;
              var signatures = expected$1.map(function(ref2) {
                var params2 = ref2[0];
                return stringifySignature(params2);
              }).join(" | ");
              var actualTypes = [];
              for (var i$2 = 1; i$2 < args.length; i$2++) {
                var parsed$1 = context.parse(args[i$2], 1 + actualTypes.length);
                if (!parsed$1) {
                  return null;
                }
                actualTypes.push(toString(parsed$1.type));
              }
              context.error("Expected arguments of type " + signatures + ", but found (" + actualTypes.join(", ") + ") instead.");
            }
            return null;
          };
          CompoundExpression.register = function register2(registry2, definitions) {
            CompoundExpression.definitions = definitions;
            for (var name3 in definitions) {
              registry2[name3] = CompoundExpression;
            }
          };
          function stringifySignature(signature) {
            if (Array.isArray(signature)) {
              return "(" + signature.map(toString).join(", ") + ")";
            } else {
              return "(" + toString(signature.type) + "...)";
            }
          }
          var CollatorExpression = function CollatorExpression2(caseSensitive, diacriticSensitive, locale) {
            this.type = CollatorType;
            this.locale = locale;
            this.caseSensitive = caseSensitive;
            this.diacriticSensitive = diacriticSensitive;
          };
          CollatorExpression.parse = function parse2(args, context) {
            if (args.length !== 2) {
              return context.error("Expected one argument.");
            }
            var options = args[1];
            if (typeof options !== "object" || Array.isArray(options)) {
              return context.error("Collator options argument must be an object.");
            }
            var caseSensitive = context.parse(options["case-sensitive"] === void 0 ? false : options["case-sensitive"], 1, BooleanType);
            if (!caseSensitive) {
              return null;
            }
            var diacriticSensitive = context.parse(options["diacritic-sensitive"] === void 0 ? false : options["diacritic-sensitive"], 1, BooleanType);
            if (!diacriticSensitive) {
              return null;
            }
            var locale = null;
            if (options["locale"]) {
              locale = context.parse(options["locale"], 1, StringType);
              if (!locale) {
                return null;
              }
            }
            return new CollatorExpression(caseSensitive, diacriticSensitive, locale);
          };
          CollatorExpression.prototype.evaluate = function evaluate(ctx) {
            return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);
          };
          CollatorExpression.prototype.eachChild = function eachChild(fn) {
            fn(this.caseSensitive);
            fn(this.diacriticSensitive);
            if (this.locale) {
              fn(this.locale);
            }
          };
          CollatorExpression.prototype.outputDefined = function outputDefined() {
            return false;
          };
          CollatorExpression.prototype.serialize = function serialize2() {
            var options = {};
            options["case-sensitive"] = this.caseSensitive.serialize();
            options["diacritic-sensitive"] = this.diacriticSensitive.serialize();
            if (this.locale) {
              options["locale"] = this.locale.serialize();
            }
            return [
              "collator",
              options
            ];
          };
          var EXTENT = 8192;
          function updateBBox(bbox, coord) {
            bbox[0] = Math.min(bbox[0], coord[0]);
            bbox[1] = Math.min(bbox[1], coord[1]);
            bbox[2] = Math.max(bbox[2], coord[0]);
            bbox[3] = Math.max(bbox[3], coord[1]);
          }
          function mercatorXfromLng(lng) {
            return (180 + lng) / 360;
          }
          function mercatorYfromLat(lat) {
            return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;
          }
          function boxWithinBox(bbox1, bbox2) {
            if (bbox1[0] <= bbox2[0]) {
              return false;
            }
            if (bbox1[2] >= bbox2[2]) {
              return false;
            }
            if (bbox1[1] <= bbox2[1]) {
              return false;
            }
            if (bbox1[3] >= bbox2[3]) {
              return false;
            }
            return true;
          }
          function getTileCoordinates(p, canonical) {
            var x = mercatorXfromLng(p[0]);
            var y = mercatorYfromLat(p[1]);
            var tilesAtZoom = Math.pow(2, canonical.z);
            return [
              Math.round(x * tilesAtZoom * EXTENT),
              Math.round(y * tilesAtZoom * EXTENT)
            ];
          }
          function onBoundary(p, p1, p2) {
            var x1 = p[0] - p1[0];
            var y1 = p[1] - p1[1];
            var x2 = p[0] - p2[0];
            var y2 = p[1] - p2[1];
            return x1 * y2 - x2 * y1 === 0 && x1 * x2 <= 0 && y1 * y2 <= 0;
          }
          function rayIntersect(p, p1, p2) {
            return p1[1] > p[1] !== p2[1] > p[1] && p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0];
          }
          function pointWithinPolygon(point, rings) {
            var inside = false;
            for (var i = 0, len = rings.length; i < len; i++) {
              var ring = rings[i];
              for (var j = 0, len2 = ring.length; j < len2 - 1; j++) {
                if (onBoundary(point, ring[j], ring[j + 1])) {
                  return false;
                }
                if (rayIntersect(point, ring[j], ring[j + 1])) {
                  inside = !inside;
                }
              }
            }
            return inside;
          }
          function pointWithinPolygons(point, polygons) {
            for (var i = 0; i < polygons.length; i++) {
              if (pointWithinPolygon(point, polygons[i])) {
                return true;
              }
            }
            return false;
          }
          function perp(v1, v2) {
            return v1[0] * v2[1] - v1[1] * v2[0];
          }
          function twoSided(p1, p2, q1, q2) {
            var x1 = p1[0] - q1[0];
            var y1 = p1[1] - q1[1];
            var x2 = p2[0] - q1[0];
            var y2 = p2[1] - q1[1];
            var x3 = q2[0] - q1[0];
            var y3 = q2[1] - q1[1];
            var det1 = x1 * y3 - x3 * y1;
            var det2 = x2 * y3 - x3 * y2;
            if (det1 > 0 && det2 < 0 || det1 < 0 && det2 > 0) {
              return true;
            }
            return false;
          }
          function lineIntersectLine(a, b, c, d) {
            var vectorP = [
              b[0] - a[0],
              b[1] - a[1]
            ];
            var vectorQ = [
              d[0] - c[0],
              d[1] - c[1]
            ];
            if (perp(vectorQ, vectorP) === 0) {
              return false;
            }
            if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) {
              return true;
            }
            return false;
          }
          function lineIntersectPolygon(p1, p2, polygon) {
            for (var i = 0, list = polygon; i < list.length; i += 1) {
              var ring = list[i];
              for (var j = 0; j < ring.length - 1; ++j) {
                if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) {
                  return true;
                }
              }
            }
            return false;
          }
          function lineStringWithinPolygon(line, polygon) {
            for (var i = 0; i < line.length; ++i) {
              if (!pointWithinPolygon(line[i], polygon)) {
                return false;
              }
            }
            for (var i$1 = 0; i$1 < line.length - 1; ++i$1) {
              if (lineIntersectPolygon(line[i$1], line[i$1 + 1], polygon)) {
                return false;
              }
            }
            return true;
          }
          function lineStringWithinPolygons(line, polygons) {
            for (var i = 0; i < polygons.length; i++) {
              if (lineStringWithinPolygon(line, polygons[i])) {
                return true;
              }
            }
            return false;
          }
          function getTilePolygon(coordinates, bbox, canonical) {
            var polygon = [];
            for (var i = 0; i < coordinates.length; i++) {
              var ring = [];
              for (var j = 0; j < coordinates[i].length; j++) {
                var coord = getTileCoordinates(coordinates[i][j], canonical);
                updateBBox(bbox, coord);
                ring.push(coord);
              }
              polygon.push(ring);
            }
            return polygon;
          }
          function getTilePolygons(coordinates, bbox, canonical) {
            var polygons = [];
            for (var i = 0; i < coordinates.length; i++) {
              var polygon = getTilePolygon(coordinates[i], bbox, canonical);
              polygons.push(polygon);
            }
            return polygons;
          }
          function updatePoint(p, bbox, polyBBox, worldSize) {
            if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {
              var halfWorldSize = worldSize * 0.5;
              var shift = p[0] - polyBBox[0] > halfWorldSize ? -worldSize : polyBBox[0] - p[0] > halfWorldSize ? worldSize : 0;
              if (shift === 0) {
                shift = p[0] - polyBBox[2] > halfWorldSize ? -worldSize : polyBBox[2] - p[0] > halfWorldSize ? worldSize : 0;
              }
              p[0] += shift;
            }
            updateBBox(bbox, p);
          }
          function resetBBox(bbox) {
            bbox[0] = bbox[1] = Infinity;
            bbox[2] = bbox[3] = -Infinity;
          }
          function getTilePoints(geometry, pointBBox, polyBBox, canonical) {
            var worldSize = Math.pow(2, canonical.z) * EXTENT;
            var shifts = [
              canonical.x * EXTENT,
              canonical.y * EXTENT
            ];
            var tilePoints = [];
            for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) {
              var points = list$1[i$1];
              for (var i = 0, list = points; i < list.length; i += 1) {
                var point = list[i];
                var p = [
                  point.x + shifts[0],
                  point.y + shifts[1]
                ];
                updatePoint(p, pointBBox, polyBBox, worldSize);
                tilePoints.push(p);
              }
            }
            return tilePoints;
          }
          function getTileLines(geometry, lineBBox, polyBBox, canonical) {
            var worldSize = Math.pow(2, canonical.z) * EXTENT;
            var shifts = [
              canonical.x * EXTENT,
              canonical.y * EXTENT
            ];
            var tileLines = [];
            for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) {
              var line = list$1[i$1];
              var tileLine = [];
              for (var i = 0, list = line; i < list.length; i += 1) {
                var point = list[i];
                var p = [
                  point.x + shifts[0],
                  point.y + shifts[1]
                ];
                updateBBox(lineBBox, p);
                tileLine.push(p);
              }
              tileLines.push(tileLine);
            }
            if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {
              resetBBox(lineBBox);
              for (var i$3 = 0, list$3 = tileLines; i$3 < list$3.length; i$3 += 1) {
                var line$1 = list$3[i$3];
                for (var i$2 = 0, list$2 = line$1; i$2 < list$2.length; i$2 += 1) {
                  var p$1 = list$2[i$2];
                  updatePoint(p$1, lineBBox, polyBBox, worldSize);
                }
              }
            }
            return tileLines;
          }
          function pointsWithinPolygons(ctx, polygonGeometry) {
            var pointBBox = [
              Infinity,
              Infinity,
              -Infinity,
              -Infinity
            ];
            var polyBBox = [
              Infinity,
              Infinity,
              -Infinity,
              -Infinity
            ];
            var canonical = ctx.canonicalID();
            if (polygonGeometry.type === "Polygon") {
              var tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
              var tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
              if (!boxWithinBox(pointBBox, polyBBox)) {
                return false;
              }
              for (var i = 0, list = tilePoints; i < list.length; i += 1) {
                var point = list[i];
                if (!pointWithinPolygon(point, tilePolygon)) {
                  return false;
                }
              }
            }
            if (polygonGeometry.type === "MultiPolygon") {
              var tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
              var tilePoints$1 = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
              if (!boxWithinBox(pointBBox, polyBBox)) {
                return false;
              }
              for (var i$1 = 0, list$1 = tilePoints$1; i$1 < list$1.length; i$1 += 1) {
                var point$1 = list$1[i$1];
                if (!pointWithinPolygons(point$1, tilePolygons)) {
                  return false;
                }
              }
            }
            return true;
          }
          function linesWithinPolygons(ctx, polygonGeometry) {
            var lineBBox = [
              Infinity,
              Infinity,
              -Infinity,
              -Infinity
            ];
            var polyBBox = [
              Infinity,
              Infinity,
              -Infinity,
              -Infinity
            ];
            var canonical = ctx.canonicalID();
            if (polygonGeometry.type === "Polygon") {
              var tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
              var tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
              if (!boxWithinBox(lineBBox, polyBBox)) {
                return false;
              }
              for (var i = 0, list = tileLines; i < list.length; i += 1) {
                var line = list[i];
                if (!lineStringWithinPolygon(line, tilePolygon)) {
                  return false;
                }
              }
            }
            if (polygonGeometry.type === "MultiPolygon") {
              var tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
              var tileLines$1 = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
              if (!boxWithinBox(lineBBox, polyBBox)) {
                return false;
              }
              for (var i$1 = 0, list$1 = tileLines$1; i$1 < list$1.length; i$1 += 1) {
                var line$1 = list$1[i$1];
                if (!lineStringWithinPolygons(line$1, tilePolygons)) {
                  return false;
                }
              }
            }
            return true;
          }
          var Within = function Within2(geojson, geometries) {
            this.type = BooleanType;
            this.geojson = geojson;
            this.geometries = geometries;
          };
          Within.parse = function parse2(args, context) {
            if (args.length !== 2) {
              return context.error("'within' expression requires exactly one argument, but found " + (args.length - 1) + " instead.");
            }
            if (isValue(args[1])) {
              var geojson = args[1];
              if (geojson.type === "FeatureCollection") {
                for (var i = 0; i < geojson.features.length; ++i) {
                  var type = geojson.features[i].geometry.type;
                  if (type === "Polygon" || type === "MultiPolygon") {
                    return new Within(geojson, geojson.features[i].geometry);
                  }
                }
              } else if (geojson.type === "Feature") {
                var type$1 = geojson.geometry.type;
                if (type$1 === "Polygon" || type$1 === "MultiPolygon") {
                  return new Within(geojson, geojson.geometry);
                }
              } else if (geojson.type === "Polygon" || geojson.type === "MultiPolygon") {
                return new Within(geojson, geojson);
              }
            }
            return context.error("'within' expression requires valid geojson object that contains polygon geometry type.");
          };
          Within.prototype.evaluate = function evaluate(ctx) {
            if (ctx.geometry() != null && ctx.canonicalID() != null) {
              if (ctx.geometryType() === "Point") {
                return pointsWithinPolygons(ctx, this.geometries);
              } else if (ctx.geometryType() === "LineString") {
                return linesWithinPolygons(ctx, this.geometries);
              }
            }
            return false;
          };
          Within.prototype.eachChild = function eachChild() {
          };
          Within.prototype.outputDefined = function outputDefined() {
            return true;
          };
          Within.prototype.serialize = function serialize2() {
            return [
              "within",
              this.geojson
            ];
          };
          function isFeatureConstant(e) {
            if (e instanceof CompoundExpression) {
              if (e.name === "get" && e.args.length === 1) {
                return false;
              } else if (e.name === "feature-state") {
                return false;
              } else if (e.name === "has" && e.args.length === 1) {
                return false;
              } else if (e.name === "properties" || e.name === "geometry-type" || e.name === "id") {
                return false;
              } else if (/^filter-/.test(e.name)) {
                return false;
              }
            }
            if (e instanceof Within) {
              return false;
            }
            var result = true;
            e.eachChild(function(arg) {
              if (result && !isFeatureConstant(arg)) {
                result = false;
              }
            });
            return result;
          }
          function isStateConstant(e) {
            if (e instanceof CompoundExpression) {
              if (e.name === "feature-state") {
                return false;
              }
            }
            var result = true;
            e.eachChild(function(arg) {
              if (result && !isStateConstant(arg)) {
                result = false;
              }
            });
            return result;
          }
          function isGlobalPropertyConstant(e, properties2) {
            if (e instanceof CompoundExpression && properties2.indexOf(e.name) >= 0) {
              return false;
            }
            var result = true;
            e.eachChild(function(arg) {
              if (result && !isGlobalPropertyConstant(arg, properties2)) {
                result = false;
              }
            });
            return result;
          }
          var Var = function Var2(name3, boundExpression) {
            this.type = boundExpression.type;
            this.name = name3;
            this.boundExpression = boundExpression;
          };
          Var.parse = function parse2(args, context) {
            if (args.length !== 2 || typeof args[1] !== "string") {
              return context.error("'var' expression requires exactly one string literal argument.");
            }
            var name3 = args[1];
            if (!context.scope.has(name3)) {
              return context.error('Unknown variable "' + name3 + '". Make sure "' + name3 + '" has been bound in an enclosing "let" expression before using it.', 1);
            }
            return new Var(name3, context.scope.get(name3));
          };
          Var.prototype.evaluate = function evaluate(ctx) {
            return this.boundExpression.evaluate(ctx);
          };
          Var.prototype.eachChild = function eachChild() {
          };
          Var.prototype.outputDefined = function outputDefined() {
            return false;
          };
          Var.prototype.serialize = function serialize2() {
            return [
              "var",
              this.name
            ];
          };
          var ParsingContext = function ParsingContext2(registry2, path, expectedType, scope, errors) {
            if (path === void 0)
              path = [];
            if (scope === void 0)
              scope = new Scope();
            if (errors === void 0)
              errors = [];
            this.registry = registry2;
            this.path = path;
            this.key = path.map(function(part) {
              return "[" + part + "]";
            }).join("");
            this.scope = scope;
            this.errors = errors;
            this.expectedType = expectedType;
          };
          ParsingContext.prototype.parse = function parse2(expr, index, expectedType, bindings, options) {
            if (options === void 0)
              options = {};
            if (index) {
              return this.concat(index, expectedType, bindings)._parse(expr, options);
            }
            return this._parse(expr, options);
          };
          ParsingContext.prototype._parse = function _parse(expr, options) {
            if (expr === null || typeof expr === "string" || typeof expr === "boolean" || typeof expr === "number") {
              expr = [
                "literal",
                expr
              ];
            }
            function annotate(parsed2, type, typeAnnotation) {
              if (typeAnnotation === "assert") {
                return new Assertion(type, [parsed2]);
              } else if (typeAnnotation === "coerce") {
                return new Coercion(type, [parsed2]);
              } else {
                return parsed2;
              }
            }
            if (Array.isArray(expr)) {
              if (expr.length === 0) {
                return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');
              }
              var op = expr[0];
              if (typeof op !== "string") {
                this.error("Expression name must be a string, but found " + typeof op + ' instead. If you wanted a literal array, use ["literal", [...]].', 0);
                return null;
              }
              var Expr = this.registry[op];
              if (Expr) {
                var parsed = Expr.parse(expr, this);
                if (!parsed) {
                  return null;
                }
                if (this.expectedType) {
                  var expected = this.expectedType;
                  var actual = parsed.type;
                  if ((expected.kind === "string" || expected.kind === "number" || expected.kind === "boolean" || expected.kind === "object" || expected.kind === "array") && actual.kind === "value") {
                    parsed = annotate(parsed, expected, options.typeAnnotation || "assert");
                  } else if ((expected.kind === "color" || expected.kind === "formatted" || expected.kind === "resolvedImage") && (actual.kind === "value" || actual.kind === "string")) {
                    parsed = annotate(parsed, expected, options.typeAnnotation || "coerce");
                  } else if (this.checkSubtype(expected, actual)) {
                    return null;
                  }
                }
                if (!(parsed instanceof Literal) && parsed.type.kind !== "resolvedImage" && isConstant(parsed)) {
                  var ec = new EvaluationContext();
                  try {
                    parsed = new Literal(parsed.type, parsed.evaluate(ec));
                  } catch (e) {
                    this.error(e.message);
                    return null;
                  }
                }
                return parsed;
              }
              return this.error('Unknown expression "' + op + '". If you wanted a literal array, use ["literal", [...]].', 0);
            } else if (typeof expr === "undefined") {
              return this.error("'undefined' value invalid. Use null instead.");
            } else if (typeof expr === "object") {
              return this.error('Bare objects invalid. Use ["literal", {...}] instead.');
            } else {
              return this.error("Expected an array, but found " + typeof expr + " instead.");
            }
          };
          ParsingContext.prototype.concat = function concat(index, expectedType, bindings) {
            var path = typeof index === "number" ? this.path.concat(index) : this.path;
            var scope = bindings ? this.scope.concat(bindings) : this.scope;
            return new ParsingContext(this.registry, path, expectedType || null, scope, this.errors);
          };
          ParsingContext.prototype.error = function error2(error$1) {
            var keys = [], len = arguments.length - 1;
            while (len-- > 0)
              keys[len] = arguments[len + 1];
            var key = "" + this.key + keys.map(function(k) {
              return "[" + k + "]";
            }).join("");
            this.errors.push(new ParsingError(key, error$1));
          };
          ParsingContext.prototype.checkSubtype = function checkSubtype$1(expected, t) {
            var error2 = checkSubtype(expected, t);
            if (error2) {
              this.error(error2);
            }
            return error2;
          };
          function isConstant(expression2) {
            if (expression2 instanceof Var) {
              return isConstant(expression2.boundExpression);
            } else if (expression2 instanceof CompoundExpression && expression2.name === "error") {
              return false;
            } else if (expression2 instanceof CollatorExpression) {
              return false;
            } else if (expression2 instanceof Within) {
              return false;
            }
            var isTypeAnnotation = expression2 instanceof Coercion || expression2 instanceof Assertion;
            var childrenConstant = true;
            expression2.eachChild(function(child) {
              if (isTypeAnnotation) {
                childrenConstant = childrenConstant && isConstant(child);
              } else {
                childrenConstant = childrenConstant && child instanceof Literal;
              }
            });
            if (!childrenConstant) {
              return false;
            }
            return isFeatureConstant(expression2) && isGlobalPropertyConstant(expression2, [
              "zoom",
              "heatmap-density",
              "line-progress",
              "accumulated",
              "is-supported-script"
            ]);
          }
          function findStopLessThanOrEqualTo(stops, input) {
            var lastIndex = stops.length - 1;
            var lowerIndex = 0;
            var upperIndex = lastIndex;
            var currentIndex = 0;
            var currentValue, nextValue;
            while (lowerIndex <= upperIndex) {
              currentIndex = Math.floor((lowerIndex + upperIndex) / 2);
              currentValue = stops[currentIndex];
              nextValue = stops[currentIndex + 1];
              if (currentValue <= input) {
                if (currentIndex === lastIndex || input < nextValue) {
                  return currentIndex;
                }
                lowerIndex = currentIndex + 1;
              } else if (currentValue > input) {
                upperIndex = currentIndex - 1;
              } else {
                throw new RuntimeError("Input is not a number.");
              }
            }
            return 0;
          }
          var Step = function Step2(type, input, stops) {
            this.type = type;
            this.input = input;
            this.labels = [];
            this.outputs = [];
            for (var i = 0, list = stops; i < list.length; i += 1) {
              var ref = list[i];
              var label = ref[0];
              var expression2 = ref[1];
              this.labels.push(label);
              this.outputs.push(expression2);
            }
          };
          Step.parse = function parse2(args, context) {
            if (args.length - 1 < 4) {
              return context.error("Expected at least 4 arguments, but found only " + (args.length - 1) + ".");
            }
            if ((args.length - 1) % 2 !== 0) {
              return context.error("Expected an even number of arguments.");
            }
            var input = context.parse(args[1], 1, NumberType);
            if (!input) {
              return null;
            }
            var stops = [];
            var outputType = null;
            if (context.expectedType && context.expectedType.kind !== "value") {
              outputType = context.expectedType;
            }
            for (var i = 1; i < args.length; i += 2) {
              var label = i === 1 ? -Infinity : args[i];
              var value = args[i + 1];
              var labelKey = i;
              var valueKey = i + 1;
              if (typeof label !== "number") {
                return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);
              }
              if (stops.length && stops[stops.length - 1][0] >= label) {
                return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey);
              }
              var parsed = context.parse(value, valueKey, outputType);
              if (!parsed) {
                return null;
              }
              outputType = outputType || parsed.type;
              stops.push([
                label,
                parsed
              ]);
            }
            return new Step(outputType, input, stops);
          };
          Step.prototype.evaluate = function evaluate(ctx) {
            var labels = this.labels;
            var outputs = this.outputs;
            if (labels.length === 1) {
              return outputs[0].evaluate(ctx);
            }
            var value = this.input.evaluate(ctx);
            if (value <= labels[0]) {
              return outputs[0].evaluate(ctx);
            }
            var stopCount = labels.length;
            if (value >= labels[stopCount - 1]) {
              return outputs[stopCount - 1].evaluate(ctx);
            }
            var index = findStopLessThanOrEqualTo(labels, value);
            return outputs[index].evaluate(ctx);
          };
          Step.prototype.eachChild = function eachChild(fn) {
            fn(this.input);
            for (var i = 0, list = this.outputs; i < list.length; i += 1) {
              var expression2 = list[i];
              fn(expression2);
            }
          };
          Step.prototype.outputDefined = function outputDefined() {
            return this.outputs.every(function(out) {
              return out.outputDefined();
            });
          };
          Step.prototype.serialize = function serialize2() {
            var serialized = [
              "step",
              this.input.serialize()
            ];
            for (var i = 0; i < this.labels.length; i++) {
              if (i > 0) {
                serialized.push(this.labels[i]);
              }
              serialized.push(this.outputs[i].serialize());
            }
            return serialized;
          };
          function number(a, b, t) {
            return a * (1 - t) + b * t;
          }
          function color2(from, to, t) {
            return new Color2(number(from.r, to.r, t), number(from.g, to.g, t), number(from.b, to.b, t), number(from.a, to.a, t));
          }
          function array$1(from, to, t) {
            return from.map(function(d, i) {
              return number(d, to[i], t);
            });
          }
          var interpolate = /* @__PURE__ */ Object.freeze({
            __proto__: null,
            number,
            color: color2,
            array: array$1
          });
          var Xn2 = 0.95047, Yn2 = 1, Zn2 = 1.08883, t02 = 4 / 29, t12 = 6 / 29, t22 = 3 * t12 * t12, t32 = t12 * t12 * t12, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI;
          function xyz2lab2(t) {
            return t > t32 ? Math.pow(t, 1 / 3) : t / t22 + t02;
          }
          function lab2xyz2(t) {
            return t > t12 ? t * t * t : t22 * (t - t02);
          }
          function xyz2rgb(x) {
            return 255 * (x <= 31308e-7 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
          }
          function rgb2xyz(x) {
            x /= 255;
            return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
          }
          function rgbToLab(rgbColor) {
            var b = rgb2xyz(rgbColor.r), a = rgb2xyz(rgbColor.g), l = rgb2xyz(rgbColor.b), x = xyz2lab2((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn2), y = xyz2lab2((0.2126729 * b + 0.7151522 * a + 0.072175 * l) / Yn2), z = xyz2lab2((0.0193339 * b + 0.119192 * a + 0.9503041 * l) / Zn2);
            return {
              l: 116 * y - 16,
              a: 500 * (x - y),
              b: 200 * (y - z),
              alpha: rgbColor.a
            };
          }
          function labToRgb(labColor) {
            var y = (labColor.l + 16) / 116, x = isNaN(labColor.a) ? y : y + labColor.a / 500, z = isNaN(labColor.b) ? y : y - labColor.b / 200;
            y = Yn2 * lab2xyz2(y);
            x = Xn2 * lab2xyz2(x);
            z = Zn2 * lab2xyz2(z);
            return new Color2(xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), xyz2rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z), xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z), labColor.alpha);
          }
          function interpolateLab(from, to, t) {
            return {
              l: number(from.l, to.l, t),
              a: number(from.a, to.a, t),
              b: number(from.b, to.b, t),
              alpha: number(from.alpha, to.alpha, t)
            };
          }
          function rgbToHcl(rgbColor) {
            var ref = rgbToLab(rgbColor);
            var l = ref.l;
            var a = ref.a;
            var b = ref.b;
            var h = Math.atan2(b, a) * rad2deg;
            return {
              h: h < 0 ? h + 360 : h,
              c: Math.sqrt(a * a + b * b),
              l,
              alpha: rgbColor.a
            };
          }
          function hclToRgb(hclColor) {
            var h = hclColor.h * deg2rad, c = hclColor.c, l = hclColor.l;
            return labToRgb({
              l,
              a: Math.cos(h) * c,
              b: Math.sin(h) * c,
              alpha: hclColor.alpha
            });
          }
          function interpolateHue(a, b, t) {
            var d = b - a;
            return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d);
          }
          function interpolateHcl(from, to, t) {
            return {
              h: interpolateHue(from.h, to.h, t),
              c: number(from.c, to.c, t),
              l: number(from.l, to.l, t),
              alpha: number(from.alpha, to.alpha, t)
            };
          }
          var lab3 = {
            forward: rgbToLab,
            reverse: labToRgb,
            interpolate: interpolateLab
          };
          var hcl3 = {
            forward: rgbToHcl,
            reverse: hclToRgb,
            interpolate: interpolateHcl
          };
          var colorSpaces = /* @__PURE__ */ Object.freeze({
            __proto__: null,
            lab: lab3,
            hcl: hcl3
          });
          var Interpolate = function Interpolate2(type, operator, interpolation, input, stops) {
            this.type = type;
            this.operator = operator;
            this.interpolation = interpolation;
            this.input = input;
            this.labels = [];
            this.outputs = [];
            for (var i = 0, list = stops; i < list.length; i += 1) {
              var ref = list[i];
              var label = ref[0];
              var expression2 = ref[1];
              this.labels.push(label);
              this.outputs.push(expression2);
            }
          };
          Interpolate.interpolationFactor = function interpolationFactor2(interpolation, input, lower, upper) {
            var t = 0;
            if (interpolation.name === "exponential") {
              t = exponentialInterpolation(input, interpolation.base, lower, upper);
            } else if (interpolation.name === "linear") {
              t = exponentialInterpolation(input, 1, lower, upper);
            } else if (interpolation.name === "cubic-bezier") {
              var c = interpolation.controlPoints;
              var ub = new unitbezier(c[0], c[1], c[2], c[3]);
              t = ub.solve(exponentialInterpolation(input, 1, lower, upper));
            }
            return t;
          };
          Interpolate.parse = function parse2(args, context) {
            var operator = args[0];
            var interpolation = args[1];
            var input = args[2];
            var rest = args.slice(3);
            if (!Array.isArray(interpolation) || interpolation.length === 0) {
              return context.error("Expected an interpolation type expression.", 1);
            }
            if (interpolation[0] === "linear") {
              interpolation = { name: "linear" };
            } else if (interpolation[0] === "exponential") {
              var base = interpolation[1];
              if (typeof base !== "number") {
                return context.error("Exponential interpolation requires a numeric base.", 1, 1);
              }
              interpolation = {
                name: "exponential",
                base
              };
            } else if (interpolation[0] === "cubic-bezier") {
              var controlPoints = interpolation.slice(1);
              if (controlPoints.length !== 4 || controlPoints.some(function(t) {
                return typeof t !== "number" || t < 0 || t > 1;
              })) {
                return context.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.", 1);
              }
              interpolation = {
                name: "cubic-bezier",
                controlPoints
              };
            } else {
              return context.error("Unknown interpolation type " + String(interpolation[0]), 1, 0);
            }
            if (args.length - 1 < 4) {
              return context.error("Expected at least 4 arguments, but found only " + (args.length - 1) + ".");
            }
            if ((args.length - 1) % 2 !== 0) {
              return context.error("Expected an even number of arguments.");
            }
            input = context.parse(input, 2, NumberType);
            if (!input) {
              return null;
            }
            var stops = [];
            var outputType = null;
            if (operator === "interpolate-hcl" || operator === "interpolate-lab") {
              outputType = ColorType;
            } else if (context.expectedType && context.expectedType.kind !== "value") {
              outputType = context.expectedType;
            }
            for (var i = 0; i < rest.length; i += 2) {
              var label = rest[i];
              var value = rest[i + 1];
              var labelKey = i + 3;
              var valueKey = i + 4;
              if (typeof label !== "number") {
                return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);
              }
              if (stops.length && stops[stops.length - 1][0] >= label) {
                return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey);
              }
              var parsed = context.parse(value, valueKey, outputType);
              if (!parsed) {
                return null;
              }
              outputType = outputType || parsed.type;
              stops.push([
                label,
                parsed
              ]);
            }
            if (outputType.kind !== "number" && outputType.kind !== "color" && !(outputType.kind === "array" && outputType.itemType.kind === "number" && typeof outputType.N === "number")) {
              return context.error("Type " + toString(outputType) + " is not interpolatable.");
            }
            return new Interpolate(outputType, operator, interpolation, input, stops);
          };
          Interpolate.prototype.evaluate = function evaluate(ctx) {
            var labels = this.labels;
            var outputs = this.outputs;
            if (labels.length === 1) {
              return outputs[0].evaluate(ctx);
            }
            var value = this.input.evaluate(ctx);
            if (value <= labels[0]) {
              return outputs[0].evaluate(ctx);
            }
            var stopCount = labels.length;
            if (value >= labels[stopCount - 1]) {
              return outputs[stopCount - 1].evaluate(ctx);
            }
            var index = findStopLessThanOrEqualTo(labels, value);
            var lower = labels[index];
            var upper = labels[index + 1];
            var t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);
            var outputLower = outputs[index].evaluate(ctx);
            var outputUpper = outputs[index + 1].evaluate(ctx);
            if (this.operator === "interpolate") {
              return interpolate[this.type.kind.toLowerCase()](outputLower, outputUpper, t);
            } else if (this.operator === "interpolate-hcl") {
              return hcl3.reverse(hcl3.interpolate(hcl3.forward(outputLower), hcl3.forward(outputUpper), t));
            } else {
              return lab3.reverse(lab3.interpolate(lab3.forward(outputLower), lab3.forward(outputUpper), t));
            }
          };
          Interpolate.prototype.eachChild = function eachChild(fn) {
            fn(this.input);
            for (var i = 0, list = this.outputs; i < list.length; i += 1) {
              var expression2 = list[i];
              fn(expression2);
            }
          };
          Interpolate.prototype.outputDefined = function outputDefined() {
            return this.outputs.every(function(out) {
              return out.outputDefined();
            });
          };
          Interpolate.prototype.serialize = function serialize2() {
            var interpolation;
            if (this.interpolation.name === "linear") {
              interpolation = ["linear"];
            } else if (this.interpolation.name === "exponential") {
              if (this.interpolation.base === 1) {
                interpolation = ["linear"];
              } else {
                interpolation = [
                  "exponential",
                  this.interpolation.base
                ];
              }
            } else {
              interpolation = ["cubic-bezier"].concat(this.interpolation.controlPoints);
            }
            var serialized = [
              this.operator,
              interpolation,
              this.input.serialize()
            ];
            for (var i = 0; i < this.labels.length; i++) {
              serialized.push(this.labels[i], this.outputs[i].serialize());
            }
            return serialized;
          };
          function exponentialInterpolation(input, base, lowerValue, upperValue) {
            var difference = upperValue - lowerValue;
            var progress = input - lowerValue;
            if (difference === 0) {
              return 0;
            } else if (base === 1) {
              return progress / difference;
            } else {
              return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);
            }
          }
          var Coalesce = function Coalesce2(type, args) {
            this.type = type;
            this.args = args;
          };
          Coalesce.parse = function parse2(args, context) {
            if (args.length < 2) {
              return context.error("Expectected at least one argument.");
            }
            var outputType = null;
            var expectedType = context.expectedType;
            if (expectedType && expectedType.kind !== "value") {
              outputType = expectedType;
            }
            var parsedArgs = [];
            for (var i = 0, list = args.slice(1); i < list.length; i += 1) {
              var arg = list[i];
              var parsed = context.parse(arg, 1 + parsedArgs.length, outputType, void 0, { typeAnnotation: "omit" });
              if (!parsed) {
                return null;
              }
              outputType = outputType || parsed.type;
              parsedArgs.push(parsed);
            }
            var needsAnnotation = expectedType && parsedArgs.some(function(arg2) {
              return checkSubtype(expectedType, arg2.type);
            });
            return needsAnnotation ? new Coalesce(ValueType, parsedArgs) : new Coalesce(outputType, parsedArgs);
          };
          Coalesce.prototype.evaluate = function evaluate(ctx) {
            var result = null;
            var argCount = 0;
            var requestedImageName;
            for (var i = 0, list = this.args; i < list.length; i += 1) {
              var arg = list[i];
              argCount++;
              result = arg.evaluate(ctx);
              if (result && result instanceof ResolvedImage && !result.available) {
                if (!requestedImageName) {
                  requestedImageName = result.name;
                }
                result = null;
                if (argCount === this.args.length) {
                  result = requestedImageName;
                }
              }
              if (result !== null) {
                break;
              }
            }
            return result;
          };
          Coalesce.prototype.eachChild = function eachChild(fn) {
            this.args.forEach(fn);
          };
          Coalesce.prototype.outputDefined = function outputDefined() {
            return this.args.every(function(arg) {
              return arg.outputDefined();
            });
          };
          Coalesce.prototype.serialize = function serialize2() {
            var serialized = ["coalesce"];
            this.eachChild(function(child) {
              serialized.push(child.serialize());
            });
            return serialized;
          };
          var Let = function Let2(bindings, result) {
            this.type = result.type;
            this.bindings = [].concat(bindings);
            this.result = result;
          };
          Let.prototype.evaluate = function evaluate(ctx) {
            return this.result.evaluate(ctx);
          };
          Let.prototype.eachChild = function eachChild(fn) {
            for (var i = 0, list = this.bindings; i < list.length; i += 1) {
              var binding = list[i];
              fn(binding[1]);
            }
            fn(this.result);
          };
          Let.parse = function parse2(args, context) {
            if (args.length < 4) {
              return context.error("Expected at least 3 arguments, but found " + (args.length - 1) + " instead.");
            }
            var bindings = [];
            for (var i = 1; i < args.length - 1; i += 2) {
              var name3 = args[i];
              if (typeof name3 !== "string") {
                return context.error("Expected string, but found " + typeof name3 + " instead.", i);
              }
              if (/[^a-zA-Z0-9_]/.test(name3)) {
                return context.error("Variable names must contain only alphanumeric characters or '_'.", i);
              }
              var value = context.parse(args[i + 1], i + 1);
              if (!value) {
                return null;
              }
              bindings.push([
                name3,
                value
              ]);
            }
            var result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);
            if (!result) {
              return null;
            }
            return new Let(bindings, result);
          };
          Let.prototype.outputDefined = function outputDefined() {
            return this.result.outputDefined();
          };
          Let.prototype.serialize = function serialize2() {
            var serialized = ["let"];
            for (var i = 0, list = this.bindings; i < list.length; i += 1) {
              var ref = list[i];
              var name3 = ref[0];
              var expr = ref[1];
              serialized.push(name3, expr.serialize());
            }
            serialized.push(this.result.serialize());
            return serialized;
          };
          var At = function At2(type, index, input) {
            this.type = type;
            this.index = index;
            this.input = input;
          };
          At.parse = function parse2(args, context) {
            if (args.length !== 3) {
              return context.error("Expected 2 arguments, but found " + (args.length - 1) + " instead.");
            }
            var index = context.parse(args[1], 1, NumberType);
            var input = context.parse(args[2], 2, array(context.expectedType || ValueType));
            if (!index || !input) {
              return null;
            }
            var t = input.type;
            return new At(t.itemType, index, input);
          };
          At.prototype.evaluate = function evaluate(ctx) {
            var index = this.index.evaluate(ctx);
            var array2 = this.input.evaluate(ctx);
            if (index < 0) {
              throw new RuntimeError("Array index out of bounds: " + index + " < 0.");
            }
            if (index >= array2.length) {
              throw new RuntimeError("Array index out of bounds: " + index + " > " + (array2.length - 1) + ".");
            }
            if (index !== Math.floor(index)) {
              throw new RuntimeError("Array index must be an integer, but found " + index + " instead.");
            }
            return array2[index];
          };
          At.prototype.eachChild = function eachChild(fn) {
            fn(this.index);
            fn(this.input);
          };
          At.prototype.outputDefined = function outputDefined() {
            return false;
          };
          At.prototype.serialize = function serialize2() {
            return [
              "at",
              this.index.serialize(),
              this.input.serialize()
            ];
          };
          var In = function In2(needle, haystack) {
            this.type = BooleanType;
            this.needle = needle;
            this.haystack = haystack;
          };
          In.parse = function parse2(args, context) {
            if (args.length !== 3) {
              return context.error("Expected 2 arguments, but found " + (args.length - 1) + " instead.");
            }
            var needle = context.parse(args[1], 1, ValueType);
            var haystack = context.parse(args[2], 2, ValueType);
            if (!needle || !haystack) {
              return null;
            }
            if (!isValidType(needle.type, [
              BooleanType,
              StringType,
              NumberType,
              NullType,
              ValueType
            ])) {
              return context.error("Expected first argument to be of type boolean, string, number or null, but found " + toString(needle.type) + " instead");
            }
            return new In(needle, haystack);
          };
          In.prototype.evaluate = function evaluate(ctx) {
            var needle = this.needle.evaluate(ctx);
            var haystack = this.haystack.evaluate(ctx);
            if (!haystack) {
              return false;
            }
            if (!isValidNativeType(needle, [
              "boolean",
              "string",
              "number",
              "null"
            ])) {
              throw new RuntimeError("Expected first argument to be of type boolean, string, number or null, but found " + toString(typeOf(needle)) + " instead.");
            }
            if (!isValidNativeType(haystack, [
              "string",
              "array"
            ])) {
              throw new RuntimeError("Expected second argument to be of type array or string, but found " + toString(typeOf(haystack)) + " instead.");
            }
            return haystack.indexOf(needle) >= 0;
          };
          In.prototype.eachChild = function eachChild(fn) {
            fn(this.needle);
            fn(this.haystack);
          };
          In.prototype.outputDefined = function outputDefined() {
            return true;
          };
          In.prototype.serialize = function serialize2() {
            return [
              "in",
              this.needle.serialize(),
              this.haystack.serialize()
            ];
          };
          var IndexOf = function IndexOf2(needle, haystack, fromIndex) {
            this.type = NumberType;
            this.needle = needle;
            this.haystack = haystack;
            this.fromIndex = fromIndex;
          };
          IndexOf.parse = function parse2(args, context) {
            if (args.length <= 2 || args.length >= 5) {
              return context.error("Expected 3 or 4 arguments, but found " + (args.length - 1) + " instead.");
            }
            var needle = context.parse(args[1], 1, ValueType);
            var haystack = context.parse(args[2], 2, ValueType);
            if (!needle || !haystack) {
              return null;
            }
            if (!isValidType(needle.type, [
              BooleanType,
              StringType,
              NumberType,
              NullType,
              ValueType
            ])) {
              return context.error("Expected first argument to be of type boolean, string, number or null, but found " + toString(needle.type) + " instead");
            }
            if (args.length === 4) {
              var fromIndex = context.parse(args[3], 3, NumberType);
              if (!fromIndex) {
                return null;
              }
              return new IndexOf(needle, haystack, fromIndex);
            } else {
              return new IndexOf(needle, haystack);
            }
          };
          IndexOf.prototype.evaluate = function evaluate(ctx) {
            var needle = this.needle.evaluate(ctx);
            var haystack = this.haystack.evaluate(ctx);
            if (!isValidNativeType(needle, [
              "boolean",
              "string",
              "number",
              "null"
            ])) {
              throw new RuntimeError("Expected first argument to be of type boolean, string, number or null, but found " + toString(typeOf(needle)) + " instead.");
            }
            if (!isValidNativeType(haystack, [
              "string",
              "array"
            ])) {
              throw new RuntimeError("Expected second argument to be of type array or string, but found " + toString(typeOf(haystack)) + " instead.");
            }
            if (this.fromIndex) {
              var fromIndex = this.fromIndex.evaluate(ctx);
              return haystack.indexOf(needle, fromIndex);
            }
            return haystack.indexOf(needle);
          };
          IndexOf.prototype.eachChild = function eachChild(fn) {
            fn(this.needle);
            fn(this.haystack);
            if (this.fromIndex) {
              fn(this.fromIndex);
            }
          };
          IndexOf.prototype.outputDefined = function outputDefined() {
            return false;
          };
          IndexOf.prototype.serialize = function serialize2() {
            if (this.fromIndex != null && this.fromIndex !== void 0) {
              var fromIndex = this.fromIndex.serialize();
              return [
                "index-of",
                this.needle.serialize(),
                this.haystack.serialize(),
                fromIndex
              ];
            }
            return [
              "index-of",
              this.needle.serialize(),
              this.haystack.serialize()
            ];
          };
          var Match = function Match2(inputType, outputType, input, cases, outputs, otherwise) {
            this.inputType = inputType;
            this.type = outputType;
            this.input = input;
            this.cases = cases;
            this.outputs = outputs;
            this.otherwise = otherwise;
          };
          Match.parse = function parse2(args, context) {
            if (args.length < 5) {
              return context.error("Expected at least 4 arguments, but found only " + (args.length - 1) + ".");
            }
            if (args.length % 2 !== 1) {
              return context.error("Expected an even number of arguments.");
            }
            var inputType;
            var outputType;
            if (context.expectedType && context.expectedType.kind !== "value") {
              outputType = context.expectedType;
            }
            var cases = {};
            var outputs = [];
            for (var i = 2; i < args.length - 1; i += 2) {
              var labels = args[i];
              var value = args[i + 1];
              if (!Array.isArray(labels)) {
                labels = [labels];
              }
              var labelContext = context.concat(i);
              if (labels.length === 0) {
                return labelContext.error("Expected at least one branch label.");
              }
              for (var i$1 = 0, list = labels; i$1 < list.length; i$1 += 1) {
                var label = list[i$1];
                if (typeof label !== "number" && typeof label !== "string") {
                  return labelContext.error("Branch labels must be numbers or strings.");
                } else if (typeof label === "number" && Math.abs(label) > Number.MAX_SAFE_INTEGER) {
                  return labelContext.error("Branch labels must be integers no larger than " + Number.MAX_SAFE_INTEGER + ".");
                } else if (typeof label === "number" && Math.floor(label) !== label) {
                  return labelContext.error("Numeric branch labels must be integer values.");
                } else if (!inputType) {
                  inputType = typeOf(label);
                } else if (labelContext.checkSubtype(inputType, typeOf(label))) {
                  return null;
                }
                if (typeof cases[String(label)] !== "undefined") {
                  return labelContext.error("Branch labels must be unique.");
                }
                cases[String(label)] = outputs.length;
              }
              var result = context.parse(value, i, outputType);
              if (!result) {
                return null;
              }
              outputType = outputType || result.type;
              outputs.push(result);
            }
            var input = context.parse(args[1], 1, ValueType);
            if (!input) {
              return null;
            }
            var otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);
            if (!otherwise) {
              return null;
            }
            if (input.type.kind !== "value" && context.concat(1).checkSubtype(inputType, input.type)) {
              return null;
            }
            return new Match(inputType, outputType, input, cases, outputs, otherwise);
          };
          Match.prototype.evaluate = function evaluate(ctx) {
            var input = this.input.evaluate(ctx);
            var output = typeOf(input) === this.inputType && this.outputs[this.cases[input]] || this.otherwise;
            return output.evaluate(ctx);
          };
          Match.prototype.eachChild = function eachChild(fn) {
            fn(this.input);
            this.outputs.forEach(fn);
            fn(this.otherwise);
          };
          Match.prototype.outputDefined = function outputDefined() {
            return this.outputs.every(function(out) {
              return out.outputDefined();
            }) && this.otherwise.outputDefined();
          };
          Match.prototype.serialize = function serialize2() {
            var this$1 = this;
            var serialized = [
              "match",
              this.input.serialize()
            ];
            var sortedLabels = Object.keys(this.cases).sort();
            var groupedByOutput = [];
            var outputLookup = {};
            for (var i = 0, list = sortedLabels; i < list.length; i += 1) {
              var label = list[i];
              var outputIndex = outputLookup[this.cases[label]];
              if (outputIndex === void 0) {
                outputLookup[this.cases[label]] = groupedByOutput.length;
                groupedByOutput.push([
                  this.cases[label],
                  [label]
                ]);
              } else {
                groupedByOutput[outputIndex][1].push(label);
              }
            }
            var coerceLabel = function(label2) {
              return this$1.inputType.kind === "number" ? Number(label2) : label2;
            };
            for (var i$1 = 0, list$1 = groupedByOutput; i$1 < list$1.length; i$1 += 1) {
              var ref = list$1[i$1];
              var outputIndex = ref[0];
              var labels = ref[1];
              if (labels.length === 1) {
                serialized.push(coerceLabel(labels[0]));
              } else {
                serialized.push(labels.map(coerceLabel));
              }
              serialized.push(this.outputs[outputIndex$1].serialize());
            }
            serialized.push(this.otherwise.serialize());
            return serialized;
          };
          var Case = function Case2(type, branches, otherwise) {
            this.type = type;
            this.branches = branches;
            this.otherwise = otherwise;
          };
          Case.parse = function parse2(args, context) {
            if (args.length < 4) {
              return context.error("Expected at least 3 arguments, but found only " + (args.length - 1) + ".");
            }
            if (args.length % 2 !== 0) {
              return context.error("Expected an odd number of arguments.");
            }
            var outputType;
            if (context.expectedType && context.expectedType.kind !== "value") {
              outputType = context.expectedType;
            }
            var branches = [];
            for (var i = 1; i < args.length - 1; i += 2) {
              var test = context.parse(args[i], i, BooleanType);
              if (!test) {
                return null;
              }
              var result = context.parse(args[i + 1], i + 1, outputType);
              if (!result) {
                return null;
              }
              branches.push([
                test,
                result
              ]);
              outputType = outputType || result.type;
            }
            var otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);
            if (!otherwise) {
              return null;
            }
            return new Case(outputType, branches, otherwise);
          };
          Case.prototype.evaluate = function evaluate(ctx) {
            for (var i = 0, list = this.branches; i < list.length; i += 1) {
              var ref = list[i];
              var test = ref[0];
              var expression2 = ref[1];
              if (test.evaluate(ctx)) {
                return expression2.evaluate(ctx);
              }
            }
            return this.otherwise.evaluate(ctx);
          };
          Case.prototype.eachChild = function eachChild(fn) {
            for (var i = 0, list = this.branches; i < list.length; i += 1) {
              var ref = list[i];
              var test = ref[0];
              var expression2 = ref[1];
              fn(test);
              fn(expression2);
            }
            fn(this.otherwise);
          };
          Case.prototype.outputDefined = function outputDefined() {
            return this.branches.every(function(ref) {
              var _ = ref[0];
              var out = ref[1];
              return out.outputDefined();
            }) && this.otherwise.outputDefined();
          };
          Case.prototype.serialize = function serialize2() {
            var serialized = ["case"];
            this.eachChild(function(child) {
              serialized.push(child.serialize());
            });
            return serialized;
          };
          var Slice = function Slice2(type, input, beginIndex, endIndex) {
            this.type = type;
            this.input = input;
            this.beginIndex = beginIndex;
            this.endIndex = endIndex;
          };
          Slice.parse = function parse2(args, context) {
            if (args.length <= 2 || args.length >= 5) {
              return context.error("Expected 3 or 4 arguments, but found " + (args.length - 1) + " instead.");
            }
            var input = context.parse(args[1], 1, ValueType);
            var beginIndex = context.parse(args[2], 2, NumberType);
            if (!input || !beginIndex) {
              return null;
            }
            if (!isValidType(input.type, [
              array(ValueType),
              StringType,
              ValueType
            ])) {
              return context.error("Expected first argument to be of type array or string, but found " + toString(input.type) + " instead");
            }
            if (args.length === 4) {
              var endIndex = context.parse(args[3], 3, NumberType);
              if (!endIndex) {
                return null;
              }
              return new Slice(input.type, input, beginIndex, endIndex);
            } else {
              return new Slice(input.type, input, beginIndex);
            }
          };
          Slice.prototype.evaluate = function evaluate(ctx) {
            var input = this.input.evaluate(ctx);
            var beginIndex = this.beginIndex.evaluate(ctx);
            if (!isValidNativeType(input, [
              "string",
              "array"
            ])) {
              throw new RuntimeError("Expected first argument to be of type array or string, but found " + toString(typeOf(input)) + " instead.");
            }
            if (this.endIndex) {
              var endIndex = this.endIndex.evaluate(ctx);
              return input.slice(beginIndex, endIndex);
            }
            return input.slice(beginIndex);
          };
          Slice.prototype.eachChild = function eachChild(fn) {
            fn(this.input);
            fn(this.beginIndex);
            if (this.endIndex) {
              fn(this.endIndex);
            }
          };
          Slice.prototype.outputDefined = function outputDefined() {
            return false;
          };
          Slice.prototype.serialize = function serialize2() {
            if (this.endIndex != null && this.endIndex !== void 0) {
              var endIndex = this.endIndex.serialize();
              return [
                "slice",
                this.input.serialize(),
                this.beginIndex.serialize(),
                endIndex
              ];
            }
            return [
              "slice",
              this.input.serialize(),
              this.beginIndex.serialize()
            ];
          };
          function isComparableType(op, type) {
            if (op === "==" || op === "!=") {
              return type.kind === "boolean" || type.kind === "string" || type.kind === "number" || type.kind === "null" || type.kind === "value";
            } else {
              return type.kind === "string" || type.kind === "number" || type.kind === "value";
            }
          }
          function eq(ctx, a, b) {
            return a === b;
          }
          function neq(ctx, a, b) {
            return a !== b;
          }
          function lt(ctx, a, b) {
            return a < b;
          }
          function gt(ctx, a, b) {
            return a > b;
          }
          function lteq(ctx, a, b) {
            return a <= b;
          }
          function gteq(ctx, a, b) {
            return a >= b;
          }
          function eqCollate(ctx, a, b, c) {
            return c.compare(a, b) === 0;
          }
          function neqCollate(ctx, a, b, c) {
            return !eqCollate(ctx, a, b, c);
          }
          function ltCollate(ctx, a, b, c) {
            return c.compare(a, b) < 0;
          }
          function gtCollate(ctx, a, b, c) {
            return c.compare(a, b) > 0;
          }
          function lteqCollate(ctx, a, b, c) {
            return c.compare(a, b) <= 0;
          }
          function gteqCollate(ctx, a, b, c) {
            return c.compare(a, b) >= 0;
          }
          function makeComparison(op, compareBasic, compareWithCollator) {
            var isOrderComparison = op !== "==" && op !== "!=";
            return function() {
              function Comparison(lhs, rhs, collator) {
                this.type = BooleanType;
                this.lhs = lhs;
                this.rhs = rhs;
                this.collator = collator;
                this.hasUntypedArgument = lhs.type.kind === "value" || rhs.type.kind === "value";
              }
              Comparison.parse = function parse2(args, context) {
                if (args.length !== 3 && args.length !== 4) {
                  return context.error("Expected two or three arguments.");
                }
                var op2 = args[0];
                var lhs = context.parse(args[1], 1, ValueType);
                if (!lhs) {
                  return null;
                }
                if (!isComparableType(op2, lhs.type)) {
                  return context.concat(1).error('"' + op2 + `" comparisons are not supported for type '` + toString(lhs.type) + "'.");
                }
                var rhs = context.parse(args[2], 2, ValueType);
                if (!rhs) {
                  return null;
                }
                if (!isComparableType(op2, rhs.type)) {
                  return context.concat(2).error('"' + op2 + `" comparisons are not supported for type '` + toString(rhs.type) + "'.");
                }
                if (lhs.type.kind !== rhs.type.kind && lhs.type.kind !== "value" && rhs.type.kind !== "value") {
                  return context.error("Cannot compare types '" + toString(lhs.type) + "' and '" + toString(rhs.type) + "'.");
                }
                if (isOrderComparison) {
                  if (lhs.type.kind === "value" && rhs.type.kind !== "value") {
                    lhs = new Assertion(rhs.type, [lhs]);
                  } else if (lhs.type.kind !== "value" && rhs.type.kind === "value") {
                    rhs = new Assertion(lhs.type, [rhs]);
                  }
                }
                var collator = null;
                if (args.length === 4) {
                  if (lhs.type.kind !== "string" && rhs.type.kind !== "string" && lhs.type.kind !== "value" && rhs.type.kind !== "value") {
                    return context.error("Cannot use collator to compare non-string types.");
                  }
                  collator = context.parse(args[3], 3, CollatorType);
                  if (!collator) {
                    return null;
                  }
                }
                return new Comparison(lhs, rhs, collator);
              };
              Comparison.prototype.evaluate = function evaluate(ctx) {
                var lhs = this.lhs.evaluate(ctx);
                var rhs = this.rhs.evaluate(ctx);
                if (isOrderComparison && this.hasUntypedArgument) {
                  var lt2 = typeOf(lhs);
                  var rt = typeOf(rhs);
                  if (lt2.kind !== rt.kind || !(lt2.kind === "string" || lt2.kind === "number")) {
                    throw new RuntimeError('Expected arguments for "' + op + '" to be (string, string) or (number, number), but found (' + lt2.kind + ", " + rt.kind + ") instead.");
                  }
                }
                if (this.collator && !isOrderComparison && this.hasUntypedArgument) {
                  var lt$1 = typeOf(lhs);
                  var rt$1 = typeOf(rhs);
                  if (lt$1.kind !== "string" || rt$1.kind !== "string") {
                    return compareBasic(ctx, lhs, rhs);
                  }
                }
                return this.collator ? compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) : compareBasic(ctx, lhs, rhs);
              };
              Comparison.prototype.eachChild = function eachChild(fn) {
                fn(this.lhs);
                fn(this.rhs);
                if (this.collator) {
                  fn(this.collator);
                }
              };
              Comparison.prototype.outputDefined = function outputDefined() {
                return true;
              };
              Comparison.prototype.serialize = function serialize2() {
                var serialized = [op];
                this.eachChild(function(child) {
                  serialized.push(child.serialize());
                });
                return serialized;
              };
              return Comparison;
            }();
          }
          var Equals = makeComparison("==", eq, eqCollate);
          var NotEquals = makeComparison("!=", neq, neqCollate);
          var LessThan = makeComparison("<", lt, ltCollate);
          var GreaterThan = makeComparison(">", gt, gtCollate);
          var LessThanOrEqual = makeComparison("<=", lteq, lteqCollate);
          var GreaterThanOrEqual = makeComparison(">=", gteq, gteqCollate);
          var NumberFormat = function NumberFormat2(number2, locale, currency, minFractionDigits, maxFractionDigits) {
            this.type = StringType;
            this.number = number2;
            this.locale = locale;
            this.currency = currency;
            this.minFractionDigits = minFractionDigits;
            this.maxFractionDigits = maxFractionDigits;
          };
          NumberFormat.parse = function parse2(args, context) {
            if (args.length !== 3) {
              return context.error("Expected two arguments.");
            }
            var number2 = context.parse(args[1], 1, NumberType);
            if (!number2) {
              return null;
            }
            var options = args[2];
            if (typeof options !== "object" || Array.isArray(options)) {
              return context.error("NumberFormat options argument must be an object.");
            }
            var locale = null;
            if (options["locale"]) {
              locale = context.parse(options["locale"], 1, StringType);
              if (!locale) {
                return null;
              }
            }
            var currency = null;
            if (options["currency"]) {
              currency = context.parse(options["currency"], 1, StringType);
              if (!currency) {
                return null;
              }
            }
            var minFractionDigits = null;
            if (options["min-fraction-digits"]) {
              minFractionDigits = context.parse(options["min-fraction-digits"], 1, NumberType);
              if (!minFractionDigits) {
                return null;
              }
            }
            var maxFractionDigits = null;
            if (options["max-fraction-digits"]) {
              maxFractionDigits = context.parse(options["max-fraction-digits"], 1, NumberType);
              if (!maxFractionDigits) {
                return null;
              }
            }
            return new NumberFormat(number2, locale, currency, minFractionDigits, maxFractionDigits);
          };
          NumberFormat.prototype.evaluate = function evaluate(ctx) {
            return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], {
              style: this.currency ? "currency" : "decimal",
              currency: this.currency ? this.currency.evaluate(ctx) : void 0,
              minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : void 0,
              maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : void 0
            }).format(this.number.evaluate(ctx));
          };
          NumberFormat.prototype.eachChild = function eachChild(fn) {
            fn(this.number);
            if (this.locale) {
              fn(this.locale);
            }
            if (this.currency) {
              fn(this.currency);
            }
            if (this.minFractionDigits) {
              fn(this.minFractionDigits);
            }
            if (this.maxFractionDigits) {
              fn(this.maxFractionDigits);
            }
          };
          NumberFormat.prototype.outputDefined = function outputDefined() {
            return false;
          };
          NumberFormat.prototype.serialize = function serialize2() {
            var options = {};
            if (this.locale) {
              options["locale"] = this.locale.serialize();
            }
            if (this.currency) {
              options["currency"] = this.currency.serialize();
            }
            if (this.minFractionDigits) {
              options["min-fraction-digits"] = this.minFractionDigits.serialize();
            }
            if (this.maxFractionDigits) {
              options["max-fraction-digits"] = this.maxFractionDigits.serialize();
            }
            return [
              "number-format",
              this.number.serialize(),
              options
            ];
          };
          var Length = function Length2(input) {
            this.type = NumberType;
            this.input = input;
          };
          Length.parse = function parse2(args, context) {
            if (args.length !== 2) {
              return context.error("Expected 1 argument, but found " + (args.length - 1) + " instead.");
            }
            var input = context.parse(args[1], 1);
            if (!input) {
              return null;
            }
            if (input.type.kind !== "array" && input.type.kind !== "string" && input.type.kind !== "value") {
              return context.error("Expected argument of type string or array, but found " + toString(input.type) + " instead.");
            }
            return new Length(input);
          };
          Length.prototype.evaluate = function evaluate(ctx) {
            var input = this.input.evaluate(ctx);
            if (typeof input === "string") {
              return input.length;
            } else if (Array.isArray(input)) {
              return input.length;
            } else {
              throw new RuntimeError("Expected value to be of type string or array, but found " + toString(typeOf(input)) + " instead.");
            }
          };
          Length.prototype.eachChild = function eachChild(fn) {
            fn(this.input);
          };
          Length.prototype.outputDefined = function outputDefined() {
            return false;
          };
          Length.prototype.serialize = function serialize2() {
            var serialized = ["length"];
            this.eachChild(function(child) {
              serialized.push(child.serialize());
            });
            return serialized;
          };
          var expressions = {
            "==": Equals,
            "!=": NotEquals,
            ">": GreaterThan,
            "<": LessThan,
            ">=": GreaterThanOrEqual,
            "<=": LessThanOrEqual,
            "array": Assertion,
            "at": At,
            "boolean": Assertion,
            "case": Case,
            "coalesce": Coalesce,
            "collator": CollatorExpression,
            "format": FormatExpression,
            "image": ImageExpression,
            "in": In,
            "index-of": IndexOf,
            "interpolate": Interpolate,
            "interpolate-hcl": Interpolate,
            "interpolate-lab": Interpolate,
            "length": Length,
            "let": Let,
            "literal": Literal,
            "match": Match,
            "number": Assertion,
            "number-format": NumberFormat,
            "object": Assertion,
            "slice": Slice,
            "step": Step,
            "string": Assertion,
            "to-boolean": Coercion,
            "to-color": Coercion,
            "to-number": Coercion,
            "to-string": Coercion,
            "var": Var,
            "within": Within
          };
          function rgba3(ctx, ref) {
            var r = ref[0];
            var g = ref[1];
            var b = ref[2];
            var a = ref[3];
            r = r.evaluate(ctx);
            g = g.evaluate(ctx);
            b = b.evaluate(ctx);
            var alpha = a ? a.evaluate(ctx) : 1;
            var error2 = validateRGBA(r, g, b, alpha);
            if (error2) {
              throw new RuntimeError(error2);
            }
            return new Color2(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);
          }
          function has(key, obj) {
            return key in obj;
          }
          function get(key, obj) {
            var v = obj[key];
            return typeof v === "undefined" ? null : v;
          }
          function binarySearch(v, a, i, j) {
            while (i <= j) {
              var m = i + j >> 1;
              if (a[m] === v) {
                return true;
              }
              if (a[m] > v) {
                j = m - 1;
              } else {
                i = m + 1;
              }
            }
            return false;
          }
          function varargs(type) {
            return { type };
          }
          CompoundExpression.register(expressions, {
            "error": [
              ErrorType,
              [StringType],
              function(ctx, ref) {
                var v = ref[0];
                throw new RuntimeError(v.evaluate(ctx));
              }
            ],
            "typeof": [
              StringType,
              [ValueType],
              function(ctx, ref) {
                var v = ref[0];
                return toString(typeOf(v.evaluate(ctx)));
              }
            ],
            "to-rgba": [
              array(NumberType, 4),
              [ColorType],
              function(ctx, ref) {
                var v = ref[0];
                return v.evaluate(ctx).toArray();
              }
            ],
            "rgb": [
              ColorType,
              [
                NumberType,
                NumberType,
                NumberType
              ],
              rgba3
            ],
            "rgba": [
              ColorType,
              [
                NumberType,
                NumberType,
                NumberType,
                NumberType
              ],
              rgba3
            ],
            "has": {
              type: BooleanType,
              overloads: [
                [
                  [StringType],
                  function(ctx, ref) {
                    var key = ref[0];
                    return has(key.evaluate(ctx), ctx.properties());
                  }
                ],
                [
                  [
                    StringType,
                    ObjectType
                  ],
                  function(ctx, ref) {
                    var key = ref[0];
                    var obj = ref[1];
                    return has(key.evaluate(ctx), obj.evaluate(ctx));
                  }
                ]
              ]
            },
            "get": {
              type: ValueType,
              overloads: [
                [
                  [StringType],
                  function(ctx, ref) {
                    var key = ref[0];
                    return get(key.evaluate(ctx), ctx.properties());
                  }
                ],
                [
                  [
                    StringType,
                    ObjectType
                  ],
                  function(ctx, ref) {
                    var key = ref[0];
                    var obj = ref[1];
                    return get(key.evaluate(ctx), obj.evaluate(ctx));
                  }
                ]
              ]
            },
            "feature-state": [
              ValueType,
              [StringType],
              function(ctx, ref) {
                var key = ref[0];
                return get(key.evaluate(ctx), ctx.featureState || {});
              }
            ],
            "properties": [
              ObjectType,
              [],
              function(ctx) {
                return ctx.properties();
              }
            ],
            "geometry-type": [
              StringType,
              [],
              function(ctx) {
                return ctx.geometryType();
              }
            ],
            "id": [
              ValueType,
              [],
              function(ctx) {
                return ctx.id();
              }
            ],
            "zoom": [
              NumberType,
              [],
              function(ctx) {
                return ctx.globals.zoom;
              }
            ],
            "heatmap-density": [
              NumberType,
              [],
              function(ctx) {
                return ctx.globals.heatmapDensity || 0;
              }
            ],
            "line-progress": [
              NumberType,
              [],
              function(ctx) {
                return ctx.globals.lineProgress || 0;
              }
            ],
            "accumulated": [
              ValueType,
              [],
              function(ctx) {
                return ctx.globals.accumulated === void 0 ? null : ctx.globals.accumulated;
              }
            ],
            "+": [
              NumberType,
              varargs(NumberType),
              function(ctx, args) {
                var result = 0;
                for (var i = 0, list = args; i < list.length; i += 1) {
                  var arg = list[i];
                  result += arg.evaluate(ctx);
                }
                return result;
              }
            ],
            "*": [
              NumberType,
              varargs(NumberType),
              function(ctx, args) {
                var result = 1;
                for (var i = 0, list = args; i < list.length; i += 1) {
                  var arg = list[i];
                  result *= arg.evaluate(ctx);
                }
                return result;
              }
            ],
            "-": {
              type: NumberType,
              overloads: [
                [
                  [
                    NumberType,
                    NumberType
                  ],
                  function(ctx, ref) {
                    var a = ref[0];
                    var b = ref[1];
                    return a.evaluate(ctx) - b.evaluate(ctx);
                  }
                ],
                [
                  [NumberType],
                  function(ctx, ref) {
                    var a = ref[0];
                    return -a.evaluate(ctx);
                  }
                ]
              ]
            },
            "/": [
              NumberType,
              [
                NumberType,
                NumberType
              ],
              function(ctx, ref) {
                var a = ref[0];
                var b = ref[1];
                return a.evaluate(ctx) / b.evaluate(ctx);
              }
            ],
            "%": [
              NumberType,
              [
                NumberType,
                NumberType
              ],
              function(ctx, ref) {
                var a = ref[0];
                var b = ref[1];
                return a.evaluate(ctx) % b.evaluate(ctx);
              }
            ],
            "ln2": [
              NumberType,
              [],
              function() {
                return Math.LN2;
              }
            ],
            "pi": [
              NumberType,
              [],
              function() {
                return Math.PI;
              }
            ],
            "e": [
              NumberType,
              [],
              function() {
                return Math.E;
              }
            ],
            "^": [
              NumberType,
              [
                NumberType,
                NumberType
              ],
              function(ctx, ref) {
                var b = ref[0];
                var e = ref[1];
                return Math.pow(b.evaluate(ctx), e.evaluate(ctx));
              }
            ],
            "sqrt": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var x = ref[0];
                return Math.sqrt(x.evaluate(ctx));
              }
            ],
            "log10": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.log(n.evaluate(ctx)) / Math.LN10;
              }
            ],
            "ln": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.log(n.evaluate(ctx));
              }
            ],
            "log2": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.log(n.evaluate(ctx)) / Math.LN2;
              }
            ],
            "sin": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.sin(n.evaluate(ctx));
              }
            ],
            "cos": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.cos(n.evaluate(ctx));
              }
            ],
            "tan": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.tan(n.evaluate(ctx));
              }
            ],
            "asin": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.asin(n.evaluate(ctx));
              }
            ],
            "acos": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.acos(n.evaluate(ctx));
              }
            ],
            "atan": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.atan(n.evaluate(ctx));
              }
            ],
            "min": [
              NumberType,
              varargs(NumberType),
              function(ctx, args) {
                return Math.min.apply(Math, args.map(function(arg) {
                  return arg.evaluate(ctx);
                }));
              }
            ],
            "max": [
              NumberType,
              varargs(NumberType),
              function(ctx, args) {
                return Math.max.apply(Math, args.map(function(arg) {
                  return arg.evaluate(ctx);
                }));
              }
            ],
            "abs": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.abs(n.evaluate(ctx));
              }
            ],
            "round": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                var v = n.evaluate(ctx);
                return v < 0 ? -Math.round(-v) : Math.round(v);
              }
            ],
            "floor": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.floor(n.evaluate(ctx));
              }
            ],
            "ceil": [
              NumberType,
              [NumberType],
              function(ctx, ref) {
                var n = ref[0];
                return Math.ceil(n.evaluate(ctx));
              }
            ],
            "filter-==": [
              BooleanType,
              [
                StringType,
                ValueType
              ],
              function(ctx, ref) {
                var k = ref[0];
                var v = ref[1];
                return ctx.properties()[k.value] === v.value;
              }
            ],
            "filter-id-==": [
              BooleanType,
              [ValueType],
              function(ctx, ref) {
                var v = ref[0];
                return ctx.id() === v.value;
              }
            ],
            "filter-type-==": [
              BooleanType,
              [StringType],
              function(ctx, ref) {
                var v = ref[0];
                return ctx.geometryType() === v.value;
              }
            ],
            "filter-<": [
              BooleanType,
              [
                StringType,
                ValueType
              ],
              function(ctx, ref) {
                var k = ref[0];
                var v = ref[1];
                var a = ctx.properties()[k.value];
                var b = v.value;
                return typeof a === typeof b && a < b;
              }
            ],
            "filter-id-<": [
              BooleanType,
              [ValueType],
              function(ctx, ref) {
                var v = ref[0];
                var a = ctx.id();
                var b = v.value;
                return typeof a === typeof b && a < b;
              }
            ],
            "filter->": [
              BooleanType,
              [
                StringType,
                ValueType
              ],
              function(ctx, ref) {
                var k = ref[0];
                var v = ref[1];
                var a = ctx.properties()[k.value];
                var b = v.value;
                return typeof a === typeof b && a > b;
              }
            ],
            "filter-id->": [
              BooleanType,
              [ValueType],
              function(ctx, ref) {
                var v = ref[0];
                var a = ctx.id();
                var b = v.value;
                return typeof a === typeof b && a > b;
              }
            ],
            "filter-<=": [
              BooleanType,
              [
                StringType,
                ValueType
              ],
              function(ctx, ref) {
                var k = ref[0];
                var v = ref[1];
                var a = ctx.properties()[k.value];
                var b = v.value;
                return typeof a === typeof b && a <= b;
              }
            ],
            "filter-id-<=": [
              BooleanType,
              [ValueType],
              function(ctx, ref) {
                var v = ref[0];
                var a = ctx.id();
                var b = v.value;
                return typeof a === typeof b && a <= b;
              }
            ],
            "filter->=": [
              BooleanType,
              [
                StringType,
                ValueType
              ],
              function(ctx, ref) {
                var k = ref[0];
                var v = ref[1];
                var a = ctx.properties()[k.value];
                var b = v.value;
                return typeof a === typeof b && a >= b;
              }
            ],
            "filter-id->=": [
              BooleanType,
              [ValueType],
              function(ctx, ref) {
                var v = ref[0];
                var a = ctx.id();
                var b = v.value;
                return typeof a === typeof b && a >= b;
              }
            ],
            "filter-has": [
              BooleanType,
              [ValueType],
              function(ctx, ref) {
                var k = ref[0];
                return k.value in ctx.properties();
              }
            ],
            "filter-has-id": [
              BooleanType,
              [],
              function(ctx) {
                return ctx.id() !== null && ctx.id() !== void 0;
              }
            ],
            "filter-type-in": [
              BooleanType,
              [array(StringType)],
              function(ctx, ref) {
                var v = ref[0];
                return v.value.indexOf(ctx.geometryType()) >= 0;
              }
            ],
            "filter-id-in": [
              BooleanType,
              [array(ValueType)],
              function(ctx, ref) {
                var v = ref[0];
                return v.value.indexOf(ctx.id()) >= 0;
              }
            ],
            "filter-in-small": [
              BooleanType,
              [
                StringType,
                array(ValueType)
              ],
              function(ctx, ref) {
                var k = ref[0];
                var v = ref[1];
                return v.value.indexOf(ctx.properties()[k.value]) >= 0;
              }
            ],
            "filter-in-large": [
              BooleanType,
              [
                StringType,
                array(ValueType)
              ],
              function(ctx, ref) {
                var k = ref[0];
                var v = ref[1];
                return binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1);
              }
            ],
            "all": {
              type: BooleanType,
              overloads: [
                [
                  [
                    BooleanType,
                    BooleanType
                  ],
                  function(ctx, ref) {
                    var a = ref[0];
                    var b = ref[1];
                    return a.evaluate(ctx) && b.evaluate(ctx);
                  }
                ],
                [
                  varargs(BooleanType),
                  function(ctx, args) {
                    for (var i = 0, list = args; i < list.length; i += 1) {
                      var arg = list[i];
                      if (!arg.evaluate(ctx)) {
                        return false;
                      }
                    }
                    return true;
                  }
                ]
              ]
            },
            "any": {
              type: BooleanType,
              overloads: [
                [
                  [
                    BooleanType,
                    BooleanType
                  ],
                  function(ctx, ref) {
                    var a = ref[0];
                    var b = ref[1];
                    return a.evaluate(ctx) || b.evaluate(ctx);
                  }
                ],
                [
                  varargs(BooleanType),
                  function(ctx, args) {
                    for (var i = 0, list = args; i < list.length; i += 1) {
                      var arg = list[i];
                      if (arg.evaluate(ctx)) {
                        return true;
                      }
                    }
                    return false;
                  }
                ]
              ]
            },
            "!": [
              BooleanType,
              [BooleanType],
              function(ctx, ref) {
                var b = ref[0];
                return !b.evaluate(ctx);
              }
            ],
            "is-supported-script": [
              BooleanType,
              [StringType],
              function(ctx, ref) {
                var s = ref[0];
                var isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;
                if (isSupportedScript) {
                  return isSupportedScript(s.evaluate(ctx));
                }
                return true;
              }
            ],
            "upcase": [
              StringType,
              [StringType],
              function(ctx, ref) {
                var s = ref[0];
                return s.evaluate(ctx).toUpperCase();
              }
            ],
            "downcase": [
              StringType,
              [StringType],
              function(ctx, ref) {
                var s = ref[0];
                return s.evaluate(ctx).toLowerCase();
              }
            ],
            "concat": [
              StringType,
              varargs(ValueType),
              function(ctx, args) {
                return args.map(function(arg) {
                  return toString$1(arg.evaluate(ctx));
                }).join("");
              }
            ],
            "resolved-locale": [
              StringType,
              [CollatorType],
              function(ctx, ref) {
                var collator = ref[0];
                return collator.evaluate(ctx).resolvedLocale();
              }
            ]
          });
          function success(value) {
            return {
              result: "success",
              value
            };
          }
          function error(value) {
            return {
              result: "error",
              value
            };
          }
          function supportsPropertyExpression(spec2) {
            return spec2["property-type"] === "data-driven" || spec2["property-type"] === "cross-faded-data-driven";
          }
          function supportsZoomExpression(spec2) {
            return !!spec2.expression && spec2.expression.parameters.indexOf("zoom") > -1;
          }
          function supportsInterpolation(spec2) {
            return !!spec2.expression && spec2.expression.interpolated;
          }
          function getType(val) {
            if (val instanceof Number) {
              return "number";
            } else if (val instanceof String) {
              return "string";
            } else if (val instanceof Boolean) {
              return "boolean";
            } else if (Array.isArray(val)) {
              return "array";
            } else if (val === null) {
              return "null";
            } else {
              return typeof val;
            }
          }
          function isFunction(value) {
            return typeof value === "object" && value !== null && !Array.isArray(value);
          }
          function identityFunction(x) {
            return x;
          }
          function createFunction(parameters, propertySpec) {
            var isColor = propertySpec.type === "color";
            var zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === "object";
            var featureDependent = zoomAndFeatureDependent || parameters.property !== void 0;
            var zoomDependent = zoomAndFeatureDependent || !featureDependent;
            var type = parameters.type || (supportsInterpolation(propertySpec) ? "exponential" : "interval");
            if (isColor) {
              parameters = extend$1({}, parameters);
              if (parameters.stops) {
                parameters.stops = parameters.stops.map(function(stop2) {
                  return [
                    stop2[0],
                    Color2.parse(stop2[1])
                  ];
                });
              }
              if (parameters.default) {
                parameters.default = Color2.parse(parameters.default);
              } else {
                parameters.default = Color2.parse(propertySpec.default);
              }
            }
            if (parameters.colorSpace && parameters.colorSpace !== "rgb" && !colorSpaces[parameters.colorSpace]) {
              throw new Error("Unknown color space: " + parameters.colorSpace);
            }
            var innerFun;
            var hashedStops;
            var categoricalKeyType;
            if (type === "exponential") {
              innerFun = evaluateExponentialFunction;
            } else if (type === "interval") {
              innerFun = evaluateIntervalFunction;
            } else if (type === "categorical") {
              innerFun = evaluateCategoricalFunction;
              hashedStops = /* @__PURE__ */ Object.create(null);
              for (var i = 0, list = parameters.stops; i < list.length; i += 1) {
                var stop = list[i];
                hashedStops[stop[0]] = stop[1];
              }
              categoricalKeyType = typeof parameters.stops[0][0];
            } else if (type === "identity") {
              innerFun = evaluateIdentityFunction;
            } else {
              throw new Error('Unknown function type "' + type + '"');
            }
            if (zoomAndFeatureDependent) {
              var featureFunctions = {};
              var zoomStops = [];
              for (var s = 0; s < parameters.stops.length; s++) {
                var stop$1 = parameters.stops[s];
                var zoom = stop$1[0].zoom;
                if (featureFunctions[zoom] === void 0) {
                  featureFunctions[zoom] = {
                    zoom,
                    type: parameters.type,
                    property: parameters.property,
                    default: parameters.default,
                    stops: []
                  };
                  zoomStops.push(zoom);
                }
                featureFunctions[zoom].stops.push([
                  stop$1[0].value,
                  stop$1[1]
                ]);
              }
              var featureFunctionStops = [];
              for (var i$1 = 0, list$1 = zoomStops; i$1 < list$1.length; i$1 += 1) {
                var z = list$1[i$1];
                featureFunctionStops.push([
                  featureFunctions[z].zoom,
                  createFunction(featureFunctions[z], propertySpec)
                ]);
              }
              var interpolationType = { name: "linear" };
              return {
                kind: "composite",
                interpolationType,
                interpolationFactor: Interpolate.interpolationFactor.bind(void 0, interpolationType),
                zoomStops: featureFunctionStops.map(function(s2) {
                  return s2[0];
                }),
                evaluate: function evaluate(ref, properties2) {
                  var zoom2 = ref.zoom;
                  return evaluateExponentialFunction({
                    stops: featureFunctionStops,
                    base: parameters.base
                  }, propertySpec, zoom2).evaluate(zoom2, properties2);
                }
              };
            } else if (zoomDependent) {
              var interpolationType$1 = type === "exponential" ? {
                name: "exponential",
                base: parameters.base !== void 0 ? parameters.base : 1
              } : null;
              return {
                kind: "camera",
                interpolationType: interpolationType$1,
                interpolationFactor: Interpolate.interpolationFactor.bind(void 0, interpolationType$1),
                zoomStops: parameters.stops.map(function(s2) {
                  return s2[0];
                }),
                evaluate: function(ref) {
                  var zoom2 = ref.zoom;
                  return innerFun(parameters, propertySpec, zoom2, hashedStops, categoricalKeyType);
                }
              };
            } else {
              return {
                kind: "source",
                evaluate: function evaluate(_, feature) {
                  var value = feature && feature.properties ? feature.properties[parameters.property] : void 0;
                  if (value === void 0) {
                    return coalesce(parameters.default, propertySpec.default);
                  }
                  return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);
                }
              };
            }
          }
          function coalesce(a, b, c) {
            if (a !== void 0) {
              return a;
            }
            if (b !== void 0) {
              return b;
            }
            if (c !== void 0) {
              return c;
            }
          }
          function evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {
            var evaluated = typeof input === keyType ? hashedStops[input] : void 0;
            return coalesce(evaluated, parameters.default, propertySpec.default);
          }
          function evaluateIntervalFunction(parameters, propertySpec, input) {
            if (getType(input) !== "number") {
              return coalesce(parameters.default, propertySpec.default);
            }
            var n = parameters.stops.length;
            if (n === 1) {
              return parameters.stops[0][1];
            }
            if (input <= parameters.stops[0][0]) {
              return parameters.stops[0][1];
            }
            if (input >= parameters.stops[n - 1][0]) {
              return parameters.stops[n - 1][1];
            }
            var index = findStopLessThanOrEqualTo(parameters.stops.map(function(stop) {
              return stop[0];
            }), input);
            return parameters.stops[index][1];
          }
          function evaluateExponentialFunction(parameters, propertySpec, input) {
            var base = parameters.base !== void 0 ? parameters.base : 1;
            if (getType(input) !== "number") {
              return coalesce(parameters.default, propertySpec.default);
            }
            var n = parameters.stops.length;
            if (n === 1) {
              return parameters.stops[0][1];
            }
            if (input <= parameters.stops[0][0]) {
              return parameters.stops[0][1];
            }
            if (input >= parameters.stops[n - 1][0]) {
              return parameters.stops[n - 1][1];
            }
            var index = findStopLessThanOrEqualTo(parameters.stops.map(function(stop) {
              return stop[0];
            }), input);
            var t = interpolationFactor(input, base, parameters.stops[index][0], parameters.stops[index + 1][0]);
            var outputLower = parameters.stops[index][1];
            var outputUpper = parameters.stops[index + 1][1];
            var interp = interpolate[propertySpec.type] || identityFunction;
            if (parameters.colorSpace && parameters.colorSpace !== "rgb") {
              var colorspace = colorSpaces[parameters.colorSpace];
              interp = function(a, b) {
                return colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t));
              };
            }
            if (typeof outputLower.evaluate === "function") {
              return {
                evaluate: function evaluate() {
                  var args = [], len = arguments.length;
                  while (len--)
                    args[len] = arguments[len];
                  var evaluatedLower = outputLower.evaluate.apply(void 0, args);
                  var evaluatedUpper = outputUpper.evaluate.apply(void 0, args);
                  if (evaluatedLower === void 0 || evaluatedUpper === void 0) {
                    return void 0;
                  }
                  return interp(evaluatedLower, evaluatedUpper, t);
                }
              };
            }
            return interp(outputLower, outputUpper, t);
          }
          function evaluateIdentityFunction(parameters, propertySpec, input) {
            if (propertySpec.type === "color") {
              input = Color2.parse(input);
            } else if (propertySpec.type === "formatted") {
              input = Formatted.fromString(input.toString());
            } else if (propertySpec.type === "resolvedImage") {
              input = ResolvedImage.fromString(input.toString());
            } else if (getType(input) !== propertySpec.type && (propertySpec.type !== "enum" || !propertySpec.values[input])) {
              input = void 0;
            }
            return coalesce(input, parameters.default, propertySpec.default);
          }
          function interpolationFactor(input, base, lowerValue, upperValue) {
            var difference = upperValue - lowerValue;
            var progress = input - lowerValue;
            if (difference === 0) {
              return 0;
            } else if (base === 1) {
              return progress / difference;
            } else {
              return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);
            }
          }
          var StyleExpression = function StyleExpression2(expression2, propertySpec) {
            this.expression = expression2;
            this._warningHistory = {};
            this._evaluator = new EvaluationContext();
            this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;
            this._enumValues = propertySpec && propertySpec.type === "enum" ? propertySpec.values : null;
          };
          StyleExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
            this._evaluator.globals = globals;
            this._evaluator.feature = feature;
            this._evaluator.featureState = featureState;
            this._evaluator.canonical = canonical;
            this._evaluator.availableImages = availableImages || null;
            this._evaluator.formattedSection = formattedSection;
            return this.expression.evaluate(this._evaluator);
          };
          StyleExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
            this._evaluator.globals = globals;
            this._evaluator.feature = feature || null;
            this._evaluator.featureState = featureState || null;
            this._evaluator.canonical = canonical;
            this._evaluator.availableImages = availableImages || null;
            this._evaluator.formattedSection = formattedSection || null;
            try {
              var val = this.expression.evaluate(this._evaluator);
              if (val === null || val === void 0 || typeof val === "number" && val !== val) {
                return this._defaultValue;
              }
              if (this._enumValues && !(val in this._enumValues)) {
                throw new RuntimeError("Expected value to be one of " + Object.keys(this._enumValues).map(function(v) {
                  return JSON.stringify(v);
                }).join(", ") + ", but found " + JSON.stringify(val) + " instead.");
              }
              return val;
            } catch (e) {
              if (!this._warningHistory[e.message]) {
                this._warningHistory[e.message] = true;
                if (typeof console !== "undefined") {
                  console.warn(e.message);
                }
              }
              return this._defaultValue;
            }
          };
          function isExpression(expression2) {
            return Array.isArray(expression2) && expression2.length > 0 && typeof expression2[0] === "string" && expression2[0] in expressions;
          }
          function createExpression(expression2, propertySpec) {
            var parser = new ParsingContext(expressions, [], propertySpec ? getExpectedType(propertySpec) : void 0);
            var parsed = parser.parse(expression2, void 0, void 0, void 0, propertySpec && propertySpec.type === "string" ? { typeAnnotation: "coerce" } : void 0);
            if (!parsed) {
              return error(parser.errors);
            }
            return success(new StyleExpression(parsed, propertySpec));
          }
          var ZoomConstantExpression = function ZoomConstantExpression2(kind, expression2) {
            this.kind = kind;
            this._styleExpression = expression2;
            this.isStateDependent = kind !== "constant" && !isStateConstant(expression2.expression);
          };
          ZoomConstantExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
            return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
          };
          ZoomConstantExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
            return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
          };
          var ZoomDependentExpression = function ZoomDependentExpression2(kind, expression2, zoomStops, interpolationType) {
            this.kind = kind;
            this.zoomStops = zoomStops;
            this._styleExpression = expression2;
            this.isStateDependent = kind !== "camera" && !isStateConstant(expression2.expression);
            this.interpolationType = interpolationType;
          };
          ZoomDependentExpression.prototype.evaluateWithoutErrorHandling = function evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
            return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
          };
          ZoomDependentExpression.prototype.evaluate = function evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
            return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
          };
          ZoomDependentExpression.prototype.interpolationFactor = function interpolationFactor2(input, lower, upper) {
            if (this.interpolationType) {
              return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);
            } else {
              return 0;
            }
          };
          function createPropertyExpression(expression2, propertySpec) {
            expression2 = createExpression(expression2, propertySpec);
            if (expression2.result === "error") {
              return expression2;
            }
            var parsed = expression2.value.expression;
            var isFeatureConstant$1 = isFeatureConstant(parsed);
            if (!isFeatureConstant$1 && !supportsPropertyExpression(propertySpec)) {
              return error([new ParsingError("", "data expressions not supported")]);
            }
            var isZoomConstant = isGlobalPropertyConstant(parsed, ["zoom"]);
            if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {
              return error([new ParsingError("", "zoom expressions not supported")]);
            }
            var zoomCurve = findZoomCurve(parsed);
            if (!zoomCurve && !isZoomConstant) {
              return error([new ParsingError("", '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);
            } else if (zoomCurve instanceof ParsingError) {
              return error([zoomCurve]);
            } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {
              return error([new ParsingError("", '"interpolate" expressions cannot be used with this property')]);
            }
            if (!zoomCurve) {
              return success(isFeatureConstant$1 ? new ZoomConstantExpression("constant", expression2.value) : new ZoomConstantExpression("source", expression2.value));
            }
            var interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : void 0;
            return success(isFeatureConstant$1 ? new ZoomDependentExpression("camera", expression2.value, zoomCurve.labels, interpolationType) : new ZoomDependentExpression("composite", expression2.value, zoomCurve.labels, interpolationType));
          }
          var StylePropertyFunction = function StylePropertyFunction2(parameters, specification) {
            this._parameters = parameters;
            this._specification = specification;
            extend$1(this, createFunction(this._parameters, this._specification));
          };
          StylePropertyFunction.deserialize = function deserialize2(serialized) {
            return new StylePropertyFunction(serialized._parameters, serialized._specification);
          };
          StylePropertyFunction.serialize = function serialize2(input) {
            return {
              _parameters: input._parameters,
              _specification: input._specification
            };
          };
          function normalizePropertyExpression(value, specification) {
            if (isFunction(value)) {
              return new StylePropertyFunction(value, specification);
            } else if (isExpression(value)) {
              var expression2 = createPropertyExpression(value, specification);
              if (expression2.result === "error") {
                throw new Error(expression2.value.map(function(err) {
                  return err.key + ": " + err.message;
                }).join(", "));
              }
              return expression2.value;
            } else {
              var constant = value;
              if (typeof value === "string" && specification.type === "color") {
                constant = Color2.parse(value);
              }
              return {
                kind: "constant",
                evaluate: function() {
                  return constant;
                }
              };
            }
          }
          function findZoomCurve(expression2) {
            var result = null;
            if (expression2 instanceof Let) {
              result = findZoomCurve(expression2.result);
            } else if (expression2 instanceof Coalesce) {
              for (var i = 0, list = expression2.args; i < list.length; i += 1) {
                var arg = list[i];
                result = findZoomCurve(arg);
                if (result) {
                  break;
                }
              }
            } else if ((expression2 instanceof Step || expression2 instanceof Interpolate) && expression2.input instanceof CompoundExpression && expression2.input.name === "zoom") {
              result = expression2;
            }
            if (result instanceof ParsingError) {
              return result;
            }
            expression2.eachChild(function(child) {
              var childResult = findZoomCurve(child);
              if (childResult instanceof ParsingError) {
                result = childResult;
              } else if (!result && childResult) {
                result = new ParsingError("", '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.');
              } else if (result && childResult && result !== childResult) {
                result = new ParsingError("", 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.');
              }
            });
            return result;
          }
          function getExpectedType(spec2) {
            var types2 = {
              color: ColorType,
              string: StringType,
              number: NumberType,
              enum: StringType,
              boolean: BooleanType,
              formatted: FormattedType,
              resolvedImage: ResolvedImageType
            };
            if (spec2.type === "array") {
              return array(types2[spec2.value] || ValueType, spec2.length);
            }
            return types2[spec2.type];
          }
          function getDefaultValue(spec2) {
            if (spec2.type === "color" && isFunction(spec2.default)) {
              return new Color2(0, 0, 0, 0);
            } else if (spec2.type === "color") {
              return Color2.parse(spec2.default) || null;
            } else if (spec2.default === void 0) {
              return null;
            } else {
              return spec2.default;
            }
          }
          function validateObject(options) {
            var key = options.key;
            var object = options.value;
            var elementSpecs = options.valueSpec || {};
            var elementValidators = options.objectElementValidators || {};
            var style = options.style;
            var styleSpec = options.styleSpec;
            var errors = [];
            var type = getType(object);
            if (type !== "object") {
              return [new ValidationError(key, object, "object expected, " + type + " found")];
            }
            for (var objectKey in object) {
              var elementSpecKey = objectKey.split(".")[0];
              var elementSpec = elementSpecs[elementSpecKey] || elementSpecs["*"];
              var validateElement = void 0;
              if (elementValidators[elementSpecKey]) {
                validateElement = elementValidators[elementSpecKey];
              } else if (elementSpecs[elementSpecKey]) {
                validateElement = validate;
              } else if (elementValidators["*"]) {
                validateElement = elementValidators["*"];
              } else if (elementSpecs["*"]) {
                validateElement = validate;
              } else {
                errors.push(new ValidationError(key, object[objectKey], 'unknown property "' + objectKey + '"'));
                continue;
              }
              errors = errors.concat(validateElement({
                key: (key ? key + "." : key) + objectKey,
                value: object[objectKey],
                valueSpec: elementSpec,
                style,
                styleSpec,
                object,
                objectKey
              }, object));
            }
            for (var elementSpecKey$1 in elementSpecs) {
              if (elementValidators[elementSpecKey$1]) {
                continue;
              }
              if (elementSpecs[elementSpecKey$1].required && elementSpecs[elementSpecKey$1]["default"] === void 0 && object[elementSpecKey$1] === void 0) {
                errors.push(new ValidationError(key, object, 'missing required property "' + elementSpecKey$1 + '"'));
              }
            }
            return errors;
          }
          function validateArray(options) {
            var array2 = options.value;
            var arraySpec = options.valueSpec;
            var style = options.style;
            var styleSpec = options.styleSpec;
            var key = options.key;
            var validateArrayElement = options.arrayElementValidator || validate;
            if (getType(array2) !== "array") {
              return [new ValidationError(key, array2, "array expected, " + getType(array2) + " found")];
            }
            if (arraySpec.length && array2.length !== arraySpec.length) {
              return [new ValidationError(key, array2, "array length " + arraySpec.length + " expected, length " + array2.length + " found")];
            }
            if (arraySpec["min-length"] && array2.length < arraySpec["min-length"]) {
              return [new ValidationError(key, array2, "array length at least " + arraySpec["min-length"] + " expected, length " + array2.length + " found")];
            }
            var arrayElementSpec = {
              "type": arraySpec.value,
              "values": arraySpec.values
            };
            if (styleSpec.$version < 7) {
              arrayElementSpec.function = arraySpec.function;
            }
            if (getType(arraySpec.value) === "object") {
              arrayElementSpec = arraySpec.value;
            }
            var errors = [];
            for (var i = 0; i < array2.length; i++) {
              errors = errors.concat(validateArrayElement({
                array: array2,
                arrayIndex: i,
                value: array2[i],
                valueSpec: arrayElementSpec,
                style,
                styleSpec,
                key: key + "[" + i + "]"
              }));
            }
            return errors;
          }
          function validateNumber(options) {
            var key = options.key;
            var value = options.value;
            var valueSpec = options.valueSpec;
            var type = getType(value);
            if (type === "number" && value !== value) {
              type = "NaN";
            }
            if (type !== "number") {
              return [new ValidationError(key, value, "number expected, " + type + " found")];
            }
            if ("minimum" in valueSpec && value < valueSpec.minimum) {
              return [new ValidationError(key, value, value + " is less than the minimum value " + valueSpec.minimum)];
            }
            if ("maximum" in valueSpec && value > valueSpec.maximum) {
              return [new ValidationError(key, value, value + " is greater than the maximum value " + valueSpec.maximum)];
            }
            return [];
          }
          function validateFunction(options) {
            var functionValueSpec = options.valueSpec;
            var functionType = unbundle(options.value.type);
            var stopKeyType;
            var stopDomainValues = {};
            var previousStopDomainValue;
            var previousStopDomainZoom;
            var isZoomFunction = functionType !== "categorical" && options.value.property === void 0;
            var isPropertyFunction = !isZoomFunction;
            var isZoomAndPropertyFunction = getType(options.value.stops) === "array" && getType(options.value.stops[0]) === "array" && getType(options.value.stops[0][0]) === "object";
            var errors = validateObject({
              key: options.key,
              value: options.value,
              valueSpec: options.styleSpec.function,
              style: options.style,
              styleSpec: options.styleSpec,
              objectElementValidators: {
                stops: validateFunctionStops,
                default: validateFunctionDefault
              }
            });
            if (functionType === "identity" && isZoomFunction) {
              errors.push(new ValidationError(options.key, options.value, 'missing required property "property"'));
            }
            if (functionType !== "identity" && !options.value.stops) {
              errors.push(new ValidationError(options.key, options.value, 'missing required property "stops"'));
            }
            if (functionType === "exponential" && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) {
              errors.push(new ValidationError(options.key, options.value, "exponential functions not supported"));
            }
            if (options.styleSpec.$version >= 8) {
              if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) {
                errors.push(new ValidationError(options.key, options.value, "property functions not supported"));
              } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) {
                errors.push(new ValidationError(options.key, options.value, "zoom functions not supported"));
              }
            }
            if ((functionType === "categorical" || isZoomAndPropertyFunction) && options.value.property === void 0) {
              errors.push(new ValidationError(options.key, options.value, '"property" property is required'));
            }
            return errors;
            function validateFunctionStops(options2) {
              if (functionType === "identity") {
                return [new ValidationError(options2.key, options2.value, 'identity function may not have a "stops" property')];
              }
              var errors2 = [];
              var value = options2.value;
              errors2 = errors2.concat(validateArray({
                key: options2.key,
                value,
                valueSpec: options2.valueSpec,
                style: options2.style,
                styleSpec: options2.styleSpec,
                arrayElementValidator: validateFunctionStop
              }));
              if (getType(value) === "array" && value.length === 0) {
                errors2.push(new ValidationError(options2.key, value, "array must have at least one stop"));
              }
              return errors2;
            }
            function validateFunctionStop(options2) {
              var errors2 = [];
              var value = options2.value;
              var key = options2.key;
              if (getType(value) !== "array") {
                return [new ValidationError(key, value, "array expected, " + getType(value) + " found")];
              }
              if (value.length !== 2) {
                return [new ValidationError(key, value, "array length 2 expected, length " + value.length + " found")];
              }
              if (isZoomAndPropertyFunction) {
                if (getType(value[0]) !== "object") {
                  return [new ValidationError(key, value, "object expected, " + getType(value[0]) + " found")];
                }
                if (value[0].zoom === void 0) {
                  return [new ValidationError(key, value, "object stop key must have zoom")];
                }
                if (value[0].value === void 0) {
                  return [new ValidationError(key, value, "object stop key must have value")];
                }
                if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) {
                  return [new ValidationError(key, value[0].zoom, "stop zoom values must appear in ascending order")];
                }
                if (unbundle(value[0].zoom) !== previousStopDomainZoom) {
                  previousStopDomainZoom = unbundle(value[0].zoom);
                  previousStopDomainValue = void 0;
                  stopDomainValues = {};
                }
                errors2 = errors2.concat(validateObject({
                  key: key + "[0]",
                  value: value[0],
                  valueSpec: { zoom: {} },
                  style: options2.style,
                  styleSpec: options2.styleSpec,
                  objectElementValidators: {
                    zoom: validateNumber,
                    value: validateStopDomainValue
                  }
                }));
              } else {
                errors2 = errors2.concat(validateStopDomainValue({
                  key: key + "[0]",
                  value: value[0],
                  valueSpec: {},
                  style: options2.style,
                  styleSpec: options2.styleSpec
                }, value));
              }
              if (isExpression(deepUnbundle(value[1]))) {
                return errors2.concat([new ValidationError(key + "[1]", value[1], "expressions are not allowed in function stops.")]);
              }
              return errors2.concat(validate({
                key: key + "[1]",
                value: value[1],
                valueSpec: functionValueSpec,
                style: options2.style,
                styleSpec: options2.styleSpec
              }));
            }
            function validateStopDomainValue(options2, stop) {
              var type = getType(options2.value);
              var value = unbundle(options2.value);
              var reportValue = options2.value !== null ? options2.value : stop;
              if (!stopKeyType) {
                stopKeyType = type;
              } else if (type !== stopKeyType) {
                return [new ValidationError(options2.key, reportValue, type + " stop domain type must match previous stop domain type " + stopKeyType)];
              }
              if (type !== "number" && type !== "string" && type !== "boolean") {
                return [new ValidationError(options2.key, reportValue, "stop domain value must be a number, string, or boolean")];
              }
              if (type !== "number" && functionType !== "categorical") {
                var message = "number expected, " + type + " found";
                if (supportsPropertyExpression(functionValueSpec) && functionType === void 0) {
                  message += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.';
                }
                return [new ValidationError(options2.key, reportValue, message)];
              }
              if (functionType === "categorical" && type === "number" && (!isFinite(value) || Math.floor(value) !== value)) {
                return [new ValidationError(options2.key, reportValue, "integer expected, found " + value)];
              }
              if (functionType !== "categorical" && type === "number" && previousStopDomainValue !== void 0 && value < previousStopDomainValue) {
                return [new ValidationError(options2.key, reportValue, "stop domain values must appear in ascending order")];
              } else {
                previousStopDomainValue = value;
              }
              if (functionType === "categorical" && value in stopDomainValues) {
                return [new ValidationError(options2.key, reportValue, "stop domain values must be unique")];
              } else {
                stopDomainValues[value] = true;
              }
              return [];
            }
            function validateFunctionDefault(options2) {
              return validate({
                key: options2.key,
                value: options2.value,
                valueSpec: functionValueSpec,
                style: options2.style,
                styleSpec: options2.styleSpec
              });
            }
          }
          function validateExpression(options) {
            var expression2 = (options.expressionContext === "property" ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec);
            if (expression2.result === "error") {
              return expression2.value.map(function(error2) {
                return new ValidationError("" + options.key + error2.key, options.value, error2.message);
              });
            }
            var expressionObj = expression2.value.expression || expression2.value._styleExpression.expression;
            if (options.expressionContext === "property" && options.propertyKey === "text-font" && !expressionObj.outputDefined()) {
              return [new ValidationError(options.key, options.value, 'Invalid data expression for "' + options.propertyKey + '". Output values must be contained as literals within the expression.')];
            }
            if (options.expressionContext === "property" && options.propertyType === "layout" && !isStateConstant(expressionObj)) {
              return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with layout properties.')];
            }
            if (options.expressionContext === "filter" && !isStateConstant(expressionObj)) {
              return [new ValidationError(options.key, options.value, '"feature-state" data expressions are not supported with filters.')];
            }
            if (options.expressionContext && options.expressionContext.indexOf("cluster") === 0) {
              if (!isGlobalPropertyConstant(expressionObj, [
                "zoom",
                "feature-state"
              ])) {
                return [new ValidationError(options.key, options.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')];
              }
              if (options.expressionContext === "cluster-initial" && !isFeatureConstant(expressionObj)) {
                return [new ValidationError(options.key, options.value, "Feature data expressions are not supported with initial expression part of cluster properties.")];
              }
            }
            return [];
          }
          function validateBoolean(options) {
            var value = options.value;
            var key = options.key;
            var type = getType(value);
            if (type !== "boolean") {
              return [new ValidationError(key, value, "boolean expected, " + type + " found")];
            }
            return [];
          }
          function validateColor(options) {
            var key = options.key;
            var value = options.value;
            var type = getType(value);
            if (type !== "string") {
              return [new ValidationError(key, value, "color expected, " + type + " found")];
            }
            if (csscolorparser_1(value) === null) {
              return [new ValidationError(key, value, 'color expected, "' + value + '" found')];
            }
            return [];
          }
          function validateEnum(options) {
            var key = options.key;
            var value = options.value;
            var valueSpec = options.valueSpec;
            var errors = [];
            if (Array.isArray(valueSpec.values)) {
              if (valueSpec.values.indexOf(unbundle(value)) === -1) {
                errors.push(new ValidationError(key, value, "expected one of [" + valueSpec.values.join(", ") + "], " + JSON.stringify(value) + " found"));
              }
            } else {
              if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) {
                errors.push(new ValidationError(key, value, "expected one of [" + Object.keys(valueSpec.values).join(", ") + "], " + JSON.stringify(value) + " found"));
              }
            }
            return errors;
          }
          function isExpressionFilter(filter2) {
            if (filter2 === true || filter2 === false) {
              return true;
            }
            if (!Array.isArray(filter2) || filter2.length === 0) {
              return false;
            }
            switch (filter2[0]) {
              case "has":
                return filter2.length >= 2 && filter2[1] !== "$id" && filter2[1] !== "$type";
              case "in":
                return filter2.length >= 3 && (typeof filter2[1] !== "string" || Array.isArray(filter2[2]));
              case "!in":
              case "!has":
              case "none":
                return false;
              case "==":
              case "!=":
              case ">":
              case ">=":
              case "<":
              case "<=":
                return filter2.length !== 3 || (Array.isArray(filter2[1]) || Array.isArray(filter2[2]));
              case "any":
              case "all":
                for (var i = 0, list = filter2.slice(1); i < list.length; i += 1) {
                  var f = list[i];
                  if (!isExpressionFilter(f) && typeof f !== "boolean") {
                    return false;
                  }
                }
                return true;
              default:
                return true;
            }
          }
          var filterSpec = {
            "type": "boolean",
            "default": false,
            "transition": false,
            "property-type": "data-driven",
            "expression": {
              "interpolated": false,
              "parameters": [
                "zoom",
                "feature"
              ]
            }
          };
          function createFilter(filter2) {
            if (filter2 === null || filter2 === void 0) {
              return {
                filter: function() {
                  return true;
                },
                needGeometry: false
              };
            }
            if (!isExpressionFilter(filter2)) {
              filter2 = convertFilter(filter2);
            }
            var compiled = createExpression(filter2, filterSpec);
            if (compiled.result === "error") {
              throw new Error(compiled.value.map(function(err) {
                return err.key + ": " + err.message;
              }).join(", "));
            } else {
              var needGeometry = geometryNeeded(filter2);
              return {
                filter: function(globalProperties, feature, canonical) {
                  return compiled.value.evaluate(globalProperties, feature, {}, canonical);
                },
                needGeometry
              };
            }
          }
          function compare(a, b) {
            return a < b ? -1 : a > b ? 1 : 0;
          }
          function geometryNeeded(filter2) {
            if (!Array.isArray(filter2)) {
              return false;
            }
            if (filter2[0] === "within") {
              return true;
            }
            for (var index = 1; index < filter2.length; index++) {
              if (geometryNeeded(filter2[index])) {
                return true;
              }
            }
            return false;
          }
          function convertFilter(filter2) {
            if (!filter2) {
              return true;
            }
            var op = filter2[0];
            if (filter2.length <= 1) {
              return op !== "any";
            }
            var converted = op === "==" ? convertComparisonOp(filter2[1], filter2[2], "==") : op === "!=" ? convertNegation(convertComparisonOp(filter2[1], filter2[2], "==")) : op === "<" || op === ">" || op === "<=" || op === ">=" ? convertComparisonOp(filter2[1], filter2[2], op) : op === "any" ? convertDisjunctionOp(filter2.slice(1)) : op === "all" ? ["all"].concat(filter2.slice(1).map(convertFilter)) : op === "none" ? ["all"].concat(filter2.slice(1).map(convertFilter).map(convertNegation)) : op === "in" ? convertInOp(filter2[1], filter2.slice(2)) : op === "!in" ? convertNegation(convertInOp(filter2[1], filter2.slice(2))) : op === "has" ? convertHasOp(filter2[1]) : op === "!has" ? convertNegation(convertHasOp(filter2[1])) : op === "within" ? filter2 : true;
            return converted;
          }
          function convertComparisonOp(property, value, op) {
            switch (property) {
              case "$type":
                return [
                  "filter-type-" + op,
                  value
                ];
              case "$id":
                return [
                  "filter-id-" + op,
                  value
                ];
              default:
                return [
                  "filter-" + op,
                  property,
                  value
                ];
            }
          }
          function convertDisjunctionOp(filters) {
            return ["any"].concat(filters.map(convertFilter));
          }
          function convertInOp(property, values2) {
            if (values2.length === 0) {
              return false;
            }
            switch (property) {
              case "$type":
                return [
                  "filter-type-in",
                  [
                    "literal",
                    values2
                  ]
                ];
              case "$id":
                return [
                  "filter-id-in",
                  [
                    "literal",
                    values2
                  ]
                ];
              default:
                if (values2.length > 200 && !values2.some(function(v) {
                  return typeof v !== typeof values2[0];
                })) {
                  return [
                    "filter-in-large",
                    property,
                    [
                      "literal",
                      values2.sort(compare)
                    ]
                  ];
                } else {
                  return [
                    "filter-in-small",
                    property,
                    [
                      "literal",
                      values2
                    ]
                  ];
                }
            }
          }
          function convertHasOp(property) {
            switch (property) {
              case "$type":
                return true;
              case "$id":
                return ["filter-has-id"];
              default:
                return [
                  "filter-has",
                  property
                ];
            }
          }
          function convertNegation(filter2) {
            return [
              "!",
              filter2
            ];
          }
          function validateFilter(options) {
            if (isExpressionFilter(deepUnbundle(options.value))) {
              return validateExpression(extend$1({}, options, {
                expressionContext: "filter",
                valueSpec: { value: "boolean" }
              }));
            } else {
              return validateNonExpressionFilter(options);
            }
          }
          function validateNonExpressionFilter(options) {
            var value = options.value;
            var key = options.key;
            if (getType(value) !== "array") {
              return [new ValidationError(key, value, "array expected, " + getType(value) + " found")];
            }
            var styleSpec = options.styleSpec;
            var type;
            var errors = [];
            if (value.length < 1) {
              return [new ValidationError(key, value, "filter array must have at least 1 element")];
            }
            errors = errors.concat(validateEnum({
              key: key + "[0]",
              value: value[0],
              valueSpec: styleSpec.filter_operator,
              style: options.style,
              styleSpec: options.styleSpec
            }));
            switch (unbundle(value[0])) {
              case "<":
              case "<=":
              case ">":
              case ">=":
                if (value.length >= 2 && unbundle(value[1]) === "$type") {
                  errors.push(new ValidationError(key, value, '"$type" cannot be use with operator "' + value[0] + '"'));
                }
              case "==":
              case "!=":
                if (value.length !== 3) {
                  errors.push(new ValidationError(key, value, 'filter array for operator "' + value[0] + '" must have 3 elements'));
                }
              case "in":
              case "!in":
                if (value.length >= 2) {
                  type = getType(value[1]);
                  if (type !== "string") {
                    errors.push(new ValidationError(key + "[1]", value[1], "string expected, " + type + " found"));
                  }
                }
                for (var i = 2; i < value.length; i++) {
                  type = getType(value[i]);
                  if (unbundle(value[1]) === "$type") {
                    errors = errors.concat(validateEnum({
                      key: key + "[" + i + "]",
                      value: value[i],
                      valueSpec: styleSpec.geometry_type,
                      style: options.style,
                      styleSpec: options.styleSpec
                    }));
                  } else if (type !== "string" && type !== "number" && type !== "boolean") {
                    errors.push(new ValidationError(key + "[" + i + "]", value[i], "string, number, or boolean expected, " + type + " found"));
                  }
                }
                break;
              case "any":
              case "all":
              case "none":
                for (var i$1 = 1; i$1 < value.length; i$1++) {
                  errors = errors.concat(validateNonExpressionFilter({
                    key: key + "[" + i$1 + "]",
                    value: value[i$1],
                    style: options.style,
                    styleSpec: options.styleSpec
                  }));
                }
                break;
              case "has":
              case "!has":
                type = getType(value[1]);
                if (value.length !== 2) {
                  errors.push(new ValidationError(key, value, 'filter array for "' + value[0] + '" operator must have 2 elements'));
                } else if (type !== "string") {
                  errors.push(new ValidationError(key + "[1]", value[1], "string expected, " + type + " found"));
                }
                break;
              case "within":
                type = getType(value[1]);
                if (value.length !== 2) {
                  errors.push(new ValidationError(key, value, 'filter array for "' + value[0] + '" operator must have 2 elements'));
                } else if (type !== "object") {
                  errors.push(new ValidationError(key + "[1]", value[1], "object expected, " + type + " found"));
                }
                break;
            }
            return errors;
          }
          function validateProperty(options, propertyType) {
            var key = options.key;
            var style = options.style;
            var styleSpec = options.styleSpec;
            var value = options.value;
            var propertyKey = options.objectKey;
            var layerSpec = styleSpec[propertyType + "_" + options.layerType];
            if (!layerSpec) {
              return [];
            }
            var transitionMatch = propertyKey.match(/^(.*)-transition$/);
            if (propertyType === "paint" && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) {
              return validate({
                key,
                value,
                valueSpec: styleSpec.transition,
                style,
                styleSpec
              });
            }
            var valueSpec = options.valueSpec || layerSpec[propertyKey];
            if (!valueSpec) {
              return [new ValidationError(key, value, 'unknown property "' + propertyKey + '"')];
            }
            var tokenMatch;
            if (getType(value) === "string" && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {
              return [new ValidationError(key, value, '"' + propertyKey + '" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": ' + JSON.stringify(tokenMatch[1]) + " }`.")];
            }
            var errors = [];
            if (options.layerType === "symbol") {
              if (propertyKey === "text-field" && style && !style.glyphs) {
                errors.push(new ValidationError(key, value, 'use of "text-field" requires a style "glyphs" property'));
              }
              if (propertyKey === "text-font" && isFunction(deepUnbundle(value)) && unbundle(value.type) === "identity") {
                errors.push(new ValidationError(key, value, '"text-font" does not support identity functions'));
              }
            }
            return errors.concat(validate({
              key: options.key,
              value,
              valueSpec,
              style,
              styleSpec,
              expressionContext: "property",
              propertyType,
              propertyKey
            }));
          }
          function validatePaintProperty(options) {
            return validateProperty(options, "paint");
          }
          function validateLayoutProperty(options) {
            return validateProperty(options, "layout");
          }
          function validateLayer(options) {
            var errors = [];
            var layer2 = options.value;
            var key = options.key;
            var style = options.style;
            var styleSpec = options.styleSpec;
            if (!layer2.type && !layer2.ref) {
              errors.push(new ValidationError(key, layer2, 'either "type" or "ref" is required'));
            }
            var type = unbundle(layer2.type);
            var ref = unbundle(layer2.ref);
            if (layer2.id) {
              var layerId = unbundle(layer2.id);
              for (var i = 0; i < options.arrayIndex; i++) {
                var otherLayer = style.layers[i];
                if (unbundle(otherLayer.id) === layerId) {
                  errors.push(new ValidationError(key, layer2.id, 'duplicate layer id "' + layer2.id + '", previously used at line ' + otherLayer.id.__line__));
                }
              }
            }
            if ("ref" in layer2) {
              [
                "type",
                "source",
                "source-layer",
                "filter",
                "layout"
              ].forEach(function(p) {
                if (p in layer2) {
                  errors.push(new ValidationError(key, layer2[p], '"' + p + '" is prohibited for ref layers'));
                }
              });
              var parent;
              style.layers.forEach(function(layer3) {
                if (unbundle(layer3.id) === ref) {
                  parent = layer3;
                }
              });
              if (!parent) {
                errors.push(new ValidationError(key, layer2.ref, 'ref layer "' + ref + '" not found'));
              } else if (parent.ref) {
                errors.push(new ValidationError(key, layer2.ref, "ref cannot reference another ref layer"));
              } else {
                type = unbundle(parent.type);
              }
            } else if (type !== "background") {
              if (!layer2.source) {
                errors.push(new ValidationError(key, layer2, 'missing required property "source"'));
              } else {
                var source2 = style.sources && style.sources[layer2.source];
                var sourceType = source2 && unbundle(source2.type);
                if (!source2) {
                  errors.push(new ValidationError(key, layer2.source, 'source "' + layer2.source + '" not found'));
                } else if (sourceType === "vector" && type === "raster") {
                  errors.push(new ValidationError(key, layer2.source, 'layer "' + layer2.id + '" requires a raster source'));
                } else if (sourceType === "raster" && type !== "raster") {
                  errors.push(new ValidationError(key, layer2.source, 'layer "' + layer2.id + '" requires a vector source'));
                } else if (sourceType === "vector" && !layer2["source-layer"]) {
                  errors.push(new ValidationError(key, layer2, 'layer "' + layer2.id + '" must specify a "source-layer"'));
                } else if (sourceType === "raster-dem" && type !== "hillshade") {
                  errors.push(new ValidationError(key, layer2.source, "raster-dem source can only be used with layer type 'hillshade'."));
                } else if (type === "line" && layer2.paint && layer2.paint["line-gradient"] && (sourceType !== "geojson" || !source2.lineMetrics)) {
                  errors.push(new ValidationError(key, layer2, 'layer "' + layer2.id + '" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.'));
                }
              }
            }
            errors = errors.concat(validateObject({
              key,
              value: layer2,
              valueSpec: styleSpec.layer,
              style: options.style,
              styleSpec: options.styleSpec,
              objectElementValidators: {
                "*": function _() {
                  return [];
                },
                type: function type2() {
                  return validate({
                    key: key + ".type",
                    value: layer2.type,
                    valueSpec: styleSpec.layer.type,
                    style: options.style,
                    styleSpec: options.styleSpec,
                    object: layer2,
                    objectKey: "type"
                  });
                },
                filter: validateFilter,
                layout: function layout2(options2) {
                  return validateObject({
                    layer: layer2,
                    key: options2.key,
                    value: options2.value,
                    style: options2.style,
                    styleSpec: options2.styleSpec,
                    objectElementValidators: {
                      "*": function _(options3) {
                        return validateLayoutProperty(extend$1({ layerType: type }, options3));
                      }
                    }
                  });
                },
                paint: function paint2(options2) {
                  return validateObject({
                    layer: layer2,
                    key: options2.key,
                    value: options2.value,
                    style: options2.style,
                    styleSpec: options2.styleSpec,
                    objectElementValidators: {
                      "*": function _(options3) {
                        return validatePaintProperty(extend$1({ layerType: type }, options3));
                      }
                    }
                  });
                }
              }
            }));
            return errors;
          }
          function validateString(options) {
            var value = options.value;
            var key = options.key;
            var type = getType(value);
            if (type !== "string") {
              return [new ValidationError(key, value, "string expected, " + type + " found")];
            }
            return [];
          }
          var objectElementValidators = { promoteId: validatePromoteId };
          function validateSource(options) {
            var value = options.value;
            var key = options.key;
            var styleSpec = options.styleSpec;
            var style = options.style;
            if (!value.type) {
              return [new ValidationError(key, value, '"type" is required')];
            }
            var type = unbundle(value.type);
            var errors;
            switch (type) {
              case "vector":
              case "raster":
              case "raster-dem":
                errors = validateObject({
                  key,
                  value,
                  valueSpec: styleSpec["source_" + type.replace("-", "_")],
                  style: options.style,
                  styleSpec,
                  objectElementValidators
                });
                return errors;
              case "geojson":
                errors = validateObject({
                  key,
                  value,
                  valueSpec: styleSpec.source_geojson,
                  style,
                  styleSpec,
                  objectElementValidators
                });
                if (value.cluster) {
                  for (var prop in value.clusterProperties) {
                    var ref = value.clusterProperties[prop];
                    var operator = ref[0];
                    var mapExpr = ref[1];
                    var reduceExpr = typeof operator === "string" ? [
                      operator,
                      ["accumulated"],
                      [
                        "get",
                        prop
                      ]
                    ] : operator;
                    errors.push.apply(errors, validateExpression({
                      key: key + "." + prop + ".map",
                      value: mapExpr,
                      expressionContext: "cluster-map"
                    }));
                    errors.push.apply(errors, validateExpression({
                      key: key + "." + prop + ".reduce",
                      value: reduceExpr,
                      expressionContext: "cluster-reduce"
                    }));
                  }
                }
                return errors;
              case "video":
                return validateObject({
                  key,
                  value,
                  valueSpec: styleSpec.source_video,
                  style,
                  styleSpec
                });
              case "image":
                return validateObject({
                  key,
                  value,
                  valueSpec: styleSpec.source_image,
                  style,
                  styleSpec
                });
              case "canvas":
                return [new ValidationError(key, null, "Please use runtime APIs to add canvas sources, rather than including them in stylesheets.", "source.canvas")];
              default:
                return validateEnum({
                  key: key + ".type",
                  value: value.type,
                  valueSpec: {
                    values: [
                      "vector",
                      "raster",
                      "raster-dem",
                      "geojson",
                      "video",
                      "image"
                    ]
                  },
                  style,
                  styleSpec
                });
            }
          }
          function validatePromoteId(ref) {
            var key = ref.key;
            var value = ref.value;
            if (getType(value) === "string") {
              return validateString({
                key,
                value
              });
            } else {
              var errors = [];
              for (var prop in value) {
                errors.push.apply(errors, validateString({
                  key: key + "." + prop,
                  value: value[prop]
                }));
              }
              return errors;
            }
          }
          function validateLight(options) {
            var light2 = options.value;
            var styleSpec = options.styleSpec;
            var lightSpec = styleSpec.light;
            var style = options.style;
            var errors = [];
            var rootType = getType(light2);
            if (light2 === void 0) {
              return errors;
            } else if (rootType !== "object") {
              errors = errors.concat([new ValidationError("light", light2, "object expected, " + rootType + " found")]);
              return errors;
            }
            for (var key in light2) {
              var transitionMatch = key.match(/^(.*)-transition$/);
              if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {
                errors = errors.concat(validate({
                  key,
                  value: light2[key],
                  valueSpec: styleSpec.transition,
                  style,
                  styleSpec
                }));
              } else if (lightSpec[key]) {
                errors = errors.concat(validate({
                  key,
                  value: light2[key],
                  valueSpec: lightSpec[key],
                  style,
                  styleSpec
                }));
              } else {
                errors = errors.concat([new ValidationError(key, light2[key], 'unknown property "' + key + '"')]);
              }
            }
            return errors;
          }
          function validateFormatted(options) {
            if (validateString(options).length === 0) {
              return [];
            }
            return validateExpression(options);
          }
          function validateImage(options) {
            if (validateString(options).length === 0) {
              return [];
            }
            return validateExpression(options);
          }
          var VALIDATORS = {
            "*": function _() {
              return [];
            },
            "array": validateArray,
            "boolean": validateBoolean,
            "number": validateNumber,
            "color": validateColor,
            "constants": validateConstants,
            "enum": validateEnum,
            "filter": validateFilter,
            "function": validateFunction,
            "layer": validateLayer,
            "object": validateObject,
            "source": validateSource,
            "light": validateLight,
            "string": validateString,
            "formatted": validateFormatted,
            "resolvedImage": validateImage
          };
          function validate(options) {
            var value = options.value;
            var valueSpec = options.valueSpec;
            var styleSpec = options.styleSpec;
            if (valueSpec.expression && isFunction(unbundle(value))) {
              return validateFunction(options);
            } else if (valueSpec.expression && isExpression(deepUnbundle(value))) {
              return validateExpression(options);
            } else if (valueSpec.type && VALIDATORS[valueSpec.type]) {
              return VALIDATORS[valueSpec.type](options);
            } else {
              var valid = validateObject(extend$1({}, options, { valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec }));
              return valid;
            }
          }
          function validateGlyphsURL(options) {
            var value = options.value;
            var key = options.key;
            var errors = validateString(options);
            if (errors.length) {
              return errors;
            }
            if (value.indexOf("{fontstack}") === -1) {
              errors.push(new ValidationError(key, value, '"glyphs" url must include a "{fontstack}" token'));
            }
            if (value.indexOf("{range}") === -1) {
              errors.push(new ValidationError(key, value, '"glyphs" url must include a "{range}" token'));
            }
            return errors;
          }
          function validateStyleMin(style, styleSpec) {
            if (styleSpec === void 0)
              styleSpec = spec;
            var errors = [];
            errors = errors.concat(validate({
              key: "",
              value: style,
              valueSpec: styleSpec.$root,
              styleSpec,
              style,
              objectElementValidators: {
                glyphs: validateGlyphsURL,
                "*": function _() {
                  return [];
                }
              }
            }));
            if (style.constants) {
              errors = errors.concat(validateConstants({
                key: "constants",
                value: style.constants,
                style,
                styleSpec
              }));
            }
            return sortErrors(errors);
          }
          validateStyleMin.source = wrapCleanErrors(validateSource);
          validateStyleMin.light = wrapCleanErrors(validateLight);
          validateStyleMin.layer = wrapCleanErrors(validateLayer);
          validateStyleMin.filter = wrapCleanErrors(validateFilter);
          validateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty);
          validateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty);
          function sortErrors(errors) {
            return [].concat(errors).sort(function(a, b) {
              return a.line - b.line;
            });
          }
          function wrapCleanErrors(inner) {
            return function() {
              var args = [], len = arguments.length;
              while (len--)
                args[len] = arguments[len];
              return sortErrors(inner.apply(this, args));
            };
          }
          var validateStyle = validateStyleMin;
          var validateLight$1 = validateStyle.light;
          var validatePaintProperty$1 = validateStyle.paintProperty;
          var validateLayoutProperty$1 = validateStyle.layoutProperty;
          function emitValidationErrors(emitter, errors) {
            var hasErrors = false;
            if (errors && errors.length) {
              for (var i = 0, list = errors; i < list.length; i += 1) {
                var error2 = list[i];
                emitter.fire(new ErrorEvent(new Error(error2.message)));
                hasErrors = true;
              }
            }
            return hasErrors;
          }
          var gridIndex = GridIndex;
          var NUM_PARAMS = 3;
          function GridIndex(extent, n, padding) {
            var cells = this.cells = [];
            if (extent instanceof ArrayBuffer) {
              this.arrayBuffer = extent;
              var array2 = new Int32Array(this.arrayBuffer);
              extent = array2[0];
              n = array2[1];
              padding = array2[2];
              this.d = n + 2 * padding;
              for (var k = 0; k < this.d * this.d; k++) {
                var start = array2[NUM_PARAMS + k];
                var end = array2[NUM_PARAMS + k + 1];
                cells.push(start === end ? null : array2.subarray(start, end));
              }
              var keysOffset = array2[NUM_PARAMS + cells.length];
              var bboxesOffset = array2[NUM_PARAMS + cells.length + 1];
              this.keys = array2.subarray(keysOffset, bboxesOffset);
              this.bboxes = array2.subarray(bboxesOffset);
              this.insert = this._insertReadonly;
            } else {
              this.d = n + 2 * padding;
              for (var i = 0; i < this.d * this.d; i++) {
                cells.push([]);
              }
              this.keys = [];
              this.bboxes = [];
            }
            this.n = n;
            this.extent = extent;
            this.padding = padding;
            this.scale = n / extent;
            this.uid = 0;
            var p = padding / n * extent;
            this.min = -p;
            this.max = extent + p;
          }
          GridIndex.prototype.insert = function(key, x1, y1, x2, y2) {
            this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++);
            this.keys.push(key);
            this.bboxes.push(x1);
            this.bboxes.push(y1);
            this.bboxes.push(x2);
            this.bboxes.push(y2);
          };
          GridIndex.prototype._insertReadonly = function() {
            throw "Cannot insert into a GridIndex created from an ArrayBuffer.";
          };
          GridIndex.prototype._insertCell = function(x1, y1, x2, y2, cellIndex, uid) {
            this.cells[cellIndex].push(uid);
          };
          GridIndex.prototype.query = function(x1, y1, x2, y2, intersectionTest) {
            var min = this.min;
            var max = this.max;
            if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) {
              return Array.prototype.slice.call(this.keys);
            } else {
              var result = [];
              var seenUids = {};
              this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest);
              return result;
            }
          };
          GridIndex.prototype._queryCell = function(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) {
            var cell = this.cells[cellIndex];
            if (cell !== null) {
              var keys = this.keys;
              var bboxes = this.bboxes;
              for (var u = 0; u < cell.length; u++) {
                var uid = cell[u];
                if (seenUids[uid] === void 0) {
                  var offset = uid * 4;
                  if (intersectionTest ? intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) : x1 <= bboxes[offset + 2] && y1 <= bboxes[offset + 3] && x2 >= bboxes[offset + 0] && y2 >= bboxes[offset + 1]) {
                    seenUids[uid] = true;
                    result.push(keys[uid]);
                  } else {
                    seenUids[uid] = false;
                  }
                }
              }
            }
          };
          GridIndex.prototype._forEachCell = function(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) {
            var cx1 = this._convertToCellCoord(x1);
            var cy1 = this._convertToCellCoord(y1);
            var cx2 = this._convertToCellCoord(x2);
            var cy2 = this._convertToCellCoord(y2);
            for (var x = cx1; x <= cx2; x++) {
              for (var y = cy1; y <= cy2; y++) {
                var cellIndex = this.d * y + x;
                if (intersectionTest && !intersectionTest(this._convertFromCellCoord(x), this._convertFromCellCoord(y), this._convertFromCellCoord(x + 1), this._convertFromCellCoord(y + 1))) {
                  continue;
                }
                if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) {
                  return;
                }
              }
            }
          };
          GridIndex.prototype._convertFromCellCoord = function(x) {
            return (x - this.padding) / this.scale;
          };
          GridIndex.prototype._convertToCellCoord = function(x) {
            return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding));
          };
          GridIndex.prototype.toArrayBuffer = function() {
            if (this.arrayBuffer) {
              return this.arrayBuffer;
            }
            var cells = this.cells;
            var metadataLength = NUM_PARAMS + this.cells.length + 1 + 1;
            var totalCellLength = 0;
            for (var i = 0; i < this.cells.length; i++) {
              totalCellLength += this.cells[i].length;
            }
            var array2 = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length);
            array2[0] = this.extent;
            array2[1] = this.n;
            array2[2] = this.padding;
            var offset = metadataLength;
            for (var k = 0; k < cells.length; k++) {
              var cell = cells[k];
              array2[NUM_PARAMS + k] = offset;
              array2.set(cell, offset);
              offset += cell.length;
            }
            array2[NUM_PARAMS + cells.length] = offset;
            array2.set(this.keys, offset);
            offset += this.keys.length;
            array2[NUM_PARAMS + cells.length + 1] = offset;
            array2.set(this.bboxes, offset);
            offset += this.bboxes.length;
            return array2.buffer;
          };
          var ImageData2 = window$1.ImageData;
          var ImageBitmap2 = window$1.ImageBitmap;
          var registry = {};
          function register(name3, klass, options) {
            if (options === void 0)
              options = {};
            Object.defineProperty(klass, "_classRegistryKey", {
              value: name3,
              writeable: false
            });
            registry[name3] = {
              klass,
              omit: options.omit || [],
              shallow: options.shallow || []
            };
          }
          register("Object", Object);
          gridIndex.serialize = function serialize2(grid, transferables) {
            var buffer = grid.toArrayBuffer();
            if (transferables) {
              transferables.push(buffer);
            }
            return { buffer };
          };
          gridIndex.deserialize = function deserialize2(serialized) {
            return new gridIndex(serialized.buffer);
          };
          register("Grid", gridIndex);
          register("Color", Color2);
          register("Error", Error);
          register("ResolvedImage", ResolvedImage);
          register("StylePropertyFunction", StylePropertyFunction);
          register("StyleExpression", StyleExpression, { omit: ["_evaluator"] });
          register("ZoomDependentExpression", ZoomDependentExpression);
          register("ZoomConstantExpression", ZoomConstantExpression);
          register("CompoundExpression", CompoundExpression, { omit: ["_evaluate"] });
          for (var name2 in expressions) {
            if (expressions[name2]._classRegistryKey) {
              continue;
            }
            register("Expression_" + name2, expressions[name2]);
          }
          function isArrayBuffer(val) {
            return val && typeof ArrayBuffer !== "undefined" && (val instanceof ArrayBuffer || val.constructor && val.constructor.name === "ArrayBuffer");
          }
          function isImageBitmap(val) {
            return ImageBitmap2 && val instanceof ImageBitmap2;
          }
          function serialize(input, transferables) {
            if (input === null || input === void 0 || typeof input === "boolean" || typeof input === "number" || typeof input === "string" || input instanceof Boolean || input instanceof Number || input instanceof String || input instanceof Date || input instanceof RegExp) {
              return input;
            }
            if (isArrayBuffer(input) || isImageBitmap(input)) {
              if (transferables) {
                transferables.push(input);
              }
              return input;
            }
            if (ArrayBuffer.isView(input)) {
              var view = input;
              if (transferables) {
                transferables.push(view.buffer);
              }
              return view;
            }
            if (input instanceof ImageData2) {
              if (transferables) {
                transferables.push(input.data.buffer);
              }
              return input;
            }
            if (Array.isArray(input)) {
              var serialized = [];
              for (var i = 0, list = input; i < list.length; i += 1) {
                var item = list[i];
                serialized.push(serialize(item, transferables));
              }
              return serialized;
            }
            if (typeof input === "object") {
              var klass = input.constructor;
              var name3 = klass._classRegistryKey;
              if (!name3) {
                throw new Error("can't serialize object of unregistered class");
              }
              var properties2 = klass.serialize ? klass.serialize(input, transferables) : {};
              if (!klass.serialize) {
                for (var key in input) {
                  if (!input.hasOwnProperty(key)) {
                    continue;
                  }
                  if (registry[name3].omit.indexOf(key) >= 0) {
                    continue;
                  }
                  var property = input[key];
                  properties2[key] = registry[name3].shallow.indexOf(key) >= 0 ? property : serialize(property, transferables);
                }
                if (input instanceof Error) {
                  properties2.message = input.message;
                }
              }
              if (properties2.$name) {
                throw new Error("$name property is reserved for worker serialization logic.");
              }
              if (name3 !== "Object") {
                properties2.$name = name3;
              }
              return properties2;
            }
            throw new Error("can't serialize object of type " + typeof input);
          }
          function deserialize(input) {
            if (input === null || input === void 0 || typeof input === "boolean" || typeof input === "number" || typeof input === "string" || input instanceof Boolean || input instanceof Number || input instanceof String || input instanceof Date || input instanceof RegExp || isArrayBuffer(input) || isImageBitmap(input) || ArrayBuffer.isView(input) || input instanceof ImageData2) {
              return input;
            }
            if (Array.isArray(input)) {
              return input.map(deserialize);
            }
            if (typeof input === "object") {
              var name3 = input.$name || "Object";
              var ref = registry[name3];
              var klass = ref.klass;
              if (!klass) {
                throw new Error("can't deserialize unregistered class " + name3);
              }
              if (klass.deserialize) {
                return klass.deserialize(input);
              }
              var result = Object.create(klass.prototype);
              for (var i = 0, list = Object.keys(input); i < list.length; i += 1) {
                var key = list[i];
                if (key === "$name") {
                  continue;
                }
                var value = input[key];
                result[key] = registry[name3].shallow.indexOf(key) >= 0 ? value : deserialize(value);
              }
              return result;
            }
            throw new Error("can't deserialize object of type " + typeof input);
          }
          var ZoomHistory = function ZoomHistory2() {
            this.first = true;
          };
          ZoomHistory.prototype.update = function update(z, now2) {
            var floorZ = Math.floor(z);
            if (this.first) {
              this.first = false;
              this.lastIntegerZoom = floorZ;
              this.lastIntegerZoomTime = 0;
              this.lastZoom = z;
              this.lastFloorZoom = floorZ;
              return true;
            }
            if (this.lastFloorZoom > floorZ) {
              this.lastIntegerZoom = floorZ + 1;
              this.lastIntegerZoomTime = now2;
            } else if (this.lastFloorZoom < floorZ) {
              this.lastIntegerZoom = floorZ;
              this.lastIntegerZoomTime = now2;
            }
            if (z !== this.lastZoom) {
              this.lastZoom = z;
              this.lastFloorZoom = floorZ;
              return true;
            }
            return false;
          };
          var unicodeBlockLookup = {
            "Latin-1 Supplement": function(char) {
              return char >= 128 && char <= 255;
            },
            "Arabic": function(char) {
              return char >= 1536 && char <= 1791;
            },
            "Arabic Supplement": function(char) {
              return char >= 1872 && char <= 1919;
            },
            "Arabic Extended-A": function(char) {
              return char >= 2208 && char <= 2303;
            },
            "Hangul Jamo": function(char) {
              return char >= 4352 && char <= 4607;
            },
            "Unified Canadian Aboriginal Syllabics": function(char) {
              return char >= 5120 && char <= 5759;
            },
            "Khmer": function(char) {
              return char >= 6016 && char <= 6143;
            },
            "Unified Canadian Aboriginal Syllabics Extended": function(char) {
              return char >= 6320 && char <= 6399;
            },
            "General Punctuation": function(char) {
              return char >= 8192 && char <= 8303;
            },
            "Letterlike Symbols": function(char) {
              return char >= 8448 && char <= 8527;
            },
            "Number Forms": function(char) {
              return char >= 8528 && char <= 8591;
            },
            "Miscellaneous Technical": function(char) {
              return char >= 8960 && char <= 9215;
            },
            "Control Pictures": function(char) {
              return char >= 9216 && char <= 9279;
            },
            "Optical Character Recognition": function(char) {
              return char >= 9280 && char <= 9311;
            },
            "Enclosed Alphanumerics": function(char) {
              return char >= 9312 && char <= 9471;
            },
            "Geometric Shapes": function(char) {
              return char >= 9632 && char <= 9727;
            },
            "Miscellaneous Symbols": function(char) {
              return char >= 9728 && char <= 9983;
            },
            "Miscellaneous Symbols and Arrows": function(char) {
              return char >= 11008 && char <= 11263;
            },
            "CJK Radicals Supplement": function(char) {
              return char >= 11904 && char <= 12031;
            },
            "Kangxi Radicals": function(char) {
              return char >= 12032 && char <= 12255;
            },
            "Ideographic Description Characters": function(char) {
              return char >= 12272 && char <= 12287;
            },
            "CJK Symbols and Punctuation": function(char) {
              return char >= 12288 && char <= 12351;
            },
            "Hiragana": function(char) {
              return char >= 12352 && char <= 12447;
            },
            "Katakana": function(char) {
              return char >= 12448 && char <= 12543;
            },
            "Bopomofo": function(char) {
              return char >= 12544 && char <= 12591;
            },
            "Hangul Compatibility Jamo": function(char) {
              return char >= 12592 && char <= 12687;
            },
            "Kanbun": function(char) {
              return char >= 12688 && char <= 12703;
            },
            "Bopomofo Extended": function(char) {
              return char >= 12704 && char <= 12735;
            },
            "CJK Strokes": function(char) {
              return char >= 12736 && char <= 12783;
            },
            "Katakana Phonetic Extensions": function(char) {
              return char >= 12784 && char <= 12799;
            },
            "Enclosed CJK Letters and Months": function(char) {
              return char >= 12800 && char <= 13055;
            },
            "CJK Compatibility": function(char) {
              return char >= 13056 && char <= 13311;
            },
            "CJK Unified Ideographs Extension A": function(char) {
              return char >= 13312 && char <= 19903;
            },
            "Yijing Hexagram Symbols": function(char) {
              return char >= 19904 && char <= 19967;
            },
            "CJK Unified Ideographs": function(char) {
              return char >= 19968 && char <= 40959;
            },
            "Yi Syllables": function(char) {
              return char >= 40960 && char <= 42127;
            },
            "Yi Radicals": function(char) {
              return char >= 42128 && char <= 42191;
            },
            "Hangul Jamo Extended-A": function(char) {
              return char >= 43360 && char <= 43391;
            },
            "Hangul Syllables": function(char) {
              return char >= 44032 && char <= 55215;
            },
            "Hangul Jamo Extended-B": function(char) {
              return char >= 55216 && char <= 55295;
            },
            "Private Use Area": function(char) {
              return char >= 57344 && char <= 63743;
            },
            "CJK Compatibility Ideographs": function(char) {
              return char >= 63744 && char <= 64255;
            },
            "Arabic Presentation Forms-A": function(char) {
              return char >= 64336 && char <= 65023;
            },
            "Vertical Forms": function(char) {
              return char >= 65040 && char <= 65055;
            },
            "CJK Compatibility Forms": function(char) {
              return char >= 65072 && char <= 65103;
            },
            "Small Form Variants": function(char) {
              return char >= 65104 && char <= 65135;
            },
            "Arabic Presentation Forms-B": function(char) {
              return char >= 65136 && char <= 65279;
            },
            "Halfwidth and Fullwidth Forms": function(char) {
              return char >= 65280 && char <= 65519;
            }
          };
          function allowsVerticalWritingMode(chars) {
            for (var i = 0, list = chars; i < list.length; i += 1) {
              var char = list[i];
              if (charHasUprightVerticalOrientation(char.charCodeAt(0))) {
                return true;
              }
            }
            return false;
          }
          function allowsLetterSpacing(chars) {
            for (var i = 0, list = chars; i < list.length; i += 1) {
              var char = list[i];
              if (!charAllowsLetterSpacing(char.charCodeAt(0))) {
                return false;
              }
            }
            return true;
          }
          function charAllowsLetterSpacing(char) {
            if (unicodeBlockLookup["Arabic"](char)) {
              return false;
            }
            if (unicodeBlockLookup["Arabic Supplement"](char)) {
              return false;
            }
            if (unicodeBlockLookup["Arabic Extended-A"](char)) {
              return false;
            }
            if (unicodeBlockLookup["Arabic Presentation Forms-A"](char)) {
              return false;
            }
            if (unicodeBlockLookup["Arabic Presentation Forms-B"](char)) {
              return false;
            }
            return true;
          }
          function charAllowsIdeographicBreaking(char) {
            if (char < 11904) {
              return false;
            }
            if (unicodeBlockLookup["Bopomofo Extended"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Bopomofo"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Compatibility Forms"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Compatibility Ideographs"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Compatibility"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Radicals Supplement"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Strokes"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Symbols and Punctuation"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Unified Ideographs Extension A"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Unified Ideographs"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Enclosed CJK Letters and Months"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Halfwidth and Fullwidth Forms"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Hiragana"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Ideographic Description Characters"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Kangxi Radicals"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Katakana Phonetic Extensions"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Katakana"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Vertical Forms"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Yi Radicals"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Yi Syllables"](char)) {
              return true;
            }
            return false;
          }
          function charHasUprightVerticalOrientation(char) {
            if (char === 746 || char === 747) {
              return true;
            }
            if (char < 4352) {
              return false;
            }
            if (unicodeBlockLookup["Bopomofo Extended"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Bopomofo"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Compatibility Forms"](char)) {
              if (!(char >= 65097 && char <= 65103)) {
                return true;
              }
            }
            if (unicodeBlockLookup["CJK Compatibility Ideographs"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Compatibility"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Radicals Supplement"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Strokes"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Symbols and Punctuation"](char)) {
              if (!(char >= 12296 && char <= 12305) && !(char >= 12308 && char <= 12319) && char !== 12336) {
                return true;
              }
            }
            if (unicodeBlockLookup["CJK Unified Ideographs Extension A"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Unified Ideographs"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Enclosed CJK Letters and Months"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Hangul Compatibility Jamo"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Hangul Jamo Extended-A"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Hangul Jamo Extended-B"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Hangul Jamo"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Hangul Syllables"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Hiragana"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Ideographic Description Characters"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Kanbun"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Kangxi Radicals"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Katakana Phonetic Extensions"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Katakana"](char)) {
              if (char !== 12540) {
                return true;
              }
            }
            if (unicodeBlockLookup["Halfwidth and Fullwidth Forms"](char)) {
              if (char !== 65288 && char !== 65289 && char !== 65293 && !(char >= 65306 && char <= 65310) && char !== 65339 && char !== 65341 && char !== 65343 && !(char >= 65371 && char <= 65503) && char !== 65507 && !(char >= 65512 && char <= 65519)) {
                return true;
              }
            }
            if (unicodeBlockLookup["Small Form Variants"](char)) {
              if (!(char >= 65112 && char <= 65118) && !(char >= 65123 && char <= 65126)) {
                return true;
              }
            }
            if (unicodeBlockLookup["Unified Canadian Aboriginal Syllabics"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Unified Canadian Aboriginal Syllabics Extended"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Vertical Forms"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Yijing Hexagram Symbols"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Yi Syllables"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Yi Radicals"](char)) {
              return true;
            }
            return false;
          }
          function charHasNeutralVerticalOrientation(char) {
            if (unicodeBlockLookup["Latin-1 Supplement"](char)) {
              if (char === 167 || char === 169 || char === 174 || char === 177 || char === 188 || char === 189 || char === 190 || char === 215 || char === 247) {
                return true;
              }
            }
            if (unicodeBlockLookup["General Punctuation"](char)) {
              if (char === 8214 || char === 8224 || char === 8225 || char === 8240 || char === 8241 || char === 8251 || char === 8252 || char === 8258 || char === 8263 || char === 8264 || char === 8265 || char === 8273) {
                return true;
              }
            }
            if (unicodeBlockLookup["Letterlike Symbols"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Number Forms"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Miscellaneous Technical"](char)) {
              if (char >= 8960 && char <= 8967 || char >= 8972 && char <= 8991 || char >= 8996 && char <= 9e3 || char === 9003 || char >= 9085 && char <= 9114 || char >= 9150 && char <= 9165 || char === 9167 || char >= 9169 && char <= 9179 || char >= 9186 && char <= 9215) {
                return true;
              }
            }
            if (unicodeBlockLookup["Control Pictures"](char) && char !== 9251) {
              return true;
            }
            if (unicodeBlockLookup["Optical Character Recognition"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Enclosed Alphanumerics"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Geometric Shapes"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Miscellaneous Symbols"](char)) {
              if (!(char >= 9754 && char <= 9759)) {
                return true;
              }
            }
            if (unicodeBlockLookup["Miscellaneous Symbols and Arrows"](char)) {
              if (char >= 11026 && char <= 11055 || char >= 11088 && char <= 11097 || char >= 11192 && char <= 11243) {
                return true;
              }
            }
            if (unicodeBlockLookup["CJK Symbols and Punctuation"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Katakana"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Private Use Area"](char)) {
              return true;
            }
            if (unicodeBlockLookup["CJK Compatibility Forms"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Small Form Variants"](char)) {
              return true;
            }
            if (unicodeBlockLookup["Halfwidth and Fullwidth Forms"](char)) {
              return true;
            }
            if (char === 8734 || char === 8756 || char === 8757 || char >= 9984 && char <= 10087 || char >= 10102 && char <= 10131 || char === 65532 || char === 65533) {
              return true;
            }
            return false;
          }
          function charHasRotatedVerticalOrientation(char) {
            return !(charHasUprightVerticalOrientation(char) || charHasNeutralVerticalOrientation(char));
          }
          function charInComplexShapingScript(char) {
            return unicodeBlockLookup["Arabic"](char) || unicodeBlockLookup["Arabic Supplement"](char) || unicodeBlockLookup["Arabic Extended-A"](char) || unicodeBlockLookup["Arabic Presentation Forms-A"](char) || unicodeBlockLookup["Arabic Presentation Forms-B"](char);
          }
          function charInRTLScript(char) {
            return char >= 1424 && char <= 2303 || unicodeBlockLookup["Arabic Presentation Forms-A"](char) || unicodeBlockLookup["Arabic Presentation Forms-B"](char);
          }
          function charInSupportedScript(char, canRenderRTL) {
            if (!canRenderRTL && charInRTLScript(char)) {
              return false;
            }
            if (char >= 2304 && char <= 3583 || char >= 3840 && char <= 4255 || unicodeBlockLookup["Khmer"](char)) {
              return false;
            }
            return true;
          }
          function stringContainsRTLText(chars) {
            for (var i = 0, list = chars; i < list.length; i += 1) {
              var char = list[i];
              if (charInRTLScript(char.charCodeAt(0))) {
                return true;
              }
            }
            return false;
          }
          function isStringInSupportedScript(chars, canRenderRTL) {
            for (var i = 0, list = chars; i < list.length; i += 1) {
              var char = list[i];
              if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) {
                return false;
              }
            }
            return true;
          }
          var status = {
            unavailable: "unavailable",
            deferred: "deferred",
            loading: "loading",
            loaded: "loaded",
            error: "error"
          };
          var _completionCallback = null;
          var pluginStatus = status.unavailable;
          var pluginURL = null;
          var triggerPluginCompletionEvent = function(error2) {
            if (error2 && typeof error2 === "string" && error2.indexOf("NetworkError") > -1) {
              pluginStatus = status.error;
            }
            if (_completionCallback) {
              _completionCallback(error2);
            }
          };
          function sendPluginStateToWorker() {
            evented.fire(new Event("pluginStateChange", {
              pluginStatus,
              pluginURL
            }));
          }
          var evented = new Evented();
          var getRTLTextPluginStatus = function() {
            return pluginStatus;
          };
          var registerForPluginStateChange = function(callback) {
            callback({
              pluginStatus,
              pluginURL
            });
            evented.on("pluginStateChange", callback);
            return callback;
          };
          var setRTLTextPlugin = function(url, callback, deferred) {
            if (deferred === void 0)
              deferred = false;
            if (pluginStatus === status.deferred || pluginStatus === status.loading || pluginStatus === status.loaded) {
              throw new Error("setRTLTextPlugin cannot be called multiple times.");
            }
            pluginURL = exported.resolveURL(url);
            pluginStatus = status.deferred;
            _completionCallback = callback;
            sendPluginStateToWorker();
            if (!deferred) {
              downloadRTLTextPlugin();
            }
          };
          var downloadRTLTextPlugin = function() {
            if (pluginStatus !== status.deferred || !pluginURL) {
              throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");
            }
            pluginStatus = status.loading;
            sendPluginStateToWorker();
            if (pluginURL) {
              getArrayBuffer({ url: pluginURL }, function(error2) {
                if (error2) {
                  triggerPluginCompletionEvent(error2);
                } else {
                  pluginStatus = status.loaded;
                  sendPluginStateToWorker();
                }
              });
            }
          };
          var plugin = {
            applyArabicShaping: null,
            processBidirectionalText: null,
            processStyledBidirectionalText: null,
            isLoaded: function isLoaded() {
              return pluginStatus === status.loaded || plugin.applyArabicShaping != null;
            },
            isLoading: function isLoading() {
              return pluginStatus === status.loading;
            },
            setState: function setState(state) {
              pluginStatus = state.pluginStatus;
              pluginURL = state.pluginURL;
            },
            isParsed: function isParsed() {
              return plugin.applyArabicShaping != null && plugin.processBidirectionalText != null && plugin.processStyledBidirectionalText != null;
            },
            getPluginURL: function getPluginURL() {
              return pluginURL;
            }
          };
          var lazyLoadRTLTextPlugin = function() {
            if (!plugin.isLoading() && !plugin.isLoaded() && getRTLTextPluginStatus() === "deferred") {
              downloadRTLTextPlugin();
            }
          };
          var EvaluationParameters = function EvaluationParameters2(zoom, options) {
            this.zoom = zoom;
            if (options) {
              this.now = options.now;
              this.fadeDuration = options.fadeDuration;
              this.zoomHistory = options.zoomHistory;
              this.transition = options.transition;
            } else {
              this.now = 0;
              this.fadeDuration = 0;
              this.zoomHistory = new ZoomHistory();
              this.transition = {};
            }
          };
          EvaluationParameters.prototype.isSupportedScript = function isSupportedScript(str) {
            return isStringInSupportedScript(str, plugin.isLoaded());
          };
          EvaluationParameters.prototype.crossFadingFactor = function crossFadingFactor() {
            if (this.fadeDuration === 0) {
              return 1;
            } else {
              return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1);
            }
          };
          EvaluationParameters.prototype.getCrossfadeParameters = function getCrossfadeParameters() {
            var z = this.zoom;
            var fraction = z - Math.floor(z);
            var t = this.crossFadingFactor();
            return z > this.zoomHistory.lastIntegerZoom ? {
              fromScale: 2,
              toScale: 1,
              t: fraction + (1 - fraction) * t
            } : {
              fromScale: 0.5,
              toScale: 1,
              t: 1 - (1 - t) * fraction
            };
          };
          var PropertyValue = function PropertyValue2(property, value) {
            this.property = property;
            this.value = value;
            this.expression = normalizePropertyExpression(value === void 0 ? property.specification.default : value, property.specification);
          };
          PropertyValue.prototype.isDataDriven = function isDataDriven() {
            return this.expression.kind === "source" || this.expression.kind === "composite";
          };
          PropertyValue.prototype.possiblyEvaluate = function possiblyEvaluate(parameters, canonical, availableImages) {
            return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);
          };
          var TransitionablePropertyValue = function TransitionablePropertyValue2(property) {
            this.property = property;
            this.value = new PropertyValue(property, void 0);
          };
          TransitionablePropertyValue.prototype.transitioned = function transitioned(parameters, prior) {
            return new TransitioningPropertyValue(this.property, this.value, prior, extend2({}, parameters.transition, this.transition), parameters.now);
          };
          TransitionablePropertyValue.prototype.untransitioned = function untransitioned() {
            return new TransitioningPropertyValue(this.property, this.value, null, {}, 0);
          };
          var Transitionable = function Transitionable2(properties2) {
            this._properties = properties2;
            this._values = Object.create(properties2.defaultTransitionablePropertyValues);
          };
          Transitionable.prototype.getValue = function getValue(name3) {
            return clone(this._values[name3].value.value);
          };
          Transitionable.prototype.setValue = function setValue(name3, value) {
            if (!this._values.hasOwnProperty(name3)) {
              this._values[name3] = new TransitionablePropertyValue(this._values[name3].property);
            }
            this._values[name3].value = new PropertyValue(this._values[name3].property, value === null ? void 0 : clone(value));
          };
          Transitionable.prototype.getTransition = function getTransition(name3) {
            return clone(this._values[name3].transition);
          };
          Transitionable.prototype.setTransition = function setTransition(name3, value) {
            if (!this._values.hasOwnProperty(name3)) {
              this._values[name3] = new TransitionablePropertyValue(this._values[name3].property);
            }
            this._values[name3].transition = clone(value) || void 0;
          };
          Transitionable.prototype.serialize = function serialize2() {
            var result = {};
            for (var i = 0, list = Object.keys(this._values); i < list.length; i += 1) {
              var property = list[i];
              var value = this.getValue(property);
              if (value !== void 0) {
                result[property] = value;
              }
              var transition2 = this.getTransition(property);
              if (transition2 !== void 0) {
                result[property + "-transition"] = transition2;
              }
            }
            return result;
          };
          Transitionable.prototype.transitioned = function transitioned(parameters, prior) {
            var result = new Transitioning(this._properties);
            for (var i = 0, list = Object.keys(this._values); i < list.length; i += 1) {
              var property = list[i];
              result._values[property] = this._values[property].transitioned(parameters, prior._values[property]);
            }
            return result;
          };
          Transitionable.prototype.untransitioned = function untransitioned() {
            var result = new Transitioning(this._properties);
            for (var i = 0, list = Object.keys(this._values); i < list.length; i += 1) {
              var property = list[i];
              result._values[property] = this._values[property].untransitioned();
            }
            return result;
          };
          var TransitioningPropertyValue = function TransitioningPropertyValue2(property, value, prior, transition2, now2) {
            this.property = property;
            this.value = value;
            this.begin = now2 + transition2.delay || 0;
            this.end = this.begin + transition2.duration || 0;
            if (property.specification.transition && (transition2.delay || transition2.duration)) {
              this.prior = prior;
            }
          };
          TransitioningPropertyValue.prototype.possiblyEvaluate = function possiblyEvaluate(parameters, canonical, availableImages) {
            var now2 = parameters.now || 0;
            var finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages);
            var prior = this.prior;
            if (!prior) {
              return finalValue;
            } else if (now2 > this.end) {
              this.prior = null;
              return finalValue;
            } else if (this.value.isDataDriven()) {
              this.prior = null;
              return finalValue;
            } else if (now2 < this.begin) {
              return prior.possiblyEvaluate(parameters, canonical, availableImages);
            } else {
              var t = (now2 - this.begin) / (this.end - this.begin);
              return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t));
            }
          };
          var Transitioning = function Transitioning2(properties2) {
            this._properties = properties2;
            this._values = Object.create(properties2.defaultTransitioningPropertyValues);
          };
          Transitioning.prototype.possiblyEvaluate = function possiblyEvaluate(parameters, canonical, availableImages) {
            var result = new PossiblyEvaluated(this._properties);
            for (var i = 0, list = Object.keys(this._values); i < list.length; i += 1) {
              var property = list[i];
              result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);
            }
            return result;
          };
          Transitioning.prototype.hasTransition = function hasTransition() {
            for (var i = 0, list = Object.keys(this._values); i < list.length; i += 1) {
              var property = list[i];
              if (this._values[property].prior) {
                return true;
              }
            }
            return false;
          };
          var Layout = function Layout2(properties2) {
            this._properties = properties2;
            this._values = Object.create(properties2.defaultPropertyValues);
          };
          Layout.prototype.getValue = function getValue(name3) {
            return clone(this._values[name3].value);
          };
          Layout.prototype.setValue = function setValue(name3, value) {
            this._values[name3] = new PropertyValue(this._values[name3].property, value === null ? void 0 : clone(value));
          };
          Layout.prototype.serialize = function serialize2() {
            var result = {};
            for (var i = 0, list = Object.keys(this._values); i < list.length; i += 1) {
              var property = list[i];
              var value = this.getValue(property);
              if (value !== void 0) {
                result[property] = value;
              }
            }
            return result;
          };
          Layout.prototype.possiblyEvaluate = function possiblyEvaluate(parameters, canonical, availableImages) {
            var result = new PossiblyEvaluated(this._properties);
            for (var i = 0, list = Object.keys(this._values); i < list.length; i += 1) {
              var property = list[i];
              result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);
            }
            return result;
          };
          var PossiblyEvaluatedPropertyValue = function PossiblyEvaluatedPropertyValue2(property, value, parameters) {
            this.property = property;
            this.value = value;
            this.parameters = parameters;
          };
          PossiblyEvaluatedPropertyValue.prototype.isConstant = function isConstant2() {
            return this.value.kind === "constant";
          };
          PossiblyEvaluatedPropertyValue.prototype.constantOr = function constantOr(value) {
            if (this.value.kind === "constant") {
              return this.value.value;
            } else {
              return value;
            }
          };
          PossiblyEvaluatedPropertyValue.prototype.evaluate = function evaluate(feature, featureState, canonical, availableImages) {
            return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages);
          };
          var PossiblyEvaluated = function PossiblyEvaluated2(properties2) {
            this._properties = properties2;
            this._values = Object.create(properties2.defaultPossiblyEvaluatedValues);
          };
          PossiblyEvaluated.prototype.get = function get2(name3) {
            return this._values[name3];
          };
          var DataConstantProperty = function DataConstantProperty2(specification) {
            this.specification = specification;
          };
          DataConstantProperty.prototype.possiblyEvaluate = function possiblyEvaluate(value, parameters) {
            return value.expression.evaluate(parameters);
          };
          DataConstantProperty.prototype.interpolate = function interpolate$1(a, b, t) {
            var interp = interpolate[this.specification.type];
            if (interp) {
              return interp(a, b, t);
            } else {
              return a;
            }
          };
          var DataDrivenProperty = function DataDrivenProperty2(specification, overrides) {
            this.specification = specification;
            this.overrides = overrides;
          };
          DataDrivenProperty.prototype.possiblyEvaluate = function possiblyEvaluate(value, parameters, canonical, availableImages) {
            if (value.expression.kind === "constant" || value.expression.kind === "camera") {
              return new PossiblyEvaluatedPropertyValue(this, {
                kind: "constant",
                value: value.expression.evaluate(parameters, null, {}, canonical, availableImages)
              }, parameters);
            } else {
              return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);
            }
          };
          DataDrivenProperty.prototype.interpolate = function interpolate$2(a, b, t) {
            if (a.value.kind !== "constant" || b.value.kind !== "constant") {
              return a;
            }
            if (a.value.value === void 0 || b.value.value === void 0) {
              return new PossiblyEvaluatedPropertyValue(this, {
                kind: "constant",
                value: void 0
              }, a.parameters);
            }
            var interp = interpolate[this.specification.type];
            if (interp) {
              return new PossiblyEvaluatedPropertyValue(this, {
                kind: "constant",
                value: interp(a.value.value, b.value.value, t)
              }, a.parameters);
            } else {
              return a;
            }
          };
          DataDrivenProperty.prototype.evaluate = function evaluate(value, parameters, feature, featureState, canonical, availableImages) {
            if (value.kind === "constant") {
              return value.value;
            } else {
              return value.evaluate(parameters, feature, featureState, canonical, availableImages);
            }
          };
          var CrossFadedDataDrivenProperty = function(DataDrivenProperty2) {
            function CrossFadedDataDrivenProperty2() {
              DataDrivenProperty2.apply(this, arguments);
            }
            if (DataDrivenProperty2)
              CrossFadedDataDrivenProperty2.__proto__ = DataDrivenProperty2;
            CrossFadedDataDrivenProperty2.prototype = Object.create(DataDrivenProperty2 && DataDrivenProperty2.prototype);
            CrossFadedDataDrivenProperty2.prototype.constructor = CrossFadedDataDrivenProperty2;
            CrossFadedDataDrivenProperty2.prototype.possiblyEvaluate = function possiblyEvaluate(value, parameters, canonical, availableImages) {
              if (value.value === void 0) {
                return new PossiblyEvaluatedPropertyValue(this, {
                  kind: "constant",
                  value: void 0
                }, parameters);
              } else if (value.expression.kind === "constant") {
                var evaluatedValue = value.expression.evaluate(parameters, null, {}, canonical, availableImages);
                var isImageExpression = value.property.specification.type === "resolvedImage";
                var constantValue = isImageExpression && typeof evaluatedValue !== "string" ? evaluatedValue.name : evaluatedValue;
                var constant = this._calculate(constantValue, constantValue, constantValue, parameters);
                return new PossiblyEvaluatedPropertyValue(this, {
                  kind: "constant",
                  value: constant
                }, parameters);
              } else if (value.expression.kind === "camera") {
                var cameraVal = this._calculate(value.expression.evaluate({ zoom: parameters.zoom - 1 }), value.expression.evaluate({ zoom: parameters.zoom }), value.expression.evaluate({ zoom: parameters.zoom + 1 }), parameters);
                return new PossiblyEvaluatedPropertyValue(this, {
                  kind: "constant",
                  value: cameraVal
                }, parameters);
              } else {
                return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);
              }
            };
            CrossFadedDataDrivenProperty2.prototype.evaluate = function evaluate(value, globals, feature, featureState, canonical, availableImages) {
              if (value.kind === "source") {
                var constant = value.evaluate(globals, feature, featureState, canonical, availableImages);
                return this._calculate(constant, constant, constant, globals);
              } else if (value.kind === "composite") {
                return this._calculate(value.evaluate({ zoom: Math.floor(globals.zoom) - 1 }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) }, feature, featureState), value.evaluate({ zoom: Math.floor(globals.zoom) + 1 }, feature, featureState), globals);
              } else {
                return value.value;
              }
            };
            CrossFadedDataDrivenProperty2.prototype._calculate = function _calculate(min, mid, max, parameters) {
              var z = parameters.zoom;
              return z > parameters.zoomHistory.lastIntegerZoom ? {
                from: min,
                to: mid
              } : {
                from: max,
                to: mid
              };
            };
            CrossFadedDataDrivenProperty2.prototype.interpolate = function interpolate2(a) {
              return a;
            };
            return CrossFadedDataDrivenProperty2;
          }(DataDrivenProperty);
          var CrossFadedProperty = function CrossFadedProperty2(specification) {
            this.specification = specification;
          };
          CrossFadedProperty.prototype.possiblyEvaluate = function possiblyEvaluate(value, parameters, canonical, availableImages) {
            if (value.value === void 0) {
              return void 0;
            } else if (value.expression.kind === "constant") {
              var constant = value.expression.evaluate(parameters, null, {}, canonical, availableImages);
              return this._calculate(constant, constant, constant, parameters);
            } else {
              return this._calculate(value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)), value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1), parameters)), parameters);
            }
          };
          CrossFadedProperty.prototype._calculate = function _calculate(min, mid, max, parameters) {
            var z = parameters.zoom;
            return z > parameters.zoomHistory.lastIntegerZoom ? {
              from: min,
              to: mid
            } : {
              from: max,
              to: mid
            };
          };
          CrossFadedProperty.prototype.interpolate = function interpolate2(a) {
            return a;
          };
          var ColorRampProperty = function ColorRampProperty2(specification) {
            this.specification = specification;
          };
          ColorRampProperty.prototype.possiblyEvaluate = function possiblyEvaluate(value, parameters, canonical, availableImages) {
            return !!value.expression.evaluate(parameters, null, {}, canonical, availableImages);
          };
          ColorRampProperty.prototype.interpolate = function interpolate2() {
            return false;
          };
          var Properties = function Properties2(properties2) {
            this.properties = properties2;
            this.defaultPropertyValues = {};
            this.defaultTransitionablePropertyValues = {};
            this.defaultTransitioningPropertyValues = {};
            this.defaultPossiblyEvaluatedValues = {};
            this.overridableProperties = [];
            for (var property in properties2) {
              var prop = properties2[property];
              if (prop.specification.overridable) {
                this.overridableProperties.push(property);
              }
              var defaultPropertyValue = this.defaultPropertyValues[property] = new PropertyValue(prop, void 0);
              var defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] = new TransitionablePropertyValue(prop);
              this.defaultTransitioningPropertyValues[property] = defaultTransitionablePropertyValue.untransitioned();
              this.defaultPossiblyEvaluatedValues[property] = defaultPropertyValue.possiblyEvaluate({});
            }
          };
          register("DataDrivenProperty", DataDrivenProperty);
          register("DataConstantProperty", DataConstantProperty);
          register("CrossFadedDataDrivenProperty", CrossFadedDataDrivenProperty);
          register("CrossFadedProperty", CrossFadedProperty);
          register("ColorRampProperty", ColorRampProperty);
          var TRANSITION_SUFFIX = "-transition";
          var StyleLayer = function(Evented2) {
            function StyleLayer2(layer2, properties2) {
              Evented2.call(this);
              this.id = layer2.id;
              this.type = layer2.type;
              this._featureFilter = {
                filter: function() {
                  return true;
                },
                needGeometry: false
              };
              if (layer2.type === "custom") {
                return;
              }
              layer2 = layer2;
              this.metadata = layer2.metadata;
              this.minzoom = layer2.minzoom;
              this.maxzoom = layer2.maxzoom;
              if (layer2.type !== "background") {
                this.source = layer2.source;
                this.sourceLayer = layer2["source-layer"];
                this.filter = layer2.filter;
              }
              if (properties2.layout) {
                this._unevaluatedLayout = new Layout(properties2.layout);
              }
              if (properties2.paint) {
                this._transitionablePaint = new Transitionable(properties2.paint);
                for (var property in layer2.paint) {
                  this.setPaintProperty(property, layer2.paint[property], { validate: false });
                }
                for (var property$1 in layer2.layout) {
                  this.setLayoutProperty(property$1, layer2.layout[property$1], { validate: false });
                }
                this._transitioningPaint = this._transitionablePaint.untransitioned();
                this.paint = new PossiblyEvaluated(properties2.paint);
              }
            }
            if (Evented2)
              StyleLayer2.__proto__ = Evented2;
            StyleLayer2.prototype = Object.create(Evented2 && Evented2.prototype);
            StyleLayer2.prototype.constructor = StyleLayer2;
            StyleLayer2.prototype.getCrossfadeParameters = function getCrossfadeParameters() {
              return this._crossfadeParameters;
            };
            StyleLayer2.prototype.getLayoutProperty = function getLayoutProperty(name3) {
              if (name3 === "visibility") {
                return this.visibility;
              }
              return this._unevaluatedLayout.getValue(name3);
            };
            StyleLayer2.prototype.setLayoutProperty = function setLayoutProperty(name3, value, options) {
              if (options === void 0)
                options = {};
              if (value !== null && value !== void 0) {
                var key = "layers." + this.id + ".layout." + name3;
                if (this._validate(validateLayoutProperty$1, key, name3, value, options)) {
                  return;
                }
              }
              if (name3 === "visibility") {
                this.visibility = value;
                return;
              }
              this._unevaluatedLayout.setValue(name3, value);
            };
            StyleLayer2.prototype.getPaintProperty = function getPaintProperty(name3) {
              if (endsWith(name3, TRANSITION_SUFFIX)) {
                return this._transitionablePaint.getTransition(name3.slice(0, -TRANSITION_SUFFIX.length));
              } else {
                return this._transitionablePaint.getValue(name3);
              }
            };
            StyleLayer2.prototype.setPaintProperty = function setPaintProperty(name3, value, options) {
              if (options === void 0)
                options = {};
              if (value !== null && value !== void 0) {
                var key = "layers." + this.id + ".paint." + name3;
                if (this._validate(validatePaintProperty$1, key, name3, value, options)) {
                  return false;
                }
              }
              if (endsWith(name3, TRANSITION_SUFFIX)) {
                this._transitionablePaint.setTransition(name3.slice(0, -TRANSITION_SUFFIX.length), value || void 0);
                return false;
              } else {
                var transitionable = this._transitionablePaint._values[name3];
                var isCrossFadedProperty = transitionable.property.specification["property-type"] === "cross-faded-data-driven";
                var wasDataDriven = transitionable.value.isDataDriven();
                var oldValue = transitionable.value;
                this._transitionablePaint.setValue(name3, value);
                this._handleSpecialPaintPropertyUpdate(name3);
                var newValue = this._transitionablePaint._values[name3].value;
                var isDataDriven = newValue.isDataDriven();
                return isDataDriven || wasDataDriven || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name3, oldValue, newValue);
              }
            };
            StyleLayer2.prototype._handleSpecialPaintPropertyUpdate = function _handleSpecialPaintPropertyUpdate(_) {
            };
            StyleLayer2.prototype._handleOverridablePaintPropertyUpdate = function _handleOverridablePaintPropertyUpdate(name3, oldValue, newValue) {
              return false;
            };
            StyleLayer2.prototype.isHidden = function isHidden(zoom) {
              if (this.minzoom && zoom < this.minzoom) {
                return true;
              }
              if (this.maxzoom && zoom >= this.maxzoom) {
                return true;
              }
              return this.visibility === "none";
            };
            StyleLayer2.prototype.updateTransitions = function updateTransitions(parameters) {
              this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint);
            };
            StyleLayer2.prototype.hasTransition = function hasTransition() {
              return this._transitioningPaint.hasTransition();
            };
            StyleLayer2.prototype.recalculate = function recalculate(parameters, availableImages) {
              if (parameters.getCrossfadeParameters) {
                this._crossfadeParameters = parameters.getCrossfadeParameters();
              }
              if (this._unevaluatedLayout) {
                this.layout = this._unevaluatedLayout.possiblyEvaluate(parameters, void 0, availableImages);
              }
              this.paint = this._transitioningPaint.possiblyEvaluate(parameters, void 0, availableImages);
            };
            StyleLayer2.prototype.serialize = function serialize2() {
              var output = {
                "id": this.id,
                "type": this.type,
                "source": this.source,
                "source-layer": this.sourceLayer,
                "metadata": this.metadata,
                "minzoom": this.minzoom,
                "maxzoom": this.maxzoom,
                "filter": this.filter,
                "layout": this._unevaluatedLayout && this._unevaluatedLayout.serialize(),
                "paint": this._transitionablePaint && this._transitionablePaint.serialize()
              };
              if (this.visibility) {
                output.layout = output.layout || {};
                output.layout.visibility = this.visibility;
              }
              return filterObject(output, function(value, key) {
                return value !== void 0 && !(key === "layout" && !Object.keys(value).length) && !(key === "paint" && !Object.keys(value).length);
              });
            };
            StyleLayer2.prototype._validate = function _validate(validate2, key, name3, value, options) {
              if (options === void 0)
                options = {};
              if (options && options.validate === false) {
                return false;
              }
              return emitValidationErrors(this, validate2.call(validateStyle, {
                key,
                layerType: this.type,
                objectKey: name3,
                value,
                styleSpec: spec,
                style: {
                  glyphs: true,
                  sprite: true
                }
              }));
            };
            StyleLayer2.prototype.is3D = function is3D() {
              return false;
            };
            StyleLayer2.prototype.isTileClipped = function isTileClipped() {
              return false;
            };
            StyleLayer2.prototype.hasOffscreenPass = function hasOffscreenPass() {
              return false;
            };
            StyleLayer2.prototype.resize = function resize() {
            };
            StyleLayer2.prototype.isStateDependent = function isStateDependent() {
              for (var property in this.paint._values) {
                var value = this.paint.get(property);
                if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {
                  continue;
                }
                if ((value.value.kind === "source" || value.value.kind === "composite") && value.value.isStateDependent) {
                  return true;
                }
              }
              return false;
            };
            return StyleLayer2;
          }(Evented);
          var viewTypes = {
            "Int8": Int8Array,
            "Uint8": Uint8Array,
            "Int16": Int16Array,
            "Uint16": Uint16Array,
            "Int32": Int32Array,
            "Uint32": Uint32Array,
            "Float32": Float32Array
          };
          var Struct = function Struct2(structArray, index) {
            this._structArray = structArray;
            this._pos1 = index * this.size;
            this._pos2 = this._pos1 / 2;
            this._pos4 = this._pos1 / 4;
            this._pos8 = this._pos1 / 8;
          };
          var DEFAULT_CAPACITY = 128;
          var RESIZE_MULTIPLIER = 5;
          var StructArray = function StructArray2() {
            this.isTransferred = false;
            this.capacity = -1;
            this.resize(0);
          };
          StructArray.serialize = function serialize2(array2, transferables) {
            array2._trim();
            if (transferables) {
              array2.isTransferred = true;
              transferables.push(array2.arrayBuffer);
            }
            return {
              length: array2.length,
              arrayBuffer: array2.arrayBuffer
            };
          };
          StructArray.deserialize = function deserialize2(input) {
            var structArray = Object.create(this.prototype);
            structArray.arrayBuffer = input.arrayBuffer;
            structArray.length = input.length;
            structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement;
            structArray._refreshViews();
            return structArray;
          };
          StructArray.prototype._trim = function _trim() {
            if (this.length !== this.capacity) {
              this.capacity = this.length;
              this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement);
              this._refreshViews();
            }
          };
          StructArray.prototype.clear = function clear() {
            this.length = 0;
          };
          StructArray.prototype.resize = function resize(n) {
            this.reserve(n);
            this.length = n;
          };
          StructArray.prototype.reserve = function reserve(n) {
            if (n > this.capacity) {
              this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY);
              this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);
              var oldUint8Array = this.uint8;
              this._refreshViews();
              if (oldUint8Array) {
                this.uint8.set(oldUint8Array);
              }
            }
          };
          StructArray.prototype._refreshViews = function _refreshViews() {
            throw new Error("_refreshViews() must be implemented by each concrete StructArray layout");
          };
          function createLayout(members2, alignment) {
            if (alignment === void 0)
              alignment = 1;
            var offset = 0;
            var maxSize = 0;
            var layoutMembers = members2.map(function(member) {
              var typeSize = sizeOf(member.type);
              var memberOffset = offset = align(offset, Math.max(alignment, typeSize));
              var components = member.components || 1;
              maxSize = Math.max(maxSize, typeSize);
              offset += typeSize * components;
              return {
                name: member.name,
                type: member.type,
                components,
                offset: memberOffset
              };
            });
            var size = align(offset, Math.max(maxSize, alignment));
            return {
              members: layoutMembers,
              size,
              alignment
            };
          }
          function sizeOf(type) {
            return viewTypes[type].BYTES_PER_ELEMENT;
          }
          function align(offset, size) {
            return Math.ceil(offset / size) * size;
          }
          var StructArrayLayout2i4 = function(StructArray2) {
            function StructArrayLayout2i42() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2i42.__proto__ = StructArray2;
            StructArrayLayout2i42.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2i42.prototype.constructor = StructArrayLayout2i42;
            StructArrayLayout2i42.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
            };
            StructArrayLayout2i42.prototype.emplaceBack = function emplaceBack(v0, v1) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1);
            };
            StructArrayLayout2i42.prototype.emplace = function emplace(i, v0, v1) {
              var o2 = i * 2;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              return i;
            };
            return StructArrayLayout2i42;
          }(StructArray);
          StructArrayLayout2i4.prototype.bytesPerElement = 4;
          register("StructArrayLayout2i4", StructArrayLayout2i4);
          var StructArrayLayout4i8 = function(StructArray2) {
            function StructArrayLayout4i82() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout4i82.__proto__ = StructArray2;
            StructArrayLayout4i82.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout4i82.prototype.constructor = StructArrayLayout4i82;
            StructArrayLayout4i82.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
            };
            StructArrayLayout4i82.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3);
            };
            StructArrayLayout4i82.prototype.emplace = function emplace(i, v0, v1, v2, v3) {
              var o2 = i * 4;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.int16[o2 + 2] = v2;
              this.int16[o2 + 3] = v3;
              return i;
            };
            return StructArrayLayout4i82;
          }(StructArray);
          StructArrayLayout4i8.prototype.bytesPerElement = 8;
          register("StructArrayLayout4i8", StructArrayLayout4i8);
          var StructArrayLayout2i4i12 = function(StructArray2) {
            function StructArrayLayout2i4i122() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2i4i122.__proto__ = StructArray2;
            StructArrayLayout2i4i122.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2i4i122.prototype.constructor = StructArrayLayout2i4i122;
            StructArrayLayout2i4i122.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
            };
            StructArrayLayout2i4i122.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5);
            };
            StructArrayLayout2i4i122.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5) {
              var o2 = i * 6;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.int16[o2 + 2] = v2;
              this.int16[o2 + 3] = v3;
              this.int16[o2 + 4] = v4;
              this.int16[o2 + 5] = v5;
              return i;
            };
            return StructArrayLayout2i4i122;
          }(StructArray);
          StructArrayLayout2i4i12.prototype.bytesPerElement = 12;
          register("StructArrayLayout2i4i12", StructArrayLayout2i4i12);
          var StructArrayLayout2i4ub8 = function(StructArray2) {
            function StructArrayLayout2i4ub82() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2i4ub82.__proto__ = StructArray2;
            StructArrayLayout2i4ub82.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2i4ub82.prototype.constructor = StructArrayLayout2i4ub82;
            StructArrayLayout2i4ub82.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
            };
            StructArrayLayout2i4ub82.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5);
            };
            StructArrayLayout2i4ub82.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5) {
              var o2 = i * 4;
              var o1 = i * 8;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.uint8[o1 + 4] = v2;
              this.uint8[o1 + 5] = v3;
              this.uint8[o1 + 6] = v4;
              this.uint8[o1 + 7] = v5;
              return i;
            };
            return StructArrayLayout2i4ub82;
          }(StructArray);
          StructArrayLayout2i4ub8.prototype.bytesPerElement = 8;
          register("StructArrayLayout2i4ub8", StructArrayLayout2i4ub8);
          var StructArrayLayout2f8 = function(StructArray2) {
            function StructArrayLayout2f82() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2f82.__proto__ = StructArray2;
            StructArrayLayout2f82.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2f82.prototype.constructor = StructArrayLayout2f82;
            StructArrayLayout2f82.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
            };
            StructArrayLayout2f82.prototype.emplaceBack = function emplaceBack(v0, v1) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1);
            };
            StructArrayLayout2f82.prototype.emplace = function emplace(i, v0, v1) {
              var o4 = i * 2;
              this.float32[o4 + 0] = v0;
              this.float32[o4 + 1] = v1;
              return i;
            };
            return StructArrayLayout2f82;
          }(StructArray);
          StructArrayLayout2f8.prototype.bytesPerElement = 8;
          register("StructArrayLayout2f8", StructArrayLayout2f8);
          var StructArrayLayout10ui20 = function(StructArray2) {
            function StructArrayLayout10ui202() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout10ui202.__proto__ = StructArray2;
            StructArrayLayout10ui202.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout10ui202.prototype.constructor = StructArrayLayout10ui202;
            StructArrayLayout10ui202.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
            };
            StructArrayLayout10ui202.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9);
            };
            StructArrayLayout10ui202.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {
              var o2 = i * 10;
              this.uint16[o2 + 0] = v0;
              this.uint16[o2 + 1] = v1;
              this.uint16[o2 + 2] = v2;
              this.uint16[o2 + 3] = v3;
              this.uint16[o2 + 4] = v4;
              this.uint16[o2 + 5] = v5;
              this.uint16[o2 + 6] = v6;
              this.uint16[o2 + 7] = v7;
              this.uint16[o2 + 8] = v8;
              this.uint16[o2 + 9] = v9;
              return i;
            };
            return StructArrayLayout10ui202;
          }(StructArray);
          StructArrayLayout10ui20.prototype.bytesPerElement = 20;
          register("StructArrayLayout10ui20", StructArrayLayout10ui20);
          var StructArrayLayout4i4ui4i24 = function(StructArray2) {
            function StructArrayLayout4i4ui4i242() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout4i4ui4i242.__proto__ = StructArray2;
            StructArrayLayout4i4ui4i242.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout4i4ui4i242.prototype.constructor = StructArrayLayout4i4ui4i242;
            StructArrayLayout4i4ui4i242.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
            };
            StructArrayLayout4i4ui4i242.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11);
            };
            StructArrayLayout4i4ui4i242.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) {
              var o2 = i * 12;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.int16[o2 + 2] = v2;
              this.int16[o2 + 3] = v3;
              this.uint16[o2 + 4] = v4;
              this.uint16[o2 + 5] = v5;
              this.uint16[o2 + 6] = v6;
              this.uint16[o2 + 7] = v7;
              this.int16[o2 + 8] = v8;
              this.int16[o2 + 9] = v9;
              this.int16[o2 + 10] = v10;
              this.int16[o2 + 11] = v11;
              return i;
            };
            return StructArrayLayout4i4ui4i242;
          }(StructArray);
          StructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24;
          register("StructArrayLayout4i4ui4i24", StructArrayLayout4i4ui4i24);
          var StructArrayLayout3f12 = function(StructArray2) {
            function StructArrayLayout3f122() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout3f122.__proto__ = StructArray2;
            StructArrayLayout3f122.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout3f122.prototype.constructor = StructArrayLayout3f122;
            StructArrayLayout3f122.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
            };
            StructArrayLayout3f122.prototype.emplaceBack = function emplaceBack(v0, v1, v2) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2);
            };
            StructArrayLayout3f122.prototype.emplace = function emplace(i, v0, v1, v2) {
              var o4 = i * 3;
              this.float32[o4 + 0] = v0;
              this.float32[o4 + 1] = v1;
              this.float32[o4 + 2] = v2;
              return i;
            };
            return StructArrayLayout3f122;
          }(StructArray);
          StructArrayLayout3f12.prototype.bytesPerElement = 12;
          register("StructArrayLayout3f12", StructArrayLayout3f12);
          var StructArrayLayout1ul4 = function(StructArray2) {
            function StructArrayLayout1ul42() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout1ul42.__proto__ = StructArray2;
            StructArrayLayout1ul42.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout1ul42.prototype.constructor = StructArrayLayout1ul42;
            StructArrayLayout1ul42.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.uint32 = new Uint32Array(this.arrayBuffer);
            };
            StructArrayLayout1ul42.prototype.emplaceBack = function emplaceBack(v0) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0);
            };
            StructArrayLayout1ul42.prototype.emplace = function emplace(i, v0) {
              var o4 = i * 1;
              this.uint32[o4 + 0] = v0;
              return i;
            };
            return StructArrayLayout1ul42;
          }(StructArray);
          StructArrayLayout1ul4.prototype.bytesPerElement = 4;
          register("StructArrayLayout1ul4", StructArrayLayout1ul4);
          var StructArrayLayout6i1ul2ui20 = function(StructArray2) {
            function StructArrayLayout6i1ul2ui202() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout6i1ul2ui202.__proto__ = StructArray2;
            StructArrayLayout6i1ul2ui202.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout6i1ul2ui202.prototype.constructor = StructArrayLayout6i1ul2ui202;
            StructArrayLayout6i1ul2ui202.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
              this.uint32 = new Uint32Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
            };
            StructArrayLayout6i1ul2ui202.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8);
            };
            StructArrayLayout6i1ul2ui202.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8) {
              var o2 = i * 10;
              var o4 = i * 5;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.int16[o2 + 2] = v2;
              this.int16[o2 + 3] = v3;
              this.int16[o2 + 4] = v4;
              this.int16[o2 + 5] = v5;
              this.uint32[o4 + 3] = v6;
              this.uint16[o2 + 8] = v7;
              this.uint16[o2 + 9] = v8;
              return i;
            };
            return StructArrayLayout6i1ul2ui202;
          }(StructArray);
          StructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20;
          register("StructArrayLayout6i1ul2ui20", StructArrayLayout6i1ul2ui20);
          var StructArrayLayout2i2i2i12 = function(StructArray2) {
            function StructArrayLayout2i2i2i122() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2i2i2i122.__proto__ = StructArray2;
            StructArrayLayout2i2i2i122.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2i2i2i122.prototype.constructor = StructArrayLayout2i2i2i122;
            StructArrayLayout2i2i2i122.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
            };
            StructArrayLayout2i2i2i122.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5);
            };
            StructArrayLayout2i2i2i122.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5) {
              var o2 = i * 6;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.int16[o2 + 2] = v2;
              this.int16[o2 + 3] = v3;
              this.int16[o2 + 4] = v4;
              this.int16[o2 + 5] = v5;
              return i;
            };
            return StructArrayLayout2i2i2i122;
          }(StructArray);
          StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12;
          register("StructArrayLayout2i2i2i12", StructArrayLayout2i2i2i12);
          var StructArrayLayout2f1f2i16 = function(StructArray2) {
            function StructArrayLayout2f1f2i162() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2f1f2i162.__proto__ = StructArray2;
            StructArrayLayout2f1f2i162.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2f1f2i162.prototype.constructor = StructArrayLayout2f1f2i162;
            StructArrayLayout2f1f2i162.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
            };
            StructArrayLayout2f1f2i162.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4);
            };
            StructArrayLayout2f1f2i162.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4) {
              var o4 = i * 4;
              var o2 = i * 8;
              this.float32[o4 + 0] = v0;
              this.float32[o4 + 1] = v1;
              this.float32[o4 + 2] = v2;
              this.int16[o2 + 6] = v3;
              this.int16[o2 + 7] = v4;
              return i;
            };
            return StructArrayLayout2f1f2i162;
          }(StructArray);
          StructArrayLayout2f1f2i16.prototype.bytesPerElement = 16;
          register("StructArrayLayout2f1f2i16", StructArrayLayout2f1f2i16);
          var StructArrayLayout2ub2f12 = function(StructArray2) {
            function StructArrayLayout2ub2f122() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2ub2f122.__proto__ = StructArray2;
            StructArrayLayout2ub2f122.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2ub2f122.prototype.constructor = StructArrayLayout2ub2f122;
            StructArrayLayout2ub2f122.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
            };
            StructArrayLayout2ub2f122.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3);
            };
            StructArrayLayout2ub2f122.prototype.emplace = function emplace(i, v0, v1, v2, v3) {
              var o1 = i * 12;
              var o4 = i * 3;
              this.uint8[o1 + 0] = v0;
              this.uint8[o1 + 1] = v1;
              this.float32[o4 + 1] = v2;
              this.float32[o4 + 2] = v3;
              return i;
            };
            return StructArrayLayout2ub2f122;
          }(StructArray);
          StructArrayLayout2ub2f12.prototype.bytesPerElement = 12;
          register("StructArrayLayout2ub2f12", StructArrayLayout2ub2f12);
          var StructArrayLayout3ui6 = function(StructArray2) {
            function StructArrayLayout3ui62() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout3ui62.__proto__ = StructArray2;
            StructArrayLayout3ui62.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout3ui62.prototype.constructor = StructArrayLayout3ui62;
            StructArrayLayout3ui62.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
            };
            StructArrayLayout3ui62.prototype.emplaceBack = function emplaceBack(v0, v1, v2) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2);
            };
            StructArrayLayout3ui62.prototype.emplace = function emplace(i, v0, v1, v2) {
              var o2 = i * 3;
              this.uint16[o2 + 0] = v0;
              this.uint16[o2 + 1] = v1;
              this.uint16[o2 + 2] = v2;
              return i;
            };
            return StructArrayLayout3ui62;
          }(StructArray);
          StructArrayLayout3ui6.prototype.bytesPerElement = 6;
          register("StructArrayLayout3ui6", StructArrayLayout3ui6);
          var StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 = function(StructArray2) {
            function StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.__proto__ = StructArray2;
            StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.prototype.constructor = StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482;
            StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
              this.uint32 = new Uint32Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
            };
            StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16);
            };
            StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) {
              var o2 = i * 24;
              var o4 = i * 12;
              var o1 = i * 48;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.uint16[o2 + 2] = v2;
              this.uint16[o2 + 3] = v3;
              this.uint32[o4 + 2] = v4;
              this.uint32[o4 + 3] = v5;
              this.uint32[o4 + 4] = v6;
              this.uint16[o2 + 10] = v7;
              this.uint16[o2 + 11] = v8;
              this.uint16[o2 + 12] = v9;
              this.float32[o4 + 7] = v10;
              this.float32[o4 + 8] = v11;
              this.uint8[o1 + 36] = v12;
              this.uint8[o1 + 37] = v13;
              this.uint8[o1 + 38] = v14;
              this.uint32[o4 + 10] = v15;
              this.int16[o2 + 22] = v16;
              return i;
            };
            return StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482;
          }(StructArray);
          StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement = 48;
          register("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48", StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48);
          var StructArrayLayout8i15ui1ul4f68 = function(StructArray2) {
            function StructArrayLayout8i15ui1ul4f682() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout8i15ui1ul4f682.__proto__ = StructArray2;
            StructArrayLayout8i15ui1ul4f682.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout8i15ui1ul4f682.prototype.constructor = StructArrayLayout8i15ui1ul4f682;
            StructArrayLayout8i15ui1ul4f682.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
              this.uint32 = new Uint32Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
            };
            StructArrayLayout8i15ui1ul4f682.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27);
            };
            StructArrayLayout8i15ui1ul4f682.prototype.emplace = function emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) {
              var o2 = i * 34;
              var o4 = i * 17;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.int16[o2 + 2] = v2;
              this.int16[o2 + 3] = v3;
              this.int16[o2 + 4] = v4;
              this.int16[o2 + 5] = v5;
              this.int16[o2 + 6] = v6;
              this.int16[o2 + 7] = v7;
              this.uint16[o2 + 8] = v8;
              this.uint16[o2 + 9] = v9;
              this.uint16[o2 + 10] = v10;
              this.uint16[o2 + 11] = v11;
              this.uint16[o2 + 12] = v12;
              this.uint16[o2 + 13] = v13;
              this.uint16[o2 + 14] = v14;
              this.uint16[o2 + 15] = v15;
              this.uint16[o2 + 16] = v16;
              this.uint16[o2 + 17] = v17;
              this.uint16[o2 + 18] = v18;
              this.uint16[o2 + 19] = v19;
              this.uint16[o2 + 20] = v20;
              this.uint16[o2 + 21] = v21;
              this.uint16[o2 + 22] = v22;
              this.uint32[o4 + 12] = v23;
              this.float32[o4 + 13] = v24;
              this.float32[o4 + 14] = v25;
              this.float32[o4 + 15] = v26;
              this.float32[o4 + 16] = v27;
              return i;
            };
            return StructArrayLayout8i15ui1ul4f682;
          }(StructArray);
          StructArrayLayout8i15ui1ul4f68.prototype.bytesPerElement = 68;
          register("StructArrayLayout8i15ui1ul4f68", StructArrayLayout8i15ui1ul4f68);
          var StructArrayLayout1f4 = function(StructArray2) {
            function StructArrayLayout1f42() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout1f42.__proto__ = StructArray2;
            StructArrayLayout1f42.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout1f42.prototype.constructor = StructArrayLayout1f42;
            StructArrayLayout1f42.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
            };
            StructArrayLayout1f42.prototype.emplaceBack = function emplaceBack(v0) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0);
            };
            StructArrayLayout1f42.prototype.emplace = function emplace(i, v0) {
              var o4 = i * 1;
              this.float32[o4 + 0] = v0;
              return i;
            };
            return StructArrayLayout1f42;
          }(StructArray);
          StructArrayLayout1f4.prototype.bytesPerElement = 4;
          register("StructArrayLayout1f4", StructArrayLayout1f4);
          var StructArrayLayout3i6 = function(StructArray2) {
            function StructArrayLayout3i62() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout3i62.__proto__ = StructArray2;
            StructArrayLayout3i62.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout3i62.prototype.constructor = StructArrayLayout3i62;
            StructArrayLayout3i62.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.int16 = new Int16Array(this.arrayBuffer);
            };
            StructArrayLayout3i62.prototype.emplaceBack = function emplaceBack(v0, v1, v2) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2);
            };
            StructArrayLayout3i62.prototype.emplace = function emplace(i, v0, v1, v2) {
              var o2 = i * 3;
              this.int16[o2 + 0] = v0;
              this.int16[o2 + 1] = v1;
              this.int16[o2 + 2] = v2;
              return i;
            };
            return StructArrayLayout3i62;
          }(StructArray);
          StructArrayLayout3i6.prototype.bytesPerElement = 6;
          register("StructArrayLayout3i6", StructArrayLayout3i6);
          var StructArrayLayout1ul2ui8 = function(StructArray2) {
            function StructArrayLayout1ul2ui82() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout1ul2ui82.__proto__ = StructArray2;
            StructArrayLayout1ul2ui82.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout1ul2ui82.prototype.constructor = StructArrayLayout1ul2ui82;
            StructArrayLayout1ul2ui82.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.uint32 = new Uint32Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
            };
            StructArrayLayout1ul2ui82.prototype.emplaceBack = function emplaceBack(v0, v1, v2) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2);
            };
            StructArrayLayout1ul2ui82.prototype.emplace = function emplace(i, v0, v1, v2) {
              var o4 = i * 2;
              var o2 = i * 4;
              this.uint32[o4 + 0] = v0;
              this.uint16[o2 + 2] = v1;
              this.uint16[o2 + 3] = v2;
              return i;
            };
            return StructArrayLayout1ul2ui82;
          }(StructArray);
          StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8;
          register("StructArrayLayout1ul2ui8", StructArrayLayout1ul2ui8);
          var StructArrayLayout2ui4 = function(StructArray2) {
            function StructArrayLayout2ui42() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout2ui42.__proto__ = StructArray2;
            StructArrayLayout2ui42.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout2ui42.prototype.constructor = StructArrayLayout2ui42;
            StructArrayLayout2ui42.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
            };
            StructArrayLayout2ui42.prototype.emplaceBack = function emplaceBack(v0, v1) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1);
            };
            StructArrayLayout2ui42.prototype.emplace = function emplace(i, v0, v1) {
              var o2 = i * 2;
              this.uint16[o2 + 0] = v0;
              this.uint16[o2 + 1] = v1;
              return i;
            };
            return StructArrayLayout2ui42;
          }(StructArray);
          StructArrayLayout2ui4.prototype.bytesPerElement = 4;
          register("StructArrayLayout2ui4", StructArrayLayout2ui4);
          var StructArrayLayout1ui2 = function(StructArray2) {
            function StructArrayLayout1ui22() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout1ui22.__proto__ = StructArray2;
            StructArrayLayout1ui22.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout1ui22.prototype.constructor = StructArrayLayout1ui22;
            StructArrayLayout1ui22.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.uint16 = new Uint16Array(this.arrayBuffer);
            };
            StructArrayLayout1ui22.prototype.emplaceBack = function emplaceBack(v0) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0);
            };
            StructArrayLayout1ui22.prototype.emplace = function emplace(i, v0) {
              var o2 = i * 1;
              this.uint16[o2 + 0] = v0;
              return i;
            };
            return StructArrayLayout1ui22;
          }(StructArray);
          StructArrayLayout1ui2.prototype.bytesPerElement = 2;
          register("StructArrayLayout1ui2", StructArrayLayout1ui2);
          var StructArrayLayout4f16 = function(StructArray2) {
            function StructArrayLayout4f162() {
              StructArray2.apply(this, arguments);
            }
            if (StructArray2)
              StructArrayLayout4f162.__proto__ = StructArray2;
            StructArrayLayout4f162.prototype = Object.create(StructArray2 && StructArray2.prototype);
            StructArrayLayout4f162.prototype.constructor = StructArrayLayout4f162;
            StructArrayLayout4f162.prototype._refreshViews = function _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer);
              this.float32 = new Float32Array(this.arrayBuffer);
            };
            StructArrayLayout4f162.prototype.emplaceBack = function emplaceBack(v0, v1, v2, v3) {
              var i = this.length;
              this.resize(i + 1);
              return this.emplace(i, v0, v1, v2, v3);
            };
            StructArrayLayout4f162.prototype.emplace = function emplace(i, v0, v1, v2, v3) {
              var o4 = i * 4;
              this.float32[o4 + 0] = v0;
              this.float32[o4 + 1] = v1;
              this.float32[o4 + 2] = v2;
              this.float32[o4 + 3] = v3;
              return i;
            };
            return StructArrayLayout4f162;
          }(StructArray);
          StructArrayLayout4f16.prototype.bytesPerElement = 16;
          register("StructArrayLayout4f16", StructArrayLayout4f16);
          var CollisionBoxStruct = function(Struct2) {
            function CollisionBoxStruct2() {
              Struct2.apply(this, arguments);
            }
            if (Struct2)
              CollisionBoxStruct2.__proto__ = Struct2;
            CollisionBoxStruct2.prototype = Object.create(Struct2 && Struct2.prototype);
            CollisionBoxStruct2.prototype.constructor = CollisionBoxStruct2;
            var prototypeAccessors2 = {
              anchorPointX: { configurable: true },
              anchorPointY: { configurable: true },
              x1: { configurable: true },
              y1: { configurable: true },
              x2: { configurable: true },
              y2: { configurable: true },
              featureIndex: { configurable: true },
              sourceLayerIndex: { configurable: true },
              bucketIndex: { configurable: true },
              anchorPoint: { configurable: true }
            };
            prototypeAccessors2.anchorPointX.get = function() {
              return this._structArray.int16[this._pos2 + 0];
            };
            prototypeAccessors2.anchorPointY.get = function() {
              return this._structArray.int16[this._pos2 + 1];
            };
            prototypeAccessors2.x1.get = function() {
              return this._structArray.int16[this._pos2 + 2];
            };
            prototypeAccessors2.y1.get = function() {
              return this._structArray.int16[this._pos2 + 3];
            };
            prototypeAccessors2.x2.get = function() {
              return this._structArray.int16[this._pos2 + 4];
            };
            prototypeAccessors2.y2.get = function() {
              return this._structArray.int16[this._pos2 + 5];
            };
            prototypeAccessors2.featureIndex.get = function() {
              return this._structArray.uint32[this._pos4 + 3];
            };
            prototypeAccessors2.sourceLayerIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 8];
            };
            prototypeAccessors2.bucketIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 9];
            };
            prototypeAccessors2.anchorPoint.get = function() {
              return new pointGeometry(this.anchorPointX, this.anchorPointY);
            };
            Object.defineProperties(CollisionBoxStruct2.prototype, prototypeAccessors2);
            return CollisionBoxStruct2;
          }(Struct);
          CollisionBoxStruct.prototype.size = 20;
          var CollisionBoxArray = function(StructArrayLayout6i1ul2ui202) {
            function CollisionBoxArray2() {
              StructArrayLayout6i1ul2ui202.apply(this, arguments);
            }
            if (StructArrayLayout6i1ul2ui202)
              CollisionBoxArray2.__proto__ = StructArrayLayout6i1ul2ui202;
            CollisionBoxArray2.prototype = Object.create(StructArrayLayout6i1ul2ui202 && StructArrayLayout6i1ul2ui202.prototype);
            CollisionBoxArray2.prototype.constructor = CollisionBoxArray2;
            CollisionBoxArray2.prototype.get = function get2(index) {
              return new CollisionBoxStruct(this, index);
            };
            return CollisionBoxArray2;
          }(StructArrayLayout6i1ul2ui20);
          register("CollisionBoxArray", CollisionBoxArray);
          var PlacedSymbolStruct = function(Struct2) {
            function PlacedSymbolStruct2() {
              Struct2.apply(this, arguments);
            }
            if (Struct2)
              PlacedSymbolStruct2.__proto__ = Struct2;
            PlacedSymbolStruct2.prototype = Object.create(Struct2 && Struct2.prototype);
            PlacedSymbolStruct2.prototype.constructor = PlacedSymbolStruct2;
            var prototypeAccessors$12 = {
              anchorX: { configurable: true },
              anchorY: { configurable: true },
              glyphStartIndex: { configurable: true },
              numGlyphs: { configurable: true },
              vertexStartIndex: { configurable: true },
              lineStartIndex: { configurable: true },
              lineLength: { configurable: true },
              segment: { configurable: true },
              lowerSize: { configurable: true },
              upperSize: { configurable: true },
              lineOffsetX: { configurable: true },
              lineOffsetY: { configurable: true },
              writingMode: { configurable: true },
              placedOrientation: { configurable: true },
              hidden: { configurable: true },
              crossTileID: { configurable: true },
              associatedIconIndex: { configurable: true }
            };
            prototypeAccessors$12.anchorX.get = function() {
              return this._structArray.int16[this._pos2 + 0];
            };
            prototypeAccessors$12.anchorY.get = function() {
              return this._structArray.int16[this._pos2 + 1];
            };
            prototypeAccessors$12.glyphStartIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 2];
            };
            prototypeAccessors$12.numGlyphs.get = function() {
              return this._structArray.uint16[this._pos2 + 3];
            };
            prototypeAccessors$12.vertexStartIndex.get = function() {
              return this._structArray.uint32[this._pos4 + 2];
            };
            prototypeAccessors$12.lineStartIndex.get = function() {
              return this._structArray.uint32[this._pos4 + 3];
            };
            prototypeAccessors$12.lineLength.get = function() {
              return this._structArray.uint32[this._pos4 + 4];
            };
            prototypeAccessors$12.segment.get = function() {
              return this._structArray.uint16[this._pos2 + 10];
            };
            prototypeAccessors$12.lowerSize.get = function() {
              return this._structArray.uint16[this._pos2 + 11];
            };
            prototypeAccessors$12.upperSize.get = function() {
              return this._structArray.uint16[this._pos2 + 12];
            };
            prototypeAccessors$12.lineOffsetX.get = function() {
              return this._structArray.float32[this._pos4 + 7];
            };
            prototypeAccessors$12.lineOffsetY.get = function() {
              return this._structArray.float32[this._pos4 + 8];
            };
            prototypeAccessors$12.writingMode.get = function() {
              return this._structArray.uint8[this._pos1 + 36];
            };
            prototypeAccessors$12.placedOrientation.get = function() {
              return this._structArray.uint8[this._pos1 + 37];
            };
            prototypeAccessors$12.placedOrientation.set = function(x) {
              this._structArray.uint8[this._pos1 + 37] = x;
            };
            prototypeAccessors$12.hidden.get = function() {
              return this._structArray.uint8[this._pos1 + 38];
            };
            prototypeAccessors$12.hidden.set = function(x) {
              this._structArray.uint8[this._pos1 + 38] = x;
            };
            prototypeAccessors$12.crossTileID.get = function() {
              return this._structArray.uint32[this._pos4 + 10];
            };
            prototypeAccessors$12.crossTileID.set = function(x) {
              this._structArray.uint32[this._pos4 + 10] = x;
            };
            prototypeAccessors$12.associatedIconIndex.get = function() {
              return this._structArray.int16[this._pos2 + 22];
            };
            Object.defineProperties(PlacedSymbolStruct2.prototype, prototypeAccessors$12);
            return PlacedSymbolStruct2;
          }(Struct);
          PlacedSymbolStruct.prototype.size = 48;
          var PlacedSymbolArray = function(StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482) {
            function PlacedSymbolArray2() {
              StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.apply(this, arguments);
            }
            if (StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482)
              PlacedSymbolArray2.__proto__ = StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482;
            PlacedSymbolArray2.prototype = Object.create(StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482 && StructArrayLayout2i2ui3ul3ui2f3ub1ul1i482.prototype);
            PlacedSymbolArray2.prototype.constructor = PlacedSymbolArray2;
            PlacedSymbolArray2.prototype.get = function get2(index) {
              return new PlacedSymbolStruct(this, index);
            };
            return PlacedSymbolArray2;
          }(StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48);
          register("PlacedSymbolArray", PlacedSymbolArray);
          var SymbolInstanceStruct = function(Struct2) {
            function SymbolInstanceStruct2() {
              Struct2.apply(this, arguments);
            }
            if (Struct2)
              SymbolInstanceStruct2.__proto__ = Struct2;
            SymbolInstanceStruct2.prototype = Object.create(Struct2 && Struct2.prototype);
            SymbolInstanceStruct2.prototype.constructor = SymbolInstanceStruct2;
            var prototypeAccessors$2 = {
              anchorX: { configurable: true },
              anchorY: { configurable: true },
              rightJustifiedTextSymbolIndex: { configurable: true },
              centerJustifiedTextSymbolIndex: { configurable: true },
              leftJustifiedTextSymbolIndex: { configurable: true },
              verticalPlacedTextSymbolIndex: { configurable: true },
              placedIconSymbolIndex: { configurable: true },
              verticalPlacedIconSymbolIndex: { configurable: true },
              key: { configurable: true },
              textBoxStartIndex: { configurable: true },
              textBoxEndIndex: { configurable: true },
              verticalTextBoxStartIndex: { configurable: true },
              verticalTextBoxEndIndex: { configurable: true },
              iconBoxStartIndex: { configurable: true },
              iconBoxEndIndex: { configurable: true },
              verticalIconBoxStartIndex: { configurable: true },
              verticalIconBoxEndIndex: { configurable: true },
              featureIndex: { configurable: true },
              numHorizontalGlyphVertices: { configurable: true },
              numVerticalGlyphVertices: { configurable: true },
              numIconVertices: { configurable: true },
              numVerticalIconVertices: { configurable: true },
              useRuntimeCollisionCircles: { configurable: true },
              crossTileID: { configurable: true },
              textBoxScale: { configurable: true },
              textOffset0: { configurable: true },
              textOffset1: { configurable: true },
              collisionCircleDiameter: { configurable: true }
            };
            prototypeAccessors$2.anchorX.get = function() {
              return this._structArray.int16[this._pos2 + 0];
            };
            prototypeAccessors$2.anchorY.get = function() {
              return this._structArray.int16[this._pos2 + 1];
            };
            prototypeAccessors$2.rightJustifiedTextSymbolIndex.get = function() {
              return this._structArray.int16[this._pos2 + 2];
            };
            prototypeAccessors$2.centerJustifiedTextSymbolIndex.get = function() {
              return this._structArray.int16[this._pos2 + 3];
            };
            prototypeAccessors$2.leftJustifiedTextSymbolIndex.get = function() {
              return this._structArray.int16[this._pos2 + 4];
            };
            prototypeAccessors$2.verticalPlacedTextSymbolIndex.get = function() {
              return this._structArray.int16[this._pos2 + 5];
            };
            prototypeAccessors$2.placedIconSymbolIndex.get = function() {
              return this._structArray.int16[this._pos2 + 6];
            };
            prototypeAccessors$2.verticalPlacedIconSymbolIndex.get = function() {
              return this._structArray.int16[this._pos2 + 7];
            };
            prototypeAccessors$2.key.get = function() {
              return this._structArray.uint16[this._pos2 + 8];
            };
            prototypeAccessors$2.textBoxStartIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 9];
            };
            prototypeAccessors$2.textBoxEndIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 10];
            };
            prototypeAccessors$2.verticalTextBoxStartIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 11];
            };
            prototypeAccessors$2.verticalTextBoxEndIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 12];
            };
            prototypeAccessors$2.iconBoxStartIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 13];
            };
            prototypeAccessors$2.iconBoxEndIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 14];
            };
            prototypeAccessors$2.verticalIconBoxStartIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 15];
            };
            prototypeAccessors$2.verticalIconBoxEndIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 16];
            };
            prototypeAccessors$2.featureIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 17];
            };
            prototypeAccessors$2.numHorizontalGlyphVertices.get = function() {
              return this._structArray.uint16[this._pos2 + 18];
            };
            prototypeAccessors$2.numVerticalGlyphVertices.get = function() {
              return this._structArray.uint16[this._pos2 + 19];
            };
            prototypeAccessors$2.numIconVertices.get = function() {
              return this._structArray.uint16[this._pos2 + 20];
            };
            prototypeAccessors$2.numVerticalIconVertices.get = function() {
              return this._structArray.uint16[this._pos2 + 21];
            };
            prototypeAccessors$2.useRuntimeCollisionCircles.get = function() {
              return this._structArray.uint16[this._pos2 + 22];
            };
            prototypeAccessors$2.crossTileID.get = function() {
              return this._structArray.uint32[this._pos4 + 12];
            };
            prototypeAccessors$2.crossTileID.set = function(x) {
              this._structArray.uint32[this._pos4 + 12] = x;
            };
            prototypeAccessors$2.textBoxScale.get = function() {
              return this._structArray.float32[this._pos4 + 13];
            };
            prototypeAccessors$2.textOffset0.get = function() {
              return this._structArray.float32[this._pos4 + 14];
            };
            prototypeAccessors$2.textOffset1.get = function() {
              return this._structArray.float32[this._pos4 + 15];
            };
            prototypeAccessors$2.collisionCircleDiameter.get = function() {
              return this._structArray.float32[this._pos4 + 16];
            };
            Object.defineProperties(SymbolInstanceStruct2.prototype, prototypeAccessors$2);
            return SymbolInstanceStruct2;
          }(Struct);
          SymbolInstanceStruct.prototype.size = 68;
          var SymbolInstanceArray = function(StructArrayLayout8i15ui1ul4f682) {
            function SymbolInstanceArray2() {
              StructArrayLayout8i15ui1ul4f682.apply(this, arguments);
            }
            if (StructArrayLayout8i15ui1ul4f682)
              SymbolInstanceArray2.__proto__ = StructArrayLayout8i15ui1ul4f682;
            SymbolInstanceArray2.prototype = Object.create(StructArrayLayout8i15ui1ul4f682 && StructArrayLayout8i15ui1ul4f682.prototype);
            SymbolInstanceArray2.prototype.constructor = SymbolInstanceArray2;
            SymbolInstanceArray2.prototype.get = function get2(index) {
              return new SymbolInstanceStruct(this, index);
            };
            return SymbolInstanceArray2;
          }(StructArrayLayout8i15ui1ul4f68);
          register("SymbolInstanceArray", SymbolInstanceArray);
          var GlyphOffsetArray = function(StructArrayLayout1f42) {
            function GlyphOffsetArray2() {
              StructArrayLayout1f42.apply(this, arguments);
            }
            if (StructArrayLayout1f42)
              GlyphOffsetArray2.__proto__ = StructArrayLayout1f42;
            GlyphOffsetArray2.prototype = Object.create(StructArrayLayout1f42 && StructArrayLayout1f42.prototype);
            GlyphOffsetArray2.prototype.constructor = GlyphOffsetArray2;
            GlyphOffsetArray2.prototype.getoffsetX = function getoffsetX(index) {
              return this.float32[index * 1 + 0];
            };
            return GlyphOffsetArray2;
          }(StructArrayLayout1f4);
          register("GlyphOffsetArray", GlyphOffsetArray);
          var SymbolLineVertexArray = function(StructArrayLayout3i62) {
            function SymbolLineVertexArray2() {
              StructArrayLayout3i62.apply(this, arguments);
            }
            if (StructArrayLayout3i62)
              SymbolLineVertexArray2.__proto__ = StructArrayLayout3i62;
            SymbolLineVertexArray2.prototype = Object.create(StructArrayLayout3i62 && StructArrayLayout3i62.prototype);
            SymbolLineVertexArray2.prototype.constructor = SymbolLineVertexArray2;
            SymbolLineVertexArray2.prototype.getx = function getx(index) {
              return this.int16[index * 3 + 0];
            };
            SymbolLineVertexArray2.prototype.gety = function gety(index) {
              return this.int16[index * 3 + 1];
            };
            SymbolLineVertexArray2.prototype.gettileUnitDistanceFromAnchor = function gettileUnitDistanceFromAnchor(index) {
              return this.int16[index * 3 + 2];
            };
            return SymbolLineVertexArray2;
          }(StructArrayLayout3i6);
          register("SymbolLineVertexArray", SymbolLineVertexArray);
          var FeatureIndexStruct = function(Struct2) {
            function FeatureIndexStruct2() {
              Struct2.apply(this, arguments);
            }
            if (Struct2)
              FeatureIndexStruct2.__proto__ = Struct2;
            FeatureIndexStruct2.prototype = Object.create(Struct2 && Struct2.prototype);
            FeatureIndexStruct2.prototype.constructor = FeatureIndexStruct2;
            var prototypeAccessors$3 = {
              featureIndex: { configurable: true },
              sourceLayerIndex: { configurable: true },
              bucketIndex: { configurable: true }
            };
            prototypeAccessors$3.featureIndex.get = function() {
              return this._structArray.uint32[this._pos4 + 0];
            };
            prototypeAccessors$3.sourceLayerIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 2];
            };
            prototypeAccessors$3.bucketIndex.get = function() {
              return this._structArray.uint16[this._pos2 + 3];
            };
            Object.defineProperties(FeatureIndexStruct2.prototype, prototypeAccessors$3);
            return FeatureIndexStruct2;
          }(Struct);
          FeatureIndexStruct.prototype.size = 8;
          var FeatureIndexArray = function(StructArrayLayout1ul2ui82) {
            function FeatureIndexArray2() {
              StructArrayLayout1ul2ui82.apply(this, arguments);
            }
            if (StructArrayLayout1ul2ui82)
              FeatureIndexArray2.__proto__ = StructArrayLayout1ul2ui82;
            FeatureIndexArray2.prototype = Object.create(StructArrayLayout1ul2ui82 && StructArrayLayout1ul2ui82.prototype);
            FeatureIndexArray2.prototype.constructor = FeatureIndexArray2;
            FeatureIndexArray2.prototype.get = function get2(index) {
              return new FeatureIndexStruct(this, index);
            };
            return FeatureIndexArray2;
          }(StructArrayLayout1ul2ui8);
          register("FeatureIndexArray", FeatureIndexArray);
          var layout$1 = createLayout([{
            name: "a_pos",
            components: 2,
            type: "Int16"
          }], 4);
          var members = layout$1.members;
          var SegmentVector = function SegmentVector2(segments) {
            if (segments === void 0)
              segments = [];
            this.segments = segments;
          };
          SegmentVector.prototype.prepareSegment = function prepareSegment(numVertices, layoutVertexArray, indexArray, sortKey) {
            var segment = this.segments[this.segments.length - 1];
            if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {
              warnOnce("Max vertices per segment is " + SegmentVector.MAX_VERTEX_ARRAY_LENGTH + ": bucket requested " + numVertices);
            }
            if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) {
              segment = {
                vertexOffset: layoutVertexArray.length,
                primitiveOffset: indexArray.length,
                vertexLength: 0,
                primitiveLength: 0
              };
              if (sortKey !== void 0) {
                segment.sortKey = sortKey;
              }
              this.segments.push(segment);
            }
            return segment;
          };
          SegmentVector.prototype.get = function get2() {
            return this.segments;
          };
          SegmentVector.prototype.destroy = function destroy() {
            for (var i = 0, list = this.segments; i < list.length; i += 1) {
              var segment = list[i];
              for (var k in segment.vaos) {
                segment.vaos[k].destroy();
              }
            }
          };
          SegmentVector.simpleSegment = function simpleSegment(vertexOffset, primitiveOffset, vertexLength, primitiveLength) {
            return new SegmentVector([{
              vertexOffset,
              primitiveOffset,
              vertexLength,
              primitiveLength,
              vaos: {},
              sortKey: 0
            }]);
          };
          SegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;
          register("SegmentVector", SegmentVector);
          function packUint8ToFloat(a, b) {
            a = clamp(Math.floor(a), 0, 255);
            b = clamp(Math.floor(b), 0, 255);
            return 256 * a + b;
          }
          var patternAttributes = createLayout([
            {
              name: "a_pattern_from",
              components: 4,
              type: "Uint16"
            },
            {
              name: "a_pattern_to",
              components: 4,
              type: "Uint16"
            },
            {
              name: "a_pixel_ratio_from",
              components: 1,
              type: "Uint16"
            },
            {
              name: "a_pixel_ratio_to",
              components: 1,
              type: "Uint16"
            }
          ]);
          var murmurhash3_gc = createCommonjsModule(function(module2) {
            function murmurhash3_32_gc(key, seed) {
              var remainder, bytes, h1, h1b, c1, c2, k1, i;
              remainder = key.length & 3;
              bytes = key.length - remainder;
              h1 = seed;
              c1 = 3432918353;
              c2 = 461845907;
              i = 0;
              while (i < bytes) {
                k1 = key.charCodeAt(i) & 255 | (key.charCodeAt(++i) & 255) << 8 | (key.charCodeAt(++i) & 255) << 16 | (key.charCodeAt(++i) & 255) << 24;
                ++i;
                k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295;
                k1 = k1 << 15 | k1 >>> 17;
                k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295;
                h1 ^= k1;
                h1 = h1 << 13 | h1 >>> 19;
                h1b = (h1 & 65535) * 5 + (((h1 >>> 16) * 5 & 65535) << 16) & 4294967295;
                h1 = (h1b & 65535) + 27492 + (((h1b >>> 16) + 58964 & 65535) << 16);
              }
              k1 = 0;
              switch (remainder) {
                case 3:
                  k1 ^= (key.charCodeAt(i + 2) & 255) << 16;
                case 2:
                  k1 ^= (key.charCodeAt(i + 1) & 255) << 8;
                case 1:
                  k1 ^= key.charCodeAt(i) & 255;
                  k1 = (k1 & 65535) * c1 + (((k1 >>> 16) * c1 & 65535) << 16) & 4294967295;
                  k1 = k1 << 15 | k1 >>> 17;
                  k1 = (k1 & 65535) * c2 + (((k1 >>> 16) * c2 & 65535) << 16) & 4294967295;
                  h1 ^= k1;
              }
              h1 ^= key.length;
              h1 ^= h1 >>> 16;
              h1 = (h1 & 65535) * 2246822507 + (((h1 >>> 16) * 2246822507 & 65535) << 16) & 4294967295;
              h1 ^= h1 >>> 13;
              h1 = (h1 & 65535) * 3266489909 + (((h1 >>> 16) * 3266489909 & 65535) << 16) & 4294967295;
              h1 ^= h1 >>> 16;
              return h1 >>> 0;
            }
            {
              module2.exports = murmurhash3_32_gc;
            }
          });
          var murmurhash2_gc = createCommonjsModule(function(module2) {
            function murmurhash2_32_gc(str, seed) {
              var l = str.length, h = seed ^ l, i = 0, k;
              while (l >= 4) {
                k = str.charCodeAt(i) & 255 | (str.charCodeAt(++i) & 255) << 8 | (str.charCodeAt(++i) & 255) << 16 | (str.charCodeAt(++i) & 255) << 24;
                k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
                k ^= k >>> 24;
                k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
                h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16) ^ k;
                l -= 4;
                ++i;
              }
              switch (l) {
                case 3:
                  h ^= (str.charCodeAt(i + 2) & 255) << 16;
                case 2:
                  h ^= (str.charCodeAt(i + 1) & 255) << 8;
                case 1:
                  h ^= str.charCodeAt(i) & 255;
                  h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
              }
              h ^= h >>> 13;
              h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
              h ^= h >>> 15;
              return h >>> 0;
            }
            {
              module2.exports = murmurhash2_32_gc;
            }
          });
          var murmurhashJs = murmurhash3_gc;
          var murmur3_1 = murmurhash3_gc;
          var murmur2_1 = murmurhash2_gc;
          murmurhashJs.murmur3 = murmur3_1;
          murmurhashJs.murmur2 = murmur2_1;
          var FeaturePositionMap = function FeaturePositionMap2() {
            this.ids = [];
            this.positions = [];
            this.indexed = false;
          };
          FeaturePositionMap.prototype.add = function add2(id2, index, start, end) {
            this.ids.push(getNumericId(id2));
            this.positions.push(index, start, end);
          };
          FeaturePositionMap.prototype.getPositions = function getPositions(id2) {
            var intId = getNumericId(id2);
            var i = 0;
            var j = this.ids.length - 1;
            while (i < j) {
              var m = i + j >> 1;
              if (this.ids[m] >= intId) {
                j = m;
              } else {
                i = m + 1;
              }
            }
            var positions = [];
            while (this.ids[i] === intId) {
              var index = this.positions[3 * i];
              var start = this.positions[3 * i + 1];
              var end = this.positions[3 * i + 2];
              positions.push({
                index,
                start,
                end
              });
              i++;
            }
            return positions;
          };
          FeaturePositionMap.serialize = function serialize2(map, transferables) {
            var ids = new Float64Array(map.ids);
            var positions = new Uint32Array(map.positions);
            sort(ids, positions, 0, ids.length - 1);
            if (transferables) {
              transferables.push(ids.buffer, positions.buffer);
            }
            return {
              ids,
              positions
            };
          };
          FeaturePositionMap.deserialize = function deserialize2(obj) {
            var map = new FeaturePositionMap();
            map.ids = obj.ids;
            map.positions = obj.positions;
            map.indexed = true;
            return map;
          };
          var MAX_SAFE_INTEGER$1 = Math.pow(2, 53) - 1;
          function getNumericId(value) {
            var numValue = +value;
            if (!isNaN(numValue) && numValue <= MAX_SAFE_INTEGER$1) {
              return numValue;
            }
            return murmurhashJs(String(value));
          }
          function sort(ids, positions, left, right) {
            while (left < right) {
              var pivot = ids[left + right >> 1];
              var i = left - 1;
              var j = right + 1;
              while (true) {
                do {
                  i++;
                } while (ids[i] < pivot);
                do {
                  j--;
                } while (ids[j] > pivot);
                if (i >= j) {
                  break;
                }
                swap(ids, i, j);
                swap(positions, 3 * i, 3 * j);
                swap(positions, 3 * i + 1, 3 * j + 1);
                swap(positions, 3 * i + 2, 3 * j + 2);
              }
              if (j - left < right - j) {
                sort(ids, positions, left, j);
                left = j + 1;
              } else {
                sort(ids, positions, j + 1, right);
                right = j;
              }
            }
          }
          function swap(arr, i, j) {
            var tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
          }
          register("FeaturePositionMap", FeaturePositionMap);
          var Uniform = function Uniform2(context, location2) {
            this.gl = context.gl;
            this.location = location2;
          };
          var Uniform1i = function(Uniform2) {
            function Uniform1i2(context, location2) {
              Uniform2.call(this, context, location2);
              this.current = 0;
            }
            if (Uniform2)
              Uniform1i2.__proto__ = Uniform2;
            Uniform1i2.prototype = Object.create(Uniform2 && Uniform2.prototype);
            Uniform1i2.prototype.constructor = Uniform1i2;
            Uniform1i2.prototype.set = function set(v) {
              if (this.current !== v) {
                this.current = v;
                this.gl.uniform1i(this.location, v);
              }
            };
            return Uniform1i2;
          }(Uniform);
          var Uniform1f = function(Uniform2) {
            function Uniform1f2(context, location2) {
              Uniform2.call(this, context, location2);
              this.current = 0;
            }
            if (Uniform2)
              Uniform1f2.__proto__ = Uniform2;
            Uniform1f2.prototype = Object.create(Uniform2 && Uniform2.prototype);
            Uniform1f2.prototype.constructor = Uniform1f2;
            Uniform1f2.prototype.set = function set(v) {
              if (this.current !== v) {
                this.current = v;
                this.gl.uniform1f(this.location, v);
              }
            };
            return Uniform1f2;
          }(Uniform);
          var Uniform2f = function(Uniform2) {
            function Uniform2f2(context, location2) {
              Uniform2.call(this, context, location2);
              this.current = [
                0,
                0
              ];
            }
            if (Uniform2)
              Uniform2f2.__proto__ = Uniform2;
            Uniform2f2.prototype = Object.create(Uniform2 && Uniform2.prototype);
            Uniform2f2.prototype.constructor = Uniform2f2;
            Uniform2f2.prototype.set = function set(v) {
              if (v[0] !== this.current[0] || v[1] !== this.current[1]) {
                this.current = v;
                this.gl.uniform2f(this.location, v[0], v[1]);
              }
            };
            return Uniform2f2;
          }(Uniform);
          var Uniform3f = function(Uniform2) {
            function Uniform3f2(context, location2) {
              Uniform2.call(this, context, location2);
              this.current = [
                0,
                0,
                0
              ];
            }
            if (Uniform2)
              Uniform3f2.__proto__ = Uniform2;
            Uniform3f2.prototype = Object.create(Uniform2 && Uniform2.prototype);
            Uniform3f2.prototype.constructor = Uniform3f2;
            Uniform3f2.prototype.set = function set(v) {
              if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) {
                this.current = v;
                this.gl.uniform3f(this.location, v[0], v[1], v[2]);
              }
            };
            return Uniform3f2;
          }(Uniform);
          var Uniform4f = function(Uniform2) {
            function Uniform4f2(context, location2) {
              Uniform2.call(this, context, location2);
              this.current = [
                0,
                0,
                0,
                0
              ];
            }
            if (Uniform2)
              Uniform4f2.__proto__ = Uniform2;
            Uniform4f2.prototype = Object.create(Uniform2 && Uniform2.prototype);
            Uniform4f2.prototype.constructor = Uniform4f2;
            Uniform4f2.prototype.set = function set(v) {
              if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2] || v[3] !== this.current[3]) {
                this.current = v;
                this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]);
              }
            };
            return Uniform4f2;
          }(Uniform);
          var UniformColor = function(Uniform2) {
            function UniformColor2(context, location2) {
              Uniform2.call(this, context, location2);
              this.current = Color2.transparent;
            }
            if (Uniform2)
              UniformColor2.__proto__ = Uniform2;
            UniformColor2.prototype = Object.create(Uniform2 && Uniform2.prototype);
            UniformColor2.prototype.constructor = UniformColor2;
            UniformColor2.prototype.set = function set(v) {
              if (v.r !== this.current.r || v.g !== this.current.g || v.b !== this.current.b || v.a !== this.current.a) {
                this.current = v;
                this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a);
              }
            };
            return UniformColor2;
          }(Uniform);
          var emptyMat4 = new Float32Array(16);
          var UniformMatrix4f = function(Uniform2) {
            function UniformMatrix4f2(context, location2) {
              Uniform2.call(this, context, location2);
              this.current = emptyMat4;
            }
            if (Uniform2)
              UniformMatrix4f2.__proto__ = Uniform2;
            UniformMatrix4f2.prototype = Object.create(Uniform2 && Uniform2.prototype);
            UniformMatrix4f2.prototype.constructor = UniformMatrix4f2;
            UniformMatrix4f2.prototype.set = function set(v) {
              if (v[12] !== this.current[12] || v[0] !== this.current[0]) {
                this.current = v;
                this.gl.uniformMatrix4fv(this.location, false, v);
                return;
              }
              for (var i = 1; i < 16; i++) {
                if (v[i] !== this.current[i]) {
                  this.current = v;
                  this.gl.uniformMatrix4fv(this.location, false, v);
                  break;
                }
              }
            };
            return UniformMatrix4f2;
          }(Uniform);
          function packColor(color3) {
            return [
              packUint8ToFloat(255 * color3.r, 255 * color3.g),
              packUint8ToFloat(255 * color3.b, 255 * color3.a)
            ];
          }
          var ConstantBinder = function ConstantBinder2(value, names2, type) {
            this.value = value;
            this.uniformNames = names2.map(function(name3) {
              return "u_" + name3;
            });
            this.type = type;
          };
          ConstantBinder.prototype.setUniform = function setUniform(uniform, globals, currentValue) {
            uniform.set(currentValue.constantOr(this.value));
          };
          ConstantBinder.prototype.getBinding = function getBinding(context, location2, _) {
            return this.type === "color" ? new UniformColor(context, location2) : new Uniform1f(context, location2);
          };
          var CrossFadedConstantBinder = function CrossFadedConstantBinder2(value, names2) {
            this.uniformNames = names2.map(function(name3) {
              return "u_" + name3;
            });
            this.patternFrom = null;
            this.patternTo = null;
            this.pixelRatioFrom = 1;
            this.pixelRatioTo = 1;
          };
          CrossFadedConstantBinder.prototype.setConstantPatternPositions = function setConstantPatternPositions(posTo, posFrom) {
            this.pixelRatioFrom = posFrom.pixelRatio;
            this.pixelRatioTo = posTo.pixelRatio;
            this.patternFrom = posFrom.tlbr;
            this.patternTo = posTo.tlbr;
          };
          CrossFadedConstantBinder.prototype.setUniform = function setUniform(uniform, globals, currentValue, uniformName) {
            var pos = uniformName === "u_pattern_to" ? this.patternTo : uniformName === "u_pattern_from" ? this.patternFrom : uniformName === "u_pixel_ratio_to" ? this.pixelRatioTo : uniformName === "u_pixel_ratio_from" ? this.pixelRatioFrom : null;
            if (pos) {
              uniform.set(pos);
            }
          };
          CrossFadedConstantBinder.prototype.getBinding = function getBinding(context, location2, name3) {
            return name3.substr(0, 9) === "u_pattern" ? new Uniform4f(context, location2) : new Uniform1f(context, location2);
          };
          var SourceExpressionBinder = function SourceExpressionBinder2(expression2, names2, type, PaintVertexArray) {
            this.expression = expression2;
            this.type = type;
            this.maxValue = 0;
            this.paintVertexAttributes = names2.map(function(name3) {
              return {
                name: "a_" + name3,
                type: "Float32",
                components: type === "color" ? 2 : 1,
                offset: 0
              };
            });
            this.paintVertexArray = new PaintVertexArray();
          };
          SourceExpressionBinder.prototype.populatePaintArray = function populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) {
            var start = this.paintVertexArray.length;
            var value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, [], formattedSection);
            this.paintVertexArray.resize(newLength);
            this._setPaintValue(start, newLength, value);
          };
          SourceExpressionBinder.prototype.updatePaintArray = function updatePaintArray(start, end, feature, featureState) {
            var value = this.expression.evaluate({ zoom: 0 }, feature, featureState);
            this._setPaintValue(start, end, value);
          };
          SourceExpressionBinder.prototype._setPaintValue = function _setPaintValue(start, end, value) {
            if (this.type === "color") {
              var color3 = packColor(value);
              for (var i = start; i < end; i++) {
                this.paintVertexArray.emplace(i, color3[0], color3[1]);
              }
            } else {
              for (var i$1 = start; i$1 < end; i$1++) {
                this.paintVertexArray.emplace(i$1, value);
              }
              this.maxValue = Math.max(this.maxValue, Math.abs(value));
            }
          };
          SourceExpressionBinder.prototype.upload = function upload(context) {
            if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {
              if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {
                this.paintVertexBuffer.updateData(this.paintVertexArray);
              } else {
                this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);
              }
            }
          };
          SourceExpressionBinder.prototype.destroy = function destroy() {
            if (this.paintVertexBuffer) {
              this.paintVertexBuffer.destroy();
            }
          };
          var CompositeExpressionBinder = function CompositeExpressionBinder2(expression2, names2, type, useIntegerZoom, zoom, PaintVertexArray) {
            this.expression = expression2;
            this.uniformNames = names2.map(function(name3) {
              return "u_" + name3 + "_t";
            });
            this.type = type;
            this.useIntegerZoom = useIntegerZoom;
            this.zoom = zoom;
            this.maxValue = 0;
            this.paintVertexAttributes = names2.map(function(name3) {
              return {
                name: "a_" + name3,
                type: "Float32",
                components: type === "color" ? 4 : 2,
                offset: 0
              };
            });
            this.paintVertexArray = new PaintVertexArray();
          };
          CompositeExpressionBinder.prototype.populatePaintArray = function populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection) {
            var min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, [], formattedSection);
            var max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, [], formattedSection);
            var start = this.paintVertexArray.length;
            this.paintVertexArray.resize(newLength);
            this._setPaintValue(start, newLength, min, max);
          };
          CompositeExpressionBinder.prototype.updatePaintArray = function updatePaintArray(start, end, feature, featureState) {
            var min = this.expression.evaluate({ zoom: this.zoom }, feature, featureState);
            var max = this.expression.evaluate({ zoom: this.zoom + 1 }, feature, featureState);
            this._setPaintValue(start, end, min, max);
          };
          CompositeExpressionBinder.prototype._setPaintValue = function _setPaintValue(start, end, min, max) {
            if (this.type === "color") {
              var minColor = packColor(min);
              var maxColor = packColor(max);
              for (var i = start; i < end; i++) {
                this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]);
              }
            } else {
              for (var i$1 = start; i$1 < end; i$1++) {
                this.paintVertexArray.emplace(i$1, min, max);
              }
              this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max));
            }
          };
          CompositeExpressionBinder.prototype.upload = function upload(context) {
            if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {
              if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {
                this.paintVertexBuffer.updateData(this.paintVertexArray);
              } else {
                this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);
              }
            }
          };
          CompositeExpressionBinder.prototype.destroy = function destroy() {
            if (this.paintVertexBuffer) {
              this.paintVertexBuffer.destroy();
            }
          };
          CompositeExpressionBinder.prototype.setUniform = function setUniform(uniform, globals) {
            var currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom;
            var factor = clamp(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1);
            uniform.set(factor);
          };
          CompositeExpressionBinder.prototype.getBinding = function getBinding(context, location2, _) {
            return new Uniform1f(context, location2);
          };
          var CrossFadedCompositeBinder = function CrossFadedCompositeBinder2(expression2, type, useIntegerZoom, zoom, PaintVertexArray, layerId) {
            this.expression = expression2;
            this.type = type;
            this.useIntegerZoom = useIntegerZoom;
            this.zoom = zoom;
            this.layerId = layerId;
            this.zoomInPaintVertexArray = new PaintVertexArray();
            this.zoomOutPaintVertexArray = new PaintVertexArray();
          };
          CrossFadedCompositeBinder.prototype.populatePaintArray = function populatePaintArray(length, feature, imagePositions) {
            var start = this.zoomInPaintVertexArray.length;
            this.zoomInPaintVertexArray.resize(length);
            this.zoomOutPaintVertexArray.resize(length);
            this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions);
          };
          CrossFadedCompositeBinder.prototype.updatePaintArray = function updatePaintArray(start, end, feature, featureState, imagePositions) {
            this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions);
          };
          CrossFadedCompositeBinder.prototype._setPaintValues = function _setPaintValues(start, end, patterns, positions) {
            if (!positions || !patterns) {
              return;
            }
            var min = patterns.min;
            var mid = patterns.mid;
            var max = patterns.max;
            var imageMin = positions[min];
            var imageMid = positions[mid];
            var imageMax = positions[max];
            if (!imageMin || !imageMid || !imageMax) {
              return;
            }
            for (var i = start; i < end; i++) {
              this.zoomInPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMin.tl[0], imageMin.tl[1], imageMin.br[0], imageMin.br[1], imageMid.pixelRatio, imageMin.pixelRatio);
              this.zoomOutPaintVertexArray.emplace(i, imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1], imageMax.tl[0], imageMax.tl[1], imageMax.br[0], imageMax.br[1], imageMid.pixelRatio, imageMax.pixelRatio);
            }
          };
          CrossFadedCompositeBinder.prototype.upload = function upload(context) {
            if (this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer) {
              this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, patternAttributes.members, this.expression.isStateDependent);
              this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, patternAttributes.members, this.expression.isStateDependent);
            }
          };
          CrossFadedCompositeBinder.prototype.destroy = function destroy() {
            if (this.zoomOutPaintVertexBuffer) {
              this.zoomOutPaintVertexBuffer.destroy();
            }
            if (this.zoomInPaintVertexBuffer) {
              this.zoomInPaintVertexBuffer.destroy();
            }
          };
          var ProgramConfiguration = function ProgramConfiguration2(layer2, zoom, filterProperties) {
            this.binders = {};
            this._buffers = [];
            var keys = [];
            for (var property in layer2.paint._values) {
              if (!filterProperties(property)) {
                continue;
              }
              var value = layer2.paint.get(property);
              if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {
                continue;
              }
              var names2 = paintAttributeNames(property, layer2.type);
              var expression2 = value.value;
              var type = value.property.specification.type;
              var useIntegerZoom = value.property.useIntegerZoom;
              var propType = value.property.specification["property-type"];
              var isCrossFaded = propType === "cross-faded" || propType === "cross-faded-data-driven";
              if (expression2.kind === "constant") {
                this.binders[property] = isCrossFaded ? new CrossFadedConstantBinder(expression2.value, names2) : new ConstantBinder(expression2.value, names2, type);
                keys.push("/u_" + property);
              } else if (expression2.kind === "source" || isCrossFaded) {
                var StructArrayLayout = layoutType(property, type, "source");
                this.binders[property] = isCrossFaded ? new CrossFadedCompositeBinder(expression2, type, useIntegerZoom, zoom, StructArrayLayout, layer2.id) : new SourceExpressionBinder(expression2, names2, type, StructArrayLayout);
                keys.push("/a_" + property);
              } else {
                var StructArrayLayout$1 = layoutType(property, type, "composite");
                this.binders[property] = new CompositeExpressionBinder(expression2, names2, type, useIntegerZoom, zoom, StructArrayLayout$1);
                keys.push("/z_" + property);
              }
            }
            this.cacheKey = keys.sort().join("");
          };
          ProgramConfiguration.prototype.getMaxValue = function getMaxValue(property) {
            var binder = this.binders[property];
            return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0;
          };
          ProgramConfiguration.prototype.populatePaintArrays = function populatePaintArrays(newLength, feature, imagePositions, canonical, formattedSection) {
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) {
                binder.populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection);
              }
            }
          };
          ProgramConfiguration.prototype.setConstantPatternPositions = function setConstantPatternPositions(posTo, posFrom) {
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof CrossFadedConstantBinder) {
                binder.setConstantPatternPositions(posTo, posFrom);
              }
            }
          };
          ProgramConfiguration.prototype.updatePaintArrays = function updatePaintArrays(featureStates, featureMap, vtLayer, layer2, imagePositions) {
            var dirty = false;
            for (var id2 in featureStates) {
              var positions = featureMap.getPositions(id2);
              for (var i = 0, list = positions; i < list.length; i += 1) {
                var pos = list[i];
                var feature = vtLayer.feature(pos.index);
                for (var property in this.binders) {
                  var binder = this.binders[property];
                  if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) && binder.expression.isStateDependent === true) {
                    var value = layer2.paint.get(property);
                    binder.expression = value.value;
                    binder.updatePaintArray(pos.start, pos.end, feature, featureStates[id2], imagePositions);
                    dirty = true;
                  }
                }
              }
            }
            return dirty;
          };
          ProgramConfiguration.prototype.defines = function defines() {
            var result = [];
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) {
                result.push.apply(result, binder.uniformNames.map(function(name3) {
                  return "#define HAS_UNIFORM_" + name3;
                }));
              }
            }
            return result;
          };
          ProgramConfiguration.prototype.getBinderAttributes = function getBinderAttributes() {
            var result = [];
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) {
                for (var i = 0; i < binder.paintVertexAttributes.length; i++) {
                  result.push(binder.paintVertexAttributes[i].name);
                }
              } else if (binder instanceof CrossFadedCompositeBinder) {
                for (var i$1 = 0; i$1 < patternAttributes.members.length; i$1++) {
                  result.push(patternAttributes.members[i$1].name);
                }
              }
            }
            return result;
          };
          ProgramConfiguration.prototype.getBinderUniforms = function getBinderUniforms() {
            var uniforms = [];
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) {
                for (var i = 0, list = binder.uniformNames; i < list.length; i += 1) {
                  var uniformName = list[i];
                  uniforms.push(uniformName);
                }
              }
            }
            return uniforms;
          };
          ProgramConfiguration.prototype.getPaintVertexBuffers = function getPaintVertexBuffers() {
            return this._buffers;
          };
          ProgramConfiguration.prototype.getUniforms = function getUniforms(context, locations) {
            var uniforms = [];
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) {
                for (var i = 0, list = binder.uniformNames; i < list.length; i += 1) {
                  var name3 = list[i];
                  if (locations[name3]) {
                    var binding = binder.getBinding(context, locations[name3], name3);
                    uniforms.push({
                      name: name3,
                      property,
                      binding
                    });
                  }
                }
              }
            }
            return uniforms;
          };
          ProgramConfiguration.prototype.setUniforms = function setUniforms(context, binderUniforms, properties2, globals) {
            for (var i = 0, list = binderUniforms; i < list.length; i += 1) {
              var ref = list[i];
              var name3 = ref.name;
              var property = ref.property;
              var binding = ref.binding;
              this.binders[property].setUniform(binding, globals, properties2.get(property), name3);
            }
          };
          ProgramConfiguration.prototype.updatePaintBuffers = function updatePaintBuffers(crossfade) {
            this._buffers = [];
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (crossfade && binder instanceof CrossFadedCompositeBinder) {
                var patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer;
                if (patternVertexBuffer) {
                  this._buffers.push(patternVertexBuffer);
                }
              } else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && binder.paintVertexBuffer) {
                this._buffers.push(binder.paintVertexBuffer);
              }
            }
          };
          ProgramConfiguration.prototype.upload = function upload(context) {
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) {
                binder.upload(context);
              }
            }
            this.updatePaintBuffers();
          };
          ProgramConfiguration.prototype.destroy = function destroy() {
            for (var property in this.binders) {
              var binder = this.binders[property];
              if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof CrossFadedCompositeBinder) {
                binder.destroy();
              }
            }
          };
          var ProgramConfigurationSet = function ProgramConfigurationSet2(layers, zoom, filterProperties) {
            if (filterProperties === void 0)
              filterProperties = function() {
                return true;
              };
            this.programConfigurations = {};
            for (var i = 0, list = layers; i < list.length; i += 1) {
              var layer2 = list[i];
              this.programConfigurations[layer2.id] = new ProgramConfiguration(layer2, zoom, filterProperties);
            }
            this.needsUpload = false;
            this._featureMap = new FeaturePositionMap();
            this._bufferOffset = 0;
          };
          ProgramConfigurationSet.prototype.populatePaintArrays = function populatePaintArrays(length, feature, index, imagePositions, canonical, formattedSection) {
            for (var key in this.programConfigurations) {
              this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, canonical, formattedSection);
            }
            if (feature.id !== void 0) {
              this._featureMap.add(feature.id, index, this._bufferOffset, length);
            }
            this._bufferOffset = length;
            this.needsUpload = true;
          };
          ProgramConfigurationSet.prototype.updatePaintArrays = function updatePaintArrays(featureStates, vtLayer, layers, imagePositions) {
            for (var i = 0, list = layers; i < list.length; i += 1) {
              var layer2 = list[i];
              this.needsUpload = this.programConfigurations[layer2.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer2, imagePositions) || this.needsUpload;
            }
          };
          ProgramConfigurationSet.prototype.get = function get2(layerId) {
            return this.programConfigurations[layerId];
          };
          ProgramConfigurationSet.prototype.upload = function upload(context) {
            if (!this.needsUpload) {
              return;
            }
            for (var layerId in this.programConfigurations) {
              this.programConfigurations[layerId].upload(context);
            }
            this.needsUpload = false;
          };
          ProgramConfigurationSet.prototype.destroy = function destroy() {
            for (var layerId in this.programConfigurations) {
              this.programConfigurations[layerId].destroy();
            }
          };
          function paintAttributeNames(property, type) {
            var attributeNameExceptions = {
              "text-opacity": ["opacity"],
              "icon-opacity": ["opacity"],
              "text-color": ["fill_color"],
              "icon-color": ["fill_color"],
              "text-halo-color": ["halo_color"],
              "icon-halo-color": ["halo_color"],
              "text-halo-blur": ["halo_blur"],
              "icon-halo-blur": ["halo_blur"],
              "text-halo-width": ["halo_width"],
              "icon-halo-width": ["halo_width"],
              "line-gap-width": ["gapwidth"],
              "line-pattern": [
                "pattern_to",
                "pattern_from",
                "pixel_ratio_to",
                "pixel_ratio_from"
              ],
              "fill-pattern": [
                "pattern_to",
                "pattern_from",
                "pixel_ratio_to",
                "pixel_ratio_from"
              ],
              "fill-extrusion-pattern": [
                "pattern_to",
                "pattern_from",
                "pixel_ratio_to",
                "pixel_ratio_from"
              ]
            };
            return attributeNameExceptions[property] || [property.replace(type + "-", "").replace(/-/g, "_")];
          }
          function getLayoutException(property) {
            var propertyExceptions = {
              "line-pattern": {
                "source": StructArrayLayout10ui20,
                "composite": StructArrayLayout10ui20
              },
              "fill-pattern": {
                "source": StructArrayLayout10ui20,
                "composite": StructArrayLayout10ui20
              },
              "fill-extrusion-pattern": {
                "source": StructArrayLayout10ui20,
                "composite": StructArrayLayout10ui20
              }
            };
            return propertyExceptions[property];
          }
          function layoutType(property, type, binderType) {
            var defaultLayouts = {
              "color": {
                "source": StructArrayLayout2f8,
                "composite": StructArrayLayout4f16
              },
              "number": {
                "source": StructArrayLayout1f4,
                "composite": StructArrayLayout2f8
              }
            };
            var layoutException = getLayoutException(property);
            return layoutException && layoutException[binderType] || defaultLayouts[type][binderType];
          }
          register("ConstantBinder", ConstantBinder);
          register("CrossFadedConstantBinder", CrossFadedConstantBinder);
          register("SourceExpressionBinder", SourceExpressionBinder);
          register("CrossFadedCompositeBinder", CrossFadedCompositeBinder);
          register("CompositeExpressionBinder", CompositeExpressionBinder);
          register("ProgramConfiguration", ProgramConfiguration, { omit: ["_buffers"] });
          register("ProgramConfigurationSet", ProgramConfigurationSet);
          var EXTENT$1 = 8192;
          var BITS = 15;
          var MAX = Math.pow(2, BITS - 1) - 1;
          var MIN = -MAX - 1;
          function loadGeometry(feature) {
            var scale2 = EXTENT$1 / feature.extent;
            var geometry = feature.loadGeometry();
            for (var r = 0; r < geometry.length; r++) {
              var ring = geometry[r];
              for (var p = 0; p < ring.length; p++) {
                var point = ring[p];
                var x = Math.round(point.x * scale2);
                var y = Math.round(point.y * scale2);
                point.x = clamp(x, MIN, MAX);
                point.y = clamp(y, MIN, MAX);
                if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) {
                  warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size");
                }
              }
            }
            return geometry;
          }
          function toEvaluationFeature(feature, needGeometry) {
            return {
              type: feature.type,
              id: feature.id,
              properties: feature.properties,
              geometry: needGeometry ? loadGeometry(feature) : []
            };
          }
          function addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {
            layoutVertexArray.emplaceBack(x * 2 + (extrudeX + 1) / 2, y * 2 + (extrudeY + 1) / 2);
          }
          var CircleBucket = function CircleBucket2(options) {
            this.zoom = options.zoom;
            this.overscaling = options.overscaling;
            this.layers = options.layers;
            this.layerIds = this.layers.map(function(layer2) {
              return layer2.id;
            });
            this.index = options.index;
            this.hasPattern = false;
            this.layoutVertexArray = new StructArrayLayout2i4();
            this.indexArray = new StructArrayLayout3ui6();
            this.segments = new SegmentVector();
            this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);
            this.stateDependentLayerIds = this.layers.filter(function(l) {
              return l.isStateDependent();
            }).map(function(l) {
              return l.id;
            });
          };
          CircleBucket.prototype.populate = function populate(features, options, canonical) {
            var styleLayer = this.layers[0];
            var bucketFeatures = [];
            var circleSortKey = null;
            if (styleLayer.type === "circle") {
              circleSortKey = styleLayer.layout.get("circle-sort-key");
            }
            for (var i = 0, list = features; i < list.length; i += 1) {
              var ref = list[i];
              var feature = ref.feature;
              var id2 = ref.id;
              var index = ref.index;
              var sourceLayerIndex = ref.sourceLayerIndex;
              var needGeometry = this.layers[0]._featureFilter.needGeometry;
              var evaluationFeature = toEvaluationFeature(feature, needGeometry);
              if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) {
                continue;
              }
              var sortKey = circleSortKey ? circleSortKey.evaluate(evaluationFeature, {}, canonical) : void 0;
              var bucketFeature = {
                id: id2,
                properties: feature.properties,
                type: feature.type,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),
                patterns: {},
                sortKey
              };
              bucketFeatures.push(bucketFeature);
            }
            if (circleSortKey) {
              bucketFeatures.sort(function(a, b) {
                return a.sortKey - b.sortKey;
              });
            }
            for (var i$1 = 0, list$1 = bucketFeatures; i$1 < list$1.length; i$1 += 1) {
              var bucketFeature$1 = list$1[i$1];
              var ref$1 = bucketFeature$1;
              var geometry = ref$1.geometry;
              var index$1 = ref$1.index;
              var sourceLayerIndex$1 = ref$1.sourceLayerIndex;
              var feature$1 = features[index$1].feature;
              this.addFeature(bucketFeature$1, geometry, index$1, canonical);
              options.featureIndex.insert(feature$1, geometry, index$1, sourceLayerIndex$1, this.index);
            }
          };
          CircleBucket.prototype.update = function update(states, vtLayer, imagePositions) {
            if (!this.stateDependentLayers.length) {
              return;
            }
            this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);
          };
          CircleBucket.prototype.isEmpty = function isEmpty2() {
            return this.layoutVertexArray.length === 0;
          };
          CircleBucket.prototype.uploadPending = function uploadPending() {
            return !this.uploaded || this.programConfigurations.needsUpload;
          };
          CircleBucket.prototype.upload = function upload(context) {
            if (!this.uploaded) {
              this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members);
              this.indexBuffer = context.createIndexBuffer(this.indexArray);
            }
            this.programConfigurations.upload(context);
            this.uploaded = true;
          };
          CircleBucket.prototype.destroy = function destroy() {
            if (!this.layoutVertexBuffer) {
              return;
            }
            this.layoutVertexBuffer.destroy();
            this.indexBuffer.destroy();
            this.programConfigurations.destroy();
            this.segments.destroy();
          };
          CircleBucket.prototype.addFeature = function addFeature2(feature, geometry, index, canonical) {
            for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) {
              var ring = list$1[i$1];
              for (var i = 0, list = ring; i < list.length; i += 1) {
                var point = list[i];
                var x = point.x;
                var y = point.y;
                if (x < 0 || x >= EXTENT$1 || y < 0 || y >= EXTENT$1) {
                  continue;
                }
                var segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey);
                var index$1 = segment.vertexLength;
                addCircleVertex(this.layoutVertexArray, x, y, -1, -1);
                addCircleVertex(this.layoutVertexArray, x, y, 1, -1);
                addCircleVertex(this.layoutVertexArray, x, y, 1, 1);
                addCircleVertex(this.layoutVertexArray, x, y, -1, 1);
                this.indexArray.emplaceBack(index$1, index$1 + 1, index$1 + 2);
                this.indexArray.emplaceBack(index$1, index$1 + 3, index$1 + 2);
                segment.vertexLength += 4;
                segment.primitiveLength += 2;
              }
            }
            this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, canonical);
          };
          register("CircleBucket", CircleBucket, { omit: ["layers"] });
          function polygonIntersectsPolygon(polygonA, polygonB) {
            for (var i = 0; i < polygonA.length; i++) {
              if (polygonContainsPoint(polygonB, polygonA[i])) {
                return true;
              }
            }
            for (var i$1 = 0; i$1 < polygonB.length; i$1++) {
              if (polygonContainsPoint(polygonA, polygonB[i$1])) {
                return true;
              }
            }
            if (lineIntersectsLine(polygonA, polygonB)) {
              return true;
            }
            return false;
          }
          function polygonIntersectsBufferedPoint(polygon, point, radius) {
            if (polygonContainsPoint(polygon, point)) {
              return true;
            }
            if (pointIntersectsBufferedLine(point, polygon, radius)) {
              return true;
            }
            return false;
          }
          function polygonIntersectsMultiPolygon(polygon, multiPolygon) {
            if (polygon.length === 1) {
              return multiPolygonContainsPoint(multiPolygon, polygon[0]);
            }
            for (var m = 0; m < multiPolygon.length; m++) {
              var ring = multiPolygon[m];
              for (var n = 0; n < ring.length; n++) {
                if (polygonContainsPoint(polygon, ring[n])) {
                  return true;
                }
              }
            }
            for (var i = 0; i < polygon.length; i++) {
              if (multiPolygonContainsPoint(multiPolygon, polygon[i])) {
                return true;
              }
            }
            for (var k = 0; k < multiPolygon.length; k++) {
              if (lineIntersectsLine(polygon, multiPolygon[k])) {
                return true;
              }
            }
            return false;
          }
          function polygonIntersectsBufferedMultiLine(polygon, multiLine, radius) {
            for (var i = 0; i < multiLine.length; i++) {
              var line = multiLine[i];
              if (polygon.length >= 3) {
                for (var k = 0; k < line.length; k++) {
                  if (polygonContainsPoint(polygon, line[k])) {
                    return true;
                  }
                }
              }
              if (lineIntersectsBufferedLine(polygon, line, radius)) {
                return true;
              }
            }
            return false;
          }
          function lineIntersectsBufferedLine(lineA, lineB, radius) {
            if (lineA.length > 1) {
              if (lineIntersectsLine(lineA, lineB)) {
                return true;
              }
              for (var j = 0; j < lineB.length; j++) {
                if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) {
                  return true;
                }
              }
            }
            for (var k = 0; k < lineA.length; k++) {
              if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) {
                return true;
              }
            }
            return false;
          }
          function lineIntersectsLine(lineA, lineB) {
            if (lineA.length === 0 || lineB.length === 0) {
              return false;
            }
            for (var i = 0; i < lineA.length - 1; i++) {
              var a0 = lineA[i];
              var a1 = lineA[i + 1];
              for (var j = 0; j < lineB.length - 1; j++) {
                var b0 = lineB[j];
                var b1 = lineB[j + 1];
                if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) {
                  return true;
                }
              }
            }
            return false;
          }
          function lineSegmentIntersectsLineSegment(a0, a1, b0, b1) {
            return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) && isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1);
          }
          function pointIntersectsBufferedLine(p, line, radius) {
            var radiusSquared = radius * radius;
            if (line.length === 1) {
              return p.distSqr(line[0]) < radiusSquared;
            }
            for (var i = 1; i < line.length; i++) {
              var v = line[i - 1], w = line[i];
              if (distToSegmentSquared(p, v, w) < radiusSquared) {
                return true;
              }
            }
            return false;
          }
          function distToSegmentSquared(p, v, w) {
            var l2 = v.distSqr(w);
            if (l2 === 0) {
              return p.distSqr(v);
            }
            var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
            if (t < 0) {
              return p.distSqr(v);
            }
            if (t > 1) {
              return p.distSqr(w);
            }
            return p.distSqr(w.sub(v)._mult(t)._add(v));
          }
          function multiPolygonContainsPoint(rings, p) {
            var c = false, ring, p1, p2;
            for (var k = 0; k < rings.length; k++) {
              ring = rings[k];
              for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
                p1 = ring[i];
                p2 = ring[j];
                if (p1.y > p.y !== p2.y > p.y && p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x) {
                  c = !c;
                }
              }
            }
            return c;
          }
          function polygonContainsPoint(ring, p) {
            var c = false;
            for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
              var p1 = ring[i];
              var p2 = ring[j];
              if (p1.y > p.y !== p2.y > p.y && p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x) {
                c = !c;
              }
            }
            return c;
          }
          function polygonIntersectsBox(ring, boxX1, boxY1, boxX2, boxY2) {
            for (var i$1 = 0, list = ring; i$1 < list.length; i$1 += 1) {
              var p = list[i$1];
              if (boxX1 <= p.x && boxY1 <= p.y && boxX2 >= p.x && boxY2 >= p.y) {
                return true;
              }
            }
            var corners = [
              new pointGeometry(boxX1, boxY1),
              new pointGeometry(boxX1, boxY2),
              new pointGeometry(boxX2, boxY2),
              new pointGeometry(boxX2, boxY1)
            ];
            if (ring.length > 2) {
              for (var i$2 = 0, list$1 = corners; i$2 < list$1.length; i$2 += 1) {
                var corner = list$1[i$2];
                if (polygonContainsPoint(ring, corner)) {
                  return true;
                }
              }
            }
            for (var i = 0; i < ring.length - 1; i++) {
              var p1 = ring[i];
              var p2 = ring[i + 1];
              if (edgeIntersectsBox(p1, p2, corners)) {
                return true;
              }
            }
            return false;
          }
          function edgeIntersectsBox(e1, e2, corners) {
            var tl = corners[0];
            var br = corners[2];
            if (e1.x < tl.x && e2.x < tl.x || e1.x > br.x && e2.x > br.x || e1.y < tl.y && e2.y < tl.y || e1.y > br.y && e2.y > br.y) {
              return false;
            }
            var dir = isCounterClockwise(e1, e2, corners[0]);
            return dir !== isCounterClockwise(e1, e2, corners[1]) || dir !== isCounterClockwise(e1, e2, corners[2]) || dir !== isCounterClockwise(e1, e2, corners[3]);
          }
          function getMaximumPaintValue(property, layer2, bucket) {
            var value = layer2.paint.get(property).value;
            if (value.kind === "constant") {
              return value.value;
            } else {
              return bucket.programConfigurations.get(layer2.id).getMaxValue(property);
            }
          }
          function translateDistance(translate2) {
            return Math.sqrt(translate2[0] * translate2[0] + translate2[1] * translate2[1]);
          }
          function translate(queryGeometry, translate2, translateAnchor, bearing, pixelsToTileUnits) {
            if (!translate2[0] && !translate2[1]) {
              return queryGeometry;
            }
            var pt = pointGeometry.convert(translate2)._mult(pixelsToTileUnits);
            if (translateAnchor === "viewport") {
              pt._rotate(-bearing);
            }
            var translated = [];
            for (var i = 0; i < queryGeometry.length; i++) {
              var point = queryGeometry[i];
              translated.push(point.sub(pt));
            }
            return translated;
          }
          var layout$2 = new Properties({ "circle-sort-key": new DataDrivenProperty(spec["layout_circle"]["circle-sort-key"]) });
          var paint$1 = new Properties({
            "circle-radius": new DataDrivenProperty(spec["paint_circle"]["circle-radius"]),
            "circle-color": new DataDrivenProperty(spec["paint_circle"]["circle-color"]),
            "circle-blur": new DataDrivenProperty(spec["paint_circle"]["circle-blur"]),
            "circle-opacity": new DataDrivenProperty(spec["paint_circle"]["circle-opacity"]),
            "circle-translate": new DataConstantProperty(spec["paint_circle"]["circle-translate"]),
            "circle-translate-anchor": new DataConstantProperty(spec["paint_circle"]["circle-translate-anchor"]),
            "circle-pitch-scale": new DataConstantProperty(spec["paint_circle"]["circle-pitch-scale"]),
            "circle-pitch-alignment": new DataConstantProperty(spec["paint_circle"]["circle-pitch-alignment"]),
            "circle-stroke-width": new DataDrivenProperty(spec["paint_circle"]["circle-stroke-width"]),
            "circle-stroke-color": new DataDrivenProperty(spec["paint_circle"]["circle-stroke-color"]),
            "circle-stroke-opacity": new DataDrivenProperty(spec["paint_circle"]["circle-stroke-opacity"])
          });
          var properties = {
            paint: paint$1,
            layout: layout$2
          };
          var ARRAY_TYPE = typeof Float32Array !== "undefined" ? Float32Array : Array;
          if (!Math.hypot) {
            Math.hypot = function() {
              var arguments$1 = arguments;
              var y = 0, i = arguments.length;
              while (i--) {
                y += arguments$1[i] * arguments$1[i];
              }
              return Math.sqrt(y);
            };
          }
          function create() {
            var out = new ARRAY_TYPE(4);
            if (ARRAY_TYPE != Float32Array) {
              out[1] = 0;
              out[2] = 0;
            }
            out[0] = 1;
            out[3] = 1;
            return out;
          }
          function rotate(out, a, rad) {
            var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
            var s = Math.sin(rad);
            var c = Math.cos(rad);
            out[0] = a0 * c + a2 * s;
            out[1] = a1 * c + a3 * s;
            out[2] = a0 * -s + a2 * c;
            out[3] = a1 * -s + a3 * c;
            return out;
          }
          function create$1() {
            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;
          }
          function fromRotation(out, rad) {
            var s = Math.sin(rad), c = Math.cos(rad);
            out[0] = c;
            out[1] = s;
            out[2] = 0;
            out[3] = -s;
            out[4] = c;
            out[5] = 0;
            out[6] = 0;
            out[7] = 0;
            out[8] = 1;
            return out;
          }
          function create$2() {
            var out = new ARRAY_TYPE(16);
            if (ARRAY_TYPE != Float32Array) {
              out[1] = 0;
              out[2] = 0;
              out[3] = 0;
              out[4] = 0;
              out[6] = 0;
              out[7] = 0;
              out[8] = 0;
              out[9] = 0;
              out[11] = 0;
              out[12] = 0;
              out[13] = 0;
              out[14] = 0;
            }
            out[0] = 1;
            out[5] = 1;
            out[10] = 1;
            out[15] = 1;
            return out;
          }
          function clone$1(a) {
            var out = new ARRAY_TYPE(16);
            out[0] = a[0];
            out[1] = a[1];
            out[2] = a[2];
            out[3] = a[3];
            out[4] = a[4];
            out[5] = a[5];
            out[6] = a[6];
            out[7] = a[7];
            out[8] = a[8];
            out[9] = a[9];
            out[10] = a[10];
            out[11] = a[11];
            out[12] = a[12];
            out[13] = a[13];
            out[14] = a[14];
            out[15] = a[15];
            return out;
          }
          function identity2(out) {
            out[0] = 1;
            out[1] = 0;
            out[2] = 0;
            out[3] = 0;
            out[4] = 0;
            out[5] = 1;
            out[6] = 0;
            out[7] = 0;
            out[8] = 0;
            out[9] = 0;
            out[10] = 1;
            out[11] = 0;
            out[12] = 0;
            out[13] = 0;
            out[14] = 0;
            out[15] = 1;
            return out;
          }
          function invert(out, a) {
            var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
            var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
            var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
            var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
            var b00 = a00 * a11 - a01 * a10;
            var b01 = a00 * a12 - a02 * a10;
            var b02 = a00 * a13 - a03 * a10;
            var b03 = a01 * a12 - a02 * a11;
            var b04 = a01 * a13 - a03 * a11;
            var b05 = a02 * a13 - a03 * a12;
            var b06 = a20 * a31 - a21 * a30;
            var b07 = a20 * a32 - a22 * a30;
            var b08 = a20 * a33 - a23 * a30;
            var b09 = a21 * a32 - a22 * a31;
            var b10 = a21 * a33 - a23 * a31;
            var b11 = a22 * a33 - a23 * a32;
            var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
            if (!det) {
              return null;
            }
            det = 1 / det;
            out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
            out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
            out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
            out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
            out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
            out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
            out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
            out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
            out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
            out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
            out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
            out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
            out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
            out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
            out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
            out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
            return out;
          }
          function multiply(out, a, b) {
            var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
            var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
            var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
            var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
            var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
            out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
            b0 = b[4];
            b1 = b[5];
            b2 = b[6];
            b3 = b[7];
            out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
            b0 = b[8];
            b1 = b[9];
            b2 = b[10];
            b3 = b[11];
            out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
            b0 = b[12];
            b1 = b[13];
            b2 = b[14];
            b3 = b[15];
            out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
            out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
            out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
            out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
            return out;
          }
          function translate$1(out, a, v) {
            var x = v[0], y = v[1], z = v[2];
            var a00, a01, a02, a03;
            var a10, a11, a12, a13;
            var a20, a21, a22, a23;
            if (a === out) {
              out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
              out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
              out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
              out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
            } else {
              a00 = a[0];
              a01 = a[1];
              a02 = a[2];
              a03 = a[3];
              a10 = a[4];
              a11 = a[5];
              a12 = a[6];
              a13 = a[7];
              a20 = a[8];
              a21 = a[9];
              a22 = a[10];
              a23 = a[11];
              out[0] = a00;
              out[1] = a01;
              out[2] = a02;
              out[3] = a03;
              out[4] = a10;
              out[5] = a11;
              out[6] = a12;
              out[7] = a13;
              out[8] = a20;
              out[9] = a21;
              out[10] = a22;
              out[11] = a23;
              out[12] = a00 * x + a10 * y + a20 * z + a[12];
              out[13] = a01 * x + a11 * y + a21 * z + a[13];
              out[14] = a02 * x + a12 * y + a22 * z + a[14];
              out[15] = a03 * x + a13 * y + a23 * z + a[15];
            }
            return out;
          }
          function scale(out, a, v) {
            var x = v[0], y = v[1], z = v[2];
            out[0] = a[0] * x;
            out[1] = a[1] * x;
            out[2] = a[2] * x;
            out[3] = a[3] * x;
            out[4] = a[4] * y;
            out[5] = a[5] * y;
            out[6] = a[6] * y;
            out[7] = a[7] * y;
            out[8] = a[8] * z;
            out[9] = a[9] * z;
            out[10] = a[10] * z;
            out[11] = a[11] * z;
            out[12] = a[12];
            out[13] = a[13];
            out[14] = a[14];
            out[15] = a[15];
            return out;
          }
          function rotateX(out, a, rad) {
            var s = Math.sin(rad);
            var c = Math.cos(rad);
            var a10 = a[4];
            var a11 = a[5];
            var a12 = a[6];
            var a13 = a[7];
            var a20 = a[8];
            var a21 = a[9];
            var a22 = a[10];
            var a23 = a[11];
            if (a !== out) {
              out[0] = a[0];
              out[1] = a[1];
              out[2] = a[2];
              out[3] = a[3];
              out[12] = a[12];
              out[13] = a[13];
              out[14] = a[14];
              out[15] = a[15];
            }
            out[4] = a10 * c + a20 * s;
            out[5] = a11 * c + a21 * s;
            out[6] = a12 * c + a22 * s;
            out[7] = a13 * c + a23 * s;
            out[8] = a20 * c - a10 * s;
            out[9] = a21 * c - a11 * s;
            out[10] = a22 * c - a12 * s;
            out[11] = a23 * c - a13 * s;
            return out;
          }
          function rotateZ(out, a, rad) {
            var s = Math.sin(rad);
            var c = Math.cos(rad);
            var a00 = a[0];
            var a01 = a[1];
            var a02 = a[2];
            var a03 = a[3];
            var a10 = a[4];
            var a11 = a[5];
            var a12 = a[6];
            var a13 = a[7];
            if (a !== out) {
              out[8] = a[8];
              out[9] = a[9];
              out[10] = a[10];
              out[11] = a[11];
              out[12] = a[12];
              out[13] = a[13];
              out[14] = a[14];
              out[15] = a[15];
            }
            out[0] = a00 * c + a10 * s;
            out[1] = a01 * c + a11 * s;
            out[2] = a02 * c + a12 * s;
            out[3] = a03 * c + a13 * s;
            out[4] = a10 * c - a00 * s;
            out[5] = a11 * c - a01 * s;
            out[6] = a12 * c - a02 * s;
            out[7] = a13 * c - a03 * s;
            return out;
          }
          function perspective(out, fovy, aspect, near, far) {
            var f = 1 / Math.tan(fovy / 2), nf;
            out[0] = f / aspect;
            out[1] = 0;
            out[2] = 0;
            out[3] = 0;
            out[4] = 0;
            out[5] = f;
            out[6] = 0;
            out[7] = 0;
            out[8] = 0;
            out[9] = 0;
            out[11] = -1;
            out[12] = 0;
            out[13] = 0;
            out[15] = 0;
            if (far != null && far !== Infinity) {
              nf = 1 / (near - far);
              out[10] = (far + near) * nf;
              out[14] = 2 * far * near * nf;
            } else {
              out[10] = -1;
              out[14] = -2 * near;
            }
            return out;
          }
          function ortho(out, left, right, bottom, top, near, far) {
            var lr = 1 / (left - right);
            var bt = 1 / (bottom - top);
            var nf = 1 / (near - far);
            out[0] = -2 * lr;
            out[1] = 0;
            out[2] = 0;
            out[3] = 0;
            out[4] = 0;
            out[5] = -2 * bt;
            out[6] = 0;
            out[7] = 0;
            out[8] = 0;
            out[9] = 0;
            out[10] = 2 * nf;
            out[11] = 0;
            out[12] = (left + right) * lr;
            out[13] = (top + bottom) * bt;
            out[14] = (far + near) * nf;
            out[15] = 1;
            return out;
          }
          var mul = multiply;
          function create$3() {
            var out = new ARRAY_TYPE(3);
            if (ARRAY_TYPE != Float32Array) {
              out[0] = 0;
              out[1] = 0;
              out[2] = 0;
            }
            return out;
          }
          function clone$2(a) {
            var out = new ARRAY_TYPE(3);
            out[0] = a[0];
            out[1] = a[1];
            out[2] = a[2];
            return out;
          }
          function add(out, a, b) {
            out[0] = a[0] + b[0];
            out[1] = a[1] + b[1];
            out[2] = a[2] + b[2];
            return out;
          }
          function subtract(out, a, b) {
            out[0] = a[0] - b[0];
            out[1] = a[1] - b[1];
            out[2] = a[2] - b[2];
            return out;
          }
          function scale$1(out, a, b) {
            out[0] = a[0] * b;
            out[1] = a[1] * b;
            out[2] = a[2] * b;
            return out;
          }
          function normalize(out, a) {
            var x = a[0];
            var y = a[1];
            var z = a[2];
            var len = x * x + y * y + z * z;
            if (len > 0) {
              len = 1 / Math.sqrt(len);
            }
            out[0] = a[0] * len;
            out[1] = a[1] * len;
            out[2] = a[2] * len;
            return out;
          }
          function dot(a, b) {
            return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
          }
          function cross(out, a, b) {
            var ax = a[0], ay = a[1], az = a[2];
            var bx = b[0], by = b[1], bz = b[2];
            out[0] = ay * bz - az * by;
            out[1] = az * bx - ax * bz;
            out[2] = ax * by - ay * bx;
            return out;
          }
          function transformMat3(out, a, m) {
            var x = a[0], y = a[1], z = a[2];
            out[0] = x * m[0] + y * m[3] + z * m[6];
            out[1] = x * m[1] + y * m[4] + z * m[7];
            out[2] = x * m[2] + y * m[5] + z * m[8];
            return out;
          }
          var sub = subtract;
          var forEach = function() {
            var vec = create$3();
            return function(a, stride, offset, count, fn, arg) {
              var i, l;
              if (!stride) {
                stride = 3;
              }
              if (!offset) {
                offset = 0;
              }
              if (count) {
                l = Math.min(count * stride + offset, a.length);
              } else {
                l = a.length;
              }
              for (i = offset; i < l; i += stride) {
                vec[0] = a[i];
                vec[1] = a[i + 1];
                vec[2] = a[i + 2];
                fn(vec, vec, arg);
                a[i] = vec[0];
                a[i + 1] = vec[1];
                a[i + 2] = vec[2];
              }
              return a;
            };
          }();
          function create$4() {
            var out = new ARRAY_TYPE(4);
            if (ARRAY_TYPE != Float32Array) {
              out[0] = 0;
              out[1] = 0;
              out[2] = 0;
              out[3] = 0;
            }
            return out;
          }
          function scale$2(out, a, b) {
            out[0] = a[0] * b;
            out[1] = a[1] * b;
            out[2] = a[2] * b;
            out[3] = a[3] * b;
            return out;
          }
          function dot$1(a, b) {
            return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
          }
          function transformMat4(out, a, m) {
            var x = a[0], y = a[1], z = a[2], w = a[3];
            out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
            out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
            out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
            out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
            return out;
          }
          var forEach$1 = function() {
            var vec = create$4();
            return function(a, stride, offset, count, fn, arg) {
              var i, l;
              if (!stride) {
                stride = 4;
              }
              if (!offset) {
                offset = 0;
              }
              if (count) {
                l = Math.min(count * stride + offset, a.length);
              } else {
                l = a.length;
              }
              for (i = offset; i < l; i += stride) {
                vec[0] = a[i];
                vec[1] = a[i + 1];
                vec[2] = a[i + 2];
                vec[3] = a[i + 3];
                fn(vec, vec, arg);
                a[i] = vec[0];
                a[i + 1] = vec[1];
                a[i + 2] = vec[2];
                a[i + 3] = vec[3];
              }
              return a;
            };
          }();
          function create$5() {
            var out = new ARRAY_TYPE(2);
            if (ARRAY_TYPE != Float32Array) {
              out[0] = 0;
              out[1] = 0;
            }
            return out;
          }
          function squaredLength(a) {
            var x = a[0], y = a[1];
            return x * x + y * y;
          }
          var sqrLen = squaredLength;
          var forEach$2 = function() {
            var vec = create$5();
            return function(a, stride, offset, count, fn, arg) {
              var i, l;
              if (!stride) {
                stride = 2;
              }
              if (!offset) {
                offset = 0;
              }
              if (count) {
                l = Math.min(count * stride + offset, a.length);
              } else {
                l = a.length;
              }
              for (i = offset; i < l; i += stride) {
                vec[0] = a[i];
                vec[1] = a[i + 1];
                fn(vec, vec, arg);
                a[i] = vec[0];
                a[i + 1] = vec[1];
              }
              return a;
            };
          }();
          var CircleStyleLayer = function(StyleLayer2) {
            function CircleStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties);
            }
            if (StyleLayer2)
              CircleStyleLayer2.__proto__ = StyleLayer2;
            CircleStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            CircleStyleLayer2.prototype.constructor = CircleStyleLayer2;
            CircleStyleLayer2.prototype.createBucket = function createBucket(parameters) {
              return new CircleBucket(parameters);
            };
            CircleStyleLayer2.prototype.queryRadius = function queryRadius(bucket) {
              var circleBucket = bucket;
              return getMaximumPaintValue("circle-radius", this, circleBucket) + getMaximumPaintValue("circle-stroke-width", this, circleBucket) + translateDistance(this.paint.get("circle-translate"));
            };
            CircleStyleLayer2.prototype.queryIntersectsFeature = function queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) {
              var translatedPolygon = translate(queryGeometry, this.paint.get("circle-translate"), this.paint.get("circle-translate-anchor"), transform.angle, pixelsToTileUnits);
              var radius = this.paint.get("circle-radius").evaluate(feature, featureState);
              var stroke = this.paint.get("circle-stroke-width").evaluate(feature, featureState);
              var size = radius + stroke;
              var alignWithMap = this.paint.get("circle-pitch-alignment") === "map";
              var transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry(translatedPolygon, pixelPosMatrix);
              var transformedSize = alignWithMap ? size * pixelsToTileUnits : size;
              for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) {
                var ring = list$1[i$1];
                for (var i = 0, list = ring; i < list.length; i += 1) {
                  var point = list[i];
                  var transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix);
                  var adjustedSize = transformedSize;
                  var projectedCenter = transformMat4([], [
                    point.x,
                    point.y,
                    0,
                    1
                  ], pixelPosMatrix);
                  if (this.paint.get("circle-pitch-scale") === "viewport" && this.paint.get("circle-pitch-alignment") === "map") {
                    adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance;
                  } else if (this.paint.get("circle-pitch-scale") === "map" && this.paint.get("circle-pitch-alignment") === "viewport") {
                    adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3];
                  }
                  if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) {
                    return true;
                  }
                }
              }
              return false;
            };
            return CircleStyleLayer2;
          }(StyleLayer);
          function projectPoint(p, pixelPosMatrix) {
            var point = transformMat4([], [
              p.x,
              p.y,
              0,
              1
            ], pixelPosMatrix);
            return new pointGeometry(point[0] / point[3], point[1] / point[3]);
          }
          function projectQueryGeometry(queryGeometry, pixelPosMatrix) {
            return queryGeometry.map(function(p) {
              return projectPoint(p, pixelPosMatrix);
            });
          }
          var HeatmapBucket = function(CircleBucket2) {
            function HeatmapBucket2() {
              CircleBucket2.apply(this, arguments);
            }
            if (CircleBucket2)
              HeatmapBucket2.__proto__ = CircleBucket2;
            HeatmapBucket2.prototype = Object.create(CircleBucket2 && CircleBucket2.prototype);
            HeatmapBucket2.prototype.constructor = HeatmapBucket2;
            return HeatmapBucket2;
          }(CircleBucket);
          register("HeatmapBucket", HeatmapBucket, { omit: ["layers"] });
          function createImage(image, ref, channels, data) {
            var width = ref.width;
            var height = ref.height;
            if (!data) {
              data = new Uint8Array(width * height * channels);
            } else if (data instanceof Uint8ClampedArray) {
              data = new Uint8Array(data.buffer);
            } else if (data.length !== width * height * channels) {
              throw new RangeError("mismatched image size");
            }
            image.width = width;
            image.height = height;
            image.data = data;
            return image;
          }
          function resizeImage(image, ref, channels) {
            var width = ref.width;
            var height = ref.height;
            if (width === image.width && height === image.height) {
              return;
            }
            var newImage = createImage({}, {
              width,
              height
            }, channels);
            copyImage(image, newImage, {
              x: 0,
              y: 0
            }, {
              x: 0,
              y: 0
            }, {
              width: Math.min(image.width, width),
              height: Math.min(image.height, height)
            }, channels);
            image.width = width;
            image.height = height;
            image.data = newImage.data;
          }
          function copyImage(srcImg, dstImg, srcPt, dstPt, size, channels) {
            if (size.width === 0 || size.height === 0) {
              return dstImg;
            }
            if (size.width > srcImg.width || size.height > srcImg.height || srcPt.x > srcImg.width - size.width || srcPt.y > srcImg.height - size.height) {
              throw new RangeError("out of range source coordinates for image copy");
            }
            if (size.width > dstImg.width || size.height > dstImg.height || dstPt.x > dstImg.width - size.width || dstPt.y > dstImg.height - size.height) {
              throw new RangeError("out of range destination coordinates for image copy");
            }
            var srcData = srcImg.data;
            var dstData = dstImg.data;
            for (var y = 0; y < size.height; y++) {
              var srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels;
              var dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels;
              for (var i = 0; i < size.width * channels; i++) {
                dstData[dstOffset + i] = srcData[srcOffset + i];
              }
            }
            return dstImg;
          }
          var AlphaImage = function AlphaImage2(size, data) {
            createImage(this, size, 1, data);
          };
          AlphaImage.prototype.resize = function resize(size) {
            resizeImage(this, size, 1);
          };
          AlphaImage.prototype.clone = function clone2() {
            return new AlphaImage({
              width: this.width,
              height: this.height
            }, new Uint8Array(this.data));
          };
          AlphaImage.copy = function copy(srcImg, dstImg, srcPt, dstPt, size) {
            copyImage(srcImg, dstImg, srcPt, dstPt, size, 1);
          };
          var RGBAImage = function RGBAImage2(size, data) {
            createImage(this, size, 4, data);
          };
          RGBAImage.prototype.resize = function resize(size) {
            resizeImage(this, size, 4);
          };
          RGBAImage.prototype.replace = function replace(data, copy) {
            if (copy) {
              this.data.set(data);
            } else if (data instanceof Uint8ClampedArray) {
              this.data = new Uint8Array(data.buffer);
            } else {
              this.data = data;
            }
          };
          RGBAImage.prototype.clone = function clone2() {
            return new RGBAImage({
              width: this.width,
              height: this.height
            }, new Uint8Array(this.data));
          };
          RGBAImage.copy = function copy(srcImg, dstImg, srcPt, dstPt, size) {
            copyImage(srcImg, dstImg, srcPt, dstPt, size, 4);
          };
          register("AlphaImage", AlphaImage);
          register("RGBAImage", RGBAImage);
          var paint$2 = new Properties({
            "heatmap-radius": new DataDrivenProperty(spec["paint_heatmap"]["heatmap-radius"]),
            "heatmap-weight": new DataDrivenProperty(spec["paint_heatmap"]["heatmap-weight"]),
            "heatmap-intensity": new DataConstantProperty(spec["paint_heatmap"]["heatmap-intensity"]),
            "heatmap-color": new ColorRampProperty(spec["paint_heatmap"]["heatmap-color"]),
            "heatmap-opacity": new DataConstantProperty(spec["paint_heatmap"]["heatmap-opacity"])
          });
          var properties$1 = { paint: paint$2 };
          function renderColorRamp(params) {
            var evaluationGlobals = {};
            var width = params.resolution || 256;
            var height = params.clips ? params.clips.length : 1;
            var image = params.image || new RGBAImage({
              width,
              height
            });
            var renderPixel = function(stride2, index, progress2) {
              evaluationGlobals[params.evaluationKey] = progress2;
              var pxColor = params.expression.evaluate(evaluationGlobals);
              image.data[stride2 + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a);
              image.data[stride2 + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a);
              image.data[stride2 + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a);
              image.data[stride2 + index + 3] = Math.floor(pxColor.a * 255);
            };
            if (!params.clips) {
              for (var i = 0, j = 0; i < width; i++, j += 4) {
                var progress = i / (width - 1);
                renderPixel(0, j, progress);
              }
            } else {
              for (var clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) {
                for (var i$1 = 0, j$1 = 0; i$1 < width; i$1++, j$1 += 4) {
                  var progress$1 = i$1 / (width - 1);
                  var ref = params.clips[clip];
                  var start = ref.start;
                  var end = ref.end;
                  var evaluationProgress = start * (1 - progress$1) + end * progress$1;
                  renderPixel(stride, j$1, evaluationProgress);
                }
              }
            }
            return image;
          }
          var HeatmapStyleLayer = function(StyleLayer2) {
            function HeatmapStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$1);
              this._updateColorRamp();
            }
            if (StyleLayer2)
              HeatmapStyleLayer2.__proto__ = StyleLayer2;
            HeatmapStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            HeatmapStyleLayer2.prototype.constructor = HeatmapStyleLayer2;
            HeatmapStyleLayer2.prototype.createBucket = function createBucket(options) {
              return new HeatmapBucket(options);
            };
            HeatmapStyleLayer2.prototype._handleSpecialPaintPropertyUpdate = function _handleSpecialPaintPropertyUpdate(name3) {
              if (name3 === "heatmap-color") {
                this._updateColorRamp();
              }
            };
            HeatmapStyleLayer2.prototype._updateColorRamp = function _updateColorRamp() {
              var expression2 = this._transitionablePaint._values["heatmap-color"].value.expression;
              this.colorRamp = renderColorRamp({
                expression: expression2,
                evaluationKey: "heatmapDensity",
                image: this.colorRamp
              });
              this.colorRampTexture = null;
            };
            HeatmapStyleLayer2.prototype.resize = function resize() {
              if (this.heatmapFbo) {
                this.heatmapFbo.destroy();
                this.heatmapFbo = null;
              }
            };
            HeatmapStyleLayer2.prototype.queryRadius = function queryRadius() {
              return 0;
            };
            HeatmapStyleLayer2.prototype.queryIntersectsFeature = function queryIntersectsFeature() {
              return false;
            };
            HeatmapStyleLayer2.prototype.hasOffscreenPass = function hasOffscreenPass() {
              return this.paint.get("heatmap-opacity") !== 0 && this.visibility !== "none";
            };
            return HeatmapStyleLayer2;
          }(StyleLayer);
          var paint$3 = new Properties({
            "hillshade-illumination-direction": new DataConstantProperty(spec["paint_hillshade"]["hillshade-illumination-direction"]),
            "hillshade-illumination-anchor": new DataConstantProperty(spec["paint_hillshade"]["hillshade-illumination-anchor"]),
            "hillshade-exaggeration": new DataConstantProperty(spec["paint_hillshade"]["hillshade-exaggeration"]),
            "hillshade-shadow-color": new DataConstantProperty(spec["paint_hillshade"]["hillshade-shadow-color"]),
            "hillshade-highlight-color": new DataConstantProperty(spec["paint_hillshade"]["hillshade-highlight-color"]),
            "hillshade-accent-color": new DataConstantProperty(spec["paint_hillshade"]["hillshade-accent-color"])
          });
          var properties$2 = { paint: paint$3 };
          var HillshadeStyleLayer = function(StyleLayer2) {
            function HillshadeStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$2);
            }
            if (StyleLayer2)
              HillshadeStyleLayer2.__proto__ = StyleLayer2;
            HillshadeStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            HillshadeStyleLayer2.prototype.constructor = HillshadeStyleLayer2;
            HillshadeStyleLayer2.prototype.hasOffscreenPass = function hasOffscreenPass() {
              return this.paint.get("hillshade-exaggeration") !== 0 && this.visibility !== "none";
            };
            return HillshadeStyleLayer2;
          }(StyleLayer);
          var layout$3 = createLayout([{
            name: "a_pos",
            components: 2,
            type: "Int16"
          }], 4);
          var members$1 = layout$3.members;
          var earcut_1 = earcut;
          var default_1 = earcut;
          function earcut(data, holeIndices, dim) {
            dim = dim || 2;
            var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
            if (!outerNode || outerNode.next === outerNode.prev) {
              return triangles;
            }
            var minX, minY, maxX, maxY, x, y, invSize;
            if (hasHoles) {
              outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
            }
            if (data.length > 80 * dim) {
              minX = maxX = data[0];
              minY = maxY = data[1];
              for (var i = dim; i < outerLen; i += dim) {
                x = data[i];
                y = data[i + 1];
                if (x < minX) {
                  minX = x;
                }
                if (y < minY) {
                  minY = y;
                }
                if (x > maxX) {
                  maxX = x;
                }
                if (y > maxY) {
                  maxY = y;
                }
              }
              invSize = Math.max(maxX - minX, maxY - minY);
              invSize = invSize !== 0 ? 1 / invSize : 0;
            }
            earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
            return triangles;
          }
          function linkedList(data, start, end, dim, clockwise) {
            var i, last;
            if (clockwise === signedArea(data, start, end, dim) > 0) {
              for (i = start; i < end; i += dim) {
                last = insertNode(i, data[i], data[i + 1], last);
              }
            } else {
              for (i = end - dim; i >= start; i -= dim) {
                last = insertNode(i, data[i], data[i + 1], last);
              }
            }
            if (last && equals(last, last.next)) {
              removeNode(last);
              last = last.next;
            }
            return last;
          }
          function filterPoints(start, end) {
            if (!start) {
              return start;
            }
            if (!end) {
              end = start;
            }
            var p = start, again;
            do {
              again = false;
              if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
                removeNode(p);
                p = end = p.prev;
                if (p === p.next) {
                  break;
                }
                again = true;
              } else {
                p = p.next;
              }
            } while (again || p !== end);
            return end;
          }
          function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
            if (!ear) {
              return;
            }
            if (!pass && invSize) {
              indexCurve(ear, minX, minY, invSize);
            }
            var stop = ear, prev, next;
            while (ear.prev !== ear.next) {
              prev = ear.prev;
              next = ear.next;
              if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
                triangles.push(prev.i / dim);
                triangles.push(ear.i / dim);
                triangles.push(next.i / dim);
                removeNode(ear);
                ear = next.next;
                stop = next.next;
                continue;
              }
              ear = next;
              if (ear === stop) {
                if (!pass) {
                  earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
                } else if (pass === 1) {
                  ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
                  earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
                } else if (pass === 2) {
                  splitEarcut(ear, triangles, dim, minX, minY, invSize);
                }
                break;
              }
            }
          }
          function isEar(ear) {
            var a = ear.prev, b = ear, c = ear.next;
            if (area(a, b, c) >= 0) {
              return false;
            }
            var p = ear.next.next;
            while (p !== ear.prev) {
              if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                return false;
              }
              p = p.next;
            }
            return true;
          }
          function isEarHashed(ear, minX, minY, invSize) {
            var a = ear.prev, b = ear, c = ear.next;
            if (area(a, b, c) >= 0) {
              return false;
            }
            var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x, minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y, maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x, maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y;
            var minZ = zOrder(minTX, minTY, minX, minY, invSize), maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
            var p = ear.prevZ, n = ear.nextZ;
            while (p && p.z >= minZ && n && n.z <= maxZ) {
              if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                return false;
              }
              p = p.prevZ;
              if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) {
                return false;
              }
              n = n.nextZ;
            }
            while (p && p.z >= minZ) {
              if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                return false;
              }
              p = p.prevZ;
            }
            while (n && n.z <= maxZ) {
              if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) {
                return false;
              }
              n = n.nextZ;
            }
            return true;
          }
          function cureLocalIntersections(start, triangles, dim) {
            var p = start;
            do {
              var a = p.prev, b = p.next.next;
              if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
                triangles.push(a.i / dim);
                triangles.push(p.i / dim);
                triangles.push(b.i / dim);
                removeNode(p);
                removeNode(p.next);
                p = start = b;
              }
              p = p.next;
            } while (p !== start);
            return filterPoints(p);
          }
          function splitEarcut(start, triangles, dim, minX, minY, invSize) {
            var a = start;
            do {
              var b = a.next.next;
              while (b !== a.prev) {
                if (a.i !== b.i && isValidDiagonal(a, b)) {
                  var c = splitPolygon(a, b);
                  a = filterPoints(a, a.next);
                  c = filterPoints(c, c.next);
                  earcutLinked(a, triangles, dim, minX, minY, invSize);
                  earcutLinked(c, triangles, dim, minX, minY, invSize);
                  return;
                }
                b = b.next;
              }
              a = a.next;
            } while (a !== start);
          }
          function eliminateHoles(data, holeIndices, outerNode, dim) {
            var queue = [], i, len, start, end, list;
            for (i = 0, len = holeIndices.length; i < len; i++) {
              start = holeIndices[i] * dim;
              end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
              list = linkedList(data, start, end, dim, false);
              if (list === list.next) {
                list.steiner = true;
              }
              queue.push(getLeftmost(list));
            }
            queue.sort(compareX);
            for (i = 0; i < queue.length; i++) {
              eliminateHole(queue[i], outerNode);
              outerNode = filterPoints(outerNode, outerNode.next);
            }
            return outerNode;
          }
          function compareX(a, b) {
            return a.x - b.x;
          }
          function eliminateHole(hole, outerNode) {
            outerNode = findHoleBridge(hole, outerNode);
            if (outerNode) {
              var b = splitPolygon(outerNode, hole);
              filterPoints(outerNode, outerNode.next);
              filterPoints(b, b.next);
            }
          }
          function findHoleBridge(hole, outerNode) {
            var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
            do {
              if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
                var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
                if (x <= hx && x > qx) {
                  qx = x;
                  if (x === hx) {
                    if (hy === p.y) {
                      return p;
                    }
                    if (hy === p.next.y) {
                      return p.next;
                    }
                  }
                  m = p.x < p.next.x ? p : p.next;
                }
              }
              p = p.next;
            } while (p !== outerNode);
            if (!m) {
              return null;
            }
            if (hx === qx) {
              return m;
            }
            var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
            p = m;
            do {
              if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
                tan = Math.abs(hy - p.y) / (hx - p.x);
                if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
                  m = p;
                  tanMin = tan;
                }
              }
              p = p.next;
            } while (p !== stop);
            return m;
          }
          function sectorContainsSector(m, p) {
            return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
          }
          function indexCurve(start, minX, minY, invSize) {
            var p = start;
            do {
              if (p.z === null) {
                p.z = zOrder(p.x, p.y, minX, minY, invSize);
              }
              p.prevZ = p.prev;
              p.nextZ = p.next;
              p = p.next;
            } while (p !== start);
            p.prevZ.nextZ = null;
            p.prevZ = null;
            sortLinked(p);
          }
          function sortLinked(list) {
            var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
            do {
              p = list;
              list = null;
              tail = null;
              numMerges = 0;
              while (p) {
                numMerges++;
                q = p;
                pSize = 0;
                for (i = 0; i < inSize; i++) {
                  pSize++;
                  q = q.nextZ;
                  if (!q) {
                    break;
                  }
                }
                qSize = inSize;
                while (pSize > 0 || qSize > 0 && q) {
                  if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
                    e = p;
                    p = p.nextZ;
                    pSize--;
                  } else {
                    e = q;
                    q = q.nextZ;
                    qSize--;
                  }
                  if (tail) {
                    tail.nextZ = e;
                  } else {
                    list = e;
                  }
                  e.prevZ = tail;
                  tail = e;
                }
                p = q;
              }
              tail.nextZ = null;
              inSize *= 2;
            } while (numMerges > 1);
            return list;
          }
          function zOrder(x, y, minX, minY, invSize) {
            x = 32767 * (x - minX) * invSize;
            y = 32767 * (y - minY) * invSize;
            x = (x | x << 8) & 16711935;
            x = (x | x << 4) & 252645135;
            x = (x | x << 2) & 858993459;
            x = (x | x << 1) & 1431655765;
            y = (y | y << 8) & 16711935;
            y = (y | y << 4) & 252645135;
            y = (y | y << 2) & 858993459;
            y = (y | y << 1) & 1431655765;
            return x | y << 1;
          }
          function getLeftmost(start) {
            var p = start, leftmost = start;
            do {
              if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) {
                leftmost = p;
              }
              p = p.next;
            } while (p !== start);
            return leftmost;
          }
          function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
            return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
          }
          function isValidDiagonal(a, b) {
            return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0);
          }
          function area(p, q, r) {
            return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
          }
          function equals(p1, p2) {
            return p1.x === p2.x && p1.y === p2.y;
          }
          function intersects(p1, q1, p2, q2) {
            var o1 = sign(area(p1, q1, p2));
            var o2 = sign(area(p1, q1, q2));
            var o3 = sign(area(p2, q2, p1));
            var o4 = sign(area(p2, q2, q1));
            if (o1 !== o2 && o3 !== o4) {
              return true;
            }
            if (o1 === 0 && onSegment(p1, p2, q1)) {
              return true;
            }
            if (o2 === 0 && onSegment(p1, q2, q1)) {
              return true;
            }
            if (o3 === 0 && onSegment(p2, p1, q2)) {
              return true;
            }
            if (o4 === 0 && onSegment(p2, q1, q2)) {
              return true;
            }
            return false;
          }
          function onSegment(p, q, r) {
            return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
          }
          function sign(num) {
            return num > 0 ? 1 : num < 0 ? -1 : 0;
          }
          function intersectsPolygon(a, b) {
            var p = a;
            do {
              if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) {
                return true;
              }
              p = p.next;
            } while (p !== a);
            return false;
          }
          function locallyInside(a, b) {
            return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
          }
          function middleInside(a, b) {
            var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
            do {
              if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) {
                inside = !inside;
              }
              p = p.next;
            } while (p !== a);
            return inside;
          }
          function splitPolygon(a, b) {
            var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
            a.next = b;
            b.prev = a;
            a2.next = an;
            an.prev = a2;
            b2.next = a2;
            a2.prev = b2;
            bp.next = b2;
            b2.prev = bp;
            return b2;
          }
          function insertNode(i, x, y, last) {
            var p = new Node(i, x, y);
            if (!last) {
              p.prev = p;
              p.next = p;
            } else {
              p.next = last.next;
              p.prev = last;
              last.next.prev = p;
              last.next = p;
            }
            return p;
          }
          function removeNode(p) {
            p.next.prev = p.prev;
            p.prev.next = p.next;
            if (p.prevZ) {
              p.prevZ.nextZ = p.nextZ;
            }
            if (p.nextZ) {
              p.nextZ.prevZ = p.prevZ;
            }
          }
          function Node(i, x, y) {
            this.i = i;
            this.x = x;
            this.y = y;
            this.prev = null;
            this.next = null;
            this.z = null;
            this.prevZ = null;
            this.nextZ = null;
            this.steiner = false;
          }
          earcut.deviation = function(data, holeIndices, dim, triangles) {
            var hasHoles = holeIndices && holeIndices.length;
            var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
            var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
            if (hasHoles) {
              for (var i = 0, len = holeIndices.length; i < len; i++) {
                var start = holeIndices[i] * dim;
                var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
                polygonArea -= Math.abs(signedArea(data, start, end, dim));
              }
            }
            var trianglesArea = 0;
            for (i = 0; i < triangles.length; i += 3) {
              var a = triangles[i] * dim;
              var b = triangles[i + 1] * dim;
              var c = triangles[i + 2] * dim;
              trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
            }
            return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
          };
          function signedArea(data, start, end, dim) {
            var sum = 0;
            for (var i = start, j = end - dim; i < end; i += dim) {
              sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
              j = i;
            }
            return sum;
          }
          earcut.flatten = function(data) {
            var dim = data[0][0].length, result = {
              vertices: [],
              holes: [],
              dimensions: dim
            }, holeIndex = 0;
            for (var i = 0; i < data.length; i++) {
              for (var j = 0; j < data[i].length; j++) {
                for (var d = 0; d < dim; d++) {
                  result.vertices.push(data[i][j][d]);
                }
              }
              if (i > 0) {
                holeIndex += data[i - 1].length;
                result.holes.push(holeIndex);
              }
            }
            return result;
          };
          earcut_1.default = default_1;
          function quickselect(arr, k, left, right, compare2) {
            quickselectStep(arr, k, left || 0, right || arr.length - 1, compare2 || defaultCompare);
          }
          function quickselectStep(arr, k, left, right, compare2) {
            while (right > left) {
              if (right - left > 600) {
                var n = right - left + 1;
                var m = k - left + 1;
                var z = Math.log(n);
                var s = 0.5 * Math.exp(2 * z / 3);
                var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
                var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
                var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
                quickselectStep(arr, k, newLeft, newRight, compare2);
              }
              var t = arr[k];
              var i = left;
              var j = right;
              swap$1(arr, left, k);
              if (compare2(arr[right], t) > 0) {
                swap$1(arr, left, right);
              }
              while (i < j) {
                swap$1(arr, i, j);
                i++;
                j--;
                while (compare2(arr[i], t) < 0) {
                  i++;
                }
                while (compare2(arr[j], t) > 0) {
                  j--;
                }
              }
              if (compare2(arr[left], t) === 0) {
                swap$1(arr, left, j);
              } else {
                j++;
                swap$1(arr, j, right);
              }
              if (j <= k) {
                left = j + 1;
              }
              if (k <= j) {
                right = j - 1;
              }
            }
          }
          function swap$1(arr, i, j) {
            var tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
          }
          function defaultCompare(a, b) {
            return a < b ? -1 : a > b ? 1 : 0;
          }
          function classifyRings(rings, maxRings) {
            var len = rings.length;
            if (len <= 1) {
              return [rings];
            }
            var polygons = [];
            var polygon, ccw;
            for (var i = 0; i < len; i++) {
              var area2 = calculateSignedArea(rings[i]);
              if (area2 === 0) {
                continue;
              }
              rings[i].area = Math.abs(area2);
              if (ccw === void 0) {
                ccw = area2 < 0;
              }
              if (ccw === area2 < 0) {
                if (polygon) {
                  polygons.push(polygon);
                }
                polygon = [rings[i]];
              } else {
                polygon.push(rings[i]);
              }
            }
            if (polygon) {
              polygons.push(polygon);
            }
            if (maxRings > 1) {
              for (var j = 0; j < polygons.length; j++) {
                if (polygons[j].length <= maxRings) {
                  continue;
                }
                quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas);
                polygons[j] = polygons[j].slice(0, maxRings);
              }
            }
            return polygons;
          }
          function compareAreas(a, b) {
            return b.area - a.area;
          }
          function hasPattern(type, layers, options) {
            var patterns = options.patternDependencies;
            var hasPattern2 = false;
            for (var i = 0, list = layers; i < list.length; i += 1) {
              var layer2 = list[i];
              var patternProperty = layer2.paint.get(type + "-pattern");
              if (!patternProperty.isConstant()) {
                hasPattern2 = true;
              }
              var constantPattern = patternProperty.constantOr(null);
              if (constantPattern) {
                hasPattern2 = true;
                patterns[constantPattern.to] = true;
                patterns[constantPattern.from] = true;
              }
            }
            return hasPattern2;
          }
          function addPatternDependencies(type, layers, patternFeature, zoom, options) {
            var patterns = options.patternDependencies;
            for (var i = 0, list = layers; i < list.length; i += 1) {
              var layer2 = list[i];
              var patternProperty = layer2.paint.get(type + "-pattern");
              var patternPropertyValue = patternProperty.value;
              if (patternPropertyValue.kind !== "constant") {
                var min = patternPropertyValue.evaluate({ zoom: zoom - 1 }, patternFeature, {}, options.availableImages);
                var mid = patternPropertyValue.evaluate({ zoom }, patternFeature, {}, options.availableImages);
                var max = patternPropertyValue.evaluate({ zoom: zoom + 1 }, patternFeature, {}, options.availableImages);
                min = min && min.name ? min.name : min;
                mid = mid && mid.name ? mid.name : mid;
                max = max && max.name ? max.name : max;
                patterns[min] = true;
                patterns[mid] = true;
                patterns[max] = true;
                patternFeature.patterns[layer2.id] = {
                  min,
                  mid,
                  max
                };
              }
            }
            return patternFeature;
          }
          var EARCUT_MAX_RINGS = 500;
          var FillBucket = function FillBucket2(options) {
            this.zoom = options.zoom;
            this.overscaling = options.overscaling;
            this.layers = options.layers;
            this.layerIds = this.layers.map(function(layer2) {
              return layer2.id;
            });
            this.index = options.index;
            this.hasPattern = false;
            this.patternFeatures = [];
            this.layoutVertexArray = new StructArrayLayout2i4();
            this.indexArray = new StructArrayLayout3ui6();
            this.indexArray2 = new StructArrayLayout2ui4();
            this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);
            this.segments = new SegmentVector();
            this.segments2 = new SegmentVector();
            this.stateDependentLayerIds = this.layers.filter(function(l) {
              return l.isStateDependent();
            }).map(function(l) {
              return l.id;
            });
          };
          FillBucket.prototype.populate = function populate(features, options, canonical) {
            this.hasPattern = hasPattern("fill", this.layers, options);
            var fillSortKey = this.layers[0].layout.get("fill-sort-key");
            var bucketFeatures = [];
            for (var i = 0, list = features; i < list.length; i += 1) {
              var ref = list[i];
              var feature = ref.feature;
              var id2 = ref.id;
              var index = ref.index;
              var sourceLayerIndex = ref.sourceLayerIndex;
              var needGeometry = this.layers[0]._featureFilter.needGeometry;
              var evaluationFeature = toEvaluationFeature(feature, needGeometry);
              if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) {
                continue;
              }
              var sortKey = fillSortKey ? fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) : void 0;
              var bucketFeature = {
                id: id2,
                properties: feature.properties,
                type: feature.type,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),
                patterns: {},
                sortKey
              };
              bucketFeatures.push(bucketFeature);
            }
            if (fillSortKey) {
              bucketFeatures.sort(function(a, b) {
                return a.sortKey - b.sortKey;
              });
            }
            for (var i$1 = 0, list$1 = bucketFeatures; i$1 < list$1.length; i$1 += 1) {
              var bucketFeature$1 = list$1[i$1];
              var ref$1 = bucketFeature$1;
              var geometry = ref$1.geometry;
              var index$1 = ref$1.index;
              var sourceLayerIndex$1 = ref$1.sourceLayerIndex;
              if (this.hasPattern) {
                var patternFeature = addPatternDependencies("fill", this.layers, bucketFeature$1, this.zoom, options);
                this.patternFeatures.push(patternFeature);
              } else {
                this.addFeature(bucketFeature$1, geometry, index$1, canonical, {});
              }
              var feature$1 = features[index$1].feature;
              options.featureIndex.insert(feature$1, geometry, index$1, sourceLayerIndex$1, this.index);
            }
          };
          FillBucket.prototype.update = function update(states, vtLayer, imagePositions) {
            if (!this.stateDependentLayers.length) {
              return;
            }
            this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);
          };
          FillBucket.prototype.addFeatures = function addFeatures(options, canonical, imagePositions) {
            for (var i = 0, list = this.patternFeatures; i < list.length; i += 1) {
              var feature = list[i];
              this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions);
            }
          };
          FillBucket.prototype.isEmpty = function isEmpty2() {
            return this.layoutVertexArray.length === 0;
          };
          FillBucket.prototype.uploadPending = function uploadPending() {
            return !this.uploaded || this.programConfigurations.needsUpload;
          };
          FillBucket.prototype.upload = function upload(context) {
            if (!this.uploaded) {
              this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$1);
              this.indexBuffer = context.createIndexBuffer(this.indexArray);
              this.indexBuffer2 = context.createIndexBuffer(this.indexArray2);
            }
            this.programConfigurations.upload(context);
            this.uploaded = true;
          };
          FillBucket.prototype.destroy = function destroy() {
            if (!this.layoutVertexBuffer) {
              return;
            }
            this.layoutVertexBuffer.destroy();
            this.indexBuffer.destroy();
            this.indexBuffer2.destroy();
            this.programConfigurations.destroy();
            this.segments.destroy();
            this.segments2.destroy();
          };
          FillBucket.prototype.addFeature = function addFeature2(feature, geometry, index, canonical, imagePositions) {
            for (var i$4 = 0, list$2 = classifyRings(geometry, EARCUT_MAX_RINGS); i$4 < list$2.length; i$4 += 1) {
              var polygon = list$2[i$4];
              var numVertices = 0;
              for (var i$2 = 0, list = polygon; i$2 < list.length; i$2 += 1) {
                var ring = list[i$2];
                numVertices += ring.length;
              }
              var triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray);
              var triangleIndex = triangleSegment.vertexLength;
              var flattened = [];
              var holeIndices = [];
              for (var i$3 = 0, list$1 = polygon; i$3 < list$1.length; i$3 += 1) {
                var ring$1 = list$1[i$3];
                if (ring$1.length === 0) {
                  continue;
                }
                if (ring$1 !== polygon[0]) {
                  holeIndices.push(flattened.length / 2);
                }
                var lineSegment = this.segments2.prepareSegment(ring$1.length, this.layoutVertexArray, this.indexArray2);
                var lineIndex = lineSegment.vertexLength;
                this.layoutVertexArray.emplaceBack(ring$1[0].x, ring$1[0].y);
                this.indexArray2.emplaceBack(lineIndex + ring$1.length - 1, lineIndex);
                flattened.push(ring$1[0].x);
                flattened.push(ring$1[0].y);
                for (var i = 1; i < ring$1.length; i++) {
                  this.layoutVertexArray.emplaceBack(ring$1[i].x, ring$1[i].y);
                  this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i);
                  flattened.push(ring$1[i].x);
                  flattened.push(ring$1[i].y);
                }
                lineSegment.vertexLength += ring$1.length;
                lineSegment.primitiveLength += ring$1.length;
              }
              var indices = earcut_1(flattened, holeIndices);
              for (var i$1 = 0; i$1 < indices.length; i$1 += 3) {
                this.indexArray.emplaceBack(triangleIndex + indices[i$1], triangleIndex + indices[i$1 + 1], triangleIndex + indices[i$1 + 2]);
              }
              triangleSegment.vertexLength += numVertices;
              triangleSegment.primitiveLength += indices.length / 3;
            }
            this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);
          };
          register("FillBucket", FillBucket, {
            omit: [
              "layers",
              "patternFeatures"
            ]
          });
          var layout$4 = new Properties({ "fill-sort-key": new DataDrivenProperty(spec["layout_fill"]["fill-sort-key"]) });
          var paint$4 = new Properties({
            "fill-antialias": new DataConstantProperty(spec["paint_fill"]["fill-antialias"]),
            "fill-opacity": new DataDrivenProperty(spec["paint_fill"]["fill-opacity"]),
            "fill-color": new DataDrivenProperty(spec["paint_fill"]["fill-color"]),
            "fill-outline-color": new DataDrivenProperty(spec["paint_fill"]["fill-outline-color"]),
            "fill-translate": new DataConstantProperty(spec["paint_fill"]["fill-translate"]),
            "fill-translate-anchor": new DataConstantProperty(spec["paint_fill"]["fill-translate-anchor"]),
            "fill-pattern": new CrossFadedDataDrivenProperty(spec["paint_fill"]["fill-pattern"])
          });
          var properties$3 = {
            paint: paint$4,
            layout: layout$4
          };
          var FillStyleLayer = function(StyleLayer2) {
            function FillStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$3);
            }
            if (StyleLayer2)
              FillStyleLayer2.__proto__ = StyleLayer2;
            FillStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            FillStyleLayer2.prototype.constructor = FillStyleLayer2;
            FillStyleLayer2.prototype.recalculate = function recalculate(parameters, availableImages) {
              StyleLayer2.prototype.recalculate.call(this, parameters, availableImages);
              var outlineColor = this.paint._values["fill-outline-color"];
              if (outlineColor.value.kind === "constant" && outlineColor.value.value === void 0) {
                this.paint._values["fill-outline-color"] = this.paint._values["fill-color"];
              }
            };
            FillStyleLayer2.prototype.createBucket = function createBucket(parameters) {
              return new FillBucket(parameters);
            };
            FillStyleLayer2.prototype.queryRadius = function queryRadius() {
              return translateDistance(this.paint.get("fill-translate"));
            };
            FillStyleLayer2.prototype.queryIntersectsFeature = function queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) {
              var translatedPolygon = translate(queryGeometry, this.paint.get("fill-translate"), this.paint.get("fill-translate-anchor"), transform.angle, pixelsToTileUnits);
              return polygonIntersectsMultiPolygon(translatedPolygon, geometry);
            };
            FillStyleLayer2.prototype.isTileClipped = function isTileClipped() {
              return true;
            };
            return FillStyleLayer2;
          }(StyleLayer);
          var layout$5 = createLayout([
            {
              name: "a_pos",
              components: 2,
              type: "Int16"
            },
            {
              name: "a_normal_ed",
              components: 4,
              type: "Int16"
            }
          ], 4);
          var members$2 = layout$5.members;
          var vectortilefeature = VectorTileFeature;
          function VectorTileFeature(pbf2, end, extent, keys, values2) {
            this.properties = {};
            this.extent = extent;
            this.type = 0;
            this._pbf = pbf2;
            this._geometry = -1;
            this._keys = keys;
            this._values = values2;
            pbf2.readFields(readFeature, this, end);
          }
          function readFeature(tag, feature, pbf2) {
            if (tag == 1) {
              feature.id = pbf2.readVarint();
            } else if (tag == 2) {
              readTag(pbf2, feature);
            } else if (tag == 3) {
              feature.type = pbf2.readVarint();
            } else if (tag == 4) {
              feature._geometry = pbf2.pos;
            }
          }
          function readTag(pbf2, feature) {
            var end = pbf2.readVarint() + pbf2.pos;
            while (pbf2.pos < end) {
              var key = feature._keys[pbf2.readVarint()], value = feature._values[pbf2.readVarint()];
              feature.properties[key] = value;
            }
          }
          VectorTileFeature.types = [
            "Unknown",
            "Point",
            "LineString",
            "Polygon"
          ];
          VectorTileFeature.prototype.loadGeometry = function() {
            var pbf2 = this._pbf;
            pbf2.pos = this._geometry;
            var end = pbf2.readVarint() + pbf2.pos, cmd = 1, length = 0, x = 0, y = 0, lines = [], line;
            while (pbf2.pos < end) {
              if (length <= 0) {
                var cmdLen = pbf2.readVarint();
                cmd = cmdLen & 7;
                length = cmdLen >> 3;
              }
              length--;
              if (cmd === 1 || cmd === 2) {
                x += pbf2.readSVarint();
                y += pbf2.readSVarint();
                if (cmd === 1) {
                  if (line) {
                    lines.push(line);
                  }
                  line = [];
                }
                line.push(new pointGeometry(x, y));
              } else if (cmd === 7) {
                if (line) {
                  line.push(line[0].clone());
                }
              } else {
                throw new Error("unknown command " + cmd);
              }
            }
            if (line) {
              lines.push(line);
            }
            return lines;
          };
          VectorTileFeature.prototype.bbox = function() {
            var pbf2 = this._pbf;
            pbf2.pos = this._geometry;
            var end = pbf2.readVarint() + pbf2.pos, cmd = 1, length = 0, x = 0, y = 0, x1 = Infinity, x2 = -Infinity, y1 = Infinity, y2 = -Infinity;
            while (pbf2.pos < end) {
              if (length <= 0) {
                var cmdLen = pbf2.readVarint();
                cmd = cmdLen & 7;
                length = cmdLen >> 3;
              }
              length--;
              if (cmd === 1 || cmd === 2) {
                x += pbf2.readSVarint();
                y += pbf2.readSVarint();
                if (x < x1) {
                  x1 = x;
                }
                if (x > x2) {
                  x2 = x;
                }
                if (y < y1) {
                  y1 = y;
                }
                if (y > y2) {
                  y2 = y;
                }
              } else if (cmd !== 7) {
                throw new Error("unknown command " + cmd);
              }
            }
            return [
              x1,
              y1,
              x2,
              y2
            ];
          };
          VectorTileFeature.prototype.toGeoJSON = function(x, y, z) {
            var size = this.extent * Math.pow(2, z), x0 = this.extent * x, y0 = this.extent * y, coords = this.loadGeometry(), type = VectorTileFeature.types[this.type], i, j;
            function project(line) {
              for (var j2 = 0; j2 < line.length; j2++) {
                var p = line[j2], y2 = 180 - (p.y + y0) * 360 / size;
                line[j2] = [
                  (p.x + x0) * 360 / size - 180,
                  360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90
                ];
              }
            }
            switch (this.type) {
              case 1:
                var points = [];
                for (i = 0; i < coords.length; i++) {
                  points[i] = coords[i][0];
                }
                coords = points;
                project(coords);
                break;
              case 2:
                for (i = 0; i < coords.length; i++) {
                  project(coords[i]);
                }
                break;
              case 3:
                coords = classifyRings$1(coords);
                for (i = 0; i < coords.length; i++) {
                  for (j = 0; j < coords[i].length; j++) {
                    project(coords[i][j]);
                  }
                }
                break;
            }
            if (coords.length === 1) {
              coords = coords[0];
            } else {
              type = "Multi" + type;
            }
            var result = {
              type: "Feature",
              geometry: {
                type,
                coordinates: coords
              },
              properties: this.properties
            };
            if ("id" in this) {
              result.id = this.id;
            }
            return result;
          };
          function classifyRings$1(rings) {
            var len = rings.length;
            if (len <= 1) {
              return [rings];
            }
            var polygons = [], polygon, ccw;
            for (var i = 0; i < len; i++) {
              var area2 = signedArea$1(rings[i]);
              if (area2 === 0) {
                continue;
              }
              if (ccw === void 0) {
                ccw = area2 < 0;
              }
              if (ccw === area2 < 0) {
                if (polygon) {
                  polygons.push(polygon);
                }
                polygon = [rings[i]];
              } else {
                polygon.push(rings[i]);
              }
            }
            if (polygon) {
              polygons.push(polygon);
            }
            return polygons;
          }
          function signedArea$1(ring) {
            var sum = 0;
            for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {
              p1 = ring[i];
              p2 = ring[j];
              sum += (p2.x - p1.x) * (p1.y + p2.y);
            }
            return sum;
          }
          var vectortilelayer = VectorTileLayer;
          function VectorTileLayer(pbf2, end) {
            this.version = 1;
            this.name = null;
            this.extent = 4096;
            this.length = 0;
            this._pbf = pbf2;
            this._keys = [];
            this._values = [];
            this._features = [];
            pbf2.readFields(readLayer, this, end);
            this.length = this._features.length;
          }
          function readLayer(tag, layer2, pbf2) {
            if (tag === 15) {
              layer2.version = pbf2.readVarint();
            } else if (tag === 1) {
              layer2.name = pbf2.readString();
            } else if (tag === 5) {
              layer2.extent = pbf2.readVarint();
            } else if (tag === 2) {
              layer2._features.push(pbf2.pos);
            } else if (tag === 3) {
              layer2._keys.push(pbf2.readString());
            } else if (tag === 4) {
              layer2._values.push(readValueMessage(pbf2));
            }
          }
          function readValueMessage(pbf2) {
            var value = null, end = pbf2.readVarint() + pbf2.pos;
            while (pbf2.pos < end) {
              var tag = pbf2.readVarint() >> 3;
              value = tag === 1 ? pbf2.readString() : tag === 2 ? pbf2.readFloat() : tag === 3 ? pbf2.readDouble() : tag === 4 ? pbf2.readVarint64() : tag === 5 ? pbf2.readVarint() : tag === 6 ? pbf2.readSVarint() : tag === 7 ? pbf2.readBoolean() : null;
            }
            return value;
          }
          VectorTileLayer.prototype.feature = function(i) {
            if (i < 0 || i >= this._features.length) {
              throw new Error("feature index out of bounds");
            }
            this._pbf.pos = this._features[i];
            var end = this._pbf.readVarint() + this._pbf.pos;
            return new vectortilefeature(this._pbf, end, this.extent, this._keys, this._values);
          };
          var vectortile = VectorTile;
          function VectorTile(pbf2, end) {
            this.layers = pbf2.readFields(readTile, {}, end);
          }
          function readTile(tag, layers, pbf2) {
            if (tag === 3) {
              var layer2 = new vectortilelayer(pbf2, pbf2.readVarint() + pbf2.pos);
              if (layer2.length) {
                layers[layer2.name] = layer2;
              }
            }
          }
          var VectorTile$1 = vectortile;
          var VectorTileFeature$1 = vectortilefeature;
          var VectorTileLayer$1 = vectortilelayer;
          var vectorTile = {
            VectorTile: VectorTile$1,
            VectorTileFeature: VectorTileFeature$1,
            VectorTileLayer: VectorTileLayer$1
          };
          var vectorTileFeatureTypes = vectorTile.VectorTileFeature.types;
          var EARCUT_MAX_RINGS$1 = 500;
          var FACTOR = Math.pow(2, 13);
          function addVertex(vertexArray, x, y, nx, ny, nz, t, e) {
            vertexArray.emplaceBack(x, y, Math.floor(nx * FACTOR) * 2 + t, ny * FACTOR * 2, nz * FACTOR * 2, Math.round(e));
          }
          var FillExtrusionBucket = function FillExtrusionBucket2(options) {
            this.zoom = options.zoom;
            this.overscaling = options.overscaling;
            this.layers = options.layers;
            this.layerIds = this.layers.map(function(layer2) {
              return layer2.id;
            });
            this.index = options.index;
            this.hasPattern = false;
            this.layoutVertexArray = new StructArrayLayout2i4i12();
            this.indexArray = new StructArrayLayout3ui6();
            this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);
            this.segments = new SegmentVector();
            this.stateDependentLayerIds = this.layers.filter(function(l) {
              return l.isStateDependent();
            }).map(function(l) {
              return l.id;
            });
          };
          FillExtrusionBucket.prototype.populate = function populate(features, options, canonical) {
            this.features = [];
            this.hasPattern = hasPattern("fill-extrusion", this.layers, options);
            for (var i = 0, list = features; i < list.length; i += 1) {
              var ref = list[i];
              var feature = ref.feature;
              var id2 = ref.id;
              var index = ref.index;
              var sourceLayerIndex = ref.sourceLayerIndex;
              var needGeometry = this.layers[0]._featureFilter.needGeometry;
              var evaluationFeature = toEvaluationFeature(feature, needGeometry);
              if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) {
                continue;
              }
              var bucketFeature = {
                id: id2,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),
                properties: feature.properties,
                type: feature.type,
                patterns: {}
              };
              if (this.hasPattern) {
                this.features.push(addPatternDependencies("fill-extrusion", this.layers, bucketFeature, this.zoom, options));
              } else {
                this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {});
              }
              options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true);
            }
          };
          FillExtrusionBucket.prototype.addFeatures = function addFeatures(options, canonical, imagePositions) {
            for (var i = 0, list = this.features; i < list.length; i += 1) {
              var feature = list[i];
              var geometry = feature.geometry;
              this.addFeature(feature, geometry, feature.index, canonical, imagePositions);
            }
          };
          FillExtrusionBucket.prototype.update = function update(states, vtLayer, imagePositions) {
            if (!this.stateDependentLayers.length) {
              return;
            }
            this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);
          };
          FillExtrusionBucket.prototype.isEmpty = function isEmpty2() {
            return this.layoutVertexArray.length === 0;
          };
          FillExtrusionBucket.prototype.uploadPending = function uploadPending() {
            return !this.uploaded || this.programConfigurations.needsUpload;
          };
          FillExtrusionBucket.prototype.upload = function upload(context) {
            if (!this.uploaded) {
              this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$2);
              this.indexBuffer = context.createIndexBuffer(this.indexArray);
            }
            this.programConfigurations.upload(context);
            this.uploaded = true;
          };
          FillExtrusionBucket.prototype.destroy = function destroy() {
            if (!this.layoutVertexBuffer) {
              return;
            }
            this.layoutVertexBuffer.destroy();
            this.indexBuffer.destroy();
            this.programConfigurations.destroy();
            this.segments.destroy();
          };
          FillExtrusionBucket.prototype.addFeature = function addFeature2(feature, geometry, index, canonical, imagePositions) {
            for (var i$4 = 0, list$3 = classifyRings(geometry, EARCUT_MAX_RINGS$1); i$4 < list$3.length; i$4 += 1) {
              var polygon = list$3[i$4];
              var numVertices = 0;
              for (var i$1 = 0, list = polygon; i$1 < list.length; i$1 += 1) {
                var ring = list[i$1];
                numVertices += ring.length;
              }
              var segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);
              for (var i$2 = 0, list$1 = polygon; i$2 < list$1.length; i$2 += 1) {
                var ring$1 = list$1[i$2];
                if (ring$1.length === 0) {
                  continue;
                }
                if (isEntirelyOutside(ring$1)) {
                  continue;
                }
                var edgeDistance = 0;
                for (var p = 0; p < ring$1.length; p++) {
                  var p1 = ring$1[p];
                  if (p >= 1) {
                    var p2 = ring$1[p - 1];
                    if (!isBoundaryEdge(p1, p2)) {
                      if (segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {
                        segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);
                      }
                      var perp2 = p1.sub(p2)._perp()._unit();
                      var dist = p2.dist(p1);
                      if (edgeDistance + dist > 32768) {
                        edgeDistance = 0;
                      }
                      addVertex(this.layoutVertexArray, p1.x, p1.y, perp2.x, perp2.y, 0, 0, edgeDistance);
                      addVertex(this.layoutVertexArray, p1.x, p1.y, perp2.x, perp2.y, 0, 1, edgeDistance);
                      edgeDistance += dist;
                      addVertex(this.layoutVertexArray, p2.x, p2.y, perp2.x, perp2.y, 0, 0, edgeDistance);
                      addVertex(this.layoutVertexArray, p2.x, p2.y, perp2.x, perp2.y, 0, 1, edgeDistance);
                      var bottomRight = segment.vertexLength;
                      this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1);
                      this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3);
                      segment.vertexLength += 4;
                      segment.primitiveLength += 2;
                    }
                  }
                }
              }
              if (segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {
                segment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray);
              }
              if (vectorTileFeatureTypes[feature.type] !== "Polygon") {
                continue;
              }
              var flattened = [];
              var holeIndices = [];
              var triangleIndex = segment.vertexLength;
              for (var i$3 = 0, list$2 = polygon; i$3 < list$2.length; i$3 += 1) {
                var ring$2 = list$2[i$3];
                if (ring$2.length === 0) {
                  continue;
                }
                if (ring$2 !== polygon[0]) {
                  holeIndices.push(flattened.length / 2);
                }
                for (var i = 0; i < ring$2.length; i++) {
                  var p$1 = ring$2[i];
                  addVertex(this.layoutVertexArray, p$1.x, p$1.y, 0, 0, 1, 1, 0);
                  flattened.push(p$1.x);
                  flattened.push(p$1.y);
                }
              }
              var indices = earcut_1(flattened, holeIndices);
              for (var j = 0; j < indices.length; j += 3) {
                this.indexArray.emplaceBack(triangleIndex + indices[j], triangleIndex + indices[j + 2], triangleIndex + indices[j + 1]);
              }
              segment.primitiveLength += indices.length / 3;
              segment.vertexLength += numVertices;
            }
            this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);
          };
          register("FillExtrusionBucket", FillExtrusionBucket, {
            omit: [
              "layers",
              "features"
            ]
          });
          function isBoundaryEdge(p1, p2) {
            return p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT$1) || p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT$1);
          }
          function isEntirelyOutside(ring) {
            return ring.every(function(p) {
              return p.x < 0;
            }) || ring.every(function(p) {
              return p.x > EXTENT$1;
            }) || ring.every(function(p) {
              return p.y < 0;
            }) || ring.every(function(p) {
              return p.y > EXTENT$1;
            });
          }
          var paint$5 = new Properties({
            "fill-extrusion-opacity": new DataConstantProperty(spec["paint_fill-extrusion"]["fill-extrusion-opacity"]),
            "fill-extrusion-color": new DataDrivenProperty(spec["paint_fill-extrusion"]["fill-extrusion-color"]),
            "fill-extrusion-translate": new DataConstantProperty(spec["paint_fill-extrusion"]["fill-extrusion-translate"]),
            "fill-extrusion-translate-anchor": new DataConstantProperty(spec["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),
            "fill-extrusion-pattern": new CrossFadedDataDrivenProperty(spec["paint_fill-extrusion"]["fill-extrusion-pattern"]),
            "fill-extrusion-height": new DataDrivenProperty(spec["paint_fill-extrusion"]["fill-extrusion-height"]),
            "fill-extrusion-base": new DataDrivenProperty(spec["paint_fill-extrusion"]["fill-extrusion-base"]),
            "fill-extrusion-vertical-gradient": new DataConstantProperty(spec["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])
          });
          var properties$4 = { paint: paint$5 };
          var FillExtrusionStyleLayer = function(StyleLayer2) {
            function FillExtrusionStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$4);
            }
            if (StyleLayer2)
              FillExtrusionStyleLayer2.__proto__ = StyleLayer2;
            FillExtrusionStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            FillExtrusionStyleLayer2.prototype.constructor = FillExtrusionStyleLayer2;
            FillExtrusionStyleLayer2.prototype.createBucket = function createBucket(parameters) {
              return new FillExtrusionBucket(parameters);
            };
            FillExtrusionStyleLayer2.prototype.queryRadius = function queryRadius() {
              return translateDistance(this.paint.get("fill-extrusion-translate"));
            };
            FillExtrusionStyleLayer2.prototype.is3D = function is3D() {
              return true;
            };
            FillExtrusionStyleLayer2.prototype.queryIntersectsFeature = function queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits, pixelPosMatrix) {
              var translatedPolygon = translate(queryGeometry, this.paint.get("fill-extrusion-translate"), this.paint.get("fill-extrusion-translate-anchor"), transform.angle, pixelsToTileUnits);
              var height = this.paint.get("fill-extrusion-height").evaluate(feature, featureState);
              var base = this.paint.get("fill-extrusion-base").evaluate(feature, featureState);
              var projectedQueryGeometry = projectQueryGeometry$1(translatedPolygon, pixelPosMatrix, transform, 0);
              var projected = projectExtrusion(geometry, base, height, pixelPosMatrix);
              var projectedBase = projected[0];
              var projectedTop = projected[1];
              return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry);
            };
            return FillExtrusionStyleLayer2;
          }(StyleLayer);
          function dot$2(a, b) {
            return a.x * b.x + a.y * b.y;
          }
          function getIntersectionDistance(projectedQueryGeometry, projectedFace) {
            if (projectedQueryGeometry.length === 1) {
              var i = 0;
              var a = projectedFace[i++];
              var b;
              while (!b || a.equals(b)) {
                b = projectedFace[i++];
                if (!b) {
                  return Infinity;
                }
              }
              for (; i < projectedFace.length; i++) {
                var c = projectedFace[i];
                var p = projectedQueryGeometry[0];
                var ab = b.sub(a);
                var ac = c.sub(a);
                var ap = p.sub(a);
                var dotABAB = dot$2(ab, ab);
                var dotABAC = dot$2(ab, ac);
                var dotACAC = dot$2(ac, ac);
                var dotAPAB = dot$2(ap, ab);
                var dotAPAC = dot$2(ap, ac);
                var denom = dotABAB * dotACAC - dotABAC * dotABAC;
                var v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom;
                var w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom;
                var u = 1 - v - w;
                var distance = a.z * u + b.z * v + c.z * w;
                if (isFinite(distance)) {
                  return distance;
                }
              }
              return Infinity;
            } else {
              var closestDistance = Infinity;
              for (var i$1 = 0, list = projectedFace; i$1 < list.length; i$1 += 1) {
                var p$1 = list[i$1];
                closestDistance = Math.min(closestDistance, p$1.z);
              }
              return closestDistance;
            }
          }
          function checkIntersection(projectedBase, projectedTop, projectedQueryGeometry) {
            var closestDistance = Infinity;
            if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) {
              closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]);
            }
            for (var r = 0; r < projectedTop.length; r++) {
              var ringTop = projectedTop[r];
              var ringBase = projectedBase[r];
              for (var p = 0; p < ringTop.length - 1; p++) {
                var topA = ringTop[p];
                var topB = ringTop[p + 1];
                var baseA = ringBase[p];
                var baseB = ringBase[p + 1];
                var face = [
                  topA,
                  topB,
                  baseB,
                  baseA,
                  topA
                ];
                if (polygonIntersectsPolygon(projectedQueryGeometry, face)) {
                  closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face));
                }
              }
            }
            return closestDistance === Infinity ? false : closestDistance;
          }
          function projectExtrusion(geometry, zBase, zTop, m) {
            var projectedBase = [];
            var projectedTop = [];
            var baseXZ = m[8] * zBase;
            var baseYZ = m[9] * zBase;
            var baseZZ = m[10] * zBase;
            var baseWZ = m[11] * zBase;
            var topXZ = m[8] * zTop;
            var topYZ = m[9] * zTop;
            var topZZ = m[10] * zTop;
            var topWZ = m[11] * zTop;
            for (var i$1 = 0, list$1 = geometry; i$1 < list$1.length; i$1 += 1) {
              var r = list$1[i$1];
              var ringBase = [];
              var ringTop = [];
              for (var i = 0, list = r; i < list.length; i += 1) {
                var p = list[i];
                var x = p.x;
                var y = p.y;
                var sX = m[0] * x + m[4] * y + m[12];
                var sY = m[1] * x + m[5] * y + m[13];
                var sZ = m[2] * x + m[6] * y + m[14];
                var sW = m[3] * x + m[7] * y + m[15];
                var baseX = sX + baseXZ;
                var baseY = sY + baseYZ;
                var baseZ = sZ + baseZZ;
                var baseW = sW + baseWZ;
                var topX = sX + topXZ;
                var topY = sY + topYZ;
                var topZ = sZ + topZZ;
                var topW = sW + topWZ;
                var b = new pointGeometry(baseX / baseW, baseY / baseW);
                b.z = baseZ / baseW;
                ringBase.push(b);
                var t = new pointGeometry(topX / topW, topY / topW);
                t.z = topZ / topW;
                ringTop.push(t);
              }
              projectedBase.push(ringBase);
              projectedTop.push(ringTop);
            }
            return [
              projectedBase,
              projectedTop
            ];
          }
          function projectQueryGeometry$1(queryGeometry, pixelPosMatrix, transform, z) {
            var projectedQueryGeometry = [];
            for (var i = 0, list = queryGeometry; i < list.length; i += 1) {
              var p = list[i];
              var v = [
                p.x,
                p.y,
                z,
                1
              ];
              transformMat4(v, v, pixelPosMatrix);
              projectedQueryGeometry.push(new pointGeometry(v[0] / v[3], v[1] / v[3]));
            }
            return projectedQueryGeometry;
          }
          var lineLayoutAttributes = createLayout([
            {
              name: "a_pos_normal",
              components: 2,
              type: "Int16"
            },
            {
              name: "a_data",
              components: 4,
              type: "Uint8"
            }
          ], 4);
          var members$3 = lineLayoutAttributes.members;
          var lineLayoutAttributesExt = createLayout([
            {
              name: "a_uv_x",
              components: 1,
              type: "Float32"
            },
            {
              name: "a_split_index",
              components: 1,
              type: "Float32"
            }
          ]);
          var members$4 = lineLayoutAttributesExt.members;
          var vectorTileFeatureTypes$1 = vectorTile.VectorTileFeature.types;
          var EXTRUDE_SCALE = 63;
          var COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180));
          var SHARP_CORNER_OFFSET = 15;
          var DEG_PER_TRIANGLE = 20;
          var LINE_DISTANCE_BUFFER_BITS = 15;
          var LINE_DISTANCE_SCALE = 1 / 2;
          var MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE;
          var LineBucket = function LineBucket2(options) {
            var this$1 = this;
            this.zoom = options.zoom;
            this.overscaling = options.overscaling;
            this.layers = options.layers;
            this.layerIds = this.layers.map(function(layer2) {
              return layer2.id;
            });
            this.index = options.index;
            this.hasPattern = false;
            this.patternFeatures = [];
            this.lineClipsArray = [];
            this.gradients = {};
            this.layers.forEach(function(layer2) {
              this$1.gradients[layer2.id] = {};
            });
            this.layoutVertexArray = new StructArrayLayout2i4ub8();
            this.layoutVertexArray2 = new StructArrayLayout2f8();
            this.indexArray = new StructArrayLayout3ui6();
            this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);
            this.segments = new SegmentVector();
            this.maxLineLength = 0;
            this.stateDependentLayerIds = this.layers.filter(function(l) {
              return l.isStateDependent();
            }).map(function(l) {
              return l.id;
            });
          };
          LineBucket.prototype.populate = function populate(features, options, canonical) {
            this.hasPattern = hasPattern("line", this.layers, options);
            var lineSortKey = this.layers[0].layout.get("line-sort-key");
            var bucketFeatures = [];
            for (var i = 0, list = features; i < list.length; i += 1) {
              var ref = list[i];
              var feature = ref.feature;
              var id2 = ref.id;
              var index = ref.index;
              var sourceLayerIndex = ref.sourceLayerIndex;
              var needGeometry = this.layers[0]._featureFilter.needGeometry;
              var evaluationFeature = toEvaluationFeature(feature, needGeometry);
              if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) {
                continue;
              }
              var sortKey = lineSortKey ? lineSortKey.evaluate(evaluationFeature, {}, canonical) : void 0;
              var bucketFeature = {
                id: id2,
                properties: feature.properties,
                type: feature.type,
                sourceLayerIndex,
                index,
                geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature),
                patterns: {},
                sortKey
              };
              bucketFeatures.push(bucketFeature);
            }
            if (lineSortKey) {
              bucketFeatures.sort(function(a, b) {
                return a.sortKey - b.sortKey;
              });
            }
            for (var i$1 = 0, list$1 = bucketFeatures; i$1 < list$1.length; i$1 += 1) {
              var bucketFeature$1 = list$1[i$1];
              var ref$1 = bucketFeature$1;
              var geometry = ref$1.geometry;
              var index$1 = ref$1.index;
              var sourceLayerIndex$1 = ref$1.sourceLayerIndex;
              if (this.hasPattern) {
                var patternBucketFeature = addPatternDependencies("line", this.layers, bucketFeature$1, this.zoom, options);
                this.patternFeatures.push(patternBucketFeature);
              } else {
                this.addFeature(bucketFeature$1, geometry, index$1, canonical, {});
              }
              var feature$1 = features[index$1].feature;
              options.featureIndex.insert(feature$1, geometry, index$1, sourceLayerIndex$1, this.index);
            }
          };
          LineBucket.prototype.update = function update(states, vtLayer, imagePositions) {
            if (!this.stateDependentLayers.length) {
              return;
            }
            this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);
          };
          LineBucket.prototype.addFeatures = function addFeatures(options, canonical, imagePositions) {
            for (var i = 0, list = this.patternFeatures; i < list.length; i += 1) {
              var feature = list[i];
              this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions);
            }
          };
          LineBucket.prototype.isEmpty = function isEmpty2() {
            return this.layoutVertexArray.length === 0;
          };
          LineBucket.prototype.uploadPending = function uploadPending() {
            return !this.uploaded || this.programConfigurations.needsUpload;
          };
          LineBucket.prototype.upload = function upload(context) {
            if (!this.uploaded) {
              if (this.layoutVertexArray2.length !== 0) {
                this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, members$4);
              }
              this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, members$3);
              this.indexBuffer = context.createIndexBuffer(this.indexArray);
            }
            this.programConfigurations.upload(context);
            this.uploaded = true;
          };
          LineBucket.prototype.destroy = function destroy() {
            if (!this.layoutVertexBuffer) {
              return;
            }
            this.layoutVertexBuffer.destroy();
            this.indexBuffer.destroy();
            this.programConfigurations.destroy();
            this.segments.destroy();
          };
          LineBucket.prototype.lineFeatureClips = function lineFeatureClips(feature) {
            if (!!feature.properties && feature.properties.hasOwnProperty("mapbox_clip_start") && feature.properties.hasOwnProperty("mapbox_clip_end")) {
              var start = +feature.properties["mapbox_clip_start"];
              var end = +feature.properties["mapbox_clip_end"];
              return {
                start,
                end
              };
            }
          };
          LineBucket.prototype.addFeature = function addFeature2(feature, geometry, index, canonical, imagePositions) {
            var layout2 = this.layers[0].layout;
            var join = layout2.get("line-join").evaluate(feature, {});
            var cap = layout2.get("line-cap");
            var miterLimit = layout2.get("line-miter-limit");
            var roundLimit = layout2.get("line-round-limit");
            this.lineClips = this.lineFeatureClips(feature);
            for (var i = 0, list = geometry; i < list.length; i += 1) {
              var line = list[i];
              this.addLine(line, feature, join, cap, miterLimit, roundLimit);
            }
            this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);
          };
          LineBucket.prototype.addLine = function addLine(vertices, feature, join, cap, miterLimit, roundLimit) {
            this.distance = 0;
            this.scaledDistance = 0;
            this.totalDistance = 0;
            if (this.lineClips) {
              this.lineClipsArray.push(this.lineClips);
              for (var i = 0; i < vertices.length - 1; i++) {
                this.totalDistance += vertices[i].dist(vertices[i + 1]);
              }
              this.updateScaledDistance();
              this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);
            }
            var isPolygon = vectorTileFeatureTypes$1[feature.type] === "Polygon";
            var len = vertices.length;
            while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {
              len--;
            }
            var first = 0;
            while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {
              first++;
            }
            if (len < (isPolygon ? 3 : 2)) {
              return;
            }
            if (join === "bevel") {
              miterLimit = 1.05;
            }
            var sharpCornerOffset = this.overscaling <= 16 ? SHARP_CORNER_OFFSET * EXTENT$1 / (512 * this.overscaling) : 0;
            var segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);
            var currentVertex;
            var prevVertex = void 0;
            var nextVertex = void 0;
            var prevNormal = void 0;
            var nextNormal = void 0;
            this.e1 = this.e2 = -1;
            if (isPolygon) {
              currentVertex = vertices[len - 2];
              nextNormal = vertices[first].sub(currentVertex)._unit()._perp();
            }
            for (var i$1 = first; i$1 < len; i$1++) {
              nextVertex = i$1 === len - 1 ? isPolygon ? vertices[first + 1] : void 0 : vertices[i$1 + 1];
              if (nextVertex && vertices[i$1].equals(nextVertex)) {
                continue;
              }
              if (nextNormal) {
                prevNormal = nextNormal;
              }
              if (currentVertex) {
                prevVertex = currentVertex;
              }
              currentVertex = vertices[i$1];
              nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;
              prevNormal = prevNormal || nextNormal;
              var joinNormal = prevNormal.add(nextNormal);
              if (joinNormal.x !== 0 || joinNormal.y !== 0) {
                joinNormal._unit();
              }
              var cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y;
              var cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;
              var miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;
              var approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle);
              var isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex;
              var lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0;
              if (isSharpCorner && i$1 > first) {
                var prevSegmentLength = currentVertex.dist(prevVertex);
                if (prevSegmentLength > 2 * sharpCornerOffset) {
                  var newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round());
                  this.updateDistance(prevVertex, newPrevVertex);
                  this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment);
                  prevVertex = newPrevVertex;
                }
              }
              var middleVertex = prevVertex && nextVertex;
              var currentJoin = middleVertex ? join : isPolygon ? "butt" : cap;
              if (middleVertex && currentJoin === "round") {
                if (miterLength < roundLimit) {
                  currentJoin = "miter";
                } else if (miterLength <= 2) {
                  currentJoin = "fakeround";
                }
              }
              if (currentJoin === "miter" && miterLength > miterLimit) {
                currentJoin = "bevel";
              }
              if (currentJoin === "bevel") {
                if (miterLength > 2) {
                  currentJoin = "flipbevel";
                }
                if (miterLength < miterLimit) {
                  currentJoin = "miter";
                }
              }
              if (prevVertex) {
                this.updateDistance(prevVertex, currentVertex);
              }
              if (currentJoin === "miter") {
                joinNormal._mult(miterLength);
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);
              } else if (currentJoin === "flipbevel") {
                if (miterLength > 100) {
                  joinNormal = nextNormal.mult(-1);
                } else {
                  var bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag();
                  joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1));
                }
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);
                this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment);
              } else if (currentJoin === "bevel" || currentJoin === "fakeround") {
                var offset = -Math.sqrt(miterLength * miterLength - 1);
                var offsetA = lineTurnsLeft ? offset : 0;
                var offsetB = lineTurnsLeft ? 0 : offset;
                if (prevVertex) {
                  this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment);
                }
                if (currentJoin === "fakeround") {
                  var n = Math.round(approxAngle * 180 / Math.PI / DEG_PER_TRIANGLE);
                  for (var m = 1; m < n; m++) {
                    var t = m / n;
                    if (t !== 0.5) {
                      var t23 = t - 0.5;
                      var A2 = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519));
                      var B2 = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638);
                      t = t + t * t23 * (t - 1) * (A2 * t23 * t23 + B2);
                    }
                    var extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1);
                    this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment);
                  }
                }
                if (nextVertex) {
                  this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment);
                }
              } else if (currentJoin === "butt") {
                this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);
              } else if (currentJoin === "square") {
                var offset$1 = prevVertex ? 1 : -1;
                this.addCurrentVertex(currentVertex, joinNormal, offset$1, offset$1, segment);
              } else if (currentJoin === "round") {
                if (prevVertex) {
                  this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment);
                  this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true);
                }
                if (nextVertex) {
                  this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true);
                  this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment);
                }
              }
              if (isSharpCorner && i$1 < len - 1) {
                var nextSegmentLength = currentVertex.dist(nextVertex);
                if (nextSegmentLength > 2 * sharpCornerOffset) {
                  var newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round());
                  this.updateDistance(currentVertex, newCurrentVertex);
                  this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment);
                  currentVertex = newCurrentVertex;
                }
              }
            }
          };
          LineBucket.prototype.addCurrentVertex = function addCurrentVertex(p, normal, endLeft, endRight, segment, round) {
            if (round === void 0)
              round = false;
            var leftX = normal.x + normal.y * endLeft;
            var leftY = normal.y - normal.x * endLeft;
            var rightX = -normal.x + normal.y * endRight;
            var rightY = -normal.y - normal.x * endRight;
            this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment);
            this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment);
            if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) {
              this.distance = 0;
              this.addCurrentVertex(p, normal, endLeft, endRight, segment, round);
            }
          };
          LineBucket.prototype.addHalfVertex = function addHalfVertex(ref, extrudeX, extrudeY, round, up, dir, segment) {
            var x = ref.x;
            var y = ref.y;
            var totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance;
            var linesofarScaled = totalDistance * LINE_DISTANCE_SCALE;
            this.layoutVertexArray.emplaceBack((x << 1) + (round ? 1 : 0), (y << 1) + (up ? 1 : 0), Math.round(EXTRUDE_SCALE * extrudeX) + 128, Math.round(EXTRUDE_SCALE * extrudeY) + 128, (dir === 0 ? 0 : dir < 0 ? -1 : 1) + 1 | (linesofarScaled & 63) << 2, linesofarScaled >> 6);
            if (this.lineClips) {
              var progressRealigned = this.scaledDistance - this.lineClips.start;
              var endClipRealigned = this.lineClips.end - this.lineClips.start;
              var uvX = progressRealigned / endClipRealigned;
              this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length);
            }
            var e = segment.vertexLength++;
            if (this.e1 >= 0 && this.e2 >= 0) {
              this.indexArray.emplaceBack(this.e1, this.e2, e);
              segment.primitiveLength++;
            }
            if (up) {
              this.e2 = e;
            } else {
              this.e1 = e;
            }
          };
          LineBucket.prototype.updateScaledDistance = function updateScaledDistance() {
            this.scaledDistance = this.lineClips ? this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance : this.distance;
          };
          LineBucket.prototype.updateDistance = function updateDistance(prev, next) {
            this.distance += prev.dist(next);
            this.updateScaledDistance();
          };
          register("LineBucket", LineBucket, {
            omit: [
              "layers",
              "patternFeatures"
            ]
          });
          var layout$6 = new Properties({
            "line-cap": new DataConstantProperty(spec["layout_line"]["line-cap"]),
            "line-join": new DataDrivenProperty(spec["layout_line"]["line-join"]),
            "line-miter-limit": new DataConstantProperty(spec["layout_line"]["line-miter-limit"]),
            "line-round-limit": new DataConstantProperty(spec["layout_line"]["line-round-limit"]),
            "line-sort-key": new DataDrivenProperty(spec["layout_line"]["line-sort-key"])
          });
          var paint$6 = new Properties({
            "line-opacity": new DataDrivenProperty(spec["paint_line"]["line-opacity"]),
            "line-color": new DataDrivenProperty(spec["paint_line"]["line-color"]),
            "line-translate": new DataConstantProperty(spec["paint_line"]["line-translate"]),
            "line-translate-anchor": new DataConstantProperty(spec["paint_line"]["line-translate-anchor"]),
            "line-width": new DataDrivenProperty(spec["paint_line"]["line-width"]),
            "line-gap-width": new DataDrivenProperty(spec["paint_line"]["line-gap-width"]),
            "line-offset": new DataDrivenProperty(spec["paint_line"]["line-offset"]),
            "line-blur": new DataDrivenProperty(spec["paint_line"]["line-blur"]),
            "line-dasharray": new CrossFadedProperty(spec["paint_line"]["line-dasharray"]),
            "line-pattern": new CrossFadedDataDrivenProperty(spec["paint_line"]["line-pattern"]),
            "line-gradient": new ColorRampProperty(spec["paint_line"]["line-gradient"])
          });
          var properties$5 = {
            paint: paint$6,
            layout: layout$6
          };
          var LineFloorwidthProperty = function(DataDrivenProperty2) {
            function LineFloorwidthProperty2() {
              DataDrivenProperty2.apply(this, arguments);
            }
            if (DataDrivenProperty2)
              LineFloorwidthProperty2.__proto__ = DataDrivenProperty2;
            LineFloorwidthProperty2.prototype = Object.create(DataDrivenProperty2 && DataDrivenProperty2.prototype);
            LineFloorwidthProperty2.prototype.constructor = LineFloorwidthProperty2;
            LineFloorwidthProperty2.prototype.possiblyEvaluate = function possiblyEvaluate(value, parameters) {
              parameters = new EvaluationParameters(Math.floor(parameters.zoom), {
                now: parameters.now,
                fadeDuration: parameters.fadeDuration,
                zoomHistory: parameters.zoomHistory,
                transition: parameters.transition
              });
              return DataDrivenProperty2.prototype.possiblyEvaluate.call(this, value, parameters);
            };
            LineFloorwidthProperty2.prototype.evaluate = function evaluate(value, globals, feature, featureState) {
              globals = extend2({}, globals, { zoom: Math.floor(globals.zoom) });
              return DataDrivenProperty2.prototype.evaluate.call(this, value, globals, feature, featureState);
            };
            return LineFloorwidthProperty2;
          }(DataDrivenProperty);
          var lineFloorwidthProperty = new LineFloorwidthProperty(properties$5.paint.properties["line-width"].specification);
          lineFloorwidthProperty.useIntegerZoom = true;
          var LineStyleLayer = function(StyleLayer2) {
            function LineStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$5);
              this.gradientVersion = 0;
            }
            if (StyleLayer2)
              LineStyleLayer2.__proto__ = StyleLayer2;
            LineStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            LineStyleLayer2.prototype.constructor = LineStyleLayer2;
            LineStyleLayer2.prototype._handleSpecialPaintPropertyUpdate = function _handleSpecialPaintPropertyUpdate(name3) {
              if (name3 === "line-gradient") {
                var expression2 = this._transitionablePaint._values["line-gradient"].value.expression;
                this.stepInterpolant = expression2._styleExpression.expression instanceof Step;
                this.gradientVersion = (this.gradientVersion + 1) % MAX_SAFE_INTEGER;
              }
            };
            LineStyleLayer2.prototype.gradientExpression = function gradientExpression() {
              return this._transitionablePaint._values["line-gradient"].value.expression;
            };
            LineStyleLayer2.prototype.recalculate = function recalculate(parameters, availableImages) {
              StyleLayer2.prototype.recalculate.call(this, parameters, availableImages);
              this.paint._values["line-floorwidth"] = lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values["line-width"].value, parameters);
            };
            LineStyleLayer2.prototype.createBucket = function createBucket(parameters) {
              return new LineBucket(parameters);
            };
            LineStyleLayer2.prototype.queryRadius = function queryRadius(bucket) {
              var lineBucket = bucket;
              var width = getLineWidth(getMaximumPaintValue("line-width", this, lineBucket), getMaximumPaintValue("line-gap-width", this, lineBucket));
              var offset = getMaximumPaintValue("line-offset", this, lineBucket);
              return width / 2 + Math.abs(offset) + translateDistance(this.paint.get("line-translate"));
            };
            LineStyleLayer2.prototype.queryIntersectsFeature = function queryIntersectsFeature(queryGeometry, feature, featureState, geometry, zoom, transform, pixelsToTileUnits) {
              var translatedPolygon = translate(queryGeometry, this.paint.get("line-translate"), this.paint.get("line-translate-anchor"), transform.angle, pixelsToTileUnits);
              var halfWidth = pixelsToTileUnits / 2 * getLineWidth(this.paint.get("line-width").evaluate(feature, featureState), this.paint.get("line-gap-width").evaluate(feature, featureState));
              var lineOffset = this.paint.get("line-offset").evaluate(feature, featureState);
              if (lineOffset) {
                geometry = offsetLine(geometry, lineOffset * pixelsToTileUnits);
              }
              return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth);
            };
            LineStyleLayer2.prototype.isTileClipped = function isTileClipped() {
              return true;
            };
            return LineStyleLayer2;
          }(StyleLayer);
          function getLineWidth(lineWidth, lineGapWidth) {
            if (lineGapWidth > 0) {
              return lineGapWidth + 2 * lineWidth;
            } else {
              return lineWidth;
            }
          }
          function offsetLine(rings, offset) {
            var newRings = [];
            var zero2 = new pointGeometry(0, 0);
            for (var k = 0; k < rings.length; k++) {
              var ring = rings[k];
              var newRing = [];
              for (var i = 0; i < ring.length; i++) {
                var a = ring[i - 1];
                var b = ring[i];
                var c = ring[i + 1];
                var aToB = i === 0 ? zero2 : b.sub(a)._unit()._perp();
                var bToC = i === ring.length - 1 ? zero2 : c.sub(b)._unit()._perp();
                var extrude = aToB._add(bToC)._unit();
                var cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y;
                extrude._mult(1 / cosHalfAngle);
                newRing.push(extrude._mult(offset)._add(b));
              }
              newRings.push(newRing);
            }
            return newRings;
          }
          var symbolLayoutAttributes = createLayout([
            {
              name: "a_pos_offset",
              components: 4,
              type: "Int16"
            },
            {
              name: "a_data",
              components: 4,
              type: "Uint16"
            },
            {
              name: "a_pixeloffset",
              components: 4,
              type: "Int16"
            }
          ], 4);
          var dynamicLayoutAttributes = createLayout([{
            name: "a_projected_pos",
            components: 3,
            type: "Float32"
          }], 4);
          var placementOpacityAttributes = createLayout([{
            name: "a_fade_opacity",
            components: 1,
            type: "Uint32"
          }], 4);
          var collisionVertexAttributes = createLayout([
            {
              name: "a_placed",
              components: 2,
              type: "Uint8"
            },
            {
              name: "a_shift",
              components: 2,
              type: "Float32"
            }
          ]);
          var collisionBox = createLayout([
            {
              type: "Int16",
              name: "anchorPointX"
            },
            {
              type: "Int16",
              name: "anchorPointY"
            },
            {
              type: "Int16",
              name: "x1"
            },
            {
              type: "Int16",
              name: "y1"
            },
            {
              type: "Int16",
              name: "x2"
            },
            {
              type: "Int16",
              name: "y2"
            },
            {
              type: "Uint32",
              name: "featureIndex"
            },
            {
              type: "Uint16",
              name: "sourceLayerIndex"
            },
            {
              type: "Uint16",
              name: "bucketIndex"
            }
          ]);
          var collisionBoxLayout = createLayout([
            {
              name: "a_pos",
              components: 2,
              type: "Int16"
            },
            {
              name: "a_anchor_pos",
              components: 2,
              type: "Int16"
            },
            {
              name: "a_extrude",
              components: 2,
              type: "Int16"
            }
          ], 4);
          var collisionCircleLayout = createLayout([
            {
              name: "a_pos",
              components: 2,
              type: "Float32"
            },
            {
              name: "a_radius",
              components: 1,
              type: "Float32"
            },
            {
              name: "a_flags",
              components: 2,
              type: "Int16"
            }
          ], 4);
          var quadTriangle = createLayout([{
            name: "triangle",
            components: 3,
            type: "Uint16"
          }]);
          var placement = createLayout([
            {
              type: "Int16",
              name: "anchorX"
            },
            {
              type: "Int16",
              name: "anchorY"
            },
            {
              type: "Uint16",
              name: "glyphStartIndex"
            },
            {
              type: "Uint16",
              name: "numGlyphs"
            },
            {
              type: "Uint32",
              name: "vertexStartIndex"
            },
            {
              type: "Uint32",
              name: "lineStartIndex"
            },
            {
              type: "Uint32",
              name: "lineLength"
            },
            {
              type: "Uint16",
              name: "segment"
            },
            {
              type: "Uint16",
              name: "lowerSize"
            },
            {
              type: "Uint16",
              name: "upperSize"
            },
            {
              type: "Float32",
              name: "lineOffsetX"
            },
            {
              type: "Float32",
              name: "lineOffsetY"
            },
            {
              type: "Uint8",
              name: "writingMode"
            },
            {
              type: "Uint8",
              name: "placedOrientation"
            },
            {
              type: "Uint8",
              name: "hidden"
            },
            {
              type: "Uint32",
              name: "crossTileID"
            },
            {
              type: "Int16",
              name: "associatedIconIndex"
            }
          ]);
          var symbolInstance = createLayout([
            {
              type: "Int16",
              name: "anchorX"
            },
            {
              type: "Int16",
              name: "anchorY"
            },
            {
              type: "Int16",
              name: "rightJustifiedTextSymbolIndex"
            },
            {
              type: "Int16",
              name: "centerJustifiedTextSymbolIndex"
            },
            {
              type: "Int16",
              name: "leftJustifiedTextSymbolIndex"
            },
            {
              type: "Int16",
              name: "verticalPlacedTextSymbolIndex"
            },
            {
              type: "Int16",
              name: "placedIconSymbolIndex"
            },
            {
              type: "Int16",
              name: "verticalPlacedIconSymbolIndex"
            },
            {
              type: "Uint16",
              name: "key"
            },
            {
              type: "Uint16",
              name: "textBoxStartIndex"
            },
            {
              type: "Uint16",
              name: "textBoxEndIndex"
            },
            {
              type: "Uint16",
              name: "verticalTextBoxStartIndex"
            },
            {
              type: "Uint16",
              name: "verticalTextBoxEndIndex"
            },
            {
              type: "Uint16",
              name: "iconBoxStartIndex"
            },
            {
              type: "Uint16",
              name: "iconBoxEndIndex"
            },
            {
              type: "Uint16",
              name: "verticalIconBoxStartIndex"
            },
            {
              type: "Uint16",
              name: "verticalIconBoxEndIndex"
            },
            {
              type: "Uint16",
              name: "featureIndex"
            },
            {
              type: "Uint16",
              name: "numHorizontalGlyphVertices"
            },
            {
              type: "Uint16",
              name: "numVerticalGlyphVertices"
            },
            {
              type: "Uint16",
              name: "numIconVertices"
            },
            {
              type: "Uint16",
              name: "numVerticalIconVertices"
            },
            {
              type: "Uint16",
              name: "useRuntimeCollisionCircles"
            },
            {
              type: "Uint32",
              name: "crossTileID"
            },
            {
              type: "Float32",
              name: "textBoxScale"
            },
            {
              type: "Float32",
              components: 2,
              name: "textOffset"
            },
            {
              type: "Float32",
              name: "collisionCircleDiameter"
            }
          ]);
          var glyphOffset = createLayout([{
            type: "Float32",
            name: "offsetX"
          }]);
          var lineVertex = createLayout([
            {
              type: "Int16",
              name: "x"
            },
            {
              type: "Int16",
              name: "y"
            },
            {
              type: "Int16",
              name: "tileUnitDistanceFromAnchor"
            }
          ]);
          function transformText(text, layer2, feature) {
            var transform = layer2.layout.get("text-transform").evaluate(feature, {});
            if (transform === "uppercase") {
              text = text.toLocaleUpperCase();
            } else if (transform === "lowercase") {
              text = text.toLocaleLowerCase();
            }
            if (plugin.applyArabicShaping) {
              text = plugin.applyArabicShaping(text);
            }
            return text;
          }
          function transformText$1(text, layer2, feature) {
            text.sections.forEach(function(section) {
              section.text = transformText(section.text, layer2, feature);
            });
            return text;
          }
          function mergeLines(features) {
            var leftIndex = {};
            var rightIndex = {};
            var mergedFeatures = [];
            var mergedIndex = 0;
            function add2(k2) {
              mergedFeatures.push(features[k2]);
              mergedIndex++;
            }
            function mergeFromRight(leftKey2, rightKey2, geom2) {
              var i2 = rightIndex[leftKey2];
              delete rightIndex[leftKey2];
              rightIndex[rightKey2] = i2;
              mergedFeatures[i2].geometry[0].pop();
              mergedFeatures[i2].geometry[0] = mergedFeatures[i2].geometry[0].concat(geom2[0]);
              return i2;
            }
            function mergeFromLeft(leftKey2, rightKey2, geom2) {
              var i2 = leftIndex[rightKey2];
              delete leftIndex[rightKey2];
              leftIndex[leftKey2] = i2;
              mergedFeatures[i2].geometry[0].shift();
              mergedFeatures[i2].geometry[0] = geom2[0].concat(mergedFeatures[i2].geometry[0]);
              return i2;
            }
            function getKey(text2, geom2, onRight) {
              var point = onRight ? geom2[0][geom2[0].length - 1] : geom2[0][0];
              return text2 + ":" + point.x + ":" + point.y;
            }
            for (var k = 0; k < features.length; k++) {
              var feature = features[k];
              var geom = feature.geometry;
              var text = feature.text ? feature.text.toString() : null;
              if (!text) {
                add2(k);
                continue;
              }
              var leftKey = getKey(text, geom), rightKey = getKey(text, geom, true);
              if (leftKey in rightIndex && rightKey in leftIndex && rightIndex[leftKey] !== leftIndex[rightKey]) {
                var j = mergeFromLeft(leftKey, rightKey, geom);
                var i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry);
                delete leftIndex[leftKey];
                delete rightIndex[rightKey];
                rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i;
                mergedFeatures[j].geometry = null;
              } else if (leftKey in rightIndex) {
                mergeFromRight(leftKey, rightKey, geom);
              } else if (rightKey in leftIndex) {
                mergeFromLeft(leftKey, rightKey, geom);
              } else {
                add2(k);
                leftIndex[leftKey] = mergedIndex - 1;
                rightIndex[rightKey] = mergedIndex - 1;
              }
            }
            return mergedFeatures.filter(function(f) {
              return f.geometry;
            });
          }
          var verticalizedCharacterMap = {
            "!": "\uFE15",
            "#": "\uFF03",
            "$": "\uFF04",
            "%": "\uFF05",
            "&": "\uFF06",
            "(": "\uFE35",
            ")": "\uFE36",
            "*": "\uFF0A",
            "+": "\uFF0B",
            ",": "\uFE10",
            "-": "\uFE32",
            ".": "\u30FB",
            "/": "\uFF0F",
            ":": "\uFE13",
            ";": "\uFE14",
            "<": "\uFE3F",
            "=": "\uFF1D",
            ">": "\uFE40",
            "?": "\uFE16",
            "@": "\uFF20",
            "[": "\uFE47",
            "\\": "\uFF3C",
            "]": "\uFE48",
            "^": "\uFF3E",
            "_": "\uFE33",
            "`": "\uFF40",
            "{": "\uFE37",
            "|": "\u2015",
            "}": "\uFE38",
            "~": "\uFF5E",
            "\xA2": "\uFFE0",
            "\xA3": "\uFFE1",
            "\xA5": "\uFFE5",
            "\xA6": "\uFFE4",
            "\xAC": "\uFFE2",
            "\xAF": "\uFFE3",
            "\u2013": "\uFE32",
            "\u2014": "\uFE31",
            "\u2018": "\uFE43",
            "\u2019": "\uFE44",
            "\u201C": "\uFE41",
            "\u201D": "\uFE42",
            "\u2026": "\uFE19",
            "\u2027": "\u30FB",
            "\u20A9": "\uFFE6",
            "\u3001": "\uFE11",
            "\u3002": "\uFE12",
            "\u3008": "\uFE3F",
            "\u3009": "\uFE40",
            "\u300A": "\uFE3D",
            "\u300B": "\uFE3E",
            "\u300C": "\uFE41",
            "\u300D": "\uFE42",
            "\u300E": "\uFE43",
            "\u300F": "\uFE44",
            "\u3010": "\uFE3B",
            "\u3011": "\uFE3C",
            "\u3014": "\uFE39",
            "\u3015": "\uFE3A",
            "\u3016": "\uFE17",
            "\u3017": "\uFE18",
            "\uFF01": "\uFE15",
            "\uFF08": "\uFE35",
            "\uFF09": "\uFE36",
            "\uFF0C": "\uFE10",
            "\uFF0D": "\uFE32",
            "\uFF0E": "\u30FB",
            "\uFF1A": "\uFE13",
            "\uFF1B": "\uFE14",
            "\uFF1C": "\uFE3F",
            "\uFF1E": "\uFE40",
            "\uFF1F": "\uFE16",
            "\uFF3B": "\uFE47",
            "\uFF3D": "\uFE48",
            "\uFF3F": "\uFE33",
            "\uFF5B": "\uFE37",
            "\uFF5C": "\u2015",
            "\uFF5D": "\uFE38",
            "\uFF5F": "\uFE35",
            "\uFF60": "\uFE36",
            "\uFF61": "\uFE12",
            "\uFF62": "\uFE41",
            "\uFF63": "\uFE42"
          };
          function verticalizePunctuation(input) {
            var output = "";
            for (var i = 0; i < input.length; i++) {
              var nextCharCode = input.charCodeAt(i + 1) || null;
              var prevCharCode = input.charCodeAt(i - 1) || null;
              var canReplacePunctuation = (!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) && (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]]);
              if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) {
                output += verticalizedCharacterMap[input[i]];
              } else {
                output += input[i];
              }
            }
            return output;
          }
          var ONE_EM = 24;
          var read = function(buffer, offset, isLE, mLen, nBytes) {
            var e, m;
            var eLen = nBytes * 8 - mLen - 1;
            var eMax = (1 << eLen) - 1;
            var eBias = eMax >> 1;
            var nBits = -7;
            var i = isLE ? nBytes - 1 : 0;
            var d = isLE ? -1 : 1;
            var s = buffer[offset + i];
            i += d;
            e = s & (1 << -nBits) - 1;
            s >>= -nBits;
            nBits += eLen;
            for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
            }
            m = e & (1 << -nBits) - 1;
            e >>= -nBits;
            nBits += mLen;
            for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
            }
            if (e === 0) {
              e = 1 - eBias;
            } else if (e === eMax) {
              return m ? NaN : (s ? -1 : 1) * Infinity;
            } else {
              m = m + Math.pow(2, mLen);
              e = e - eBias;
            }
            return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
          };
          var write = function(buffer, value, offset, isLE, mLen, nBytes) {
            var e, m, c;
            var eLen = nBytes * 8 - mLen - 1;
            var eMax = (1 << eLen) - 1;
            var eBias = eMax >> 1;
            var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
            var i = isLE ? 0 : nBytes - 1;
            var d = isLE ? 1 : -1;
            var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
            value = Math.abs(value);
            if (isNaN(value) || value === Infinity) {
              m = isNaN(value) ? 1 : 0;
              e = eMax;
            } else {
              e = Math.floor(Math.log(value) / Math.LN2);
              if (value * (c = Math.pow(2, -e)) < 1) {
                e--;
                c *= 2;
              }
              if (e + eBias >= 1) {
                value += rt / c;
              } else {
                value += rt * Math.pow(2, 1 - eBias);
              }
              if (value * c >= 2) {
                e++;
                c /= 2;
              }
              if (e + eBias >= eMax) {
                m = 0;
                e = eMax;
              } else if (e + eBias >= 1) {
                m = (value * c - 1) * Math.pow(2, mLen);
                e = e + eBias;
              } else {
                m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
                e = 0;
              }
            }
            for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
            }
            e = e << mLen | m;
            eLen += mLen;
            for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
            }
            buffer[offset + i - d] |= s * 128;
          };
          var ieee754 = {
            read,
            write
          };
          var pbf = Pbf;
          function Pbf(buf) {
            this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
            this.pos = 0;
            this.type = 0;
            this.length = this.buf.length;
          }
          Pbf.Varint = 0;
          Pbf.Fixed64 = 1;
          Pbf.Bytes = 2;
          Pbf.Fixed32 = 5;
          var SHIFT_LEFT_32 = (1 << 16) * (1 << 16), SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
          var TEXT_DECODER_MIN_LENGTH = 12;
          var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf8");
          Pbf.prototype = {
            destroy: function() {
              this.buf = null;
            },
            readFields: function(readField, result, end) {
              end = end || this.length;
              while (this.pos < end) {
                var val = this.readVarint(), tag = val >> 3, startPos = this.pos;
                this.type = val & 7;
                readField(tag, result, this);
                if (this.pos === startPos) {
                  this.skip(val);
                }
              }
              return result;
            },
            readMessage: function(readField, result) {
              return this.readFields(readField, result, this.readVarint() + this.pos);
            },
            readFixed32: function() {
              var val = readUInt32(this.buf, this.pos);
              this.pos += 4;
              return val;
            },
            readSFixed32: function() {
              var val = readInt32(this.buf, this.pos);
              this.pos += 4;
              return val;
            },
            readFixed64: function() {
              var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
              this.pos += 8;
              return val;
            },
            readSFixed64: function() {
              var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
              this.pos += 8;
              return val;
            },
            readFloat: function() {
              var val = ieee754.read(this.buf, this.pos, true, 23, 4);
              this.pos += 4;
              return val;
            },
            readDouble: function() {
              var val = ieee754.read(this.buf, this.pos, true, 52, 8);
              this.pos += 8;
              return val;
            },
            readVarint: function(isSigned) {
              var buf = this.buf, val, b;
              b = buf[this.pos++];
              val = b & 127;
              if (b < 128) {
                return val;
              }
              b = buf[this.pos++];
              val |= (b & 127) << 7;
              if (b < 128) {
                return val;
              }
              b = buf[this.pos++];
              val |= (b & 127) << 14;
              if (b < 128) {
                return val;
              }
              b = buf[this.pos++];
              val |= (b & 127) << 21;
              if (b < 128) {
                return val;
              }
              b = buf[this.pos];
              val |= (b & 15) << 28;
              return readVarintRemainder(val, isSigned, this);
            },
            readVarint64: function() {
              return this.readVarint(true);
            },
            readSVarint: function() {
              var num = this.readVarint();
              return num % 2 === 1 ? (num + 1) / -2 : num / 2;
            },
            readBoolean: function() {
              return Boolean(this.readVarint());
            },
            readString: function() {
              var end = this.readVarint() + this.pos;
              var pos = this.pos;
              this.pos = end;
              if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) {
                return readUtf8TextDecoder(this.buf, pos, end);
              }
              return readUtf8(this.buf, pos, end);
            },
            readBytes: function() {
              var end = this.readVarint() + this.pos, buffer = this.buf.subarray(this.pos, end);
              this.pos = end;
              return buffer;
            },
            readPackedVarint: function(arr, isSigned) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readVarint(isSigned));
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readVarint(isSigned));
              }
              return arr;
            },
            readPackedSVarint: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readSVarint());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readSVarint());
              }
              return arr;
            },
            readPackedBoolean: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readBoolean());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readBoolean());
              }
              return arr;
            },
            readPackedFloat: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readFloat());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readFloat());
              }
              return arr;
            },
            readPackedDouble: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readDouble());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readDouble());
              }
              return arr;
            },
            readPackedFixed32: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readFixed32());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readFixed32());
              }
              return arr;
            },
            readPackedSFixed32: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readSFixed32());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readSFixed32());
              }
              return arr;
            },
            readPackedFixed64: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readFixed64());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readFixed64());
              }
              return arr;
            },
            readPackedSFixed64: function(arr) {
              if (this.type !== Pbf.Bytes) {
                return arr.push(this.readSFixed64());
              }
              var end = readPackedEnd(this);
              arr = arr || [];
              while (this.pos < end) {
                arr.push(this.readSFixed64());
              }
              return arr;
            },
            skip: function(val) {
              var type = val & 7;
              if (type === Pbf.Varint) {
                while (this.buf[this.pos++] > 127) {
                }
              } else if (type === Pbf.Bytes) {
                this.pos = this.readVarint() + this.pos;
              } else if (type === Pbf.Fixed32) {
                this.pos += 4;
              } else if (type === Pbf.Fixed64) {
                this.pos += 8;
              } else {
                throw new Error("Unimplemented type: " + type);
              }
            },
            writeTag: function(tag, type) {
              this.writeVarint(tag << 3 | type);
            },
            realloc: function(min) {
              var length = this.length || 16;
              while (length < this.pos + min) {
                length *= 2;
              }
              if (length !== this.length) {
                var buf = new Uint8Array(length);
                buf.set(this.buf);
                this.buf = buf;
                this.length = length;
              }
            },
            finish: function() {
              this.length = this.pos;
              this.pos = 0;
              return this.buf.subarray(0, this.length);
            },
            writeFixed32: function(val) {
              this.realloc(4);
              writeInt32(this.buf, val, this.pos);
              this.pos += 4;
            },
            writeSFixed32: function(val) {
              this.realloc(4);
              writeInt32(this.buf, val, this.pos);
              this.pos += 4;
            },
            writeFixed64: function(val) {
              this.realloc(8);
              writeInt32(this.buf, val & -1, this.pos);
              writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
              this.pos += 8;
            },
            writeSFixed64: function(val) {
              this.realloc(8);
              writeInt32(this.buf, val & -1, this.pos);
              writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
              this.pos += 8;
            },
            writeVarint: function(val) {
              val = +val || 0;
              if (val > 268435455 || val < 0) {
                writeBigVarint(val, this);
                return;
              }
              this.realloc(4);
              this.buf[this.pos++] = val & 127 | (val > 127 ? 128 : 0);
              if (val <= 127) {
                return;
              }
              this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0);
              if (val <= 127) {
                return;
              }
              this.buf[this.pos++] = (val >>>= 7) & 127 | (val > 127 ? 128 : 0);
              if (val <= 127) {
                return;
              }
              this.buf[this.pos++] = val >>> 7 & 127;
            },
            writeSVarint: function(val) {
              this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
            },
            writeBoolean: function(val) {
              this.writeVarint(Boolean(val));
            },
            writeString: function(str) {
              str = String(str);
              this.realloc(str.length * 4);
              this.pos++;
              var startPos = this.pos;
              this.pos = writeUtf8(this.buf, str, this.pos);
              var len = this.pos - startPos;
              if (len >= 128) {
                makeRoomForExtraLength(startPos, len, this);
              }
              this.pos = startPos - 1;
              this.writeVarint(len);
              this.pos += len;
            },
            writeFloat: function(val) {
              this.realloc(4);
              ieee754.write(this.buf, val, this.pos, true, 23, 4);
              this.pos += 4;
            },
            writeDouble: function(val) {
              this.realloc(8);
              ieee754.write(this.buf, val, this.pos, true, 52, 8);
              this.pos += 8;
            },
            writeBytes: function(buffer) {
              var len = buffer.length;
              this.writeVarint(len);
              this.realloc(len);
              for (var i = 0; i < len; i++) {
                this.buf[this.pos++] = buffer[i];
              }
            },
            writeRawMessage: function(fn, obj) {
              this.pos++;
              var startPos = this.pos;
              fn(obj, this);
              var len = this.pos - startPos;
              if (len >= 128) {
                makeRoomForExtraLength(startPos, len, this);
              }
              this.pos = startPos - 1;
              this.writeVarint(len);
              this.pos += len;
            },
            writeMessage: function(tag, fn, obj) {
              this.writeTag(tag, Pbf.Bytes);
              this.writeRawMessage(fn, obj);
            },
            writePackedVarint: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedVarint, arr);
              }
            },
            writePackedSVarint: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedSVarint, arr);
              }
            },
            writePackedBoolean: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedBoolean, arr);
              }
            },
            writePackedFloat: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedFloat, arr);
              }
            },
            writePackedDouble: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedDouble, arr);
              }
            },
            writePackedFixed32: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedFixed32, arr);
              }
            },
            writePackedSFixed32: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedSFixed32, arr);
              }
            },
            writePackedFixed64: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedFixed64, arr);
              }
            },
            writePackedSFixed64: function(tag, arr) {
              if (arr.length) {
                this.writeMessage(tag, writePackedSFixed64, arr);
              }
            },
            writeBytesField: function(tag, buffer) {
              this.writeTag(tag, Pbf.Bytes);
              this.writeBytes(buffer);
            },
            writeFixed32Field: function(tag, val) {
              this.writeTag(tag, Pbf.Fixed32);
              this.writeFixed32(val);
            },
            writeSFixed32Field: function(tag, val) {
              this.writeTag(tag, Pbf.Fixed32);
              this.writeSFixed32(val);
            },
            writeFixed64Field: function(tag, val) {
              this.writeTag(tag, Pbf.Fixed64);
              this.writeFixed64(val);
            },
            writeSFixed64Field: function(tag, val) {
              this.writeTag(tag, Pbf.Fixed64);
              this.writeSFixed64(val);
            },
            writeVarintField: function(tag, val) {
              this.writeTag(tag, Pbf.Varint);
              this.writeVarint(val);
            },
            writeSVarintField: function(tag, val) {
              this.writeTag(tag, Pbf.Varint);
              this.writeSVarint(val);
            },
            writeStringField: function(tag, str) {
              this.writeTag(tag, Pbf.Bytes);
              this.writeString(str);
            },
            writeFloatField: function(tag, val) {
              this.writeTag(tag, Pbf.Fixed32);
              this.writeFloat(val);
            },
            writeDoubleField: function(tag, val) {
              this.writeTag(tag, Pbf.Fixed64);
              this.writeDouble(val);
            },
            writeBooleanField: function(tag, val) {
              this.writeVarintField(tag, Boolean(val));
            }
          };
          function readVarintRemainder(l, s, p) {
            var buf = p.buf, h, b;
            b = buf[p.pos++];
            h = (b & 112) >> 4;
            if (b < 128) {
              return toNum(l, h, s);
            }
            b = buf[p.pos++];
            h |= (b & 127) << 3;
            if (b < 128) {
              return toNum(l, h, s);
            }
            b = buf[p.pos++];
            h |= (b & 127) << 10;
            if (b < 128) {
              return toNum(l, h, s);
            }
            b = buf[p.pos++];
            h |= (b & 127) << 17;
            if (b < 128) {
              return toNum(l, h, s);
            }
            b = buf[p.pos++];
            h |= (b & 127) << 24;
            if (b < 128) {
              return toNum(l, h, s);
            }
            b = buf[p.pos++];
            h |= (b & 1) << 31;
            if (b < 128) {
              return toNum(l, h, s);
            }
            throw new Error("Expected varint not more than 10 bytes");
          }
          function readPackedEnd(pbf2) {
            return pbf2.type === Pbf.Bytes ? pbf2.readVarint() + pbf2.pos : pbf2.pos + 1;
          }
          function toNum(low, high, isSigned) {
            if (isSigned) {
              return high * 4294967296 + (low >>> 0);
            }
            return (high >>> 0) * 4294967296 + (low >>> 0);
          }
          function writeBigVarint(val, pbf2) {
            var low, high;
            if (val >= 0) {
              low = val % 4294967296 | 0;
              high = val / 4294967296 | 0;
            } else {
              low = ~(-val % 4294967296);
              high = ~(-val / 4294967296);
              if (low ^ 4294967295) {
                low = low + 1 | 0;
              } else {
                low = 0;
                high = high + 1 | 0;
              }
            }
            if (val >= 18446744073709552e3 || val < -18446744073709552e3) {
              throw new Error("Given varint doesn't fit into 10 bytes");
            }
            pbf2.realloc(10);
            writeBigVarintLow(low, high, pbf2);
            writeBigVarintHigh(high, pbf2);
          }
          function writeBigVarintLow(low, high, pbf2) {
            pbf2.buf[pbf2.pos++] = low & 127 | 128;
            low >>>= 7;
            pbf2.buf[pbf2.pos++] = low & 127 | 128;
            low >>>= 7;
            pbf2.buf[pbf2.pos++] = low & 127 | 128;
            low >>>= 7;
            pbf2.buf[pbf2.pos++] = low & 127 | 128;
            low >>>= 7;
            pbf2.buf[pbf2.pos] = low & 127;
          }
          function writeBigVarintHigh(high, pbf2) {
            var lsb = (high & 7) << 4;
            pbf2.buf[pbf2.pos++] |= lsb | ((high >>>= 3) ? 128 : 0);
            if (!high) {
              return;
            }
            pbf2.buf[pbf2.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
            if (!high) {
              return;
            }
            pbf2.buf[pbf2.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
            if (!high) {
              return;
            }
            pbf2.buf[pbf2.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
            if (!high) {
              return;
            }
            pbf2.buf[pbf2.pos++] = high & 127 | ((high >>>= 7) ? 128 : 0);
            if (!high) {
              return;
            }
            pbf2.buf[pbf2.pos++] = high & 127;
          }
          function makeRoomForExtraLength(startPos, len, pbf2) {
            var extraLen = len <= 16383 ? 1 : len <= 2097151 ? 2 : len <= 268435455 ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7));
            pbf2.realloc(extraLen);
            for (var i = pbf2.pos - 1; i >= startPos; i--) {
              pbf2.buf[i + extraLen] = pbf2.buf[i];
            }
          }
          function writePackedVarint(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeVarint(arr[i]);
            }
          }
          function writePackedSVarint(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeSVarint(arr[i]);
            }
          }
          function writePackedFloat(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeFloat(arr[i]);
            }
          }
          function writePackedDouble(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeDouble(arr[i]);
            }
          }
          function writePackedBoolean(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeBoolean(arr[i]);
            }
          }
          function writePackedFixed32(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeFixed32(arr[i]);
            }
          }
          function writePackedSFixed32(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeSFixed32(arr[i]);
            }
          }
          function writePackedFixed64(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeFixed64(arr[i]);
            }
          }
          function writePackedSFixed64(arr, pbf2) {
            for (var i = 0; i < arr.length; i++) {
              pbf2.writeSFixed64(arr[i]);
            }
          }
          function readUInt32(buf, pos) {
            return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16) + buf[pos + 3] * 16777216;
          }
          function writeInt32(buf, val, pos) {
            buf[pos] = val;
            buf[pos + 1] = val >>> 8;
            buf[pos + 2] = val >>> 16;
            buf[pos + 3] = val >>> 24;
          }
          function readInt32(buf, pos) {
            return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16) + (buf[pos + 3] << 24);
          }
          function readUtf8(buf, pos, end) {
            var str = "";
            var i = pos;
            while (i < end) {
              var b0 = buf[i];
              var c = null;
              var bytesPerSequence = b0 > 239 ? 4 : b0 > 223 ? 3 : b0 > 191 ? 2 : 1;
              if (i + bytesPerSequence > end) {
                break;
              }
              var b1, b2, b3;
              if (bytesPerSequence === 1) {
                if (b0 < 128) {
                  c = b0;
                }
              } else if (bytesPerSequence === 2) {
                b1 = buf[i + 1];
                if ((b1 & 192) === 128) {
                  c = (b0 & 31) << 6 | b1 & 63;
                  if (c <= 127) {
                    c = null;
                  }
                }
              } else if (bytesPerSequence === 3) {
                b1 = buf[i + 1];
                b2 = buf[i + 2];
                if ((b1 & 192) === 128 && (b2 & 192) === 128) {
                  c = (b0 & 15) << 12 | (b1 & 63) << 6 | b2 & 63;
                  if (c <= 2047 || c >= 55296 && c <= 57343) {
                    c = null;
                  }
                }
              } else if (bytesPerSequence === 4) {
                b1 = buf[i + 1];
                b2 = buf[i + 2];
                b3 = buf[i + 3];
                if ((b1 & 192) === 128 && (b2 & 192) === 128 && (b3 & 192) === 128) {
                  c = (b0 & 15) << 18 | (b1 & 63) << 12 | (b2 & 63) << 6 | b3 & 63;
                  if (c <= 65535 || c >= 1114112) {
                    c = null;
                  }
                }
              }
              if (c === null) {
                c = 65533;
                bytesPerSequence = 1;
              } else if (c > 65535) {
                c -= 65536;
                str += String.fromCharCode(c >>> 10 & 1023 | 55296);
                c = 56320 | c & 1023;
              }
              str += String.fromCharCode(c);
              i += bytesPerSequence;
            }
            return str;
          }
          function readUtf8TextDecoder(buf, pos, end) {
            return utf8TextDecoder.decode(buf.subarray(pos, end));
          }
          function writeUtf8(buf, str, pos) {
            for (var i = 0, c, lead; i < str.length; i++) {
              c = str.charCodeAt(i);
              if (c > 55295 && c < 57344) {
                if (lead) {
                  if (c < 56320) {
                    buf[pos++] = 239;
                    buf[pos++] = 191;
                    buf[pos++] = 189;
                    lead = c;
                    continue;
                  } else {
                    c = lead - 55296 << 10 | c - 56320 | 65536;
                    lead = null;
                  }
                } else {
                  if (c > 56319 || i + 1 === str.length) {
                    buf[pos++] = 239;
                    buf[pos++] = 191;
                    buf[pos++] = 189;
                  } else {
                    lead = c;
                  }
                  continue;
                }
              } else if (lead) {
                buf[pos++] = 239;
                buf[pos++] = 191;
                buf[pos++] = 189;
                lead = null;
              }
              if (c < 128) {
                buf[pos++] = c;
              } else {
                if (c < 2048) {
                  buf[pos++] = c >> 6 | 192;
                } else {
                  if (c < 65536) {
                    buf[pos++] = c >> 12 | 224;
                  } else {
                    buf[pos++] = c >> 18 | 240;
                    buf[pos++] = c >> 12 & 63 | 128;
                  }
                  buf[pos++] = c >> 6 & 63 | 128;
                }
                buf[pos++] = c & 63 | 128;
              }
            }
            return pos;
          }
          var border = 3;
          function readFontstacks(tag, glyphs, pbf2) {
            if (tag === 1) {
              pbf2.readMessage(readFontstack, glyphs);
            }
          }
          function readFontstack(tag, glyphs, pbf2) {
            if (tag === 3) {
              var ref = pbf2.readMessage(readGlyph, {});
              var id2 = ref.id;
              var bitmap = ref.bitmap;
              var width = ref.width;
              var height = ref.height;
              var left = ref.left;
              var top = ref.top;
              var advance = ref.advance;
              glyphs.push({
                id: id2,
                bitmap: new AlphaImage({
                  width: width + 2 * border,
                  height: height + 2 * border
                }, bitmap),
                metrics: {
                  width,
                  height,
                  left,
                  top,
                  advance
                }
              });
            }
          }
          function readGlyph(tag, glyph, pbf2) {
            if (tag === 1) {
              glyph.id = pbf2.readVarint();
            } else if (tag === 2) {
              glyph.bitmap = pbf2.readBytes();
            } else if (tag === 3) {
              glyph.width = pbf2.readVarint();
            } else if (tag === 4) {
              glyph.height = pbf2.readVarint();
            } else if (tag === 5) {
              glyph.left = pbf2.readSVarint();
            } else if (tag === 6) {
              glyph.top = pbf2.readSVarint();
            } else if (tag === 7) {
              glyph.advance = pbf2.readVarint();
            }
          }
          function parseGlyphPBF(data) {
            return new pbf(data).readFields(readFontstacks, []);
          }
          var GLYPH_PBF_BORDER = border;
          function potpack(boxes) {
            var area2 = 0;
            var maxWidth = 0;
            for (var i$1 = 0, list = boxes; i$1 < list.length; i$1 += 1) {
              var box = list[i$1];
              area2 += box.w * box.h;
              maxWidth = Math.max(maxWidth, box.w);
            }
            boxes.sort(function(a, b) {
              return b.h - a.h;
            });
            var startWidth = Math.max(Math.ceil(Math.sqrt(area2 / 0.95)), maxWidth);
            var spaces = [{ x: 0, y: 0, w: startWidth, h: Infinity }];
            var width = 0;
            var height = 0;
            for (var i$2 = 0, list$1 = boxes; i$2 < list$1.length; i$2 += 1) {
              var box$1 = list$1[i$2];
              for (var i = spaces.length - 1; i >= 0; i--) {
                var space = spaces[i];
                if (box$1.w > space.w || box$1.h > space.h) {
                  continue;
                }
                box$1.x = space.x;
                box$1.y = space.y;
                height = Math.max(height, box$1.y + box$1.h);
                width = Math.max(width, box$1.x + box$1.w);
                if (box$1.w === space.w && box$1.h === space.h) {
                  var last = spaces.pop();
                  if (i < spaces.length) {
                    spaces[i] = last;
                  }
                } else if (box$1.h === space.h) {
                  space.x += box$1.w;
                  space.w -= box$1.w;
                } else if (box$1.w === space.w) {
                  space.y += box$1.h;
                  space.h -= box$1.h;
                } else {
                  spaces.push({
                    x: space.x + box$1.w,
                    y: space.y,
                    w: space.w - box$1.w,
                    h: box$1.h
                  });
                  space.y += box$1.h;
                  space.h -= box$1.h;
                }
                break;
              }
            }
            return {
              w: width,
              // container width
              h: height,
              // container height
              fill: area2 / (width * height) || 0
              // space utilization
            };
          }
          var IMAGE_PADDING = 1;
          var ImagePosition = function ImagePosition2(paddedRect, ref) {
            var pixelRatio = ref.pixelRatio;
            var version2 = ref.version;
            var stretchX = ref.stretchX;
            var stretchY = ref.stretchY;
            var content = ref.content;
            this.paddedRect = paddedRect;
            this.pixelRatio = pixelRatio;
            this.stretchX = stretchX;
            this.stretchY = stretchY;
            this.content = content;
            this.version = version2;
          };
          var prototypeAccessors = {
            tl: { configurable: true },
            br: { configurable: true },
            tlbr: { configurable: true },
            displaySize: { configurable: true }
          };
          prototypeAccessors.tl.get = function() {
            return [
              this.paddedRect.x + IMAGE_PADDING,
              this.paddedRect.y + IMAGE_PADDING
            ];
          };
          prototypeAccessors.br.get = function() {
            return [
              this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING,
              this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING
            ];
          };
          prototypeAccessors.tlbr.get = function() {
            return this.tl.concat(this.br);
          };
          prototypeAccessors.displaySize.get = function() {
            return [
              (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio,
              (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio
            ];
          };
          Object.defineProperties(ImagePosition.prototype, prototypeAccessors);
          var ImageAtlas = function ImageAtlas2(icons, patterns) {
            var iconPositions = {}, patternPositions = {};
            this.haveRenderCallbacks = [];
            var bins = [];
            this.addImages(icons, iconPositions, bins);
            this.addImages(patterns, patternPositions, bins);
            var ref = potpack(bins);
            var w = ref.w;
            var h = ref.h;
            var image = new RGBAImage({
              width: w || 1,
              height: h || 1
            });
            for (var id2 in icons) {
              var src = icons[id2];
              var bin = iconPositions[id2].paddedRect;
              RGBAImage.copy(src.data, image, {
                x: 0,
                y: 0
              }, {
                x: bin.x + IMAGE_PADDING,
                y: bin.y + IMAGE_PADDING
              }, src.data);
            }
            for (var id$1 in patterns) {
              var src$1 = patterns[id$1];
              var bin$1 = patternPositions[id$1].paddedRect;
              var x = bin$1.x + IMAGE_PADDING, y = bin$1.y + IMAGE_PADDING, w$1 = src$1.data.width, h$1 = src$1.data.height;
              RGBAImage.copy(src$1.data, image, {
                x: 0,
                y: 0
              }, {
                x,
                y
              }, src$1.data);
              RGBAImage.copy(src$1.data, image, {
                x: 0,
                y: h$1 - 1
              }, {
                x,
                y: y - 1
              }, {
                width: w$1,
                height: 1
              });
              RGBAImage.copy(src$1.data, image, {
                x: 0,
                y: 0
              }, {
                x,
                y: y + h$1
              }, {
                width: w$1,
                height: 1
              });
              RGBAImage.copy(src$1.data, image, {
                x: w$1 - 1,
                y: 0
              }, {
                x: x - 1,
                y
              }, {
                width: 1,
                height: h$1
              });
              RGBAImage.copy(src$1.data, image, {
                x: 0,
                y: 0
              }, {
                x: x + w$1,
                y
              }, {
                width: 1,
                height: h$1
              });
            }
            this.image = image;
            this.iconPositions = iconPositions;
            this.patternPositions = patternPositions;
          };
          ImageAtlas.prototype.addImages = function addImages(images, positions, bins) {
            for (var id2 in images) {
              var src = images[id2];
              var bin = {
                x: 0,
                y: 0,
                w: src.data.width + 2 * IMAGE_PADDING,
                h: src.data.height + 2 * IMAGE_PADDING
              };
              bins.push(bin);
              positions[id2] = new ImagePosition(bin, src);
              if (src.hasRenderCallback) {
                this.haveRenderCallbacks.push(id2);
              }
            }
          };
          ImageAtlas.prototype.patchUpdatedImages = function patchUpdatedImages(imageManager, texture) {
            imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks);
            for (var name3 in imageManager.updatedImages) {
              this.patchUpdatedImage(this.iconPositions[name3], imageManager.getImage(name3), texture);
              this.patchUpdatedImage(this.patternPositions[name3], imageManager.getImage(name3), texture);
            }
          };
          ImageAtlas.prototype.patchUpdatedImage = function patchUpdatedImage(position, image, texture) {
            if (!position || !image) {
              return;
            }
            if (position.version === image.version) {
              return;
            }
            position.version = image.version;
            var ref = position.tl;
            var x = ref[0];
            var y = ref[1];
            texture.update(image.data, void 0, {
              x,
              y
            });
          };
          register("ImagePosition", ImagePosition);
          register("ImageAtlas", ImageAtlas);
          var WritingMode = {
            horizontal: 1,
            vertical: 2,
            horizontalOnly: 3
          };
          var SHAPING_DEFAULT_OFFSET = -17;
          function isEmpty(positionedLines) {
            for (var i = 0, list = positionedLines; i < list.length; i += 1) {
              var line = list[i];
              if (line.positionedGlyphs.length !== 0) {
                return false;
              }
            }
            return true;
          }
          var PUAbegin = 57344;
          var PUAend = 63743;
          var SectionOptions = function SectionOptions2() {
            this.scale = 1;
            this.fontStack = "";
            this.imageName = null;
          };
          SectionOptions.forText = function forText(scale2, fontStack) {
            var textOptions = new SectionOptions();
            textOptions.scale = scale2 || 1;
            textOptions.fontStack = fontStack;
            return textOptions;
          };
          SectionOptions.forImage = function forImage(imageName) {
            var imageOptions = new SectionOptions();
            imageOptions.imageName = imageName;
            return imageOptions;
          };
          var TaggedString = function TaggedString2() {
            this.text = "";
            this.sectionIndex = [];
            this.sections = [];
            this.imageSectionID = null;
          };
          TaggedString.fromFeature = function fromFeature(text, defaultFontStack) {
            var result = new TaggedString();
            for (var i = 0; i < text.sections.length; i++) {
              var section = text.sections[i];
              if (!section.image) {
                result.addTextSection(section, defaultFontStack);
              } else {
                result.addImageSection(section);
              }
            }
            return result;
          };
          TaggedString.prototype.length = function length() {
            return this.text.length;
          };
          TaggedString.prototype.getSection = function getSection(index) {
            return this.sections[this.sectionIndex[index]];
          };
          TaggedString.prototype.getSectionIndex = function getSectionIndex(index) {
            return this.sectionIndex[index];
          };
          TaggedString.prototype.getCharCode = function getCharCode(index) {
            return this.text.charCodeAt(index);
          };
          TaggedString.prototype.verticalizePunctuation = function verticalizePunctuation$1() {
            this.text = verticalizePunctuation(this.text);
          };
          TaggedString.prototype.trim = function trim() {
            var beginningWhitespace = 0;
            for (var i = 0; i < this.text.length && whitespace[this.text.charCodeAt(i)]; i++) {
              beginningWhitespace++;
            }
            var trailingWhitespace = this.text.length;
            for (var i$1 = this.text.length - 1; i$1 >= 0 && i$1 >= beginningWhitespace && whitespace[this.text.charCodeAt(i$1)]; i$1--) {
              trailingWhitespace--;
            }
            this.text = this.text.substring(beginningWhitespace, trailingWhitespace);
            this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace);
          };
          TaggedString.prototype.substring = function substring(start, end) {
            var substring2 = new TaggedString();
            substring2.text = this.text.substring(start, end);
            substring2.sectionIndex = this.sectionIndex.slice(start, end);
            substring2.sections = this.sections;
            return substring2;
          };
          TaggedString.prototype.toString = function toString2() {
            return this.text;
          };
          TaggedString.prototype.getMaxScale = function getMaxScale() {
            var this$1 = this;
            return this.sectionIndex.reduce(function(max, index) {
              return Math.max(max, this$1.sections[index].scale);
            }, 0);
          };
          TaggedString.prototype.addTextSection = function addTextSection(section, defaultFontStack) {
            this.text += section.text;
            this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack));
            var index = this.sections.length - 1;
            for (var i = 0; i < section.text.length; ++i) {
              this.sectionIndex.push(index);
            }
          };
          TaggedString.prototype.addImageSection = function addImageSection(section) {
            var imageName = section.image ? section.image.name : "";
            if (imageName.length === 0) {
              warnOnce("Can't add FormattedSection with an empty image.");
              return;
            }
            var nextImageSectionCharCode = this.getNextImageSectionCharCode();
            if (!nextImageSectionCharCode) {
              warnOnce("Reached maximum number of images " + (PUAend - PUAbegin + 2));
              return;
            }
            this.text += String.fromCharCode(nextImageSectionCharCode);
            this.sections.push(SectionOptions.forImage(imageName));
            this.sectionIndex.push(this.sections.length - 1);
          };
          TaggedString.prototype.getNextImageSectionCharCode = function getNextImageSectionCharCode() {
            if (!this.imageSectionID) {
              this.imageSectionID = PUAbegin;
              return this.imageSectionID;
            }
            if (this.imageSectionID >= PUAend) {
              return null;
            }
            return ++this.imageSectionID;
          };
          function breakLines(input, lineBreakPoints) {
            var lines = [];
            var text = input.text;
            var start = 0;
            for (var i = 0, list = lineBreakPoints; i < list.length; i += 1) {
              var lineBreak = list[i];
              lines.push(input.substring(start, lineBreak));
              start = lineBreak;
            }
            if (start < text.length) {
              lines.push(input.substring(start, text.length));
            }
            return lines;
          }
          function shapeText(text, glyphMap, glyphPositions, imagePositions, defaultFontStack, maxWidth, lineHeight, textAnchor, textJustify, spacing, translate2, writingMode, allowVerticalPlacement, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom) {
            var logicalInput = TaggedString.fromFeature(text, defaultFontStack);
            if (writingMode === WritingMode.vertical) {
              logicalInput.verticalizePunctuation();
            }
            var lines;
            var processBidirectionalText = plugin.processBidirectionalText;
            var processStyledBidirectionalText = plugin.processStyledBidirectionalText;
            if (processBidirectionalText && logicalInput.sections.length === 1) {
              lines = [];
              var untaggedLines = processBidirectionalText(logicalInput.toString(), determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize));
              for (var i$1 = 0, list = untaggedLines; i$1 < list.length; i$1 += 1) {
                var line = list[i$1];
                var taggedLine = new TaggedString();
                taggedLine.text = line;
                taggedLine.sections = logicalInput.sections;
                for (var i = 0; i < line.length; i++) {
                  taggedLine.sectionIndex.push(0);
                }
                lines.push(taggedLine);
              }
            } else if (processStyledBidirectionalText) {
              lines = [];
              var processedLines = processStyledBidirectionalText(logicalInput.text, logicalInput.sectionIndex, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize));
              for (var i$2 = 0, list$1 = processedLines; i$2 < list$1.length; i$2 += 1) {
                var line$1 = list$1[i$2];
                var taggedLine$1 = new TaggedString();
                taggedLine$1.text = line$1[0];
                taggedLine$1.sectionIndex = line$1[1];
                taggedLine$1.sections = logicalInput.sections;
                lines.push(taggedLine$1);
              }
            } else {
              lines = breakLines(logicalInput, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize));
            }
            var positionedLines = [];
            var shaping = {
              positionedLines,
              text: logicalInput.toString(),
              top: translate2[1],
              bottom: translate2[1],
              left: translate2[0],
              right: translate2[0],
              writingMode,
              iconsInText: false,
              verticalizable: false
            };
            shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom);
            if (isEmpty(positionedLines)) {
              return false;
            }
            return shaping;
          }
          var whitespace = {};
          whitespace[9] = true;
          whitespace[10] = true;
          whitespace[11] = true;
          whitespace[12] = true;
          whitespace[13] = true;
          whitespace[32] = true;
          var breakable = {};
          breakable[10] = true;
          breakable[32] = true;
          breakable[38] = true;
          breakable[40] = true;
          breakable[41] = true;
          breakable[43] = true;
          breakable[45] = true;
          breakable[47] = true;
          breakable[173] = true;
          breakable[183] = true;
          breakable[8203] = true;
          breakable[8208] = true;
          breakable[8211] = true;
          breakable[8231] = true;
          function getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize) {
            if (!section.imageName) {
              var positions = glyphMap[section.fontStack];
              var glyph = positions && positions[codePoint];
              if (!glyph) {
                return 0;
              }
              return glyph.metrics.advance * section.scale + spacing;
            } else {
              var imagePosition = imagePositions[section.imageName];
              if (!imagePosition) {
                return 0;
              }
              return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing;
            }
          }
          function determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize) {
            var totalWidth = 0;
            for (var index = 0; index < logicalInput.length(); index++) {
              var section = logicalInput.getSection(index);
              totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize);
            }
            var lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth));
            return totalWidth / lineCount;
          }
          function calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) {
            var raggedness = Math.pow(lineWidth - targetWidth, 2);
            if (isLastBreak) {
              if (lineWidth < targetWidth) {
                return raggedness / 2;
              } else {
                return raggedness * 2;
              }
            }
            return raggedness + Math.abs(penalty) * penalty;
          }
          function calculatePenalty(codePoint, nextCodePoint, penalizableIdeographicBreak) {
            var penalty = 0;
            if (codePoint === 10) {
              penalty -= 1e4;
            }
            if (penalizableIdeographicBreak) {
              penalty += 150;
            }
            if (codePoint === 40 || codePoint === 65288) {
              penalty += 50;
            }
            if (nextCodePoint === 41 || nextCodePoint === 65289) {
              penalty += 50;
            }
            return penalty;
          }
          function evaluateBreak(breakIndex, breakX, targetWidth, potentialBreaks, penalty, isLastBreak) {
            var bestPriorBreak = null;
            var bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak);
            for (var i = 0, list = potentialBreaks; i < list.length; i += 1) {
              var potentialBreak = list[i];
              var lineWidth = breakX - potentialBreak.x;
              var breakBadness = calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness;
              if (breakBadness <= bestBreakBadness) {
                bestPriorBreak = potentialBreak;
                bestBreakBadness = breakBadness;
              }
            }
            return {
              index: breakIndex,
              x: breakX,
              priorBreak: bestPriorBreak,
              badness: bestBreakBadness
            };
          }
          function leastBadBreaks(lastLineBreak) {
            if (!lastLineBreak) {
              return [];
            }
            return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index);
          }
          function determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize) {
            if (symbolPlacement !== "point") {
              return [];
            }
            if (!logicalInput) {
              return [];
            }
            var potentialLineBreaks = [];
            var targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);
            var hasServerSuggestedBreakpoints = logicalInput.text.indexOf("\u200B") >= 0;
            var currentX = 0;
            for (var i = 0; i < logicalInput.length(); i++) {
              var section = logicalInput.getSection(i);
              var codePoint = logicalInput.getCharCode(i);
              if (!whitespace[codePoint]) {
                currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize);
              }
              if (i < logicalInput.length() - 1) {
                var ideographicBreak = charAllowsIdeographicBreaking(codePoint);
                if (breakable[codePoint] || ideographicBreak || section.imageName) {
                  potentialLineBreaks.push(evaluateBreak(i + 1, currentX, targetWidth, potentialLineBreaks, calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints), false));
                }
              }
            }
            return leastBadBreaks(evaluateBreak(logicalInput.length(), currentX, targetWidth, potentialLineBreaks, 0, true));
          }
          function getAnchorAlignment(anchor) {
            var horizontalAlign = 0.5, verticalAlign = 0.5;
            switch (anchor) {
              case "right":
              case "top-right":
              case "bottom-right":
                horizontalAlign = 1;
                break;
              case "left":
              case "top-left":
              case "bottom-left":
                horizontalAlign = 0;
                break;
            }
            switch (anchor) {
              case "bottom":
              case "bottom-right":
              case "bottom-left":
                verticalAlign = 1;
                break;
              case "top":
              case "top-right":
              case "top-left":
                verticalAlign = 0;
                break;
            }
            return {
              horizontalAlign,
              verticalAlign
            };
          }
          function shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom) {
            var x = 0;
            var y = SHAPING_DEFAULT_OFFSET;
            var maxLineLength = 0;
            var maxLineHeight = 0;
            var justify = textJustify === "right" ? 1 : textJustify === "left" ? 0 : 0.5;
            var lineIndex = 0;
            for (var i$1 = 0, list = lines; i$1 < list.length; i$1 += 1) {
              var line = list[i$1];
              line.trim();
              var lineMaxScale = line.getMaxScale();
              var maxLineOffset = (lineMaxScale - 1) * ONE_EM;
              var positionedLine = {
                positionedGlyphs: [],
                lineOffset: 0
              };
              shaping.positionedLines[lineIndex] = positionedLine;
              var positionedGlyphs = positionedLine.positionedGlyphs;
              var lineOffset = 0;
              if (!line.length()) {
                y += lineHeight;
                ++lineIndex;
                continue;
              }
              for (var i = 0; i < line.length(); i++) {
                var section = line.getSection(i);
                var sectionIndex = line.getSectionIndex(i);
                var codePoint = line.getCharCode(i);
                var baselineOffset2 = 0;
                var metrics = null;
                var rect = null;
                var imageName = null;
                var verticalAdvance = ONE_EM;
                var vertical = !(writingMode === WritingMode.horizontal || !allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint) || allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint)));
                if (!section.imageName) {
                  var positions = glyphPositions[section.fontStack];
                  var glyphPosition = positions && positions[codePoint];
                  if (glyphPosition && glyphPosition.rect) {
                    rect = glyphPosition.rect;
                    metrics = glyphPosition.metrics;
                  } else {
                    var glyphs = glyphMap[section.fontStack];
                    var glyph = glyphs && glyphs[codePoint];
                    if (!glyph) {
                      continue;
                    }
                    metrics = glyph.metrics;
                  }
                  baselineOffset2 = (lineMaxScale - section.scale) * ONE_EM;
                } else {
                  var imagePosition = imagePositions[section.imageName];
                  if (!imagePosition) {
                    continue;
                  }
                  imageName = section.imageName;
                  shaping.iconsInText = shaping.iconsInText || true;
                  rect = imagePosition.paddedRect;
                  var size = imagePosition.displaySize;
                  section.scale = section.scale * ONE_EM / layoutTextSizeThisZoom;
                  metrics = {
                    width: size[0],
                    height: size[1],
                    left: IMAGE_PADDING,
                    top: -GLYPH_PBF_BORDER,
                    advance: vertical ? size[1] : size[0]
                  };
                  var imageOffset = ONE_EM - size[1] * section.scale;
                  baselineOffset2 = maxLineOffset + imageOffset;
                  verticalAdvance = metrics.advance;
                  var offset = vertical ? size[0] * section.scale - ONE_EM * lineMaxScale : size[1] * section.scale - ONE_EM * lineMaxScale;
                  if (offset > 0 && offset > lineOffset) {
                    lineOffset = offset;
                  }
                }
                if (!vertical) {
                  positionedGlyphs.push({
                    glyph: codePoint,
                    imageName,
                    x,
                    y: y + baselineOffset2,
                    vertical,
                    scale: section.scale,
                    fontStack: section.fontStack,
                    sectionIndex,
                    metrics,
                    rect
                  });
                  x += metrics.advance * section.scale + spacing;
                } else {
                  shaping.verticalizable = true;
                  positionedGlyphs.push({
                    glyph: codePoint,
                    imageName,
                    x,
                    y: y + baselineOffset2,
                    vertical,
                    scale: section.scale,
                    fontStack: section.fontStack,
                    sectionIndex,
                    metrics,
                    rect
                  });
                  x += verticalAdvance * section.scale + spacing;
                }
              }
              if (positionedGlyphs.length !== 0) {
                var lineLength = x - spacing;
                maxLineLength = Math.max(lineLength, maxLineLength);
                justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset);
              }
              x = 0;
              var currentLineHeight = lineHeight * lineMaxScale + lineOffset;
              positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset);
              y += currentLineHeight;
              maxLineHeight = Math.max(currentLineHeight, maxLineHeight);
              ++lineIndex;
            }
            var height = y - SHAPING_DEFAULT_OFFSET;
            var ref = getAnchorAlignment(textAnchor);
            var horizontalAlign = ref.horizontalAlign;
            var verticalAlign = ref.verticalAlign;
            align$1(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length);
            shaping.top += -verticalAlign * height;
            shaping.bottom = shaping.top + height;
            shaping.left += -horizontalAlign * maxLineLength;
            shaping.right = shaping.left + maxLineLength;
          }
          function justifyLine(positionedGlyphs, start, end, justify, lineOffset) {
            if (!justify && !lineOffset) {
              return;
            }
            var lastPositionedGlyph = positionedGlyphs[end];
            var lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale;
            var lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify;
            for (var j = start; j <= end; j++) {
              positionedGlyphs[j].x -= lineIndent;
              positionedGlyphs[j].y += lineOffset;
            }
          }
          function align$1(positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, blockHeight, lineCount) {
            var shiftX = (justify - horizontalAlign) * maxLineLength;
            var shiftY = 0;
            if (maxLineHeight !== lineHeight) {
              shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET;
            } else {
              shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight;
            }
            for (var i$1 = 0, list$1 = positionedLines; i$1 < list$1.length; i$1 += 1) {
              var line = list$1[i$1];
              for (var i = 0, list = line.positionedGlyphs; i < list.length; i += 1) {
                var positionedGlyph = list[i];
                positionedGlyph.x += shiftX;
                positionedGlyph.y += shiftY;
              }
            }
          }
          function shapeIcon(image, iconOffset, iconAnchor) {
            var ref = getAnchorAlignment(iconAnchor);
            var horizontalAlign = ref.horizontalAlign;
            var verticalAlign = ref.verticalAlign;
            var dx = iconOffset[0];
            var dy = iconOffset[1];
            var x1 = dx - image.displaySize[0] * horizontalAlign;
            var x2 = x1 + image.displaySize[0];
            var y1 = dy - image.displaySize[1] * verticalAlign;
            var y2 = y1 + image.displaySize[1];
            return {
              image,
              top: y1,
              bottom: y2,
              left: x1,
              right: x2
            };
          }
          function fitIconToText(shapedIcon, shapedText, textFit, padding, iconOffset, fontScale) {
            var image = shapedIcon.image;
            var collisionPadding;
            if (image.content) {
              var content = image.content;
              var pixelRatio = image.pixelRatio || 1;
              collisionPadding = [
                content[0] / pixelRatio,
                content[1] / pixelRatio,
                image.displaySize[0] - content[2] / pixelRatio,
                image.displaySize[1] - content[3] / pixelRatio
              ];
            }
            var textLeft = shapedText.left * fontScale;
            var textRight = shapedText.right * fontScale;
            var top, right, bottom, left;
            if (textFit === "width" || textFit === "both") {
              left = iconOffset[0] + textLeft - padding[3];
              right = iconOffset[0] + textRight + padding[1];
            } else {
              left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2;
              right = left + image.displaySize[0];
            }
            var textTop = shapedText.top * fontScale;
            var textBottom = shapedText.bottom * fontScale;
            if (textFit === "height" || textFit === "both") {
              top = iconOffset[1] + textTop - padding[0];
              bottom = iconOffset[1] + textBottom + padding[2];
            } else {
              top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2;
              bottom = top + image.displaySize[1];
            }
            return {
              image,
              top,
              right,
              bottom,
              left,
              collisionPadding
            };
          }
          var Anchor = function(Point2) {
            function Anchor2(x, y, angle, segment) {
              Point2.call(this, x, y);
              this.angle = angle;
              if (segment !== void 0) {
                this.segment = segment;
              }
            }
            if (Point2)
              Anchor2.__proto__ = Point2;
            Anchor2.prototype = Object.create(Point2 && Point2.prototype);
            Anchor2.prototype.constructor = Anchor2;
            Anchor2.prototype.clone = function clone2() {
              return new Anchor2(this.x, this.y, this.angle, this.segment);
            };
            return Anchor2;
          }(pointGeometry);
          register("Anchor", Anchor);
          var SIZE_PACK_FACTOR = 128;
          function getSizeData(tileZoom, value) {
            var expression2 = value.expression;
            if (expression2.kind === "constant") {
              var layoutSize = expression2.evaluate(new EvaluationParameters(tileZoom + 1));
              return {
                kind: "constant",
                layoutSize
              };
            } else if (expression2.kind === "source") {
              return { kind: "source" };
            } else {
              var zoomStops = expression2.zoomStops;
              var interpolationType = expression2.interpolationType;
              var lower = 0;
              while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) {
                lower++;
              }
              lower = Math.max(0, lower - 1);
              var upper = lower;
              while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) {
                upper++;
              }
              upper = Math.min(zoomStops.length - 1, upper);
              var minZoom = zoomStops[lower];
              var maxZoom = zoomStops[upper];
              if (expression2.kind === "composite") {
                return {
                  kind: "composite",
                  minZoom,
                  maxZoom,
                  interpolationType
                };
              }
              var minSize = expression2.evaluate(new EvaluationParameters(minZoom));
              var maxSize = expression2.evaluate(new EvaluationParameters(maxZoom));
              return {
                kind: "camera",
                minZoom,
                maxZoom,
                minSize,
                maxSize,
                interpolationType
              };
            }
          }
          function evaluateSizeForFeature(sizeData, ref, ref$1) {
            var uSize = ref.uSize;
            var uSizeT = ref.uSizeT;
            var lowerSize = ref$1.lowerSize;
            var upperSize = ref$1.upperSize;
            if (sizeData.kind === "source") {
              return lowerSize / SIZE_PACK_FACTOR;
            } else if (sizeData.kind === "composite") {
              return number(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT);
            }
            return uSize;
          }
          function evaluateSizeForZoom(sizeData, zoom) {
            var uSizeT = 0;
            var uSize = 0;
            if (sizeData.kind === "constant") {
              uSize = sizeData.layoutSize;
            } else if (sizeData.kind !== "source") {
              var interpolationType = sizeData.interpolationType;
              var minZoom = sizeData.minZoom;
              var maxZoom = sizeData.maxZoom;
              var t = !interpolationType ? 0 : clamp(Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1);
              if (sizeData.kind === "camera") {
                uSize = number(sizeData.minSize, sizeData.maxSize, t);
              } else {
                uSizeT = t;
              }
            }
            return {
              uSizeT,
              uSize
            };
          }
          var symbolSize = /* @__PURE__ */ Object.freeze({
            __proto__: null,
            getSizeData,
            evaluateSizeForFeature,
            evaluateSizeForZoom,
            SIZE_PACK_FACTOR
          });
          function checkMaxAngle(line, anchor, labelLength, windowSize, maxAngle) {
            if (anchor.segment === void 0) {
              return true;
            }
            var p = anchor;
            var index = anchor.segment + 1;
            var anchorDistance = 0;
            while (anchorDistance > -labelLength / 2) {
              index--;
              if (index < 0) {
                return false;
              }
              anchorDistance -= line[index].dist(p);
              p = line[index];
            }
            anchorDistance += line[index].dist(line[index + 1]);
            index++;
            var recentCorners = [];
            var recentAngleDelta = 0;
            while (anchorDistance < labelLength / 2) {
              var prev = line[index - 1];
              var current = line[index];
              var next = line[index + 1];
              if (!next) {
                return false;
              }
              var angleDelta = prev.angleTo(current) - current.angleTo(next);
              angleDelta = Math.abs((angleDelta + 3 * Math.PI) % (Math.PI * 2) - Math.PI);
              recentCorners.push({
                distance: anchorDistance,
                angleDelta
              });
              recentAngleDelta += angleDelta;
              while (anchorDistance - recentCorners[0].distance > windowSize) {
                recentAngleDelta -= recentCorners.shift().angleDelta;
              }
              if (recentAngleDelta > maxAngle) {
                return false;
              }
              index++;
              anchorDistance += current.dist(next);
            }
            return true;
          }
          function getLineLength(line) {
            var lineLength = 0;
            for (var k = 0; k < line.length - 1; k++) {
              lineLength += line[k].dist(line[k + 1]);
            }
            return lineLength;
          }
          function getAngleWindowSize(shapedText, glyphSize, boxScale) {
            return shapedText ? 3 / 5 * glyphSize * boxScale : 0;
          }
          function getShapedLabelLength(shapedText, shapedIcon) {
            return Math.max(shapedText ? shapedText.right - shapedText.left : 0, shapedIcon ? shapedIcon.right - shapedIcon.left : 0);
          }
          function getCenterAnchor(line, maxAngle, shapedText, shapedIcon, glyphSize, boxScale) {
            var angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);
            var labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale;
            var prevDistance = 0;
            var centerDistance = getLineLength(line) / 2;
            for (var i = 0; i < line.length - 1; i++) {
              var a = line[i], b = line[i + 1];
              var segmentDistance = a.dist(b);
              if (prevDistance + segmentDistance > centerDistance) {
                var t = (centerDistance - prevDistance) / segmentDistance, x = number(a.x, b.x, t), y = number(a.y, b.y, t);
                var anchor = new Anchor(x, y, b.angleTo(a), i);
                anchor._round();
                if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {
                  return anchor;
                } else {
                  return;
                }
              }
              prevDistance += segmentDistance;
            }
          }
          function getAnchors(line, spacing, maxAngle, shapedText, shapedIcon, glyphSize, boxScale, overscaling, tileExtent) {
            var angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);
            var shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon);
            var labelLength = shapedLabelLength * boxScale;
            var isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent;
            if (spacing - labelLength < spacing / 4) {
              spacing = labelLength + spacing / 4;
            }
            var fixedExtraOffset = glyphSize * 2;
            var offset = !isLineContinued ? (shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling % spacing : spacing / 2 * overscaling % spacing;
            return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent);
          }
          function resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) {
            var halfLabelLength = labelLength / 2;
            var lineLength = getLineLength(line);
            var distance = 0, markedDistance = offset - spacing;
            var anchors = [];
            for (var i = 0; i < line.length - 1; i++) {
              var a = line[i], b = line[i + 1];
              var segmentDist = a.dist(b), angle = b.angleTo(a);
              while (markedDistance + spacing < distance + segmentDist) {
                markedDistance += spacing;
                var t = (markedDistance - distance) / segmentDist, x = number(a.x, b.x, t), y = number(a.y, b.y, t);
                if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent && markedDistance - halfLabelLength >= 0 && markedDistance + halfLabelLength <= lineLength) {
                  var anchor = new Anchor(x, y, angle, i);
                  anchor._round();
                  if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {
                    anchors.push(anchor);
                  }
                }
              }
              distance += segmentDist;
            }
            if (!placeAtMiddle && !anchors.length && !isLineContinued) {
              anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent);
            }
            return anchors;
          }
          function clipLine(lines, x1, y1, x2, y2) {
            var clippedLines = [];
            for (var l = 0; l < lines.length; l++) {
              var line = lines[l];
              var clippedLine = void 0;
              for (var i = 0; i < line.length - 1; i++) {
                var p0 = line[i];
                var p1 = line[i + 1];
                if (p0.x < x1 && p1.x < x1) {
                  continue;
                } else if (p0.x < x1) {
                  p0 = new pointGeometry(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();
                } else if (p1.x < x1) {
                  p1 = new pointGeometry(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();
                }
                if (p0.y < y1 && p1.y < y1) {
                  continue;
                } else if (p0.y < y1) {
                  p0 = new pointGeometry(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();
                } else if (p1.y < y1) {
                  p1 = new pointGeometry(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();
                }
                if (p0.x >= x2 && p1.x >= x2) {
                  continue;
                } else if (p0.x >= x2) {
                  p0 = new pointGeometry(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();
                } else if (p1.x >= x2) {
                  p1 = new pointGeometry(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();
                }
                if (p0.y >= y2 && p1.y >= y2) {
                  continue;
                } else if (p0.y >= y2) {
                  p0 = new pointGeometry(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();
                } else if (p1.y >= y2) {
                  p1 = new pointGeometry(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();
                }
                if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) {
                  clippedLine = [p0];
                  clippedLines.push(clippedLine);
                }
                clippedLine.push(p1);
              }
            }
            return clippedLines;
          }
          var border$1 = IMAGE_PADDING;
          function getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit) {
            var quads = [];
            var image = shapedIcon.image;
            var pixelRatio = image.pixelRatio;
            var imageWidth = image.paddedRect.w - 2 * border$1;
            var imageHeight = image.paddedRect.h - 2 * border$1;
            var iconWidth = shapedIcon.right - shapedIcon.left;
            var iconHeight = shapedIcon.bottom - shapedIcon.top;
            var stretchX = image.stretchX || [[
              0,
              imageWidth
            ]];
            var stretchY = image.stretchY || [[
              0,
              imageHeight
            ]];
            var reduceRanges = function(sum, range) {
              return sum + range[1] - range[0];
            };
            var stretchWidth = stretchX.reduce(reduceRanges, 0);
            var stretchHeight = stretchY.reduce(reduceRanges, 0);
            var fixedWidth = imageWidth - stretchWidth;
            var fixedHeight = imageHeight - stretchHeight;
            var stretchOffsetX = 0;
            var stretchContentWidth = stretchWidth;
            var stretchOffsetY = 0;
            var stretchContentHeight = stretchHeight;
            var fixedOffsetX = 0;
            var fixedContentWidth = fixedWidth;
            var fixedOffsetY = 0;
            var fixedContentHeight = fixedHeight;
            if (image.content && hasIconTextFit) {
              var content = image.content;
              stretchOffsetX = sumWithinRange(stretchX, 0, content[0]);
              stretchOffsetY = sumWithinRange(stretchY, 0, content[1]);
              stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]);
              stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]);
              fixedOffsetX = content[0] - stretchOffsetX;
              fixedOffsetY = content[1] - stretchOffsetY;
              fixedContentWidth = content[2] - content[0] - stretchContentWidth;
              fixedContentHeight = content[3] - content[1] - stretchContentHeight;
            }
            var makeBox = function(left, top, right, bottom) {
              var leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);
              var leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth);
              var topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);
              var topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight);
              var rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);
              var rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth);
              var bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);
              var bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight);
              var tl = new pointGeometry(leftEm, topEm);
              var tr = new pointGeometry(rightEm, topEm);
              var br = new pointGeometry(rightEm, bottomEm);
              var bl = new pointGeometry(leftEm, bottomEm);
              var pixelOffsetTL = new pointGeometry(leftPx / pixelRatio, topPx / pixelRatio);
              var pixelOffsetBR = new pointGeometry(rightPx / pixelRatio, bottomPx / pixelRatio);
              var angle = iconRotate * Math.PI / 180;
              if (angle) {
                var sin = Math.sin(angle), cos = Math.cos(angle), matrix = [
                  cos,
                  -sin,
                  sin,
                  cos
                ];
                tl._matMult(matrix);
                tr._matMult(matrix);
                bl._matMult(matrix);
                br._matMult(matrix);
              }
              var x12 = left.stretch + left.fixed;
              var x22 = right.stretch + right.fixed;
              var y12 = top.stretch + top.fixed;
              var y22 = bottom.stretch + bottom.fixed;
              var subRect = {
                x: image.paddedRect.x + border$1 + x12,
                y: image.paddedRect.y + border$1 + y12,
                w: x22 - x12,
                h: y22 - y12
              };
              var minFontScaleX = fixedContentWidth / pixelRatio / iconWidth;
              var minFontScaleY = fixedContentHeight / pixelRatio / iconHeight;
              return {
                tl,
                tr,
                bl,
                br,
                tex: subRect,
                writingMode: void 0,
                glyphOffset: [
                  0,
                  0
                ],
                sectionIndex: 0,
                pixelOffsetTL,
                pixelOffsetBR,
                minFontScaleX,
                minFontScaleY,
                isSDF: isSDFIcon
              };
            };
            if (!hasIconTextFit || !image.stretchX && !image.stretchY) {
              quads.push(makeBox({
                fixed: 0,
                stretch: -1
              }, {
                fixed: 0,
                stretch: -1
              }, {
                fixed: 0,
                stretch: imageWidth + 1
              }, {
                fixed: 0,
                stretch: imageHeight + 1
              }));
            } else {
              var xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth);
              var yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight);
              for (var xi = 0; xi < xCuts.length - 1; xi++) {
                var x1 = xCuts[xi];
                var x2 = xCuts[xi + 1];
                for (var yi = 0; yi < yCuts.length - 1; yi++) {
                  var y1 = yCuts[yi];
                  var y2 = yCuts[yi + 1];
                  quads.push(makeBox(x1, y1, x2, y2));
                }
              }
            }
            return quads;
          }
          function sumWithinRange(ranges, min, max) {
            var sum = 0;
            for (var i = 0, list = ranges; i < list.length; i += 1) {
              var range = list[i];
              sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0]));
            }
            return sum;
          }
          function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) {
            var cuts = [{
              fixed: -border$1,
              stretch: 0
            }];
            for (var i = 0, list = stretchZones; i < list.length; i += 1) {
              var ref = list[i];
              var c1 = ref[0];
              var c2 = ref[1];
              var last = cuts[cuts.length - 1];
              cuts.push({
                fixed: c1 - last.stretch,
                stretch: last.stretch
              });
              cuts.push({
                fixed: c1 - last.stretch,
                stretch: last.stretch + (c2 - c1)
              });
            }
            cuts.push({
              fixed: fixedSize + border$1,
              stretch: stretchSize
            });
            return cuts;
          }
          function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) {
            return stretchOffset / stretchSize * iconSize + iconOffset;
          }
          function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) {
            return fixedOffset - fixedSize * stretchOffset / stretchSize;
          }
          function getGlyphQuads(anchor, shaping, textOffset, layer2, alongLine, feature, imageMap, allowVerticalPlacement) {
            var textRotate = layer2.layout.get("text-rotate").evaluate(feature, {}) * Math.PI / 180;
            var quads = [];
            for (var i$1 = 0, list$1 = shaping.positionedLines; i$1 < list$1.length; i$1 += 1) {
              var line = list$1[i$1];
              for (var i = 0, list = line.positionedGlyphs; i < list.length; i += 1) {
                var positionedGlyph = list[i];
                if (!positionedGlyph.rect) {
                  continue;
                }
                var textureRect = positionedGlyph.rect || {};
                var glyphPadding = 1;
                var rectBuffer = GLYPH_PBF_BORDER + glyphPadding;
                var isSDF = true;
                var pixelRatio = 1;
                var lineOffset = 0;
                var rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical;
                var halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2;
                if (allowVerticalPlacement && shaping.verticalizable) {
                  var scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM;
                  var imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2;
                  lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset);
                }
                if (positionedGlyph.imageName) {
                  var image = imageMap[positionedGlyph.imageName];
                  isSDF = image.sdf;
                  pixelRatio = image.pixelRatio;
                  rectBuffer = IMAGE_PADDING / pixelRatio;
                }
                var glyphOffset2 = alongLine ? [
                  positionedGlyph.x + halfAdvance,
                  positionedGlyph.y
                ] : [
                  0,
                  0
                ];
                var builtInOffset = alongLine ? [
                  0,
                  0
                ] : [
                  positionedGlyph.x + halfAdvance + textOffset[0],
                  positionedGlyph.y + textOffset[1] - lineOffset
                ];
                var verticalizedLabelOffset = [
                  0,
                  0
                ];
                if (rotateVerticalGlyph) {
                  verticalizedLabelOffset = builtInOffset;
                  builtInOffset = [
                    0,
                    0
                  ];
                }
                var x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0];
                var y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1];
                var x2 = x1 + textureRect.w * positionedGlyph.scale / pixelRatio;
                var y2 = y1 + textureRect.h * positionedGlyph.scale / pixelRatio;
                var tl = new pointGeometry(x1, y1);
                var tr = new pointGeometry(x2, y1);
                var bl = new pointGeometry(x1, y2);
                var br = new pointGeometry(x2, y2);
                if (rotateVerticalGlyph) {
                  var center = new pointGeometry(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET);
                  var verticalRotation = -Math.PI / 2;
                  var xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance;
                  var yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0;
                  var halfWidthOffsetCorrection = new pointGeometry(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection);
                  var verticalOffsetCorrection = new (Function.prototype.bind.apply(pointGeometry, [null].concat(verticalizedLabelOffset)))();
                  tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);
                  tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);
                  bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);
                  br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);
                }
                if (textRotate) {
                  var sin = Math.sin(textRotate), cos = Math.cos(textRotate), matrix = [
                    cos,
                    -sin,
                    sin,
                    cos
                  ];
                  tl._matMult(matrix);
                  tr._matMult(matrix);
                  bl._matMult(matrix);
                  br._matMult(matrix);
                }
                var pixelOffsetTL = new pointGeometry(0, 0);
                var pixelOffsetBR = new pointGeometry(0, 0);
                var minFontScaleX = 0;
                var minFontScaleY = 0;
                quads.push({
                  tl,
                  tr,
                  bl,
                  br,
                  tex: textureRect,
                  writingMode: shaping.writingMode,
                  glyphOffset: glyphOffset2,
                  sectionIndex: positionedGlyph.sectionIndex,
                  isSDF,
                  pixelOffsetTL,
                  pixelOffsetBR,
                  minFontScaleX,
                  minFontScaleY
                });
              }
            }
            return quads;
          }
          var CollisionFeature = function CollisionFeature2(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaped, boxScale, padding, alignLine, rotate2) {
            this.boxStartIndex = collisionBoxArray.length;
            if (alignLine) {
              var top = shaped.top;
              var bottom = shaped.bottom;
              var collisionPadding = shaped.collisionPadding;
              if (collisionPadding) {
                top -= collisionPadding[1];
                bottom += collisionPadding[3];
              }
              var height = bottom - top;
              if (height > 0) {
                height = Math.max(10, height);
                this.circleDiameter = height;
              }
            } else {
              var y1 = shaped.top * boxScale - padding;
              var y2 = shaped.bottom * boxScale + padding;
              var x1 = shaped.left * boxScale - padding;
              var x2 = shaped.right * boxScale + padding;
              var collisionPadding$1 = shaped.collisionPadding;
              if (collisionPadding$1) {
                x1 -= collisionPadding$1[0] * boxScale;
                y1 -= collisionPadding$1[1] * boxScale;
                x2 += collisionPadding$1[2] * boxScale;
                y2 += collisionPadding$1[3] * boxScale;
              }
              if (rotate2) {
                var tl = new pointGeometry(x1, y1);
                var tr = new pointGeometry(x2, y1);
                var bl = new pointGeometry(x1, y2);
                var br = new pointGeometry(x2, y2);
                var rotateRadians = rotate2 * Math.PI / 180;
                tl._rotate(rotateRadians);
                tr._rotate(rotateRadians);
                bl._rotate(rotateRadians);
                br._rotate(rotateRadians);
                x1 = Math.min(tl.x, tr.x, bl.x, br.x);
                x2 = Math.max(tl.x, tr.x, bl.x, br.x);
                y1 = Math.min(tl.y, tr.y, bl.y, br.y);
                y2 = Math.max(tl.y, tr.y, bl.y, br.y);
              }
              collisionBoxArray.emplaceBack(anchor.x, anchor.y, x1, y1, x2, y2, featureIndex, sourceLayerIndex, bucketIndex);
            }
            this.boxEndIndex = collisionBoxArray.length;
          };
          var TinyQueue = function TinyQueue2(data, compare2) {
            if (data === void 0)
              data = [];
            if (compare2 === void 0)
              compare2 = defaultCompare$1;
            this.data = data;
            this.length = this.data.length;
            this.compare = compare2;
            if (this.length > 0) {
              for (var i = (this.length >> 1) - 1; i >= 0; i--) {
                this._down(i);
              }
            }
          };
          TinyQueue.prototype.push = function push(item) {
            this.data.push(item);
            this.length++;
            this._up(this.length - 1);
          };
          TinyQueue.prototype.pop = function pop() {
            if (this.length === 0) {
              return void 0;
            }
            var top = this.data[0];
            var bottom = this.data.pop();
            this.length--;
            if (this.length > 0) {
              this.data[0] = bottom;
              this._down(0);
            }
            return top;
          };
          TinyQueue.prototype.peek = function peek() {
            return this.data[0];
          };
          TinyQueue.prototype._up = function _up(pos) {
            var ref = this;
            var data = ref.data;
            var compare2 = ref.compare;
            var item = data[pos];
            while (pos > 0) {
              var parent = pos - 1 >> 1;
              var current = data[parent];
              if (compare2(item, current) >= 0) {
                break;
              }
              data[pos] = current;
              pos = parent;
            }
            data[pos] = item;
          };
          TinyQueue.prototype._down = function _down(pos) {
            var ref = this;
            var data = ref.data;
            var compare2 = ref.compare;
            var halfLength = this.length >> 1;
            var item = data[pos];
            while (pos < halfLength) {
              var left = (pos << 1) + 1;
              var best = data[left];
              var right = left + 1;
              if (right < this.length && compare2(data[right], best) < 0) {
                left = right;
                best = data[right];
              }
              if (compare2(best, item) >= 0) {
                break;
              }
              data[pos] = best;
              pos = left;
            }
            data[pos] = item;
          };
          function defaultCompare$1(a, b) {
            return a < b ? -1 : a > b ? 1 : 0;
          }
          function findPoleOfInaccessibility(polygonRings, precision, debug) {
            if (precision === void 0)
              precision = 1;
            if (debug === void 0)
              debug = false;
            var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
            var outerRing = polygonRings[0];
            for (var i = 0; i < outerRing.length; i++) {
              var p = outerRing[i];
              if (!i || p.x < minX) {
                minX = p.x;
              }
              if (!i || p.y < minY) {
                minY = p.y;
              }
              if (!i || p.x > maxX) {
                maxX = p.x;
              }
              if (!i || p.y > maxY) {
                maxY = p.y;
              }
            }
            var width = maxX - minX;
            var height = maxY - minY;
            var cellSize = Math.min(width, height);
            var h = cellSize / 2;
            var cellQueue = new TinyQueue([], compareMax);
            if (cellSize === 0) {
              return new pointGeometry(minX, minY);
            }
            for (var x = minX; x < maxX; x += cellSize) {
              for (var y = minY; y < maxY; y += cellSize) {
                cellQueue.push(new Cell(x + h, y + h, h, polygonRings));
              }
            }
            var bestCell = getCentroidCell(polygonRings);
            var numProbes = cellQueue.length;
            while (cellQueue.length) {
              var cell = cellQueue.pop();
              if (cell.d > bestCell.d || !bestCell.d) {
                bestCell = cell;
                if (debug) {
                  console.log("found best %d after %d probes", Math.round(1e4 * cell.d) / 1e4, numProbes);
                }
              }
              if (cell.max - bestCell.d <= precision) {
                continue;
              }
              h = cell.h / 2;
              cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings));
              cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings));
              cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings));
              cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings));
              numProbes += 4;
            }
            if (debug) {
              console.log("num probes: " + numProbes);
              console.log("best distance: " + bestCell.d);
            }
            return bestCell.p;
          }
          function compareMax(a, b) {
            return b.max - a.max;
          }
          function Cell(x, y, h, polygon) {
            this.p = new pointGeometry(x, y);
            this.h = h;
            this.d = pointToPolygonDist(this.p, polygon);
            this.max = this.d + this.h * Math.SQRT2;
          }
          function pointToPolygonDist(p, polygon) {
            var inside = false;
            var minDistSq = Infinity;
            for (var k = 0; k < polygon.length; k++) {
              var ring = polygon[k];
              for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
                var a = ring[i];
                var b = ring[j];
                if (a.y > p.y !== b.y > p.y && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x) {
                  inside = !inside;
                }
                minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b));
              }
            }
            return (inside ? 1 : -1) * Math.sqrt(minDistSq);
          }
          function getCentroidCell(polygon) {
            var area2 = 0;
            var x = 0;
            var y = 0;
            var points = polygon[0];
            for (var i = 0, len = points.length, j = len - 1; i < len; j = i++) {
              var a = points[i];
              var b = points[j];
              var f = a.x * b.y - b.x * a.y;
              x += (a.x + b.x) * f;
              y += (a.y + b.y) * f;
              area2 += f * 3;
            }
            return new Cell(x / area2, y / area2, 0, polygon);
          }
          var baselineOffset = 7;
          var INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY;
          function evaluateVariableOffset(anchor, offset) {
            function fromRadialOffset(anchor2, radialOffset) {
              var x = 0, y = 0;
              if (radialOffset < 0) {
                radialOffset = 0;
              }
              var hypotenuse = radialOffset / Math.sqrt(2);
              switch (anchor2) {
                case "top-right":
                case "top-left":
                  y = hypotenuse - baselineOffset;
                  break;
                case "bottom-right":
                case "bottom-left":
                  y = -hypotenuse + baselineOffset;
                  break;
                case "bottom":
                  y = -radialOffset + baselineOffset;
                  break;
                case "top":
                  y = radialOffset - baselineOffset;
                  break;
              }
              switch (anchor2) {
                case "top-right":
                case "bottom-right":
                  x = -hypotenuse;
                  break;
                case "top-left":
                case "bottom-left":
                  x = hypotenuse;
                  break;
                case "left":
                  x = radialOffset;
                  break;
                case "right":
                  x = -radialOffset;
                  break;
              }
              return [
                x,
                y
              ];
            }
            function fromTextOffset(anchor2, offsetX, offsetY) {
              var x = 0, y = 0;
              offsetX = Math.abs(offsetX);
              offsetY = Math.abs(offsetY);
              switch (anchor2) {
                case "top-right":
                case "top-left":
                case "top":
                  y = offsetY - baselineOffset;
                  break;
                case "bottom-right":
                case "bottom-left":
                case "bottom":
                  y = -offsetY + baselineOffset;
                  break;
              }
              switch (anchor2) {
                case "top-right":
                case "bottom-right":
                case "right":
                  x = -offsetX;
                  break;
                case "top-left":
                case "bottom-left":
                case "left":
                  x = offsetX;
                  break;
              }
              return [
                x,
                y
              ];
            }
            return offset[1] !== INVALID_TEXT_OFFSET ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]);
          }
          function performSymbolLayout(bucket, glyphMap, glyphPositions, imageMap, imagePositions, showCollisionBoxes, canonical) {
            bucket.createArrays();
            var tileSize = 512 * bucket.overscaling;
            bucket.tilePixelRatio = EXTENT$1 / tileSize;
            bucket.compareText = {};
            bucket.iconsNeedLinear = false;
            var layout2 = bucket.layers[0].layout;
            var unevaluatedLayoutValues = bucket.layers[0]._unevaluatedLayout._values;
            var sizes = {};
            if (bucket.textSizeData.kind === "composite") {
              var ref = bucket.textSizeData;
              var minZoom = ref.minZoom;
              var maxZoom = ref.maxZoom;
              sizes.compositeTextSizes = [
                unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(minZoom), canonical),
                unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical)
              ];
            }
            if (bucket.iconSizeData.kind === "composite") {
              var ref$1 = bucket.iconSizeData;
              var minZoom$1 = ref$1.minZoom;
              var maxZoom$1 = ref$1.maxZoom;
              sizes.compositeIconSizes = [
                unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(minZoom$1), canonical),
                unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(maxZoom$1), canonical)
              ];
            }
            sizes.layoutTextSize = unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1), canonical);
            sizes.layoutIconSize = unevaluatedLayoutValues["icon-size"].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1), canonical);
            sizes.textMaxSize = unevaluatedLayoutValues["text-size"].possiblyEvaluate(new EvaluationParameters(18));
            var lineHeight = layout2.get("text-line-height") * ONE_EM;
            var textAlongLine = layout2.get("text-rotation-alignment") === "map" && layout2.get("symbol-placement") !== "point";
            var keepUpright = layout2.get("text-keep-upright");
            var textSize = layout2.get("text-size");
            var loop = function() {
              var feature = list[i$1];
              var fontstack = layout2.get("text-font").evaluate(feature, {}, canonical).join(",");
              var layoutTextSizeThisZoom = textSize.evaluate(feature, {}, canonical);
              var layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, canonical);
              var layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, canonical);
              var shapedTextOrientations = {
                horizontal: {},
                vertical: void 0
              };
              var text = feature.text;
              var textOffset = [
                0,
                0
              ];
              if (text) {
                var unformattedText = text.toString();
                var spacing = layout2.get("text-letter-spacing").evaluate(feature, {}, canonical) * ONE_EM;
                var spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0;
                var textAnchor = layout2.get("text-anchor").evaluate(feature, {}, canonical);
                var variableTextAnchor = layout2.get("text-variable-anchor");
                if (!variableTextAnchor) {
                  var radialOffset = layout2.get("text-radial-offset").evaluate(feature, {}, canonical);
                  if (radialOffset) {
                    textOffset = evaluateVariableOffset(textAnchor, [
                      radialOffset * ONE_EM,
                      INVALID_TEXT_OFFSET
                    ]);
                  } else {
                    textOffset = layout2.get("text-offset").evaluate(feature, {}, canonical).map(function(t) {
                      return t * ONE_EM;
                    });
                  }
                }
                var textJustify = textAlongLine ? "center" : layout2.get("text-justify").evaluate(feature, {}, canonical);
                var symbolPlacement = layout2.get("symbol-placement");
                var maxWidth = symbolPlacement === "point" ? layout2.get("text-max-width").evaluate(feature, {}, canonical) * ONE_EM : 0;
                var addVerticalShapingForPointLabelIfNeeded = function() {
                  if (bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) {
                    shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, "left", spacingIfAllowed, textOffset, WritingMode.vertical, true, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom);
                  }
                };
                if (!textAlongLine && variableTextAnchor) {
                  var justifications = textJustify === "auto" ? variableTextAnchor.map(function(a) {
                    return getAnchorJustification(a);
                  }) : [textJustify];
                  var singleLine = false;
                  for (var i = 0; i < justifications.length; i++) {
                    var justification = justifications[i];
                    if (shapedTextOrientations.horizontal[justification]) {
                      continue;
                    }
                    if (singleLine) {
                      shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0];
                    } else {
                      var shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, "center", justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom);
                      if (shaping) {
                        shapedTextOrientations.horizontal[justification] = shaping;
                        singleLine = shaping.positionedLines.length === 1;
                      }
                    }
                  }
                  addVerticalShapingForPointLabelIfNeeded();
                } else {
                  if (textJustify === "auto") {
                    textJustify = getAnchorJustification(textAnchor);
                  }
                  var shaping$1 = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.horizontal, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom);
                  if (shaping$1) {
                    shapedTextOrientations.horizontal[textJustify] = shaping$1;
                  }
                  addVerticalShapingForPointLabelIfNeeded();
                  if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) {
                    shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed, textOffset, WritingMode.vertical, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom);
                  }
                }
              }
              var shapedIcon = void 0;
              var isSDFIcon = false;
              if (feature.icon && feature.icon.name) {
                var image = imageMap[feature.icon.name];
                if (image) {
                  shapedIcon = shapeIcon(imagePositions[feature.icon.name], layout2.get("icon-offset").evaluate(feature, {}, canonical), layout2.get("icon-anchor").evaluate(feature, {}, canonical));
                  isSDFIcon = image.sdf;
                  if (bucket.sdfIcons === void 0) {
                    bucket.sdfIcons = image.sdf;
                  } else if (bucket.sdfIcons !== image.sdf) {
                    warnOnce("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer");
                  }
                  if (image.pixelRatio !== bucket.pixelRatio) {
                    bucket.iconsNeedLinear = true;
                  } else if (layout2.get("icon-rotate").constantOr(1) !== 0) {
                    bucket.iconsNeedLinear = true;
                  }
                }
              }
              var shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical;
              bucket.iconsInText = shapedText ? shapedText.iconsInText : false;
              if (shapedText || shapedIcon) {
                addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical);
              }
            };
            for (var i$1 = 0, list = bucket.features; i$1 < list.length; i$1 += 1)
              loop();
            if (showCollisionBoxes) {
              bucket.generateCollisionDebugBuffers();
            }
          }
          function getAnchorJustification(anchor) {
            switch (anchor) {
              case "right":
              case "top-right":
              case "bottom-right":
                return "right";
              case "left":
              case "top-left":
              case "bottom-left":
                return "left";
            }
            return "center";
          }
          function addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical) {
            var textMaxSize = sizes.textMaxSize.evaluate(feature, {});
            if (textMaxSize === void 0) {
              textMaxSize = layoutTextSize;
            }
            var layout2 = bucket.layers[0].layout;
            var iconOffset = layout2.get("icon-offset").evaluate(feature, {}, canonical);
            var defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal);
            var glyphSize = 24, fontScale = layoutTextSize / glyphSize, textBoxScale = bucket.tilePixelRatio * fontScale, textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize, iconBoxScale = bucket.tilePixelRatio * layoutIconSize, symbolMinDistance = bucket.tilePixelRatio * layout2.get("symbol-spacing"), textPadding = layout2.get("text-padding") * bucket.tilePixelRatio, iconPadding = layout2.get("icon-padding") * bucket.tilePixelRatio, textMaxAngle = layout2.get("text-max-angle") / 180 * Math.PI, textAlongLine = layout2.get("text-rotation-alignment") === "map" && layout2.get("symbol-placement") !== "point", iconAlongLine = layout2.get("icon-rotation-alignment") === "map" && layout2.get("symbol-placement") !== "point", symbolPlacement = layout2.get("symbol-placement"), textRepeatDistance = symbolMinDistance / 2;
            var iconTextFit = layout2.get("icon-text-fit");
            var verticallyShapedIcon;
            if (shapedIcon && iconTextFit !== "none") {
              if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {
                verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit, layout2.get("icon-text-fit-padding"), iconOffset, fontScale);
              }
              if (defaultHorizontalShaping) {
                shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit, layout2.get("icon-text-fit-padding"), iconOffset, fontScale);
              }
            }
            var addSymbolAtAnchor = function(line2, anchor2) {
              if (anchor2.x < 0 || anchor2.x >= EXTENT$1 || anchor2.y < 0 || anchor2.y >= EXTENT$1) {
                return;
              }
              addSymbol(bucket, anchor2, line2, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0], bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index, textBoxScale, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize);
            };
            if (symbolPlacement === "line") {
              for (var i$1 = 0, list$1 = clipLine(feature.geometry, 0, 0, EXTENT$1, EXTENT$1); i$1 < list$1.length; i$1 += 1) {
                var line = list$1[i$1];
                var anchors = getAnchors(line, symbolMinDistance, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale, bucket.overscaling, EXTENT$1);
                for (var i = 0, list = anchors; i < list.length; i += 1) {
                  var anchor = list[i];
                  var shapedText = defaultHorizontalShaping;
                  if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) {
                    addSymbolAtAnchor(line, anchor);
                  }
                }
              }
            } else if (symbolPlacement === "line-center") {
              for (var i$2 = 0, list$2 = feature.geometry; i$2 < list$2.length; i$2 += 1) {
                var line$1 = list$2[i$2];
                if (line$1.length > 1) {
                  var anchor$1 = getCenterAnchor(line$1, textMaxAngle, shapedTextOrientations.vertical || defaultHorizontalShaping, shapedIcon, glyphSize, textMaxBoxScale);
                  if (anchor$1) {
                    addSymbolAtAnchor(line$1, anchor$1);
                  }
                }
              }
            } else if (feature.type === "Polygon") {
              for (var i$3 = 0, list$3 = classifyRings(feature.geometry, 0); i$3 < list$3.length; i$3 += 1) {
                var polygon = list$3[i$3];
                var poi = findPoleOfInaccessibility(polygon, 16);
                addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0));
              }
            } else if (feature.type === "LineString") {
              for (var i$4 = 0, list$4 = feature.geometry; i$4 < list$4.length; i$4 += 1) {
                var line$2 = list$4[i$4];
                addSymbolAtAnchor(line$2, new Anchor(line$2[0].x, line$2[0].y, 0));
              }
            } else if (feature.type === "Point") {
              for (var i$6 = 0, list$6 = feature.geometry; i$6 < list$6.length; i$6 += 1) {
                var points = list$6[i$6];
                for (var i$5 = 0, list$5 = points; i$5 < list$5.length; i$5 += 1) {
                  var point = list$5[i$5];
                  addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0));
                }
              }
            }
          }
          var MAX_GLYPH_ICON_SIZE = 255;
          var MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR;
          function addTextVertices(bucket, anchor, shapedText, imageMap, layer2, textAlongLine, feature, textOffset, lineArray, writingMode, placementTypes, placedTextSymbolIndices, placedIconIndex, sizes, canonical) {
            var glyphQuads = getGlyphQuads(anchor, shapedText, textOffset, layer2, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement);
            var sizeData = bucket.textSizeData;
            var textSizeData = null;
            if (sizeData.kind === "source") {
              textSizeData = [SIZE_PACK_FACTOR * layer2.layout.get("text-size").evaluate(feature, {})];
              if (textSizeData[0] > MAX_PACKED_SIZE) {
                warnOnce(bucket.layerIds[0] + ': Value for "text-size" is >= ' + MAX_GLYPH_ICON_SIZE + '. Reduce your "text-size".');
              }
            } else if (sizeData.kind === "composite") {
              textSizeData = [
                SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical),
                SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical)
              ];
              if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) {
                warnOnce(bucket.layerIds[0] + ': Value for "text-size" is >= ' + MAX_GLYPH_ICON_SIZE + '. Reduce your "text-size".');
              }
            }
            bucket.addSymbols(bucket.text, glyphQuads, textSizeData, textOffset, textAlongLine, feature, writingMode, anchor, lineArray.lineStartIndex, lineArray.lineLength, placedIconIndex, canonical);
            for (var i = 0, list = placementTypes; i < list.length; i += 1) {
              var placementType = list[i];
              placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1;
            }
            return glyphQuads.length * 4;
          }
          function getDefaultHorizontalShaping(horizontalShaping) {
            for (var justification in horizontalShaping) {
              return horizontalShaping[justification];
            }
            return null;
          }
          function addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, layer2, collisionBoxArray, featureIndex, sourceLayerIndex, bucketIndex, textBoxScale, textPadding, textAlongLine, textOffset, iconBoxScale, iconPadding, iconAlongLine, iconOffset, feature, sizes, isSDFIcon, canonical, layoutTextSize) {
            var assign;
            var lineArray = bucket.addToLineVertexArray(anchor, line);
            var textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature;
            var numIconVertices = 0;
            var numVerticalIconVertices = 0;
            var numHorizontalGlyphVertices = 0;
            var numVerticalGlyphVertices = 0;
            var placedIconSymbolIndex = -1;
            var verticalPlacedIconSymbolIndex = -1;
            var placedTextSymbolIndices = {};
            var key = murmurhashJs("");
            var textOffset0 = 0;
            var textOffset1 = 0;
            if (layer2._unevaluatedLayout.getValue("text-radial-offset") === void 0) {
              assign = layer2.layout.get("text-offset").evaluate(feature, {}, canonical).map(function(t) {
                return t * ONE_EM;
              }), textOffset0 = assign[0], textOffset1 = assign[1];
            } else {
              textOffset0 = layer2.layout.get("text-radial-offset").evaluate(feature, {}, canonical) * ONE_EM;
              textOffset1 = INVALID_TEXT_OFFSET;
            }
            if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {
              var textRotation = layer2.layout.get("text-rotate").evaluate(feature, {}, canonical);
              var verticalTextRotation = textRotation + 90;
              var verticalShaping = shapedTextOrientations.vertical;
              verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation);
              if (verticallyShapedIcon) {
                verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation);
              }
            }
            if (shapedIcon) {
              var iconRotate = layer2.layout.get("icon-rotate").evaluate(feature, {});
              var hasIconTextFit = layer2.layout.get("icon-text-fit") !== "none";
              var iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit);
              var verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : void 0;
              iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, false, iconRotate);
              numIconVertices = iconQuads.length * 4;
              var sizeData = bucket.iconSizeData;
              var iconSizeData = null;
              if (sizeData.kind === "source") {
                iconSizeData = [SIZE_PACK_FACTOR * layer2.layout.get("icon-size").evaluate(feature, {})];
                if (iconSizeData[0] > MAX_PACKED_SIZE) {
                  warnOnce(bucket.layerIds[0] + ': Value for "icon-size" is >= ' + MAX_GLYPH_ICON_SIZE + '. Reduce your "icon-size".');
                }
              } else if (sizeData.kind === "composite") {
                iconSizeData = [
                  SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical),
                  SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical)
                ];
                if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) {
                  warnOnce(bucket.layerIds[0] + ': Value for "icon-size" is >= ' + MAX_GLYPH_ICON_SIZE + '. Reduce your "icon-size".');
                }
              }
              bucket.addSymbols(bucket.icon, iconQuads, iconSizeData, iconOffset, iconAlongLine, feature, false, anchor, lineArray.lineStartIndex, lineArray.lineLength, -1, canonical);
              placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;
              if (verticalIconQuads) {
                numVerticalIconVertices = verticalIconQuads.length * 4;
                bucket.addSymbols(bucket.icon, verticalIconQuads, iconSizeData, iconOffset, iconAlongLine, feature, WritingMode.vertical, anchor, lineArray.lineStartIndex, lineArray.lineLength, -1, canonical);
                verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;
              }
            }
            for (var justification in shapedTextOrientations.horizontal) {
              var shaping = shapedTextOrientations.horizontal[justification];
              if (!textCollisionFeature) {
                key = murmurhashJs(shaping.text);
                var textRotate = layer2.layout.get("text-rotate").evaluate(feature, {}, canonical);
                textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate);
              }
              var singleLine = shaping.positionedLines.length === 1;
              numHorizontalGlyphVertices += addTextVertices(bucket, anchor, shaping, imageMap, layer2, textAlongLine, feature, textOffset, lineArray, shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly, singleLine ? Object.keys(shapedTextOrientations.horizontal) : [justification], placedTextSymbolIndices, placedIconSymbolIndex, sizes, canonical);
              if (singleLine) {
                break;
              }
            }
            if (shapedTextOrientations.vertical) {
              numVerticalGlyphVertices += addTextVertices(bucket, anchor, shapedTextOrientations.vertical, imageMap, layer2, textAlongLine, feature, textOffset, lineArray, WritingMode.vertical, ["vertical"], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical);
            }
            var textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;
            var textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;
            var verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;
            var verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;
            var iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;
            var iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;
            var verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;
            var verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;
            var collisionCircleDiameter = -1;
            var getCollisionCircleHeight = function(feature2, prevHeight) {
              if (feature2 && feature2.circleDiameter) {
                return Math.max(feature2.circleDiameter, prevHeight);
              }
              return prevHeight;
            };
            collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter);
            collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter);
            collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter);
            collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter);
            var useRuntimeCollisionCircles = collisionCircleDiameter > -1 ? 1 : 0;
            if (useRuntimeCollisionCircles) {
              collisionCircleDiameter *= layoutTextSize / ONE_EM;
            }
            if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) {
              warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907");
            }
            if (feature.sortKey !== void 0) {
              bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey);
            }
            bucket.symbolInstances.emplaceBack(anchor.x, anchor.y, placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1, placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1, placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1, placedTextSymbolIndices.vertical || -1, placedIconSymbolIndex, verticalPlacedIconSymbolIndex, key, textBoxStartIndex, textBoxEndIndex, verticalTextBoxStartIndex, verticalTextBoxEndIndex, iconBoxStartIndex, iconBoxEndIndex, verticalIconBoxStartIndex, verticalIconBoxEndIndex, featureIndex, numHorizontalGlyphVertices, numVerticalGlyphVertices, numIconVertices, numVerticalIconVertices, useRuntimeCollisionCircles, 0, textBoxScale, textOffset0, textOffset1, collisionCircleDiameter);
          }
          function anchorIsTooClose(bucket, text, repeatDistance, anchor) {
            var compareText = bucket.compareText;
            if (!(text in compareText)) {
              compareText[text] = [];
            } else {
              var otherAnchors = compareText[text];
              for (var k = otherAnchors.length - 1; k >= 0; k--) {
                if (anchor.dist(otherAnchors[k]) < repeatDistance) {
                  return true;
                }
              }
            }
            compareText[text].push(anchor);
            return false;
          }
          var vectorTileFeatureTypes$2 = vectorTile.VectorTileFeature.types;
          var shaderOpacityAttributes = [{
            name: "a_fade_opacity",
            components: 1,
            type: "Uint8",
            offset: 0
          }];
          function addVertex$1(array2, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) {
            var aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0;
            var aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0;
            array2.emplaceBack(anchorX, anchorY, Math.round(ox * 32), Math.round(oy * 32), tx, ty, (aSizeX << 1) + (isSDF ? 1 : 0), aSizeY, pixelOffsetX * 16, pixelOffsetY * 16, minFontScaleX * 256, minFontScaleY * 256);
          }
          function addDynamicAttributes(dynamicLayoutVertexArray, p, angle) {
            dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
            dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
            dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
            dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);
          }
          function containsRTLText(formattedText) {
            for (var i = 0, list = formattedText.sections; i < list.length; i += 1) {
              var section = list[i];
              if (stringContainsRTLText(section.text)) {
                return true;
              }
            }
            return false;
          }
          var SymbolBuffers = function SymbolBuffers2(programConfigurations) {
            this.layoutVertexArray = new StructArrayLayout4i4ui4i24();
            this.indexArray = new StructArrayLayout3ui6();
            this.programConfigurations = programConfigurations;
            this.segments = new SegmentVector();
            this.dynamicLayoutVertexArray = new StructArrayLayout3f12();
            this.opacityVertexArray = new StructArrayLayout1ul4();
            this.placedSymbolArray = new PlacedSymbolArray();
          };
          SymbolBuffers.prototype.isEmpty = function isEmpty2() {
            return this.layoutVertexArray.length === 0 && this.indexArray.length === 0 && this.dynamicLayoutVertexArray.length === 0 && this.opacityVertexArray.length === 0;
          };
          SymbolBuffers.prototype.upload = function upload(context, dynamicIndexBuffer, upload$1, update) {
            if (this.isEmpty()) {
              return;
            }
            if (upload$1) {
              this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members);
              this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer);
              this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true);
              this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true);
              this.opacityVertexBuffer.itemSize = 1;
            }
            if (upload$1 || update) {
              this.programConfigurations.upload(context);
            }
          };
          SymbolBuffers.prototype.destroy = function destroy() {
            if (!this.layoutVertexBuffer) {
              return;
            }
            this.layoutVertexBuffer.destroy();
            this.indexBuffer.destroy();
            this.programConfigurations.destroy();
            this.segments.destroy();
            this.dynamicLayoutVertexBuffer.destroy();
            this.opacityVertexBuffer.destroy();
          };
          register("SymbolBuffers", SymbolBuffers);
          var CollisionBuffers = function CollisionBuffers2(LayoutArray, layoutAttributes, IndexArray) {
            this.layoutVertexArray = new LayoutArray();
            this.layoutAttributes = layoutAttributes;
            this.indexArray = new IndexArray();
            this.segments = new SegmentVector();
            this.collisionVertexArray = new StructArrayLayout2ub2f12();
          };
          CollisionBuffers.prototype.upload = function upload(context) {
            this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes);
            this.indexBuffer = context.createIndexBuffer(this.indexArray);
            this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true);
          };
          CollisionBuffers.prototype.destroy = function destroy() {
            if (!this.layoutVertexBuffer) {
              return;
            }
            this.layoutVertexBuffer.destroy();
            this.indexBuffer.destroy();
            this.segments.destroy();
            this.collisionVertexBuffer.destroy();
          };
          register("CollisionBuffers", CollisionBuffers);
          var SymbolBucket = function SymbolBucket2(options) {
            this.collisionBoxArray = options.collisionBoxArray;
            this.zoom = options.zoom;
            this.overscaling = options.overscaling;
            this.layers = options.layers;
            this.layerIds = this.layers.map(function(layer3) {
              return layer3.id;
            });
            this.index = options.index;
            this.pixelRatio = options.pixelRatio;
            this.sourceLayerIndex = options.sourceLayerIndex;
            this.hasPattern = false;
            this.hasRTLText = false;
            this.sortKeyRanges = [];
            this.collisionCircleArray = [];
            this.placementInvProjMatrix = identity2([]);
            this.placementViewportMatrix = identity2([]);
            var layer2 = this.layers[0];
            var unevaluatedLayoutValues = layer2._unevaluatedLayout._values;
            this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues["text-size"]);
            this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues["icon-size"]);
            var layout2 = this.layers[0].layout;
            var sortKey = layout2.get("symbol-sort-key");
            var zOrder2 = layout2.get("symbol-z-order");
            this.canOverlap = layout2.get("text-allow-overlap") || layout2.get("icon-allow-overlap") || layout2.get("text-ignore-placement") || layout2.get("icon-ignore-placement");
            this.sortFeaturesByKey = zOrder2 !== "viewport-y" && sortKey.constantOr(1) !== void 0;
            var zOrderByViewportY = zOrder2 === "viewport-y" || zOrder2 === "auto" && !this.sortFeaturesByKey;
            this.sortFeaturesByY = zOrderByViewportY && this.canOverlap;
            if (layout2.get("symbol-placement") === "point") {
              this.writingModes = layout2.get("text-writing-mode").map(function(wm) {
                return WritingMode[wm];
              });
            }
            this.stateDependentLayerIds = this.layers.filter(function(l) {
              return l.isStateDependent();
            }).map(function(l) {
              return l.id;
            });
            this.sourceID = options.sourceID;
          };
          SymbolBucket.prototype.createArrays = function createArrays() {
            this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, function(property) {
              return /^text/.test(property);
            }));
            this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, function(property) {
              return /^icon/.test(property);
            }));
            this.glyphOffsetArray = new GlyphOffsetArray();
            this.lineVertexArray = new SymbolLineVertexArray();
            this.symbolInstances = new SymbolInstanceArray();
          };
          SymbolBucket.prototype.calculateGlyphDependencies = function calculateGlyphDependencies(text, stack, textAlongLine, allowVerticalPlacement, doesAllowVerticalWritingMode) {
            for (var i = 0; i < text.length; i++) {
              stack[text.charCodeAt(i)] = true;
              if ((textAlongLine || allowVerticalPlacement) && doesAllowVerticalWritingMode) {
                var verticalChar = verticalizedCharacterMap[text.charAt(i)];
                if (verticalChar) {
                  stack[verticalChar.charCodeAt(0)] = true;
                }
              }
            }
          };
          SymbolBucket.prototype.populate = function populate(features, options, canonical) {
            var layer2 = this.layers[0];
            var layout2 = layer2.layout;
            var textFont = layout2.get("text-font");
            var textField = layout2.get("text-field");
            var iconImage = layout2.get("icon-image");
            var hasText = (textField.value.kind !== "constant" || textField.value.value instanceof Formatted && !textField.value.value.isEmpty() || textField.value.value.toString().length > 0) && (textFont.value.kind !== "constant" || textFont.value.value.length > 0);
            var hasIcon = iconImage.value.kind !== "constant" || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0;
            var symbolSortKey = layout2.get("symbol-sort-key");
            this.features = [];
            if (!hasText && !hasIcon) {
              return;
            }
            var icons = options.iconDependencies;
            var stacks = options.glyphDependencies;
            var availableImages = options.availableImages;
            var globalProperties = new EvaluationParameters(this.zoom);
            for (var i$1 = 0, list$1 = features; i$1 < list$1.length; i$1 += 1) {
              var ref = list$1[i$1];
              var feature = ref.feature;
              var id2 = ref.id;
              var index = ref.index;
              var sourceLayerIndex = ref.sourceLayerIndex;
              var needGeometry = layer2._featureFilter.needGeometry;
              var evaluationFeature = toEvaluationFeature(feature, needGeometry);
              if (!layer2._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {
                continue;
              }
              if (!needGeometry) {
                evaluationFeature.geometry = loadGeometry(feature);
              }
              var text = void 0;
              if (hasText) {
                var resolvedTokens = layer2.getValueAndResolveTokens("text-field", evaluationFeature, canonical, availableImages);
                var formattedText = Formatted.factory(resolvedTokens);
                if (containsRTLText(formattedText)) {
                  this.hasRTLText = true;
                }
                if (!this.hasRTLText || getRTLTextPluginStatus() === "unavailable" || this.hasRTLText && plugin.isParsed()) {
                  text = transformText$1(formattedText, layer2, evaluationFeature);
                }
              }
              var icon = void 0;
              if (hasIcon) {
                var resolvedTokens$1 = layer2.getValueAndResolveTokens("icon-image", evaluationFeature, canonical, availableImages);
                if (resolvedTokens$1 instanceof ResolvedImage) {
                  icon = resolvedTokens$1;
                } else {
                  icon = ResolvedImage.fromString(resolvedTokens$1);
                }
              }
              if (!text && !icon) {
                continue;
              }
              var sortKey = this.sortFeaturesByKey ? symbolSortKey.evaluate(evaluationFeature, {}, canonical) : void 0;
              var symbolFeature = {
                id: id2,
                text,
                icon,
                index,
                sourceLayerIndex,
                geometry: evaluationFeature.geometry,
                properties: feature.properties,
                type: vectorTileFeatureTypes$2[feature.type],
                sortKey
              };
              this.features.push(symbolFeature);
              if (icon) {
                icons[icon.name] = true;
              }
              if (text) {
                var fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(",");
                var textAlongLine = layout2.get("text-rotation-alignment") === "map" && layout2.get("symbol-placement") !== "point";
                this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0;
                for (var i = 0, list = text.sections; i < list.length; i += 1) {
                  var section = list[i];
                  if (!section.image) {
                    var doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString());
                    var sectionFont = section.fontStack || fontStack;
                    var sectionStack = stacks[sectionFont] = stacks[sectionFont] || {};
                    this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode);
                  } else {
                    icons[section.image.name] = true;
                  }
                }
              }
            }
            if (layout2.get("symbol-placement") === "line") {
              this.features = mergeLines(this.features);
            }
            if (this.sortFeaturesByKey) {
              this.features.sort(function(a, b) {
                return a.sortKey - b.sortKey;
              });
            }
          };
          SymbolBucket.prototype.update = function update(states, vtLayer, imagePositions) {
            if (!this.stateDependentLayers.length) {
              return;
            }
            this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);
            this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);
          };
          SymbolBucket.prototype.isEmpty = function isEmpty2() {
            return this.symbolInstances.length === 0 && !this.hasRTLText;
          };
          SymbolBucket.prototype.uploadPending = function uploadPending() {
            return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload;
          };
          SymbolBucket.prototype.upload = function upload(context) {
            if (!this.uploaded && this.hasDebugData()) {
              this.textCollisionBox.upload(context);
              this.iconCollisionBox.upload(context);
            }
            this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload);
            this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload);
            this.uploaded = true;
          };
          SymbolBucket.prototype.destroyDebugData = function destroyDebugData() {
            this.textCollisionBox.destroy();
            this.iconCollisionBox.destroy();
          };
          SymbolBucket.prototype.destroy = function destroy() {
            this.text.destroy();
            this.icon.destroy();
            if (this.hasDebugData()) {
              this.destroyDebugData();
            }
          };
          SymbolBucket.prototype.addToLineVertexArray = function addToLineVertexArray(anchor, line) {
            var lineStartIndex = this.lineVertexArray.length;
            if (anchor.segment !== void 0) {
              var sumForwardLength = anchor.dist(line[anchor.segment + 1]);
              var sumBackwardLength = anchor.dist(line[anchor.segment]);
              var vertices = {};
              for (var i = anchor.segment + 1; i < line.length; i++) {
                vertices[i] = {
                  x: line[i].x,
                  y: line[i].y,
                  tileUnitDistanceFromAnchor: sumForwardLength
                };
                if (i < line.length - 1) {
                  sumForwardLength += line[i + 1].dist(line[i]);
                }
              }
              for (var i$1 = anchor.segment || 0; i$1 >= 0; i$1--) {
                vertices[i$1] = {
                  x: line[i$1].x,
                  y: line[i$1].y,
                  tileUnitDistanceFromAnchor: sumBackwardLength
                };
                if (i$1 > 0) {
                  sumBackwardLength += line[i$1 - 1].dist(line[i$1]);
                }
              }
              for (var i$2 = 0; i$2 < line.length; i$2++) {
                var vertex = vertices[i$2];
                this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor);
              }
            }
            return {
              lineStartIndex,
              lineLength: this.lineVertexArray.length - lineStartIndex
            };
          };
          SymbolBucket.prototype.addSymbols = function addSymbols(arrays, quads, sizeVertex, lineOffset, alongLine, feature, writingMode, labelAnchor, lineStartIndex, lineLength, associatedIconIndex, canonical) {
            var indexArray = arrays.indexArray;
            var layoutVertexArray = arrays.layoutVertexArray;
            var segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : void 0);
            var glyphOffsetArrayStart = this.glyphOffsetArray.length;
            var vertexStartIndex = segment.vertexLength;
            var angle = this.allowVerticalPlacement && writingMode === WritingMode.vertical ? Math.PI / 2 : 0;
            var sections = feature.text && feature.text.sections;
            for (var i = 0; i < quads.length; i++) {
              var ref = quads[i];
              var tl = ref.tl;
              var tr = ref.tr;
              var bl = ref.bl;
              var br = ref.br;
              var tex = ref.tex;
              var pixelOffsetTL = ref.pixelOffsetTL;
              var pixelOffsetBR = ref.pixelOffsetBR;
              var minFontScaleX = ref.minFontScaleX;
              var minFontScaleY = ref.minFontScaleY;
              var glyphOffset2 = ref.glyphOffset;
              var isSDF = ref.isSDF;
              var sectionIndex = ref.sectionIndex;
              var index = segment.vertexLength;
              var y = glyphOffset2[1];
              addVertex$1(layoutVertexArray, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);
              addVertex$1(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);
              addVertex$1(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);
              addVertex$1(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);
              addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle);
              indexArray.emplaceBack(index, index + 1, index + 2);
              indexArray.emplaceBack(index + 1, index + 2, index + 3);
              segment.vertexLength += 4;
              segment.primitiveLength += 2;
              this.glyphOffsetArray.emplaceBack(glyphOffset2[0]);
              if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) {
                arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, canonical, sections && sections[sectionIndex]);
              }
            }
            arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y, glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex, lineStartIndex, lineLength, labelAnchor.segment, sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0, lineOffset[0], lineOffset[1], writingMode, 0, false, 0, associatedIconIndex);
          };
          SymbolBucket.prototype._addCollisionDebugVertex = function _addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, point, anchorX, anchorY, extrude) {
            collisionVertexArray.emplaceBack(0, 0);
            return layoutVertexArray.emplaceBack(point.x, point.y, anchorX, anchorY, Math.round(extrude.x), Math.round(extrude.y));
          };
          SymbolBucket.prototype.addCollisionDebugVertices = function addCollisionDebugVertices(x1, y1, x2, y2, arrays, boxAnchorPoint, symbolInstance2) {
            var segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);
            var index = segment.vertexLength;
            var layoutVertexArray = arrays.layoutVertexArray;
            var collisionVertexArray = arrays.collisionVertexArray;
            var anchorX = symbolInstance2.anchorX;
            var anchorY = symbolInstance2.anchorY;
            this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new pointGeometry(x1, y1));
            this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new pointGeometry(x2, y1));
            this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new pointGeometry(x2, y2));
            this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new pointGeometry(x1, y2));
            segment.vertexLength += 4;
            var indexArray = arrays.indexArray;
            indexArray.emplaceBack(index, index + 1);
            indexArray.emplaceBack(index + 1, index + 2);
            indexArray.emplaceBack(index + 2, index + 3);
            indexArray.emplaceBack(index + 3, index);
            segment.primitiveLength += 4;
          };
          SymbolBucket.prototype.addDebugCollisionBoxes = function addDebugCollisionBoxes(startIndex, endIndex, symbolInstance2, isText) {
            for (var b = startIndex; b < endIndex; b++) {
              var box = this.collisionBoxArray.get(b);
              var x1 = box.x1;
              var y1 = box.y1;
              var x2 = box.x2;
              var y2 = box.y2;
              this.addCollisionDebugVertices(x1, y1, x2, y2, isText ? this.textCollisionBox : this.iconCollisionBox, box.anchorPoint, symbolInstance2);
            }
          };
          SymbolBucket.prototype.generateCollisionDebugBuffers = function generateCollisionDebugBuffers() {
            if (this.hasDebugData()) {
              this.destroyDebugData();
            }
            this.textCollisionBox = new CollisionBuffers(StructArrayLayout2i2i2i12, collisionBoxLayout.members, StructArrayLayout2ui4);
            this.iconCollisionBox = new CollisionBuffers(StructArrayLayout2i2i2i12, collisionBoxLayout.members, StructArrayLayout2ui4);
            for (var i = 0; i < this.symbolInstances.length; i++) {
              var symbolInstance2 = this.symbolInstances.get(i);
              this.addDebugCollisionBoxes(symbolInstance2.textBoxStartIndex, symbolInstance2.textBoxEndIndex, symbolInstance2, true);
              this.addDebugCollisionBoxes(symbolInstance2.verticalTextBoxStartIndex, symbolInstance2.verticalTextBoxEndIndex, symbolInstance2, true);
              this.addDebugCollisionBoxes(symbolInstance2.iconBoxStartIndex, symbolInstance2.iconBoxEndIndex, symbolInstance2, false);
              this.addDebugCollisionBoxes(symbolInstance2.verticalIconBoxStartIndex, symbolInstance2.verticalIconBoxEndIndex, symbolInstance2, false);
            }
          };
          SymbolBucket.prototype._deserializeCollisionBoxesForSymbol = function _deserializeCollisionBoxesForSymbol(collisionBoxArray, textStartIndex, textEndIndex, verticalTextStartIndex, verticalTextEndIndex, iconStartIndex, iconEndIndex, verticalIconStartIndex, verticalIconEndIndex) {
            var collisionArrays = {};
            for (var k = textStartIndex; k < textEndIndex; k++) {
              var box = collisionBoxArray.get(k);
              collisionArrays.textBox = {
                x1: box.x1,
                y1: box.y1,
                x2: box.x2,
                y2: box.y2,
                anchorPointX: box.anchorPointX,
                anchorPointY: box.anchorPointY
              };
              collisionArrays.textFeatureIndex = box.featureIndex;
              break;
            }
            for (var k$1 = verticalTextStartIndex; k$1 < verticalTextEndIndex; k$1++) {
              var box$1 = collisionBoxArray.get(k$1);
              collisionArrays.verticalTextBox = {
                x1: box$1.x1,
                y1: box$1.y1,
                x2: box$1.x2,
                y2: box$1.y2,
                anchorPointX: box$1.anchorPointX,
                anchorPointY: box$1.anchorPointY
              };
              collisionArrays.verticalTextFeatureIndex = box$1.featureIndex;
              break;
            }
            for (var k$2 = iconStartIndex; k$2 < iconEndIndex; k$2++) {
              var box$2 = collisionBoxArray.get(k$2);
              collisionArrays.iconBox = {
                x1: box$2.x1,
                y1: box$2.y1,
                x2: box$2.x2,
                y2: box$2.y2,
                anchorPointX: box$2.anchorPointX,
                anchorPointY: box$2.anchorPointY
              };
              collisionArrays.iconFeatureIndex = box$2.featureIndex;
              break;
            }
            for (var k$3 = verticalIconStartIndex; k$3 < verticalIconEndIndex; k$3++) {
              var box$3 = collisionBoxArray.get(k$3);
              collisionArrays.verticalIconBox = {
                x1: box$3.x1,
                y1: box$3.y1,
                x2: box$3.x2,
                y2: box$3.y2,
                anchorPointX: box$3.anchorPointX,
                anchorPointY: box$3.anchorPointY
              };
              collisionArrays.verticalIconFeatureIndex = box$3.featureIndex;
              break;
            }
            return collisionArrays;
          };
          SymbolBucket.prototype.deserializeCollisionBoxes = function deserializeCollisionBoxes(collisionBoxArray) {
            this.collisionArrays = [];
            for (var i = 0; i < this.symbolInstances.length; i++) {
              var symbolInstance2 = this.symbolInstances.get(i);
              this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(collisionBoxArray, symbolInstance2.textBoxStartIndex, symbolInstance2.textBoxEndIndex, symbolInstance2.verticalTextBoxStartIndex, symbolInstance2.verticalTextBoxEndIndex, symbolInstance2.iconBoxStartIndex, symbolInstance2.iconBoxEndIndex, symbolInstance2.verticalIconBoxStartIndex, symbolInstance2.verticalIconBoxEndIndex));
            }
          };
          SymbolBucket.prototype.hasTextData = function hasTextData() {
            return this.text.segments.get().length > 0;
          };
          SymbolBucket.prototype.hasIconData = function hasIconData() {
            return this.icon.segments.get().length > 0;
          };
          SymbolBucket.prototype.hasDebugData = function hasDebugData() {
            return this.textCollisionBox && this.iconCollisionBox;
          };
          SymbolBucket.prototype.hasTextCollisionBoxData = function hasTextCollisionBoxData() {
            return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;
          };
          SymbolBucket.prototype.hasIconCollisionBoxData = function hasIconCollisionBoxData() {
            return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0;
          };
          SymbolBucket.prototype.addIndicesForPlacedSymbol = function addIndicesForPlacedSymbol(iconOrText, placedSymbolIndex) {
            var placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex);
            var endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;
            for (var vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {
              iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);
              iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);
            }
          };
          SymbolBucket.prototype.getSortedSymbolIndexes = function getSortedSymbolIndexes(angle) {
            if (this.sortedAngle === angle && this.symbolInstanceIndexes !== void 0) {
              return this.symbolInstanceIndexes;
            }
            var sin = Math.sin(angle);
            var cos = Math.cos(angle);
            var rotatedYs = [];
            var featureIndexes = [];
            var result = [];
            for (var i = 0; i < this.symbolInstances.length; ++i) {
              result.push(i);
              var symbolInstance2 = this.symbolInstances.get(i);
              rotatedYs.push(Math.round(sin * symbolInstance2.anchorX + cos * symbolInstance2.anchorY) | 0);
              featureIndexes.push(symbolInstance2.featureIndex);
            }
            result.sort(function(aIndex, bIndex) {
              return rotatedYs[aIndex] - rotatedYs[bIndex] || featureIndexes[bIndex] - featureIndexes[aIndex];
            });
            return result;
          };
          SymbolBucket.prototype.addToSortKeyRanges = function addToSortKeyRanges(symbolInstanceIndex, sortKey) {
            var last = this.sortKeyRanges[this.sortKeyRanges.length - 1];
            if (last && last.sortKey === sortKey) {
              last.symbolInstanceEnd = symbolInstanceIndex + 1;
            } else {
              this.sortKeyRanges.push({
                sortKey,
                symbolInstanceStart: symbolInstanceIndex,
                symbolInstanceEnd: symbolInstanceIndex + 1
              });
            }
          };
          SymbolBucket.prototype.sortFeatures = function sortFeatures(angle) {
            var this$1 = this;
            if (!this.sortFeaturesByY) {
              return;
            }
            if (this.sortedAngle === angle) {
              return;
            }
            if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) {
              return;
            }
            this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle);
            this.sortedAngle = angle;
            this.text.indexArray.clear();
            this.icon.indexArray.clear();
            this.featureSortOrder = [];
            for (var i$1 = 0, list = this.symbolInstanceIndexes; i$1 < list.length; i$1 += 1) {
              var i = list[i$1];
              var symbolInstance2 = this.symbolInstances.get(i);
              this.featureSortOrder.push(symbolInstance2.featureIndex);
              [
                symbolInstance2.rightJustifiedTextSymbolIndex,
                symbolInstance2.centerJustifiedTextSymbolIndex,
                symbolInstance2.leftJustifiedTextSymbolIndex
              ].forEach(function(index, i2, array2) {
                if (index >= 0 && array2.indexOf(index) === i2) {
                  this$1.addIndicesForPlacedSymbol(this$1.text, index);
                }
              });
              if (symbolInstance2.verticalPlacedTextSymbolIndex >= 0) {
                this.addIndicesForPlacedSymbol(this.text, symbolInstance2.verticalPlacedTextSymbolIndex);
              }
              if (symbolInstance2.placedIconSymbolIndex >= 0) {
                this.addIndicesForPlacedSymbol(this.icon, symbolInstance2.placedIconSymbolIndex);
              }
              if (symbolInstance2.verticalPlacedIconSymbolIndex >= 0) {
                this.addIndicesForPlacedSymbol(this.icon, symbolInstance2.verticalPlacedIconSymbolIndex);
              }
            }
            if (this.text.indexBuffer) {
              this.text.indexBuffer.updateData(this.text.indexArray);
            }
            if (this.icon.indexBuffer) {
              this.icon.indexBuffer.updateData(this.icon.indexArray);
            }
          };
          register("SymbolBucket", SymbolBucket, {
            omit: [
              "layers",
              "collisionBoxArray",
              "features",
              "compareText"
            ]
          });
          SymbolBucket.MAX_GLYPHS = 65535;
          SymbolBucket.addDynamicAttributes = addDynamicAttributes;
          function resolveTokens(properties2, text) {
            return text.replace(/{([^{}]+)}/g, function(match, key) {
              return key in properties2 ? String(properties2[key]) : "";
            });
          }
          var layout$7 = new Properties({
            "symbol-placement": new DataConstantProperty(spec["layout_symbol"]["symbol-placement"]),
            "symbol-spacing": new DataConstantProperty(spec["layout_symbol"]["symbol-spacing"]),
            "symbol-avoid-edges": new DataConstantProperty(spec["layout_symbol"]["symbol-avoid-edges"]),
            "symbol-sort-key": new DataDrivenProperty(spec["layout_symbol"]["symbol-sort-key"]),
            "symbol-z-order": new DataConstantProperty(spec["layout_symbol"]["symbol-z-order"]),
            "icon-allow-overlap": new DataConstantProperty(spec["layout_symbol"]["icon-allow-overlap"]),
            "icon-ignore-placement": new DataConstantProperty(spec["layout_symbol"]["icon-ignore-placement"]),
            "icon-optional": new DataConstantProperty(spec["layout_symbol"]["icon-optional"]),
            "icon-rotation-alignment": new DataConstantProperty(spec["layout_symbol"]["icon-rotation-alignment"]),
            "icon-size": new DataDrivenProperty(spec["layout_symbol"]["icon-size"]),
            "icon-text-fit": new DataConstantProperty(spec["layout_symbol"]["icon-text-fit"]),
            "icon-text-fit-padding": new DataConstantProperty(spec["layout_symbol"]["icon-text-fit-padding"]),
            "icon-image": new DataDrivenProperty(spec["layout_symbol"]["icon-image"]),
            "icon-rotate": new DataDrivenProperty(spec["layout_symbol"]["icon-rotate"]),
            "icon-padding": new DataConstantProperty(spec["layout_symbol"]["icon-padding"]),
            "icon-keep-upright": new DataConstantProperty(spec["layout_symbol"]["icon-keep-upright"]),
            "icon-offset": new DataDrivenProperty(spec["layout_symbol"]["icon-offset"]),
            "icon-anchor": new DataDrivenProperty(spec["layout_symbol"]["icon-anchor"]),
            "icon-pitch-alignment": new DataConstantProperty(spec["layout_symbol"]["icon-pitch-alignment"]),
            "text-pitch-alignment": new DataConstantProperty(spec["layout_symbol"]["text-pitch-alignment"]),
            "text-rotation-alignment": new DataConstantProperty(spec["layout_symbol"]["text-rotation-alignment"]),
            "text-field": new DataDrivenProperty(spec["layout_symbol"]["text-field"]),
            "text-font": new DataDrivenProperty(spec["layout_symbol"]["text-font"]),
            "text-size": new DataDrivenProperty(spec["layout_symbol"]["text-size"]),
            "text-max-width": new DataDrivenProperty(spec["layout_symbol"]["text-max-width"]),
            "text-line-height": new DataConstantProperty(spec["layout_symbol"]["text-line-height"]),
            "text-letter-spacing": new DataDrivenProperty(spec["layout_symbol"]["text-letter-spacing"]),
            "text-justify": new DataDrivenProperty(spec["layout_symbol"]["text-justify"]),
            "text-radial-offset": new DataDrivenProperty(spec["layout_symbol"]["text-radial-offset"]),
            "text-variable-anchor": new DataConstantProperty(spec["layout_symbol"]["text-variable-anchor"]),
            "text-anchor": new DataDrivenProperty(spec["layout_symbol"]["text-anchor"]),
            "text-max-angle": new DataConstantProperty(spec["layout_symbol"]["text-max-angle"]),
            "text-writing-mode": new DataConstantProperty(spec["layout_symbol"]["text-writing-mode"]),
            "text-rotate": new DataDrivenProperty(spec["layout_symbol"]["text-rotate"]),
            "text-padding": new DataConstantProperty(spec["layout_symbol"]["text-padding"]),
            "text-keep-upright": new DataConstantProperty(spec["layout_symbol"]["text-keep-upright"]),
            "text-transform": new DataDrivenProperty(spec["layout_symbol"]["text-transform"]),
            "text-offset": new DataDrivenProperty(spec["layout_symbol"]["text-offset"]),
            "text-allow-overlap": new DataConstantProperty(spec["layout_symbol"]["text-allow-overlap"]),
            "text-ignore-placement": new DataConstantProperty(spec["layout_symbol"]["text-ignore-placement"]),
            "text-optional": new DataConstantProperty(spec["layout_symbol"]["text-optional"])
          });
          var paint$7 = new Properties({
            "icon-opacity": new DataDrivenProperty(spec["paint_symbol"]["icon-opacity"]),
            "icon-color": new DataDrivenProperty(spec["paint_symbol"]["icon-color"]),
            "icon-halo-color": new DataDrivenProperty(spec["paint_symbol"]["icon-halo-color"]),
            "icon-halo-width": new DataDrivenProperty(spec["paint_symbol"]["icon-halo-width"]),
            "icon-halo-blur": new DataDrivenProperty(spec["paint_symbol"]["icon-halo-blur"]),
            "icon-translate": new DataConstantProperty(spec["paint_symbol"]["icon-translate"]),
            "icon-translate-anchor": new DataConstantProperty(spec["paint_symbol"]["icon-translate-anchor"]),
            "text-opacity": new DataDrivenProperty(spec["paint_symbol"]["text-opacity"]),
            "text-color": new DataDrivenProperty(spec["paint_symbol"]["text-color"], {
              runtimeType: ColorType,
              getOverride: function(o) {
                return o.textColor;
              },
              hasOverride: function(o) {
                return !!o.textColor;
              }
            }),
            "text-halo-color": new DataDrivenProperty(spec["paint_symbol"]["text-halo-color"]),
            "text-halo-width": new DataDrivenProperty(spec["paint_symbol"]["text-halo-width"]),
            "text-halo-blur": new DataDrivenProperty(spec["paint_symbol"]["text-halo-blur"]),
            "text-translate": new DataConstantProperty(spec["paint_symbol"]["text-translate"]),
            "text-translate-anchor": new DataConstantProperty(spec["paint_symbol"]["text-translate-anchor"])
          });
          var properties$6 = {
            paint: paint$7,
            layout: layout$7
          };
          var FormatSectionOverride = function FormatSectionOverride2(defaultValue) {
            this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType;
            this.defaultValue = defaultValue;
          };
          FormatSectionOverride.prototype.evaluate = function evaluate(ctx) {
            if (ctx.formattedSection) {
              var overrides = this.defaultValue.property.overrides;
              if (overrides && overrides.hasOverride(ctx.formattedSection)) {
                return overrides.getOverride(ctx.formattedSection);
              }
            }
            if (ctx.feature && ctx.featureState) {
              return this.defaultValue.evaluate(ctx.feature, ctx.featureState);
            }
            return this.defaultValue.property.specification.default;
          };
          FormatSectionOverride.prototype.eachChild = function eachChild(fn) {
            if (!this.defaultValue.isConstant()) {
              var expr = this.defaultValue.value;
              fn(expr._styleExpression.expression);
            }
          };
          FormatSectionOverride.prototype.outputDefined = function outputDefined() {
            return false;
          };
          FormatSectionOverride.prototype.serialize = function serialize2() {
            return null;
          };
          register("FormatSectionOverride", FormatSectionOverride, { omit: ["defaultValue"] });
          var SymbolStyleLayer = function(StyleLayer2) {
            function SymbolStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$6);
            }
            if (StyleLayer2)
              SymbolStyleLayer2.__proto__ = StyleLayer2;
            SymbolStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            SymbolStyleLayer2.prototype.constructor = SymbolStyleLayer2;
            SymbolStyleLayer2.prototype.recalculate = function recalculate(parameters, availableImages) {
              StyleLayer2.prototype.recalculate.call(this, parameters, availableImages);
              if (this.layout.get("icon-rotation-alignment") === "auto") {
                if (this.layout.get("symbol-placement") !== "point") {
                  this.layout._values["icon-rotation-alignment"] = "map";
                } else {
                  this.layout._values["icon-rotation-alignment"] = "viewport";
                }
              }
              if (this.layout.get("text-rotation-alignment") === "auto") {
                if (this.layout.get("symbol-placement") !== "point") {
                  this.layout._values["text-rotation-alignment"] = "map";
                } else {
                  this.layout._values["text-rotation-alignment"] = "viewport";
                }
              }
              if (this.layout.get("text-pitch-alignment") === "auto") {
                this.layout._values["text-pitch-alignment"] = this.layout.get("text-rotation-alignment");
              }
              if (this.layout.get("icon-pitch-alignment") === "auto") {
                this.layout._values["icon-pitch-alignment"] = this.layout.get("icon-rotation-alignment");
              }
              if (this.layout.get("symbol-placement") === "point") {
                var writingModes = this.layout.get("text-writing-mode");
                if (writingModes) {
                  var deduped = [];
                  for (var i = 0, list = writingModes; i < list.length; i += 1) {
                    var m = list[i];
                    if (deduped.indexOf(m) < 0) {
                      deduped.push(m);
                    }
                  }
                  this.layout._values["text-writing-mode"] = deduped;
                } else {
                  this.layout._values["text-writing-mode"] = ["horizontal"];
                }
              }
              this._setPaintOverrides();
            };
            SymbolStyleLayer2.prototype.getValueAndResolveTokens = function getValueAndResolveTokens(name3, feature, canonical, availableImages) {
              var value = this.layout.get(name3).evaluate(feature, {}, canonical, availableImages);
              var unevaluated = this._unevaluatedLayout._values[name3];
              if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) {
                return resolveTokens(feature.properties, value);
              }
              return value;
            };
            SymbolStyleLayer2.prototype.createBucket = function createBucket(parameters) {
              return new SymbolBucket(parameters);
            };
            SymbolStyleLayer2.prototype.queryRadius = function queryRadius() {
              return 0;
            };
            SymbolStyleLayer2.prototype.queryIntersectsFeature = function queryIntersectsFeature() {
              return false;
            };
            SymbolStyleLayer2.prototype._setPaintOverrides = function _setPaintOverrides() {
              for (var i = 0, list = properties$6.paint.overridableProperties; i < list.length; i += 1) {
                var overridable = list[i];
                if (!SymbolStyleLayer2.hasPaintOverride(this.layout, overridable)) {
                  continue;
                }
                var overriden = this.paint.get(overridable);
                var override = new FormatSectionOverride(overriden);
                var styleExpression = new StyleExpression(override, overriden.property.specification);
                var expression2 = null;
                if (overriden.value.kind === "constant" || overriden.value.kind === "source") {
                  expression2 = new ZoomConstantExpression("source", styleExpression);
                } else {
                  expression2 = new ZoomDependentExpression("composite", styleExpression, overriden.value.zoomStops, overriden.value._interpolationType);
                }
                this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overriden.property, expression2, overriden.parameters);
              }
            };
            SymbolStyleLayer2.prototype._handleOverridablePaintPropertyUpdate = function _handleOverridablePaintPropertyUpdate(name3, oldValue, newValue) {
              if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {
                return false;
              }
              return SymbolStyleLayer2.hasPaintOverride(this.layout, name3);
            };
            SymbolStyleLayer2.hasPaintOverride = function hasPaintOverride(layout2, propertyName) {
              var textField = layout2.get("text-field");
              var property = properties$6.paint.properties[propertyName];
              var hasOverrides = false;
              var checkSections = function(sections) {
                for (var i = 0, list = sections; i < list.length; i += 1) {
                  var section = list[i];
                  if (property.overrides && property.overrides.hasOverride(section)) {
                    hasOverrides = true;
                    return;
                  }
                }
              };
              if (textField.value.kind === "constant" && textField.value.value instanceof Formatted) {
                checkSections(textField.value.value.sections);
              } else if (textField.value.kind === "source") {
                var checkExpression = function(expression2) {
                  if (hasOverrides) {
                    return;
                  }
                  if (expression2 instanceof Literal && typeOf(expression2.value) === FormattedType) {
                    var formatted = expression2.value;
                    checkSections(formatted.sections);
                  } else if (expression2 instanceof FormatExpression) {
                    checkSections(expression2.sections);
                  } else {
                    expression2.eachChild(checkExpression);
                  }
                };
                var expr = textField.value;
                if (expr._styleExpression) {
                  checkExpression(expr._styleExpression.expression);
                }
              }
              return hasOverrides;
            };
            return SymbolStyleLayer2;
          }(StyleLayer);
          var paint$8 = new Properties({
            "background-color": new DataConstantProperty(spec["paint_background"]["background-color"]),
            "background-pattern": new CrossFadedProperty(spec["paint_background"]["background-pattern"]),
            "background-opacity": new DataConstantProperty(spec["paint_background"]["background-opacity"])
          });
          var properties$7 = { paint: paint$8 };
          var BackgroundStyleLayer = function(StyleLayer2) {
            function BackgroundStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$7);
            }
            if (StyleLayer2)
              BackgroundStyleLayer2.__proto__ = StyleLayer2;
            BackgroundStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            BackgroundStyleLayer2.prototype.constructor = BackgroundStyleLayer2;
            return BackgroundStyleLayer2;
          }(StyleLayer);
          var paint$9 = new Properties({
            "raster-opacity": new DataConstantProperty(spec["paint_raster"]["raster-opacity"]),
            "raster-hue-rotate": new DataConstantProperty(spec["paint_raster"]["raster-hue-rotate"]),
            "raster-brightness-min": new DataConstantProperty(spec["paint_raster"]["raster-brightness-min"]),
            "raster-brightness-max": new DataConstantProperty(spec["paint_raster"]["raster-brightness-max"]),
            "raster-saturation": new DataConstantProperty(spec["paint_raster"]["raster-saturation"]),
            "raster-contrast": new DataConstantProperty(spec["paint_raster"]["raster-contrast"]),
            "raster-resampling": new DataConstantProperty(spec["paint_raster"]["raster-resampling"]),
            "raster-fade-duration": new DataConstantProperty(spec["paint_raster"]["raster-fade-duration"])
          });
          var properties$8 = { paint: paint$9 };
          var RasterStyleLayer = function(StyleLayer2) {
            function RasterStyleLayer2(layer2) {
              StyleLayer2.call(this, layer2, properties$8);
            }
            if (StyleLayer2)
              RasterStyleLayer2.__proto__ = StyleLayer2;
            RasterStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            RasterStyleLayer2.prototype.constructor = RasterStyleLayer2;
            return RasterStyleLayer2;
          }(StyleLayer);
          function validateCustomStyleLayer(layerObject) {
            var errors = [];
            var id2 = layerObject.id;
            if (id2 === void 0) {
              errors.push({ message: "layers." + id2 + ': missing required property "id"' });
            }
            if (layerObject.render === void 0) {
              errors.push({ message: "layers." + id2 + ': missing required method "render"' });
            }
            if (layerObject.renderingMode && layerObject.renderingMode !== "2d" && layerObject.renderingMode !== "3d") {
              errors.push({ message: "layers." + id2 + ': property "renderingMode" must be either "2d" or "3d"' });
            }
            return errors;
          }
          var CustomStyleLayer = function(StyleLayer2) {
            function CustomStyleLayer2(implementation) {
              StyleLayer2.call(this, implementation, {});
              this.implementation = implementation;
            }
            if (StyleLayer2)
              CustomStyleLayer2.__proto__ = StyleLayer2;
            CustomStyleLayer2.prototype = Object.create(StyleLayer2 && StyleLayer2.prototype);
            CustomStyleLayer2.prototype.constructor = CustomStyleLayer2;
            CustomStyleLayer2.prototype.is3D = function is3D() {
              return this.implementation.renderingMode === "3d";
            };
            CustomStyleLayer2.prototype.hasOffscreenPass = function hasOffscreenPass() {
              return this.implementation.prerender !== void 0;
            };
            CustomStyleLayer2.prototype.recalculate = function recalculate() {
            };
            CustomStyleLayer2.prototype.updateTransitions = function updateTransitions() {
            };
            CustomStyleLayer2.prototype.hasTransition = function hasTransition() {
            };
            CustomStyleLayer2.prototype.serialize = function serialize2() {
            };
            CustomStyleLayer2.prototype.onAdd = function onAdd(map) {
              if (this.implementation.onAdd) {
                this.implementation.onAdd(map, map.painter.context.gl);
              }
            };
            CustomStyleLayer2.prototype.onRemove = function onRemove(map) {
              if (this.implementation.onRemove) {
                this.implementation.onRemove(map, map.painter.context.gl);
              }
            };
            return CustomStyleLayer2;
          }(StyleLayer);
          var subclasses = {
            circle: CircleStyleLayer,
            heatmap: HeatmapStyleLayer,
            hillshade: HillshadeStyleLayer,
            fill: FillStyleLayer,
            "fill-extrusion": FillExtrusionStyleLayer,
            line: LineStyleLayer,
            symbol: SymbolStyleLayer,
            background: BackgroundStyleLayer,
            raster: RasterStyleLayer
          };
          function createStyleLayer(layer2) {
            if (layer2.type === "custom") {
              return new CustomStyleLayer(layer2);
            } else {
              return new subclasses[layer2.type](layer2);
            }
          }
          var HTMLImageElement2 = window$1.HTMLImageElement;
          var HTMLCanvasElement2 = window$1.HTMLCanvasElement;
          var HTMLVideoElement2 = window$1.HTMLVideoElement;
          var ImageData$1 = window$1.ImageData;
          var ImageBitmap$1 = window$1.ImageBitmap;
          var Texture = function Texture2(context, image, format, options) {
            this.context = context;
            this.format = format;
            this.texture = context.gl.createTexture();
            this.update(image, options);
          };
          Texture.prototype.update = function update(image, options, position) {
            var width = image.width;
            var height = image.height;
            var resize = (!this.size || this.size[0] !== width || this.size[1] !== height) && !position;
            var ref = this;
            var context = ref.context;
            var gl2 = context.gl;
            this.useMipmap = Boolean(options && options.useMipmap);
            gl2.bindTexture(gl2.TEXTURE_2D, this.texture);
            context.pixelStoreUnpackFlipY.set(false);
            context.pixelStoreUnpack.set(1);
            context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl2.RGBA && (!options || options.premultiply !== false));
            if (resize) {
              this.size = [
                width,
                height
              ];
              if (image instanceof HTMLImageElement2 || image instanceof HTMLCanvasElement2 || image instanceof HTMLVideoElement2 || image instanceof ImageData$1 || ImageBitmap$1 && image instanceof ImageBitmap$1) {
                gl2.texImage2D(gl2.TEXTURE_2D, 0, this.format, this.format, gl2.UNSIGNED_BYTE, image);
              } else {
                gl2.texImage2D(gl2.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl2.UNSIGNED_BYTE, image.data);
              }
            } else {
              var ref$1 = position || {
                x: 0,
                y: 0
              };
              var x = ref$1.x;
              var y = ref$1.y;
              if (image instanceof HTMLImageElement2 || image instanceof HTMLCanvasElement2 || image instanceof HTMLVideoElement2 || image instanceof ImageData$1 || ImageBitmap$1 && image instanceof ImageBitmap$1) {
                gl2.texSubImage2D(gl2.TEXTURE_2D, 0, x, y, gl2.RGBA, gl2.UNSIGNED_BYTE, image);
              } else {
                gl2.texSubImage2D(gl2.TEXTURE_2D, 0, x, y, width, height, gl2.RGBA, gl2.UNSIGNED_BYTE, image.data);
              }
            }
            if (this.useMipmap && this.isSizePowerOfTwo()) {
              gl2.generateMipmap(gl2.TEXTURE_2D);
            }
          };
          Texture.prototype.bind = function bind(filter2, wrap2, minFilter) {
            var ref = this;
            var context = ref.context;
            var gl2 = context.gl;
            gl2.bindTexture(gl2.TEXTURE_2D, this.texture);
            if (minFilter === gl2.LINEAR_MIPMAP_NEAREST && !this.isSizePowerOfTwo()) {
              minFilter = gl2.LINEAR;
            }
            if (filter2 !== this.filter) {
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, filter2);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, minFilter || filter2);
              this.filter = filter2;
            }
            if (wrap2 !== this.wrap) {
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, wrap2);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, wrap2);
              this.wrap = wrap2;
            }
          };
          Texture.prototype.isSizePowerOfTwo = function isSizePowerOfTwo() {
            return this.size[0] === this.size[1] && Math.log(this.size[0]) / Math.LN2 % 1 === 0;
          };
          Texture.prototype.destroy = function destroy() {
            var ref = this.context;
            var gl2 = ref.gl;
            gl2.deleteTexture(this.texture);
            this.texture = null;
          };
          var ThrottledInvoker = function ThrottledInvoker2(callback) {
            var this$1 = this;
            this._callback = callback;
            this._triggered = false;
            if (typeof MessageChannel !== "undefined") {
              this._channel = new MessageChannel();
              this._channel.port2.onmessage = function() {
                this$1._triggered = false;
                this$1._callback();
              };
            }
          };
          ThrottledInvoker.prototype.trigger = function trigger() {
            var this$1 = this;
            if (!this._triggered) {
              this._triggered = true;
              if (this._channel) {
                this._channel.port1.postMessage(true);
              } else {
                setTimeout(function() {
                  this$1._triggered = false;
                  this$1._callback();
                }, 0);
              }
            }
          };
          ThrottledInvoker.prototype.remove = function remove() {
            delete this._channel;
            this._callback = function() {
            };
          };
          var Actor = function Actor2(target, parent, mapId) {
            this.target = target;
            this.parent = parent;
            this.mapId = mapId;
            this.callbacks = {};
            this.tasks = {};
            this.taskQueue = [];
            this.cancelCallbacks = {};
            bindAll([
              "receive",
              "process"
            ], this);
            this.invoker = new ThrottledInvoker(this.process);
            this.target.addEventListener("message", this.receive, false);
            this.globalScope = isWorker() ? target : window$1;
          };
          Actor.prototype.send = function send(type, data, callback, targetMapId, mustQueue) {
            var this$1 = this;
            if (mustQueue === void 0)
              mustQueue = false;
            var id2 = Math.round(Math.random() * 1e18).toString(36).substring(0, 10);
            if (callback) {
              this.callbacks[id2] = callback;
            }
            var buffers = isSafari(this.globalScope) ? void 0 : [];
            this.target.postMessage({
              id: id2,
              type,
              hasCallback: !!callback,
              targetMapId,
              mustQueue,
              sourceMapId: this.mapId,
              data: serialize(data, buffers)
            }, buffers);
            return {
              cancel: function() {
                if (callback) {
                  delete this$1.callbacks[id2];
                }
                this$1.target.postMessage({
                  id: id2,
                  type: "<cancel>",
                  targetMapId,
                  sourceMapId: this$1.mapId
                });
              }
            };
          };
          Actor.prototype.receive = function receive(message) {
            var data = message.data, id2 = data.id;
            if (!id2) {
              return;
            }
            if (data.targetMapId && this.mapId !== data.targetMapId) {
              return;
            }
            if (data.type === "<cancel>") {
              delete this.tasks[id2];
              var cancel2 = this.cancelCallbacks[id2];
              delete this.cancelCallbacks[id2];
              if (cancel2) {
                cancel2();
              }
            } else {
              if (isWorker() || data.mustQueue) {
                this.tasks[id2] = data;
                this.taskQueue.push(id2);
                this.invoker.trigger();
              } else {
                this.processTask(id2, data);
              }
            }
          };
          Actor.prototype.process = function process2() {
            if (!this.taskQueue.length) {
              return;
            }
            var id2 = this.taskQueue.shift();
            var task = this.tasks[id2];
            delete this.tasks[id2];
            if (this.taskQueue.length) {
              this.invoker.trigger();
            }
            if (!task) {
              return;
            }
            this.processTask(id2, task);
          };
          Actor.prototype.processTask = function processTask(id2, task) {
            var this$1 = this;
            if (task.type === "<response>") {
              var callback = this.callbacks[id2];
              delete this.callbacks[id2];
              if (callback) {
                if (task.error) {
                  callback(deserialize(task.error));
                } else {
                  callback(null, deserialize(task.data));
                }
              }
            } else {
              var completed = false;
              var buffers = isSafari(this.globalScope) ? void 0 : [];
              var done = task.hasCallback ? function(err, data) {
                completed = true;
                delete this$1.cancelCallbacks[id2];
                this$1.target.postMessage({
                  id: id2,
                  type: "<response>",
                  sourceMapId: this$1.mapId,
                  error: err ? serialize(err) : null,
                  data: serialize(data, buffers)
                }, buffers);
              } : function(_) {
                completed = true;
              };
              var callback$1 = null;
              var params = deserialize(task.data);
              if (this.parent[task.type]) {
                callback$1 = this.parent[task.type](task.sourceMapId, params, done);
              } else if (this.parent.getWorkerSource) {
                var keys = task.type.split(".");
                var scope = this.parent.getWorkerSource(task.sourceMapId, keys[0], params.source);
                callback$1 = scope[keys[1]](params, done);
              } else {
                done(new Error("Could not find function " + task.type));
              }
              if (!completed && callback$1 && callback$1.cancel) {
                this.cancelCallbacks[id2] = callback$1.cancel;
              }
            }
          };
          Actor.prototype.remove = function remove() {
            this.invoker.remove();
            this.target.removeEventListener("message", this.receive, false);
          };
          function getTileBBox(x, y, z) {
            y = Math.pow(2, z) - y - 1;
            var min = getMercCoords(x * 256, y * 256, z), max = getMercCoords((x + 1) * 256, (y + 1) * 256, z);
            return min[0] + "," + min[1] + "," + max[0] + "," + max[1];
          }
          function getMercCoords(x, y, z) {
            var resolution = 2 * Math.PI * 6378137 / 256 / Math.pow(2, z), merc_x = x * resolution - 2 * Math.PI * 6378137 / 2, merc_y = y * resolution - 2 * Math.PI * 6378137 / 2;
            return [merc_x, merc_y];
          }
          var LngLatBounds = function LngLatBounds2(sw, ne) {
            if (!sw) ;
            else if (ne) {
              this.setSouthWest(sw).setNorthEast(ne);
            } else if (sw.length === 4) {
              this.setSouthWest([
                sw[0],
                sw[1]
              ]).setNorthEast([
                sw[2],
                sw[3]
              ]);
            } else {
              this.setSouthWest(sw[0]).setNorthEast(sw[1]);
            }
          };
          LngLatBounds.prototype.setNorthEast = function setNorthEast(ne) {
            this._ne = ne instanceof LngLat ? new LngLat(ne.lng, ne.lat) : LngLat.convert(ne);
            return this;
          };
          LngLatBounds.prototype.setSouthWest = function setSouthWest(sw) {
            this._sw = sw instanceof LngLat ? new LngLat(sw.lng, sw.lat) : LngLat.convert(sw);
            return this;
          };
          LngLatBounds.prototype.extend = function extend3(obj) {
            var sw = this._sw, ne = this._ne;
            var sw2, ne2;
            if (obj instanceof LngLat) {
              sw2 = obj;
              ne2 = obj;
            } else if (obj instanceof LngLatBounds) {
              sw2 = obj._sw;
              ne2 = obj._ne;
              if (!sw2 || !ne2) {
                return this;
              }
            } else {
              if (Array.isArray(obj)) {
                if (obj.length === 4 || obj.every(Array.isArray)) {
                  var lngLatBoundsObj = obj;
                  return this.extend(LngLatBounds.convert(lngLatBoundsObj));
                } else {
                  var lngLatObj = obj;
                  return this.extend(LngLat.convert(lngLatObj));
                }
              }
              return this;
            }
            if (!sw && !ne) {
              this._sw = new LngLat(sw2.lng, sw2.lat);
              this._ne = new LngLat(ne2.lng, ne2.lat);
            } else {
              sw.lng = Math.min(sw2.lng, sw.lng);
              sw.lat = Math.min(sw2.lat, sw.lat);
              ne.lng = Math.max(ne2.lng, ne.lng);
              ne.lat = Math.max(ne2.lat, ne.lat);
            }
            return this;
          };
          LngLatBounds.prototype.getCenter = function getCenter() {
            return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);
          };
          LngLatBounds.prototype.getSouthWest = function getSouthWest() {
            return this._sw;
          };
          LngLatBounds.prototype.getNorthEast = function getNorthEast() {
            return this._ne;
          };
          LngLatBounds.prototype.getNorthWest = function getNorthWest() {
            return new LngLat(this.getWest(), this.getNorth());
          };
          LngLatBounds.prototype.getSouthEast = function getSouthEast() {
            return new LngLat(this.getEast(), this.getSouth());
          };
          LngLatBounds.prototype.getWest = function getWest() {
            return this._sw.lng;
          };
          LngLatBounds.prototype.getSouth = function getSouth() {
            return this._sw.lat;
          };
          LngLatBounds.prototype.getEast = function getEast() {
            return this._ne.lng;
          };
          LngLatBounds.prototype.getNorth = function getNorth() {
            return this._ne.lat;
          };
          LngLatBounds.prototype.toArray = function toArray() {
            return [
              this._sw.toArray(),
              this._ne.toArray()
            ];
          };
          LngLatBounds.prototype.toString = function toString2() {
            return "LngLatBounds(" + this._sw.toString() + ", " + this._ne.toString() + ")";
          };
          LngLatBounds.prototype.isEmpty = function isEmpty2() {
            return !(this._sw && this._ne);
          };
          LngLatBounds.prototype.contains = function contains(lnglat) {
            var ref = LngLat.convert(lnglat);
            var lng = ref.lng;
            var lat = ref.lat;
            var containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat;
            var containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng;
            if (this._sw.lng > this._ne.lng) {
              containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng;
            }
            return containsLatitude && containsLongitude;
          };
          LngLatBounds.convert = function convert(input) {
            if (!input || input instanceof LngLatBounds) {
              return input;
            }
            return new LngLatBounds(input);
          };
          var earthRadius = 63710088e-1;
          var LngLat = function LngLat2(lng, lat) {
            if (isNaN(lng) || isNaN(lat)) {
              throw new Error("Invalid LngLat object: (" + lng + ", " + lat + ")");
            }
            this.lng = +lng;
            this.lat = +lat;
            if (this.lat > 90 || this.lat < -90) {
              throw new Error("Invalid LngLat latitude value: must be between -90 and 90");
            }
          };
          LngLat.prototype.wrap = function wrap$1() {
            return new LngLat(wrap(this.lng, -180, 180), this.lat);
          };
          LngLat.prototype.toArray = function toArray() {
            return [
              this.lng,
              this.lat
            ];
          };
          LngLat.prototype.toString = function toString2() {
            return "LngLat(" + this.lng + ", " + this.lat + ")";
          };
          LngLat.prototype.distanceTo = function distanceTo(lngLat) {
            var rad = Math.PI / 180;
            var lat1 = this.lat * rad;
            var lat2 = lngLat.lat * rad;
            var a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad);
            var maxMeters = earthRadius * Math.acos(Math.min(a, 1));
            return maxMeters;
          };
          LngLat.prototype.toBounds = function toBounds(radius) {
            if (radius === void 0)
              radius = 0;
            var earthCircumferenceInMetersAtEquator = 40075017;
            var latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator, lngAccuracy = latAccuracy / Math.cos(Math.PI / 180 * this.lat);
            return new LngLatBounds(new LngLat(this.lng - lngAccuracy, this.lat - latAccuracy), new LngLat(this.lng + lngAccuracy, this.lat + latAccuracy));
          };
          LngLat.convert = function convert(input) {
            if (input instanceof LngLat) {
              return input;
            }
            if (Array.isArray(input) && (input.length === 2 || input.length === 3)) {
              return new LngLat(Number(input[0]), Number(input[1]));
            }
            if (!Array.isArray(input) && typeof input === "object" && input !== null) {
              return new LngLat(Number("lng" in input ? input.lng : input.lon), Number(input.lat));
            }
            throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]");
          };
          var earthCircumfrence = 2 * Math.PI * earthRadius;
          function circumferenceAtLatitude(latitude) {
            return earthCircumfrence * Math.cos(latitude * Math.PI / 180);
          }
          function mercatorXfromLng$1(lng) {
            return (180 + lng) / 360;
          }
          function mercatorYfromLat$1(lat) {
            return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360))) / 360;
          }
          function mercatorZfromAltitude(altitude, lat) {
            return altitude / circumferenceAtLatitude(lat);
          }
          function lngFromMercatorX(x) {
            return x * 360 - 180;
          }
          function latFromMercatorY(y) {
            var y2 = 180 - y * 360;
            return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;
          }
          function altitudeFromMercatorZ(z, y) {
            return z * circumferenceAtLatitude(latFromMercatorY(y));
          }
          function mercatorScale(lat) {
            return 1 / Math.cos(lat * Math.PI / 180);
          }
          var MercatorCoordinate = function MercatorCoordinate2(x, y, z) {
            if (z === void 0)
              z = 0;
            this.x = +x;
            this.y = +y;
            this.z = +z;
          };
          MercatorCoordinate.fromLngLat = function fromLngLat(lngLatLike, altitude) {
            if (altitude === void 0)
              altitude = 0;
            var lngLat = LngLat.convert(lngLatLike);
            return new MercatorCoordinate(mercatorXfromLng$1(lngLat.lng), mercatorYfromLat$1(lngLat.lat), mercatorZfromAltitude(altitude, lngLat.lat));
          };
          MercatorCoordinate.prototype.toLngLat = function toLngLat() {
            return new LngLat(lngFromMercatorX(this.x), latFromMercatorY(this.y));
          };
          MercatorCoordinate.prototype.toAltitude = function toAltitude() {
            return altitudeFromMercatorZ(this.z, this.y);
          };
          MercatorCoordinate.prototype.meterInMercatorCoordinateUnits = function meterInMercatorCoordinateUnits() {
            return 1 / earthCircumfrence * mercatorScale(latFromMercatorY(this.y));
          };
          var CanonicalTileID = function CanonicalTileID2(z, x, y) {
            this.z = z;
            this.x = x;
            this.y = y;
            this.key = calculateKey(0, z, z, x, y);
          };
          CanonicalTileID.prototype.equals = function equals2(id2) {
            return this.z === id2.z && this.x === id2.x && this.y === id2.y;
          };
          CanonicalTileID.prototype.url = function url(urls, scheme) {
            var bbox = getTileBBox(this.x, this.y, this.z);
            var quadkey = getQuadkey(this.z, this.x, this.y);
            return urls[(this.x + this.y) % urls.length].replace("{prefix}", (this.x % 16).toString(16) + (this.y % 16).toString(16)).replace("{z}", String(this.z)).replace("{x}", String(this.x)).replace("{y}", String(scheme === "tms" ? Math.pow(2, this.z) - this.y - 1 : this.y)).replace("{quadkey}", quadkey).replace("{bbox-epsg-3857}", bbox);
          };
          CanonicalTileID.prototype.getTilePoint = function getTilePoint(coord) {
            var tilesAtZoom = Math.pow(2, this.z);
            return new pointGeometry((coord.x * tilesAtZoom - this.x) * EXTENT$1, (coord.y * tilesAtZoom - this.y) * EXTENT$1);
          };
          CanonicalTileID.prototype.toString = function toString2() {
            return this.z + "/" + this.x + "/" + this.y;
          };
          var UnwrappedTileID = function UnwrappedTileID2(wrap2, canonical) {
            this.wrap = wrap2;
            this.canonical = canonical;
            this.key = calculateKey(wrap2, canonical.z, canonical.z, canonical.x, canonical.y);
          };
          var OverscaledTileID = function OverscaledTileID2(overscaledZ, wrap2, z, x, y) {
            this.overscaledZ = overscaledZ;
            this.wrap = wrap2;
            this.canonical = new CanonicalTileID(z, +x, +y);
            this.key = calculateKey(wrap2, overscaledZ, z, x, y);
          };
          OverscaledTileID.prototype.equals = function equals2(id2) {
            return this.overscaledZ === id2.overscaledZ && this.wrap === id2.wrap && this.canonical.equals(id2.canonical);
          };
          OverscaledTileID.prototype.scaledTo = function scaledTo(targetZ) {
            var zDifference = this.canonical.z - targetZ;
            if (targetZ > this.canonical.z) {
              return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);
            } else {
              return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);
            }
          };
          OverscaledTileID.prototype.calculateScaledKey = function calculateScaledKey(targetZ, withWrap) {
            var zDifference = this.canonical.z - targetZ;
            if (targetZ > this.canonical.z) {
              return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);
            } else {
              return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);
            }
          };
          OverscaledTileID.prototype.isChildOf = function isChildOf(parent) {
            if (parent.wrap !== this.wrap) {
              return false;
            }
            var zDifference = this.canonical.z - parent.canonical.z;
            return parent.overscaledZ === 0 || parent.overscaledZ < this.overscaledZ && parent.canonical.x === this.canonical.x >> zDifference && parent.canonical.y === this.canonical.y >> zDifference;
          };
          OverscaledTileID.prototype.children = function children(sourceMaxZoom) {
            if (this.overscaledZ >= sourceMaxZoom) {
              return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];
            }
            var z = this.canonical.z + 1;
            var x = this.canonical.x * 2;
            var y = this.canonical.y * 2;
            return [
              new OverscaledTileID(z, this.wrap, z, x, y),
              new OverscaledTileID(z, this.wrap, z, x + 1, y),
              new OverscaledTileID(z, this.wrap, z, x, y + 1),
              new OverscaledTileID(z, this.wrap, z, x + 1, y + 1)
            ];
          };
          OverscaledTileID.prototype.isLessThan = function isLessThan(rhs) {
            if (this.wrap < rhs.wrap) {
              return true;
            }
            if (this.wrap > rhs.wrap) {
              return false;
            }
            if (this.overscaledZ < rhs.overscaledZ) {
              return true;
            }
            if (this.overscaledZ > rhs.overscaledZ) {
              return false;
            }
            if (this.canonical.x < rhs.canonical.x) {
              return true;
            }
            if (this.canonical.x > rhs.canonical.x) {
              return false;
            }
            if (this.canonical.y < rhs.canonical.y) {
              return true;
            }
            return false;
          };
          OverscaledTileID.prototype.wrapped = function wrapped() {
            return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);
          };
          OverscaledTileID.prototype.unwrapTo = function unwrapTo(wrap2) {
            return new OverscaledTileID(this.overscaledZ, wrap2, this.canonical.z, this.canonical.x, this.canonical.y);
          };
          OverscaledTileID.prototype.overscaleFactor = function overscaleFactor() {
            return Math.pow(2, this.overscaledZ - this.canonical.z);
          };
          OverscaledTileID.prototype.toUnwrapped = function toUnwrapped() {
            return new UnwrappedTileID(this.wrap, this.canonical);
          };
          OverscaledTileID.prototype.toString = function toString2() {
            return this.overscaledZ + "/" + this.canonical.x + "/" + this.canonical.y;
          };
          OverscaledTileID.prototype.getTilePoint = function getTilePoint(coord) {
            return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y));
          };
          function calculateKey(wrap2, overscaledZ, z, x, y) {
            wrap2 *= 2;
            if (wrap2 < 0) {
              wrap2 = wrap2 * -1 - 1;
            }
            var dim = 1 << z;
            return (dim * dim * wrap2 + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36);
          }
          function getQuadkey(z, x, y) {
            var quadkey = "", mask;
            for (var i = z; i > 0; i--) {
              mask = 1 << i - 1;
              quadkey += (x & mask ? 1 : 0) + (y & mask ? 2 : 0);
            }
            return quadkey;
          }
          register("CanonicalTileID", CanonicalTileID);
          register("OverscaledTileID", OverscaledTileID, { omit: ["posMatrix"] });
          var DEMData = function DEMData2(uid, data, encoding) {
            this.uid = uid;
            if (data.height !== data.width) {
              throw new RangeError("DEM tiles must be square");
            }
            if (encoding && encoding !== "mapbox" && encoding !== "terrarium") {
              return warnOnce('"' + encoding + '" is not a valid encoding type. Valid types include "mapbox" and "terrarium".');
            }
            this.stride = data.height;
            var dim = this.dim = data.height - 2;
            this.data = new Uint32Array(data.data.buffer);
            this.encoding = encoding || "mapbox";
            for (var x = 0; x < dim; x++) {
              this.data[this._idx(-1, x)] = this.data[this._idx(0, x)];
              this.data[this._idx(dim, x)] = this.data[this._idx(dim - 1, x)];
              this.data[this._idx(x, -1)] = this.data[this._idx(x, 0)];
              this.data[this._idx(x, dim)] = this.data[this._idx(x, dim - 1)];
            }
            this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)];
            this.data[this._idx(dim, -1)] = this.data[this._idx(dim - 1, 0)];
            this.data[this._idx(-1, dim)] = this.data[this._idx(0, dim - 1)];
            this.data[this._idx(dim, dim)] = this.data[this._idx(dim - 1, dim - 1)];
          };
          DEMData.prototype.get = function get2(x, y) {
            var pixels = new Uint8Array(this.data.buffer);
            var index = this._idx(x, y) * 4;
            var unpack = this.encoding === "terrarium" ? this._unpackTerrarium : this._unpackMapbox;
            return unpack(pixels[index], pixels[index + 1], pixels[index + 2]);
          };
          DEMData.prototype.getUnpackVector = function getUnpackVector() {
            return this.encoding === "terrarium" ? [
              256,
              1,
              1 / 256,
              32768
            ] : [
              6553.6,
              25.6,
              0.1,
              1e4
            ];
          };
          DEMData.prototype._idx = function _idx(x, y) {
            if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1) {
              throw new RangeError("out of range source coordinates for DEM data");
            }
            return (y + 1) * this.stride + (x + 1);
          };
          DEMData.prototype._unpackMapbox = function _unpackMapbox(r, g, b) {
            return (r * 256 * 256 + g * 256 + b) / 10 - 1e4;
          };
          DEMData.prototype._unpackTerrarium = function _unpackTerrarium(r, g, b) {
            return r * 256 + g + b / 256 - 32768;
          };
          DEMData.prototype.getPixels = function getPixels() {
            return new RGBAImage({
              width: this.stride,
              height: this.stride
            }, new Uint8Array(this.data.buffer));
          };
          DEMData.prototype.backfillBorder = function backfillBorder(borderTile, dx, dy) {
            if (this.dim !== borderTile.dim) {
              throw new Error("dem dimension mismatch");
            }
            var xMin = dx * this.dim, xMax = dx * this.dim + this.dim, yMin = dy * this.dim, yMax = dy * this.dim + this.dim;
            switch (dx) {
              case -1:
                xMin = xMax - 1;
                break;
              case 1:
                xMax = xMin + 1;
                break;
            }
            switch (dy) {
              case -1:
                yMin = yMax - 1;
                break;
              case 1:
                yMax = yMin + 1;
                break;
            }
            var ox = -dx * this.dim;
            var oy = -dy * this.dim;
            for (var y = yMin; y < yMax; y++) {
              for (var x = xMin; x < xMax; x++) {
                this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)];
              }
            }
          };
          register("DEMData", DEMData);
          function deserialize$1(input, style) {
            var output = {};
            if (!style) {
              return output;
            }
            var loop = function() {
              var bucket = list$1[i$1];
              var layers = bucket.layerIds.map(function(id2) {
                return style.getLayer(id2);
              }).filter(Boolean);
              if (layers.length === 0) {
                return;
              }
              bucket.layers = layers;
              if (bucket.stateDependentLayerIds) {
                bucket.stateDependentLayers = bucket.stateDependentLayerIds.map(function(lId) {
                  return layers.filter(function(l) {
                    return l.id === lId;
                  })[0];
                });
              }
              for (var i = 0, list = layers; i < list.length; i += 1) {
                var layer2 = list[i];
                output[layer2.id] = bucket;
              }
            };
            for (var i$1 = 0, list$1 = input; i$1 < list$1.length; i$1 += 1)
              loop();
            return output;
          }
          var DictionaryCoder = function DictionaryCoder2(strings) {
            this._stringToNumber = {};
            this._numberToString = [];
            for (var i = 0; i < strings.length; i++) {
              var string = strings[i];
              this._stringToNumber[string] = i;
              this._numberToString[i] = string;
            }
          };
          DictionaryCoder.prototype.encode = function encode(string) {
            return this._stringToNumber[string];
          };
          DictionaryCoder.prototype.decode = function decode(n) {
            return this._numberToString[n];
          };
          var Feature = function Feature2(vectorTileFeature, z, x, y, id2) {
            this.type = "Feature";
            this._vectorTileFeature = vectorTileFeature;
            vectorTileFeature._z = z;
            vectorTileFeature._x = x;
            vectorTileFeature._y = y;
            this.properties = vectorTileFeature.properties;
            this.id = id2;
          };
          var prototypeAccessors$1 = { geometry: { configurable: true } };
          prototypeAccessors$1.geometry.get = function() {
            if (this._geometry === void 0) {
              this._geometry = this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x, this._vectorTileFeature._y, this._vectorTileFeature._z).geometry;
            }
            return this._geometry;
          };
          prototypeAccessors$1.geometry.set = function(g) {
            this._geometry = g;
          };
          Feature.prototype.toJSON = function toJSON() {
            var json = { geometry: this.geometry };
            for (var i in this) {
              if (i === "_geometry" || i === "_vectorTileFeature") {
                continue;
              }
              json[i] = this[i];
            }
            return json;
          };
          Object.defineProperties(Feature.prototype, prototypeAccessors$1);
          var SourceFeatureState = function SourceFeatureState2() {
            this.state = {};
            this.stateChanges = {};
            this.deletedStates = {};
          };
          SourceFeatureState.prototype.updateState = function updateState(sourceLayer, featureId, newState) {
            var feature = String(featureId);
            this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {};
            this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {};
            extend2(this.stateChanges[sourceLayer][feature], newState);
            if (this.deletedStates[sourceLayer] === null) {
              this.deletedStates[sourceLayer] = {};
              for (var ft in this.state[sourceLayer]) {
                if (ft !== feature) {
                  this.deletedStates[sourceLayer][ft] = null;
                }
              }
            } else {
              var featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null;
              if (featureDeletionQueued) {
                this.deletedStates[sourceLayer][feature] = {};
                for (var prop in this.state[sourceLayer][feature]) {
                  if (!newState[prop]) {
                    this.deletedStates[sourceLayer][feature][prop] = null;
                  }
                }
              } else {
                for (var key in newState) {
                  var deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null;
                  if (deletionInQueue) {
                    delete this.deletedStates[sourceLayer][feature][key];
                  }
                }
              }
            }
          };
          SourceFeatureState.prototype.removeFeatureState = function removeFeatureState(sourceLayer, featureId, key) {
            var sourceLayerDeleted = this.deletedStates[sourceLayer] === null;
            if (sourceLayerDeleted) {
              return;
            }
            var feature = String(featureId);
            this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {};
            if (key && featureId !== void 0) {
              if (this.deletedStates[sourceLayer][feature] !== null) {
                this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {};
                this.deletedStates[sourceLayer][feature][key] = null;
              }
            } else if (featureId !== void 0) {
              var updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature];
              if (updateInQueue) {
                this.deletedStates[sourceLayer][feature] = {};
                for (key in this.stateChanges[sourceLayer][feature]) {
                  this.deletedStates[sourceLayer][feature][key] = null;
                }
              } else {
                this.deletedStates[sourceLayer][feature] = null;
              }
            } else {
              this.deletedStates[sourceLayer] = null;
            }
          };
          SourceFeatureState.prototype.getState = function getState(sourceLayer, featureId) {
            var feature = String(featureId);
            var base = this.state[sourceLayer] || {};
            var changes = this.stateChanges[sourceLayer] || {};
            var reconciledState = extend2({}, base[feature], changes[feature]);
            if (this.deletedStates[sourceLayer] === null) {
              return {};
            } else if (this.deletedStates[sourceLayer]) {
              var featureDeletions = this.deletedStates[sourceLayer][featureId];
              if (featureDeletions === null) {
                return {};
              }
              for (var prop in featureDeletions) {
                delete reconciledState[prop];
              }
            }
            return reconciledState;
          };
          SourceFeatureState.prototype.initializeTileState = function initializeTileState(tile, painter) {
            tile.setFeatureState(this.state, painter);
          };
          SourceFeatureState.prototype.coalesceChanges = function coalesceChanges(tiles, painter) {
            var featuresChanged = {};
            for (var sourceLayer in this.stateChanges) {
              this.state[sourceLayer] = this.state[sourceLayer] || {};
              var layerStates = {};
              for (var feature in this.stateChanges[sourceLayer]) {
                if (!this.state[sourceLayer][feature]) {
                  this.state[sourceLayer][feature] = {};
                }
                extend2(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);
                layerStates[feature] = this.state[sourceLayer][feature];
              }
              featuresChanged[sourceLayer] = layerStates;
            }
            for (var sourceLayer$1 in this.deletedStates) {
              this.state[sourceLayer$1] = this.state[sourceLayer$1] || {};
              var layerStates$1 = {};
              if (this.deletedStates[sourceLayer$1] === null) {
                for (var ft in this.state[sourceLayer$1]) {
                  layerStates$1[ft] = {};
                  this.state[sourceLayer$1][ft] = {};
                }
              } else {
                for (var feature$1 in this.deletedStates[sourceLayer$1]) {
                  var deleteWholeFeatureState = this.deletedStates[sourceLayer$1][feature$1] === null;
                  if (deleteWholeFeatureState) {
                    this.state[sourceLayer$1][feature$1] = {};
                  } else {
                    for (var i = 0, list = Object.keys(this.deletedStates[sourceLayer$1][feature$1]); i < list.length; i += 1) {
                      var key = list[i];
                      delete this.state[sourceLayer$1][feature$1][key];
                    }
                  }
                  layerStates$1[feature$1] = this.state[sourceLayer$1][feature$1];
                }
              }
              featuresChanged[sourceLayer$1] = featuresChanged[sourceLayer$1] || {};
              extend2(featuresChanged[sourceLayer$1], layerStates$1);
            }
            this.stateChanges = {};
            this.deletedStates = {};
            if (Object.keys(featuresChanged).length === 0) {
              return;
            }
            for (var id2 in tiles) {
              var tile = tiles[id2];
              tile.setFeatureState(featuresChanged, painter);
            }
          };
          var FeatureIndex = function FeatureIndex2(tileID, promoteId2) {
            this.tileID = tileID;
            this.x = tileID.canonical.x;
            this.y = tileID.canonical.y;
            this.z = tileID.canonical.z;
            this.grid = new gridIndex(EXTENT$1, 16, 0);
            this.grid3D = new gridIndex(EXTENT$1, 16, 0);
            this.featureIndexArray = new FeatureIndexArray();
            this.promoteId = promoteId2;
          };
          FeatureIndex.prototype.insert = function insert(feature, geometry, featureIndex, sourceLayerIndex, bucketIndex, is3D) {
            var key = this.featureIndexArray.length;
            this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex);
            var grid = is3D ? this.grid3D : this.grid;
            for (var r = 0; r < geometry.length; r++) {
              var ring = geometry[r];
              var bbox = [
                Infinity,
                Infinity,
                -Infinity,
                -Infinity
              ];
              for (var i = 0; i < ring.length; i++) {
                var p = ring[i];
                bbox[0] = Math.min(bbox[0], p.x);
                bbox[1] = Math.min(bbox[1], p.y);
                bbox[2] = Math.max(bbox[2], p.x);
                bbox[3] = Math.max(bbox[3], p.y);
              }
              if (bbox[0] < EXTENT$1 && bbox[1] < EXTENT$1 && bbox[2] >= 0 && bbox[3] >= 0) {
                grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);
              }
            }
          };
          FeatureIndex.prototype.loadVTLayers = function loadVTLayers() {
            if (!this.vtLayers) {
              this.vtLayers = new vectorTile.VectorTile(new pbf(this.rawTileData)).layers;
              this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ["_geojsonTileLayer"]);
            }
            return this.vtLayers;
          };
          FeatureIndex.prototype.query = function query(args, styleLayers, serializedLayers, sourceFeatureState) {
            var this$1 = this;
            this.loadVTLayers();
            var params = args.params || {}, pixelsToTileUnits = EXTENT$1 / args.tileSize / args.scale, filter2 = createFilter(params.filter);
            var queryGeometry = args.queryGeometry;
            var queryPadding = args.queryPadding * pixelsToTileUnits;
            var bounds = getBounds(queryGeometry);
            var matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding);
            var cameraBounds = getBounds(args.cameraQueryGeometry);
            var matching3D = this.grid3D.query(cameraBounds.minX - queryPadding, cameraBounds.minY - queryPadding, cameraBounds.maxX + queryPadding, cameraBounds.maxY + queryPadding, function(bx1, by1, bx2, by2) {
              return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding);
            });
            for (var i = 0, list = matching3D; i < list.length; i += 1) {
              var key = list[i];
              matching.push(key);
            }
            matching.sort(topDownFeatureComparator);
            var result = {};
            var previousIndex;
            var loop = function(k2) {
              var index = matching[k2];
              if (index === previousIndex) {
                return;
              }
              previousIndex = index;
              var match = this$1.featureIndexArray.get(index);
              var featureGeometry = null;
              this$1.loadMatchingFeature(result, match.bucketIndex, match.sourceLayerIndex, match.featureIndex, filter2, params.layers, params.availableImages, styleLayers, serializedLayers, sourceFeatureState, function(feature, styleLayer, featureState) {
                if (!featureGeometry) {
                  featureGeometry = loadGeometry(feature);
                }
                return styleLayer.queryIntersectsFeature(queryGeometry, feature, featureState, featureGeometry, this$1.z, args.transform, pixelsToTileUnits, args.pixelPosMatrix);
              });
            };
            for (var k = 0; k < matching.length; k++)
              loop(k);
            return result;
          };
          FeatureIndex.prototype.loadMatchingFeature = function loadMatchingFeature(result, bucketIndex, sourceLayerIndex, featureIndex, filter2, filterLayerIDs, availableImages, styleLayers, serializedLayers, sourceFeatureState, intersectionTest) {
            var layerIDs = this.bucketLayerIDs[bucketIndex];
            if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs)) {
              return;
            }
            var sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);
            var sourceLayer = this.vtLayers[sourceLayerName];
            var feature = sourceLayer.feature(featureIndex);
            if (filter2.needGeometry) {
              var evaluationFeature = toEvaluationFeature(feature, true);
              if (!filter2.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {
                return;
              }
            } else if (!filter2.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {
              return;
            }
            var id2 = this.getId(feature, sourceLayerName);
            for (var l = 0; l < layerIDs.length; l++) {
              var layerID = layerIDs[l];
              if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) {
                continue;
              }
              var styleLayer = styleLayers[layerID];
              if (!styleLayer) {
                continue;
              }
              var featureState = {};
              if (id2 !== void 0 && sourceFeatureState) {
                featureState = sourceFeatureState.getState(styleLayer.sourceLayer || "_geojsonTileLayer", id2);
              }
              var serializedLayer = extend2({}, serializedLayers[layerID]);
              serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages);
              serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages);
              var intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState);
              if (!intersectionZ) {
                continue;
              }
              var geojsonFeature = new Feature(feature, this.z, this.x, this.y, id2);
              geojsonFeature.layer = serializedLayer;
              var layerResult = result[layerID];
              if (layerResult === void 0) {
                layerResult = result[layerID] = [];
              }
              layerResult.push({
                featureIndex,
                feature: geojsonFeature,
                intersectionZ
              });
            }
          };
          FeatureIndex.prototype.lookupSymbolFeatures = function lookupSymbolFeatures(symbolFeatureIndexes, serializedLayers, bucketIndex, sourceLayerIndex, filterSpec2, filterLayerIDs, availableImages, styleLayers) {
            var result = {};
            this.loadVTLayers();
            var filter2 = createFilter(filterSpec2);
            for (var i = 0, list = symbolFeatureIndexes; i < list.length; i += 1) {
              var symbolFeatureIndex = list[i];
              this.loadMatchingFeature(result, bucketIndex, sourceLayerIndex, symbolFeatureIndex, filter2, filterLayerIDs, availableImages, styleLayers, serializedLayers);
            }
            return result;
          };
          FeatureIndex.prototype.hasLayer = function hasLayer(id2) {
            for (var i$1 = 0, list$1 = this.bucketLayerIDs; i$1 < list$1.length; i$1 += 1) {
              var layerIDs = list$1[i$1];
              for (var i = 0, list = layerIDs; i < list.length; i += 1) {
                var layerID = list[i];
                if (id2 === layerID) {
                  return true;
                }
              }
            }
            return false;
          };
          FeatureIndex.prototype.getId = function getId(feature, sourceLayerId) {
            var id2 = feature.id;
            if (this.promoteId) {
              var propName = typeof this.promoteId === "string" ? this.promoteId : this.promoteId[sourceLayerId];
              id2 = feature.properties[propName];
              if (typeof id2 === "boolean") {
                id2 = Number(id2);
              }
            }
            return id2;
          };
          register("FeatureIndex", FeatureIndex, {
            omit: [
              "rawTileData",
              "sourceLayerCoder"
            ]
          });
          function evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) {
            return mapObject(serializedProperties, function(property, key) {
              var prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null;
              return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop;
            });
          }
          function getBounds(geometry) {
            var minX = Infinity;
            var minY = Infinity;
            var maxX = -Infinity;
            var maxY = -Infinity;
            for (var i = 0, list = geometry; i < list.length; i += 1) {
              var p = list[i];
              minX = Math.min(minX, p.x);
              minY = Math.min(minY, p.y);
              maxX = Math.max(maxX, p.x);
              maxY = Math.max(maxY, p.y);
            }
            return {
              minX,
              minY,
              maxX,
              maxY
            };
          }
          function topDownFeatureComparator(a, b) {
            return b - a;
          }
          var CLOCK_SKEW_RETRY_TIMEOUT = 3e4;
          var Tile = function Tile2(tileID, size) {
            this.tileID = tileID;
            this.uid = uniqueId();
            this.uses = 0;
            this.tileSize = size;
            this.buckets = {};
            this.expirationTime = null;
            this.queryPadding = 0;
            this.hasSymbolBuckets = false;
            this.hasRTLText = false;
            this.dependencies = {};
            this.expiredRequestCount = 0;
            this.state = "loading";
          };
          Tile.prototype.registerFadeDuration = function registerFadeDuration(duration) {
            var fadeEndTime = duration + this.timeAdded;
            if (fadeEndTime < exported.now()) {
              return;
            }
            if (this.fadeEndTime && fadeEndTime < this.fadeEndTime) {
              return;
            }
            this.fadeEndTime = fadeEndTime;
          };
          Tile.prototype.wasRequested = function wasRequested() {
            return this.state === "errored" || this.state === "loaded" || this.state === "reloading";
          };
          Tile.prototype.loadVectorData = function loadVectorData(data, painter, justReloaded) {
            if (this.hasData()) {
              this.unloadVectorData();
            }
            this.state = "loaded";
            if (!data) {
              this.collisionBoxArray = new CollisionBoxArray();
              return;
            }
            if (data.featureIndex) {
              this.latestFeatureIndex = data.featureIndex;
              if (data.rawTileData) {
                this.latestRawTileData = data.rawTileData;
                this.latestFeatureIndex.rawTileData = data.rawTileData;
              } else if (this.latestRawTileData) {
                this.latestFeatureIndex.rawTileData = this.latestRawTileData;
              }
            }
            this.collisionBoxArray = data.collisionBoxArray;
            this.buckets = deserialize$1(data.buckets, painter.style);
            this.hasSymbolBuckets = false;
            for (var id2 in this.buckets) {
              var bucket = this.buckets[id2];
              if (bucket instanceof SymbolBucket) {
                this.hasSymbolBuckets = true;
                if (justReloaded) {
                  bucket.justReloaded = true;
                } else {
                  break;
                }
              }
            }
            this.hasRTLText = false;
            if (this.hasSymbolBuckets) {
              for (var id$1 in this.buckets) {
                var bucket$1 = this.buckets[id$1];
                if (bucket$1 instanceof SymbolBucket) {
                  if (bucket$1.hasRTLText) {
                    this.hasRTLText = true;
                    lazyLoadRTLTextPlugin();
                    break;
                  }
                }
              }
            }
            this.queryPadding = 0;
            for (var id$2 in this.buckets) {
              var bucket$2 = this.buckets[id$2];
              this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id$2).queryRadius(bucket$2));
            }
            if (data.imageAtlas) {
              this.imageAtlas = data.imageAtlas;
            }
            if (data.glyphAtlasImage) {
              this.glyphAtlasImage = data.glyphAtlasImage;
            }
          };
          Tile.prototype.unloadVectorData = function unloadVectorData() {
            for (var id2 in this.buckets) {
              this.buckets[id2].destroy();
            }
            this.buckets = {};
            if (this.imageAtlasTexture) {
              this.imageAtlasTexture.destroy();
            }
            if (this.imageAtlas) {
              this.imageAtlas = null;
            }
            if (this.glyphAtlasTexture) {
              this.glyphAtlasTexture.destroy();
            }
            this.latestFeatureIndex = null;
            this.state = "unloaded";
          };
          Tile.prototype.getBucket = function getBucket(layer2) {
            return this.buckets[layer2.id];
          };
          Tile.prototype.upload = function upload(context) {
            for (var id2 in this.buckets) {
              var bucket = this.buckets[id2];
              if (bucket.uploadPending()) {
                bucket.upload(context);
              }
            }
            var gl2 = context.gl;
            if (this.imageAtlas && !this.imageAtlas.uploaded) {
              this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl2.RGBA);
              this.imageAtlas.uploaded = true;
            }
            if (this.glyphAtlasImage) {
              this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl2.ALPHA);
              this.glyphAtlasImage = null;
            }
          };
          Tile.prototype.prepare = function prepare(imageManager) {
            if (this.imageAtlas) {
              this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);
            }
          };
          Tile.prototype.queryRenderedFeatures = function queryRenderedFeatures(layers, serializedLayers, sourceFeatureState, queryGeometry, cameraQueryGeometry, scale2, params, transform, maxPitchScaleFactor, pixelPosMatrix) {
            if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) {
              return {};
            }
            return this.latestFeatureIndex.query({
              queryGeometry,
              cameraQueryGeometry,
              scale: scale2,
              tileSize: this.tileSize,
              pixelPosMatrix,
              transform,
              params,
              queryPadding: this.queryPadding * maxPitchScaleFactor
            }, layers, serializedLayers, sourceFeatureState);
          };
          Tile.prototype.querySourceFeatures = function querySourceFeatures(result, params) {
            var featureIndex = this.latestFeatureIndex;
            if (!featureIndex || !featureIndex.rawTileData) {
              return;
            }
            var vtLayers = featureIndex.loadVTLayers();
            var sourceLayer = params ? params.sourceLayer : "";
            var layer2 = vtLayers._geojsonTileLayer || vtLayers[sourceLayer];
            if (!layer2) {
              return;
            }
            var filter2 = createFilter(params && params.filter);
            var ref = this.tileID.canonical;
            var z = ref.z;
            var x = ref.x;
            var y = ref.y;
            var coord = {
              z,
              x,
              y
            };
            for (var i = 0; i < layer2.length; i++) {
              var feature = layer2.feature(i);
              if (filter2.needGeometry) {
                var evaluationFeature = toEvaluationFeature(feature, true);
                if (!filter2.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {
                  continue;
                }
              } else if (!filter2.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {
                continue;
              }
              var id2 = featureIndex.getId(feature, sourceLayer);
              var geojsonFeature = new Feature(feature, z, x, y, id2);
              geojsonFeature.tile = coord;
              result.push(geojsonFeature);
            }
          };
          Tile.prototype.hasData = function hasData() {
            return this.state === "loaded" || this.state === "reloading" || this.state === "expired";
          };
          Tile.prototype.patternsLoaded = function patternsLoaded() {
            return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;
          };
          Tile.prototype.setExpiryData = function setExpiryData(data) {
            var prior = this.expirationTime;
            if (data.cacheControl) {
              var parsedCC = parseCacheControl(data.cacheControl);
              if (parsedCC["max-age"]) {
                this.expirationTime = Date.now() + parsedCC["max-age"] * 1e3;
              }
            } else if (data.expires) {
              this.expirationTime = new Date(data.expires).getTime();
            }
            if (this.expirationTime) {
              var now2 = Date.now();
              var isExpired = false;
              if (this.expirationTime > now2) {
                isExpired = false;
              } else if (!prior) {
                isExpired = true;
              } else if (this.expirationTime < prior) {
                isExpired = true;
              } else {
                var delta = this.expirationTime - prior;
                if (!delta) {
                  isExpired = true;
                } else {
                  this.expirationTime = now2 + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);
                }
              }
              if (isExpired) {
                this.expiredRequestCount++;
                this.state = "expired";
              } else {
                this.expiredRequestCount = 0;
              }
            }
          };
          Tile.prototype.getExpiryTimeout = function getExpiryTimeout() {
            if (this.expirationTime) {
              if (this.expiredRequestCount) {
                return 1e3 * (1 << Math.min(this.expiredRequestCount - 1, 31));
              } else {
                return Math.min(this.expirationTime - (/* @__PURE__ */ new Date()).getTime(), Math.pow(2, 31) - 1);
              }
            }
          };
          Tile.prototype.setFeatureState = function setFeatureState(states, painter) {
            if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData || Object.keys(states).length === 0) {
              return;
            }
            var vtLayers = this.latestFeatureIndex.loadVTLayers();
            for (var id2 in this.buckets) {
              if (!painter.style.hasLayer(id2)) {
                continue;
              }
              var bucket = this.buckets[id2];
              var sourceLayerId = bucket.layers[0]["sourceLayer"] || "_geojsonTileLayer";
              var sourceLayer = vtLayers[sourceLayerId];
              var sourceLayerStates = states[sourceLayerId];
              if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) {
                continue;
              }
              bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {});
              var layer2 = painter && painter.style && painter.style.getLayer(id2);
              if (layer2) {
                this.queryPadding = Math.max(this.queryPadding, layer2.queryRadius(bucket));
              }
            }
          };
          Tile.prototype.holdingForFade = function holdingForFade() {
            return this.symbolFadeHoldUntil !== void 0;
          };
          Tile.prototype.symbolFadeFinished = function symbolFadeFinished() {
            return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < exported.now();
          };
          Tile.prototype.clearFadeHold = function clearFadeHold() {
            this.symbolFadeHoldUntil = void 0;
          };
          Tile.prototype.setHoldDuration = function setHoldDuration(duration) {
            this.symbolFadeHoldUntil = exported.now() + duration;
          };
          Tile.prototype.setDependencies = function setDependencies(namespace, dependencies) {
            var index = {};
            for (var i = 0, list = dependencies; i < list.length; i += 1) {
              var dep = list[i];
              index[dep] = true;
            }
            this.dependencies[namespace] = index;
          };
          Tile.prototype.hasDependency = function hasDependency(namespaces, keys) {
            for (var i$1 = 0, list$1 = namespaces; i$1 < list$1.length; i$1 += 1) {
              var namespace = list$1[i$1];
              var dependencies = this.dependencies[namespace];
              if (dependencies) {
                for (var i = 0, list = keys; i < list.length; i += 1) {
                  var key = list[i];
                  if (dependencies[key]) {
                    return true;
                  }
                }
              }
            }
            return false;
          };
          var refProperties = [
            "type",
            "source",
            "source-layer",
            "minzoom",
            "maxzoom",
            "filter",
            "layout"
          ];
          var performance2 = window$1.performance;
          var RequestPerformance = function RequestPerformance2(request) {
            this._marks = {
              start: [
                request.url,
                "start"
              ].join("#"),
              end: [
                request.url,
                "end"
              ].join("#"),
              measure: request.url.toString()
            };
            performance2.mark(this._marks.start);
          };
          RequestPerformance.prototype.finish = function finish() {
            performance2.mark(this._marks.end);
            var resourceTimingData = performance2.getEntriesByName(this._marks.measure);
            if (resourceTimingData.length === 0) {
              performance2.measure(this._marks.measure, this._marks.start, this._marks.end);
              resourceTimingData = performance2.getEntriesByName(this._marks.measure);
              performance2.clearMarks(this._marks.start);
              performance2.clearMarks(this._marks.end);
              performance2.clearMeasures(this._marks.measure);
            }
            return resourceTimingData;
          };
          exports2.Actor = Actor;
          exports2.AlphaImage = AlphaImage;
          exports2.CanonicalTileID = CanonicalTileID;
          exports2.CollisionBoxArray = CollisionBoxArray;
          exports2.Color = Color2;
          exports2.DEMData = DEMData;
          exports2.DataConstantProperty = DataConstantProperty;
          exports2.DictionaryCoder = DictionaryCoder;
          exports2.EXTENT = EXTENT$1;
          exports2.ErrorEvent = ErrorEvent;
          exports2.EvaluationParameters = EvaluationParameters;
          exports2.Event = Event;
          exports2.Evented = Evented;
          exports2.FeatureIndex = FeatureIndex;
          exports2.FillBucket = FillBucket;
          exports2.FillExtrusionBucket = FillExtrusionBucket;
          exports2.ImageAtlas = ImageAtlas;
          exports2.ImagePosition = ImagePosition;
          exports2.LineBucket = LineBucket;
          exports2.LngLat = LngLat;
          exports2.LngLatBounds = LngLatBounds;
          exports2.MercatorCoordinate = MercatorCoordinate;
          exports2.ONE_EM = ONE_EM;
          exports2.OverscaledTileID = OverscaledTileID;
          exports2.Point = pointGeometry;
          exports2.Point$1 = pointGeometry;
          exports2.Properties = Properties;
          exports2.Protobuf = pbf;
          exports2.RGBAImage = RGBAImage;
          exports2.RequestManager = RequestManager;
          exports2.RequestPerformance = RequestPerformance;
          exports2.ResourceType = ResourceType;
          exports2.SegmentVector = SegmentVector;
          exports2.SourceFeatureState = SourceFeatureState;
          exports2.StructArrayLayout1ui2 = StructArrayLayout1ui2;
          exports2.StructArrayLayout2f1f2i16 = StructArrayLayout2f1f2i16;
          exports2.StructArrayLayout2i4 = StructArrayLayout2i4;
          exports2.StructArrayLayout3ui6 = StructArrayLayout3ui6;
          exports2.StructArrayLayout4i8 = StructArrayLayout4i8;
          exports2.SymbolBucket = SymbolBucket;
          exports2.Texture = Texture;
          exports2.Tile = Tile;
          exports2.Transitionable = Transitionable;
          exports2.Uniform1f = Uniform1f;
          exports2.Uniform1i = Uniform1i;
          exports2.Uniform2f = Uniform2f;
          exports2.Uniform3f = Uniform3f;
          exports2.Uniform4f = Uniform4f;
          exports2.UniformColor = UniformColor;
          exports2.UniformMatrix4f = UniformMatrix4f;
          exports2.UnwrappedTileID = UnwrappedTileID;
          exports2.ValidationError = ValidationError;
          exports2.WritingMode = WritingMode;
          exports2.ZoomHistory = ZoomHistory;
          exports2.add = add;
          exports2.addDynamicAttributes = addDynamicAttributes;
          exports2.asyncAll = asyncAll;
          exports2.bezier = bezier;
          exports2.bindAll = bindAll;
          exports2.browser = exported;
          exports2.cacheEntryPossiblyAdded = cacheEntryPossiblyAdded;
          exports2.clamp = clamp;
          exports2.clearTileCache = clearTileCache;
          exports2.clipLine = clipLine;
          exports2.clone = clone$1;
          exports2.clone$1 = clone;
          exports2.clone$2 = clone$2;
          exports2.collisionCircleLayout = collisionCircleLayout;
          exports2.config = config;
          exports2.create = create$2;
          exports2.create$1 = create$1;
          exports2.create$2 = create;
          exports2.createCommonjsModule = createCommonjsModule;
          exports2.createExpression = createExpression;
          exports2.createLayout = createLayout;
          exports2.createStyleLayer = createStyleLayer;
          exports2.cross = cross;
          exports2.deepEqual = deepEqual;
          exports2.dot = dot;
          exports2.dot$1 = dot$1;
          exports2.ease = ease;
          exports2.emitValidationErrors = emitValidationErrors;
          exports2.endsWith = endsWith;
          exports2.enforceCacheSizeLimit = enforceCacheSizeLimit;
          exports2.evaluateSizeForFeature = evaluateSizeForFeature;
          exports2.evaluateSizeForZoom = evaluateSizeForZoom;
          exports2.evaluateVariableOffset = evaluateVariableOffset;
          exports2.evented = evented;
          exports2.extend = extend2;
          exports2.featureFilter = createFilter;
          exports2.filterObject = filterObject;
          exports2.fromRotation = fromRotation;
          exports2.getAnchorAlignment = getAnchorAlignment;
          exports2.getAnchorJustification = getAnchorJustification;
          exports2.getArrayBuffer = getArrayBuffer;
          exports2.getImage = getImage;
          exports2.getJSON = getJSON;
          exports2.getRTLTextPluginStatus = getRTLTextPluginStatus;
          exports2.getReferrer = getReferrer;
          exports2.getVideo = getVideo;
          exports2.identity = identity2;
          exports2.invert = invert;
          exports2.isChar = unicodeBlockLookup;
          exports2.isMapboxURL = isMapboxURL;
          exports2.keysDifference = keysDifference;
          exports2.makeRequest = makeRequest;
          exports2.mapObject = mapObject;
          exports2.mercatorXfromLng = mercatorXfromLng$1;
          exports2.mercatorYfromLat = mercatorYfromLat$1;
          exports2.mercatorZfromAltitude = mercatorZfromAltitude;
          exports2.mul = mul;
          exports2.multiply = multiply;
          exports2.mvt = vectorTile;
          exports2.nextPowerOfTwo = nextPowerOfTwo;
          exports2.normalize = normalize;
          exports2.number = number;
          exports2.offscreenCanvasSupported = offscreenCanvasSupported;
          exports2.ortho = ortho;
          exports2.parseGlyphPBF = parseGlyphPBF;
          exports2.pbf = pbf;
          exports2.performSymbolLayout = performSymbolLayout;
          exports2.perspective = perspective;
          exports2.pick = pick;
          exports2.plugin = plugin;
          exports2.polygonIntersectsPolygon = polygonIntersectsPolygon;
          exports2.postMapLoadEvent = postMapLoadEvent;
          exports2.postTurnstileEvent = postTurnstileEvent;
          exports2.potpack = potpack;
          exports2.refProperties = refProperties;
          exports2.register = register;
          exports2.registerForPluginStateChange = registerForPluginStateChange;
          exports2.renderColorRamp = renderColorRamp;
          exports2.rotate = rotate;
          exports2.rotateX = rotateX;
          exports2.rotateZ = rotateZ;
          exports2.scale = scale;
          exports2.scale$1 = scale$2;
          exports2.scale$2 = scale$1;
          exports2.setCacheLimits = setCacheLimits;
          exports2.setRTLTextPlugin = setRTLTextPlugin;
          exports2.sphericalToCartesian = sphericalToCartesian;
          exports2.sqrLen = sqrLen;
          exports2.styleSpec = spec;
          exports2.sub = sub;
          exports2.symbolSize = symbolSize;
          exports2.transformMat3 = transformMat3;
          exports2.transformMat4 = transformMat4;
          exports2.translate = translate$1;
          exports2.triggerPluginCompletionEvent = triggerPluginCompletionEvent;
          exports2.uniqueId = uniqueId;
          exports2.validateCustomStyleLayer = validateCustomStyleLayer;
          exports2.validateLight = validateLight$1;
          exports2.validateStyle = validateStyle;
          exports2.values = values;
          exports2.vectorTile = vectorTile;
          exports2.version = version;
          exports2.warnOnce = warnOnce;
          exports2.webpSupported = exported$1;
          exports2.window = window$1;
          exports2.wrap = wrap;
        });
        define2(["./shared"], function(performance2) {
          "use strict";
          function stringify(obj) {
            var type = typeof obj;
            if (type === "number" || type === "boolean" || type === "string" || obj === void 0 || obj === null) {
              return JSON.stringify(obj);
            }
            if (Array.isArray(obj)) {
              var str$1 = "[";
              for (var i$1 = 0, list = obj; i$1 < list.length; i$1 += 1) {
                var val = list[i$1];
                str$1 += stringify(val) + ",";
              }
              return str$1 + "]";
            }
            var keys = Object.keys(obj).sort();
            var str = "{";
            for (var i = 0; i < keys.length; i++) {
              str += JSON.stringify(keys[i]) + ":" + stringify(obj[keys[i]]) + ",";
            }
            return str + "}";
          }
          function getKey(layer) {
            var key = "";
            for (var i = 0, list = performance2.refProperties; i < list.length; i += 1) {
              var k = list[i];
              key += "/" + stringify(layer[k]);
            }
            return key;
          }
          function groupByLayout(layers, cachedKeys) {
            var groups = {};
            for (var i = 0; i < layers.length; i++) {
              var k = cachedKeys && cachedKeys[layers[i].id] || getKey(layers[i]);
              if (cachedKeys) {
                cachedKeys[layers[i].id] = k;
              }
              var group = groups[k];
              if (!group) {
                group = groups[k] = [];
              }
              group.push(layers[i]);
            }
            var result = [];
            for (var k$1 in groups) {
              result.push(groups[k$1]);
            }
            return result;
          }
          var StyleLayerIndex = function StyleLayerIndex2(layerConfigs) {
            this.keyCache = {};
            if (layerConfigs) {
              this.replace(layerConfigs);
            }
          };
          StyleLayerIndex.prototype.replace = function replace(layerConfigs) {
            this._layerConfigs = {};
            this._layers = {};
            this.update(layerConfigs, []);
          };
          StyleLayerIndex.prototype.update = function update(layerConfigs, removedIds) {
            var this$1 = this;
            for (var i = 0, list = layerConfigs; i < list.length; i += 1) {
              var layerConfig = list[i];
              this._layerConfigs[layerConfig.id] = layerConfig;
              var layer = this._layers[layerConfig.id] = performance2.createStyleLayer(layerConfig);
              layer._featureFilter = performance2.featureFilter(layer.filter);
              if (this.keyCache[layerConfig.id]) {
                delete this.keyCache[layerConfig.id];
              }
            }
            for (var i$1 = 0, list$1 = removedIds; i$1 < list$1.length; i$1 += 1) {
              var id = list$1[i$1];
              delete this.keyCache[id];
              delete this._layerConfigs[id];
              delete this._layers[id];
            }
            this.familiesBySource = {};
            var groups = groupByLayout(performance2.values(this._layerConfigs), this.keyCache);
            for (var i$2 = 0, list$2 = groups; i$2 < list$2.length; i$2 += 1) {
              var layerConfigs$1 = list$2[i$2];
              var layers = layerConfigs$1.map(function(layerConfig2) {
                return this$1._layers[layerConfig2.id];
              });
              var layer$1 = layers[0];
              if (layer$1.visibility === "none") {
                continue;
              }
              var sourceId = layer$1.source || "";
              var sourceGroup = this.familiesBySource[sourceId];
              if (!sourceGroup) {
                sourceGroup = this.familiesBySource[sourceId] = {};
              }
              var sourceLayerId = layer$1.sourceLayer || "_geojsonTileLayer";
              var sourceLayerFamilies = sourceGroup[sourceLayerId];
              if (!sourceLayerFamilies) {
                sourceLayerFamilies = sourceGroup[sourceLayerId] = [];
              }
              sourceLayerFamilies.push(layers);
            }
          };
          var padding = 1;
          var GlyphAtlas = function GlyphAtlas2(stacks) {
            var positions = {};
            var bins = [];
            for (var stack in stacks) {
              var glyphs = stacks[stack];
              var stackPositions = positions[stack] = {};
              for (var id in glyphs) {
                var src = glyphs[+id];
                if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) {
                  continue;
                }
                var bin = {
                  x: 0,
                  y: 0,
                  w: src.bitmap.width + 2 * padding,
                  h: src.bitmap.height + 2 * padding
                };
                bins.push(bin);
                stackPositions[id] = {
                  rect: bin,
                  metrics: src.metrics
                };
              }
            }
            var ref = performance2.potpack(bins);
            var w = ref.w;
            var h = ref.h;
            var image = new performance2.AlphaImage({
              width: w || 1,
              height: h || 1
            });
            for (var stack$1 in stacks) {
              var glyphs$1 = stacks[stack$1];
              for (var id$1 in glyphs$1) {
                var src$1 = glyphs$1[+id$1];
                if (!src$1 || src$1.bitmap.width === 0 || src$1.bitmap.height === 0) {
                  continue;
                }
                var bin$1 = positions[stack$1][id$1].rect;
                performance2.AlphaImage.copy(src$1.bitmap, image, {
                  x: 0,
                  y: 0
                }, {
                  x: bin$1.x + padding,
                  y: bin$1.y + padding
                }, src$1.bitmap);
              }
            }
            this.image = image;
            this.positions = positions;
          };
          performance2.register("GlyphAtlas", GlyphAtlas);
          var WorkerTile = function WorkerTile2(params) {
            this.tileID = new performance2.OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);
            this.uid = params.uid;
            this.zoom = params.zoom;
            this.pixelRatio = params.pixelRatio;
            this.tileSize = params.tileSize;
            this.source = params.source;
            this.overscaling = this.tileID.overscaleFactor();
            this.showCollisionBoxes = params.showCollisionBoxes;
            this.collectResourceTiming = !!params.collectResourceTiming;
            this.returnDependencies = !!params.returnDependencies;
            this.promoteId = params.promoteId;
          };
          WorkerTile.prototype.parse = function parse2(data, layerIndex, availableImages, actor, callback) {
            var this$1 = this;
            this.status = "parsing";
            this.data = data;
            this.collisionBoxArray = new performance2.CollisionBoxArray();
            var sourceLayerCoder = new performance2.DictionaryCoder(Object.keys(data.layers).sort());
            var featureIndex = new performance2.FeatureIndex(this.tileID, this.promoteId);
            featureIndex.bucketLayerIDs = [];
            var buckets = {};
            var options = {
              featureIndex,
              iconDependencies: {},
              patternDependencies: {},
              glyphDependencies: {},
              availableImages
            };
            var layerFamilies = layerIndex.familiesBySource[this.source];
            for (var sourceLayerId in layerFamilies) {
              var sourceLayer = data.layers[sourceLayerId];
              if (!sourceLayer) {
                continue;
              }
              if (sourceLayer.version === 1) {
                performance2.warnOnce('Vector tile source "' + this.source + '" layer "' + sourceLayerId + '" does not use vector tile spec v2 and therefore may have some rendering errors.');
              }
              var sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId);
              var features = [];
              for (var index = 0; index < sourceLayer.length; index++) {
                var feature = sourceLayer.feature(index);
                var id = featureIndex.getId(feature, sourceLayerId);
                features.push({
                  feature,
                  id,
                  index,
                  sourceLayerIndex
                });
              }
              for (var i = 0, list = layerFamilies[sourceLayerId]; i < list.length; i += 1) {
                var family = list[i];
                var layer = family[0];
                if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) {
                  continue;
                }
                if (layer.maxzoom && this.zoom >= layer.maxzoom) {
                  continue;
                }
                if (layer.visibility === "none") {
                  continue;
                }
                recalculateLayers(family, this.zoom, availableImages);
                var bucket = buckets[layer.id] = layer.createBucket({
                  index: featureIndex.bucketLayerIDs.length,
                  layers: family,
                  zoom: this.zoom,
                  pixelRatio: this.pixelRatio,
                  overscaling: this.overscaling,
                  collisionBoxArray: this.collisionBoxArray,
                  sourceLayerIndex,
                  sourceID: this.source
                });
                bucket.populate(features, options, this.tileID.canonical);
                featureIndex.bucketLayerIDs.push(family.map(function(l) {
                  return l.id;
                }));
              }
            }
            var error;
            var glyphMap;
            var iconMap;
            var patternMap;
            var stacks = performance2.mapObject(options.glyphDependencies, function(glyphs) {
              return Object.keys(glyphs).map(Number);
            });
            if (Object.keys(stacks).length) {
              actor.send("getGlyphs", {
                uid: this.uid,
                stacks
              }, function(err, result) {
                if (!error) {
                  error = err;
                  glyphMap = result;
                  maybePrepare.call(this$1);
                }
              });
            } else {
              glyphMap = {};
            }
            var icons = Object.keys(options.iconDependencies);
            if (icons.length) {
              actor.send("getImages", {
                icons,
                source: this.source,
                tileID: this.tileID,
                type: "icons"
              }, function(err, result) {
                if (!error) {
                  error = err;
                  iconMap = result;
                  maybePrepare.call(this$1);
                }
              });
            } else {
              iconMap = {};
            }
            var patterns = Object.keys(options.patternDependencies);
            if (patterns.length) {
              actor.send("getImages", {
                icons: patterns,
                source: this.source,
                tileID: this.tileID,
                type: "patterns"
              }, function(err, result) {
                if (!error) {
                  error = err;
                  patternMap = result;
                  maybePrepare.call(this$1);
                }
              });
            } else {
              patternMap = {};
            }
            maybePrepare.call(this);
            function maybePrepare() {
              if (error) {
                return callback(error);
              } else if (glyphMap && iconMap && patternMap) {
                var glyphAtlas = new GlyphAtlas(glyphMap);
                var imageAtlas = new performance2.ImageAtlas(iconMap, patternMap);
                for (var key in buckets) {
                  var bucket2 = buckets[key];
                  if (bucket2 instanceof performance2.SymbolBucket) {
                    recalculateLayers(bucket2.layers, this.zoom, availableImages);
                    performance2.performSymbolLayout(bucket2, glyphMap, glyphAtlas.positions, iconMap, imageAtlas.iconPositions, this.showCollisionBoxes, this.tileID.canonical);
                  } else if (bucket2.hasPattern && (bucket2 instanceof performance2.LineBucket || bucket2 instanceof performance2.FillBucket || bucket2 instanceof performance2.FillExtrusionBucket)) {
                    recalculateLayers(bucket2.layers, this.zoom, availableImages);
                    bucket2.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions);
                  }
                }
                this.status = "done";
                callback(null, {
                  buckets: performance2.values(buckets).filter(function(b) {
                    return !b.isEmpty();
                  }),
                  featureIndex,
                  collisionBoxArray: this.collisionBoxArray,
                  glyphAtlasImage: glyphAtlas.image,
                  imageAtlas,
                  glyphMap: this.returnDependencies ? glyphMap : null,
                  iconMap: this.returnDependencies ? iconMap : null,
                  glyphPositions: this.returnDependencies ? glyphAtlas.positions : null
                });
              }
            }
          };
          function recalculateLayers(layers, zoom, availableImages) {
            var parameters = new performance2.EvaluationParameters(zoom);
            for (var i = 0, list = layers; i < list.length; i += 1) {
              var layer = list[i];
              layer.recalculate(parameters, availableImages);
            }
          }
          function loadVectorTile(params, callback) {
            var request = performance2.getArrayBuffer(params.request, function(err, data, cacheControl, expires) {
              if (err) {
                callback(err);
              } else if (data) {
                callback(null, {
                  vectorTile: new performance2.vectorTile.VectorTile(new performance2.pbf(data)),
                  rawData: data,
                  cacheControl,
                  expires
                });
              }
            });
            return function() {
              request.cancel();
              callback();
            };
          }
          var VectorTileWorkerSource = function VectorTileWorkerSource2(actor, layerIndex, availableImages, loadVectorData) {
            this.actor = actor;
            this.layerIndex = layerIndex;
            this.availableImages = availableImages;
            this.loadVectorData = loadVectorData || loadVectorTile;
            this.loading = {};
            this.loaded = {};
          };
          VectorTileWorkerSource.prototype.loadTile = function loadTile(params, callback) {
            var this$1 = this;
            var uid = params.uid;
            if (!this.loading) {
              this.loading = {};
            }
            var perf = params && params.request && params.request.collectResourceTiming ? new performance2.RequestPerformance(params.request) : false;
            var workerTile = this.loading[uid] = new WorkerTile(params);
            workerTile.abort = this.loadVectorData(params, function(err, response) {
              delete this$1.loading[uid];
              if (err || !response) {
                workerTile.status = "done";
                this$1.loaded[uid] = workerTile;
                return callback(err);
              }
              var rawTileData = response.rawData;
              var cacheControl = {};
              if (response.expires) {
                cacheControl.expires = response.expires;
              }
              if (response.cacheControl) {
                cacheControl.cacheControl = response.cacheControl;
              }
              var resourceTiming = {};
              if (perf) {
                var resourceTimingData = perf.finish();
                if (resourceTimingData) {
                  resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData));
                }
              }
              workerTile.vectorTile = response.vectorTile;
              workerTile.parse(response.vectorTile, this$1.layerIndex, this$1.availableImages, this$1.actor, function(err2, result) {
                if (err2 || !result) {
                  return callback(err2);
                }
                callback(null, performance2.extend({ rawTileData: rawTileData.slice(0) }, result, cacheControl, resourceTiming));
              });
              this$1.loaded = this$1.loaded || {};
              this$1.loaded[uid] = workerTile;
            });
          };
          VectorTileWorkerSource.prototype.reloadTile = function reloadTile(params, callback) {
            var this$1 = this;
            var loaded = this.loaded, uid = params.uid, vtSource = this;
            if (loaded && loaded[uid]) {
              var workerTile = loaded[uid];
              workerTile.showCollisionBoxes = params.showCollisionBoxes;
              var done = function(err, data) {
                var reloadCallback = workerTile.reloadCallback;
                if (reloadCallback) {
                  delete workerTile.reloadCallback;
                  workerTile.parse(workerTile.vectorTile, vtSource.layerIndex, this$1.availableImages, vtSource.actor, reloadCallback);
                }
                callback(err, data);
              };
              if (workerTile.status === "parsing") {
                workerTile.reloadCallback = done;
              } else if (workerTile.status === "done") {
                if (workerTile.vectorTile) {
                  workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, done);
                } else {
                  done();
                }
              }
            }
          };
          VectorTileWorkerSource.prototype.abortTile = function abortTile(params, callback) {
            var loading = this.loading, uid = params.uid;
            if (loading && loading[uid] && loading[uid].abort) {
              loading[uid].abort();
              delete loading[uid];
            }
            callback();
          };
          VectorTileWorkerSource.prototype.removeTile = function removeTile(params, callback) {
            var loaded = this.loaded, uid = params.uid;
            if (loaded && loaded[uid]) {
              delete loaded[uid];
            }
            callback();
          };
          var ImageBitmap2 = performance2.window.ImageBitmap;
          var RasterDEMTileWorkerSource = function RasterDEMTileWorkerSource2() {
            this.loaded = {};
          };
          RasterDEMTileWorkerSource.prototype.loadTile = function loadTile(params, callback) {
            var uid = params.uid;
            var encoding = params.encoding;
            var rawImageData = params.rawImageData;
            var imagePixels = ImageBitmap2 && rawImageData instanceof ImageBitmap2 ? this.getImageData(rawImageData) : rawImageData;
            var dem = new performance2.DEMData(uid, imagePixels, encoding);
            this.loaded = this.loaded || {};
            this.loaded[uid] = dem;
            callback(null, dem);
          };
          RasterDEMTileWorkerSource.prototype.getImageData = function getImageData(imgBitmap) {
            if (!this.offscreenCanvas || !this.offscreenCanvasContext) {
              this.offscreenCanvas = new OffscreenCanvas(imgBitmap.width, imgBitmap.height);
              this.offscreenCanvasContext = this.offscreenCanvas.getContext("2d");
            }
            this.offscreenCanvas.width = imgBitmap.width;
            this.offscreenCanvas.height = imgBitmap.height;
            this.offscreenCanvasContext.drawImage(imgBitmap, 0, 0, imgBitmap.width, imgBitmap.height);
            var imgData = this.offscreenCanvasContext.getImageData(-1, -1, imgBitmap.width + 2, imgBitmap.height + 2);
            this.offscreenCanvasContext.clearRect(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height);
            return new performance2.RGBAImage({
              width: imgData.width,
              height: imgData.height
            }, imgData.data);
          };
          RasterDEMTileWorkerSource.prototype.removeTile = function removeTile(params) {
            var loaded = this.loaded, uid = params.uid;
            if (loaded && loaded[uid]) {
              delete loaded[uid];
            }
          };
          var geojsonRewind = rewind;
          function rewind(gj, outer) {
            var type = gj && gj.type, i;
            if (type === "FeatureCollection") {
              for (i = 0; i < gj.features.length; i++) {
                rewind(gj.features[i], outer);
              }
            } else if (type === "GeometryCollection") {
              for (i = 0; i < gj.geometries.length; i++) {
                rewind(gj.geometries[i], outer);
              }
            } else if (type === "Feature") {
              rewind(gj.geometry, outer);
            } else if (type === "Polygon") {
              rewindRings(gj.coordinates, outer);
            } else if (type === "MultiPolygon") {
              for (i = 0; i < gj.coordinates.length; i++) {
                rewindRings(gj.coordinates[i], outer);
              }
            }
            return gj;
          }
          function rewindRings(rings, outer) {
            if (rings.length === 0) {
              return;
            }
            rewindRing(rings[0], outer);
            for (var i = 1; i < rings.length; i++) {
              rewindRing(rings[i], !outer);
            }
          }
          function rewindRing(ring, dir) {
            var area = 0;
            for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
              area += (ring[i][0] - ring[j][0]) * (ring[j][1] + ring[i][1]);
            }
            if (area >= 0 !== !!dir) {
              ring.reverse();
            }
          }
          var toGeoJSON = performance2.vectorTile.VectorTileFeature.prototype.toGeoJSON;
          var FeatureWrapper = function FeatureWrapper2(feature) {
            this._feature = feature;
            this.extent = performance2.EXTENT;
            this.type = feature.type;
            this.properties = feature.tags;
            if ("id" in feature && !isNaN(feature.id)) {
              this.id = parseInt(feature.id, 10);
            }
          };
          FeatureWrapper.prototype.loadGeometry = function loadGeometry() {
            if (this._feature.type === 1) {
              var geometry = [];
              for (var i = 0, list = this._feature.geometry; i < list.length; i += 1) {
                var point = list[i];
                geometry.push([new performance2.Point$1(point[0], point[1])]);
              }
              return geometry;
            } else {
              var geometry$1 = [];
              for (var i$2 = 0, list$2 = this._feature.geometry; i$2 < list$2.length; i$2 += 1) {
                var ring = list$2[i$2];
                var newRing = [];
                for (var i$1 = 0, list$1 = ring; i$1 < list$1.length; i$1 += 1) {
                  var point$1 = list$1[i$1];
                  newRing.push(new performance2.Point$1(point$1[0], point$1[1]));
                }
                geometry$1.push(newRing);
              }
              return geometry$1;
            }
          };
          FeatureWrapper.prototype.toGeoJSON = function toGeoJSON$1(x, y, z) {
            return toGeoJSON.call(this, x, y, z);
          };
          var GeoJSONWrapper = function GeoJSONWrapper2(features) {
            this.layers = { "_geojsonTileLayer": this };
            this.name = "_geojsonTileLayer";
            this.extent = performance2.EXTENT;
            this.length = features.length;
            this._features = features;
          };
          GeoJSONWrapper.prototype.feature = function feature(i) {
            return new FeatureWrapper(this._features[i]);
          };
          var VectorTileFeature = performance2.vectorTile.VectorTileFeature;
          var geojson_wrapper = GeoJSONWrapper$1;
          function GeoJSONWrapper$1(features, options) {
            this.options = options || {};
            this.features = features;
            this.length = features.length;
          }
          GeoJSONWrapper$1.prototype.feature = function(i) {
            return new FeatureWrapper$1(this.features[i], this.options.extent);
          };
          function FeatureWrapper$1(feature, extent) {
            this.id = typeof feature.id === "number" ? feature.id : void 0;
            this.type = feature.type;
            this.rawGeometry = feature.type === 1 ? [feature.geometry] : feature.geometry;
            this.properties = feature.tags;
            this.extent = extent || 4096;
          }
          FeatureWrapper$1.prototype.loadGeometry = function() {
            var rings = this.rawGeometry;
            this.geometry = [];
            for (var i = 0; i < rings.length; i++) {
              var ring = rings[i];
              var newRing = [];
              for (var j = 0; j < ring.length; j++) {
                newRing.push(new performance2.Point$1(ring[j][0], ring[j][1]));
              }
              this.geometry.push(newRing);
            }
            return this.geometry;
          };
          FeatureWrapper$1.prototype.bbox = function() {
            if (!this.geometry) {
              this.loadGeometry();
            }
            var rings = this.geometry;
            var x1 = Infinity;
            var x2 = -Infinity;
            var y1 = Infinity;
            var y2 = -Infinity;
            for (var i = 0; i < rings.length; i++) {
              var ring = rings[i];
              for (var j = 0; j < ring.length; j++) {
                var coord = ring[j];
                x1 = Math.min(x1, coord.x);
                x2 = Math.max(x2, coord.x);
                y1 = Math.min(y1, coord.y);
                y2 = Math.max(y2, coord.y);
              }
            }
            return [
              x1,
              y1,
              x2,
              y2
            ];
          };
          FeatureWrapper$1.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON;
          var vtPbf = fromVectorTileJs;
          var fromVectorTileJs_1 = fromVectorTileJs;
          var fromGeojsonVt_1 = fromGeojsonVt;
          var GeoJSONWrapper_1 = geojson_wrapper;
          function fromVectorTileJs(tile) {
            var out = new performance2.pbf();
            writeTile(tile, out);
            return out.finish();
          }
          function fromGeojsonVt(layers, options) {
            options = options || {};
            var l = {};
            for (var k in layers) {
              l[k] = new geojson_wrapper(layers[k].features, options);
              l[k].name = k;
              l[k].version = options.version;
              l[k].extent = options.extent;
            }
            return fromVectorTileJs({ layers: l });
          }
          function writeTile(tile, pbf) {
            for (var key in tile.layers) {
              pbf.writeMessage(3, writeLayer, tile.layers[key]);
            }
          }
          function writeLayer(layer, pbf) {
            pbf.writeVarintField(15, layer.version || 1);
            pbf.writeStringField(1, layer.name || "");
            pbf.writeVarintField(5, layer.extent || 4096);
            var i;
            var context = {
              keys: [],
              values: [],
              keycache: {},
              valuecache: {}
            };
            for (i = 0; i < layer.length; i++) {
              context.feature = layer.feature(i);
              pbf.writeMessage(2, writeFeature, context);
            }
            var keys = context.keys;
            for (i = 0; i < keys.length; i++) {
              pbf.writeStringField(3, keys[i]);
            }
            var values = context.values;
            for (i = 0; i < values.length; i++) {
              pbf.writeMessage(4, writeValue, values[i]);
            }
          }
          function writeFeature(context, pbf) {
            var feature = context.feature;
            if (feature.id !== void 0) {
              pbf.writeVarintField(1, feature.id);
            }
            pbf.writeMessage(2, writeProperties, context);
            pbf.writeVarintField(3, feature.type);
            pbf.writeMessage(4, writeGeometry, feature);
          }
          function writeProperties(context, pbf) {
            var feature = context.feature;
            var keys = context.keys;
            var values = context.values;
            var keycache = context.keycache;
            var valuecache = context.valuecache;
            for (var key in feature.properties) {
              var keyIndex = keycache[key];
              if (typeof keyIndex === "undefined") {
                keys.push(key);
                keyIndex = keys.length - 1;
                keycache[key] = keyIndex;
              }
              pbf.writeVarint(keyIndex);
              var value = feature.properties[key];
              var type = typeof value;
              if (type !== "string" && type !== "boolean" && type !== "number") {
                value = JSON.stringify(value);
              }
              var valueKey = type + ":" + value;
              var valueIndex = valuecache[valueKey];
              if (typeof valueIndex === "undefined") {
                values.push(value);
                valueIndex = values.length - 1;
                valuecache[valueKey] = valueIndex;
              }
              pbf.writeVarint(valueIndex);
            }
          }
          function command(cmd, length) {
            return (length << 3) + (cmd & 7);
          }
          function zigzag(num) {
            return num << 1 ^ num >> 31;
          }
          function writeGeometry(feature, pbf) {
            var geometry = feature.loadGeometry();
            var type = feature.type;
            var x = 0;
            var y = 0;
            var rings = geometry.length;
            for (var r = 0; r < rings; r++) {
              var ring = geometry[r];
              var count = 1;
              if (type === 1) {
                count = ring.length;
              }
              pbf.writeVarint(command(1, count));
              var lineCount = type === 3 ? ring.length - 1 : ring.length;
              for (var i = 0; i < lineCount; i++) {
                if (i === 1 && type !== 1) {
                  pbf.writeVarint(command(2, lineCount - 1));
                }
                var dx = ring[i].x - x;
                var dy = ring[i].y - y;
                pbf.writeVarint(zigzag(dx));
                pbf.writeVarint(zigzag(dy));
                x += dx;
                y += dy;
              }
              if (type === 3) {
                pbf.writeVarint(command(7, 1));
              }
            }
          }
          function writeValue(value, pbf) {
            var type = typeof value;
            if (type === "string") {
              pbf.writeStringField(1, value);
            } else if (type === "boolean") {
              pbf.writeBooleanField(7, value);
            } else if (type === "number") {
              if (value % 1 !== 0) {
                pbf.writeDoubleField(3, value);
              } else if (value < 0) {
                pbf.writeSVarintField(6, value);
              } else {
                pbf.writeVarintField(5, value);
              }
            }
          }
          vtPbf.fromVectorTileJs = fromVectorTileJs_1;
          vtPbf.fromGeojsonVt = fromGeojsonVt_1;
          vtPbf.GeoJSONWrapper = GeoJSONWrapper_1;
          function sortKD(ids, coords, nodeSize, left, right, depth) {
            if (right - left <= nodeSize) {
              return;
            }
            var m = left + right >> 1;
            select(ids, coords, m, left, right, depth % 2);
            sortKD(ids, coords, nodeSize, left, m - 1, depth + 1);
            sortKD(ids, coords, nodeSize, m + 1, right, depth + 1);
          }
          function select(ids, coords, k, left, right, inc) {
            while (right > left) {
              if (right - left > 600) {
                var n = right - left + 1;
                var m = k - left + 1;
                var z = Math.log(n);
                var s = 0.5 * Math.exp(2 * z / 3);
                var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
                var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
                var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
                select(ids, coords, k, newLeft, newRight, inc);
              }
              var t = coords[2 * k + inc];
              var i = left;
              var j = right;
              swapItem(ids, coords, left, k);
              if (coords[2 * right + inc] > t) {
                swapItem(ids, coords, left, right);
              }
              while (i < j) {
                swapItem(ids, coords, i, j);
                i++;
                j--;
                while (coords[2 * i + inc] < t) {
                  i++;
                }
                while (coords[2 * j + inc] > t) {
                  j--;
                }
              }
              if (coords[2 * left + inc] === t) {
                swapItem(ids, coords, left, j);
              } else {
                j++;
                swapItem(ids, coords, j, right);
              }
              if (j <= k) {
                left = j + 1;
              }
              if (k <= j) {
                right = j - 1;
              }
            }
          }
          function swapItem(ids, coords, i, j) {
            swap(ids, i, j);
            swap(coords, 2 * i, 2 * j);
            swap(coords, 2 * i + 1, 2 * j + 1);
          }
          function swap(arr, i, j) {
            var tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
          }
          function range(ids, coords, minX, minY, maxX, maxY, nodeSize) {
            var stack = [
              0,
              ids.length - 1,
              0
            ];
            var result = [];
            var x, y;
            while (stack.length) {
              var axis = stack.pop();
              var right = stack.pop();
              var left = stack.pop();
              if (right - left <= nodeSize) {
                for (var i = left; i <= right; i++) {
                  x = coords[2 * i];
                  y = coords[2 * i + 1];
                  if (x >= minX && x <= maxX && y >= minY && y <= maxY) {
                    result.push(ids[i]);
                  }
                }
                continue;
              }
              var m = Math.floor((left + right) / 2);
              x = coords[2 * m];
              y = coords[2 * m + 1];
              if (x >= minX && x <= maxX && y >= minY && y <= maxY) {
                result.push(ids[m]);
              }
              var nextAxis = (axis + 1) % 2;
              if (axis === 0 ? minX <= x : minY <= y) {
                stack.push(left);
                stack.push(m - 1);
                stack.push(nextAxis);
              }
              if (axis === 0 ? maxX >= x : maxY >= y) {
                stack.push(m + 1);
                stack.push(right);
                stack.push(nextAxis);
              }
            }
            return result;
          }
          function within(ids, coords, qx, qy, r, nodeSize) {
            var stack = [
              0,
              ids.length - 1,
              0
            ];
            var result = [];
            var r2 = r * r;
            while (stack.length) {
              var axis = stack.pop();
              var right = stack.pop();
              var left = stack.pop();
              if (right - left <= nodeSize) {
                for (var i = left; i <= right; i++) {
                  if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) {
                    result.push(ids[i]);
                  }
                }
                continue;
              }
              var m = Math.floor((left + right) / 2);
              var x = coords[2 * m];
              var y = coords[2 * m + 1];
              if (sqDist(x, y, qx, qy) <= r2) {
                result.push(ids[m]);
              }
              var nextAxis = (axis + 1) % 2;
              if (axis === 0 ? qx - r <= x : qy - r <= y) {
                stack.push(left);
                stack.push(m - 1);
                stack.push(nextAxis);
              }
              if (axis === 0 ? qx + r >= x : qy + r >= y) {
                stack.push(m + 1);
                stack.push(right);
                stack.push(nextAxis);
              }
            }
            return result;
          }
          function sqDist(ax, ay, bx, by) {
            var dx = ax - bx;
            var dy = ay - by;
            return dx * dx + dy * dy;
          }
          var defaultGetX = function(p) {
            return p[0];
          };
          var defaultGetY = function(p) {
            return p[1];
          };
          var KDBush = function KDBush2(points, getX2, getY2, nodeSize, ArrayType) {
            if (getX2 === void 0)
              getX2 = defaultGetX;
            if (getY2 === void 0)
              getY2 = defaultGetY;
            if (nodeSize === void 0)
              nodeSize = 64;
            if (ArrayType === void 0)
              ArrayType = Float64Array;
            this.nodeSize = nodeSize;
            this.points = points;
            var IndexArrayType = points.length < 65536 ? Uint16Array : Uint32Array;
            var ids = this.ids = new IndexArrayType(points.length);
            var coords = this.coords = new ArrayType(points.length * 2);
            for (var i = 0; i < points.length; i++) {
              ids[i] = i;
              coords[2 * i] = getX2(points[i]);
              coords[2 * i + 1] = getY2(points[i]);
            }
            sortKD(ids, coords, nodeSize, 0, ids.length - 1, 0);
          };
          KDBush.prototype.range = function range$1(minX, minY, maxX, maxY) {
            return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize);
          };
          KDBush.prototype.within = function within$1(x, y, r) {
            return within(this.ids, this.coords, x, y, r, this.nodeSize);
          };
          var defaultOptions = {
            minZoom: 0,
            maxZoom: 16,
            minPoints: 2,
            radius: 40,
            extent: 512,
            nodeSize: 64,
            log: false,
            generateId: false,
            reduce: null,
            map: function(props) {
              return props;
            }
          };
          var Supercluster = function Supercluster2(options) {
            this.options = extend2(Object.create(defaultOptions), options);
            this.trees = new Array(this.options.maxZoom + 1);
          };
          Supercluster.prototype.load = function load(points) {
            var ref = this.options;
            var log = ref.log;
            var minZoom = ref.minZoom;
            var maxZoom = ref.maxZoom;
            var nodeSize = ref.nodeSize;
            if (log) {
              console.time("total time");
            }
            var timerId = "prepare " + points.length + " points";
            if (log) {
              console.time(timerId);
            }
            this.points = points;
            var clusters = [];
            for (var i = 0; i < points.length; i++) {
              if (!points[i].geometry) {
                continue;
              }
              clusters.push(createPointCluster(points[i], i));
            }
            this.trees[maxZoom + 1] = new KDBush(clusters, getX, getY, nodeSize, Float32Array);
            if (log) {
              console.timeEnd(timerId);
            }
            for (var z = maxZoom; z >= minZoom; z--) {
              var now = +Date.now();
              clusters = this._cluster(clusters, z);
              this.trees[z] = new KDBush(clusters, getX, getY, nodeSize, Float32Array);
              if (log) {
                console.log("z%d: %d clusters in %dms", z, clusters.length, +Date.now() - now);
              }
            }
            if (log) {
              console.timeEnd("total time");
            }
            return this;
          };
          Supercluster.prototype.getClusters = function getClusters(bbox, zoom) {
            var minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;
            var minLat = Math.max(-90, Math.min(90, bbox[1]));
            var maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;
            var maxLat = Math.max(-90, Math.min(90, bbox[3]));
            if (bbox[2] - bbox[0] >= 360) {
              minLng = -180;
              maxLng = 180;
            } else if (minLng > maxLng) {
              var easternHem = this.getClusters([
                minLng,
                minLat,
                180,
                maxLat
              ], zoom);
              var westernHem = this.getClusters([
                -180,
                minLat,
                maxLng,
                maxLat
              ], zoom);
              return easternHem.concat(westernHem);
            }
            var tree = this.trees[this._limitZoom(zoom)];
            var ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat));
            var clusters = [];
            for (var i = 0, list = ids; i < list.length; i += 1) {
              var id = list[i];
              var c = tree.points[id];
              clusters.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]);
            }
            return clusters;
          };
          Supercluster.prototype.getChildren = function getChildren(clusterId) {
            var originId = this._getOriginId(clusterId);
            var originZoom = this._getOriginZoom(clusterId);
            var errorMsg = "No cluster with the specified id.";
            var index = this.trees[originZoom];
            if (!index) {
              throw new Error(errorMsg);
            }
            var origin = index.points[originId];
            if (!origin) {
              throw new Error(errorMsg);
            }
            var r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));
            var ids = index.within(origin.x, origin.y, r);
            var children = [];
            for (var i = 0, list = ids; i < list.length; i += 1) {
              var id = list[i];
              var c = index.points[id];
              if (c.parentId === clusterId) {
                children.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]);
              }
            }
            if (children.length === 0) {
              throw new Error(errorMsg);
            }
            return children;
          };
          Supercluster.prototype.getLeaves = function getLeaves(clusterId, limit, offset) {
            limit = limit || 10;
            offset = offset || 0;
            var leaves = [];
            this._appendLeaves(leaves, clusterId, limit, offset, 0);
            return leaves;
          };
          Supercluster.prototype.getTile = function getTile(z, x, y) {
            var tree = this.trees[this._limitZoom(z)];
            var z2 = Math.pow(2, z);
            var ref = this.options;
            var extent = ref.extent;
            var radius = ref.radius;
            var p = radius / extent;
            var top = (y - p) / z2;
            var bottom = (y + 1 + p) / z2;
            var tile = { features: [] };
            this._addTileFeatures(tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), tree.points, x, y, z2, tile);
            if (x === 0) {
              this._addTileFeatures(tree.range(1 - p / z2, top, 1, bottom), tree.points, z2, y, z2, tile);
            }
            if (x === z2 - 1) {
              this._addTileFeatures(tree.range(0, top, p / z2, bottom), tree.points, -1, y, z2, tile);
            }
            return tile.features.length ? tile : null;
          };
          Supercluster.prototype.getClusterExpansionZoom = function getClusterExpansionZoom(clusterId) {
            var expansionZoom = this._getOriginZoom(clusterId) - 1;
            while (expansionZoom <= this.options.maxZoom) {
              var children = this.getChildren(clusterId);
              expansionZoom++;
              if (children.length !== 1) {
                break;
              }
              clusterId = children[0].properties.cluster_id;
            }
            return expansionZoom;
          };
          Supercluster.prototype._appendLeaves = function _appendLeaves(result, clusterId, limit, offset, skipped) {
            var children = this.getChildren(clusterId);
            for (var i = 0, list = children; i < list.length; i += 1) {
              var child = list[i];
              var props = child.properties;
              if (props && props.cluster) {
                if (skipped + props.point_count <= offset) {
                  skipped += props.point_count;
                } else {
                  skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped);
                }
              } else if (skipped < offset) {
                skipped++;
              } else {
                result.push(child);
              }
              if (result.length === limit) {
                break;
              }
            }
            return skipped;
          };
          Supercluster.prototype._addTileFeatures = function _addTileFeatures(ids, points, x, y, z2, tile) {
            for (var i$1 = 0, list = ids; i$1 < list.length; i$1 += 1) {
              var i = list[i$1];
              var c = points[i];
              var isCluster = c.numPoints;
              var f = {
                type: 1,
                geometry: [[
                  Math.round(this.options.extent * (c.x * z2 - x)),
                  Math.round(this.options.extent * (c.y * z2 - y))
                ]],
                tags: isCluster ? getClusterProperties(c) : this.points[c.index].properties
              };
              var id = void 0;
              if (isCluster) {
                id = c.id;
              } else if (this.options.generateId) {
                id = c.index;
              } else if (this.points[c.index].id) {
                id = this.points[c.index].id;
              }
              if (id !== void 0) {
                f.id = id;
              }
              tile.features.push(f);
            }
          };
          Supercluster.prototype._limitZoom = function _limitZoom(z) {
            return Math.max(this.options.minZoom, Math.min(+z, this.options.maxZoom + 1));
          };
          Supercluster.prototype._cluster = function _cluster(points, zoom) {
            var clusters = [];
            var ref = this.options;
            var radius = ref.radius;
            var extent = ref.extent;
            var reduce = ref.reduce;
            var minPoints = ref.minPoints;
            var r = radius / (extent * Math.pow(2, zoom));
            for (var i = 0; i < points.length; i++) {
              var p = points[i];
              if (p.zoom <= zoom) {
                continue;
              }
              p.zoom = zoom;
              var tree = this.trees[zoom + 1];
              var neighborIds = tree.within(p.x, p.y, r);
              var numPointsOrigin = p.numPoints || 1;
              var numPoints = numPointsOrigin;
              for (var i$1 = 0, list = neighborIds; i$1 < list.length; i$1 += 1) {
                var neighborId = list[i$1];
                var b = tree.points[neighborId];
                if (b.zoom > zoom) {
                  numPoints += b.numPoints || 1;
                }
              }
              if (numPoints >= minPoints) {
                var wx = p.x * numPointsOrigin;
                var wy = p.y * numPointsOrigin;
                var clusterProperties = reduce && numPointsOrigin > 1 ? this._map(p, true) : null;
                var id = (i << 5) + (zoom + 1) + this.points.length;
                for (var i$2 = 0, list$1 = neighborIds; i$2 < list$1.length; i$2 += 1) {
                  var neighborId$1 = list$1[i$2];
                  var b$1 = tree.points[neighborId$1];
                  if (b$1.zoom <= zoom) {
                    continue;
                  }
                  b$1.zoom = zoom;
                  var numPoints2 = b$1.numPoints || 1;
                  wx += b$1.x * numPoints2;
                  wy += b$1.y * numPoints2;
                  b$1.parentId = id;
                  if (reduce) {
                    if (!clusterProperties) {
                      clusterProperties = this._map(p, true);
                    }
                    reduce(clusterProperties, this._map(b$1));
                  }
                }
                p.parentId = id;
                clusters.push(createCluster(wx / numPoints, wy / numPoints, id, numPoints, clusterProperties));
              } else {
                clusters.push(p);
                if (numPoints > 1) {
                  for (var i$3 = 0, list$2 = neighborIds; i$3 < list$2.length; i$3 += 1) {
                    var neighborId$2 = list$2[i$3];
                    var b$2 = tree.points[neighborId$2];
                    if (b$2.zoom <= zoom) {
                      continue;
                    }
                    b$2.zoom = zoom;
                    clusters.push(b$2);
                  }
                }
              }
            }
            return clusters;
          };
          Supercluster.prototype._getOriginId = function _getOriginId(clusterId) {
            return clusterId - this.points.length >> 5;
          };
          Supercluster.prototype._getOriginZoom = function _getOriginZoom(clusterId) {
            return (clusterId - this.points.length) % 32;
          };
          Supercluster.prototype._map = function _map(point, clone) {
            if (point.numPoints) {
              return clone ? extend2({}, point.properties) : point.properties;
            }
            var original = this.points[point.index].properties;
            var result = this.options.map(original);
            return clone && result === original ? extend2({}, result) : result;
          };
          function createCluster(x, y, id, numPoints, properties) {
            return {
              x,
              y,
              zoom: Infinity,
              id,
              parentId: -1,
              numPoints,
              properties
            };
          }
          function createPointCluster(p, id) {
            var ref = p.geometry.coordinates;
            var x = ref[0];
            var y = ref[1];
            return {
              x: lngX(x),
              y: latY(y),
              zoom: Infinity,
              index: id,
              parentId: -1
            };
          }
          function getClusterJSON(cluster) {
            return {
              type: "Feature",
              id: cluster.id,
              properties: getClusterProperties(cluster),
              geometry: {
                type: "Point",
                coordinates: [
                  xLng(cluster.x),
                  yLat(cluster.y)
                ]
              }
            };
          }
          function getClusterProperties(cluster) {
            var count = cluster.numPoints;
            var abbrev = count >= 1e4 ? Math.round(count / 1e3) + "k" : count >= 1e3 ? Math.round(count / 100) / 10 + "k" : count;
            return extend2(extend2({}, cluster.properties), {
              cluster: true,
              cluster_id: cluster.id,
              point_count: count,
              point_count_abbreviated: abbrev
            });
          }
          function lngX(lng) {
            return lng / 360 + 0.5;
          }
          function latY(lat) {
            var sin = Math.sin(lat * Math.PI / 180);
            var y = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
            return y < 0 ? 0 : y > 1 ? 1 : y;
          }
          function xLng(x) {
            return (x - 0.5) * 360;
          }
          function yLat(y) {
            var y2 = (180 - y * 360) * Math.PI / 180;
            return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;
          }
          function extend2(dest, src) {
            for (var id in src) {
              dest[id] = src[id];
            }
            return dest;
          }
          function getX(p) {
            return p.x;
          }
          function getY(p) {
            return p.y;
          }
          function simplify(coords, first, last, sqTolerance) {
            var maxSqDist = sqTolerance;
            var mid = last - first >> 1;
            var minPosToMid = last - first;
            var index;
            var ax = coords[first];
            var ay = coords[first + 1];
            var bx = coords[last];
            var by = coords[last + 1];
            for (var i = first + 3; i < last; i += 3) {
              var d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
              if (d > maxSqDist) {
                index = i;
                maxSqDist = d;
              } else if (d === maxSqDist) {
                var posToMid = Math.abs(i - mid);
                if (posToMid < minPosToMid) {
                  index = i;
                  minPosToMid = posToMid;
                }
              }
            }
            if (maxSqDist > sqTolerance) {
              if (index - first > 3) {
                simplify(coords, first, index, sqTolerance);
              }
              coords[index + 2] = maxSqDist;
              if (last - index > 3) {
                simplify(coords, index, last, sqTolerance);
              }
            }
          }
          function getSqSegDist(px, py, x, y, bx, by) {
            var dx = bx - x;
            var dy = by - y;
            if (dx !== 0 || dy !== 0) {
              var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
              if (t > 1) {
                x = bx;
                y = by;
              } else if (t > 0) {
                x += dx * t;
                y += dy * t;
              }
            }
            dx = px - x;
            dy = py - y;
            return dx * dx + dy * dy;
          }
          function createFeature(id, type, geom, tags) {
            var feature = {
              id: typeof id === "undefined" ? null : id,
              type,
              geometry: geom,
              tags,
              minX: Infinity,
              minY: Infinity,
              maxX: -Infinity,
              maxY: -Infinity
            };
            calcBBox(feature);
            return feature;
          }
          function calcBBox(feature) {
            var geom = feature.geometry;
            var type = feature.type;
            if (type === "Point" || type === "MultiPoint" || type === "LineString") {
              calcLineBBox(feature, geom);
            } else if (type === "Polygon" || type === "MultiLineString") {
              for (var i = 0; i < geom.length; i++) {
                calcLineBBox(feature, geom[i]);
              }
            } else if (type === "MultiPolygon") {
              for (i = 0; i < geom.length; i++) {
                for (var j = 0; j < geom[i].length; j++) {
                  calcLineBBox(feature, geom[i][j]);
                }
              }
            }
          }
          function calcLineBBox(feature, geom) {
            for (var i = 0; i < geom.length; i += 3) {
              feature.minX = Math.min(feature.minX, geom[i]);
              feature.minY = Math.min(feature.minY, geom[i + 1]);
              feature.maxX = Math.max(feature.maxX, geom[i]);
              feature.maxY = Math.max(feature.maxY, geom[i + 1]);
            }
          }
          function convert(data, options) {
            var features = [];
            if (data.type === "FeatureCollection") {
              for (var i = 0; i < data.features.length; i++) {
                convertFeature(features, data.features[i], options, i);
              }
            } else if (data.type === "Feature") {
              convertFeature(features, data, options);
            } else {
              convertFeature(features, { geometry: data }, options);
            }
            return features;
          }
          function convertFeature(features, geojson, options, index) {
            if (!geojson.geometry) {
              return;
            }
            var coords = geojson.geometry.coordinates;
            var type = geojson.geometry.type;
            var tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
            var geometry = [];
            var id = geojson.id;
            if (options.promoteId) {
              id = geojson.properties[options.promoteId];
            } else if (options.generateId) {
              id = index || 0;
            }
            if (type === "Point") {
              convertPoint(coords, geometry);
            } else if (type === "MultiPoint") {
              for (var i = 0; i < coords.length; i++) {
                convertPoint(coords[i], geometry);
              }
            } else if (type === "LineString") {
              convertLine(coords, geometry, tolerance, false);
            } else if (type === "MultiLineString") {
              if (options.lineMetrics) {
                for (i = 0; i < coords.length; i++) {
                  geometry = [];
                  convertLine(coords[i], geometry, tolerance, false);
                  features.push(createFeature(id, "LineString", geometry, geojson.properties));
                }
                return;
              } else {
                convertLines(coords, geometry, tolerance, false);
              }
            } else if (type === "Polygon") {
              convertLines(coords, geometry, tolerance, true);
            } else if (type === "MultiPolygon") {
              for (i = 0; i < coords.length; i++) {
                var polygon = [];
                convertLines(coords[i], polygon, tolerance, true);
                geometry.push(polygon);
              }
            } else if (type === "GeometryCollection") {
              for (i = 0; i < geojson.geometry.geometries.length; i++) {
                convertFeature(features, {
                  id,
                  geometry: geojson.geometry.geometries[i],
                  properties: geojson.properties
                }, options, index);
              }
              return;
            } else {
              throw new Error("Input data is not a valid GeoJSON object.");
            }
            features.push(createFeature(id, type, geometry, geojson.properties));
          }
          function convertPoint(coords, out) {
            out.push(projectX(coords[0]));
            out.push(projectY(coords[1]));
            out.push(0);
          }
          function convertLine(ring, out, tolerance, isPolygon) {
            var x0, y0;
            var size = 0;
            for (var j = 0; j < ring.length; j++) {
              var x = projectX(ring[j][0]);
              var y = projectY(ring[j][1]);
              out.push(x);
              out.push(y);
              out.push(0);
              if (j > 0) {
                if (isPolygon) {
                  size += (x0 * y - x * y0) / 2;
                } else {
                  size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2));
                }
              }
              x0 = x;
              y0 = y;
            }
            var last = out.length - 3;
            out[2] = 1;
            simplify(out, 0, last, tolerance);
            out[last + 2] = 1;
            out.size = Math.abs(size);
            out.start = 0;
            out.end = out.size;
          }
          function convertLines(rings, out, tolerance, isPolygon) {
            for (var i = 0; i < rings.length; i++) {
              var geom = [];
              convertLine(rings[i], geom, tolerance, isPolygon);
              out.push(geom);
            }
          }
          function projectX(x) {
            return x / 360 + 0.5;
          }
          function projectY(y) {
            var sin = Math.sin(y * Math.PI / 180);
            var y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
            return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;
          }
          function clip(features, scale, k1, k2, axis, minAll, maxAll, options) {
            k1 /= scale;
            k2 /= scale;
            if (minAll >= k1 && maxAll < k2) {
              return features;
            } else if (maxAll < k1 || minAll >= k2) {
              return null;
            }
            var clipped = [];
            for (var i = 0; i < features.length; i++) {
              var feature = features[i];
              var geometry = feature.geometry;
              var type = feature.type;
              var min = axis === 0 ? feature.minX : feature.minY;
              var max = axis === 0 ? feature.maxX : feature.maxY;
              if (min >= k1 && max < k2) {
                clipped.push(feature);
                continue;
              } else if (max < k1 || min >= k2) {
                continue;
              }
              var newGeometry = [];
              if (type === "Point" || type === "MultiPoint") {
                clipPoints(geometry, newGeometry, k1, k2, axis);
              } else if (type === "LineString") {
                clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics);
              } else if (type === "MultiLineString") {
                clipLines(geometry, newGeometry, k1, k2, axis, false);
              } else if (type === "Polygon") {
                clipLines(geometry, newGeometry, k1, k2, axis, true);
              } else if (type === "MultiPolygon") {
                for (var j = 0; j < geometry.length; j++) {
                  var polygon = [];
                  clipLines(geometry[j], polygon, k1, k2, axis, true);
                  if (polygon.length) {
                    newGeometry.push(polygon);
                  }
                }
              }
              if (newGeometry.length) {
                if (options.lineMetrics && type === "LineString") {
                  for (j = 0; j < newGeometry.length; j++) {
                    clipped.push(createFeature(feature.id, type, newGeometry[j], feature.tags));
                  }
                  continue;
                }
                if (type === "LineString" || type === "MultiLineString") {
                  if (newGeometry.length === 1) {
                    type = "LineString";
                    newGeometry = newGeometry[0];
                  } else {
                    type = "MultiLineString";
                  }
                }
                if (type === "Point" || type === "MultiPoint") {
                  type = newGeometry.length === 3 ? "Point" : "MultiPoint";
                }
                clipped.push(createFeature(feature.id, type, newGeometry, feature.tags));
              }
            }
            return clipped.length ? clipped : null;
          }
          function clipPoints(geom, newGeom, k1, k2, axis) {
            for (var i = 0; i < geom.length; i += 3) {
              var a = geom[i + axis];
              if (a >= k1 && a <= k2) {
                newGeom.push(geom[i]);
                newGeom.push(geom[i + 1]);
                newGeom.push(geom[i + 2]);
              }
            }
          }
          function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) {
            var slice = newSlice(geom);
            var intersect = axis === 0 ? intersectX : intersectY;
            var len = geom.start;
            var segLen, t;
            for (var i = 0; i < geom.length - 3; i += 3) {
              var ax = geom[i];
              var ay = geom[i + 1];
              var az = geom[i + 2];
              var bx = geom[i + 3];
              var by = geom[i + 4];
              var a = axis === 0 ? ax : ay;
              var b = axis === 0 ? bx : by;
              var exited = false;
              if (trackMetrics) {
                segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
              }
              if (a < k1) {
                if (b > k1) {
                  t = intersect(slice, ax, ay, bx, by, k1);
                  if (trackMetrics) {
                    slice.start = len + segLen * t;
                  }
                }
              } else if (a > k2) {
                if (b < k2) {
                  t = intersect(slice, ax, ay, bx, by, k2);
                  if (trackMetrics) {
                    slice.start = len + segLen * t;
                  }
                }
              } else {
                addPoint(slice, ax, ay, az);
              }
              if (b < k1 && a >= k1) {
                t = intersect(slice, ax, ay, bx, by, k1);
                exited = true;
              }
              if (b > k2 && a <= k2) {
                t = intersect(slice, ax, ay, bx, by, k2);
                exited = true;
              }
              if (!isPolygon && exited) {
                if (trackMetrics) {
                  slice.end = len + segLen * t;
                }
                newGeom.push(slice);
                slice = newSlice(geom);
              }
              if (trackMetrics) {
                len += segLen;
              }
            }
            var last = geom.length - 3;
            ax = geom[last];
            ay = geom[last + 1];
            az = geom[last + 2];
            a = axis === 0 ? ax : ay;
            if (a >= k1 && a <= k2) {
              addPoint(slice, ax, ay, az);
            }
            last = slice.length - 3;
            if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) {
              addPoint(slice, slice[0], slice[1], slice[2]);
            }
            if (slice.length) {
              newGeom.push(slice);
            }
          }
          function newSlice(line) {
            var slice = [];
            slice.size = line.size;
            slice.start = line.start;
            slice.end = line.end;
            return slice;
          }
          function clipLines(geom, newGeom, k1, k2, axis, isPolygon) {
            for (var i = 0; i < geom.length; i++) {
              clipLine(geom[i], newGeom, k1, k2, axis, isPolygon, false);
            }
          }
          function addPoint(out, x, y, z) {
            out.push(x);
            out.push(y);
            out.push(z);
          }
          function intersectX(out, ax, ay, bx, by, x) {
            var t = (x - ax) / (bx - ax);
            out.push(x);
            out.push(ay + (by - ay) * t);
            out.push(1);
            return t;
          }
          function intersectY(out, ax, ay, bx, by, y) {
            var t = (y - ay) / (by - ay);
            out.push(ax + (bx - ax) * t);
            out.push(y);
            out.push(1);
            return t;
          }
          function wrap(features, options) {
            var buffer = options.buffer / options.extent;
            var merged = features;
            var left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options);
            var right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options);
            if (left || right) {
              merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || [];
              if (left) {
                merged = shiftFeatureCoords(left, 1).concat(merged);
              }
              if (right) {
                merged = merged.concat(shiftFeatureCoords(right, -1));
              }
            }
            return merged;
          }
          function shiftFeatureCoords(features, offset) {
            var newFeatures = [];
            for (var i = 0; i < features.length; i++) {
              var feature = features[i], type = feature.type;
              var newGeometry;
              if (type === "Point" || type === "MultiPoint" || type === "LineString") {
                newGeometry = shiftCoords(feature.geometry, offset);
              } else if (type === "MultiLineString" || type === "Polygon") {
                newGeometry = [];
                for (var j = 0; j < feature.geometry.length; j++) {
                  newGeometry.push(shiftCoords(feature.geometry[j], offset));
                }
              } else if (type === "MultiPolygon") {
                newGeometry = [];
                for (j = 0; j < feature.geometry.length; j++) {
                  var newPolygon = [];
                  for (var k = 0; k < feature.geometry[j].length; k++) {
                    newPolygon.push(shiftCoords(feature.geometry[j][k], offset));
                  }
                  newGeometry.push(newPolygon);
                }
              }
              newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags));
            }
            return newFeatures;
          }
          function shiftCoords(points, offset) {
            var newPoints = [];
            newPoints.size = points.size;
            if (points.start !== void 0) {
              newPoints.start = points.start;
              newPoints.end = points.end;
            }
            for (var i = 0; i < points.length; i += 3) {
              newPoints.push(points[i] + offset, points[i + 1], points[i + 2]);
            }
            return newPoints;
          }
          function transformTile(tile, extent) {
            if (tile.transformed) {
              return tile;
            }
            var z2 = 1 << tile.z, tx = tile.x, ty = tile.y, i, j, k;
            for (i = 0; i < tile.features.length; i++) {
              var feature = tile.features[i], geom = feature.geometry, type = feature.type;
              feature.geometry = [];
              if (type === 1) {
                for (j = 0; j < geom.length; j += 2) {
                  feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));
                }
              } else {
                for (j = 0; j < geom.length; j++) {
                  var ring = [];
                  for (k = 0; k < geom[j].length; k += 2) {
                    ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty));
                  }
                  feature.geometry.push(ring);
                }
              }
            }
            tile.transformed = true;
            return tile;
          }
          function transformPoint(x, y, extent, z2, tx, ty) {
            return [
              Math.round(extent * (x * z2 - tx)),
              Math.round(extent * (y * z2 - ty))
            ];
          }
          function createTile(features, z, tx, ty, options) {
            var tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
            var tile = {
              features: [],
              numPoints: 0,
              numSimplified: 0,
              numFeatures: 0,
              source: null,
              x: tx,
              y: ty,
              z,
              transformed: false,
              minX: 2,
              minY: 1,
              maxX: -1,
              maxY: 0
            };
            for (var i = 0; i < features.length; i++) {
              tile.numFeatures++;
              addFeature(tile, features[i], tolerance, options);
              var minX = features[i].minX;
              var minY = features[i].minY;
              var maxX = features[i].maxX;
              var maxY = features[i].maxY;
              if (minX < tile.minX) {
                tile.minX = minX;
              }
              if (minY < tile.minY) {
                tile.minY = minY;
              }
              if (maxX > tile.maxX) {
                tile.maxX = maxX;
              }
              if (maxY > tile.maxY) {
                tile.maxY = maxY;
              }
            }
            return tile;
          }
          function addFeature(tile, feature, tolerance, options) {
            var geom = feature.geometry, type = feature.type, simplified = [];
            if (type === "Point" || type === "MultiPoint") {
              for (var i = 0; i < geom.length; i += 3) {
                simplified.push(geom[i]);
                simplified.push(geom[i + 1]);
                tile.numPoints++;
                tile.numSimplified++;
              }
            } else if (type === "LineString") {
              addLine(simplified, geom, tile, tolerance, false, false);
            } else if (type === "MultiLineString" || type === "Polygon") {
              for (i = 0; i < geom.length; i++) {
                addLine(simplified, geom[i], tile, tolerance, type === "Polygon", i === 0);
              }
            } else if (type === "MultiPolygon") {
              for (var k = 0; k < geom.length; k++) {
                var polygon = geom[k];
                for (i = 0; i < polygon.length; i++) {
                  addLine(simplified, polygon[i], tile, tolerance, true, i === 0);
                }
              }
            }
            if (simplified.length) {
              var tags = feature.tags || null;
              if (type === "LineString" && options.lineMetrics) {
                tags = {};
                for (var key in feature.tags) {
                  tags[key] = feature.tags[key];
                }
                tags["mapbox_clip_start"] = geom.start / geom.size;
                tags["mapbox_clip_end"] = geom.end / geom.size;
              }
              var tileFeature = {
                geometry: simplified,
                type: type === "Polygon" || type === "MultiPolygon" ? 3 : type === "LineString" || type === "MultiLineString" ? 2 : 1,
                tags
              };
              if (feature.id !== null) {
                tileFeature.id = feature.id;
              }
              tile.features.push(tileFeature);
            }
          }
          function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
            var sqTolerance = tolerance * tolerance;
            if (tolerance > 0 && geom.size < (isPolygon ? sqTolerance : tolerance)) {
              tile.numPoints += geom.length / 3;
              return;
            }
            var ring = [];
            for (var i = 0; i < geom.length; i += 3) {
              if (tolerance === 0 || geom[i + 2] > sqTolerance) {
                tile.numSimplified++;
                ring.push(geom[i]);
                ring.push(geom[i + 1]);
              }
              tile.numPoints++;
            }
            if (isPolygon) {
              rewind$1(ring, isOuter);
            }
            result.push(ring);
          }
          function rewind$1(ring, clockwise) {
            var area = 0;
            for (var i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {
              area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
            }
            if (area > 0 === clockwise) {
              for (i = 0, len = ring.length; i < len / 2; i += 2) {
                var x = ring[i];
                var y = ring[i + 1];
                ring[i] = ring[len - 2 - i];
                ring[i + 1] = ring[len - 1 - i];
                ring[len - 2 - i] = x;
                ring[len - 1 - i] = y;
              }
            }
          }
          function geojsonvt(data, options) {
            return new GeoJSONVT(data, options);
          }
          function GeoJSONVT(data, options) {
            options = this.options = extend$1(Object.create(this.options), options);
            var debug = options.debug;
            if (debug) {
              console.time("preprocess data");
            }
            if (options.maxZoom < 0 || options.maxZoom > 24) {
              throw new Error("maxZoom should be in the 0-24 range");
            }
            if (options.promoteId && options.generateId) {
              throw new Error("promoteId and generateId cannot be used together.");
            }
            var features = convert(data, options);
            this.tiles = {};
            this.tileCoords = [];
            if (debug) {
              console.timeEnd("preprocess data");
              console.log("index: maxZoom: %d, maxPoints: %d", options.indexMaxZoom, options.indexMaxPoints);
              console.time("generate tiles");
              this.stats = {};
              this.total = 0;
            }
            features = wrap(features, options);
            if (features.length) {
              this.splitTile(features, 0, 0, 0);
            }
            if (debug) {
              if (features.length) {
                console.log("features: %d, points: %d", this.tiles[0].numFeatures, this.tiles[0].numPoints);
              }
              console.timeEnd("generate tiles");
              console.log("tiles generated:", this.total, JSON.stringify(this.stats));
            }
          }
          GeoJSONVT.prototype.options = {
            maxZoom: 14,
            indexMaxZoom: 5,
            indexMaxPoints: 1e5,
            tolerance: 3,
            extent: 4096,
            buffer: 64,
            lineMetrics: false,
            promoteId: null,
            generateId: false,
            debug: 0
          };
          GeoJSONVT.prototype.splitTile = function(features, z, x, y, cz, cx, cy) {
            var stack = [
              features,
              z,
              x,
              y
            ], options = this.options, debug = options.debug;
            while (stack.length) {
              y = stack.pop();
              x = stack.pop();
              z = stack.pop();
              features = stack.pop();
              var z2 = 1 << z, id = toID(z, x, y), tile = this.tiles[id];
              if (!tile) {
                if (debug > 1) {
                  console.time("creation");
                }
                tile = this.tiles[id] = createTile(features, z, x, y, options);
                this.tileCoords.push({
                  z,
                  x,
                  y
                });
                if (debug) {
                  if (debug > 1) {
                    console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)", z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
                    console.timeEnd("creation");
                  }
                  var key = "z" + z;
                  this.stats[key] = (this.stats[key] || 0) + 1;
                  this.total++;
                }
              }
              tile.source = features;
              if (!cz) {
                if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) {
                  continue;
                }
              } else {
                if (z === options.maxZoom || z === cz) {
                  continue;
                }
                var m = 1 << cz - z;
                if (x !== Math.floor(cx / m) || y !== Math.floor(cy / m)) {
                  continue;
                }
              }
              tile.source = null;
              if (features.length === 0) {
                continue;
              }
              if (debug > 1) {
                console.time("clipping");
              }
              var k1 = 0.5 * options.buffer / options.extent, k2 = 0.5 - k1, k3 = 0.5 + k1, k4 = 1 + k1, tl, bl, tr, br, left, right;
              tl = bl = tr = br = null;
              left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);
              right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);
              features = null;
              if (left) {
                tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
                bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
                left = null;
              }
              if (right) {
                tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
                br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
                right = null;
              }
              if (debug > 1) {
                console.timeEnd("clipping");
              }
              stack.push(tl || [], z + 1, x * 2, y * 2);
              stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
              stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
              stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
            }
          };
          GeoJSONVT.prototype.getTile = function(z, x, y) {
            var options = this.options, extent = options.extent, debug = options.debug;
            if (z < 0 || z > 24) {
              return null;
            }
            var z2 = 1 << z;
            x = (x % z2 + z2) % z2;
            var id = toID(z, x, y);
            if (this.tiles[id]) {
              return transformTile(this.tiles[id], extent);
            }
            if (debug > 1) {
              console.log("drilling down to z%d-%d-%d", z, x, y);
            }
            var z0 = z, x0 = x, y0 = y, parent;
            while (!parent && z0 > 0) {
              z0--;
              x0 = Math.floor(x0 / 2);
              y0 = Math.floor(y0 / 2);
              parent = this.tiles[toID(z0, x0, y0)];
            }
            if (!parent || !parent.source) {
              return null;
            }
            if (debug > 1) {
              console.log("found parent tile z%d-%d-%d", z0, x0, y0);
            }
            if (debug > 1) {
              console.time("drilling down");
            }
            this.splitTile(parent.source, z0, x0, y0, z, x, y);
            if (debug > 1) {
              console.timeEnd("drilling down");
            }
            return this.tiles[id] ? transformTile(this.tiles[id], extent) : null;
          };
          function toID(z, x, y) {
            return ((1 << z) * y + x) * 32 + z;
          }
          function extend$1(dest, src) {
            for (var i in src) {
              dest[i] = src[i];
            }
            return dest;
          }
          function loadGeoJSONTile(params, callback) {
            var canonical = params.tileID.canonical;
            if (!this._geoJSONIndex) {
              return callback(null, null);
            }
            var geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y);
            if (!geoJSONTile) {
              return callback(null, null);
            }
            var geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features);
            var pbf = vtPbf(geojsonWrapper);
            if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {
              pbf = new Uint8Array(pbf);
            }
            callback(null, {
              vectorTile: geojsonWrapper,
              rawData: pbf.buffer
            });
          }
          var GeoJSONWorkerSource = function(VectorTileWorkerSource2) {
            function GeoJSONWorkerSource2(actor, layerIndex, availableImages, loadGeoJSON) {
              VectorTileWorkerSource2.call(this, actor, layerIndex, availableImages, loadGeoJSONTile);
              if (loadGeoJSON) {
                this.loadGeoJSON = loadGeoJSON;
              }
            }
            if (VectorTileWorkerSource2)
              GeoJSONWorkerSource2.__proto__ = VectorTileWorkerSource2;
            GeoJSONWorkerSource2.prototype = Object.create(VectorTileWorkerSource2 && VectorTileWorkerSource2.prototype);
            GeoJSONWorkerSource2.prototype.constructor = GeoJSONWorkerSource2;
            GeoJSONWorkerSource2.prototype.loadData = function loadData(params, callback) {
              if (this._pendingCallback) {
                this._pendingCallback(null, { abandoned: true });
              }
              this._pendingCallback = callback;
              this._pendingLoadDataParams = params;
              if (this._state && this._state !== "Idle") {
                this._state = "NeedsLoadData";
              } else {
                this._state = "Coalescing";
                this._loadData();
              }
            };
            GeoJSONWorkerSource2.prototype._loadData = function _loadData() {
              var this$1 = this;
              if (!this._pendingCallback || !this._pendingLoadDataParams) {
                return;
              }
              var callback = this._pendingCallback;
              var params = this._pendingLoadDataParams;
              delete this._pendingCallback;
              delete this._pendingLoadDataParams;
              var perf = params && params.request && params.request.collectResourceTiming ? new performance2.RequestPerformance(params.request) : false;
              this.loadGeoJSON(params, function(err, data) {
                if (err || !data) {
                  return callback(err);
                } else if (typeof data !== "object") {
                  return callback(new Error("Input data given to '" + params.source + "' is not a valid GeoJSON object."));
                } else {
                  geojsonRewind(data, true);
                  try {
                    if (params.filter) {
                      var compiled = performance2.createExpression(params.filter, {
                        type: "boolean",
                        "property-type": "data-driven",
                        overridable: false,
                        transition: false
                      });
                      if (compiled.result === "error") {
                        throw new Error(compiled.value.map(function(err2) {
                          return err2.key + ": " + err2.message;
                        }).join(", "));
                      }
                      var features = data.features.filter(function(feature) {
                        return compiled.value.evaluate({ zoom: 0 }, feature);
                      });
                      data = {
                        type: "FeatureCollection",
                        features
                      };
                    }
                    this$1._geoJSONIndex = params.cluster ? new Supercluster(getSuperclusterOptions(params)).load(data.features) : geojsonvt(data, params.geojsonVtOptions);
                  } catch (err2) {
                    return callback(err2);
                  }
                  this$1.loaded = {};
                  var result = {};
                  if (perf) {
                    var resourceTimingData = perf.finish();
                    if (resourceTimingData) {
                      result.resourceTiming = {};
                      result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData));
                    }
                  }
                  callback(null, result);
                }
              });
            };
            GeoJSONWorkerSource2.prototype.coalesce = function coalesce() {
              if (this._state === "Coalescing") {
                this._state = "Idle";
              } else if (this._state === "NeedsLoadData") {
                this._state = "Coalescing";
                this._loadData();
              }
            };
            GeoJSONWorkerSource2.prototype.reloadTile = function reloadTile(params, callback) {
              var loaded = this.loaded, uid = params.uid;
              if (loaded && loaded[uid]) {
                return VectorTileWorkerSource2.prototype.reloadTile.call(this, params, callback);
              } else {
                return this.loadTile(params, callback);
              }
            };
            GeoJSONWorkerSource2.prototype.loadGeoJSON = function loadGeoJSON(params, callback) {
              if (params.request) {
                performance2.getJSON(params.request, callback);
              } else if (typeof params.data === "string") {
                try {
                  return callback(null, JSON.parse(params.data));
                } catch (e) {
                  return callback(new Error("Input data given to '" + params.source + "' is not a valid GeoJSON object."));
                }
              } else {
                return callback(new Error("Input data given to '" + params.source + "' is not a valid GeoJSON object."));
              }
            };
            GeoJSONWorkerSource2.prototype.removeSource = function removeSource(params, callback) {
              if (this._pendingCallback) {
                this._pendingCallback(null, { abandoned: true });
              }
              callback();
            };
            GeoJSONWorkerSource2.prototype.getClusterExpansionZoom = function getClusterExpansionZoom(params, callback) {
              try {
                callback(null, this._geoJSONIndex.getClusterExpansionZoom(params.clusterId));
              } catch (e) {
                callback(e);
              }
            };
            GeoJSONWorkerSource2.prototype.getClusterChildren = function getClusterChildren(params, callback) {
              try {
                callback(null, this._geoJSONIndex.getChildren(params.clusterId));
              } catch (e) {
                callback(e);
              }
            };
            GeoJSONWorkerSource2.prototype.getClusterLeaves = function getClusterLeaves(params, callback) {
              try {
                callback(null, this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset));
              } catch (e) {
                callback(e);
              }
            };
            return GeoJSONWorkerSource2;
          }(VectorTileWorkerSource);
          function getSuperclusterOptions(ref) {
            var superclusterOptions = ref.superclusterOptions;
            var clusterProperties = ref.clusterProperties;
            if (!clusterProperties || !superclusterOptions) {
              return superclusterOptions;
            }
            var mapExpressions = {};
            var reduceExpressions = {};
            var globals = {
              accumulated: null,
              zoom: 0
            };
            var feature = { properties: null };
            var propertyNames = Object.keys(clusterProperties);
            for (var i = 0, list = propertyNames; i < list.length; i += 1) {
              var key = list[i];
              var ref$1 = clusterProperties[key];
              var operator = ref$1[0];
              var mapExpression = ref$1[1];
              var mapExpressionParsed = performance2.createExpression(mapExpression);
              var reduceExpressionParsed = performance2.createExpression(typeof operator === "string" ? [
                operator,
                ["accumulated"],
                [
                  "get",
                  key
                ]
              ] : operator);
              mapExpressions[key] = mapExpressionParsed.value;
              reduceExpressions[key] = reduceExpressionParsed.value;
            }
            superclusterOptions.map = function(pointProperties) {
              feature.properties = pointProperties;
              var properties = {};
              for (var i2 = 0, list2 = propertyNames; i2 < list2.length; i2 += 1) {
                var key2 = list2[i2];
                properties[key2] = mapExpressions[key2].evaluate(globals, feature);
              }
              return properties;
            };
            superclusterOptions.reduce = function(accumulated, clusterProperties2) {
              feature.properties = clusterProperties2;
              for (var i2 = 0, list2 = propertyNames; i2 < list2.length; i2 += 1) {
                var key2 = list2[i2];
                globals.accumulated = accumulated[key2];
                accumulated[key2] = reduceExpressions[key2].evaluate(globals, feature);
              }
            };
            return superclusterOptions;
          }
          var Worker2 = function Worker3(self2) {
            var this$1 = this;
            this.self = self2;
            this.actor = new performance2.Actor(self2, this);
            this.layerIndexes = {};
            this.availableImages = {};
            this.workerSourceTypes = {
              vector: VectorTileWorkerSource,
              geojson: GeoJSONWorkerSource
            };
            this.workerSources = {};
            this.demWorkerSources = {};
            this.self.registerWorkerSource = function(name2, WorkerSource) {
              if (this$1.workerSourceTypes[name2]) {
                throw new Error('Worker source with name "' + name2 + '" already registered.');
              }
              this$1.workerSourceTypes[name2] = WorkerSource;
            };
            this.self.registerRTLTextPlugin = function(rtlTextPlugin) {
              if (performance2.plugin.isParsed()) {
                throw new Error("RTL text plugin already registered.");
              }
              performance2.plugin["applyArabicShaping"] = rtlTextPlugin.applyArabicShaping;
              performance2.plugin["processBidirectionalText"] = rtlTextPlugin.processBidirectionalText;
              performance2.plugin["processStyledBidirectionalText"] = rtlTextPlugin.processStyledBidirectionalText;
            };
          };
          Worker2.prototype.setReferrer = function setReferrer(mapID, referrer) {
            this.referrer = referrer;
          };
          Worker2.prototype.setImages = function setImages(mapId, images, callback) {
            this.availableImages[mapId] = images;
            for (var workerSource in this.workerSources[mapId]) {
              var ws = this.workerSources[mapId][workerSource];
              for (var source in ws) {
                ws[source].availableImages = images;
              }
            }
            callback();
          };
          Worker2.prototype.setLayers = function setLayers(mapId, layers, callback) {
            this.getLayerIndex(mapId).replace(layers);
            callback();
          };
          Worker2.prototype.updateLayers = function updateLayers(mapId, params, callback) {
            this.getLayerIndex(mapId).update(params.layers, params.removedIds);
            callback();
          };
          Worker2.prototype.loadTile = function loadTile(mapId, params, callback) {
            this.getWorkerSource(mapId, params.type, params.source).loadTile(params, callback);
          };
          Worker2.prototype.loadDEMTile = function loadDEMTile(mapId, params, callback) {
            this.getDEMWorkerSource(mapId, params.source).loadTile(params, callback);
          };
          Worker2.prototype.reloadTile = function reloadTile(mapId, params, callback) {
            this.getWorkerSource(mapId, params.type, params.source).reloadTile(params, callback);
          };
          Worker2.prototype.abortTile = function abortTile(mapId, params, callback) {
            this.getWorkerSource(mapId, params.type, params.source).abortTile(params, callback);
          };
          Worker2.prototype.removeTile = function removeTile(mapId, params, callback) {
            this.getWorkerSource(mapId, params.type, params.source).removeTile(params, callback);
          };
          Worker2.prototype.removeDEMTile = function removeDEMTile(mapId, params) {
            this.getDEMWorkerSource(mapId, params.source).removeTile(params);
          };
          Worker2.prototype.removeSource = function removeSource(mapId, params, callback) {
            if (!this.workerSources[mapId] || !this.workerSources[mapId][params.type] || !this.workerSources[mapId][params.type][params.source]) {
              return;
            }
            var worker2 = this.workerSources[mapId][params.type][params.source];
            delete this.workerSources[mapId][params.type][params.source];
            if (worker2.removeSource !== void 0) {
              worker2.removeSource(params, callback);
            } else {
              callback();
            }
          };
          Worker2.prototype.loadWorkerSource = function loadWorkerSource(map, params, callback) {
            try {
              this.self.importScripts(params.url);
              callback();
            } catch (e) {
              callback(e.toString());
            }
          };
          Worker2.prototype.syncRTLPluginState = function syncRTLPluginState(map, state, callback) {
            try {
              performance2.plugin.setState(state);
              var pluginURL = performance2.plugin.getPluginURL();
              if (performance2.plugin.isLoaded() && !performance2.plugin.isParsed() && pluginURL != null) {
                this.self.importScripts(pluginURL);
                var complete = performance2.plugin.isParsed();
                var error = complete ? void 0 : new Error("RTL Text Plugin failed to import scripts from " + pluginURL);
                callback(error, complete);
              }
            } catch (e) {
              callback(e.toString());
            }
          };
          Worker2.prototype.getAvailableImages = function getAvailableImages(mapId) {
            var availableImages = this.availableImages[mapId];
            if (!availableImages) {
              availableImages = [];
            }
            return availableImages;
          };
          Worker2.prototype.getLayerIndex = function getLayerIndex(mapId) {
            var layerIndexes = this.layerIndexes[mapId];
            if (!layerIndexes) {
              layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex();
            }
            return layerIndexes;
          };
          Worker2.prototype.getWorkerSource = function getWorkerSource(mapId, type, source) {
            var this$1 = this;
            if (!this.workerSources[mapId]) {
              this.workerSources[mapId] = {};
            }
            if (!this.workerSources[mapId][type]) {
              this.workerSources[mapId][type] = {};
            }
            if (!this.workerSources[mapId][type][source]) {
              var actor = {
                send: function(type2, data, callback) {
                  this$1.actor.send(type2, data, callback, mapId);
                }
              };
              this.workerSources[mapId][type][source] = new this.workerSourceTypes[type](actor, this.getLayerIndex(mapId), this.getAvailableImages(mapId));
            }
            return this.workerSources[mapId][type][source];
          };
          Worker2.prototype.getDEMWorkerSource = function getDEMWorkerSource(mapId, source) {
            if (!this.demWorkerSources[mapId]) {
              this.demWorkerSources[mapId] = {};
            }
            if (!this.demWorkerSources[mapId][source]) {
              this.demWorkerSources[mapId][source] = new RasterDEMTileWorkerSource();
            }
            return this.demWorkerSources[mapId][source];
          };
          Worker2.prototype.enforceCacheSizeLimit = function enforceCacheSizeLimit$1(mapId, limit) {
            performance2.enforceCacheSizeLimit(limit);
          };
          if (typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope) {
            self.worker = new Worker2(self);
          }
          return Worker2;
        });
        define2(["./shared"], function(performance2) {
          "use strict";
          var mapboxGlSupported = performance2.createCommonjsModule(function(module2) {
            if (module2.exports) {
              module2.exports = isSupported;
            } else if (window) {
              window.mapboxgl = window.mapboxgl || {};
              window.mapboxgl.supported = isSupported;
              window.mapboxgl.notSupportedReason = notSupportedReason;
            }
            function isSupported(options) {
              return !notSupportedReason(options);
            }
            function notSupportedReason(options) {
              if (!isBrowser()) {
                return "not a browser";
              }
              if (!isArraySupported()) {
                return "insufficent Array support";
              }
              if (!isFunctionSupported()) {
                return "insufficient Function support";
              }
              if (!isObjectSupported()) {
                return "insufficient Object support";
              }
              if (!isJSONSupported()) {
                return "insufficient JSON support";
              }
              if (!isWorkerSupported()) {
                return "insufficient worker support";
              }
              if (!isUint8ClampedArraySupported()) {
                return "insufficient Uint8ClampedArray support";
              }
              if (!isArrayBufferSupported()) {
                return "insufficient ArrayBuffer support";
              }
              if (!isCanvasGetImageDataSupported()) {
                return "insufficient Canvas/getImageData support";
              }
              if (!isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat)) {
                return "insufficient WebGL support";
              }
            }
            function isBrowser() {
              return typeof window !== "undefined" && typeof document !== "undefined";
            }
            function isArraySupported() {
              return Array.prototype && Array.prototype.every && Array.prototype.filter && Array.prototype.forEach && Array.prototype.indexOf && Array.prototype.lastIndexOf && Array.prototype.map && Array.prototype.some && Array.prototype.reduce && Array.prototype.reduceRight && Array.isArray;
            }
            function isFunctionSupported() {
              return Function.prototype && Function.prototype.bind;
            }
            function isObjectSupported() {
              return Object.keys && Object.create && Object.getPrototypeOf && Object.getOwnPropertyNames && Object.isSealed && Object.isFrozen && Object.isExtensible && Object.getOwnPropertyDescriptor && Object.defineProperty && Object.defineProperties && Object.seal && Object.freeze && Object.preventExtensions;
            }
            function isJSONSupported() {
              return "JSON" in window && "parse" in JSON && "stringify" in JSON;
            }
            function isWorkerSupported() {
              if (!("Worker" in window && "Blob" in window && "URL" in window)) {
                return false;
              }
              var blob = new Blob([""], { type: "text/javascript" });
              var workerURL = URL.createObjectURL(blob);
              var supported;
              var worker2;
              try {
                worker2 = new Worker(workerURL);
                supported = true;
              } catch (e) {
                supported = false;
              }
              if (worker2) {
                worker2.terminate();
              }
              URL.revokeObjectURL(workerURL);
              return supported;
            }
            function isUint8ClampedArraySupported() {
              return "Uint8ClampedArray" in window;
            }
            function isArrayBufferSupported() {
              return ArrayBuffer.isView;
            }
            function isCanvasGetImageDataSupported() {
              var canvas = document.createElement("canvas");
              canvas.width = canvas.height = 1;
              var context = canvas.getContext("2d");
              if (!context) {
                return false;
              }
              var imageData = context.getImageData(0, 0, 1, 1);
              return imageData && imageData.width === canvas.width;
            }
            var isWebGLSupportedCache = {};
            function isWebGLSupportedCached(failIfMajorPerformanceCaveat) {
              if (isWebGLSupportedCache[failIfMajorPerformanceCaveat] === void 0) {
                isWebGLSupportedCache[failIfMajorPerformanceCaveat] = isWebGLSupported(failIfMajorPerformanceCaveat);
              }
              return isWebGLSupportedCache[failIfMajorPerformanceCaveat];
            }
            isSupported.webGLContextAttributes = {
              antialias: false,
              alpha: true,
              stencil: true,
              depth: true
            };
            function getWebGLContext(failIfMajorPerformanceCaveat) {
              var canvas = document.createElement("canvas");
              var attributes = Object.create(isSupported.webGLContextAttributes);
              attributes.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;
              if (canvas.probablySupportsContext) {
                return canvas.probablySupportsContext("webgl", attributes) || canvas.probablySupportsContext("experimental-webgl", attributes);
              } else if (canvas.supportsContext) {
                return canvas.supportsContext("webgl", attributes) || canvas.supportsContext("experimental-webgl", attributes);
              } else {
                return canvas.getContext("webgl", attributes) || canvas.getContext("experimental-webgl", attributes);
              }
            }
            function isWebGLSupported(failIfMajorPerformanceCaveat) {
              var gl2 = getWebGLContext(failIfMajorPerformanceCaveat);
              if (!gl2) {
                return false;
              }
              var shader = gl2.createShader(gl2.VERTEX_SHADER);
              if (!shader || gl2.isContextLost()) {
                return false;
              }
              gl2.shaderSource(shader, "void main() {}");
              gl2.compileShader(shader);
              return gl2.getShaderParameter(shader, gl2.COMPILE_STATUS) === true;
            }
          });
          var DOM = {};
          DOM.create = function(tagName, className, container) {
            var el = performance2.window.document.createElement(tagName);
            if (className !== void 0) {
              el.className = className;
            }
            if (container) {
              container.appendChild(el);
            }
            return el;
          };
          DOM.createNS = function(namespaceURI, tagName) {
            var el = performance2.window.document.createElementNS(namespaceURI, tagName);
            return el;
          };
          var docStyle = performance2.window.document && performance2.window.document.documentElement.style;
          function testProp(props) {
            if (!docStyle) {
              return props[0];
            }
            for (var i = 0; i < props.length; i++) {
              if (props[i] in docStyle) {
                return props[i];
              }
            }
            return props[0];
          }
          var selectProp = testProp([
            "userSelect",
            "MozUserSelect",
            "WebkitUserSelect",
            "msUserSelect"
          ]);
          var userSelect;
          DOM.disableDrag = function() {
            if (docStyle && selectProp) {
              userSelect = docStyle[selectProp];
              docStyle[selectProp] = "none";
            }
          };
          DOM.enableDrag = function() {
            if (docStyle && selectProp) {
              docStyle[selectProp] = userSelect;
            }
          };
          var transformProp = testProp([
            "transform",
            "WebkitTransform"
          ]);
          DOM.setTransform = function(el, value) {
            el.style[transformProp] = value;
          };
          var passiveSupported = false;
          try {
            var options$1 = Object.defineProperty({}, "passive", {
              get: function get() {
                passiveSupported = true;
              }
            });
            performance2.window.addEventListener("test", options$1, options$1);
            performance2.window.removeEventListener("test", options$1, options$1);
          } catch (err) {
            passiveSupported = false;
          }
          DOM.addEventListener = function(target, type, callback, options) {
            if (options === void 0)
              options = {};
            if ("passive" in options && passiveSupported) {
              target.addEventListener(type, callback, options);
            } else {
              target.addEventListener(type, callback, options.capture);
            }
          };
          DOM.removeEventListener = function(target, type, callback, options) {
            if (options === void 0)
              options = {};
            if ("passive" in options && passiveSupported) {
              target.removeEventListener(type, callback, options);
            } else {
              target.removeEventListener(type, callback, options.capture);
            }
          };
          var suppressClick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            performance2.window.removeEventListener("click", suppressClick, true);
          };
          DOM.suppressClick = function() {
            performance2.window.addEventListener("click", suppressClick, true);
            performance2.window.setTimeout(function() {
              performance2.window.removeEventListener("click", suppressClick, true);
            }, 0);
          };
          DOM.mousePos = function(el, e) {
            var rect = el.getBoundingClientRect();
            return new performance2.Point(e.clientX - rect.left - el.clientLeft, e.clientY - rect.top - el.clientTop);
          };
          DOM.touchPos = function(el, touches) {
            var rect = el.getBoundingClientRect(), points = [];
            for (var i = 0; i < touches.length; i++) {
              points.push(new performance2.Point(touches[i].clientX - rect.left - el.clientLeft, touches[i].clientY - rect.top - el.clientTop));
            }
            return points;
          };
          DOM.mouseButton = function(e) {
            if (typeof performance2.window.InstallTrigger !== "undefined" && e.button === 2 && e.ctrlKey && performance2.window.navigator.platform.toUpperCase().indexOf("MAC") >= 0) {
              return 0;
            }
            return e.button;
          };
          DOM.remove = function(node) {
            if (node.parentNode) {
              node.parentNode.removeChild(node);
            }
          };
          function loadSprite(baseURL, requestManager, callback) {
            var json, image, error;
            var format = performance2.browser.devicePixelRatio > 1 ? "@2x" : "";
            var jsonRequest = performance2.getJSON(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, ".json"), performance2.ResourceType.SpriteJSON), function(err, data) {
              jsonRequest = null;
              if (!error) {
                error = err;
                json = data;
                maybeComplete();
              }
            });
            var imageRequest = performance2.getImage(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, ".png"), performance2.ResourceType.SpriteImage), function(err, img) {
              imageRequest = null;
              if (!error) {
                error = err;
                image = img;
                maybeComplete();
              }
            });
            function maybeComplete() {
              if (error) {
                callback(error);
              } else if (json && image) {
                var imageData = performance2.browser.getImageData(image);
                var result = {};
                for (var id in json) {
                  var ref = json[id];
                  var width = ref.width;
                  var height = ref.height;
                  var x = ref.x;
                  var y = ref.y;
                  var sdf = ref.sdf;
                  var pixelRatio = ref.pixelRatio;
                  var stretchX = ref.stretchX;
                  var stretchY = ref.stretchY;
                  var content = ref.content;
                  var data = new performance2.RGBAImage({
                    width,
                    height
                  });
                  performance2.RGBAImage.copy(imageData, data, {
                    x,
                    y
                  }, {
                    x: 0,
                    y: 0
                  }, {
                    width,
                    height
                  });
                  result[id] = {
                    data,
                    pixelRatio,
                    sdf,
                    stretchX,
                    stretchY,
                    content
                  };
                }
                callback(null, result);
              }
            }
            return {
              cancel: function cancel() {
                if (jsonRequest) {
                  jsonRequest.cancel();
                  jsonRequest = null;
                }
                if (imageRequest) {
                  imageRequest.cancel();
                  imageRequest = null;
                }
              }
            };
          }
          function renderStyleImage(image) {
            var userImage = image.userImage;
            if (userImage && userImage.render) {
              var updated = userImage.render();
              if (updated) {
                image.data.replace(new Uint8Array(userImage.data.buffer));
                return true;
              }
            }
            return false;
          }
          var padding = 1;
          var ImageManager = function(Evented) {
            function ImageManager2() {
              Evented.call(this);
              this.images = {};
              this.updatedImages = {};
              this.callbackDispatchedThisFrame = {};
              this.loaded = false;
              this.requestors = [];
              this.patterns = {};
              this.atlasImage = new performance2.RGBAImage({
                width: 1,
                height: 1
              });
              this.dirty = true;
            }
            if (Evented)
              ImageManager2.__proto__ = Evented;
            ImageManager2.prototype = Object.create(Evented && Evented.prototype);
            ImageManager2.prototype.constructor = ImageManager2;
            ImageManager2.prototype.isLoaded = function isLoaded() {
              return this.loaded;
            };
            ImageManager2.prototype.setLoaded = function setLoaded(loaded) {
              if (this.loaded === loaded) {
                return;
              }
              this.loaded = loaded;
              if (loaded) {
                for (var i = 0, list = this.requestors; i < list.length; i += 1) {
                  var ref = list[i];
                  var ids = ref.ids;
                  var callback = ref.callback;
                  this._notify(ids, callback);
                }
                this.requestors = [];
              }
            };
            ImageManager2.prototype.getImage = function getImage(id) {
              return this.images[id];
            };
            ImageManager2.prototype.addImage = function addImage(id, image) {
              if (this._validate(id, image)) {
                this.images[id] = image;
              }
            };
            ImageManager2.prototype._validate = function _validate(id, image) {
              var valid = true;
              if (!this._validateStretch(image.stretchX, image.data && image.data.width)) {
                this.fire(new performance2.ErrorEvent(new Error('Image "' + id + '" has invalid "stretchX" value')));
                valid = false;
              }
              if (!this._validateStretch(image.stretchY, image.data && image.data.height)) {
                this.fire(new performance2.ErrorEvent(new Error('Image "' + id + '" has invalid "stretchY" value')));
                valid = false;
              }
              if (!this._validateContent(image.content, image)) {
                this.fire(new performance2.ErrorEvent(new Error('Image "' + id + '" has invalid "content" value')));
                valid = false;
              }
              return valid;
            };
            ImageManager2.prototype._validateStretch = function _validateStretch(stretch, size) {
              if (!stretch) {
                return true;
              }
              var last = 0;
              for (var i = 0, list = stretch; i < list.length; i += 1) {
                var part = list[i];
                if (part[0] < last || part[1] < part[0] || size < part[1]) {
                  return false;
                }
                last = part[1];
              }
              return true;
            };
            ImageManager2.prototype._validateContent = function _validateContent(content, image) {
              if (!content) {
                return true;
              }
              if (content.length !== 4) {
                return false;
              }
              if (content[0] < 0 || image.data.width < content[0]) {
                return false;
              }
              if (content[1] < 0 || image.data.height < content[1]) {
                return false;
              }
              if (content[2] < 0 || image.data.width < content[2]) {
                return false;
              }
              if (content[3] < 0 || image.data.height < content[3]) {
                return false;
              }
              if (content[2] < content[0]) {
                return false;
              }
              if (content[3] < content[1]) {
                return false;
              }
              return true;
            };
            ImageManager2.prototype.updateImage = function updateImage(id, image) {
              var oldImage = this.images[id];
              image.version = oldImage.version + 1;
              this.images[id] = image;
              this.updatedImages[id] = true;
            };
            ImageManager2.prototype.removeImage = function removeImage(id) {
              var image = this.images[id];
              delete this.images[id];
              delete this.patterns[id];
              if (image.userImage && image.userImage.onRemove) {
                image.userImage.onRemove();
              }
            };
            ImageManager2.prototype.listImages = function listImages() {
              return Object.keys(this.images);
            };
            ImageManager2.prototype.getImages = function getImages(ids, callback) {
              var hasAllDependencies = true;
              if (!this.isLoaded()) {
                for (var i = 0, list = ids; i < list.length; i += 1) {
                  var id = list[i];
                  if (!this.images[id]) {
                    hasAllDependencies = false;
                  }
                }
              }
              if (this.isLoaded() || hasAllDependencies) {
                this._notify(ids, callback);
              } else {
                this.requestors.push({
                  ids,
                  callback
                });
              }
            };
            ImageManager2.prototype._notify = function _notify(ids, callback) {
              var response = {};
              for (var i = 0, list = ids; i < list.length; i += 1) {
                var id = list[i];
                if (!this.images[id]) {
                  this.fire(new performance2.Event("styleimagemissing", { id }));
                }
                var image = this.images[id];
                if (image) {
                  response[id] = {
                    data: image.data.clone(),
                    pixelRatio: image.pixelRatio,
                    sdf: image.sdf,
                    version: image.version,
                    stretchX: image.stretchX,
                    stretchY: image.stretchY,
                    content: image.content,
                    hasRenderCallback: Boolean(image.userImage && image.userImage.render)
                  };
                } else {
                  performance2.warnOnce('Image "' + id + '" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.');
                }
              }
              callback(null, response);
            };
            ImageManager2.prototype.getPixelSize = function getPixelSize() {
              var ref = this.atlasImage;
              var width = ref.width;
              var height = ref.height;
              return {
                width,
                height
              };
            };
            ImageManager2.prototype.getPattern = function getPattern(id) {
              var pattern = this.patterns[id];
              var image = this.getImage(id);
              if (!image) {
                return null;
              }
              if (pattern && pattern.position.version === image.version) {
                return pattern.position;
              }
              if (!pattern) {
                var w = image.data.width + padding * 2;
                var h = image.data.height + padding * 2;
                var bin = {
                  w,
                  h,
                  x: 0,
                  y: 0
                };
                var position = new performance2.ImagePosition(bin, image);
                this.patterns[id] = {
                  bin,
                  position
                };
              } else {
                pattern.position.version = image.version;
              }
              this._updatePatternAtlas();
              return this.patterns[id].position;
            };
            ImageManager2.prototype.bind = function bind(context) {
              var gl2 = context.gl;
              if (!this.atlasTexture) {
                this.atlasTexture = new performance2.Texture(context, this.atlasImage, gl2.RGBA);
              } else if (this.dirty) {
                this.atlasTexture.update(this.atlasImage);
                this.dirty = false;
              }
              this.atlasTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
            };
            ImageManager2.prototype._updatePatternAtlas = function _updatePatternAtlas() {
              var bins = [];
              for (var id in this.patterns) {
                bins.push(this.patterns[id].bin);
              }
              var ref = performance2.potpack(bins);
              var w = ref.w;
              var h = ref.h;
              var dst = this.atlasImage;
              dst.resize({
                width: w || 1,
                height: h || 1
              });
              for (var id$1 in this.patterns) {
                var ref$1 = this.patterns[id$1];
                var bin = ref$1.bin;
                var x = bin.x + padding;
                var y = bin.y + padding;
                var src = this.images[id$1].data;
                var w$1 = src.width;
                var h$1 = src.height;
                performance2.RGBAImage.copy(src, dst, {
                  x: 0,
                  y: 0
                }, {
                  x,
                  y
                }, {
                  width: w$1,
                  height: h$1
                });
                performance2.RGBAImage.copy(src, dst, {
                  x: 0,
                  y: h$1 - 1
                }, {
                  x,
                  y: y - 1
                }, {
                  width: w$1,
                  height: 1
                });
                performance2.RGBAImage.copy(src, dst, {
                  x: 0,
                  y: 0
                }, {
                  x,
                  y: y + h$1
                }, {
                  width: w$1,
                  height: 1
                });
                performance2.RGBAImage.copy(src, dst, {
                  x: w$1 - 1,
                  y: 0
                }, {
                  x: x - 1,
                  y
                }, {
                  width: 1,
                  height: h$1
                });
                performance2.RGBAImage.copy(src, dst, {
                  x: 0,
                  y: 0
                }, {
                  x: x + w$1,
                  y
                }, {
                  width: 1,
                  height: h$1
                });
              }
              this.dirty = true;
            };
            ImageManager2.prototype.beginFrame = function beginFrame() {
              this.callbackDispatchedThisFrame = {};
            };
            ImageManager2.prototype.dispatchRenderCallbacks = function dispatchRenderCallbacks(ids) {
              for (var i = 0, list = ids; i < list.length; i += 1) {
                var id = list[i];
                if (this.callbackDispatchedThisFrame[id]) {
                  continue;
                }
                this.callbackDispatchedThisFrame[id] = true;
                var image = this.images[id];
                var updated = renderStyleImage(image);
                if (updated) {
                  this.updateImage(id, image);
                }
              }
            };
            return ImageManager2;
          }(performance2.Evented);
          function loadGlyphRange(fontstack, range, urlTemplate, requestManager, callback) {
            var begin = range * 256;
            var end = begin + 255;
            var request = requestManager.transformRequest(requestManager.normalizeGlyphsURL(urlTemplate).replace("{fontstack}", fontstack).replace("{range}", begin + "-" + end), performance2.ResourceType.Glyphs);
            performance2.getArrayBuffer(request, function(err, data) {
              if (err) {
                callback(err);
              } else if (data) {
                var glyphs = {};
                for (var i = 0, list = performance2.parseGlyphPBF(data); i < list.length; i += 1) {
                  var glyph = list[i];
                  glyphs[glyph.id] = glyph;
                }
                callback(null, glyphs);
              }
            });
          }
          var tinySdf = TinySDF;
          var default_1 = TinySDF;
          var INF = 1e20;
          function TinySDF(fontSize, buffer, radius, cutoff, fontFamily, fontWeight) {
            this.fontSize = fontSize || 24;
            this.buffer = buffer === void 0 ? 3 : buffer;
            this.cutoff = cutoff || 0.25;
            this.fontFamily = fontFamily || "sans-serif";
            this.fontWeight = fontWeight || "normal";
            this.radius = radius || 8;
            var size = this.size = this.fontSize + this.buffer * 2;
            this.canvas = document.createElement("canvas");
            this.canvas.width = this.canvas.height = size;
            this.ctx = this.canvas.getContext("2d");
            this.ctx.font = this.fontWeight + " " + this.fontSize + "px " + this.fontFamily;
            this.ctx.textBaseline = "middle";
            this.ctx.fillStyle = "black";
            this.gridOuter = new Float64Array(size * size);
            this.gridInner = new Float64Array(size * size);
            this.f = new Float64Array(size);
            this.d = new Float64Array(size);
            this.z = new Float64Array(size + 1);
            this.v = new Int16Array(size);
            this.middle = Math.round(size / 2 * (navigator.userAgent.indexOf("Gecko/") >= 0 ? 1.2 : 1));
          }
          TinySDF.prototype.draw = function(char) {
            this.ctx.clearRect(0, 0, this.size, this.size);
            this.ctx.fillText(char, this.buffer, this.middle);
            var imgData = this.ctx.getImageData(0, 0, this.size, this.size);
            var alphaChannel = new Uint8ClampedArray(this.size * this.size);
            for (var i = 0; i < this.size * this.size; i++) {
              var a = imgData.data[i * 4 + 3] / 255;
              this.gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2);
              this.gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);
            }
            edt(this.gridOuter, this.size, this.size, this.f, this.d, this.v, this.z);
            edt(this.gridInner, this.size, this.size, this.f, this.d, this.v, this.z);
            for (i = 0; i < this.size * this.size; i++) {
              var d = this.gridOuter[i] - this.gridInner[i];
              alphaChannel[i] = Math.max(0, Math.min(255, Math.round(255 - 255 * (d / this.radius + this.cutoff))));
            }
            return alphaChannel;
          };
          function edt(data, width, height, f, d, v, z) {
            for (var x = 0; x < width; x++) {
              for (var y = 0; y < height; y++) {
                f[y] = data[y * width + x];
              }
              edt1d(f, d, v, z, height);
              for (y = 0; y < height; y++) {
                data[y * width + x] = d[y];
              }
            }
            for (y = 0; y < height; y++) {
              for (x = 0; x < width; x++) {
                f[x] = data[y * width + x];
              }
              edt1d(f, d, v, z, width);
              for (x = 0; x < width; x++) {
                data[y * width + x] = Math.sqrt(d[x]);
              }
            }
          }
          function edt1d(f, d, v, z, n) {
            v[0] = 0;
            z[0] = -INF;
            z[1] = +INF;
            for (var q = 1, k = 0; q < n; q++) {
              var s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
              while (s <= z[k]) {
                k--;
                s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
              }
              k++;
              v[k] = q;
              z[k] = s;
              z[k + 1] = +INF;
            }
            for (q = 0, k = 0; q < n; q++) {
              while (z[k + 1] < q) {
                k++;
              }
              d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];
            }
          }
          tinySdf.default = default_1;
          var GlyphManager = function GlyphManager2(requestManager, localIdeographFontFamily) {
            this.requestManager = requestManager;
            this.localIdeographFontFamily = localIdeographFontFamily;
            this.entries = {};
          };
          GlyphManager.prototype.setURL = function setURL(url) {
            this.url = url;
          };
          GlyphManager.prototype.getGlyphs = function getGlyphs(glyphs, callback) {
            var this$1 = this;
            var all = [];
            for (var stack in glyphs) {
              for (var i = 0, list = glyphs[stack]; i < list.length; i += 1) {
                var id = list[i];
                all.push({
                  stack,
                  id
                });
              }
            }
            performance2.asyncAll(all, function(ref, callback2) {
              var stack2 = ref.stack;
              var id2 = ref.id;
              var entry = this$1.entries[stack2];
              if (!entry) {
                entry = this$1.entries[stack2] = {
                  glyphs: {},
                  requests: {},
                  ranges: {}
                };
              }
              var glyph = entry.glyphs[id2];
              if (glyph !== void 0) {
                callback2(null, {
                  stack: stack2,
                  id: id2,
                  glyph
                });
                return;
              }
              glyph = this$1._tinySDF(entry, stack2, id2);
              if (glyph) {
                entry.glyphs[id2] = glyph;
                callback2(null, {
                  stack: stack2,
                  id: id2,
                  glyph
                });
                return;
              }
              var range = Math.floor(id2 / 256);
              if (range * 256 > 65535) {
                callback2(new Error("glyphs > 65535 not supported"));
                return;
              }
              if (entry.ranges[range]) {
                callback2(null, {
                  stack: stack2,
                  id: id2,
                  glyph
                });
                return;
              }
              var requests = entry.requests[range];
              if (!requests) {
                requests = entry.requests[range] = [];
                GlyphManager.loadGlyphRange(stack2, range, this$1.url, this$1.requestManager, function(err, response) {
                  if (response) {
                    for (var id3 in response) {
                      if (!this$1._doesCharSupportLocalGlyph(+id3)) {
                        entry.glyphs[+id3] = response[+id3];
                      }
                    }
                    entry.ranges[range] = true;
                  }
                  for (var i2 = 0, list2 = requests; i2 < list2.length; i2 += 1) {
                    var cb = list2[i2];
                    cb(err, response);
                  }
                  delete entry.requests[range];
                });
              }
              requests.push(function(err, result) {
                if (err) {
                  callback2(err);
                } else if (result) {
                  callback2(null, {
                    stack: stack2,
                    id: id2,
                    glyph: result[id2] || null
                  });
                }
              });
            }, function(err, glyphs2) {
              if (err) {
                callback(err);
              } else if (glyphs2) {
                var result = {};
                for (var i2 = 0, list2 = glyphs2; i2 < list2.length; i2 += 1) {
                  var ref = list2[i2];
                  var stack2 = ref.stack;
                  var id2 = ref.id;
                  var glyph = ref.glyph;
                  (result[stack2] || (result[stack2] = {}))[id2] = glyph && {
                    id: glyph.id,
                    bitmap: glyph.bitmap.clone(),
                    metrics: glyph.metrics
                  };
                }
                callback(null, result);
              }
            });
          };
          GlyphManager.prototype._doesCharSupportLocalGlyph = function _doesCharSupportLocalGlyph(id) {
            return !!this.localIdeographFontFamily && (performance2.isChar["CJK Unified Ideographs"](id) || performance2.isChar["Hangul Syllables"](id) || performance2.isChar["Hiragana"](id) || performance2.isChar["Katakana"](id));
          };
          GlyphManager.prototype._tinySDF = function _tinySDF(entry, stack, id) {
            var family = this.localIdeographFontFamily;
            if (!family) {
              return;
            }
            if (!this._doesCharSupportLocalGlyph(id)) {
              return;
            }
            var tinySDF = entry.tinySDF;
            if (!tinySDF) {
              var fontWeight = "400";
              if (/bold/i.test(stack)) {
                fontWeight = "900";
              } else if (/medium/i.test(stack)) {
                fontWeight = "500";
              } else if (/light/i.test(stack)) {
                fontWeight = "200";
              }
              tinySDF = entry.tinySDF = new GlyphManager.TinySDF(24, 3, 8, 0.25, family, fontWeight);
            }
            return {
              id,
              bitmap: new performance2.AlphaImage({
                width: 30,
                height: 30
              }, tinySDF.draw(String.fromCharCode(id))),
              metrics: {
                width: 24,
                height: 24,
                left: 0,
                top: -8,
                advance: 24
              }
            };
          };
          GlyphManager.loadGlyphRange = loadGlyphRange;
          GlyphManager.TinySDF = tinySdf;
          var LightPositionProperty = function LightPositionProperty2() {
            this.specification = performance2.styleSpec.light.position;
          };
          LightPositionProperty.prototype.possiblyEvaluate = function possiblyEvaluate(value, parameters) {
            return performance2.sphericalToCartesian(value.expression.evaluate(parameters));
          };
          LightPositionProperty.prototype.interpolate = function interpolate$1(a, b, t) {
            return {
              x: performance2.number(a.x, b.x, t),
              y: performance2.number(a.y, b.y, t),
              z: performance2.number(a.z, b.z, t)
            };
          };
          var properties = new performance2.Properties({
            "anchor": new performance2.DataConstantProperty(performance2.styleSpec.light.anchor),
            "position": new LightPositionProperty(),
            "color": new performance2.DataConstantProperty(performance2.styleSpec.light.color),
            "intensity": new performance2.DataConstantProperty(performance2.styleSpec.light.intensity)
          });
          var TRANSITION_SUFFIX = "-transition";
          var Light = function(Evented) {
            function Light2(lightOptions) {
              Evented.call(this);
              this._transitionable = new performance2.Transitionable(properties);
              this.setLight(lightOptions);
              this._transitioning = this._transitionable.untransitioned();
            }
            if (Evented)
              Light2.__proto__ = Evented;
            Light2.prototype = Object.create(Evented && Evented.prototype);
            Light2.prototype.constructor = Light2;
            Light2.prototype.getLight = function getLight() {
              return this._transitionable.serialize();
            };
            Light2.prototype.setLight = function setLight(light, options) {
              if (options === void 0)
                options = {};
              if (this._validate(performance2.validateLight, light, options)) {
                return;
              }
              for (var name2 in light) {
                var value = light[name2];
                if (performance2.endsWith(name2, TRANSITION_SUFFIX)) {
                  this._transitionable.setTransition(name2.slice(0, -TRANSITION_SUFFIX.length), value);
                } else {
                  this._transitionable.setValue(name2, value);
                }
              }
            };
            Light2.prototype.updateTransitions = function updateTransitions(parameters) {
              this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
            };
            Light2.prototype.hasTransition = function hasTransition() {
              return this._transitioning.hasTransition();
            };
            Light2.prototype.recalculate = function recalculate(parameters) {
              this.properties = this._transitioning.possiblyEvaluate(parameters);
            };
            Light2.prototype._validate = function _validate(validate, value, options) {
              if (options && options.validate === false) {
                return false;
              }
              return performance2.emitValidationErrors(this, validate.call(performance2.validateStyle, performance2.extend({
                value,
                style: {
                  glyphs: true,
                  sprite: true
                },
                styleSpec: performance2.styleSpec
              })));
            };
            return Light2;
          }(performance2.Evented);
          var LineAtlas = function LineAtlas2(width, height) {
            this.width = width;
            this.height = height;
            this.nextRow = 0;
            this.data = new Uint8Array(this.width * this.height);
            this.dashEntry = {};
          };
          LineAtlas.prototype.getDash = function getDash(dasharray, round) {
            var key = dasharray.join(",") + String(round);
            if (!this.dashEntry[key]) {
              this.dashEntry[key] = this.addDash(dasharray, round);
            }
            return this.dashEntry[key];
          };
          LineAtlas.prototype.getDashRanges = function getDashRanges(dasharray, lineAtlasWidth, stretch) {
            var oddDashArray = dasharray.length % 2 === 1;
            var ranges = [];
            var left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0;
            var right = dasharray[0] * stretch;
            var isDash = true;
            ranges.push({
              left,
              right,
              isDash,
              zeroLength: dasharray[0] === 0
            });
            var currentDashLength = dasharray[0];
            for (var i = 1; i < dasharray.length; i++) {
              isDash = !isDash;
              var dashLength = dasharray[i];
              left = currentDashLength * stretch;
              currentDashLength += dashLength;
              right = currentDashLength * stretch;
              ranges.push({
                left,
                right,
                isDash,
                zeroLength: dashLength === 0
              });
            }
            return ranges;
          };
          LineAtlas.prototype.addRoundDash = function addRoundDash(ranges, stretch, n) {
            var halfStretch = stretch / 2;
            for (var y = -n; y <= n; y++) {
              var row = this.nextRow + n + y;
              var index = this.width * row;
              var currIndex = 0;
              var range = ranges[currIndex];
              for (var x = 0; x < this.width; x++) {
                if (x / range.right > 1) {
                  range = ranges[++currIndex];
                }
                var distLeft = Math.abs(x - range.left);
                var distRight = Math.abs(x - range.right);
                var minDist = Math.min(distLeft, distRight);
                var signedDistance = void 0;
                var distMiddle = y / n * (halfStretch + 1);
                if (range.isDash) {
                  var distEdge = halfStretch - Math.abs(distMiddle);
                  signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge);
                } else {
                  signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle);
                }
                this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));
              }
            }
          };
          LineAtlas.prototype.addRegularDash = function addRegularDash(ranges) {
            for (var i = ranges.length - 1; i >= 0; --i) {
              var part = ranges[i];
              var next = ranges[i + 1];
              if (part.zeroLength) {
                ranges.splice(i, 1);
              } else if (next && next.isDash === part.isDash) {
                next.left = part.left;
                ranges.splice(i, 1);
              }
            }
            var first = ranges[0];
            var last = ranges[ranges.length - 1];
            if (first.isDash === last.isDash) {
              first.left = last.left - this.width;
              last.right = first.right + this.width;
            }
            var index = this.width * this.nextRow;
            var currIndex = 0;
            var range = ranges[currIndex];
            for (var x = 0; x < this.width; x++) {
              if (x / range.right > 1) {
                range = ranges[++currIndex];
              }
              var distLeft = Math.abs(x - range.left);
              var distRight = Math.abs(x - range.right);
              var minDist = Math.min(distLeft, distRight);
              var signedDistance = range.isDash ? minDist : -minDist;
              this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));
            }
          };
          LineAtlas.prototype.addDash = function addDash(dasharray, round) {
            var n = round ? 7 : 0;
            var height = 2 * n + 1;
            if (this.nextRow + height > this.height) {
              performance2.warnOnce("LineAtlas out of space");
              return null;
            }
            var length = 0;
            for (var i = 0; i < dasharray.length; i++) {
              length += dasharray[i];
            }
            if (length !== 0) {
              var stretch = this.width / length;
              var ranges = this.getDashRanges(dasharray, this.width, stretch);
              if (round) {
                this.addRoundDash(ranges, stretch, n);
              } else {
                this.addRegularDash(ranges);
              }
            }
            var dashEntry = {
              y: (this.nextRow + n + 0.5) / this.height,
              height: 2 * n / this.height,
              width: length
            };
            this.nextRow += height;
            this.dirty = true;
            return dashEntry;
          };
          LineAtlas.prototype.bind = function bind(context) {
            var gl2 = context.gl;
            if (!this.texture) {
              this.texture = gl2.createTexture();
              gl2.bindTexture(gl2.TEXTURE_2D, this.texture);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.REPEAT);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.REPEAT);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
              gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.ALPHA, this.width, this.height, 0, gl2.ALPHA, gl2.UNSIGNED_BYTE, this.data);
            } else {
              gl2.bindTexture(gl2.TEXTURE_2D, this.texture);
              if (this.dirty) {
                this.dirty = false;
                gl2.texSubImage2D(gl2.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl2.ALPHA, gl2.UNSIGNED_BYTE, this.data);
              }
            }
          };
          var Dispatcher = function Dispatcher2(workerPool, parent) {
            this.workerPool = workerPool;
            this.actors = [];
            this.currentActor = 0;
            this.id = performance2.uniqueId();
            var workers = this.workerPool.acquire(this.id);
            for (var i = 0; i < workers.length; i++) {
              var worker2 = workers[i];
              var actor = new Dispatcher2.Actor(worker2, parent, this.id);
              actor.name = "Worker " + i;
              this.actors.push(actor);
            }
          };
          Dispatcher.prototype.broadcast = function broadcast(type, data, cb) {
            cb = cb || function() {
            };
            performance2.asyncAll(this.actors, function(actor, done) {
              actor.send(type, data, done);
            }, cb);
          };
          Dispatcher.prototype.getActor = function getActor() {
            this.currentActor = (this.currentActor + 1) % this.actors.length;
            return this.actors[this.currentActor];
          };
          Dispatcher.prototype.remove = function remove() {
            this.actors.forEach(function(actor) {
              actor.remove();
            });
            this.actors = [];
            this.workerPool.release(this.id);
          };
          Dispatcher.Actor = performance2.Actor;
          function loadTileJSON(options, requestManager, callback) {
            var loaded = function(err, tileJSON) {
              if (err) {
                return callback(err);
              } else if (tileJSON) {
                var result = performance2.pick(performance2.extend(tileJSON, options), [
                  "tiles",
                  "minzoom",
                  "maxzoom",
                  "attribution",
                  "mapbox_logo",
                  "bounds",
                  "scheme",
                  "tileSize",
                  "encoding"
                ]);
                if (tileJSON.vector_layers) {
                  result.vectorLayers = tileJSON.vector_layers;
                  result.vectorLayerIds = result.vectorLayers.map(function(layer) {
                    return layer.id;
                  });
                }
                result.tiles = requestManager.canonicalizeTileset(result, options.url);
                callback(null, result);
              }
            };
            if (options.url) {
              return performance2.getJSON(requestManager.transformRequest(requestManager.normalizeSourceURL(options.url), performance2.ResourceType.Source), loaded);
            } else {
              return performance2.browser.frame(function() {
                return loaded(null, options);
              });
            }
          }
          var TileBounds = function TileBounds2(bounds, minzoom, maxzoom) {
            this.bounds = performance2.LngLatBounds.convert(this.validateBounds(bounds));
            this.minzoom = minzoom || 0;
            this.maxzoom = maxzoom || 24;
          };
          TileBounds.prototype.validateBounds = function validateBounds(bounds) {
            if (!Array.isArray(bounds) || bounds.length !== 4) {
              return [
                -180,
                -90,
                180,
                90
              ];
            }
            return [
              Math.max(-180, bounds[0]),
              Math.max(-90, bounds[1]),
              Math.min(180, bounds[2]),
              Math.min(90, bounds[3])
            ];
          };
          TileBounds.prototype.contains = function contains(tileID) {
            var worldSize = Math.pow(2, tileID.z);
            var level = {
              minX: Math.floor(performance2.mercatorXfromLng(this.bounds.getWest()) * worldSize),
              minY: Math.floor(performance2.mercatorYfromLat(this.bounds.getNorth()) * worldSize),
              maxX: Math.ceil(performance2.mercatorXfromLng(this.bounds.getEast()) * worldSize),
              maxY: Math.ceil(performance2.mercatorYfromLat(this.bounds.getSouth()) * worldSize)
            };
            var hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;
            return hit;
          };
          var VectorTileSource = function(Evented) {
            function VectorTileSource2(id, options, dispatcher, eventedParent) {
              Evented.call(this);
              this.id = id;
              this.dispatcher = dispatcher;
              this.type = "vector";
              this.minzoom = 0;
              this.maxzoom = 22;
              this.scheme = "xyz";
              this.tileSize = 512;
              this.reparseOverscaled = true;
              this.isTileClipped = true;
              this._loaded = false;
              performance2.extend(this, performance2.pick(options, [
                "url",
                "scheme",
                "tileSize",
                "promoteId"
              ]));
              this._options = performance2.extend({ type: "vector" }, options);
              this._collectResourceTiming = options.collectResourceTiming;
              if (this.tileSize !== 512) {
                throw new Error("vector tile sources must have a tileSize of 512");
              }
              this.setEventedParent(eventedParent);
            }
            if (Evented)
              VectorTileSource2.__proto__ = Evented;
            VectorTileSource2.prototype = Object.create(Evented && Evented.prototype);
            VectorTileSource2.prototype.constructor = VectorTileSource2;
            VectorTileSource2.prototype.load = function load() {
              var this$1 = this;
              this._loaded = false;
              this.fire(new performance2.Event("dataloading", { dataType: "source" }));
              this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, function(err, tileJSON) {
                this$1._tileJSONRequest = null;
                this$1._loaded = true;
                if (err) {
                  this$1.fire(new performance2.ErrorEvent(err));
                } else if (tileJSON) {
                  performance2.extend(this$1, tileJSON);
                  if (tileJSON.bounds) {
                    this$1.tileBounds = new TileBounds(tileJSON.bounds, this$1.minzoom, this$1.maxzoom);
                  }
                  performance2.postTurnstileEvent(tileJSON.tiles, this$1.map._requestManager._customAccessToken);
                  performance2.postMapLoadEvent(tileJSON.tiles, this$1.map._getMapId(), this$1.map._requestManager._skuToken, this$1.map._requestManager._customAccessToken);
                  this$1.fire(new performance2.Event("data", {
                    dataType: "source",
                    sourceDataType: "metadata"
                  }));
                  this$1.fire(new performance2.Event("data", {
                    dataType: "source",
                    sourceDataType: "content"
                  }));
                }
              });
            };
            VectorTileSource2.prototype.loaded = function loaded() {
              return this._loaded;
            };
            VectorTileSource2.prototype.hasTile = function hasTile(tileID) {
              return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
            };
            VectorTileSource2.prototype.onAdd = function onAdd(map) {
              this.map = map;
              this.load();
            };
            VectorTileSource2.prototype.setSourceProperty = function setSourceProperty(callback) {
              if (this._tileJSONRequest) {
                this._tileJSONRequest.cancel();
              }
              callback();
              var sourceCache = this.map.style.sourceCaches[this.id];
              sourceCache.clearTiles();
              this.load();
            };
            VectorTileSource2.prototype.setTiles = function setTiles(tiles) {
              var this$1 = this;
              this.setSourceProperty(function() {
                this$1._options.tiles = tiles;
              });
              return this;
            };
            VectorTileSource2.prototype.setUrl = function setUrl(url) {
              var this$1 = this;
              this.setSourceProperty(function() {
                this$1.url = url;
                this$1._options.url = url;
              });
              return this;
            };
            VectorTileSource2.prototype.onRemove = function onRemove() {
              if (this._tileJSONRequest) {
                this._tileJSONRequest.cancel();
                this._tileJSONRequest = null;
              }
            };
            VectorTileSource2.prototype.serialize = function serialize() {
              return performance2.extend({}, this._options);
            };
            VectorTileSource2.prototype.loadTile = function loadTile(tile, callback) {
              var url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme));
              var params = {
                request: this.map._requestManager.transformRequest(url, performance2.ResourceType.Tile),
                uid: tile.uid,
                tileID: tile.tileID,
                zoom: tile.tileID.overscaledZ,
                tileSize: this.tileSize * tile.tileID.overscaleFactor(),
                type: this.type,
                source: this.id,
                pixelRatio: performance2.browser.devicePixelRatio,
                showCollisionBoxes: this.map.showCollisionBoxes,
                promoteId: this.promoteId
              };
              params.request.collectResourceTiming = this._collectResourceTiming;
              if (!tile.actor || tile.state === "expired") {
                tile.actor = this.dispatcher.getActor();
                tile.request = tile.actor.send("loadTile", params, done.bind(this));
              } else if (tile.state === "loading") {
                tile.reloadCallback = callback;
              } else {
                tile.request = tile.actor.send("reloadTile", params, done.bind(this));
              }
              function done(err, data) {
                delete tile.request;
                if (tile.aborted) {
                  return callback(null);
                }
                if (err && err.status !== 404) {
                  return callback(err);
                }
                if (data && data.resourceTiming) {
                  tile.resourceTiming = data.resourceTiming;
                }
                if (this.map._refreshExpiredTiles && data) {
                  tile.setExpiryData(data);
                }
                tile.loadVectorData(data, this.map.painter);
                performance2.cacheEntryPossiblyAdded(this.dispatcher);
                callback(null);
                if (tile.reloadCallback) {
                  this.loadTile(tile, tile.reloadCallback);
                  tile.reloadCallback = null;
                }
              }
            };
            VectorTileSource2.prototype.abortTile = function abortTile(tile) {
              if (tile.request) {
                tile.request.cancel();
                delete tile.request;
              }
              if (tile.actor) {
                tile.actor.send("abortTile", {
                  uid: tile.uid,
                  type: this.type,
                  source: this.id
                }, void 0);
              }
            };
            VectorTileSource2.prototype.unloadTile = function unloadTile(tile) {
              tile.unloadVectorData();
              if (tile.actor) {
                tile.actor.send("removeTile", {
                  uid: tile.uid,
                  type: this.type,
                  source: this.id
                }, void 0);
              }
            };
            VectorTileSource2.prototype.hasTransition = function hasTransition() {
              return false;
            };
            return VectorTileSource2;
          }(performance2.Evented);
          var RasterTileSource = function(Evented) {
            function RasterTileSource2(id, options, dispatcher, eventedParent) {
              Evented.call(this);
              this.id = id;
              this.dispatcher = dispatcher;
              this.setEventedParent(eventedParent);
              this.type = "raster";
              this.minzoom = 0;
              this.maxzoom = 22;
              this.roundZoom = true;
              this.scheme = "xyz";
              this.tileSize = 512;
              this._loaded = false;
              this._options = performance2.extend({ type: "raster" }, options);
              performance2.extend(this, performance2.pick(options, [
                "url",
                "scheme",
                "tileSize"
              ]));
            }
            if (Evented)
              RasterTileSource2.__proto__ = Evented;
            RasterTileSource2.prototype = Object.create(Evented && Evented.prototype);
            RasterTileSource2.prototype.constructor = RasterTileSource2;
            RasterTileSource2.prototype.load = function load() {
              var this$1 = this;
              this._loaded = false;
              this.fire(new performance2.Event("dataloading", { dataType: "source" }));
              this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, function(err, tileJSON) {
                this$1._tileJSONRequest = null;
                this$1._loaded = true;
                if (err) {
                  this$1.fire(new performance2.ErrorEvent(err));
                } else if (tileJSON) {
                  performance2.extend(this$1, tileJSON);
                  if (tileJSON.bounds) {
                    this$1.tileBounds = new TileBounds(tileJSON.bounds, this$1.minzoom, this$1.maxzoom);
                  }
                  performance2.postTurnstileEvent(tileJSON.tiles);
                  performance2.postMapLoadEvent(tileJSON.tiles, this$1.map._getMapId(), this$1.map._requestManager._skuToken);
                  this$1.fire(new performance2.Event("data", {
                    dataType: "source",
                    sourceDataType: "metadata"
                  }));
                  this$1.fire(new performance2.Event("data", {
                    dataType: "source",
                    sourceDataType: "content"
                  }));
                }
              });
            };
            RasterTileSource2.prototype.loaded = function loaded() {
              return this._loaded;
            };
            RasterTileSource2.prototype.onAdd = function onAdd(map) {
              this.map = map;
              this.load();
            };
            RasterTileSource2.prototype.onRemove = function onRemove() {
              if (this._tileJSONRequest) {
                this._tileJSONRequest.cancel();
                this._tileJSONRequest = null;
              }
            };
            RasterTileSource2.prototype.serialize = function serialize() {
              return performance2.extend({}, this._options);
            };
            RasterTileSource2.prototype.hasTile = function hasTile(tileID) {
              return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
            };
            RasterTileSource2.prototype.loadTile = function loadTile(tile, callback) {
              var this$1 = this;
              var url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize);
              tile.request = performance2.getImage(this.map._requestManager.transformRequest(url, performance2.ResourceType.Tile), function(err, img) {
                delete tile.request;
                if (tile.aborted) {
                  tile.state = "unloaded";
                  callback(null);
                } else if (err) {
                  tile.state = "errored";
                  callback(err);
                } else if (img) {
                  if (this$1.map._refreshExpiredTiles) {
                    tile.setExpiryData(img);
                  }
                  delete img.cacheControl;
                  delete img.expires;
                  var context = this$1.map.painter.context;
                  var gl2 = context.gl;
                  tile.texture = this$1.map.painter.getTileTexture(img.width);
                  if (tile.texture) {
                    tile.texture.update(img, { useMipmap: true });
                  } else {
                    tile.texture = new performance2.Texture(context, img, gl2.RGBA, { useMipmap: true });
                    tile.texture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE, gl2.LINEAR_MIPMAP_NEAREST);
                    if (context.extTextureFilterAnisotropic) {
                      gl2.texParameterf(gl2.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
                    }
                  }
                  tile.state = "loaded";
                  performance2.cacheEntryPossiblyAdded(this$1.dispatcher);
                  callback(null);
                }
              });
            };
            RasterTileSource2.prototype.abortTile = function abortTile(tile, callback) {
              if (tile.request) {
                tile.request.cancel();
                delete tile.request;
              }
              callback();
            };
            RasterTileSource2.prototype.unloadTile = function unloadTile(tile, callback) {
              if (tile.texture) {
                this.map.painter.saveTileTexture(tile.texture);
              }
              callback();
            };
            RasterTileSource2.prototype.hasTransition = function hasTransition() {
              return false;
            };
            return RasterTileSource2;
          }(performance2.Evented);
          var RasterDEMTileSource = function(RasterTileSource2) {
            function RasterDEMTileSource2(id, options, dispatcher, eventedParent) {
              RasterTileSource2.call(this, id, options, dispatcher, eventedParent);
              this.type = "raster-dem";
              this.maxzoom = 22;
              this._options = performance2.extend({ type: "raster-dem" }, options);
              this.encoding = options.encoding || "mapbox";
            }
            if (RasterTileSource2)
              RasterDEMTileSource2.__proto__ = RasterTileSource2;
            RasterDEMTileSource2.prototype = Object.create(RasterTileSource2 && RasterTileSource2.prototype);
            RasterDEMTileSource2.prototype.constructor = RasterDEMTileSource2;
            RasterDEMTileSource2.prototype.serialize = function serialize() {
              return {
                type: "raster-dem",
                url: this.url,
                tileSize: this.tileSize,
                tiles: this.tiles,
                bounds: this.bounds,
                encoding: this.encoding
              };
            };
            RasterDEMTileSource2.prototype.loadTile = function loadTile(tile, callback) {
              var url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize);
              tile.request = performance2.getImage(this.map._requestManager.transformRequest(url, performance2.ResourceType.Tile), imageLoaded.bind(this));
              tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);
              function imageLoaded(err, img) {
                delete tile.request;
                if (tile.aborted) {
                  tile.state = "unloaded";
                  callback(null);
                } else if (err) {
                  tile.state = "errored";
                  callback(err);
                } else if (img) {
                  if (this.map._refreshExpiredTiles) {
                    tile.setExpiryData(img);
                  }
                  delete img.cacheControl;
                  delete img.expires;
                  var transfer = performance2.window.ImageBitmap && img instanceof performance2.window.ImageBitmap && performance2.offscreenCanvasSupported();
                  var rawImageData = transfer ? img : performance2.browser.getImageData(img, 1);
                  var params = {
                    uid: tile.uid,
                    coord: tile.tileID,
                    source: this.id,
                    rawImageData,
                    encoding: this.encoding
                  };
                  if (!tile.actor || tile.state === "expired") {
                    tile.actor = this.dispatcher.getActor();
                    tile.actor.send("loadDEMTile", params, done.bind(this));
                  }
                }
              }
              function done(err, dem) {
                if (err) {
                  tile.state = "errored";
                  callback(err);
                }
                if (dem) {
                  tile.dem = dem;
                  tile.needsHillshadePrepare = true;
                  tile.state = "loaded";
                  callback(null);
                }
              }
            };
            RasterDEMTileSource2.prototype._getNeighboringTiles = function _getNeighboringTiles(tileID) {
              var canonical = tileID.canonical;
              var dim = Math.pow(2, canonical.z);
              var px = (canonical.x - 1 + dim) % dim;
              var pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap;
              var nx = (canonical.x + 1 + dim) % dim;
              var nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap;
              var neighboringTiles = {};
              neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false };
              neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false };
              if (canonical.y > 0) {
                neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false };
                neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false };
                neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false };
              }
              if (canonical.y + 1 < dim) {
                neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false };
                neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false };
                neighboringTiles[new performance2.OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false };
              }
              return neighboringTiles;
            };
            RasterDEMTileSource2.prototype.unloadTile = function unloadTile(tile) {
              if (tile.demTexture) {
                this.map.painter.saveTileTexture(tile.demTexture);
              }
              if (tile.fbo) {
                tile.fbo.destroy();
                delete tile.fbo;
              }
              if (tile.dem) {
                delete tile.dem;
              }
              delete tile.neighboringTiles;
              tile.state = "unloaded";
              if (tile.actor) {
                tile.actor.send("removeDEMTile", {
                  uid: tile.uid,
                  source: this.id
                });
              }
            };
            return RasterDEMTileSource2;
          }(RasterTileSource);
          var GeoJSONSource = function(Evented) {
            function GeoJSONSource2(id, options, dispatcher, eventedParent) {
              Evented.call(this);
              this.id = id;
              this.type = "geojson";
              this.minzoom = 0;
              this.maxzoom = 18;
              this.tileSize = 512;
              this.isTileClipped = true;
              this.reparseOverscaled = true;
              this._removed = false;
              this._loaded = false;
              this.actor = dispatcher.getActor();
              this.setEventedParent(eventedParent);
              this._data = options.data;
              this._options = performance2.extend({}, options);
              this._collectResourceTiming = options.collectResourceTiming;
              this._resourceTiming = [];
              if (options.maxzoom !== void 0) {
                this.maxzoom = options.maxzoom;
              }
              if (options.type) {
                this.type = options.type;
              }
              if (options.attribution) {
                this.attribution = options.attribution;
              }
              this.promoteId = options.promoteId;
              var scale = performance2.EXTENT / this.tileSize;
              this.workerOptions = performance2.extend({
                source: this.id,
                cluster: options.cluster || false,
                geojsonVtOptions: {
                  buffer: (options.buffer !== void 0 ? options.buffer : 128) * scale,
                  tolerance: (options.tolerance !== void 0 ? options.tolerance : 0.375) * scale,
                  extent: performance2.EXTENT,
                  maxZoom: this.maxzoom,
                  lineMetrics: options.lineMetrics || false,
                  generateId: options.generateId || false
                },
                superclusterOptions: {
                  maxZoom: options.clusterMaxZoom !== void 0 ? Math.min(options.clusterMaxZoom, this.maxzoom - 1) : this.maxzoom - 1,
                  minPoints: Math.max(2, options.clusterMinPoints || 2),
                  extent: performance2.EXTENT,
                  radius: (options.clusterRadius || 50) * scale,
                  log: false,
                  generateId: options.generateId || false
                },
                clusterProperties: options.clusterProperties,
                filter: options.filter
              }, options.workerOptions);
            }
            if (Evented)
              GeoJSONSource2.__proto__ = Evented;
            GeoJSONSource2.prototype = Object.create(Evented && Evented.prototype);
            GeoJSONSource2.prototype.constructor = GeoJSONSource2;
            GeoJSONSource2.prototype.load = function load() {
              var this$1 = this;
              this.fire(new performance2.Event("dataloading", { dataType: "source" }));
              this._updateWorkerData(function(err) {
                if (err) {
                  this$1.fire(new performance2.ErrorEvent(err));
                  return;
                }
                var data = {
                  dataType: "source",
                  sourceDataType: "metadata"
                };
                if (this$1._collectResourceTiming && this$1._resourceTiming && this$1._resourceTiming.length > 0) {
                  data.resourceTiming = this$1._resourceTiming;
                  this$1._resourceTiming = [];
                }
                this$1.fire(new performance2.Event("data", data));
              });
            };
            GeoJSONSource2.prototype.onAdd = function onAdd(map) {
              this.map = map;
              this.load();
            };
            GeoJSONSource2.prototype.setData = function setData(data) {
              var this$1 = this;
              this._data = data;
              this.fire(new performance2.Event("dataloading", { dataType: "source" }));
              this._updateWorkerData(function(err) {
                if (err) {
                  this$1.fire(new performance2.ErrorEvent(err));
                  return;
                }
                var data2 = {
                  dataType: "source",
                  sourceDataType: "content"
                };
                if (this$1._collectResourceTiming && this$1._resourceTiming && this$1._resourceTiming.length > 0) {
                  data2.resourceTiming = this$1._resourceTiming;
                  this$1._resourceTiming = [];
                }
                this$1.fire(new performance2.Event("data", data2));
              });
              return this;
            };
            GeoJSONSource2.prototype.getClusterExpansionZoom = function getClusterExpansionZoom(clusterId, callback) {
              this.actor.send("geojson.getClusterExpansionZoom", {
                clusterId,
                source: this.id
              }, callback);
              return this;
            };
            GeoJSONSource2.prototype.getClusterChildren = function getClusterChildren(clusterId, callback) {
              this.actor.send("geojson.getClusterChildren", {
                clusterId,
                source: this.id
              }, callback);
              return this;
            };
            GeoJSONSource2.prototype.getClusterLeaves = function getClusterLeaves(clusterId, limit, offset, callback) {
              this.actor.send("geojson.getClusterLeaves", {
                source: this.id,
                clusterId,
                limit,
                offset
              }, callback);
              return this;
            };
            GeoJSONSource2.prototype._updateWorkerData = function _updateWorkerData(callback) {
              var this$1 = this;
              this._loaded = false;
              var options = performance2.extend({}, this.workerOptions);
              var data = this._data;
              if (typeof data === "string") {
                options.request = this.map._requestManager.transformRequest(performance2.browser.resolveURL(data), performance2.ResourceType.Source);
                options.request.collectResourceTiming = this._collectResourceTiming;
              } else {
                options.data = JSON.stringify(data);
              }
              this.actor.send(this.type + ".loadData", options, function(err, result) {
                if (this$1._removed || result && result.abandoned) {
                  return;
                }
                this$1._loaded = true;
                if (result && result.resourceTiming && result.resourceTiming[this$1.id]) {
                  this$1._resourceTiming = result.resourceTiming[this$1.id].slice(0);
                }
                this$1.actor.send(this$1.type + ".coalesce", { source: options.source }, null);
                callback(err);
              });
            };
            GeoJSONSource2.prototype.loaded = function loaded() {
              return this._loaded;
            };
            GeoJSONSource2.prototype.loadTile = function loadTile(tile, callback) {
              var this$1 = this;
              var message = !tile.actor ? "loadTile" : "reloadTile";
              tile.actor = this.actor;
              var params = {
                type: this.type,
                uid: tile.uid,
                tileID: tile.tileID,
                zoom: tile.tileID.overscaledZ,
                maxZoom: this.maxzoom,
                tileSize: this.tileSize,
                source: this.id,
                pixelRatio: performance2.browser.devicePixelRatio,
                showCollisionBoxes: this.map.showCollisionBoxes,
                promoteId: this.promoteId
              };
              tile.request = this.actor.send(message, params, function(err, data) {
                delete tile.request;
                tile.unloadVectorData();
                if (tile.aborted) {
                  return callback(null);
                }
                if (err) {
                  return callback(err);
                }
                tile.loadVectorData(data, this$1.map.painter, message === "reloadTile");
                return callback(null);
              });
            };
            GeoJSONSource2.prototype.abortTile = function abortTile(tile) {
              if (tile.request) {
                tile.request.cancel();
                delete tile.request;
              }
              tile.aborted = true;
            };
            GeoJSONSource2.prototype.unloadTile = function unloadTile(tile) {
              tile.unloadVectorData();
              this.actor.send("removeTile", {
                uid: tile.uid,
                type: this.type,
                source: this.id
              });
            };
            GeoJSONSource2.prototype.onRemove = function onRemove() {
              this._removed = true;
              this.actor.send("removeSource", {
                type: this.type,
                source: this.id
              });
            };
            GeoJSONSource2.prototype.serialize = function serialize() {
              return performance2.extend({}, this._options, {
                type: this.type,
                data: this._data
              });
            };
            GeoJSONSource2.prototype.hasTransition = function hasTransition() {
              return false;
            };
            return GeoJSONSource2;
          }(performance2.Evented);
          var rasterBoundsAttributes = performance2.createLayout([
            {
              name: "a_pos",
              type: "Int16",
              components: 2
            },
            {
              name: "a_texture_pos",
              type: "Int16",
              components: 2
            }
          ]);
          var ImageSource = function(Evented) {
            function ImageSource2(id, options, dispatcher, eventedParent) {
              Evented.call(this);
              this.id = id;
              this.dispatcher = dispatcher;
              this.coordinates = options.coordinates;
              this.type = "image";
              this.minzoom = 0;
              this.maxzoom = 22;
              this.tileSize = 512;
              this.tiles = {};
              this._loaded = false;
              this.setEventedParent(eventedParent);
              this.options = options;
            }
            if (Evented)
              ImageSource2.__proto__ = Evented;
            ImageSource2.prototype = Object.create(Evented && Evented.prototype);
            ImageSource2.prototype.constructor = ImageSource2;
            ImageSource2.prototype.load = function load(newCoordinates, successCallback) {
              var this$1 = this;
              this._loaded = false;
              this.fire(new performance2.Event("dataloading", { dataType: "source" }));
              this.url = this.options.url;
              performance2.getImage(this.map._requestManager.transformRequest(this.url, performance2.ResourceType.Image), function(err, image) {
                this$1._loaded = true;
                if (err) {
                  this$1.fire(new performance2.ErrorEvent(err));
                } else if (image) {
                  this$1.image = image;
                  if (newCoordinates) {
                    this$1.coordinates = newCoordinates;
                  }
                  if (successCallback) {
                    successCallback();
                  }
                  this$1._finishLoading();
                }
              });
            };
            ImageSource2.prototype.loaded = function loaded() {
              return this._loaded;
            };
            ImageSource2.prototype.updateImage = function updateImage(options) {
              var this$1 = this;
              if (!this.image || !options.url) {
                return this;
              }
              this.options.url = options.url;
              this.load(options.coordinates, function() {
                this$1.texture = null;
              });
              return this;
            };
            ImageSource2.prototype._finishLoading = function _finishLoading() {
              if (this.map) {
                this.setCoordinates(this.coordinates);
                this.fire(new performance2.Event("data", {
                  dataType: "source",
                  sourceDataType: "metadata"
                }));
              }
            };
            ImageSource2.prototype.onAdd = function onAdd(map) {
              this.map = map;
              this.load();
            };
            ImageSource2.prototype.setCoordinates = function setCoordinates(coordinates) {
              var this$1 = this;
              this.coordinates = coordinates;
              var cornerCoords = coordinates.map(performance2.MercatorCoordinate.fromLngLat);
              this.tileID = getCoordinatesCenterTileID(cornerCoords);
              this.minzoom = this.maxzoom = this.tileID.z;
              var tileCoords = cornerCoords.map(function(coord) {
                return this$1.tileID.getTilePoint(coord)._round();
              });
              this._boundsArray = new performance2.StructArrayLayout4i8();
              this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0);
              this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, performance2.EXTENT, 0);
              this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, performance2.EXTENT);
              this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, performance2.EXTENT, performance2.EXTENT);
              if (this.boundsBuffer) {
                this.boundsBuffer.destroy();
                delete this.boundsBuffer;
              }
              this.fire(new performance2.Event("data", {
                dataType: "source",
                sourceDataType: "content"
              }));
              return this;
            };
            ImageSource2.prototype.prepare = function prepare() {
              if (Object.keys(this.tiles).length === 0 || !this.image) {
                return;
              }
              var context = this.map.painter.context;
              var gl2 = context.gl;
              if (!this.boundsBuffer) {
                this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);
              }
              if (!this.boundsSegments) {
                this.boundsSegments = performance2.SegmentVector.simpleSegment(0, 0, 4, 2);
              }
              if (!this.texture) {
                this.texture = new performance2.Texture(context, this.image, gl2.RGBA);
                this.texture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
              }
              for (var w in this.tiles) {
                var tile = this.tiles[w];
                if (tile.state !== "loaded") {
                  tile.state = "loaded";
                  tile.texture = this.texture;
                }
              }
            };
            ImageSource2.prototype.loadTile = function loadTile(tile, callback) {
              if (this.tileID && this.tileID.equals(tile.tileID.canonical)) {
                this.tiles[String(tile.tileID.wrap)] = tile;
                tile.buckets = {};
                callback(null);
              } else {
                tile.state = "errored";
                callback(null);
              }
            };
            ImageSource2.prototype.serialize = function serialize() {
              return {
                type: "image",
                url: this.options.url,
                coordinates: this.coordinates
              };
            };
            ImageSource2.prototype.hasTransition = function hasTransition() {
              return false;
            };
            return ImageSource2;
          }(performance2.Evented);
          function getCoordinatesCenterTileID(coords) {
            var minX = Infinity;
            var minY = Infinity;
            var maxX = -Infinity;
            var maxY = -Infinity;
            for (var i = 0, list = coords; i < list.length; i += 1) {
              var coord = list[i];
              minX = Math.min(minX, coord.x);
              minY = Math.min(minY, coord.y);
              maxX = Math.max(maxX, coord.x);
              maxY = Math.max(maxY, coord.y);
            }
            var dx = maxX - minX;
            var dy = maxY - minY;
            var dMax = Math.max(dx, dy);
            var zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2));
            var tilesAtZoom = Math.pow(2, zoom);
            return new performance2.CanonicalTileID(zoom, Math.floor((minX + maxX) / 2 * tilesAtZoom), Math.floor((minY + maxY) / 2 * tilesAtZoom));
          }
          var VideoSource = function(ImageSource2) {
            function VideoSource2(id, options, dispatcher, eventedParent) {
              ImageSource2.call(this, id, options, dispatcher, eventedParent);
              this.roundZoom = true;
              this.type = "video";
              this.options = options;
            }
            if (ImageSource2)
              VideoSource2.__proto__ = ImageSource2;
            VideoSource2.prototype = Object.create(ImageSource2 && ImageSource2.prototype);
            VideoSource2.prototype.constructor = VideoSource2;
            VideoSource2.prototype.load = function load() {
              var this$1 = this;
              this._loaded = false;
              var options = this.options;
              this.urls = [];
              for (var i = 0, list = options.urls; i < list.length; i += 1) {
                var url = list[i];
                this.urls.push(this.map._requestManager.transformRequest(url, performance2.ResourceType.Source).url);
              }
              performance2.getVideo(this.urls, function(err, video) {
                this$1._loaded = true;
                if (err) {
                  this$1.fire(new performance2.ErrorEvent(err));
                } else if (video) {
                  this$1.video = video;
                  this$1.video.loop = true;
                  this$1.video.addEventListener("playing", function() {
                    this$1.map.triggerRepaint();
                  });
                  if (this$1.map) {
                    this$1.video.play();
                  }
                  this$1._finishLoading();
                }
              });
            };
            VideoSource2.prototype.pause = function pause() {
              if (this.video) {
                this.video.pause();
              }
            };
            VideoSource2.prototype.play = function play() {
              if (this.video) {
                this.video.play();
              }
            };
            VideoSource2.prototype.seek = function seek(seconds) {
              if (this.video) {
                var seekableRange = this.video.seekable;
                if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) {
                  this.fire(new performance2.ErrorEvent(new performance2.ValidationError("sources." + this.id, null, "Playback for this video can be set only between the " + seekableRange.start(0) + " and " + seekableRange.end(0) + "-second mark.")));
                } else {
                  this.video.currentTime = seconds;
                }
              }
            };
            VideoSource2.prototype.getVideo = function getVideo() {
              return this.video;
            };
            VideoSource2.prototype.onAdd = function onAdd(map) {
              if (this.map) {
                return;
              }
              this.map = map;
              this.load();
              if (this.video) {
                this.video.play();
                this.setCoordinates(this.coordinates);
              }
            };
            VideoSource2.prototype.prepare = function prepare() {
              if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) {
                return;
              }
              var context = this.map.painter.context;
              var gl2 = context.gl;
              if (!this.boundsBuffer) {
                this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);
              }
              if (!this.boundsSegments) {
                this.boundsSegments = performance2.SegmentVector.simpleSegment(0, 0, 4, 2);
              }
              if (!this.texture) {
                this.texture = new performance2.Texture(context, this.video, gl2.RGBA);
                this.texture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
              } else if (!this.video.paused) {
                this.texture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
                gl2.texSubImage2D(gl2.TEXTURE_2D, 0, 0, 0, gl2.RGBA, gl2.UNSIGNED_BYTE, this.video);
              }
              for (var w in this.tiles) {
                var tile = this.tiles[w];
                if (tile.state !== "loaded") {
                  tile.state = "loaded";
                  tile.texture = this.texture;
                }
              }
            };
            VideoSource2.prototype.serialize = function serialize() {
              return {
                type: "video",
                urls: this.urls,
                coordinates: this.coordinates
              };
            };
            VideoSource2.prototype.hasTransition = function hasTransition() {
              return this.video && !this.video.paused;
            };
            return VideoSource2;
          }(ImageSource);
          var CanvasSource = function(ImageSource2) {
            function CanvasSource2(id, options, dispatcher, eventedParent) {
              ImageSource2.call(this, id, options, dispatcher, eventedParent);
              if (!options.coordinates) {
                this.fire(new performance2.ErrorEvent(new performance2.ValidationError("sources." + id, null, 'missing required property "coordinates"')));
              } else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 || options.coordinates.some(function(c) {
                return !Array.isArray(c) || c.length !== 2 || c.some(function(l) {
                  return typeof l !== "number";
                });
              })) {
                this.fire(new performance2.ErrorEvent(new performance2.ValidationError("sources." + id, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs')));
              }
              if (options.animate && typeof options.animate !== "boolean") {
                this.fire(new performance2.ErrorEvent(new performance2.ValidationError("sources." + id, null, 'optional "animate" property must be a boolean value')));
              }
              if (!options.canvas) {
                this.fire(new performance2.ErrorEvent(new performance2.ValidationError("sources." + id, null, 'missing required property "canvas"')));
              } else if (typeof options.canvas !== "string" && !(options.canvas instanceof performance2.window.HTMLCanvasElement)) {
                this.fire(new performance2.ErrorEvent(new performance2.ValidationError("sources." + id, null, '"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance')));
              }
              this.options = options;
              this.animate = options.animate !== void 0 ? options.animate : true;
            }
            if (ImageSource2)
              CanvasSource2.__proto__ = ImageSource2;
            CanvasSource2.prototype = Object.create(ImageSource2 && ImageSource2.prototype);
            CanvasSource2.prototype.constructor = CanvasSource2;
            CanvasSource2.prototype.load = function load() {
              this._loaded = true;
              if (!this.canvas) {
                this.canvas = this.options.canvas instanceof performance2.window.HTMLCanvasElement ? this.options.canvas : performance2.window.document.getElementById(this.options.canvas);
              }
              this.width = this.canvas.width;
              this.height = this.canvas.height;
              if (this._hasInvalidDimensions()) {
                this.fire(new performance2.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero.")));
                return;
              }
              this.play = function() {
                this._playing = true;
                this.map.triggerRepaint();
              };
              this.pause = function() {
                if (this._playing) {
                  this.prepare();
                  this._playing = false;
                }
              };
              this._finishLoading();
            };
            CanvasSource2.prototype.getCanvas = function getCanvas() {
              return this.canvas;
            };
            CanvasSource2.prototype.onAdd = function onAdd(map) {
              this.map = map;
              this.load();
              if (this.canvas) {
                if (this.animate) {
                  this.play();
                }
              }
            };
            CanvasSource2.prototype.onRemove = function onRemove() {
              this.pause();
            };
            CanvasSource2.prototype.prepare = function prepare() {
              var resize = false;
              if (this.canvas.width !== this.width) {
                this.width = this.canvas.width;
                resize = true;
              }
              if (this.canvas.height !== this.height) {
                this.height = this.canvas.height;
                resize = true;
              }
              if (this._hasInvalidDimensions()) {
                return;
              }
              if (Object.keys(this.tiles).length === 0) {
                return;
              }
              var context = this.map.painter.context;
              var gl2 = context.gl;
              if (!this.boundsBuffer) {
                this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);
              }
              if (!this.boundsSegments) {
                this.boundsSegments = performance2.SegmentVector.simpleSegment(0, 0, 4, 2);
              }
              if (!this.texture) {
                this.texture = new performance2.Texture(context, this.canvas, gl2.RGBA, { premultiply: true });
              } else if (resize || this._playing) {
                this.texture.update(this.canvas, { premultiply: true });
              }
              for (var w in this.tiles) {
                var tile = this.tiles[w];
                if (tile.state !== "loaded") {
                  tile.state = "loaded";
                  tile.texture = this.texture;
                }
              }
            };
            CanvasSource2.prototype.serialize = function serialize() {
              return {
                type: "canvas",
                coordinates: this.coordinates
              };
            };
            CanvasSource2.prototype.hasTransition = function hasTransition() {
              return this._playing;
            };
            CanvasSource2.prototype._hasInvalidDimensions = function _hasInvalidDimensions() {
              for (var i = 0, list = [
                this.canvas.width,
                this.canvas.height
              ]; i < list.length; i += 1) {
                var x = list[i];
                if (isNaN(x) || x <= 0) {
                  return true;
                }
              }
              return false;
            };
            return CanvasSource2;
          }(ImageSource);
          var sourceTypes = {
            vector: VectorTileSource,
            raster: RasterTileSource,
            "raster-dem": RasterDEMTileSource,
            geojson: GeoJSONSource,
            video: VideoSource,
            image: ImageSource,
            canvas: CanvasSource
          };
          var create = function(id, specification, dispatcher, eventedParent) {
            var source = new sourceTypes[specification.type](id, specification, dispatcher, eventedParent);
            if (source.id !== id) {
              throw new Error("Expected Source id to be " + id + " instead of " + source.id);
            }
            performance2.bindAll([
              "load",
              "abort",
              "unload",
              "serialize",
              "prepare"
            ], source);
            return source;
          };
          var getType = function(name2) {
            return sourceTypes[name2];
          };
          var setType = function(name2, type) {
            sourceTypes[name2] = type;
          };
          function getPixelPosMatrix(transform, tileID) {
            var t = performance2.identity([]);
            performance2.translate(t, t, [
              1,
              1,
              0
            ]);
            performance2.scale(t, t, [
              transform.width * 0.5,
              transform.height * 0.5,
              1
            ]);
            return performance2.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped()));
          }
          function queryIncludes3DLayer(layers, styleLayers, sourceID) {
            if (layers) {
              for (var i = 0, list = layers; i < list.length; i += 1) {
                var layerID = list[i];
                var layer = styleLayers[layerID];
                if (layer && layer.source === sourceID && layer.type === "fill-extrusion") {
                  return true;
                }
              }
            } else {
              for (var key in styleLayers) {
                var layer$1 = styleLayers[key];
                if (layer$1.source === sourceID && layer$1.type === "fill-extrusion") {
                  return true;
                }
              }
            }
            return false;
          }
          function queryRenderedFeatures(sourceCache, styleLayers, serializedLayers, queryGeometry, params, transform) {
            var has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id);
            var maxPitchScaleFactor = transform.maxPitchScaleFactor();
            var tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer);
            tilesIn.sort(sortTilesIn);
            var renderedFeatureLayers = [];
            for (var i = 0, list = tilesIn; i < list.length; i += 1) {
              var tileIn = list[i];
              renderedFeatureLayers.push({
                wrappedTileID: tileIn.tileID.wrapped().key,
                queryResults: tileIn.tile.queryRenderedFeatures(styleLayers, serializedLayers, sourceCache._state, tileIn.queryGeometry, tileIn.cameraQueryGeometry, tileIn.scale, params, transform, maxPitchScaleFactor, getPixelPosMatrix(sourceCache.transform, tileIn.tileID))
              });
            }
            var result = mergeRenderedFeatureLayers(renderedFeatureLayers);
            for (var layerID in result) {
              result[layerID].forEach(function(featureWrapper) {
                var feature = featureWrapper.feature;
                var state = sourceCache.getFeatureState(feature.layer["source-layer"], feature.id);
                feature.source = feature.layer.source;
                if (feature.layer["source-layer"]) {
                  feature.sourceLayer = feature.layer["source-layer"];
                }
                feature.state = state;
              });
            }
            return result;
          }
          function queryRenderedSymbols(styleLayers, serializedLayers, sourceCaches, queryGeometry, params, collisionIndex, retainedQueryData) {
            var result = {};
            var renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry);
            var bucketQueryData = [];
            for (var i = 0, list = Object.keys(renderedSymbols).map(Number); i < list.length; i += 1) {
              var bucketInstanceId = list[i];
              bucketQueryData.push(retainedQueryData[bucketInstanceId]);
            }
            bucketQueryData.sort(sortTilesIn);
            var loop = function() {
              var queryData = list$2[i$2];
              var bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId], serializedLayers, queryData.bucketIndex, queryData.sourceLayerIndex, params.filter, params.layers, params.availableImages, styleLayers);
              for (var layerID in bucketSymbols) {
                var resultFeatures = result[layerID] = result[layerID] || [];
                var layerSymbols = bucketSymbols[layerID];
                layerSymbols.sort(function(a, b) {
                  var featureSortOrder = queryData.featureSortOrder;
                  if (featureSortOrder) {
                    var sortedA = featureSortOrder.indexOf(a.featureIndex);
                    var sortedB = featureSortOrder.indexOf(b.featureIndex);
                    return sortedB - sortedA;
                  } else {
                    return b.featureIndex - a.featureIndex;
                  }
                });
                for (var i$1 = 0, list$1 = layerSymbols; i$1 < list$1.length; i$1 += 1) {
                  var symbolFeature = list$1[i$1];
                  resultFeatures.push(symbolFeature);
                }
              }
            };
            for (var i$2 = 0, list$2 = bucketQueryData; i$2 < list$2.length; i$2 += 1)
              loop();
            var loop$1 = function(layerName2) {
              result[layerName2].forEach(function(featureWrapper) {
                var feature = featureWrapper.feature;
                var layer = styleLayers[layerName2];
                var sourceCache = sourceCaches[layer.source];
                var state = sourceCache.getFeatureState(feature.layer["source-layer"], feature.id);
                feature.source = feature.layer.source;
                if (feature.layer["source-layer"]) {
                  feature.sourceLayer = feature.layer["source-layer"];
                }
                feature.state = state;
              });
            };
            for (var layerName in result)
              loop$1(layerName);
            return result;
          }
          function querySourceFeatures(sourceCache, params) {
            var tiles = sourceCache.getRenderableIds().map(function(id) {
              return sourceCache.getTileByID(id);
            });
            var result = [];
            var dataTiles = {};
            for (var i = 0; i < tiles.length; i++) {
              var tile = tiles[i];
              var dataID = tile.tileID.canonical.key;
              if (!dataTiles[dataID]) {
                dataTiles[dataID] = true;
                tile.querySourceFeatures(result, params);
              }
            }
            return result;
          }
          function sortTilesIn(a, b) {
            var idA = a.tileID;
            var idB = b.tileID;
            return idA.overscaledZ - idB.overscaledZ || idA.canonical.y - idB.canonical.y || idA.wrap - idB.wrap || idA.canonical.x - idB.canonical.x;
          }
          function mergeRenderedFeatureLayers(tiles) {
            var result = {};
            var wrappedIDLayerMap = {};
            for (var i$1 = 0, list$1 = tiles; i$1 < list$1.length; i$1 += 1) {
              var tile = list$1[i$1];
              var queryResults = tile.queryResults;
              var wrappedID = tile.wrappedTileID;
              var wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {};
              for (var layerID in queryResults) {
                var tileFeatures = queryResults[layerID];
                var wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {};
                var resultFeatures = result[layerID] = result[layerID] || [];
                for (var i = 0, list = tileFeatures; i < list.length; i += 1) {
                  var tileFeature = list[i];
                  if (!wrappedIDFeatures[tileFeature.featureIndex]) {
                    wrappedIDFeatures[tileFeature.featureIndex] = true;
                    resultFeatures.push(tileFeature);
                  }
                }
              }
            }
            return result;
          }
          var TileCache = function TileCache2(max, onRemove) {
            this.max = max;
            this.onRemove = onRemove;
            this.reset();
          };
          TileCache.prototype.reset = function reset() {
            for (var key in this.data) {
              for (var i = 0, list = this.data[key]; i < list.length; i += 1) {
                var removedData = list[i];
                if (removedData.timeout) {
                  clearTimeout(removedData.timeout);
                }
                this.onRemove(removedData.value);
              }
            }
            this.data = {};
            this.order = [];
            return this;
          };
          TileCache.prototype.add = function add(tileID, data, expiryTimeout) {
            var this$1 = this;
            var key = tileID.wrapped().key;
            if (this.data[key] === void 0) {
              this.data[key] = [];
            }
            var dataWrapper = {
              value: data,
              timeout: void 0
            };
            if (expiryTimeout !== void 0) {
              dataWrapper.timeout = setTimeout(function() {
                this$1.remove(tileID, dataWrapper);
              }, expiryTimeout);
            }
            this.data[key].push(dataWrapper);
            this.order.push(key);
            if (this.order.length > this.max) {
              var removedData = this._getAndRemoveByKey(this.order[0]);
              if (removedData) {
                this.onRemove(removedData);
              }
            }
            return this;
          };
          TileCache.prototype.has = function has(tileID) {
            return tileID.wrapped().key in this.data;
          };
          TileCache.prototype.getAndRemove = function getAndRemove(tileID) {
            if (!this.has(tileID)) {
              return null;
            }
            return this._getAndRemoveByKey(tileID.wrapped().key);
          };
          TileCache.prototype._getAndRemoveByKey = function _getAndRemoveByKey(key) {
            var data = this.data[key].shift();
            if (data.timeout) {
              clearTimeout(data.timeout);
            }
            if (this.data[key].length === 0) {
              delete this.data[key];
            }
            this.order.splice(this.order.indexOf(key), 1);
            return data.value;
          };
          TileCache.prototype.getByKey = function getByKey(key) {
            var data = this.data[key];
            return data ? data[0].value : null;
          };
          TileCache.prototype.get = function get(tileID) {
            if (!this.has(tileID)) {
              return null;
            }
            var data = this.data[tileID.wrapped().key][0];
            return data.value;
          };
          TileCache.prototype.remove = function remove(tileID, value) {
            if (!this.has(tileID)) {
              return this;
            }
            var key = tileID.wrapped().key;
            var dataIndex = value === void 0 ? 0 : this.data[key].indexOf(value);
            var data = this.data[key][dataIndex];
            this.data[key].splice(dataIndex, 1);
            if (data.timeout) {
              clearTimeout(data.timeout);
            }
            if (this.data[key].length === 0) {
              delete this.data[key];
            }
            this.onRemove(data.value);
            this.order.splice(this.order.indexOf(key), 1);
            return this;
          };
          TileCache.prototype.setMaxSize = function setMaxSize(max) {
            this.max = max;
            while (this.order.length > this.max) {
              var removedData = this._getAndRemoveByKey(this.order[0]);
              if (removedData) {
                this.onRemove(removedData);
              }
            }
            return this;
          };
          TileCache.prototype.filter = function filter(filterFn) {
            var removed = [];
            for (var key in this.data) {
              for (var i = 0, list = this.data[key]; i < list.length; i += 1) {
                var entry = list[i];
                if (!filterFn(entry.value)) {
                  removed.push(entry);
                }
              }
            }
            for (var i$1 = 0, list$1 = removed; i$1 < list$1.length; i$1 += 1) {
              var r = list$1[i$1];
              this.remove(r.value.tileID, r);
            }
          };
          var IndexBuffer = function IndexBuffer2(context, array, dynamicDraw) {
            this.context = context;
            var gl2 = context.gl;
            this.buffer = gl2.createBuffer();
            this.dynamicDraw = Boolean(dynamicDraw);
            this.context.unbindVAO();
            context.bindElementBuffer.set(this.buffer);
            gl2.bufferData(gl2.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl2.DYNAMIC_DRAW : gl2.STATIC_DRAW);
            if (!this.dynamicDraw) {
              delete array.arrayBuffer;
            }
          };
          IndexBuffer.prototype.bind = function bind() {
            this.context.bindElementBuffer.set(this.buffer);
          };
          IndexBuffer.prototype.updateData = function updateData(array) {
            var gl2 = this.context.gl;
            this.context.unbindVAO();
            this.bind();
            gl2.bufferSubData(gl2.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer);
          };
          IndexBuffer.prototype.destroy = function destroy() {
            var gl2 = this.context.gl;
            if (this.buffer) {
              gl2.deleteBuffer(this.buffer);
              delete this.buffer;
            }
          };
          var AttributeType = {
            Int8: "BYTE",
            Uint8: "UNSIGNED_BYTE",
            Int16: "SHORT",
            Uint16: "UNSIGNED_SHORT",
            Int32: "INT",
            Uint32: "UNSIGNED_INT",
            Float32: "FLOAT"
          };
          var VertexBuffer = function VertexBuffer2(context, array, attributes, dynamicDraw) {
            this.length = array.length;
            this.attributes = attributes;
            this.itemSize = array.bytesPerElement;
            this.dynamicDraw = dynamicDraw;
            this.context = context;
            var gl2 = context.gl;
            this.buffer = gl2.createBuffer();
            context.bindVertexBuffer.set(this.buffer);
            gl2.bufferData(gl2.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl2.DYNAMIC_DRAW : gl2.STATIC_DRAW);
            if (!this.dynamicDraw) {
              delete array.arrayBuffer;
            }
          };
          VertexBuffer.prototype.bind = function bind() {
            this.context.bindVertexBuffer.set(this.buffer);
          };
          VertexBuffer.prototype.updateData = function updateData(array) {
            var gl2 = this.context.gl;
            this.bind();
            gl2.bufferSubData(gl2.ARRAY_BUFFER, 0, array.arrayBuffer);
          };
          VertexBuffer.prototype.enableAttributes = function enableAttributes(gl2, program) {
            for (var j = 0; j < this.attributes.length; j++) {
              var member = this.attributes[j];
              var attribIndex = program.attributes[member.name];
              if (attribIndex !== void 0) {
                gl2.enableVertexAttribArray(attribIndex);
              }
            }
          };
          VertexBuffer.prototype.setVertexAttribPointers = function setVertexAttribPointers(gl2, program, vertexOffset) {
            for (var j = 0; j < this.attributes.length; j++) {
              var member = this.attributes[j];
              var attribIndex = program.attributes[member.name];
              if (attribIndex !== void 0) {
                gl2.vertexAttribPointer(attribIndex, member.components, gl2[AttributeType[member.type]], false, this.itemSize, member.offset + this.itemSize * (vertexOffset || 0));
              }
            }
          };
          VertexBuffer.prototype.destroy = function destroy() {
            var gl2 = this.context.gl;
            if (this.buffer) {
              gl2.deleteBuffer(this.buffer);
              delete this.buffer;
            }
          };
          var BaseValue = function BaseValue2(context) {
            this.gl = context.gl;
            this.default = this.getDefault();
            this.current = this.default;
            this.dirty = false;
          };
          BaseValue.prototype.get = function get() {
            return this.current;
          };
          BaseValue.prototype.set = function set(value) {
          };
          BaseValue.prototype.getDefault = function getDefault() {
            return this.default;
          };
          BaseValue.prototype.setDefault = function setDefault() {
            this.set(this.default);
          };
          var ClearColor = function(BaseValue2) {
            function ClearColor2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              ClearColor2.__proto__ = BaseValue2;
            ClearColor2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            ClearColor2.prototype.constructor = ClearColor2;
            ClearColor2.prototype.getDefault = function getDefault() {
              return performance2.Color.transparent;
            };
            ClearColor2.prototype.set = function set(v) {
              var c = this.current;
              if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) {
                return;
              }
              this.gl.clearColor(v.r, v.g, v.b, v.a);
              this.current = v;
              this.dirty = false;
            };
            return ClearColor2;
          }(BaseValue);
          var ClearDepth = function(BaseValue2) {
            function ClearDepth2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              ClearDepth2.__proto__ = BaseValue2;
            ClearDepth2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            ClearDepth2.prototype.constructor = ClearDepth2;
            ClearDepth2.prototype.getDefault = function getDefault() {
              return 1;
            };
            ClearDepth2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.clearDepth(v);
              this.current = v;
              this.dirty = false;
            };
            return ClearDepth2;
          }(BaseValue);
          var ClearStencil = function(BaseValue2) {
            function ClearStencil2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              ClearStencil2.__proto__ = BaseValue2;
            ClearStencil2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            ClearStencil2.prototype.constructor = ClearStencil2;
            ClearStencil2.prototype.getDefault = function getDefault() {
              return 0;
            };
            ClearStencil2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.clearStencil(v);
              this.current = v;
              this.dirty = false;
            };
            return ClearStencil2;
          }(BaseValue);
          var ColorMask = function(BaseValue2) {
            function ColorMask2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              ColorMask2.__proto__ = BaseValue2;
            ColorMask2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            ColorMask2.prototype.constructor = ColorMask2;
            ColorMask2.prototype.getDefault = function getDefault() {
              return [
                true,
                true,
                true,
                true
              ];
            };
            ColorMask2.prototype.set = function set(v) {
              var c = this.current;
              if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) {
                return;
              }
              this.gl.colorMask(v[0], v[1], v[2], v[3]);
              this.current = v;
              this.dirty = false;
            };
            return ColorMask2;
          }(BaseValue);
          var DepthMask = function(BaseValue2) {
            function DepthMask2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              DepthMask2.__proto__ = BaseValue2;
            DepthMask2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            DepthMask2.prototype.constructor = DepthMask2;
            DepthMask2.prototype.getDefault = function getDefault() {
              return true;
            };
            DepthMask2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.depthMask(v);
              this.current = v;
              this.dirty = false;
            };
            return DepthMask2;
          }(BaseValue);
          var StencilMask = function(BaseValue2) {
            function StencilMask2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              StencilMask2.__proto__ = BaseValue2;
            StencilMask2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            StencilMask2.prototype.constructor = StencilMask2;
            StencilMask2.prototype.getDefault = function getDefault() {
              return 255;
            };
            StencilMask2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.stencilMask(v);
              this.current = v;
              this.dirty = false;
            };
            return StencilMask2;
          }(BaseValue);
          var StencilFunc = function(BaseValue2) {
            function StencilFunc2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              StencilFunc2.__proto__ = BaseValue2;
            StencilFunc2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            StencilFunc2.prototype.constructor = StencilFunc2;
            StencilFunc2.prototype.getDefault = function getDefault() {
              return {
                func: this.gl.ALWAYS,
                ref: 0,
                mask: 255
              };
            };
            StencilFunc2.prototype.set = function set(v) {
              var c = this.current;
              if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) {
                return;
              }
              this.gl.stencilFunc(v.func, v.ref, v.mask);
              this.current = v;
              this.dirty = false;
            };
            return StencilFunc2;
          }(BaseValue);
          var StencilOp = function(BaseValue2) {
            function StencilOp2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              StencilOp2.__proto__ = BaseValue2;
            StencilOp2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            StencilOp2.prototype.constructor = StencilOp2;
            StencilOp2.prototype.getDefault = function getDefault() {
              var gl2 = this.gl;
              return [
                gl2.KEEP,
                gl2.KEEP,
                gl2.KEEP
              ];
            };
            StencilOp2.prototype.set = function set(v) {
              var c = this.current;
              if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) {
                return;
              }
              this.gl.stencilOp(v[0], v[1], v[2]);
              this.current = v;
              this.dirty = false;
            };
            return StencilOp2;
          }(BaseValue);
          var StencilTest = function(BaseValue2) {
            function StencilTest2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              StencilTest2.__proto__ = BaseValue2;
            StencilTest2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            StencilTest2.prototype.constructor = StencilTest2;
            StencilTest2.prototype.getDefault = function getDefault() {
              return false;
            };
            StencilTest2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              if (v) {
                gl2.enable(gl2.STENCIL_TEST);
              } else {
                gl2.disable(gl2.STENCIL_TEST);
              }
              this.current = v;
              this.dirty = false;
            };
            return StencilTest2;
          }(BaseValue);
          var DepthRange = function(BaseValue2) {
            function DepthRange2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              DepthRange2.__proto__ = BaseValue2;
            DepthRange2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            DepthRange2.prototype.constructor = DepthRange2;
            DepthRange2.prototype.getDefault = function getDefault() {
              return [
                0,
                1
              ];
            };
            DepthRange2.prototype.set = function set(v) {
              var c = this.current;
              if (v[0] === c[0] && v[1] === c[1] && !this.dirty) {
                return;
              }
              this.gl.depthRange(v[0], v[1]);
              this.current = v;
              this.dirty = false;
            };
            return DepthRange2;
          }(BaseValue);
          var DepthTest = function(BaseValue2) {
            function DepthTest2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              DepthTest2.__proto__ = BaseValue2;
            DepthTest2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            DepthTest2.prototype.constructor = DepthTest2;
            DepthTest2.prototype.getDefault = function getDefault() {
              return false;
            };
            DepthTest2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              if (v) {
                gl2.enable(gl2.DEPTH_TEST);
              } else {
                gl2.disable(gl2.DEPTH_TEST);
              }
              this.current = v;
              this.dirty = false;
            };
            return DepthTest2;
          }(BaseValue);
          var DepthFunc = function(BaseValue2) {
            function DepthFunc2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              DepthFunc2.__proto__ = BaseValue2;
            DepthFunc2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            DepthFunc2.prototype.constructor = DepthFunc2;
            DepthFunc2.prototype.getDefault = function getDefault() {
              return this.gl.LESS;
            };
            DepthFunc2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.depthFunc(v);
              this.current = v;
              this.dirty = false;
            };
            return DepthFunc2;
          }(BaseValue);
          var Blend = function(BaseValue2) {
            function Blend2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              Blend2.__proto__ = BaseValue2;
            Blend2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            Blend2.prototype.constructor = Blend2;
            Blend2.prototype.getDefault = function getDefault() {
              return false;
            };
            Blend2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              if (v) {
                gl2.enable(gl2.BLEND);
              } else {
                gl2.disable(gl2.BLEND);
              }
              this.current = v;
              this.dirty = false;
            };
            return Blend2;
          }(BaseValue);
          var BlendFunc = function(BaseValue2) {
            function BlendFunc2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BlendFunc2.__proto__ = BaseValue2;
            BlendFunc2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BlendFunc2.prototype.constructor = BlendFunc2;
            BlendFunc2.prototype.getDefault = function getDefault() {
              var gl2 = this.gl;
              return [
                gl2.ONE,
                gl2.ZERO
              ];
            };
            BlendFunc2.prototype.set = function set(v) {
              var c = this.current;
              if (v[0] === c[0] && v[1] === c[1] && !this.dirty) {
                return;
              }
              this.gl.blendFunc(v[0], v[1]);
              this.current = v;
              this.dirty = false;
            };
            return BlendFunc2;
          }(BaseValue);
          var BlendColor = function(BaseValue2) {
            function BlendColor2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BlendColor2.__proto__ = BaseValue2;
            BlendColor2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BlendColor2.prototype.constructor = BlendColor2;
            BlendColor2.prototype.getDefault = function getDefault() {
              return performance2.Color.transparent;
            };
            BlendColor2.prototype.set = function set(v) {
              var c = this.current;
              if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) {
                return;
              }
              this.gl.blendColor(v.r, v.g, v.b, v.a);
              this.current = v;
              this.dirty = false;
            };
            return BlendColor2;
          }(BaseValue);
          var BlendEquation = function(BaseValue2) {
            function BlendEquation2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BlendEquation2.__proto__ = BaseValue2;
            BlendEquation2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BlendEquation2.prototype.constructor = BlendEquation2;
            BlendEquation2.prototype.getDefault = function getDefault() {
              return this.gl.FUNC_ADD;
            };
            BlendEquation2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.blendEquation(v);
              this.current = v;
              this.dirty = false;
            };
            return BlendEquation2;
          }(BaseValue);
          var CullFace = function(BaseValue2) {
            function CullFace2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              CullFace2.__proto__ = BaseValue2;
            CullFace2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            CullFace2.prototype.constructor = CullFace2;
            CullFace2.prototype.getDefault = function getDefault() {
              return false;
            };
            CullFace2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              if (v) {
                gl2.enable(gl2.CULL_FACE);
              } else {
                gl2.disable(gl2.CULL_FACE);
              }
              this.current = v;
              this.dirty = false;
            };
            return CullFace2;
          }(BaseValue);
          var CullFaceSide = function(BaseValue2) {
            function CullFaceSide2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              CullFaceSide2.__proto__ = BaseValue2;
            CullFaceSide2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            CullFaceSide2.prototype.constructor = CullFaceSide2;
            CullFaceSide2.prototype.getDefault = function getDefault() {
              return this.gl.BACK;
            };
            CullFaceSide2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.cullFace(v);
              this.current = v;
              this.dirty = false;
            };
            return CullFaceSide2;
          }(BaseValue);
          var FrontFace = function(BaseValue2) {
            function FrontFace2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              FrontFace2.__proto__ = BaseValue2;
            FrontFace2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            FrontFace2.prototype.constructor = FrontFace2;
            FrontFace2.prototype.getDefault = function getDefault() {
              return this.gl.CCW;
            };
            FrontFace2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.frontFace(v);
              this.current = v;
              this.dirty = false;
            };
            return FrontFace2;
          }(BaseValue);
          var Program = function(BaseValue2) {
            function Program2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              Program2.__proto__ = BaseValue2;
            Program2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            Program2.prototype.constructor = Program2;
            Program2.prototype.getDefault = function getDefault() {
              return null;
            };
            Program2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.useProgram(v);
              this.current = v;
              this.dirty = false;
            };
            return Program2;
          }(BaseValue);
          var ActiveTextureUnit = function(BaseValue2) {
            function ActiveTextureUnit2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              ActiveTextureUnit2.__proto__ = BaseValue2;
            ActiveTextureUnit2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            ActiveTextureUnit2.prototype.constructor = ActiveTextureUnit2;
            ActiveTextureUnit2.prototype.getDefault = function getDefault() {
              return this.gl.TEXTURE0;
            };
            ActiveTextureUnit2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.gl.activeTexture(v);
              this.current = v;
              this.dirty = false;
            };
            return ActiveTextureUnit2;
          }(BaseValue);
          var Viewport = function(BaseValue2) {
            function Viewport2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              Viewport2.__proto__ = BaseValue2;
            Viewport2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            Viewport2.prototype.constructor = Viewport2;
            Viewport2.prototype.getDefault = function getDefault() {
              var gl2 = this.gl;
              return [
                0,
                0,
                gl2.drawingBufferWidth,
                gl2.drawingBufferHeight
              ];
            };
            Viewport2.prototype.set = function set(v) {
              var c = this.current;
              if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) {
                return;
              }
              this.gl.viewport(v[0], v[1], v[2], v[3]);
              this.current = v;
              this.dirty = false;
            };
            return Viewport2;
          }(BaseValue);
          var BindFramebuffer = function(BaseValue2) {
            function BindFramebuffer2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BindFramebuffer2.__proto__ = BaseValue2;
            BindFramebuffer2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BindFramebuffer2.prototype.constructor = BindFramebuffer2;
            BindFramebuffer2.prototype.getDefault = function getDefault() {
              return null;
            };
            BindFramebuffer2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              gl2.bindFramebuffer(gl2.FRAMEBUFFER, v);
              this.current = v;
              this.dirty = false;
            };
            return BindFramebuffer2;
          }(BaseValue);
          var BindRenderbuffer = function(BaseValue2) {
            function BindRenderbuffer2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BindRenderbuffer2.__proto__ = BaseValue2;
            BindRenderbuffer2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BindRenderbuffer2.prototype.constructor = BindRenderbuffer2;
            BindRenderbuffer2.prototype.getDefault = function getDefault() {
              return null;
            };
            BindRenderbuffer2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              gl2.bindRenderbuffer(gl2.RENDERBUFFER, v);
              this.current = v;
              this.dirty = false;
            };
            return BindRenderbuffer2;
          }(BaseValue);
          var BindTexture = function(BaseValue2) {
            function BindTexture2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BindTexture2.__proto__ = BaseValue2;
            BindTexture2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BindTexture2.prototype.constructor = BindTexture2;
            BindTexture2.prototype.getDefault = function getDefault() {
              return null;
            };
            BindTexture2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              gl2.bindTexture(gl2.TEXTURE_2D, v);
              this.current = v;
              this.dirty = false;
            };
            return BindTexture2;
          }(BaseValue);
          var BindVertexBuffer = function(BaseValue2) {
            function BindVertexBuffer2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BindVertexBuffer2.__proto__ = BaseValue2;
            BindVertexBuffer2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BindVertexBuffer2.prototype.constructor = BindVertexBuffer2;
            BindVertexBuffer2.prototype.getDefault = function getDefault() {
              return null;
            };
            BindVertexBuffer2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              gl2.bindBuffer(gl2.ARRAY_BUFFER, v);
              this.current = v;
              this.dirty = false;
            };
            return BindVertexBuffer2;
          }(BaseValue);
          var BindElementBuffer = function(BaseValue2) {
            function BindElementBuffer2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              BindElementBuffer2.__proto__ = BaseValue2;
            BindElementBuffer2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BindElementBuffer2.prototype.constructor = BindElementBuffer2;
            BindElementBuffer2.prototype.getDefault = function getDefault() {
              return null;
            };
            BindElementBuffer2.prototype.set = function set(v) {
              var gl2 = this.gl;
              gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, v);
              this.current = v;
              this.dirty = false;
            };
            return BindElementBuffer2;
          }(BaseValue);
          var BindVertexArrayOES = function(BaseValue2) {
            function BindVertexArrayOES2(context) {
              BaseValue2.call(this, context);
              this.vao = context.extVertexArrayObject;
            }
            if (BaseValue2)
              BindVertexArrayOES2.__proto__ = BaseValue2;
            BindVertexArrayOES2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            BindVertexArrayOES2.prototype.constructor = BindVertexArrayOES2;
            BindVertexArrayOES2.prototype.getDefault = function getDefault() {
              return null;
            };
            BindVertexArrayOES2.prototype.set = function set(v) {
              if (!this.vao || v === this.current && !this.dirty) {
                return;
              }
              this.vao.bindVertexArrayOES(v);
              this.current = v;
              this.dirty = false;
            };
            return BindVertexArrayOES2;
          }(BaseValue);
          var PixelStoreUnpack = function(BaseValue2) {
            function PixelStoreUnpack2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              PixelStoreUnpack2.__proto__ = BaseValue2;
            PixelStoreUnpack2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            PixelStoreUnpack2.prototype.constructor = PixelStoreUnpack2;
            PixelStoreUnpack2.prototype.getDefault = function getDefault() {
              return 4;
            };
            PixelStoreUnpack2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              gl2.pixelStorei(gl2.UNPACK_ALIGNMENT, v);
              this.current = v;
              this.dirty = false;
            };
            return PixelStoreUnpack2;
          }(BaseValue);
          var PixelStoreUnpackPremultiplyAlpha = function(BaseValue2) {
            function PixelStoreUnpackPremultiplyAlpha2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              PixelStoreUnpackPremultiplyAlpha2.__proto__ = BaseValue2;
            PixelStoreUnpackPremultiplyAlpha2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            PixelStoreUnpackPremultiplyAlpha2.prototype.constructor = PixelStoreUnpackPremultiplyAlpha2;
            PixelStoreUnpackPremultiplyAlpha2.prototype.getDefault = function getDefault() {
              return false;
            };
            PixelStoreUnpackPremultiplyAlpha2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              gl2.pixelStorei(gl2.UNPACK_PREMULTIPLY_ALPHA_WEBGL, v);
              this.current = v;
              this.dirty = false;
            };
            return PixelStoreUnpackPremultiplyAlpha2;
          }(BaseValue);
          var PixelStoreUnpackFlipY = function(BaseValue2) {
            function PixelStoreUnpackFlipY2() {
              BaseValue2.apply(this, arguments);
            }
            if (BaseValue2)
              PixelStoreUnpackFlipY2.__proto__ = BaseValue2;
            PixelStoreUnpackFlipY2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            PixelStoreUnpackFlipY2.prototype.constructor = PixelStoreUnpackFlipY2;
            PixelStoreUnpackFlipY2.prototype.getDefault = function getDefault() {
              return false;
            };
            PixelStoreUnpackFlipY2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              var gl2 = this.gl;
              gl2.pixelStorei(gl2.UNPACK_FLIP_Y_WEBGL, v);
              this.current = v;
              this.dirty = false;
            };
            return PixelStoreUnpackFlipY2;
          }(BaseValue);
          var FramebufferAttachment = function(BaseValue2) {
            function FramebufferAttachment2(context, parent) {
              BaseValue2.call(this, context);
              this.context = context;
              this.parent = parent;
            }
            if (BaseValue2)
              FramebufferAttachment2.__proto__ = BaseValue2;
            FramebufferAttachment2.prototype = Object.create(BaseValue2 && BaseValue2.prototype);
            FramebufferAttachment2.prototype.constructor = FramebufferAttachment2;
            FramebufferAttachment2.prototype.getDefault = function getDefault() {
              return null;
            };
            return FramebufferAttachment2;
          }(BaseValue);
          var ColorAttachment = function(FramebufferAttachment2) {
            function ColorAttachment2() {
              FramebufferAttachment2.apply(this, arguments);
            }
            if (FramebufferAttachment2)
              ColorAttachment2.__proto__ = FramebufferAttachment2;
            ColorAttachment2.prototype = Object.create(FramebufferAttachment2 && FramebufferAttachment2.prototype);
            ColorAttachment2.prototype.constructor = ColorAttachment2;
            ColorAttachment2.prototype.setDirty = function setDirty() {
              this.dirty = true;
            };
            ColorAttachment2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.context.bindFramebuffer.set(this.parent);
              var gl2 = this.gl;
              gl2.framebufferTexture2D(gl2.FRAMEBUFFER, gl2.COLOR_ATTACHMENT0, gl2.TEXTURE_2D, v, 0);
              this.current = v;
              this.dirty = false;
            };
            return ColorAttachment2;
          }(FramebufferAttachment);
          var DepthAttachment = function(FramebufferAttachment2) {
            function DepthAttachment2() {
              FramebufferAttachment2.apply(this, arguments);
            }
            if (FramebufferAttachment2)
              DepthAttachment2.__proto__ = FramebufferAttachment2;
            DepthAttachment2.prototype = Object.create(FramebufferAttachment2 && FramebufferAttachment2.prototype);
            DepthAttachment2.prototype.constructor = DepthAttachment2;
            DepthAttachment2.prototype.set = function set(v) {
              if (v === this.current && !this.dirty) {
                return;
              }
              this.context.bindFramebuffer.set(this.parent);
              var gl2 = this.gl;
              gl2.framebufferRenderbuffer(gl2.FRAMEBUFFER, gl2.DEPTH_ATTACHMENT, gl2.RENDERBUFFER, v);
              this.current = v;
              this.dirty = false;
            };
            return DepthAttachment2;
          }(FramebufferAttachment);
          var Framebuffer = function Framebuffer2(context, width, height, hasDepth) {
            this.context = context;
            this.width = width;
            this.height = height;
            var gl2 = context.gl;
            var fbo = this.framebuffer = gl2.createFramebuffer();
            this.colorAttachment = new ColorAttachment(context, fbo);
            if (hasDepth) {
              this.depthAttachment = new DepthAttachment(context, fbo);
            }
          };
          Framebuffer.prototype.destroy = function destroy() {
            var gl2 = this.context.gl;
            var texture = this.colorAttachment.get();
            if (texture) {
              gl2.deleteTexture(texture);
            }
            if (this.depthAttachment) {
              var renderbuffer = this.depthAttachment.get();
              if (renderbuffer) {
                gl2.deleteRenderbuffer(renderbuffer);
              }
            }
            gl2.deleteFramebuffer(this.framebuffer);
          };
          var ALWAYS = 519;
          var DepthMode = function DepthMode2(depthFunc, depthMask, depthRange) {
            this.func = depthFunc;
            this.mask = depthMask;
            this.range = depthRange;
          };
          DepthMode.ReadOnly = false;
          DepthMode.ReadWrite = true;
          DepthMode.disabled = new DepthMode(ALWAYS, DepthMode.ReadOnly, [
            0,
            1
          ]);
          var ALWAYS$1 = 519;
          var KEEP = 7680;
          var StencilMode = function StencilMode2(test, ref, mask, fail, depthFail, pass) {
            this.test = test;
            this.ref = ref;
            this.mask = mask;
            this.fail = fail;
            this.depthFail = depthFail;
            this.pass = pass;
          };
          StencilMode.disabled = new StencilMode({
            func: ALWAYS$1,
            mask: 0
          }, 0, 0, KEEP, KEEP, KEEP);
          var ZERO = 0;
          var ONE = 1;
          var ONE_MINUS_SRC_ALPHA = 771;
          var ColorMode = function ColorMode2(blendFunction, blendColor, mask) {
            this.blendFunction = blendFunction;
            this.blendColor = blendColor;
            this.mask = mask;
          };
          ColorMode.Replace = [
            ONE,
            ZERO
          ];
          ColorMode.disabled = new ColorMode(ColorMode.Replace, performance2.Color.transparent, [
            false,
            false,
            false,
            false
          ]);
          ColorMode.unblended = new ColorMode(ColorMode.Replace, performance2.Color.transparent, [
            true,
            true,
            true,
            true
          ]);
          ColorMode.alphaBlended = new ColorMode([
            ONE,
            ONE_MINUS_SRC_ALPHA
          ], performance2.Color.transparent, [
            true,
            true,
            true,
            true
          ]);
          var BACK = 1029;
          var CCW = 2305;
          var CullFaceMode = function CullFaceMode2(enable, mode, frontFace) {
            this.enable = enable;
            this.mode = mode;
            this.frontFace = frontFace;
          };
          CullFaceMode.disabled = new CullFaceMode(false, BACK, CCW);
          CullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW);
          var Context = function Context2(gl2) {
            this.gl = gl2;
            this.extVertexArrayObject = this.gl.getExtension("OES_vertex_array_object");
            this.clearColor = new ClearColor(this);
            this.clearDepth = new ClearDepth(this);
            this.clearStencil = new ClearStencil(this);
            this.colorMask = new ColorMask(this);
            this.depthMask = new DepthMask(this);
            this.stencilMask = new StencilMask(this);
            this.stencilFunc = new StencilFunc(this);
            this.stencilOp = new StencilOp(this);
            this.stencilTest = new StencilTest(this);
            this.depthRange = new DepthRange(this);
            this.depthTest = new DepthTest(this);
            this.depthFunc = new DepthFunc(this);
            this.blend = new Blend(this);
            this.blendFunc = new BlendFunc(this);
            this.blendColor = new BlendColor(this);
            this.blendEquation = new BlendEquation(this);
            this.cullFace = new CullFace(this);
            this.cullFaceSide = new CullFaceSide(this);
            this.frontFace = new FrontFace(this);
            this.program = new Program(this);
            this.activeTexture = new ActiveTextureUnit(this);
            this.viewport = new Viewport(this);
            this.bindFramebuffer = new BindFramebuffer(this);
            this.bindRenderbuffer = new BindRenderbuffer(this);
            this.bindTexture = new BindTexture(this);
            this.bindVertexBuffer = new BindVertexBuffer(this);
            this.bindElementBuffer = new BindElementBuffer(this);
            this.bindVertexArrayOES = this.extVertexArrayObject && new BindVertexArrayOES(this);
            this.pixelStoreUnpack = new PixelStoreUnpack(this);
            this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this);
            this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this);
            this.extTextureFilterAnisotropic = gl2.getExtension("EXT_texture_filter_anisotropic") || gl2.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl2.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
            if (this.extTextureFilterAnisotropic) {
              this.extTextureFilterAnisotropicMax = gl2.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
            }
            this.extTextureHalfFloat = gl2.getExtension("OES_texture_half_float");
            if (this.extTextureHalfFloat) {
              gl2.getExtension("OES_texture_half_float_linear");
              this.extRenderToTextureHalfFloat = gl2.getExtension("EXT_color_buffer_half_float");
            }
            this.extTimerQuery = gl2.getExtension("EXT_disjoint_timer_query");
            this.maxTextureSize = gl2.getParameter(gl2.MAX_TEXTURE_SIZE);
          };
          Context.prototype.setDefault = function setDefault() {
            this.unbindVAO();
            this.clearColor.setDefault();
            this.clearDepth.setDefault();
            this.clearStencil.setDefault();
            this.colorMask.setDefault();
            this.depthMask.setDefault();
            this.stencilMask.setDefault();
            this.stencilFunc.setDefault();
            this.stencilOp.setDefault();
            this.stencilTest.setDefault();
            this.depthRange.setDefault();
            this.depthTest.setDefault();
            this.depthFunc.setDefault();
            this.blend.setDefault();
            this.blendFunc.setDefault();
            this.blendColor.setDefault();
            this.blendEquation.setDefault();
            this.cullFace.setDefault();
            this.cullFaceSide.setDefault();
            this.frontFace.setDefault();
            this.program.setDefault();
            this.activeTexture.setDefault();
            this.bindFramebuffer.setDefault();
            this.pixelStoreUnpack.setDefault();
            this.pixelStoreUnpackPremultiplyAlpha.setDefault();
            this.pixelStoreUnpackFlipY.setDefault();
          };
          Context.prototype.setDirty = function setDirty() {
            this.clearColor.dirty = true;
            this.clearDepth.dirty = true;
            this.clearStencil.dirty = true;
            this.colorMask.dirty = true;
            this.depthMask.dirty = true;
            this.stencilMask.dirty = true;
            this.stencilFunc.dirty = true;
            this.stencilOp.dirty = true;
            this.stencilTest.dirty = true;
            this.depthRange.dirty = true;
            this.depthTest.dirty = true;
            this.depthFunc.dirty = true;
            this.blend.dirty = true;
            this.blendFunc.dirty = true;
            this.blendColor.dirty = true;
            this.blendEquation.dirty = true;
            this.cullFace.dirty = true;
            this.cullFaceSide.dirty = true;
            this.frontFace.dirty = true;
            this.program.dirty = true;
            this.activeTexture.dirty = true;
            this.viewport.dirty = true;
            this.bindFramebuffer.dirty = true;
            this.bindRenderbuffer.dirty = true;
            this.bindTexture.dirty = true;
            this.bindVertexBuffer.dirty = true;
            this.bindElementBuffer.dirty = true;
            if (this.extVertexArrayObject) {
              this.bindVertexArrayOES.dirty = true;
            }
            this.pixelStoreUnpack.dirty = true;
            this.pixelStoreUnpackPremultiplyAlpha.dirty = true;
            this.pixelStoreUnpackFlipY.dirty = true;
          };
          Context.prototype.createIndexBuffer = function createIndexBuffer(array, dynamicDraw) {
            return new IndexBuffer(this, array, dynamicDraw);
          };
          Context.prototype.createVertexBuffer = function createVertexBuffer(array, attributes, dynamicDraw) {
            return new VertexBuffer(this, array, attributes, dynamicDraw);
          };
          Context.prototype.createRenderbuffer = function createRenderbuffer(storageFormat, width, height) {
            var gl2 = this.gl;
            var rbo = gl2.createRenderbuffer();
            this.bindRenderbuffer.set(rbo);
            gl2.renderbufferStorage(gl2.RENDERBUFFER, storageFormat, width, height);
            this.bindRenderbuffer.set(null);
            return rbo;
          };
          Context.prototype.createFramebuffer = function createFramebuffer(width, height, hasDepth) {
            return new Framebuffer(this, width, height, hasDepth);
          };
          Context.prototype.clear = function clear(ref) {
            var color2 = ref.color;
            var depth = ref.depth;
            var gl2 = this.gl;
            var mask = 0;
            if (color2) {
              mask |= gl2.COLOR_BUFFER_BIT;
              this.clearColor.set(color2);
              this.colorMask.set([
                true,
                true,
                true,
                true
              ]);
            }
            if (typeof depth !== "undefined") {
              mask |= gl2.DEPTH_BUFFER_BIT;
              this.depthRange.set([
                0,
                1
              ]);
              this.clearDepth.set(depth);
              this.depthMask.set(true);
            }
            gl2.clear(mask);
          };
          Context.prototype.setCullFace = function setCullFace(cullFaceMode) {
            if (cullFaceMode.enable === false) {
              this.cullFace.set(false);
            } else {
              this.cullFace.set(true);
              this.cullFaceSide.set(cullFaceMode.mode);
              this.frontFace.set(cullFaceMode.frontFace);
            }
          };
          Context.prototype.setDepthMode = function setDepthMode(depthMode) {
            if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) {
              this.depthTest.set(false);
            } else {
              this.depthTest.set(true);
              this.depthFunc.set(depthMode.func);
              this.depthMask.set(depthMode.mask);
              this.depthRange.set(depthMode.range);
            }
          };
          Context.prototype.setStencilMode = function setStencilMode(stencilMode) {
            if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) {
              this.stencilTest.set(false);
            } else {
              this.stencilTest.set(true);
              this.stencilMask.set(stencilMode.mask);
              this.stencilOp.set([
                stencilMode.fail,
                stencilMode.depthFail,
                stencilMode.pass
              ]);
              this.stencilFunc.set({
                func: stencilMode.test.func,
                ref: stencilMode.ref,
                mask: stencilMode.test.mask
              });
            }
          };
          Context.prototype.setColorMode = function setColorMode(colorMode) {
            if (performance2.deepEqual(colorMode.blendFunction, ColorMode.Replace)) {
              this.blend.set(false);
            } else {
              this.blend.set(true);
              this.blendFunc.set(colorMode.blendFunction);
              this.blendColor.set(colorMode.blendColor);
            }
            this.colorMask.set(colorMode.mask);
          };
          Context.prototype.unbindVAO = function unbindVAO() {
            if (this.extVertexArrayObject) {
              this.bindVertexArrayOES.set(null);
            }
          };
          var SourceCache = function(Evented) {
            function SourceCache2(id, options, dispatcher) {
              var this$1 = this;
              Evented.call(this);
              this.id = id;
              this.dispatcher = dispatcher;
              this.on("data", function(e) {
                if (e.dataType === "source" && e.sourceDataType === "metadata") {
                  this$1._sourceLoaded = true;
                }
                if (this$1._sourceLoaded && !this$1._paused && e.dataType === "source" && e.sourceDataType === "content") {
                  this$1.reload();
                  if (this$1.transform) {
                    this$1.update(this$1.transform);
                  }
                }
              });
              this.on("error", function() {
                this$1._sourceErrored = true;
              });
              this._source = create(id, options, dispatcher, this);
              this._tiles = {};
              this._cache = new TileCache(0, this._unloadTile.bind(this));
              this._timers = {};
              this._cacheTimers = {};
              this._maxTileCacheSize = null;
              this._loadedParentTiles = {};
              this._coveredTiles = {};
              this._state = new performance2.SourceFeatureState();
            }
            if (Evented)
              SourceCache2.__proto__ = Evented;
            SourceCache2.prototype = Object.create(Evented && Evented.prototype);
            SourceCache2.prototype.constructor = SourceCache2;
            SourceCache2.prototype.onAdd = function onAdd(map) {
              this.map = map;
              this._maxTileCacheSize = map ? map._maxTileCacheSize : null;
              if (this._source && this._source.onAdd) {
                this._source.onAdd(map);
              }
            };
            SourceCache2.prototype.onRemove = function onRemove(map) {
              if (this._source && this._source.onRemove) {
                this._source.onRemove(map);
              }
            };
            SourceCache2.prototype.loaded = function loaded() {
              if (this._sourceErrored) {
                return true;
              }
              if (!this._sourceLoaded) {
                return false;
              }
              if (!this._source.loaded()) {
                return false;
              }
              for (var t in this._tiles) {
                var tile = this._tiles[t];
                if (tile.state !== "loaded" && tile.state !== "errored") {
                  return false;
                }
              }
              return true;
            };
            SourceCache2.prototype.getSource = function getSource() {
              return this._source;
            };
            SourceCache2.prototype.pause = function pause() {
              this._paused = true;
            };
            SourceCache2.prototype.resume = function resume() {
              if (!this._paused) {
                return;
              }
              var shouldReload = this._shouldReloadOnResume;
              this._paused = false;
              this._shouldReloadOnResume = false;
              if (shouldReload) {
                this.reload();
              }
              if (this.transform) {
                this.update(this.transform);
              }
            };
            SourceCache2.prototype._loadTile = function _loadTile(tile, callback) {
              return this._source.loadTile(tile, callback);
            };
            SourceCache2.prototype._unloadTile = function _unloadTile(tile) {
              if (this._source.unloadTile) {
                return this._source.unloadTile(tile, function() {
                });
              }
            };
            SourceCache2.prototype._abortTile = function _abortTile(tile) {
              if (this._source.abortTile) {
                return this._source.abortTile(tile, function() {
                });
              }
            };
            SourceCache2.prototype.serialize = function serialize() {
              return this._source.serialize();
            };
            SourceCache2.prototype.prepare = function prepare(context) {
              if (this._source.prepare) {
                this._source.prepare();
              }
              this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null);
              for (var i in this._tiles) {
                var tile = this._tiles[i];
                tile.upload(context);
                tile.prepare(this.map.style.imageManager);
              }
            };
            SourceCache2.prototype.getIds = function getIds() {
              return performance2.values(this._tiles).map(function(tile) {
                return tile.tileID;
              }).sort(compareTileId).map(function(id) {
                return id.key;
              });
            };
            SourceCache2.prototype.getRenderableIds = function getRenderableIds(symbolLayer) {
              var this$1 = this;
              var renderables = [];
              for (var id in this._tiles) {
                if (this._isIdRenderable(id, symbolLayer)) {
                  renderables.push(this._tiles[id]);
                }
              }
              if (symbolLayer) {
                return renderables.sort(function(a_, b_) {
                  var a = a_.tileID;
                  var b = b_.tileID;
                  var rotatedA = new performance2.Point(a.canonical.x, a.canonical.y)._rotate(this$1.transform.angle);
                  var rotatedB = new performance2.Point(b.canonical.x, b.canonical.y)._rotate(this$1.transform.angle);
                  return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;
                }).map(function(tile) {
                  return tile.tileID.key;
                });
              }
              return renderables.map(function(tile) {
                return tile.tileID;
              }).sort(compareTileId).map(function(id2) {
                return id2.key;
              });
            };
            SourceCache2.prototype.hasRenderableParent = function hasRenderableParent(tileID) {
              var parentTile = this.findLoadedParent(tileID, 0);
              if (parentTile) {
                return this._isIdRenderable(parentTile.tileID.key);
              }
              return false;
            };
            SourceCache2.prototype._isIdRenderable = function _isIdRenderable(id, symbolLayer) {
              return this._tiles[id] && this._tiles[id].hasData() && !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade());
            };
            SourceCache2.prototype.reload = function reload() {
              if (this._paused) {
                this._shouldReloadOnResume = true;
                return;
              }
              this._cache.reset();
              for (var i in this._tiles) {
                if (this._tiles[i].state !== "errored") {
                  this._reloadTile(i, "reloading");
                }
              }
            };
            SourceCache2.prototype._reloadTile = function _reloadTile(id, state) {
              var tile = this._tiles[id];
              if (!tile) {
                return;
              }
              if (tile.state !== "loading") {
                tile.state = state;
              }
              this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state));
            };
            SourceCache2.prototype._tileLoaded = function _tileLoaded(tile, id, previousState, err) {
              if (err) {
                tile.state = "errored";
                if (err.status !== 404) {
                  this._source.fire(new performance2.ErrorEvent(err, { tile }));
                } else {
                  this.update(this.transform);
                }
                return;
              }
              tile.timeAdded = performance2.browser.now();
              if (previousState === "expired") {
                tile.refreshedUponExpiration = true;
              }
              this._setTileReloadTimer(id, tile);
              if (this.getSource().type === "raster-dem" && tile.dem) {
                this._backfillDEM(tile);
              }
              this._state.initializeTileState(tile, this.map ? this.map.painter : null);
              this._source.fire(new performance2.Event("data", {
                dataType: "source",
                tile,
                coord: tile.tileID
              }));
            };
            SourceCache2.prototype._backfillDEM = function _backfillDEM(tile) {
              var renderables = this.getRenderableIds();
              for (var i = 0; i < renderables.length; i++) {
                var borderId = renderables[i];
                if (tile.neighboringTiles && tile.neighboringTiles[borderId]) {
                  var borderTile = this.getTileByID(borderId);
                  fillBorder(tile, borderTile);
                  fillBorder(borderTile, tile);
                }
              }
              function fillBorder(tile2, borderTile2) {
                tile2.needsHillshadePrepare = true;
                var dx = borderTile2.tileID.canonical.x - tile2.tileID.canonical.x;
                var dy = borderTile2.tileID.canonical.y - tile2.tileID.canonical.y;
                var dim = Math.pow(2, tile2.tileID.canonical.z);
                var borderId2 = borderTile2.tileID.key;
                if (dx === 0 && dy === 0) {
                  return;
                }
                if (Math.abs(dy) > 1) {
                  return;
                }
                if (Math.abs(dx) > 1) {
                  if (Math.abs(dx + dim) === 1) {
                    dx += dim;
                  } else if (Math.abs(dx - dim) === 1) {
                    dx -= dim;
                  }
                }
                if (!borderTile2.dem || !tile2.dem) {
                  return;
                }
                tile2.dem.backfillBorder(borderTile2.dem, dx, dy);
                if (tile2.neighboringTiles && tile2.neighboringTiles[borderId2]) {
                  tile2.neighboringTiles[borderId2].backfilled = true;
                }
              }
            };
            SourceCache2.prototype.getTile = function getTile(tileID) {
              return this.getTileByID(tileID.key);
            };
            SourceCache2.prototype.getTileByID = function getTileByID(id) {
              return this._tiles[id];
            };
            SourceCache2.prototype._retainLoadedChildren = function _retainLoadedChildren(idealTiles, zoom, maxCoveringZoom, retain) {
              for (var id in this._tiles) {
                var tile = this._tiles[id];
                if (retain[id] || !tile.hasData() || tile.tileID.overscaledZ <= zoom || tile.tileID.overscaledZ > maxCoveringZoom) {
                  continue;
                }
                var topmostLoadedID = tile.tileID;
                while (tile && tile.tileID.overscaledZ > zoom + 1) {
                  var parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1);
                  tile = this._tiles[parentID.key];
                  if (tile && tile.hasData()) {
                    topmostLoadedID = parentID;
                  }
                }
                var tileID = topmostLoadedID;
                while (tileID.overscaledZ > zoom) {
                  tileID = tileID.scaledTo(tileID.overscaledZ - 1);
                  if (idealTiles[tileID.key]) {
                    retain[topmostLoadedID.key] = topmostLoadedID;
                    break;
                  }
                }
              }
            };
            SourceCache2.prototype.findLoadedParent = function findLoadedParent(tileID, minCoveringZoom) {
              if (tileID.key in this._loadedParentTiles) {
                var parent = this._loadedParentTiles[tileID.key];
                if (parent && parent.tileID.overscaledZ >= minCoveringZoom) {
                  return parent;
                } else {
                  return null;
                }
              }
              for (var z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) {
                var parentTileID = tileID.scaledTo(z);
                var tile = this._getLoadedTile(parentTileID);
                if (tile) {
                  return tile;
                }
              }
            };
            SourceCache2.prototype._getLoadedTile = function _getLoadedTile(tileID) {
              var tile = this._tiles[tileID.key];
              if (tile && tile.hasData()) {
                return tile;
              }
              var cachedTile = this._cache.getByKey(tileID.wrapped().key);
              return cachedTile;
            };
            SourceCache2.prototype.updateCacheSize = function updateCacheSize(transform) {
              var widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1;
              var heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1;
              var approxTilesInView = widthInTiles * heightInTiles;
              var commonZoomRange = 5;
              var viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);
              var maxSize = typeof this._maxTileCacheSize === "number" ? Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;
              this._cache.setMaxSize(maxSize);
            };
            SourceCache2.prototype.handleWrapJump = function handleWrapJump(lng) {
              var prevLng = this._prevLng === void 0 ? lng : this._prevLng;
              var lngDifference = lng - prevLng;
              var worldDifference = lngDifference / 360;
              var wrapDelta = Math.round(worldDifference);
              this._prevLng = lng;
              if (wrapDelta) {
                var tiles = {};
                for (var key in this._tiles) {
                  var tile = this._tiles[key];
                  tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);
                  tiles[tile.tileID.key] = tile;
                }
                this._tiles = tiles;
                for (var id in this._timers) {
                  clearTimeout(this._timers[id]);
                  delete this._timers[id];
                }
                for (var id$1 in this._tiles) {
                  var tile$1 = this._tiles[id$1];
                  this._setTileReloadTimer(id$1, tile$1);
                }
              }
            };
            SourceCache2.prototype.update = function update(transform) {
              var this$1 = this;
              this.transform = transform;
              if (!this._sourceLoaded || this._paused) {
                return;
              }
              this.updateCacheSize(transform);
              this.handleWrapJump(this.transform.center.lng);
              this._coveredTiles = {};
              var idealTileIDs;
              if (!this.used) {
                idealTileIDs = [];
              } else if (this._source.tileID) {
                idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(unwrapped) {
                  return new performance2.OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y);
                });
              } else {
                idealTileIDs = transform.coveringTiles({
                  tileSize: this._source.tileSize,
                  minzoom: this._source.minzoom,
                  maxzoom: this._source.maxzoom,
                  roundZoom: this._source.roundZoom,
                  reparseOverscaled: this._source.reparseOverscaled
                });
                if (this._source.hasTile) {
                  idealTileIDs = idealTileIDs.filter(function(coord) {
                    return this$1._source.hasTile(coord);
                  });
                }
              }
              var zoom = transform.coveringZoomLevel(this._source);
              var minCoveringZoom = Math.max(zoom - SourceCache2.maxOverzooming, this._source.minzoom);
              var maxCoveringZoom = Math.max(zoom + SourceCache2.maxUnderzooming, this._source.minzoom);
              var retain = this._updateRetainedTiles(idealTileIDs, zoom);
              if (isRasterType(this._source.type)) {
                var parentsForFading = {};
                var fadingTiles = {};
                var ids = Object.keys(retain);
                for (var i = 0, list = ids; i < list.length; i += 1) {
                  var id = list[i];
                  var tileID = retain[id];
                  var tile = this._tiles[id];
                  if (!tile || tile.fadeEndTime && tile.fadeEndTime <= performance2.browser.now()) {
                    continue;
                  }
                  var parentTile = this.findLoadedParent(tileID, minCoveringZoom);
                  if (parentTile) {
                    this._addTile(parentTile.tileID);
                    parentsForFading[parentTile.tileID.key] = parentTile.tileID;
                  }
                  fadingTiles[id] = tileID;
                }
                this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain);
                for (var id$1 in parentsForFading) {
                  if (!retain[id$1]) {
                    this._coveredTiles[id$1] = true;
                    retain[id$1] = parentsForFading[id$1];
                  }
                }
              }
              for (var retainedId in retain) {
                this._tiles[retainedId].clearFadeHold();
              }
              var remove = performance2.keysDifference(this._tiles, retain);
              for (var i$1 = 0, list$1 = remove; i$1 < list$1.length; i$1 += 1) {
                var tileID$1 = list$1[i$1];
                var tile$1 = this._tiles[tileID$1];
                if (tile$1.hasSymbolBuckets && !tile$1.holdingForFade()) {
                  tile$1.setHoldDuration(this.map._fadeDuration);
                } else if (!tile$1.hasSymbolBuckets || tile$1.symbolFadeFinished()) {
                  this._removeTile(tileID$1);
                }
              }
              this._updateLoadedParentTileCache();
            };
            SourceCache2.prototype.releaseSymbolFadeTiles = function releaseSymbolFadeTiles() {
              for (var id in this._tiles) {
                if (this._tiles[id].holdingForFade()) {
                  this._removeTile(id);
                }
              }
            };
            SourceCache2.prototype._updateRetainedTiles = function _updateRetainedTiles(idealTileIDs, zoom) {
              var retain = {};
              var checked = {};
              var minCoveringZoom = Math.max(zoom - SourceCache2.maxOverzooming, this._source.minzoom);
              var maxCoveringZoom = Math.max(zoom + SourceCache2.maxUnderzooming, this._source.minzoom);
              var missingTiles = {};
              for (var i = 0, list = idealTileIDs; i < list.length; i += 1) {
                var tileID = list[i];
                var tile = this._addTile(tileID);
                retain[tileID.key] = tileID;
                if (tile.hasData()) {
                  continue;
                }
                if (zoom < this._source.maxzoom) {
                  missingTiles[tileID.key] = tileID;
                }
              }
              this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain);
              for (var i$1 = 0, list$1 = idealTileIDs; i$1 < list$1.length; i$1 += 1) {
                var tileID$1 = list$1[i$1];
                var tile$1 = this._tiles[tileID$1.key];
                if (tile$1.hasData()) {
                  continue;
                }
                if (zoom + 1 > this._source.maxzoom) {
                  var childCoord = tileID$1.children(this._source.maxzoom)[0];
                  var childTile = this.getTile(childCoord);
                  if (!!childTile && childTile.hasData()) {
                    retain[childCoord.key] = childCoord;
                    continue;
                  }
                } else {
                  var children = tileID$1.children(this._source.maxzoom);
                  if (retain[children[0].key] && retain[children[1].key] && retain[children[2].key] && retain[children[3].key]) {
                    continue;
                  }
                }
                var parentWasRequested = tile$1.wasRequested();
                for (var overscaledZ = tileID$1.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {
                  var parentId = tileID$1.scaledTo(overscaledZ);
                  if (checked[parentId.key]) {
                    break;
                  }
                  checked[parentId.key] = true;
                  tile$1 = this.getTile(parentId);
                  if (!tile$1 && parentWasRequested) {
                    tile$1 = this._addTile(parentId);
                  }
                  if (tile$1) {
                    retain[parentId.key] = parentId;
                    parentWasRequested = tile$1.wasRequested();
                    if (tile$1.hasData()) {
                      break;
                    }
                  }
                }
              }
              return retain;
            };
            SourceCache2.prototype._updateLoadedParentTileCache = function _updateLoadedParentTileCache() {
              this._loadedParentTiles = {};
              for (var tileKey in this._tiles) {
                var path = [];
                var parentTile = void 0;
                var currentId = this._tiles[tileKey].tileID;
                while (currentId.overscaledZ > 0) {
                  if (currentId.key in this._loadedParentTiles) {
                    parentTile = this._loadedParentTiles[currentId.key];
                    break;
                  }
                  path.push(currentId.key);
                  var parentId = currentId.scaledTo(currentId.overscaledZ - 1);
                  parentTile = this._getLoadedTile(parentId);
                  if (parentTile) {
                    break;
                  }
                  currentId = parentId;
                }
                for (var i = 0, list = path; i < list.length; i += 1) {
                  var key = list[i];
                  this._loadedParentTiles[key] = parentTile;
                }
              }
            };
            SourceCache2.prototype._addTile = function _addTile(tileID) {
              var tile = this._tiles[tileID.key];
              if (tile) {
                return tile;
              }
              tile = this._cache.getAndRemove(tileID);
              if (tile) {
                this._setTileReloadTimer(tileID.key, tile);
                tile.tileID = tileID;
                this._state.initializeTileState(tile, this.map ? this.map.painter : null);
                if (this._cacheTimers[tileID.key]) {
                  clearTimeout(this._cacheTimers[tileID.key]);
                  delete this._cacheTimers[tileID.key];
                  this._setTileReloadTimer(tileID.key, tile);
                }
              }
              var cached = Boolean(tile);
              if (!cached) {
                tile = new performance2.Tile(tileID, this._source.tileSize * tileID.overscaleFactor());
                this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));
              }
              if (!tile) {
                return null;
              }
              tile.uses++;
              this._tiles[tileID.key] = tile;
              if (!cached) {
                this._source.fire(new performance2.Event("dataloading", {
                  tile,
                  coord: tile.tileID,
                  dataType: "source"
                }));
              }
              return tile;
            };
            SourceCache2.prototype._setTileReloadTimer = function _setTileReloadTimer(id, tile) {
              var this$1 = this;
              if (id in this._timers) {
                clearTimeout(this._timers[id]);
                delete this._timers[id];
              }
              var expiryTimeout = tile.getExpiryTimeout();
              if (expiryTimeout) {
                this._timers[id] = setTimeout(function() {
                  this$1._reloadTile(id, "expired");
                  delete this$1._timers[id];
                }, expiryTimeout);
              }
            };
            SourceCache2.prototype._removeTile = function _removeTile(id) {
              var tile = this._tiles[id];
              if (!tile) {
                return;
              }
              tile.uses--;
              delete this._tiles[id];
              if (this._timers[id]) {
                clearTimeout(this._timers[id]);
                delete this._timers[id];
              }
              if (tile.uses > 0) {
                return;
              }
              if (tile.hasData() && tile.state !== "reloading") {
                this._cache.add(tile.tileID, tile, tile.getExpiryTimeout());
              } else {
                tile.aborted = true;
                this._abortTile(tile);
                this._unloadTile(tile);
              }
            };
            SourceCache2.prototype.clearTiles = function clearTiles() {
              this._shouldReloadOnResume = false;
              this._paused = false;
              for (var id in this._tiles) {
                this._removeTile(id);
              }
              this._cache.reset();
            };
            SourceCache2.prototype.tilesIn = function tilesIn(pointQueryGeometry, maxPitchScaleFactor, has3DLayer) {
              var this$1 = this;
              var tileResults = [];
              var transform = this.transform;
              if (!transform) {
                return tileResults;
              }
              var cameraPointQueryGeometry = has3DLayer ? transform.getCameraQueryGeometry(pointQueryGeometry) : pointQueryGeometry;
              var queryGeometry = pointQueryGeometry.map(function(p2) {
                return transform.pointCoordinate(p2);
              });
              var cameraQueryGeometry = cameraPointQueryGeometry.map(function(p2) {
                return transform.pointCoordinate(p2);
              });
              var ids = this.getIds();
              var minX = Infinity;
              var minY = Infinity;
              var maxX = -Infinity;
              var maxY = -Infinity;
              for (var i$1 = 0, list = cameraQueryGeometry; i$1 < list.length; i$1 += 1) {
                var p = list[i$1];
                minX = Math.min(minX, p.x);
                minY = Math.min(minY, p.y);
                maxX = Math.max(maxX, p.x);
                maxY = Math.max(maxY, p.y);
              }
              var loop = function(i2) {
                var tile = this$1._tiles[ids[i2]];
                if (tile.holdingForFade()) {
                  return;
                }
                var tileID = tile.tileID;
                var scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);
                var queryPadding = maxPitchScaleFactor * tile.queryPadding * performance2.EXTENT / tile.tileSize / scale;
                var tileSpaceBounds = [
                  tileID.getTilePoint(new performance2.MercatorCoordinate(minX, minY)),
                  tileID.getTilePoint(new performance2.MercatorCoordinate(maxX, maxY))
                ];
                if (tileSpaceBounds[0].x - queryPadding < performance2.EXTENT && tileSpaceBounds[0].y - queryPadding < performance2.EXTENT && tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) {
                  var tileSpaceQueryGeometry = queryGeometry.map(function(c) {
                    return tileID.getTilePoint(c);
                  });
                  var tileSpaceCameraQueryGeometry = cameraQueryGeometry.map(function(c) {
                    return tileID.getTilePoint(c);
                  });
                  tileResults.push({
                    tile,
                    tileID,
                    queryGeometry: tileSpaceQueryGeometry,
                    cameraQueryGeometry: tileSpaceCameraQueryGeometry,
                    scale
                  });
                }
              };
              for (var i = 0; i < ids.length; i++)
                loop(i);
              return tileResults;
            };
            SourceCache2.prototype.getVisibleCoordinates = function getVisibleCoordinates(symbolLayer) {
              var this$1 = this;
              var coords = this.getRenderableIds(symbolLayer).map(function(id) {
                return this$1._tiles[id].tileID;
              });
              for (var i = 0, list = coords; i < list.length; i += 1) {
                var coord = list[i];
                coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped());
              }
              return coords;
            };
            SourceCache2.prototype.hasTransition = function hasTransition() {
              if (this._source.hasTransition()) {
                return true;
              }
              if (isRasterType(this._source.type)) {
                for (var id in this._tiles) {
                  var tile = this._tiles[id];
                  if (tile.fadeEndTime !== void 0 && tile.fadeEndTime >= performance2.browser.now()) {
                    return true;
                  }
                }
              }
              return false;
            };
            SourceCache2.prototype.setFeatureState = function setFeatureState(sourceLayer, featureId, state) {
              sourceLayer = sourceLayer || "_geojsonTileLayer";
              this._state.updateState(sourceLayer, featureId, state);
            };
            SourceCache2.prototype.removeFeatureState = function removeFeatureState(sourceLayer, featureId, key) {
              sourceLayer = sourceLayer || "_geojsonTileLayer";
              this._state.removeFeatureState(sourceLayer, featureId, key);
            };
            SourceCache2.prototype.getFeatureState = function getFeatureState(sourceLayer, featureId) {
              sourceLayer = sourceLayer || "_geojsonTileLayer";
              return this._state.getState(sourceLayer, featureId);
            };
            SourceCache2.prototype.setDependencies = function setDependencies(tileKey, namespace, dependencies) {
              var tile = this._tiles[tileKey];
              if (tile) {
                tile.setDependencies(namespace, dependencies);
              }
            };
            SourceCache2.prototype.reloadTilesForDependencies = function reloadTilesForDependencies(namespaces, keys) {
              for (var id in this._tiles) {
                var tile = this._tiles[id];
                if (tile.hasDependency(namespaces, keys)) {
                  this._reloadTile(id, "reloading");
                }
              }
              this._cache.filter(function(tile2) {
                return !tile2.hasDependency(namespaces, keys);
              });
            };
            return SourceCache2;
          }(performance2.Evented);
          SourceCache.maxOverzooming = 10;
          SourceCache.maxUnderzooming = 3;
          function compareTileId(a, b) {
            var aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0);
            var bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0);
            return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x;
          }
          function isRasterType(type) {
            return type === "raster" || type === "image" || type === "video";
          }
          function WebWorker() {
            return new performance2.window.Worker(exported.workerUrl);
          }
          var PRELOAD_POOL_ID = "mapboxgl_preloaded_worker_pool";
          var WorkerPool = function WorkerPool2() {
            this.active = {};
          };
          WorkerPool.prototype.acquire = function acquire(mapId) {
            if (!this.workers) {
              this.workers = [];
              while (this.workers.length < WorkerPool.workerCount) {
                this.workers.push(new WebWorker());
              }
            }
            this.active[mapId] = true;
            return this.workers.slice();
          };
          WorkerPool.prototype.release = function release(mapId) {
            delete this.active[mapId];
            if (this.numActive() === 0) {
              this.workers.forEach(function(w) {
                w.terminate();
              });
              this.workers = null;
            }
          };
          WorkerPool.prototype.isPreloaded = function isPreloaded() {
            return !!this.active[PRELOAD_POOL_ID];
          };
          WorkerPool.prototype.numActive = function numActive() {
            return Object.keys(this.active).length;
          };
          var availableLogicalProcessors = Math.floor(performance2.browser.hardwareConcurrency / 2);
          WorkerPool.workerCount = Math.max(Math.min(availableLogicalProcessors, 6), 1);
          var globalWorkerPool;
          function getGlobalWorkerPool() {
            if (!globalWorkerPool) {
              globalWorkerPool = new WorkerPool();
            }
            return globalWorkerPool;
          }
          function prewarm() {
            var workerPool = getGlobalWorkerPool();
            workerPool.acquire(PRELOAD_POOL_ID);
          }
          function clearPrewarmedResources() {
            var pool = globalWorkerPool;
            if (pool) {
              if (pool.isPreloaded() && pool.numActive() === 1) {
                pool.release(PRELOAD_POOL_ID);
                globalWorkerPool = null;
              } else {
                console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()");
              }
            }
          }
          function deref(layer, parent) {
            var result = {};
            for (var k in layer) {
              if (k !== "ref") {
                result[k] = layer[k];
              }
            }
            performance2.refProperties.forEach(function(k2) {
              if (k2 in parent) {
                result[k2] = parent[k2];
              }
            });
            return result;
          }
          function derefLayers(layers) {
            layers = layers.slice();
            var map = /* @__PURE__ */ Object.create(null);
            for (var i = 0; i < layers.length; i++) {
              map[layers[i].id] = layers[i];
            }
            for (var i$1 = 0; i$1 < layers.length; i$1++) {
              if ("ref" in layers[i$1]) {
                layers[i$1] = deref(layers[i$1], map[layers[i$1].ref]);
              }
            }
            return layers;
          }
          function emptyStyle() {
            var style = {};
            var version = performance2.styleSpec["$version"];
            for (var styleKey in performance2.styleSpec["$root"]) {
              var spec = performance2.styleSpec["$root"][styleKey];
              if (spec.required) {
                var value = null;
                if (styleKey === "version") {
                  value = version;
                } else {
                  if (spec.type === "array") {
                    value = [];
                  } else {
                    value = {};
                  }
                }
                if (value != null) {
                  style[styleKey] = value;
                }
              }
            }
            return style;
          }
          var operations = {
            setStyle: "setStyle",
            addLayer: "addLayer",
            removeLayer: "removeLayer",
            setPaintProperty: "setPaintProperty",
            setLayoutProperty: "setLayoutProperty",
            setFilter: "setFilter",
            addSource: "addSource",
            removeSource: "removeSource",
            setGeoJSONSourceData: "setGeoJSONSourceData",
            setLayerZoomRange: "setLayerZoomRange",
            setLayerProperty: "setLayerProperty",
            setCenter: "setCenter",
            setZoom: "setZoom",
            setBearing: "setBearing",
            setPitch: "setPitch",
            setSprite: "setSprite",
            setGlyphs: "setGlyphs",
            setTransition: "setTransition",
            setLight: "setLight"
          };
          function addSource(sourceId, after, commands) {
            commands.push({
              command: operations.addSource,
              args: [
                sourceId,
                after[sourceId]
              ]
            });
          }
          function removeSource(sourceId, commands, sourcesRemoved) {
            commands.push({
              command: operations.removeSource,
              args: [sourceId]
            });
            sourcesRemoved[sourceId] = true;
          }
          function updateSource(sourceId, after, commands, sourcesRemoved) {
            removeSource(sourceId, commands, sourcesRemoved);
            addSource(sourceId, after, commands);
          }
          function canUpdateGeoJSON(before, after, sourceId) {
            var prop;
            for (prop in before[sourceId]) {
              if (!before[sourceId].hasOwnProperty(prop)) {
                continue;
              }
              if (prop !== "data" && !performance2.deepEqual(before[sourceId][prop], after[sourceId][prop])) {
                return false;
              }
            }
            for (prop in after[sourceId]) {
              if (!after[sourceId].hasOwnProperty(prop)) {
                continue;
              }
              if (prop !== "data" && !performance2.deepEqual(before[sourceId][prop], after[sourceId][prop])) {
                return false;
              }
            }
            return true;
          }
          function diffSources(before, after, commands, sourcesRemoved) {
            before = before || {};
            after = after || {};
            var sourceId;
            for (sourceId in before) {
              if (!before.hasOwnProperty(sourceId)) {
                continue;
              }
              if (!after.hasOwnProperty(sourceId)) {
                removeSource(sourceId, commands, sourcesRemoved);
              }
            }
            for (sourceId in after) {
              if (!after.hasOwnProperty(sourceId)) {
                continue;
              }
              if (!before.hasOwnProperty(sourceId)) {
                addSource(sourceId, after, commands);
              } else if (!performance2.deepEqual(before[sourceId], after[sourceId])) {
                if (before[sourceId].type === "geojson" && after[sourceId].type === "geojson" && canUpdateGeoJSON(before, after, sourceId)) {
                  commands.push({
                    command: operations.setGeoJSONSourceData,
                    args: [
                      sourceId,
                      after[sourceId].data
                    ]
                  });
                } else {
                  updateSource(sourceId, after, commands, sourcesRemoved);
                }
              }
            }
          }
          function diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {
            before = before || {};
            after = after || {};
            var prop;
            for (prop in before) {
              if (!before.hasOwnProperty(prop)) {
                continue;
              }
              if (!performance2.deepEqual(before[prop], after[prop])) {
                commands.push({
                  command,
                  args: [
                    layerId,
                    prop,
                    after[prop],
                    klass
                  ]
                });
              }
            }
            for (prop in after) {
              if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) {
                continue;
              }
              if (!performance2.deepEqual(before[prop], after[prop])) {
                commands.push({
                  command,
                  args: [
                    layerId,
                    prop,
                    after[prop],
                    klass
                  ]
                });
              }
            }
          }
          function pluckId(layer) {
            return layer.id;
          }
          function indexById(group, layer) {
            group[layer.id] = layer;
            return group;
          }
          function diffLayers(before, after, commands) {
            before = before || [];
            after = after || [];
            var beforeOrder = before.map(pluckId);
            var afterOrder = after.map(pluckId);
            var beforeIndex = before.reduce(indexById, {});
            var afterIndex = after.reduce(indexById, {});
            var tracker = beforeOrder.slice();
            var clean = /* @__PURE__ */ Object.create(null);
            var i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;
            for (i = 0, d = 0; i < beforeOrder.length; i++) {
              layerId = beforeOrder[i];
              if (!afterIndex.hasOwnProperty(layerId)) {
                commands.push({
                  command: operations.removeLayer,
                  args: [layerId]
                });
                tracker.splice(tracker.indexOf(layerId, d), 1);
              } else {
                d++;
              }
            }
            for (i = 0, d = 0; i < afterOrder.length; i++) {
              layerId = afterOrder[afterOrder.length - 1 - i];
              if (tracker[tracker.length - 1 - i] === layerId) {
                continue;
              }
              if (beforeIndex.hasOwnProperty(layerId)) {
                commands.push({
                  command: operations.removeLayer,
                  args: [layerId]
                });
                tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);
              } else {
                d++;
              }
              insertBeforeLayerId = tracker[tracker.length - i];
              commands.push({
                command: operations.addLayer,
                args: [
                  afterIndex[layerId],
                  insertBeforeLayerId
                ]
              });
              tracker.splice(tracker.length - i, 0, layerId);
              clean[layerId] = true;
            }
            for (i = 0; i < afterOrder.length; i++) {
              layerId = afterOrder[i];
              beforeLayer = beforeIndex[layerId];
              afterLayer = afterIndex[layerId];
              if (clean[layerId] || performance2.deepEqual(beforeLayer, afterLayer)) {
                continue;
              }
              if (!performance2.deepEqual(beforeLayer.source, afterLayer.source) || !performance2.deepEqual(beforeLayer["source-layer"], afterLayer["source-layer"]) || !performance2.deepEqual(beforeLayer.type, afterLayer.type)) {
                commands.push({
                  command: operations.removeLayer,
                  args: [layerId]
                });
                insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];
                commands.push({
                  command: operations.addLayer,
                  args: [
                    afterLayer,
                    insertBeforeLayerId
                  ]
                });
                continue;
              }
              diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);
              diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);
              if (!performance2.deepEqual(beforeLayer.filter, afterLayer.filter)) {
                commands.push({
                  command: operations.setFilter,
                  args: [
                    layerId,
                    afterLayer.filter
                  ]
                });
              }
              if (!performance2.deepEqual(beforeLayer.minzoom, afterLayer.minzoom) || !performance2.deepEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {
                commands.push({
                  command: operations.setLayerZoomRange,
                  args: [
                    layerId,
                    afterLayer.minzoom,
                    afterLayer.maxzoom
                  ]
                });
              }
              for (prop in beforeLayer) {
                if (!beforeLayer.hasOwnProperty(prop)) {
                  continue;
                }
                if (prop === "layout" || prop === "paint" || prop === "filter" || prop === "metadata" || prop === "minzoom" || prop === "maxzoom") {
                  continue;
                }
                if (prop.indexOf("paint.") === 0) {
                  diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
                } else if (!performance2.deepEqual(beforeLayer[prop], afterLayer[prop])) {
                  commands.push({
                    command: operations.setLayerProperty,
                    args: [
                      layerId,
                      prop,
                      afterLayer[prop]
                    ]
                  });
                }
              }
              for (prop in afterLayer) {
                if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) {
                  continue;
                }
                if (prop === "layout" || prop === "paint" || prop === "filter" || prop === "metadata" || prop === "minzoom" || prop === "maxzoom") {
                  continue;
                }
                if (prop.indexOf("paint.") === 0) {
                  diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);
                } else if (!performance2.deepEqual(beforeLayer[prop], afterLayer[prop])) {
                  commands.push({
                    command: operations.setLayerProperty,
                    args: [
                      layerId,
                      prop,
                      afterLayer[prop]
                    ]
                  });
                }
              }
            }
          }
          function diffStyles(before, after) {
            if (!before) {
              return [{
                command: operations.setStyle,
                args: [after]
              }];
            }
            var commands = [];
            try {
              if (!performance2.deepEqual(before.version, after.version)) {
                return [{
                  command: operations.setStyle,
                  args: [after]
                }];
              }
              if (!performance2.deepEqual(before.center, after.center)) {
                commands.push({
                  command: operations.setCenter,
                  args: [after.center]
                });
              }
              if (!performance2.deepEqual(before.zoom, after.zoom)) {
                commands.push({
                  command: operations.setZoom,
                  args: [after.zoom]
                });
              }
              if (!performance2.deepEqual(before.bearing, after.bearing)) {
                commands.push({
                  command: operations.setBearing,
                  args: [after.bearing]
                });
              }
              if (!performance2.deepEqual(before.pitch, after.pitch)) {
                commands.push({
                  command: operations.setPitch,
                  args: [after.pitch]
                });
              }
              if (!performance2.deepEqual(before.sprite, after.sprite)) {
                commands.push({
                  command: operations.setSprite,
                  args: [after.sprite]
                });
              }
              if (!performance2.deepEqual(before.glyphs, after.glyphs)) {
                commands.push({
                  command: operations.setGlyphs,
                  args: [after.glyphs]
                });
              }
              if (!performance2.deepEqual(before.transition, after.transition)) {
                commands.push({
                  command: operations.setTransition,
                  args: [after.transition]
                });
              }
              if (!performance2.deepEqual(before.light, after.light)) {
                commands.push({
                  command: operations.setLight,
                  args: [after.light]
                });
              }
              var sourcesRemoved = {};
              var removeOrAddSourceCommands = [];
              diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);
              var beforeLayers = [];
              if (before.layers) {
                before.layers.forEach(function(layer) {
                  if (sourcesRemoved[layer.source]) {
                    commands.push({
                      command: operations.removeLayer,
                      args: [layer.id]
                    });
                  } else {
                    beforeLayers.push(layer);
                  }
                });
              }
              commands = commands.concat(removeOrAddSourceCommands);
              diffLayers(beforeLayers, after.layers, commands);
            } catch (e) {
              console.warn("Unable to compute style diff:", e);
              commands = [{
                command: operations.setStyle,
                args: [after]
              }];
            }
            return commands;
          }
          var PathInterpolator = function PathInterpolator2(points_, padding_) {
            this.reset(points_, padding_);
          };
          PathInterpolator.prototype.reset = function reset(points_, padding_) {
            this.points = points_ || [];
            this._distances = [0];
            for (var i = 1; i < this.points.length; i++) {
              this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]);
            }
            this.length = this._distances[this._distances.length - 1];
            this.padding = Math.min(padding_ || 0, this.length * 0.5);
            this.paddedLength = this.length - this.padding * 2;
          };
          PathInterpolator.prototype.lerp = function lerp(t) {
            if (this.points.length === 1) {
              return this.points[0];
            }
            t = performance2.clamp(t, 0, 1);
            var currentIndex = 1;
            var distOfCurrentIdx = this._distances[currentIndex];
            var distToTarget = t * this.paddedLength + this.padding;
            while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) {
              distOfCurrentIdx = this._distances[++currentIndex];
            }
            var idxOfPrevPoint = currentIndex - 1;
            var distOfPrevIdx = this._distances[idxOfPrevPoint];
            var segmentLength = distOfCurrentIdx - distOfPrevIdx;
            var segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0;
            return this.points[idxOfPrevPoint].mult(1 - segmentT).add(this.points[currentIndex].mult(segmentT));
          };
          var GridIndex = function GridIndex2(width, height, cellSize) {
            var boxCells = this.boxCells = [];
            var circleCells = this.circleCells = [];
            this.xCellCount = Math.ceil(width / cellSize);
            this.yCellCount = Math.ceil(height / cellSize);
            for (var i = 0; i < this.xCellCount * this.yCellCount; i++) {
              boxCells.push([]);
              circleCells.push([]);
            }
            this.circleKeys = [];
            this.boxKeys = [];
            this.bboxes = [];
            this.circles = [];
            this.width = width;
            this.height = height;
            this.xScale = this.xCellCount / width;
            this.yScale = this.yCellCount / height;
            this.boxUid = 0;
            this.circleUid = 0;
          };
          GridIndex.prototype.keysLength = function keysLength() {
            return this.boxKeys.length + this.circleKeys.length;
          };
          GridIndex.prototype.insert = function insert(key, x1, y1, x2, y2) {
            this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++);
            this.boxKeys.push(key);
            this.bboxes.push(x1);
            this.bboxes.push(y1);
            this.bboxes.push(x2);
            this.bboxes.push(y2);
          };
          GridIndex.prototype.insertCircle = function insertCircle(key, x, y, radius) {
            this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++);
            this.circleKeys.push(key);
            this.circles.push(x);
            this.circles.push(y);
            this.circles.push(radius);
          };
          GridIndex.prototype._insertBoxCell = function _insertBoxCell(x1, y1, x2, y2, cellIndex, uid) {
            this.boxCells[cellIndex].push(uid);
          };
          GridIndex.prototype._insertCircleCell = function _insertCircleCell(x1, y1, x2, y2, cellIndex, uid) {
            this.circleCells[cellIndex].push(uid);
          };
          GridIndex.prototype._query = function _query(x1, y1, x2, y2, hitTest, predicate) {
            if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {
              return hitTest ? false : [];
            }
            var result = [];
            if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {
              if (hitTest) {
                return true;
              }
              for (var boxUid = 0; boxUid < this.boxKeys.length; boxUid++) {
                result.push({
                  key: this.boxKeys[boxUid],
                  x1: this.bboxes[boxUid * 4],
                  y1: this.bboxes[boxUid * 4 + 1],
                  x2: this.bboxes[boxUid * 4 + 2],
                  y2: this.bboxes[boxUid * 4 + 3]
                });
              }
              for (var circleUid = 0; circleUid < this.circleKeys.length; circleUid++) {
                var x = this.circles[circleUid * 3];
                var y = this.circles[circleUid * 3 + 1];
                var radius = this.circles[circleUid * 3 + 2];
                result.push({
                  key: this.circleKeys[circleUid],
                  x1: x - radius,
                  y1: y - radius,
                  x2: x + radius,
                  y2: y + radius
                });
              }
              return predicate ? result.filter(predicate) : result;
            } else {
              var queryArgs = {
                hitTest,
                seenUids: {
                  box: {},
                  circle: {}
                }
              };
              this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);
              return hitTest ? result.length > 0 : result;
            }
          };
          GridIndex.prototype._queryCircle = function _queryCircle(x, y, radius, hitTest, predicate) {
            var x1 = x - radius;
            var x2 = x + radius;
            var y1 = y - radius;
            var y2 = y + radius;
            if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {
              return hitTest ? false : [];
            }
            var result = [];
            var queryArgs = {
              hitTest,
              circle: {
                x,
                y,
                radius
              },
              seenUids: {
                box: {},
                circle: {}
              }
            };
            this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);
            return hitTest ? result.length > 0 : result;
          };
          GridIndex.prototype.query = function query(x1, y1, x2, y2, predicate) {
            return this._query(x1, y1, x2, y2, false, predicate);
          };
          GridIndex.prototype.hitTest = function hitTest(x1, y1, x2, y2, predicate) {
            return this._query(x1, y1, x2, y2, true, predicate);
          };
          GridIndex.prototype.hitTestCircle = function hitTestCircle(x, y, radius, predicate) {
            return this._queryCircle(x, y, radius, true, predicate);
          };
          GridIndex.prototype._queryCell = function _queryCell(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) {
            var seenUids = queryArgs.seenUids;
            var boxCell = this.boxCells[cellIndex];
            if (boxCell !== null) {
              var bboxes = this.bboxes;
              for (var i = 0, list = boxCell; i < list.length; i += 1) {
                var boxUid = list[i];
                if (!seenUids.box[boxUid]) {
                  seenUids.box[boxUid] = true;
                  var offset = boxUid * 4;
                  if (x1 <= bboxes[offset + 2] && y1 <= bboxes[offset + 3] && x2 >= bboxes[offset + 0] && y2 >= bboxes[offset + 1] && (!predicate || predicate(this.boxKeys[boxUid]))) {
                    if (queryArgs.hitTest) {
                      result.push(true);
                      return true;
                    } else {
                      result.push({
                        key: this.boxKeys[boxUid],
                        x1: bboxes[offset],
                        y1: bboxes[offset + 1],
                        x2: bboxes[offset + 2],
                        y2: bboxes[offset + 3]
                      });
                    }
                  }
                }
              }
            }
            var circleCell = this.circleCells[cellIndex];
            if (circleCell !== null) {
              var circles = this.circles;
              for (var i$1 = 0, list$1 = circleCell; i$1 < list$1.length; i$1 += 1) {
                var circleUid = list$1[i$1];
                if (!seenUids.circle[circleUid]) {
                  seenUids.circle[circleUid] = true;
                  var offset$1 = circleUid * 3;
                  if (this._circleAndRectCollide(circles[offset$1], circles[offset$1 + 1], circles[offset$1 + 2], x1, y1, x2, y2) && (!predicate || predicate(this.circleKeys[circleUid]))) {
                    if (queryArgs.hitTest) {
                      result.push(true);
                      return true;
                    } else {
                      var x = circles[offset$1];
                      var y = circles[offset$1 + 1];
                      var radius = circles[offset$1 + 2];
                      result.push({
                        key: this.circleKeys[circleUid],
                        x1: x - radius,
                        y1: y - radius,
                        x2: x + radius,
                        y2: y + radius
                      });
                    }
                  }
                }
              }
            }
          };
          GridIndex.prototype._queryCellCircle = function _queryCellCircle(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) {
            var circle2 = queryArgs.circle;
            var seenUids = queryArgs.seenUids;
            var boxCell = this.boxCells[cellIndex];
            if (boxCell !== null) {
              var bboxes = this.bboxes;
              for (var i = 0, list = boxCell; i < list.length; i += 1) {
                var boxUid = list[i];
                if (!seenUids.box[boxUid]) {
                  seenUids.box[boxUid] = true;
                  var offset = boxUid * 4;
                  if (this._circleAndRectCollide(circle2.x, circle2.y, circle2.radius, bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) && (!predicate || predicate(this.boxKeys[boxUid]))) {
                    result.push(true);
                    return true;
                  }
                }
              }
            }
            var circleCell = this.circleCells[cellIndex];
            if (circleCell !== null) {
              var circles = this.circles;
              for (var i$1 = 0, list$1 = circleCell; i$1 < list$1.length; i$1 += 1) {
                var circleUid = list$1[i$1];
                if (!seenUids.circle[circleUid]) {
                  seenUids.circle[circleUid] = true;
                  var offset$1 = circleUid * 3;
                  if (this._circlesCollide(circles[offset$1], circles[offset$1 + 1], circles[offset$1 + 2], circle2.x, circle2.y, circle2.radius) && (!predicate || predicate(this.circleKeys[circleUid]))) {
                    result.push(true);
                    return true;
                  }
                }
              }
            }
          };
          GridIndex.prototype._forEachCell = function _forEachCell(x1, y1, x2, y2, fn, arg1, arg2, predicate) {
            var cx1 = this._convertToXCellCoord(x1);
            var cy1 = this._convertToYCellCoord(y1);
            var cx2 = this._convertToXCellCoord(x2);
            var cy2 = this._convertToYCellCoord(y2);
            for (var x = cx1; x <= cx2; x++) {
              for (var y = cy1; y <= cy2; y++) {
                var cellIndex = this.xCellCount * y + x;
                if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) {
                  return;
                }
              }
            }
          };
          GridIndex.prototype._convertToXCellCoord = function _convertToXCellCoord(x) {
            return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));
          };
          GridIndex.prototype._convertToYCellCoord = function _convertToYCellCoord(y) {
            return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));
          };
          GridIndex.prototype._circlesCollide = function _circlesCollide(x1, y1, r1, x2, y2, r2) {
            var dx = x2 - x1;
            var dy = y2 - y1;
            var bothRadii = r1 + r2;
            return bothRadii * bothRadii > dx * dx + dy * dy;
          };
          GridIndex.prototype._circleAndRectCollide = function _circleAndRectCollide(circleX, circleY, radius, x1, y1, x2, y2) {
            var halfRectWidth = (x2 - x1) / 2;
            var distX = Math.abs(circleX - (x1 + halfRectWidth));
            if (distX > halfRectWidth + radius) {
              return false;
            }
            var halfRectHeight = (y2 - y1) / 2;
            var distY = Math.abs(circleY - (y1 + halfRectHeight));
            if (distY > halfRectHeight + radius) {
              return false;
            }
            if (distX <= halfRectWidth || distY <= halfRectHeight) {
              return true;
            }
            var dx = distX - halfRectWidth;
            var dy = distY - halfRectHeight;
            return dx * dx + dy * dy <= radius * radius;
          };
          function getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits2) {
            var m = performance2.create();
            if (pitchWithMap) {
              performance2.scale(m, m, [
                1 / pixelsToTileUnits2,
                1 / pixelsToTileUnits2,
                1
              ]);
              if (!rotateWithMap) {
                performance2.rotateZ(m, m, transform.angle);
              }
            } else {
              performance2.multiply(m, transform.labelPlaneMatrix, posMatrix);
            }
            return m;
          }
          function getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, transform, pixelsToTileUnits2) {
            if (pitchWithMap) {
              var m = performance2.clone(posMatrix);
              performance2.scale(m, m, [
                pixelsToTileUnits2,
                pixelsToTileUnits2,
                1
              ]);
              if (!rotateWithMap) {
                performance2.rotateZ(m, m, -transform.angle);
              }
              return m;
            } else {
              return transform.glCoordMatrix;
            }
          }
          function project(point, matrix) {
            var pos = [
              point.x,
              point.y,
              0,
              1
            ];
            xyTransformMat4(pos, pos, matrix);
            var w = pos[3];
            return {
              point: new performance2.Point(pos[0] / w, pos[1] / w),
              signedDistanceFromCamera: w
            };
          }
          function getPerspectiveRatio(cameraToCenterDistance, signedDistanceFromCamera) {
            return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera);
          }
          function isVisible(anchorPos, clippingBuffer) {
            var x = anchorPos[0] / anchorPos[3];
            var y = anchorPos[1] / anchorPos[3];
            var inPaddedViewport = x >= -clippingBuffer[0] && x <= clippingBuffer[0] && y >= -clippingBuffer[1] && y <= clippingBuffer[1];
            return inPaddedViewport;
          }
          function updateLineLabels(bucket, posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright) {
            var sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;
            var partiallyEvaluatedSize = performance2.evaluateSizeForZoom(sizeData, painter.transform.zoom);
            var clippingBuffer = [
              256 / painter.width * 2 + 1,
              256 / painter.height * 2 + 1
            ];
            var dynamicLayoutVertexArray = isText ? bucket.text.dynamicLayoutVertexArray : bucket.icon.dynamicLayoutVertexArray;
            dynamicLayoutVertexArray.clear();
            var lineVertexArray = bucket.lineVertexArray;
            var placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray;
            var aspectRatio = painter.transform.width / painter.transform.height;
            var useVertical = false;
            for (var s = 0; s < placedSymbols.length; s++) {
              var symbol = placedSymbols.get(s);
              if (symbol.hidden || symbol.writingMode === performance2.WritingMode.vertical && !useVertical) {
                hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);
                continue;
              }
              useVertical = false;
              var anchorPos = [
                symbol.anchorX,
                symbol.anchorY,
                0,
                1
              ];
              performance2.transformMat4(anchorPos, anchorPos, posMatrix);
              if (!isVisible(anchorPos, clippingBuffer)) {
                hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);
                continue;
              }
              var cameraToAnchorDistance = anchorPos[3];
              var perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance);
              var fontSize = performance2.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);
              var pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;
              var tileAnchorPoint = new performance2.Point(symbol.anchorX, symbol.anchorY);
              var anchorPoint = project(tileAnchorPoint, labelPlaneMatrix).point;
              var projectionCache = {};
              var placeUnflipped = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio);
              useVertical = placeUnflipped.useVertical;
              if (placeUnflipped.notEnoughRoom || useVertical || placeUnflipped.needsFlipping && placeGlyphsAlongLine(symbol, pitchScaledFontSize, true, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio).notEnoughRoom) {
                hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);
              }
            }
            if (isText) {
              bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);
            } else {
              bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);
            }
          }
          function placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache) {
            var glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;
            var lineStartIndex = symbol.lineStartIndex;
            var lineEndIndex = symbol.lineStartIndex + symbol.lineLength;
            var firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex);
            var lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1);
            var firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache);
            if (!firstPlacedGlyph) {
              return null;
            }
            var lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache);
            if (!lastPlacedGlyph) {
              return null;
            }
            return {
              first: firstPlacedGlyph,
              last: lastPlacedGlyph
            };
          }
          function requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) {
            if (writingMode === performance2.WritingMode.horizontal) {
              var rise = Math.abs(lastPoint.y - firstPoint.y);
              var run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio;
              if (rise > run) {
                return { useVertical: true };
              }
            }
            if (writingMode === performance2.WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) {
              return { needsFlipping: true };
            }
            return null;
          }
          function placeGlyphsAlongLine(symbol, fontSize, flip, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio) {
            var fontScale = fontSize / 24;
            var lineOffsetX = symbol.lineOffsetX * fontScale;
            var lineOffsetY = symbol.lineOffsetY * fontScale;
            var placedGlyphs;
            if (symbol.numGlyphs > 1) {
              var glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;
              var lineStartIndex = symbol.lineStartIndex;
              var lineEndIndex = symbol.lineStartIndex + symbol.lineLength;
              var firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache);
              if (!firstAndLastGlyph) {
                return { notEnoughRoom: true };
              }
              var firstPoint = project(firstAndLastGlyph.first.point, glCoordMatrix).point;
              var lastPoint = project(firstAndLastGlyph.last.point, glCoordMatrix).point;
              if (keepUpright && !flip) {
                var orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio);
                if (orientationChange) {
                  return orientationChange;
                }
              }
              placedGlyphs = [firstAndLastGlyph.first];
              for (var glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) {
                placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache));
              }
              placedGlyphs.push(firstAndLastGlyph.last);
            } else {
              if (keepUpright && !flip) {
                var a = project(tileAnchorPoint, posMatrix).point;
                var tileVertexIndex = symbol.lineStartIndex + symbol.segment + 1;
                var tileSegmentEnd = new performance2.Point(lineVertexArray.getx(tileVertexIndex), lineVertexArray.gety(tileVertexIndex));
                var projectedVertex = project(tileSegmentEnd, posMatrix);
                var b = projectedVertex.signedDistanceFromCamera > 0 ? projectedVertex.point : projectTruncatedLineSegment(tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix);
                var orientationChange$1 = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio);
                if (orientationChange$1) {
                  return orientationChange$1;
                }
              }
              var singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment, symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, lineVertexArray, labelPlaneMatrix, projectionCache);
              if (!singleGlyph) {
                return { notEnoughRoom: true };
              }
              placedGlyphs = [singleGlyph];
            }
            for (var i = 0, list = placedGlyphs; i < list.length; i += 1) {
              var glyph = list[i];
              performance2.addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle);
            }
            return {};
          }
          function projectTruncatedLineSegment(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionMatrix) {
            var projectedUnitVertex = project(previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()), projectionMatrix).point;
            var projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex);
            return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag()));
          }
          function placeGlyphAlongLine(offsetX, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, anchorSegment, lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache) {
            var combinedOffsetX = flip ? offsetX - lineOffsetX : offsetX + lineOffsetX;
            var dir = combinedOffsetX > 0 ? 1 : -1;
            var angle = 0;
            if (flip) {
              dir *= -1;
              angle = Math.PI;
            }
            if (dir < 0) {
              angle += Math.PI;
            }
            var currentIndex = dir > 0 ? lineStartIndex + anchorSegment : lineStartIndex + anchorSegment + 1;
            var current = anchorPoint;
            var prev = anchorPoint;
            var distanceToPrev = 0;
            var currentSegmentDistance = 0;
            var absOffsetX = Math.abs(combinedOffsetX);
            var pathVertices = [];
            while (distanceToPrev + currentSegmentDistance <= absOffsetX) {
              currentIndex += dir;
              if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex) {
                return null;
              }
              prev = current;
              pathVertices.push(current);
              current = projectionCache[currentIndex];
              if (current === void 0) {
                var currentVertex = new performance2.Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex));
                var projection = project(currentVertex, labelPlaneMatrix);
                if (projection.signedDistanceFromCamera > 0) {
                  current = projectionCache[currentIndex] = projection.point;
                } else {
                  var previousLineVertexIndex = currentIndex - dir;
                  var previousTilePoint = distanceToPrev === 0 ? tileAnchorPoint : new performance2.Point(lineVertexArray.getx(previousLineVertexIndex), lineVertexArray.gety(previousLineVertexIndex));
                  current = projectTruncatedLineSegment(previousTilePoint, currentVertex, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix);
                }
              }
              distanceToPrev += currentSegmentDistance;
              currentSegmentDistance = prev.dist(current);
            }
            var segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance;
            var prevToCurrent = current.sub(prev);
            var p = prevToCurrent.mult(segmentInterpolationT)._add(prev);
            p._add(prevToCurrent._unit()._perp()._mult(lineOffsetY * dir));
            var segmentAngle = angle + Math.atan2(current.y - prev.y, current.x - prev.x);
            pathVertices.push(p);
            return {
              point: p,
              angle: segmentAngle,
              path: pathVertices
            };
          }
          var hiddenGlyphAttributes = new Float32Array([
            -Infinity,
            -Infinity,
            0,
            -Infinity,
            -Infinity,
            0,
            -Infinity,
            -Infinity,
            0,
            -Infinity,
            -Infinity,
            0
          ]);
          function hideGlyphs(num, dynamicLayoutVertexArray) {
            for (var i = 0; i < num; i++) {
              var offset = dynamicLayoutVertexArray.length;
              dynamicLayoutVertexArray.resize(offset + 4);
              dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3);
            }
          }
          function xyTransformMat4(out, a, m) {
            var x = a[0], y = a[1];
            out[0] = m[0] * x + m[4] * y + m[12];
            out[1] = m[1] * x + m[5] * y + m[13];
            out[3] = m[3] * x + m[7] * y + m[15];
            return out;
          }
          var viewportPadding = 100;
          var CollisionIndex = function CollisionIndex2(transform, grid, ignoredGrid) {
            if (grid === void 0)
              grid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25);
            if (ignoredGrid === void 0)
              ignoredGrid = new GridIndex(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25);
            this.transform = transform;
            this.grid = grid;
            this.ignoredGrid = ignoredGrid;
            this.pitchfactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance;
            this.screenRightBoundary = transform.width + viewportPadding;
            this.screenBottomBoundary = transform.height + viewportPadding;
            this.gridRightBoundary = transform.width + 2 * viewportPadding;
            this.gridBottomBoundary = transform.height + 2 * viewportPadding;
          };
          CollisionIndex.prototype.placeCollisionBox = function placeCollisionBox(collisionBox2, allowOverlap, textPixelRatio, posMatrix, collisionGroupPredicate) {
            var projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox2.anchorPointX, collisionBox2.anchorPointY);
            var tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;
            var tlX = collisionBox2.x1 * tileToViewport + projectedPoint.point.x;
            var tlY = collisionBox2.y1 * tileToViewport + projectedPoint.point.y;
            var brX = collisionBox2.x2 * tileToViewport + projectedPoint.point.x;
            var brY = collisionBox2.y2 * tileToViewport + projectedPoint.point.y;
            if (!this.isInsideGrid(tlX, tlY, brX, brY) || !allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate)) {
              return {
                box: [],
                offscreen: false
              };
            }
            return {
              box: [
                tlX,
                tlY,
                brX,
                brY
              ],
              offscreen: this.isOffscreen(tlX, tlY, brX, brY)
            };
          };
          CollisionIndex.prototype.placeCollisionCircles = function placeCollisionCircles(allowOverlap, symbol, lineVertexArray, glyphOffsetArray, fontSize, posMatrix, labelPlaneMatrix, labelToScreenMatrix, showCollisionCircles, pitchWithMap, collisionGroupPredicate, circlePixelDiameter, textPixelPadding) {
            var placedCollisionCircles = [];
            var tileUnitAnchorPoint = new performance2.Point(symbol.anchorX, symbol.anchorY);
            var screenAnchorPoint = project(tileUnitAnchorPoint, posMatrix);
            var perspectiveRatio = getPerspectiveRatio(this.transform.cameraToCenterDistance, screenAnchorPoint.signedDistanceFromCamera);
            var labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;
            var labelPlaneFontScale = labelPlaneFontSize / performance2.ONE_EM;
            var labelPlaneAnchorPoint = project(tileUnitAnchorPoint, labelPlaneMatrix).point;
            var projectionCache = {};
            var lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;
            var lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;
            var firstAndLastGlyph = placeFirstAndLastGlyph(labelPlaneFontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, false, labelPlaneAnchorPoint, tileUnitAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache);
            var collisionDetected = false;
            var inGrid = false;
            var entirelyOffscreen = true;
            if (firstAndLastGlyph) {
              var radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding;
              var screenPlaneMin = new performance2.Point(-viewportPadding, -viewportPadding);
              var screenPlaneMax = new performance2.Point(this.screenRightBoundary, this.screenBottomBoundary);
              var interpolator = new PathInterpolator();
              var first = firstAndLastGlyph.first;
              var last = firstAndLastGlyph.last;
              var projectedPath = [];
              for (var i = first.path.length - 1; i >= 1; i--) {
                projectedPath.push(first.path[i]);
              }
              for (var i$1 = 1; i$1 < last.path.length; i$1++) {
                projectedPath.push(last.path[i$1]);
              }
              var circleDist = radius * 2.5;
              if (labelToScreenMatrix) {
                var screenSpacePath = projectedPath.map(function(p) {
                  return project(p, labelToScreenMatrix);
                });
                if (screenSpacePath.some(function(point) {
                  return point.signedDistanceFromCamera <= 0;
                })) {
                  projectedPath = [];
                } else {
                  projectedPath = screenSpacePath.map(function(p) {
                    return p.point;
                  });
                }
              }
              var segments = [];
              if (projectedPath.length > 0) {
                var minPoint = projectedPath[0].clone();
                var maxPoint = projectedPath[0].clone();
                for (var i$2 = 1; i$2 < projectedPath.length; i$2++) {
                  minPoint.x = Math.min(minPoint.x, projectedPath[i$2].x);
                  minPoint.y = Math.min(minPoint.y, projectedPath[i$2].y);
                  maxPoint.x = Math.max(maxPoint.x, projectedPath[i$2].x);
                  maxPoint.y = Math.max(maxPoint.y, projectedPath[i$2].y);
                }
                if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x && minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) {
                  segments = [projectedPath];
                } else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x || maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) {
                  segments = [];
                } else {
                  segments = performance2.clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);
                }
              }
              for (var i$4 = 0, list = segments; i$4 < list.length; i$4 += 1) {
                var seg = list[i$4];
                interpolator.reset(seg, radius * 0.25);
                var numCircles = 0;
                if (interpolator.length <= 0.5 * radius) {
                  numCircles = 1;
                } else {
                  numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;
                }
                for (var i$3 = 0; i$3 < numCircles; i$3++) {
                  var t = i$3 / Math.max(numCircles - 1, 1);
                  var circlePosition = interpolator.lerp(t);
                  var centerX = circlePosition.x + viewportPadding;
                  var centerY = circlePosition.y + viewportPadding;
                  placedCollisionCircles.push(centerX, centerY, radius, 0);
                  var x1 = centerX - radius;
                  var y1 = centerY - radius;
                  var x2 = centerX + radius;
                  var y2 = centerY + radius;
                  entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2);
                  inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2);
                  if (!allowOverlap) {
                    if (this.grid.hitTestCircle(centerX, centerY, radius, collisionGroupPredicate)) {
                      collisionDetected = true;
                      if (!showCollisionCircles) {
                        return {
                          circles: [],
                          offscreen: false,
                          collisionDetected
                        };
                      }
                    }
                  }
                }
              }
            }
            return {
              circles: !showCollisionCircles && collisionDetected || !inGrid ? [] : placedCollisionCircles,
              offscreen: entirelyOffscreen,
              collisionDetected
            };
          };
          CollisionIndex.prototype.queryRenderedSymbols = function queryRenderedSymbols2(viewportQueryGeometry) {
            if (viewportQueryGeometry.length === 0 || this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0) {
              return {};
            }
            var query = [];
            var minX = Infinity;
            var minY = Infinity;
            var maxX = -Infinity;
            var maxY = -Infinity;
            for (var i = 0, list = viewportQueryGeometry; i < list.length; i += 1) {
              var point = list[i];
              var gridPoint = new performance2.Point(point.x + viewportPadding, point.y + viewportPadding);
              minX = Math.min(minX, gridPoint.x);
              minY = Math.min(minY, gridPoint.y);
              maxX = Math.max(maxX, gridPoint.x);
              maxY = Math.max(maxY, gridPoint.y);
              query.push(gridPoint);
            }
            var features = this.grid.query(minX, minY, maxX, maxY).concat(this.ignoredGrid.query(minX, minY, maxX, maxY));
            var seenFeatures = {};
            var result = {};
            for (var i$1 = 0, list$1 = features; i$1 < list$1.length; i$1 += 1) {
              var feature = list$1[i$1];
              var featureKey = feature.key;
              if (seenFeatures[featureKey.bucketInstanceId] === void 0) {
                seenFeatures[featureKey.bucketInstanceId] = {};
              }
              if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {
                continue;
              }
              var bbox = [
                new performance2.Point(feature.x1, feature.y1),
                new performance2.Point(feature.x2, feature.y1),
                new performance2.Point(feature.x2, feature.y2),
                new performance2.Point(feature.x1, feature.y2)
              ];
              if (!performance2.polygonIntersectsPolygon(query, bbox)) {
                continue;
              }
              seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;
              if (result[featureKey.bucketInstanceId] === void 0) {
                result[featureKey.bucketInstanceId] = [];
              }
              result[featureKey.bucketInstanceId].push(featureKey.featureIndex);
            }
            return result;
          };
          CollisionIndex.prototype.insertCollisionBox = function insertCollisionBox(collisionBox2, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) {
            var grid = ignorePlacement ? this.ignoredGrid : this.grid;
            var key = {
              bucketInstanceId,
              featureIndex,
              collisionGroupID
            };
            grid.insert(key, collisionBox2[0], collisionBox2[1], collisionBox2[2], collisionBox2[3]);
          };
          CollisionIndex.prototype.insertCollisionCircles = function insertCollisionCircles(collisionCircles, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) {
            var grid = ignorePlacement ? this.ignoredGrid : this.grid;
            var key = {
              bucketInstanceId,
              featureIndex,
              collisionGroupID
            };
            for (var k = 0; k < collisionCircles.length; k += 4) {
              grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);
            }
          };
          CollisionIndex.prototype.projectAndGetPerspectiveRatio = function projectAndGetPerspectiveRatio(posMatrix, x, y) {
            var p = [
              x,
              y,
              0,
              1
            ];
            xyTransformMat4(p, p, posMatrix);
            var a = new performance2.Point((p[0] / p[3] + 1) / 2 * this.transform.width + viewportPadding, (-p[1] / p[3] + 1) / 2 * this.transform.height + viewportPadding);
            return {
              point: a,
              perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3])
            };
          };
          CollisionIndex.prototype.isOffscreen = function isOffscreen(x1, y1, x2, y2) {
            return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary;
          };
          CollisionIndex.prototype.isInsideGrid = function isInsideGrid(x1, y1, x2, y2) {
            return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;
          };
          CollisionIndex.prototype.getViewportMatrix = function getViewportMatrix() {
            var m = performance2.identity([]);
            performance2.translate(m, m, [
              -viewportPadding,
              -viewportPadding,
              0
            ]);
            return m;
          };
          function pixelsToTileUnits(tile, pixelValue, z) {
            return pixelValue * (performance2.EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));
          }
          var OpacityState = function OpacityState2(prevState, increment, placed, skipFade) {
            if (prevState) {
              this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment)));
            } else {
              this.opacity = skipFade && placed ? 1 : 0;
            }
            this.placed = placed;
          };
          OpacityState.prototype.isHidden = function isHidden() {
            return this.opacity === 0 && !this.placed;
          };
          var JointOpacityState = function JointOpacityState2(prevState, increment, placedText, placedIcon, skipFade) {
            this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade);
            this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade);
          };
          JointOpacityState.prototype.isHidden = function isHidden() {
            return this.text.isHidden() && this.icon.isHidden();
          };
          var JointPlacement = function JointPlacement2(text, icon, skipFade) {
            this.text = text;
            this.icon = icon;
            this.skipFade = skipFade;
          };
          var CollisionCircleArray = function CollisionCircleArray2() {
            this.invProjMatrix = performance2.create();
            this.viewportMatrix = performance2.create();
            this.circles = [];
          };
          var RetainedQueryData = function RetainedQueryData2(bucketInstanceId, featureIndex, sourceLayerIndex, bucketIndex, tileID) {
            this.bucketInstanceId = bucketInstanceId;
            this.featureIndex = featureIndex;
            this.sourceLayerIndex = sourceLayerIndex;
            this.bucketIndex = bucketIndex;
            this.tileID = tileID;
          };
          var CollisionGroups = function CollisionGroups2(crossSourceCollisions) {
            this.crossSourceCollisions = crossSourceCollisions;
            this.maxGroupID = 0;
            this.collisionGroups = {};
          };
          CollisionGroups.prototype.get = function get(sourceID) {
            if (!this.crossSourceCollisions) {
              if (!this.collisionGroups[sourceID]) {
                var nextGroupID = ++this.maxGroupID;
                this.collisionGroups[sourceID] = {
                  ID: nextGroupID,
                  predicate: function(key) {
                    return key.collisionGroupID === nextGroupID;
                  }
                };
              }
              return this.collisionGroups[sourceID];
            } else {
              return {
                ID: 0,
                predicate: null
              };
            }
          };
          function calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale) {
            var ref = performance2.getAnchorAlignment(anchor);
            var horizontalAlign = ref.horizontalAlign;
            var verticalAlign = ref.verticalAlign;
            var shiftX = -(horizontalAlign - 0.5) * width;
            var shiftY = -(verticalAlign - 0.5) * height;
            var offset = performance2.evaluateVariableOffset(anchor, textOffset);
            return new performance2.Point(shiftX + offset[0] * textBoxScale, shiftY + offset[1] * textBoxScale);
          }
          function shiftVariableCollisionBox(collisionBox2, shiftX, shiftY, rotateWithMap, pitchWithMap, angle) {
            var x1 = collisionBox2.x1;
            var x2 = collisionBox2.x2;
            var y1 = collisionBox2.y1;
            var y2 = collisionBox2.y2;
            var anchorPointX = collisionBox2.anchorPointX;
            var anchorPointY = collisionBox2.anchorPointY;
            var rotatedOffset = new performance2.Point(shiftX, shiftY);
            if (rotateWithMap) {
              rotatedOffset._rotate(pitchWithMap ? angle : -angle);
            }
            return {
              x1: x1 + rotatedOffset.x,
              y1: y1 + rotatedOffset.y,
              x2: x2 + rotatedOffset.x,
              y2: y2 + rotatedOffset.y,
              anchorPointX,
              anchorPointY
            };
          }
          var Placement = function Placement2(transform, fadeDuration, crossSourceCollisions, prevPlacement) {
            this.transform = transform.clone();
            this.collisionIndex = new CollisionIndex(this.transform);
            this.placements = {};
            this.opacities = {};
            this.variableOffsets = {};
            this.stale = false;
            this.commitTime = 0;
            this.fadeDuration = fadeDuration;
            this.retainedQueryData = {};
            this.collisionGroups = new CollisionGroups(crossSourceCollisions);
            this.collisionCircleArrays = {};
            this.prevPlacement = prevPlacement;
            if (prevPlacement) {
              prevPlacement.prevPlacement = void 0;
            }
            this.placedOrientations = {};
          };
          Placement.prototype.getBucketParts = function getBucketParts(results, styleLayer, tile, sortAcrossTiles) {
            var symbolBucket = tile.getBucket(styleLayer);
            var bucketFeatureIndex = tile.latestFeatureIndex;
            if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) {
              return;
            }
            var collisionBoxArray = tile.collisionBoxArray;
            var layout = symbolBucket.layers[0].layout;
            var scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);
            var textPixelRatio = tile.tileSize / performance2.EXTENT;
            var posMatrix = this.transform.calculatePosMatrix(tile.tileID.toUnwrapped());
            var pitchWithMap = layout.get("text-pitch-alignment") === "map";
            var rotateWithMap = layout.get("text-rotation-alignment") === "map";
            var pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom);
            var textLabelPlaneMatrix = getLabelPlaneMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles);
            var labelToScreenMatrix = null;
            if (pitchWithMap) {
              var glMatrix = getGlCoordMatrix(posMatrix, pitchWithMap, rotateWithMap, this.transform, pixelsToTiles);
              labelToScreenMatrix = performance2.multiply([], this.transform.labelPlaneMatrix, glMatrix);
            }
            this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(symbolBucket.bucketInstanceId, bucketFeatureIndex, symbolBucket.sourceLayerIndex, symbolBucket.index, tile.tileID);
            var parameters = {
              bucket: symbolBucket,
              layout,
              posMatrix,
              textLabelPlaneMatrix,
              labelToScreenMatrix,
              scale,
              textPixelRatio,
              holdingForFade: tile.holdingForFade(),
              collisionBoxArray,
              partiallyEvaluatedTextSize: performance2.evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom),
              collisionGroup: this.collisionGroups.get(symbolBucket.sourceID)
            };
            if (sortAcrossTiles) {
              for (var i = 0, list = symbolBucket.sortKeyRanges; i < list.length; i += 1) {
                var range = list[i];
                var sortKey = range.sortKey;
                var symbolInstanceStart = range.symbolInstanceStart;
                var symbolInstanceEnd = range.symbolInstanceEnd;
                results.push({
                  sortKey,
                  symbolInstanceStart,
                  symbolInstanceEnd,
                  parameters
                });
              }
            } else {
              results.push({
                symbolInstanceStart: 0,
                symbolInstanceEnd: symbolBucket.symbolInstances.length,
                parameters
              });
            }
          };
          Placement.prototype.attemptAnchorPlacement = function attemptAnchorPlacement(anchor, textBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, collisionGroup, textAllowOverlap, symbolInstance, bucket, orientation, iconBox) {
            var textOffset = [
              symbolInstance.textOffset0,
              symbolInstance.textOffset1
            ];
            var shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale);
            var placedGlyphBoxes = this.collisionIndex.placeCollisionBox(shiftVariableCollisionBox(textBox, shift.x, shift.y, rotateWithMap, pitchWithMap, this.transform.angle), textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
            if (iconBox) {
              var placedIconBoxes = this.collisionIndex.placeCollisionBox(shiftVariableCollisionBox(iconBox, shift.x, shift.y, rotateWithMap, pitchWithMap, this.transform.angle), textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
              if (placedIconBoxes.box.length === 0) {
                return;
              }
            }
            if (placedGlyphBoxes.box.length > 0) {
              var prevAnchor;
              if (this.prevPlacement && this.prevPlacement.variableOffsets[symbolInstance.crossTileID] && this.prevPlacement.placements[symbolInstance.crossTileID] && this.prevPlacement.placements[symbolInstance.crossTileID].text) {
                prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor;
              }
              this.variableOffsets[symbolInstance.crossTileID] = {
                textOffset,
                width,
                height,
                anchor,
                textBoxScale,
                prevAnchor
              };
              this.markUsedJustification(bucket, anchor, symbolInstance, orientation);
              if (bucket.allowVerticalPlacement) {
                this.markUsedOrientation(bucket, orientation, symbolInstance);
                this.placedOrientations[symbolInstance.crossTileID] = orientation;
              }
              return {
                shift,
                placedGlyphBoxes
              };
            }
          };
          Placement.prototype.placeLayerBucketPart = function placeLayerBucketPart(bucketPart, seenCrossTileIDs, showCollisionBoxes) {
            var this$1 = this;
            var ref = bucketPart.parameters;
            var bucket = ref.bucket;
            var layout = ref.layout;
            var posMatrix = ref.posMatrix;
            var textLabelPlaneMatrix = ref.textLabelPlaneMatrix;
            var labelToScreenMatrix = ref.labelToScreenMatrix;
            var textPixelRatio = ref.textPixelRatio;
            var holdingForFade = ref.holdingForFade;
            var collisionBoxArray = ref.collisionBoxArray;
            var partiallyEvaluatedTextSize = ref.partiallyEvaluatedTextSize;
            var collisionGroup = ref.collisionGroup;
            var textOptional = layout.get("text-optional");
            var iconOptional = layout.get("icon-optional");
            var textAllowOverlap = layout.get("text-allow-overlap");
            var iconAllowOverlap = layout.get("icon-allow-overlap");
            var rotateWithMap = layout.get("text-rotation-alignment") === "map";
            var pitchWithMap = layout.get("text-pitch-alignment") === "map";
            var hasIconTextFit = layout.get("icon-text-fit") !== "none";
            var zOrderByViewportY = layout.get("symbol-z-order") === "viewport-y";
            var alwaysShowText = textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || iconOptional);
            var alwaysShowIcon = iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || textOptional);
            if (!bucket.collisionArrays && collisionBoxArray) {
              bucket.deserializeCollisionBoxes(collisionBoxArray);
            }
            var placeSymbol = function(symbolInstance, collisionArrays) {
              if (seenCrossTileIDs[symbolInstance.crossTileID]) {
                return;
              }
              if (holdingForFade) {
                this$1.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false);
                return;
              }
              var placeText = false;
              var placeIcon = false;
              var offscreen = true;
              var shift = null;
              var placed = {
                box: null,
                offscreen: null
              };
              var placedVerticalText = {
                box: null,
                offscreen: null
              };
              var placedGlyphBoxes = null;
              var placedGlyphCircles = null;
              var placedIconBoxes = null;
              var textFeatureIndex = 0;
              var verticalTextFeatureIndex = 0;
              var iconFeatureIndex = 0;
              if (collisionArrays.textFeatureIndex) {
                textFeatureIndex = collisionArrays.textFeatureIndex;
              } else if (symbolInstance.useRuntimeCollisionCircles) {
                textFeatureIndex = symbolInstance.featureIndex;
              }
              if (collisionArrays.verticalTextFeatureIndex) {
                verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex;
              }
              var textBox = collisionArrays.textBox;
              if (textBox) {
                var updatePreviousOrientationIfNotPlaced = function(isPlaced) {
                  var previousOrientation = performance2.WritingMode.horizontal;
                  if (bucket.allowVerticalPlacement && !isPlaced && this$1.prevPlacement) {
                    var prevPlacedOrientation = this$1.prevPlacement.placedOrientations[symbolInstance.crossTileID];
                    if (prevPlacedOrientation) {
                      this$1.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation;
                      previousOrientation = prevPlacedOrientation;
                      this$1.markUsedOrientation(bucket, previousOrientation, symbolInstance);
                    }
                  }
                  return previousOrientation;
                };
                var placeTextForPlacementModes = function(placeHorizontalFn, placeVerticalFn) {
                  if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) {
                    for (var i3 = 0, list = bucket.writingModes; i3 < list.length; i3 += 1) {
                      var placementMode = list[i3];
                      if (placementMode === performance2.WritingMode.vertical) {
                        placed = placeVerticalFn();
                        placedVerticalText = placed;
                      } else {
                        placed = placeHorizontalFn();
                      }
                      if (placed && placed.box && placed.box.length) {
                        break;
                      }
                    }
                  } else {
                    placed = placeHorizontalFn();
                  }
                };
                if (!layout.get("text-variable-anchor")) {
                  var placeBox = function(collisionTextBox, orientation) {
                    var placedFeature = this$1.collisionIndex.placeCollisionBox(collisionTextBox, textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
                    if (placedFeature && placedFeature.box && placedFeature.box.length) {
                      this$1.markUsedOrientation(bucket, orientation, symbolInstance);
                      this$1.placedOrientations[symbolInstance.crossTileID] = orientation;
                    }
                    return placedFeature;
                  };
                  var placeHorizontal = function() {
                    return placeBox(textBox, performance2.WritingMode.horizontal);
                  };
                  var placeVertical = function() {
                    var verticalTextBox = collisionArrays.verticalTextBox;
                    if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {
                      return placeBox(verticalTextBox, performance2.WritingMode.vertical);
                    }
                    return {
                      box: null,
                      offscreen: null
                    };
                  };
                  placeTextForPlacementModes(placeHorizontal, placeVertical);
                  updatePreviousOrientationIfNotPlaced(placed && placed.box && placed.box.length);
                } else {
                  var anchors = layout.get("text-variable-anchor");
                  if (this$1.prevPlacement && this$1.prevPlacement.variableOffsets[symbolInstance.crossTileID]) {
                    var prevOffsets = this$1.prevPlacement.variableOffsets[symbolInstance.crossTileID];
                    if (anchors.indexOf(prevOffsets.anchor) > 0) {
                      anchors = anchors.filter(function(anchor) {
                        return anchor !== prevOffsets.anchor;
                      });
                      anchors.unshift(prevOffsets.anchor);
                    }
                  }
                  var placeBoxForVariableAnchors = function(collisionTextBox, collisionIconBox, orientation) {
                    var width = collisionTextBox.x2 - collisionTextBox.x1;
                    var height = collisionTextBox.y2 - collisionTextBox.y1;
                    var textBoxScale = symbolInstance.textBoxScale;
                    var variableIconBox = hasIconTextFit && !iconAllowOverlap ? collisionIconBox : null;
                    var placedBox = {
                      box: [],
                      offscreen: false
                    };
                    var placementAttempts = textAllowOverlap ? anchors.length * 2 : anchors.length;
                    for (var i3 = 0; i3 < placementAttempts; ++i3) {
                      var anchor = anchors[i3 % anchors.length];
                      var allowOverlap = i3 >= anchors.length;
                      var result = this$1.attemptAnchorPlacement(anchor, collisionTextBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix, collisionGroup, allowOverlap, symbolInstance, bucket, orientation, variableIconBox);
                      if (result) {
                        placedBox = result.placedGlyphBoxes;
                        if (placedBox && placedBox.box && placedBox.box.length) {
                          placeText = true;
                          shift = result.shift;
                          break;
                        }
                      }
                    }
                    return placedBox;
                  };
                  var placeHorizontal$1 = function() {
                    return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, performance2.WritingMode.horizontal);
                  };
                  var placeVertical$1 = function() {
                    var verticalTextBox = collisionArrays.verticalTextBox;
                    var wasPlaced = placed && placed.box && placed.box.length;
                    if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {
                      return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, performance2.WritingMode.vertical);
                    }
                    return {
                      box: null,
                      offscreen: null
                    };
                  };
                  placeTextForPlacementModes(placeHorizontal$1, placeVertical$1);
                  if (placed) {
                    placeText = placed.box;
                    offscreen = placed.offscreen;
                  }
                  var prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.box);
                  if (!placeText && this$1.prevPlacement) {
                    var prevOffset = this$1.prevPlacement.variableOffsets[symbolInstance.crossTileID];
                    if (prevOffset) {
                      this$1.variableOffsets[symbolInstance.crossTileID] = prevOffset;
                      this$1.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation);
                    }
                  }
                }
              }
              placedGlyphBoxes = placed;
              placeText = placedGlyphBoxes && placedGlyphBoxes.box && placedGlyphBoxes.box.length > 0;
              offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen;
              if (symbolInstance.useRuntimeCollisionCircles) {
                var placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);
                var fontSize = performance2.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);
                var textPixelPadding = layout.get("text-padding");
                var circlePixelDiameter = symbolInstance.collisionCircleDiameter;
                placedGlyphCircles = this$1.collisionIndex.placeCollisionCircles(textAllowOverlap, placedSymbol, bucket.lineVertexArray, bucket.glyphOffsetArray, fontSize, posMatrix, textLabelPlaneMatrix, labelToScreenMatrix, showCollisionBoxes, pitchWithMap, collisionGroup.predicate, circlePixelDiameter, textPixelPadding);
                placeText = textAllowOverlap || placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected;
                offscreen = offscreen && placedGlyphCircles.offscreen;
              }
              if (collisionArrays.iconFeatureIndex) {
                iconFeatureIndex = collisionArrays.iconFeatureIndex;
              }
              if (collisionArrays.iconBox) {
                var placeIconFeature = function(iconBox) {
                  var shiftedIconBox = hasIconTextFit && shift ? shiftVariableCollisionBox(iconBox, shift.x, shift.y, rotateWithMap, pitchWithMap, this$1.transform.angle) : iconBox;
                  return this$1.collisionIndex.placeCollisionBox(shiftedIconBox, iconAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);
                };
                if (placedVerticalText && placedVerticalText.box && placedVerticalText.box.length && collisionArrays.verticalIconBox) {
                  placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox);
                  placeIcon = placedIconBoxes.box.length > 0;
                } else {
                  placedIconBoxes = placeIconFeature(collisionArrays.iconBox);
                  placeIcon = placedIconBoxes.box.length > 0;
                }
                offscreen = offscreen && placedIconBoxes.offscreen;
              }
              var iconWithoutText = textOptional || symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0;
              var textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0;
              if (!iconWithoutText && !textWithoutIcon) {
                placeIcon = placeText = placeIcon && placeText;
              } else if (!textWithoutIcon) {
                placeText = placeIcon && placeText;
              } else if (!iconWithoutText) {
                placeIcon = placeIcon && placeText;
              }
              if (placeText && placedGlyphBoxes && placedGlyphBoxes.box) {
                if (placedVerticalText && placedVerticalText.box && verticalTextFeatureIndex) {
                  this$1.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get("text-ignore-placement"), bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID);
                } else {
                  this$1.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get("text-ignore-placement"), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);
                }
              }
              if (placeIcon && placedIconBoxes) {
                this$1.collisionIndex.insertCollisionBox(placedIconBoxes.box, layout.get("icon-ignore-placement"), bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID);
              }
              if (placedGlyphCircles) {
                if (placeText) {
                  this$1.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, layout.get("text-ignore-placement"), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);
                }
                if (showCollisionBoxes) {
                  var id = bucket.bucketInstanceId;
                  var circleArray2 = this$1.collisionCircleArrays[id];
                  if (circleArray2 === void 0) {
                    circleArray2 = this$1.collisionCircleArrays[id] = new CollisionCircleArray();
                  }
                  for (var i2 = 0; i2 < placedGlyphCircles.circles.length; i2 += 4) {
                    circleArray2.circles.push(placedGlyphCircles.circles[i2 + 0]);
                    circleArray2.circles.push(placedGlyphCircles.circles[i2 + 1]);
                    circleArray2.circles.push(placedGlyphCircles.circles[i2 + 2]);
                    circleArray2.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0);
                  }
                }
              }
              this$1.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded);
              seenCrossTileIDs[symbolInstance.crossTileID] = true;
            };
            if (zOrderByViewportY) {
              var symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle);
              for (var i = symbolIndexes.length - 1; i >= 0; --i) {
                var symbolIndex = symbolIndexes[i];
                placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex]);
              }
            } else {
              for (var i$1 = bucketPart.symbolInstanceStart; i$1 < bucketPart.symbolInstanceEnd; i$1++) {
                placeSymbol(bucket.symbolInstances.get(i$1), bucket.collisionArrays[i$1]);
              }
            }
            if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) {
              var circleArray = this.collisionCircleArrays[bucket.bucketInstanceId];
              performance2.invert(circleArray.invProjMatrix, posMatrix);
              circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix();
            }
            bucket.justReloaded = false;
          };
          Placement.prototype.markUsedJustification = function markUsedJustification(bucket, placedAnchor, symbolInstance, orientation) {
            var justifications = {
              "left": symbolInstance.leftJustifiedTextSymbolIndex,
              "center": symbolInstance.centerJustifiedTextSymbolIndex,
              "right": symbolInstance.rightJustifiedTextSymbolIndex
            };
            var autoIndex;
            if (orientation === performance2.WritingMode.vertical) {
              autoIndex = symbolInstance.verticalPlacedTextSymbolIndex;
            } else {
              autoIndex = justifications[performance2.getAnchorJustification(placedAnchor)];
            }
            var indexes = [
              symbolInstance.leftJustifiedTextSymbolIndex,
              symbolInstance.centerJustifiedTextSymbolIndex,
              symbolInstance.rightJustifiedTextSymbolIndex,
              symbolInstance.verticalPlacedTextSymbolIndex
            ];
            for (var i = 0, list = indexes; i < list.length; i += 1) {
              var index = list[i];
              if (index >= 0) {
                if (autoIndex >= 0 && index !== autoIndex) {
                  bucket.text.placedSymbolArray.get(index).crossTileID = 0;
                } else {
                  bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID;
                }
              }
            }
          };
          Placement.prototype.markUsedOrientation = function markUsedOrientation(bucket, orientation, symbolInstance) {
            var horizontal = orientation === performance2.WritingMode.horizontal || orientation === performance2.WritingMode.horizontalOnly ? orientation : 0;
            var vertical = orientation === performance2.WritingMode.vertical ? orientation : 0;
            var horizontalIndexes = [
              symbolInstance.leftJustifiedTextSymbolIndex,
              symbolInstance.centerJustifiedTextSymbolIndex,
              symbolInstance.rightJustifiedTextSymbolIndex
            ];
            for (var i = 0, list = horizontalIndexes; i < list.length; i += 1) {
              var index = list[i];
              bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal;
            }
            if (symbolInstance.verticalPlacedTextSymbolIndex) {
              bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical;
            }
          };
          Placement.prototype.commit = function commit(now) {
            this.commitTime = now;
            this.zoomAtLastRecencyCheck = this.transform.zoom;
            var prevPlacement = this.prevPlacement;
            var placementChanged = false;
            this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0;
            var increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1;
            var prevOpacities = prevPlacement ? prevPlacement.opacities : {};
            var prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {};
            var prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {};
            for (var crossTileID in this.placements) {
              var jointPlacement = this.placements[crossTileID];
              var prevOpacity = prevOpacities[crossTileID];
              if (prevOpacity) {
                this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon);
                placementChanged = placementChanged || jointPlacement.text !== prevOpacity.text.placed || jointPlacement.icon !== prevOpacity.icon.placed;
              } else {
                this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade);
                placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon;
              }
            }
            for (var crossTileID$1 in prevOpacities) {
              var prevOpacity$1 = prevOpacities[crossTileID$1];
              if (!this.opacities[crossTileID$1]) {
                var jointOpacity = new JointOpacityState(prevOpacity$1, increment, false, false);
                if (!jointOpacity.isHidden()) {
                  this.opacities[crossTileID$1] = jointOpacity;
                  placementChanged = placementChanged || prevOpacity$1.text.placed || prevOpacity$1.icon.placed;
                }
              }
            }
            for (var crossTileID$2 in prevOffsets) {
              if (!this.variableOffsets[crossTileID$2] && this.opacities[crossTileID$2] && !this.opacities[crossTileID$2].isHidden()) {
                this.variableOffsets[crossTileID$2] = prevOffsets[crossTileID$2];
              }
            }
            for (var crossTileID$3 in prevOrientations) {
              if (!this.placedOrientations[crossTileID$3] && this.opacities[crossTileID$3] && !this.opacities[crossTileID$3].isHidden()) {
                this.placedOrientations[crossTileID$3] = prevOrientations[crossTileID$3];
              }
            }
            if (placementChanged) {
              this.lastPlacementChangeTime = now;
            } else if (typeof this.lastPlacementChangeTime !== "number") {
              this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now;
            }
          };
          Placement.prototype.updateLayerOpacities = function updateLayerOpacities(styleLayer, tiles) {
            var seenCrossTileIDs = {};
            for (var i = 0, list = tiles; i < list.length; i += 1) {
              var tile = list[i];
              var symbolBucket = tile.getBucket(styleLayer);
              if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) {
                this.updateBucketOpacities(symbolBucket, seenCrossTileIDs, tile.collisionBoxArray);
              }
            }
          };
          Placement.prototype.updateBucketOpacities = function updateBucketOpacities(bucket, seenCrossTileIDs, collisionBoxArray) {
            var this$1 = this;
            if (bucket.hasTextData()) {
              bucket.text.opacityVertexArray.clear();
            }
            if (bucket.hasIconData()) {
              bucket.icon.opacityVertexArray.clear();
            }
            if (bucket.hasIconCollisionBoxData()) {
              bucket.iconCollisionBox.collisionVertexArray.clear();
            }
            if (bucket.hasTextCollisionBoxData()) {
              bucket.textCollisionBox.collisionVertexArray.clear();
            }
            var layout = bucket.layers[0].layout;
            var duplicateOpacityState = new JointOpacityState(null, 0, false, false, true);
            var textAllowOverlap = layout.get("text-allow-overlap");
            var iconAllowOverlap = layout.get("icon-allow-overlap");
            var variablePlacement = layout.get("text-variable-anchor");
            var rotateWithMap = layout.get("text-rotation-alignment") === "map";
            var pitchWithMap = layout.get("text-pitch-alignment") === "map";
            var hasIconTextFit = layout.get("icon-text-fit") !== "none";
            var defaultOpacityState = new JointOpacityState(null, 0, textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get("icon-optional")), iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get("text-optional")), true);
            if (!bucket.collisionArrays && collisionBoxArray && (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData())) {
              bucket.deserializeCollisionBoxes(collisionBoxArray);
            }
            var addOpacities = function(iconOrText, numVertices, opacity) {
              for (var i = 0; i < numVertices / 4; i++) {
                iconOrText.opacityVertexArray.emplaceBack(opacity);
              }
            };
            var loop = function(s2) {
              var symbolInstance = bucket.symbolInstances.get(s2);
              var numHorizontalGlyphVertices = symbolInstance.numHorizontalGlyphVertices;
              var numVerticalGlyphVertices = symbolInstance.numVerticalGlyphVertices;
              var crossTileID = symbolInstance.crossTileID;
              var isDuplicate = seenCrossTileIDs[crossTileID];
              var opacityState = this$1.opacities[crossTileID];
              if (isDuplicate) {
                opacityState = duplicateOpacityState;
              } else if (!opacityState) {
                opacityState = defaultOpacityState;
                this$1.opacities[crossTileID] = opacityState;
              }
              seenCrossTileIDs[crossTileID] = true;
              var hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0;
              var hasIcon = symbolInstance.numIconVertices > 0;
              var placedOrientation = this$1.placedOrientations[symbolInstance.crossTileID];
              var horizontalHidden = placedOrientation === performance2.WritingMode.vertical;
              var verticalHidden = placedOrientation === performance2.WritingMode.horizontal || placedOrientation === performance2.WritingMode.horizontalOnly;
              if (hasText) {
                var packedOpacity = packOpacity(opacityState.text);
                var horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
                addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity);
                var verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
                addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity);
                var symbolHidden = opacityState.text.isHidden();
                [
                  symbolInstance.rightJustifiedTextSymbolIndex,
                  symbolInstance.centerJustifiedTextSymbolIndex,
                  symbolInstance.leftJustifiedTextSymbolIndex
                ].forEach(function(index) {
                  if (index >= 0) {
                    bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0;
                  }
                });
                if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {
                  bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0;
                }
                var prevOffset = this$1.variableOffsets[symbolInstance.crossTileID];
                if (prevOffset) {
                  this$1.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation);
                }
                var prevOrientation = this$1.placedOrientations[symbolInstance.crossTileID];
                if (prevOrientation) {
                  this$1.markUsedJustification(bucket, "left", symbolInstance, prevOrientation);
                  this$1.markUsedOrientation(bucket, prevOrientation, symbolInstance);
                }
              }
              if (hasIcon) {
                var packedOpacity$1 = packOpacity(opacityState.icon);
                var useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden);
                if (symbolInstance.placedIconSymbolIndex >= 0) {
                  var horizontalOpacity$1 = useHorizontal ? packedOpacity$1 : PACKED_HIDDEN_OPACITY;
                  addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity$1);
                  bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden = opacityState.icon.isHidden();
                }
                if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {
                  var verticalOpacity$1 = !useHorizontal ? packedOpacity$1 : PACKED_HIDDEN_OPACITY;
                  addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity$1);
                  bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden = opacityState.icon.isHidden();
                }
              }
              if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) {
                var collisionArrays = bucket.collisionArrays[s2];
                if (collisionArrays) {
                  var shift = new performance2.Point(0, 0);
                  if (collisionArrays.textBox || collisionArrays.verticalTextBox) {
                    var used = true;
                    if (variablePlacement) {
                      var variableOffset = this$1.variableOffsets[crossTileID];
                      if (variableOffset) {
                        shift = calculateVariableLayoutShift(variableOffset.anchor, variableOffset.width, variableOffset.height, variableOffset.textOffset, variableOffset.textBoxScale);
                        if (rotateWithMap) {
                          shift._rotate(pitchWithMap ? this$1.transform.angle : -this$1.transform.angle);
                        }
                      } else {
                        used = false;
                      }
                    }
                    if (collisionArrays.textBox) {
                      updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || horizontalHidden, shift.x, shift.y);
                    }
                    if (collisionArrays.verticalTextBox) {
                      updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || verticalHidden, shift.x, shift.y);
                    }
                  }
                  var verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox);
                  if (collisionArrays.iconBox) {
                    updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, verticalIconUsed, hasIconTextFit ? shift.x : 0, hasIconTextFit ? shift.y : 0);
                  }
                  if (collisionArrays.verticalIconBox) {
                    updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, !verticalIconUsed, hasIconTextFit ? shift.x : 0, hasIconTextFit ? shift.y : 0);
                  }
                }
              }
            };
            for (var s = 0; s < bucket.symbolInstances.length; s++)
              loop(s);
            bucket.sortFeatures(this.transform.angle);
            if (this.retainedQueryData[bucket.bucketInstanceId]) {
              this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder;
            }
            if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) {
              bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray);
            }
            if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) {
              bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray);
            }
            if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) {
              bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray);
            }
            if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) {
              bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray);
            }
            if (bucket.bucketInstanceId in this.collisionCircleArrays) {
              var instance = this.collisionCircleArrays[bucket.bucketInstanceId];
              bucket.placementInvProjMatrix = instance.invProjMatrix;
              bucket.placementViewportMatrix = instance.viewportMatrix;
              bucket.collisionCircleArray = instance.circles;
              delete this.collisionCircleArrays[bucket.bucketInstanceId];
            }
          };
          Placement.prototype.symbolFadeChange = function symbolFadeChange(now) {
            return this.fadeDuration === 0 ? 1 : (now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment;
          };
          Placement.prototype.zoomAdjustment = function zoomAdjustment(zoom) {
            return Math.max(0, (this.transform.zoom - zoom) / 1.5);
          };
          Placement.prototype.hasTransitions = function hasTransitions(now) {
            return this.stale || now - this.lastPlacementChangeTime < this.fadeDuration;
          };
          Placement.prototype.stillRecent = function stillRecent(now, zoom) {
            var durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? 1 - this.zoomAdjustment(zoom) : 1;
            this.zoomAtLastRecencyCheck = zoom;
            return this.commitTime + this.fadeDuration * durationAdjustment > now;
          };
          Placement.prototype.setStale = function setStale() {
            this.stale = true;
          };
          function updateCollisionVertices(collisionVertexArray, placed, notUsed, shiftX, shiftY) {
            collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
            collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
            collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
            collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);
          }
          var shift25 = Math.pow(2, 25);
          var shift24 = Math.pow(2, 24);
          var shift17 = Math.pow(2, 17);
          var shift16 = Math.pow(2, 16);
          var shift9 = Math.pow(2, 9);
          var shift8 = Math.pow(2, 8);
          var shift1 = Math.pow(2, 1);
          function packOpacity(opacityState) {
            if (opacityState.opacity === 0 && !opacityState.placed) {
              return 0;
            } else if (opacityState.opacity === 1 && opacityState.placed) {
              return 4294967295;
            }
            var targetBit = opacityState.placed ? 1 : 0;
            var opacityBits = Math.floor(opacityState.opacity * 127);
            return opacityBits * shift25 + targetBit * shift24 + opacityBits * shift17 + targetBit * shift16 + opacityBits * shift9 + targetBit * shift8 + opacityBits * shift1 + targetBit;
          }
          var PACKED_HIDDEN_OPACITY = 0;
          var LayerPlacement = function LayerPlacement2(styleLayer) {
            this._sortAcrossTiles = styleLayer.layout.get("symbol-z-order") !== "viewport-y" && styleLayer.layout.get("symbol-sort-key").constantOr(1) !== void 0;
            this._currentTileIndex = 0;
            this._currentPartIndex = 0;
            this._seenCrossTileIDs = {};
            this._bucketParts = [];
          };
          LayerPlacement.prototype.continuePlacement = function continuePlacement(tiles, placement, showCollisionBoxes, styleLayer, shouldPausePlacement) {
            var bucketParts = this._bucketParts;
            while (this._currentTileIndex < tiles.length) {
              var tile = tiles[this._currentTileIndex];
              placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles);
              this._currentTileIndex++;
              if (shouldPausePlacement()) {
                return true;
              }
            }
            if (this._sortAcrossTiles) {
              this._sortAcrossTiles = false;
              bucketParts.sort(function(a, b) {
                return a.sortKey - b.sortKey;
              });
            }
            while (this._currentPartIndex < bucketParts.length) {
              var bucketPart = bucketParts[this._currentPartIndex];
              placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes);
              this._currentPartIndex++;
              if (shouldPausePlacement()) {
                return true;
              }
            }
            return false;
          };
          var PauseablePlacement = function PauseablePlacement2(transform, order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, prevPlacement) {
            this.placement = new Placement(transform, fadeDuration, crossSourceCollisions, prevPlacement);
            this._currentPlacementIndex = order.length - 1;
            this._forceFullPlacement = forceFullPlacement;
            this._showCollisionBoxes = showCollisionBoxes;
            this._done = false;
          };
          PauseablePlacement.prototype.isDone = function isDone() {
            return this._done;
          };
          PauseablePlacement.prototype.continuePlacement = function continuePlacement(order, layers, layerTiles) {
            var this$1 = this;
            var startTime = performance2.browser.now();
            var shouldPausePlacement = function() {
              var elapsedTime = performance2.browser.now() - startTime;
              return this$1._forceFullPlacement ? false : elapsedTime > 2;
            };
            while (this._currentPlacementIndex >= 0) {
              var layerId = order[this._currentPlacementIndex];
              var layer = layers[layerId];
              var placementZoom = this.placement.collisionIndex.transform.zoom;
              if (layer.type === "symbol" && (!layer.minzoom || layer.minzoom <= placementZoom) && (!layer.maxzoom || layer.maxzoom > placementZoom)) {
                if (!this._inProgressLayer) {
                  this._inProgressLayer = new LayerPlacement(layer);
                }
                var pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement);
                if (pausePlacement) {
                  return;
                }
                delete this._inProgressLayer;
              }
              this._currentPlacementIndex--;
            }
            this._done = true;
          };
          PauseablePlacement.prototype.commit = function commit(now) {
            this.placement.commit(now);
            return this.placement;
          };
          var roundingFactor = 512 / performance2.EXTENT / 2;
          var TileLayerIndex = function TileLayerIndex2(tileID, symbolInstances, bucketInstanceId) {
            this.tileID = tileID;
            this.indexedSymbolInstances = {};
            this.bucketInstanceId = bucketInstanceId;
            for (var i = 0; i < symbolInstances.length; i++) {
              var symbolInstance = symbolInstances.get(i);
              var key = symbolInstance.key;
              if (!this.indexedSymbolInstances[key]) {
                this.indexedSymbolInstances[key] = [];
              }
              this.indexedSymbolInstances[key].push({
                crossTileID: symbolInstance.crossTileID,
                coord: this.getScaledCoordinates(symbolInstance, tileID)
              });
            }
          };
          TileLayerIndex.prototype.getScaledCoordinates = function getScaledCoordinates(symbolInstance, childTileID) {
            var zDifference = childTileID.canonical.z - this.tileID.canonical.z;
            var scale = roundingFactor / Math.pow(2, zDifference);
            return {
              x: Math.floor((childTileID.canonical.x * performance2.EXTENT + symbolInstance.anchorX) * scale),
              y: Math.floor((childTileID.canonical.y * performance2.EXTENT + symbolInstance.anchorY) * scale)
            };
          };
          TileLayerIndex.prototype.findMatches = function findMatches(symbolInstances, newTileID, zoomCrossTileIDs) {
            var tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z);
            for (var i = 0; i < symbolInstances.length; i++) {
              var symbolInstance = symbolInstances.get(i);
              if (symbolInstance.crossTileID) {
                continue;
              }
              var indexedInstances = this.indexedSymbolInstances[symbolInstance.key];
              if (!indexedInstances) {
                continue;
              }
              var scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID);
              for (var i$1 = 0, list = indexedInstances; i$1 < list.length; i$1 += 1) {
                var thisTileSymbol = list[i$1];
                if (Math.abs(thisTileSymbol.coord.x - scaledSymbolCoord.x) <= tolerance && Math.abs(thisTileSymbol.coord.y - scaledSymbolCoord.y) <= tolerance && !zoomCrossTileIDs[thisTileSymbol.crossTileID]) {
                  zoomCrossTileIDs[thisTileSymbol.crossTileID] = true;
                  symbolInstance.crossTileID = thisTileSymbol.crossTileID;
                  break;
                }
              }
            }
          };
          var CrossTileIDs = function CrossTileIDs2() {
            this.maxCrossTileID = 0;
          };
          CrossTileIDs.prototype.generate = function generate() {
            return ++this.maxCrossTileID;
          };
          var CrossTileSymbolLayerIndex = function CrossTileSymbolLayerIndex2() {
            this.indexes = {};
            this.usedCrossTileIDs = {};
            this.lng = 0;
          };
          CrossTileSymbolLayerIndex.prototype.handleWrapJump = function handleWrapJump(lng) {
            var wrapDelta = Math.round((lng - this.lng) / 360);
            if (wrapDelta !== 0) {
              for (var zoom in this.indexes) {
                var zoomIndexes = this.indexes[zoom];
                var newZoomIndex = {};
                for (var key in zoomIndexes) {
                  var index = zoomIndexes[key];
                  index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta);
                  newZoomIndex[index.tileID.key] = index;
                }
                this.indexes[zoom] = newZoomIndex;
              }
            }
            this.lng = lng;
          };
          CrossTileSymbolLayerIndex.prototype.addBucket = function addBucket(tileID, bucket, crossTileIDs) {
            if (this.indexes[tileID.overscaledZ] && this.indexes[tileID.overscaledZ][tileID.key]) {
              if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === bucket.bucketInstanceId) {
                return false;
              } else {
                this.removeBucketCrossTileIDs(tileID.overscaledZ, this.indexes[tileID.overscaledZ][tileID.key]);
              }
            }
            for (var i = 0; i < bucket.symbolInstances.length; i++) {
              var symbolInstance = bucket.symbolInstances.get(i);
              symbolInstance.crossTileID = 0;
            }
            if (!this.usedCrossTileIDs[tileID.overscaledZ]) {
              this.usedCrossTileIDs[tileID.overscaledZ] = {};
            }
            var zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ];
            for (var zoom in this.indexes) {
              var zoomIndexes = this.indexes[zoom];
              if (Number(zoom) > tileID.overscaledZ) {
                for (var id in zoomIndexes) {
                  var childIndex = zoomIndexes[id];
                  if (childIndex.tileID.isChildOf(tileID)) {
                    childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);
                  }
                }
              } else {
                var parentCoord = tileID.scaledTo(Number(zoom));
                var parentIndex = zoomIndexes[parentCoord.key];
                if (parentIndex) {
                  parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);
                }
              }
            }
            for (var i$1 = 0; i$1 < bucket.symbolInstances.length; i$1++) {
              var symbolInstance$1 = bucket.symbolInstances.get(i$1);
              if (!symbolInstance$1.crossTileID) {
                symbolInstance$1.crossTileID = crossTileIDs.generate();
                zoomCrossTileIDs[symbolInstance$1.crossTileID] = true;
              }
            }
            if (this.indexes[tileID.overscaledZ] === void 0) {
              this.indexes[tileID.overscaledZ] = {};
            }
            this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId);
            return true;
          };
          CrossTileSymbolLayerIndex.prototype.removeBucketCrossTileIDs = function removeBucketCrossTileIDs(zoom, removedBucket) {
            for (var key in removedBucket.indexedSymbolInstances) {
              for (var i = 0, list = removedBucket.indexedSymbolInstances[key]; i < list.length; i += 1) {
                var symbolInstance = list[i];
                delete this.usedCrossTileIDs[zoom][symbolInstance.crossTileID];
              }
            }
          };
          CrossTileSymbolLayerIndex.prototype.removeStaleBuckets = function removeStaleBuckets(currentIDs) {
            var tilesChanged = false;
            for (var z in this.indexes) {
              var zoomIndexes = this.indexes[z];
              for (var tileKey in zoomIndexes) {
                if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) {
                  this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]);
                  delete zoomIndexes[tileKey];
                  tilesChanged = true;
                }
              }
            }
            return tilesChanged;
          };
          var CrossTileSymbolIndex = function CrossTileSymbolIndex2() {
            this.layerIndexes = {};
            this.crossTileIDs = new CrossTileIDs();
            this.maxBucketInstanceId = 0;
            this.bucketsInCurrentPlacement = {};
          };
          CrossTileSymbolIndex.prototype.addLayer = function addLayer(styleLayer, tiles, lng) {
            var layerIndex = this.layerIndexes[styleLayer.id];
            if (layerIndex === void 0) {
              layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex();
            }
            var symbolBucketsChanged = false;
            var currentBucketIDs = {};
            layerIndex.handleWrapJump(lng);
            for (var i = 0, list = tiles; i < list.length; i += 1) {
              var tile = list[i];
              var symbolBucket = tile.getBucket(styleLayer);
              if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0]) {
                continue;
              }
              if (!symbolBucket.bucketInstanceId) {
                symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId;
              }
              if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) {
                symbolBucketsChanged = true;
              }
              currentBucketIDs[symbolBucket.bucketInstanceId] = true;
            }
            if (layerIndex.removeStaleBuckets(currentBucketIDs)) {
              symbolBucketsChanged = true;
            }
            return symbolBucketsChanged;
          };
          CrossTileSymbolIndex.prototype.pruneUnusedLayers = function pruneUnusedLayers(usedLayers) {
            var usedLayerMap = {};
            usedLayers.forEach(function(usedLayer) {
              usedLayerMap[usedLayer] = true;
            });
            for (var layerId in this.layerIndexes) {
              if (!usedLayerMap[layerId]) {
                delete this.layerIndexes[layerId];
              }
            }
          };
          var emitValidationErrors = function(evented, errors) {
            return performance2.emitValidationErrors(evented, errors && errors.filter(function(error) {
              return error.identifier !== "source.canvas";
            }));
          };
          var supportedDiffOperations = performance2.pick(operations, [
            "addLayer",
            "removeLayer",
            "setPaintProperty",
            "setLayoutProperty",
            "setFilter",
            "addSource",
            "removeSource",
            "setLayerZoomRange",
            "setLight",
            "setTransition",
            "setGeoJSONSourceData"
          ]);
          var ignoredDiffOperations = performance2.pick(operations, [
            "setCenter",
            "setZoom",
            "setBearing",
            "setPitch"
          ]);
          var empty = emptyStyle();
          var Style = function(Evented) {
            function Style2(map, options) {
              var this$1 = this;
              if (options === void 0)
                options = {};
              Evented.call(this);
              this.map = map;
              this.dispatcher = new Dispatcher(getGlobalWorkerPool(), this);
              this.imageManager = new ImageManager();
              this.imageManager.setEventedParent(this);
              this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily);
              this.lineAtlas = new LineAtlas(256, 512);
              this.crossTileSymbolIndex = new CrossTileSymbolIndex();
              this._layers = {};
              this._serializedLayers = {};
              this._order = [];
              this.sourceCaches = {};
              this.zoomHistory = new performance2.ZoomHistory();
              this._loaded = false;
              this._availableImages = [];
              this._resetUpdates();
              this.dispatcher.broadcast("setReferrer", performance2.getReferrer());
              var self2 = this;
              this._rtlTextPluginCallback = Style2.registerForPluginStateChange(function(event) {
                var state = {
                  pluginStatus: event.pluginStatus,
                  pluginURL: event.pluginURL
                };
                self2.dispatcher.broadcast("syncRTLPluginState", state, function(err, results) {
                  performance2.triggerPluginCompletionEvent(err);
                  if (results) {
                    var allComplete = results.every(function(elem) {
                      return elem;
                    });
                    if (allComplete) {
                      for (var id in self2.sourceCaches) {
                        self2.sourceCaches[id].reload();
                      }
                    }
                  }
                });
              });
              this.on("data", function(event) {
                if (event.dataType !== "source" || event.sourceDataType !== "metadata") {
                  return;
                }
                var sourceCache = this$1.sourceCaches[event.sourceId];
                if (!sourceCache) {
                  return;
                }
                var source = sourceCache.getSource();
                if (!source || !source.vectorLayerIds) {
                  return;
                }
                for (var layerId in this$1._layers) {
                  var layer = this$1._layers[layerId];
                  if (layer.source === source.id) {
                    this$1._validateLayer(layer);
                  }
                }
              });
            }
            if (Evented)
              Style2.__proto__ = Evented;
            Style2.prototype = Object.create(Evented && Evented.prototype);
            Style2.prototype.constructor = Style2;
            Style2.prototype.loadURL = function loadURL(url, options) {
              var this$1 = this;
              if (options === void 0)
                options = {};
              this.fire(new performance2.Event("dataloading", { dataType: "style" }));
              var validate = typeof options.validate === "boolean" ? options.validate : !performance2.isMapboxURL(url);
              url = this.map._requestManager.normalizeStyleURL(url, options.accessToken);
              var request = this.map._requestManager.transformRequest(url, performance2.ResourceType.Style);
              this._request = performance2.getJSON(request, function(error, json) {
                this$1._request = null;
                if (error) {
                  this$1.fire(new performance2.ErrorEvent(error));
                } else if (json) {
                  this$1._load(json, validate);
                }
              });
            };
            Style2.prototype.loadJSON = function loadJSON(json, options) {
              var this$1 = this;
              if (options === void 0)
                options = {};
              this.fire(new performance2.Event("dataloading", { dataType: "style" }));
              this._request = performance2.browser.frame(function() {
                this$1._request = null;
                this$1._load(json, options.validate !== false);
              });
            };
            Style2.prototype.loadEmpty = function loadEmpty() {
              this.fire(new performance2.Event("dataloading", { dataType: "style" }));
              this._load(empty, false);
            };
            Style2.prototype._load = function _load(json, validate) {
              if (validate && emitValidationErrors(this, performance2.validateStyle(json))) {
                return;
              }
              this._loaded = true;
              this.stylesheet = json;
              for (var id in json.sources) {
                this.addSource(id, json.sources[id], { validate: false });
              }
              if (json.sprite) {
                this._loadSprite(json.sprite);
              } else {
                this.imageManager.setLoaded(true);
              }
              this.glyphManager.setURL(json.glyphs);
              var layers = derefLayers(this.stylesheet.layers);
              this._order = layers.map(function(layer2) {
                return layer2.id;
              });
              this._layers = {};
              this._serializedLayers = {};
              for (var i = 0, list = layers; i < list.length; i += 1) {
                var layer = list[i];
                layer = performance2.createStyleLayer(layer);
                layer.setEventedParent(this, { layer: { id: layer.id } });
                this._layers[layer.id] = layer;
                this._serializedLayers[layer.id] = layer.serialize();
              }
              this.dispatcher.broadcast("setLayers", this._serializeLayers(this._order));
              this.light = new Light(this.stylesheet.light);
              this.fire(new performance2.Event("data", { dataType: "style" }));
              this.fire(new performance2.Event("style.load"));
            };
            Style2.prototype._loadSprite = function _loadSprite(url) {
              var this$1 = this;
              this._spriteRequest = loadSprite(url, this.map._requestManager, function(err, images) {
                this$1._spriteRequest = null;
                if (err) {
                  this$1.fire(new performance2.ErrorEvent(err));
                } else if (images) {
                  for (var id in images) {
                    this$1.imageManager.addImage(id, images[id]);
                  }
                }
                this$1.imageManager.setLoaded(true);
                this$1._availableImages = this$1.imageManager.listImages();
                this$1.dispatcher.broadcast("setImages", this$1._availableImages);
                this$1.fire(new performance2.Event("data", { dataType: "style" }));
              });
            };
            Style2.prototype._validateLayer = function _validateLayer(layer) {
              var sourceCache = this.sourceCaches[layer.source];
              if (!sourceCache) {
                return;
              }
              var sourceLayer = layer.sourceLayer;
              if (!sourceLayer) {
                return;
              }
              var source = sourceCache.getSource();
              if (source.type === "geojson" || source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1) {
                this.fire(new performance2.ErrorEvent(new Error('Source layer "' + sourceLayer + '" does not exist on source "' + source.id + '" as specified by style layer "' + layer.id + '"')));
              }
            };
            Style2.prototype.loaded = function loaded() {
              if (!this._loaded) {
                return false;
              }
              if (Object.keys(this._updatedSources).length) {
                return false;
              }
              for (var id in this.sourceCaches) {
                if (!this.sourceCaches[id].loaded()) {
                  return false;
                }
              }
              if (!this.imageManager.isLoaded()) {
                return false;
              }
              return true;
            };
            Style2.prototype._serializeLayers = function _serializeLayers(ids) {
              var serializedLayers = [];
              for (var i = 0, list = ids; i < list.length; i += 1) {
                var id = list[i];
                var layer = this._layers[id];
                if (layer.type !== "custom") {
                  serializedLayers.push(layer.serialize());
                }
              }
              return serializedLayers;
            };
            Style2.prototype.hasTransitions = function hasTransitions() {
              if (this.light && this.light.hasTransition()) {
                return true;
              }
              for (var id in this.sourceCaches) {
                if (this.sourceCaches[id].hasTransition()) {
                  return true;
                }
              }
              for (var id$1 in this._layers) {
                if (this._layers[id$1].hasTransition()) {
                  return true;
                }
              }
              return false;
            };
            Style2.prototype._checkLoaded = function _checkLoaded() {
              if (!this._loaded) {
                throw new Error("Style is not done loading");
              }
            };
            Style2.prototype.update = function update(parameters) {
              if (!this._loaded) {
                return;
              }
              var changed = this._changed;
              if (this._changed) {
                var updatedIds = Object.keys(this._updatedLayers);
                var removedIds = Object.keys(this._removedLayers);
                if (updatedIds.length || removedIds.length) {
                  this._updateWorkerLayers(updatedIds, removedIds);
                }
                for (var id in this._updatedSources) {
                  var action = this._updatedSources[id];
                  if (action === "reload") {
                    this._reloadSource(id);
                  } else if (action === "clear") {
                    this._clearSource(id);
                  }
                }
                this._updateTilesForChangedImages();
                for (var id$1 in this._updatedPaintProps) {
                  this._layers[id$1].updateTransitions(parameters);
                }
                this.light.updateTransitions(parameters);
                this._resetUpdates();
              }
              var sourcesUsedBefore = {};
              for (var sourceId in this.sourceCaches) {
                var sourceCache = this.sourceCaches[sourceId];
                sourcesUsedBefore[sourceId] = sourceCache.used;
                sourceCache.used = false;
              }
              for (var i = 0, list = this._order; i < list.length; i += 1) {
                var layerId = list[i];
                var layer = this._layers[layerId];
                layer.recalculate(parameters, this._availableImages);
                if (!layer.isHidden(parameters.zoom) && layer.source) {
                  this.sourceCaches[layer.source].used = true;
                }
              }
              for (var sourceId$1 in sourcesUsedBefore) {
                var sourceCache$1 = this.sourceCaches[sourceId$1];
                if (sourcesUsedBefore[sourceId$1] !== sourceCache$1.used) {
                  sourceCache$1.fire(new performance2.Event("data", {
                    sourceDataType: "visibility",
                    dataType: "source",
                    sourceId: sourceId$1
                  }));
                }
              }
              this.light.recalculate(parameters);
              this.z = parameters.zoom;
              if (changed) {
                this.fire(new performance2.Event("data", { dataType: "style" }));
              }
            };
            Style2.prototype._updateTilesForChangedImages = function _updateTilesForChangedImages() {
              var changedImages = Object.keys(this._changedImages);
              if (changedImages.length) {
                for (var name2 in this.sourceCaches) {
                  this.sourceCaches[name2].reloadTilesForDependencies([
                    "icons",
                    "patterns"
                  ], changedImages);
                }
                this._changedImages = {};
              }
            };
            Style2.prototype._updateWorkerLayers = function _updateWorkerLayers(updatedIds, removedIds) {
              this.dispatcher.broadcast("updateLayers", {
                layers: this._serializeLayers(updatedIds),
                removedIds
              });
            };
            Style2.prototype._resetUpdates = function _resetUpdates() {
              this._changed = false;
              this._updatedLayers = {};
              this._removedLayers = {};
              this._updatedSources = {};
              this._updatedPaintProps = {};
              this._changedImages = {};
            };
            Style2.prototype.setState = function setState(nextState) {
              var this$1 = this;
              this._checkLoaded();
              if (emitValidationErrors(this, performance2.validateStyle(nextState))) {
                return false;
              }
              nextState = performance2.clone$1(nextState);
              nextState.layers = derefLayers(nextState.layers);
              var changes = diffStyles(this.serialize(), nextState).filter(function(op) {
                return !(op.command in ignoredDiffOperations);
              });
              if (changes.length === 0) {
                return false;
              }
              var unimplementedOps = changes.filter(function(op) {
                return !(op.command in supportedDiffOperations);
              });
              if (unimplementedOps.length > 0) {
                throw new Error("Unimplemented: " + unimplementedOps.map(function(op) {
                  return op.command;
                }).join(", ") + ".");
              }
              changes.forEach(function(op) {
                if (op.command === "setTransition") {
                  return;
                }
                this$1[op.command].apply(this$1, op.args);
              });
              this.stylesheet = nextState;
              return true;
            };
            Style2.prototype.addImage = function addImage(id, image) {
              if (this.getImage(id)) {
                return this.fire(new performance2.ErrorEvent(new Error("An image with this name already exists.")));
              }
              this.imageManager.addImage(id, image);
              this._afterImageUpdated(id);
            };
            Style2.prototype.updateImage = function updateImage(id, image) {
              this.imageManager.updateImage(id, image);
            };
            Style2.prototype.getImage = function getImage(id) {
              return this.imageManager.getImage(id);
            };
            Style2.prototype.removeImage = function removeImage(id) {
              if (!this.getImage(id)) {
                return this.fire(new performance2.ErrorEvent(new Error("No image with this name exists.")));
              }
              this.imageManager.removeImage(id);
              this._afterImageUpdated(id);
            };
            Style2.prototype._afterImageUpdated = function _afterImageUpdated(id) {
              this._availableImages = this.imageManager.listImages();
              this._changedImages[id] = true;
              this._changed = true;
              this.dispatcher.broadcast("setImages", this._availableImages);
              this.fire(new performance2.Event("data", { dataType: "style" }));
            };
            Style2.prototype.listImages = function listImages() {
              this._checkLoaded();
              return this.imageManager.listImages();
            };
            Style2.prototype.addSource = function addSource2(id, source, options) {
              var this$1 = this;
              if (options === void 0)
                options = {};
              this._checkLoaded();
              if (this.sourceCaches[id] !== void 0) {
                throw new Error("There is already a source with this ID");
              }
              if (!source.type) {
                throw new Error("The type property must be defined, but only the following properties were given: " + Object.keys(source).join(", ") + ".");
              }
              var builtIns = [
                "vector",
                "raster",
                "geojson",
                "video",
                "image"
              ];
              var shouldValidate = builtIns.indexOf(source.type) >= 0;
              if (shouldValidate && this._validate(performance2.validateStyle.source, "sources." + id, source, null, options)) {
                return;
              }
              if (this.map && this.map._collectResourceTiming) {
                source.collectResourceTiming = true;
              }
              var sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher);
              sourceCache.style = this;
              sourceCache.setEventedParent(this, function() {
                return {
                  isSourceLoaded: this$1.loaded(),
                  source: sourceCache.serialize(),
                  sourceId: id
                };
              });
              sourceCache.onAdd(this.map);
              this._changed = true;
            };
            Style2.prototype.removeSource = function removeSource2(id) {
              this._checkLoaded();
              if (this.sourceCaches[id] === void 0) {
                throw new Error("There is no source with this ID");
              }
              for (var layerId in this._layers) {
                if (this._layers[layerId].source === id) {
                  return this.fire(new performance2.ErrorEvent(new Error('Source "' + id + '" cannot be removed while layer "' + layerId + '" is using it.')));
                }
              }
              var sourceCache = this.sourceCaches[id];
              delete this.sourceCaches[id];
              delete this._updatedSources[id];
              sourceCache.fire(new performance2.Event("data", {
                sourceDataType: "metadata",
                dataType: "source",
                sourceId: id
              }));
              sourceCache.setEventedParent(null);
              sourceCache.clearTiles();
              if (sourceCache.onRemove) {
                sourceCache.onRemove(this.map);
              }
              this._changed = true;
            };
            Style2.prototype.setGeoJSONSourceData = function setGeoJSONSourceData(id, data) {
              this._checkLoaded();
              var geojsonSource = this.sourceCaches[id].getSource();
              geojsonSource.setData(data);
              this._changed = true;
            };
            Style2.prototype.getSource = function getSource(id) {
              return this.sourceCaches[id] && this.sourceCaches[id].getSource();
            };
            Style2.prototype.addLayer = function addLayer(layerObject, before, options) {
              if (options === void 0)
                options = {};
              this._checkLoaded();
              var id = layerObject.id;
              if (this.getLayer(id)) {
                this.fire(new performance2.ErrorEvent(new Error('Layer with id "' + id + '" already exists on this map')));
                return;
              }
              var layer;
              if (layerObject.type === "custom") {
                if (emitValidationErrors(this, performance2.validateCustomStyleLayer(layerObject))) {
                  return;
                }
                layer = performance2.createStyleLayer(layerObject);
              } else {
                if (typeof layerObject.source === "object") {
                  this.addSource(id, layerObject.source);
                  layerObject = performance2.clone$1(layerObject);
                  layerObject = performance2.extend(layerObject, { source: id });
                }
                if (this._validate(performance2.validateStyle.layer, "layers." + id, layerObject, { arrayIndex: -1 }, options)) {
                  return;
                }
                layer = performance2.createStyleLayer(layerObject);
                this._validateLayer(layer);
                layer.setEventedParent(this, { layer: { id } });
                this._serializedLayers[layer.id] = layer.serialize();
              }
              var index = before ? this._order.indexOf(before) : this._order.length;
              if (before && index === -1) {
                this.fire(new performance2.ErrorEvent(new Error('Layer with id "' + before + '" does not exist on this map.')));
                return;
              }
              this._order.splice(index, 0, id);
              this._layerOrderChanged = true;
              this._layers[id] = layer;
              if (this._removedLayers[id] && layer.source && layer.type !== "custom") {
                var removed = this._removedLayers[id];
                delete this._removedLayers[id];
                if (removed.type !== layer.type) {
                  this._updatedSources[layer.source] = "clear";
                } else {
                  this._updatedSources[layer.source] = "reload";
                  this.sourceCaches[layer.source].pause();
                }
              }
              this._updateLayer(layer);
              if (layer.onAdd) {
                layer.onAdd(this.map);
              }
            };
            Style2.prototype.moveLayer = function moveLayer(id, before) {
              this._checkLoaded();
              this._changed = true;
              var layer = this._layers[id];
              if (!layer) {
                this.fire(new performance2.ErrorEvent(new Error("The layer '" + id + "' does not exist in the map's style and cannot be moved.")));
                return;
              }
              if (id === before) {
                return;
              }
              var index = this._order.indexOf(id);
              this._order.splice(index, 1);
              var newIndex = before ? this._order.indexOf(before) : this._order.length;
              if (before && newIndex === -1) {
                this.fire(new performance2.ErrorEvent(new Error('Layer with id "' + before + '" does not exist on this map.')));
                return;
              }
              this._order.splice(newIndex, 0, id);
              this._layerOrderChanged = true;
            };
            Style2.prototype.removeLayer = function removeLayer(id) {
              this._checkLoaded();
              var layer = this._layers[id];
              if (!layer) {
                this.fire(new performance2.ErrorEvent(new Error("The layer '" + id + "' does not exist in the map's style and cannot be removed.")));
                return;
              }
              layer.setEventedParent(null);
              var index = this._order.indexOf(id);
              this._order.splice(index, 1);
              this._layerOrderChanged = true;
              this._changed = true;
              this._removedLayers[id] = layer;
              delete this._layers[id];
              delete this._serializedLayers[id];
              delete this._updatedLayers[id];
              delete this._updatedPaintProps[id];
              if (layer.onRemove) {
                layer.onRemove(this.map);
              }
            };
            Style2.prototype.getLayer = function getLayer(id) {
              return this._layers[id];
            };
            Style2.prototype.hasLayer = function hasLayer(id) {
              return id in this._layers;
            };
            Style2.prototype.setLayerZoomRange = function setLayerZoomRange(layerId, minzoom, maxzoom) {
              this._checkLoaded();
              var layer = this.getLayer(layerId);
              if (!layer) {
                this.fire(new performance2.ErrorEvent(new Error("The layer '" + layerId + "' does not exist in the map's style and cannot have zoom extent.")));
                return;
              }
              if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) {
                return;
              }
              if (minzoom != null) {
                layer.minzoom = minzoom;
              }
              if (maxzoom != null) {
                layer.maxzoom = maxzoom;
              }
              this._updateLayer(layer);
            };
            Style2.prototype.setFilter = function setFilter(layerId, filter, options) {
              if (options === void 0)
                options = {};
              this._checkLoaded();
              var layer = this.getLayer(layerId);
              if (!layer) {
                this.fire(new performance2.ErrorEvent(new Error("The layer '" + layerId + "' does not exist in the map's style and cannot be filtered.")));
                return;
              }
              if (performance2.deepEqual(layer.filter, filter)) {
                return;
              }
              if (filter === null || filter === void 0) {
                layer.filter = void 0;
                this._updateLayer(layer);
                return;
              }
              if (this._validate(performance2.validateStyle.filter, "layers." + layer.id + ".filter", filter, null, options)) {
                return;
              }
              layer.filter = performance2.clone$1(filter);
              this._updateLayer(layer);
            };
            Style2.prototype.getFilter = function getFilter(layer) {
              return performance2.clone$1(this.getLayer(layer).filter);
            };
            Style2.prototype.setLayoutProperty = function setLayoutProperty(layerId, name2, value, options) {
              if (options === void 0)
                options = {};
              this._checkLoaded();
              var layer = this.getLayer(layerId);
              if (!layer) {
                this.fire(new performance2.ErrorEvent(new Error("The layer '" + layerId + "' does not exist in the map's style and cannot be styled.")));
                return;
              }
              if (performance2.deepEqual(layer.getLayoutProperty(name2), value)) {
                return;
              }
              layer.setLayoutProperty(name2, value, options);
              this._updateLayer(layer);
            };
            Style2.prototype.getLayoutProperty = function getLayoutProperty(layerId, name2) {
              var layer = this.getLayer(layerId);
              if (!layer) {
                this.fire(new performance2.ErrorEvent(new Error("The layer '" + layerId + "' does not exist in the map's style.")));
                return;
              }
              return layer.getLayoutProperty(name2);
            };
            Style2.prototype.setPaintProperty = function setPaintProperty(layerId, name2, value, options) {
              if (options === void 0)
                options = {};
              this._checkLoaded();
              var layer = this.getLayer(layerId);
              if (!layer) {
                this.fire(new performance2.ErrorEvent(new Error("The layer '" + layerId + "' does not exist in the map's style and cannot be styled.")));
                return;
              }
              if (performance2.deepEqual(layer.getPaintProperty(name2), value)) {
                return;
              }
              var requiresRelayout = layer.setPaintProperty(name2, value, options);
              if (requiresRelayout) {
                this._updateLayer(layer);
              }
              this._changed = true;
              this._updatedPaintProps[layerId] = true;
            };
            Style2.prototype.getPaintProperty = function getPaintProperty(layer, name2) {
              return this.getLayer(layer).getPaintProperty(name2);
            };
            Style2.prototype.setFeatureState = function setFeatureState(target, state) {
              this._checkLoaded();
              var sourceId = target.source;
              var sourceLayer = target.sourceLayer;
              var sourceCache = this.sourceCaches[sourceId];
              if (sourceCache === void 0) {
                this.fire(new performance2.ErrorEvent(new Error("The source '" + sourceId + "' does not exist in the map's style.")));
                return;
              }
              var sourceType = sourceCache.getSource().type;
              if (sourceType === "geojson" && sourceLayer) {
                this.fire(new performance2.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));
                return;
              }
              if (sourceType === "vector" && !sourceLayer) {
                this.fire(new performance2.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));
                return;
              }
              if (target.id === void 0) {
                this.fire(new performance2.ErrorEvent(new Error("The feature id parameter must be provided.")));
              }
              sourceCache.setFeatureState(sourceLayer, target.id, state);
            };
            Style2.prototype.removeFeatureState = function removeFeatureState(target, key) {
              this._checkLoaded();
              var sourceId = target.source;
              var sourceCache = this.sourceCaches[sourceId];
              if (sourceCache === void 0) {
                this.fire(new performance2.ErrorEvent(new Error("The source '" + sourceId + "' does not exist in the map's style.")));
                return;
              }
              var sourceType = sourceCache.getSource().type;
              var sourceLayer = sourceType === "vector" ? target.sourceLayer : void 0;
              if (sourceType === "vector" && !sourceLayer) {
                this.fire(new performance2.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));
                return;
              }
              if (key && (typeof target.id !== "string" && typeof target.id !== "number")) {
                this.fire(new performance2.ErrorEvent(new Error("A feature id is required to remove its specific state property.")));
                return;
              }
              sourceCache.removeFeatureState(sourceLayer, target.id, key);
            };
            Style2.prototype.getFeatureState = function getFeatureState(target) {
              this._checkLoaded();
              var sourceId = target.source;
              var sourceLayer = target.sourceLayer;
              var sourceCache = this.sourceCaches[sourceId];
              if (sourceCache === void 0) {
                this.fire(new performance2.ErrorEvent(new Error("The source '" + sourceId + "' does not exist in the map's style.")));
                return;
              }
              var sourceType = sourceCache.getSource().type;
              if (sourceType === "vector" && !sourceLayer) {
                this.fire(new performance2.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));
                return;
              }
              if (target.id === void 0) {
                this.fire(new performance2.ErrorEvent(new Error("The feature id parameter must be provided.")));
              }
              return sourceCache.getFeatureState(sourceLayer, target.id);
            };
            Style2.prototype.getTransition = function getTransition() {
              return performance2.extend({
                duration: 300,
                delay: 0
              }, this.stylesheet && this.stylesheet.transition);
            };
            Style2.prototype.serialize = function serialize() {
              return performance2.filterObject({
                version: this.stylesheet.version,
                name: this.stylesheet.name,
                metadata: this.stylesheet.metadata,
                light: this.stylesheet.light,
                center: this.stylesheet.center,
                zoom: this.stylesheet.zoom,
                bearing: this.stylesheet.bearing,
                pitch: this.stylesheet.pitch,
                sprite: this.stylesheet.sprite,
                glyphs: this.stylesheet.glyphs,
                transition: this.stylesheet.transition,
                sources: performance2.mapObject(this.sourceCaches, function(source) {
                  return source.serialize();
                }),
                layers: this._serializeLayers(this._order)
              }, function(value) {
                return value !== void 0;
              });
            };
            Style2.prototype._updateLayer = function _updateLayer(layer) {
              this._updatedLayers[layer.id] = true;
              if (layer.source && !this._updatedSources[layer.source] && this.sourceCaches[layer.source].getSource().type !== "raster") {
                this._updatedSources[layer.source] = "reload";
                this.sourceCaches[layer.source].pause();
              }
              this._changed = true;
            };
            Style2.prototype._flattenAndSortRenderedFeatures = function _flattenAndSortRenderedFeatures(sourceResults) {
              var this$1 = this;
              var isLayer3D = function(layerId2) {
                return this$1._layers[layerId2].type === "fill-extrusion";
              };
              var layerIndex = {};
              var features3D = [];
              for (var l = this._order.length - 1; l >= 0; l--) {
                var layerId = this._order[l];
                if (isLayer3D(layerId)) {
                  layerIndex[layerId] = l;
                  for (var i$2 = 0, list$1 = sourceResults; i$2 < list$1.length; i$2 += 1) {
                    var sourceResult = list$1[i$2];
                    var layerFeatures = sourceResult[layerId];
                    if (layerFeatures) {
                      for (var i$1 = 0, list = layerFeatures; i$1 < list.length; i$1 += 1) {
                        var featureWrapper = list[i$1];
                        features3D.push(featureWrapper);
                      }
                    }
                  }
                }
              }
              features3D.sort(function(a, b) {
                return b.intersectionZ - a.intersectionZ;
              });
              var features = [];
              for (var l$1 = this._order.length - 1; l$1 >= 0; l$1--) {
                var layerId$1 = this._order[l$1];
                if (isLayer3D(layerId$1)) {
                  for (var i = features3D.length - 1; i >= 0; i--) {
                    var topmost3D = features3D[i].feature;
                    if (layerIndex[topmost3D.layer.id] < l$1) {
                      break;
                    }
                    features.push(topmost3D);
                    features3D.pop();
                  }
                } else {
                  for (var i$4 = 0, list$3 = sourceResults; i$4 < list$3.length; i$4 += 1) {
                    var sourceResult$1 = list$3[i$4];
                    var layerFeatures$1 = sourceResult$1[layerId$1];
                    if (layerFeatures$1) {
                      for (var i$3 = 0, list$2 = layerFeatures$1; i$3 < list$2.length; i$3 += 1) {
                        var featureWrapper$1 = list$2[i$3];
                        features.push(featureWrapper$1.feature);
                      }
                    }
                  }
                }
              }
              return features;
            };
            Style2.prototype.queryRenderedFeatures = function queryRenderedFeatures$1(queryGeometry, params, transform) {
              if (params && params.filter) {
                this._validate(performance2.validateStyle.filter, "queryRenderedFeatures.filter", params.filter, null, params);
              }
              var includedSources = {};
              if (params && params.layers) {
                if (!Array.isArray(params.layers)) {
                  this.fire(new performance2.ErrorEvent(new Error("parameters.layers must be an Array.")));
                  return [];
                }
                for (var i = 0, list = params.layers; i < list.length; i += 1) {
                  var layerId = list[i];
                  var layer = this._layers[layerId];
                  if (!layer) {
                    this.fire(new performance2.ErrorEvent(new Error("The layer '" + layerId + "' does not exist in the map's style and cannot be queried for features.")));
                    return [];
                  }
                  includedSources[layer.source] = true;
                }
              }
              var sourceResults = [];
              params.availableImages = this._availableImages;
              for (var id in this.sourceCaches) {
                if (params.layers && !includedSources[id]) {
                  continue;
                }
                sourceResults.push(queryRenderedFeatures(this.sourceCaches[id], this._layers, this._serializedLayers, queryGeometry, params, transform));
              }
              if (this.placement) {
                sourceResults.push(queryRenderedSymbols(this._layers, this._serializedLayers, this.sourceCaches, queryGeometry, params, this.placement.collisionIndex, this.placement.retainedQueryData));
              }
              return this._flattenAndSortRenderedFeatures(sourceResults);
            };
            Style2.prototype.querySourceFeatures = function querySourceFeatures$1(sourceID, params) {
              if (params && params.filter) {
                this._validate(performance2.validateStyle.filter, "querySourceFeatures.filter", params.filter, null, params);
              }
              var sourceCache = this.sourceCaches[sourceID];
              return sourceCache ? querySourceFeatures(sourceCache, params) : [];
            };
            Style2.prototype.addSourceType = function addSourceType(name2, SourceType, callback) {
              if (Style2.getSourceType(name2)) {
                return callback(new Error('A source type called "' + name2 + '" already exists.'));
              }
              Style2.setSourceType(name2, SourceType);
              if (!SourceType.workerSourceURL) {
                return callback(null, null);
              }
              this.dispatcher.broadcast("loadWorkerSource", {
                name: name2,
                url: SourceType.workerSourceURL
              }, callback);
            };
            Style2.prototype.getLight = function getLight() {
              return this.light.getLight();
            };
            Style2.prototype.setLight = function setLight(lightOptions, options) {
              if (options === void 0)
                options = {};
              this._checkLoaded();
              var light = this.light.getLight();
              var _update = false;
              for (var key in lightOptions) {
                if (!performance2.deepEqual(lightOptions[key], light[key])) {
                  _update = true;
                  break;
                }
              }
              if (!_update) {
                return;
              }
              var parameters = {
                now: performance2.browser.now(),
                transition: performance2.extend({
                  duration: 300,
                  delay: 0
                }, this.stylesheet.transition)
              };
              this.light.setLight(lightOptions, options);
              this.light.updateTransitions(parameters);
            };
            Style2.prototype._validate = function _validate(validate, key, value, props, options) {
              if (options === void 0)
                options = {};
              if (options && options.validate === false) {
                return false;
              }
              return emitValidationErrors(this, validate.call(performance2.validateStyle, performance2.extend({
                key,
                style: this.serialize(),
                value,
                styleSpec: performance2.styleSpec
              }, props)));
            };
            Style2.prototype._remove = function _remove() {
              if (this._request) {
                this._request.cancel();
                this._request = null;
              }
              if (this._spriteRequest) {
                this._spriteRequest.cancel();
                this._spriteRequest = null;
              }
              performance2.evented.off("pluginStateChange", this._rtlTextPluginCallback);
              for (var layerId in this._layers) {
                var layer = this._layers[layerId];
                layer.setEventedParent(null);
              }
              for (var id in this.sourceCaches) {
                this.sourceCaches[id].clearTiles();
                this.sourceCaches[id].setEventedParent(null);
              }
              this.imageManager.setEventedParent(null);
              this.setEventedParent(null);
              this.dispatcher.remove();
            };
            Style2.prototype._clearSource = function _clearSource(id) {
              this.sourceCaches[id].clearTiles();
            };
            Style2.prototype._reloadSource = function _reloadSource(id) {
              this.sourceCaches[id].resume();
              this.sourceCaches[id].reload();
            };
            Style2.prototype._updateSources = function _updateSources(transform) {
              for (var id in this.sourceCaches) {
                this.sourceCaches[id].update(transform);
              }
            };
            Style2.prototype._generateCollisionBoxes = function _generateCollisionBoxes() {
              for (var id in this.sourceCaches) {
                this._reloadSource(id);
              }
            };
            Style2.prototype._updatePlacement = function _updatePlacement(transform, showCollisionBoxes, fadeDuration, crossSourceCollisions, forceFullPlacement) {
              if (forceFullPlacement === void 0)
                forceFullPlacement = false;
              var symbolBucketsChanged = false;
              var placementCommitted = false;
              var layerTiles = {};
              for (var i = 0, list = this._order; i < list.length; i += 1) {
                var layerID = list[i];
                var styleLayer = this._layers[layerID];
                if (styleLayer.type !== "symbol") {
                  continue;
                }
                if (!layerTiles[styleLayer.source]) {
                  var sourceCache = this.sourceCaches[styleLayer.source];
                  layerTiles[styleLayer.source] = sourceCache.getRenderableIds(true).map(function(id) {
                    return sourceCache.getTileByID(id);
                  }).sort(function(a, b) {
                    return b.tileID.overscaledZ - a.tileID.overscaledZ || (a.tileID.isLessThan(b.tileID) ? -1 : 1);
                  });
                }
                var layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng);
                symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged;
              }
              this.crossTileSymbolIndex.pruneUnusedLayers(this._order);
              forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0;
              if (forceFullPlacement || !this.pauseablePlacement || this.pauseablePlacement.isDone() && !this.placement.stillRecent(performance2.browser.now(), transform.zoom)) {
                this.pauseablePlacement = new PauseablePlacement(transform, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement);
                this._layerOrderChanged = false;
              }
              if (this.pauseablePlacement.isDone()) {
                this.placement.setStale();
              } else {
                this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles);
                if (this.pauseablePlacement.isDone()) {
                  this.placement = this.pauseablePlacement.commit(performance2.browser.now());
                  placementCommitted = true;
                }
                if (symbolBucketsChanged) {
                  this.pauseablePlacement.placement.setStale();
                }
              }
              if (placementCommitted || symbolBucketsChanged) {
                for (var i$1 = 0, list$1 = this._order; i$1 < list$1.length; i$1 += 1) {
                  var layerID$1 = list$1[i$1];
                  var styleLayer$1 = this._layers[layerID$1];
                  if (styleLayer$1.type !== "symbol") {
                    continue;
                  }
                  this.placement.updateLayerOpacities(styleLayer$1, layerTiles[styleLayer$1.source]);
                }
              }
              var needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(performance2.browser.now());
              return needsRerender;
            };
            Style2.prototype._releaseSymbolFadeTiles = function _releaseSymbolFadeTiles() {
              for (var id in this.sourceCaches) {
                this.sourceCaches[id].releaseSymbolFadeTiles();
              }
            };
            Style2.prototype.getImages = function getImages(mapId, params, callback) {
              this.imageManager.getImages(params.icons, callback);
              this._updateTilesForChangedImages();
              var sourceCache = this.sourceCaches[params.source];
              if (sourceCache) {
                sourceCache.setDependencies(params.tileID.key, params.type, params.icons);
              }
            };
            Style2.prototype.getGlyphs = function getGlyphs(mapId, params, callback) {
              this.glyphManager.getGlyphs(params.stacks, callback);
            };
            Style2.prototype.getResource = function getResource(mapId, params, callback) {
              return performance2.makeRequest(params, callback);
            };
            return Style2;
          }(performance2.Evented);
          Style.getSourceType = getType;
          Style.setSourceType = setType;
          Style.registerForPluginStateChange = performance2.registerForPluginStateChange;
          var posAttributes = performance2.createLayout([{
            name: "a_pos",
            type: "Int16",
            components: 2
          }]);
          var preludeFrag = "#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif";
          var preludeVert = "#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}";
          var backgroundFrag = "uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var backgroundVert = "attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}";
          var backgroundPatternFrag = "uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var backgroundPatternVert = "uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}";
          var circleFrag = "varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var circleVert = "uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,0,1);} else {gl_Position=u_matrix*vec4(circle_center,0,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}";
          var clippingMaskFrag = "void main() {gl_FragColor=vec4(1.0);}";
          var clippingMaskVert = "attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}";
          var heatmapFrag = "uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var heatmapVert = "uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,0,1);gl_Position=u_matrix*pos;}";
          var heatmapTextureFrag = "uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}";
          var heatmapTextureVert = "uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}";
          var collisionBoxFrag = "varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}";
          var collisionBoxVert = "attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,0.0,1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}";
          var collisionCircleFrag = "varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}";
          var collisionCircleVert = "attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd  =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz  /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}";
          var debugFrag = "uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}";
          var debugVert = "attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,0,1);}";
          var fillFrag = "#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var fillVert = "attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}";
          var fillOutlineFrag = "varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var fillOutlineVert = "attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}";
          var fillOutlinePatternFrag = "uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var fillOutlinePatternVert = "uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}";
          var fillPatternFrag = "uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var fillPatternVert = "uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}";
          var fillExtrusionFrag = "varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var fillExtrusionVert = "uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}";
          var fillExtrusionPatternFrag = "uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var fillExtrusionPatternVert = "uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}";
          var hillshadePrepareFrag = "#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var hillshadePrepareVert = "uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}";
          var hillshadeFrag = "uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var hillshadeVert = "uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}";
          var lineFrag = "uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var lineVert = "\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}";
          var lineGradientFrag = "uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var lineGradientVert = "\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}";
          var linePatternFrag = "uniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var linePatternVert = "\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}";
          var lineSDFFrag = "uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var lineSDFVert = "\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}";
          var rasterFrag = "uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var rasterVert = "uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}";
          var symbolIconFrag = "uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var symbolIconVert = "const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),0.0,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;v_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));}";
          var symbolSDFFrag = "#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var symbolSDFVert = "const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}";
          var symbolTextAndIconFrag = "#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}";
          var symbolTextAndIconVert = "const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}";
          var prelude = compile(preludeFrag, preludeVert);
          var background = compile(backgroundFrag, backgroundVert);
          var backgroundPattern = compile(backgroundPatternFrag, backgroundPatternVert);
          var circle = compile(circleFrag, circleVert);
          var clippingMask = compile(clippingMaskFrag, clippingMaskVert);
          var heatmap = compile(heatmapFrag, heatmapVert);
          var heatmapTexture = compile(heatmapTextureFrag, heatmapTextureVert);
          var collisionBox = compile(collisionBoxFrag, collisionBoxVert);
          var collisionCircle = compile(collisionCircleFrag, collisionCircleVert);
          var debug = compile(debugFrag, debugVert);
          var fill = compile(fillFrag, fillVert);
          var fillOutline = compile(fillOutlineFrag, fillOutlineVert);
          var fillOutlinePattern = compile(fillOutlinePatternFrag, fillOutlinePatternVert);
          var fillPattern = compile(fillPatternFrag, fillPatternVert);
          var fillExtrusion = compile(fillExtrusionFrag, fillExtrusionVert);
          var fillExtrusionPattern = compile(fillExtrusionPatternFrag, fillExtrusionPatternVert);
          var hillshadePrepare = compile(hillshadePrepareFrag, hillshadePrepareVert);
          var hillshade = compile(hillshadeFrag, hillshadeVert);
          var line = compile(lineFrag, lineVert);
          var lineGradient = compile(lineGradientFrag, lineGradientVert);
          var linePattern = compile(linePatternFrag, linePatternVert);
          var lineSDF = compile(lineSDFFrag, lineSDFVert);
          var raster = compile(rasterFrag, rasterVert);
          var symbolIcon = compile(symbolIconFrag, symbolIconVert);
          var symbolSDF = compile(symbolSDFFrag, symbolSDFVert);
          var symbolTextAndIcon = compile(symbolTextAndIconFrag, symbolTextAndIconVert);
          function compile(fragmentSource, vertexSource) {
            var re = /#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g;
            var staticAttributes = vertexSource.match(/attribute ([\w]+) ([\w]+)/g);
            var fragmentUniforms = fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);
            var vertexUniforms = vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);
            var staticUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms;
            var fragmentPragmas = {};
            fragmentSource = fragmentSource.replace(re, function(match, operation, precision, type, name2) {
              fragmentPragmas[name2] = true;
              if (operation === "define") {
                return "\n#ifndef HAS_UNIFORM_u_" + name2 + "\nvarying " + precision + " " + type + " " + name2 + ";\n#else\nuniform " + precision + " " + type + " u_" + name2 + ";\n#endif\n";
              } else {
                return "\n#ifdef HAS_UNIFORM_u_" + name2 + "\n    " + precision + " " + type + " " + name2 + " = u_" + name2 + ";\n#endif\n";
              }
            });
            vertexSource = vertexSource.replace(re, function(match, operation, precision, type, name2) {
              var attrType = type === "float" ? "vec2" : "vec4";
              var unpackType = name2.match(/color/) ? "color" : attrType;
              if (fragmentPragmas[name2]) {
                if (operation === "define") {
                  return "\n#ifndef HAS_UNIFORM_u_" + name2 + "\nuniform lowp float u_" + name2 + "_t;\nattribute " + precision + " " + attrType + " a_" + name2 + ";\nvarying " + precision + " " + type + " " + name2 + ";\n#else\nuniform " + precision + " " + type + " u_" + name2 + ";\n#endif\n";
                } else {
                  if (unpackType === "vec4") {
                    return "\n#ifndef HAS_UNIFORM_u_" + name2 + "\n    " + name2 + " = a_" + name2 + ";\n#else\n    " + precision + " " + type + " " + name2 + " = u_" + name2 + ";\n#endif\n";
                  } else {
                    return "\n#ifndef HAS_UNIFORM_u_" + name2 + "\n    " + name2 + " = unpack_mix_" + unpackType + "(a_" + name2 + ", u_" + name2 + "_t);\n#else\n    " + precision + " " + type + " " + name2 + " = u_" + name2 + ";\n#endif\n";
                  }
                }
              } else {
                if (operation === "define") {
                  return "\n#ifndef HAS_UNIFORM_u_" + name2 + "\nuniform lowp float u_" + name2 + "_t;\nattribute " + precision + " " + attrType + " a_" + name2 + ";\n#else\nuniform " + precision + " " + type + " u_" + name2 + ";\n#endif\n";
                } else {
                  if (unpackType === "vec4") {
                    return "\n#ifndef HAS_UNIFORM_u_" + name2 + "\n    " + precision + " " + type + " " + name2 + " = a_" + name2 + ";\n#else\n    " + precision + " " + type + " " + name2 + " = u_" + name2 + ";\n#endif\n";
                  } else {
                    return "\n#ifndef HAS_UNIFORM_u_" + name2 + "\n    " + precision + " " + type + " " + name2 + " = unpack_mix_" + unpackType + "(a_" + name2 + ", u_" + name2 + "_t);\n#else\n    " + precision + " " + type + " " + name2 + " = u_" + name2 + ";\n#endif\n";
                  }
                }
              }
            });
            return {
              fragmentSource,
              vertexSource,
              staticAttributes,
              staticUniforms
            };
          }
          var shaders = /* @__PURE__ */ Object.freeze({
            __proto__: null,
            prelude,
            background,
            backgroundPattern,
            circle,
            clippingMask,
            heatmap,
            heatmapTexture,
            collisionBox,
            collisionCircle,
            debug,
            fill,
            fillOutline,
            fillOutlinePattern,
            fillPattern,
            fillExtrusion,
            fillExtrusionPattern,
            hillshadePrepare,
            hillshade,
            line,
            lineGradient,
            linePattern,
            lineSDF,
            raster,
            symbolIcon,
            symbolSDF,
            symbolTextAndIcon
          });
          var VertexArrayObject = function VertexArrayObject2() {
            this.boundProgram = null;
            this.boundLayoutVertexBuffer = null;
            this.boundPaintVertexBuffers = [];
            this.boundIndexBuffer = null;
            this.boundVertexOffset = null;
            this.boundDynamicVertexBuffer = null;
            this.vao = null;
          };
          VertexArrayObject.prototype.bind = function bind(context, program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2) {
            this.context = context;
            var paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length;
            for (var i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) {
              if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) {
                paintBuffersDiffer = true;
              }
            }
            var isFreshBindRequired = !this.vao || this.boundProgram !== program || this.boundLayoutVertexBuffer !== layoutVertexBuffer || paintBuffersDiffer || this.boundIndexBuffer !== indexBuffer || this.boundVertexOffset !== vertexOffset || this.boundDynamicVertexBuffer !== dynamicVertexBuffer || this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2;
            if (!context.extVertexArrayObject || isFreshBindRequired) {
              this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2);
            } else {
              context.bindVertexArrayOES.set(this.vao);
              if (dynamicVertexBuffer) {
                dynamicVertexBuffer.bind();
              }
              if (indexBuffer && indexBuffer.dynamicDraw) {
                indexBuffer.bind();
              }
              if (dynamicVertexBuffer2) {
                dynamicVertexBuffer2.bind();
              }
            }
          };
          VertexArrayObject.prototype.freshBind = function freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2) {
            var numPrevAttributes;
            var numNextAttributes = program.numAttributes;
            var context = this.context;
            var gl2 = context.gl;
            if (context.extVertexArrayObject) {
              if (this.vao) {
                this.destroy();
              }
              this.vao = context.extVertexArrayObject.createVertexArrayOES();
              context.bindVertexArrayOES.set(this.vao);
              numPrevAttributes = 0;
              this.boundProgram = program;
              this.boundLayoutVertexBuffer = layoutVertexBuffer;
              this.boundPaintVertexBuffers = paintVertexBuffers;
              this.boundIndexBuffer = indexBuffer;
              this.boundVertexOffset = vertexOffset;
              this.boundDynamicVertexBuffer = dynamicVertexBuffer;
              this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2;
            } else {
              numPrevAttributes = context.currentNumAttributes || 0;
              for (var i = numNextAttributes; i < numPrevAttributes; i++) {
                gl2.disableVertexAttribArray(i);
              }
            }
            layoutVertexBuffer.enableAttributes(gl2, program);
            for (var i$1 = 0, list = paintVertexBuffers; i$1 < list.length; i$1 += 1) {
              var vertexBuffer = list[i$1];
              vertexBuffer.enableAttributes(gl2, program);
            }
            if (dynamicVertexBuffer) {
              dynamicVertexBuffer.enableAttributes(gl2, program);
            }
            if (dynamicVertexBuffer2) {
              dynamicVertexBuffer2.enableAttributes(gl2, program);
            }
            layoutVertexBuffer.bind();
            layoutVertexBuffer.setVertexAttribPointers(gl2, program, vertexOffset);
            for (var i$2 = 0, list$1 = paintVertexBuffers; i$2 < list$1.length; i$2 += 1) {
              var vertexBuffer$1 = list$1[i$2];
              vertexBuffer$1.bind();
              vertexBuffer$1.setVertexAttribPointers(gl2, program, vertexOffset);
            }
            if (dynamicVertexBuffer) {
              dynamicVertexBuffer.bind();
              dynamicVertexBuffer.setVertexAttribPointers(gl2, program, vertexOffset);
            }
            if (indexBuffer) {
              indexBuffer.bind();
            }
            if (dynamicVertexBuffer2) {
              dynamicVertexBuffer2.bind();
              dynamicVertexBuffer2.setVertexAttribPointers(gl2, program, vertexOffset);
            }
            context.currentNumAttributes = numNextAttributes;
          };
          VertexArrayObject.prototype.destroy = function destroy() {
            if (this.vao) {
              this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao);
              this.vao = null;
            }
          };
          function getTokenizedAttributesAndUniforms(array) {
            var result = [];
            for (var i = 0; i < array.length; i++) {
              if (array[i] === null) {
                continue;
              }
              var token = array[i].split(" ");
              result.push(token.pop());
            }
            return result;
          }
          var Program$1 = function Program2(context, name2, source, configuration, fixedUniforms, showOverdrawInspector) {
            var gl2 = context.gl;
            this.program = gl2.createProgram();
            var staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes);
            var dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : [];
            var allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo);
            var staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : [];
            var dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : [];
            var uniformList = staticUniformsInfo.concat(dynamicUniformsInfo);
            var allUniformsInfo = [];
            for (var i$1 = 0, list = uniformList; i$1 < list.length; i$1 += 1) {
              var uniform = list[i$1];
              if (allUniformsInfo.indexOf(uniform) < 0) {
                allUniformsInfo.push(uniform);
              }
            }
            var defines = configuration ? configuration.defines() : [];
            if (showOverdrawInspector) {
              defines.push("#define OVERDRAW_INSPECTOR;");
            }
            var fragmentSource = defines.concat(prelude.fragmentSource, source.fragmentSource).join("\n");
            var vertexSource = defines.concat(prelude.vertexSource, source.vertexSource).join("\n");
            var fragmentShader = gl2.createShader(gl2.FRAGMENT_SHADER);
            if (gl2.isContextLost()) {
              this.failedToCreate = true;
              return;
            }
            gl2.shaderSource(fragmentShader, fragmentSource);
            gl2.compileShader(fragmentShader);
            gl2.attachShader(this.program, fragmentShader);
            var vertexShader = gl2.createShader(gl2.VERTEX_SHADER);
            if (gl2.isContextLost()) {
              this.failedToCreate = true;
              return;
            }
            gl2.shaderSource(vertexShader, vertexSource);
            gl2.compileShader(vertexShader);
            gl2.attachShader(this.program, vertexShader);
            this.attributes = {};
            var uniformLocations = {};
            this.numAttributes = allAttrInfo.length;
            for (var i = 0; i < this.numAttributes; i++) {
              if (allAttrInfo[i]) {
                gl2.bindAttribLocation(this.program, i, allAttrInfo[i]);
                this.attributes[allAttrInfo[i]] = i;
              }
            }
            gl2.linkProgram(this.program);
            gl2.deleteShader(vertexShader);
            gl2.deleteShader(fragmentShader);
            for (var it = 0; it < allUniformsInfo.length; it++) {
              var uniform$1 = allUniformsInfo[it];
              if (uniform$1 && !uniformLocations[uniform$1]) {
                var uniformLocation = gl2.getUniformLocation(this.program, uniform$1);
                if (uniformLocation) {
                  uniformLocations[uniform$1] = uniformLocation;
                }
              }
            }
            this.fixedUniforms = fixedUniforms(context, uniformLocations);
            this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : [];
          };
          Program$1.prototype.draw = function draw2(context, drawMode, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, layerID, layoutVertexBuffer, indexBuffer, segments, currentProperties, zoom, configuration, dynamicLayoutBuffer, dynamicLayoutBuffer2) {
            var obj;
            var gl2 = context.gl;
            if (this.failedToCreate) {
              return;
            }
            context.program.set(this.program);
            context.setDepthMode(depthMode);
            context.setStencilMode(stencilMode);
            context.setColorMode(colorMode);
            context.setCullFace(cullFaceMode);
            for (var name2 in this.fixedUniforms) {
              this.fixedUniforms[name2].set(uniformValues[name2]);
            }
            if (configuration) {
              configuration.setUniforms(context, this.binderUniforms, currentProperties, { zoom });
            }
            var primitiveSize = (obj = {}, obj[gl2.LINES] = 2, obj[gl2.TRIANGLES] = 3, obj[gl2.LINE_STRIP] = 1, obj)[drawMode];
            for (var i = 0, list = segments.get(); i < list.length; i += 1) {
              var segment = list[i];
              var vaos = segment.vaos || (segment.vaos = {});
              var vao = vaos[layerID] || (vaos[layerID] = new VertexArrayObject());
              vao.bind(context, this, layoutVertexBuffer, configuration ? configuration.getPaintVertexBuffers() : [], indexBuffer, segment.vertexOffset, dynamicLayoutBuffer, dynamicLayoutBuffer2);
              gl2.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl2.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2);
            }
          };
          function patternUniformValues(crossfade, painter, tile) {
            var tileRatio = 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom);
            var numTiles = Math.pow(2, tile.tileID.overscaledZ);
            var tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;
            var pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);
            var pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;
            return {
              "u_image": 0,
              "u_texsize": tile.imageAtlasTexture.size,
              "u_scale": [
                tileRatio,
                crossfade.fromScale,
                crossfade.toScale
              ],
              "u_fade": crossfade.t,
              "u_pixel_coord_upper": [
                pixelX >> 16,
                pixelY >> 16
              ],
              "u_pixel_coord_lower": [
                pixelX & 65535,
                pixelY & 65535
              ]
            };
          }
          function bgPatternUniformValues(image, crossfade, painter, tile) {
            var imagePosA = painter.imageManager.getPattern(image.from.toString());
            var imagePosB = painter.imageManager.getPattern(image.to.toString());
            var ref = painter.imageManager.getPixelSize();
            var width = ref.width;
            var height = ref.height;
            var numTiles = Math.pow(2, tile.tileID.overscaledZ);
            var tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;
            var pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);
            var pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;
            return {
              "u_image": 0,
              "u_pattern_tl_a": imagePosA.tl,
              "u_pattern_br_a": imagePosA.br,
              "u_pattern_tl_b": imagePosB.tl,
              "u_pattern_br_b": imagePosB.br,
              "u_texsize": [
                width,
                height
              ],
              "u_mix": crossfade.t,
              "u_pattern_size_a": imagePosA.displaySize,
              "u_pattern_size_b": imagePosB.displaySize,
              "u_scale_a": crossfade.fromScale,
              "u_scale_b": crossfade.toScale,
              "u_tile_units_to_pixels": 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom),
              "u_pixel_coord_upper": [
                pixelX >> 16,
                pixelY >> 16
              ],
              "u_pixel_coord_lower": [
                pixelX & 65535,
                pixelY & 65535
              ]
            };
          }
          var fillExtrusionUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_lightpos": new performance2.Uniform3f(context, locations.u_lightpos),
              "u_lightintensity": new performance2.Uniform1f(context, locations.u_lightintensity),
              "u_lightcolor": new performance2.Uniform3f(context, locations.u_lightcolor),
              "u_vertical_gradient": new performance2.Uniform1f(context, locations.u_vertical_gradient),
              "u_opacity": new performance2.Uniform1f(context, locations.u_opacity)
            };
          };
          var fillExtrusionPatternUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_lightpos": new performance2.Uniform3f(context, locations.u_lightpos),
              "u_lightintensity": new performance2.Uniform1f(context, locations.u_lightintensity),
              "u_lightcolor": new performance2.Uniform3f(context, locations.u_lightcolor),
              "u_vertical_gradient": new performance2.Uniform1f(context, locations.u_vertical_gradient),
              "u_height_factor": new performance2.Uniform1f(context, locations.u_height_factor),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_pixel_coord_upper": new performance2.Uniform2f(context, locations.u_pixel_coord_upper),
              "u_pixel_coord_lower": new performance2.Uniform2f(context, locations.u_pixel_coord_lower),
              "u_scale": new performance2.Uniform3f(context, locations.u_scale),
              "u_fade": new performance2.Uniform1f(context, locations.u_fade),
              "u_opacity": new performance2.Uniform1f(context, locations.u_opacity)
            };
          };
          var fillExtrusionUniformValues = function(matrix, painter, shouldUseVerticalGradient, opacity) {
            var light = painter.style.light;
            var _lp = light.properties.get("position");
            var lightPos = [
              _lp.x,
              _lp.y,
              _lp.z
            ];
            var lightMat = performance2.create$1();
            if (light.properties.get("anchor") === "viewport") {
              performance2.fromRotation(lightMat, -painter.transform.angle);
            }
            performance2.transformMat3(lightPos, lightPos, lightMat);
            var lightColor = light.properties.get("color");
            return {
              "u_matrix": matrix,
              "u_lightpos": lightPos,
              "u_lightintensity": light.properties.get("intensity"),
              "u_lightcolor": [
                lightColor.r,
                lightColor.g,
                lightColor.b
              ],
              "u_vertical_gradient": +shouldUseVerticalGradient,
              "u_opacity": opacity
            };
          };
          var fillExtrusionPatternUniformValues = function(matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) {
            return performance2.extend(fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity), patternUniformValues(crossfade, painter, tile), { "u_height_factor": -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8 });
          };
          var fillUniforms = function(context, locations) {
            return { "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix) };
          };
          var fillPatternUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_pixel_coord_upper": new performance2.Uniform2f(context, locations.u_pixel_coord_upper),
              "u_pixel_coord_lower": new performance2.Uniform2f(context, locations.u_pixel_coord_lower),
              "u_scale": new performance2.Uniform3f(context, locations.u_scale),
              "u_fade": new performance2.Uniform1f(context, locations.u_fade)
            };
          };
          var fillOutlineUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_world": new performance2.Uniform2f(context, locations.u_world)
            };
          };
          var fillOutlinePatternUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_world": new performance2.Uniform2f(context, locations.u_world),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_pixel_coord_upper": new performance2.Uniform2f(context, locations.u_pixel_coord_upper),
              "u_pixel_coord_lower": new performance2.Uniform2f(context, locations.u_pixel_coord_lower),
              "u_scale": new performance2.Uniform3f(context, locations.u_scale),
              "u_fade": new performance2.Uniform1f(context, locations.u_fade)
            };
          };
          var fillUniformValues = function(matrix) {
            return { "u_matrix": matrix };
          };
          var fillPatternUniformValues = function(matrix, painter, crossfade, tile) {
            return performance2.extend(fillUniformValues(matrix), patternUniformValues(crossfade, painter, tile));
          };
          var fillOutlineUniformValues = function(matrix, drawingBufferSize) {
            return {
              "u_matrix": matrix,
              "u_world": drawingBufferSize
            };
          };
          var fillOutlinePatternUniformValues = function(matrix, painter, crossfade, tile, drawingBufferSize) {
            return performance2.extend(fillPatternUniformValues(matrix, painter, crossfade, tile), { "u_world": drawingBufferSize });
          };
          var circleUniforms = function(context, locations) {
            return {
              "u_camera_to_center_distance": new performance2.Uniform1f(context, locations.u_camera_to_center_distance),
              "u_scale_with_map": new performance2.Uniform1i(context, locations.u_scale_with_map),
              "u_pitch_with_map": new performance2.Uniform1i(context, locations.u_pitch_with_map),
              "u_extrude_scale": new performance2.Uniform2f(context, locations.u_extrude_scale),
              "u_device_pixel_ratio": new performance2.Uniform1f(context, locations.u_device_pixel_ratio),
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix)
            };
          };
          var circleUniformValues = function(painter, coord, tile, layer) {
            var transform = painter.transform;
            var pitchWithMap, extrudeScale;
            if (layer.paint.get("circle-pitch-alignment") === "map") {
              var pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);
              pitchWithMap = true;
              extrudeScale = [
                pixelRatio,
                pixelRatio
              ];
            } else {
              pitchWithMap = false;
              extrudeScale = transform.pixelsToGLUnits;
            }
            return {
              "u_camera_to_center_distance": transform.cameraToCenterDistance,
              "u_scale_with_map": +(layer.paint.get("circle-pitch-scale") === "map"),
              "u_matrix": painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get("circle-translate"), layer.paint.get("circle-translate-anchor")),
              "u_pitch_with_map": +pitchWithMap,
              "u_device_pixel_ratio": performance2.browser.devicePixelRatio,
              "u_extrude_scale": extrudeScale
            };
          };
          var collisionUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_camera_to_center_distance": new performance2.Uniform1f(context, locations.u_camera_to_center_distance),
              "u_pixels_to_tile_units": new performance2.Uniform1f(context, locations.u_pixels_to_tile_units),
              "u_extrude_scale": new performance2.Uniform2f(context, locations.u_extrude_scale),
              "u_overscale_factor": new performance2.Uniform1f(context, locations.u_overscale_factor)
            };
          };
          var collisionCircleUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_inv_matrix": new performance2.UniformMatrix4f(context, locations.u_inv_matrix),
              "u_camera_to_center_distance": new performance2.Uniform1f(context, locations.u_camera_to_center_distance),
              "u_viewport_size": new performance2.Uniform2f(context, locations.u_viewport_size)
            };
          };
          var collisionUniformValues = function(matrix, transform, tile) {
            var pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);
            var scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);
            var overscaleFactor = tile.tileID.overscaleFactor();
            return {
              "u_matrix": matrix,
              "u_camera_to_center_distance": transform.cameraToCenterDistance,
              "u_pixels_to_tile_units": pixelRatio,
              "u_extrude_scale": [
                transform.pixelsToGLUnits[0] / (pixelRatio * scale),
                transform.pixelsToGLUnits[1] / (pixelRatio * scale)
              ],
              "u_overscale_factor": overscaleFactor
            };
          };
          var collisionCircleUniformValues = function(matrix, invMatrix, transform) {
            return {
              "u_matrix": matrix,
              "u_inv_matrix": invMatrix,
              "u_camera_to_center_distance": transform.cameraToCenterDistance,
              "u_viewport_size": [
                transform.width,
                transform.height
              ]
            };
          };
          var debugUniforms = function(context, locations) {
            return {
              "u_color": new performance2.UniformColor(context, locations.u_color),
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_overlay": new performance2.Uniform1i(context, locations.u_overlay),
              "u_overlay_scale": new performance2.Uniform1f(context, locations.u_overlay_scale)
            };
          };
          var debugUniformValues = function(matrix, color2, scaleRatio) {
            if (scaleRatio === void 0)
              scaleRatio = 1;
            return {
              "u_matrix": matrix,
              "u_color": color2,
              "u_overlay": 0,
              "u_overlay_scale": scaleRatio
            };
          };
          var clippingMaskUniforms = function(context, locations) {
            return { "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix) };
          };
          var clippingMaskUniformValues = function(matrix) {
            return { "u_matrix": matrix };
          };
          var heatmapUniforms = function(context, locations) {
            return {
              "u_extrude_scale": new performance2.Uniform1f(context, locations.u_extrude_scale),
              "u_intensity": new performance2.Uniform1f(context, locations.u_intensity),
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix)
            };
          };
          var heatmapTextureUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_world": new performance2.Uniform2f(context, locations.u_world),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_color_ramp": new performance2.Uniform1i(context, locations.u_color_ramp),
              "u_opacity": new performance2.Uniform1f(context, locations.u_opacity)
            };
          };
          var heatmapUniformValues = function(matrix, tile, zoom, intensity) {
            return {
              "u_matrix": matrix,
              "u_extrude_scale": pixelsToTileUnits(tile, 1, zoom),
              "u_intensity": intensity
            };
          };
          var heatmapTextureUniformValues = function(painter, layer, textureUnit, colorRampUnit) {
            var matrix = performance2.create();
            performance2.ortho(matrix, 0, painter.width, painter.height, 0, 0, 1);
            var gl2 = painter.context.gl;
            return {
              "u_matrix": matrix,
              "u_world": [
                gl2.drawingBufferWidth,
                gl2.drawingBufferHeight
              ],
              "u_image": textureUnit,
              "u_color_ramp": colorRampUnit,
              "u_opacity": layer.paint.get("heatmap-opacity")
            };
          };
          var hillshadeUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_latrange": new performance2.Uniform2f(context, locations.u_latrange),
              "u_light": new performance2.Uniform2f(context, locations.u_light),
              "u_shadow": new performance2.UniformColor(context, locations.u_shadow),
              "u_highlight": new performance2.UniformColor(context, locations.u_highlight),
              "u_accent": new performance2.UniformColor(context, locations.u_accent)
            };
          };
          var hillshadePrepareUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_dimension": new performance2.Uniform2f(context, locations.u_dimension),
              "u_zoom": new performance2.Uniform1f(context, locations.u_zoom),
              "u_unpack": new performance2.Uniform4f(context, locations.u_unpack)
            };
          };
          var hillshadeUniformValues = function(painter, tile, layer) {
            var shadow = layer.paint.get("hillshade-shadow-color");
            var highlight = layer.paint.get("hillshade-highlight-color");
            var accent = layer.paint.get("hillshade-accent-color");
            var azimuthal = layer.paint.get("hillshade-illumination-direction") * (Math.PI / 180);
            if (layer.paint.get("hillshade-illumination-anchor") === "viewport") {
              azimuthal -= painter.transform.angle;
            }
            var align = !painter.options.moving;
            return {
              "u_matrix": painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(), align),
              "u_image": 0,
              "u_latrange": getTileLatRange(painter, tile.tileID),
              "u_light": [
                layer.paint.get("hillshade-exaggeration"),
                azimuthal
              ],
              "u_shadow": shadow,
              "u_highlight": highlight,
              "u_accent": accent
            };
          };
          var hillshadeUniformPrepareValues = function(tileID, dem) {
            var stride = dem.stride;
            var matrix = performance2.create();
            performance2.ortho(matrix, 0, performance2.EXTENT, -performance2.EXTENT, 0, 0, 1);
            performance2.translate(matrix, matrix, [
              0,
              -performance2.EXTENT,
              0
            ]);
            return {
              "u_matrix": matrix,
              "u_image": 1,
              "u_dimension": [
                stride,
                stride
              ],
              "u_zoom": tileID.overscaledZ,
              "u_unpack": dem.getUnpackVector()
            };
          };
          function getTileLatRange(painter, tileID) {
            var tilesAtZoom = Math.pow(2, tileID.canonical.z);
            var y = tileID.canonical.y;
            return [
              new performance2.MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat,
              new performance2.MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat
            ];
          }
          var lineUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_ratio": new performance2.Uniform1f(context, locations.u_ratio),
              "u_device_pixel_ratio": new performance2.Uniform1f(context, locations.u_device_pixel_ratio),
              "u_units_to_pixels": new performance2.Uniform2f(context, locations.u_units_to_pixels)
            };
          };
          var lineGradientUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_ratio": new performance2.Uniform1f(context, locations.u_ratio),
              "u_device_pixel_ratio": new performance2.Uniform1f(context, locations.u_device_pixel_ratio),
              "u_units_to_pixels": new performance2.Uniform2f(context, locations.u_units_to_pixels),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_image_height": new performance2.Uniform1f(context, locations.u_image_height)
            };
          };
          var linePatternUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_ratio": new performance2.Uniform1f(context, locations.u_ratio),
              "u_device_pixel_ratio": new performance2.Uniform1f(context, locations.u_device_pixel_ratio),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_units_to_pixels": new performance2.Uniform2f(context, locations.u_units_to_pixels),
              "u_scale": new performance2.Uniform3f(context, locations.u_scale),
              "u_fade": new performance2.Uniform1f(context, locations.u_fade)
            };
          };
          var lineSDFUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_ratio": new performance2.Uniform1f(context, locations.u_ratio),
              "u_device_pixel_ratio": new performance2.Uniform1f(context, locations.u_device_pixel_ratio),
              "u_units_to_pixels": new performance2.Uniform2f(context, locations.u_units_to_pixels),
              "u_patternscale_a": new performance2.Uniform2f(context, locations.u_patternscale_a),
              "u_patternscale_b": new performance2.Uniform2f(context, locations.u_patternscale_b),
              "u_sdfgamma": new performance2.Uniform1f(context, locations.u_sdfgamma),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_tex_y_a": new performance2.Uniform1f(context, locations.u_tex_y_a),
              "u_tex_y_b": new performance2.Uniform1f(context, locations.u_tex_y_b),
              "u_mix": new performance2.Uniform1f(context, locations.u_mix)
            };
          };
          var lineUniformValues = function(painter, tile, layer) {
            var transform = painter.transform;
            return {
              "u_matrix": calculateMatrix(painter, tile, layer),
              "u_ratio": 1 / pixelsToTileUnits(tile, 1, transform.zoom),
              "u_device_pixel_ratio": performance2.browser.devicePixelRatio,
              "u_units_to_pixels": [
                1 / transform.pixelsToGLUnits[0],
                1 / transform.pixelsToGLUnits[1]
              ]
            };
          };
          var lineGradientUniformValues = function(painter, tile, layer, imageHeight) {
            return performance2.extend(lineUniformValues(painter, tile, layer), {
              "u_image": 0,
              "u_image_height": imageHeight
            });
          };
          var linePatternUniformValues = function(painter, tile, layer, crossfade) {
            var transform = painter.transform;
            var tileZoomRatio = calculateTileRatio(tile, transform);
            return {
              "u_matrix": calculateMatrix(painter, tile, layer),
              "u_texsize": tile.imageAtlasTexture.size,
              "u_ratio": 1 / pixelsToTileUnits(tile, 1, transform.zoom),
              "u_device_pixel_ratio": performance2.browser.devicePixelRatio,
              "u_image": 0,
              "u_scale": [
                tileZoomRatio,
                crossfade.fromScale,
                crossfade.toScale
              ],
              "u_fade": crossfade.t,
              "u_units_to_pixels": [
                1 / transform.pixelsToGLUnits[0],
                1 / transform.pixelsToGLUnits[1]
              ]
            };
          };
          var lineSDFUniformValues = function(painter, tile, layer, dasharray, crossfade) {
            var transform = painter.transform;
            var lineAtlas = painter.lineAtlas;
            var tileRatio = calculateTileRatio(tile, transform);
            var round = layer.layout.get("line-cap") === "round";
            var posA = lineAtlas.getDash(dasharray.from, round);
            var posB = lineAtlas.getDash(dasharray.to, round);
            var widthA = posA.width * crossfade.fromScale;
            var widthB = posB.width * crossfade.toScale;
            return performance2.extend(lineUniformValues(painter, tile, layer), {
              "u_patternscale_a": [
                tileRatio / widthA,
                -posA.height / 2
              ],
              "u_patternscale_b": [
                tileRatio / widthB,
                -posB.height / 2
              ],
              "u_sdfgamma": lineAtlas.width / (Math.min(widthA, widthB) * 256 * performance2.browser.devicePixelRatio) / 2,
              "u_image": 0,
              "u_tex_y_a": posA.y,
              "u_tex_y_b": posB.y,
              "u_mix": crossfade.t
            });
          };
          function calculateTileRatio(tile, transform) {
            return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom);
          }
          function calculateMatrix(painter, tile, layer) {
            return painter.translatePosMatrix(tile.tileID.posMatrix, tile, layer.paint.get("line-translate"), layer.paint.get("line-translate-anchor"));
          }
          var rasterUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_tl_parent": new performance2.Uniform2f(context, locations.u_tl_parent),
              "u_scale_parent": new performance2.Uniform1f(context, locations.u_scale_parent),
              "u_buffer_scale": new performance2.Uniform1f(context, locations.u_buffer_scale),
              "u_fade_t": new performance2.Uniform1f(context, locations.u_fade_t),
              "u_opacity": new performance2.Uniform1f(context, locations.u_opacity),
              "u_image0": new performance2.Uniform1i(context, locations.u_image0),
              "u_image1": new performance2.Uniform1i(context, locations.u_image1),
              "u_brightness_low": new performance2.Uniform1f(context, locations.u_brightness_low),
              "u_brightness_high": new performance2.Uniform1f(context, locations.u_brightness_high),
              "u_saturation_factor": new performance2.Uniform1f(context, locations.u_saturation_factor),
              "u_contrast_factor": new performance2.Uniform1f(context, locations.u_contrast_factor),
              "u_spin_weights": new performance2.Uniform3f(context, locations.u_spin_weights)
            };
          };
          var rasterUniformValues = function(matrix, parentTL, parentScaleBy, fade, layer) {
            return {
              "u_matrix": matrix,
              "u_tl_parent": parentTL,
              "u_scale_parent": parentScaleBy,
              "u_buffer_scale": 1,
              "u_fade_t": fade.mix,
              "u_opacity": fade.opacity * layer.paint.get("raster-opacity"),
              "u_image0": 0,
              "u_image1": 1,
              "u_brightness_low": layer.paint.get("raster-brightness-min"),
              "u_brightness_high": layer.paint.get("raster-brightness-max"),
              "u_saturation_factor": saturationFactor(layer.paint.get("raster-saturation")),
              "u_contrast_factor": contrastFactor(layer.paint.get("raster-contrast")),
              "u_spin_weights": spinWeights(layer.paint.get("raster-hue-rotate"))
            };
          };
          function spinWeights(angle) {
            angle *= Math.PI / 180;
            var s = Math.sin(angle);
            var c = Math.cos(angle);
            return [
              (2 * c + 1) / 3,
              (-Math.sqrt(3) * s - c + 1) / 3,
              (Math.sqrt(3) * s - c + 1) / 3
            ];
          }
          function contrastFactor(contrast) {
            return contrast > 0 ? 1 / (1 - contrast) : 1 + contrast;
          }
          function saturationFactor(saturation) {
            return saturation > 0 ? 1 - 1 / (1.001 - saturation) : -saturation;
          }
          var symbolIconUniforms = function(context, locations) {
            return {
              "u_is_size_zoom_constant": new performance2.Uniform1i(context, locations.u_is_size_zoom_constant),
              "u_is_size_feature_constant": new performance2.Uniform1i(context, locations.u_is_size_feature_constant),
              "u_size_t": new performance2.Uniform1f(context, locations.u_size_t),
              "u_size": new performance2.Uniform1f(context, locations.u_size),
              "u_camera_to_center_distance": new performance2.Uniform1f(context, locations.u_camera_to_center_distance),
              "u_pitch": new performance2.Uniform1f(context, locations.u_pitch),
              "u_rotate_symbol": new performance2.Uniform1i(context, locations.u_rotate_symbol),
              "u_aspect_ratio": new performance2.Uniform1f(context, locations.u_aspect_ratio),
              "u_fade_change": new performance2.Uniform1f(context, locations.u_fade_change),
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_label_plane_matrix": new performance2.UniformMatrix4f(context, locations.u_label_plane_matrix),
              "u_coord_matrix": new performance2.UniformMatrix4f(context, locations.u_coord_matrix),
              "u_is_text": new performance2.Uniform1i(context, locations.u_is_text),
              "u_pitch_with_map": new performance2.Uniform1i(context, locations.u_pitch_with_map),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_texture": new performance2.Uniform1i(context, locations.u_texture)
            };
          };
          var symbolSDFUniforms = function(context, locations) {
            return {
              "u_is_size_zoom_constant": new performance2.Uniform1i(context, locations.u_is_size_zoom_constant),
              "u_is_size_feature_constant": new performance2.Uniform1i(context, locations.u_is_size_feature_constant),
              "u_size_t": new performance2.Uniform1f(context, locations.u_size_t),
              "u_size": new performance2.Uniform1f(context, locations.u_size),
              "u_camera_to_center_distance": new performance2.Uniform1f(context, locations.u_camera_to_center_distance),
              "u_pitch": new performance2.Uniform1f(context, locations.u_pitch),
              "u_rotate_symbol": new performance2.Uniform1i(context, locations.u_rotate_symbol),
              "u_aspect_ratio": new performance2.Uniform1f(context, locations.u_aspect_ratio),
              "u_fade_change": new performance2.Uniform1f(context, locations.u_fade_change),
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_label_plane_matrix": new performance2.UniformMatrix4f(context, locations.u_label_plane_matrix),
              "u_coord_matrix": new performance2.UniformMatrix4f(context, locations.u_coord_matrix),
              "u_is_text": new performance2.Uniform1i(context, locations.u_is_text),
              "u_pitch_with_map": new performance2.Uniform1i(context, locations.u_pitch_with_map),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_texture": new performance2.Uniform1i(context, locations.u_texture),
              "u_gamma_scale": new performance2.Uniform1f(context, locations.u_gamma_scale),
              "u_device_pixel_ratio": new performance2.Uniform1f(context, locations.u_device_pixel_ratio),
              "u_is_halo": new performance2.Uniform1i(context, locations.u_is_halo)
            };
          };
          var symbolTextAndIconUniforms = function(context, locations) {
            return {
              "u_is_size_zoom_constant": new performance2.Uniform1i(context, locations.u_is_size_zoom_constant),
              "u_is_size_feature_constant": new performance2.Uniform1i(context, locations.u_is_size_feature_constant),
              "u_size_t": new performance2.Uniform1f(context, locations.u_size_t),
              "u_size": new performance2.Uniform1f(context, locations.u_size),
              "u_camera_to_center_distance": new performance2.Uniform1f(context, locations.u_camera_to_center_distance),
              "u_pitch": new performance2.Uniform1f(context, locations.u_pitch),
              "u_rotate_symbol": new performance2.Uniform1i(context, locations.u_rotate_symbol),
              "u_aspect_ratio": new performance2.Uniform1f(context, locations.u_aspect_ratio),
              "u_fade_change": new performance2.Uniform1f(context, locations.u_fade_change),
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_label_plane_matrix": new performance2.UniformMatrix4f(context, locations.u_label_plane_matrix),
              "u_coord_matrix": new performance2.UniformMatrix4f(context, locations.u_coord_matrix),
              "u_is_text": new performance2.Uniform1i(context, locations.u_is_text),
              "u_pitch_with_map": new performance2.Uniform1i(context, locations.u_pitch_with_map),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_texsize_icon": new performance2.Uniform2f(context, locations.u_texsize_icon),
              "u_texture": new performance2.Uniform1i(context, locations.u_texture),
              "u_texture_icon": new performance2.Uniform1i(context, locations.u_texture_icon),
              "u_gamma_scale": new performance2.Uniform1f(context, locations.u_gamma_scale),
              "u_device_pixel_ratio": new performance2.Uniform1f(context, locations.u_device_pixel_ratio),
              "u_is_halo": new performance2.Uniform1i(context, locations.u_is_halo)
            };
          };
          var symbolIconUniformValues = function(functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, isText, texSize) {
            var transform = painter.transform;
            return {
              "u_is_size_zoom_constant": +(functionType === "constant" || functionType === "source"),
              "u_is_size_feature_constant": +(functionType === "constant" || functionType === "camera"),
              "u_size_t": size ? size.uSizeT : 0,
              "u_size": size ? size.uSize : 0,
              "u_camera_to_center_distance": transform.cameraToCenterDistance,
              "u_pitch": transform.pitch / 360 * 2 * Math.PI,
              "u_rotate_symbol": +rotateInShader,
              "u_aspect_ratio": transform.width / transform.height,
              "u_fade_change": painter.options.fadeDuration ? painter.symbolFadeChange : 1,
              "u_matrix": matrix,
              "u_label_plane_matrix": labelPlaneMatrix,
              "u_coord_matrix": glCoordMatrix,
              "u_is_text": +isText,
              "u_pitch_with_map": +pitchWithMap,
              "u_texsize": texSize,
              "u_texture": 0
            };
          };
          var symbolSDFUniformValues = function(functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, isText, texSize, isHalo) {
            var transform = painter.transform;
            return performance2.extend(symbolIconUniformValues(functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, isText, texSize), {
              "u_gamma_scale": pitchWithMap ? Math.cos(transform._pitch) * transform.cameraToCenterDistance : 1,
              "u_device_pixel_ratio": performance2.browser.devicePixelRatio,
              "u_is_halo": +isHalo
            });
          };
          var symbolTextAndIconUniformValues = function(functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, texSizeSDF, texSizeIcon) {
            return performance2.extend(symbolSDFUniformValues(functionType, size, rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix, glCoordMatrix, true, texSizeSDF, true), {
              "u_texsize_icon": texSizeIcon,
              "u_texture_icon": 1
            });
          };
          var backgroundUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_opacity": new performance2.Uniform1f(context, locations.u_opacity),
              "u_color": new performance2.UniformColor(context, locations.u_color)
            };
          };
          var backgroundPatternUniforms = function(context, locations) {
            return {
              "u_matrix": new performance2.UniformMatrix4f(context, locations.u_matrix),
              "u_opacity": new performance2.Uniform1f(context, locations.u_opacity),
              "u_image": new performance2.Uniform1i(context, locations.u_image),
              "u_pattern_tl_a": new performance2.Uniform2f(context, locations.u_pattern_tl_a),
              "u_pattern_br_a": new performance2.Uniform2f(context, locations.u_pattern_br_a),
              "u_pattern_tl_b": new performance2.Uniform2f(context, locations.u_pattern_tl_b),
              "u_pattern_br_b": new performance2.Uniform2f(context, locations.u_pattern_br_b),
              "u_texsize": new performance2.Uniform2f(context, locations.u_texsize),
              "u_mix": new performance2.Uniform1f(context, locations.u_mix),
              "u_pattern_size_a": new performance2.Uniform2f(context, locations.u_pattern_size_a),
              "u_pattern_size_b": new performance2.Uniform2f(context, locations.u_pattern_size_b),
              "u_scale_a": new performance2.Uniform1f(context, locations.u_scale_a),
              "u_scale_b": new performance2.Uniform1f(context, locations.u_scale_b),
              "u_pixel_coord_upper": new performance2.Uniform2f(context, locations.u_pixel_coord_upper),
              "u_pixel_coord_lower": new performance2.Uniform2f(context, locations.u_pixel_coord_lower),
              "u_tile_units_to_pixels": new performance2.Uniform1f(context, locations.u_tile_units_to_pixels)
            };
          };
          var backgroundUniformValues = function(matrix, opacity, color2) {
            return {
              "u_matrix": matrix,
              "u_opacity": opacity,
              "u_color": color2
            };
          };
          var backgroundPatternUniformValues = function(matrix, opacity, painter, image, tile, crossfade) {
            return performance2.extend(bgPatternUniformValues(image, crossfade, painter, tile), {
              "u_matrix": matrix,
              "u_opacity": opacity
            });
          };
          var programUniforms = {
            fillExtrusion: fillExtrusionUniforms,
            fillExtrusionPattern: fillExtrusionPatternUniforms,
            fill: fillUniforms,
            fillPattern: fillPatternUniforms,
            fillOutline: fillOutlineUniforms,
            fillOutlinePattern: fillOutlinePatternUniforms,
            circle: circleUniforms,
            collisionBox: collisionUniforms,
            collisionCircle: collisionCircleUniforms,
            debug: debugUniforms,
            clippingMask: clippingMaskUniforms,
            heatmap: heatmapUniforms,
            heatmapTexture: heatmapTextureUniforms,
            hillshade: hillshadeUniforms,
            hillshadePrepare: hillshadePrepareUniforms,
            line: lineUniforms,
            lineGradient: lineGradientUniforms,
            linePattern: linePatternUniforms,
            lineSDF: lineSDFUniforms,
            raster: rasterUniforms,
            symbolIcon: symbolIconUniforms,
            symbolSDF: symbolSDFUniforms,
            symbolTextAndIcon: symbolTextAndIconUniforms,
            background: backgroundUniforms,
            backgroundPattern: backgroundPatternUniforms
          };
          var quadTriangles;
          function drawCollisionDebug(painter, sourceCache, layer, coords, translate, translateAnchor, isText) {
            var context = painter.context;
            var gl2 = context.gl;
            var program = painter.useProgram("collisionBox");
            var tileBatches = [];
            var circleCount = 0;
            var circleOffset = 0;
            for (var i = 0; i < coords.length; i++) {
              var coord = coords[i];
              var tile = sourceCache.getTile(coord);
              var bucket = tile.getBucket(layer);
              if (!bucket) {
                continue;
              }
              var posMatrix = coord.posMatrix;
              if (translate[0] !== 0 || translate[1] !== 0) {
                posMatrix = painter.translatePosMatrix(coord.posMatrix, tile, translate, translateAnchor);
              }
              var buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox;
              var circleArray = bucket.collisionCircleArray;
              if (circleArray.length > 0) {
                var invTransform = performance2.create();
                var transform = posMatrix;
                performance2.mul(invTransform, bucket.placementInvProjMatrix, painter.transform.glCoordMatrix);
                performance2.mul(invTransform, invTransform, bucket.placementViewportMatrix);
                tileBatches.push({
                  circleArray,
                  circleOffset,
                  transform,
                  invTransform
                });
                circleCount += circleArray.length / 4;
                circleOffset = circleCount;
              }
              if (!buffers) {
                continue;
              }
              program.draw(context, gl2.LINES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, collisionUniformValues(posMatrix, painter.transform, tile), layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, buffers.segments, null, painter.transform.zoom, null, null, buffers.collisionVertexBuffer);
            }
            if (!isText || !tileBatches.length) {
              return;
            }
            var circleProgram = painter.useProgram("collisionCircle");
            var vertexData = new performance2.StructArrayLayout2f1f2i16();
            vertexData.resize(circleCount * 4);
            vertexData._trim();
            var vertexOffset = 0;
            for (var i$2 = 0, list = tileBatches; i$2 < list.length; i$2 += 1) {
              var batch = list[i$2];
              for (var i$1 = 0; i$1 < batch.circleArray.length / 4; i$1++) {
                var circleIdx = i$1 * 4;
                var x = batch.circleArray[circleIdx + 0];
                var y = batch.circleArray[circleIdx + 1];
                var radius = batch.circleArray[circleIdx + 2];
                var collision = batch.circleArray[circleIdx + 3];
                vertexData.emplace(vertexOffset++, x, y, radius, collision, 0);
                vertexData.emplace(vertexOffset++, x, y, radius, collision, 1);
                vertexData.emplace(vertexOffset++, x, y, radius, collision, 2);
                vertexData.emplace(vertexOffset++, x, y, radius, collision, 3);
              }
            }
            if (!quadTriangles || quadTriangles.length < circleCount * 2) {
              quadTriangles = createQuadTriangles(circleCount);
            }
            var indexBuffer = context.createIndexBuffer(quadTriangles, true);
            var vertexBuffer = context.createVertexBuffer(vertexData, performance2.collisionCircleLayout.members, true);
            for (var i$3 = 0, list$1 = tileBatches; i$3 < list$1.length; i$3 += 1) {
              var batch$1 = list$1[i$3];
              var uniforms = collisionCircleUniformValues(batch$1.transform, batch$1.invTransform, painter.transform);
              circleProgram.draw(context, gl2.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, uniforms, layer.id, vertexBuffer, indexBuffer, performance2.SegmentVector.simpleSegment(0, batch$1.circleOffset * 2, batch$1.circleArray.length, batch$1.circleArray.length / 2), null, painter.transform.zoom, null, null, null);
            }
            vertexBuffer.destroy();
            indexBuffer.destroy();
          }
          function createQuadTriangles(quadCount) {
            var triCount = quadCount * 2;
            var array = new performance2.StructArrayLayout3ui6();
            array.resize(triCount);
            array._trim();
            for (var i = 0; i < triCount; i++) {
              var idx = i * 6;
              array.uint16[idx + 0] = i * 4 + 0;
              array.uint16[idx + 1] = i * 4 + 1;
              array.uint16[idx + 2] = i * 4 + 2;
              array.uint16[idx + 3] = i * 4 + 2;
              array.uint16[idx + 4] = i * 4 + 3;
              array.uint16[idx + 5] = i * 4 + 0;
            }
            return array;
          }
          var identityMat4 = performance2.identity(new Float32Array(16));
          function drawSymbols(painter, sourceCache, layer, coords, variableOffsets) {
            if (painter.renderPass !== "translucent") {
              return;
            }
            var stencilMode = StencilMode.disabled;
            var colorMode = painter.colorModeForRenderPass();
            var variablePlacement = layer.layout.get("text-variable-anchor");
            if (variablePlacement) {
              updateVariableAnchors(coords, painter, layer, sourceCache, layer.layout.get("text-rotation-alignment"), layer.layout.get("text-pitch-alignment"), variableOffsets);
            }
            if (layer.paint.get("icon-opacity").constantOr(1) !== 0) {
              drawLayerSymbols(painter, sourceCache, layer, coords, false, layer.paint.get("icon-translate"), layer.paint.get("icon-translate-anchor"), layer.layout.get("icon-rotation-alignment"), layer.layout.get("icon-pitch-alignment"), layer.layout.get("icon-keep-upright"), stencilMode, colorMode);
            }
            if (layer.paint.get("text-opacity").constantOr(1) !== 0) {
              drawLayerSymbols(painter, sourceCache, layer, coords, true, layer.paint.get("text-translate"), layer.paint.get("text-translate-anchor"), layer.layout.get("text-rotation-alignment"), layer.layout.get("text-pitch-alignment"), layer.layout.get("text-keep-upright"), stencilMode, colorMode);
            }
            if (sourceCache.map.showCollisionBoxes) {
              drawCollisionDebug(painter, sourceCache, layer, coords, layer.paint.get("text-translate"), layer.paint.get("text-translate-anchor"), true);
              drawCollisionDebug(painter, sourceCache, layer, coords, layer.paint.get("icon-translate"), layer.paint.get("icon-translate-anchor"), false);
            }
          }
          function calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize) {
            var ref = performance2.getAnchorAlignment(anchor);
            var horizontalAlign = ref.horizontalAlign;
            var verticalAlign = ref.verticalAlign;
            var shiftX = -(horizontalAlign - 0.5) * width;
            var shiftY = -(verticalAlign - 0.5) * height;
            var variableOffset = performance2.evaluateVariableOffset(anchor, textOffset);
            return new performance2.Point((shiftX / textBoxScale + variableOffset[0]) * renderTextSize, (shiftY / textBoxScale + variableOffset[1]) * renderTextSize);
          }
          function updateVariableAnchors(coords, painter, layer, sourceCache, rotationAlignment, pitchAlignment, variableOffsets) {
            var tr = painter.transform;
            var rotateWithMap = rotationAlignment === "map";
            var pitchWithMap = pitchAlignment === "map";
            for (var i = 0, list = coords; i < list.length; i += 1) {
              var coord = list[i];
              var tile = sourceCache.getTile(coord);
              var bucket = tile.getBucket(layer);
              if (!bucket || !bucket.text || !bucket.text.segments.get().length) {
                continue;
              }
              var sizeData = bucket.textSizeData;
              var size = performance2.evaluateSizeForZoom(sizeData, tr.zoom);
              var pixelToTileScale = pixelsToTileUnits(tile, 1, painter.transform.zoom);
              var labelPlaneMatrix = getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, pixelToTileScale);
              var updateTextFitIcon = layer.layout.get("icon-text-fit") !== "none" && bucket.hasIconData();
              if (size) {
                var tileScale = Math.pow(2, tr.zoom - tile.tileID.overscaledZ);
                updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, performance2.symbolSize, tr, labelPlaneMatrix, coord.posMatrix, tileScale, size, updateTextFitIcon);
              }
            }
          }
          function updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize, transform, labelPlaneMatrix, posMatrix, tileScale, size, updateTextFitIcon) {
            var placedSymbols = bucket.text.placedSymbolArray;
            var dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;
            var dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray;
            var placedTextShifts = {};
            dynamicTextLayoutVertexArray.clear();
            for (var s = 0; s < placedSymbols.length; s++) {
              var symbol = placedSymbols.get(s);
              var skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation;
              var variableOffset = !symbol.hidden && symbol.crossTileID && !skipOrientation ? variableOffsets[symbol.crossTileID] : null;
              if (!variableOffset) {
                hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray);
              } else {
                var tileAnchor = new performance2.Point(symbol.anchorX, symbol.anchorY);
                var projectedAnchor = project(tileAnchor, pitchWithMap ? posMatrix : labelPlaneMatrix);
                var perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera);
                var renderTextSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / performance2.ONE_EM;
                if (pitchWithMap) {
                  renderTextSize *= bucket.tilePixelRatio / tileScale;
                }
                var width = variableOffset.width;
                var height = variableOffset.height;
                var anchor = variableOffset.anchor;
                var textOffset = variableOffset.textOffset;
                var textBoxScale = variableOffset.textBoxScale;
                var shift = calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize);
                var shiftedAnchor = pitchWithMap ? project(tileAnchor.add(shift), labelPlaneMatrix).point : projectedAnchor.point.add(rotateWithMap ? shift.rotate(-transform.angle) : shift);
                var angle = bucket.allowVerticalPlacement && symbol.placedOrientation === performance2.WritingMode.vertical ? Math.PI / 2 : 0;
                for (var g = 0; g < symbol.numGlyphs; g++) {
                  performance2.addDynamicAttributes(dynamicTextLayoutVertexArray, shiftedAnchor, angle);
                }
                if (updateTextFitIcon && symbol.associatedIconIndex >= 0) {
                  placedTextShifts[symbol.associatedIconIndex] = {
                    shiftedAnchor,
                    angle
                  };
                }
              }
            }
            if (updateTextFitIcon) {
              dynamicIconLayoutVertexArray.clear();
              var placedIcons = bucket.icon.placedSymbolArray;
              for (var i = 0; i < placedIcons.length; i++) {
                var placedIcon = placedIcons.get(i);
                if (placedIcon.hidden) {
                  hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);
                } else {
                  var shift$1 = placedTextShifts[i];
                  if (!shift$1) {
                    hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);
                  } else {
                    for (var g$1 = 0; g$1 < placedIcon.numGlyphs; g$1++) {
                      performance2.addDynamicAttributes(dynamicIconLayoutVertexArray, shift$1.shiftedAnchor, shift$1.angle);
                    }
                  }
                }
              }
              bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray);
            }
            bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray);
          }
          function getSymbolProgramName(isSDF, isText, bucket) {
            if (bucket.iconsInText && isText) {
              return "symbolTextAndIcon";
            } else if (isSDF) {
              return "symbolSDF";
            } else {
              return "symbolIcon";
            }
          }
          function drawLayerSymbols(painter, sourceCache, layer, coords, isText, translate, translateAnchor, rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode) {
            var context = painter.context;
            var gl2 = context.gl;
            var tr = painter.transform;
            var rotateWithMap = rotationAlignment === "map";
            var pitchWithMap = pitchAlignment === "map";
            var alongLine = rotateWithMap && layer.layout.get("symbol-placement") !== "point";
            var rotateInShader = rotateWithMap && !pitchWithMap && !alongLine;
            var hasSortKey = layer.layout.get("symbol-sort-key").constantOr(1) !== void 0;
            var sortFeaturesByKey = false;
            var depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
            var variablePlacement = layer.layout.get("text-variable-anchor");
            var tileRenderState = [];
            for (var i$1 = 0, list$1 = coords; i$1 < list$1.length; i$1 += 1) {
              var coord = list$1[i$1];
              var tile = sourceCache.getTile(coord);
              var bucket = tile.getBucket(layer);
              if (!bucket) {
                continue;
              }
              var buffers = isText ? bucket.text : bucket.icon;
              if (!buffers || !buffers.segments.get().length) {
                continue;
              }
              var programConfiguration = buffers.programConfigurations.get(layer.id);
              var isSDF = isText || bucket.sdfIcons;
              var sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;
              var transformed = pitchWithMap || tr.pitch !== 0;
              var program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration);
              var size = performance2.evaluateSizeForZoom(sizeData, tr.zoom);
              var texSize = void 0;
              var texSizeIcon = [
                0,
                0
              ];
              var atlasTexture = void 0;
              var atlasInterpolation = void 0;
              var atlasTextureIcon = null;
              var atlasInterpolationIcon = void 0;
              if (isText) {
                atlasTexture = tile.glyphAtlasTexture;
                atlasInterpolation = gl2.LINEAR;
                texSize = tile.glyphAtlasTexture.size;
                if (bucket.iconsInText) {
                  texSizeIcon = tile.imageAtlasTexture.size;
                  atlasTextureIcon = tile.imageAtlasTexture;
                  var zoomDependentSize = sizeData.kind === "composite" || sizeData.kind === "camera";
                  atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl2.LINEAR : gl2.NEAREST;
                }
              } else {
                var iconScaled = layer.layout.get("icon-size").constantOr(0) !== 1 || bucket.iconsNeedLinear;
                atlasTexture = tile.imageAtlasTexture;
                atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ? gl2.LINEAR : gl2.NEAREST;
                texSize = tile.imageAtlasTexture.size;
              }
              var s = pixelsToTileUnits(tile, 1, painter.transform.zoom);
              var labelPlaneMatrix = getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s);
              var glCoordMatrix = getGlCoordMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s);
              var hasVariableAnchors = variablePlacement && bucket.hasTextData();
              var updateTextFitIcon = layer.layout.get("icon-text-fit") !== "none" && hasVariableAnchors && bucket.hasIconData();
              if (alongLine) {
                updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright);
              }
              var matrix = painter.translatePosMatrix(coord.posMatrix, tile, translate, translateAnchor), uLabelPlaneMatrix = alongLine || isText && variablePlacement || updateTextFitIcon ? identityMat4 : labelPlaneMatrix, uglCoordMatrix = painter.translatePosMatrix(glCoordMatrix, tile, translate, translateAnchor, true);
              var hasHalo = isSDF && layer.paint.get(isText ? "text-halo-width" : "icon-halo-width").constantOr(1) !== 0;
              var uniformValues = void 0;
              if (isSDF) {
                if (!bucket.iconsInText) {
                  uniformValues = symbolSDFUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, isText, texSize, true);
                } else {
                  uniformValues = symbolTextAndIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, texSize, texSizeIcon);
                }
              } else {
                uniformValues = symbolIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, painter, matrix, uLabelPlaneMatrix, uglCoordMatrix, isText, texSize);
              }
              var state = {
                program,
                buffers,
                uniformValues,
                atlasTexture,
                atlasTextureIcon,
                atlasInterpolation,
                atlasInterpolationIcon,
                isSDF,
                hasHalo
              };
              if (hasSortKey && bucket.canOverlap) {
                sortFeaturesByKey = true;
                var oldSegments = buffers.segments.get();
                for (var i = 0, list = oldSegments; i < list.length; i += 1) {
                  var segment = list[i];
                  tileRenderState.push({
                    segments: new performance2.SegmentVector([segment]),
                    sortKey: segment.sortKey,
                    state
                  });
                }
              } else {
                tileRenderState.push({
                  segments: buffers.segments,
                  sortKey: 0,
                  state
                });
              }
            }
            if (sortFeaturesByKey) {
              tileRenderState.sort(function(a, b) {
                return a.sortKey - b.sortKey;
              });
            }
            for (var i$2 = 0, list$2 = tileRenderState; i$2 < list$2.length; i$2 += 1) {
              var segmentState = list$2[i$2];
              var state$1 = segmentState.state;
              context.activeTexture.set(gl2.TEXTURE0);
              state$1.atlasTexture.bind(state$1.atlasInterpolation, gl2.CLAMP_TO_EDGE);
              if (state$1.atlasTextureIcon) {
                context.activeTexture.set(gl2.TEXTURE1);
                if (state$1.atlasTextureIcon) {
                  state$1.atlasTextureIcon.bind(state$1.atlasInterpolationIcon, gl2.CLAMP_TO_EDGE);
                }
              }
              if (state$1.isSDF) {
                var uniformValues$1 = state$1.uniformValues;
                if (state$1.hasHalo) {
                  uniformValues$1["u_is_halo"] = 1;
                  drawSymbolElements(state$1.buffers, segmentState.segments, layer, painter, state$1.program, depthMode, stencilMode, colorMode, uniformValues$1);
                }
                uniformValues$1["u_is_halo"] = 0;
              }
              drawSymbolElements(state$1.buffers, segmentState.segments, layer, painter, state$1.program, depthMode, stencilMode, colorMode, state$1.uniformValues);
            }
          }
          function drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues) {
            var context = painter.context;
            var gl2 = context.gl;
            program.draw(context, gl2.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, segments, layer.paint, painter.transform.zoom, buffers.programConfigurations.get(layer.id), buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer);
          }
          function drawCircles(painter, sourceCache, layer, coords) {
            if (painter.renderPass !== "translucent") {
              return;
            }
            var opacity = layer.paint.get("circle-opacity");
            var strokeWidth = layer.paint.get("circle-stroke-width");
            var strokeOpacity = layer.paint.get("circle-stroke-opacity");
            var sortFeaturesByKey = layer.layout.get("circle-sort-key").constantOr(1) !== void 0;
            if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) {
              return;
            }
            var context = painter.context;
            var gl2 = context.gl;
            var depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
            var stencilMode = StencilMode.disabled;
            var colorMode = painter.colorModeForRenderPass();
            var segmentsRenderStates = [];
            for (var i = 0; i < coords.length; i++) {
              var coord = coords[i];
              var tile = sourceCache.getTile(coord);
              var bucket = tile.getBucket(layer);
              if (!bucket) {
                continue;
              }
              var programConfiguration = bucket.programConfigurations.get(layer.id);
              var program = painter.useProgram("circle", programConfiguration);
              var layoutVertexBuffer = bucket.layoutVertexBuffer;
              var indexBuffer = bucket.indexBuffer;
              var uniformValues = circleUniformValues(painter, coord, tile, layer);
              var state = {
                programConfiguration,
                program,
                layoutVertexBuffer,
                indexBuffer,
                uniformValues
              };
              if (sortFeaturesByKey) {
                var oldSegments = bucket.segments.get();
                for (var i$1 = 0, list = oldSegments; i$1 < list.length; i$1 += 1) {
                  var segment = list[i$1];
                  segmentsRenderStates.push({
                    segments: new performance2.SegmentVector([segment]),
                    sortKey: segment.sortKey,
                    state
                  });
                }
              } else {
                segmentsRenderStates.push({
                  segments: bucket.segments,
                  sortKey: 0,
                  state
                });
              }
            }
            if (sortFeaturesByKey) {
              segmentsRenderStates.sort(function(a, b) {
                return a.sortKey - b.sortKey;
              });
            }
            for (var i$2 = 0, list$1 = segmentsRenderStates; i$2 < list$1.length; i$2 += 1) {
              var segmentsState = list$1[i$2];
              var ref = segmentsState.state;
              var programConfiguration$1 = ref.programConfiguration;
              var program$1 = ref.program;
              var layoutVertexBuffer$1 = ref.layoutVertexBuffer;
              var indexBuffer$1 = ref.indexBuffer;
              var uniformValues$1 = ref.uniformValues;
              var segments = segmentsState.segments;
              program$1.draw(context, gl2.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues$1, layer.id, layoutVertexBuffer$1, indexBuffer$1, segments, layer.paint, painter.transform.zoom, programConfiguration$1);
            }
          }
          function drawHeatmap(painter, sourceCache, layer, coords) {
            if (layer.paint.get("heatmap-opacity") === 0) {
              return;
            }
            if (painter.renderPass === "offscreen") {
              var context = painter.context;
              var gl2 = context.gl;
              var stencilMode = StencilMode.disabled;
              var colorMode = new ColorMode([
                gl2.ONE,
                gl2.ONE
              ], performance2.Color.transparent, [
                true,
                true,
                true,
                true
              ]);
              bindFramebuffer(context, painter, layer);
              context.clear({ color: performance2.Color.transparent });
              for (var i = 0; i < coords.length; i++) {
                var coord = coords[i];
                if (sourceCache.hasRenderableParent(coord)) {
                  continue;
                }
                var tile = sourceCache.getTile(coord);
                var bucket = tile.getBucket(layer);
                if (!bucket) {
                  continue;
                }
                var programConfiguration = bucket.programConfigurations.get(layer.id);
                var program = painter.useProgram("heatmap", programConfiguration);
                var ref = painter.transform;
                var zoom = ref.zoom;
                program.draw(context, gl2.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(coord.posMatrix, tile, zoom, layer.paint.get("heatmap-intensity")), layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration);
              }
              context.viewport.set([
                0,
                0,
                painter.width,
                painter.height
              ]);
            } else if (painter.renderPass === "translucent") {
              painter.context.setColorMode(painter.colorModeForRenderPass());
              renderTextureToMap(painter, layer);
            }
          }
          function bindFramebuffer(context, painter, layer) {
            var gl2 = context.gl;
            context.activeTexture.set(gl2.TEXTURE1);
            context.viewport.set([
              0,
              0,
              painter.width / 4,
              painter.height / 4
            ]);
            var fbo = layer.heatmapFbo;
            if (!fbo) {
              var texture = gl2.createTexture();
              gl2.bindTexture(gl2.TEXTURE_2D, texture);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
              gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
              fbo = layer.heatmapFbo = context.createFramebuffer(painter.width / 4, painter.height / 4, false);
              bindTextureToFramebuffer(context, painter, texture, fbo);
            } else {
              gl2.bindTexture(gl2.TEXTURE_2D, fbo.colorAttachment.get());
              context.bindFramebuffer.set(fbo.framebuffer);
            }
          }
          function bindTextureToFramebuffer(context, painter, texture, fbo) {
            var gl2 = context.gl;
            var internalFormat = context.extRenderToTextureHalfFloat ? context.extTextureHalfFloat.HALF_FLOAT_OES : gl2.UNSIGNED_BYTE;
            gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, painter.width / 4, painter.height / 4, 0, gl2.RGBA, internalFormat, null);
            fbo.colorAttachment.set(texture);
          }
          function renderTextureToMap(painter, layer) {
            var context = painter.context;
            var gl2 = context.gl;
            var fbo = layer.heatmapFbo;
            if (!fbo) {
              return;
            }
            context.activeTexture.set(gl2.TEXTURE0);
            gl2.bindTexture(gl2.TEXTURE_2D, fbo.colorAttachment.get());
            context.activeTexture.set(gl2.TEXTURE1);
            var colorRampTexture = layer.colorRampTexture;
            if (!colorRampTexture) {
              colorRampTexture = layer.colorRampTexture = new performance2.Texture(context, layer.colorRamp, gl2.RGBA);
            }
            colorRampTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
            painter.useProgram("heatmapTexture").draw(context, gl2.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom);
          }
          function drawLine(painter, sourceCache, layer, coords) {
            if (painter.renderPass !== "translucent") {
              return;
            }
            var opacity = layer.paint.get("line-opacity");
            var width = layer.paint.get("line-width");
            if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0) {
              return;
            }
            var depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
            var colorMode = painter.colorModeForRenderPass();
            var dasharray = layer.paint.get("line-dasharray");
            var patternProperty = layer.paint.get("line-pattern");
            var image = patternProperty.constantOr(1);
            var gradient = layer.paint.get("line-gradient");
            var crossfade = layer.getCrossfadeParameters();
            var programId = image ? "linePattern" : dasharray ? "lineSDF" : gradient ? "lineGradient" : "line";
            var context = painter.context;
            var gl2 = context.gl;
            var firstTile = true;
            for (var i = 0, list = coords; i < list.length; i += 1) {
              var coord = list[i];
              var tile = sourceCache.getTile(coord);
              if (image && !tile.patternsLoaded()) {
                continue;
              }
              var bucket = tile.getBucket(layer);
              if (!bucket) {
                continue;
              }
              var programConfiguration = bucket.programConfigurations.get(layer.id);
              var prevProgram = painter.context.program.get();
              var program = painter.useProgram(programId, programConfiguration);
              var programChanged = firstTile || program.program !== prevProgram;
              var constantPattern = patternProperty.constantOr(null);
              if (constantPattern && tile.imageAtlas) {
                var atlas = tile.imageAtlas;
                var posTo = atlas.patternPositions[constantPattern.to.toString()];
                var posFrom = atlas.patternPositions[constantPattern.from.toString()];
                if (posTo && posFrom) {
                  programConfiguration.setConstantPatternPositions(posTo, posFrom);
                }
              }
              var uniformValues = image ? linePatternUniformValues(painter, tile, layer, crossfade) : dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade) : gradient ? lineGradientUniformValues(painter, tile, layer, bucket.lineClipsArray.length) : lineUniformValues(painter, tile, layer);
              if (image) {
                context.activeTexture.set(gl2.TEXTURE0);
                tile.imageAtlasTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
                programConfiguration.updatePaintBuffers(crossfade);
              } else if (dasharray && (programChanged || painter.lineAtlas.dirty)) {
                context.activeTexture.set(gl2.TEXTURE0);
                painter.lineAtlas.bind(context);
              } else if (gradient) {
                var layerGradient = bucket.gradients[layer.id];
                var gradientTexture = layerGradient.texture;
                if (layer.gradientVersion !== layerGradient.version) {
                  var textureResolution = 256;
                  if (layer.stepInterpolant) {
                    var sourceMaxZoom = sourceCache.getSource().maxzoom;
                    var potentialOverzoom = coord.canonical.z === sourceMaxZoom ? Math.ceil(1 << painter.transform.maxZoom - coord.canonical.z) : 1;
                    var lineLength = bucket.maxLineLength / performance2.EXTENT;
                    var maxTilePixelSize = 1024;
                    var maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom;
                    textureResolution = performance2.clamp(performance2.nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize);
                  }
                  layerGradient.gradient = performance2.renderColorRamp({
                    expression: layer.gradientExpression(),
                    evaluationKey: "lineProgress",
                    resolution: textureResolution,
                    image: layerGradient.gradient || void 0,
                    clips: bucket.lineClipsArray
                  });
                  if (layerGradient.texture) {
                    layerGradient.texture.update(layerGradient.gradient);
                  } else {
                    layerGradient.texture = new performance2.Texture(context, layerGradient.gradient, gl2.RGBA);
                  }
                  layerGradient.version = layer.gradientVersion;
                  gradientTexture = layerGradient.texture;
                }
                context.activeTexture.set(gl2.TEXTURE0);
                gradientTexture.bind(layer.stepInterpolant ? gl2.NEAREST : gl2.LINEAR, gl2.CLAMP_TO_EDGE);
              }
              program.draw(context, gl2.TRIANGLES, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2);
              firstTile = false;
            }
          }
          function drawFill(painter, sourceCache, layer, coords) {
            var color2 = layer.paint.get("fill-color");
            var opacity = layer.paint.get("fill-opacity");
            if (opacity.constantOr(1) === 0) {
              return;
            }
            var colorMode = painter.colorModeForRenderPass();
            var pattern = layer.paint.get("fill-pattern");
            var pass = painter.opaquePassEnabledForLayer() && (!pattern.constantOr(1) && color2.constantOr(performance2.Color.transparent).a === 1 && opacity.constantOr(0) === 1) ? "opaque" : "translucent";
            if (painter.renderPass === pass) {
              var depthMode = painter.depthModeForSublayer(1, painter.renderPass === "opaque" ? DepthMode.ReadWrite : DepthMode.ReadOnly);
              drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false);
            }
            if (painter.renderPass === "translucent" && layer.paint.get("fill-antialias")) {
              var depthMode$1 = painter.depthModeForSublayer(layer.getPaintProperty("fill-outline-color") ? 2 : 0, DepthMode.ReadOnly);
              drawFillTiles(painter, sourceCache, layer, coords, depthMode$1, colorMode, true);
            }
          }
          function drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, isOutline) {
            var gl2 = painter.context.gl;
            var patternProperty = layer.paint.get("fill-pattern");
            var image = patternProperty && patternProperty.constantOr(1);
            var crossfade = layer.getCrossfadeParameters();
            var drawMode, programName, uniformValues, indexBuffer, segments;
            if (!isOutline) {
              programName = image ? "fillPattern" : "fill";
              drawMode = gl2.TRIANGLES;
            } else {
              programName = image && !layer.getPaintProperty("fill-outline-color") ? "fillOutlinePattern" : "fillOutline";
              drawMode = gl2.LINES;
            }
            for (var i = 0, list = coords; i < list.length; i += 1) {
              var coord = list[i];
              var tile = sourceCache.getTile(coord);
              if (image && !tile.patternsLoaded()) {
                continue;
              }
              var bucket = tile.getBucket(layer);
              if (!bucket) {
                continue;
              }
              var programConfiguration = bucket.programConfigurations.get(layer.id);
              var program = painter.useProgram(programName, programConfiguration);
              if (image) {
                painter.context.activeTexture.set(gl2.TEXTURE0);
                tile.imageAtlasTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
                programConfiguration.updatePaintBuffers(crossfade);
              }
              var constantPattern = patternProperty.constantOr(null);
              if (constantPattern && tile.imageAtlas) {
                var atlas = tile.imageAtlas;
                var posTo = atlas.patternPositions[constantPattern.to.toString()];
                var posFrom = atlas.patternPositions[constantPattern.from.toString()];
                if (posTo && posFrom) {
                  programConfiguration.setConstantPatternPositions(posTo, posFrom);
                }
              }
              var tileMatrix = painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get("fill-translate"), layer.paint.get("fill-translate-anchor"));
              if (!isOutline) {
                indexBuffer = bucket.indexBuffer;
                segments = bucket.segments;
                uniformValues = image ? fillPatternUniformValues(tileMatrix, painter, crossfade, tile) : fillUniformValues(tileMatrix);
              } else {
                indexBuffer = bucket.indexBuffer2;
                segments = bucket.segments2;
                var drawingBufferSize = [
                  gl2.drawingBufferWidth,
                  gl2.drawingBufferHeight
                ];
                uniformValues = programName === "fillOutlinePattern" && image ? fillOutlinePatternUniformValues(tileMatrix, painter, crossfade, tile, drawingBufferSize) : fillOutlineUniformValues(tileMatrix, drawingBufferSize);
              }
              program.draw(painter.context, drawMode, depthMode, painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration);
            }
          }
          function draw(painter, source, layer, coords) {
            var opacity = layer.paint.get("fill-extrusion-opacity");
            if (opacity === 0) {
              return;
            }
            if (painter.renderPass === "translucent") {
              var depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
              if (opacity === 1 && !layer.paint.get("fill-extrusion-pattern").constantOr(1)) {
                var colorMode = painter.colorModeForRenderPass();
                drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode);
              } else {
                drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled);
                drawExtrusionTiles(painter, source, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass());
              }
            }
          }
          function drawExtrusionTiles(painter, source, layer, coords, depthMode, stencilMode, colorMode) {
            var context = painter.context;
            var gl2 = context.gl;
            var patternProperty = layer.paint.get("fill-extrusion-pattern");
            var image = patternProperty.constantOr(1);
            var crossfade = layer.getCrossfadeParameters();
            var opacity = layer.paint.get("fill-extrusion-opacity");
            for (var i = 0, list = coords; i < list.length; i += 1) {
              var coord = list[i];
              var tile = source.getTile(coord);
              var bucket = tile.getBucket(layer);
              if (!bucket) {
                continue;
              }
              var programConfiguration = bucket.programConfigurations.get(layer.id);
              var program = painter.useProgram(image ? "fillExtrusionPattern" : "fillExtrusion", programConfiguration);
              if (image) {
                painter.context.activeTexture.set(gl2.TEXTURE0);
                tile.imageAtlasTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
                programConfiguration.updatePaintBuffers(crossfade);
              }
              var constantPattern = patternProperty.constantOr(null);
              if (constantPattern && tile.imageAtlas) {
                var atlas = tile.imageAtlas;
                var posTo = atlas.patternPositions[constantPattern.to.toString()];
                var posFrom = atlas.patternPositions[constantPattern.from.toString()];
                if (posTo && posFrom) {
                  programConfiguration.setConstantPatternPositions(posTo, posFrom);
                }
              }
              var matrix = painter.translatePosMatrix(coord.posMatrix, tile, layer.paint.get("fill-extrusion-translate"), layer.paint.get("fill-extrusion-translate-anchor"));
              var shouldUseVerticalGradient = layer.paint.get("fill-extrusion-vertical-gradient");
              var uniformValues = image ? fillExtrusionPatternUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) : fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity);
              program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration);
            }
          }
          function drawHillshade(painter, sourceCache, layer, tileIDs) {
            if (painter.renderPass !== "offscreen" && painter.renderPass !== "translucent") {
              return;
            }
            var context = painter.context;
            var depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);
            var colorMode = painter.colorModeForRenderPass();
            var ref = painter.renderPass === "translucent" ? painter.stencilConfigForOverlap(tileIDs) : [
              {},
              tileIDs
            ];
            var stencilModes = ref[0];
            var coords = ref[1];
            for (var i = 0, list = coords; i < list.length; i += 1) {
              var coord = list[i];
              var tile = sourceCache.getTile(coord);
              if (tile.needsHillshadePrepare && painter.renderPass === "offscreen") {
                prepareHillshade(painter, tile, layer, depthMode, StencilMode.disabled, colorMode);
              } else if (painter.renderPass === "translucent") {
                renderHillshade(painter, tile, layer, depthMode, stencilModes[coord.overscaledZ], colorMode);
              }
            }
            context.viewport.set([
              0,
              0,
              painter.width,
              painter.height
            ]);
          }
          function renderHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) {
            var context = painter.context;
            var gl2 = context.gl;
            var fbo = tile.fbo;
            if (!fbo) {
              return;
            }
            var program = painter.useProgram("hillshade");
            context.activeTexture.set(gl2.TEXTURE0);
            gl2.bindTexture(gl2.TEXTURE_2D, fbo.colorAttachment.get());
            var uniformValues = hillshadeUniformValues(painter, tile, layer);
            program.draw(context, gl2.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);
          }
          function prepareHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) {
            var context = painter.context;
            var gl2 = context.gl;
            var dem = tile.dem;
            if (dem && dem.data) {
              var tileSize = dem.dim;
              var textureStride = dem.stride;
              var pixelData = dem.getPixels();
              context.activeTexture.set(gl2.TEXTURE1);
              context.pixelStoreUnpackPremultiplyAlpha.set(false);
              tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride);
              if (tile.demTexture) {
                var demTexture = tile.demTexture;
                demTexture.update(pixelData, { premultiply: false });
                demTexture.bind(gl2.NEAREST, gl2.CLAMP_TO_EDGE);
              } else {
                tile.demTexture = new performance2.Texture(context, pixelData, gl2.RGBA, { premultiply: false });
                tile.demTexture.bind(gl2.NEAREST, gl2.CLAMP_TO_EDGE);
              }
              context.activeTexture.set(gl2.TEXTURE0);
              var fbo = tile.fbo;
              if (!fbo) {
                var renderTexture = new performance2.Texture(context, {
                  width: tileSize,
                  height: tileSize,
                  data: null
                }, gl2.RGBA);
                renderTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
                fbo = tile.fbo = context.createFramebuffer(tileSize, tileSize, true);
                fbo.colorAttachment.set(renderTexture.texture);
              }
              context.bindFramebuffer.set(fbo.framebuffer);
              context.viewport.set([
                0,
                0,
                tileSize,
                tileSize
              ]);
              painter.useProgram("hillshadePrepare").draw(context, gl2.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformPrepareValues(tile.tileID, dem), layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);
              tile.needsHillshadePrepare = false;
            }
          }
          function drawRaster(painter, sourceCache, layer, tileIDs) {
            if (painter.renderPass !== "translucent") {
              return;
            }
            if (layer.paint.get("raster-opacity") === 0) {
              return;
            }
            if (!tileIDs.length) {
              return;
            }
            var context = painter.context;
            var gl2 = context.gl;
            var source = sourceCache.getSource();
            var program = painter.useProgram("raster");
            var colorMode = painter.colorModeForRenderPass();
            var ref = source instanceof ImageSource ? [
              {},
              tileIDs
            ] : painter.stencilConfigForOverlap(tileIDs);
            var stencilModes = ref[0];
            var coords = ref[1];
            var minTileZ = coords[coords.length - 1].overscaledZ;
            var align = !painter.options.moving;
            for (var i = 0, list = coords; i < list.length; i += 1) {
              var coord = list[i];
              var depthMode = painter.depthModeForSublayer(coord.overscaledZ - minTileZ, layer.paint.get("raster-opacity") === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl2.LESS);
              var tile = sourceCache.getTile(coord);
              var posMatrix = painter.transform.calculatePosMatrix(coord.toUnwrapped(), align);
              tile.registerFadeDuration(layer.paint.get("raster-fade-duration"));
              var parentTile = sourceCache.findLoadedParent(coord, 0), fade = getFadeValues(tile, parentTile, sourceCache, layer, painter.transform);
              var parentScaleBy = void 0, parentTL = void 0;
              var textureFilter = layer.paint.get("raster-resampling") === "nearest" ? gl2.NEAREST : gl2.LINEAR;
              context.activeTexture.set(gl2.TEXTURE0);
              tile.texture.bind(textureFilter, gl2.CLAMP_TO_EDGE, gl2.LINEAR_MIPMAP_NEAREST);
              context.activeTexture.set(gl2.TEXTURE1);
              if (parentTile) {
                parentTile.texture.bind(textureFilter, gl2.CLAMP_TO_EDGE, gl2.LINEAR_MIPMAP_NEAREST);
                parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ);
                parentTL = [
                  tile.tileID.canonical.x * parentScaleBy % 1,
                  tile.tileID.canonical.y * parentScaleBy % 1
                ];
              } else {
                tile.texture.bind(textureFilter, gl2.CLAMP_TO_EDGE, gl2.LINEAR_MIPMAP_NEAREST);
              }
              var uniformValues = rasterUniformValues(posMatrix, parentTL || [
                0,
                0
              ], parentScaleBy || 1, fade, layer);
              if (source instanceof ImageSource) {
                program.draw(context, gl2.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled, uniformValues, layer.id, source.boundsBuffer, painter.quadTriangleIndexBuffer, source.boundsSegments);
              } else {
                program.draw(context, gl2.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.disabled, uniformValues, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);
              }
            }
          }
          function getFadeValues(tile, parentTile, sourceCache, layer, transform) {
            var fadeDuration = layer.paint.get("raster-fade-duration");
            if (fadeDuration > 0) {
              var now = performance2.browser.now();
              var sinceTile = (now - tile.timeAdded) / fadeDuration;
              var sinceParent = parentTile ? (now - parentTile.timeAdded) / fadeDuration : -1;
              var source = sourceCache.getSource();
              var idealZ = transform.coveringZoomLevel({
                tileSize: source.tileSize,
                roundZoom: source.roundZoom
              });
              var fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ);
              var childOpacity = fadeIn && tile.refreshedUponExpiration ? 1 : performance2.clamp(fadeIn ? sinceTile : 1 - sinceParent, 0, 1);
              if (tile.refreshedUponExpiration && sinceTile >= 1) {
                tile.refreshedUponExpiration = false;
              }
              if (parentTile) {
                return {
                  opacity: 1,
                  mix: 1 - childOpacity
                };
              } else {
                return {
                  opacity: childOpacity,
                  mix: 0
                };
              }
            } else {
              return {
                opacity: 1,
                mix: 0
              };
            }
          }
          function drawBackground(painter, sourceCache, layer) {
            var color2 = layer.paint.get("background-color");
            var opacity = layer.paint.get("background-opacity");
            if (opacity === 0) {
              return;
            }
            var context = painter.context;
            var gl2 = context.gl;
            var transform = painter.transform;
            var tileSize = transform.tileSize;
            var image = layer.paint.get("background-pattern");
            if (painter.isPatternMissing(image)) {
              return;
            }
            var pass = !image && color2.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer() ? "opaque" : "translucent";
            if (painter.renderPass !== pass) {
              return;
            }
            var stencilMode = StencilMode.disabled;
            var depthMode = painter.depthModeForSublayer(0, pass === "opaque" ? DepthMode.ReadWrite : DepthMode.ReadOnly);
            var colorMode = painter.colorModeForRenderPass();
            var program = painter.useProgram(image ? "backgroundPattern" : "background");
            var tileIDs = transform.coveringTiles({ tileSize });
            if (image) {
              context.activeTexture.set(gl2.TEXTURE0);
              painter.imageManager.bind(painter.context);
            }
            var crossfade = layer.getCrossfadeParameters();
            for (var i = 0, list = tileIDs; i < list.length; i += 1) {
              var tileID = list[i];
              var matrix = painter.transform.calculatePosMatrix(tileID.toUnwrapped());
              var uniformValues = image ? backgroundPatternUniformValues(matrix, opacity, painter, image, {
                tileID,
                tileSize
              }, crossfade) : backgroundUniformValues(matrix, opacity, color2);
              program.draw(context, gl2.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, uniformValues, layer.id, painter.tileExtentBuffer, painter.quadTriangleIndexBuffer, painter.tileExtentSegments);
            }
          }
          var topColor = new performance2.Color(1, 0, 0, 1);
          var btmColor = new performance2.Color(0, 1, 0, 1);
          var leftColor = new performance2.Color(0, 0, 1, 1);
          var rightColor = new performance2.Color(1, 0, 1, 1);
          var centerColor = new performance2.Color(0, 1, 1, 1);
          function drawDebugPadding(painter) {
            var padding2 = painter.transform.padding;
            var lineWidth = 3;
            drawHorizontalLine(painter, painter.transform.height - (padding2.top || 0), lineWidth, topColor);
            drawHorizontalLine(painter, padding2.bottom || 0, lineWidth, btmColor);
            drawVerticalLine(painter, padding2.left || 0, lineWidth, leftColor);
            drawVerticalLine(painter, painter.transform.width - (padding2.right || 0), lineWidth, rightColor);
            var center = painter.transform.centerPoint;
            drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor);
          }
          function drawCrosshair(painter, x, y, color2) {
            var size = 20;
            var lineWidth = 2;
            drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color2);
            drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color2);
          }
          function drawHorizontalLine(painter, y, lineWidth, color2) {
            drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color2);
          }
          function drawVerticalLine(painter, x, lineWidth, color2) {
            drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color2);
          }
          function drawDebugSSRect(painter, x, y, width, height, color2) {
            var context = painter.context;
            var gl2 = context.gl;
            gl2.enable(gl2.SCISSOR_TEST);
            gl2.scissor(x * performance2.browser.devicePixelRatio, y * performance2.browser.devicePixelRatio, width * performance2.browser.devicePixelRatio, height * performance2.browser.devicePixelRatio);
            context.clear({ color: color2 });
            gl2.disable(gl2.SCISSOR_TEST);
          }
          function drawDebug(painter, sourceCache, coords) {
            for (var i = 0; i < coords.length; i++) {
              drawDebugTile(painter, sourceCache, coords[i]);
            }
          }
          function drawDebugTile(painter, sourceCache, coord) {
            var context = painter.context;
            var gl2 = context.gl;
            var posMatrix = coord.posMatrix;
            var program = painter.useProgram("debug");
            var depthMode = DepthMode.disabled;
            var stencilMode = StencilMode.disabled;
            var colorMode = painter.colorModeForRenderPass();
            var id = "$debug";
            context.activeTexture.set(gl2.TEXTURE0);
            painter.emptyTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
            program.draw(context, gl2.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled, debugUniformValues(posMatrix, performance2.Color.red), id, painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments);
            var tileRawData = sourceCache.getTileByID(coord.key).latestRawTileData;
            var tileByteLength = tileRawData && tileRawData.byteLength || 0;
            var tileSizeKb = Math.floor(tileByteLength / 1024);
            var tileSize = sourceCache.getTile(coord).tileSize;
            var scaleRatio = 512 / Math.min(tileSize, 512) * (coord.overscaledZ / painter.transform.zoom) * 0.5;
            var tileIdText = coord.canonical.toString();
            if (coord.overscaledZ !== coord.canonical.z) {
              tileIdText += " => " + coord.overscaledZ;
            }
            var tileLabel = tileIdText + " " + tileSizeKb + "kb";
            drawTextToOverlay(painter, tileLabel);
            program.draw(context, gl2.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled, debugUniformValues(posMatrix, performance2.Color.transparent, scaleRatio), id, painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments);
          }
          function drawTextToOverlay(painter, text) {
            painter.initDebugOverlayCanvas();
            var canvas = painter.debugOverlayCanvas;
            var gl2 = painter.context.gl;
            var ctx2d = painter.debugOverlayCanvas.getContext("2d");
            ctx2d.clearRect(0, 0, canvas.width, canvas.height);
            ctx2d.shadowColor = "white";
            ctx2d.shadowBlur = 2;
            ctx2d.lineWidth = 1.5;
            ctx2d.strokeStyle = "white";
            ctx2d.textBaseline = "top";
            ctx2d.font = "bold 36px Open Sans, sans-serif";
            ctx2d.fillText(text, 5, 5);
            ctx2d.strokeText(text, 5, 5);
            painter.debugOverlayTexture.update(canvas);
            painter.debugOverlayTexture.bind(gl2.LINEAR, gl2.CLAMP_TO_EDGE);
          }
          function drawCustom(painter, sourceCache, layer) {
            var context = painter.context;
            var implementation = layer.implementation;
            if (painter.renderPass === "offscreen") {
              var prerender = implementation.prerender;
              if (prerender) {
                painter.setCustomLayerDefaults();
                context.setColorMode(painter.colorModeForRenderPass());
                prerender.call(implementation, context.gl, painter.transform.customLayerMatrix());
                context.setDirty();
                painter.setBaseState();
              }
            } else if (painter.renderPass === "translucent") {
              painter.setCustomLayerDefaults();
              context.setColorMode(painter.colorModeForRenderPass());
              context.setStencilMode(StencilMode.disabled);
              var depthMode = implementation.renderingMode === "3d" ? new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D) : painter.depthModeForSublayer(0, DepthMode.ReadOnly);
              context.setDepthMode(depthMode);
              implementation.render(context.gl, painter.transform.customLayerMatrix());
              context.setDirty();
              painter.setBaseState();
              context.bindFramebuffer.set(null);
            }
          }
          var draw$1 = {
            symbol: drawSymbols,
            circle: drawCircles,
            heatmap: drawHeatmap,
            line: drawLine,
            fill: drawFill,
            "fill-extrusion": draw,
            hillshade: drawHillshade,
            raster: drawRaster,
            background: drawBackground,
            debug: drawDebug,
            custom: drawCustom
          };
          var Painter = function Painter2(gl2, transform) {
            this.context = new Context(gl2);
            this.transform = transform;
            this._tileTextures = {};
            this.setup();
            this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1;
            this.depthEpsilon = 1 / Math.pow(2, 16);
            this.crossTileSymbolIndex = new CrossTileSymbolIndex();
            this.gpuTimers = {};
          };
          Painter.prototype.resize = function resize(width, height) {
            this.width = width * performance2.browser.devicePixelRatio;
            this.height = height * performance2.browser.devicePixelRatio;
            this.context.viewport.set([
              0,
              0,
              this.width,
              this.height
            ]);
            if (this.style) {
              for (var i = 0, list = this.style._order; i < list.length; i += 1) {
                var layerId = list[i];
                this.style._layers[layerId].resize();
              }
            }
          };
          Painter.prototype.setup = function setup() {
            var context = this.context;
            var tileExtentArray = new performance2.StructArrayLayout2i4();
            tileExtentArray.emplaceBack(0, 0);
            tileExtentArray.emplaceBack(performance2.EXTENT, 0);
            tileExtentArray.emplaceBack(0, performance2.EXTENT);
            tileExtentArray.emplaceBack(performance2.EXTENT, performance2.EXTENT);
            this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);
            this.tileExtentSegments = performance2.SegmentVector.simpleSegment(0, 0, 4, 2);
            var debugArray = new performance2.StructArrayLayout2i4();
            debugArray.emplaceBack(0, 0);
            debugArray.emplaceBack(performance2.EXTENT, 0);
            debugArray.emplaceBack(0, performance2.EXTENT);
            debugArray.emplaceBack(performance2.EXTENT, performance2.EXTENT);
            this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members);
            this.debugSegments = performance2.SegmentVector.simpleSegment(0, 0, 4, 5);
            var rasterBoundsArray = new performance2.StructArrayLayout4i8();
            rasterBoundsArray.emplaceBack(0, 0, 0, 0);
            rasterBoundsArray.emplaceBack(performance2.EXTENT, 0, performance2.EXTENT, 0);
            rasterBoundsArray.emplaceBack(0, performance2.EXTENT, 0, performance2.EXTENT);
            rasterBoundsArray.emplaceBack(performance2.EXTENT, performance2.EXTENT, performance2.EXTENT, performance2.EXTENT);
            this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members);
            this.rasterBoundsSegments = performance2.SegmentVector.simpleSegment(0, 0, 4, 2);
            var viewportArray = new performance2.StructArrayLayout2i4();
            viewportArray.emplaceBack(0, 0);
            viewportArray.emplaceBack(1, 0);
            viewportArray.emplaceBack(0, 1);
            viewportArray.emplaceBack(1, 1);
            this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members);
            this.viewportSegments = performance2.SegmentVector.simpleSegment(0, 0, 4, 2);
            var tileLineStripIndices = new performance2.StructArrayLayout1ui2();
            tileLineStripIndices.emplaceBack(0);
            tileLineStripIndices.emplaceBack(1);
            tileLineStripIndices.emplaceBack(3);
            tileLineStripIndices.emplaceBack(2);
            tileLineStripIndices.emplaceBack(0);
            this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices);
            var quadTriangleIndices = new performance2.StructArrayLayout3ui6();
            quadTriangleIndices.emplaceBack(0, 1, 2);
            quadTriangleIndices.emplaceBack(2, 1, 3);
            this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);
            this.emptyTexture = new performance2.Texture(context, {
              width: 1,
              height: 1,
              data: new Uint8Array([
                0,
                0,
                0,
                0
              ])
            }, context.gl.RGBA);
            var gl2 = this.context.gl;
            this.stencilClearMode = new StencilMode({
              func: gl2.ALWAYS,
              mask: 0
            }, 0, 255, gl2.ZERO, gl2.ZERO, gl2.ZERO);
          };
          Painter.prototype.clearStencil = function clearStencil() {
            var context = this.context;
            var gl2 = context.gl;
            this.nextStencilID = 1;
            this.currentStencilSource = void 0;
            var matrix = performance2.create();
            performance2.ortho(matrix, 0, this.width, this.height, 0, 0, 1);
            performance2.scale(matrix, matrix, [
              gl2.drawingBufferWidth,
              gl2.drawingBufferHeight,
              0
            ]);
            this.useProgram("clippingMask").draw(context, gl2.TRIANGLES, DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(matrix), "$clipping", this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments);
          };
          Painter.prototype._renderTileClippingMasks = function _renderTileClippingMasks(layer, tileIDs) {
            if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs || !tileIDs.length) {
              return;
            }
            this.currentStencilSource = layer.source;
            var context = this.context;
            var gl2 = context.gl;
            if (this.nextStencilID + tileIDs.length > 256) {
              this.clearStencil();
            }
            context.setColorMode(ColorMode.disabled);
            context.setDepthMode(DepthMode.disabled);
            var program = this.useProgram("clippingMask");
            this._tileClippingMaskIDs = {};
            for (var i = 0, list = tileIDs; i < list.length; i += 1) {
              var tileID = list[i];
              var id = this._tileClippingMaskIDs[tileID.key] = this.nextStencilID++;
              program.draw(context, gl2.TRIANGLES, DepthMode.disabled, new StencilMode({
                func: gl2.ALWAYS,
                mask: 0
              }, id, 255, gl2.KEEP, gl2.KEEP, gl2.REPLACE), ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.posMatrix), "$clipping", this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments);
            }
          };
          Painter.prototype.stencilModeFor3D = function stencilModeFor3D() {
            this.currentStencilSource = void 0;
            if (this.nextStencilID + 1 > 256) {
              this.clearStencil();
            }
            var id = this.nextStencilID++;
            var gl2 = this.context.gl;
            return new StencilMode({
              func: gl2.NOTEQUAL,
              mask: 255
            }, id, 255, gl2.KEEP, gl2.KEEP, gl2.REPLACE);
          };
          Painter.prototype.stencilModeForClipping = function stencilModeForClipping(tileID) {
            var gl2 = this.context.gl;
            return new StencilMode({
              func: gl2.EQUAL,
              mask: 255
            }, this._tileClippingMaskIDs[tileID.key], 0, gl2.KEEP, gl2.KEEP, gl2.REPLACE);
          };
          Painter.prototype.stencilConfigForOverlap = function stencilConfigForOverlap(tileIDs) {
            var obj;
            var gl2 = this.context.gl;
            var coords = tileIDs.sort(function(a, b) {
              return b.overscaledZ - a.overscaledZ;
            });
            var minTileZ = coords[coords.length - 1].overscaledZ;
            var stencilValues = coords[0].overscaledZ - minTileZ + 1;
            if (stencilValues > 1) {
              this.currentStencilSource = void 0;
              if (this.nextStencilID + stencilValues > 256) {
                this.clearStencil();
              }
              var zToStencilMode = {};
              for (var i = 0; i < stencilValues; i++) {
                zToStencilMode[i + minTileZ] = new StencilMode({
                  func: gl2.GEQUAL,
                  mask: 255
                }, i + this.nextStencilID, 255, gl2.KEEP, gl2.KEEP, gl2.REPLACE);
              }
              this.nextStencilID += stencilValues;
              return [
                zToStencilMode,
                coords
              ];
            }
            return [
              (obj = {}, obj[minTileZ] = StencilMode.disabled, obj),
              coords
            ];
          };
          Painter.prototype.colorModeForRenderPass = function colorModeForRenderPass() {
            var gl2 = this.context.gl;
            if (this._showOverdrawInspector) {
              var numOverdrawSteps = 8;
              var a = 1 / numOverdrawSteps;
              return new ColorMode([
                gl2.CONSTANT_COLOR,
                gl2.ONE
              ], new performance2.Color(a, a, a, 0), [
                true,
                true,
                true,
                true
              ]);
            } else if (this.renderPass === "opaque") {
              return ColorMode.unblended;
            } else {
              return ColorMode.alphaBlended;
            }
          };
          Painter.prototype.depthModeForSublayer = function depthModeForSublayer(n, mask, func) {
            if (!this.opaquePassEnabledForLayer()) {
              return DepthMode.disabled;
            }
            var depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon;
            return new DepthMode(func || this.context.gl.LEQUAL, mask, [
              depth,
              depth
            ]);
          };
          Painter.prototype.opaquePassEnabledForLayer = function opaquePassEnabledForLayer() {
            return this.currentLayer < this.opaquePassCutoff;
          };
          Painter.prototype.render = function render(style, options) {
            var this$1 = this;
            this.style = style;
            this.options = options;
            this.lineAtlas = style.lineAtlas;
            this.imageManager = style.imageManager;
            this.glyphManager = style.glyphManager;
            this.symbolFadeChange = style.placement.symbolFadeChange(performance2.browser.now());
            this.imageManager.beginFrame();
            var layerIds = this.style._order;
            var sourceCaches = this.style.sourceCaches;
            for (var id in sourceCaches) {
              var sourceCache = sourceCaches[id];
              if (sourceCache.used) {
                sourceCache.prepare(this.context);
              }
            }
            var coordsAscending = {};
            var coordsDescending = {};
            var coordsDescendingSymbol = {};
            for (var id$1 in sourceCaches) {
              var sourceCache$1 = sourceCaches[id$1];
              coordsAscending[id$1] = sourceCache$1.getVisibleCoordinates();
              coordsDescending[id$1] = coordsAscending[id$1].slice().reverse();
              coordsDescendingSymbol[id$1] = sourceCache$1.getVisibleCoordinates(true).reverse();
            }
            this.opaquePassCutoff = Infinity;
            for (var i = 0; i < layerIds.length; i++) {
              var layerId = layerIds[i];
              if (this.style._layers[layerId].is3D()) {
                this.opaquePassCutoff = i;
                break;
              }
            }
            this.renderPass = "offscreen";
            for (var i$1 = 0, list = layerIds; i$1 < list.length; i$1 += 1) {
              var layerId$1 = list[i$1];
              var layer = this.style._layers[layerId$1];
              if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) {
                continue;
              }
              var coords = coordsDescending[layer.source];
              if (layer.type !== "custom" && !coords.length) {
                continue;
              }
              this.renderLayer(this, sourceCaches[layer.source], layer, coords);
            }
            this.context.bindFramebuffer.set(null);
            this.context.clear({
              color: options.showOverdrawInspector ? performance2.Color.black : performance2.Color.transparent,
              depth: 1
            });
            this.clearStencil();
            this._showOverdrawInspector = options.showOverdrawInspector;
            this.depthRangeFor3D = [
              0,
              1 - (style._order.length + 2) * this.numSublayers * this.depthEpsilon
            ];
            this.renderPass = "opaque";
            for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) {
              var layer$1 = this.style._layers[layerIds[this.currentLayer]];
              var sourceCache$2 = sourceCaches[layer$1.source];
              var coords$1 = coordsAscending[layer$1.source];
              this._renderTileClippingMasks(layer$1, coords$1);
              this.renderLayer(this, sourceCache$2, layer$1, coords$1);
            }
            this.renderPass = "translucent";
            for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) {
              var layer$2 = this.style._layers[layerIds[this.currentLayer]];
              var sourceCache$3 = sourceCaches[layer$2.source];
              var coords$2 = (layer$2.type === "symbol" ? coordsDescendingSymbol : coordsDescending)[layer$2.source];
              this._renderTileClippingMasks(layer$2, coordsAscending[layer$2.source]);
              this.renderLayer(this, sourceCache$3, layer$2, coords$2);
            }
            if (this.options.showTileBoundaries) {
              var selectedSource;
              var sourceCache$4;
              var layers = performance2.values(this.style._layers);
              layers.forEach(function(layer2) {
                if (layer2.source && !layer2.isHidden(this$1.transform.zoom)) {
                  if (layer2.source !== (sourceCache$4 && sourceCache$4.id)) {
                    sourceCache$4 = this$1.style.sourceCaches[layer2.source];
                  }
                  if (!selectedSource || selectedSource.getSource().maxzoom < sourceCache$4.getSource().maxzoom) {
                    selectedSource = sourceCache$4;
                  }
                }
              });
              if (selectedSource) {
                draw$1.debug(this, selectedSource, selectedSource.getVisibleCoordinates());
              }
            }
            if (this.options.showPadding) {
              drawDebugPadding(this);
            }
            this.context.setDefault();
          };
          Painter.prototype.renderLayer = function renderLayer(painter, sourceCache, layer, coords) {
            if (layer.isHidden(this.transform.zoom)) {
              return;
            }
            if (layer.type !== "background" && layer.type !== "custom" && !coords.length) {
              return;
            }
            this.id = layer.id;
            this.gpuTimingStart(layer);
            draw$1[layer.type](painter, sourceCache, layer, coords, this.style.placement.variableOffsets);
            this.gpuTimingEnd();
          };
          Painter.prototype.gpuTimingStart = function gpuTimingStart(layer) {
            if (!this.options.gpuTiming) {
              return;
            }
            var ext = this.context.extTimerQuery;
            var layerTimer = this.gpuTimers[layer.id];
            if (!layerTimer) {
              layerTimer = this.gpuTimers[layer.id] = {
                calls: 0,
                cpuTime: 0,
                query: ext.createQueryEXT()
              };
            }
            layerTimer.calls++;
            ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, layerTimer.query);
          };
          Painter.prototype.gpuTimingEnd = function gpuTimingEnd() {
            if (!this.options.gpuTiming) {
              return;
            }
            var ext = this.context.extTimerQuery;
            ext.endQueryEXT(ext.TIME_ELAPSED_EXT);
          };
          Painter.prototype.collectGpuTimers = function collectGpuTimers() {
            var currentLayerTimers = this.gpuTimers;
            this.gpuTimers = {};
            return currentLayerTimers;
          };
          Painter.prototype.queryGpuTimers = function queryGpuTimers(gpuTimers) {
            var layers = {};
            for (var layerId in gpuTimers) {
              var gpuTimer = gpuTimers[layerId];
              var ext = this.context.extTimerQuery;
              var gpuTime = ext.getQueryObjectEXT(gpuTimer.query, ext.QUERY_RESULT_EXT) / (1e3 * 1e3);
              ext.deleteQueryEXT(gpuTimer.query);
              layers[layerId] = gpuTime;
            }
            return layers;
          };
          Painter.prototype.translatePosMatrix = function translatePosMatrix(matrix, tile, translate, translateAnchor, inViewportPixelUnitsUnits) {
            if (!translate[0] && !translate[1]) {
              return matrix;
            }
            var angle = inViewportPixelUnitsUnits ? translateAnchor === "map" ? this.transform.angle : 0 : translateAnchor === "viewport" ? -this.transform.angle : 0;
            if (angle) {
              var sinA = Math.sin(angle);
              var cosA = Math.cos(angle);
              translate = [
                translate[0] * cosA - translate[1] * sinA,
                translate[0] * sinA + translate[1] * cosA
              ];
            }
            var translation = [
              inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], this.transform.zoom),
              inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], this.transform.zoom),
              0
            ];
            var translatedMatrix = new Float32Array(16);
            performance2.translate(translatedMatrix, matrix, translation);
            return translatedMatrix;
          };
          Painter.prototype.saveTileTexture = function saveTileTexture(texture) {
            var textures = this._tileTextures[texture.size[0]];
            if (!textures) {
              this._tileTextures[texture.size[0]] = [texture];
            } else {
              textures.push(texture);
            }
          };
          Painter.prototype.getTileTexture = function getTileTexture(size) {
            var textures = this._tileTextures[size];
            return textures && textures.length > 0 ? textures.pop() : null;
          };
          Painter.prototype.isPatternMissing = function isPatternMissing(image) {
            if (!image) {
              return false;
            }
            if (!image.from || !image.to) {
              return true;
            }
            var imagePosA = this.imageManager.getPattern(image.from.toString());
            var imagePosB = this.imageManager.getPattern(image.to.toString());
            return !imagePosA || !imagePosB;
          };
          Painter.prototype.useProgram = function useProgram(name2, programConfiguration) {
            this.cache = this.cache || {};
            var key = "" + name2 + (programConfiguration ? programConfiguration.cacheKey : "") + (this._showOverdrawInspector ? "/overdraw" : "");
            if (!this.cache[key]) {
              this.cache[key] = new Program$1(this.context, name2, shaders[name2], programConfiguration, programUniforms[name2], this._showOverdrawInspector);
            }
            return this.cache[key];
          };
          Painter.prototype.setCustomLayerDefaults = function setCustomLayerDefaults() {
            this.context.unbindVAO();
            this.context.cullFace.setDefault();
            this.context.activeTexture.setDefault();
            this.context.pixelStoreUnpack.setDefault();
            this.context.pixelStoreUnpackPremultiplyAlpha.setDefault();
            this.context.pixelStoreUnpackFlipY.setDefault();
          };
          Painter.prototype.setBaseState = function setBaseState() {
            var gl2 = this.context.gl;
            this.context.cullFace.set(false);
            this.context.viewport.set([
              0,
              0,
              this.width,
              this.height
            ]);
            this.context.blendEquation.set(gl2.FUNC_ADD);
          };
          Painter.prototype.initDebugOverlayCanvas = function initDebugOverlayCanvas() {
            if (this.debugOverlayCanvas == null) {
              this.debugOverlayCanvas = performance2.window.document.createElement("canvas");
              this.debugOverlayCanvas.width = 512;
              this.debugOverlayCanvas.height = 512;
              var gl2 = this.context.gl;
              this.debugOverlayTexture = new performance2.Texture(this.context, this.debugOverlayCanvas, gl2.RGBA);
            }
          };
          Painter.prototype.destroy = function destroy() {
            this.emptyTexture.destroy();
            if (this.debugOverlayTexture) {
              this.debugOverlayTexture.destroy();
            }
          };
          var Frustum = function Frustum2(points_, planes_) {
            this.points = points_;
            this.planes = planes_;
          };
          Frustum.fromInvProjectionMatrix = function fromInvProjectionMatrix(invProj, worldSize, zoom) {
            var clipSpaceCorners = [
              [
                -1,
                1,
                -1,
                1
              ],
              [
                1,
                1,
                -1,
                1
              ],
              [
                1,
                -1,
                -1,
                1
              ],
              [
                -1,
                -1,
                -1,
                1
              ],
              [
                -1,
                1,
                1,
                1
              ],
              [
                1,
                1,
                1,
                1
              ],
              [
                1,
                -1,
                1,
                1
              ],
              [
                -1,
                -1,
                1,
                1
              ]
            ];
            var scale = Math.pow(2, zoom);
            var frustumCoords = clipSpaceCorners.map(function(v) {
              return performance2.transformMat4([], v, invProj);
            }).map(function(v) {
              return performance2.scale$1([], v, 1 / v[3] / worldSize * scale);
            });
            var frustumPlanePointIndices = [
              [
                0,
                1,
                2
              ],
              [
                6,
                5,
                4
              ],
              [
                0,
                3,
                7
              ],
              [
                2,
                1,
                5
              ],
              [
                3,
                2,
                6
              ],
              [
                0,
                4,
                5
              ]
            ];
            var frustumPlanes = frustumPlanePointIndices.map(function(p) {
              var a = performance2.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);
              var b = performance2.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);
              var n = performance2.normalize([], performance2.cross([], a, b));
              var d = -performance2.dot(n, frustumCoords[p[1]]);
              return n.concat(d);
            });
            return new Frustum(frustumCoords, frustumPlanes);
          };
          var Aabb = function Aabb2(min_, max_) {
            this.min = min_;
            this.max = max_;
            this.center = performance2.scale$2([], performance2.add([], this.min, this.max), 0.5);
          };
          Aabb.prototype.quadrant = function quadrant(index) {
            var split = [
              index % 2 === 0,
              index < 2
            ];
            var qMin = performance2.clone$2(this.min);
            var qMax = performance2.clone$2(this.max);
            for (var axis = 0; axis < split.length; axis++) {
              qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];
              qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];
            }
            qMax[2] = this.max[2];
            return new Aabb(qMin, qMax);
          };
          Aabb.prototype.distanceX = function distanceX(point) {
            var pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]);
            return pointOnAabb - point[0];
          };
          Aabb.prototype.distanceY = function distanceY(point) {
            var pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]);
            return pointOnAabb - point[1];
          };
          Aabb.prototype.intersects = function intersects(frustum) {
            var aabbPoints = [
              [
                this.min[0],
                this.min[1],
                0,
                1
              ],
              [
                this.max[0],
                this.min[1],
                0,
                1
              ],
              [
                this.max[0],
                this.max[1],
                0,
                1
              ],
              [
                this.min[0],
                this.max[1],
                0,
                1
              ]
            ];
            var fullyInside = true;
            for (var p = 0; p < frustum.planes.length; p++) {
              var plane = frustum.planes[p];
              var pointsInside = 0;
              for (var i = 0; i < aabbPoints.length; i++) {
                pointsInside += performance2.dot$1(plane, aabbPoints[i]) >= 0;
              }
              if (pointsInside === 0) {
                return 0;
              }
              if (pointsInside !== aabbPoints.length) {
                fullyInside = false;
              }
            }
            if (fullyInside) {
              return 2;
            }
            for (var axis = 0; axis < 3; axis++) {
              var projMin = Number.MAX_VALUE;
              var projMax = -Number.MAX_VALUE;
              for (var p$1 = 0; p$1 < frustum.points.length; p$1++) {
                var projectedPoint = frustum.points[p$1][axis] - this.min[axis];
                projMin = Math.min(projMin, projectedPoint);
                projMax = Math.max(projMax, projectedPoint);
              }
              if (projMax < 0 || projMin > this.max[axis] - this.min[axis]) {
                return 0;
              }
            }
            return 1;
          };
          var EdgeInsets = function EdgeInsets2(top, bottom, left, right) {
            if (top === void 0)
              top = 0;
            if (bottom === void 0)
              bottom = 0;
            if (left === void 0)
              left = 0;
            if (right === void 0)
              right = 0;
            if (isNaN(top) || top < 0 || isNaN(bottom) || bottom < 0 || isNaN(left) || left < 0 || isNaN(right) || right < 0) {
              throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");
            }
            this.top = top;
            this.bottom = bottom;
            this.left = left;
            this.right = right;
          };
          EdgeInsets.prototype.interpolate = function interpolate(start, target, t) {
            if (target.top != null && start.top != null) {
              this.top = performance2.number(start.top, target.top, t);
            }
            if (target.bottom != null && start.bottom != null) {
              this.bottom = performance2.number(start.bottom, target.bottom, t);
            }
            if (target.left != null && start.left != null) {
              this.left = performance2.number(start.left, target.left, t);
            }
            if (target.right != null && start.right != null) {
              this.right = performance2.number(start.right, target.right, t);
            }
            return this;
          };
          EdgeInsets.prototype.getCenter = function getCenter(width, height) {
            var x = performance2.clamp((this.left + width - this.right) / 2, 0, width);
            var y = performance2.clamp((this.top + height - this.bottom) / 2, 0, height);
            return new performance2.Point(x, y);
          };
          EdgeInsets.prototype.equals = function equals(other) {
            return this.top === other.top && this.bottom === other.bottom && this.left === other.left && this.right === other.right;
          };
          EdgeInsets.prototype.clone = function clone() {
            return new EdgeInsets(this.top, this.bottom, this.left, this.right);
          };
          EdgeInsets.prototype.toJSON = function toJSON() {
            return {
              top: this.top,
              bottom: this.bottom,
              left: this.left,
              right: this.right
            };
          };
          var Transform = function Transform2(minZoom, maxZoom, minPitch, maxPitch, renderWorldCopies) {
            this.tileSize = 512;
            this.maxValidLatitude = 85.051129;
            this._renderWorldCopies = renderWorldCopies === void 0 ? true : renderWorldCopies;
            this._minZoom = minZoom || 0;
            this._maxZoom = maxZoom || 22;
            this._minPitch = minPitch === void 0 || minPitch === null ? 0 : minPitch;
            this._maxPitch = maxPitch === void 0 || maxPitch === null ? 60 : maxPitch;
            this.setMaxBounds();
            this.width = 0;
            this.height = 0;
            this._center = new performance2.LngLat(0, 0);
            this.zoom = 0;
            this.angle = 0;
            this._fov = 0.6435011087932844;
            this._pitch = 0;
            this._unmodified = true;
            this._edgeInsets = new EdgeInsets();
            this._posMatrixCache = {};
            this._alignedPosMatrixCache = {};
          };
          var prototypeAccessors = {
            minZoom: { configurable: true },
            maxZoom: { configurable: true },
            minPitch: { configurable: true },
            maxPitch: { configurable: true },
            renderWorldCopies: { configurable: true },
            worldSize: { configurable: true },
            centerOffset: { configurable: true },
            size: { configurable: true },
            bearing: { configurable: true },
            pitch: { configurable: true },
            fov: { configurable: true },
            zoom: { configurable: true },
            center: { configurable: true },
            padding: { configurable: true },
            centerPoint: { configurable: true },
            unmodified: { configurable: true },
            point: { configurable: true }
          };
          Transform.prototype.clone = function clone() {
            var clone2 = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies);
            clone2.tileSize = this.tileSize;
            clone2.latRange = this.latRange;
            clone2.width = this.width;
            clone2.height = this.height;
            clone2._center = this._center;
            clone2.zoom = this.zoom;
            clone2.angle = this.angle;
            clone2._fov = this._fov;
            clone2._pitch = this._pitch;
            clone2._unmodified = this._unmodified;
            clone2._edgeInsets = this._edgeInsets.clone();
            clone2._calcMatrices();
            return clone2;
          };
          prototypeAccessors.minZoom.get = function() {
            return this._minZoom;
          };
          prototypeAccessors.minZoom.set = function(zoom) {
            if (this._minZoom === zoom) {
              return;
            }
            this._minZoom = zoom;
            this.zoom = Math.max(this.zoom, zoom);
          };
          prototypeAccessors.maxZoom.get = function() {
            return this._maxZoom;
          };
          prototypeAccessors.maxZoom.set = function(zoom) {
            if (this._maxZoom === zoom) {
              return;
            }
            this._maxZoom = zoom;
            this.zoom = Math.min(this.zoom, zoom);
          };
          prototypeAccessors.minPitch.get = function() {
            return this._minPitch;
          };
          prototypeAccessors.minPitch.set = function(pitch) {
            if (this._minPitch === pitch) {
              return;
            }
            this._minPitch = pitch;
            this.pitch = Math.max(this.pitch, pitch);
          };
          prototypeAccessors.maxPitch.get = function() {
            return this._maxPitch;
          };
          prototypeAccessors.maxPitch.set = function(pitch) {
            if (this._maxPitch === pitch) {
              return;
            }
            this._maxPitch = pitch;
            this.pitch = Math.min(this.pitch, pitch);
          };
          prototypeAccessors.renderWorldCopies.get = function() {
            return this._renderWorldCopies;
          };
          prototypeAccessors.renderWorldCopies.set = function(renderWorldCopies) {
            if (renderWorldCopies === void 0) {
              renderWorldCopies = true;
            } else if (renderWorldCopies === null) {
              renderWorldCopies = false;
            }
            this._renderWorldCopies = renderWorldCopies;
          };
          prototypeAccessors.worldSize.get = function() {
            return this.tileSize * this.scale;
          };
          prototypeAccessors.centerOffset.get = function() {
            return this.centerPoint._sub(this.size._div(2));
          };
          prototypeAccessors.size.get = function() {
            return new performance2.Point(this.width, this.height);
          };
          prototypeAccessors.bearing.get = function() {
            return -this.angle / Math.PI * 180;
          };
          prototypeAccessors.bearing.set = function(bearing) {
            var b = -performance2.wrap(bearing, -180, 180) * Math.PI / 180;
            if (this.angle === b) {
              return;
            }
            this._unmodified = false;
            this.angle = b;
            this._calcMatrices();
            this.rotationMatrix = performance2.create$2();
            performance2.rotate(this.rotationMatrix, this.rotationMatrix, this.angle);
          };
          prototypeAccessors.pitch.get = function() {
            return this._pitch / Math.PI * 180;
          };
          prototypeAccessors.pitch.set = function(pitch) {
            var p = performance2.clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI;
            if (this._pitch === p) {
              return;
            }
            this._unmodified = false;
            this._pitch = p;
            this._calcMatrices();
          };
          prototypeAccessors.fov.get = function() {
            return this._fov / Math.PI * 180;
          };
          prototypeAccessors.fov.set = function(fov) {
            fov = Math.max(0.01, Math.min(60, fov));
            if (this._fov === fov) {
              return;
            }
            this._unmodified = false;
            this._fov = fov / 180 * Math.PI;
            this._calcMatrices();
          };
          prototypeAccessors.zoom.get = function() {
            return this._zoom;
          };
          prototypeAccessors.zoom.set = function(zoom) {
            var z = Math.min(Math.max(zoom, this.minZoom), this.maxZoom);
            if (this._zoom === z) {
              return;
            }
            this._unmodified = false;
            this._zoom = z;
            this.scale = this.zoomScale(z);
            this.tileZoom = Math.floor(z);
            this.zoomFraction = z - this.tileZoom;
            this._constrain();
            this._calcMatrices();
          };
          prototypeAccessors.center.get = function() {
            return this._center;
          };
          prototypeAccessors.center.set = function(center) {
            if (center.lat === this._center.lat && center.lng === this._center.lng) {
              return;
            }
            this._unmodified = false;
            this._center = center;
            this._constrain();
            this._calcMatrices();
          };
          prototypeAccessors.padding.get = function() {
            return this._edgeInsets.toJSON();
          };
          prototypeAccessors.padding.set = function(padding2) {
            if (this._edgeInsets.equals(padding2)) {
              return;
            }
            this._unmodified = false;
            this._edgeInsets.interpolate(this._edgeInsets, padding2, 1);
            this._calcMatrices();
          };
          prototypeAccessors.centerPoint.get = function() {
            return this._edgeInsets.getCenter(this.width, this.height);
          };
          Transform.prototype.isPaddingEqual = function isPaddingEqual(padding2) {
            return this._edgeInsets.equals(padding2);
          };
          Transform.prototype.interpolatePadding = function interpolatePadding(start, target, t) {
            this._unmodified = false;
            this._edgeInsets.interpolate(start, target, t);
            this._constrain();
            this._calcMatrices();
          };
          Transform.prototype.coveringZoomLevel = function coveringZoomLevel(options) {
            var z = (options.roundZoom ? Math.round : Math.floor)(this.zoom + this.scaleZoom(this.tileSize / options.tileSize));
            return Math.max(0, z);
          };
          Transform.prototype.getVisibleUnwrappedCoordinates = function getVisibleUnwrappedCoordinates(tileID) {
            var result = [new performance2.UnwrappedTileID(0, tileID)];
            if (this._renderWorldCopies) {
              var utl = this.pointCoordinate(new performance2.Point(0, 0));
              var utr = this.pointCoordinate(new performance2.Point(this.width, 0));
              var ubl = this.pointCoordinate(new performance2.Point(this.width, this.height));
              var ubr = this.pointCoordinate(new performance2.Point(0, this.height));
              var w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x));
              var w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x));
              var extraWorldCopy = 1;
              for (var w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {
                if (w === 0) {
                  continue;
                }
                result.push(new performance2.UnwrappedTileID(w, tileID));
              }
            }
            return result;
          };
          Transform.prototype.coveringTiles = function coveringTiles(options) {
            var z = this.coveringZoomLevel(options);
            var actualZ = z;
            if (options.minzoom !== void 0 && z < options.minzoom) {
              return [];
            }
            if (options.maxzoom !== void 0 && z > options.maxzoom) {
              z = options.maxzoom;
            }
            var centerCoord = performance2.MercatorCoordinate.fromLngLat(this.center);
            var numTiles = Math.pow(2, z);
            var centerPoint = [
              numTiles * centerCoord.x,
              numTiles * centerCoord.y,
              0
            ];
            var cameraFrustum = Frustum.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, z);
            var minZoom = options.minzoom || 0;
            if (this.pitch <= 60 && this._edgeInsets.top < 0.1) {
              minZoom = z;
            }
            var radiusOfMaxLvlLodInTiles = 3;
            var newRootTile = function(wrap) {
              return {
                aabb: new Aabb([
                  wrap * numTiles,
                  0,
                  0
                ], [
                  (wrap + 1) * numTiles,
                  numTiles,
                  0
                ]),
                zoom: 0,
                x: 0,
                y: 0,
                wrap,
                fullyVisible: false
              };
            };
            var stack = [];
            var result = [];
            var maxZoom = z;
            var overscaledZ = options.reparseOverscaled ? actualZ : z;
            if (this._renderWorldCopies) {
              for (var i = 1; i <= 3; i++) {
                stack.push(newRootTile(-i));
                stack.push(newRootTile(i));
              }
            }
            stack.push(newRootTile(0));
            while (stack.length > 0) {
              var it = stack.pop();
              var x = it.x;
              var y = it.y;
              var fullyVisible = it.fullyVisible;
              if (!fullyVisible) {
                var intersectResult = it.aabb.intersects(cameraFrustum);
                if (intersectResult === 0) {
                  continue;
                }
                fullyVisible = intersectResult === 2;
              }
              var distanceX = it.aabb.distanceX(centerPoint);
              var distanceY = it.aabb.distanceY(centerPoint);
              var longestDim = Math.max(Math.abs(distanceX), Math.abs(distanceY));
              var distToSplit = radiusOfMaxLvlLodInTiles + (1 << maxZoom - it.zoom) - 2;
              if (it.zoom === maxZoom || longestDim > distToSplit && it.zoom >= minZoom) {
                result.push({
                  tileID: new performance2.OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y),
                  distanceSq: performance2.sqrLen([
                    centerPoint[0] - 0.5 - x,
                    centerPoint[1] - 0.5 - y
                  ])
                });
                continue;
              }
              for (var i$1 = 0; i$1 < 4; i$1++) {
                var childX = (x << 1) + i$1 % 2;
                var childY = (y << 1) + (i$1 >> 1);
                stack.push({
                  aabb: it.aabb.quadrant(i$1),
                  zoom: it.zoom + 1,
                  x: childX,
                  y: childY,
                  wrap: it.wrap,
                  fullyVisible
                });
              }
            }
            return result.sort(function(a, b) {
              return a.distanceSq - b.distanceSq;
            }).map(function(a) {
              return a.tileID;
            });
          };
          Transform.prototype.resize = function resize(width, height) {
            this.width = width;
            this.height = height;
            this.pixelsToGLUnits = [
              2 / width,
              -2 / height
            ];
            this._constrain();
            this._calcMatrices();
          };
          prototypeAccessors.unmodified.get = function() {
            return this._unmodified;
          };
          Transform.prototype.zoomScale = function zoomScale(zoom) {
            return Math.pow(2, zoom);
          };
          Transform.prototype.scaleZoom = function scaleZoom(scale) {
            return Math.log(scale) / Math.LN2;
          };
          Transform.prototype.project = function project2(lnglat) {
            var lat = performance2.clamp(lnglat.lat, -this.maxValidLatitude, this.maxValidLatitude);
            return new performance2.Point(performance2.mercatorXfromLng(lnglat.lng) * this.worldSize, performance2.mercatorYfromLat(lat) * this.worldSize);
          };
          Transform.prototype.unproject = function unproject(point) {
            return new performance2.MercatorCoordinate(point.x / this.worldSize, point.y / this.worldSize).toLngLat();
          };
          prototypeAccessors.point.get = function() {
            return this.project(this.center);
          };
          Transform.prototype.setLocationAtPoint = function setLocationAtPoint(lnglat, point) {
            var a = this.pointCoordinate(point);
            var b = this.pointCoordinate(this.centerPoint);
            var loc = this.locationCoordinate(lnglat);
            var newCenter = new performance2.MercatorCoordinate(loc.x - (a.x - b.x), loc.y - (a.y - b.y));
            this.center = this.coordinateLocation(newCenter);
            if (this._renderWorldCopies) {
              this.center = this.center.wrap();
            }
          };
          Transform.prototype.locationPoint = function locationPoint(lnglat) {
            return this.coordinatePoint(this.locationCoordinate(lnglat));
          };
          Transform.prototype.pointLocation = function pointLocation(p) {
            return this.coordinateLocation(this.pointCoordinate(p));
          };
          Transform.prototype.locationCoordinate = function locationCoordinate(lnglat) {
            return performance2.MercatorCoordinate.fromLngLat(lnglat);
          };
          Transform.prototype.coordinateLocation = function coordinateLocation(coord) {
            return coord.toLngLat();
          };
          Transform.prototype.pointCoordinate = function pointCoordinate(p) {
            var targetZ = 0;
            var coord0 = [
              p.x,
              p.y,
              0,
              1
            ];
            var coord1 = [
              p.x,
              p.y,
              1,
              1
            ];
            performance2.transformMat4(coord0, coord0, this.pixelMatrixInverse);
            performance2.transformMat4(coord1, coord1, this.pixelMatrixInverse);
            var w0 = coord0[3];
            var w1 = coord1[3];
            var x0 = coord0[0] / w0;
            var x1 = coord1[0] / w1;
            var y0 = coord0[1] / w0;
            var y1 = coord1[1] / w1;
            var z0 = coord0[2] / w0;
            var z1 = coord1[2] / w1;
            var t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);
            return new performance2.MercatorCoordinate(performance2.number(x0, x1, t) / this.worldSize, performance2.number(y0, y1, t) / this.worldSize);
          };
          Transform.prototype.coordinatePoint = function coordinatePoint(coord) {
            var p = [
              coord.x * this.worldSize,
              coord.y * this.worldSize,
              0,
              1
            ];
            performance2.transformMat4(p, p, this.pixelMatrix);
            return new performance2.Point(p[0] / p[3], p[1] / p[3]);
          };
          Transform.prototype.getBounds = function getBounds() {
            return new performance2.LngLatBounds().extend(this.pointLocation(new performance2.Point(0, 0))).extend(this.pointLocation(new performance2.Point(this.width, 0))).extend(this.pointLocation(new performance2.Point(this.width, this.height))).extend(this.pointLocation(new performance2.Point(0, this.height)));
          };
          Transform.prototype.getMaxBounds = function getMaxBounds() {
            if (!this.latRange || this.latRange.length !== 2 || !this.lngRange || this.lngRange.length !== 2) {
              return null;
            }
            return new performance2.LngLatBounds([
              this.lngRange[0],
              this.latRange[0]
            ], [
              this.lngRange[1],
              this.latRange[1]
            ]);
          };
          Transform.prototype.setMaxBounds = function setMaxBounds(bounds) {
            if (bounds) {
              this.lngRange = [
                bounds.getWest(),
                bounds.getEast()
              ];
              this.latRange = [
                bounds.getSouth(),
                bounds.getNorth()
              ];
              this._constrain();
            } else {
              this.lngRange = null;
              this.latRange = [
                -this.maxValidLatitude,
                this.maxValidLatitude
              ];
            }
          };
          Transform.prototype.calculatePosMatrix = function calculatePosMatrix(unwrappedTileID, aligned) {
            if (aligned === void 0)
              aligned = false;
            var posMatrixKey = unwrappedTileID.key;
            var cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache;
            if (cache[posMatrixKey]) {
              return cache[posMatrixKey];
            }
            var canonical = unwrappedTileID.canonical;
            var scale = this.worldSize / this.zoomScale(canonical.z);
            var unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;
            var posMatrix = performance2.identity(new Float64Array(16));
            performance2.translate(posMatrix, posMatrix, [
              unwrappedX * scale,
              canonical.y * scale,
              0
            ]);
            performance2.scale(posMatrix, posMatrix, [
              scale / performance2.EXTENT,
              scale / performance2.EXTENT,
              1
            ]);
            performance2.multiply(posMatrix, aligned ? this.alignedProjMatrix : this.projMatrix, posMatrix);
            cache[posMatrixKey] = new Float32Array(posMatrix);
            return cache[posMatrixKey];
          };
          Transform.prototype.customLayerMatrix = function customLayerMatrix() {
            return this.mercatorMatrix.slice();
          };
          Transform.prototype._constrain = function _constrain() {
            if (!this.center || !this.width || !this.height || this._constraining) {
              return;
            }
            this._constraining = true;
            var minY = -90;
            var maxY = 90;
            var minX = -180;
            var maxX = 180;
            var sy, sx, x2, y2;
            var size = this.size, unmodified = this._unmodified;
            if (this.latRange) {
              var latRange = this.latRange;
              minY = performance2.mercatorYfromLat(latRange[1]) * this.worldSize;
              maxY = performance2.mercatorYfromLat(latRange[0]) * this.worldSize;
              sy = maxY - minY < size.y ? size.y / (maxY - minY) : 0;
            }
            if (this.lngRange) {
              var lngRange = this.lngRange;
              minX = performance2.mercatorXfromLng(lngRange[0]) * this.worldSize;
              maxX = performance2.mercatorXfromLng(lngRange[1]) * this.worldSize;
              sx = maxX - minX < size.x ? size.x / (maxX - minX) : 0;
            }
            var point = this.point;
            var s = Math.max(sx || 0, sy || 0);
            if (s) {
              this.center = this.unproject(new performance2.Point(sx ? (maxX + minX) / 2 : point.x, sy ? (maxY + minY) / 2 : point.y));
              this.zoom += this.scaleZoom(s);
              this._unmodified = unmodified;
              this._constraining = false;
              return;
            }
            if (this.latRange) {
              var y = point.y, h2 = size.y / 2;
              if (y - h2 < minY) {
                y2 = minY + h2;
              }
              if (y + h2 > maxY) {
                y2 = maxY - h2;
              }
            }
            if (this.lngRange) {
              var x = point.x, w2 = size.x / 2;
              if (x - w2 < minX) {
                x2 = minX + w2;
              }
              if (x + w2 > maxX) {
                x2 = maxX - w2;
              }
            }
            if (x2 !== void 0 || y2 !== void 0) {
              this.center = this.unproject(new performance2.Point(x2 !== void 0 ? x2 : point.x, y2 !== void 0 ? y2 : point.y));
            }
            this._unmodified = unmodified;
            this._constraining = false;
          };
          Transform.prototype._calcMatrices = function _calcMatrices() {
            if (!this.height) {
              return;
            }
            var halfFov = this._fov / 2;
            var offset = this.centerOffset;
            this.cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this.height;
            var groundAngle = Math.PI / 2 + this._pitch;
            var fovAboveCenter = this._fov * (0.5 + offset.y / this.height);
            var topHalfSurfaceDistance = Math.sin(fovAboveCenter) * this.cameraToCenterDistance / Math.sin(performance2.clamp(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01));
            var point = this.point;
            var x = point.x, y = point.y;
            var furthestDistance = Math.cos(Math.PI / 2 - this._pitch) * topHalfSurfaceDistance + this.cameraToCenterDistance;
            var farZ = furthestDistance * 1.01;
            var nearZ = this.height / 50;
            var m = new Float64Array(16);
            performance2.perspective(m, this._fov, this.width / this.height, nearZ, farZ);
            m[8] = -offset.x * 2 / this.width;
            m[9] = offset.y * 2 / this.height;
            performance2.scale(m, m, [
              1,
              -1,
              1
            ]);
            performance2.translate(m, m, [
              0,
              0,
              -this.cameraToCenterDistance
            ]);
            performance2.rotateX(m, m, this._pitch);
            performance2.rotateZ(m, m, this.angle);
            performance2.translate(m, m, [
              -x,
              -y,
              0
            ]);
            this.mercatorMatrix = performance2.scale([], m, [
              this.worldSize,
              this.worldSize,
              this.worldSize
            ]);
            performance2.scale(m, m, [
              1,
              1,
              performance2.mercatorZfromAltitude(1, this.center.lat) * this.worldSize,
              1
            ]);
            this.projMatrix = m;
            this.invProjMatrix = performance2.invert([], this.projMatrix);
            var xShift = this.width % 2 / 2, yShift = this.height % 2 / 2, angleCos = Math.cos(this.angle), angleSin = Math.sin(this.angle), dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift, dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;
            var alignedM = new Float64Array(m);
            performance2.translate(alignedM, alignedM, [
              dx > 0.5 ? dx - 1 : dx,
              dy > 0.5 ? dy - 1 : dy,
              0
            ]);
            this.alignedProjMatrix = alignedM;
            m = performance2.create();
            performance2.scale(m, m, [
              this.width / 2,
              -this.height / 2,
              1
            ]);
            performance2.translate(m, m, [
              1,
              -1,
              0
            ]);
            this.labelPlaneMatrix = m;
            m = performance2.create();
            performance2.scale(m, m, [
              1,
              -1,
              1
            ]);
            performance2.translate(m, m, [
              -1,
              -1,
              0
            ]);
            performance2.scale(m, m, [
              2 / this.width,
              2 / this.height,
              1
            ]);
            this.glCoordMatrix = m;
            this.pixelMatrix = performance2.multiply(new Float64Array(16), this.labelPlaneMatrix, this.projMatrix);
            m = performance2.invert(new Float64Array(16), this.pixelMatrix);
            if (!m) {
              throw new Error("failed to invert matrix");
            }
            this.pixelMatrixInverse = m;
            this._posMatrixCache = {};
            this._alignedPosMatrixCache = {};
          };
          Transform.prototype.maxPitchScaleFactor = function maxPitchScaleFactor() {
            if (!this.pixelMatrixInverse) {
              return 1;
            }
            var coord = this.pointCoordinate(new performance2.Point(0, 0));
            var p = [
              coord.x * this.worldSize,
              coord.y * this.worldSize,
              0,
              1
            ];
            var topPoint = performance2.transformMat4(p, p, this.pixelMatrix);
            return topPoint[3] / this.cameraToCenterDistance;
          };
          Transform.prototype.getCameraPoint = function getCameraPoint() {
            var pitch = this._pitch;
            var yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);
            return this.centerPoint.add(new performance2.Point(0, yOffset));
          };
          Transform.prototype.getCameraQueryGeometry = function getCameraQueryGeometry(queryGeometry) {
            var c = this.getCameraPoint();
            if (queryGeometry.length === 1) {
              return [
                queryGeometry[0],
                c
              ];
            } else {
              var minX = c.x;
              var minY = c.y;
              var maxX = c.x;
              var maxY = c.y;
              for (var i = 0, list = queryGeometry; i < list.length; i += 1) {
                var p = list[i];
                minX = Math.min(minX, p.x);
                minY = Math.min(minY, p.y);
                maxX = Math.max(maxX, p.x);
                maxY = Math.max(maxY, p.y);
              }
              return [
                new performance2.Point(minX, minY),
                new performance2.Point(maxX, minY),
                new performance2.Point(maxX, maxY),
                new performance2.Point(minX, maxY),
                new performance2.Point(minX, minY)
              ];
            }
          };
          Object.defineProperties(Transform.prototype, prototypeAccessors);
          function throttle(fn, time) {
            var pending = false;
            var timerId = null;
            var later = function() {
              timerId = null;
              if (pending) {
                fn();
                timerId = setTimeout(later, time);
                pending = false;
              }
            };
            return function() {
              pending = true;
              if (!timerId) {
                later();
              }
              return timerId;
            };
          }
          var Hash = function Hash2(hashName) {
            this._hashName = hashName && encodeURIComponent(hashName);
            performance2.bindAll([
              "_getCurrentHash",
              "_onHashChange",
              "_updateHash"
            ], this);
            this._updateHash = throttle(this._updateHashUnthrottled.bind(this), 30 * 1e3 / 100);
          };
          Hash.prototype.addTo = function addTo(map) {
            this._map = map;
            performance2.window.addEventListener("hashchange", this._onHashChange, false);
            this._map.on("moveend", this._updateHash);
            return this;
          };
          Hash.prototype.remove = function remove() {
            performance2.window.removeEventListener("hashchange", this._onHashChange, false);
            this._map.off("moveend", this._updateHash);
            clearTimeout(this._updateHash());
            delete this._map;
            return this;
          };
          Hash.prototype.getHashString = function getHashString(mapFeedback) {
            var center = this._map.getCenter(), zoom = Math.round(this._map.getZoom() * 100) / 100, precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), m = Math.pow(10, precision), lng = Math.round(center.lng * m) / m, lat = Math.round(center.lat * m) / m, bearing = this._map.getBearing(), pitch = this._map.getPitch();
            var hash = "";
            if (mapFeedback) {
              hash += "/" + lng + "/" + lat + "/" + zoom;
            } else {
              hash += zoom + "/" + lat + "/" + lng;
            }
            if (bearing || pitch) {
              hash += "/" + Math.round(bearing * 10) / 10;
            }
            if (pitch) {
              hash += "/" + Math.round(pitch);
            }
            if (this._hashName) {
              var hashName = this._hashName;
              var found = false;
              var parts = performance2.window.location.hash.slice(1).split("&").map(function(part) {
                var key = part.split("=")[0];
                if (key === hashName) {
                  found = true;
                  return key + "=" + hash;
                }
                return part;
              }).filter(function(a) {
                return a;
              });
              if (!found) {
                parts.push(hashName + "=" + hash);
              }
              return "#" + parts.join("&");
            }
            return "#" + hash;
          };
          Hash.prototype._getCurrentHash = function _getCurrentHash() {
            var this$1 = this;
            var hash = performance2.window.location.hash.replace("#", "");
            if (this._hashName) {
              var keyval;
              hash.split("&").map(function(part) {
                return part.split("=");
              }).forEach(function(part) {
                if (part[0] === this$1._hashName) {
                  keyval = part;
                }
              });
              return (keyval ? keyval[1] || "" : "").split("/");
            }
            return hash.split("/");
          };
          Hash.prototype._onHashChange = function _onHashChange() {
            var loc = this._getCurrentHash();
            if (loc.length >= 3 && !loc.some(function(v) {
              return isNaN(v);
            })) {
              var bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing();
              this._map.jumpTo({
                center: [
                  +loc[2],
                  +loc[1]
                ],
                zoom: +loc[0],
                bearing,
                pitch: +(loc[4] || 0)
              });
              return true;
            }
            return false;
          };
          Hash.prototype._updateHashUnthrottled = function _updateHashUnthrottled() {
            var location2 = performance2.window.location.href.replace(/(#.+)?$/, this.getHashString());
            try {
              performance2.window.history.replaceState(performance2.window.history.state, null, location2);
            } catch (SecurityError) {
            }
          };
          var defaultInertiaOptions = {
            linearity: 0.3,
            easing: performance2.bezier(0, 0, 0.3, 1)
          };
          var defaultPanInertiaOptions = performance2.extend({
            deceleration: 2500,
            maxSpeed: 1400
          }, defaultInertiaOptions);
          var defaultZoomInertiaOptions = performance2.extend({
            deceleration: 20,
            maxSpeed: 1400
          }, defaultInertiaOptions);
          var defaultBearingInertiaOptions = performance2.extend({
            deceleration: 1e3,
            maxSpeed: 360
          }, defaultInertiaOptions);
          var defaultPitchInertiaOptions = performance2.extend({
            deceleration: 1e3,
            maxSpeed: 90
          }, defaultInertiaOptions);
          var HandlerInertia = function HandlerInertia2(map) {
            this._map = map;
            this.clear();
          };
          HandlerInertia.prototype.clear = function clear() {
            this._inertiaBuffer = [];
          };
          HandlerInertia.prototype.record = function record(settings) {
            this._drainInertiaBuffer();
            this._inertiaBuffer.push({
              time: performance2.browser.now(),
              settings
            });
          };
          HandlerInertia.prototype._drainInertiaBuffer = function _drainInertiaBuffer() {
            var inertia = this._inertiaBuffer, now = performance2.browser.now(), cutoff = 160;
            while (inertia.length > 0 && now - inertia[0].time > cutoff) {
              inertia.shift();
            }
          };
          HandlerInertia.prototype._onMoveEnd = function _onMoveEnd(panInertiaOptions) {
            this._drainInertiaBuffer();
            if (this._inertiaBuffer.length < 2) {
              return;
            }
            var deltas = {
              zoom: 0,
              bearing: 0,
              pitch: 0,
              pan: new performance2.Point(0, 0),
              pinchAround: void 0,
              around: void 0
            };
            for (var i = 0, list = this._inertiaBuffer; i < list.length; i += 1) {
              var ref = list[i];
              var settings = ref.settings;
              deltas.zoom += settings.zoomDelta || 0;
              deltas.bearing += settings.bearingDelta || 0;
              deltas.pitch += settings.pitchDelta || 0;
              if (settings.panDelta) {
                deltas.pan._add(settings.panDelta);
              }
              if (settings.around) {
                deltas.around = settings.around;
              }
              if (settings.pinchAround) {
                deltas.pinchAround = settings.pinchAround;
              }
            }
            var lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1];
            var duration = lastEntry.time - this._inertiaBuffer[0].time;
            var easeOptions = {};
            if (deltas.pan.mag()) {
              var result = calculateEasing(deltas.pan.mag(), duration, performance2.extend({}, defaultPanInertiaOptions, panInertiaOptions || {}));
              easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag());
              easeOptions.center = this._map.transform.center;
              extendDuration(easeOptions, result);
            }
            if (deltas.zoom) {
              var result$1 = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions);
              easeOptions.zoom = this._map.transform.zoom + result$1.amount;
              extendDuration(easeOptions, result$1);
            }
            if (deltas.bearing) {
              var result$2 = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions);
              easeOptions.bearing = this._map.transform.bearing + performance2.clamp(result$2.amount, -179, 179);
              extendDuration(easeOptions, result$2);
            }
            if (deltas.pitch) {
              var result$3 = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions);
              easeOptions.pitch = this._map.transform.pitch + result$3.amount;
              extendDuration(easeOptions, result$3);
            }
            if (easeOptions.zoom || easeOptions.bearing) {
              var last = deltas.pinchAround === void 0 ? deltas.around : deltas.pinchAround;
              easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter();
            }
            this.clear();
            return performance2.extend(easeOptions, { noMoveStart: true });
          };
          function extendDuration(easeOptions, result) {
            if (!easeOptions.duration || easeOptions.duration < result.duration) {
              easeOptions.duration = result.duration;
              easeOptions.easing = result.easing;
            }
          }
          function calculateEasing(amount, inertiaDuration, inertiaOptions) {
            var maxSpeed = inertiaOptions.maxSpeed;
            var linearity = inertiaOptions.linearity;
            var deceleration = inertiaOptions.deceleration;
            var speed = performance2.clamp(amount * linearity / (inertiaDuration / 1e3), -maxSpeed, maxSpeed);
            var duration = Math.abs(speed) / (deceleration * linearity);
            return {
              easing: inertiaOptions.easing,
              duration: duration * 1e3,
              amount: speed * (duration / 2)
            };
          }
          var MapMouseEvent = function(Event) {
            function MapMouseEvent2(type, map, originalEvent, data) {
              if (data === void 0)
                data = {};
              var point = DOM.mousePos(map.getCanvasContainer(), originalEvent);
              var lngLat = map.unproject(point);
              Event.call(this, type, performance2.extend({
                point,
                lngLat,
                originalEvent
              }, data));
              this._defaultPrevented = false;
              this.target = map;
            }
            if (Event)
              MapMouseEvent2.__proto__ = Event;
            MapMouseEvent2.prototype = Object.create(Event && Event.prototype);
            MapMouseEvent2.prototype.constructor = MapMouseEvent2;
            var prototypeAccessors2 = { defaultPrevented: { configurable: true } };
            MapMouseEvent2.prototype.preventDefault = function preventDefault() {
              this._defaultPrevented = true;
            };
            prototypeAccessors2.defaultPrevented.get = function() {
              return this._defaultPrevented;
            };
            Object.defineProperties(MapMouseEvent2.prototype, prototypeAccessors2);
            return MapMouseEvent2;
          }(performance2.Event);
          var MapTouchEvent = function(Event) {
            function MapTouchEvent2(type, map, originalEvent) {
              var touches = type === "touchend" ? originalEvent.changedTouches : originalEvent.touches;
              var points = DOM.touchPos(map.getCanvasContainer(), touches);
              var lngLats = points.map(function(t) {
                return map.unproject(t);
              });
              var point = points.reduce(function(prev, curr, i, arr) {
                return prev.add(curr.div(arr.length));
              }, new performance2.Point(0, 0));
              var lngLat = map.unproject(point);
              Event.call(this, type, {
                points,
                point,
                lngLats,
                lngLat,
                originalEvent
              });
              this._defaultPrevented = false;
            }
            if (Event)
              MapTouchEvent2.__proto__ = Event;
            MapTouchEvent2.prototype = Object.create(Event && Event.prototype);
            MapTouchEvent2.prototype.constructor = MapTouchEvent2;
            var prototypeAccessors$1 = { defaultPrevented: { configurable: true } };
            MapTouchEvent2.prototype.preventDefault = function preventDefault() {
              this._defaultPrevented = true;
            };
            prototypeAccessors$1.defaultPrevented.get = function() {
              return this._defaultPrevented;
            };
            Object.defineProperties(MapTouchEvent2.prototype, prototypeAccessors$1);
            return MapTouchEvent2;
          }(performance2.Event);
          var MapWheelEvent = function(Event) {
            function MapWheelEvent2(type, map, originalEvent) {
              Event.call(this, type, { originalEvent });
              this._defaultPrevented = false;
            }
            if (Event)
              MapWheelEvent2.__proto__ = Event;
            MapWheelEvent2.prototype = Object.create(Event && Event.prototype);
            MapWheelEvent2.prototype.constructor = MapWheelEvent2;
            var prototypeAccessors$2 = { defaultPrevented: { configurable: true } };
            MapWheelEvent2.prototype.preventDefault = function preventDefault() {
              this._defaultPrevented = true;
            };
            prototypeAccessors$2.defaultPrevented.get = function() {
              return this._defaultPrevented;
            };
            Object.defineProperties(MapWheelEvent2.prototype, prototypeAccessors$2);
            return MapWheelEvent2;
          }(performance2.Event);
          var MapEventHandler = function MapEventHandler2(map, options) {
            this._map = map;
            this._clickTolerance = options.clickTolerance;
          };
          MapEventHandler.prototype.reset = function reset() {
            delete this._mousedownPos;
          };
          MapEventHandler.prototype.wheel = function wheel(e) {
            return this._firePreventable(new MapWheelEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.mousedown = function mousedown(e, point) {
            this._mousedownPos = point;
            return this._firePreventable(new MapMouseEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.mouseup = function mouseup(e) {
            this._map.fire(new MapMouseEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.click = function click(e, point) {
            if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) {
              return;
            }
            this._map.fire(new MapMouseEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.dblclick = function dblclick(e) {
            return this._firePreventable(new MapMouseEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.mouseover = function mouseover(e) {
            this._map.fire(new MapMouseEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.mouseout = function mouseout(e) {
            this._map.fire(new MapMouseEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.touchstart = function touchstart(e) {
            return this._firePreventable(new MapTouchEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.touchmove = function touchmove(e) {
            this._map.fire(new MapTouchEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.touchend = function touchend(e) {
            this._map.fire(new MapTouchEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype.touchcancel = function touchcancel(e) {
            this._map.fire(new MapTouchEvent(e.type, this._map, e));
          };
          MapEventHandler.prototype._firePreventable = function _firePreventable(mapEvent) {
            this._map.fire(mapEvent);
            if (mapEvent.defaultPrevented) {
              return {};
            }
          };
          MapEventHandler.prototype.isEnabled = function isEnabled() {
            return true;
          };
          MapEventHandler.prototype.isActive = function isActive() {
            return false;
          };
          MapEventHandler.prototype.enable = function enable() {
          };
          MapEventHandler.prototype.disable = function disable() {
          };
          var BlockableMapEventHandler = function BlockableMapEventHandler2(map) {
            this._map = map;
          };
          BlockableMapEventHandler.prototype.reset = function reset() {
            this._delayContextMenu = false;
            delete this._contextMenuEvent;
          };
          BlockableMapEventHandler.prototype.mousemove = function mousemove(e) {
            this._map.fire(new MapMouseEvent(e.type, this._map, e));
          };
          BlockableMapEventHandler.prototype.mousedown = function mousedown() {
            this._delayContextMenu = true;
          };
          BlockableMapEventHandler.prototype.mouseup = function mouseup() {
            this._delayContextMenu = false;
            if (this._contextMenuEvent) {
              this._map.fire(new MapMouseEvent("contextmenu", this._map, this._contextMenuEvent));
              delete this._contextMenuEvent;
            }
          };
          BlockableMapEventHandler.prototype.contextmenu = function contextmenu(e) {
            if (this._delayContextMenu) {
              this._contextMenuEvent = e;
            } else {
              this._map.fire(new MapMouseEvent(e.type, this._map, e));
            }
            if (this._map.listens("contextmenu")) {
              e.preventDefault();
            }
          };
          BlockableMapEventHandler.prototype.isEnabled = function isEnabled() {
            return true;
          };
          BlockableMapEventHandler.prototype.isActive = function isActive() {
            return false;
          };
          BlockableMapEventHandler.prototype.enable = function enable() {
          };
          BlockableMapEventHandler.prototype.disable = function disable() {
          };
          var BoxZoomHandler = function BoxZoomHandler2(map, options) {
            this._map = map;
            this._el = map.getCanvasContainer();
            this._container = map.getContainer();
            this._clickTolerance = options.clickTolerance || 1;
          };
          BoxZoomHandler.prototype.isEnabled = function isEnabled() {
            return !!this._enabled;
          };
          BoxZoomHandler.prototype.isActive = function isActive() {
            return !!this._active;
          };
          BoxZoomHandler.prototype.enable = function enable() {
            if (this.isEnabled()) {
              return;
            }
            this._enabled = true;
          };
          BoxZoomHandler.prototype.disable = function disable() {
            if (!this.isEnabled()) {
              return;
            }
            this._enabled = false;
          };
          BoxZoomHandler.prototype.mousedown = function mousedown(e, point) {
            if (!this.isEnabled()) {
              return;
            }
            if (!(e.shiftKey && e.button === 0)) {
              return;
            }
            DOM.disableDrag();
            this._startPos = this._lastPos = point;
            this._active = true;
          };
          BoxZoomHandler.prototype.mousemoveWindow = function mousemoveWindow(e, point) {
            if (!this._active) {
              return;
            }
            var pos = point;
            if (this._lastPos.equals(pos) || !this._box && pos.dist(this._startPos) < this._clickTolerance) {
              return;
            }
            var p0 = this._startPos;
            this._lastPos = pos;
            if (!this._box) {
              this._box = DOM.create("div", "mapboxgl-boxzoom", this._container);
              this._container.classList.add("mapboxgl-crosshair");
              this._fireEvent("boxzoomstart", e);
            }
            var minX = Math.min(p0.x, pos.x), maxX = Math.max(p0.x, pos.x), minY = Math.min(p0.y, pos.y), maxY = Math.max(p0.y, pos.y);
            DOM.setTransform(this._box, "translate(" + minX + "px," + minY + "px)");
            this._box.style.width = maxX - minX + "px";
            this._box.style.height = maxY - minY + "px";
          };
          BoxZoomHandler.prototype.mouseupWindow = function mouseupWindow(e, point) {
            var this$1 = this;
            if (!this._active) {
              return;
            }
            if (e.button !== 0) {
              return;
            }
            var p0 = this._startPos, p1 = point;
            this.reset();
            DOM.suppressClick();
            if (p0.x === p1.x && p0.y === p1.y) {
              this._fireEvent("boxzoomcancel", e);
            } else {
              this._map.fire(new performance2.Event("boxzoomend", { originalEvent: e }));
              return {
                cameraAnimation: function(map) {
                  return map.fitScreenCoordinates(p0, p1, this$1._map.getBearing(), { linear: true });
                }
              };
            }
          };
          BoxZoomHandler.prototype.keydown = function keydown(e) {
            if (!this._active) {
              return;
            }
            if (e.keyCode === 27) {
              this.reset();
              this._fireEvent("boxzoomcancel", e);
            }
          };
          BoxZoomHandler.prototype.reset = function reset() {
            this._active = false;
            this._container.classList.remove("mapboxgl-crosshair");
            if (this._box) {
              DOM.remove(this._box);
              this._box = null;
            }
            DOM.enableDrag();
            delete this._startPos;
            delete this._lastPos;
          };
          BoxZoomHandler.prototype._fireEvent = function _fireEvent(type, e) {
            return this._map.fire(new performance2.Event(type, { originalEvent: e }));
          };
          function indexTouches(touches, points) {
            var obj = {};
            for (var i = 0; i < touches.length; i++) {
              obj[touches[i].identifier] = points[i];
            }
            return obj;
          }
          function getCentroid(points) {
            var sum = new performance2.Point(0, 0);
            for (var i = 0, list = points; i < list.length; i += 1) {
              var point = list[i];
              sum._add(point);
            }
            return sum.div(points.length);
          }
          var MAX_TAP_INTERVAL = 500;
          var MAX_TOUCH_TIME = 500;
          var MAX_DIST = 30;
          var SingleTapRecognizer = function SingleTapRecognizer2(options) {
            this.reset();
            this.numTouches = options.numTouches;
          };
          SingleTapRecognizer.prototype.reset = function reset() {
            delete this.centroid;
            delete this.startTime;
            delete this.touches;
            this.aborted = false;
          };
          SingleTapRecognizer.prototype.touchstart = function touchstart(e, points, mapTouches) {
            if (this.centroid || mapTouches.length > this.numTouches) {
              this.aborted = true;
            }
            if (this.aborted) {
              return;
            }
            if (this.startTime === void 0) {
              this.startTime = e.timeStamp;
            }
            if (mapTouches.length === this.numTouches) {
              this.centroid = getCentroid(points);
              this.touches = indexTouches(mapTouches, points);
            }
          };
          SingleTapRecognizer.prototype.touchmove = function touchmove(e, points, mapTouches) {
            if (this.aborted || !this.centroid) {
              return;
            }
            var newTouches = indexTouches(mapTouches, points);
            for (var id in this.touches) {
              var prevPos = this.touches[id];
              var pos = newTouches[id];
              if (!pos || pos.dist(prevPos) > MAX_DIST) {
                this.aborted = true;
              }
            }
          };
          SingleTapRecognizer.prototype.touchend = function touchend(e, points, mapTouches) {
            if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) {
              this.aborted = true;
            }
            if (mapTouches.length === 0) {
              var centroid = !this.aborted && this.centroid;
              this.reset();
              if (centroid) {
                return centroid;
              }
            }
          };
          var TapRecognizer = function TapRecognizer2(options) {
            this.singleTap = new SingleTapRecognizer(options);
            this.numTaps = options.numTaps;
            this.reset();
          };
          TapRecognizer.prototype.reset = function reset() {
            this.lastTime = Infinity;
            delete this.lastTap;
            this.count = 0;
            this.singleTap.reset();
          };
          TapRecognizer.prototype.touchstart = function touchstart(e, points, mapTouches) {
            this.singleTap.touchstart(e, points, mapTouches);
          };
          TapRecognizer.prototype.touchmove = function touchmove(e, points, mapTouches) {
            this.singleTap.touchmove(e, points, mapTouches);
          };
          TapRecognizer.prototype.touchend = function touchend(e, points, mapTouches) {
            var tap = this.singleTap.touchend(e, points, mapTouches);
            if (tap) {
              var soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL;
              var closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST;
              if (!soonEnough || !closeEnough) {
                this.reset();
              }
              this.count++;
              this.lastTime = e.timeStamp;
              this.lastTap = tap;
              if (this.count === this.numTaps) {
                this.reset();
                return tap;
              }
            }
          };
          var TapZoomHandler = function TapZoomHandler2() {
            this._zoomIn = new TapRecognizer({
              numTouches: 1,
              numTaps: 2
            });
            this._zoomOut = new TapRecognizer({
              numTouches: 2,
              numTaps: 1
            });
            this.reset();
          };
          TapZoomHandler.prototype.reset = function reset() {
            this._active = false;
            this._zoomIn.reset();
            this._zoomOut.reset();
          };
          TapZoomHandler.prototype.touchstart = function touchstart(e, points, mapTouches) {
            this._zoomIn.touchstart(e, points, mapTouches);
            this._zoomOut.touchstart(e, points, mapTouches);
          };
          TapZoomHandler.prototype.touchmove = function touchmove(e, points, mapTouches) {
            this._zoomIn.touchmove(e, points, mapTouches);
            this._zoomOut.touchmove(e, points, mapTouches);
          };
          TapZoomHandler.prototype.touchend = function touchend(e, points, mapTouches) {
            var this$1 = this;
            var zoomInPoint = this._zoomIn.touchend(e, points, mapTouches);
            var zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches);
            if (zoomInPoint) {
              this._active = true;
              e.preventDefault();
              setTimeout(function() {
                return this$1.reset();
              }, 0);
              return {
                cameraAnimation: function(map) {
                  return map.easeTo({
                    duration: 300,
                    zoom: map.getZoom() + 1,
                    around: map.unproject(zoomInPoint)
                  }, { originalEvent: e });
                }
              };
            } else if (zoomOutPoint) {
              this._active = true;
              e.preventDefault();
              setTimeout(function() {
                return this$1.reset();
              }, 0);
              return {
                cameraAnimation: function(map) {
                  return map.easeTo({
                    duration: 300,
                    zoom: map.getZoom() - 1,
                    around: map.unproject(zoomOutPoint)
                  }, { originalEvent: e });
                }
              };
            }
          };
          TapZoomHandler.prototype.touchcancel = function touchcancel() {
            this.reset();
          };
          TapZoomHandler.prototype.enable = function enable() {
            this._enabled = true;
          };
          TapZoomHandler.prototype.disable = function disable() {
            this._enabled = false;
            this.reset();
          };
          TapZoomHandler.prototype.isEnabled = function isEnabled() {
            return this._enabled;
          };
          TapZoomHandler.prototype.isActive = function isActive() {
            return this._active;
          };
          var LEFT_BUTTON = 0;
          var RIGHT_BUTTON = 2;
          var BUTTONS_FLAGS = {};
          BUTTONS_FLAGS[LEFT_BUTTON] = 1;
          BUTTONS_FLAGS[RIGHT_BUTTON] = 2;
          function buttonStillPressed(e, button) {
            var flag = BUTTONS_FLAGS[button];
            return e.buttons === void 0 || (e.buttons & flag) !== flag;
          }
          var MouseHandler = function MouseHandler2(options) {
            this.reset();
            this._clickTolerance = options.clickTolerance || 1;
          };
          MouseHandler.prototype.reset = function reset() {
            this._active = false;
            this._moved = false;
            delete this._lastPoint;
            delete this._eventButton;
          };
          MouseHandler.prototype._correctButton = function _correctButton(e, button) {
            return false;
          };
          MouseHandler.prototype._move = function _move(lastPoint, point) {
            return {};
          };
          MouseHandler.prototype.mousedown = function mousedown(e, point) {
            if (this._lastPoint) {
              return;
            }
            var eventButton = DOM.mouseButton(e);
            if (!this._correctButton(e, eventButton)) {
              return;
            }
            this._lastPoint = point;
            this._eventButton = eventButton;
          };
          MouseHandler.prototype.mousemoveWindow = function mousemoveWindow(e, point) {
            var lastPoint = this._lastPoint;
            if (!lastPoint) {
              return;
            }
            e.preventDefault();
            if (buttonStillPressed(e, this._eventButton)) {
              this.reset();
              return;
            }
            if (!this._moved && point.dist(lastPoint) < this._clickTolerance) {
              return;
            }
            this._moved = true;
            this._lastPoint = point;
            return this._move(lastPoint, point);
          };
          MouseHandler.prototype.mouseupWindow = function mouseupWindow(e) {
            if (!this._lastPoint) {
              return;
            }
            var eventButton = DOM.mouseButton(e);
            if (eventButton !== this._eventButton) {
              return;
            }
            if (this._moved) {
              DOM.suppressClick();
            }
            this.reset();
          };
          MouseHandler.prototype.enable = function enable() {
            this._enabled = true;
          };
          MouseHandler.prototype.disable = function disable() {
            this._enabled = false;
            this.reset();
          };
          MouseHandler.prototype.isEnabled = function isEnabled() {
            return this._enabled;
          };
          MouseHandler.prototype.isActive = function isActive() {
            return this._active;
          };
          var MousePanHandler = function(MouseHandler2) {
            function MousePanHandler2() {
              MouseHandler2.apply(this, arguments);
            }
            if (MouseHandler2)
              MousePanHandler2.__proto__ = MouseHandler2;
            MousePanHandler2.prototype = Object.create(MouseHandler2 && MouseHandler2.prototype);
            MousePanHandler2.prototype.constructor = MousePanHandler2;
            MousePanHandler2.prototype.mousedown = function mousedown(e, point) {
              MouseHandler2.prototype.mousedown.call(this, e, point);
              if (this._lastPoint) {
                this._active = true;
              }
            };
            MousePanHandler2.prototype._correctButton = function _correctButton(e, button) {
              return button === LEFT_BUTTON && !e.ctrlKey;
            };
            MousePanHandler2.prototype._move = function _move(lastPoint, point) {
              return {
                around: point,
                panDelta: point.sub(lastPoint)
              };
            };
            return MousePanHandler2;
          }(MouseHandler);
          var MouseRotateHandler = function(MouseHandler2) {
            function MouseRotateHandler2() {
              MouseHandler2.apply(this, arguments);
            }
            if (MouseHandler2)
              MouseRotateHandler2.__proto__ = MouseHandler2;
            MouseRotateHandler2.prototype = Object.create(MouseHandler2 && MouseHandler2.prototype);
            MouseRotateHandler2.prototype.constructor = MouseRotateHandler2;
            MouseRotateHandler2.prototype._correctButton = function _correctButton(e, button) {
              return button === LEFT_BUTTON && e.ctrlKey || button === RIGHT_BUTTON;
            };
            MouseRotateHandler2.prototype._move = function _move(lastPoint, point) {
              var degreesPerPixelMoved = 0.8;
              var bearingDelta = (point.x - lastPoint.x) * degreesPerPixelMoved;
              if (bearingDelta) {
                this._active = true;
                return { bearingDelta };
              }
            };
            MouseRotateHandler2.prototype.contextmenu = function contextmenu(e) {
              e.preventDefault();
            };
            return MouseRotateHandler2;
          }(MouseHandler);
          var MousePitchHandler = function(MouseHandler2) {
            function MousePitchHandler2() {
              MouseHandler2.apply(this, arguments);
            }
            if (MouseHandler2)
              MousePitchHandler2.__proto__ = MouseHandler2;
            MousePitchHandler2.prototype = Object.create(MouseHandler2 && MouseHandler2.prototype);
            MousePitchHandler2.prototype.constructor = MousePitchHandler2;
            MousePitchHandler2.prototype._correctButton = function _correctButton(e, button) {
              return button === LEFT_BUTTON && e.ctrlKey || button === RIGHT_BUTTON;
            };
            MousePitchHandler2.prototype._move = function _move(lastPoint, point) {
              var degreesPerPixelMoved = -0.5;
              var pitchDelta = (point.y - lastPoint.y) * degreesPerPixelMoved;
              if (pitchDelta) {
                this._active = true;
                return { pitchDelta };
              }
            };
            MousePitchHandler2.prototype.contextmenu = function contextmenu(e) {
              e.preventDefault();
            };
            return MousePitchHandler2;
          }(MouseHandler);
          var TouchPanHandler = function TouchPanHandler2(options) {
            this._minTouches = 1;
            this._clickTolerance = options.clickTolerance || 1;
            this.reset();
          };
          TouchPanHandler.prototype.reset = function reset() {
            this._active = false;
            this._touches = {};
            this._sum = new performance2.Point(0, 0);
          };
          TouchPanHandler.prototype.touchstart = function touchstart(e, points, mapTouches) {
            return this._calculateTransform(e, points, mapTouches);
          };
          TouchPanHandler.prototype.touchmove = function touchmove(e, points, mapTouches) {
            if (!this._active || mapTouches.length < this._minTouches) {
              return;
            }
            e.preventDefault();
            return this._calculateTransform(e, points, mapTouches);
          };
          TouchPanHandler.prototype.touchend = function touchend(e, points, mapTouches) {
            this._calculateTransform(e, points, mapTouches);
            if (this._active && mapTouches.length < this._minTouches) {
              this.reset();
            }
          };
          TouchPanHandler.prototype.touchcancel = function touchcancel() {
            this.reset();
          };
          TouchPanHandler.prototype._calculateTransform = function _calculateTransform(e, points, mapTouches) {
            if (mapTouches.length > 0) {
              this._active = true;
            }
            var touches = indexTouches(mapTouches, points);
            var touchPointSum = new performance2.Point(0, 0);
            var touchDeltaSum = new performance2.Point(0, 0);
            var touchDeltaCount = 0;
            for (var identifier in touches) {
              var point = touches[identifier];
              var prevPoint = this._touches[identifier];
              if (prevPoint) {
                touchPointSum._add(point);
                touchDeltaSum._add(point.sub(prevPoint));
                touchDeltaCount++;
                touches[identifier] = point;
              }
            }
            this._touches = touches;
            if (touchDeltaCount < this._minTouches || !touchDeltaSum.mag()) {
              return;
            }
            var panDelta = touchDeltaSum.div(touchDeltaCount);
            this._sum._add(panDelta);
            if (this._sum.mag() < this._clickTolerance) {
              return;
            }
            var around = touchPointSum.div(touchDeltaCount);
            return {
              around,
              panDelta
            };
          };
          TouchPanHandler.prototype.enable = function enable() {
            this._enabled = true;
          };
          TouchPanHandler.prototype.disable = function disable() {
            this._enabled = false;
            this.reset();
          };
          TouchPanHandler.prototype.isEnabled = function isEnabled() {
            return this._enabled;
          };
          TouchPanHandler.prototype.isActive = function isActive() {
            return this._active;
          };
          var TwoTouchHandler = function TwoTouchHandler2() {
            this.reset();
          };
          TwoTouchHandler.prototype.reset = function reset() {
            this._active = false;
            delete this._firstTwoTouches;
          };
          TwoTouchHandler.prototype._start = function _start(points) {
          };
          TwoTouchHandler.prototype._move = function _move(points, pinchAround, e) {
            return {};
          };
          TwoTouchHandler.prototype.touchstart = function touchstart(e, points, mapTouches) {
            if (this._firstTwoTouches || mapTouches.length < 2) {
              return;
            }
            this._firstTwoTouches = [
              mapTouches[0].identifier,
              mapTouches[1].identifier
            ];
            this._start([
              points[0],
              points[1]
            ]);
          };
          TwoTouchHandler.prototype.touchmove = function touchmove(e, points, mapTouches) {
            if (!this._firstTwoTouches) {
              return;
            }
            e.preventDefault();
            var ref = this._firstTwoTouches;
            var idA = ref[0];
            var idB = ref[1];
            var a = getTouchById(mapTouches, points, idA);
            var b = getTouchById(mapTouches, points, idB);
            if (!a || !b) {
              return;
            }
            var pinchAround = this._aroundCenter ? null : a.add(b).div(2);
            return this._move([
              a,
              b
            ], pinchAround, e);
          };
          TwoTouchHandler.prototype.touchend = function touchend(e, points, mapTouches) {
            if (!this._firstTwoTouches) {
              return;
            }
            var ref = this._firstTwoTouches;
            var idA = ref[0];
            var idB = ref[1];
            var a = getTouchById(mapTouches, points, idA);
            var b = getTouchById(mapTouches, points, idB);
            if (a && b) {
              return;
            }
            if (this._active) {
              DOM.suppressClick();
            }
            this.reset();
          };
          TwoTouchHandler.prototype.touchcancel = function touchcancel() {
            this.reset();
          };
          TwoTouchHandler.prototype.enable = function enable(options) {
            this._enabled = true;
            this._aroundCenter = !!options && options.around === "center";
          };
          TwoTouchHandler.prototype.disable = function disable() {
            this._enabled = false;
            this.reset();
          };
          TwoTouchHandler.prototype.isEnabled = function isEnabled() {
            return this._enabled;
          };
          TwoTouchHandler.prototype.isActive = function isActive() {
            return this._active;
          };
          function getTouchById(mapTouches, points, identifier) {
            for (var i = 0; i < mapTouches.length; i++) {
              if (mapTouches[i].identifier === identifier) {
                return points[i];
              }
            }
          }
          var ZOOM_THRESHOLD = 0.1;
          function getZoomDelta(distance, lastDistance) {
            return Math.log(distance / lastDistance) / Math.LN2;
          }
          var TouchZoomHandler = function(TwoTouchHandler2) {
            function TouchZoomHandler2() {
              TwoTouchHandler2.apply(this, arguments);
            }
            if (TwoTouchHandler2)
              TouchZoomHandler2.__proto__ = TwoTouchHandler2;
            TouchZoomHandler2.prototype = Object.create(TwoTouchHandler2 && TwoTouchHandler2.prototype);
            TouchZoomHandler2.prototype.constructor = TouchZoomHandler2;
            TouchZoomHandler2.prototype.reset = function reset() {
              TwoTouchHandler2.prototype.reset.call(this);
              delete this._distance;
              delete this._startDistance;
            };
            TouchZoomHandler2.prototype._start = function _start(points) {
              this._startDistance = this._distance = points[0].dist(points[1]);
            };
            TouchZoomHandler2.prototype._move = function _move(points, pinchAround) {
              var lastDistance = this._distance;
              this._distance = points[0].dist(points[1]);
              if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD) {
                return;
              }
              this._active = true;
              return {
                zoomDelta: getZoomDelta(this._distance, lastDistance),
                pinchAround
              };
            };
            return TouchZoomHandler2;
          }(TwoTouchHandler);
          var ROTATION_THRESHOLD = 25;
          function getBearingDelta(a, b) {
            return a.angleWith(b) * 180 / Math.PI;
          }
          var TouchRotateHandler = function(TwoTouchHandler2) {
            function TouchRotateHandler2() {
              TwoTouchHandler2.apply(this, arguments);
            }
            if (TwoTouchHandler2)
              TouchRotateHandler2.__proto__ = TwoTouchHandler2;
            TouchRotateHandler2.prototype = Object.create(TwoTouchHandler2 && TwoTouchHandler2.prototype);
            TouchRotateHandler2.prototype.constructor = TouchRotateHandler2;
            TouchRotateHandler2.prototype.reset = function reset() {
              TwoTouchHandler2.prototype.reset.call(this);
              delete this._minDiameter;
              delete this._startVector;
              delete this._vector;
            };
            TouchRotateHandler2.prototype._start = function _start(points) {
              this._startVector = this._vector = points[0].sub(points[1]);
              this._minDiameter = points[0].dist(points[1]);
            };
            TouchRotateHandler2.prototype._move = function _move(points, pinchAround) {
              var lastVector = this._vector;
              this._vector = points[0].sub(points[1]);
              if (!this._active && this._isBelowThreshold(this._vector)) {
                return;
              }
              this._active = true;
              return {
                bearingDelta: getBearingDelta(this._vector, lastVector),
                pinchAround
              };
            };
            TouchRotateHandler2.prototype._isBelowThreshold = function _isBelowThreshold(vector) {
              this._minDiameter = Math.min(this._minDiameter, vector.mag());
              var circumference = Math.PI * this._minDiameter;
              var threshold = ROTATION_THRESHOLD / circumference * 360;
              var bearingDeltaSinceStart = getBearingDelta(vector, this._startVector);
              return Math.abs(bearingDeltaSinceStart) < threshold;
            };
            return TouchRotateHandler2;
          }(TwoTouchHandler);
          function isVertical(vector) {
            return Math.abs(vector.y) > Math.abs(vector.x);
          }
          var ALLOWED_SINGLE_TOUCH_TIME = 100;
          var TouchPitchHandler = function(TwoTouchHandler2) {
            function TouchPitchHandler2() {
              TwoTouchHandler2.apply(this, arguments);
            }
            if (TwoTouchHandler2)
              TouchPitchHandler2.__proto__ = TwoTouchHandler2;
            TouchPitchHandler2.prototype = Object.create(TwoTouchHandler2 && TwoTouchHandler2.prototype);
            TouchPitchHandler2.prototype.constructor = TouchPitchHandler2;
            TouchPitchHandler2.prototype.reset = function reset() {
              TwoTouchHandler2.prototype.reset.call(this);
              this._valid = void 0;
              delete this._firstMove;
              delete this._lastPoints;
            };
            TouchPitchHandler2.prototype._start = function _start(points) {
              this._lastPoints = points;
              if (isVertical(points[0].sub(points[1]))) {
                this._valid = false;
              }
            };
            TouchPitchHandler2.prototype._move = function _move(points, center, e) {
              var vectorA = points[0].sub(this._lastPoints[0]);
              var vectorB = points[1].sub(this._lastPoints[1]);
              this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp);
              if (!this._valid) {
                return;
              }
              this._lastPoints = points;
              this._active = true;
              var yDeltaAverage = (vectorA.y + vectorB.y) / 2;
              var degreesPerPixelMoved = -0.5;
              return { pitchDelta: yDeltaAverage * degreesPerPixelMoved };
            };
            TouchPitchHandler2.prototype.gestureBeginsVertically = function gestureBeginsVertically(vectorA, vectorB, timeStamp) {
              if (this._valid !== void 0) {
                return this._valid;
              }
              var threshold = 2;
              var movedA = vectorA.mag() >= threshold;
              var movedB = vectorB.mag() >= threshold;
              if (!movedA && !movedB) {
                return;
              }
              if (!movedA || !movedB) {
                if (this._firstMove === void 0) {
                  this._firstMove = timeStamp;
                }
                if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) {
                  return void 0;
                } else {
                  return false;
                }
              }
              var isSameDirection = vectorA.y > 0 === vectorB.y > 0;
              return isVertical(vectorA) && isVertical(vectorB) && isSameDirection;
            };
            return TouchPitchHandler2;
          }(TwoTouchHandler);
          var defaultOptions = {
            panStep: 100,
            bearingStep: 15,
            pitchStep: 10
          };
          var KeyboardHandler = function KeyboardHandler2() {
            var stepOptions = defaultOptions;
            this._panStep = stepOptions.panStep;
            this._bearingStep = stepOptions.bearingStep;
            this._pitchStep = stepOptions.pitchStep;
            this._rotationDisabled = false;
          };
          KeyboardHandler.prototype.reset = function reset() {
            this._active = false;
          };
          KeyboardHandler.prototype.keydown = function keydown(e) {
            var this$1 = this;
            if (e.altKey || e.ctrlKey || e.metaKey) {
              return;
            }
            var zoomDir = 0;
            var bearingDir = 0;
            var pitchDir = 0;
            var xDir = 0;
            var yDir = 0;
            switch (e.keyCode) {
              case 61:
              case 107:
              case 171:
              case 187:
                zoomDir = 1;
                break;
              case 189:
              case 109:
              case 173:
                zoomDir = -1;
                break;
              case 37:
                if (e.shiftKey) {
                  bearingDir = -1;
                } else {
                  e.preventDefault();
                  xDir = -1;
                }
                break;
              case 39:
                if (e.shiftKey) {
                  bearingDir = 1;
                } else {
                  e.preventDefault();
                  xDir = 1;
                }
                break;
              case 38:
                if (e.shiftKey) {
                  pitchDir = 1;
                } else {
                  e.preventDefault();
                  yDir = -1;
                }
                break;
              case 40:
                if (e.shiftKey) {
                  pitchDir = -1;
                } else {
                  e.preventDefault();
                  yDir = 1;
                }
                break;
              default:
                return;
            }
            if (this._rotationDisabled) {
              bearingDir = 0;
              pitchDir = 0;
            }
            return {
              cameraAnimation: function(map) {
                var zoom = map.getZoom();
                map.easeTo({
                  duration: 300,
                  easeId: "keyboardHandler",
                  easing: easeOut,
                  zoom: zoomDir ? Math.round(zoom) + zoomDir * (e.shiftKey ? 2 : 1) : zoom,
                  bearing: map.getBearing() + bearingDir * this$1._bearingStep,
                  pitch: map.getPitch() + pitchDir * this$1._pitchStep,
                  offset: [
                    -xDir * this$1._panStep,
                    -yDir * this$1._panStep
                  ],
                  center: map.getCenter()
                }, { originalEvent: e });
              }
            };
          };
          KeyboardHandler.prototype.enable = function enable() {
            this._enabled = true;
          };
          KeyboardHandler.prototype.disable = function disable() {
            this._enabled = false;
            this.reset();
          };
          KeyboardHandler.prototype.isEnabled = function isEnabled() {
            return this._enabled;
          };
          KeyboardHandler.prototype.isActive = function isActive() {
            return this._active;
          };
          KeyboardHandler.prototype.disableRotation = function disableRotation() {
            this._rotationDisabled = true;
          };
          KeyboardHandler.prototype.enableRotation = function enableRotation() {
            this._rotationDisabled = false;
          };
          function easeOut(t) {
            return t * (2 - t);
          }
          var wheelZoomDelta = 4.000244140625;
          var defaultZoomRate = 1 / 100;
          var wheelZoomRate = 1 / 450;
          var maxScalePerFrame = 2;
          var ScrollZoomHandler = function ScrollZoomHandler2(map, handler) {
            this._map = map;
            this._el = map.getCanvasContainer();
            this._handler = handler;
            this._delta = 0;
            this._defaultZoomRate = defaultZoomRate;
            this._wheelZoomRate = wheelZoomRate;
            performance2.bindAll(["_onTimeout"], this);
          };
          ScrollZoomHandler.prototype.setZoomRate = function setZoomRate(zoomRate) {
            this._defaultZoomRate = zoomRate;
          };
          ScrollZoomHandler.prototype.setWheelZoomRate = function setWheelZoomRate(wheelZoomRate2) {
            this._wheelZoomRate = wheelZoomRate2;
          };
          ScrollZoomHandler.prototype.isEnabled = function isEnabled() {
            return !!this._enabled;
          };
          ScrollZoomHandler.prototype.isActive = function isActive() {
            return !!this._active || this._finishTimeout !== void 0;
          };
          ScrollZoomHandler.prototype.isZooming = function isZooming() {
            return !!this._zooming;
          };
          ScrollZoomHandler.prototype.enable = function enable(options) {
            if (this.isEnabled()) {
              return;
            }
            this._enabled = true;
            this._aroundCenter = options && options.around === "center";
          };
          ScrollZoomHandler.prototype.disable = function disable() {
            if (!this.isEnabled()) {
              return;
            }
            this._enabled = false;
          };
          ScrollZoomHandler.prototype.wheel = function wheel(e) {
            if (!this.isEnabled()) {
              return;
            }
            var value = e.deltaMode === performance2.window.WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY;
            var now = performance2.browser.now(), timeDelta = now - (this._lastWheelEventTime || 0);
            this._lastWheelEventTime = now;
            if (value !== 0 && value % wheelZoomDelta === 0) {
              this._type = "wheel";
            } else if (value !== 0 && Math.abs(value) < 4) {
              this._type = "trackpad";
            } else if (timeDelta > 400) {
              this._type = null;
              this._lastValue = value;
              this._timeout = setTimeout(this._onTimeout, 40, e);
            } else if (!this._type) {
              this._type = Math.abs(timeDelta * value) < 200 ? "trackpad" : "wheel";
              if (this._timeout) {
                clearTimeout(this._timeout);
                this._timeout = null;
                value += this._lastValue;
              }
            }
            if (e.shiftKey && value) {
              value = value / 4;
            }
            if (this._type) {
              this._lastWheelEvent = e;
              this._delta -= value;
              if (!this._active) {
                this._start(e);
              }
            }
            e.preventDefault();
          };
          ScrollZoomHandler.prototype._onTimeout = function _onTimeout(initialEvent) {
            this._type = "wheel";
            this._delta -= this._lastValue;
            if (!this._active) {
              this._start(initialEvent);
            }
          };
          ScrollZoomHandler.prototype._start = function _start(e) {
            if (!this._delta) {
              return;
            }
            if (this._frameId) {
              this._frameId = null;
            }
            this._active = true;
            if (!this.isZooming()) {
              this._zooming = true;
            }
            if (this._finishTimeout) {
              clearTimeout(this._finishTimeout);
              delete this._finishTimeout;
            }
            var pos = DOM.mousePos(this._el, e);
            this._around = performance2.LngLat.convert(this._aroundCenter ? this._map.getCenter() : this._map.unproject(pos));
            this._aroundPoint = this._map.transform.locationPoint(this._around);
            if (!this._frameId) {
              this._frameId = true;
              this._handler._triggerRenderFrame();
            }
          };
          ScrollZoomHandler.prototype.renderFrame = function renderFrame() {
            var this$1 = this;
            if (!this._frameId) {
              return;
            }
            this._frameId = null;
            if (!this.isActive()) {
              return;
            }
            var tr = this._map.transform;
            if (this._delta !== 0) {
              var zoomRate = this._type === "wheel" && Math.abs(this._delta) > wheelZoomDelta ? this._wheelZoomRate : this._defaultZoomRate;
              var scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate)));
              if (this._delta < 0 && scale !== 0) {
                scale = 1 / scale;
              }
              var fromScale = typeof this._targetZoom === "number" ? tr.zoomScale(this._targetZoom) : tr.scale;
              this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale)));
              if (this._type === "wheel") {
                this._startZoom = tr.zoom;
                this._easing = this._smoothOutEasing(200);
              }
              this._delta = 0;
            }
            var targetZoom = typeof this._targetZoom === "number" ? this._targetZoom : tr.zoom;
            var startZoom = this._startZoom;
            var easing = this._easing;
            var finished = false;
            var zoom;
            if (this._type === "wheel" && startZoom && easing) {
              var t = Math.min((performance2.browser.now() - this._lastWheelEventTime) / 200, 1);
              var k = easing(t);
              zoom = performance2.number(startZoom, targetZoom, k);
              if (t < 1) {
                if (!this._frameId) {
                  this._frameId = true;
                }
              } else {
                finished = true;
              }
            } else {
              zoom = targetZoom;
              finished = true;
            }
            this._active = true;
            if (finished) {
              this._active = false;
              this._finishTimeout = setTimeout(function() {
                this$1._zooming = false;
                this$1._handler._triggerRenderFrame();
                delete this$1._targetZoom;
                delete this$1._finishTimeout;
              }, 200);
            }
            return {
              noInertia: true,
              needsRenderFrame: !finished,
              zoomDelta: zoom - tr.zoom,
              around: this._aroundPoint,
              originalEvent: this._lastWheelEvent
            };
          };
          ScrollZoomHandler.prototype._smoothOutEasing = function _smoothOutEasing(duration) {
            var easing = performance2.ease;
            if (this._prevEase) {
              var ease = this._prevEase, t = (performance2.browser.now() - ease.start) / ease.duration, speed = ease.easing(t + 0.01) - ease.easing(t), x = 0.27 / Math.sqrt(speed * speed + 1e-4) * 0.01, y = Math.sqrt(0.27 * 0.27 - x * x);
              easing = performance2.bezier(x, y, 0.25, 1);
            }
            this._prevEase = {
              start: performance2.browser.now(),
              duration,
              easing
            };
            return easing;
          };
          ScrollZoomHandler.prototype.reset = function reset() {
            this._active = false;
          };
          var DoubleClickZoomHandler = function DoubleClickZoomHandler2(clickZoom, TapZoom) {
            this._clickZoom = clickZoom;
            this._tapZoom = TapZoom;
          };
          DoubleClickZoomHandler.prototype.enable = function enable() {
            this._clickZoom.enable();
            this._tapZoom.enable();
          };
          DoubleClickZoomHandler.prototype.disable = function disable() {
            this._clickZoom.disable();
            this._tapZoom.disable();
          };
          DoubleClickZoomHandler.prototype.isEnabled = function isEnabled() {
            return this._clickZoom.isEnabled() && this._tapZoom.isEnabled();
          };
          DoubleClickZoomHandler.prototype.isActive = function isActive() {
            return this._clickZoom.isActive() || this._tapZoom.isActive();
          };
          var ClickZoomHandler = function ClickZoomHandler2() {
            this.reset();
          };
          ClickZoomHandler.prototype.reset = function reset() {
            this._active = false;
          };
          ClickZoomHandler.prototype.dblclick = function dblclick(e, point) {
            e.preventDefault();
            return {
              cameraAnimation: function(map) {
                map.easeTo({
                  duration: 300,
                  zoom: map.getZoom() + (e.shiftKey ? -1 : 1),
                  around: map.unproject(point)
                }, { originalEvent: e });
              }
            };
          };
          ClickZoomHandler.prototype.enable = function enable() {
            this._enabled = true;
          };
          ClickZoomHandler.prototype.disable = function disable() {
            this._enabled = false;
            this.reset();
          };
          ClickZoomHandler.prototype.isEnabled = function isEnabled() {
            return this._enabled;
          };
          ClickZoomHandler.prototype.isActive = function isActive() {
            return this._active;
          };
          var TapDragZoomHandler = function TapDragZoomHandler2() {
            this._tap = new TapRecognizer({
              numTouches: 1,
              numTaps: 1
            });
            this.reset();
          };
          TapDragZoomHandler.prototype.reset = function reset() {
            this._active = false;
            delete this._swipePoint;
            delete this._swipeTouch;
            delete this._tapTime;
            this._tap.reset();
          };
          TapDragZoomHandler.prototype.touchstart = function touchstart(e, points, mapTouches) {
            if (this._swipePoint) {
              return;
            }
            if (this._tapTime && e.timeStamp - this._tapTime > MAX_TAP_INTERVAL) {
              this.reset();
            }
            if (!this._tapTime) {
              this._tap.touchstart(e, points, mapTouches);
            } else if (mapTouches.length > 0) {
              this._swipePoint = points[0];
              this._swipeTouch = mapTouches[0].identifier;
            }
          };
          TapDragZoomHandler.prototype.touchmove = function touchmove(e, points, mapTouches) {
            if (!this._tapTime) {
              this._tap.touchmove(e, points, mapTouches);
            } else if (this._swipePoint) {
              if (mapTouches[0].identifier !== this._swipeTouch) {
                return;
              }
              var newSwipePoint = points[0];
              var dist = newSwipePoint.y - this._swipePoint.y;
              this._swipePoint = newSwipePoint;
              e.preventDefault();
              this._active = true;
              return { zoomDelta: dist / 128 };
            }
          };
          TapDragZoomHandler.prototype.touchend = function touchend(e, points, mapTouches) {
            if (!this._tapTime) {
              var point = this._tap.touchend(e, points, mapTouches);
              if (point) {
                this._tapTime = e.timeStamp;
              }
            } else if (this._swipePoint) {
              if (mapTouches.length === 0) {
                this.reset();
              }
            }
          };
          TapDragZoomHandler.prototype.touchcancel = function touchcancel() {
            this.reset();
          };
          TapDragZoomHandler.prototype.enable = function enable() {
            this._enabled = true;
          };
          TapDragZoomHandler.prototype.disable = function disable() {
            this._enabled = false;
            this.reset();
          };
          TapDragZoomHandler.prototype.isEnabled = function isEnabled() {
            return this._enabled;
          };
          TapDragZoomHandler.prototype.isActive = function isActive() {
            return this._active;
          };
          var DragPanHandler = function DragPanHandler2(el, mousePan, touchPan) {
            this._el = el;
            this._mousePan = mousePan;
            this._touchPan = touchPan;
          };
          DragPanHandler.prototype.enable = function enable(options) {
            this._inertiaOptions = options || {};
            this._mousePan.enable();
            this._touchPan.enable();
            this._el.classList.add("mapboxgl-touch-drag-pan");
          };
          DragPanHandler.prototype.disable = function disable() {
            this._mousePan.disable();
            this._touchPan.disable();
            this._el.classList.remove("mapboxgl-touch-drag-pan");
          };
          DragPanHandler.prototype.isEnabled = function isEnabled() {
            return this._mousePan.isEnabled() && this._touchPan.isEnabled();
          };
          DragPanHandler.prototype.isActive = function isActive() {
            return this._mousePan.isActive() || this._touchPan.isActive();
          };
          var DragRotateHandler = function DragRotateHandler2(options, mouseRotate, mousePitch) {
            this._pitchWithRotate = options.pitchWithRotate;
            this._mouseRotate = mouseRotate;
            this._mousePitch = mousePitch;
          };
          DragRotateHandler.prototype.enable = function enable() {
            this._mouseRotate.enable();
            if (this._pitchWithRotate) {
              this._mousePitch.enable();
            }
          };
          DragRotateHandler.prototype.disable = function disable() {
            this._mouseRotate.disable();
            this._mousePitch.disable();
          };
          DragRotateHandler.prototype.isEnabled = function isEnabled() {
            return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled());
          };
          DragRotateHandler.prototype.isActive = function isActive() {
            return this._mouseRotate.isActive() || this._mousePitch.isActive();
          };
          var TouchZoomRotateHandler = function TouchZoomRotateHandler2(el, touchZoom, touchRotate, tapDragZoom) {
            this._el = el;
            this._touchZoom = touchZoom;
            this._touchRotate = touchRotate;
            this._tapDragZoom = tapDragZoom;
            this._rotationDisabled = false;
            this._enabled = true;
          };
          TouchZoomRotateHandler.prototype.enable = function enable(options) {
            this._touchZoom.enable(options);
            if (!this._rotationDisabled) {
              this._touchRotate.enable(options);
            }
            this._tapDragZoom.enable();
            this._el.classList.add("mapboxgl-touch-zoom-rotate");
          };
          TouchZoomRotateHandler.prototype.disable = function disable() {
            this._touchZoom.disable();
            this._touchRotate.disable();
            this._tapDragZoom.disable();
            this._el.classList.remove("mapboxgl-touch-zoom-rotate");
          };
          TouchZoomRotateHandler.prototype.isEnabled = function isEnabled() {
            return this._touchZoom.isEnabled() && (this._rotationDisabled || this._touchRotate.isEnabled()) && this._tapDragZoom.isEnabled();
          };
          TouchZoomRotateHandler.prototype.isActive = function isActive() {
            return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive();
          };
          TouchZoomRotateHandler.prototype.disableRotation = function disableRotation() {
            this._rotationDisabled = true;
            this._touchRotate.disable();
          };
          TouchZoomRotateHandler.prototype.enableRotation = function enableRotation() {
            this._rotationDisabled = false;
            if (this._touchZoom.isEnabled()) {
              this._touchRotate.enable();
            }
          };
          var isMoving = function(p) {
            return p.zoom || p.drag || p.pitch || p.rotate;
          };
          var RenderFrameEvent = function(Event) {
            function RenderFrameEvent2() {
              Event.apply(this, arguments);
            }
            if (Event)
              RenderFrameEvent2.__proto__ = Event;
            RenderFrameEvent2.prototype = Object.create(Event && Event.prototype);
            RenderFrameEvent2.prototype.constructor = RenderFrameEvent2;
            return RenderFrameEvent2;
          }(performance2.Event);
          function hasChange(result) {
            return result.panDelta && result.panDelta.mag() || result.zoomDelta || result.bearingDelta || result.pitchDelta;
          }
          var HandlerManager = function HandlerManager2(map, options) {
            this._map = map;
            this._el = this._map.getCanvasContainer();
            this._handlers = [];
            this._handlersById = {};
            this._changes = [];
            this._inertia = new HandlerInertia(map);
            this._bearingSnap = options.bearingSnap;
            this._previousActiveHandlers = {};
            this._eventsInProgress = {};
            this._addDefaultHandlers(options);
            performance2.bindAll([
              "handleEvent",
              "handleWindowEvent"
            ], this);
            var el = this._el;
            this._listeners = [
              [
                el,
                "touchstart",
                { passive: true }
              ],
              [
                el,
                "touchmove",
                { passive: false }
              ],
              [
                el,
                "touchend",
                void 0
              ],
              [
                el,
                "touchcancel",
                void 0
              ],
              [
                el,
                "mousedown",
                void 0
              ],
              [
                el,
                "mousemove",
                void 0
              ],
              [
                el,
                "mouseup",
                void 0
              ],
              [
                performance2.window.document,
                "mousemove",
                { capture: true }
              ],
              [
                performance2.window.document,
                "mouseup",
                void 0
              ],
              [
                el,
                "mouseover",
                void 0
              ],
              [
                el,
                "mouseout",
                void 0
              ],
              [
                el,
                "dblclick",
                void 0
              ],
              [
                el,
                "click",
                void 0
              ],
              [
                el,
                "keydown",
                { capture: false }
              ],
              [
                el,
                "keyup",
                void 0
              ],
              [
                el,
                "wheel",
                { passive: false }
              ],
              [
                el,
                "contextmenu",
                void 0
              ],
              [
                performance2.window,
                "blur",
                void 0
              ]
            ];
            for (var i = 0, list = this._listeners; i < list.length; i += 1) {
              var ref = list[i];
              var target = ref[0];
              var type = ref[1];
              var listenerOptions = ref[2];
              DOM.addEventListener(target, type, target === performance2.window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions);
            }
          };
          HandlerManager.prototype.destroy = function destroy() {
            for (var i = 0, list = this._listeners; i < list.length; i += 1) {
              var ref = list[i];
              var target = ref[0];
              var type = ref[1];
              var listenerOptions = ref[2];
              DOM.removeEventListener(target, type, target === performance2.window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions);
            }
          };
          HandlerManager.prototype._addDefaultHandlers = function _addDefaultHandlers(options) {
            var map = this._map;
            var el = map.getCanvasContainer();
            this._add("mapEvent", new MapEventHandler(map, options));
            var boxZoom = map.boxZoom = new BoxZoomHandler(map, options);
            this._add("boxZoom", boxZoom);
            var tapZoom = new TapZoomHandler();
            var clickZoom = new ClickZoomHandler();
            map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);
            this._add("tapZoom", tapZoom);
            this._add("clickZoom", clickZoom);
            var tapDragZoom = new TapDragZoomHandler();
            this._add("tapDragZoom", tapDragZoom);
            var touchPitch = map.touchPitch = new TouchPitchHandler();
            this._add("touchPitch", touchPitch);
            var mouseRotate = new MouseRotateHandler(options);
            var mousePitch = new MousePitchHandler(options);
            map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch);
            this._add("mouseRotate", mouseRotate, ["mousePitch"]);
            this._add("mousePitch", mousePitch, ["mouseRotate"]);
            var mousePan = new MousePanHandler(options);
            var touchPan = new TouchPanHandler(options);
            map.dragPan = new DragPanHandler(el, mousePan, touchPan);
            this._add("mousePan", mousePan);
            this._add("touchPan", touchPan, [
              "touchZoom",
              "touchRotate"
            ]);
            var touchRotate = new TouchRotateHandler();
            var touchZoom = new TouchZoomHandler();
            map.touchZoomRotate = new TouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);
            this._add("touchRotate", touchRotate, [
              "touchPan",
              "touchZoom"
            ]);
            this._add("touchZoom", touchZoom, [
              "touchPan",
              "touchRotate"
            ]);
            var scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, this);
            this._add("scrollZoom", scrollZoom, ["mousePan"]);
            var keyboard = map.keyboard = new KeyboardHandler();
            this._add("keyboard", keyboard);
            this._add("blockableMapEvent", new BlockableMapEventHandler(map));
            for (var i = 0, list = [
              "boxZoom",
              "doubleClickZoom",
              "tapDragZoom",
              "touchPitch",
              "dragRotate",
              "dragPan",
              "touchZoomRotate",
              "scrollZoom",
              "keyboard"
            ]; i < list.length; i += 1) {
              var name2 = list[i];
              if (options.interactive && options[name2]) {
                map[name2].enable(options[name2]);
              }
            }
          };
          HandlerManager.prototype._add = function _add(handlerName, handler, allowed) {
            this._handlers.push({
              handlerName,
              handler,
              allowed
            });
            this._handlersById[handlerName] = handler;
          };
          HandlerManager.prototype.stop = function stop(allowEndAnimation) {
            if (this._updatingCamera) {
              return;
            }
            for (var i = 0, list = this._handlers; i < list.length; i += 1) {
              var ref = list[i];
              var handler = ref.handler;
              handler.reset();
            }
            this._inertia.clear();
            this._fireEvents({}, {}, allowEndAnimation);
            this._changes = [];
          };
          HandlerManager.prototype.isActive = function isActive() {
            for (var i = 0, list = this._handlers; i < list.length; i += 1) {
              var ref = list[i];
              var handler = ref.handler;
              if (handler.isActive()) {
                return true;
              }
            }
            return false;
          };
          HandlerManager.prototype.isZooming = function isZooming() {
            return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();
          };
          HandlerManager.prototype.isRotating = function isRotating() {
            return !!this._eventsInProgress.rotate;
          };
          HandlerManager.prototype.isMoving = function isMoving$1() {
            return Boolean(isMoving(this._eventsInProgress)) || this.isZooming();
          };
          HandlerManager.prototype._blockedByActive = function _blockedByActive(activeHandlers, allowed, myName) {
            for (var name2 in activeHandlers) {
              if (name2 === myName) {
                continue;
              }
              if (!allowed || allowed.indexOf(name2) < 0) {
                return true;
              }
            }
            return false;
          };
          HandlerManager.prototype.handleWindowEvent = function handleWindowEvent(e) {
            this.handleEvent(e, e.type + "Window");
          };
          HandlerManager.prototype._getMapTouches = function _getMapTouches(touches) {
            var mapTouches = [];
            for (var i = 0, list = touches; i < list.length; i += 1) {
              var t = list[i];
              var target = t.target;
              if (this._el.contains(target)) {
                mapTouches.push(t);
              }
            }
            return mapTouches;
          };
          HandlerManager.prototype.handleEvent = function handleEvent(e, eventName) {
            if (e.type === "blur") {
              this.stop(true);
              return;
            }
            this._updatingCamera = true;
            var inputEvent = e.type === "renderFrame" ? void 0 : e;
            var mergedHandlerResult = { needsRenderFrame: false };
            var eventsInProgress = {};
            var activeHandlers = {};
            var mapTouches = e.touches ? this._getMapTouches(e.touches) : void 0;
            var points = mapTouches ? DOM.touchPos(this._el, mapTouches) : DOM.mousePos(this._el, e);
            for (var i = 0, list = this._handlers; i < list.length; i += 1) {
              var ref = list[i];
              var handlerName = ref.handlerName;
              var handler = ref.handler;
              var allowed = ref.allowed;
              if (!handler.isEnabled()) {
                continue;
              }
              var data = void 0;
              if (this._blockedByActive(activeHandlers, allowed, handlerName)) {
                handler.reset();
              } else {
                if (handler[eventName || e.type]) {
                  data = handler[eventName || e.type](e, points, mapTouches);
                  this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);
                  if (data && data.needsRenderFrame) {
                    this._triggerRenderFrame();
                  }
                }
              }
              if (data || handler.isActive()) {
                activeHandlers[handlerName] = handler;
              }
            }
            var deactivatedHandlers = {};
            for (var name2 in this._previousActiveHandlers) {
              if (!activeHandlers[name2]) {
                deactivatedHandlers[name2] = inputEvent;
              }
            }
            this._previousActiveHandlers = activeHandlers;
            if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) {
              this._changes.push([
                mergedHandlerResult,
                eventsInProgress,
                deactivatedHandlers
              ]);
              this._triggerRenderFrame();
            }
            if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) {
              this._map._stop(true);
            }
            this._updatingCamera = false;
            var cameraAnimation = mergedHandlerResult.cameraAnimation;
            if (cameraAnimation) {
              this._inertia.clear();
              this._fireEvents({}, {}, true);
              this._changes = [];
              cameraAnimation(this._map);
            }
          };
          HandlerManager.prototype.mergeHandlerResult = function mergeHandlerResult(mergedHandlerResult, eventsInProgress, handlerResult, name2, e) {
            if (!handlerResult) {
              return;
            }
            performance2.extend(mergedHandlerResult, handlerResult);
            var eventData = {
              handlerName: name2,
              originalEvent: handlerResult.originalEvent || e
            };
            if (handlerResult.zoomDelta !== void 0) {
              eventsInProgress.zoom = eventData;
            }
            if (handlerResult.panDelta !== void 0) {
              eventsInProgress.drag = eventData;
            }
            if (handlerResult.pitchDelta !== void 0) {
              eventsInProgress.pitch = eventData;
            }
            if (handlerResult.bearingDelta !== void 0) {
              eventsInProgress.rotate = eventData;
            }
          };
          HandlerManager.prototype._applyChanges = function _applyChanges() {
            var combined = {};
            var combinedEventsInProgress = {};
            var combinedDeactivatedHandlers = {};
            for (var i = 0, list = this._changes; i < list.length; i += 1) {
              var ref = list[i];
              var change = ref[0];
              var eventsInProgress = ref[1];
              var deactivatedHandlers = ref[2];
              if (change.panDelta) {
                combined.panDelta = (combined.panDelta || new performance2.Point(0, 0))._add(change.panDelta);
              }
              if (change.zoomDelta) {
                combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta;
              }
              if (change.bearingDelta) {
                combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta;
              }
              if (change.pitchDelta) {
                combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta;
              }
              if (change.around !== void 0) {
                combined.around = change.around;
              }
              if (change.pinchAround !== void 0) {
                combined.pinchAround = change.pinchAround;
              }
              if (change.noInertia) {
                combined.noInertia = change.noInertia;
              }
              performance2.extend(combinedEventsInProgress, eventsInProgress);
              performance2.extend(combinedDeactivatedHandlers, deactivatedHandlers);
            }
            this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers);
            this._changes = [];
          };
          HandlerManager.prototype._updateMapTransform = function _updateMapTransform(combinedResult, combinedEventsInProgress, deactivatedHandlers) {
            var map = this._map;
            var tr = map.transform;
            if (!hasChange(combinedResult)) {
              return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
            }
            var panDelta = combinedResult.panDelta;
            var zoomDelta = combinedResult.zoomDelta;
            var bearingDelta = combinedResult.bearingDelta;
            var pitchDelta = combinedResult.pitchDelta;
            var around = combinedResult.around;
            var pinchAround = combinedResult.pinchAround;
            if (pinchAround !== void 0) {
              around = pinchAround;
            }
            map._stop(true);
            around = around || map.transform.centerPoint;
            var loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around);
            if (bearingDelta) {
              tr.bearing += bearingDelta;
            }
            if (pitchDelta) {
              tr.pitch += pitchDelta;
            }
            if (zoomDelta) {
              tr.zoom += zoomDelta;
            }
            tr.setLocationAtPoint(loc, around);
            this._map._update();
            if (!combinedResult.noInertia) {
              this._inertia.record(combinedResult);
            }
            this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
          };
          HandlerManager.prototype._fireEvents = function _fireEvents(newEventsInProgress, deactivatedHandlers, allowEndAnimation) {
            var this$1 = this;
            var wasMoving = isMoving(this._eventsInProgress);
            var nowMoving = isMoving(newEventsInProgress);
            var startEvents = {};
            for (var eventName in newEventsInProgress) {
              var ref = newEventsInProgress[eventName];
              var originalEvent = ref.originalEvent;
              if (!this._eventsInProgress[eventName]) {
                startEvents[eventName + "start"] = originalEvent;
              }
              this._eventsInProgress[eventName] = newEventsInProgress[eventName];
            }
            if (!wasMoving && nowMoving) {
              this._fireEvent("movestart", nowMoving.originalEvent);
            }
            for (var name2 in startEvents) {
              this._fireEvent(name2, startEvents[name2]);
            }
            if (nowMoving) {
              this._fireEvent("move", nowMoving.originalEvent);
            }
            for (var eventName$1 in newEventsInProgress) {
              var ref$1 = newEventsInProgress[eventName$1];
              var originalEvent$1 = ref$1.originalEvent;
              this._fireEvent(eventName$1, originalEvent$1);
            }
            var endEvents = {};
            var originalEndEvent;
            for (var eventName$2 in this._eventsInProgress) {
              var ref$2 = this._eventsInProgress[eventName$2];
              var handlerName = ref$2.handlerName;
              var originalEvent$2 = ref$2.originalEvent;
              if (!this._handlersById[handlerName].isActive()) {
                delete this._eventsInProgress[eventName$2];
                originalEndEvent = deactivatedHandlers[handlerName] || originalEvent$2;
                endEvents[eventName$2 + "end"] = originalEndEvent;
              }
            }
            for (var name$1 in endEvents) {
              this._fireEvent(name$1, endEvents[name$1]);
            }
            var stillMoving = isMoving(this._eventsInProgress);
            if (allowEndAnimation && (wasMoving || nowMoving) && !stillMoving) {
              this._updatingCamera = true;
              var inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);
              var shouldSnapToNorth = function(bearing) {
                return bearing !== 0 && -this$1._bearingSnap < bearing && bearing < this$1._bearingSnap;
              };
              if (inertialEase) {
                if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) {
                  inertialEase.bearing = 0;
                }
                this._map.easeTo(inertialEase, { originalEvent: originalEndEvent });
              } else {
                this._map.fire(new performance2.Event("moveend", { originalEvent: originalEndEvent }));
                if (shouldSnapToNorth(this._map.getBearing())) {
                  this._map.resetNorth();
                }
              }
              this._updatingCamera = false;
            }
          };
          HandlerManager.prototype._fireEvent = function _fireEvent(type, e) {
            this._map.fire(new performance2.Event(type, e ? { originalEvent: e } : {}));
          };
          HandlerManager.prototype._requestFrame = function _requestFrame() {
            var this$1 = this;
            this._map.triggerRepaint();
            return this._map._renderTaskQueue.add(function(timeStamp) {
              delete this$1._frameId;
              this$1.handleEvent(new RenderFrameEvent("renderFrame", { timeStamp }));
              this$1._applyChanges();
            });
          };
          HandlerManager.prototype._triggerRenderFrame = function _triggerRenderFrame() {
            if (this._frameId === void 0) {
              this._frameId = this._requestFrame();
            }
          };
          var Camera = function(Evented) {
            function Camera2(transform, options) {
              Evented.call(this);
              this._moving = false;
              this._zooming = false;
              this.transform = transform;
              this._bearingSnap = options.bearingSnap;
              performance2.bindAll(["_renderFrameCallback"], this);
            }
            if (Evented)
              Camera2.__proto__ = Evented;
            Camera2.prototype = Object.create(Evented && Evented.prototype);
            Camera2.prototype.constructor = Camera2;
            Camera2.prototype.getCenter = function getCenter() {
              return new performance2.LngLat(this.transform.center.lng, this.transform.center.lat);
            };
            Camera2.prototype.setCenter = function setCenter(center, eventData) {
              return this.jumpTo({ center }, eventData);
            };
            Camera2.prototype.panBy = function panBy(offset, options, eventData) {
              offset = performance2.Point.convert(offset).mult(-1);
              return this.panTo(this.transform.center, performance2.extend({ offset }, options), eventData);
            };
            Camera2.prototype.panTo = function panTo(lnglat, options, eventData) {
              return this.easeTo(performance2.extend({ center: lnglat }, options), eventData);
            };
            Camera2.prototype.getZoom = function getZoom() {
              return this.transform.zoom;
            };
            Camera2.prototype.setZoom = function setZoom(zoom, eventData) {
              this.jumpTo({ zoom }, eventData);
              return this;
            };
            Camera2.prototype.zoomTo = function zoomTo(zoom, options, eventData) {
              return this.easeTo(performance2.extend({ zoom }, options), eventData);
            };
            Camera2.prototype.zoomIn = function zoomIn(options, eventData) {
              this.zoomTo(this.getZoom() + 1, options, eventData);
              return this;
            };
            Camera2.prototype.zoomOut = function zoomOut(options, eventData) {
              this.zoomTo(this.getZoom() - 1, options, eventData);
              return this;
            };
            Camera2.prototype.getBearing = function getBearing() {
              return this.transform.bearing;
            };
            Camera2.prototype.setBearing = function setBearing(bearing, eventData) {
              this.jumpTo({ bearing }, eventData);
              return this;
            };
            Camera2.prototype.getPadding = function getPadding() {
              return this.transform.padding;
            };
            Camera2.prototype.setPadding = function setPadding(padding2, eventData) {
              this.jumpTo({ padding: padding2 }, eventData);
              return this;
            };
            Camera2.prototype.rotateTo = function rotateTo(bearing, options, eventData) {
              return this.easeTo(performance2.extend({ bearing }, options), eventData);
            };
            Camera2.prototype.resetNorth = function resetNorth(options, eventData) {
              this.rotateTo(0, performance2.extend({ duration: 1e3 }, options), eventData);
              return this;
            };
            Camera2.prototype.resetNorthPitch = function resetNorthPitch(options, eventData) {
              this.easeTo(performance2.extend({
                bearing: 0,
                pitch: 0,
                duration: 1e3
              }, options), eventData);
              return this;
            };
            Camera2.prototype.snapToNorth = function snapToNorth(options, eventData) {
              if (Math.abs(this.getBearing()) < this._bearingSnap) {
                return this.resetNorth(options, eventData);
              }
              return this;
            };
            Camera2.prototype.getPitch = function getPitch() {
              return this.transform.pitch;
            };
            Camera2.prototype.setPitch = function setPitch(pitch, eventData) {
              this.jumpTo({ pitch }, eventData);
              return this;
            };
            Camera2.prototype.cameraForBounds = function cameraForBounds(bounds, options) {
              bounds = performance2.LngLatBounds.convert(bounds);
              var bearing = options && options.bearing || 0;
              return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options);
            };
            Camera2.prototype._cameraForBoxAndBearing = function _cameraForBoxAndBearing(p0, p1, bearing, options) {
              var defaultPadding = {
                top: 0,
                bottom: 0,
                right: 0,
                left: 0
              };
              options = performance2.extend({
                padding: defaultPadding,
                offset: [
                  0,
                  0
                ],
                maxZoom: this.transform.maxZoom
              }, options);
              if (typeof options.padding === "number") {
                var p = options.padding;
                options.padding = {
                  top: p,
                  bottom: p,
                  right: p,
                  left: p
                };
              }
              options.padding = performance2.extend(defaultPadding, options.padding);
              var tr = this.transform;
              var edgePadding = tr.padding;
              var p0world = tr.project(performance2.LngLat.convert(p0));
              var p1world = tr.project(performance2.LngLat.convert(p1));
              var p0rotated = p0world.rotate(-bearing * Math.PI / 180);
              var p1rotated = p1world.rotate(-bearing * Math.PI / 180);
              var upperRight = new performance2.Point(Math.max(p0rotated.x, p1rotated.x), Math.max(p0rotated.y, p1rotated.y));
              var lowerLeft = new performance2.Point(Math.min(p0rotated.x, p1rotated.x), Math.min(p0rotated.y, p1rotated.y));
              var size = upperRight.sub(lowerLeft);
              var scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x;
              var scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y;
              if (scaleY < 0 || scaleX < 0) {
                performance2.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset.");
                return;
              }
              var zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);
              var offset = typeof options.offset.x === "number" ? new performance2.Point(options.offset.x, options.offset.y) : performance2.Point.convert(options.offset);
              var paddingOffsetX = (options.padding.left - options.padding.right) / 2;
              var paddingOffsetY = (options.padding.top - options.padding.bottom) / 2;
              var paddingOffset = new performance2.Point(paddingOffsetX, paddingOffsetY);
              var rotatedPaddingOffset = paddingOffset.rotate(bearing * Math.PI / 180);
              var offsetAtInitialZoom = offset.add(rotatedPaddingOffset);
              var offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom));
              var center = tr.unproject(p0world.add(p1world).div(2).sub(offsetAtFinalZoom));
              return {
                center,
                zoom,
                bearing
              };
            };
            Camera2.prototype.fitBounds = function fitBounds(bounds, options, eventData) {
              return this._fitInternal(this.cameraForBounds(bounds, options), options, eventData);
            };
            Camera2.prototype.fitScreenCoordinates = function fitScreenCoordinates(p0, p1, bearing, options, eventData) {
              return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(performance2.Point.convert(p0)), this.transform.pointLocation(performance2.Point.convert(p1)), bearing, options), options, eventData);
            };
            Camera2.prototype._fitInternal = function _fitInternal(calculatedOptions, options, eventData) {
              if (!calculatedOptions) {
                return this;
              }
              options = performance2.extend(calculatedOptions, options);
              delete options.padding;
              return options.linear ? this.easeTo(options, eventData) : this.flyTo(options, eventData);
            };
            Camera2.prototype.jumpTo = function jumpTo(options, eventData) {
              this.stop();
              var tr = this.transform;
              var zoomChanged = false, bearingChanged = false, pitchChanged = false;
              if ("zoom" in options && tr.zoom !== +options.zoom) {
                zoomChanged = true;
                tr.zoom = +options.zoom;
              }
              if (options.center !== void 0) {
                tr.center = performance2.LngLat.convert(options.center);
              }
              if ("bearing" in options && tr.bearing !== +options.bearing) {
                bearingChanged = true;
                tr.bearing = +options.bearing;
              }
              if ("pitch" in options && tr.pitch !== +options.pitch) {
                pitchChanged = true;
                tr.pitch = +options.pitch;
              }
              if (options.padding != null && !tr.isPaddingEqual(options.padding)) {
                tr.padding = options.padding;
              }
              this.fire(new performance2.Event("movestart", eventData)).fire(new performance2.Event("move", eventData));
              if (zoomChanged) {
                this.fire(new performance2.Event("zoomstart", eventData)).fire(new performance2.Event("zoom", eventData)).fire(new performance2.Event("zoomend", eventData));
              }
              if (bearingChanged) {
                this.fire(new performance2.Event("rotatestart", eventData)).fire(new performance2.Event("rotate", eventData)).fire(new performance2.Event("rotateend", eventData));
              }
              if (pitchChanged) {
                this.fire(new performance2.Event("pitchstart", eventData)).fire(new performance2.Event("pitch", eventData)).fire(new performance2.Event("pitchend", eventData));
              }
              return this.fire(new performance2.Event("moveend", eventData));
            };
            Camera2.prototype.easeTo = function easeTo(options, eventData) {
              var this$1 = this;
              this._stop(false, options.easeId);
              options = performance2.extend({
                offset: [
                  0,
                  0
                ],
                duration: 500,
                easing: performance2.ease
              }, options);
              if (options.animate === false || !options.essential && performance2.browser.prefersReducedMotion) {
                options.duration = 0;
              }
              var tr = this.transform, startZoom = this.getZoom(), startBearing = this.getBearing(), startPitch = this.getPitch(), startPadding = this.getPadding(), zoom = "zoom" in options ? +options.zoom : startZoom, bearing = "bearing" in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = "pitch" in options ? +options.pitch : startPitch, padding2 = "padding" in options ? options.padding : tr.padding;
              var offsetAsPoint = performance2.Point.convert(options.offset);
              var pointAtOffset = tr.centerPoint.add(offsetAsPoint);
              var locationAtOffset = tr.pointLocation(pointAtOffset);
              var center = performance2.LngLat.convert(options.center || locationAtOffset);
              this._normalizeCenter(center);
              var from = tr.project(locationAtOffset);
              var delta = tr.project(center).sub(from);
              var finalScale = tr.zoomScale(zoom - startZoom);
              var around, aroundPoint;
              if (options.around) {
                around = performance2.LngLat.convert(options.around);
                aroundPoint = tr.locationPoint(around);
              }
              var currently = {
                moving: this._moving,
                zooming: this._zooming,
                rotating: this._rotating,
                pitching: this._pitching
              };
              this._zooming = this._zooming || zoom !== startZoom;
              this._rotating = this._rotating || startBearing !== bearing;
              this._pitching = this._pitching || pitch !== startPitch;
              this._padding = !tr.isPaddingEqual(padding2);
              this._easeId = options.easeId;
              this._prepareEase(eventData, options.noMoveStart, currently);
              this._ease(function(k) {
                if (this$1._zooming) {
                  tr.zoom = performance2.number(startZoom, zoom, k);
                }
                if (this$1._rotating) {
                  tr.bearing = performance2.number(startBearing, bearing, k);
                }
                if (this$1._pitching) {
                  tr.pitch = performance2.number(startPitch, pitch, k);
                }
                if (this$1._padding) {
                  tr.interpolatePadding(startPadding, padding2, k);
                  pointAtOffset = tr.centerPoint.add(offsetAsPoint);
                }
                if (around) {
                  tr.setLocationAtPoint(around, aroundPoint);
                } else {
                  var scale = tr.zoomScale(tr.zoom - startZoom);
                  var base = zoom > startZoom ? Math.min(2, finalScale) : Math.max(0.5, finalScale);
                  var speedup = Math.pow(base, 1 - k);
                  var newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale));
                  tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
                }
                this$1._fireMoveEvents(eventData);
              }, function(interruptingEaseId) {
                this$1._afterEase(eventData, interruptingEaseId);
              }, options);
              return this;
            };
            Camera2.prototype._prepareEase = function _prepareEase(eventData, noMoveStart, currently) {
              if (currently === void 0)
                currently = {};
              this._moving = true;
              if (!noMoveStart && !currently.moving) {
                this.fire(new performance2.Event("movestart", eventData));
              }
              if (this._zooming && !currently.zooming) {
                this.fire(new performance2.Event("zoomstart", eventData));
              }
              if (this._rotating && !currently.rotating) {
                this.fire(new performance2.Event("rotatestart", eventData));
              }
              if (this._pitching && !currently.pitching) {
                this.fire(new performance2.Event("pitchstart", eventData));
              }
            };
            Camera2.prototype._fireMoveEvents = function _fireMoveEvents(eventData) {
              this.fire(new performance2.Event("move", eventData));
              if (this._zooming) {
                this.fire(new performance2.Event("zoom", eventData));
              }
              if (this._rotating) {
                this.fire(new performance2.Event("rotate", eventData));
              }
              if (this._pitching) {
                this.fire(new performance2.Event("pitch", eventData));
              }
            };
            Camera2.prototype._afterEase = function _afterEase(eventData, easeId) {
              if (this._easeId && easeId && this._easeId === easeId) {
                return;
              }
              delete this._easeId;
              var wasZooming = this._zooming;
              var wasRotating = this._rotating;
              var wasPitching = this._pitching;
              this._moving = false;
              this._zooming = false;
              this._rotating = false;
              this._pitching = false;
              this._padding = false;
              if (wasZooming) {
                this.fire(new performance2.Event("zoomend", eventData));
              }
              if (wasRotating) {
                this.fire(new performance2.Event("rotateend", eventData));
              }
              if (wasPitching) {
                this.fire(new performance2.Event("pitchend", eventData));
              }
              this.fire(new performance2.Event("moveend", eventData));
            };
            Camera2.prototype.flyTo = function flyTo(options, eventData) {
              var this$1 = this;
              if (!options.essential && performance2.browser.prefersReducedMotion) {
                var coercedOptions = performance2.pick(options, [
                  "center",
                  "zoom",
                  "bearing",
                  "pitch",
                  "around"
                ]);
                return this.jumpTo(coercedOptions, eventData);
              }
              this.stop();
              options = performance2.extend({
                offset: [
                  0,
                  0
                ],
                speed: 1.2,
                curve: 1.42,
                easing: performance2.ease
              }, options);
              var tr = this.transform, startZoom = this.getZoom(), startBearing = this.getBearing(), startPitch = this.getPitch(), startPadding = this.getPadding();
              var zoom = "zoom" in options ? performance2.clamp(+options.zoom, tr.minZoom, tr.maxZoom) : startZoom;
              var bearing = "bearing" in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;
              var pitch = "pitch" in options ? +options.pitch : startPitch;
              var padding2 = "padding" in options ? options.padding : tr.padding;
              var scale = tr.zoomScale(zoom - startZoom);
              var offsetAsPoint = performance2.Point.convert(options.offset);
              var pointAtOffset = tr.centerPoint.add(offsetAsPoint);
              var locationAtOffset = tr.pointLocation(pointAtOffset);
              var center = performance2.LngLat.convert(options.center || locationAtOffset);
              this._normalizeCenter(center);
              var from = tr.project(locationAtOffset);
              var delta = tr.project(center).sub(from);
              var rho = options.curve;
              var w0 = Math.max(tr.width, tr.height), w1 = w0 / scale, u1 = delta.mag();
              if ("minZoom" in options) {
                var minZoom = performance2.clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom);
                var wMax = w0 / tr.zoomScale(minZoom - startZoom);
                rho = Math.sqrt(wMax / u1 * 2);
              }
              var rho2 = rho * rho;
              function r(i) {
                var b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1);
                return Math.log(Math.sqrt(b * b + 1) - b);
              }
              function sinh2(n) {
                return (Math.exp(n) - Math.exp(-n)) / 2;
              }
              function cosh2(n) {
                return (Math.exp(n) + Math.exp(-n)) / 2;
              }
              function tanh2(n) {
                return sinh2(n) / cosh2(n);
              }
              var r0 = r(0);
              var w = function(s) {
                return cosh2(r0) / cosh2(r0 + rho * s);
              };
              var u = function(s) {
                return w0 * ((cosh2(r0) * tanh2(r0 + rho * s) - sinh2(r0)) / rho2) / u1;
              };
              var S = (r(1) - r0) / rho;
              if (Math.abs(u1) < 1e-6 || !isFinite(S)) {
                if (Math.abs(w0 - w1) < 1e-6) {
                  return this.easeTo(options, eventData);
                }
                var k = w1 < w0 ? -1 : 1;
                S = Math.abs(Math.log(w1 / w0)) / rho;
                u = function() {
                  return 0;
                };
                w = function(s) {
                  return Math.exp(k * rho * s);
                };
              }
              if ("duration" in options) {
                options.duration = +options.duration;
              } else {
                var V = "screenSpeed" in options ? +options.screenSpeed / rho : +options.speed;
                options.duration = 1e3 * S / V;
              }
              if (options.maxDuration && options.duration > options.maxDuration) {
                options.duration = 0;
              }
              this._zooming = true;
              this._rotating = startBearing !== bearing;
              this._pitching = pitch !== startPitch;
              this._padding = !tr.isPaddingEqual(padding2);
              this._prepareEase(eventData, false);
              this._ease(function(k2) {
                var s = k2 * S;
                var scale2 = 1 / w(s);
                tr.zoom = k2 === 1 ? zoom : startZoom + tr.scaleZoom(scale2);
                if (this$1._rotating) {
                  tr.bearing = performance2.number(startBearing, bearing, k2);
                }
                if (this$1._pitching) {
                  tr.pitch = performance2.number(startPitch, pitch, k2);
                }
                if (this$1._padding) {
                  tr.interpolatePadding(startPadding, padding2, k2);
                  pointAtOffset = tr.centerPoint.add(offsetAsPoint);
                }
                var newCenter = k2 === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale2));
                tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
                this$1._fireMoveEvents(eventData);
              }, function() {
                return this$1._afterEase(eventData);
              }, options);
              return this;
            };
            Camera2.prototype.isEasing = function isEasing() {
              return !!this._easeFrameId;
            };
            Camera2.prototype.stop = function stop() {
              return this._stop();
            };
            Camera2.prototype._stop = function _stop(allowGestures, easeId) {
              if (this._easeFrameId) {
                this._cancelRenderFrame(this._easeFrameId);
                delete this._easeFrameId;
                delete this._onEaseFrame;
              }
              if (this._onEaseEnd) {
                var onEaseEnd = this._onEaseEnd;
                delete this._onEaseEnd;
                onEaseEnd.call(this, easeId);
              }
              if (!allowGestures) {
                var handlers = this.handlers;
                if (handlers) {
                  handlers.stop(false);
                }
              }
              return this;
            };
            Camera2.prototype._ease = function _ease(frame, finish, options) {
              if (options.animate === false || options.duration === 0) {
                frame(1);
                finish();
              } else {
                this._easeStart = performance2.browser.now();
                this._easeOptions = options;
                this._onEaseFrame = frame;
                this._onEaseEnd = finish;
                this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);
              }
            };
            Camera2.prototype._renderFrameCallback = function _renderFrameCallback() {
              var t = Math.min((performance2.browser.now() - this._easeStart) / this._easeOptions.duration, 1);
              this._onEaseFrame(this._easeOptions.easing(t));
              if (t < 1) {
                this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);
              } else {
                this.stop();
              }
            };
            Camera2.prototype._normalizeBearing = function _normalizeBearing(bearing, currentBearing) {
              bearing = performance2.wrap(bearing, -180, 180);
              var diff = Math.abs(bearing - currentBearing);
              if (Math.abs(bearing - 360 - currentBearing) < diff) {
                bearing -= 360;
              }
              if (Math.abs(bearing + 360 - currentBearing) < diff) {
                bearing += 360;
              }
              return bearing;
            };
            Camera2.prototype._normalizeCenter = function _normalizeCenter(center) {
              var tr = this.transform;
              if (!tr.renderWorldCopies || tr.lngRange) {
                return;
              }
              var delta = center.lng - tr.center.lng;
              center.lng += delta > 180 ? -360 : delta < -180 ? 360 : 0;
            };
            return Camera2;
          }(performance2.Evented);
          var AttributionControl = function AttributionControl2(options) {
            if (options === void 0)
              options = {};
            this.options = options;
            performance2.bindAll([
              "_toggleAttribution",
              "_updateEditLink",
              "_updateData",
              "_updateCompact"
            ], this);
          };
          AttributionControl.prototype.getDefaultPosition = function getDefaultPosition() {
            return "bottom-right";
          };
          AttributionControl.prototype.onAdd = function onAdd(map) {
            var compact = this.options && this.options.compact;
            this._map = map;
            this._container = DOM.create("div", "mapboxgl-ctrl mapboxgl-ctrl-attrib");
            this._compactButton = DOM.create("button", "mapboxgl-ctrl-attrib-button", this._container);
            this._compactButton.addEventListener("click", this._toggleAttribution);
            this._setElementTitle(this._compactButton, "ToggleAttribution");
            this._innerContainer = DOM.create("div", "mapboxgl-ctrl-attrib-inner", this._container);
            this._innerContainer.setAttribute("role", "list");
            if (compact) {
              this._container.classList.add("mapboxgl-compact");
            }
            this._updateAttributions();
            this._updateEditLink();
            this._map.on("styledata", this._updateData);
            this._map.on("sourcedata", this._updateData);
            this._map.on("moveend", this._updateEditLink);
            if (compact === void 0) {
              this._map.on("resize", this._updateCompact);
              this._updateCompact();
            }
            return this._container;
          };
          AttributionControl.prototype.onRemove = function onRemove() {
            DOM.remove(this._container);
            this._map.off("styledata", this._updateData);
            this._map.off("sourcedata", this._updateData);
            this._map.off("moveend", this._updateEditLink);
            this._map.off("resize", this._updateCompact);
            this._map = void 0;
            this._attribHTML = void 0;
          };
          AttributionControl.prototype._setElementTitle = function _setElementTitle(element, title) {
            var str = this._map._getUIString("AttributionControl." + title);
            element.title = str;
            element.setAttribute("aria-label", str);
          };
          AttributionControl.prototype._toggleAttribution = function _toggleAttribution() {
            if (this._container.classList.contains("mapboxgl-compact-show")) {
              this._container.classList.remove("mapboxgl-compact-show");
              this._compactButton.setAttribute("aria-pressed", "false");
            } else {
              this._container.classList.add("mapboxgl-compact-show");
              this._compactButton.setAttribute("aria-pressed", "true");
            }
          };
          AttributionControl.prototype._updateEditLink = function _updateEditLink() {
            var editLink = this._editLink;
            if (!editLink) {
              editLink = this._editLink = this._container.querySelector(".mapbox-improve-map");
            }
            var params = [
              {
                key: "owner",
                value: this.styleOwner
              },
              {
                key: "id",
                value: this.styleId
              },
              {
                key: "access_token",
                value: this._map._requestManager._customAccessToken || performance2.config.ACCESS_TOKEN
              }
            ];
            if (editLink) {
              var paramString = params.reduce(function(acc, next, i) {
                if (next.value) {
                  acc += next.key + "=" + next.value + (i < params.length - 1 ? "&" : "");
                }
                return acc;
              }, "?");
              editLink.href = performance2.config.FEEDBACK_URL + "/" + paramString + (this._map._hash ? this._map._hash.getHashString(true) : "");
              editLink.rel = "noopener nofollow";
              this._setElementTitle(editLink, "MapFeedback");
            }
          };
          AttributionControl.prototype._updateData = function _updateData(e) {
            if (e && (e.sourceDataType === "metadata" || e.sourceDataType === "visibility" || e.dataType === "style")) {
              this._updateAttributions();
              this._updateEditLink();
            }
          };
          AttributionControl.prototype._updateAttributions = function _updateAttributions() {
            if (!this._map.style) {
              return;
            }
            var attributions = [];
            if (this.options.customAttribution) {
              if (Array.isArray(this.options.customAttribution)) {
                attributions = attributions.concat(this.options.customAttribution.map(function(attribution) {
                  if (typeof attribution !== "string") {
                    return "";
                  }
                  return attribution;
                }));
              } else if (typeof this.options.customAttribution === "string") {
                attributions.push(this.options.customAttribution);
              }
            }
            if (this._map.style.stylesheet) {
              var stylesheet = this._map.style.stylesheet;
              this.styleOwner = stylesheet.owner;
              this.styleId = stylesheet.id;
            }
            var sourceCaches = this._map.style.sourceCaches;
            for (var id in sourceCaches) {
              var sourceCache = sourceCaches[id];
              if (sourceCache.used) {
                var source = sourceCache.getSource();
                if (source.attribution && attributions.indexOf(source.attribution) < 0) {
                  attributions.push(source.attribution);
                }
              }
            }
            attributions.sort(function(a, b) {
              return a.length - b.length;
            });
            attributions = attributions.filter(function(attrib, i) {
              for (var j = i + 1; j < attributions.length; j++) {
                if (attributions[j].indexOf(attrib) >= 0) {
                  return false;
                }
              }
              return true;
            });
            var attribHTML = attributions.join(" | ");
            if (attribHTML === this._attribHTML) {
              return;
            }
            this._attribHTML = attribHTML;
            if (attributions.length) {
              this._innerContainer.innerHTML = attribHTML;
              this._container.classList.remove("mapboxgl-attrib-empty");
            } else {
              this._container.classList.add("mapboxgl-attrib-empty");
            }
            this._editLink = null;
          };
          AttributionControl.prototype._updateCompact = function _updateCompact() {
            if (this._map.getCanvasContainer().offsetWidth <= 640) {
              this._container.classList.add("mapboxgl-compact");
            } else {
              this._container.classList.remove("mapboxgl-compact", "mapboxgl-compact-show");
            }
          };
          var LogoControl = function LogoControl2() {
            performance2.bindAll(["_updateLogo"], this);
            performance2.bindAll(["_updateCompact"], this);
          };
          LogoControl.prototype.onAdd = function onAdd(map) {
            this._map = map;
            this._container = DOM.create("div", "mapboxgl-ctrl");
            var anchor = DOM.create("a", "mapboxgl-ctrl-logo");
            anchor.target = "_blank";
            anchor.rel = "noopener nofollow";
            anchor.href = "https://www.mapbox.com/";
            anchor.setAttribute("aria-label", this._map._getUIString("LogoControl.Title"));
            anchor.setAttribute("rel", "noopener nofollow");
            this._container.appendChild(anchor);
            this._container.style.display = "none";
            this._map.on("sourcedata", this._updateLogo);
            this._updateLogo();
            this._map.on("resize", this._updateCompact);
            this._updateCompact();
            return this._container;
          };
          LogoControl.prototype.onRemove = function onRemove() {
            DOM.remove(this._container);
            this._map.off("sourcedata", this._updateLogo);
            this._map.off("resize", this._updateCompact);
          };
          LogoControl.prototype.getDefaultPosition = function getDefaultPosition() {
            return "bottom-left";
          };
          LogoControl.prototype._updateLogo = function _updateLogo(e) {
            if (!e || e.sourceDataType === "metadata") {
              this._container.style.display = this._logoRequired() ? "block" : "none";
            }
          };
          LogoControl.prototype._logoRequired = function _logoRequired() {
            if (!this._map.style) {
              return;
            }
            var sourceCaches = this._map.style.sourceCaches;
            for (var id in sourceCaches) {
              var source = sourceCaches[id].getSource();
              if (source.mapbox_logo) {
                return true;
              }
            }
            return false;
          };
          LogoControl.prototype._updateCompact = function _updateCompact() {
            var containerChildren = this._container.children;
            if (containerChildren.length) {
              var anchor = containerChildren[0];
              if (this._map.getCanvasContainer().offsetWidth < 250) {
                anchor.classList.add("mapboxgl-compact");
              } else {
                anchor.classList.remove("mapboxgl-compact");
              }
            }
          };
          var TaskQueue = function TaskQueue2() {
            this._queue = [];
            this._id = 0;
            this._cleared = false;
            this._currentlyRunning = false;
          };
          TaskQueue.prototype.add = function add(callback) {
            var id = ++this._id;
            var queue = this._queue;
            queue.push({
              callback,
              id,
              cancelled: false
            });
            return id;
          };
          TaskQueue.prototype.remove = function remove(id) {
            var running = this._currentlyRunning;
            var queue = running ? this._queue.concat(running) : this._queue;
            for (var i = 0, list = queue; i < list.length; i += 1) {
              var task = list[i];
              if (task.id === id) {
                task.cancelled = true;
                return;
              }
            }
          };
          TaskQueue.prototype.run = function run(timeStamp) {
            if (timeStamp === void 0)
              timeStamp = 0;
            var queue = this._currentlyRunning = this._queue;
            this._queue = [];
            for (var i = 0, list = queue; i < list.length; i += 1) {
              var task = list[i];
              if (task.cancelled) {
                continue;
              }
              task.callback(timeStamp);
              if (this._cleared) {
                break;
              }
            }
            this._cleared = false;
            this._currentlyRunning = false;
          };
          TaskQueue.prototype.clear = function clear() {
            if (this._currentlyRunning) {
              this._cleared = true;
            }
            this._queue = [];
          };
          var defaultLocale = {
            "AttributionControl.ToggleAttribution": "Toggle attribution",
            "AttributionControl.MapFeedback": "Map feedback",
            "FullscreenControl.Enter": "Enter fullscreen",
            "FullscreenControl.Exit": "Exit fullscreen",
            "GeolocateControl.FindMyLocation": "Find my location",
            "GeolocateControl.LocationNotAvailable": "Location not available",
            "LogoControl.Title": "Mapbox logo",
            "NavigationControl.ResetBearing": "Reset bearing to north",
            "NavigationControl.ZoomIn": "Zoom in",
            "NavigationControl.ZoomOut": "Zoom out",
            "ScaleControl.Feet": "ft",
            "ScaleControl.Meters": "m",
            "ScaleControl.Kilometers": "km",
            "ScaleControl.Miles": "mi",
            "ScaleControl.NauticalMiles": "nm"
          };
          var HTMLImageElement2 = performance2.window.HTMLImageElement;
          var HTMLElement2 = performance2.window.HTMLElement;
          var ImageBitmap2 = performance2.window.ImageBitmap;
          var defaultMinZoom = -2;
          var defaultMaxZoom = 22;
          var defaultMinPitch = 0;
          var defaultMaxPitch = 60;
          var defaultOptions$1 = {
            center: [
              0,
              0
            ],
            zoom: 0,
            bearing: 0,
            pitch: 0,
            minZoom: defaultMinZoom,
            maxZoom: defaultMaxZoom,
            minPitch: defaultMinPitch,
            maxPitch: defaultMaxPitch,
            interactive: true,
            scrollZoom: true,
            boxZoom: true,
            dragRotate: true,
            dragPan: true,
            keyboard: true,
            doubleClickZoom: true,
            touchZoomRotate: true,
            touchPitch: true,
            bearingSnap: 7,
            clickTolerance: 3,
            pitchWithRotate: true,
            hash: false,
            attributionControl: true,
            failIfMajorPerformanceCaveat: false,
            preserveDrawingBuffer: false,
            trackResize: true,
            renderWorldCopies: true,
            refreshExpiredTiles: true,
            maxTileCacheSize: null,
            localIdeographFontFamily: "sans-serif",
            transformRequest: null,
            accessToken: null,
            fadeDuration: 300,
            crossSourceCollisions: true
          };
          var Map2 = function(Camera2) {
            function Map3(options) {
              var this$1 = this;
              options = performance2.extend({}, defaultOptions$1, options);
              if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) {
                throw new Error("maxZoom must be greater than or equal to minZoom");
              }
              if (options.minPitch != null && options.maxPitch != null && options.minPitch > options.maxPitch) {
                throw new Error("maxPitch must be greater than or equal to minPitch");
              }
              if (options.minPitch != null && options.minPitch < defaultMinPitch) {
                throw new Error("minPitch must be greater than or equal to " + defaultMinPitch);
              }
              if (options.maxPitch != null && options.maxPitch > defaultMaxPitch) {
                throw new Error("maxPitch must be less than or equal to " + defaultMaxPitch);
              }
              var transform = new Transform(options.minZoom, options.maxZoom, options.minPitch, options.maxPitch, options.renderWorldCopies);
              Camera2.call(this, transform, options);
              this._interactive = options.interactive;
              this._maxTileCacheSize = options.maxTileCacheSize;
              this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat;
              this._preserveDrawingBuffer = options.preserveDrawingBuffer;
              this._antialias = options.antialias;
              this._trackResize = options.trackResize;
              this._bearingSnap = options.bearingSnap;
              this._refreshExpiredTiles = options.refreshExpiredTiles;
              this._fadeDuration = options.fadeDuration;
              this._crossSourceCollisions = options.crossSourceCollisions;
              this._crossFadingFactor = 1;
              this._collectResourceTiming = options.collectResourceTiming;
              this._renderTaskQueue = new TaskQueue();
              this._controls = [];
              this._mapId = performance2.uniqueId();
              this._locale = performance2.extend({}, defaultLocale, options.locale);
              this._clickTolerance = options.clickTolerance;
              this._requestManager = new performance2.RequestManager(options.transformRequest, options.accessToken);
              if (typeof options.container === "string") {
                this._container = performance2.window.document.getElementById(options.container);
                if (!this._container) {
                  throw new Error("Container '" + options.container + "' not found.");
                }
              } else if (options.container instanceof HTMLElement2) {
                this._container = options.container;
              } else {
                throw new Error("Invalid type: 'container' must be a String or HTMLElement.");
              }
              if (options.maxBounds) {
                this.setMaxBounds(options.maxBounds);
              }
              performance2.bindAll([
                "_onWindowOnline",
                "_onWindowResize",
                "_onMapScroll",
                "_contextLost",
                "_contextRestored"
              ], this);
              this._setupContainer();
              this._setupPainter();
              if (this.painter === void 0) {
                throw new Error("Failed to initialize WebGL.");
              }
              this.on("move", function() {
                return this$1._update(false);
              });
              this.on("moveend", function() {
                return this$1._update(false);
              });
              this.on("zoom", function() {
                return this$1._update(true);
              });
              if (typeof performance2.window !== "undefined") {
                performance2.window.addEventListener("online", this._onWindowOnline, false);
                performance2.window.addEventListener("resize", this._onWindowResize, false);
                performance2.window.addEventListener("orientationchange", this._onWindowResize, false);
              }
              this.handlers = new HandlerManager(this, options);
              var hashName = typeof options.hash === "string" && options.hash || void 0;
              this._hash = options.hash && new Hash(hashName).addTo(this);
              if (!this._hash || !this._hash._onHashChange()) {
                this.jumpTo({
                  center: options.center,
                  zoom: options.zoom,
                  bearing: options.bearing,
                  pitch: options.pitch
                });
                if (options.bounds) {
                  this.resize();
                  this.fitBounds(options.bounds, performance2.extend({}, options.fitBoundsOptions, { duration: 0 }));
                }
              }
              this.resize();
              this._localIdeographFontFamily = options.localIdeographFontFamily;
              if (options.style) {
                this.setStyle(options.style, { localIdeographFontFamily: options.localIdeographFontFamily });
              }
              if (options.attributionControl) {
                this.addControl(new AttributionControl({ customAttribution: options.customAttribution }));
              }
              this.addControl(new LogoControl(), options.logoPosition);
              this.on("style.load", function() {
                if (this$1.transform.unmodified) {
                  this$1.jumpTo(this$1.style.stylesheet);
                }
              });
              this.on("data", function(event) {
                this$1._update(event.dataType === "style");
                this$1.fire(new performance2.Event(event.dataType + "data", event));
              });
              this.on("dataloading", function(event) {
                this$1.fire(new performance2.Event(event.dataType + "dataloading", event));
              });
            }
            if (Camera2)
              Map3.__proto__ = Camera2;
            Map3.prototype = Object.create(Camera2 && Camera2.prototype);
            Map3.prototype.constructor = Map3;
            var prototypeAccessors2 = {
              showTileBoundaries: { configurable: true },
              showPadding: { configurable: true },
              showCollisionBoxes: { configurable: true },
              showOverdrawInspector: { configurable: true },
              repaint: { configurable: true },
              vertices: { configurable: true },
              version: { configurable: true }
            };
            Map3.prototype._getMapId = function _getMapId() {
              return this._mapId;
            };
            Map3.prototype.addControl = function addControl(control, position) {
              if (position === void 0) {
                if (control.getDefaultPosition) {
                  position = control.getDefaultPosition();
                } else {
                  position = "top-right";
                }
              }
              if (!control || !control.onAdd) {
                return this.fire(new performance2.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));
              }
              var controlElement = control.onAdd(this);
              this._controls.push(control);
              var positionContainer = this._controlPositions[position];
              if (position.indexOf("bottom") !== -1) {
                positionContainer.insertBefore(controlElement, positionContainer.firstChild);
              } else {
                positionContainer.appendChild(controlElement);
              }
              return this;
            };
            Map3.prototype.removeControl = function removeControl(control) {
              if (!control || !control.onRemove) {
                return this.fire(new performance2.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));
              }
              var ci = this._controls.indexOf(control);
              if (ci > -1) {
                this._controls.splice(ci, 1);
              }
              control.onRemove(this);
              return this;
            };
            Map3.prototype.hasControl = function hasControl(control) {
              return this._controls.indexOf(control) > -1;
            };
            Map3.prototype.resize = function resize(eventData) {
              var dimensions = this._containerDimensions();
              var width = dimensions[0];
              var height = dimensions[1];
              this._resizeCanvas(width, height);
              this.transform.resize(width, height);
              this.painter.resize(width, height);
              var fireMoving = !this._moving;
              if (fireMoving) {
                this.stop();
                this.fire(new performance2.Event("movestart", eventData)).fire(new performance2.Event("move", eventData));
              }
              this.fire(new performance2.Event("resize", eventData));
              if (fireMoving) {
                this.fire(new performance2.Event("moveend", eventData));
              }
              return this;
            };
            Map3.prototype.getBounds = function getBounds() {
              return this.transform.getBounds();
            };
            Map3.prototype.getMaxBounds = function getMaxBounds() {
              return this.transform.getMaxBounds();
            };
            Map3.prototype.setMaxBounds = function setMaxBounds(bounds) {
              this.transform.setMaxBounds(performance2.LngLatBounds.convert(bounds));
              return this._update();
            };
            Map3.prototype.setMinZoom = function setMinZoom(minZoom) {
              minZoom = minZoom === null || minZoom === void 0 ? defaultMinZoom : minZoom;
              if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) {
                this.transform.minZoom = minZoom;
                this._update();
                if (this.getZoom() < minZoom) {
                  this.setZoom(minZoom);
                }
                return this;
              } else {
                throw new Error("minZoom must be between " + defaultMinZoom + " and the current maxZoom, inclusive");
              }
            };
            Map3.prototype.getMinZoom = function getMinZoom() {
              return this.transform.minZoom;
            };
            Map3.prototype.setMaxZoom = function setMaxZoom(maxZoom) {
              maxZoom = maxZoom === null || maxZoom === void 0 ? defaultMaxZoom : maxZoom;
              if (maxZoom >= this.transform.minZoom) {
                this.transform.maxZoom = maxZoom;
                this._update();
                if (this.getZoom() > maxZoom) {
                  this.setZoom(maxZoom);
                }
                return this;
              } else {
                throw new Error("maxZoom must be greater than the current minZoom");
              }
            };
            Map3.prototype.getMaxZoom = function getMaxZoom() {
              return this.transform.maxZoom;
            };
            Map3.prototype.setMinPitch = function setMinPitch(minPitch) {
              minPitch = minPitch === null || minPitch === void 0 ? defaultMinPitch : minPitch;
              if (minPitch < defaultMinPitch) {
                throw new Error("minPitch must be greater than or equal to " + defaultMinPitch);
              }
              if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) {
                this.transform.minPitch = minPitch;
                this._update();
                if (this.getPitch() < minPitch) {
                  this.setPitch(minPitch);
                }
                return this;
              } else {
                throw new Error("minPitch must be between " + defaultMinPitch + " and the current maxPitch, inclusive");
              }
            };
            Map3.prototype.getMinPitch = function getMinPitch() {
              return this.transform.minPitch;
            };
            Map3.prototype.setMaxPitch = function setMaxPitch(maxPitch) {
              maxPitch = maxPitch === null || maxPitch === void 0 ? defaultMaxPitch : maxPitch;
              if (maxPitch > defaultMaxPitch) {
                throw new Error("maxPitch must be less than or equal to " + defaultMaxPitch);
              }
              if (maxPitch >= this.transform.minPitch) {
                this.transform.maxPitch = maxPitch;
                this._update();
                if (this.getPitch() > maxPitch) {
                  this.setPitch(maxPitch);
                }
                return this;
              } else {
                throw new Error("maxPitch must be greater than the current minPitch");
              }
            };
            Map3.prototype.getMaxPitch = function getMaxPitch() {
              return this.transform.maxPitch;
            };
            Map3.prototype.getRenderWorldCopies = function getRenderWorldCopies() {
              return this.transform.renderWorldCopies;
            };
            Map3.prototype.setRenderWorldCopies = function setRenderWorldCopies(renderWorldCopies) {
              this.transform.renderWorldCopies = renderWorldCopies;
              return this._update();
            };
            Map3.prototype.project = function project2(lnglat) {
              return this.transform.locationPoint(performance2.LngLat.convert(lnglat));
            };
            Map3.prototype.unproject = function unproject(point) {
              return this.transform.pointLocation(performance2.Point.convert(point));
            };
            Map3.prototype.isMoving = function isMoving2() {
              return this._moving || this.handlers.isMoving();
            };
            Map3.prototype.isZooming = function isZooming() {
              return this._zooming || this.handlers.isZooming();
            };
            Map3.prototype.isRotating = function isRotating() {
              return this._rotating || this.handlers.isRotating();
            };
            Map3.prototype._createDelegatedListener = function _createDelegatedListener(type, layerId, listener) {
              var this$1 = this;
              var obj;
              if (type === "mouseenter" || type === "mouseover") {
                var mousein = false;
                var mousemove = function(e) {
                  var features = this$1.getLayer(layerId) ? this$1.queryRenderedFeatures(e.point, { layers: [layerId] }) : [];
                  if (!features.length) {
                    mousein = false;
                  } else if (!mousein) {
                    mousein = true;
                    listener.call(this$1, new MapMouseEvent(type, this$1, e.originalEvent, { features }));
                  }
                };
                var mouseout = function() {
                  mousein = false;
                };
                return {
                  layer: layerId,
                  listener,
                  delegates: {
                    mousemove,
                    mouseout
                  }
                };
              } else if (type === "mouseleave" || type === "mouseout") {
                var mousein$1 = false;
                var mousemove$1 = function(e) {
                  var features = this$1.getLayer(layerId) ? this$1.queryRenderedFeatures(e.point, { layers: [layerId] }) : [];
                  if (features.length) {
                    mousein$1 = true;
                  } else if (mousein$1) {
                    mousein$1 = false;
                    listener.call(this$1, new MapMouseEvent(type, this$1, e.originalEvent));
                  }
                };
                var mouseout$1 = function(e) {
                  if (mousein$1) {
                    mousein$1 = false;
                    listener.call(this$1, new MapMouseEvent(type, this$1, e.originalEvent));
                  }
                };
                return {
                  layer: layerId,
                  listener,
                  delegates: {
                    mousemove: mousemove$1,
                    mouseout: mouseout$1
                  }
                };
              } else {
                var delegate = function(e) {
                  var features = this$1.getLayer(layerId) ? this$1.queryRenderedFeatures(e.point, { layers: [layerId] }) : [];
                  if (features.length) {
                    e.features = features;
                    listener.call(this$1, e);
                    delete e.features;
                  }
                };
                return {
                  layer: layerId,
                  listener,
                  delegates: (obj = {}, obj[type] = delegate, obj)
                };
              }
            };
            Map3.prototype.on = function on(type, layerId, listener) {
              if (listener === void 0) {
                return Camera2.prototype.on.call(this, type, layerId);
              }
              var delegatedListener = this._createDelegatedListener(type, layerId, listener);
              this._delegatedListeners = this._delegatedListeners || {};
              this._delegatedListeners[type] = this._delegatedListeners[type] || [];
              this._delegatedListeners[type].push(delegatedListener);
              for (var event in delegatedListener.delegates) {
                this.on(event, delegatedListener.delegates[event]);
              }
              return this;
            };
            Map3.prototype.once = function once(type, layerId, listener) {
              if (listener === void 0) {
                return Camera2.prototype.once.call(this, type, layerId);
              }
              var delegatedListener = this._createDelegatedListener(type, layerId, listener);
              for (var event in delegatedListener.delegates) {
                this.once(event, delegatedListener.delegates[event]);
              }
              return this;
            };
            Map3.prototype.off = function off(type, layerId, listener) {
              var this$1 = this;
              if (listener === void 0) {
                return Camera2.prototype.off.call(this, type, layerId);
              }
              var removeDelegatedListener = function(delegatedListeners) {
                var listeners = delegatedListeners[type];
                for (var i = 0; i < listeners.length; i++) {
                  var delegatedListener = listeners[i];
                  if (delegatedListener.layer === layerId && delegatedListener.listener === listener) {
                    for (var event in delegatedListener.delegates) {
                      this$1.off(event, delegatedListener.delegates[event]);
                    }
                    listeners.splice(i, 1);
                    return this$1;
                  }
                }
              };
              if (this._delegatedListeners && this._delegatedListeners[type]) {
                removeDelegatedListener(this._delegatedListeners);
              }
              return this;
            };
            Map3.prototype.queryRenderedFeatures = function queryRenderedFeatures2(geometry, options) {
              if (!this.style) {
                return [];
              }
              if (options === void 0 && geometry !== void 0 && !(geometry instanceof performance2.Point) && !Array.isArray(geometry)) {
                options = geometry;
                geometry = void 0;
              }
              options = options || {};
              geometry = geometry || [
                [
                  0,
                  0
                ],
                [
                  this.transform.width,
                  this.transform.height
                ]
              ];
              var queryGeometry;
              if (geometry instanceof performance2.Point || typeof geometry[0] === "number") {
                queryGeometry = [performance2.Point.convert(geometry)];
              } else {
                var tl = performance2.Point.convert(geometry[0]);
                var br = performance2.Point.convert(geometry[1]);
                queryGeometry = [
                  tl,
                  new performance2.Point(br.x, tl.y),
                  br,
                  new performance2.Point(tl.x, br.y),
                  tl
                ];
              }
              return this.style.queryRenderedFeatures(queryGeometry, options, this.transform);
            };
            Map3.prototype.querySourceFeatures = function querySourceFeatures2(sourceId, parameters) {
              return this.style.querySourceFeatures(sourceId, parameters);
            };
            Map3.prototype.setStyle = function setStyle(style, options) {
              options = performance2.extend({}, { localIdeographFontFamily: this._localIdeographFontFamily }, options);
              if (options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily && this.style && style) {
                this._diffStyle(style, options);
                return this;
              } else {
                this._localIdeographFontFamily = options.localIdeographFontFamily;
                return this._updateStyle(style, options);
              }
            };
            Map3.prototype._getUIString = function _getUIString(key) {
              var str = this._locale[key];
              if (str == null) {
                throw new Error("Missing UI string '" + key + "'");
              }
              return str;
            };
            Map3.prototype._updateStyle = function _updateStyle(style, options) {
              if (this.style) {
                this.style.setEventedParent(null);
                this.style._remove();
              }
              if (!style) {
                delete this.style;
                return this;
              } else {
                this.style = new Style(this, options || {});
              }
              this.style.setEventedParent(this, { style: this.style });
              if (typeof style === "string") {
                this.style.loadURL(style);
              } else {
                this.style.loadJSON(style);
              }
              return this;
            };
            Map3.prototype._lazyInitEmptyStyle = function _lazyInitEmptyStyle() {
              if (!this.style) {
                this.style = new Style(this, {});
                this.style.setEventedParent(this, { style: this.style });
                this.style.loadEmpty();
              }
            };
            Map3.prototype._diffStyle = function _diffStyle(style, options) {
              var this$1 = this;
              if (typeof style === "string") {
                var url = this._requestManager.normalizeStyleURL(style);
                var request = this._requestManager.transformRequest(url, performance2.ResourceType.Style);
                performance2.getJSON(request, function(error, json) {
                  if (error) {
                    this$1.fire(new performance2.ErrorEvent(error));
                  } else if (json) {
                    this$1._updateDiff(json, options);
                  }
                });
              } else if (typeof style === "object") {
                this._updateDiff(style, options);
              }
            };
            Map3.prototype._updateDiff = function _updateDiff(style, options) {
              try {
                if (this.style.setState(style)) {
                  this._update(true);
                }
              } catch (e) {
                performance2.warnOnce("Unable to perform style diff: " + (e.message || e.error || e) + ".  Rebuilding the style from scratch.");
                this._updateStyle(style, options);
              }
            };
            Map3.prototype.getStyle = function getStyle() {
              if (this.style) {
                return this.style.serialize();
              }
            };
            Map3.prototype.isStyleLoaded = function isStyleLoaded() {
              if (!this.style) {
                return performance2.warnOnce("There is no style added to the map.");
              }
              return this.style.loaded();
            };
            Map3.prototype.addSource = function addSource2(id, source) {
              this._lazyInitEmptyStyle();
              this.style.addSource(id, source);
              return this._update(true);
            };
            Map3.prototype.isSourceLoaded = function isSourceLoaded(id) {
              var source = this.style && this.style.sourceCaches[id];
              if (source === void 0) {
                this.fire(new performance2.ErrorEvent(new Error("There is no source with ID '" + id + "'")));
                return;
              }
              return source.loaded();
            };
            Map3.prototype.areTilesLoaded = function areTilesLoaded() {
              var sources = this.style && this.style.sourceCaches;
              for (var id in sources) {
                var source = sources[id];
                var tiles = source._tiles;
                for (var t in tiles) {
                  var tile = tiles[t];
                  if (!(tile.state === "loaded" || tile.state === "errored")) {
                    return false;
                  }
                }
              }
              return true;
            };
            Map3.prototype.addSourceType = function addSourceType(name2, SourceType, callback) {
              this._lazyInitEmptyStyle();
              return this.style.addSourceType(name2, SourceType, callback);
            };
            Map3.prototype.removeSource = function removeSource2(id) {
              this.style.removeSource(id);
              return this._update(true);
            };
            Map3.prototype.getSource = function getSource(id) {
              return this.style.getSource(id);
            };
            Map3.prototype.addImage = function addImage(id, image, ref) {
              if (ref === void 0)
                ref = {};
              var pixelRatio = ref.pixelRatio;
              if (pixelRatio === void 0)
                pixelRatio = 1;
              var sdf = ref.sdf;
              if (sdf === void 0)
                sdf = false;
              var stretchX = ref.stretchX;
              var stretchY = ref.stretchY;
              var content = ref.content;
              this._lazyInitEmptyStyle();
              var version = 0;
              if (image instanceof HTMLImageElement2 || ImageBitmap2 && image instanceof ImageBitmap2) {
                var ref$1 = performance2.browser.getImageData(image);
                var width = ref$1.width;
                var height = ref$1.height;
                var data = ref$1.data;
                this.style.addImage(id, {
                  data: new performance2.RGBAImage({
                    width,
                    height
                  }, data),
                  pixelRatio,
                  stretchX,
                  stretchY,
                  content,
                  sdf,
                  version
                });
              } else if (image.width === void 0 || image.height === void 0) {
                return this.fire(new performance2.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));
              } else {
                var width$1 = image.width;
                var height$1 = image.height;
                var data$1 = image.data;
                var userImage = image;
                this.style.addImage(id, {
                  data: new performance2.RGBAImage({
                    width: width$1,
                    height: height$1
                  }, new Uint8Array(data$1)),
                  pixelRatio,
                  stretchX,
                  stretchY,
                  content,
                  sdf,
                  version,
                  userImage
                });
                if (userImage.onAdd) {
                  userImage.onAdd(this, id);
                }
              }
            };
            Map3.prototype.updateImage = function updateImage(id, image) {
              var existingImage = this.style.getImage(id);
              if (!existingImage) {
                return this.fire(new performance2.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));
              }
              var imageData = image instanceof HTMLImageElement2 || ImageBitmap2 && image instanceof ImageBitmap2 ? performance2.browser.getImageData(image) : image;
              var width = imageData.width;
              var height = imageData.height;
              var data = imageData.data;
              if (width === void 0 || height === void 0) {
                return this.fire(new performance2.ErrorEvent(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));
              }
              if (width !== existingImage.data.width || height !== existingImage.data.height) {
                return this.fire(new performance2.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image")));
              }
              var copy = !(image instanceof HTMLImageElement2 || ImageBitmap2 && image instanceof ImageBitmap2);
              existingImage.data.replace(data, copy);
              this.style.updateImage(id, existingImage);
            };
            Map3.prototype.hasImage = function hasImage(id) {
              if (!id) {
                this.fire(new performance2.ErrorEvent(new Error("Missing required image id")));
                return false;
              }
              return !!this.style.getImage(id);
            };
            Map3.prototype.removeImage = function removeImage(id) {
              this.style.removeImage(id);
            };
            Map3.prototype.loadImage = function loadImage(url, callback) {
              performance2.getImage(this._requestManager.transformRequest(url, performance2.ResourceType.Image), callback);
            };
            Map3.prototype.listImages = function listImages() {
              return this.style.listImages();
            };
            Map3.prototype.addLayer = function addLayer(layer, beforeId) {
              this._lazyInitEmptyStyle();
              this.style.addLayer(layer, beforeId);
              return this._update(true);
            };
            Map3.prototype.moveLayer = function moveLayer(id, beforeId) {
              this.style.moveLayer(id, beforeId);
              return this._update(true);
            };
            Map3.prototype.removeLayer = function removeLayer(id) {
              this.style.removeLayer(id);
              return this._update(true);
            };
            Map3.prototype.getLayer = function getLayer(id) {
              return this.style.getLayer(id);
            };
            Map3.prototype.setLayerZoomRange = function setLayerZoomRange(layerId, minzoom, maxzoom) {
              this.style.setLayerZoomRange(layerId, minzoom, maxzoom);
              return this._update(true);
            };
            Map3.prototype.setFilter = function setFilter(layerId, filter, options) {
              if (options === void 0)
                options = {};
              this.style.setFilter(layerId, filter, options);
              return this._update(true);
            };
            Map3.prototype.getFilter = function getFilter(layerId) {
              return this.style.getFilter(layerId);
            };
            Map3.prototype.setPaintProperty = function setPaintProperty(layerId, name2, value, options) {
              if (options === void 0)
                options = {};
              this.style.setPaintProperty(layerId, name2, value, options);
              return this._update(true);
            };
            Map3.prototype.getPaintProperty = function getPaintProperty(layerId, name2) {
              return this.style.getPaintProperty(layerId, name2);
            };
            Map3.prototype.setLayoutProperty = function setLayoutProperty(layerId, name2, value, options) {
              if (options === void 0)
                options = {};
              this.style.setLayoutProperty(layerId, name2, value, options);
              return this._update(true);
            };
            Map3.prototype.getLayoutProperty = function getLayoutProperty(layerId, name2) {
              return this.style.getLayoutProperty(layerId, name2);
            };
            Map3.prototype.setLight = function setLight(light, options) {
              if (options === void 0)
                options = {};
              this._lazyInitEmptyStyle();
              this.style.setLight(light, options);
              return this._update(true);
            };
            Map3.prototype.getLight = function getLight() {
              return this.style.getLight();
            };
            Map3.prototype.setFeatureState = function setFeatureState(feature, state) {
              this.style.setFeatureState(feature, state);
              return this._update();
            };
            Map3.prototype.removeFeatureState = function removeFeatureState(target, key) {
              this.style.removeFeatureState(target, key);
              return this._update();
            };
            Map3.prototype.getFeatureState = function getFeatureState(feature) {
              return this.style.getFeatureState(feature);
            };
            Map3.prototype.getContainer = function getContainer() {
              return this._container;
            };
            Map3.prototype.getCanvasContainer = function getCanvasContainer() {
              return this._canvasContainer;
            };
            Map3.prototype.getCanvas = function getCanvas() {
              return this._canvas;
            };
            Map3.prototype._containerDimensions = function _containerDimensions() {
              var width = 0;
              var height = 0;
              if (this._container) {
                width = this._container.clientWidth || 400;
                height = this._container.clientHeight || 300;
              }
              return [
                width,
                height
              ];
            };
            Map3.prototype._detectMissingCSS = function _detectMissingCSS() {
              var computedColor = performance2.window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color");
              if (computedColor !== "rgb(250, 128, 114)") {
                performance2.warnOnce("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.");
              }
            };
            Map3.prototype._setupContainer = function _setupContainer() {
              var container = this._container;
              container.classList.add("mapboxgl-map");
              var missingCSSCanary = this._missingCSSCanary = DOM.create("div", "mapboxgl-canary", container);
              missingCSSCanary.style.visibility = "hidden";
              this._detectMissingCSS();
              var canvasContainer = this._canvasContainer = DOM.create("div", "mapboxgl-canvas-container", container);
              if (this._interactive) {
                canvasContainer.classList.add("mapboxgl-interactive");
              }
              this._canvas = DOM.create("canvas", "mapboxgl-canvas", canvasContainer);
              this._canvas.addEventListener("webglcontextlost", this._contextLost, false);
              this._canvas.addEventListener("webglcontextrestored", this._contextRestored, false);
              this._canvas.setAttribute("tabindex", "0");
              this._canvas.setAttribute("aria-label", "Map");
              this._canvas.setAttribute("role", "region");
              var dimensions = this._containerDimensions();
              this._resizeCanvas(dimensions[0], dimensions[1]);
              var controlContainer = this._controlContainer = DOM.create("div", "mapboxgl-control-container", container);
              var positions = this._controlPositions = {};
              [
                "top-left",
                "top-right",
                "bottom-left",
                "bottom-right"
              ].forEach(function(positionName) {
                positions[positionName] = DOM.create("div", "mapboxgl-ctrl-" + positionName, controlContainer);
              });
              this._container.addEventListener("scroll", this._onMapScroll, false);
            };
            Map3.prototype._resizeCanvas = function _resizeCanvas(width, height) {
              var pixelRatio = performance2.browser.devicePixelRatio || 1;
              this._canvas.width = pixelRatio * width;
              this._canvas.height = pixelRatio * height;
              this._canvas.style.width = width + "px";
              this._canvas.style.height = height + "px";
            };
            Map3.prototype._setupPainter = function _setupPainter() {
              var attributes = performance2.extend({}, mapboxGlSupported.webGLContextAttributes, {
                failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,
                preserveDrawingBuffer: this._preserveDrawingBuffer,
                antialias: this._antialias || false
              });
              var gl2 = this._canvas.getContext("webgl", attributes) || this._canvas.getContext("experimental-webgl", attributes);
              if (!gl2) {
                this.fire(new performance2.ErrorEvent(new Error("Failed to initialize WebGL")));
                return;
              }
              this.painter = new Painter(gl2, this.transform);
              performance2.webpSupported.testSupport(gl2);
            };
            Map3.prototype._contextLost = function _contextLost(event) {
              event.preventDefault();
              if (this._frame) {
                this._frame.cancel();
                this._frame = null;
              }
              this.fire(new performance2.Event("webglcontextlost", { originalEvent: event }));
            };
            Map3.prototype._contextRestored = function _contextRestored(event) {
              this._setupPainter();
              this.resize();
              this._update();
              this.fire(new performance2.Event("webglcontextrestored", { originalEvent: event }));
            };
            Map3.prototype._onMapScroll = function _onMapScroll(event) {
              if (event.target !== this._container) {
                return;
              }
              this._container.scrollTop = 0;
              this._container.scrollLeft = 0;
              return false;
            };
            Map3.prototype.loaded = function loaded() {
              return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();
            };
            Map3.prototype._update = function _update(updateStyle) {
              if (!this.style) {
                return this;
              }
              this._styleDirty = this._styleDirty || updateStyle;
              this._sourcesDirty = true;
              this.triggerRepaint();
              return this;
            };
            Map3.prototype._requestRenderFrame = function _requestRenderFrame(callback) {
              this._update();
              return this._renderTaskQueue.add(callback);
            };
            Map3.prototype._cancelRenderFrame = function _cancelRenderFrame(id) {
              this._renderTaskQueue.remove(id);
            };
            Map3.prototype._render = function _render(paintStartTimeStamp) {
              var this$1 = this;
              var gpuTimer, frameStartTime = 0;
              var extTimerQuery = this.painter.context.extTimerQuery;
              if (this.listens("gpu-timing-frame")) {
                gpuTimer = extTimerQuery.createQueryEXT();
                extTimerQuery.beginQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);
                frameStartTime = performance2.browser.now();
              }
              this.painter.context.setDirty();
              this.painter.setBaseState();
              this._renderTaskQueue.run(paintStartTimeStamp);
              if (this._removed) {
                return;
              }
              var crossFading = false;
              if (this.style && this._styleDirty) {
                this._styleDirty = false;
                var zoom = this.transform.zoom;
                var now = performance2.browser.now();
                this.style.zoomHistory.update(zoom, now);
                var parameters = new performance2.EvaluationParameters(zoom, {
                  now,
                  fadeDuration: this._fadeDuration,
                  zoomHistory: this.style.zoomHistory,
                  transition: this.style.getTransition()
                });
                var factor = parameters.crossFadingFactor();
                if (factor !== 1 || factor !== this._crossFadingFactor) {
                  crossFading = true;
                  this._crossFadingFactor = factor;
                }
                this.style.update(parameters);
              }
              if (this.style && this._sourcesDirty) {
                this._sourcesDirty = false;
                this.style._updateSources(this.transform);
              }
              this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, this._fadeDuration, this._crossSourceCollisions);
              this.painter.render(this.style, {
                showTileBoundaries: this.showTileBoundaries,
                showOverdrawInspector: this._showOverdrawInspector,
                rotating: this.isRotating(),
                zooming: this.isZooming(),
                moving: this.isMoving(),
                fadeDuration: this._fadeDuration,
                showPadding: this.showPadding,
                gpuTiming: !!this.listens("gpu-timing-layer")
              });
              this.fire(new performance2.Event("render"));
              if (this.loaded() && !this._loaded) {
                this._loaded = true;
                this.fire(new performance2.Event("load"));
              }
              if (this.style && (this.style.hasTransitions() || crossFading)) {
                this._styleDirty = true;
              }
              if (this.style && !this._placementDirty) {
                this.style._releaseSymbolFadeTiles();
              }
              if (this.listens("gpu-timing-frame")) {
                var renderCPUTime = performance2.browser.now() - frameStartTime;
                extTimerQuery.endQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);
                setTimeout(function() {
                  var renderGPUTime = extTimerQuery.getQueryObjectEXT(gpuTimer, extTimerQuery.QUERY_RESULT_EXT) / (1e3 * 1e3);
                  extTimerQuery.deleteQueryEXT(gpuTimer);
                  this$1.fire(new performance2.Event("gpu-timing-frame", {
                    cpuTime: renderCPUTime,
                    gpuTime: renderGPUTime
                  }));
                }, 50);
              }
              if (this.listens("gpu-timing-layer")) {
                var frameLayerQueries = this.painter.collectGpuTimers();
                setTimeout(function() {
                  var renderedLayerTimes = this$1.painter.queryGpuTimers(frameLayerQueries);
                  this$1.fire(new performance2.Event("gpu-timing-layer", { layerTimes: renderedLayerTimes }));
                }, 50);
              }
              var somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty;
              if (somethingDirty || this._repaint) {
                this.triggerRepaint();
              } else if (!this.isMoving() && this.loaded()) {
                this.fire(new performance2.Event("idle"));
              }
              if (this._loaded && !this._fullyLoaded && !somethingDirty) {
                this._fullyLoaded = true;
              }
              return this;
            };
            Map3.prototype.remove = function remove() {
              if (this._hash) {
                this._hash.remove();
              }
              for (var i = 0, list = this._controls; i < list.length; i += 1) {
                var control = list[i];
                control.onRemove(this);
              }
              this._controls = [];
              if (this._frame) {
                this._frame.cancel();
                this._frame = null;
              }
              this._renderTaskQueue.clear();
              this.painter.destroy();
              this.handlers.destroy();
              delete this.handlers;
              this.setStyle(null);
              if (typeof performance2.window !== "undefined") {
                performance2.window.removeEventListener("resize", this._onWindowResize, false);
                performance2.window.removeEventListener("orientationchange", this._onWindowResize, false);
                performance2.window.removeEventListener("online", this._onWindowOnline, false);
              }
              var extension = this.painter.context.gl.getExtension("WEBGL_lose_context");
              if (extension && extension.loseContext) {
                extension.loseContext();
              }
              removeNode(this._canvasContainer);
              removeNode(this._controlContainer);
              removeNode(this._missingCSSCanary);
              this._container.classList.remove("mapboxgl-map");
              this._removed = true;
              this.fire(new performance2.Event("remove"));
            };
            Map3.prototype.triggerRepaint = function triggerRepaint() {
              var this$1 = this;
              if (this.style && !this._frame) {
                this._frame = performance2.browser.frame(function(paintStartTimeStamp) {
                  this$1._frame = null;
                  this$1._render(paintStartTimeStamp);
                });
              }
            };
            Map3.prototype._onWindowOnline = function _onWindowOnline() {
              this._update();
            };
            Map3.prototype._onWindowResize = function _onWindowResize(event) {
              if (this._trackResize) {
                this.resize({ originalEvent: event })._update();
              }
            };
            prototypeAccessors2.showTileBoundaries.get = function() {
              return !!this._showTileBoundaries;
            };
            prototypeAccessors2.showTileBoundaries.set = function(value) {
              if (this._showTileBoundaries === value) {
                return;
              }
              this._showTileBoundaries = value;
              this._update();
            };
            prototypeAccessors2.showPadding.get = function() {
              return !!this._showPadding;
            };
            prototypeAccessors2.showPadding.set = function(value) {
              if (this._showPadding === value) {
                return;
              }
              this._showPadding = value;
              this._update();
            };
            prototypeAccessors2.showCollisionBoxes.get = function() {
              return !!this._showCollisionBoxes;
            };
            prototypeAccessors2.showCollisionBoxes.set = function(value) {
              if (this._showCollisionBoxes === value) {
                return;
              }
              this._showCollisionBoxes = value;
              if (value) {
                this.style._generateCollisionBoxes();
              } else {
                this._update();
              }
            };
            prototypeAccessors2.showOverdrawInspector.get = function() {
              return !!this._showOverdrawInspector;
            };
            prototypeAccessors2.showOverdrawInspector.set = function(value) {
              if (this._showOverdrawInspector === value) {
                return;
              }
              this._showOverdrawInspector = value;
              this._update();
            };
            prototypeAccessors2.repaint.get = function() {
              return !!this._repaint;
            };
            prototypeAccessors2.repaint.set = function(value) {
              if (this._repaint !== value) {
                this._repaint = value;
                this.triggerRepaint();
              }
            };
            prototypeAccessors2.vertices.get = function() {
              return !!this._vertices;
            };
            prototypeAccessors2.vertices.set = function(value) {
              this._vertices = value;
              this._update();
            };
            Map3.prototype._setCacheLimits = function _setCacheLimits(limit, checkThreshold) {
              performance2.setCacheLimits(limit, checkThreshold);
            };
            prototypeAccessors2.version.get = function() {
              return performance2.version;
            };
            Object.defineProperties(Map3.prototype, prototypeAccessors2);
            return Map3;
          }(Camera);
          function removeNode(node) {
            if (node.parentNode) {
              node.parentNode.removeChild(node);
            }
          }
          var defaultOptions$2 = {
            showCompass: true,
            showZoom: true,
            visualizePitch: false
          };
          var NavigationControl = function NavigationControl2(options) {
            var this$1 = this;
            this.options = performance2.extend({}, defaultOptions$2, options);
            this._container = DOM.create("div", "mapboxgl-ctrl mapboxgl-ctrl-group");
            this._container.addEventListener("contextmenu", function(e) {
              return e.preventDefault();
            });
            if (this.options.showZoom) {
              performance2.bindAll([
                "_setButtonTitle",
                "_updateZoomButtons"
              ], this);
              this._zoomInButton = this._createButton("mapboxgl-ctrl-zoom-in", function(e) {
                return this$1._map.zoomIn({}, { originalEvent: e });
              });
              DOM.create("span", "mapboxgl-ctrl-icon", this._zoomInButton).setAttribute("aria-hidden", true);
              this._zoomOutButton = this._createButton("mapboxgl-ctrl-zoom-out", function(e) {
                return this$1._map.zoomOut({}, { originalEvent: e });
              });
              DOM.create("span", "mapboxgl-ctrl-icon", this._zoomOutButton).setAttribute("aria-hidden", true);
            }
            if (this.options.showCompass) {
              performance2.bindAll(["_rotateCompassArrow"], this);
              this._compass = this._createButton("mapboxgl-ctrl-compass", function(e) {
                if (this$1.options.visualizePitch) {
                  this$1._map.resetNorthPitch({}, { originalEvent: e });
                } else {
                  this$1._map.resetNorth({}, { originalEvent: e });
                }
              });
              this._compassIcon = DOM.create("span", "mapboxgl-ctrl-icon", this._compass);
              this._compassIcon.setAttribute("aria-hidden", true);
            }
          };
          NavigationControl.prototype._updateZoomButtons = function _updateZoomButtons() {
            var zoom = this._map.getZoom();
            var isMax = zoom === this._map.getMaxZoom();
            var isMin = zoom === this._map.getMinZoom();
            this._zoomInButton.disabled = isMax;
            this._zoomOutButton.disabled = isMin;
            this._zoomInButton.setAttribute("aria-disabled", isMax.toString());
            this._zoomOutButton.setAttribute("aria-disabled", isMin.toString());
          };
          NavigationControl.prototype._rotateCompassArrow = function _rotateCompassArrow() {
            var rotate = this.options.visualizePitch ? "scale(" + 1 / Math.pow(Math.cos(this._map.transform.pitch * (Math.PI / 180)), 0.5) + ") rotateX(" + this._map.transform.pitch + "deg) rotateZ(" + this._map.transform.angle * (180 / Math.PI) + "deg)" : "rotate(" + this._map.transform.angle * (180 / Math.PI) + "deg)";
            this._compassIcon.style.transform = rotate;
          };
          NavigationControl.prototype.onAdd = function onAdd(map) {
            this._map = map;
            if (this.options.showZoom) {
              this._setButtonTitle(this._zoomInButton, "ZoomIn");
              this._setButtonTitle(this._zoomOutButton, "ZoomOut");
              this._map.on("zoom", this._updateZoomButtons);
              this._updateZoomButtons();
            }
            if (this.options.showCompass) {
              this._setButtonTitle(this._compass, "ResetBearing");
              if (this.options.visualizePitch) {
                this._map.on("pitch", this._rotateCompassArrow);
              }
              this._map.on("rotate", this._rotateCompassArrow);
              this._rotateCompassArrow();
              this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch);
            }
            return this._container;
          };
          NavigationControl.prototype.onRemove = function onRemove() {
            DOM.remove(this._container);
            if (this.options.showZoom) {
              this._map.off("zoom", this._updateZoomButtons);
            }
            if (this.options.showCompass) {
              if (this.options.visualizePitch) {
                this._map.off("pitch", this._rotateCompassArrow);
              }
              this._map.off("rotate", this._rotateCompassArrow);
              this._handler.off();
              delete this._handler;
            }
            delete this._map;
          };
          NavigationControl.prototype._createButton = function _createButton(className, fn) {
            var a = DOM.create("button", className, this._container);
            a.type = "button";
            a.addEventListener("click", fn);
            return a;
          };
          NavigationControl.prototype._setButtonTitle = function _setButtonTitle(button, title) {
            var str = this._map._getUIString("NavigationControl." + title);
            button.title = str;
            button.setAttribute("aria-label", str);
          };
          var MouseRotateWrapper = function MouseRotateWrapper2(map, element, pitch) {
            if (pitch === void 0)
              pitch = false;
            this._clickTolerance = 10;
            this.element = element;
            this.mouseRotate = new MouseRotateHandler({ clickTolerance: map.dragRotate._mouseRotate._clickTolerance });
            this.map = map;
            if (pitch) {
              this.mousePitch = new MousePitchHandler({ clickTolerance: map.dragRotate._mousePitch._clickTolerance });
            }
            performance2.bindAll([
              "mousedown",
              "mousemove",
              "mouseup",
              "touchstart",
              "touchmove",
              "touchend",
              "reset"
            ], this);
            DOM.addEventListener(element, "mousedown", this.mousedown);
            DOM.addEventListener(element, "touchstart", this.touchstart, { passive: false });
            DOM.addEventListener(element, "touchmove", this.touchmove);
            DOM.addEventListener(element, "touchend", this.touchend);
            DOM.addEventListener(element, "touchcancel", this.reset);
          };
          MouseRotateWrapper.prototype.down = function down(e, point) {
            this.mouseRotate.mousedown(e, point);
            if (this.mousePitch) {
              this.mousePitch.mousedown(e, point);
            }
            DOM.disableDrag();
          };
          MouseRotateWrapper.prototype.move = function move(e, point) {
            var map = this.map;
            var r = this.mouseRotate.mousemoveWindow(e, point);
            if (r && r.bearingDelta) {
              map.setBearing(map.getBearing() + r.bearingDelta);
            }
            if (this.mousePitch) {
              var p = this.mousePitch.mousemoveWindow(e, point);
              if (p && p.pitchDelta) {
                map.setPitch(map.getPitch() + p.pitchDelta);
              }
            }
          };
          MouseRotateWrapper.prototype.off = function off() {
            var element = this.element;
            DOM.removeEventListener(element, "mousedown", this.mousedown);
            DOM.removeEventListener(element, "touchstart", this.touchstart, { passive: false });
            DOM.removeEventListener(element, "touchmove", this.touchmove);
            DOM.removeEventListener(element, "touchend", this.touchend);
            DOM.removeEventListener(element, "touchcancel", this.reset);
            this.offTemp();
          };
          MouseRotateWrapper.prototype.offTemp = function offTemp() {
            DOM.enableDrag();
            DOM.removeEventListener(performance2.window, "mousemove", this.mousemove);
            DOM.removeEventListener(performance2.window, "mouseup", this.mouseup);
          };
          MouseRotateWrapper.prototype.mousedown = function mousedown(e) {
            this.down(performance2.extend({}, e, {
              ctrlKey: true,
              preventDefault: function() {
                return e.preventDefault();
              }
            }), DOM.mousePos(this.element, e));
            DOM.addEventListener(performance2.window, "mousemove", this.mousemove);
            DOM.addEventListener(performance2.window, "mouseup", this.mouseup);
          };
          MouseRotateWrapper.prototype.mousemove = function mousemove(e) {
            this.move(e, DOM.mousePos(this.element, e));
          };
          MouseRotateWrapper.prototype.mouseup = function mouseup(e) {
            this.mouseRotate.mouseupWindow(e);
            if (this.mousePitch) {
              this.mousePitch.mouseupWindow(e);
            }
            this.offTemp();
          };
          MouseRotateWrapper.prototype.touchstart = function touchstart(e) {
            if (e.targetTouches.length !== 1) {
              this.reset();
            } else {
              this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];
              this.down({
                type: "mousedown",
                button: 0,
                ctrlKey: true,
                preventDefault: function() {
                  return e.preventDefault();
                }
              }, this._startPos);
            }
          };
          MouseRotateWrapper.prototype.touchmove = function touchmove(e) {
            if (e.targetTouches.length !== 1) {
              this.reset();
            } else {
              this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];
              this.move({
                preventDefault: function() {
                  return e.preventDefault();
                }
              }, this._lastPos);
            }
          };
          MouseRotateWrapper.prototype.touchend = function touchend(e) {
            if (e.targetTouches.length === 0 && this._startPos && this._lastPos && this._startPos.dist(this._lastPos) < this._clickTolerance) {
              this.element.click();
            }
            this.reset();
          };
          MouseRotateWrapper.prototype.reset = function reset() {
            this.mouseRotate.reset();
            if (this.mousePitch) {
              this.mousePitch.reset();
            }
            delete this._startPos;
            delete this._lastPos;
            this.offTemp();
          };
          function smartWrap(lngLat, priorPos, transform) {
            lngLat = new performance2.LngLat(lngLat.lng, lngLat.lat);
            if (priorPos) {
              var left = new performance2.LngLat(lngLat.lng - 360, lngLat.lat);
              var right = new performance2.LngLat(lngLat.lng + 360, lngLat.lat);
              var delta = transform.locationPoint(lngLat).distSqr(priorPos);
              if (transform.locationPoint(left).distSqr(priorPos) < delta) {
                lngLat = left;
              } else if (transform.locationPoint(right).distSqr(priorPos) < delta) {
                lngLat = right;
              }
            }
            while (Math.abs(lngLat.lng - transform.center.lng) > 180) {
              var pos = transform.locationPoint(lngLat);
              if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) {
                break;
              }
              if (lngLat.lng > transform.center.lng) {
                lngLat.lng -= 360;
              } else {
                lngLat.lng += 360;
              }
            }
            return lngLat;
          }
          var anchorTranslate = {
            "center": "translate(-50%,-50%)",
            "top": "translate(-50%,0)",
            "top-left": "translate(0,0)",
            "top-right": "translate(-100%,0)",
            "bottom": "translate(-50%,-100%)",
            "bottom-left": "translate(0,-100%)",
            "bottom-right": "translate(-100%,-100%)",
            "left": "translate(0,-50%)",
            "right": "translate(-100%,-50%)"
          };
          function applyAnchorClass(element, anchor, prefix) {
            var classList = element.classList;
            for (var key in anchorTranslate) {
              classList.remove("mapboxgl-" + prefix + "-anchor-" + key);
            }
            classList.add("mapboxgl-" + prefix + "-anchor-" + anchor);
          }
          var Marker = function(Evented) {
            function Marker2(options, legacyOptions) {
              Evented.call(this);
              if (options instanceof performance2.window.HTMLElement || legacyOptions) {
                options = performance2.extend({ element: options }, legacyOptions);
              }
              performance2.bindAll([
                "_update",
                "_onMove",
                "_onUp",
                "_addDragHandler",
                "_onMapClick",
                "_onKeyPress"
              ], this);
              this._anchor = options && options.anchor || "center";
              this._color = options && options.color || "#3FB1CE";
              this._scale = options && options.scale || 1;
              this._draggable = options && options.draggable || false;
              this._clickTolerance = options && options.clickTolerance || 0;
              this._isDragging = false;
              this._state = "inactive";
              this._rotation = options && options.rotation || 0;
              this._rotationAlignment = options && options.rotationAlignment || "auto";
              this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== "auto" ? options.pitchAlignment : this._rotationAlignment;
              if (!options || !options.element) {
                this._defaultMarker = true;
                this._element = DOM.create("div");
                this._element.setAttribute("aria-label", "Map marker");
                var svg = DOM.createNS("http://www.w3.org/2000/svg", "svg");
                var defaultHeight = 41;
                var defaultWidth = 27;
                svg.setAttributeNS(null, "display", "block");
                svg.setAttributeNS(null, "height", defaultHeight + "px");
                svg.setAttributeNS(null, "width", defaultWidth + "px");
                svg.setAttributeNS(null, "viewBox", "0 0 " + defaultWidth + " " + defaultHeight);
                var markerLarge = DOM.createNS("http://www.w3.org/2000/svg", "g");
                markerLarge.setAttributeNS(null, "stroke", "none");
                markerLarge.setAttributeNS(null, "stroke-width", "1");
                markerLarge.setAttributeNS(null, "fill", "none");
                markerLarge.setAttributeNS(null, "fill-rule", "evenodd");
                var page1 = DOM.createNS("http://www.w3.org/2000/svg", "g");
                page1.setAttributeNS(null, "fill-rule", "nonzero");
                var shadow = DOM.createNS("http://www.w3.org/2000/svg", "g");
                shadow.setAttributeNS(null, "transform", "translate(3.0, 29.0)");
                shadow.setAttributeNS(null, "fill", "#000000");
                var ellipses = [
                  {
                    "rx": "10.5",
                    "ry": "5.25002273"
                  },
                  {
                    "rx": "10.5",
                    "ry": "5.25002273"
                  },
                  {
                    "rx": "9.5",
                    "ry": "4.77275007"
                  },
                  {
                    "rx": "8.5",
                    "ry": "4.29549936"
                  },
                  {
                    "rx": "7.5",
                    "ry": "3.81822308"
                  },
                  {
                    "rx": "6.5",
                    "ry": "3.34094679"
                  },
                  {
                    "rx": "5.5",
                    "ry": "2.86367051"
                  },
                  {
                    "rx": "4.5",
                    "ry": "2.38636864"
                  }
                ];
                for (var i = 0, list = ellipses; i < list.length; i += 1) {
                  var data = list[i];
                  var ellipse = DOM.createNS("http://www.w3.org/2000/svg", "ellipse");
                  ellipse.setAttributeNS(null, "opacity", "0.04");
                  ellipse.setAttributeNS(null, "cx", "10.5");
                  ellipse.setAttributeNS(null, "cy", "5.80029008");
                  ellipse.setAttributeNS(null, "rx", data["rx"]);
                  ellipse.setAttributeNS(null, "ry", data["ry"]);
                  shadow.appendChild(ellipse);
                }
                var background2 = DOM.createNS("http://www.w3.org/2000/svg", "g");
                background2.setAttributeNS(null, "fill", this._color);
                var bgPath = DOM.createNS("http://www.w3.org/2000/svg", "path");
                bgPath.setAttributeNS(null, "d", "M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z");
                background2.appendChild(bgPath);
                var border = DOM.createNS("http://www.w3.org/2000/svg", "g");
                border.setAttributeNS(null, "opacity", "0.25");
                border.setAttributeNS(null, "fill", "#000000");
                var borderPath = DOM.createNS("http://www.w3.org/2000/svg", "path");
                borderPath.setAttributeNS(null, "d", "M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z");
                border.appendChild(borderPath);
                var maki = DOM.createNS("http://www.w3.org/2000/svg", "g");
                maki.setAttributeNS(null, "transform", "translate(6.0, 7.0)");
                maki.setAttributeNS(null, "fill", "#FFFFFF");
                var circleContainer = DOM.createNS("http://www.w3.org/2000/svg", "g");
                circleContainer.setAttributeNS(null, "transform", "translate(8.0, 8.0)");
                var circle1 = DOM.createNS("http://www.w3.org/2000/svg", "circle");
                circle1.setAttributeNS(null, "fill", "#000000");
                circle1.setAttributeNS(null, "opacity", "0.25");
                circle1.setAttributeNS(null, "cx", "5.5");
                circle1.setAttributeNS(null, "cy", "5.5");
                circle1.setAttributeNS(null, "r", "5.4999962");
                var circle2 = DOM.createNS("http://www.w3.org/2000/svg", "circle");
                circle2.setAttributeNS(null, "fill", "#FFFFFF");
                circle2.setAttributeNS(null, "cx", "5.5");
                circle2.setAttributeNS(null, "cy", "5.5");
                circle2.setAttributeNS(null, "r", "5.4999962");
                circleContainer.appendChild(circle1);
                circleContainer.appendChild(circle2);
                page1.appendChild(shadow);
                page1.appendChild(background2);
                page1.appendChild(border);
                page1.appendChild(maki);
                page1.appendChild(circleContainer);
                svg.appendChild(page1);
                svg.setAttributeNS(null, "height", defaultHeight * this._scale + "px");
                svg.setAttributeNS(null, "width", defaultWidth * this._scale + "px");
                this._element.appendChild(svg);
                this._offset = performance2.Point.convert(options && options.offset || [
                  0,
                  -14
                ]);
              } else {
                this._element = options.element;
                this._offset = performance2.Point.convert(options && options.offset || [
                  0,
                  0
                ]);
              }
              this._element.classList.add("mapboxgl-marker");
              this._element.addEventListener("dragstart", function(e) {
                e.preventDefault();
              });
              this._element.addEventListener("mousedown", function(e) {
                e.preventDefault();
              });
              applyAnchorClass(this._element, this._anchor, "marker");
              this._popup = null;
            }
            if (Evented)
              Marker2.__proto__ = Evented;
            Marker2.prototype = Object.create(Evented && Evented.prototype);
            Marker2.prototype.constructor = Marker2;
            Marker2.prototype.addTo = function addTo(map) {
              this.remove();
              this._map = map;
              map.getCanvasContainer().appendChild(this._element);
              map.on("move", this._update);
              map.on("moveend", this._update);
              this.setDraggable(this._draggable);
              this._update();
              this._map.on("click", this._onMapClick);
              return this;
            };
            Marker2.prototype.remove = function remove() {
              if (this._map) {
                this._map.off("click", this._onMapClick);
                this._map.off("move", this._update);
                this._map.off("moveend", this._update);
                this._map.off("mousedown", this._addDragHandler);
                this._map.off("touchstart", this._addDragHandler);
                this._map.off("mouseup", this._onUp);
                this._map.off("touchend", this._onUp);
                this._map.off("mousemove", this._onMove);
                this._map.off("touchmove", this._onMove);
                delete this._map;
              }
              DOM.remove(this._element);
              if (this._popup) {
                this._popup.remove();
              }
              return this;
            };
            Marker2.prototype.getLngLat = function getLngLat() {
              return this._lngLat;
            };
            Marker2.prototype.setLngLat = function setLngLat(lnglat) {
              this._lngLat = performance2.LngLat.convert(lnglat);
              this._pos = null;
              if (this._popup) {
                this._popup.setLngLat(this._lngLat);
              }
              this._update();
              return this;
            };
            Marker2.prototype.getElement = function getElement() {
              return this._element;
            };
            Marker2.prototype.setPopup = function setPopup(popup) {
              if (this._popup) {
                this._popup.remove();
                this._popup = null;
                this._element.removeEventListener("keypress", this._onKeyPress);
                if (!this._originalTabIndex) {
                  this._element.removeAttribute("tabindex");
                }
              }
              if (popup) {
                if (!("offset" in popup.options)) {
                  var markerHeight = 41 - 5.8 / 2;
                  var markerRadius = 13.5;
                  var linearOffset = Math.sqrt(Math.pow(markerRadius, 2) / 2);
                  popup.options.offset = this._defaultMarker ? {
                    "top": [
                      0,
                      0
                    ],
                    "top-left": [
                      0,
                      0
                    ],
                    "top-right": [
                      0,
                      0
                    ],
                    "bottom": [
                      0,
                      -markerHeight
                    ],
                    "bottom-left": [
                      linearOffset,
                      (markerHeight - markerRadius + linearOffset) * -1
                    ],
                    "bottom-right": [
                      -linearOffset,
                      (markerHeight - markerRadius + linearOffset) * -1
                    ],
                    "left": [
                      markerRadius,
                      (markerHeight - markerRadius) * -1
                    ],
                    "right": [
                      -markerRadius,
                      (markerHeight - markerRadius) * -1
                    ]
                  } : this._offset;
                }
                this._popup = popup;
                if (this._lngLat) {
                  this._popup.setLngLat(this._lngLat);
                }
                this._originalTabIndex = this._element.getAttribute("tabindex");
                if (!this._originalTabIndex) {
                  this._element.setAttribute("tabindex", "0");
                }
                this._element.addEventListener("keypress", this._onKeyPress);
              }
              return this;
            };
            Marker2.prototype._onKeyPress = function _onKeyPress(e) {
              var code = e.code;
              var legacyCode = e.charCode || e.keyCode;
              if (code === "Space" || code === "Enter" || legacyCode === 32 || legacyCode === 13) {
                this.togglePopup();
              }
            };
            Marker2.prototype._onMapClick = function _onMapClick(e) {
              var targetElement = e.originalEvent.target;
              var element = this._element;
              if (this._popup && (targetElement === element || element.contains(targetElement))) {
                this.togglePopup();
              }
            };
            Marker2.prototype.getPopup = function getPopup() {
              return this._popup;
            };
            Marker2.prototype.togglePopup = function togglePopup() {
              var popup = this._popup;
              if (!popup) {
                return this;
              } else if (popup.isOpen()) {
                popup.remove();
              } else {
                popup.addTo(this._map);
              }
              return this;
            };
            Marker2.prototype._update = function _update(e) {
              if (!this._map) {
                return;
              }
              if (this._map.transform.renderWorldCopies) {
                this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform);
              }
              this._pos = this._map.project(this._lngLat)._add(this._offset);
              var rotation = "";
              if (this._rotationAlignment === "viewport" || this._rotationAlignment === "auto") {
                rotation = "rotateZ(" + this._rotation + "deg)";
              } else if (this._rotationAlignment === "map") {
                rotation = "rotateZ(" + (this._rotation - this._map.getBearing()) + "deg)";
              }
              var pitch = "";
              if (this._pitchAlignment === "viewport" || this._pitchAlignment === "auto") {
                pitch = "rotateX(0deg)";
              } else if (this._pitchAlignment === "map") {
                pitch = "rotateX(" + this._map.getPitch() + "deg)";
              }
              if (!e || e.type === "moveend") {
                this._pos = this._pos.round();
              }
              DOM.setTransform(this._element, anchorTranslate[this._anchor] + " translate(" + this._pos.x + "px, " + this._pos.y + "px) " + pitch + " " + rotation);
            };
            Marker2.prototype.getOffset = function getOffset() {
              return this._offset;
            };
            Marker2.prototype.setOffset = function setOffset(offset) {
              this._offset = performance2.Point.convert(offset);
              this._update();
              return this;
            };
            Marker2.prototype._onMove = function _onMove(e) {
              if (!this._isDragging) {
                var clickTolerance = this._clickTolerance || this._map._clickTolerance;
                this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance;
              }
              if (!this._isDragging) {
                return;
              }
              this._pos = e.point.sub(this._positionDelta);
              this._lngLat = this._map.unproject(this._pos);
              this.setLngLat(this._lngLat);
              this._element.style.pointerEvents = "none";
              if (this._state === "pending") {
                this._state = "active";
                this.fire(new performance2.Event("dragstart"));
              }
              this.fire(new performance2.Event("drag"));
            };
            Marker2.prototype._onUp = function _onUp() {
              this._element.style.pointerEvents = "auto";
              this._positionDelta = null;
              this._pointerdownPos = null;
              this._isDragging = false;
              this._map.off("mousemove", this._onMove);
              this._map.off("touchmove", this._onMove);
              if (this._state === "active") {
                this.fire(new performance2.Event("dragend"));
              }
              this._state = "inactive";
            };
            Marker2.prototype._addDragHandler = function _addDragHandler(e) {
              if (this._element.contains(e.originalEvent.target)) {
                e.preventDefault();
                this._positionDelta = e.point.sub(this._pos).add(this._offset);
                this._pointerdownPos = e.point;
                this._state = "pending";
                this._map.on("mousemove", this._onMove);
                this._map.on("touchmove", this._onMove);
                this._map.once("mouseup", this._onUp);
                this._map.once("touchend", this._onUp);
              }
            };
            Marker2.prototype.setDraggable = function setDraggable(shouldBeDraggable) {
              this._draggable = !!shouldBeDraggable;
              if (this._map) {
                if (shouldBeDraggable) {
                  this._map.on("mousedown", this._addDragHandler);
                  this._map.on("touchstart", this._addDragHandler);
                } else {
                  this._map.off("mousedown", this._addDragHandler);
                  this._map.off("touchstart", this._addDragHandler);
                }
              }
              return this;
            };
            Marker2.prototype.isDraggable = function isDraggable() {
              return this._draggable;
            };
            Marker2.prototype.setRotation = function setRotation(rotation) {
              this._rotation = rotation || 0;
              this._update();
              return this;
            };
            Marker2.prototype.getRotation = function getRotation() {
              return this._rotation;
            };
            Marker2.prototype.setRotationAlignment = function setRotationAlignment(alignment) {
              this._rotationAlignment = alignment || "auto";
              this._update();
              return this;
            };
            Marker2.prototype.getRotationAlignment = function getRotationAlignment() {
              return this._rotationAlignment;
            };
            Marker2.prototype.setPitchAlignment = function setPitchAlignment(alignment) {
              this._pitchAlignment = alignment && alignment !== "auto" ? alignment : this._rotationAlignment;
              this._update();
              return this;
            };
            Marker2.prototype.getPitchAlignment = function getPitchAlignment() {
              return this._pitchAlignment;
            };
            return Marker2;
          }(performance2.Evented);
          var defaultOptions$3 = {
            positionOptions: {
              enableHighAccuracy: false,
              maximumAge: 0,
              timeout: 6e3
            },
            fitBoundsOptions: { maxZoom: 15 },
            trackUserLocation: false,
            showAccuracyCircle: true,
            showUserLocation: true
          };
          var supportsGeolocation;
          function checkGeolocationSupport(callback) {
            if (supportsGeolocation !== void 0) {
              callback(supportsGeolocation);
            } else if (performance2.window.navigator.permissions !== void 0) {
              performance2.window.navigator.permissions.query({ name: "geolocation" }).then(function(p) {
                supportsGeolocation = p.state !== "denied";
                callback(supportsGeolocation);
              });
            } else {
              supportsGeolocation = !!performance2.window.navigator.geolocation;
              callback(supportsGeolocation);
            }
          }
          var numberOfWatches = 0;
          var noTimeout = false;
          var GeolocateControl = function(Evented) {
            function GeolocateControl2(options) {
              Evented.call(this);
              this.options = performance2.extend({}, defaultOptions$3, options);
              performance2.bindAll([
                "_onSuccess",
                "_onError",
                "_onZoom",
                "_finish",
                "_setupUI",
                "_updateCamera",
                "_updateMarker"
              ], this);
            }
            if (Evented)
              GeolocateControl2.__proto__ = Evented;
            GeolocateControl2.prototype = Object.create(Evented && Evented.prototype);
            GeolocateControl2.prototype.constructor = GeolocateControl2;
            GeolocateControl2.prototype.onAdd = function onAdd(map) {
              this._map = map;
              this._container = DOM.create("div", "mapboxgl-ctrl mapboxgl-ctrl-group");
              checkGeolocationSupport(this._setupUI);
              return this._container;
            };
            GeolocateControl2.prototype.onRemove = function onRemove() {
              if (this._geolocationWatchID !== void 0) {
                performance2.window.navigator.geolocation.clearWatch(this._geolocationWatchID);
                this._geolocationWatchID = void 0;
              }
              if (this.options.showUserLocation && this._userLocationDotMarker) {
                this._userLocationDotMarker.remove();
              }
              if (this.options.showAccuracyCircle && this._accuracyCircleMarker) {
                this._accuracyCircleMarker.remove();
              }
              DOM.remove(this._container);
              this._map.off("zoom", this._onZoom);
              this._map = void 0;
              numberOfWatches = 0;
              noTimeout = false;
            };
            GeolocateControl2.prototype._isOutOfMapMaxBounds = function _isOutOfMapMaxBounds(position) {
              var bounds = this._map.getMaxBounds();
              var coordinates = position.coords;
              return bounds && (coordinates.longitude < bounds.getWest() || coordinates.longitude > bounds.getEast() || coordinates.latitude < bounds.getSouth() || coordinates.latitude > bounds.getNorth());
            };
            GeolocateControl2.prototype._setErrorState = function _setErrorState() {
              switch (this._watchState) {
                case "WAITING_ACTIVE":
                  this._watchState = "ACTIVE_ERROR";
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active");
                  this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");
                  break;
                case "ACTIVE_LOCK":
                  this._watchState = "ACTIVE_ERROR";
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active");
                  this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");
                  this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");
                  break;
                case "BACKGROUND":
                  this._watchState = "BACKGROUND_ERROR";
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background");
                  this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");
                  this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");
                  break;
              }
            };
            GeolocateControl2.prototype._onSuccess = function _onSuccess(position) {
              if (!this._map) {
                return;
              }
              if (this._isOutOfMapMaxBounds(position)) {
                this._setErrorState();
                this.fire(new performance2.Event("outofmaxbounds", position));
                this._updateMarker();
                this._finish();
                return;
              }
              if (this.options.trackUserLocation) {
                this._lastKnownPosition = position;
                switch (this._watchState) {
                  case "WAITING_ACTIVE":
                  case "ACTIVE_LOCK":
                  case "ACTIVE_ERROR":
                    this._watchState = "ACTIVE_LOCK";
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting");
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error");
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");
                    break;
                  case "BACKGROUND":
                  case "BACKGROUND_ERROR":
                    this._watchState = "BACKGROUND";
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting");
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error");
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");
                    break;
                }
              }
              if (this.options.showUserLocation && this._watchState !== "OFF") {
                this._updateMarker(position);
              }
              if (!this.options.trackUserLocation || this._watchState === "ACTIVE_LOCK") {
                this._updateCamera(position);
              }
              if (this.options.showUserLocation) {
                this._dotElement.classList.remove("mapboxgl-user-location-dot-stale");
              }
              this.fire(new performance2.Event("geolocate", position));
              this._finish();
            };
            GeolocateControl2.prototype._updateCamera = function _updateCamera(position) {
              var center = new performance2.LngLat(position.coords.longitude, position.coords.latitude);
              var radius = position.coords.accuracy;
              var bearing = this._map.getBearing();
              var options = performance2.extend({ bearing }, this.options.fitBoundsOptions);
              this._map.fitBounds(center.toBounds(radius), options, { geolocateSource: true });
            };
            GeolocateControl2.prototype._updateMarker = function _updateMarker(position) {
              if (position) {
                var center = new performance2.LngLat(position.coords.longitude, position.coords.latitude);
                this._accuracyCircleMarker.setLngLat(center).addTo(this._map);
                this._userLocationDotMarker.setLngLat(center).addTo(this._map);
                this._accuracy = position.coords.accuracy;
                if (this.options.showUserLocation && this.options.showAccuracyCircle) {
                  this._updateCircleRadius();
                }
              } else {
                this._userLocationDotMarker.remove();
                this._accuracyCircleMarker.remove();
              }
            };
            GeolocateControl2.prototype._updateCircleRadius = function _updateCircleRadius() {
              var y = this._map._container.clientHeight / 2;
              var a = this._map.unproject([
                0,
                y
              ]);
              var b = this._map.unproject([
                1,
                y
              ]);
              var metersPerPixel = a.distanceTo(b);
              var circleDiameter = Math.ceil(2 * this._accuracy / metersPerPixel);
              this._circleElement.style.width = circleDiameter + "px";
              this._circleElement.style.height = circleDiameter + "px";
            };
            GeolocateControl2.prototype._onZoom = function _onZoom() {
              if (this.options.showUserLocation && this.options.showAccuracyCircle) {
                this._updateCircleRadius();
              }
            };
            GeolocateControl2.prototype._onError = function _onError(error) {
              if (!this._map) {
                return;
              }
              if (this.options.trackUserLocation) {
                if (error.code === 1) {
                  this._watchState = "OFF";
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting");
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active");
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error");
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background");
                  this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error");
                  this._geolocateButton.disabled = true;
                  var title = this._map._getUIString("GeolocateControl.LocationNotAvailable");
                  this._geolocateButton.title = title;
                  this._geolocateButton.setAttribute("aria-label", title);
                  if (this._geolocationWatchID !== void 0) {
                    this._clearWatch();
                  }
                } else if (error.code === 3 && noTimeout) {
                  return;
                } else {
                  this._setErrorState();
                }
              }
              if (this._watchState !== "OFF" && this.options.showUserLocation) {
                this._dotElement.classList.add("mapboxgl-user-location-dot-stale");
              }
              this.fire(new performance2.Event("error", error));
              this._finish();
            };
            GeolocateControl2.prototype._finish = function _finish() {
              if (this._timeoutId) {
                clearTimeout(this._timeoutId);
              }
              this._timeoutId = void 0;
            };
            GeolocateControl2.prototype._setupUI = function _setupUI(supported) {
              var this$1 = this;
              this._container.addEventListener("contextmenu", function(e) {
                return e.preventDefault();
              });
              this._geolocateButton = DOM.create("button", "mapboxgl-ctrl-geolocate", this._container);
              DOM.create("span", "mapboxgl-ctrl-icon", this._geolocateButton).setAttribute("aria-hidden", true);
              this._geolocateButton.type = "button";
              if (supported === false) {
                performance2.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");
                var title = this._map._getUIString("GeolocateControl.LocationNotAvailable");
                this._geolocateButton.disabled = true;
                this._geolocateButton.title = title;
                this._geolocateButton.setAttribute("aria-label", title);
              } else {
                var title$1 = this._map._getUIString("GeolocateControl.FindMyLocation");
                this._geolocateButton.title = title$1;
                this._geolocateButton.setAttribute("aria-label", title$1);
              }
              if (this.options.trackUserLocation) {
                this._geolocateButton.setAttribute("aria-pressed", "false");
                this._watchState = "OFF";
              }
              if (this.options.showUserLocation) {
                this._dotElement = DOM.create("div", "mapboxgl-user-location-dot");
                this._userLocationDotMarker = new Marker(this._dotElement);
                this._circleElement = DOM.create("div", "mapboxgl-user-location-accuracy-circle");
                this._accuracyCircleMarker = new Marker({
                  element: this._circleElement,
                  pitchAlignment: "map"
                });
                if (this.options.trackUserLocation) {
                  this._watchState = "OFF";
                }
                this._map.on("zoom", this._onZoom);
              }
              this._geolocateButton.addEventListener("click", this.trigger.bind(this));
              this._setup = true;
              if (this.options.trackUserLocation) {
                this._map.on("movestart", function(event) {
                  var fromResize = event.originalEvent && event.originalEvent.type === "resize";
                  if (!event.geolocateSource && this$1._watchState === "ACTIVE_LOCK" && !fromResize) {
                    this$1._watchState = "BACKGROUND";
                    this$1._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");
                    this$1._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active");
                    this$1.fire(new performance2.Event("trackuserlocationend"));
                  }
                });
              }
            };
            GeolocateControl2.prototype.trigger = function trigger() {
              if (!this._setup) {
                performance2.warnOnce("Geolocate control triggered before added to a map");
                return false;
              }
              if (this.options.trackUserLocation) {
                switch (this._watchState) {
                  case "OFF":
                    this._watchState = "WAITING_ACTIVE";
                    this.fire(new performance2.Event("trackuserlocationstart"));
                    break;
                  case "WAITING_ACTIVE":
                  case "ACTIVE_LOCK":
                  case "ACTIVE_ERROR":
                  case "BACKGROUND_ERROR":
                    numberOfWatches--;
                    noTimeout = false;
                    this._watchState = "OFF";
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting");
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active");
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error");
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background");
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error");
                    this.fire(new performance2.Event("trackuserlocationend"));
                    break;
                  case "BACKGROUND":
                    this._watchState = "ACTIVE_LOCK";
                    this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background");
                    if (this._lastKnownPosition) {
                      this._updateCamera(this._lastKnownPosition);
                    }
                    this.fire(new performance2.Event("trackuserlocationstart"));
                    break;
                }
                switch (this._watchState) {
                  case "WAITING_ACTIVE":
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");
                    break;
                  case "ACTIVE_LOCK":
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");
                    break;
                  case "ACTIVE_ERROR":
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");
                    break;
                  case "BACKGROUND":
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");
                    break;
                  case "BACKGROUND_ERROR":
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");
                    this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");
                    break;
                }
                if (this._watchState === "OFF" && this._geolocationWatchID !== void 0) {
                  this._clearWatch();
                } else if (this._geolocationWatchID === void 0) {
                  this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");
                  this._geolocateButton.setAttribute("aria-pressed", "true");
                  numberOfWatches++;
                  var positionOptions;
                  if (numberOfWatches > 1) {
                    positionOptions = {
                      maximumAge: 6e5,
                      timeout: 0
                    };
                    noTimeout = true;
                  } else {
                    positionOptions = this.options.positionOptions;
                    noTimeout = false;
                  }
                  this._geolocationWatchID = performance2.window.navigator.geolocation.watchPosition(this._onSuccess, this._onError, positionOptions);
                }
              } else {
                performance2.window.navigator.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions);
                this._timeoutId = setTimeout(this._finish, 1e4);
              }
              return true;
            };
            GeolocateControl2.prototype._clearWatch = function _clearWatch() {
              performance2.window.navigator.geolocation.clearWatch(this._geolocationWatchID);
              this._geolocationWatchID = void 0;
              this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting");
              this._geolocateButton.setAttribute("aria-pressed", "false");
              if (this.options.showUserLocation) {
                this._updateMarker(null);
              }
            };
            return GeolocateControl2;
          }(performance2.Evented);
          var defaultOptions$4 = {
            maxWidth: 100,
            unit: "metric"
          };
          var ScaleControl = function ScaleControl2(options) {
            this.options = performance2.extend({}, defaultOptions$4, options);
            performance2.bindAll([
              "_onMove",
              "setUnit"
            ], this);
          };
          ScaleControl.prototype.getDefaultPosition = function getDefaultPosition() {
            return "bottom-left";
          };
          ScaleControl.prototype._onMove = function _onMove() {
            updateScale(this._map, this._container, this.options);
          };
          ScaleControl.prototype.onAdd = function onAdd(map) {
            this._map = map;
            this._container = DOM.create("div", "mapboxgl-ctrl mapboxgl-ctrl-scale", map.getContainer());
            this._map.on("move", this._onMove);
            this._onMove();
            return this._container;
          };
          ScaleControl.prototype.onRemove = function onRemove() {
            DOM.remove(this._container);
            this._map.off("move", this._onMove);
            this._map = void 0;
          };
          ScaleControl.prototype.setUnit = function setUnit(unit) {
            this.options.unit = unit;
            updateScale(this._map, this._container, this.options);
          };
          function updateScale(map, container, options) {
            var maxWidth = options && options.maxWidth || 100;
            var y = map._container.clientHeight / 2;
            var left = map.unproject([
              0,
              y
            ]);
            var right = map.unproject([
              maxWidth,
              y
            ]);
            var maxMeters = left.distanceTo(right);
            if (options && options.unit === "imperial") {
              var maxFeet = 3.2808 * maxMeters;
              if (maxFeet > 5280) {
                var maxMiles = maxFeet / 5280;
                setScale(container, maxWidth, maxMiles, map._getUIString("ScaleControl.Miles"));
              } else {
                setScale(container, maxWidth, maxFeet, map._getUIString("ScaleControl.Feet"));
              }
            } else if (options && options.unit === "nautical") {
              var maxNauticals = maxMeters / 1852;
              setScale(container, maxWidth, maxNauticals, map._getUIString("ScaleControl.NauticalMiles"));
            } else if (maxMeters >= 1e3) {
              setScale(container, maxWidth, maxMeters / 1e3, map._getUIString("ScaleControl.Kilometers"));
            } else {
              setScale(container, maxWidth, maxMeters, map._getUIString("ScaleControl.Meters"));
            }
          }
          function setScale(container, maxWidth, maxDistance, unit) {
            var distance = getRoundNum(maxDistance);
            var ratio = distance / maxDistance;
            container.style.width = maxWidth * ratio + "px";
            container.innerHTML = distance + "&nbsp;" + unit;
          }
          function getDecimalRoundNum(d) {
            var multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10));
            return Math.round(d * multiplier) / multiplier;
          }
          function getRoundNum(num) {
            var pow10 = Math.pow(10, ("" + Math.floor(num)).length - 1);
            var d = num / pow10;
            d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : d >= 1 ? 1 : getDecimalRoundNum(d);
            return pow10 * d;
          }
          var FullscreenControl = function FullscreenControl2(options) {
            this._fullscreen = false;
            if (options && options.container) {
              if (options.container instanceof performance2.window.HTMLElement) {
                this._container = options.container;
              } else {
                performance2.warnOnce("Full screen control 'container' must be a DOM element.");
              }
            }
            performance2.bindAll([
              "_onClickFullscreen",
              "_changeIcon"
            ], this);
            if ("onfullscreenchange" in performance2.window.document) {
              this._fullscreenchange = "fullscreenchange";
            } else if ("onmozfullscreenchange" in performance2.window.document) {
              this._fullscreenchange = "mozfullscreenchange";
            } else if ("onwebkitfullscreenchange" in performance2.window.document) {
              this._fullscreenchange = "webkitfullscreenchange";
            } else if ("onmsfullscreenchange" in performance2.window.document) {
              this._fullscreenchange = "MSFullscreenChange";
            }
          };
          FullscreenControl.prototype.onAdd = function onAdd(map) {
            this._map = map;
            if (!this._container) {
              this._container = this._map.getContainer();
            }
            this._controlContainer = DOM.create("div", "mapboxgl-ctrl mapboxgl-ctrl-group");
            if (this._checkFullscreenSupport()) {
              this._setupUI();
            } else {
              this._controlContainer.style.display = "none";
              performance2.warnOnce("This device does not support fullscreen mode.");
            }
            return this._controlContainer;
          };
          FullscreenControl.prototype.onRemove = function onRemove() {
            DOM.remove(this._controlContainer);
            this._map = null;
            performance2.window.document.removeEventListener(this._fullscreenchange, this._changeIcon);
          };
          FullscreenControl.prototype._checkFullscreenSupport = function _checkFullscreenSupport() {
            return !!(performance2.window.document.fullscreenEnabled || performance2.window.document.mozFullScreenEnabled || performance2.window.document.msFullscreenEnabled || performance2.window.document.webkitFullscreenEnabled);
          };
          FullscreenControl.prototype._setupUI = function _setupUI() {
            var button = this._fullscreenButton = DOM.create("button", "mapboxgl-ctrl-fullscreen", this._controlContainer);
            DOM.create("span", "mapboxgl-ctrl-icon", button).setAttribute("aria-hidden", true);
            button.type = "button";
            this._updateTitle();
            this._fullscreenButton.addEventListener("click", this._onClickFullscreen);
            performance2.window.document.addEventListener(this._fullscreenchange, this._changeIcon);
          };
          FullscreenControl.prototype._updateTitle = function _updateTitle() {
            var title = this._getTitle();
            this._fullscreenButton.setAttribute("aria-label", title);
            this._fullscreenButton.title = title;
          };
          FullscreenControl.prototype._getTitle = function _getTitle() {
            return this._map._getUIString(this._isFullscreen() ? "FullscreenControl.Exit" : "FullscreenControl.Enter");
          };
          FullscreenControl.prototype._isFullscreen = function _isFullscreen() {
            return this._fullscreen;
          };
          FullscreenControl.prototype._changeIcon = function _changeIcon() {
            var fullscreenElement = performance2.window.document.fullscreenElement || performance2.window.document.mozFullScreenElement || performance2.window.document.webkitFullscreenElement || performance2.window.document.msFullscreenElement;
            if (fullscreenElement === this._container !== this._fullscreen) {
              this._fullscreen = !this._fullscreen;
              this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink");
              this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen");
              this._updateTitle();
            }
          };
          FullscreenControl.prototype._onClickFullscreen = function _onClickFullscreen() {
            if (this._isFullscreen()) {
              if (performance2.window.document.exitFullscreen) {
                performance2.window.document.exitFullscreen();
              } else if (performance2.window.document.mozCancelFullScreen) {
                performance2.window.document.mozCancelFullScreen();
              } else if (performance2.window.document.msExitFullscreen) {
                performance2.window.document.msExitFullscreen();
              } else if (performance2.window.document.webkitCancelFullScreen) {
                performance2.window.document.webkitCancelFullScreen();
              }
            } else if (this._container.requestFullscreen) {
              this._container.requestFullscreen();
            } else if (this._container.mozRequestFullScreen) {
              this._container.mozRequestFullScreen();
            } else if (this._container.msRequestFullscreen) {
              this._container.msRequestFullscreen();
            } else if (this._container.webkitRequestFullscreen) {
              this._container.webkitRequestFullscreen();
            }
          };
          var defaultOptions$5 = {
            closeButton: true,
            closeOnClick: true,
            focusAfterOpen: true,
            className: "",
            maxWidth: "240px"
          };
          var focusQuerySelector = [
            "a[href]",
            "[tabindex]:not([tabindex='-1'])",
            "[contenteditable]:not([contenteditable='false'])",
            "button:not([disabled])",
            "input:not([disabled])",
            "select:not([disabled])",
            "textarea:not([disabled])"
          ].join(", ");
          var Popup = function(Evented) {
            function Popup2(options) {
              Evented.call(this);
              this.options = performance2.extend(Object.create(defaultOptions$5), options);
              performance2.bindAll([
                "_update",
                "_onClose",
                "remove",
                "_onMouseMove",
                "_onMouseUp",
                "_onDrag"
              ], this);
            }
            if (Evented)
              Popup2.__proto__ = Evented;
            Popup2.prototype = Object.create(Evented && Evented.prototype);
            Popup2.prototype.constructor = Popup2;
            Popup2.prototype.addTo = function addTo(map) {
              if (this._map) {
                this.remove();
              }
              this._map = map;
              if (this.options.closeOnClick) {
                this._map.on("click", this._onClose);
              }
              if (this.options.closeOnMove) {
                this._map.on("move", this._onClose);
              }
              this._map.on("remove", this.remove);
              this._update();
              this._focusFirstElement();
              if (this._trackPointer) {
                this._map.on("mousemove", this._onMouseMove);
                this._map.on("mouseup", this._onMouseUp);
                if (this._container) {
                  this._container.classList.add("mapboxgl-popup-track-pointer");
                }
                this._map._canvasContainer.classList.add("mapboxgl-track-pointer");
              } else {
                this._map.on("move", this._update);
              }
              this.fire(new performance2.Event("open"));
              return this;
            };
            Popup2.prototype.isOpen = function isOpen() {
              return !!this._map;
            };
            Popup2.prototype.remove = function remove() {
              if (this._content) {
                DOM.remove(this._content);
              }
              if (this._container) {
                DOM.remove(this._container);
                delete this._container;
              }
              if (this._map) {
                this._map.off("move", this._update);
                this._map.off("move", this._onClose);
                this._map.off("click", this._onClose);
                this._map.off("remove", this.remove);
                this._map.off("mousemove", this._onMouseMove);
                this._map.off("mouseup", this._onMouseUp);
                this._map.off("drag", this._onDrag);
                delete this._map;
              }
              this.fire(new performance2.Event("close"));
              return this;
            };
            Popup2.prototype.getLngLat = function getLngLat() {
              return this._lngLat;
            };
            Popup2.prototype.setLngLat = function setLngLat(lnglat) {
              this._lngLat = performance2.LngLat.convert(lnglat);
              this._pos = null;
              this._trackPointer = false;
              this._update();
              if (this._map) {
                this._map.on("move", this._update);
                this._map.off("mousemove", this._onMouseMove);
                if (this._container) {
                  this._container.classList.remove("mapboxgl-popup-track-pointer");
                }
                this._map._canvasContainer.classList.remove("mapboxgl-track-pointer");
              }
              return this;
            };
            Popup2.prototype.trackPointer = function trackPointer() {
              this._trackPointer = true;
              this._pos = null;
              this._update();
              if (this._map) {
                this._map.off("move", this._update);
                this._map.on("mousemove", this._onMouseMove);
                this._map.on("drag", this._onDrag);
                if (this._container) {
                  this._container.classList.add("mapboxgl-popup-track-pointer");
                }
                this._map._canvasContainer.classList.add("mapboxgl-track-pointer");
              }
              return this;
            };
            Popup2.prototype.getElement = function getElement() {
              return this._container;
            };
            Popup2.prototype.setText = function setText(text) {
              return this.setDOMContent(performance2.window.document.createTextNode(text));
            };
            Popup2.prototype.setHTML = function setHTML(html) {
              var frag = performance2.window.document.createDocumentFragment();
              var temp = performance2.window.document.createElement("body");
              var child;
              temp.innerHTML = html;
              while (true) {
                child = temp.firstChild;
                if (!child) {
                  break;
                }
                frag.appendChild(child);
              }
              return this.setDOMContent(frag);
            };
            Popup2.prototype.getMaxWidth = function getMaxWidth() {
              return this._container && this._container.style.maxWidth;
            };
            Popup2.prototype.setMaxWidth = function setMaxWidth(maxWidth) {
              this.options.maxWidth = maxWidth;
              this._update();
              return this;
            };
            Popup2.prototype.setDOMContent = function setDOMContent(htmlNode) {
              if (this._content) {
                while (this._content.hasChildNodes()) {
                  if (this._content.firstChild) {
                    this._content.removeChild(this._content.firstChild);
                  }
                }
              } else {
                this._content = DOM.create("div", "mapboxgl-popup-content", this._container);
              }
              this._content.appendChild(htmlNode);
              this._createCloseButton();
              this._update();
              this._focusFirstElement();
              return this;
            };
            Popup2.prototype.addClassName = function addClassName(className) {
              if (this._container) {
                this._container.classList.add(className);
              }
            };
            Popup2.prototype.removeClassName = function removeClassName(className) {
              if (this._container) {
                this._container.classList.remove(className);
              }
            };
            Popup2.prototype.setOffset = function setOffset(offset) {
              this.options.offset = offset;
              this._update();
              return this;
            };
            Popup2.prototype.toggleClassName = function toggleClassName(className) {
              if (this._container) {
                return this._container.classList.toggle(className);
              }
            };
            Popup2.prototype._createCloseButton = function _createCloseButton() {
              if (this.options.closeButton) {
                this._closeButton = DOM.create("button", "mapboxgl-popup-close-button", this._content);
                this._closeButton.type = "button";
                this._closeButton.setAttribute("aria-label", "Close popup");
                this._closeButton.innerHTML = "&#215;";
                this._closeButton.addEventListener("click", this._onClose);
              }
            };
            Popup2.prototype._onMouseUp = function _onMouseUp(event) {
              this._update(event.point);
            };
            Popup2.prototype._onMouseMove = function _onMouseMove(event) {
              this._update(event.point);
            };
            Popup2.prototype._onDrag = function _onDrag(event) {
              this._update(event.point);
            };
            Popup2.prototype._update = function _update(cursor) {
              var this$1 = this;
              var hasPosition = this._lngLat || this._trackPointer;
              if (!this._map || !hasPosition || !this._content) {
                return;
              }
              if (!this._container) {
                this._container = DOM.create("div", "mapboxgl-popup", this._map.getContainer());
                this._tip = DOM.create("div", "mapboxgl-popup-tip", this._container);
                this._container.appendChild(this._content);
                if (this.options.className) {
                  this.options.className.split(" ").forEach(function(name2) {
                    return this$1._container.classList.add(name2);
                  });
                }
                if (this._trackPointer) {
                  this._container.classList.add("mapboxgl-popup-track-pointer");
                }
              }
              if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) {
                this._container.style.maxWidth = this.options.maxWidth;
              }
              if (this._map.transform.renderWorldCopies && !this._trackPointer) {
                this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform);
              }
              if (this._trackPointer && !cursor) {
                return;
              }
              var pos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat);
              var anchor = this.options.anchor;
              var offset = normalizeOffset(this.options.offset);
              if (!anchor) {
                var width = this._container.offsetWidth;
                var height = this._container.offsetHeight;
                var anchorComponents;
                if (pos.y + offset.bottom.y < height) {
                  anchorComponents = ["top"];
                } else if (pos.y > this._map.transform.height - height) {
                  anchorComponents = ["bottom"];
                } else {
                  anchorComponents = [];
                }
                if (pos.x < width / 2) {
                  anchorComponents.push("left");
                } else if (pos.x > this._map.transform.width - width / 2) {
                  anchorComponents.push("right");
                }
                if (anchorComponents.length === 0) {
                  anchor = "bottom";
                } else {
                  anchor = anchorComponents.join("-");
                }
              }
              var offsetedPos = pos.add(offset[anchor]).round();
              DOM.setTransform(this._container, anchorTranslate[anchor] + " translate(" + offsetedPos.x + "px," + offsetedPos.y + "px)");
              applyAnchorClass(this._container, anchor, "popup");
            };
            Popup2.prototype._focusFirstElement = function _focusFirstElement() {
              if (!this.options.focusAfterOpen || !this._container) {
                return;
              }
              var firstFocusable = this._container.querySelector(focusQuerySelector);
              if (firstFocusable) {
                firstFocusable.focus();
              }
            };
            Popup2.prototype._onClose = function _onClose() {
              this.remove();
            };
            return Popup2;
          }(performance2.Evented);
          function normalizeOffset(offset) {
            if (!offset) {
              return normalizeOffset(new performance2.Point(0, 0));
            } else if (typeof offset === "number") {
              var cornerOffset = Math.round(Math.sqrt(0.5 * Math.pow(offset, 2)));
              return {
                "center": new performance2.Point(0, 0),
                "top": new performance2.Point(0, offset),
                "top-left": new performance2.Point(cornerOffset, cornerOffset),
                "top-right": new performance2.Point(-cornerOffset, cornerOffset),
                "bottom": new performance2.Point(0, -offset),
                "bottom-left": new performance2.Point(cornerOffset, -cornerOffset),
                "bottom-right": new performance2.Point(-cornerOffset, -cornerOffset),
                "left": new performance2.Point(offset, 0),
                "right": new performance2.Point(-offset, 0)
              };
            } else if (offset instanceof performance2.Point || Array.isArray(offset)) {
              var convertedOffset = performance2.Point.convert(offset);
              return {
                "center": convertedOffset,
                "top": convertedOffset,
                "top-left": convertedOffset,
                "top-right": convertedOffset,
                "bottom": convertedOffset,
                "bottom-left": convertedOffset,
                "bottom-right": convertedOffset,
                "left": convertedOffset,
                "right": convertedOffset
              };
            } else {
              return {
                "center": performance2.Point.convert(offset["center"] || [
                  0,
                  0
                ]),
                "top": performance2.Point.convert(offset["top"] || [
                  0,
                  0
                ]),
                "top-left": performance2.Point.convert(offset["top-left"] || [
                  0,
                  0
                ]),
                "top-right": performance2.Point.convert(offset["top-right"] || [
                  0,
                  0
                ]),
                "bottom": performance2.Point.convert(offset["bottom"] || [
                  0,
                  0
                ]),
                "bottom-left": performance2.Point.convert(offset["bottom-left"] || [
                  0,
                  0
                ]),
                "bottom-right": performance2.Point.convert(offset["bottom-right"] || [
                  0,
                  0
                ]),
                "left": performance2.Point.convert(offset["left"] || [
                  0,
                  0
                ]),
                "right": performance2.Point.convert(offset["right"] || [
                  0,
                  0
                ])
              };
            }
          }
          var exported = {
            version: performance2.version,
            supported: mapboxGlSupported,
            setRTLTextPlugin: performance2.setRTLTextPlugin,
            getRTLTextPluginStatus: performance2.getRTLTextPluginStatus,
            Map: Map2,
            NavigationControl,
            GeolocateControl,
            AttributionControl,
            ScaleControl,
            FullscreenControl,
            Popup,
            Marker,
            Style,
            LngLat: performance2.LngLat,
            LngLatBounds: performance2.LngLatBounds,
            Point: performance2.Point,
            MercatorCoordinate: performance2.MercatorCoordinate,
            Evented: performance2.Evented,
            config: performance2.config,
            prewarm,
            clearPrewarmedResources,
            get accessToken() {
              return performance2.config.ACCESS_TOKEN;
            },
            set accessToken(token) {
              performance2.config.ACCESS_TOKEN = token;
            },
            get baseApiUrl() {
              return performance2.config.API_URL;
            },
            set baseApiUrl(url) {
              performance2.config.API_URL = url;
            },
            get workerCount() {
              return WorkerPool.workerCount;
            },
            set workerCount(count) {
              WorkerPool.workerCount = count;
            },
            get maxParallelImageRequests() {
              return performance2.config.MAX_PARALLEL_IMAGE_REQUESTS;
            },
            set maxParallelImageRequests(numRequests) {
              performance2.config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests;
            },
            clearStorage: function clearStorage(callback) {
              performance2.clearTileCache(callback);
            },
            workerUrl: ""
          };
          return exported;
        });
        return mapboxgl;
      });
    }
  });

  // src/plots/mapbox/layers.js
  var require_layers = __commonJS({
    "src/plots/mapbox/layers.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var sanitizeHTML = require_svg_text_utils().sanitizeHTML;
      var convertTextOpts = require_convert_text_opts();
      var constants = require_constants25();
      function MapboxLayer(subplot, index) {
        this.subplot = subplot;
        this.uid = subplot.uid + "-" + index;
        this.index = index;
        this.idSource = "source-" + this.uid;
        this.idLayer = constants.layoutLayerPrefix + this.uid;
        this.sourceType = null;
        this.source = null;
        this.layerType = null;
        this.below = null;
        this.visible = false;
      }
      var proto = MapboxLayer.prototype;
      proto.update = function update(opts) {
        if (!this.visible) {
          this.updateSource(opts);
          this.updateLayer(opts);
        } else if (this.needsNewImage(opts)) {
          this.updateImage(opts);
        } else if (this.needsNewSource(opts)) {
          this.removeLayer();
          this.updateSource(opts);
          this.updateLayer(opts);
        } else if (this.needsNewLayer(opts)) {
          this.updateLayer(opts);
        } else {
          this.updateStyle(opts);
        }
        this.visible = isVisible(opts);
      };
      proto.needsNewImage = function(opts) {
        var map = this.subplot.map;
        return map.getSource(this.idSource) && this.sourceType === "image" && opts.sourcetype === "image" && (this.source !== opts.source || JSON.stringify(this.coordinates) !== JSON.stringify(opts.coordinates));
      };
      proto.needsNewSource = function(opts) {
        return this.sourceType !== opts.sourcetype || JSON.stringify(this.source) !== JSON.stringify(opts.source) || this.layerType !== opts.type;
      };
      proto.needsNewLayer = function(opts) {
        return this.layerType !== opts.type || this.below !== this.subplot.belowLookup["layout-" + this.index];
      };
      proto.lookupBelow = function() {
        return this.subplot.belowLookup["layout-" + this.index];
      };
      proto.updateImage = function(opts) {
        var map = this.subplot.map;
        map.getSource(this.idSource).updateImage({
          url: opts.source,
          coordinates: opts.coordinates
        });
        var _below = this.findFollowingMapboxLayerId(this.lookupBelow());
        if (_below !== null) {
          this.subplot.map.moveLayer(this.idLayer, _below);
        }
      };
      proto.updateSource = function(opts) {
        var map = this.subplot.map;
        if (map.getSource(this.idSource)) map.removeSource(this.idSource);
        this.sourceType = opts.sourcetype;
        this.source = opts.source;
        if (!isVisible(opts)) return;
        var sourceOpts = convertSourceOpts(opts);
        map.addSource(this.idSource, sourceOpts);
      };
      proto.findFollowingMapboxLayerId = function(below) {
        if (below === "traces") {
          var mapLayers = this.subplot.getMapLayers();
          for (var i = 0; i < mapLayers.length; i++) {
            var layerId = mapLayers[i].id;
            if (typeof layerId === "string" && layerId.indexOf(constants.traceLayerPrefix) === 0) {
              below = layerId;
              break;
            }
          }
        }
        return below;
      };
      proto.updateLayer = function(opts) {
        var subplot = this.subplot;
        var convertedOpts = convertOpts(opts);
        var below = this.lookupBelow();
        var _below = this.findFollowingMapboxLayerId(below);
        this.removeLayer();
        if (isVisible(opts)) {
          subplot.addLayer({
            id: this.idLayer,
            source: this.idSource,
            "source-layer": opts.sourcelayer || "",
            type: opts.type,
            minzoom: opts.minzoom,
            maxzoom: opts.maxzoom,
            layout: convertedOpts.layout,
            paint: convertedOpts.paint
          }, _below);
        }
        this.layerType = opts.type;
        this.below = below;
      };
      proto.updateStyle = function(opts) {
        if (isVisible(opts)) {
          var convertedOpts = convertOpts(opts);
          this.subplot.setOptions(this.idLayer, "setLayoutProperty", convertedOpts.layout);
          this.subplot.setOptions(this.idLayer, "setPaintProperty", convertedOpts.paint);
        }
      };
      proto.removeLayer = function() {
        var map = this.subplot.map;
        if (map.getLayer(this.idLayer)) {
          map.removeLayer(this.idLayer);
        }
      };
      proto.dispose = function() {
        var map = this.subplot.map;
        if (map.getLayer(this.idLayer)) map.removeLayer(this.idLayer);
        if (map.getSource(this.idSource)) map.removeSource(this.idSource);
      };
      function isVisible(opts) {
        if (!opts.visible) return false;
        var source = opts.source;
        if (Array.isArray(source) && source.length > 0) {
          for (var i = 0; i < source.length; i++) {
            if (typeof source[i] !== "string" || source[i].length === 0) {
              return false;
            }
          }
          return true;
        }
        return Lib.isPlainObject(source) || typeof source === "string" && source.length > 0;
      }
      function convertOpts(opts) {
        var layout = {};
        var paint = {};
        switch (opts.type) {
          case "circle":
            Lib.extendFlat(paint, {
              "circle-radius": opts.circle.radius,
              "circle-color": opts.color,
              "circle-opacity": opts.opacity
            });
            break;
          case "line":
            Lib.extendFlat(paint, {
              "line-width": opts.line.width,
              "line-color": opts.color,
              "line-opacity": opts.opacity,
              "line-dasharray": opts.line.dash
            });
            break;
          case "fill":
            Lib.extendFlat(paint, {
              "fill-color": opts.color,
              "fill-outline-color": opts.fill.outlinecolor,
              "fill-opacity": opts.opacity
              // no way to pass specify outline width at the moment
            });
            break;
          case "symbol":
            var symbol = opts.symbol;
            var textOpts = convertTextOpts(symbol.textposition, symbol.iconsize);
            Lib.extendFlat(layout, {
              "icon-image": symbol.icon + "-15",
              "icon-size": symbol.iconsize / 10,
              "text-field": symbol.text,
              "text-size": symbol.textfont.size,
              "text-anchor": textOpts.anchor,
              "text-offset": textOpts.offset,
              "symbol-placement": symbol.placement
              // TODO font family
              // 'text-font': symbol.textfont.family.split(', '),
            });
            Lib.extendFlat(paint, {
              "icon-color": opts.color,
              "text-color": symbol.textfont.color,
              "text-opacity": opts.opacity
            });
            break;
          case "raster":
            Lib.extendFlat(paint, {
              "raster-fade-duration": 0,
              "raster-opacity": opts.opacity
            });
            break;
        }
        return {
          layout,
          paint
        };
      }
      function convertSourceOpts(opts) {
        var sourceType = opts.sourcetype;
        var source = opts.source;
        var sourceOpts = { type: sourceType };
        var field;
        if (sourceType === "geojson") {
          field = "data";
        } else if (sourceType === "vector") {
          field = typeof source === "string" ? "url" : "tiles";
        } else if (sourceType === "raster") {
          field = "tiles";
          sourceOpts.tileSize = 256;
        } else if (sourceType === "image") {
          field = "url";
          sourceOpts.coordinates = opts.coordinates;
        }
        sourceOpts[field] = source;
        if (opts.sourceattribution) {
          sourceOpts.attribution = sanitizeHTML(opts.sourceattribution);
        }
        return sourceOpts;
      }
      module.exports = function createMapboxLayer(subplot, index, opts) {
        var mapboxLayer = new MapboxLayer(subplot, index);
        mapboxLayer.update(opts);
        return mapboxLayer;
      };
    }
  });

  // src/plots/mapbox/mapbox.js
  var require_mapbox = __commonJS({
    "src/plots/mapbox/mapbox.js"(exports, module) {
      "use strict";
      var mapboxgl = require_mapbox_gl_unminified();
      var Lib = require_lib();
      var geoUtils = require_geo_location_utils();
      var Registry = require_registry();
      var Axes = require_axes();
      var dragElement = require_dragelement();
      var Fx = require_fx();
      var dragHelpers = require_helpers5();
      var drawMode = dragHelpers.drawMode;
      var selectMode = dragHelpers.selectMode;
      var prepSelect = require_selections().prepSelect;
      var clearOutline = require_selections().clearOutline;
      var clearSelectionsCache = require_selections().clearSelectionsCache;
      var selectOnClick = require_selections().selectOnClick;
      var constants = require_constants25();
      var createMapboxLayer = require_layers();
      function Mapbox(gd, id) {
        this.id = id;
        this.gd = gd;
        var fullLayout = gd._fullLayout;
        var context = gd._context;
        this.container = fullLayout._glcontainer.node();
        this.isStatic = context.staticPlot;
        this.uid = fullLayout._uid + "-" + this.id;
        this.div = null;
        this.xaxis = null;
        this.yaxis = null;
        this.createFramework(fullLayout);
        this.map = null;
        this.accessToken = null;
        this.styleObj = null;
        this.traceHash = {};
        this.layerList = [];
        this.belowLookup = {};
        this.dragging = false;
        this.wheeling = false;
      }
      var proto = Mapbox.prototype;
      proto.plot = function(calcData, fullLayout, promises) {
        var self2 = this;
        var opts = fullLayout[self2.id];
        if (self2.map && opts.accesstoken !== self2.accessToken) {
          self2.map.remove();
          self2.map = null;
          self2.styleObj = null;
          self2.traceHash = {};
          self2.layerList = [];
        }
        var promise;
        if (!self2.map) {
          promise = new Promise(function(resolve, reject) {
            self2.createMap(calcData, fullLayout, resolve, reject);
          });
        } else {
          promise = new Promise(function(resolve, reject) {
            self2.updateMap(calcData, fullLayout, resolve, reject);
          });
        }
        promises.push(promise);
      };
      proto.createMap = function(calcData, fullLayout, resolve, reject) {
        var self2 = this;
        var opts = fullLayout[self2.id];
        var styleObj = self2.styleObj = getStyleObj(opts.style, fullLayout);
        self2.accessToken = opts.accesstoken;
        var bounds = opts.bounds;
        var maxBounds = bounds ? [[bounds.west, bounds.south], [bounds.east, bounds.north]] : null;
        var map = self2.map = new mapboxgl.Map({
          container: self2.div,
          style: styleObj.style,
          center: convertCenter(opts.center),
          zoom: opts.zoom,
          bearing: opts.bearing,
          pitch: opts.pitch,
          maxBounds,
          interactive: !self2.isStatic,
          preserveDrawingBuffer: self2.isStatic,
          doubleClickZoom: false,
          boxZoom: false,
          attributionControl: false
        }).addControl(new mapboxgl.AttributionControl({
          compact: true
        }));
        map._canvas.style.left = "0px";
        map._canvas.style.top = "0px";
        self2.rejectOnError(reject);
        if (!self2.isStatic) {
          self2.initFx(calcData, fullLayout);
        }
        var promises = [];
        promises.push(new Promise(function(resolve2) {
          map.once("load", resolve2);
        }));
        promises = promises.concat(geoUtils.fetchTraceGeoData(calcData));
        Promise.all(promises).then(function() {
          self2.fillBelowLookup(calcData, fullLayout);
          self2.updateData(calcData);
          self2.updateLayout(fullLayout);
          self2.resolveOnRender(resolve);
        }).catch(reject);
      };
      proto.updateMap = function(calcData, fullLayout, resolve, reject) {
        var self2 = this;
        var map = self2.map;
        var opts = fullLayout[this.id];
        self2.rejectOnError(reject);
        var promises = [];
        var styleObj = getStyleObj(opts.style, fullLayout);
        if (JSON.stringify(self2.styleObj) !== JSON.stringify(styleObj)) {
          self2.styleObj = styleObj;
          map.setStyle(styleObj.style);
          self2.traceHash = {};
          promises.push(new Promise(function(resolve2) {
            map.once("styledata", resolve2);
          }));
        }
        promises = promises.concat(geoUtils.fetchTraceGeoData(calcData));
        Promise.all(promises).then(function() {
          self2.fillBelowLookup(calcData, fullLayout);
          self2.updateData(calcData);
          self2.updateLayout(fullLayout);
          self2.resolveOnRender(resolve);
        }).catch(reject);
      };
      proto.fillBelowLookup = function(calcData, fullLayout) {
        var opts = fullLayout[this.id];
        var layers = opts.layers;
        var i, val;
        var belowLookup = this.belowLookup = {};
        var hasTraceAtTop = false;
        for (i = 0; i < calcData.length; i++) {
          var trace = calcData[i][0].trace;
          var _module = trace._module;
          if (typeof trace.below === "string") {
            val = trace.below;
          } else if (_module.getBelow) {
            val = _module.getBelow(trace, this);
          }
          if (val === "") {
            hasTraceAtTop = true;
          }
          belowLookup["trace-" + trace.uid] = val || "";
        }
        for (i = 0; i < layers.length; i++) {
          var item = layers[i];
          if (typeof item.below === "string") {
            val = item.below;
          } else if (hasTraceAtTop) {
            val = "traces";
          } else {
            val = "";
          }
          belowLookup["layout-" + i] = val;
        }
        var val2list = {};
        var k, id;
        for (k in belowLookup) {
          val = belowLookup[k];
          if (val2list[val]) {
            val2list[val].push(k);
          } else {
            val2list[val] = [k];
          }
        }
        for (val in val2list) {
          var list = val2list[val];
          if (list.length > 1) {
            for (i = 0; i < list.length; i++) {
              k = list[i];
              if (k.indexOf("trace-") === 0) {
                id = k.split("trace-")[1];
                if (this.traceHash[id]) {
                  this.traceHash[id].below = null;
                }
              } else if (k.indexOf("layout-") === 0) {
                id = k.split("layout-")[1];
                if (this.layerList[id]) {
                  this.layerList[id].below = null;
                }
              }
            }
          }
        }
      };
      var traceType2orderIndex = {
        choroplethmapbox: 0,
        densitymapbox: 1,
        scattermapbox: 2
      };
      proto.updateData = function(calcData) {
        var traceHash = this.traceHash;
        var traceObj, trace, i, j;
        var calcDataSorted = calcData.slice().sort(function(a, b) {
          return traceType2orderIndex[a[0].trace.type] - traceType2orderIndex[b[0].trace.type];
        });
        for (i = 0; i < calcDataSorted.length; i++) {
          var calcTrace = calcDataSorted[i];
          trace = calcTrace[0].trace;
          traceObj = traceHash[trace.uid];
          var didUpdate = false;
          if (traceObj) {
            if (traceObj.type === trace.type) {
              traceObj.update(calcTrace);
              didUpdate = true;
            } else {
              traceObj.dispose();
            }
          }
          if (!didUpdate && trace._module) {
            traceHash[trace.uid] = trace._module.plot(this, calcTrace);
          }
        }
        var ids = Object.keys(traceHash);
        idLoop:
          for (i = 0; i < ids.length; i++) {
            var id = ids[i];
            for (j = 0; j < calcData.length; j++) {
              trace = calcData[j][0].trace;
              if (id === trace.uid) continue idLoop;
            }
            traceObj = traceHash[id];
            traceObj.dispose();
            delete traceHash[id];
          }
      };
      proto.updateLayout = function(fullLayout) {
        var map = this.map;
        var opts = fullLayout[this.id];
        if (!this.dragging && !this.wheeling) {
          map.setCenter(convertCenter(opts.center));
          map.setZoom(opts.zoom);
          map.setBearing(opts.bearing);
          map.setPitch(opts.pitch);
        }
        this.updateLayers(fullLayout);
        this.updateFramework(fullLayout);
        this.updateFx(fullLayout);
        this.map.resize();
        if (this.gd._context._scrollZoom.mapbox) {
          map.scrollZoom.enable();
        } else {
          map.scrollZoom.disable();
        }
      };
      proto.resolveOnRender = function(resolve) {
        var map = this.map;
        map.on("render", function onRender() {
          if (map.loaded()) {
            map.off("render", onRender);
            setTimeout(resolve, 10);
          }
        });
      };
      proto.rejectOnError = function(reject) {
        var map = this.map;
        function handler() {
          reject(new Error(constants.mapOnErrorMsg));
        }
        map.once("error", handler);
        map.once("style.error", handler);
        map.once("source.error", handler);
        map.once("tile.error", handler);
        map.once("layer.error", handler);
      };
      proto.createFramework = function(fullLayout) {
        var self2 = this;
        var div = self2.div = document.createElement("div");
        div.id = self2.uid;
        div.style.position = "absolute";
        self2.container.appendChild(div);
        self2.xaxis = {
          _id: "x",
          c2p: function(v) {
            return self2.project(v).x;
          }
        };
        self2.yaxis = {
          _id: "y",
          c2p: function(v) {
            return self2.project(v).y;
          }
        };
        self2.updateFramework(fullLayout);
        self2.mockAxis = {
          type: "linear",
          showexponent: "all",
          exponentformat: "B"
        };
        Axes.setConvert(self2.mockAxis, fullLayout);
      };
      proto.initFx = function(calcData, fullLayout) {
        var self2 = this;
        var gd = self2.gd;
        var map = self2.map;
        map.on("moveend", function(evt) {
          if (!self2.map) return;
          var fullLayoutNow = gd._fullLayout;
          if (evt.originalEvent || self2.wheeling) {
            var optsNow = fullLayoutNow[self2.id];
            Registry.call("_storeDirectGUIEdit", gd.layout, fullLayoutNow._preGUI, self2.getViewEdits(optsNow));
            var viewNow = self2.getView();
            optsNow._input.center = optsNow.center = viewNow.center;
            optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
            optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
            optsNow._input.pitch = optsNow.pitch = viewNow.pitch;
            gd.emit("plotly_relayout", self2.getViewEditsWithDerived(viewNow));
          }
          if (evt.originalEvent && evt.originalEvent.type === "mouseup") {
            self2.dragging = false;
          } else if (self2.wheeling) {
            self2.wheeling = false;
          }
          if (fullLayoutNow._rehover) {
            fullLayoutNow._rehover();
          }
        });
        map.on("wheel", function() {
          self2.wheeling = true;
        });
        map.on("mousemove", function(evt) {
          var bb = self2.div.getBoundingClientRect();
          var xy = [
            evt.originalEvent.offsetX,
            evt.originalEvent.offsetY
          ];
          evt.target.getBoundingClientRect = function() {
            return bb;
          };
          self2.xaxis.p2c = function() {
            return map.unproject(xy).lng;
          };
          self2.yaxis.p2c = function() {
            return map.unproject(xy).lat;
          };
          gd._fullLayout._rehover = function() {
            if (gd._fullLayout._hoversubplot === self2.id && gd._fullLayout[self2.id]) {
              Fx.hover(gd, evt, self2.id);
            }
          };
          Fx.hover(gd, evt, self2.id);
          gd._fullLayout._hoversubplot = self2.id;
        });
        function unhover() {
          Fx.loneUnhover(fullLayout._hoverlayer);
        }
        map.on("dragstart", function() {
          self2.dragging = true;
          unhover();
        });
        map.on("zoomstart", unhover);
        map.on("mouseout", function() {
          gd._fullLayout._hoversubplot = null;
        });
        function emitUpdate() {
          var viewNow = self2.getView();
          gd.emit("plotly_relayouting", self2.getViewEditsWithDerived(viewNow));
        }
        map.on("drag", emitUpdate);
        map.on("zoom", emitUpdate);
        map.on("dblclick", function() {
          var optsNow = gd._fullLayout[self2.id];
          Registry.call("_storeDirectGUIEdit", gd.layout, gd._fullLayout._preGUI, self2.getViewEdits(optsNow));
          var viewInitial = self2.viewInitial;
          map.setCenter(convertCenter(viewInitial.center));
          map.setZoom(viewInitial.zoom);
          map.setBearing(viewInitial.bearing);
          map.setPitch(viewInitial.pitch);
          var viewNow = self2.getView();
          optsNow._input.center = optsNow.center = viewNow.center;
          optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
          optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
          optsNow._input.pitch = optsNow.pitch = viewNow.pitch;
          gd.emit("plotly_doubleclick", null);
          gd.emit("plotly_relayout", self2.getViewEditsWithDerived(viewNow));
        });
        self2.clearOutline = function() {
          clearSelectionsCache(self2.dragOptions);
          clearOutline(self2.dragOptions.gd);
        };
        self2.onClickInPanFn = function(dragOptions) {
          return function(evt) {
            var clickMode = gd._fullLayout.clickmode;
            if (clickMode.indexOf("select") > -1) {
              selectOnClick(evt.originalEvent, gd, [self2.xaxis], [self2.yaxis], self2.id, dragOptions);
            }
            if (clickMode.indexOf("event") > -1) {
              Fx.click(gd, evt.originalEvent);
            }
          };
        };
      };
      proto.updateFx = function(fullLayout) {
        var self2 = this;
        var map = self2.map;
        var gd = self2.gd;
        if (self2.isStatic) return;
        function invert(pxpy) {
          var obj = self2.map.unproject(pxpy);
          return [obj.lng, obj.lat];
        }
        var dragMode = fullLayout.dragmode;
        var fillRangeItems;
        fillRangeItems = function(eventData, poly) {
          if (poly.isRect) {
            var ranges = eventData.range = {};
            ranges[self2.id] = [
              invert([poly.xmin, poly.ymin]),
              invert([poly.xmax, poly.ymax])
            ];
          } else {
            var dataPts = eventData.lassoPoints = {};
            dataPts[self2.id] = poly.map(invert);
          }
        };
        var oldDragOptions = self2.dragOptions;
        self2.dragOptions = Lib.extendDeep(oldDragOptions || {}, {
          dragmode: fullLayout.dragmode,
          element: self2.div,
          gd,
          plotinfo: {
            id: self2.id,
            domain: fullLayout[self2.id].domain,
            xaxis: self2.xaxis,
            yaxis: self2.yaxis,
            fillRangeItems
          },
          xaxes: [self2.xaxis],
          yaxes: [self2.yaxis],
          subplot: self2.id
        });
        map.off("click", self2.onClickInPanHandler);
        if (selectMode(dragMode) || drawMode(dragMode)) {
          map.dragPan.disable();
          map.on("zoomstart", self2.clearOutline);
          self2.dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, self2.dragOptions, dragMode);
          };
          dragElement.init(self2.dragOptions);
        } else {
          map.dragPan.enable();
          map.off("zoomstart", self2.clearOutline);
          self2.div.onmousedown = null;
          self2.div.ontouchstart = null;
          self2.div.removeEventListener("touchstart", self2.div._ontouchstart);
          self2.onClickInPanHandler = self2.onClickInPanFn(self2.dragOptions);
          map.on("click", self2.onClickInPanHandler);
        }
      };
      proto.updateFramework = function(fullLayout) {
        var domain = fullLayout[this.id].domain;
        var size = fullLayout._size;
        var style = this.div.style;
        style.width = size.w * (domain.x[1] - domain.x[0]) + "px";
        style.height = size.h * (domain.y[1] - domain.y[0]) + "px";
        style.left = size.l + domain.x[0] * size.w + "px";
        style.top = size.t + (1 - domain.y[1]) * size.h + "px";
        this.xaxis._offset = size.l + domain.x[0] * size.w;
        this.xaxis._length = size.w * (domain.x[1] - domain.x[0]);
        this.yaxis._offset = size.t + (1 - domain.y[1]) * size.h;
        this.yaxis._length = size.h * (domain.y[1] - domain.y[0]);
      };
      proto.updateLayers = function(fullLayout) {
        var opts = fullLayout[this.id];
        var layers = opts.layers;
        var layerList = this.layerList;
        var i;
        if (layers.length !== layerList.length) {
          for (i = 0; i < layerList.length; i++) {
            layerList[i].dispose();
          }
          layerList = this.layerList = [];
          for (i = 0; i < layers.length; i++) {
            layerList.push(createMapboxLayer(this, i, layers[i]));
          }
        } else {
          for (i = 0; i < layers.length; i++) {
            layerList[i].update(layers[i]);
          }
        }
      };
      proto.destroy = function() {
        if (this.map) {
          this.map.remove();
          this.map = null;
          this.container.removeChild(this.div);
        }
      };
      proto.toImage = function() {
        this.map.stop();
        return this.map.getCanvas().toDataURL();
      };
      proto.setOptions = function(id, methodName, opts) {
        for (var k in opts) {
          this.map[methodName](id, k, opts[k]);
        }
      };
      proto.getMapLayers = function() {
        return this.map.getStyle().layers;
      };
      proto.addLayer = function(opts, below) {
        var map = this.map;
        if (typeof below === "string") {
          if (below === "") {
            map.addLayer(opts, below);
            return;
          }
          var mapLayers = this.getMapLayers();
          for (var i = 0; i < mapLayers.length; i++) {
            if (below === mapLayers[i].id) {
              map.addLayer(opts, below);
              return;
            }
          }
          Lib.warn([
            "Trying to add layer with *below* value",
            below,
            "referencing a layer that does not exist",
            "or that does not yet exist."
          ].join(" "));
        }
        map.addLayer(opts);
      };
      proto.project = function(v) {
        return this.map.project(new mapboxgl.LngLat(v[0], v[1]));
      };
      proto.getView = function() {
        var map = this.map;
        var mapCenter = map.getCenter();
        var lon = mapCenter.lng;
        var lat = mapCenter.lat;
        var center = { lon, lat };
        var canvas = map.getCanvas();
        var w = parseInt(canvas.style.width);
        var h = parseInt(canvas.style.height);
        return {
          center,
          zoom: map.getZoom(),
          bearing: map.getBearing(),
          pitch: map.getPitch(),
          _derived: {
            coordinates: [
              map.unproject([0, 0]).toArray(),
              map.unproject([w, 0]).toArray(),
              map.unproject([w, h]).toArray(),
              map.unproject([0, h]).toArray()
            ]
          }
        };
      };
      proto.getViewEdits = function(cont) {
        var id = this.id;
        var keys = ["center", "zoom", "bearing", "pitch"];
        var obj = {};
        for (var i = 0; i < keys.length; i++) {
          var k = keys[i];
          obj[id + "." + k] = cont[k];
        }
        return obj;
      };
      proto.getViewEditsWithDerived = function(cont) {
        var id = this.id;
        var obj = this.getViewEdits(cont);
        obj[id + "._derived"] = cont._derived;
        return obj;
      };
      function getStyleObj(val, fullLayout) {
        var styleObj = {};
        if (Lib.isPlainObject(val)) {
          styleObj.id = val.id;
          styleObj.style = val;
        } else if (typeof val === "string") {
          styleObj.id = val;
          if (constants.styleValuesMapbox.indexOf(val) !== -1) {
            styleObj.style = convertStyleVal(val);
          } else if (constants.stylesNonMapbox[val]) {
            styleObj.style = constants.stylesNonMapbox[val];
            var spec = styleObj.style.sources["plotly-" + val];
            var tiles = spec ? spec.tiles : void 0;
            if (tiles && tiles[0] && tiles[0].slice(-9) === "?api_key=") {
              tiles[0] += fullLayout._mapboxAccessToken;
            }
          } else {
            styleObj.style = val;
          }
        } else {
          styleObj.id = constants.styleValueDflt;
          styleObj.style = convertStyleVal(constants.styleValueDflt);
        }
        styleObj.transition = { duration: 0, delay: 0 };
        return styleObj;
      }
      function convertStyleVal(val) {
        return constants.styleUrlPrefix + val + "-" + constants.styleUrlSuffix;
      }
      function convertCenter(center) {
        return [center.lon, center.lat];
      }
      module.exports = Mapbox;
    }
  });

  // src/plots/mapbox/layout_defaults.js
  var require_layout_defaults17 = __commonJS({
    "src/plots/mapbox/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleSubplotDefaults = require_subplot_defaults();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var layoutAttributes = require_layout_attributes19();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        handleSubplotDefaults(layoutIn, layoutOut, fullData, {
          type: "mapbox",
          attributes: layoutAttributes,
          handleDefaults,
          partition: "y",
          accessToken: layoutOut._mapboxAccessToken
        });
      };
      function handleDefaults(containerIn, containerOut, coerce, opts) {
        coerce("accesstoken", opts.accessToken);
        coerce("style");
        coerce("center.lon");
        coerce("center.lat");
        coerce("zoom");
        coerce("bearing");
        coerce("pitch");
        var west = coerce("bounds.west");
        var east = coerce("bounds.east");
        var south = coerce("bounds.south");
        var north = coerce("bounds.north");
        if (west === void 0 || east === void 0 || south === void 0 || north === void 0) {
          delete containerOut.bounds;
        }
        handleArrayContainerDefaults(containerIn, containerOut, {
          name: "layers",
          handleItemDefaults: handleLayerDefaults
        });
        containerOut._input = containerIn;
      }
      function handleLayerDefaults(layerIn, layerOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layerIn, layerOut, layoutAttributes.layers, attr, dflt);
        }
        var visible = coerce("visible");
        if (visible) {
          var sourceType = coerce("sourcetype");
          var mustBeRasterLayer = sourceType === "raster" || sourceType === "image";
          coerce("source");
          coerce("sourceattribution");
          if (sourceType === "vector") {
            coerce("sourcelayer");
          }
          if (sourceType === "image") {
            coerce("coordinates");
          }
          var typeDflt;
          if (mustBeRasterLayer) typeDflt = "raster";
          var type = coerce("type", typeDflt);
          if (mustBeRasterLayer && type !== "raster") {
            type = layerOut.type = "raster";
            Lib.log("Source types *raster* and *image* must drawn *raster* layer type.");
          }
          coerce("below");
          coerce("color");
          coerce("opacity");
          coerce("minzoom");
          coerce("maxzoom");
          if (type === "circle") {
            coerce("circle.radius");
          }
          if (type === "line") {
            coerce("line.width");
            coerce("line.dash");
          }
          if (type === "fill") {
            coerce("fill.outlinecolor");
          }
          if (type === "symbol") {
            coerce("symbol.icon");
            coerce("symbol.iconsize");
            coerce("symbol.text");
            Lib.coerceFont(coerce, "symbol.textfont", void 0, {
              noFontVariant: true,
              noFontShadow: true,
              noFontLineposition: true,
              noFontTextcase: true
            });
            coerce("symbol.textposition");
            coerce("symbol.placement");
          }
        }
      }
    }
  });

  // src/plots/mapbox/index.js
  var require_mapbox2 = __commonJS({
    "src/plots/mapbox/index.js"(exports) {
      "use strict";
      var mapboxgl = require_mapbox_gl_unminified();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var strScale = Lib.strScale;
      var getSubplotCalcData = require_get_data().getSubplotCalcData;
      var xmlnsNamespaces = require_xmlns_namespaces();
      var d3 = require_d3();
      var Drawing = require_drawing();
      var svgTextUtils = require_svg_text_utils();
      var Mapbox = require_mapbox();
      var MAPBOX = "mapbox";
      var constants = exports.constants = require_constants25();
      exports.name = MAPBOX;
      exports.attr = "subplot";
      exports.idRoot = MAPBOX;
      exports.idRegex = exports.attrRegex = Lib.counterRegex(MAPBOX);
      var deprecationWarning = [
        "mapbox subplots and traces are deprecated!",
        "Please consider switching to `map` subplots and traces.",
        "Learn more at: https://plotly.com/python/maplibre-migration/",
        "as well as https://plotly.com/javascript/maplibre-migration/"
      ].join(" ");
      exports.attributes = {
        subplot: {
          valType: "subplotid",
          dflt: "mapbox",
          editType: "calc"
        }
      };
      exports.layoutAttributes = require_layout_attributes19();
      exports.supplyLayoutDefaults = require_layout_defaults17();
      var firstPlot = true;
      exports.plot = function plot(gd) {
        if (firstPlot) {
          firstPlot = false;
          Lib.warn(deprecationWarning);
        }
        var fullLayout = gd._fullLayout;
        var calcData = gd.calcdata;
        var mapboxIds = fullLayout._subplots[MAPBOX];
        if (mapboxgl.version !== constants.requiredVersion) {
          throw new Error(constants.wrongVersionErrorMsg);
        }
        var accessToken = findAccessToken(gd, mapboxIds);
        mapboxgl.accessToken = accessToken;
        for (var i = 0; i < mapboxIds.length; i++) {
          var id = mapboxIds[i];
          var subplotCalcData = getSubplotCalcData(calcData, MAPBOX, id);
          var opts = fullLayout[id];
          var mapbox = opts._subplot;
          if (!mapbox) {
            mapbox = new Mapbox(gd, id);
            fullLayout[id]._subplot = mapbox;
          }
          if (!mapbox.viewInitial) {
            mapbox.viewInitial = {
              center: Lib.extendFlat({}, opts.center),
              zoom: opts.zoom,
              bearing: opts.bearing,
              pitch: opts.pitch
            };
          }
          mapbox.plot(subplotCalcData, fullLayout, gd._promises);
        }
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldMapboxKeys = oldFullLayout._subplots[MAPBOX] || [];
        for (var i = 0; i < oldMapboxKeys.length; i++) {
          var oldMapboxKey = oldMapboxKeys[i];
          if (!newFullLayout[oldMapboxKey] && !!oldFullLayout[oldMapboxKey]._subplot) {
            oldFullLayout[oldMapboxKey]._subplot.destroy();
          }
        }
      };
      exports.toSVG = function(gd) {
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[MAPBOX];
        var size = fullLayout._size;
        for (var i = 0; i < subplotIds.length; i++) {
          var opts = fullLayout[subplotIds[i]];
          var domain = opts.domain;
          var mapbox = opts._subplot;
          var imageData = mapbox.toImage("png");
          var image = fullLayout._glimages.append("svg:image");
          image.attr({
            xmlns: xmlnsNamespaces.svg,
            "xlink:href": imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: "none"
          });
          var subplotDiv = d3.select(opts._subplot.div);
          var hidden = subplotDiv.select(".mapboxgl-ctrl-logo").node().offsetParent === null;
          if (!hidden) {
            var logo = fullLayout._glimages.append("g");
            logo.attr("transform", strTranslate(size.l + size.w * domain.x[0] + 10, size.t + size.h * (1 - domain.y[0]) - 31));
            logo.append("path").attr("d", constants.mapboxLogo.path0).style({
              opacity: 0.9,
              fill: "#ffffff",
              "enable-background": "new"
            });
            logo.append("path").attr("d", constants.mapboxLogo.path1).style("opacity", 0.35).style("enable-background", "new");
            logo.append("path").attr("d", constants.mapboxLogo.path2).style("opacity", 0.35).style("enable-background", "new");
            logo.append("polygon").attr("points", constants.mapboxLogo.polygon).style({
              opacity: 0.9,
              fill: "#ffffff",
              "enable-background": "new"
            });
          }
          var attributions = subplotDiv.select(".mapboxgl-ctrl-attrib").text().replace("Improve this map", "");
          var attributionGroup = fullLayout._glimages.append("g");
          var attributionText = attributionGroup.append("text");
          attributionText.text(attributions).classed("static-attribution", true).attr({
            "font-size": 12,
            "font-family": "Arial",
            color: "rgba(0, 0, 0, 0.75)",
            "text-anchor": "end",
            "data-unformatted": attributions
          });
          var bBox = Drawing.bBox(attributionText.node());
          var maxWidth = size.w * (domain.x[1] - domain.x[0]);
          if (bBox.width > maxWidth / 2) {
            var multilineAttributions = attributions.split("|").join("<br>");
            attributionText.text(multilineAttributions).attr("data-unformatted", multilineAttributions).call(svgTextUtils.convertToTspans, gd);
            bBox = Drawing.bBox(attributionText.node());
          }
          attributionText.attr("transform", strTranslate(-3, -bBox.height + 8));
          attributionGroup.insert("rect", ".static-attribution").attr({
            x: -bBox.width - 6,
            y: -bBox.height - 3,
            width: bBox.width + 6,
            height: bBox.height + 3,
            fill: "rgba(255, 255, 255, 0.75)"
          });
          var scaleRatio = 1;
          if (bBox.width + 6 > maxWidth) scaleRatio = maxWidth / (bBox.width + 6);
          var offset = [size.l + size.w * domain.x[1], size.t + size.h * (1 - domain.y[0])];
          attributionGroup.attr("transform", strTranslate(offset[0], offset[1]) + strScale(scaleRatio));
        }
      };
      function findAccessToken(gd, mapboxIds) {
        var fullLayout = gd._fullLayout;
        var context = gd._context;
        if (context.mapboxAccessToken === "") return "";
        var tokensUseful = [];
        var tokensListed = [];
        var hasOneSetMapboxStyle = false;
        var wontWork = false;
        for (var i = 0; i < mapboxIds.length; i++) {
          var opts = fullLayout[mapboxIds[i]];
          var token = opts.accesstoken;
          if (isStyleRequireAccessToken(opts.style)) {
            if (token) {
              Lib.pushUnique(tokensUseful, token);
            } else {
              if (isStyleRequireAccessToken(opts._input.style)) {
                Lib.error("Uses Mapbox map style, but did not set an access token.");
                hasOneSetMapboxStyle = true;
              }
              wontWork = true;
            }
          }
          if (token) {
            Lib.pushUnique(tokensListed, token);
          }
        }
        if (wontWork) {
          var msg = hasOneSetMapboxStyle ? constants.noAccessTokenErrorMsg : constants.missingStyleErrorMsg;
          Lib.error(msg);
          throw new Error(msg);
        }
        if (tokensUseful.length) {
          if (tokensUseful.length > 1) {
            Lib.warn(constants.multipleTokensErrorMsg);
          }
          return tokensUseful[0];
        } else {
          if (tokensListed.length) {
            Lib.log([
              "Listed mapbox access token(s)",
              tokensListed.join(","),
              "but did not use a Mapbox map style, ignoring token(s)."
            ].join(" "));
          }
          return "";
        }
      }
      function isStyleRequireAccessToken(s) {
        return typeof s === "string" && (constants.styleValuesMapbox.indexOf(s) !== -1 || s.indexOf("mapbox://") === 0 || s.indexOf("stamen") === 0);
      }
      exports.updateFx = function(gd) {
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[MAPBOX];
        for (var i = 0; i < subplotIds.length; i++) {
          var subplotObj = fullLayout[subplotIds[i]]._subplot;
          subplotObj.updateFx(fullLayout);
        }
      };
    }
  });

  // src/traces/scattermapbox/index.js
  var require_scattermapbox = __commonJS({
    "src/traces/scattermapbox/index.js"(exports, module) {
      "use strict";
      var deprecationWarning = [
        "*scattermapbox* trace is deprecated!",
        "Please consider switching to the *scattermap* trace type and `map` subplots.",
        "Learn more at: https://plotly.com/python/maplibre-migration/",
        "as well as https://plotly.com/javascript/maplibre-migration/"
      ].join(" ");
      module.exports = {
        attributes: require_attributes54(),
        supplyDefaults: require_defaults50(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels5(),
        calc: require_calc27(),
        plot: require_plot23(),
        hoverPoints: require_hover18().hoverPoints,
        eventData: require_event_data11(),
        selectPoints: require_select9(),
        styleOnSelect: function(_, cd) {
          if (cd) {
            var trace = cd[0].trace;
            trace._glTrace.update(cd);
          }
        },
        moduleType: "trace",
        name: "scattermapbox",
        basePlotModule: require_mapbox2(),
        categories: ["mapbox", "gl", "symbols", "showLegend", "scatter-like"],
        meta: {}
      };
    }
  });

  // lib/scattermapbox.js
  var require_scattermapbox2 = __commonJS({
    "lib/scattermapbox.js"(exports, module) {
      "use strict";
      module.exports = require_scattermapbox();
    }
  });

  // src/traces/choroplethmapbox/attributes.js
  var require_attributes55 = __commonJS({
    "src/traces/choroplethmapbox/attributes.js"(exports, module) {
      "use strict";
      var choroplethAttrs = require_attributes49();
      var colorScaleAttrs = require_attributes8();
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      module.exports = extendFlat(
        {
          locations: {
            valType: "data_array",
            editType: "calc"
          },
          // TODO
          // Maybe start with only one value (that we could name e.g. 'geojson-id'),
          // but eventually:
          // - we could also support for our own dist/topojson/*
          //   .. and locationmode: choroplethAttrs.locationmode,
          z: {
            valType: "data_array",
            editType: "calc"
          },
          // TODO maybe we could also set a "key" to dig out values out of the
          // GeoJSON feature `properties` fields?
          geojson: {
            valType: "any",
            editType: "calc"
          },
          featureidkey: extendFlat({}, choroplethAttrs.featureidkey, {}),
          // TODO agree on name / behaviour
          //
          // 'below' is used currently for layout.mapbox.layers,
          // even though it's not very plotly-esque.
          //
          // Note also, that the mapbox-gl style don't all have the same layers,
          // see https://codepen.io/etpinard/pen/ydVMwM for full list
          below: {
            valType: "string",
            editType: "plot"
          },
          text: choroplethAttrs.text,
          hovertext: choroplethAttrs.hovertext,
          marker: {
            line: {
              color: extendFlat({}, choroplethAttrs.marker.line.color, { editType: "plot" }),
              width: extendFlat({}, choroplethAttrs.marker.line.width, { editType: "plot" }),
              editType: "calc"
            },
            // TODO maybe having a dflt less than 1, together with `below:''` would be better?
            opacity: extendFlat({}, choroplethAttrs.marker.opacity, { editType: "plot" }),
            editType: "calc"
          },
          selected: {
            marker: {
              opacity: extendFlat({}, choroplethAttrs.selected.marker.opacity, { editType: "plot" }),
              editType: "plot"
            },
            editType: "plot"
          },
          unselected: {
            marker: {
              opacity: extendFlat({}, choroplethAttrs.unselected.marker.opacity, { editType: "plot" }),
              editType: "plot"
            },
            editType: "plot"
          },
          hoverinfo: choroplethAttrs.hoverinfo,
          hovertemplate: hovertemplateAttrs({}, { keys: ["properties"] }),
          hovertemplatefallback: templatefallbackAttrs(),
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
        },
        colorScaleAttrs("", {
          cLetter: "z",
          editTypeOverride: "calc"
        })
      );
    }
  });

  // src/traces/choroplethmapbox/defaults.js
  var require_defaults51 = __commonJS({
    "src/traces/choroplethmapbox/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes55();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var locations = coerce("locations");
        var z = coerce("z");
        var geojson = coerce("geojson");
        if (!Lib.isArrayOrTypedArray(locations) || !locations.length || !Lib.isArrayOrTypedArray(z) || !z.length || !(typeof geojson === "string" && geojson !== "" || Lib.isPlainObject(geojson))) {
          traceOut.visible = false;
          return;
        }
        coerce("featureidkey");
        traceOut._length = Math.min(locations.length, z.length);
        coerce("below");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var mlw = coerce("marker.line.width");
        if (mlw) coerce("marker.line.color");
        coerce("marker.opacity");
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "z" });
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/choroplethmapbox/convert.js
  var require_convert12 = __commonJS({
    "src/traces/choroplethmapbox/convert.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Colorscale = require_colorscale();
      var Drawing = require_drawing();
      var makeBlank = require_geojson_utils().makeBlank;
      var geoUtils = require_geo_location_utils();
      function convert(calcTrace) {
        var trace = calcTrace[0].trace;
        var isVisible = trace.visible === true && trace._length !== 0;
        var fill = {
          layout: { visibility: "none" },
          paint: {}
        };
        var line = {
          layout: { visibility: "none" },
          paint: {}
        };
        var opts = trace._opts = {
          fill,
          line,
          geojson: makeBlank()
        };
        if (!isVisible) return opts;
        var features = geoUtils.extractTraceFeature(calcTrace);
        if (!features) return opts;
        var sclFunc = Colorscale.makeColorScaleFuncFromTrace(trace);
        var marker = trace.marker;
        var markerLine = marker.line || {};
        var opacityFn;
        if (Lib.isArrayOrTypedArray(marker.opacity)) {
          opacityFn = function(d) {
            var mo = d.mo;
            return isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
          };
        }
        var lineColorFn;
        if (Lib.isArrayOrTypedArray(markerLine.color)) {
          lineColorFn = function(d) {
            return d.mlc;
          };
        }
        var lineWidthFn;
        if (Lib.isArrayOrTypedArray(markerLine.width)) {
          lineWidthFn = function(d) {
            return d.mlw;
          };
        }
        for (var i = 0; i < calcTrace.length; i++) {
          var cdi = calcTrace[i];
          var fOut = cdi.fOut;
          if (fOut) {
            var props = fOut.properties;
            props.fc = sclFunc(cdi.z);
            if (opacityFn) props.mo = opacityFn(cdi);
            if (lineColorFn) props.mlc = lineColorFn(cdi);
            if (lineWidthFn) props.mlw = lineWidthFn(cdi);
            cdi.ct = props.ct;
            cdi._polygons = geoUtils.feature2polygons(fOut);
          }
        }
        var opacitySetting = opacityFn ? { type: "identity", property: "mo" } : marker.opacity;
        Lib.extendFlat(fill.paint, {
          "fill-color": { type: "identity", property: "fc" },
          "fill-opacity": opacitySetting
        });
        Lib.extendFlat(line.paint, {
          "line-color": lineColorFn ? { type: "identity", property: "mlc" } : markerLine.color,
          "line-width": lineWidthFn ? { type: "identity", property: "mlw" } : markerLine.width,
          "line-opacity": opacitySetting
        });
        fill.layout.visibility = "visible";
        line.layout.visibility = "visible";
        opts.geojson = { type: "FeatureCollection", features };
        convertOnSelect(calcTrace);
        return opts;
      }
      function convertOnSelect(calcTrace) {
        var trace = calcTrace[0].trace;
        var opts = trace._opts;
        var opacitySetting;
        if (trace.selectedpoints) {
          var fns = Drawing.makeSelectedPointStyleFns(trace);
          for (var i = 0; i < calcTrace.length; i++) {
            var cdi = calcTrace[i];
            if (cdi.fOut) {
              cdi.fOut.properties.mo2 = fns.selectedOpacityFn(cdi);
            }
          }
          opacitySetting = { type: "identity", property: "mo2" };
        } else {
          opacitySetting = Lib.isArrayOrTypedArray(trace.marker.opacity) ? { type: "identity", property: "mo" } : trace.marker.opacity;
        }
        Lib.extendFlat(opts.fill.paint, { "fill-opacity": opacitySetting });
        Lib.extendFlat(opts.line.paint, { "line-opacity": opacitySetting });
        return opts;
      }
      module.exports = {
        convert,
        convertOnSelect
      };
    }
  });

  // src/traces/choroplethmapbox/plot.js
  var require_plot24 = __commonJS({
    "src/traces/choroplethmapbox/plot.js"(exports, module) {
      "use strict";
      var convert = require_convert12().convert;
      var convertOnSelect = require_convert12().convertOnSelect;
      var LAYER_PREFIX = require_constants25().traceLayerPrefix;
      function ChoroplethMapbox(subplot, uid) {
        this.type = "choroplethmapbox";
        this.subplot = subplot;
        this.uid = uid;
        this.sourceId = "source-" + uid;
        this.layerList = [
          ["fill", LAYER_PREFIX + uid + "-fill"],
          ["line", LAYER_PREFIX + uid + "-line"]
        ];
        this.below = null;
      }
      var proto = ChoroplethMapbox.prototype;
      proto.update = function(calcTrace) {
        this._update(convert(calcTrace));
        calcTrace[0].trace._glTrace = this;
      };
      proto.updateOnSelect = function(calcTrace) {
        this._update(convertOnSelect(calcTrace));
      };
      proto._update = function(optsAll) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var below = subplot.belowLookup["trace-" + this.uid];
        subplot.map.getSource(this.sourceId).setData(optsAll.geojson);
        if (below !== this.below) {
          this._removeLayers();
          this._addLayers(optsAll, below);
          this.below = below;
        }
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var id = item[1];
          var opts = optsAll[k];
          subplot.setOptions(id, "setLayoutProperty", opts.layout);
          if (opts.layout.visibility === "visible") {
            subplot.setOptions(id, "setPaintProperty", opts.paint);
          }
        }
      };
      proto._addLayers = function(optsAll, below) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var sourceId = this.sourceId;
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var opts = optsAll[k];
          subplot.addLayer({
            type: k,
            id: item[1],
            source: sourceId,
            layout: opts.layout,
            paint: opts.paint
          }, below);
        }
      };
      proto._removeLayers = function() {
        var map = this.subplot.map;
        var layerList = this.layerList;
        for (var i = layerList.length - 1; i >= 0; i--) {
          map.removeLayer(layerList[i][1]);
        }
      };
      proto.dispose = function() {
        var map = this.subplot.map;
        this._removeLayers();
        map.removeSource(this.sourceId);
      };
      module.exports = function createChoroplethMapbox(subplot, calcTrace) {
        var trace = calcTrace[0].trace;
        var choroplethMapbox = new ChoroplethMapbox(subplot, trace.uid);
        var sourceId = choroplethMapbox.sourceId;
        var optsAll = convert(calcTrace);
        var below = choroplethMapbox.below = subplot.belowLookup["trace-" + trace.uid];
        subplot.map.addSource(sourceId, {
          type: "geojson",
          data: optsAll.geojson
        });
        choroplethMapbox._addLayers(optsAll, below);
        calcTrace[0].trace._glTrace = choroplethMapbox;
        return choroplethMapbox;
      };
    }
  });

  // src/traces/choroplethmapbox/index.js
  var require_choroplethmapbox = __commonJS({
    "src/traces/choroplethmapbox/index.js"(exports, module) {
      "use strict";
      var deprecationWarning = [
        "*choroplethmapbox* trace is deprecated!",
        "Please consider switching to the *choroplethmap* trace type and `map` subplots.",
        "Learn more at: https://plotly.com/python/maplibre-migration/",
        "as well as https://plotly.com/javascript/maplibre-migration/"
      ].join(" ");
      module.exports = {
        attributes: require_attributes55(),
        supplyDefaults: require_defaults51(),
        colorbar: require_colorbar2(),
        calc: require_calc28(),
        plot: require_plot24(),
        hoverPoints: require_hover15(),
        eventData: require_event_data10(),
        selectPoints: require_select6(),
        styleOnSelect: function(_, cd) {
          if (cd) {
            var trace = cd[0].trace;
            trace._glTrace.updateOnSelect(cd);
          }
        },
        getBelow: function(trace, subplot) {
          var mapLayers = subplot.getMapLayers();
          for (var i = mapLayers.length - 2; i >= 0; i--) {
            var layerId = mapLayers[i].id;
            if (typeof layerId === "string" && layerId.indexOf("water") === 0) {
              for (var j = i + 1; j < mapLayers.length; j++) {
                layerId = mapLayers[j].id;
                if (typeof layerId === "string" && layerId.indexOf("plotly-") === -1) {
                  return layerId;
                }
              }
            }
          }
        },
        moduleType: "trace",
        name: "choroplethmapbox",
        basePlotModule: require_mapbox2(),
        categories: ["mapbox", "gl", "noOpacity", "showLegend"],
        meta: {
          hr_name: "choropleth_mapbox"
        }
      };
    }
  });

  // lib/choroplethmapbox.js
  var require_choroplethmapbox2 = __commonJS({
    "lib/choroplethmapbox.js"(exports, module) {
      "use strict";
      module.exports = require_choroplethmapbox();
    }
  });

  // src/traces/densitymapbox/attributes.js
  var require_attributes56 = __commonJS({
    "src/traces/densitymapbox/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var baseAttrs = require_attributes2();
      var scatterMapboxAttrs = require_attributes54();
      var extendFlat = require_extend().extendFlat;
      module.exports = extendFlat(
        {
          lon: scatterMapboxAttrs.lon,
          lat: scatterMapboxAttrs.lat,
          z: {
            valType: "data_array",
            editType: "calc"
          },
          radius: {
            valType: "number",
            editType: "plot",
            arrayOk: true,
            min: 1,
            dflt: 30
          },
          below: {
            valType: "string",
            editType: "plot"
          },
          text: scatterMapboxAttrs.text,
          hovertext: scatterMapboxAttrs.hovertext,
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
            flags: ["lon", "lat", "z", "text", "name"]
          }),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs(),
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
        },
        colorScaleAttrs("", {
          cLetter: "z",
          editTypeOverride: "calc"
        })
      );
    }
  });

  // src/traces/densitymapbox/defaults.js
  var require_defaults52 = __commonJS({
    "src/traces/densitymapbox/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes56();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var lon = coerce("lon") || [];
        var lat = coerce("lat") || [];
        var len = Math.min(lon.length, lat.length);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        coerce("z");
        coerce("radius");
        coerce("below");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "z" });
      };
    }
  });

  // src/traces/densitymapbox/calc.js
  var require_calc33 = __commonJS({
    "src/traces/densitymapbox/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var BADNUM = require_numerical().BADNUM;
      var colorscaleCalc = require_calc();
      var _ = require_lib()._;
      module.exports = function calc(gd, trace) {
        var len = trace._length;
        var calcTrace = new Array(len);
        var z = trace.z;
        var hasZ = isArrayOrTypedArray(z) && z.length;
        for (var i = 0; i < len; i++) {
          var cdi = calcTrace[i] = {};
          var lon = trace.lon[i];
          var lat = trace.lat[i];
          cdi.lonlat = isNumeric(lon) && isNumeric(lat) ? [+lon, +lat] : [BADNUM, BADNUM];
          if (hasZ) {
            var zi = z[i];
            cdi.z = isNumeric(zi) ? zi : BADNUM;
          }
        }
        colorscaleCalc(gd, trace, {
          vals: hasZ ? z : [0, 1],
          containerStr: "",
          cLetter: "z"
        });
        if (len) {
          calcTrace[0].t = {
            labels: {
              lat: _(gd, "lat:") + " ",
              lon: _(gd, "lon:") + " "
            }
          };
        }
        return calcTrace;
      };
    }
  });

  // src/traces/densitymapbox/convert.js
  var require_convert13 = __commonJS({
    "src/traces/densitymapbox/convert.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Color2 = require_color();
      var Colorscale = require_colorscale();
      var BADNUM = require_numerical().BADNUM;
      var makeBlank = require_geojson_utils().makeBlank;
      module.exports = function convert(calcTrace) {
        var trace = calcTrace[0].trace;
        var isVisible = trace.visible === true && trace._length !== 0;
        var heatmap = {
          layout: { visibility: "none" },
          paint: {}
        };
        var opts = trace._opts = {
          heatmap,
          geojson: makeBlank()
        };
        if (!isVisible) return opts;
        var features = [];
        var i;
        var z = trace.z;
        var radius = trace.radius;
        var hasZ = Lib.isArrayOrTypedArray(z) && z.length;
        var hasArrayRadius = Lib.isArrayOrTypedArray(radius);
        for (i = 0; i < calcTrace.length; i++) {
          var cdi = calcTrace[i];
          var lonlat = cdi.lonlat;
          if (lonlat[0] !== BADNUM) {
            var props = {};
            if (hasZ) {
              var zi = cdi.z;
              props.z = zi !== BADNUM ? zi : 0;
            }
            if (hasArrayRadius) {
              props.r = isNumeric(radius[i]) && radius[i] > 0 ? +radius[i] : 0;
            }
            features.push({
              type: "Feature",
              geometry: { type: "Point", coordinates: lonlat },
              properties: props
            });
          }
        }
        var cOpts = Colorscale.extractOpts(trace);
        var scl = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : cOpts.colorscale;
        var scl01 = scl[0][1];
        var color0 = Color2.opacity(scl01) < 1 ? scl01 : Color2.addOpacity(scl01, 0);
        var heatmapColor = [
          "interpolate",
          ["linear"],
          ["heatmap-density"],
          0,
          color0
        ];
        for (i = 1; i < scl.length; i++) {
          heatmapColor.push(scl[i][0], scl[i][1]);
        }
        var zExp = [
          "interpolate",
          ["linear"],
          ["get", "z"],
          cOpts.min,
          0,
          cOpts.max,
          1
        ];
        Lib.extendFlat(opts.heatmap.paint, {
          "heatmap-weight": hasZ ? zExp : 1 / (cOpts.max - cOpts.min),
          "heatmap-color": heatmapColor,
          "heatmap-radius": hasArrayRadius ? { type: "identity", property: "r" } : trace.radius,
          "heatmap-opacity": trace.opacity
        });
        opts.geojson = { type: "FeatureCollection", features };
        opts.heatmap.layout.visibility = "visible";
        return opts;
      };
    }
  });

  // src/traces/densitymapbox/plot.js
  var require_plot25 = __commonJS({
    "src/traces/densitymapbox/plot.js"(exports, module) {
      "use strict";
      var convert = require_convert13();
      var LAYER_PREFIX = require_constants25().traceLayerPrefix;
      function DensityMapbox(subplot, uid) {
        this.type = "densitymapbox";
        this.subplot = subplot;
        this.uid = uid;
        this.sourceId = "source-" + uid;
        this.layerList = [
          ["heatmap", LAYER_PREFIX + uid + "-heatmap"]
        ];
        this.below = null;
      }
      var proto = DensityMapbox.prototype;
      proto.update = function(calcTrace) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var optsAll = convert(calcTrace);
        var below = subplot.belowLookup["trace-" + this.uid];
        subplot.map.getSource(this.sourceId).setData(optsAll.geojson);
        if (below !== this.below) {
          this._removeLayers();
          this._addLayers(optsAll, below);
          this.below = below;
        }
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var id = item[1];
          var opts = optsAll[k];
          subplot.setOptions(id, "setLayoutProperty", opts.layout);
          if (opts.layout.visibility === "visible") {
            subplot.setOptions(id, "setPaintProperty", opts.paint);
          }
        }
      };
      proto._addLayers = function(optsAll, below) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var sourceId = this.sourceId;
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var opts = optsAll[k];
          subplot.addLayer({
            type: k,
            id: item[1],
            source: sourceId,
            layout: opts.layout,
            paint: opts.paint
          }, below);
        }
      };
      proto._removeLayers = function() {
        var map = this.subplot.map;
        var layerList = this.layerList;
        for (var i = layerList.length - 1; i >= 0; i--) {
          map.removeLayer(layerList[i][1]);
        }
      };
      proto.dispose = function() {
        var map = this.subplot.map;
        this._removeLayers();
        map.removeSource(this.sourceId);
      };
      module.exports = function createDensityMapbox(subplot, calcTrace) {
        var trace = calcTrace[0].trace;
        var densityMapbox = new DensityMapbox(subplot, trace.uid);
        var sourceId = densityMapbox.sourceId;
        var optsAll = convert(calcTrace);
        var below = densityMapbox.below = subplot.belowLookup["trace-" + trace.uid];
        subplot.map.addSource(sourceId, {
          type: "geojson",
          data: optsAll.geojson
        });
        densityMapbox._addLayers(optsAll, below);
        return densityMapbox;
      };
    }
  });

  // src/traces/densitymapbox/hover.js
  var require_hover19 = __commonJS({
    "src/traces/densitymapbox/hover.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var scatterMapboxHoverPoints = require_hover18().hoverPoints;
      var getExtraText = require_hover18().getExtraText;
      module.exports = function hoverPoints(pointData, xval, yval) {
        var pts = scatterMapboxHoverPoints(pointData, xval, yval);
        if (!pts) return;
        var newPointData = pts[0];
        var cd = newPointData.cd;
        var trace = cd[0].trace;
        var di = cd[newPointData.index];
        delete newPointData.color;
        if ("z" in di) {
          var ax = newPointData.subplot.mockAxis;
          newPointData.z = di.z;
          newPointData.zLabel = Axes.tickText(ax, ax.c2l(di.z), "hover").text;
        }
        newPointData.extraText = getExtraText(trace, di, cd[0].t.labels);
        return [newPointData];
      };
    }
  });

  // src/traces/densitymapbox/event_data.js
  var require_event_data12 = __commonJS({
    "src/traces/densitymapbox/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        out.lon = pt.lon;
        out.lat = pt.lat;
        out.z = pt.z;
        return out;
      };
    }
  });

  // src/traces/densitymapbox/index.js
  var require_densitymapbox = __commonJS({
    "src/traces/densitymapbox/index.js"(exports, module) {
      "use strict";
      var deprecationWarning = [
        "*densitymapbox* trace is deprecated!",
        "Please consider switching to the *densitymap* trace type and `map` subplots.",
        "Learn more at: https://plotly.com/python/maplibre-migration/",
        "as well as https://plotly.com/javascript/maplibre-migration/"
      ].join(" ");
      module.exports = {
        attributes: require_attributes56(),
        supplyDefaults: require_defaults52(),
        colorbar: require_colorbar2(),
        formatLabels: require_format_labels5(),
        calc: require_calc33(),
        plot: require_plot25(),
        hoverPoints: require_hover19(),
        eventData: require_event_data12(),
        getBelow: function(trace, subplot) {
          var mapLayers = subplot.getMapLayers();
          for (var i = 0; i < mapLayers.length; i++) {
            var layer = mapLayers[i];
            var layerId = layer.id;
            if (layer.type === "symbol" && typeof layerId === "string" && layerId.indexOf("plotly-") === -1) {
              return layerId;
            }
          }
        },
        moduleType: "trace",
        name: "densitymapbox",
        basePlotModule: require_mapbox2(),
        categories: ["mapbox", "gl", "showLegend"],
        meta: {
          hr_name: "density_mapbox"
        }
      };
    }
  });

  // lib/densitymapbox.js
  var require_densitymapbox2 = __commonJS({
    "lib/densitymapbox.js"(exports, module) {
      "use strict";
      module.exports = require_densitymapbox();
    }
  });

  // src/plots/map/styles/arcgis-sat-hybrid.js
  var require_arcgis_sat_hybrid = __commonJS({
    "src/plots/map/styles/arcgis-sat-hybrid.js"(exports, module) {
      module.exports = {
        "version": 8,
        "name": "orto",
        "metadata": { "maputnik:renderer": "mlgljs" },
        "center": [1.537786, 41.837539],
        "zoom": 12,
        "bearing": 0,
        "pitch": 0,
        "light": {
          "anchor": "viewport",
          "color": "white",
          "intensity": 0.4,
          "position": [1.15, 45, 30]
        },
        "sources": {
          "ortoEsri": {
            "type": "raster",
            "tiles": [
              "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
            ],
            "tileSize": 256,
            "maxzoom": 18,
            "attribution": "ESRI &copy; <a href='http://www.esri.com'>ESRI</a>"
          },
          "ortoInstaMaps": {
            "type": "raster",
            "tiles": [
              "https://tilemaps.icgc.cat/mapfactory/wmts/orto_8_12/CAT3857/{z}/{x}/{y}.png"
            ],
            "tileSize": 256,
            "maxzoom": 13
          },
          "ortoICGC": {
            "type": "raster",
            "tiles": [
              "https://geoserveis.icgc.cat/icc_mapesmultibase/noutm/wmts/orto/GRID3857/{z}/{x}/{y}.jpeg"
            ],
            "tileSize": 256,
            "minzoom": 13.1,
            "maxzoom": 20
          },
          "openmaptiles": {
            "type": "vector",
            "url": "https://geoserveis.icgc.cat/contextmaps/basemap.json"
          }
        },
        "sprite": "https://geoserveis.icgc.cat/contextmaps/sprites/sprite@1",
        "glyphs": "https://geoserveis.icgc.cat/contextmaps/glyphs/{fontstack}/{range}.pbf",
        "layers": [
          {
            "id": "background",
            "type": "background",
            "paint": { "background-color": "#F4F9F4" }
          },
          {
            "id": "ortoEsri",
            "type": "raster",
            "source": "ortoEsri",
            "maxzoom": 16,
            "layout": { "visibility": "visible" }
          },
          {
            "id": "ortoICGC",
            "type": "raster",
            "source": "ortoICGC",
            "minzoom": 13.1,
            "maxzoom": 19,
            "layout": { "visibility": "visible" }
          },
          {
            "id": "ortoInstaMaps",
            "type": "raster",
            "source": "ortoInstaMaps",
            "maxzoom": 13,
            "layout": { "visibility": "visible" }
          },
          {
            "id": "waterway_tunnel",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "waterway",
            "minzoom": 14,
            "filter": [
              "all",
              ["in", "class", "river", "stream", "canal"],
              ["==", "brunnel", "tunnel"]
            ],
            "layout": { "line-cap": "round" },
            "paint": {
              "line-color": "#a0c8f0",
              "line-width": { "base": 1.3, "stops": [[13, 0.5], [20, 6]] },
              "line-dasharray": [2, 4]
            }
          },
          {
            "id": "waterway-other",
            "type": "line",
            "metadata": { "mapbox:group": "1444849382550.77" },
            "source": "openmaptiles",
            "source-layer": "waterway",
            "filter": ["!in", "class", "canal", "river", "stream"],
            "layout": { "line-cap": "round" },
            "paint": {
              "line-color": "#a0c8f0",
              "line-width": { "base": 1.3, "stops": [[13, 0.5], [20, 2]] }
            }
          },
          {
            "id": "waterway-stream-canal",
            "type": "line",
            "metadata": { "mapbox:group": "1444849382550.77" },
            "source": "openmaptiles",
            "source-layer": "waterway",
            "filter": [
              "all",
              ["in", "class", "canal", "stream"],
              ["!=", "brunnel", "tunnel"]
            ],
            "layout": { "line-cap": "round" },
            "paint": {
              "line-color": "#a0c8f0",
              "line-width": { "base": 1.3, "stops": [[13, 0.5], [20, 6]] }
            }
          },
          {
            "id": "waterway-river",
            "type": "line",
            "metadata": { "mapbox:group": "1444849382550.77" },
            "source": "openmaptiles",
            "source-layer": "waterway",
            "filter": ["all", ["==", "class", "river"], ["!=", "brunnel", "tunnel"]],
            "layout": { "line-cap": "round" },
            "paint": {
              "line-color": "#a0c8f0",
              "line-width": { "base": 1.2, "stops": [[10, 0.8], [20, 4]] },
              "line-opacity": 0.5
            }
          },
          {
            "id": "water-offset",
            "type": "fill",
            "metadata": { "mapbox:group": "1444849382550.77" },
            "source": "openmaptiles",
            "source-layer": "water",
            "maxzoom": 8,
            "filter": ["==", "$type", "Polygon"],
            "layout": { "visibility": "visible" },
            "paint": {
              "fill-opacity": 0,
              "fill-color": "#a0c8f0",
              "fill-translate": { "base": 1, "stops": [[6, [2, 0]], [8, [0, 0]]] }
            }
          },
          {
            "id": "water",
            "type": "fill",
            "metadata": { "mapbox:group": "1444849382550.77" },
            "source": "openmaptiles",
            "source-layer": "water",
            "layout": { "visibility": "visible" },
            "paint": { "fill-color": "hsl(210, 67%, 85%)", "fill-opacity": 0 }
          },
          {
            "id": "water-pattern",
            "type": "fill",
            "metadata": { "mapbox:group": "1444849382550.77" },
            "source": "openmaptiles",
            "source-layer": "water",
            "layout": { "visibility": "visible" },
            "paint": {
              "fill-translate": [0, 2.5],
              "fill-pattern": "wave",
              "fill-opacity": 1
            }
          },
          {
            "id": "landcover-ice-shelf",
            "type": "fill",
            "metadata": { "mapbox:group": "1444849382550.77" },
            "source": "openmaptiles",
            "source-layer": "landcover",
            "filter": ["==", "subclass", "ice_shelf"],
            "layout": { "visibility": "visible" },
            "paint": {
              "fill-color": "#fff",
              "fill-opacity": { "base": 1, "stops": [[0, 0.9], [10, 0.3]] }
            }
          },
          {
            "id": "tunnel-service-track-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["in", "class", "service", "track"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#cfcdca",
              "line-dasharray": [0.5, 0.25],
              "line-width": { "base": 1.2, "stops": [[15, 1], [16, 4], [20, 11]] }
            }
          },
          {
            "id": "tunnel-minor-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": ["all", ["==", "brunnel", "tunnel"], ["==", "class", "minor"]],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#cfcdca",
              "line-opacity": { "stops": [[12, 0], [12.5, 1]] },
              "line-width": {
                "base": 1.2,
                "stops": [[12, 0.5], [13, 1], [14, 4], [20, 15]]
              }
            }
          },
          {
            "id": "tunnel-secondary-tertiary-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["in", "class", "secondary", "tertiary"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": 1,
              "line-width": { "base": 1.2, "stops": [[8, 1.5], [20, 17]] }
            }
          },
          {
            "id": "tunnel-trunk-primary-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["in", "class", "primary", "trunk"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#e9ac77",
              "line-width": {
                "base": 1.2,
                "stops": [[5, 0.4], [6, 0.6], [7, 1.5], [20, 22]]
              },
              "line-opacity": 0.7
            }
          },
          {
            "id": "tunnel-motorway-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["==", "class", "motorway"]
            ],
            "layout": { "line-join": "round", "visibility": "visible" },
            "paint": {
              "line-color": "#e9ac77",
              "line-dasharray": [0.5, 0.25],
              "line-width": {
                "base": 1.2,
                "stops": [[5, 0.4], [6, 0.6], [7, 1.5], [20, 22]]
              },
              "line-opacity": 0.5
            }
          },
          {
            "id": "tunnel-path",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["==", "brunnel", "tunnel"], ["==", "class", "path"]]
            ],
            "paint": {
              "line-color": "#cba",
              "line-dasharray": [1.5, 0.75],
              "line-width": { "base": 1.2, "stops": [[15, 1.2], [20, 4]] }
            }
          },
          {
            "id": "tunnel-service-track",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["in", "class", "service", "track"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fff",
              "line-width": { "base": 1.2, "stops": [[15.5, 0], [16, 2], [20, 7.5]] }
            }
          },
          {
            "id": "tunnel-minor",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["==", "class", "minor_road"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fff",
              "line-opacity": 1,
              "line-width": { "base": 1.2, "stops": [[13.5, 0], [14, 2.5], [20, 11.5]] }
            }
          },
          {
            "id": "tunnel-secondary-tertiary",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["in", "class", "secondary", "tertiary"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fff4c6",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 10]] }
            }
          },
          {
            "id": "tunnel-trunk-primary",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["in", "class", "primary", "trunk"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fff4c6",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 18]] },
              "line-opacity": 0.5
            }
          },
          {
            "id": "tunnel-motorway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "tunnel"],
              ["==", "class", "motorway"]
            ],
            "layout": { "line-join": "round", "visibility": "visible" },
            "paint": {
              "line-color": "#ffdaa6",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 18]] },
              "line-opacity": 0.5
            }
          },
          {
            "id": "tunnel-railway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849354174.1904" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": ["all", ["==", "brunnel", "tunnel"], ["==", "class", "rail"]],
            "paint": {
              "line-color": "#bbb",
              "line-width": { "base": 1.4, "stops": [[14, 0.4], [15, 0.75], [20, 2]] },
              "line-dasharray": [2, 2]
            }
          },
          {
            "id": "ferry",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": ["all", ["in", "class", "ferry"]],
            "layout": { "line-join": "round", "visibility": "visible" },
            "paint": {
              "line-color": "rgba(108, 159, 182, 1)",
              "line-width": 1.1,
              "line-dasharray": [2, 2]
            }
          },
          {
            "id": "aeroway-taxiway-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "aeroway",
            "minzoom": 12,
            "filter": ["all", ["in", "class", "taxiway"]],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "rgba(153, 153, 153, 1)",
              "line-width": { "base": 1.5, "stops": [[11, 2], [17, 12]] },
              "line-opacity": 1
            }
          },
          {
            "id": "aeroway-runway-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "aeroway",
            "minzoom": 12,
            "filter": ["all", ["in", "class", "runway"]],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "rgba(153, 153, 153, 1)",
              "line-width": { "base": 1.5, "stops": [[11, 5], [17, 55]] },
              "line-opacity": 1
            }
          },
          {
            "id": "aeroway-taxiway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "aeroway",
            "minzoom": 4,
            "filter": [
              "all",
              ["in", "class", "taxiway"],
              ["==", "$type", "LineString"]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "rgba(255, 255, 255, 1)",
              "line-width": { "base": 1.5, "stops": [[11, 1], [17, 10]] },
              "line-opacity": { "base": 1, "stops": [[11, 0], [12, 1]] }
            }
          },
          {
            "id": "aeroway-runway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "aeroway",
            "minzoom": 4,
            "filter": [
              "all",
              ["in", "class", "runway"],
              ["==", "$type", "LineString"]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "rgba(255, 255, 255, 1)",
              "line-width": { "base": 1.5, "stops": [[11, 4], [17, 50]] },
              "line-opacity": { "base": 1, "stops": [[11, 0], [12, 1]] }
            }
          },
          {
            "id": "highway-motorway-link-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 12,
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              ["==", "class", "motorway_link"]
            ],
            "layout": { "line-cap": "round", "line-join": "round" },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": 1,
              "line-width": {
                "base": 1.2,
                "stops": [[12, 1], [13, 3], [14, 4], [20, 15]]
              }
            }
          },
          {
            "id": "highway-link-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 13,
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              [
                "in",
                "class",
                "primary_link",
                "secondary_link",
                "tertiary_link",
                "trunk_link"
              ]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": 1,
              "line-width": {
                "base": 1.2,
                "stops": [[12, 1], [13, 3], [14, 4], [20, 15]]
              }
            }
          },
          {
            "id": "highway-minor-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              [
                "all",
                ["!=", "brunnel", "tunnel"],
                ["in", "class", "minor", "service", "track"]
              ]
            ],
            "layout": { "line-cap": "round", "line-join": "round" },
            "paint": {
              "line-color": "#cfcdca",
              "line-opacity": { "stops": [[12, 0], [12.5, 0]] },
              "line-width": {
                "base": 1.2,
                "stops": [[12, 0.5], [13, 1], [14, 4], [20, 15]]
              }
            }
          },
          {
            "id": "highway-secondary-tertiary-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              ["in", "class", "secondary", "tertiary"]
            ],
            "layout": {
              "line-cap": "butt",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": 0.5,
              "line-width": { "base": 1.2, "stops": [[8, 1.5], [20, 17]] }
            }
          },
          {
            "id": "highway-primary-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 5,
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              ["in", "class", "primary"]
            ],
            "layout": {
              "line-cap": "butt",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": { "stops": [[7, 0], [8, 0.6]] },
              "line-width": {
                "base": 1.2,
                "stops": [[7, 0], [8, 0.6], [9, 1.5], [20, 22]]
              }
            }
          },
          {
            "id": "highway-trunk-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 5,
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              ["in", "class", "trunk"]
            ],
            "layout": {
              "line-cap": "butt",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": { "stops": [[5, 0], [6, 0.5]] },
              "line-width": {
                "base": 1.2,
                "stops": [[5, 0], [6, 0.6], [7, 1.5], [20, 22]]
              }
            }
          },
          {
            "id": "highway-motorway-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 4,
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              ["==", "class", "motorway"]
            ],
            "layout": {
              "line-cap": "butt",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#e9ac77",
              "line-width": {
                "base": 1.2,
                "stops": [[4, 0], [5, 0.4], [6, 0.6], [7, 1.5], [20, 22]]
              },
              "line-opacity": { "stops": [[4, 0], [5, 0.5]] }
            }
          },
          {
            "id": "highway-path",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["!in", "brunnel", "bridge", "tunnel"], ["==", "class", "path"]]
            ],
            "paint": {
              "line-color": "#cba",
              "line-dasharray": [1.5, 0.75],
              "line-width": { "base": 1.2, "stops": [[15, 1.2], [20, 4]] }
            }
          },
          {
            "id": "highway-motorway-link",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 12,
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              ["==", "class", "motorway_link"]
            ],
            "layout": { "line-cap": "round", "line-join": "round" },
            "paint": {
              "line-color": "#fc8",
              "line-width": {
                "base": 1.2,
                "stops": [[12.5, 0], [13, 1.5], [14, 2.5], [20, 11.5]]
              }
            }
          },
          {
            "id": "highway-link",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 13,
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              [
                "in",
                "class",
                "primary_link",
                "secondary_link",
                "tertiary_link",
                "trunk_link"
              ]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#fea",
              "line-width": {
                "base": 1.2,
                "stops": [[12.5, 0], [13, 1.5], [14, 2.5], [20, 11.5]]
              }
            }
          },
          {
            "id": "highway-minor",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              [
                "all",
                ["!=", "brunnel", "tunnel"],
                ["in", "class", "minor", "service", "track"]
              ]
            ],
            "layout": { "line-cap": "round", "line-join": "round" },
            "paint": {
              "line-color": "#fff",
              "line-opacity": 0.5,
              "line-width": { "base": 1.2, "stops": [[13.5, 0], [14, 2.5], [20, 11.5]] }
            }
          },
          {
            "id": "highway-secondary-tertiary",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["!in", "brunnel", "bridge", "tunnel"],
              ["in", "class", "secondary", "tertiary"]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#fea",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [8, 0.5], [20, 13]] },
              "line-opacity": 0.5
            }
          },
          {
            "id": "highway-primary",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              [
                "all",
                ["!in", "brunnel", "bridge", "tunnel"],
                ["in", "class", "primary"]
              ]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#fea",
              "line-width": { "base": 1.2, "stops": [[8.5, 0], [9, 0.5], [20, 18]] },
              "line-opacity": 0
            }
          },
          {
            "id": "highway-trunk",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              [
                "all",
                ["!in", "brunnel", "bridge", "tunnel"],
                ["in", "class", "trunk"]
              ]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#fea",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 18]] },
              "line-opacity": 0.5
            }
          },
          {
            "id": "highway-motorway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 5,
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              [
                "all",
                ["!in", "brunnel", "bridge", "tunnel"],
                ["==", "class", "motorway"]
              ]
            ],
            "layout": {
              "line-cap": "round",
              "line-join": "round",
              "visibility": "visible"
            },
            "paint": {
              "line-color": "#fc8",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 18]] },
              "line-opacity": 0.5
            }
          },
          {
            "id": "railway-transit",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["==", "class", "transit"], ["!in", "brunnel", "tunnel"]]
            ],
            "layout": { "visibility": "visible" },
            "paint": {
              "line-color": "hsla(0, 0%, 73%, 0.77)",
              "line-width": { "base": 1.4, "stops": [[14, 0.4], [20, 1]] }
            }
          },
          {
            "id": "railway-transit-hatching",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["==", "class", "transit"], ["!in", "brunnel", "tunnel"]]
            ],
            "layout": { "visibility": "visible" },
            "paint": {
              "line-color": "hsla(0, 0%, 73%, 0.68)",
              "line-dasharray": [0.2, 8],
              "line-width": { "base": 1.4, "stops": [[14.5, 0], [15, 2], [20, 6]] }
            }
          },
          {
            "id": "railway-service",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["==", "class", "rail"], ["has", "service"]]
            ],
            "paint": {
              "line-color": "hsla(0, 0%, 73%, 0.77)",
              "line-width": { "base": 1.4, "stops": [[14, 0.4], [20, 1]] }
            }
          },
          {
            "id": "railway-service-hatching",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["==", "class", "rail"], ["has", "service"]]
            ],
            "layout": { "visibility": "visible" },
            "paint": {
              "line-color": "hsla(0, 0%, 73%, 0.68)",
              "line-dasharray": [0.2, 8],
              "line-width": { "base": 1.4, "stops": [[14.5, 0], [15, 2], [20, 6]] }
            }
          },
          {
            "id": "railway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              [
                "all",
                ["!has", "service"],
                ["!in", "brunnel", "bridge", "tunnel"],
                ["==", "class", "rail"]
              ]
            ],
            "paint": {
              "line-color": "#bbb",
              "line-width": { "base": 1.4, "stops": [[14, 0.4], [15, 0.75], [20, 2]] }
            }
          },
          {
            "id": "railway-hatching",
            "type": "line",
            "metadata": { "mapbox:group": "1444849345966.4436" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              [
                "all",
                ["!has", "service"],
                ["!in", "brunnel", "bridge", "tunnel"],
                ["==", "class", "rail"]
              ]
            ],
            "paint": {
              "line-color": "#bbb",
              "line-dasharray": [0.2, 8],
              "line-width": { "base": 1.4, "stops": [[14.5, 0], [15, 3], [20, 8]] }
            }
          },
          {
            "id": "bridge-motorway-link-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["==", "class", "motorway_link"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": 1,
              "line-width": {
                "base": 1.2,
                "stops": [[12, 1], [13, 3], [14, 4], [20, 15]]
              }
            }
          },
          {
            "id": "bridge-link-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              [
                "in",
                "class",
                "primary_link",
                "secondary_link",
                "tertiary_link",
                "trunk_link"
              ]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": 1,
              "line-width": {
                "base": 1.2,
                "stops": [[12, 1], [13, 3], [14, 4], [20, 15]]
              }
            }
          },
          {
            "id": "bridge-secondary-tertiary-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["in", "class", "secondary", "tertiary"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#e9ac77",
              "line-opacity": 1,
              "line-width": { "base": 1.2, "stops": [[8, 1.5], [20, 28]] }
            }
          },
          {
            "id": "bridge-trunk-primary-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["in", "class", "primary", "trunk"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "hsl(28, 76%, 67%)",
              "line-width": {
                "base": 1.2,
                "stops": [[5, 0.4], [6, 0.6], [7, 1.5], [20, 26]]
              }
            }
          },
          {
            "id": "bridge-motorway-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["==", "class", "motorway"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#e9ac77",
              "line-width": {
                "base": 1.2,
                "stops": [[5, 0.4], [6, 0.6], [7, 1.5], [20, 22]]
              },
              "line-opacity": 0.5
            }
          },
          {
            "id": "bridge-path-casing",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["==", "brunnel", "bridge"], ["==", "class", "path"]]
            ],
            "paint": {
              "line-color": "#f8f4f0",
              "line-width": { "base": 1.2, "stops": [[15, 1.2], [20, 18]] }
            }
          },
          {
            "id": "bridge-path",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["all", ["==", "brunnel", "bridge"], ["==", "class", "path"]]
            ],
            "paint": {
              "line-color": "#cba",
              "line-width": { "base": 1.2, "stops": [[15, 1.2], [20, 4]] },
              "line-dasharray": [1.5, 0.75]
            }
          },
          {
            "id": "bridge-motorway-link",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["==", "class", "motorway_link"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fc8",
              "line-width": {
                "base": 1.2,
                "stops": [[12.5, 0], [13, 1.5], [14, 2.5], [20, 11.5]]
              }
            }
          },
          {
            "id": "bridge-link",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              [
                "in",
                "class",
                "primary_link",
                "secondary_link",
                "tertiary_link",
                "trunk_link"
              ]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fea",
              "line-width": {
                "base": 1.2,
                "stops": [[12.5, 0], [13, 1.5], [14, 2.5], [20, 11.5]]
              }
            }
          },
          {
            "id": "bridge-secondary-tertiary",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["in", "class", "secondary", "tertiary"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fea",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 20]] }
            }
          },
          {
            "id": "bridge-trunk-primary",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["in", "class", "primary", "trunk"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fea",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 18]] }
            }
          },
          {
            "id": "bridge-motorway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": [
              "all",
              ["==", "brunnel", "bridge"],
              ["==", "class", "motorway"]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#fc8",
              "line-width": { "base": 1.2, "stops": [[6.5, 0], [7, 0.5], [20, 18]] },
              "line-opacity": 0.5
            }
          },
          {
            "id": "bridge-railway",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": ["all", ["==", "brunnel", "bridge"], ["==", "class", "rail"]],
            "paint": {
              "line-color": "#bbb",
              "line-width": { "base": 1.4, "stops": [[14, 0.4], [15, 0.75], [20, 2]] }
            }
          },
          {
            "id": "bridge-railway-hatching",
            "type": "line",
            "metadata": { "mapbox:group": "1444849334699.1902" },
            "source": "openmaptiles",
            "source-layer": "transportation",
            "filter": ["all", ["==", "brunnel", "bridge"], ["==", "class", "rail"]],
            "paint": {
              "line-color": "#bbb",
              "line-dasharray": [0.2, 8],
              "line-width": { "base": 1.4, "stops": [[14.5, 0], [15, 3], [20, 8]] }
            }
          },
          {
            "id": "cablecar",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 13,
            "filter": ["==", "class", "cable_car"],
            "layout": { "visibility": "visible", "line-cap": "round" },
            "paint": {
              "line-color": "hsl(0, 0%, 70%)",
              "line-width": { "base": 1, "stops": [[11, 1], [19, 2.5]] }
            }
          },
          {
            "id": "cablecar-dash",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 13,
            "filter": ["==", "class", "cable_car"],
            "layout": { "visibility": "visible", "line-cap": "round" },
            "paint": {
              "line-color": "hsl(0, 0%, 70%)",
              "line-width": { "base": 1, "stops": [[11, 3], [19, 5.5]] },
              "line-dasharray": [2, 3]
            }
          },
          {
            "id": "boundary-land-level-4",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "boundary",
            "filter": [
              "all",
              [">=", "admin_level", 4],
              ["<=", "admin_level", 8],
              ["!=", "maritime", 1]
            ],
            "layout": { "line-join": "round" },
            "paint": {
              "line-color": "#9e9cab",
              "line-dasharray": [3, 1, 1, 1],
              "line-width": { "base": 1.4, "stops": [[4, 0.4], [5, 1], [12, 3]] },
              "line-opacity": 0.6
            }
          },
          {
            "id": "boundary-land-level-2",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "boundary",
            "filter": [
              "all",
              ["==", "admin_level", 2],
              ["!=", "maritime", 1],
              ["!=", "disputed", 1]
            ],
            "layout": { "line-cap": "round", "line-join": "round" },
            "paint": {
              "line-color": "hsl(248, 7%, 66%)",
              "line-width": {
                "base": 1,
                "stops": [[0, 0.6], [4, 1.4], [5, 2], [12, 2]]
              }
            }
          },
          {
            "id": "boundary-land-disputed",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "boundary",
            "filter": ["all", ["!=", "maritime", 1], ["==", "disputed", 1]],
            "layout": { "line-cap": "round", "line-join": "round" },
            "paint": {
              "line-color": "hsl(248, 7%, 70%)",
              "line-dasharray": [1, 3],
              "line-width": {
                "base": 1,
                "stops": [[0, 0.6], [4, 1.4], [5, 2], [12, 8]]
              }
            }
          },
          {
            "id": "boundary-water",
            "type": "line",
            "source": "openmaptiles",
            "source-layer": "boundary",
            "filter": ["all", ["in", "admin_level", 2, 4], ["==", "maritime", 1]],
            "layout": { "line-cap": "round", "line-join": "round" },
            "paint": {
              "line-color": "rgba(154, 189, 214, 1)",
              "line-width": { "base": 1, "stops": [[0, 0.6], [4, 1], [5, 1], [12, 1]] },
              "line-opacity": { "stops": [[6, 0], [10, 0]] }
            }
          },
          {
            "id": "waterway-name",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "waterway",
            "minzoom": 13,
            "filter": ["all", ["==", "$type", "LineString"], ["has", "name"]],
            "layout": {
              "text-font": ["Noto Sans Italic"],
              "text-size": 14,
              "text-field": "{name:latin} {name:nonlatin}",
              "text-max-width": 5,
              "text-rotation-alignment": "map",
              "symbol-placement": "line",
              "text-letter-spacing": 0.2,
              "symbol-spacing": 350
            },
            "paint": {
              "text-color": "#74aee9",
              "text-halo-width": 1.5,
              "text-halo-color": "rgba(255,255,255,0.7)"
            }
          },
          {
            "id": "water-name-lakeline",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "water_name",
            "filter": ["==", "$type", "LineString"],
            "layout": {
              "text-font": ["Noto Sans Italic"],
              "text-size": 14,
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-max-width": 5,
              "text-rotation-alignment": "map",
              "symbol-placement": "line",
              "symbol-spacing": 350,
              "text-letter-spacing": 0.2
            },
            "paint": {
              "text-color": "#74aee9",
              "text-halo-width": 1.5,
              "text-halo-color": "rgba(255,255,255,0.7)"
            }
          },
          {
            "id": "water-name-ocean",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "water_name",
            "filter": ["all", ["==", "$type", "Point"], ["==", "class", "ocean"]],
            "layout": {
              "text-font": ["Noto Sans Italic"],
              "text-size": 14,
              "text-field": "{name:latin}",
              "text-max-width": 5,
              "text-rotation-alignment": "map",
              "symbol-placement": "point",
              "symbol-spacing": 350,
              "text-letter-spacing": 0.2
            },
            "paint": {
              "text-color": "#74aee9",
              "text-halo-width": 1.5,
              "text-halo-color": "rgba(255,255,255,0.7)"
            }
          },
          {
            "id": "water-name-other",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "water_name",
            "filter": ["all", ["==", "$type", "Point"], ["!in", "class", "ocean"]],
            "layout": {
              "text-font": ["Noto Sans Italic"],
              "text-size": { "stops": [[0, 10], [6, 14]] },
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-max-width": 5,
              "text-rotation-alignment": "map",
              "symbol-placement": "point",
              "symbol-spacing": 350,
              "text-letter-spacing": 0.2,
              "visibility": "visible"
            },
            "paint": {
              "text-color": "#74aee9",
              "text-halo-width": 1.5,
              "text-halo-color": "rgba(255,255,255,0.7)"
            }
          },
          {
            "id": "poi-level-3",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "poi",
            "minzoom": 16,
            "filter": ["all", ["==", "$type", "Point"], [">=", "rank", 25]],
            "layout": {
              "text-padding": 2,
              "text-font": ["Noto Sans Regular"],
              "text-anchor": "top",
              "icon-image": "{class}_11",
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-offset": [0, 0.6],
              "text-size": 12,
              "text-max-width": 9
            },
            "paint": {
              "text-halo-blur": 0.5,
              "text-color": "#666",
              "text-halo-width": 1,
              "text-halo-color": "#ffffff"
            }
          },
          {
            "id": "poi-level-2",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "poi",
            "minzoom": 15,
            "filter": [
              "all",
              ["==", "$type", "Point"],
              ["<=", "rank", 24],
              [">=", "rank", 15]
            ],
            "layout": {
              "text-padding": 2,
              "text-font": ["Noto Sans Regular"],
              "text-anchor": "top",
              "icon-image": "{class}_11",
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-offset": [0, 0.6],
              "text-size": 12,
              "text-max-width": 9
            },
            "paint": {
              "text-halo-blur": 0.5,
              "text-color": "#666",
              "text-halo-width": 1,
              "text-halo-color": "#ffffff"
            }
          },
          {
            "id": "poi-level-1",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "poi",
            "minzoom": 14,
            "filter": [
              "all",
              ["==", "$type", "Point"],
              ["<=", "rank", 14],
              ["has", "name"]
            ],
            "layout": {
              "text-padding": 2,
              "text-font": ["Noto Sans Regular"],
              "text-anchor": "top",
              "icon-image": "{class}_11",
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-offset": [0, 0.6],
              "text-size": 11,
              "text-max-width": 9
            },
            "paint": {
              "text-halo-blur": 0.5,
              "text-color": "rgba(191, 228, 172, 1)",
              "text-halo-width": 1,
              "text-halo-color": "rgba(30, 29, 29, 1)"
            }
          },
          {
            "id": "poi-railway",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "poi",
            "minzoom": 13,
            "filter": [
              "all",
              ["==", "$type", "Point"],
              ["has", "name"],
              ["==", "class", "railway"],
              ["==", "subclass", "station"]
            ],
            "layout": {
              "text-padding": 2,
              "text-font": ["Noto Sans Regular"],
              "text-anchor": "top",
              "icon-image": "{class}_11",
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-offset": [0, 0.6],
              "text-size": 12,
              "text-max-width": 9,
              "icon-optional": false,
              "icon-ignore-placement": false,
              "icon-allow-overlap": false,
              "text-ignore-placement": false,
              "text-allow-overlap": false,
              "text-optional": true
            },
            "paint": {
              "text-halo-blur": 0.5,
              "text-color": "#666",
              "text-halo-width": 1,
              "text-halo-color": "#ffffff"
            }
          },
          {
            "id": "road_oneway",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 15,
            "filter": [
              "all",
              ["==", "oneway", 1],
              [
                "in",
                "class",
                "motorway",
                "trunk",
                "primary",
                "secondary",
                "tertiary",
                "minor",
                "service"
              ]
            ],
            "layout": {
              "symbol-placement": "line",
              "icon-image": "oneway",
              "symbol-spacing": 75,
              "icon-padding": 2,
              "icon-rotation-alignment": "map",
              "icon-rotate": 90,
              "icon-size": { "stops": [[15, 0.5], [19, 1]] }
            },
            "paint": { "icon-opacity": 0.5 }
          },
          {
            "id": "road_oneway_opposite",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation",
            "minzoom": 15,
            "filter": [
              "all",
              ["==", "oneway", -1],
              [
                "in",
                "class",
                "motorway",
                "trunk",
                "primary",
                "secondary",
                "tertiary",
                "minor",
                "service"
              ]
            ],
            "layout": {
              "symbol-placement": "line",
              "icon-image": "oneway",
              "symbol-spacing": 75,
              "icon-padding": 2,
              "icon-rotation-alignment": "map",
              "icon-rotate": -90,
              "icon-size": { "stops": [[15, 0.5], [19, 1]] }
            },
            "paint": { "icon-opacity": 0.5 }
          },
          {
            "id": "highway-name-path",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation_name",
            "minzoom": 15.5,
            "filter": ["==", "class", "path"],
            "layout": {
              "text-size": { "base": 1, "stops": [[13, 12], [14, 13]] },
              "text-font": ["Noto Sans Regular"],
              "text-field": "{name:latin} {name:nonlatin}",
              "symbol-placement": "line",
              "text-rotation-alignment": "map"
            },
            "paint": {
              "text-halo-color": "#f8f4f0",
              "text-color": "hsl(30, 23%, 62%)",
              "text-halo-width": 0.5
            }
          },
          {
            "id": "highway-name-minor",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation_name",
            "minzoom": 15,
            "filter": [
              "all",
              ["==", "$type", "LineString"],
              ["in", "class", "minor", "service", "track"]
            ],
            "layout": {
              "text-size": { "base": 1, "stops": [[13, 12], [14, 13]] },
              "text-font": ["Noto Sans Regular"],
              "text-field": "{name:latin} {name:nonlatin}",
              "symbol-placement": "line",
              "text-rotation-alignment": "map"
            },
            "paint": {
              "text-halo-blur": 0.5,
              "text-color": "#765",
              "text-halo-width": 1
            }
          },
          {
            "id": "highway-name-major",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation_name",
            "minzoom": 12.2,
            "filter": ["in", "class", "primary", "secondary", "tertiary", "trunk"],
            "layout": {
              "text-size": { "base": 1, "stops": [[13, 12], [14, 13]] },
              "text-font": ["Noto Sans Regular"],
              "text-field": "{name:latin} {name:nonlatin}",
              "symbol-placement": "line",
              "text-rotation-alignment": "map"
            },
            "paint": {
              "text-halo-blur": 0.5,
              "text-color": "#765",
              "text-halo-width": 1
            }
          },
          {
            "id": "highway-shield",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation_name",
            "minzoom": 8,
            "filter": [
              "all",
              ["<=", "ref_length", 6],
              ["==", "$type", "LineString"],
              ["!in", "network", "us-interstate", "us-highway", "us-state"]
            ],
            "layout": {
              "text-size": 10,
              "icon-image": "road_{ref_length}",
              "icon-rotation-alignment": "viewport",
              "symbol-spacing": 200,
              "text-font": ["Noto Sans Regular"],
              "symbol-placement": { "base": 1, "stops": [[10, "point"], [11, "line"]] },
              "text-rotation-alignment": "viewport",
              "icon-size": 1,
              "text-field": "{ref}"
            },
            "paint": {
              "text-opacity": 1,
              "text-color": "rgba(20, 19, 19, 1)",
              "text-halo-color": "rgba(230, 221, 221, 0)",
              "text-halo-width": 2,
              "icon-color": "rgba(183, 18, 18, 1)",
              "icon-opacity": 0.3,
              "icon-halo-color": "rgba(183, 55, 55, 0)"
            }
          },
          {
            "id": "highway-shield-us-interstate",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation_name",
            "minzoom": 7,
            "filter": [
              "all",
              ["<=", "ref_length", 6],
              ["==", "$type", "LineString"],
              ["in", "network", "us-interstate"]
            ],
            "layout": {
              "text-size": 10,
              "icon-image": "{network}_{ref_length}",
              "icon-rotation-alignment": "viewport",
              "symbol-spacing": 200,
              "text-font": ["Noto Sans Regular"],
              "symbol-placement": {
                "base": 1,
                "stops": [[7, "point"], [7, "line"], [8, "line"]]
              },
              "text-rotation-alignment": "viewport",
              "icon-size": 1,
              "text-field": "{ref}"
            },
            "paint": { "text-color": "rgba(0, 0, 0, 1)" }
          },
          {
            "id": "highway-shield-us-other",
            "type": "symbol",
            "source": "openmaptiles",
            "source-layer": "transportation_name",
            "minzoom": 9,
            "filter": [
              "all",
              ["<=", "ref_length", 6],
              ["==", "$type", "LineString"],
              ["in", "network", "us-highway", "us-state"]
            ],
            "layout": {
              "text-size": 10,
              "icon-image": "{network}_{ref_length}",
              "icon-rotation-alignment": "viewport",
              "symbol-spacing": 200,
              "text-font": ["Noto Sans Regular"],
              "symbol-placement": { "base": 1, "stops": [[10, "point"], [11, "line"]] },
              "text-rotation-alignment": "viewport",
              "icon-size": 1,
              "text-field": "{ref}"
            },
            "paint": { "text-color": "rgba(0, 0, 0, 1)" }
          },
          {
            "id": "place-other",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "minzoom": 12,
            "filter": [
              "!in",
              "class",
              "city",
              "town",
              "village",
              "country",
              "continent"
            ],
            "layout": {
              "text-letter-spacing": 0.1,
              "text-size": { "base": 1.2, "stops": [[12, 10], [15, 14]] },
              "text-font": ["Noto Sans Bold"],
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-transform": "uppercase",
              "text-max-width": 9,
              "visibility": "visible"
            },
            "paint": {
              "text-color": "rgba(255,255,255,1)",
              "text-halo-width": 1.2,
              "text-halo-color": "rgba(57, 28, 28, 1)"
            }
          },
          {
            "id": "place-village",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "minzoom": 10,
            "filter": ["==", "class", "village"],
            "layout": {
              "text-font": ["Noto Sans Regular"],
              "text-size": { "base": 1.2, "stops": [[10, 12], [15, 16]] },
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-max-width": 8,
              "visibility": "visible"
            },
            "paint": {
              "text-color": "rgba(255, 255, 255, 1)",
              "text-halo-width": 1.2,
              "text-halo-color": "rgba(10, 9, 9, 0.8)"
            }
          },
          {
            "id": "place-town",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "filter": ["==", "class", "town"],
            "layout": {
              "text-font": ["Noto Sans Regular"],
              "text-size": { "base": 1.2, "stops": [[10, 14], [15, 24]] },
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-max-width": 8,
              "visibility": "visible"
            },
            "paint": {
              "text-color": "rgba(255, 255, 255, 1)",
              "text-halo-width": 1.2,
              "text-halo-color": "rgba(22, 22, 22, 0.8)"
            }
          },
          {
            "id": "place-city",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "filter": ["all", ["!=", "capital", 2], ["==", "class", "city"]],
            "layout": {
              "text-font": ["Noto Sans Regular"],
              "text-size": { "base": 1.2, "stops": [[7, 14], [11, 24]] },
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-max-width": 8,
              "visibility": "visible"
            },
            "paint": {
              "text-color": "rgba(0, 0, 0, 1)",
              "text-halo-width": 1.2,
              "text-halo-color": "rgba(255,255,255,0.8)"
            }
          },
          {
            "id": "place-city-capital",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "filter": ["all", ["==", "capital", 2], ["==", "class", "city"]],
            "layout": {
              "text-font": ["Noto Sans Regular"],
              "text-size": { "base": 1.2, "stops": [[7, 14], [11, 24]] },
              "text-field": "{name:latin}\n{name:nonlatin}",
              "text-max-width": 8,
              "icon-image": "star_11",
              "text-offset": [0.4, 0],
              "icon-size": 0.8,
              "text-anchor": "left",
              "visibility": "visible"
            },
            "paint": {
              "text-color": "#333",
              "text-halo-width": 1.2,
              "text-halo-color": "rgba(255,255,255,0.8)"
            }
          },
          {
            "id": "place-country-other",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "filter": [
              "all",
              ["==", "class", "country"],
              [">=", "rank", 3],
              ["!has", "iso_a2"]
            ],
            "layout": {
              "text-font": ["Noto Sans Italic"],
              "text-field": "{name:latin}",
              "text-size": { "stops": [[3, 11], [7, 17]] },
              "text-transform": "uppercase",
              "text-max-width": 6.25,
              "visibility": "visible"
            },
            "paint": {
              "text-halo-blur": 1,
              "text-color": "#334",
              "text-halo-width": 2,
              "text-halo-color": "rgba(255,255,255,0.8)"
            }
          },
          {
            "id": "place-country-3",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "filter": [
              "all",
              ["==", "class", "country"],
              [">=", "rank", 3],
              ["has", "iso_a2"]
            ],
            "layout": {
              "text-font": ["Noto Sans Bold"],
              "text-field": "{name:latin}",
              "text-size": { "stops": [[3, 11], [7, 17]] },
              "text-transform": "uppercase",
              "text-max-width": 6.25,
              "visibility": "visible"
            },
            "paint": {
              "text-halo-blur": 1,
              "text-color": "#334",
              "text-halo-width": 2,
              "text-halo-color": "rgba(255,255,255,0.8)"
            }
          },
          {
            "id": "place-country-2",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "filter": [
              "all",
              ["==", "class", "country"],
              ["==", "rank", 2],
              ["has", "iso_a2"]
            ],
            "layout": {
              "text-font": ["Noto Sans Bold"],
              "text-field": "{name:latin}",
              "text-size": { "stops": [[2, 11], [5, 17]] },
              "text-transform": "uppercase",
              "text-max-width": 6.25,
              "visibility": "visible"
            },
            "paint": {
              "text-halo-blur": 1,
              "text-color": "#334",
              "text-halo-width": 2,
              "text-halo-color": "rgba(255,255,255,0.8)"
            }
          },
          {
            "id": "place-country-1",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "filter": [
              "all",
              ["==", "class", "country"],
              ["==", "rank", 1],
              ["has", "iso_a2"]
            ],
            "layout": {
              "text-font": ["Noto Sans Bold"],
              "text-field": "{name:latin}",
              "text-size": { "stops": [[1, 11], [4, 17]] },
              "text-transform": "uppercase",
              "text-max-width": 6.25,
              "visibility": "visible"
            },
            "paint": {
              "text-halo-blur": 1,
              "text-color": "#334",
              "text-halo-width": 2,
              "text-halo-color": "rgba(255,255,255,0.8)"
            }
          },
          {
            "id": "place-continent",
            "type": "symbol",
            "metadata": { "mapbox:group": "1444849242106.713" },
            "source": "openmaptiles",
            "source-layer": "place",
            "maxzoom": 1,
            "filter": ["==", "class", "continent"],
            "layout": {
              "text-font": ["Noto Sans Bold"],
              "text-field": "{name:latin}",
              "text-size": 14,
              "text-max-width": 6.25,
              "text-transform": "uppercase",
              "visibility": "visible"
            },
            "paint": {
              "text-halo-blur": 1,
              "text-color": "#334",
              "text-halo-width": 2,
              "text-halo-color": "rgba(255,255,255,0.8)"
            }
          }
        ],
        "id": "qebnlkra6"
      };
    }
  });

  // src/plots/map/styles/arcgis-sat.js
  var require_arcgis_sat = __commonJS({
    "src/plots/map/styles/arcgis-sat.js"(exports, module) {
      module.exports = {
        "version": 8,
        "name": "orto",
        "metadata": {},
        "center": [
          1.537786,
          41.837539
        ],
        "zoom": 12,
        "bearing": 0,
        "pitch": 0,
        "light": {
          "anchor": "viewport",
          "color": "white",
          "intensity": 0.4,
          "position": [
            1.15,
            45,
            30
          ]
        },
        "sources": {
          "ortoEsri": {
            "type": "raster",
            "tiles": [
              "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
            ],
            "tileSize": 256,
            "maxzoom": 18,
            "attribution": "ESRI &copy; <a href='http://www.esri.com'>ESRI</a>"
          },
          "ortoInstaMaps": {
            "type": "raster",
            "tiles": [
              "https://tilemaps.icgc.cat/mapfactory/wmts/orto_8_12/CAT3857/{z}/{x}/{y}.png"
            ],
            "tileSize": 256,
            "maxzoom": 13
          },
          "ortoICGC": {
            "type": "raster",
            "tiles": [
              "https://geoserveis.icgc.cat/icc_mapesmultibase/noutm/wmts/orto/GRID3857/{z}/{x}/{y}.jpeg"
            ],
            "tileSize": 256,
            "minzoom": 13.1,
            "maxzoom": 20
          },
          "openmaptiles": {
            "type": "vector",
            "url": "https://geoserveis.icgc.cat/contextmaps/basemap.json"
          }
        },
        "sprite": "https://geoserveis.icgc.cat/contextmaps/sprites/sprite@1",
        "glyphs": "https://geoserveis.icgc.cat/contextmaps/glyphs/{fontstack}/{range}.pbf",
        "layers": [
          {
            "id": "background",
            "type": "background",
            "paint": {
              "background-color": "#F4F9F4"
            }
          },
          {
            "id": "ortoEsri",
            "type": "raster",
            "source": "ortoEsri",
            "maxzoom": 16,
            "layout": {
              "visibility": "visible"
            }
          },
          {
            "id": "ortoICGC",
            "type": "raster",
            "source": "ortoICGC",
            "minzoom": 13.1,
            "maxzoom": 19,
            "layout": {
              "visibility": "visible"
            }
          },
          {
            "id": "ortoInstaMaps",
            "type": "raster",
            "source": "ortoInstaMaps",
            "maxzoom": 13,
            "layout": {
              "visibility": "visible"
            }
          }
        ]
      };
    }
  });

  // src/plots/map/constants.js
  var require_constants27 = __commonJS({
    "src/plots/map/constants.js"(exports, module) {
      "use strict";
      var sortObjectKeys = require_sort_object_keys();
      var arcgisSatHybrid = require_arcgis_sat_hybrid();
      var arcgisSat = require_arcgis_sat();
      var OSM = '\xA9 <a target="_blank" href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
      var cartoPositron = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json";
      var cartoDarkmatter = "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json";
      var cartoVoyager = "https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json";
      var cartoPositronNoLabels = "https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json";
      var cartoDarkmatterNoLabels = "https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json";
      var cartoVoyagerNoLabels = "https://basemaps.cartocdn.com/gl/voyager-nolabels-gl-style/style.json";
      var stylesMap = {
        basic: cartoVoyager,
        streets: cartoVoyager,
        outdoors: cartoVoyager,
        light: cartoPositron,
        dark: cartoDarkmatter,
        satellite: arcgisSat,
        "satellite-streets": arcgisSatHybrid,
        "open-street-map": {
          id: "osm",
          version: 8,
          sources: {
            "plotly-osm-tiles": {
              type: "raster",
              attribution: OSM,
              tiles: [
                "https://tile.openstreetmap.org/{z}/{x}/{y}.png"
              ],
              tileSize: 256
            }
          },
          layers: [{
            id: "plotly-osm-tiles",
            type: "raster",
            source: "plotly-osm-tiles",
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "white-bg": {
          id: "white-bg",
          version: 8,
          sources: {},
          layers: [{
            id: "white-bg",
            type: "background",
            paint: { "background-color": "#FFFFFF" },
            minzoom: 0,
            maxzoom: 22
          }],
          glyphs: "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf"
        },
        "carto-positron": cartoPositron,
        "carto-darkmatter": cartoDarkmatter,
        "carto-voyager": cartoVoyager,
        "carto-positron-nolabels": cartoPositronNoLabels,
        "carto-darkmatter-nolabels": cartoDarkmatterNoLabels,
        "carto-voyager-nolabels": cartoVoyagerNoLabels
      };
      var styleValuesMap = sortObjectKeys(stylesMap);
      module.exports = {
        styleValueDflt: "basic",
        stylesMap,
        styleValuesMap,
        traceLayerPrefix: "plotly-trace-layer-",
        layoutLayerPrefix: "plotly-layout-layer-",
        missingStyleErrorMsg: [
          "No valid maplibre style found, please set `map.style` to one of:",
          styleValuesMap.join(", "),
          "or use a tile service."
        ].join("\n"),
        mapOnErrorMsg: "Map error."
      };
    }
  });

  // src/plots/map/layout_attributes.js
  var require_layout_attributes20 = __commonJS({
    "src/plots/map/layout_attributes.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var defaultLine = require_color().defaultLine;
      var domainAttrs = require_domain().attributes;
      var fontAttrs = require_font_attributes();
      var textposition = require_attributes12().textposition;
      var overrideAll = require_edit_types().overrideAll;
      var templatedArray = require_plot_template().templatedArray;
      var constants = require_constants27();
      var fontAttr = fontAttrs({
        noFontVariant: true,
        noFontShadow: true,
        noFontLineposition: true,
        noFontTextcase: true
      });
      fontAttr.family.dflt = "Open Sans Regular, Arial Unicode MS Regular";
      var attrs = module.exports = overrideAll({
        _arrayAttrRegexps: [Lib.counterRegex("map", ".layers", true)],
        domain: domainAttrs({ name: "map" }),
        style: {
          valType: "any",
          values: constants.styleValuesMap,
          dflt: constants.styleValueDflt
        },
        center: {
          lon: {
            valType: "number",
            dflt: 0
          },
          lat: {
            valType: "number",
            dflt: 0
          }
        },
        zoom: {
          valType: "number",
          dflt: 1
        },
        bearing: {
          valType: "number",
          dflt: 0
        },
        pitch: {
          valType: "number",
          dflt: 0
        },
        bounds: {
          west: {
            valType: "number"
          },
          east: {
            valType: "number"
          },
          south: {
            valType: "number"
          },
          north: {
            valType: "number"
          }
        },
        layers: templatedArray("layer", {
          visible: {
            valType: "boolean",
            dflt: true
          },
          sourcetype: {
            valType: "enumerated",
            values: ["geojson", "vector", "raster", "image"],
            dflt: "geojson"
          },
          source: {
            valType: "any"
          },
          sourcelayer: {
            valType: "string",
            dflt: ""
          },
          sourceattribution: {
            valType: "string"
          },
          type: {
            valType: "enumerated",
            values: ["circle", "line", "fill", "symbol", "raster"],
            dflt: "circle"
          },
          coordinates: {
            valType: "any"
          },
          // attributes shared between all types
          below: {
            valType: "string"
          },
          color: {
            valType: "color",
            dflt: defaultLine
          },
          opacity: {
            valType: "number",
            min: 0,
            max: 1,
            dflt: 1
          },
          minzoom: {
            valType: "number",
            min: 0,
            max: 24,
            dflt: 0
          },
          maxzoom: {
            valType: "number",
            min: 0,
            max: 24,
            dflt: 24
          },
          // type-specific style attributes
          circle: {
            radius: {
              valType: "number",
              dflt: 15
            }
          },
          line: {
            width: {
              valType: "number",
              dflt: 2
            },
            dash: {
              valType: "data_array"
            }
          },
          fill: {
            outlinecolor: {
              valType: "color",
              dflt: defaultLine
            }
          },
          symbol: {
            icon: {
              valType: "string",
              dflt: "marker"
            },
            iconsize: {
              valType: "number",
              dflt: 10
            },
            text: {
              valType: "string",
              dflt: ""
            },
            placement: {
              valType: "enumerated",
              values: ["point", "line", "line-center"],
              dflt: "point"
            },
            textfont: fontAttr,
            textposition: Lib.extendFlat({}, textposition, { arrayOk: false })
          }
        })
      }, "plot", "from-root");
      attrs.uirevision = {
        valType: "any",
        editType: "none"
      };
    }
  });

  // src/traces/scattermap/attributes.js
  var require_attributes57 = __commonJS({
    "src/traces/scattermap/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterGeoAttrs = require_attributes48();
      var scatterAttrs = require_attributes12();
      var mapAttrs = require_layout_attributes20();
      var baseAttrs = require_attributes2();
      var colorScaleAttrs = require_attributes8();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var mapLayoutAtributes = require_layout_attributes20();
      var lineAttrs = scatterGeoAttrs.line;
      var markerAttrs = scatterGeoAttrs.marker;
      module.exports = overrideAll(
        {
          lon: scatterGeoAttrs.lon,
          lat: scatterGeoAttrs.lat,
          cluster: {
            enabled: {
              valType: "boolean"
            },
            maxzoom: extendFlat({}, mapLayoutAtributes.layers.maxzoom, {}),
            step: {
              valType: "number",
              arrayOk: true,
              dflt: -1,
              min: -1
            },
            size: {
              valType: "number",
              arrayOk: true,
              dflt: 20,
              min: 0
            },
            color: {
              valType: "color",
              arrayOk: true
            },
            opacity: extendFlat({}, markerAttrs.opacity, {
              dflt: 1
            })
          },
          // locations
          // locationmode
          mode: extendFlat({}, scatterAttrs.mode, {
            dflt: "markers"
          }),
          text: extendFlat({}, scatterAttrs.text, {}),
          texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["lat", "lon", "text"] }),
          texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
          hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
          line: {
            color: lineAttrs.color,
            width: lineAttrs.width
            // TODO
            // dash: dash
          },
          connectgaps: scatterAttrs.connectgaps,
          marker: extendFlat(
            {
              symbol: {
                valType: "string",
                dflt: "circle",
                arrayOk: true
              },
              angle: {
                valType: "number",
                dflt: "auto",
                arrayOk: true
              },
              allowoverlap: {
                valType: "boolean",
                dflt: false
              },
              opacity: markerAttrs.opacity,
              size: markerAttrs.size,
              sizeref: markerAttrs.sizeref,
              sizemin: markerAttrs.sizemin,
              sizemode: markerAttrs.sizemode
            },
            colorScaleAttrs("marker")
            // line
          ),
          fill: scatterGeoAttrs.fill,
          fillcolor: makeFillcolorAttr(),
          textfont: mapAttrs.layers.symbol.textfont,
          textposition: mapAttrs.layers.symbol.textposition,
          below: {
            valType: "string"
          },
          selected: {
            marker: scatterAttrs.selected.marker
          },
          unselected: {
            marker: scatterAttrs.unselected.marker
          },
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
            flags: ["lon", "lat", "text", "name"]
          }),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs()
        },
        "calc",
        "nested"
      );
    }
  });

  // src/traces/scattermap/constants.js
  var require_constants28 = __commonJS({
    "src/traces/scattermap/constants.js"(exports, module) {
      "use strict";
      var supportedFonts = [
        "Metropolis Black Italic",
        "Metropolis Black",
        "Metropolis Bold Italic",
        "Metropolis Bold",
        "Metropolis Extra Bold Italic",
        "Metropolis Extra Bold",
        "Metropolis Extra Light Italic",
        "Metropolis Extra Light",
        "Metropolis Light Italic",
        "Metropolis Light",
        "Metropolis Medium Italic",
        "Metropolis Medium",
        "Metropolis Regular Italic",
        "Metropolis Regular",
        "Metropolis Semi Bold Italic",
        "Metropolis Semi Bold",
        "Metropolis Thin Italic",
        "Metropolis Thin",
        "Open Sans Bold Italic",
        "Open Sans Bold",
        "Open Sans Extrabold Italic",
        "Open Sans Extrabold",
        "Open Sans Italic",
        "Open Sans Light Italic",
        "Open Sans Light",
        "Open Sans Regular",
        "Open Sans Semibold Italic",
        "Open Sans Semibold",
        "Klokantech Noto Sans Bold",
        "Klokantech Noto Sans CJK Bold",
        "Klokantech Noto Sans CJK Regular",
        "Klokantech Noto Sans Italic",
        "Klokantech Noto Sans Regular"
      ];
      module.exports = {
        isSupportedFont: function(a) {
          return supportedFonts.indexOf(a) !== -1;
        }
      };
    }
  });

  // src/traces/scattermap/defaults.js
  var require_defaults53 = __commonJS({
    "src/traces/scattermap/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var attributes = require_attributes57();
      var isSupportedFont = require_constants28().isSupportedFont;
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        function coerce2(attr, dflt) {
          return Lib.coerce2(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleLonLatDefaults(traceIn, traceOut, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        coerce("text");
        coerce("texttemplate");
        coerce("texttemplatefallback");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("mode");
        coerce("below");
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { noLine: true, noAngle: true });
          coerce("marker.allowoverlap");
          coerce("marker.angle");
          var marker = traceOut.marker;
          if (marker.symbol !== "circle") {
            if (Lib.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0];
            if (Lib.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0];
          }
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, { noDash: true });
          coerce("connectgaps");
        }
        var clusterMaxzoom = coerce2("cluster.maxzoom");
        var clusterStep = coerce2("cluster.step");
        var clusterColor = coerce2("cluster.color", traceOut.marker && traceOut.marker.color || defaultColor);
        var clusterSize = coerce2("cluster.size");
        var clusterOpacity = coerce2("cluster.opacity");
        var clusterEnabledDflt = clusterMaxzoom !== false || clusterStep !== false || clusterColor !== false || clusterSize !== false || clusterOpacity !== false;
        var clusterEnabled = coerce("cluster.enabled", clusterEnabledDflt);
        if (clusterEnabled || subTypes.hasText(traceOut)) {
          var layoutFontFamily = layout.font.family;
          handleTextDefaults(traceIn, traceOut, layout, coerce, {
            noSelect: true,
            noFontVariant: true,
            noFontShadow: true,
            noFontLineposition: true,
            noFontTextcase: true,
            font: {
              family: isSupportedFont(layoutFontFamily) ? layoutFontFamily : "Open Sans Regular",
              weight: layout.font.weight,
              style: layout.font.style,
              size: layout.font.size,
              color: layout.font.color
            }
          });
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        }
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
      function handleLonLatDefaults(traceIn, traceOut, coerce) {
        var lon = coerce("lon") || [];
        var lat = coerce("lat") || [];
        var len = Math.min(lon.length, lat.length);
        traceOut._length = len;
        return len;
      }
    }
  });

  // src/traces/scattermap/format_labels.js
  var require_format_labels6 = __commonJS({
    "src/traces/scattermap/format_labels.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var labels = {};
        var subplot = fullLayout[trace.subplot]._subplot;
        var ax = subplot.mockAxis;
        var lonlat = cdi.lonlat;
        labels.lonLabel = Axes.tickText(ax, ax.c2l(lonlat[0]), true).text;
        labels.latLabel = Axes.tickText(ax, ax.c2l(lonlat[1]), true).text;
        return labels;
      };
    }
  });

  // src/plots/map/convert_text_opts.js
  var require_convert_text_opts2 = __commonJS({
    "src/plots/map/convert_text_opts.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function convertTextOpts(textposition, iconSize) {
        var parts = textposition.split(" ");
        var vPos = parts[0];
        var hPos = parts[1];
        var factor = Lib.isArrayOrTypedArray(iconSize) ? Lib.mean(iconSize) : iconSize;
        var xInc = 0.5 + factor / 100;
        var yInc = 1.5 + factor / 100;
        var anchorVals = ["", ""];
        var offset = [0, 0];
        switch (vPos) {
          case "top":
            anchorVals[0] = "top";
            offset[1] = -yInc;
            break;
          case "bottom":
            anchorVals[0] = "bottom";
            offset[1] = yInc;
            break;
        }
        switch (hPos) {
          case "left":
            anchorVals[1] = "right";
            offset[0] = -xInc;
            break;
          case "right":
            anchorVals[1] = "left";
            offset[0] = xInc;
            break;
        }
        var anchor;
        if (anchorVals[0] && anchorVals[1]) anchor = anchorVals.join("-");
        else if (anchorVals[0]) anchor = anchorVals[0];
        else if (anchorVals[1]) anchor = anchorVals[1];
        else anchor = "center";
        return { anchor, offset };
      };
    }
  });

  // src/traces/scattermap/convert.js
  var require_convert14 = __commonJS({
    "src/traces/scattermap/convert.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var BADNUM = require_numerical().BADNUM;
      var geoJsonUtils = require_geojson_utils();
      var Colorscale = require_colorscale();
      var Drawing = require_drawing();
      var makeBubbleSizeFn = require_make_bubble_size_func();
      var subTypes = require_subtypes();
      var isSupportedFont = require_constants28().isSupportedFont;
      var convertTextOpts = require_convert_text_opts2();
      var appendArrayPointValue = require_helpers2().appendArrayPointValue;
      var NEWLINES = require_svg_text_utils().NEWLINES;
      var BR_TAG_ALL = require_svg_text_utils().BR_TAG_ALL;
      module.exports = function convert(gd, calcTrace) {
        var trace = calcTrace[0].trace;
        var isVisible = trace.visible === true && trace._length !== 0;
        var hasFill = trace.fill !== "none";
        var hasLines = subTypes.hasLines(trace);
        var hasMarkers = subTypes.hasMarkers(trace);
        var hasText = subTypes.hasText(trace);
        var hasCircles = hasMarkers && trace.marker.symbol === "circle";
        var hasSymbols = hasMarkers && trace.marker.symbol !== "circle";
        var hasCluster = trace.cluster && trace.cluster.enabled;
        var fill = initContainer("fill");
        var line = initContainer("line");
        var circle = initContainer("circle");
        var symbol = initContainer("symbol");
        var opts = {
          fill,
          line,
          circle,
          symbol
        };
        if (!isVisible) return opts;
        var lineCoords;
        if (hasFill || hasLines) {
          lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
        }
        if (hasFill) {
          fill.geojson = geoJsonUtils.makePolygon(lineCoords);
          fill.layout.visibility = "visible";
          Lib.extendFlat(fill.paint, {
            "fill-color": trace.fillcolor
          });
        }
        if (hasLines) {
          line.geojson = geoJsonUtils.makeLine(lineCoords);
          line.layout.visibility = "visible";
          Lib.extendFlat(line.paint, {
            "line-width": trace.line.width,
            "line-color": trace.line.color,
            "line-opacity": trace.opacity
          });
        }
        if (hasCircles) {
          var circleOpts = makeCircleOpts(calcTrace);
          circle.geojson = circleOpts.geojson;
          circle.layout.visibility = "visible";
          if (hasCluster) {
            circle.filter = ["!", ["has", "point_count"]];
            opts.cluster = {
              type: "circle",
              filter: ["has", "point_count"],
              layout: { visibility: "visible" },
              paint: {
                "circle-color": arrayifyAttribute(trace.cluster.color, trace.cluster.step),
                "circle-radius": arrayifyAttribute(trace.cluster.size, trace.cluster.step),
                "circle-opacity": arrayifyAttribute(trace.cluster.opacity, trace.cluster.step)
              }
            };
            opts.clusterCount = {
              type: "symbol",
              filter: ["has", "point_count"],
              paint: {},
              layout: {
                "text-field": "{point_count_abbreviated}",
                "text-font": getTextFont(trace),
                "text-size": 12
              }
            };
          }
          Lib.extendFlat(circle.paint, {
            "circle-color": circleOpts.mcc,
            "circle-radius": circleOpts.mrc,
            "circle-opacity": circleOpts.mo
          });
        }
        if (hasCircles && hasCluster) {
          circle.filter = ["!", ["has", "point_count"]];
        }
        if (hasSymbols || hasText) {
          symbol.geojson = makeSymbolGeoJSON(calcTrace, gd);
          Lib.extendFlat(symbol.layout, {
            visibility: "visible",
            "icon-image": "{symbol}-15",
            "text-field": "{text}"
          });
          if (hasSymbols) {
            Lib.extendFlat(symbol.layout, {
              "icon-size": trace.marker.size / 10
            });
            if ("angle" in trace.marker && trace.marker.angle !== "auto") {
              Lib.extendFlat(symbol.layout, {
                // unfortunately cant use {angle} do to this issue:
                // https://github.com/mapbox/mapbox-gl-js/issues/873
                "icon-rotate": {
                  type: "identity",
                  property: "angle"
                },
                "icon-rotation-alignment": "map"
              });
            }
            symbol.layout["icon-allow-overlap"] = trace.marker.allowoverlap;
            Lib.extendFlat(symbol.paint, {
              "icon-opacity": trace.opacity * trace.marker.opacity,
              // TODO does not work ??
              "icon-color": trace.marker.color
            });
          }
          if (hasText) {
            var iconSize = (trace.marker || {}).size;
            var textOpts = convertTextOpts(trace.textposition, iconSize);
            Lib.extendFlat(symbol.layout, {
              "text-size": trace.textfont.size,
              "text-anchor": textOpts.anchor,
              "text-offset": textOpts.offset,
              "text-font": getTextFont(trace)
            });
            Lib.extendFlat(symbol.paint, {
              "text-color": trace.textfont.color,
              "text-opacity": trace.opacity
            });
          }
        }
        return opts;
      };
      function initContainer(type) {
        return {
          type,
          geojson: geoJsonUtils.makeBlank(),
          layout: { visibility: "none" },
          filter: null,
          paint: {}
        };
      }
      function makeCircleOpts(calcTrace) {
        var trace = calcTrace[0].trace;
        var marker = trace.marker;
        var selectedpoints = trace.selectedpoints;
        var arrayColor = Lib.isArrayOrTypedArray(marker.color);
        var arraySize = Lib.isArrayOrTypedArray(marker.size);
        var arrayOpacity = Lib.isArrayOrTypedArray(marker.opacity);
        var i;
        function addTraceOpacity(o) {
          return trace.opacity * o;
        }
        function size2radius(s) {
          return s / 2;
        }
        var colorFn;
        if (arrayColor) {
          if (Colorscale.hasColorscale(trace, "marker")) {
            colorFn = Colorscale.makeColorScaleFuncFromTrace(marker);
          } else {
            colorFn = Lib.identity;
          }
        }
        var sizeFn;
        if (arraySize) {
          sizeFn = makeBubbleSizeFn(trace);
        }
        var opacityFn;
        if (arrayOpacity) {
          opacityFn = function(mo) {
            var mo2 = isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
            return addTraceOpacity(mo2);
          };
        }
        var features = [];
        for (i = 0; i < calcTrace.length; i++) {
          var calcPt = calcTrace[i];
          var lonlat = calcPt.lonlat;
          if (isBADNUM(lonlat)) continue;
          var props = {};
          if (colorFn) props.mcc = calcPt.mcc = colorFn(calcPt.mc);
          if (sizeFn) props.mrc = calcPt.mrc = sizeFn(calcPt.ms);
          if (opacityFn) props.mo = opacityFn(calcPt.mo);
          if (selectedpoints) props.selected = calcPt.selected || 0;
          features.push({
            type: "Feature",
            id: i + 1,
            geometry: { type: "Point", coordinates: lonlat },
            properties: props
          });
        }
        var fns;
        if (selectedpoints) {
          fns = Drawing.makeSelectedPointStyleFns(trace);
          for (i = 0; i < features.length; i++) {
            var d = features[i].properties;
            if (fns.selectedOpacityFn) {
              d.mo = addTraceOpacity(fns.selectedOpacityFn(d));
            }
            if (fns.selectedColorFn) {
              d.mcc = fns.selectedColorFn(d);
            }
            if (fns.selectedSizeFn) {
              d.mrc = fns.selectedSizeFn(d);
            }
          }
        }
        return {
          geojson: { type: "FeatureCollection", features },
          mcc: arrayColor || fns && fns.selectedColorFn ? { type: "identity", property: "mcc" } : marker.color,
          mrc: arraySize || fns && fns.selectedSizeFn ? { type: "identity", property: "mrc" } : size2radius(marker.size),
          mo: arrayOpacity || fns && fns.selectedOpacityFn ? { type: "identity", property: "mo" } : addTraceOpacity(marker.opacity)
        };
      }
      function makeSymbolGeoJSON(calcTrace, gd) {
        var fullLayout = gd._fullLayout;
        var trace = calcTrace[0].trace;
        var marker = trace.marker || {};
        var symbol = marker.symbol;
        var angle = marker.angle;
        var fillSymbol = symbol !== "circle" ? getFillFunc(symbol) : blankFillFunc;
        var fillAngle = angle !== "auto" ? getFillFunc(angle, true) : blankFillFunc;
        var fillText = subTypes.hasText(trace) ? getFillFunc(trace.text) : blankFillFunc;
        var features = [];
        for (var i = 0; i < calcTrace.length; i++) {
          var calcPt = calcTrace[i];
          if (isBADNUM(calcPt.lonlat)) continue;
          var texttemplate = trace.texttemplate;
          var text;
          if (texttemplate) {
            var tt = Array.isArray(texttemplate) ? texttemplate[i] || "" : texttemplate;
            var labels = trace._module.formatLabels(calcPt, trace, fullLayout);
            var pointValues = {};
            appendArrayPointValue(pointValues, trace, calcPt.i);
            text = Lib.texttemplateString({
              data: [pointValues, calcPt, trace._meta],
              fallback: trace.texttemplatefallback,
              labels,
              locale: fullLayout._d3locale,
              template: tt
            });
          } else {
            text = fillText(i);
          }
          if (text) {
            text = text.replace(NEWLINES, "").replace(BR_TAG_ALL, "\n");
          }
          features.push({
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: calcPt.lonlat
            },
            properties: {
              symbol: fillSymbol(i),
              angle: fillAngle(i),
              text
            }
          });
        }
        return {
          type: "FeatureCollection",
          features
        };
      }
      function getFillFunc(attr, numeric) {
        if (Lib.isArrayOrTypedArray(attr)) {
          if (numeric) {
            return function(i) {
              return isNumeric(attr[i]) ? +attr[i] : 0;
            };
          }
          return function(i) {
            return attr[i];
          };
        } else if (attr) {
          return function() {
            return attr;
          };
        } else {
          return blankFillFunc;
        }
      }
      function blankFillFunc() {
        return "";
      }
      function isBADNUM(lonlat) {
        return lonlat[0] === BADNUM;
      }
      function arrayifyAttribute(values, step) {
        var newAttribute;
        if (Lib.isArrayOrTypedArray(values) && Lib.isArrayOrTypedArray(step)) {
          newAttribute = ["step", ["get", "point_count"], values[0]];
          for (var idx = 1; idx < values.length; idx++) {
            newAttribute.push(step[idx - 1], values[idx]);
          }
        } else {
          newAttribute = values;
        }
        return newAttribute;
      }
      function getTextFont(trace) {
        var font = trace.textfont;
        var family = font.family;
        var style = font.style;
        var weight = font.weight;
        var parts = family.split(" ");
        var isItalic = parts[parts.length - 1] === "Italic";
        if (isItalic) parts.pop();
        isItalic = isItalic || style === "italic";
        var str = parts.join(" ");
        if (weight === "bold" && parts.indexOf("Bold") === -1) {
          str += " Bold";
        } else if (weight <= 1e3) {
          if (parts[0] === "Metropolis") {
            str = "Metropolis";
            if (weight > 850) str += " Black";
            else if (weight > 750) str += " Extra Bold";
            else if (weight > 650) str += " Bold";
            else if (weight > 550) str += " Semi Bold";
            else if (weight > 450) str += " Medium";
            else if (weight > 350) str += " Regular";
            else if (weight > 250) str += " Light";
            else if (weight > 150) str += " Extra Light";
            else str += " Thin";
          } else if (parts.slice(0, 2).join(" ") === "Open Sans") {
            str = "Open Sans";
            if (weight > 750) str += " Extrabold";
            else if (weight > 650) str += " Bold";
            else if (weight > 550) str += " Semibold";
            else if (weight > 350) str += " Regular";
            else str += " Light";
          } else if (parts.slice(0, 3).join(" ") === "Klokantech Noto Sans") {
            str = "Klokantech Noto Sans";
            if (parts[3] === "CJK") str += " CJK";
            str += weight > 500 ? " Bold" : " Regular";
          }
        }
        if (isItalic) str += " Italic";
        if (str === "Open Sans Regular Italic") str = "Open Sans Italic";
        else if (str === "Open Sans Regular Bold") str = "Open Sans Bold";
        else if (str === "Open Sans Regular Bold Italic") str = "Open Sans Bold Italic";
        else if (str === "Klokantech Noto Sans Regular Italic") str = "Klokantech Noto Sans Italic";
        if (!isSupportedFont(str)) {
          str = family;
        }
        var textFont = str.split(", ");
        return textFont;
      }
    }
  });

  // src/traces/scattermap/plot.js
  var require_plot26 = __commonJS({
    "src/traces/scattermap/plot.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var convert = require_convert14();
      var LAYER_PREFIX = require_constants27().traceLayerPrefix;
      var ORDER = {
        cluster: ["cluster", "clusterCount", "circle"],
        nonCluster: ["fill", "line", "circle", "symbol"]
      };
      function ScatterMap(subplot, uid, clusterEnabled, isHidden) {
        this.type = "scattermap";
        this.subplot = subplot;
        this.uid = uid;
        this.clusterEnabled = clusterEnabled;
        this.isHidden = isHidden;
        this.sourceIds = {
          fill: "source-" + uid + "-fill",
          line: "source-" + uid + "-line",
          circle: "source-" + uid + "-circle",
          symbol: "source-" + uid + "-symbol",
          cluster: "source-" + uid + "-circle",
          clusterCount: "source-" + uid + "-circle"
        };
        this.layerIds = {
          fill: LAYER_PREFIX + uid + "-fill",
          line: LAYER_PREFIX + uid + "-line",
          circle: LAYER_PREFIX + uid + "-circle",
          symbol: LAYER_PREFIX + uid + "-symbol",
          cluster: LAYER_PREFIX + uid + "-cluster",
          clusterCount: LAYER_PREFIX + uid + "-cluster-count"
        };
        this.below = null;
      }
      var proto = ScatterMap.prototype;
      proto.addSource = function(k, opts, cluster) {
        var sourceOpts = {
          type: "geojson",
          data: opts.geojson
        };
        if (cluster && cluster.enabled) {
          Lib.extendFlat(sourceOpts, {
            cluster: true,
            clusterMaxZoom: cluster.maxzoom
          });
        }
        var isSourceExists = this.subplot.map.getSource(this.sourceIds[k]);
        if (isSourceExists) {
          isSourceExists.setData(opts.geojson);
        } else {
          this.subplot.map.addSource(this.sourceIds[k], sourceOpts);
        }
      };
      proto.setSourceData = function(k, opts) {
        this.subplot.map.getSource(this.sourceIds[k]).setData(opts.geojson);
      };
      proto.addLayer = function(k, opts, below) {
        var source = {
          type: opts.type,
          id: this.layerIds[k],
          source: this.sourceIds[k],
          layout: opts.layout,
          paint: opts.paint
        };
        if (opts.filter) {
          source.filter = opts.filter;
        }
        var currentLayerId = this.layerIds[k];
        var layerExist;
        var layers = this.subplot.getMapLayers();
        for (var i = 0; i < layers.length; i++) {
          if (layers[i].id === currentLayerId) {
            layerExist = true;
            break;
          }
        }
        if (layerExist) {
          this.subplot.setOptions(currentLayerId, "setLayoutProperty", source.layout);
          if (source.layout.visibility === "visible") {
            this.subplot.setOptions(currentLayerId, "setPaintProperty", source.paint);
          }
        } else {
          this.subplot.addLayer(source, below);
        }
      };
      proto.update = function update(calcTrace) {
        var trace = calcTrace[0].trace;
        var subplot = this.subplot;
        var map = subplot.map;
        var optsAll = convert(subplot.gd, calcTrace);
        var below = subplot.belowLookup["trace-" + this.uid];
        var hasCluster = !!(trace.cluster && trace.cluster.enabled);
        var hadCluster = !!this.clusterEnabled;
        var lThis = this;
        function addCluster(noSource) {
          if (!noSource) lThis.addSource("circle", optsAll.circle, trace.cluster);
          var order = ORDER.cluster;
          for (var i = 0; i < order.length; i++) {
            var k = order[i];
            var opts = optsAll[k];
            lThis.addLayer(k, opts, below);
          }
        }
        function removeCluster(noSource) {
          var order = ORDER.cluster;
          for (var i = order.length - 1; i >= 0; i--) {
            var k = order[i];
            map.removeLayer(lThis.layerIds[k]);
          }
          if (!noSource) map.removeSource(lThis.sourceIds.circle);
        }
        function addNonCluster(noSource) {
          var order = ORDER.nonCluster;
          for (var i = 0; i < order.length; i++) {
            var k = order[i];
            var opts = optsAll[k];
            if (!noSource) lThis.addSource(k, opts);
            lThis.addLayer(k, opts, below);
          }
        }
        function removeNonCluster(noSource) {
          var order = ORDER.nonCluster;
          for (var i = order.length - 1; i >= 0; i--) {
            var k = order[i];
            map.removeLayer(lThis.layerIds[k]);
            if (!noSource) map.removeSource(lThis.sourceIds[k]);
          }
        }
        function remove(noSource) {
          if (hadCluster) removeCluster(noSource);
          else removeNonCluster(noSource);
        }
        function add(noSource) {
          if (hasCluster) addCluster(noSource);
          else addNonCluster(noSource);
        }
        function repaint() {
          var order = hasCluster ? ORDER.cluster : ORDER.nonCluster;
          for (var i = 0; i < order.length; i++) {
            var k = order[i];
            var opts = optsAll[k];
            if (!opts) continue;
            subplot.setOptions(lThis.layerIds[k], "setLayoutProperty", opts.layout);
            if (opts.layout.visibility === "visible") {
              if (k !== "cluster") {
                lThis.setSourceData(k, opts);
              }
              subplot.setOptions(lThis.layerIds[k], "setPaintProperty", opts.paint);
            }
          }
        }
        var wasHidden = this.isHidden;
        var isHidden = trace.visible !== true;
        if (isHidden) {
          if (!wasHidden) remove();
        } else if (wasHidden) {
          if (!isHidden) add();
        } else if (hadCluster !== hasCluster) {
          remove();
          add();
        } else if (this.below !== below) {
          remove(true);
          add(true);
          repaint();
        } else {
          repaint();
        }
        this.clusterEnabled = hasCluster;
        this.isHidden = isHidden;
        this.below = below;
        calcTrace[0].trace._glTrace = this;
      };
      proto.dispose = function dispose() {
        var map = this.subplot.map;
        var order = this.clusterEnabled ? ORDER.cluster : ORDER.nonCluster;
        for (var i = order.length - 1; i >= 0; i--) {
          var k = order[i];
          map.removeLayer(this.layerIds[k]);
          map.removeSource(this.sourceIds[k]);
        }
      };
      module.exports = function createScatterMap(subplot, calcTrace) {
        var trace = calcTrace[0].trace;
        var hasCluster = trace.cluster && trace.cluster.enabled;
        var isHidden = trace.visible !== true;
        var scatterMap = new ScatterMap(
          subplot,
          trace.uid,
          hasCluster,
          isHidden
        );
        var optsAll = convert(subplot.gd, calcTrace);
        var below = scatterMap.below = subplot.belowLookup["trace-" + trace.uid];
        var i, k, opts;
        if (hasCluster) {
          scatterMap.addSource("circle", optsAll.circle, trace.cluster);
          for (i = 0; i < ORDER.cluster.length; i++) {
            k = ORDER.cluster[i];
            opts = optsAll[k];
            scatterMap.addLayer(k, opts, below);
          }
        } else {
          for (i = 0; i < ORDER.nonCluster.length; i++) {
            k = ORDER.nonCluster[i];
            opts = optsAll[k];
            scatterMap.addSource(k, opts, trace.cluster);
            scatterMap.addLayer(k, opts, below);
          }
        }
        calcTrace[0].trace._glTrace = scatterMap;
        return scatterMap;
      };
    }
  });

  // src/traces/scattermap/hover.js
  var require_hover20 = __commonJS({
    "src/traces/scattermap/hover.js"(exports, module) {
      "use strict";
      var Fx = require_fx();
      var Lib = require_lib();
      var getTraceColor = require_get_trace_color();
      var fillText = Lib.fillText;
      var BADNUM = require_numerical().BADNUM;
      var LAYER_PREFIX = require_constants27().traceLayerPrefix;
      function hoverPoints(pointData, xval, yval) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var xa = pointData.xa;
        var ya = pointData.ya;
        var subplot = pointData.subplot;
        var clusteredPointsIds = [];
        var layer = LAYER_PREFIX + trace.uid + "-circle";
        var hasCluster = trace.cluster && trace.cluster.enabled;
        if (hasCluster) {
          var elems = subplot.map.queryRenderedFeatures(null, { layers: [layer] });
          clusteredPointsIds = elems.map(function(elem) {
            return elem.id;
          });
        }
        var winding = xval >= 0 ? Math.floor((xval + 180) / 360) : Math.ceil((xval - 180) / 360);
        var lonShift = winding * 360;
        var xval2 = xval - lonShift;
        function distFn(d) {
          var lonlat2 = d.lonlat;
          if (lonlat2[0] === BADNUM) return Infinity;
          if (hasCluster && clusteredPointsIds.indexOf(d.i + 1) === -1) return Infinity;
          var lon = Lib.modHalf(lonlat2[0], 360);
          var lat = lonlat2[1];
          var pt = subplot.project([lon, lat]);
          var dx = pt.x - xa.c2p([xval2, lat]);
          var dy = pt.y - ya.c2p([lon, yval]);
          var rad2 = Math.max(3, d.mrc || 0);
          return Math.max(Math.sqrt(dx * dx + dy * dy) - rad2, 1 - 3 / rad2);
        }
        Fx.getClosest(cd, distFn, pointData);
        if (pointData.index === false) return;
        var di = cd[pointData.index];
        var lonlat = di.lonlat;
        var lonlatShifted = [Lib.modHalf(lonlat[0], 360) + lonShift, lonlat[1]];
        var xc = xa.c2p(lonlatShifted);
        var yc = ya.c2p(lonlatShifted);
        var rad = di.mrc || 1;
        pointData.x0 = xc - rad;
        pointData.x1 = xc + rad;
        pointData.y0 = yc - rad;
        pointData.y1 = yc + rad;
        var fullLayout = {};
        fullLayout[trace.subplot] = { _subplot: subplot };
        var labels = trace._module.formatLabels(di, trace, fullLayout);
        pointData.lonLabel = labels.lonLabel;
        pointData.latLabel = labels.latLabel;
        pointData.color = getTraceColor(trace, di);
        pointData.extraText = getExtraText(trace, di, cd[0].t.labels);
        pointData.hovertemplate = trace.hovertemplate;
        return [pointData];
      }
      function getExtraText(trace, di, labels) {
        if (trace.hovertemplate) return;
        var hoverinfo = di.hi || trace.hoverinfo;
        var parts = hoverinfo.split("+");
        var isAll = parts.indexOf("all") !== -1;
        var hasLon = parts.indexOf("lon") !== -1;
        var hasLat = parts.indexOf("lat") !== -1;
        var lonlat = di.lonlat;
        var text = [];
        function format(v) {
          return v + "\xB0";
        }
        if (isAll || hasLon && hasLat) {
          text.push("(" + format(lonlat[1]) + ", " + format(lonlat[0]) + ")");
        } else if (hasLon) {
          text.push(labels.lon + format(lonlat[0]));
        } else if (hasLat) {
          text.push(labels.lat + format(lonlat[1]));
        }
        if (isAll || parts.indexOf("text") !== -1) {
          fillText(di, trace, text);
        }
        return text.join("<br>");
      }
      module.exports = {
        hoverPoints,
        getExtraText
      };
    }
  });

  // src/traces/scattermap/event_data.js
  var require_event_data13 = __commonJS({
    "src/traces/scattermap/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        out.lon = pt.lon;
        out.lat = pt.lat;
        return out;
      };
    }
  });

  // src/traces/scattermap/select.js
  var require_select10 = __commonJS({
    "src/traces/scattermap/select.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subtypes = require_subtypes();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var trace = cd[0].trace;
        var i;
        if (!subtypes.hasMarkers(trace)) return [];
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            var di = cd[i];
            var lonlat = di.lonlat;
            if (lonlat[0] !== BADNUM) {
              var lonlat2 = [Lib.modHalf(lonlat[0], 360), lonlat[1]];
              var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)];
              if (selectionTester.contains(xy, null, i, searchInfo)) {
                selection.push({
                  pointNumber: i,
                  lon: lonlat[0],
                  lat: lonlat[1]
                });
                di.selected = 1;
              } else {
                di.selected = 0;
              }
            }
          }
        }
        return selection;
      };
    }
  });

  // node_modules/maplibre-gl/dist/maplibre-gl.js
  var require_maplibre_gl2 = __commonJS({
    "node_modules/maplibre-gl/dist/maplibre-gl.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && false ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.maplibregl = factory());
      })(exports, function() {
        "use strict";
        var maplibregl = {};
        var modules = {};
        function define2(moduleName, _dependencies, moduleFactory) {
          modules[moduleName] = moduleFactory;
          if (moduleName !== "index") {
            return;
          }
          var workerBundleString = "var sharedModule = {}; (" + modules.shared + ")(sharedModule); (" + modules.worker + ")(sharedModule);";
          var sharedModule = {};
          modules.shared(sharedModule);
          modules.index(maplibregl, sharedModule);
          if (typeof window !== "undefined") {
            maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: "text/javascript" })));
          }
          return maplibregl;
        }
        ;
        define2("shared", ["exports"], function(t) {
          "use strict";
          function e(t4, e2, r2, n2) {
            return new (r2 || (r2 = Promise))(function(i2, s2) {
              function a2(t5) {
                try {
                  l2(n2.next(t5));
                } catch (t6) {
                  s2(t6);
                }
              }
              function o2(t5) {
                try {
                  l2(n2.throw(t5));
                } catch (t6) {
                  s2(t6);
                }
              }
              function l2(t5) {
                var e3;
                t5.done ? i2(t5.value) : (e3 = t5.value, e3 instanceof r2 ? e3 : new r2(function(t6) {
                  t6(e3);
                })).then(a2, o2);
              }
              l2((n2 = n2.apply(t4, e2 || [])).next());
            });
          }
          function r(t4) {
            return t4 && t4.__esModule && Object.prototype.hasOwnProperty.call(t4, "default") ? t4.default : t4;
          }
          "function" == typeof SuppressedError && SuppressedError;
          var n = i;
          function i(t4, e2) {
            this.x = t4, this.y = e2;
          }
          i.prototype = { clone: function() {
            return new i(this.x, this.y);
          }, add: function(t4) {
            return this.clone()._add(t4);
          }, sub: function(t4) {
            return this.clone()._sub(t4);
          }, multByPoint: function(t4) {
            return this.clone()._multByPoint(t4);
          }, divByPoint: function(t4) {
            return this.clone()._divByPoint(t4);
          }, mult: function(t4) {
            return this.clone()._mult(t4);
          }, div: function(t4) {
            return this.clone()._div(t4);
          }, rotate: function(t4) {
            return this.clone()._rotate(t4);
          }, rotateAround: function(t4, e2) {
            return this.clone()._rotateAround(t4, e2);
          }, matMult: function(t4) {
            return this.clone()._matMult(t4);
          }, unit: function() {
            return this.clone()._unit();
          }, perp: function() {
            return this.clone()._perp();
          }, round: function() {
            return this.clone()._round();
          }, mag: function() {
            return Math.sqrt(this.x * this.x + this.y * this.y);
          }, equals: function(t4) {
            return this.x === t4.x && this.y === t4.y;
          }, dist: function(t4) {
            return Math.sqrt(this.distSqr(t4));
          }, distSqr: function(t4) {
            var e2 = t4.x - this.x, r2 = t4.y - this.y;
            return e2 * e2 + r2 * r2;
          }, angle: function() {
            return Math.atan2(this.y, this.x);
          }, angleTo: function(t4) {
            return Math.atan2(this.y - t4.y, this.x - t4.x);
          }, angleWith: function(t4) {
            return this.angleWithSep(t4.x, t4.y);
          }, angleWithSep: function(t4, e2) {
            return Math.atan2(this.x * e2 - this.y * t4, this.x * t4 + this.y * e2);
          }, _matMult: function(t4) {
            var e2 = t4[2] * this.x + t4[3] * this.y;
            return this.x = t4[0] * this.x + t4[1] * this.y, this.y = e2, this;
          }, _add: function(t4) {
            return this.x += t4.x, this.y += t4.y, this;
          }, _sub: function(t4) {
            return this.x -= t4.x, this.y -= t4.y, this;
          }, _mult: function(t4) {
            return this.x *= t4, this.y *= t4, this;
          }, _div: function(t4) {
            return this.x /= t4, this.y /= t4, this;
          }, _multByPoint: function(t4) {
            return this.x *= t4.x, this.y *= t4.y, this;
          }, _divByPoint: function(t4) {
            return this.x /= t4.x, this.y /= t4.y, this;
          }, _unit: function() {
            return this._div(this.mag()), this;
          }, _perp: function() {
            var t4 = this.y;
            return this.y = this.x, this.x = -t4, this;
          }, _rotate: function(t4) {
            var e2 = Math.cos(t4), r2 = Math.sin(t4), n2 = r2 * this.x + e2 * this.y;
            return this.x = e2 * this.x - r2 * this.y, this.y = n2, this;
          }, _rotateAround: function(t4, e2) {
            var r2 = Math.cos(t4), n2 = Math.sin(t4), i2 = e2.y + n2 * (this.x - e2.x) + r2 * (this.y - e2.y);
            return this.x = e2.x + r2 * (this.x - e2.x) - n2 * (this.y - e2.y), this.y = i2, this;
          }, _round: function() {
            return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
          } }, i.convert = function(t4) {
            return t4 instanceof i ? t4 : Array.isArray(t4) ? new i(t4[0], t4[1]) : t4;
          };
          var s = r(n), a = o;
          function o(t4, e2, r2, n2) {
            this.cx = 3 * t4, this.bx = 3 * (r2 - t4) - this.cx, this.ax = 1 - this.cx - this.bx, this.cy = 3 * e2, this.by = 3 * (n2 - e2) - this.cy, this.ay = 1 - this.cy - this.by, this.p1x = t4, this.p1y = e2, this.p2x = r2, this.p2y = n2;
          }
          o.prototype = { sampleCurveX: function(t4) {
            return ((this.ax * t4 + this.bx) * t4 + this.cx) * t4;
          }, sampleCurveY: function(t4) {
            return ((this.ay * t4 + this.by) * t4 + this.cy) * t4;
          }, sampleCurveDerivativeX: function(t4) {
            return (3 * this.ax * t4 + 2 * this.bx) * t4 + this.cx;
          }, solveCurveX: function(t4, e2) {
            if (void 0 === e2 && (e2 = 1e-6), t4 < 0) return 0;
            if (t4 > 1) return 1;
            for (var r2 = t4, n2 = 0; n2 < 8; n2++) {
              var i2 = this.sampleCurveX(r2) - t4;
              if (Math.abs(i2) < e2) return r2;
              var s2 = this.sampleCurveDerivativeX(r2);
              if (Math.abs(s2) < 1e-6) break;
              r2 -= i2 / s2;
            }
            var a2 = 0, o2 = 1;
            for (r2 = t4, n2 = 0; n2 < 20 && (i2 = this.sampleCurveX(r2), !(Math.abs(i2 - t4) < e2)); n2++) t4 > i2 ? a2 = r2 : o2 = r2, r2 = 0.5 * (o2 - a2) + a2;
            return r2;
          }, solve: function(t4, e2) {
            return this.sampleCurveY(this.solveCurveX(t4, e2));
          } };
          var l = r(a);
          let u, c;
          function h() {
            return null == u && (u = "undefined" != typeof OffscreenCanvas && new OffscreenCanvas(1, 1).getContext("2d") && "function" == typeof createImageBitmap), u;
          }
          function p() {
            if (null == c && (c = false, h())) {
              const t4 = 5, e2 = new OffscreenCanvas(t4, t4).getContext("2d", { willReadFrequently: true });
              if (e2) {
                for (let r3 = 0; r3 < t4 * t4; r3++) {
                  const n2 = 4 * r3;
                  e2.fillStyle = `rgb(${n2},${n2 + 1},${n2 + 2})`, e2.fillRect(r3 % t4, Math.floor(r3 / t4), 1, 1);
                }
                const r2 = e2.getImageData(0, 0, t4, t4).data;
                for (let e3 = 0; e3 < t4 * t4 * 4; e3++) if (e3 % 4 != 3 && r2[e3] !== e3) {
                  c = true;
                  break;
                }
              }
            }
            return c || false;
          }
          function f(t4, e2, r2, n2) {
            const i2 = new l(t4, e2, r2, n2);
            return (t5) => i2.solve(t5);
          }
          const d = f(0.25, 0.1, 0.25, 1);
          function y(t4, e2, r2) {
            return Math.min(r2, Math.max(e2, t4));
          }
          function m(t4, e2, r2) {
            const n2 = r2 - e2, i2 = ((t4 - e2) % n2 + n2) % n2 + e2;
            return i2 === e2 ? r2 : i2;
          }
          function g(t4, ...e2) {
            for (const r2 of e2) for (const e3 in r2) t4[e3] = r2[e3];
            return t4;
          }
          let x = 1;
          function v(t4, e2, r2) {
            const n2 = {};
            for (const r3 in t4) n2[r3] = e2.call(this, t4[r3], r3, t4);
            return n2;
          }
          function b(t4, e2, r2) {
            const n2 = {};
            for (const r3 in t4) e2.call(this, t4[r3], r3, t4) && (n2[r3] = t4[r3]);
            return n2;
          }
          function w(t4) {
            return Array.isArray(t4) ? t4.map(w) : "object" == typeof t4 && t4 ? v(t4, w) : t4;
          }
          const _ = {};
          function A2(t4) {
            _[t4] || ("undefined" != typeof console && console.warn(t4), _[t4] = true);
          }
          function S(t4, e2, r2) {
            return (r2.y - t4.y) * (e2.x - t4.x) > (e2.y - t4.y) * (r2.x - t4.x);
          }
          function k(t4) {
            return "undefined" != typeof WorkerGlobalScope && void 0 !== t4 && t4 instanceof WorkerGlobalScope;
          }
          let M = null;
          function I(t4) {
            return "undefined" != typeof ImageBitmap && t4 instanceof ImageBitmap;
          }
          const z = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";
          function P(t4, r2, n2, i2, s2) {
            return e(this, void 0, void 0, function* () {
              if ("undefined" == typeof VideoFrame) throw new Error("VideoFrame not supported");
              const e2 = new VideoFrame(t4, { timestamp: 0 });
              try {
                const a2 = null == e2 ? void 0 : e2.format;
                if (!a2 || !a2.startsWith("BGR") && !a2.startsWith("RGB")) throw new Error(`Unrecognized format ${a2}`);
                const o2 = a2.startsWith("BGR"), l2 = new Uint8ClampedArray(i2 * s2 * 4);
                if (yield e2.copyTo(l2, function(t5, e3, r3, n3, i3) {
                  const s3 = 4 * Math.max(-e3, 0), a3 = (Math.max(0, r3) - r3) * n3 * 4 + s3, o3 = 4 * n3, l3 = Math.max(0, e3), u2 = Math.max(0, r3);
                  return { rect: { x: l3, y: u2, width: Math.min(t5.width, e3 + n3) - l3, height: Math.min(t5.height, r3 + i3) - u2 }, layout: [{ offset: a3, stride: o3 }] };
                }(t4, r2, n2, i2, s2)), o2) for (let t5 = 0; t5 < l2.length; t5 += 4) {
                  const e3 = l2[t5];
                  l2[t5] = l2[t5 + 2], l2[t5 + 2] = e3;
                }
                return l2;
              } finally {
                e2.close();
              }
            });
          }
          let C2, B2;
          const V = "AbortError";
          function E2() {
            return new Error(V);
          }
          const F = { MAX_PARALLEL_IMAGE_REQUESTS: 16, MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME: 8, MAX_TILE_CACHE_ZOOM_LEVELS: 5, REGISTERED_PROTOCOLS: {}, WORKER_URL: "" };
          function T(t4) {
            return F.REGISTERED_PROTOCOLS[t4.substring(0, t4.indexOf("://"))];
          }
          const $ = "global-dispatcher";
          class L extends Error {
            constructor(t4, e2, r2, n2) {
              super(`AJAXError: ${e2} (${t4}): ${r2}`), this.status = t4, this.statusText = e2, this.url = r2, this.body = n2;
            }
          }
          const D2 = () => k(self) ? self.worker && self.worker.referrer : ("blob:" === window.location.protocol ? window.parent : window).location.href, O = function(t4, r2) {
            if (/:\/\//.test(t4.url) && !/^https?:|^file:/.test(t4.url)) {
              const e2 = T(t4.url);
              if (e2) return e2(t4, r2);
              if (k(self) && self.worker && self.worker.actor) return self.worker.actor.sendAsync({ type: "GR", data: t4, targetMapId: $ }, r2);
            }
            if (!(/^file:/.test(n2 = t4.url) || /^file:/.test(D2()) && !/^\w+:/.test(n2))) {
              if (fetch && Request && AbortController && Object.prototype.hasOwnProperty.call(Request.prototype, "signal")) return function(t5, r3) {
                return e(this, void 0, void 0, function* () {
                  const e2 = new Request(t5.url, { method: t5.method || "GET", body: t5.body, credentials: t5.credentials, headers: t5.headers, cache: t5.cache, referrer: D2(), signal: r3.signal });
                  "json" !== t5.type || e2.headers.has("Accept") || e2.headers.set("Accept", "application/json");
                  const n3 = yield fetch(e2);
                  if (!n3.ok) {
                    const e3 = yield n3.blob();
                    throw new L(n3.status, n3.statusText, t5.url, e3);
                  }
                  let i2;
                  i2 = "arrayBuffer" === t5.type || "image" === t5.type ? n3.arrayBuffer() : "json" === t5.type ? n3.json() : n3.text();
                  const s2 = yield i2;
                  if (r3.signal.aborted) throw E2();
                  return { data: s2, cacheControl: n3.headers.get("Cache-Control"), expires: n3.headers.get("Expires") };
                });
              }(t4, r2);
              if (k(self) && self.worker && self.worker.actor) return self.worker.actor.sendAsync({ type: "GR", data: t4, mustQueue: true, targetMapId: $ }, r2);
            }
            var n2;
            return function(t5, e2) {
              return new Promise((r3, n3) => {
                var i2;
                const s2 = new XMLHttpRequest();
                s2.open(t5.method || "GET", t5.url, true), "arrayBuffer" !== t5.type && "image" !== t5.type || (s2.responseType = "arraybuffer");
                for (const e3 in t5.headers) s2.setRequestHeader(e3, t5.headers[e3]);
                "json" === t5.type && (s2.responseType = "text", (null === (i2 = t5.headers) || void 0 === i2 ? void 0 : i2.Accept) || s2.setRequestHeader("Accept", "application/json")), s2.withCredentials = "include" === t5.credentials, s2.onerror = () => {
                  n3(new Error(s2.statusText));
                }, s2.onload = () => {
                  if (!e2.signal.aborted) if ((s2.status >= 200 && s2.status < 300 || 0 === s2.status) && null !== s2.response) {
                    let e3 = s2.response;
                    if ("json" === t5.type) try {
                      e3 = JSON.parse(s2.response);
                    } catch (t6) {
                      return void n3(t6);
                    }
                    r3({ data: e3, cacheControl: s2.getResponseHeader("Cache-Control"), expires: s2.getResponseHeader("Expires") });
                  } else {
                    const e3 = new Blob([s2.response], { type: s2.getResponseHeader("Content-Type") });
                    n3(new L(s2.status, s2.statusText, t5.url, e3));
                  }
                }, e2.signal.addEventListener("abort", () => {
                  s2.abort(), n3(E2());
                }), s2.send(t5.body);
              });
            }(t4, r2);
          };
          function j(t4) {
            if (!t4 || t4.indexOf("://") <= 0 || 0 === t4.indexOf("data:image/") || 0 === t4.indexOf("blob:")) return true;
            const e2 = new URL(t4), r2 = window.location;
            return e2.protocol === r2.protocol && e2.host === r2.host;
          }
          function R(t4, e2, r2) {
            r2[t4] && -1 !== r2[t4].indexOf(e2) || (r2[t4] = r2[t4] || [], r2[t4].push(e2));
          }
          function U(t4, e2, r2) {
            if (r2 && r2[t4]) {
              const n2 = r2[t4].indexOf(e2);
              -1 !== n2 && r2[t4].splice(n2, 1);
            }
          }
          class q {
            constructor(t4, e2 = {}) {
              g(this, e2), this.type = t4;
            }
          }
          class N extends q {
            constructor(t4, e2 = {}) {
              super("error", g({ error: t4 }, e2));
            }
          }
          class Z {
            on(t4, e2) {
              return this._listeners = this._listeners || {}, R(t4, e2, this._listeners), this;
            }
            off(t4, e2) {
              return U(t4, e2, this._listeners), U(t4, e2, this._oneTimeListeners), this;
            }
            once(t4, e2) {
              return e2 ? (this._oneTimeListeners = this._oneTimeListeners || {}, R(t4, e2, this._oneTimeListeners), this) : new Promise((e3) => this.once(t4, e3));
            }
            fire(t4, e2) {
              "string" == typeof t4 && (t4 = new q(t4, e2 || {}));
              const r2 = t4.type;
              if (this.listens(r2)) {
                t4.target = this;
                const e3 = this._listeners && this._listeners[r2] ? this._listeners[r2].slice() : [];
                for (const r3 of e3) r3.call(this, t4);
                const n2 = this._oneTimeListeners && this._oneTimeListeners[r2] ? this._oneTimeListeners[r2].slice() : [];
                for (const e4 of n2) U(r2, e4, this._oneTimeListeners), e4.call(this, t4);
                const i2 = this._eventedParent;
                i2 && (g(t4, "function" == typeof this._eventedParentData ? this._eventedParentData() : this._eventedParentData), i2.fire(t4));
              } else t4 instanceof N && console.error(t4.error);
              return this;
            }
            listens(t4) {
              return this._listeners && this._listeners[t4] && this._listeners[t4].length > 0 || this._oneTimeListeners && this._oneTimeListeners[t4] && this._oneTimeListeners[t4].length > 0 || this._eventedParent && this._eventedParent.listens(t4);
            }
            setEventedParent(t4, e2) {
              return this._eventedParent = t4, this._eventedParentData = e2, this;
            }
          }
          var G = { $version: 8, $root: { version: { required: true, type: "enum", values: [8] }, name: { type: "string" }, metadata: { type: "*" }, center: { type: "array", value: "number" }, zoom: { type: "number" }, bearing: { type: "number", default: 0, period: 360, units: "degrees" }, pitch: { type: "number", default: 0, units: "degrees" }, light: { type: "light" }, sky: { type: "sky" }, projection: { type: "projection" }, terrain: { type: "terrain" }, sources: { required: true, type: "sources" }, sprite: { type: "sprite" }, glyphs: { type: "string" }, transition: { type: "transition" }, layers: { required: true, type: "array", value: "layer" } }, sources: { "*": { type: "source" } }, source: ["source_vector", "source_raster", "source_raster_dem", "source_geojson", "source_video", "source_image"], source_vector: { type: { required: true, type: "enum", values: { vector: {} } }, url: { type: "string" }, tiles: { type: "array", value: "string" }, bounds: { type: "array", value: "number", length: 4, default: [-180, -85.051129, 180, 85.051129] }, scheme: { type: "enum", values: { xyz: {}, tms: {} }, default: "xyz" }, minzoom: { type: "number", default: 0 }, maxzoom: { type: "number", default: 22 }, attribution: { type: "string" }, promoteId: { type: "promoteId" }, volatile: { type: "boolean", default: false }, "*": { type: "*" } }, source_raster: { type: { required: true, type: "enum", values: { raster: {} } }, url: { type: "string" }, tiles: { type: "array", value: "string" }, bounds: { type: "array", value: "number", length: 4, default: [-180, -85.051129, 180, 85.051129] }, minzoom: { type: "number", default: 0 }, maxzoom: { type: "number", default: 22 }, tileSize: { type: "number", default: 512, units: "pixels" }, scheme: { type: "enum", values: { xyz: {}, tms: {} }, default: "xyz" }, attribution: { type: "string" }, volatile: { type: "boolean", default: false }, "*": { type: "*" } }, source_raster_dem: { type: { required: true, type: "enum", values: { "raster-dem": {} } }, url: { type: "string" }, tiles: { type: "array", value: "string" }, bounds: { type: "array", value: "number", length: 4, default: [-180, -85.051129, 180, 85.051129] }, minzoom: { type: "number", default: 0 }, maxzoom: { type: "number", default: 22 }, tileSize: { type: "number", default: 512, units: "pixels" }, attribution: { type: "string" }, encoding: { type: "enum", values: { terrarium: {}, mapbox: {}, custom: {} }, default: "mapbox" }, redFactor: { type: "number", default: 1 }, blueFactor: { type: "number", default: 1 }, greenFactor: { type: "number", default: 1 }, baseShift: { type: "number", default: 0 }, volatile: { type: "boolean", default: false }, "*": { type: "*" } }, source_geojson: { type: { required: true, type: "enum", values: { geojson: {} } }, data: { required: true, type: "*" }, maxzoom: { type: "number", default: 18 }, attribution: { type: "string" }, buffer: { type: "number", default: 128, maximum: 512, minimum: 0 }, filter: { type: "*" }, tolerance: { type: "number", default: 0.375 }, cluster: { type: "boolean", default: false }, clusterRadius: { type: "number", default: 50, minimum: 0 }, clusterMaxZoom: { type: "number" }, clusterMinPoints: { type: "number" }, clusterProperties: { type: "*" }, lineMetrics: { type: "boolean", default: false }, generateId: { type: "boolean", default: false }, promoteId: { type: "promoteId" } }, source_video: { type: { required: true, type: "enum", values: { video: {} } }, urls: { required: true, type: "array", value: "string" }, coordinates: { required: true, type: "array", length: 4, value: { type: "array", length: 2, value: "number" } } }, source_image: { type: { required: true, type: "enum", values: { image: {} } }, url: { required: true, type: "string" }, coordinates: { required: true, type: "array", length: 4, value: { type: "array", length: 2, value: "number" } } }, layer: { id: { type: "string", required: true }, type: { type: "enum", values: { fill: {}, line: {}, symbol: {}, circle: {}, heatmap: {}, "fill-extrusion": {}, raster: {}, hillshade: {}, background: {} }, required: true }, metadata: { type: "*" }, source: { type: "string" }, "source-layer": { type: "string" }, minzoom: { type: "number", minimum: 0, maximum: 24 }, maxzoom: { type: "number", minimum: 0, maximum: 24 }, filter: { type: "filter" }, layout: { type: "layout" }, paint: { type: "paint" } }, layout: ["layout_fill", "layout_line", "layout_circle", "layout_heatmap", "layout_fill-extrusion", "layout_symbol", "layout_raster", "layout_hillshade", "layout_background"], layout_background: { visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, layout_fill: { "fill-sort-key": { type: "number", expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, layout_circle: { "circle-sort-key": { type: "number", expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, layout_heatmap: { visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, "layout_fill-extrusion": { visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, layout_line: { "line-cap": { type: "enum", values: { butt: {}, round: {}, square: {} }, default: "butt", expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "line-join": { type: "enum", values: { bevel: {}, round: {}, miter: {} }, default: "miter", expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "line-miter-limit": { type: "number", default: 2, requires: [{ "line-join": "miter" }], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "line-round-limit": { type: "number", default: 1.05, requires: [{ "line-join": "round" }], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "line-sort-key": { type: "number", expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, layout_symbol: { "symbol-placement": { type: "enum", values: { point: {}, line: {}, "line-center": {} }, default: "point", expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "symbol-spacing": { type: "number", default: 250, minimum: 1, units: "pixels", requires: [{ "symbol-placement": "line" }], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "symbol-avoid-edges": { type: "boolean", default: false, expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "symbol-sort-key": { type: "number", expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "symbol-z-order": { type: "enum", values: { auto: {}, "viewport-y": {}, source: {} }, default: "auto", expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-allow-overlap": { type: "boolean", default: false, requires: ["icon-image", { "!": "icon-overlap" }], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-overlap": { type: "enum", values: { never: {}, always: {}, cooperative: {} }, requires: ["icon-image"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-ignore-placement": { type: "boolean", default: false, requires: ["icon-image"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-optional": { type: "boolean", default: false, requires: ["icon-image", "text-field"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-rotation-alignment": { type: "enum", values: { map: {}, viewport: {}, auto: {} }, default: "auto", requires: ["icon-image"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-size": { type: "number", default: 1, minimum: 0, units: "factor of the original icon size", requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "icon-text-fit": { type: "enum", values: { none: {}, width: {}, height: {}, both: {} }, default: "none", requires: ["icon-image", "text-field"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-text-fit-padding": { type: "array", value: "number", length: 4, default: [0, 0, 0, 0], units: "pixels", requires: ["icon-image", "text-field", { "icon-text-fit": ["both", "width", "height"] }], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-image": { type: "resolvedImage", tokens: true, expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "icon-rotate": { type: "number", default: 0, period: 360, units: "degrees", requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "icon-padding": { type: "padding", default: [2], units: "pixels", requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "icon-keep-upright": { type: "boolean", default: false, requires: ["icon-image", { "icon-rotation-alignment": "map" }, { "symbol-placement": ["line", "line-center"] }], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-offset": { type: "array", value: "number", length: 2, default: [0, 0], requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "icon-anchor": { type: "enum", values: { center: {}, left: {}, right: {}, top: {}, bottom: {}, "top-left": {}, "top-right": {}, "bottom-left": {}, "bottom-right": {} }, default: "center", requires: ["icon-image"], expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "icon-pitch-alignment": { type: "enum", values: { map: {}, viewport: {}, auto: {} }, default: "auto", requires: ["icon-image"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-pitch-alignment": { type: "enum", values: { map: {}, viewport: {}, auto: {} }, default: "auto", requires: ["text-field"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-rotation-alignment": { type: "enum", values: { map: {}, viewport: {}, "viewport-glyph": {}, auto: {} }, default: "auto", requires: ["text-field"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-field": { type: "formatted", default: "", tokens: true, expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-font": { type: "array", value: "string", default: ["Open Sans Regular", "Arial Unicode MS Regular"], requires: ["text-field"], expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-size": { type: "number", default: 16, minimum: 0, units: "pixels", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-max-width": { type: "number", default: 10, minimum: 0, units: "ems", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-line-height": { type: "number", default: 1.2, units: "ems", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-letter-spacing": { type: "number", default: 0, units: "ems", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-justify": { type: "enum", values: { auto: {}, left: {}, center: {}, right: {} }, default: "center", requires: ["text-field"], expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-radial-offset": { type: "number", units: "ems", default: 0, requires: ["text-field"], "property-type": "data-driven", expression: { interpolated: true, parameters: ["zoom", "feature"] } }, "text-variable-anchor": { type: "array", value: "enum", values: { center: {}, left: {}, right: {}, top: {}, bottom: {}, "top-left": {}, "top-right": {}, "bottom-left": {}, "bottom-right": {} }, requires: ["text-field", { "symbol-placement": ["point"] }], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-variable-anchor-offset": { type: "variableAnchorOffsetCollection", requires: ["text-field", { "symbol-placement": ["point"] }], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-anchor": { type: "enum", values: { center: {}, left: {}, right: {}, top: {}, bottom: {}, "top-left": {}, "top-right": {}, "bottom-left": {}, "bottom-right": {} }, default: "center", requires: ["text-field", { "!": "text-variable-anchor" }], expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-max-angle": { type: "number", default: 45, units: "degrees", requires: ["text-field", { "symbol-placement": ["line", "line-center"] }], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-writing-mode": { type: "array", value: "enum", values: { horizontal: {}, vertical: {} }, requires: ["text-field", { "symbol-placement": ["point"] }], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-rotate": { type: "number", default: 0, period: 360, units: "degrees", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-padding": { type: "number", default: 2, minimum: 0, units: "pixels", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-keep-upright": { type: "boolean", default: true, requires: ["text-field", { "text-rotation-alignment": "map" }, { "symbol-placement": ["line", "line-center"] }], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-transform": { type: "enum", values: { none: {}, uppercase: {}, lowercase: {} }, default: "none", requires: ["text-field"], expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-offset": { type: "array", value: "number", units: "ems", length: 2, default: [0, 0], requires: ["text-field", { "!": "text-radial-offset" }], expression: { interpolated: true, parameters: ["zoom", "feature"] }, "property-type": "data-driven" }, "text-allow-overlap": { type: "boolean", default: false, requires: ["text-field", { "!": "text-overlap" }], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-overlap": { type: "enum", values: { never: {}, always: {}, cooperative: {} }, requires: ["text-field"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-ignore-placement": { type: "boolean", default: false, requires: ["text-field"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-optional": { type: "boolean", default: false, requires: ["text-field", "icon-image"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, layout_raster: { visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, layout_hillshade: { visibility: { type: "enum", values: { visible: {}, none: {} }, default: "visible", "property-type": "constant" } }, filter: { type: "array", value: "*" }, filter_operator: { type: "enum", values: { "==": {}, "!=": {}, ">": {}, ">=": {}, "<": {}, "<=": {}, in: {}, "!in": {}, all: {}, any: {}, none: {}, has: {}, "!has": {} } }, geometry_type: { type: "enum", values: { Point: {}, LineString: {}, Polygon: {} } }, function: { expression: { type: "expression" }, stops: { type: "array", value: "function_stop" }, base: { type: "number", default: 1, minimum: 0 }, property: { type: "string", default: "$zoom" }, type: { type: "enum", values: { identity: {}, exponential: {}, interval: {}, categorical: {} }, default: "exponential" }, colorSpace: { type: "enum", values: { rgb: {}, lab: {}, hcl: {} }, default: "rgb" }, default: { type: "*", required: false } }, function_stop: { type: "array", minimum: 0, maximum: 24, value: ["number", "color"], length: 2 }, expression: { type: "array", value: "*", minimum: 1 }, light: { anchor: { type: "enum", default: "viewport", values: { map: {}, viewport: {} }, "property-type": "data-constant", transition: false, expression: { interpolated: false, parameters: ["zoom"] } }, position: { type: "array", default: [1.15, 210, 30], length: 3, value: "number", "property-type": "data-constant", transition: true, expression: { interpolated: true, parameters: ["zoom"] } }, color: { type: "color", "property-type": "data-constant", default: "#ffffff", expression: { interpolated: true, parameters: ["zoom"] }, transition: true }, intensity: { type: "number", "property-type": "data-constant", default: 0.5, minimum: 0, maximum: 1, expression: { interpolated: true, parameters: ["zoom"] }, transition: true } }, sky: { "sky-color": { type: "color", "property-type": "data-constant", default: "#88C6FC", expression: { interpolated: true, parameters: ["zoom"] }, transition: true }, "horizon-color": { type: "color", "property-type": "data-constant", default: "#ffffff", expression: { interpolated: true, parameters: ["zoom"] }, transition: true }, "fog-color": { type: "color", "property-type": "data-constant", default: "#ffffff", expression: { interpolated: true, parameters: ["zoom"] }, transition: true }, "fog-ground-blend": { type: "number", "property-type": "data-constant", default: 0.5, minimum: 0, maximum: 1, expression: { interpolated: true, parameters: ["zoom"] }, transition: true }, "horizon-fog-blend": { type: "number", "property-type": "data-constant", default: 0.8, minimum: 0, maximum: 1, expression: { interpolated: true, parameters: ["zoom"] }, transition: true }, "sky-horizon-blend": { type: "number", "property-type": "data-constant", default: 0.8, minimum: 0, maximum: 1, expression: { interpolated: true, parameters: ["zoom"] }, transition: true }, "atmosphere-blend": { type: "number", "property-type": "data-constant", default: 0.8, minimum: 0, maximum: 1, expression: { interpolated: true, parameters: ["zoom"] }, transition: true } }, terrain: { source: { type: "string", required: true }, exaggeration: { type: "number", minimum: 0, default: 1 } }, projection: { type: { type: "enum", default: "mercator", values: { mercator: {}, globe: {} } } }, paint: ["paint_fill", "paint_line", "paint_circle", "paint_heatmap", "paint_fill-extrusion", "paint_symbol", "paint_raster", "paint_hillshade", "paint_background"], paint_fill: { "fill-antialias": { type: "boolean", default: true, expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "fill-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "fill-color": { type: "color", default: "#000000", transition: true, requires: [{ "!": "fill-pattern" }], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "fill-outline-color": { type: "color", transition: true, requires: [{ "!": "fill-pattern" }, { "fill-antialias": true }], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "fill-translate": { type: "array", value: "number", length: 2, default: [0, 0], transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "fill-translate-anchor": { type: "enum", values: { map: {}, viewport: {} }, default: "map", requires: ["fill-translate"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "fill-pattern": { type: "resolvedImage", transition: true, expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "cross-faded-data-driven" } }, "paint_fill-extrusion": { "fill-extrusion-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "fill-extrusion-color": { type: "color", default: "#000000", transition: true, requires: [{ "!": "fill-extrusion-pattern" }], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "fill-extrusion-translate": { type: "array", value: "number", length: 2, default: [0, 0], transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "fill-extrusion-translate-anchor": { type: "enum", values: { map: {}, viewport: {} }, default: "map", requires: ["fill-extrusion-translate"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "fill-extrusion-pattern": { type: "resolvedImage", transition: true, expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "cross-faded-data-driven" }, "fill-extrusion-height": { type: "number", default: 0, minimum: 0, units: "meters", transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "fill-extrusion-base": { type: "number", default: 0, minimum: 0, units: "meters", transition: true, requires: ["fill-extrusion-height"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "fill-extrusion-vertical-gradient": { type: "boolean", default: true, transition: false, expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" } }, paint_line: { "line-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "line-color": { type: "color", default: "#000000", transition: true, requires: [{ "!": "line-pattern" }], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "line-translate": { type: "array", value: "number", length: 2, default: [0, 0], transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "line-translate-anchor": { type: "enum", values: { map: {}, viewport: {} }, default: "map", requires: ["line-translate"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "line-width": { type: "number", default: 1, minimum: 0, transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "line-gap-width": { type: "number", default: 0, minimum: 0, transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "line-offset": { type: "number", default: 0, transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "line-blur": { type: "number", default: 0, minimum: 0, transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "line-dasharray": { type: "array", value: "number", minimum: 0, transition: true, units: "line widths", requires: [{ "!": "line-pattern" }], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "cross-faded" }, "line-pattern": { type: "resolvedImage", transition: true, expression: { interpolated: false, parameters: ["zoom", "feature"] }, "property-type": "cross-faded-data-driven" }, "line-gradient": { type: "color", transition: false, requires: [{ "!": "line-dasharray" }, { "!": "line-pattern" }, { source: "geojson", has: { lineMetrics: true } }], expression: { interpolated: true, parameters: ["line-progress"] }, "property-type": "color-ramp" } }, paint_circle: { "circle-radius": { type: "number", default: 5, minimum: 0, transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "circle-color": { type: "color", default: "#000000", transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "circle-blur": { type: "number", default: 0, transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "circle-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "circle-translate": { type: "array", value: "number", length: 2, default: [0, 0], transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "circle-translate-anchor": { type: "enum", values: { map: {}, viewport: {} }, default: "map", requires: ["circle-translate"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "circle-pitch-scale": { type: "enum", values: { map: {}, viewport: {} }, default: "map", expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "circle-pitch-alignment": { type: "enum", values: { map: {}, viewport: {} }, default: "viewport", expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "circle-stroke-width": { type: "number", default: 0, minimum: 0, transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "circle-stroke-color": { type: "color", default: "#000000", transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "circle-stroke-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" } }, paint_heatmap: { "heatmap-radius": { type: "number", default: 30, minimum: 1, transition: true, units: "pixels", expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "heatmap-weight": { type: "number", default: 1, minimum: 0, transition: false, expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "heatmap-intensity": { type: "number", default: 1, minimum: 0, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "heatmap-color": { type: "color", default: ["interpolate", ["linear"], ["heatmap-density"], 0, "rgba(0, 0, 255, 0)", 0.1, "royalblue", 0.3, "cyan", 0.5, "lime", 0.7, "yellow", 1, "red"], transition: false, expression: { interpolated: true, parameters: ["heatmap-density"] }, "property-type": "color-ramp" }, "heatmap-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" } }, paint_symbol: { "icon-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "icon-color": { type: "color", default: "#000000", transition: true, requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "icon-halo-color": { type: "color", default: "rgba(0, 0, 0, 0)", transition: true, requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "icon-halo-width": { type: "number", default: 0, minimum: 0, transition: true, units: "pixels", requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "icon-halo-blur": { type: "number", default: 0, minimum: 0, transition: true, units: "pixels", requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "icon-translate": { type: "array", value: "number", length: 2, default: [0, 0], transition: true, units: "pixels", requires: ["icon-image"], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "icon-translate-anchor": { type: "enum", values: { map: {}, viewport: {} }, default: "map", requires: ["icon-image", "icon-translate"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "text-color": { type: "color", default: "#000000", transition: true, overridable: true, requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "text-halo-color": { type: "color", default: "rgba(0, 0, 0, 0)", transition: true, requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "text-halo-width": { type: "number", default: 0, minimum: 0, transition: true, units: "pixels", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "text-halo-blur": { type: "number", default: 0, minimum: 0, transition: true, units: "pixels", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom", "feature", "feature-state"] }, "property-type": "data-driven" }, "text-translate": { type: "array", value: "number", length: 2, default: [0, 0], transition: true, units: "pixels", requires: ["text-field"], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "text-translate-anchor": { type: "enum", values: { map: {}, viewport: {} }, default: "map", requires: ["text-field", "text-translate"], expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" } }, paint_raster: { "raster-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "raster-hue-rotate": { type: "number", default: 0, period: 360, transition: true, units: "degrees", expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "raster-brightness-min": { type: "number", default: 0, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "raster-brightness-max": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "raster-saturation": { type: "number", default: 0, minimum: -1, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "raster-contrast": { type: "number", default: 0, minimum: -1, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "raster-resampling": { type: "enum", values: { linear: {}, nearest: {} }, default: "linear", expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "raster-fade-duration": { type: "number", default: 300, minimum: 0, transition: false, units: "milliseconds", expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" } }, paint_hillshade: { "hillshade-illumination-direction": { type: "number", default: 335, minimum: 0, maximum: 359, transition: false, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "hillshade-illumination-anchor": { type: "enum", values: { map: {}, viewport: {} }, default: "viewport", expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "data-constant" }, "hillshade-exaggeration": { type: "number", default: 0.5, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "hillshade-shadow-color": { type: "color", default: "#000000", transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "hillshade-highlight-color": { type: "color", default: "#FFFFFF", transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "hillshade-accent-color": { type: "color", default: "#000000", transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" } }, paint_background: { "background-color": { type: "color", default: "#000000", transition: true, requires: [{ "!": "background-pattern" }], expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" }, "background-pattern": { type: "resolvedImage", transition: true, expression: { interpolated: false, parameters: ["zoom"] }, "property-type": "cross-faded" }, "background-opacity": { type: "number", default: 1, minimum: 0, maximum: 1, transition: true, expression: { interpolated: true, parameters: ["zoom"] }, "property-type": "data-constant" } }, transition: { duration: { type: "number", default: 300, minimum: 0, units: "milliseconds" }, delay: { type: "number", default: 0, minimum: 0, units: "milliseconds" } }, "property-type": { "data-driven": { type: "property-type" }, "cross-faded": { type: "property-type" }, "cross-faded-data-driven": { type: "property-type" }, "color-ramp": { type: "property-type" }, "data-constant": { type: "property-type" }, constant: { type: "property-type" } }, promoteId: { "*": { type: "string" } } };
          const K2 = ["type", "source", "source-layer", "minzoom", "maxzoom", "filter", "layout"];
          function X(t4, e2) {
            const r2 = {};
            for (const e3 in t4) "ref" !== e3 && (r2[e3] = t4[e3]);
            return K2.forEach((t5) => {
              t5 in e2 && (r2[t5] = e2[t5]);
            }), r2;
          }
          function H(t4, e2) {
            if (Array.isArray(t4)) {
              if (!Array.isArray(e2) || t4.length !== e2.length) return false;
              for (let r2 = 0; r2 < t4.length; r2++) if (!H(t4[r2], e2[r2])) return false;
              return true;
            }
            if ("object" == typeof t4 && null !== t4 && null !== e2) {
              if ("object" != typeof e2) return false;
              if (Object.keys(t4).length !== Object.keys(e2).length) return false;
              for (const r2 in t4) if (!H(t4[r2], e2[r2])) return false;
              return true;
            }
            return t4 === e2;
          }
          function Y(t4, e2) {
            t4.push(e2);
          }
          function J(t4, e2, r2) {
            Y(r2, { command: "addSource", args: [t4, e2[t4]] });
          }
          function W(t4, e2, r2) {
            Y(e2, { command: "removeSource", args: [t4] }), r2[t4] = true;
          }
          function Q(t4, e2, r2, n2) {
            W(t4, r2, n2), J(t4, e2, r2);
          }
          function tt(t4, e2, r2) {
            let n2;
            for (n2 in t4[r2]) if (Object.prototype.hasOwnProperty.call(t4[r2], n2) && "data" !== n2 && !H(t4[r2][n2], e2[r2][n2])) return false;
            for (n2 in e2[r2]) if (Object.prototype.hasOwnProperty.call(e2[r2], n2) && "data" !== n2 && !H(t4[r2][n2], e2[r2][n2])) return false;
            return true;
          }
          function et(t4, e2, r2, n2, i2, s2) {
            t4 = t4 || {}, e2 = e2 || {};
            for (const a2 in t4) Object.prototype.hasOwnProperty.call(t4, a2) && (H(t4[a2], e2[a2]) || r2.push({ command: s2, args: [n2, a2, e2[a2], i2] }));
            for (const a2 in e2) Object.prototype.hasOwnProperty.call(e2, a2) && !Object.prototype.hasOwnProperty.call(t4, a2) && (H(t4[a2], e2[a2]) || r2.push({ command: s2, args: [n2, a2, e2[a2], i2] }));
          }
          function rt(t4) {
            return t4.id;
          }
          function nt(t4, e2) {
            return t4[e2.id] = e2, t4;
          }
          class it {
            constructor(t4, e2, r2, n2) {
              this.message = (t4 ? `${t4}: ` : "") + r2, n2 && (this.identifier = n2), null != e2 && e2.__line__ && (this.line = e2.__line__);
            }
          }
          function st(t4, ...e2) {
            for (const r2 of e2) for (const e3 in r2) t4[e3] = r2[e3];
            return t4;
          }
          class at extends Error {
            constructor(t4, e2) {
              super(e2), this.message = e2, this.key = t4;
            }
          }
          class ot {
            constructor(t4, e2 = []) {
              this.parent = t4, this.bindings = {};
              for (const [t5, r2] of e2) this.bindings[t5] = r2;
            }
            concat(t4) {
              return new ot(this, t4);
            }
            get(t4) {
              if (this.bindings[t4]) return this.bindings[t4];
              if (this.parent) return this.parent.get(t4);
              throw new Error(`${t4} not found in scope.`);
            }
            has(t4) {
              return !!this.bindings[t4] || !!this.parent && this.parent.has(t4);
            }
          }
          const lt = { kind: "null" }, ut = { kind: "number" }, ct = { kind: "string" }, ht = { kind: "boolean" }, pt = { kind: "color" }, ft = { kind: "object" }, dt = { kind: "value" }, yt = { kind: "collator" }, mt = { kind: "formatted" }, gt = { kind: "padding" }, xt = { kind: "resolvedImage" }, vt = { kind: "variableAnchorOffsetCollection" };
          function bt(t4, e2) {
            return { kind: "array", itemType: t4, N: e2 };
          }
          function wt(t4) {
            if ("array" === t4.kind) {
              const e2 = wt(t4.itemType);
              return "number" == typeof t4.N ? `array<${e2}, ${t4.N}>` : "value" === t4.itemType.kind ? "array" : `array<${e2}>`;
            }
            return t4.kind;
          }
          const _t = [lt, ut, ct, ht, pt, mt, ft, bt(dt), gt, xt, vt];
          function At(t4, e2) {
            if ("error" === e2.kind) return null;
            if ("array" === t4.kind) {
              if ("array" === e2.kind && (0 === e2.N && "value" === e2.itemType.kind || !At(t4.itemType, e2.itemType)) && ("number" != typeof t4.N || t4.N === e2.N)) return null;
            } else {
              if (t4.kind === e2.kind) return null;
              if ("value" === t4.kind) {
                for (const t5 of _t) if (!At(t5, e2)) return null;
              }
            }
            return `Expected ${wt(t4)} but found ${wt(e2)} instead.`;
          }
          function St(t4, e2) {
            return e2.some((e3) => e3.kind === t4.kind);
          }
          function kt(t4, e2) {
            return e2.some((e3) => "null" === e3 ? null === t4 : "array" === e3 ? Array.isArray(t4) : "object" === e3 ? t4 && !Array.isArray(t4) && "object" == typeof t4 : e3 === typeof t4);
          }
          function Mt(t4, e2) {
            return "array" === t4.kind && "array" === e2.kind ? t4.itemType.kind === e2.itemType.kind && "number" == typeof t4.N : t4.kind === e2.kind;
          }
          const It = 0.96422, zt = 0.82521, Pt = 4 / 29, Ct = 6 / 29, Bt = 3 * Ct * Ct, Vt = Ct * Ct * Ct, Et = Math.PI / 180, Ft = 180 / Math.PI;
          function Tt(t4) {
            return (t4 %= 360) < 0 && (t4 += 360), t4;
          }
          function $t([t4, e2, r2, n2]) {
            let i2, s2;
            const a2 = Dt((0.2225045 * (t4 = Lt(t4)) + 0.7168786 * (e2 = Lt(e2)) + 0.0606169 * (r2 = Lt(r2))) / 1);
            t4 === e2 && e2 === r2 ? i2 = s2 = a2 : (i2 = Dt((0.4360747 * t4 + 0.3850649 * e2 + 0.1430804 * r2) / It), s2 = Dt((0.0139322 * t4 + 0.0971045 * e2 + 0.7141733 * r2) / zt));
            const o2 = 116 * a2 - 16;
            return [o2 < 0 ? 0 : o2, 500 * (i2 - a2), 200 * (a2 - s2), n2];
          }
          function Lt(t4) {
            return t4 <= 0.04045 ? t4 / 12.92 : Math.pow((t4 + 0.055) / 1.055, 2.4);
          }
          function Dt(t4) {
            return t4 > Vt ? Math.pow(t4, 1 / 3) : t4 / Bt + Pt;
          }
          function Ot([t4, e2, r2, n2]) {
            let i2 = (t4 + 16) / 116, s2 = isNaN(e2) ? i2 : i2 + e2 / 500, a2 = isNaN(r2) ? i2 : i2 - r2 / 200;
            return i2 = 1 * Rt(i2), s2 = It * Rt(s2), a2 = zt * Rt(a2), [jt(3.1338561 * s2 - 1.6168667 * i2 - 0.4906146 * a2), jt(-0.9787684 * s2 + 1.9161415 * i2 + 0.033454 * a2), jt(0.0719453 * s2 - 0.2289914 * i2 + 1.4052427 * a2), n2];
          }
          function jt(t4) {
            return (t4 = t4 <= 304e-5 ? 12.92 * t4 : 1.055 * Math.pow(t4, 1 / 2.4) - 0.055) < 0 ? 0 : t4 > 1 ? 1 : t4;
          }
          function Rt(t4) {
            return t4 > Ct ? t4 * t4 * t4 : Bt * (t4 - Pt);
          }
          function Ut(t4) {
            return parseInt(t4.padEnd(2, t4), 16) / 255;
          }
          function qt(t4, e2) {
            return Nt(e2 ? t4 / 100 : t4, 0, 1);
          }
          function Nt(t4, e2, r2) {
            return Math.min(Math.max(e2, t4), r2);
          }
          function Zt(t4) {
            return !t4.some(Number.isNaN);
          }
          const Gt = { 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], green: [0, 128, 0], greenyellow: [173, 255, 47], grey: [128, 128, 128], 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], rebeccapurple: [102, 51, 153], 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] };
          class Kt {
            constructor(t4, e2, r2, n2 = 1, i2 = true) {
              this.r = t4, this.g = e2, this.b = r2, this.a = n2, i2 || (this.r *= n2, this.g *= n2, this.b *= n2, n2 || this.overwriteGetter("rgb", [t4, e2, r2, n2]));
            }
            static parse(t4) {
              if (t4 instanceof Kt) return t4;
              if ("string" != typeof t4) return;
              const e2 = function(t5) {
                if ("transparent" === (t5 = t5.toLowerCase().trim())) return [0, 0, 0, 0];
                const e3 = Gt[t5];
                if (e3) {
                  const [t6, r3, n2] = e3;
                  return [t6 / 255, r3 / 255, n2 / 255, 1];
                }
                if (t5.startsWith("#") && /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t5)) {
                  const e4 = t5.length < 6 ? 1 : 2;
                  let r3 = 1;
                  return [Ut(t5.slice(r3, r3 += e4)), Ut(t5.slice(r3, r3 += e4)), Ut(t5.slice(r3, r3 += e4)), Ut(t5.slice(r3, r3 + e4) || "ff")];
                }
                if (t5.startsWith("rgb")) {
                  const e4 = t5.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);
                  if (e4) {
                    const [t6, r3, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2] = e4, f2 = [i2 || " ", o2 || " ", c2].join("");
                    if ("  " === f2 || "  /" === f2 || ",," === f2 || ",,," === f2) {
                      const t7 = [n2, a2, u2].join(""), e5 = "%%%" === t7 ? 100 : "" === t7 ? 255 : 0;
                      if (e5) {
                        const t8 = [Nt(+r3 / e5, 0, 1), Nt(+s2 / e5, 0, 1), Nt(+l2 / e5, 0, 1), h2 ? qt(+h2, p2) : 1];
                        if (Zt(t8)) return t8;
                      }
                    }
                    return;
                  }
                }
                const r2 = t5.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);
                if (r2) {
                  const [t6, e4, n2, i2, s2, a2, o2, l2, u2] = r2, c2 = [n2 || " ", s2 || " ", o2].join("");
                  if ("  " === c2 || "  /" === c2 || ",," === c2 || ",,," === c2) {
                    const t7 = [+e4, Nt(+i2, 0, 100), Nt(+a2, 0, 100), l2 ? qt(+l2, u2) : 1];
                    if (Zt(t7)) return function([t8, e5, r3, n3]) {
                      function i3(n4) {
                        const i4 = (n4 + t8 / 30) % 12, s3 = e5 * Math.min(r3, 1 - r3);
                        return r3 - s3 * Math.max(-1, Math.min(i4 - 3, 9 - i4, 1));
                      }
                      return t8 = Tt(t8), e5 /= 100, r3 /= 100, [i3(0), i3(8), i3(4), n3];
                    }(t7);
                  }
                }
              }(t4);
              return e2 ? new Kt(...e2, false) : void 0;
            }
            get rgb() {
              const { r: t4, g: e2, b: r2, a: n2 } = this, i2 = n2 || 1 / 0;
              return this.overwriteGetter("rgb", [t4 / i2, e2 / i2, r2 / i2, n2]);
            }
            get hcl() {
              return this.overwriteGetter("hcl", function(t4) {
                const [e2, r2, n2, i2] = $t(t4), s2 = Math.sqrt(r2 * r2 + n2 * n2);
                return [Math.round(1e4 * s2) ? Tt(Math.atan2(n2, r2) * Ft) : NaN, s2, e2, i2];
              }(this.rgb));
            }
            get lab() {
              return this.overwriteGetter("lab", $t(this.rgb));
            }
            overwriteGetter(t4, e2) {
              return Object.defineProperty(this, t4, { value: e2 }), e2;
            }
            toString() {
              const [t4, e2, r2, n2] = this.rgb;
              return `rgba(${[t4, e2, r2].map((t5) => Math.round(255 * t5)).join(",")},${n2})`;
            }
          }
          Kt.black = new Kt(0, 0, 0, 1), Kt.white = new Kt(1, 1, 1, 1), Kt.transparent = new Kt(0, 0, 0, 0), Kt.red = new Kt(1, 0, 0, 1);
          class Xt {
            constructor(t4, e2, r2) {
              this.sensitivity = t4 ? e2 ? "variant" : "case" : e2 ? "accent" : "base", this.locale = r2, this.collator = new Intl.Collator(this.locale ? this.locale : [], { sensitivity: this.sensitivity, usage: "search" });
            }
            compare(t4, e2) {
              return this.collator.compare(t4, e2);
            }
            resolvedLocale() {
              return new Intl.Collator(this.locale ? this.locale : []).resolvedOptions().locale;
            }
          }
          class Ht {
            constructor(t4, e2, r2, n2, i2) {
              this.text = t4, this.image = e2, this.scale = r2, this.fontStack = n2, this.textColor = i2;
            }
          }
          class Yt {
            constructor(t4) {
              this.sections = t4;
            }
            static fromString(t4) {
              return new Yt([new Ht(t4, null, null, null, null)]);
            }
            isEmpty() {
              return 0 === this.sections.length || !this.sections.some((t4) => 0 !== t4.text.length || t4.image && 0 !== t4.image.name.length);
            }
            static factory(t4) {
              return t4 instanceof Yt ? t4 : Yt.fromString(t4);
            }
            toString() {
              return 0 === this.sections.length ? "" : this.sections.map((t4) => t4.text).join("");
            }
          }
          class Jt {
            constructor(t4) {
              this.values = t4.slice();
            }
            static parse(t4) {
              if (t4 instanceof Jt) return t4;
              if ("number" == typeof t4) return new Jt([t4, t4, t4, t4]);
              if (Array.isArray(t4) && !(t4.length < 1 || t4.length > 4)) {
                for (const e2 of t4) if ("number" != typeof e2) return;
                switch (t4.length) {
                  case 1:
                    t4 = [t4[0], t4[0], t4[0], t4[0]];
                    break;
                  case 2:
                    t4 = [t4[0], t4[1], t4[0], t4[1]];
                    break;
                  case 3:
                    t4 = [t4[0], t4[1], t4[2], t4[1]];
                }
                return new Jt(t4);
              }
            }
            toString() {
              return JSON.stringify(this.values);
            }
          }
          const Wt = /* @__PURE__ */ new Set(["center", "left", "right", "top", "bottom", "top-left", "top-right", "bottom-left", "bottom-right"]);
          class Qt {
            constructor(t4) {
              this.values = t4.slice();
            }
            static parse(t4) {
              if (t4 instanceof Qt) return t4;
              if (Array.isArray(t4) && !(t4.length < 1) && t4.length % 2 == 0) {
                for (let e2 = 0; e2 < t4.length; e2 += 2) {
                  const r2 = t4[e2], n2 = t4[e2 + 1];
                  if ("string" != typeof r2 || !Wt.has(r2)) return;
                  if (!Array.isArray(n2) || 2 !== n2.length || "number" != typeof n2[0] || "number" != typeof n2[1]) return;
                }
                return new Qt(t4);
              }
            }
            toString() {
              return JSON.stringify(this.values);
            }
          }
          class te {
            constructor(t4) {
              this.name = t4.name, this.available = t4.available;
            }
            toString() {
              return this.name;
            }
            static fromString(t4) {
              return t4 ? new te({ name: t4, available: false }) : null;
            }
          }
          function ee(t4, e2, r2, n2) {
            return "number" == typeof t4 && t4 >= 0 && t4 <= 255 && "number" == typeof e2 && e2 >= 0 && e2 <= 255 && "number" == typeof r2 && r2 >= 0 && r2 <= 255 ? void 0 === n2 || "number" == typeof n2 && n2 >= 0 && n2 <= 1 ? null : `Invalid rgba value [${[t4, e2, r2, n2].join(", ")}]: 'a' must be between 0 and 1.` : `Invalid rgba value [${("number" == typeof n2 ? [t4, e2, r2, n2] : [t4, e2, r2]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`;
          }
          function re(t4) {
            if (null === t4 || "string" == typeof t4 || "boolean" == typeof t4 || "number" == typeof t4 || t4 instanceof Kt || t4 instanceof Xt || t4 instanceof Yt || t4 instanceof Jt || t4 instanceof Qt || t4 instanceof te) return true;
            if (Array.isArray(t4)) {
              for (const e2 of t4) if (!re(e2)) return false;
              return true;
            }
            if ("object" == typeof t4) {
              for (const e2 in t4) if (!re(t4[e2])) return false;
              return true;
            }
            return false;
          }
          function ne(t4) {
            if (null === t4) return lt;
            if ("string" == typeof t4) return ct;
            if ("boolean" == typeof t4) return ht;
            if ("number" == typeof t4) return ut;
            if (t4 instanceof Kt) return pt;
            if (t4 instanceof Xt) return yt;
            if (t4 instanceof Yt) return mt;
            if (t4 instanceof Jt) return gt;
            if (t4 instanceof Qt) return vt;
            if (t4 instanceof te) return xt;
            if (Array.isArray(t4)) {
              const e2 = t4.length;
              let r2;
              for (const e3 of t4) {
                const t5 = ne(e3);
                if (r2) {
                  if (r2 === t5) continue;
                  r2 = dt;
                  break;
                }
                r2 = t5;
              }
              return bt(r2 || dt, e2);
            }
            return ft;
          }
          function ie(t4) {
            const e2 = typeof t4;
            return null === t4 ? "" : "string" === e2 || "number" === e2 || "boolean" === e2 ? String(t4) : t4 instanceof Kt || t4 instanceof Yt || t4 instanceof Jt || t4 instanceof Qt || t4 instanceof te ? t4.toString() : JSON.stringify(t4);
          }
          class se {
            constructor(t4, e2) {
              this.type = t4, this.value = e2;
            }
            static parse(t4, e2) {
              if (2 !== t4.length) return e2.error(`'literal' expression requires exactly one argument, but found ${t4.length - 1} instead.`);
              if (!re(t4[1])) return e2.error("invalid value");
              const r2 = t4[1];
              let n2 = ne(r2);
              const i2 = e2.expectedType;
              return "array" !== n2.kind || 0 !== n2.N || !i2 || "array" !== i2.kind || "number" == typeof i2.N && 0 !== i2.N || (n2 = i2), new se(n2, r2);
            }
            evaluate() {
              return this.value;
            }
            eachChild() {
            }
            outputDefined() {
              return true;
            }
          }
          class ae {
            constructor(t4) {
              this.name = "ExpressionEvaluationError", this.message = t4;
            }
            toJSON() {
              return this.message;
            }
          }
          const oe = { string: ct, number: ut, boolean: ht, object: ft };
          class le {
            constructor(t4, e2) {
              this.type = t4, this.args = e2;
            }
            static parse(t4, e2) {
              if (t4.length < 2) return e2.error("Expected at least one argument.");
              let r2, n2 = 1;
              const i2 = t4[0];
              if ("array" === i2) {
                let i3, s3;
                if (t4.length > 2) {
                  const r3 = t4[1];
                  if ("string" != typeof r3 || !(r3 in oe) || "object" === r3) return e2.error('The item type argument of "array" must be one of string, number, boolean', 1);
                  i3 = oe[r3], n2++;
                } else i3 = dt;
                if (t4.length > 3) {
                  if (null !== t4[2] && ("number" != typeof t4[2] || t4[2] < 0 || t4[2] !== Math.floor(t4[2]))) return e2.error('The length argument to "array" must be a positive integer literal', 2);
                  s3 = t4[2], n2++;
                }
                r2 = bt(i3, s3);
              } else {
                if (!oe[i2]) throw new Error(`Types doesn't contain name = ${i2}`);
                r2 = oe[i2];
              }
              const s2 = [];
              for (; n2 < t4.length; n2++) {
                const r3 = e2.parse(t4[n2], n2, dt);
                if (!r3) return null;
                s2.push(r3);
              }
              return new le(r2, s2);
            }
            evaluate(t4) {
              for (let e2 = 0; e2 < this.args.length; e2++) {
                const r2 = this.args[e2].evaluate(t4);
                if (!At(this.type, ne(r2))) return r2;
                if (e2 === this.args.length - 1) throw new ae(`Expected value to be of type ${wt(this.type)}, but found ${wt(ne(r2))} instead.`);
              }
              throw new Error();
            }
            eachChild(t4) {
              this.args.forEach(t4);
            }
            outputDefined() {
              return this.args.every((t4) => t4.outputDefined());
            }
          }
          const ue = { "to-boolean": ht, "to-color": pt, "to-number": ut, "to-string": ct };
          class ce {
            constructor(t4, e2) {
              this.type = t4, this.args = e2;
            }
            static parse(t4, e2) {
              if (t4.length < 2) return e2.error("Expected at least one argument.");
              const r2 = t4[0];
              if (!ue[r2]) throw new Error(`Can't parse ${r2} as it is not part of the known types`);
              if (("to-boolean" === r2 || "to-string" === r2) && 2 !== t4.length) return e2.error("Expected one argument.");
              const n2 = ue[r2], i2 = [];
              for (let r3 = 1; r3 < t4.length; r3++) {
                const n3 = e2.parse(t4[r3], r3, dt);
                if (!n3) return null;
                i2.push(n3);
              }
              return new ce(n2, i2);
            }
            evaluate(t4) {
              switch (this.type.kind) {
                case "boolean":
                  return Boolean(this.args[0].evaluate(t4));
                case "color": {
                  let e2, r2;
                  for (const n2 of this.args) {
                    if (e2 = n2.evaluate(t4), r2 = null, e2 instanceof Kt) return e2;
                    if ("string" == typeof e2) {
                      const r3 = t4.parseColor(e2);
                      if (r3) return r3;
                    } else if (Array.isArray(e2) && (r2 = e2.length < 3 || e2.length > 4 ? `Invalid rbga value ${JSON.stringify(e2)}: expected an array containing either three or four numeric values.` : ee(e2[0], e2[1], e2[2], e2[3]), !r2)) return new Kt(e2[0] / 255, e2[1] / 255, e2[2] / 255, e2[3]);
                  }
                  throw new ae(r2 || `Could not parse color from value '${"string" == typeof e2 ? e2 : JSON.stringify(e2)}'`);
                }
                case "padding": {
                  let e2;
                  for (const r2 of this.args) {
                    e2 = r2.evaluate(t4);
                    const n2 = Jt.parse(e2);
                    if (n2) return n2;
                  }
                  throw new ae(`Could not parse padding from value '${"string" == typeof e2 ? e2 : JSON.stringify(e2)}'`);
                }
                case "variableAnchorOffsetCollection": {
                  let e2;
                  for (const r2 of this.args) {
                    e2 = r2.evaluate(t4);
                    const n2 = Qt.parse(e2);
                    if (n2) return n2;
                  }
                  throw new ae(`Could not parse variableAnchorOffsetCollection from value '${"string" == typeof e2 ? e2 : JSON.stringify(e2)}'`);
                }
                case "number": {
                  let e2 = null;
                  for (const r2 of this.args) {
                    if (e2 = r2.evaluate(t4), null === e2) return 0;
                    const n2 = Number(e2);
                    if (!isNaN(n2)) return n2;
                  }
                  throw new ae(`Could not convert ${JSON.stringify(e2)} to number.`);
                }
                case "formatted":
                  return Yt.fromString(ie(this.args[0].evaluate(t4)));
                case "resolvedImage":
                  return te.fromString(ie(this.args[0].evaluate(t4)));
                default:
                  return ie(this.args[0].evaluate(t4));
              }
            }
            eachChild(t4) {
              this.args.forEach(t4);
            }
            outputDefined() {
              return this.args.every((t4) => t4.outputDefined());
            }
          }
          const he = ["Unknown", "Point", "LineString", "Polygon"];
          class pe {
            constructor() {
              this.globals = null, this.feature = null, this.featureState = null, this.formattedSection = null, this._parseColorCache = {}, this.availableImages = null, this.canonical = null;
            }
            id() {
              return this.feature && "id" in this.feature ? this.feature.id : null;
            }
            geometryType() {
              return this.feature ? "number" == typeof this.feature.type ? he[this.feature.type] : this.feature.type : null;
            }
            geometry() {
              return this.feature && "geometry" in this.feature ? this.feature.geometry : null;
            }
            canonicalID() {
              return this.canonical;
            }
            properties() {
              return this.feature && this.feature.properties || {};
            }
            parseColor(t4) {
              let e2 = this._parseColorCache[t4];
              return e2 || (e2 = this._parseColorCache[t4] = Kt.parse(t4)), e2;
            }
          }
          class fe {
            constructor(t4, e2, r2 = [], n2, i2 = new ot(), s2 = []) {
              this.registry = t4, this.path = r2, this.key = r2.map((t5) => `[${t5}]`).join(""), this.scope = i2, this.errors = s2, this.expectedType = n2, this._isConstant = e2;
            }
            parse(t4, e2, r2, n2, i2 = {}) {
              return e2 ? this.concat(e2, r2, n2)._parse(t4, i2) : this._parse(t4, i2);
            }
            _parse(t4, e2) {
              function r2(t5, e3, r3) {
                return "assert" === r3 ? new le(e3, [t5]) : "coerce" === r3 ? new ce(e3, [t5]) : t5;
              }
              if (null !== t4 && "string" != typeof t4 && "boolean" != typeof t4 && "number" != typeof t4 || (t4 = ["literal", t4]), Array.isArray(t4)) {
                if (0 === t4.length) return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');
                const n2 = t4[0];
                if ("string" != typeof n2) return this.error(`Expression name must be a string, but found ${typeof n2} instead. If you wanted a literal array, use ["literal", [...]].`, 0), null;
                const i2 = this.registry[n2];
                if (i2) {
                  let n3 = i2.parse(t4, this);
                  if (!n3) return null;
                  if (this.expectedType) {
                    const t5 = this.expectedType, i3 = n3.type;
                    if ("string" !== t5.kind && "number" !== t5.kind && "boolean" !== t5.kind && "object" !== t5.kind && "array" !== t5.kind || "value" !== i3.kind) if ("color" !== t5.kind && "formatted" !== t5.kind && "resolvedImage" !== t5.kind || "value" !== i3.kind && "string" !== i3.kind) if ("padding" !== t5.kind || "value" !== i3.kind && "number" !== i3.kind && "array" !== i3.kind) if ("variableAnchorOffsetCollection" !== t5.kind || "value" !== i3.kind && "array" !== i3.kind) {
                      if (this.checkSubtype(t5, i3)) return null;
                    } else n3 = r2(n3, t5, e2.typeAnnotation || "coerce");
                    else n3 = r2(n3, t5, e2.typeAnnotation || "coerce");
                    else n3 = r2(n3, t5, e2.typeAnnotation || "coerce");
                    else n3 = r2(n3, t5, e2.typeAnnotation || "assert");
                  }
                  if (!(n3 instanceof se) && "resolvedImage" !== n3.type.kind && this._isConstant(n3)) {
                    const t5 = new pe();
                    try {
                      n3 = new se(n3.type, n3.evaluate(t5));
                    } catch (t6) {
                      return this.error(t6.message), null;
                    }
                  }
                  return n3;
                }
                return this.error(`Unknown expression "${n2}". If you wanted a literal array, use ["literal", [...]].`, 0);
              }
              return this.error(void 0 === t4 ? "'undefined' value invalid. Use null instead." : "object" == typeof t4 ? 'Bare objects invalid. Use ["literal", {...}] instead.' : `Expected an array, but found ${typeof t4} instead.`);
            }
            concat(t4, e2, r2) {
              const n2 = "number" == typeof t4 ? this.path.concat(t4) : this.path, i2 = r2 ? this.scope.concat(r2) : this.scope;
              return new fe(this.registry, this._isConstant, n2, e2 || null, i2, this.errors);
            }
            error(t4, ...e2) {
              const r2 = `${this.key}${e2.map((t5) => `[${t5}]`).join("")}`;
              this.errors.push(new at(r2, t4));
            }
            checkSubtype(t4, e2) {
              const r2 = At(t4, e2);
              return r2 && this.error(r2), r2;
            }
          }
          class de {
            constructor(t4, e2) {
              this.type = e2.type, this.bindings = [].concat(t4), this.result = e2;
            }
            evaluate(t4) {
              return this.result.evaluate(t4);
            }
            eachChild(t4) {
              for (const e2 of this.bindings) t4(e2[1]);
              t4(this.result);
            }
            static parse(t4, e2) {
              if (t4.length < 4) return e2.error(`Expected at least 3 arguments, but found ${t4.length - 1} instead.`);
              const r2 = [];
              for (let n3 = 1; n3 < t4.length - 1; n3 += 2) {
                const i2 = t4[n3];
                if ("string" != typeof i2) return e2.error(`Expected string, but found ${typeof i2} instead.`, n3);
                if (/[^a-zA-Z0-9_]/.test(i2)) return e2.error("Variable names must contain only alphanumeric characters or '_'.", n3);
                const s2 = e2.parse(t4[n3 + 1], n3 + 1);
                if (!s2) return null;
                r2.push([i2, s2]);
              }
              const n2 = e2.parse(t4[t4.length - 1], t4.length - 1, e2.expectedType, r2);
              return n2 ? new de(r2, n2) : null;
            }
            outputDefined() {
              return this.result.outputDefined();
            }
          }
          class ye {
            constructor(t4, e2) {
              this.type = e2.type, this.name = t4, this.boundExpression = e2;
            }
            static parse(t4, e2) {
              if (2 !== t4.length || "string" != typeof t4[1]) return e2.error("'var' expression requires exactly one string literal argument.");
              const r2 = t4[1];
              return e2.scope.has(r2) ? new ye(r2, e2.scope.get(r2)) : e2.error(`Unknown variable "${r2}". Make sure "${r2}" has been bound in an enclosing "let" expression before using it.`, 1);
            }
            evaluate(t4) {
              return this.boundExpression.evaluate(t4);
            }
            eachChild() {
            }
            outputDefined() {
              return false;
            }
          }
          class me {
            constructor(t4, e2, r2) {
              this.type = t4, this.index = e2, this.input = r2;
            }
            static parse(t4, e2) {
              if (3 !== t4.length) return e2.error(`Expected 2 arguments, but found ${t4.length - 1} instead.`);
              const r2 = e2.parse(t4[1], 1, ut), n2 = e2.parse(t4[2], 2, bt(e2.expectedType || dt));
              return r2 && n2 ? new me(n2.type.itemType, r2, n2) : null;
            }
            evaluate(t4) {
              const e2 = this.index.evaluate(t4), r2 = this.input.evaluate(t4);
              if (e2 < 0) throw new ae(`Array index out of bounds: ${e2} < 0.`);
              if (e2 >= r2.length) throw new ae(`Array index out of bounds: ${e2} > ${r2.length - 1}.`);
              if (e2 !== Math.floor(e2)) throw new ae(`Array index must be an integer, but found ${e2} instead.`);
              return r2[e2];
            }
            eachChild(t4) {
              t4(this.index), t4(this.input);
            }
            outputDefined() {
              return false;
            }
          }
          class ge {
            constructor(t4, e2) {
              this.type = ht, this.needle = t4, this.haystack = e2;
            }
            static parse(t4, e2) {
              if (3 !== t4.length) return e2.error(`Expected 2 arguments, but found ${t4.length - 1} instead.`);
              const r2 = e2.parse(t4[1], 1, dt), n2 = e2.parse(t4[2], 2, dt);
              return r2 && n2 ? St(r2.type, [ht, ct, ut, lt, dt]) ? new ge(r2, n2) : e2.error(`Expected first argument to be of type boolean, string, number or null, but found ${wt(r2.type)} instead`) : null;
            }
            evaluate(t4) {
              const e2 = this.needle.evaluate(t4), r2 = this.haystack.evaluate(t4);
              if (!r2) return false;
              if (!kt(e2, ["boolean", "string", "number", "null"])) throw new ae(`Expected first argument to be of type boolean, string, number or null, but found ${wt(ne(e2))} instead.`);
              if (!kt(r2, ["string", "array"])) throw new ae(`Expected second argument to be of type array or string, but found ${wt(ne(r2))} instead.`);
              return r2.indexOf(e2) >= 0;
            }
            eachChild(t4) {
              t4(this.needle), t4(this.haystack);
            }
            outputDefined() {
              return true;
            }
          }
          class xe {
            constructor(t4, e2, r2) {
              this.type = ut, this.needle = t4, this.haystack = e2, this.fromIndex = r2;
            }
            static parse(t4, e2) {
              if (t4.length <= 2 || t4.length >= 5) return e2.error(`Expected 3 or 4 arguments, but found ${t4.length - 1} instead.`);
              const r2 = e2.parse(t4[1], 1, dt), n2 = e2.parse(t4[2], 2, dt);
              if (!r2 || !n2) return null;
              if (!St(r2.type, [ht, ct, ut, lt, dt])) return e2.error(`Expected first argument to be of type boolean, string, number or null, but found ${wt(r2.type)} instead`);
              if (4 === t4.length) {
                const i2 = e2.parse(t4[3], 3, ut);
                return i2 ? new xe(r2, n2, i2) : null;
              }
              return new xe(r2, n2);
            }
            evaluate(t4) {
              const e2 = this.needle.evaluate(t4), r2 = this.haystack.evaluate(t4);
              if (!kt(e2, ["boolean", "string", "number", "null"])) throw new ae(`Expected first argument to be of type boolean, string, number or null, but found ${wt(ne(e2))} instead.`);
              let n2;
              if (this.fromIndex && (n2 = this.fromIndex.evaluate(t4)), kt(r2, ["string"])) {
                const t5 = r2.indexOf(e2, n2);
                return -1 === t5 ? -1 : [...r2.slice(0, t5)].length;
              }
              if (kt(r2, ["array"])) return r2.indexOf(e2, n2);
              throw new ae(`Expected second argument to be of type array or string, but found ${wt(ne(r2))} instead.`);
            }
            eachChild(t4) {
              t4(this.needle), t4(this.haystack), this.fromIndex && t4(this.fromIndex);
            }
            outputDefined() {
              return false;
            }
          }
          class ve {
            constructor(t4, e2, r2, n2, i2, s2) {
              this.inputType = t4, this.type = e2, this.input = r2, this.cases = n2, this.outputs = i2, this.otherwise = s2;
            }
            static parse(t4, e2) {
              if (t4.length < 5) return e2.error(`Expected at least 4 arguments, but found only ${t4.length - 1}.`);
              if (t4.length % 2 != 1) return e2.error("Expected an even number of arguments.");
              let r2, n2;
              e2.expectedType && "value" !== e2.expectedType.kind && (n2 = e2.expectedType);
              const i2 = {}, s2 = [];
              for (let a3 = 2; a3 < t4.length - 1; a3 += 2) {
                let o3 = t4[a3];
                const l2 = t4[a3 + 1];
                Array.isArray(o3) || (o3 = [o3]);
                const u2 = e2.concat(a3);
                if (0 === o3.length) return u2.error("Expected at least one branch label.");
                for (const t5 of o3) {
                  if ("number" != typeof t5 && "string" != typeof t5) return u2.error("Branch labels must be numbers or strings.");
                  if ("number" == typeof t5 && Math.abs(t5) > Number.MAX_SAFE_INTEGER) return u2.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);
                  if ("number" == typeof t5 && Math.floor(t5) !== t5) return u2.error("Numeric branch labels must be integer values.");
                  if (r2) {
                    if (u2.checkSubtype(r2, ne(t5))) return null;
                  } else r2 = ne(t5);
                  if (void 0 !== i2[String(t5)]) return u2.error("Branch labels must be unique.");
                  i2[String(t5)] = s2.length;
                }
                const c2 = e2.parse(l2, a3, n2);
                if (!c2) return null;
                n2 = n2 || c2.type, s2.push(c2);
              }
              const a2 = e2.parse(t4[1], 1, dt);
              if (!a2) return null;
              const o2 = e2.parse(t4[t4.length - 1], t4.length - 1, n2);
              return o2 ? "value" !== a2.type.kind && e2.concat(1).checkSubtype(r2, a2.type) ? null : new ve(r2, n2, a2, i2, s2, o2) : null;
            }
            evaluate(t4) {
              const e2 = this.input.evaluate(t4);
              return (ne(e2) === this.inputType && this.outputs[this.cases[e2]] || this.otherwise).evaluate(t4);
            }
            eachChild(t4) {
              t4(this.input), this.outputs.forEach(t4), t4(this.otherwise);
            }
            outputDefined() {
              return this.outputs.every((t4) => t4.outputDefined()) && this.otherwise.outputDefined();
            }
          }
          class be {
            constructor(t4, e2, r2) {
              this.type = t4, this.branches = e2, this.otherwise = r2;
            }
            static parse(t4, e2) {
              if (t4.length < 4) return e2.error(`Expected at least 3 arguments, but found only ${t4.length - 1}.`);
              if (t4.length % 2 != 0) return e2.error("Expected an odd number of arguments.");
              let r2;
              e2.expectedType && "value" !== e2.expectedType.kind && (r2 = e2.expectedType);
              const n2 = [];
              for (let i3 = 1; i3 < t4.length - 1; i3 += 2) {
                const s2 = e2.parse(t4[i3], i3, ht);
                if (!s2) return null;
                const a2 = e2.parse(t4[i3 + 1], i3 + 1, r2);
                if (!a2) return null;
                n2.push([s2, a2]), r2 = r2 || a2.type;
              }
              const i2 = e2.parse(t4[t4.length - 1], t4.length - 1, r2);
              if (!i2) return null;
              if (!r2) throw new Error("Can't infer output type");
              return new be(r2, n2, i2);
            }
            evaluate(t4) {
              for (const [e2, r2] of this.branches) if (e2.evaluate(t4)) return r2.evaluate(t4);
              return this.otherwise.evaluate(t4);
            }
            eachChild(t4) {
              for (const [e2, r2] of this.branches) t4(e2), t4(r2);
              t4(this.otherwise);
            }
            outputDefined() {
              return this.branches.every(([t4, e2]) => e2.outputDefined()) && this.otherwise.outputDefined();
            }
          }
          class we {
            constructor(t4, e2, r2, n2) {
              this.type = t4, this.input = e2, this.beginIndex = r2, this.endIndex = n2;
            }
            static parse(t4, e2) {
              if (t4.length <= 2 || t4.length >= 5) return e2.error(`Expected 3 or 4 arguments, but found ${t4.length - 1} instead.`);
              const r2 = e2.parse(t4[1], 1, dt), n2 = e2.parse(t4[2], 2, ut);
              if (!r2 || !n2) return null;
              if (!St(r2.type, [bt(dt), ct, dt])) return e2.error(`Expected first argument to be of type array or string, but found ${wt(r2.type)} instead`);
              if (4 === t4.length) {
                const i2 = e2.parse(t4[3], 3, ut);
                return i2 ? new we(r2.type, r2, n2, i2) : null;
              }
              return new we(r2.type, r2, n2);
            }
            evaluate(t4) {
              const e2 = this.input.evaluate(t4), r2 = this.beginIndex.evaluate(t4);
              let n2;
              if (this.endIndex && (n2 = this.endIndex.evaluate(t4)), kt(e2, ["string"])) return [...e2].slice(r2, n2).join("");
              if (kt(e2, ["array"])) return e2.slice(r2, n2);
              throw new ae(`Expected first argument to be of type array or string, but found ${wt(ne(e2))} instead.`);
            }
            eachChild(t4) {
              t4(this.input), t4(this.beginIndex), this.endIndex && t4(this.endIndex);
            }
            outputDefined() {
              return false;
            }
          }
          function _e(t4, e2) {
            const r2 = t4.length - 1;
            let n2, i2, s2 = 0, a2 = r2, o2 = 0;
            for (; s2 <= a2; ) if (o2 = Math.floor((s2 + a2) / 2), n2 = t4[o2], i2 = t4[o2 + 1], n2 <= e2) {
              if (o2 === r2 || e2 < i2) return o2;
              s2 = o2 + 1;
            } else {
              if (!(n2 > e2)) throw new ae("Input is not a number.");
              a2 = o2 - 1;
            }
            return 0;
          }
          class Ae {
            constructor(t4, e2, r2) {
              this.type = t4, this.input = e2, this.labels = [], this.outputs = [];
              for (const [t5, e3] of r2) this.labels.push(t5), this.outputs.push(e3);
            }
            static parse(t4, e2) {
              if (t4.length - 1 < 4) return e2.error(`Expected at least 4 arguments, but found only ${t4.length - 1}.`);
              if ((t4.length - 1) % 2 != 0) return e2.error("Expected an even number of arguments.");
              const r2 = e2.parse(t4[1], 1, ut);
              if (!r2) return null;
              const n2 = [];
              let i2 = null;
              e2.expectedType && "value" !== e2.expectedType.kind && (i2 = e2.expectedType);
              for (let r3 = 1; r3 < t4.length; r3 += 2) {
                const s2 = 1 === r3 ? -1 / 0 : t4[r3], a2 = t4[r3 + 1], o2 = r3, l2 = r3 + 1;
                if ("number" != typeof s2) return e2.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', o2);
                if (n2.length && n2[n2.length - 1][0] >= s2) return e2.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', o2);
                const u2 = e2.parse(a2, l2, i2);
                if (!u2) return null;
                i2 = i2 || u2.type, n2.push([s2, u2]);
              }
              return new Ae(i2, r2, n2);
            }
            evaluate(t4) {
              const e2 = this.labels, r2 = this.outputs;
              if (1 === e2.length) return r2[0].evaluate(t4);
              const n2 = this.input.evaluate(t4);
              if (n2 <= e2[0]) return r2[0].evaluate(t4);
              const i2 = e2.length;
              return n2 >= e2[i2 - 1] ? r2[i2 - 1].evaluate(t4) : r2[_e(e2, n2)].evaluate(t4);
            }
            eachChild(t4) {
              t4(this.input);
              for (const e2 of this.outputs) t4(e2);
            }
            outputDefined() {
              return this.outputs.every((t4) => t4.outputDefined());
            }
          }
          function Se(t4) {
            return t4 && t4.__esModule && Object.prototype.hasOwnProperty.call(t4, "default") ? t4.default : t4;
          }
          var ke = Me;
          function Me(t4, e2, r2, n2) {
            this.cx = 3 * t4, this.bx = 3 * (r2 - t4) - this.cx, this.ax = 1 - this.cx - this.bx, this.cy = 3 * e2, this.by = 3 * (n2 - e2) - this.cy, this.ay = 1 - this.cy - this.by, this.p1x = t4, this.p1y = e2, this.p2x = r2, this.p2y = n2;
          }
          Me.prototype = { sampleCurveX: function(t4) {
            return ((this.ax * t4 + this.bx) * t4 + this.cx) * t4;
          }, sampleCurveY: function(t4) {
            return ((this.ay * t4 + this.by) * t4 + this.cy) * t4;
          }, sampleCurveDerivativeX: function(t4) {
            return (3 * this.ax * t4 + 2 * this.bx) * t4 + this.cx;
          }, solveCurveX: function(t4, e2) {
            if (void 0 === e2 && (e2 = 1e-6), t4 < 0) return 0;
            if (t4 > 1) return 1;
            for (var r2 = t4, n2 = 0; n2 < 8; n2++) {
              var i2 = this.sampleCurveX(r2) - t4;
              if (Math.abs(i2) < e2) return r2;
              var s2 = this.sampleCurveDerivativeX(r2);
              if (Math.abs(s2) < 1e-6) break;
              r2 -= i2 / s2;
            }
            var a2 = 0, o2 = 1;
            for (r2 = t4, n2 = 0; n2 < 20 && (i2 = this.sampleCurveX(r2), !(Math.abs(i2 - t4) < e2)); n2++) t4 > i2 ? a2 = r2 : o2 = r2, r2 = 0.5 * (o2 - a2) + a2;
            return r2;
          }, solve: function(t4, e2) {
            return this.sampleCurveY(this.solveCurveX(t4, e2));
          } };
          var Ie = Se(ke);
          function ze(t4, e2, r2) {
            return t4 + r2 * (e2 - t4);
          }
          function Pe(t4, e2, r2) {
            return t4.map((t5, n2) => ze(t5, e2[n2], r2));
          }
          const Ce = { number: ze, color: function(t4, e2, r2, n2 = "rgb") {
            switch (n2) {
              case "rgb": {
                const [n3, i2, s2, a2] = Pe(t4.rgb, e2.rgb, r2);
                return new Kt(n3, i2, s2, a2, false);
              }
              case "hcl": {
                const [n3, i2, s2, a2] = t4.hcl, [o2, l2, u2, c2] = e2.hcl;
                let h2, p2;
                if (isNaN(n3) || isNaN(o2)) isNaN(n3) ? isNaN(o2) ? h2 = NaN : (h2 = o2, 1 !== s2 && 0 !== s2 || (p2 = l2)) : (h2 = n3, 1 !== u2 && 0 !== u2 || (p2 = i2));
                else {
                  let t5 = o2 - n3;
                  o2 > n3 && t5 > 180 ? t5 -= 360 : o2 < n3 && n3 - o2 > 180 && (t5 += 360), h2 = n3 + r2 * t5;
                }
                const [f2, d2, y2, m2] = function([t5, e3, r3, n4]) {
                  return t5 = isNaN(t5) ? 0 : t5 * Et, Ot([r3, Math.cos(t5) * e3, Math.sin(t5) * e3, n4]);
                }([h2, null != p2 ? p2 : ze(i2, l2, r2), ze(s2, u2, r2), ze(a2, c2, r2)]);
                return new Kt(f2, d2, y2, m2, false);
              }
              case "lab": {
                const [n3, i2, s2, a2] = Ot(Pe(t4.lab, e2.lab, r2));
                return new Kt(n3, i2, s2, a2, false);
              }
            }
          }, array: Pe, padding: function(t4, e2, r2) {
            return new Jt(Pe(t4.values, e2.values, r2));
          }, variableAnchorOffsetCollection: function(t4, e2, r2) {
            const n2 = t4.values, i2 = e2.values;
            if (n2.length !== i2.length) throw new ae(`Cannot interpolate values of different length. from: ${t4.toString()}, to: ${e2.toString()}`);
            const s2 = [];
            for (let t5 = 0; t5 < n2.length; t5 += 2) {
              if (n2[t5] !== i2[t5]) throw new ae(`Cannot interpolate values containing mismatched anchors. from[${t5}]: ${n2[t5]}, to[${t5}]: ${i2[t5]}`);
              s2.push(n2[t5]);
              const [e3, a2] = n2[t5 + 1], [o2, l2] = i2[t5 + 1];
              s2.push([ze(e3, o2, r2), ze(a2, l2, r2)]);
            }
            return new Qt(s2);
          } };
          class Be {
            constructor(t4, e2, r2, n2, i2) {
              this.type = t4, this.operator = e2, this.interpolation = r2, this.input = n2, this.labels = [], this.outputs = [];
              for (const [t5, e3] of i2) this.labels.push(t5), this.outputs.push(e3);
            }
            static interpolationFactor(t4, e2, r2, n2) {
              let i2 = 0;
              if ("exponential" === t4.name) i2 = Ve(e2, t4.base, r2, n2);
              else if ("linear" === t4.name) i2 = Ve(e2, 1, r2, n2);
              else if ("cubic-bezier" === t4.name) {
                const s2 = t4.controlPoints;
                i2 = new Ie(s2[0], s2[1], s2[2], s2[3]).solve(Ve(e2, 1, r2, n2));
              }
              return i2;
            }
            static parse(t4, e2) {
              let [r2, n2, i2, ...s2] = t4;
              if (!Array.isArray(n2) || 0 === n2.length) return e2.error("Expected an interpolation type expression.", 1);
              if ("linear" === n2[0]) n2 = { name: "linear" };
              else if ("exponential" === n2[0]) {
                const t5 = n2[1];
                if ("number" != typeof t5) return e2.error("Exponential interpolation requires a numeric base.", 1, 1);
                n2 = { name: "exponential", base: t5 };
              } else {
                if ("cubic-bezier" !== n2[0]) return e2.error(`Unknown interpolation type ${String(n2[0])}`, 1, 0);
                {
                  const t5 = n2.slice(1);
                  if (4 !== t5.length || t5.some((t6) => "number" != typeof t6 || t6 < 0 || t6 > 1)) return e2.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.", 1);
                  n2 = { name: "cubic-bezier", controlPoints: t5 };
                }
              }
              if (t4.length - 1 < 4) return e2.error(`Expected at least 4 arguments, but found only ${t4.length - 1}.`);
              if ((t4.length - 1) % 2 != 0) return e2.error("Expected an even number of arguments.");
              if (i2 = e2.parse(i2, 2, ut), !i2) return null;
              const a2 = [];
              let o2 = null;
              "interpolate-hcl" === r2 || "interpolate-lab" === r2 ? o2 = pt : e2.expectedType && "value" !== e2.expectedType.kind && (o2 = e2.expectedType);
              for (let t5 = 0; t5 < s2.length; t5 += 2) {
                const r3 = s2[t5], n3 = s2[t5 + 1], i3 = t5 + 3, l2 = t5 + 4;
                if ("number" != typeof r3) return e2.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', i3);
                if (a2.length && a2[a2.length - 1][0] >= r3) return e2.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', i3);
                const u2 = e2.parse(n3, l2, o2);
                if (!u2) return null;
                o2 = o2 || u2.type, a2.push([r3, u2]);
              }
              return Mt(o2, ut) || Mt(o2, pt) || Mt(o2, gt) || Mt(o2, vt) || Mt(o2, bt(ut)) ? new Be(o2, r2, n2, i2, a2) : e2.error(`Type ${wt(o2)} is not interpolatable.`);
            }
            evaluate(t4) {
              const e2 = this.labels, r2 = this.outputs;
              if (1 === e2.length) return r2[0].evaluate(t4);
              const n2 = this.input.evaluate(t4);
              if (n2 <= e2[0]) return r2[0].evaluate(t4);
              const i2 = e2.length;
              if (n2 >= e2[i2 - 1]) return r2[i2 - 1].evaluate(t4);
              const s2 = _e(e2, n2), a2 = Be.interpolationFactor(this.interpolation, n2, e2[s2], e2[s2 + 1]), o2 = r2[s2].evaluate(t4), l2 = r2[s2 + 1].evaluate(t4);
              switch (this.operator) {
                case "interpolate":
                  return Ce[this.type.kind](o2, l2, a2);
                case "interpolate-hcl":
                  return Ce.color(o2, l2, a2, "hcl");
                case "interpolate-lab":
                  return Ce.color(o2, l2, a2, "lab");
              }
            }
            eachChild(t4) {
              t4(this.input);
              for (const e2 of this.outputs) t4(e2);
            }
            outputDefined() {
              return this.outputs.every((t4) => t4.outputDefined());
            }
          }
          function Ve(t4, e2, r2, n2) {
            const i2 = n2 - r2, s2 = t4 - r2;
            return 0 === i2 ? 0 : 1 === e2 ? s2 / i2 : (Math.pow(e2, s2) - 1) / (Math.pow(e2, i2) - 1);
          }
          class Ee {
            constructor(t4, e2) {
              this.type = t4, this.args = e2;
            }
            static parse(t4, e2) {
              if (t4.length < 2) return e2.error("Expectected at least one argument.");
              let r2 = null;
              const n2 = e2.expectedType;
              n2 && "value" !== n2.kind && (r2 = n2);
              const i2 = [];
              for (const n3 of t4.slice(1)) {
                const t5 = e2.parse(n3, 1 + i2.length, r2, void 0, { typeAnnotation: "omit" });
                if (!t5) return null;
                r2 = r2 || t5.type, i2.push(t5);
              }
              if (!r2) throw new Error("No output type");
              const s2 = n2 && i2.some((t5) => At(n2, t5.type));
              return new Ee(s2 ? dt : r2, i2);
            }
            evaluate(t4) {
              let e2, r2 = null, n2 = 0;
              for (const i2 of this.args) if (n2++, r2 = i2.evaluate(t4), r2 && r2 instanceof te && !r2.available && (e2 || (e2 = r2.name), r2 = null, n2 === this.args.length && (r2 = e2)), null !== r2) break;
              return r2;
            }
            eachChild(t4) {
              this.args.forEach(t4);
            }
            outputDefined() {
              return this.args.every((t4) => t4.outputDefined());
            }
          }
          function Fe(t4, e2) {
            return "==" === t4 || "!=" === t4 ? "boolean" === e2.kind || "string" === e2.kind || "number" === e2.kind || "null" === e2.kind || "value" === e2.kind : "string" === e2.kind || "number" === e2.kind || "value" === e2.kind;
          }
          function Te(t4, e2, r2, n2) {
            return 0 === n2.compare(e2, r2);
          }
          function $e(t4, e2, r2) {
            const n2 = "==" !== t4 && "!=" !== t4;
            return class i2 {
              constructor(t5, e3, r3) {
                this.type = ht, this.lhs = t5, this.rhs = e3, this.collator = r3, this.hasUntypedArgument = "value" === t5.type.kind || "value" === e3.type.kind;
              }
              static parse(t5, e3) {
                if (3 !== t5.length && 4 !== t5.length) return e3.error("Expected two or three arguments.");
                const r3 = t5[0];
                let s2 = e3.parse(t5[1], 1, dt);
                if (!s2) return null;
                if (!Fe(r3, s2.type)) return e3.concat(1).error(`"${r3}" comparisons are not supported for type '${wt(s2.type)}'.`);
                let a2 = e3.parse(t5[2], 2, dt);
                if (!a2) return null;
                if (!Fe(r3, a2.type)) return e3.concat(2).error(`"${r3}" comparisons are not supported for type '${wt(a2.type)}'.`);
                if (s2.type.kind !== a2.type.kind && "value" !== s2.type.kind && "value" !== a2.type.kind) return e3.error(`Cannot compare types '${wt(s2.type)}' and '${wt(a2.type)}'.`);
                n2 && ("value" === s2.type.kind && "value" !== a2.type.kind ? s2 = new le(a2.type, [s2]) : "value" !== s2.type.kind && "value" === a2.type.kind && (a2 = new le(s2.type, [a2])));
                let o2 = null;
                if (4 === t5.length) {
                  if ("string" !== s2.type.kind && "string" !== a2.type.kind && "value" !== s2.type.kind && "value" !== a2.type.kind) return e3.error("Cannot use collator to compare non-string types.");
                  if (o2 = e3.parse(t5[3], 3, yt), !o2) return null;
                }
                return new i2(s2, a2, o2);
              }
              evaluate(i3) {
                const s2 = this.lhs.evaluate(i3), a2 = this.rhs.evaluate(i3);
                if (n2 && this.hasUntypedArgument) {
                  const e3 = ne(s2), r3 = ne(a2);
                  if (e3.kind !== r3.kind || "string" !== e3.kind && "number" !== e3.kind) throw new ae(`Expected arguments for "${t4}" to be (string, string) or (number, number), but found (${e3.kind}, ${r3.kind}) instead.`);
                }
                if (this.collator && !n2 && this.hasUntypedArgument) {
                  const t5 = ne(s2), r3 = ne(a2);
                  if ("string" !== t5.kind || "string" !== r3.kind) return e2(i3, s2, a2);
                }
                return this.collator ? r2(i3, s2, a2, this.collator.evaluate(i3)) : e2(i3, s2, a2);
              }
              eachChild(t5) {
                t5(this.lhs), t5(this.rhs), this.collator && t5(this.collator);
              }
              outputDefined() {
                return true;
              }
            };
          }
          const Le = $e("==", function(t4, e2, r2) {
            return e2 === r2;
          }, Te), De = $e("!=", function(t4, e2, r2) {
            return e2 !== r2;
          }, function(t4, e2, r2, n2) {
            return !Te(0, e2, r2, n2);
          }), Oe = $e("<", function(t4, e2, r2) {
            return e2 < r2;
          }, function(t4, e2, r2, n2) {
            return n2.compare(e2, r2) < 0;
          }), je = $e(">", function(t4, e2, r2) {
            return e2 > r2;
          }, function(t4, e2, r2, n2) {
            return n2.compare(e2, r2) > 0;
          }), Re = $e("<=", function(t4, e2, r2) {
            return e2 <= r2;
          }, function(t4, e2, r2, n2) {
            return n2.compare(e2, r2) <= 0;
          }), Ue = $e(">=", function(t4, e2, r2) {
            return e2 >= r2;
          }, function(t4, e2, r2, n2) {
            return n2.compare(e2, r2) >= 0;
          });
          class qe {
            constructor(t4, e2, r2) {
              this.type = yt, this.locale = r2, this.caseSensitive = t4, this.diacriticSensitive = e2;
            }
            static parse(t4, e2) {
              if (2 !== t4.length) return e2.error("Expected one argument.");
              const r2 = t4[1];
              if ("object" != typeof r2 || Array.isArray(r2)) return e2.error("Collator options argument must be an object.");
              const n2 = e2.parse(void 0 !== r2["case-sensitive"] && r2["case-sensitive"], 1, ht);
              if (!n2) return null;
              const i2 = e2.parse(void 0 !== r2["diacritic-sensitive"] && r2["diacritic-sensitive"], 1, ht);
              if (!i2) return null;
              let s2 = null;
              return r2.locale && (s2 = e2.parse(r2.locale, 1, ct), !s2) ? null : new qe(n2, i2, s2);
            }
            evaluate(t4) {
              return new Xt(this.caseSensitive.evaluate(t4), this.diacriticSensitive.evaluate(t4), this.locale ? this.locale.evaluate(t4) : null);
            }
            eachChild(t4) {
              t4(this.caseSensitive), t4(this.diacriticSensitive), this.locale && t4(this.locale);
            }
            outputDefined() {
              return false;
            }
          }
          class Ne {
            constructor(t4, e2, r2, n2, i2) {
              this.type = ct, this.number = t4, this.locale = e2, this.currency = r2, this.minFractionDigits = n2, this.maxFractionDigits = i2;
            }
            static parse(t4, e2) {
              if (3 !== t4.length) return e2.error("Expected two arguments.");
              const r2 = e2.parse(t4[1], 1, ut);
              if (!r2) return null;
              const n2 = t4[2];
              if ("object" != typeof n2 || Array.isArray(n2)) return e2.error("NumberFormat options argument must be an object.");
              let i2 = null;
              if (n2.locale && (i2 = e2.parse(n2.locale, 1, ct), !i2)) return null;
              let s2 = null;
              if (n2.currency && (s2 = e2.parse(n2.currency, 1, ct), !s2)) return null;
              let a2 = null;
              if (n2["min-fraction-digits"] && (a2 = e2.parse(n2["min-fraction-digits"], 1, ut), !a2)) return null;
              let o2 = null;
              return n2["max-fraction-digits"] && (o2 = e2.parse(n2["max-fraction-digits"], 1, ut), !o2) ? null : new Ne(r2, i2, s2, a2, o2);
            }
            evaluate(t4) {
              return new Intl.NumberFormat(this.locale ? this.locale.evaluate(t4) : [], { style: this.currency ? "currency" : "decimal", currency: this.currency ? this.currency.evaluate(t4) : void 0, minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(t4) : void 0, maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(t4) : void 0 }).format(this.number.evaluate(t4));
            }
            eachChild(t4) {
              t4(this.number), this.locale && t4(this.locale), this.currency && t4(this.currency), this.minFractionDigits && t4(this.minFractionDigits), this.maxFractionDigits && t4(this.maxFractionDigits);
            }
            outputDefined() {
              return false;
            }
          }
          class Ze {
            constructor(t4) {
              this.type = mt, this.sections = t4;
            }
            static parse(t4, e2) {
              if (t4.length < 2) return e2.error("Expected at least one argument.");
              const r2 = t4[1];
              if (!Array.isArray(r2) && "object" == typeof r2) return e2.error("First argument must be an image or text section.");
              const n2 = [];
              let i2 = false;
              for (let r3 = 1; r3 <= t4.length - 1; ++r3) {
                const s2 = t4[r3];
                if (i2 && "object" == typeof s2 && !Array.isArray(s2)) {
                  i2 = false;
                  let t5 = null;
                  if (s2["font-scale"] && (t5 = e2.parse(s2["font-scale"], 1, ut), !t5)) return null;
                  let r4 = null;
                  if (s2["text-font"] && (r4 = e2.parse(s2["text-font"], 1, bt(ct)), !r4)) return null;
                  let a2 = null;
                  if (s2["text-color"] && (a2 = e2.parse(s2["text-color"], 1, pt), !a2)) return null;
                  const o2 = n2[n2.length - 1];
                  o2.scale = t5, o2.font = r4, o2.textColor = a2;
                } else {
                  const s3 = e2.parse(t4[r3], 1, dt);
                  if (!s3) return null;
                  const a2 = s3.type.kind;
                  if ("string" !== a2 && "value" !== a2 && "null" !== a2 && "resolvedImage" !== a2) return e2.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");
                  i2 = true, n2.push({ content: s3, scale: null, font: null, textColor: null });
                }
              }
              return new Ze(n2);
            }
            evaluate(t4) {
              return new Yt(this.sections.map((e2) => {
                const r2 = e2.content.evaluate(t4);
                return ne(r2) === xt ? new Ht("", r2, null, null, null) : new Ht(ie(r2), null, e2.scale ? e2.scale.evaluate(t4) : null, e2.font ? e2.font.evaluate(t4).join(",") : null, e2.textColor ? e2.textColor.evaluate(t4) : null);
              }));
            }
            eachChild(t4) {
              for (const e2 of this.sections) t4(e2.content), e2.scale && t4(e2.scale), e2.font && t4(e2.font), e2.textColor && t4(e2.textColor);
            }
            outputDefined() {
              return false;
            }
          }
          class Ge {
            constructor(t4) {
              this.type = xt, this.input = t4;
            }
            static parse(t4, e2) {
              if (2 !== t4.length) return e2.error("Expected two arguments.");
              const r2 = e2.parse(t4[1], 1, ct);
              return r2 ? new Ge(r2) : e2.error("No image name provided.");
            }
            evaluate(t4) {
              const e2 = this.input.evaluate(t4), r2 = te.fromString(e2);
              return r2 && t4.availableImages && (r2.available = t4.availableImages.indexOf(e2) > -1), r2;
            }
            eachChild(t4) {
              t4(this.input);
            }
            outputDefined() {
              return false;
            }
          }
          class Ke {
            constructor(t4) {
              this.type = ut, this.input = t4;
            }
            static parse(t4, e2) {
              if (2 !== t4.length) return e2.error(`Expected 1 argument, but found ${t4.length - 1} instead.`);
              const r2 = e2.parse(t4[1], 1);
              return r2 ? "array" !== r2.type.kind && "string" !== r2.type.kind && "value" !== r2.type.kind ? e2.error(`Expected argument of type string or array, but found ${wt(r2.type)} instead.`) : new Ke(r2) : null;
            }
            evaluate(t4) {
              const e2 = this.input.evaluate(t4);
              if ("string" == typeof e2) return [...e2].length;
              if (Array.isArray(e2)) return e2.length;
              throw new ae(`Expected value to be of type string or array, but found ${wt(ne(e2))} instead.`);
            }
            eachChild(t4) {
              t4(this.input);
            }
            outputDefined() {
              return false;
            }
          }
          const Xe = 8192;
          function He(t4, e2) {
            const r2 = (180 + t4[0]) / 360, n2 = (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + t4[1] * Math.PI / 360))) / 360, i2 = Math.pow(2, e2.z);
            return [Math.round(r2 * i2 * Xe), Math.round(n2 * i2 * Xe)];
          }
          function Ye(t4, e2) {
            const r2 = Math.pow(2, e2.z);
            return [(i2 = (t4[0] / Xe + e2.x) / r2, 360 * i2 - 180), (n2 = (t4[1] / Xe + e2.y) / r2, 360 / Math.PI * Math.atan(Math.exp((180 - 360 * n2) * Math.PI / 180)) - 90)];
            var n2, i2;
          }
          function Je(t4, e2) {
            t4[0] = Math.min(t4[0], e2[0]), t4[1] = Math.min(t4[1], e2[1]), t4[2] = Math.max(t4[2], e2[0]), t4[3] = Math.max(t4[3], e2[1]);
          }
          function We(t4, e2) {
            return !(t4[0] <= e2[0] || t4[2] >= e2[2] || t4[1] <= e2[1] || t4[3] >= e2[3]);
          }
          function Qe(t4, e2, r2) {
            const n2 = t4[0] - e2[0], i2 = t4[1] - e2[1], s2 = t4[0] - r2[0], a2 = t4[1] - r2[1];
            return n2 * a2 - s2 * i2 == 0 && n2 * s2 <= 0 && i2 * a2 <= 0;
          }
          function tr(t4, e2, r2, n2) {
            return 0 != (i2 = [n2[0] - r2[0], n2[1] - r2[1]])[0] * (s2 = [e2[0] - t4[0], e2[1] - t4[1]])[1] - i2[1] * s2[0] && !(!ar(t4, e2, r2, n2) || !ar(r2, n2, t4, e2));
            var i2, s2;
          }
          function er(t4, e2, r2) {
            for (const n2 of r2) for (let r3 = 0; r3 < n2.length - 1; ++r3) if (tr(t4, e2, n2[r3], n2[r3 + 1])) return true;
            return false;
          }
          function rr(t4, e2, r2 = false) {
            let n2 = false;
            for (const o2 of e2) for (let e3 = 0; e3 < o2.length - 1; e3++) {
              if (Qe(t4, o2[e3], o2[e3 + 1])) return r2;
              (s2 = o2[e3])[1] > (i2 = t4)[1] != (a2 = o2[e3 + 1])[1] > i2[1] && i2[0] < (a2[0] - s2[0]) * (i2[1] - s2[1]) / (a2[1] - s2[1]) + s2[0] && (n2 = !n2);
            }
            var i2, s2, a2;
            return n2;
          }
          function nr(t4, e2) {
            for (const r2 of e2) if (rr(t4, r2)) return true;
            return false;
          }
          function ir(t4, e2) {
            for (const r2 of t4) if (!rr(r2, e2)) return false;
            for (let r2 = 0; r2 < t4.length - 1; ++r2) if (er(t4[r2], t4[r2 + 1], e2)) return false;
            return true;
          }
          function sr(t4, e2) {
            for (const r2 of e2) if (ir(t4, r2)) return true;
            return false;
          }
          function ar(t4, e2, r2, n2) {
            const i2 = n2[0] - r2[0], s2 = n2[1] - r2[1], a2 = (t4[0] - r2[0]) * s2 - i2 * (t4[1] - r2[1]), o2 = (e2[0] - r2[0]) * s2 - i2 * (e2[1] - r2[1]);
            return a2 > 0 && o2 < 0 || a2 < 0 && o2 > 0;
          }
          function or(t4, e2, r2) {
            const n2 = [];
            for (let i2 = 0; i2 < t4.length; i2++) {
              const s2 = [];
              for (let n3 = 0; n3 < t4[i2].length; n3++) {
                const a2 = He(t4[i2][n3], r2);
                Je(e2, a2), s2.push(a2);
              }
              n2.push(s2);
            }
            return n2;
          }
          function lr(t4, e2, r2) {
            const n2 = [];
            for (let i2 = 0; i2 < t4.length; i2++) {
              const s2 = or(t4[i2], e2, r2);
              n2.push(s2);
            }
            return n2;
          }
          function ur(t4, e2, r2, n2) {
            if (t4[0] < r2[0] || t4[0] > r2[2]) {
              const e3 = 0.5 * n2;
              let i2 = t4[0] - r2[0] > e3 ? -n2 : r2[0] - t4[0] > e3 ? n2 : 0;
              0 === i2 && (i2 = t4[0] - r2[2] > e3 ? -n2 : r2[2] - t4[0] > e3 ? n2 : 0), t4[0] += i2;
            }
            Je(e2, t4);
          }
          function cr(t4, e2, r2, n2) {
            const i2 = Math.pow(2, n2.z) * Xe, s2 = [n2.x * Xe, n2.y * Xe], a2 = [];
            for (const n3 of t4) for (const t5 of n3) {
              const n4 = [t5.x + s2[0], t5.y + s2[1]];
              ur(n4, e2, r2, i2), a2.push(n4);
            }
            return a2;
          }
          function hr(t4, e2, r2, n2) {
            const i2 = Math.pow(2, n2.z) * Xe, s2 = [n2.x * Xe, n2.y * Xe], a2 = [];
            for (const r3 of t4) {
              const t5 = [];
              for (const n3 of r3) {
                const r4 = [n3.x + s2[0], n3.y + s2[1]];
                Je(e2, r4), t5.push(r4);
              }
              a2.push(t5);
            }
            if (e2[2] - e2[0] <= i2 / 2) {
              (o2 = e2)[0] = o2[1] = 1 / 0, o2[2] = o2[3] = -1 / 0;
              for (const t5 of a2) for (const n3 of t5) ur(n3, e2, r2, i2);
            }
            var o2;
            return a2;
          }
          class pr {
            constructor(t4, e2) {
              this.type = ht, this.geojson = t4, this.geometries = e2;
            }
            static parse(t4, e2) {
              if (2 !== t4.length) return e2.error(`'within' expression requires exactly one argument, but found ${t4.length - 1} instead.`);
              if (re(t4[1])) {
                const e3 = t4[1];
                if ("FeatureCollection" === e3.type) {
                  const t5 = [];
                  for (const r2 of e3.features) {
                    const { type: e4, coordinates: n2 } = r2.geometry;
                    "Polygon" === e4 && t5.push(n2), "MultiPolygon" === e4 && t5.push(...n2);
                  }
                  if (t5.length) return new pr(e3, { type: "MultiPolygon", coordinates: t5 });
                } else if ("Feature" === e3.type) {
                  const t5 = e3.geometry.type;
                  if ("Polygon" === t5 || "MultiPolygon" === t5) return new pr(e3, e3.geometry);
                } else if ("Polygon" === e3.type || "MultiPolygon" === e3.type) return new pr(e3, e3);
              }
              return e2.error("'within' expression requires valid geojson object that contains polygon geometry type.");
            }
            evaluate(t4) {
              if (null != t4.geometry() && null != t4.canonicalID()) {
                if ("Point" === t4.geometryType()) return function(t5, e2) {
                  const r2 = [1 / 0, 1 / 0, -1 / 0, -1 / 0], n2 = [1 / 0, 1 / 0, -1 / 0, -1 / 0], i2 = t5.canonicalID();
                  if ("Polygon" === e2.type) {
                    const s2 = or(e2.coordinates, n2, i2), a2 = cr(t5.geometry(), r2, n2, i2);
                    if (!We(r2, n2)) return false;
                    for (const t6 of a2) if (!rr(t6, s2)) return false;
                  }
                  if ("MultiPolygon" === e2.type) {
                    const s2 = lr(e2.coordinates, n2, i2), a2 = cr(t5.geometry(), r2, n2, i2);
                    if (!We(r2, n2)) return false;
                    for (const t6 of a2) if (!nr(t6, s2)) return false;
                  }
                  return true;
                }(t4, this.geometries);
                if ("LineString" === t4.geometryType()) return function(t5, e2) {
                  const r2 = [1 / 0, 1 / 0, -1 / 0, -1 / 0], n2 = [1 / 0, 1 / 0, -1 / 0, -1 / 0], i2 = t5.canonicalID();
                  if ("Polygon" === e2.type) {
                    const s2 = or(e2.coordinates, n2, i2), a2 = hr(t5.geometry(), r2, n2, i2);
                    if (!We(r2, n2)) return false;
                    for (const t6 of a2) if (!ir(t6, s2)) return false;
                  }
                  if ("MultiPolygon" === e2.type) {
                    const s2 = lr(e2.coordinates, n2, i2), a2 = hr(t5.geometry(), r2, n2, i2);
                    if (!We(r2, n2)) return false;
                    for (const t6 of a2) if (!sr(t6, s2)) return false;
                  }
                  return true;
                }(t4, this.geometries);
              }
              return false;
            }
            eachChild() {
            }
            outputDefined() {
              return true;
            }
          }
          let fr = class {
            constructor(t4 = [], e2 = (t5, e3) => t5 < e3 ? -1 : t5 > e3 ? 1 : 0) {
              if (this.data = t4, this.length = this.data.length, this.compare = e2, this.length > 0) for (let t5 = (this.length >> 1) - 1; t5 >= 0; t5--) this._down(t5);
            }
            push(t4) {
              this.data.push(t4), this._up(this.length++);
            }
            pop() {
              if (0 === this.length) return;
              const t4 = this.data[0], e2 = this.data.pop();
              return --this.length > 0 && (this.data[0] = e2, this._down(0)), t4;
            }
            peek() {
              return this.data[0];
            }
            _up(t4) {
              const { data: e2, compare: r2 } = this, n2 = e2[t4];
              for (; t4 > 0; ) {
                const i2 = t4 - 1 >> 1, s2 = e2[i2];
                if (r2(n2, s2) >= 0) break;
                e2[t4] = s2, t4 = i2;
              }
              e2[t4] = n2;
            }
            _down(t4) {
              const { data: e2, compare: r2 } = this, n2 = this.length >> 1, i2 = e2[t4];
              for (; t4 < n2; ) {
                let n3 = 1 + (t4 << 1);
                const s2 = n3 + 1;
                if (s2 < this.length && r2(e2[s2], e2[n3]) < 0 && (n3 = s2), r2(e2[n3], i2) >= 0) break;
                e2[t4] = e2[n3], t4 = n3;
              }
              e2[t4] = i2;
            }
          };
          function dr(t4, e2, r2, n2, i2) {
            yr(t4, e2, r2, n2 || t4.length - 1, i2 || gr);
          }
          function yr(t4, e2, r2, n2, i2) {
            for (; n2 > r2; ) {
              if (n2 - r2 > 600) {
                var s2 = n2 - r2 + 1, a2 = e2 - r2 + 1, o2 = Math.log(s2), l2 = 0.5 * Math.exp(2 * o2 / 3), u2 = 0.5 * Math.sqrt(o2 * l2 * (s2 - l2) / s2) * (a2 - s2 / 2 < 0 ? -1 : 1);
                yr(t4, e2, Math.max(r2, Math.floor(e2 - a2 * l2 / s2 + u2)), Math.min(n2, Math.floor(e2 + (s2 - a2) * l2 / s2 + u2)), i2);
              }
              var c2 = t4[e2], h2 = r2, p2 = n2;
              for (mr(t4, r2, e2), i2(t4[n2], c2) > 0 && mr(t4, r2, n2); h2 < p2; ) {
                for (mr(t4, h2, p2), h2++, p2--; i2(t4[h2], c2) < 0; ) h2++;
                for (; i2(t4[p2], c2) > 0; ) p2--;
              }
              0 === i2(t4[r2], c2) ? mr(t4, r2, p2) : mr(t4, ++p2, n2), p2 <= e2 && (r2 = p2 + 1), e2 <= p2 && (n2 = p2 - 1);
            }
          }
          function mr(t4, e2, r2) {
            var n2 = t4[e2];
            t4[e2] = t4[r2], t4[r2] = n2;
          }
          function gr(t4, e2) {
            return t4 < e2 ? -1 : t4 > e2 ? 1 : 0;
          }
          function xr(t4, e2) {
            if (t4.length <= 1) return [t4];
            const r2 = [];
            let n2, i2;
            for (const e3 of t4) {
              const t5 = br(e3);
              0 !== t5 && (e3.area = Math.abs(t5), void 0 === i2 && (i2 = t5 < 0), i2 === t5 < 0 ? (n2 && r2.push(n2), n2 = [e3]) : n2.push(e3));
            }
            if (n2 && r2.push(n2), e2 > 1) for (let t5 = 0; t5 < r2.length; t5++) r2[t5].length <= e2 || (dr(r2[t5], e2, 1, r2[t5].length - 1, vr), r2[t5] = r2[t5].slice(0, e2));
            return r2;
          }
          function vr(t4, e2) {
            return e2.area - t4.area;
          }
          function br(t4) {
            let e2 = 0;
            for (let r2, n2, i2 = 0, s2 = t4.length, a2 = s2 - 1; i2 < s2; a2 = i2++) r2 = t4[i2], n2 = t4[a2], e2 += (n2.x - r2.x) * (r2.y + n2.y);
            return e2;
          }
          const wr = 1 / 298.257223563, _r = wr * (2 - wr), Ar = Math.PI / 180;
          class Sr {
            constructor(t4) {
              const e2 = 6378.137 * Ar * 1e3, r2 = Math.cos(t4 * Ar), n2 = 1 / (1 - _r * (1 - r2 * r2)), i2 = Math.sqrt(n2);
              this.kx = e2 * i2 * r2, this.ky = e2 * i2 * n2 * (1 - _r);
            }
            distance(t4, e2) {
              const r2 = this.wrap(t4[0] - e2[0]) * this.kx, n2 = (t4[1] - e2[1]) * this.ky;
              return Math.sqrt(r2 * r2 + n2 * n2);
            }
            pointOnLine(t4, e2) {
              let r2, n2, i2, s2, a2 = 1 / 0;
              for (let o2 = 0; o2 < t4.length - 1; o2++) {
                let l2 = t4[o2][0], u2 = t4[o2][1], c2 = this.wrap(t4[o2 + 1][0] - l2) * this.kx, h2 = (t4[o2 + 1][1] - u2) * this.ky, p2 = 0;
                0 === c2 && 0 === h2 || (p2 = (this.wrap(e2[0] - l2) * this.kx * c2 + (e2[1] - u2) * this.ky * h2) / (c2 * c2 + h2 * h2), p2 > 1 ? (l2 = t4[o2 + 1][0], u2 = t4[o2 + 1][1]) : p2 > 0 && (l2 += c2 / this.kx * p2, u2 += h2 / this.ky * p2)), c2 = this.wrap(e2[0] - l2) * this.kx, h2 = (e2[1] - u2) * this.ky;
                const f2 = c2 * c2 + h2 * h2;
                f2 < a2 && (a2 = f2, r2 = l2, n2 = u2, i2 = o2, s2 = p2);
              }
              return { point: [r2, n2], index: i2, t: Math.max(0, Math.min(1, s2)) };
            }
            wrap(t4) {
              for (; t4 < -180; ) t4 += 360;
              for (; t4 > 180; ) t4 -= 360;
              return t4;
            }
          }
          function kr(t4, e2) {
            return e2[0] - t4[0];
          }
          function Mr(t4) {
            return t4[1] - t4[0] + 1;
          }
          function Ir(t4, e2) {
            return t4[1] >= t4[0] && t4[1] < e2;
          }
          function zr(t4, e2) {
            if (t4[0] > t4[1]) return [null, null];
            const r2 = Mr(t4);
            if (e2) {
              if (2 === r2) return [t4, null];
              const e3 = Math.floor(r2 / 2);
              return [[t4[0], t4[0] + e3], [t4[0] + e3, t4[1]]];
            }
            if (1 === r2) return [t4, null];
            const n2 = Math.floor(r2 / 2) - 1;
            return [[t4[0], t4[0] + n2], [t4[0] + n2 + 1, t4[1]]];
          }
          function Pr(t4, e2) {
            if (!Ir(e2, t4.length)) return [1 / 0, 1 / 0, -1 / 0, -1 / 0];
            const r2 = [1 / 0, 1 / 0, -1 / 0, -1 / 0];
            for (let n2 = e2[0]; n2 <= e2[1]; ++n2) Je(r2, t4[n2]);
            return r2;
          }
          function Cr(t4) {
            const e2 = [1 / 0, 1 / 0, -1 / 0, -1 / 0];
            for (const r2 of t4) for (const t5 of r2) Je(e2, t5);
            return e2;
          }
          function Br(t4) {
            return t4[0] !== -1 / 0 && t4[1] !== -1 / 0 && t4[2] !== 1 / 0 && t4[3] !== 1 / 0;
          }
          function Vr(t4, e2, r2) {
            if (!Br(t4) || !Br(e2)) return NaN;
            let n2 = 0, i2 = 0;
            return t4[2] < e2[0] && (n2 = e2[0] - t4[2]), t4[0] > e2[2] && (n2 = t4[0] - e2[2]), t4[1] > e2[3] && (i2 = t4[1] - e2[3]), t4[3] < e2[1] && (i2 = e2[1] - t4[3]), r2.distance([0, 0], [n2, i2]);
          }
          function Er(t4, e2, r2) {
            const n2 = r2.pointOnLine(e2, t4);
            return r2.distance(t4, n2.point);
          }
          function Fr(t4, e2, r2, n2, i2) {
            const s2 = Math.min(Er(t4, [r2, n2], i2), Er(e2, [r2, n2], i2)), a2 = Math.min(Er(r2, [t4, e2], i2), Er(n2, [t4, e2], i2));
            return Math.min(s2, a2);
          }
          function Tr(t4, e2, r2, n2, i2) {
            if (!Ir(e2, t4.length) || !Ir(n2, r2.length)) return 1 / 0;
            let s2 = 1 / 0;
            for (let a2 = e2[0]; a2 < e2[1]; ++a2) {
              const e3 = t4[a2], o2 = t4[a2 + 1];
              for (let t5 = n2[0]; t5 < n2[1]; ++t5) {
                const n3 = r2[t5], a3 = r2[t5 + 1];
                if (tr(e3, o2, n3, a3)) return 0;
                s2 = Math.min(s2, Fr(e3, o2, n3, a3, i2));
              }
            }
            return s2;
          }
          function $r(t4, e2, r2, n2, i2) {
            if (!Ir(e2, t4.length) || !Ir(n2, r2.length)) return NaN;
            let s2 = 1 / 0;
            for (let a2 = e2[0]; a2 <= e2[1]; ++a2) for (let e3 = n2[0]; e3 <= n2[1]; ++e3) if (s2 = Math.min(s2, i2.distance(t4[a2], r2[e3])), 0 === s2) return s2;
            return s2;
          }
          function Lr(t4, e2, r2) {
            if (rr(t4, e2, true)) return 0;
            let n2 = 1 / 0;
            for (const i2 of e2) {
              const e3 = i2[0], s2 = i2[i2.length - 1];
              if (e3 !== s2 && (n2 = Math.min(n2, Er(t4, [s2, e3], r2)), 0 === n2)) return n2;
              const a2 = r2.pointOnLine(i2, t4);
              if (n2 = Math.min(n2, r2.distance(t4, a2.point)), 0 === n2) return n2;
            }
            return n2;
          }
          function Dr(t4, e2, r2, n2) {
            if (!Ir(e2, t4.length)) return NaN;
            for (let n3 = e2[0]; n3 <= e2[1]; ++n3) if (rr(t4[n3], r2, true)) return 0;
            let i2 = 1 / 0;
            for (let s2 = e2[0]; s2 < e2[1]; ++s2) {
              const e3 = t4[s2], a2 = t4[s2 + 1];
              for (const t5 of r2) for (let r3 = 0, s3 = t5.length, o2 = s3 - 1; r3 < s3; o2 = r3++) {
                const s4 = t5[o2], l2 = t5[r3];
                if (tr(e3, a2, s4, l2)) return 0;
                i2 = Math.min(i2, Fr(e3, a2, s4, l2, n2));
              }
            }
            return i2;
          }
          function Or(t4, e2) {
            for (const r2 of t4) for (const t5 of r2) if (rr(t5, e2, true)) return true;
            return false;
          }
          function jr(t4, e2, r2, n2 = 1 / 0) {
            const i2 = Cr(t4), s2 = Cr(e2);
            if (n2 !== 1 / 0 && Vr(i2, s2, r2) >= n2) return n2;
            if (We(i2, s2)) {
              if (Or(t4, e2)) return 0;
            } else if (Or(e2, t4)) return 0;
            let a2 = 1 / 0;
            for (const n3 of t4) for (let t5 = 0, i3 = n3.length, s3 = i3 - 1; t5 < i3; s3 = t5++) {
              const i4 = n3[s3], o2 = n3[t5];
              for (const t6 of e2) for (let e3 = 0, n4 = t6.length, s4 = n4 - 1; e3 < n4; s4 = e3++) {
                const n5 = t6[s4], l2 = t6[e3];
                if (tr(i4, o2, n5, l2)) return 0;
                a2 = Math.min(a2, Fr(i4, o2, n5, l2, r2));
              }
            }
            return a2;
          }
          function Rr(t4, e2, r2, n2, i2, s2) {
            if (!s2) return;
            const a2 = Vr(Pr(n2, s2), i2, r2);
            a2 < e2 && t4.push([a2, s2, [0, 0]]);
          }
          function Ur(t4, e2, r2, n2, i2, s2, a2) {
            if (!s2 || !a2) return;
            const o2 = Vr(Pr(n2, s2), Pr(i2, a2), r2);
            o2 < e2 && t4.push([o2, s2, a2]);
          }
          function qr(t4, e2, r2, n2, i2 = 1 / 0) {
            let s2 = Math.min(n2.distance(t4[0], r2[0][0]), i2);
            if (0 === s2) return s2;
            const a2 = new fr([[0, [0, t4.length - 1], [0, 0]]], kr), o2 = Cr(r2);
            for (; a2.length > 0; ) {
              const i3 = a2.pop();
              if (i3[0] >= s2) continue;
              const l2 = i3[1], u2 = e2 ? 50 : 100;
              if (Mr(l2) <= u2) {
                if (!Ir(l2, t4.length)) return NaN;
                if (e2) {
                  const e3 = Dr(t4, l2, r2, n2);
                  if (isNaN(e3) || 0 === e3) return e3;
                  s2 = Math.min(s2, e3);
                } else for (let e3 = l2[0]; e3 <= l2[1]; ++e3) {
                  const i4 = Lr(t4[e3], r2, n2);
                  if (s2 = Math.min(s2, i4), 0 === s2) return 0;
                }
              } else {
                const r3 = zr(l2, e2);
                Rr(a2, s2, n2, t4, o2, r3[0]), Rr(a2, s2, n2, t4, o2, r3[1]);
              }
            }
            return s2;
          }
          function Nr(t4, e2, r2, n2, i2, s2 = 1 / 0) {
            let a2 = Math.min(s2, i2.distance(t4[0], r2[0]));
            if (0 === a2) return a2;
            const o2 = new fr([[0, [0, t4.length - 1], [0, r2.length - 1]]], kr);
            for (; o2.length > 0; ) {
              const s3 = o2.pop();
              if (s3[0] >= a2) continue;
              const l2 = s3[1], u2 = s3[2], c2 = e2 ? 50 : 100, h2 = n2 ? 50 : 100;
              if (Mr(l2) <= c2 && Mr(u2) <= h2) {
                if (!Ir(l2, t4.length) && Ir(u2, r2.length)) return NaN;
                let s4;
                if (e2 && n2) s4 = Tr(t4, l2, r2, u2, i2), a2 = Math.min(a2, s4);
                else if (e2 && !n2) {
                  const e3 = t4.slice(l2[0], l2[1] + 1);
                  for (let t5 = u2[0]; t5 <= u2[1]; ++t5) if (s4 = Er(r2[t5], e3, i2), a2 = Math.min(a2, s4), 0 === a2) return a2;
                } else if (!e2 && n2) {
                  const e3 = r2.slice(u2[0], u2[1] + 1);
                  for (let r3 = l2[0]; r3 <= l2[1]; ++r3) if (s4 = Er(t4[r3], e3, i2), a2 = Math.min(a2, s4), 0 === a2) return a2;
                } else s4 = $r(t4, l2, r2, u2, i2), a2 = Math.min(a2, s4);
              } else {
                const s4 = zr(l2, e2), c3 = zr(u2, n2);
                Ur(o2, a2, i2, t4, r2, s4[0], c3[0]), Ur(o2, a2, i2, t4, r2, s4[0], c3[1]), Ur(o2, a2, i2, t4, r2, s4[1], c3[0]), Ur(o2, a2, i2, t4, r2, s4[1], c3[1]);
              }
            }
            return a2;
          }
          function Zr(t4) {
            return "MultiPolygon" === t4.type ? t4.coordinates.map((t5) => ({ type: "Polygon", coordinates: t5 })) : "MultiLineString" === t4.type ? t4.coordinates.map((t5) => ({ type: "LineString", coordinates: t5 })) : "MultiPoint" === t4.type ? t4.coordinates.map((t5) => ({ type: "Point", coordinates: t5 })) : [t4];
          }
          class Gr {
            constructor(t4, e2) {
              this.type = ut, this.geojson = t4, this.geometries = e2;
            }
            static parse(t4, e2) {
              if (2 !== t4.length) return e2.error(`'distance' expression requires exactly one argument, but found ${t4.length - 1} instead.`);
              if (re(t4[1])) {
                const e3 = t4[1];
                if ("FeatureCollection" === e3.type) return new Gr(e3, e3.features.map((t5) => Zr(t5.geometry)).flat());
                if ("Feature" === e3.type) return new Gr(e3, Zr(e3.geometry));
                if ("type" in e3 && "coordinates" in e3) return new Gr(e3, Zr(e3));
              }
              return e2.error("'distance' expression requires valid geojson object that contains polygon geometry type.");
            }
            evaluate(t4) {
              if (null != t4.geometry() && null != t4.canonicalID()) {
                if ("Point" === t4.geometryType()) return function(t5, e2) {
                  const r2 = t5.geometry(), n2 = r2.flat().map((e3) => Ye([e3.x, e3.y], t5.canonical));
                  if (0 === r2.length) return NaN;
                  const i2 = new Sr(n2[0][1]);
                  let s2 = 1 / 0;
                  for (const t6 of e2) {
                    switch (t6.type) {
                      case "Point":
                        s2 = Math.min(s2, Nr(n2, false, [t6.coordinates], false, i2, s2));
                        break;
                      case "LineString":
                        s2 = Math.min(s2, Nr(n2, false, t6.coordinates, true, i2, s2));
                        break;
                      case "Polygon":
                        s2 = Math.min(s2, qr(n2, false, t6.coordinates, i2, s2));
                    }
                    if (0 === s2) return s2;
                  }
                  return s2;
                }(t4, this.geometries);
                if ("LineString" === t4.geometryType()) return function(t5, e2) {
                  const r2 = t5.geometry(), n2 = r2.flat().map((e3) => Ye([e3.x, e3.y], t5.canonical));
                  if (0 === r2.length) return NaN;
                  const i2 = new Sr(n2[0][1]);
                  let s2 = 1 / 0;
                  for (const t6 of e2) {
                    switch (t6.type) {
                      case "Point":
                        s2 = Math.min(s2, Nr(n2, true, [t6.coordinates], false, i2, s2));
                        break;
                      case "LineString":
                        s2 = Math.min(s2, Nr(n2, true, t6.coordinates, true, i2, s2));
                        break;
                      case "Polygon":
                        s2 = Math.min(s2, qr(n2, true, t6.coordinates, i2, s2));
                    }
                    if (0 === s2) return s2;
                  }
                  return s2;
                }(t4, this.geometries);
                if ("Polygon" === t4.geometryType()) return function(t5, e2) {
                  const r2 = t5.geometry();
                  if (0 === r2.length || 0 === r2[0].length) return NaN;
                  const n2 = xr(r2, 0).map((e3) => e3.map((e4) => e4.map((e5) => Ye([e5.x, e5.y], t5.canonical)))), i2 = new Sr(n2[0][0][0][1]);
                  let s2 = 1 / 0;
                  for (const t6 of e2) for (const e3 of n2) {
                    switch (t6.type) {
                      case "Point":
                        s2 = Math.min(s2, qr([t6.coordinates], false, e3, i2, s2));
                        break;
                      case "LineString":
                        s2 = Math.min(s2, qr(t6.coordinates, true, e3, i2, s2));
                        break;
                      case "Polygon":
                        s2 = Math.min(s2, jr(e3, t6.coordinates, i2, s2));
                    }
                    if (0 === s2) return s2;
                  }
                  return s2;
                }(t4, this.geometries);
              }
              return NaN;
            }
            eachChild() {
            }
            outputDefined() {
              return true;
            }
          }
          const Kr = { "==": Le, "!=": De, ">": je, "<": Oe, ">=": Ue, "<=": Re, array: le, at: me, boolean: le, case: be, coalesce: Ee, collator: qe, format: Ze, image: Ge, in: ge, "index-of": xe, interpolate: Be, "interpolate-hcl": Be, "interpolate-lab": Be, length: Ke, let: de, literal: se, match: ve, number: le, "number-format": Ne, object: le, slice: we, step: Ae, string: le, "to-boolean": ce, "to-color": ce, "to-number": ce, "to-string": ce, var: ye, within: pr, distance: Gr };
          class Xr {
            constructor(t4, e2, r2, n2) {
              this.name = t4, this.type = e2, this._evaluate = r2, this.args = n2;
            }
            evaluate(t4) {
              return this._evaluate(t4, this.args);
            }
            eachChild(t4) {
              this.args.forEach(t4);
            }
            outputDefined() {
              return false;
            }
            static parse(t4, e2) {
              const r2 = t4[0], n2 = Xr.definitions[r2];
              if (!n2) return e2.error(`Unknown expression "${r2}". If you wanted a literal array, use ["literal", [...]].`, 0);
              const i2 = Array.isArray(n2) ? n2[0] : n2.type, s2 = Array.isArray(n2) ? [[n2[1], n2[2]]] : n2.overloads, a2 = s2.filter(([e3]) => !Array.isArray(e3) || e3.length === t4.length - 1);
              let o2 = null;
              for (const [n3, s3] of a2) {
                o2 = new fe(e2.registry, Qr, e2.path, null, e2.scope);
                const a3 = [];
                let l2 = false;
                for (let e3 = 1; e3 < t4.length; e3++) {
                  const r3 = t4[e3], i3 = Array.isArray(n3) ? n3[e3 - 1] : n3.type, s4 = o2.parse(r3, 1 + a3.length, i3);
                  if (!s4) {
                    l2 = true;
                    break;
                  }
                  a3.push(s4);
                }
                if (!l2) if (Array.isArray(n3) && n3.length !== a3.length) o2.error(`Expected ${n3.length} arguments, but found ${a3.length} instead.`);
                else {
                  for (let t5 = 0; t5 < a3.length; t5++) {
                    const e3 = Array.isArray(n3) ? n3[t5] : n3.type, r3 = a3[t5];
                    o2.concat(t5 + 1).checkSubtype(e3, r3.type);
                  }
                  if (0 === o2.errors.length) return new Xr(r2, i2, s3, a3);
                }
              }
              if (1 === a2.length) e2.errors.push(...o2.errors);
              else {
                const r3 = (a2.length ? a2 : s2).map(([t5]) => {
                  return e3 = t5, Array.isArray(e3) ? `(${e3.map(wt).join(", ")})` : `(${wt(e3.type)}...)`;
                  var e3;
                }).join(" | "), n3 = [];
                for (let r4 = 1; r4 < t4.length; r4++) {
                  const i3 = e2.parse(t4[r4], 1 + n3.length);
                  if (!i3) return null;
                  n3.push(wt(i3.type));
                }
                e2.error(`Expected arguments of type ${r3}, but found (${n3.join(", ")}) instead.`);
              }
              return null;
            }
            static register(t4, e2) {
              Xr.definitions = e2;
              for (const r2 in e2) t4[r2] = Xr;
            }
          }
          function Hr(t4, [e2, r2, n2, i2]) {
            e2 = e2.evaluate(t4), r2 = r2.evaluate(t4), n2 = n2.evaluate(t4);
            const s2 = i2 ? i2.evaluate(t4) : 1, a2 = ee(e2, r2, n2, s2);
            if (a2) throw new ae(a2);
            return new Kt(e2 / 255, r2 / 255, n2 / 255, s2, false);
          }
          function Yr(t4, e2) {
            return t4 in e2;
          }
          function Jr(t4, e2) {
            const r2 = e2[t4];
            return void 0 === r2 ? null : r2;
          }
          function Wr(t4) {
            return { type: t4 };
          }
          function Qr(t4) {
            if (t4 instanceof ye) return Qr(t4.boundExpression);
            if (t4 instanceof Xr && "error" === t4.name) return false;
            if (t4 instanceof qe) return false;
            if (t4 instanceof pr) return false;
            if (t4 instanceof Gr) return false;
            const e2 = t4 instanceof ce || t4 instanceof le;
            let r2 = true;
            return t4.eachChild((t5) => {
              r2 = e2 ? r2 && Qr(t5) : r2 && t5 instanceof se;
            }), !!r2 && tn(t4) && rn(t4, ["zoom", "heatmap-density", "line-progress", "accumulated", "is-supported-script"]);
          }
          function tn(t4) {
            if (t4 instanceof Xr) {
              if ("get" === t4.name && 1 === t4.args.length) return false;
              if ("feature-state" === t4.name) return false;
              if ("has" === t4.name && 1 === t4.args.length) return false;
              if ("properties" === t4.name || "geometry-type" === t4.name || "id" === t4.name) return false;
              if (/^filter-/.test(t4.name)) return false;
            }
            if (t4 instanceof pr) return false;
            if (t4 instanceof Gr) return false;
            let e2 = true;
            return t4.eachChild((t5) => {
              e2 && !tn(t5) && (e2 = false);
            }), e2;
          }
          function en(t4) {
            if (t4 instanceof Xr && "feature-state" === t4.name) return false;
            let e2 = true;
            return t4.eachChild((t5) => {
              e2 && !en(t5) && (e2 = false);
            }), e2;
          }
          function rn(t4, e2) {
            if (t4 instanceof Xr && e2.indexOf(t4.name) >= 0) return false;
            let r2 = true;
            return t4.eachChild((t5) => {
              r2 && !rn(t5, e2) && (r2 = false);
            }), r2;
          }
          function nn(t4) {
            return { result: "success", value: t4 };
          }
          function sn(t4) {
            return { result: "error", value: t4 };
          }
          function an(t4) {
            return "data-driven" === t4["property-type"] || "cross-faded-data-driven" === t4["property-type"];
          }
          function on(t4) {
            return !!t4.expression && t4.expression.parameters.indexOf("zoom") > -1;
          }
          function ln(t4) {
            return !!t4.expression && t4.expression.interpolated;
          }
          function un(t4) {
            return t4 instanceof Number ? "number" : t4 instanceof String ? "string" : t4 instanceof Boolean ? "boolean" : Array.isArray(t4) ? "array" : null === t4 ? "null" : typeof t4;
          }
          function cn(t4) {
            return "object" == typeof t4 && null !== t4 && !Array.isArray(t4);
          }
          function hn(t4) {
            return t4;
          }
          function pn(t4, e2) {
            const r2 = "color" === e2.type, n2 = t4.stops && "object" == typeof t4.stops[0][0], i2 = n2 || !(n2 || void 0 !== t4.property), s2 = t4.type || (ln(e2) ? "exponential" : "interval");
            if (r2 || "padding" === e2.type) {
              const n3 = r2 ? Kt.parse : Jt.parse;
              (t4 = st({}, t4)).stops && (t4.stops = t4.stops.map((t5) => [t5[0], n3(t5[1])])), t4.default = n3(t4.default ? t4.default : e2.default);
            }
            if (t4.colorSpace && "rgb" !== (a2 = t4.colorSpace) && "hcl" !== a2 && "lab" !== a2) throw new Error(`Unknown color space: "${t4.colorSpace}"`);
            var a2;
            let o2, l2, u2;
            if ("exponential" === s2) o2 = mn;
            else if ("interval" === s2) o2 = yn;
            else if ("categorical" === s2) {
              o2 = dn, l2 = /* @__PURE__ */ Object.create(null);
              for (const e3 of t4.stops) l2[e3[0]] = e3[1];
              u2 = typeof t4.stops[0][0];
            } else {
              if ("identity" !== s2) throw new Error(`Unknown function type "${s2}"`);
              o2 = gn;
            }
            if (n2) {
              const r3 = {}, n3 = [];
              for (let e3 = 0; e3 < t4.stops.length; e3++) {
                const i4 = t4.stops[e3], s4 = i4[0].zoom;
                void 0 === r3[s4] && (r3[s4] = { zoom: s4, type: t4.type, property: t4.property, default: t4.default, stops: [] }, n3.push(s4)), r3[s4].stops.push([i4[0].value, i4[1]]);
              }
              const i3 = [];
              for (const t5 of n3) i3.push([r3[t5].zoom, pn(r3[t5], e2)]);
              const s3 = { name: "linear" };
              return { kind: "composite", interpolationType: s3, interpolationFactor: Be.interpolationFactor.bind(void 0, s3), zoomStops: i3.map((t5) => t5[0]), evaluate: ({ zoom: r4 }, n4) => mn({ stops: i3, base: t4.base }, e2, r4).evaluate(r4, n4) };
            }
            if (i2) {
              const r3 = "exponential" === s2 ? { name: "exponential", base: void 0 !== t4.base ? t4.base : 1 } : null;
              return { kind: "camera", interpolationType: r3, interpolationFactor: Be.interpolationFactor.bind(void 0, r3), zoomStops: t4.stops.map((t5) => t5[0]), evaluate: ({ zoom: r4 }) => o2(t4, e2, r4, l2, u2) };
            }
            return { kind: "source", evaluate(r3, n3) {
              const i3 = n3 && n3.properties ? n3.properties[t4.property] : void 0;
              return void 0 === i3 ? fn(t4.default, e2.default) : o2(t4, e2, i3, l2, u2);
            } };
          }
          function fn(t4, e2, r2) {
            return void 0 !== t4 ? t4 : void 0 !== e2 ? e2 : void 0 !== r2 ? r2 : void 0;
          }
          function dn(t4, e2, r2, n2, i2) {
            return fn(typeof r2 === i2 ? n2[r2] : void 0, t4.default, e2.default);
          }
          function yn(t4, e2, r2) {
            if ("number" !== un(r2)) return fn(t4.default, e2.default);
            const n2 = t4.stops.length;
            if (1 === n2) return t4.stops[0][1];
            if (r2 <= t4.stops[0][0]) return t4.stops[0][1];
            if (r2 >= t4.stops[n2 - 1][0]) return t4.stops[n2 - 1][1];
            const i2 = _e(t4.stops.map((t5) => t5[0]), r2);
            return t4.stops[i2][1];
          }
          function mn(t4, e2, r2) {
            const n2 = void 0 !== t4.base ? t4.base : 1;
            if ("number" !== un(r2)) return fn(t4.default, e2.default);
            const i2 = t4.stops.length;
            if (1 === i2) return t4.stops[0][1];
            if (r2 <= t4.stops[0][0]) return t4.stops[0][1];
            if (r2 >= t4.stops[i2 - 1][0]) return t4.stops[i2 - 1][1];
            const s2 = _e(t4.stops.map((t5) => t5[0]), r2), a2 = function(t5, e3, r3, n3) {
              const i3 = n3 - r3, s3 = t5 - r3;
              return 0 === i3 ? 0 : 1 === e3 ? s3 / i3 : (Math.pow(e3, s3) - 1) / (Math.pow(e3, i3) - 1);
            }(r2, n2, t4.stops[s2][0], t4.stops[s2 + 1][0]), o2 = t4.stops[s2][1], l2 = t4.stops[s2 + 1][1], u2 = Ce[e2.type] || hn;
            return "function" == typeof o2.evaluate ? { evaluate(...e3) {
              const r3 = o2.evaluate.apply(void 0, e3), n3 = l2.evaluate.apply(void 0, e3);
              if (void 0 !== r3 && void 0 !== n3) return u2(r3, n3, a2, t4.colorSpace);
            } } : u2(o2, l2, a2, t4.colorSpace);
          }
          function gn(t4, e2, r2) {
            switch (e2.type) {
              case "color":
                r2 = Kt.parse(r2);
                break;
              case "formatted":
                r2 = Yt.fromString(r2.toString());
                break;
              case "resolvedImage":
                r2 = te.fromString(r2.toString());
                break;
              case "padding":
                r2 = Jt.parse(r2);
                break;
              default:
                un(r2) === e2.type || "enum" === e2.type && e2.values[r2] || (r2 = void 0);
            }
            return fn(r2, t4.default, e2.default);
          }
          Xr.register(Kr, { error: [{ kind: "error" }, [ct], (t4, [e2]) => {
            throw new ae(e2.evaluate(t4));
          }], typeof: [ct, [dt], (t4, [e2]) => wt(ne(e2.evaluate(t4)))], "to-rgba": [bt(ut, 4), [pt], (t4, [e2]) => {
            const [r2, n2, i2, s2] = e2.evaluate(t4).rgb;
            return [255 * r2, 255 * n2, 255 * i2, s2];
          }], rgb: [pt, [ut, ut, ut], Hr], rgba: [pt, [ut, ut, ut, ut], Hr], has: { type: ht, overloads: [[[ct], (t4, [e2]) => Yr(e2.evaluate(t4), t4.properties())], [[ct, ft], (t4, [e2, r2]) => Yr(e2.evaluate(t4), r2.evaluate(t4))]] }, get: { type: dt, overloads: [[[ct], (t4, [e2]) => Jr(e2.evaluate(t4), t4.properties())], [[ct, ft], (t4, [e2, r2]) => Jr(e2.evaluate(t4), r2.evaluate(t4))]] }, "feature-state": [dt, [ct], (t4, [e2]) => Jr(e2.evaluate(t4), t4.featureState || {})], properties: [ft, [], (t4) => t4.properties()], "geometry-type": [ct, [], (t4) => t4.geometryType()], id: [dt, [], (t4) => t4.id()], zoom: [ut, [], (t4) => t4.globals.zoom], "heatmap-density": [ut, [], (t4) => t4.globals.heatmapDensity || 0], "line-progress": [ut, [], (t4) => t4.globals.lineProgress || 0], accumulated: [dt, [], (t4) => void 0 === t4.globals.accumulated ? null : t4.globals.accumulated], "+": [ut, Wr(ut), (t4, e2) => {
            let r2 = 0;
            for (const n2 of e2) r2 += n2.evaluate(t4);
            return r2;
          }], "*": [ut, Wr(ut), (t4, e2) => {
            let r2 = 1;
            for (const n2 of e2) r2 *= n2.evaluate(t4);
            return r2;
          }], "-": { type: ut, overloads: [[[ut, ut], (t4, [e2, r2]) => e2.evaluate(t4) - r2.evaluate(t4)], [[ut], (t4, [e2]) => -e2.evaluate(t4)]] }, "/": [ut, [ut, ut], (t4, [e2, r2]) => e2.evaluate(t4) / r2.evaluate(t4)], "%": [ut, [ut, ut], (t4, [e2, r2]) => e2.evaluate(t4) % r2.evaluate(t4)], ln2: [ut, [], () => Math.LN2], pi: [ut, [], () => Math.PI], e: [ut, [], () => Math.E], "^": [ut, [ut, ut], (t4, [e2, r2]) => Math.pow(e2.evaluate(t4), r2.evaluate(t4))], sqrt: [ut, [ut], (t4, [e2]) => Math.sqrt(e2.evaluate(t4))], log10: [ut, [ut], (t4, [e2]) => Math.log(e2.evaluate(t4)) / Math.LN10], ln: [ut, [ut], (t4, [e2]) => Math.log(e2.evaluate(t4))], log2: [ut, [ut], (t4, [e2]) => Math.log(e2.evaluate(t4)) / Math.LN2], sin: [ut, [ut], (t4, [e2]) => Math.sin(e2.evaluate(t4))], cos: [ut, [ut], (t4, [e2]) => Math.cos(e2.evaluate(t4))], tan: [ut, [ut], (t4, [e2]) => Math.tan(e2.evaluate(t4))], asin: [ut, [ut], (t4, [e2]) => Math.asin(e2.evaluate(t4))], acos: [ut, [ut], (t4, [e2]) => Math.acos(e2.evaluate(t4))], atan: [ut, [ut], (t4, [e2]) => Math.atan(e2.evaluate(t4))], min: [ut, Wr(ut), (t4, e2) => Math.min(...e2.map((e3) => e3.evaluate(t4)))], max: [ut, Wr(ut), (t4, e2) => Math.max(...e2.map((e3) => e3.evaluate(t4)))], abs: [ut, [ut], (t4, [e2]) => Math.abs(e2.evaluate(t4))], round: [ut, [ut], (t4, [e2]) => {
            const r2 = e2.evaluate(t4);
            return r2 < 0 ? -Math.round(-r2) : Math.round(r2);
          }], floor: [ut, [ut], (t4, [e2]) => Math.floor(e2.evaluate(t4))], ceil: [ut, [ut], (t4, [e2]) => Math.ceil(e2.evaluate(t4))], "filter-==": [ht, [ct, dt], (t4, [e2, r2]) => t4.properties()[e2.value] === r2.value], "filter-id-==": [ht, [dt], (t4, [e2]) => t4.id() === e2.value], "filter-type-==": [ht, [ct], (t4, [e2]) => t4.geometryType() === e2.value], "filter-<": [ht, [ct, dt], (t4, [e2, r2]) => {
            const n2 = t4.properties()[e2.value], i2 = r2.value;
            return typeof n2 == typeof i2 && n2 < i2;
          }], "filter-id-<": [ht, [dt], (t4, [e2]) => {
            const r2 = t4.id(), n2 = e2.value;
            return typeof r2 == typeof n2 && r2 < n2;
          }], "filter->": [ht, [ct, dt], (t4, [e2, r2]) => {
            const n2 = t4.properties()[e2.value], i2 = r2.value;
            return typeof n2 == typeof i2 && n2 > i2;
          }], "filter-id->": [ht, [dt], (t4, [e2]) => {
            const r2 = t4.id(), n2 = e2.value;
            return typeof r2 == typeof n2 && r2 > n2;
          }], "filter-<=": [ht, [ct, dt], (t4, [e2, r2]) => {
            const n2 = t4.properties()[e2.value], i2 = r2.value;
            return typeof n2 == typeof i2 && n2 <= i2;
          }], "filter-id-<=": [ht, [dt], (t4, [e2]) => {
            const r2 = t4.id(), n2 = e2.value;
            return typeof r2 == typeof n2 && r2 <= n2;
          }], "filter->=": [ht, [ct, dt], (t4, [e2, r2]) => {
            const n2 = t4.properties()[e2.value], i2 = r2.value;
            return typeof n2 == typeof i2 && n2 >= i2;
          }], "filter-id->=": [ht, [dt], (t4, [e2]) => {
            const r2 = t4.id(), n2 = e2.value;
            return typeof r2 == typeof n2 && r2 >= n2;
          }], "filter-has": [ht, [dt], (t4, [e2]) => e2.value in t4.properties()], "filter-has-id": [ht, [], (t4) => null !== t4.id() && void 0 !== t4.id()], "filter-type-in": [ht, [bt(ct)], (t4, [e2]) => e2.value.indexOf(t4.geometryType()) >= 0], "filter-id-in": [ht, [bt(dt)], (t4, [e2]) => e2.value.indexOf(t4.id()) >= 0], "filter-in-small": [ht, [ct, bt(dt)], (t4, [e2, r2]) => r2.value.indexOf(t4.properties()[e2.value]) >= 0], "filter-in-large": [ht, [ct, bt(dt)], (t4, [e2, r2]) => function(t5, e3, r3, n2) {
            for (; r3 <= n2; ) {
              const i2 = r3 + n2 >> 1;
              if (e3[i2] === t5) return true;
              e3[i2] > t5 ? n2 = i2 - 1 : r3 = i2 + 1;
            }
            return false;
          }(t4.properties()[e2.value], r2.value, 0, r2.value.length - 1)], all: { type: ht, overloads: [[[ht, ht], (t4, [e2, r2]) => e2.evaluate(t4) && r2.evaluate(t4)], [Wr(ht), (t4, e2) => {
            for (const r2 of e2) if (!r2.evaluate(t4)) return false;
            return true;
          }]] }, any: { type: ht, overloads: [[[ht, ht], (t4, [e2, r2]) => e2.evaluate(t4) || r2.evaluate(t4)], [Wr(ht), (t4, e2) => {
            for (const r2 of e2) if (r2.evaluate(t4)) return true;
            return false;
          }]] }, "!": [ht, [ht], (t4, [e2]) => !e2.evaluate(t4)], "is-supported-script": [ht, [ct], (t4, [e2]) => {
            const r2 = t4.globals && t4.globals.isSupportedScript;
            return !r2 || r2(e2.evaluate(t4));
          }], upcase: [ct, [ct], (t4, [e2]) => e2.evaluate(t4).toUpperCase()], downcase: [ct, [ct], (t4, [e2]) => e2.evaluate(t4).toLowerCase()], concat: [ct, Wr(dt), (t4, e2) => e2.map((e3) => ie(e3.evaluate(t4))).join("")], "resolved-locale": [ct, [yt], (t4, [e2]) => e2.evaluate(t4).resolvedLocale()] });
          class xn {
            constructor(t4, e2) {
              var r2;
              this.expression = t4, this._warningHistory = {}, this._evaluator = new pe(), this._defaultValue = e2 ? "color" === (r2 = e2).type && cn(r2.default) ? new Kt(0, 0, 0, 0) : "color" === r2.type ? Kt.parse(r2.default) || null : "padding" === r2.type ? Jt.parse(r2.default) || null : "variableAnchorOffsetCollection" === r2.type ? Qt.parse(r2.default) || null : void 0 === r2.default ? null : r2.default : null, this._enumValues = e2 && "enum" === e2.type ? e2.values : null;
            }
            evaluateWithoutErrorHandling(t4, e2, r2, n2, i2, s2) {
              return this._evaluator.globals = t4, this._evaluator.feature = e2, this._evaluator.featureState = r2, this._evaluator.canonical = n2, this._evaluator.availableImages = i2 || null, this._evaluator.formattedSection = s2, this.expression.evaluate(this._evaluator);
            }
            evaluate(t4, e2, r2, n2, i2, s2) {
              this._evaluator.globals = t4, this._evaluator.feature = e2 || null, this._evaluator.featureState = r2 || null, this._evaluator.canonical = n2, this._evaluator.availableImages = i2 || null, this._evaluator.formattedSection = s2 || null;
              try {
                const t5 = this.expression.evaluate(this._evaluator);
                if (null == t5 || "number" == typeof t5 && t5 != t5) return this._defaultValue;
                if (this._enumValues && !(t5 in this._enumValues)) throw new ae(`Expected value to be one of ${Object.keys(this._enumValues).map((t6) => JSON.stringify(t6)).join(", ")}, but found ${JSON.stringify(t5)} instead.`);
                return t5;
              } catch (t5) {
                return this._warningHistory[t5.message] || (this._warningHistory[t5.message] = true, "undefined" != typeof console && console.warn(t5.message)), this._defaultValue;
              }
            }
          }
          function vn(t4) {
            return Array.isArray(t4) && t4.length > 0 && "string" == typeof t4[0] && t4[0] in Kr;
          }
          function bn(t4, e2) {
            const r2 = new fe(Kr, Qr, [], e2 ? function(t5) {
              const e3 = { color: pt, string: ct, number: ut, enum: ct, boolean: ht, formatted: mt, padding: gt, resolvedImage: xt, variableAnchorOffsetCollection: vt };
              return "array" === t5.type ? bt(e3[t5.value] || dt, t5.length) : e3[t5.type];
            }(e2) : void 0), n2 = r2.parse(t4, void 0, void 0, void 0, e2 && "string" === e2.type ? { typeAnnotation: "coerce" } : void 0);
            return n2 ? nn(new xn(n2, e2)) : sn(r2.errors);
          }
          class wn {
            constructor(t4, e2) {
              this.kind = t4, this._styleExpression = e2, this.isStateDependent = "constant" !== t4 && !en(e2.expression);
            }
            evaluateWithoutErrorHandling(t4, e2, r2, n2, i2, s2) {
              return this._styleExpression.evaluateWithoutErrorHandling(t4, e2, r2, n2, i2, s2);
            }
            evaluate(t4, e2, r2, n2, i2, s2) {
              return this._styleExpression.evaluate(t4, e2, r2, n2, i2, s2);
            }
          }
          class _n {
            constructor(t4, e2, r2, n2) {
              this.kind = t4, this.zoomStops = r2, this._styleExpression = e2, this.isStateDependent = "camera" !== t4 && !en(e2.expression), this.interpolationType = n2;
            }
            evaluateWithoutErrorHandling(t4, e2, r2, n2, i2, s2) {
              return this._styleExpression.evaluateWithoutErrorHandling(t4, e2, r2, n2, i2, s2);
            }
            evaluate(t4, e2, r2, n2, i2, s2) {
              return this._styleExpression.evaluate(t4, e2, r2, n2, i2, s2);
            }
            interpolationFactor(t4, e2, r2) {
              return this.interpolationType ? Be.interpolationFactor(this.interpolationType, t4, e2, r2) : 0;
            }
          }
          function An(t4, e2) {
            const r2 = bn(t4, e2);
            if ("error" === r2.result) return r2;
            const n2 = r2.value.expression, i2 = tn(n2);
            if (!i2 && !an(e2)) return sn([new at("", "data expressions not supported")]);
            const s2 = rn(n2, ["zoom"]);
            if (!s2 && !on(e2)) return sn([new at("", "zoom expressions not supported")]);
            const a2 = kn(n2);
            return a2 || s2 ? a2 instanceof at ? sn([a2]) : a2 instanceof Be && !ln(e2) ? sn([new at("", '"interpolate" expressions cannot be used with this property')]) : nn(a2 ? new _n(i2 ? "camera" : "composite", r2.value, a2.labels, a2 instanceof Be ? a2.interpolation : void 0) : new wn(i2 ? "constant" : "source", r2.value)) : sn([new at("", '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);
          }
          class Sn {
            constructor(t4, e2) {
              this._parameters = t4, this._specification = e2, st(this, pn(this._parameters, this._specification));
            }
            static deserialize(t4) {
              return new Sn(t4._parameters, t4._specification);
            }
            static serialize(t4) {
              return { _parameters: t4._parameters, _specification: t4._specification };
            }
          }
          function kn(t4) {
            let e2 = null;
            if (t4 instanceof de) e2 = kn(t4.result);
            else if (t4 instanceof Ee) {
              for (const r2 of t4.args) if (e2 = kn(r2), e2) break;
            } else (t4 instanceof Ae || t4 instanceof Be) && t4.input instanceof Xr && "zoom" === t4.input.name && (e2 = t4);
            return e2 instanceof at || t4.eachChild((t5) => {
              const r2 = kn(t5);
              r2 instanceof at ? e2 = r2 : !e2 && r2 ? e2 = new at("", '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.') : e2 && r2 && e2 !== r2 && (e2 = new at("", 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));
            }), e2;
          }
          function Mn(t4) {
            if (true === t4 || false === t4) return true;
            if (!Array.isArray(t4) || 0 === t4.length) return false;
            switch (t4[0]) {
              case "has":
                return t4.length >= 2 && "$id" !== t4[1] && "$type" !== t4[1];
              case "in":
                return t4.length >= 3 && ("string" != typeof t4[1] || Array.isArray(t4[2]));
              case "!in":
              case "!has":
              case "none":
                return false;
              case "==":
              case "!=":
              case ">":
              case ">=":
              case "<":
              case "<=":
                return 3 !== t4.length || Array.isArray(t4[1]) || Array.isArray(t4[2]);
              case "any":
              case "all":
                for (const e2 of t4.slice(1)) if (!Mn(e2) && "boolean" != typeof e2) return false;
                return true;
              default:
                return true;
            }
          }
          const In = { type: "boolean", default: false, transition: false, "property-type": "data-driven", expression: { interpolated: false, parameters: ["zoom", "feature"] } };
          function zn(t4) {
            if (null == t4) return { filter: () => true, needGeometry: false };
            Mn(t4) || (t4 = Bn(t4));
            const e2 = bn(t4, In);
            if ("error" === e2.result) throw new Error(e2.value.map((t5) => `${t5.key}: ${t5.message}`).join(", "));
            return { filter: (t5, r2, n2) => e2.value.evaluate(t5, r2, {}, n2), needGeometry: Cn(t4) };
          }
          function Pn(t4, e2) {
            return t4 < e2 ? -1 : t4 > e2 ? 1 : 0;
          }
          function Cn(t4) {
            if (!Array.isArray(t4)) return false;
            if ("within" === t4[0] || "distance" === t4[0]) return true;
            for (let e2 = 1; e2 < t4.length; e2++) if (Cn(t4[e2])) return true;
            return false;
          }
          function Bn(t4) {
            if (!t4) return true;
            const e2 = t4[0];
            return t4.length <= 1 ? "any" !== e2 : "==" === e2 ? Vn(t4[1], t4[2], "==") : "!=" === e2 ? Tn(Vn(t4[1], t4[2], "==")) : "<" === e2 || ">" === e2 || "<=" === e2 || ">=" === e2 ? Vn(t4[1], t4[2], e2) : "any" === e2 ? (r2 = t4.slice(1), ["any"].concat(r2.map(Bn))) : "all" === e2 ? ["all"].concat(t4.slice(1).map(Bn)) : "none" === e2 ? ["all"].concat(t4.slice(1).map(Bn).map(Tn)) : "in" === e2 ? En(t4[1], t4.slice(2)) : "!in" === e2 ? Tn(En(t4[1], t4.slice(2))) : "has" === e2 ? Fn(t4[1]) : "!has" !== e2 || Tn(Fn(t4[1]));
            var r2;
          }
          function Vn(t4, e2, r2) {
            switch (t4) {
              case "$type":
                return [`filter-type-${r2}`, e2];
              case "$id":
                return [`filter-id-${r2}`, e2];
              default:
                return [`filter-${r2}`, t4, e2];
            }
          }
          function En(t4, e2) {
            if (0 === e2.length) return false;
            switch (t4) {
              case "$type":
                return ["filter-type-in", ["literal", e2]];
              case "$id":
                return ["filter-id-in", ["literal", e2]];
              default:
                return e2.length > 200 && !e2.some((t5) => typeof t5 != typeof e2[0]) ? ["filter-in-large", t4, ["literal", e2.sort(Pn)]] : ["filter-in-small", t4, ["literal", e2]];
            }
          }
          function Fn(t4) {
            switch (t4) {
              case "$type":
                return true;
              case "$id":
                return ["filter-has-id"];
              default:
                return ["filter-has", t4];
            }
          }
          function Tn(t4) {
            return ["!", t4];
          }
          function $n(t4) {
            const e2 = typeof t4;
            if ("number" === e2 || "boolean" === e2 || "string" === e2 || null == t4) return JSON.stringify(t4);
            if (Array.isArray(t4)) {
              let e3 = "[";
              for (const r3 of t4) e3 += `${$n(r3)},`;
              return `${e3}]`;
            }
            const r2 = Object.keys(t4).sort();
            let n2 = "{";
            for (let e3 = 0; e3 < r2.length; e3++) n2 += `${JSON.stringify(r2[e3])}:${$n(t4[r2[e3]])},`;
            return `${n2}}`;
          }
          function Ln(t4) {
            let e2 = "";
            for (const r2 of K2) e2 += `/${$n(t4[r2])}`;
            return e2;
          }
          function Dn(t4) {
            const e2 = t4.value;
            return e2 ? [new it(t4.key, e2, "constants have been deprecated as of v8")] : [];
          }
          function On(t4) {
            return t4 instanceof Number || t4 instanceof String || t4 instanceof Boolean ? t4.valueOf() : t4;
          }
          function jn(t4) {
            if (Array.isArray(t4)) return t4.map(jn);
            if (t4 instanceof Object && !(t4 instanceof Number || t4 instanceof String || t4 instanceof Boolean)) {
              const e2 = {};
              for (const r2 in t4) e2[r2] = jn(t4[r2]);
              return e2;
            }
            return On(t4);
          }
          function Rn(t4) {
            const e2 = t4.key, r2 = t4.value, n2 = t4.valueSpec || {}, i2 = t4.objectElementValidators || {}, s2 = t4.style, a2 = t4.styleSpec, o2 = t4.validateSpec;
            let l2 = [];
            const u2 = un(r2);
            if ("object" !== u2) return [new it(e2, r2, `object expected, ${u2} found`)];
            for (const t5 in r2) {
              const u3 = t5.split(".")[0], c2 = n2[u3] || n2["*"];
              let h2;
              if (i2[u3]) h2 = i2[u3];
              else if (n2[u3]) h2 = o2;
              else if (i2["*"]) h2 = i2["*"];
              else {
                if (!n2["*"]) {
                  l2.push(new it(e2, r2[t5], `unknown property "${t5}"`));
                  continue;
                }
                h2 = o2;
              }
              l2 = l2.concat(h2({ key: (e2 ? `${e2}.` : e2) + t5, value: r2[t5], valueSpec: c2, style: s2, styleSpec: a2, object: r2, objectKey: t5, validateSpec: o2 }, r2));
            }
            for (const t5 in n2) i2[t5] || n2[t5].required && void 0 === n2[t5].default && void 0 === r2[t5] && l2.push(new it(e2, r2, `missing required property "${t5}"`));
            return l2;
          }
          function Un(t4) {
            const e2 = t4.value, r2 = t4.valueSpec, n2 = t4.style, i2 = t4.styleSpec, s2 = t4.key, a2 = t4.arrayElementValidator || t4.validateSpec;
            if ("array" !== un(e2)) return [new it(s2, e2, `array expected, ${un(e2)} found`)];
            if (r2.length && e2.length !== r2.length) return [new it(s2, e2, `array length ${r2.length} expected, length ${e2.length} found`)];
            if (r2["min-length"] && e2.length < r2["min-length"]) return [new it(s2, e2, `array length at least ${r2["min-length"]} expected, length ${e2.length} found`)];
            let o2 = { type: r2.value, values: r2.values };
            i2.$version < 7 && (o2.function = r2.function), "object" === un(r2.value) && (o2 = r2.value);
            let l2 = [];
            for (let r3 = 0; r3 < e2.length; r3++) l2 = l2.concat(a2({ array: e2, arrayIndex: r3, value: e2[r3], valueSpec: o2, validateSpec: t4.validateSpec, style: n2, styleSpec: i2, key: `${s2}[${r3}]` }));
            return l2;
          }
          function qn(t4) {
            const e2 = t4.key, r2 = t4.value, n2 = t4.valueSpec;
            let i2 = un(r2);
            return "number" === i2 && r2 != r2 && (i2 = "NaN"), "number" !== i2 ? [new it(e2, r2, `number expected, ${i2} found`)] : "minimum" in n2 && r2 < n2.minimum ? [new it(e2, r2, `${r2} is less than the minimum value ${n2.minimum}`)] : "maximum" in n2 && r2 > n2.maximum ? [new it(e2, r2, `${r2} is greater than the maximum value ${n2.maximum}`)] : [];
          }
          function Nn(t4) {
            const e2 = t4.valueSpec, r2 = On(t4.value.type);
            let n2, i2, s2, a2 = {};
            const o2 = "categorical" !== r2 && void 0 === t4.value.property, l2 = !o2, u2 = "array" === un(t4.value.stops) && "array" === un(t4.value.stops[0]) && "object" === un(t4.value.stops[0][0]), c2 = Rn({ key: t4.key, value: t4.value, valueSpec: t4.styleSpec.function, validateSpec: t4.validateSpec, style: t4.style, styleSpec: t4.styleSpec, objectElementValidators: { stops: function(t5) {
              if ("identity" === r2) return [new it(t5.key, t5.value, 'identity function may not have a "stops" property')];
              let e3 = [];
              const n3 = t5.value;
              return e3 = e3.concat(Un({ key: t5.key, value: n3, valueSpec: t5.valueSpec, validateSpec: t5.validateSpec, style: t5.style, styleSpec: t5.styleSpec, arrayElementValidator: h2 })), "array" === un(n3) && 0 === n3.length && e3.push(new it(t5.key, n3, "array must have at least one stop")), e3;
            }, default: function(t5) {
              return t5.validateSpec({ key: t5.key, value: t5.value, valueSpec: e2, validateSpec: t5.validateSpec, style: t5.style, styleSpec: t5.styleSpec });
            } } });
            return "identity" === r2 && o2 && c2.push(new it(t4.key, t4.value, 'missing required property "property"')), "identity" === r2 || t4.value.stops || c2.push(new it(t4.key, t4.value, 'missing required property "stops"')), "exponential" === r2 && t4.valueSpec.expression && !ln(t4.valueSpec) && c2.push(new it(t4.key, t4.value, "exponential functions not supported")), t4.styleSpec.$version >= 8 && (l2 && !an(t4.valueSpec) ? c2.push(new it(t4.key, t4.value, "property functions not supported")) : o2 && !on(t4.valueSpec) && c2.push(new it(t4.key, t4.value, "zoom functions not supported"))), "categorical" !== r2 && !u2 || void 0 !== t4.value.property || c2.push(new it(t4.key, t4.value, '"property" property is required')), c2;
            function h2(t5) {
              let r3 = [];
              const n3 = t5.value, o3 = t5.key;
              if ("array" !== un(n3)) return [new it(o3, n3, `array expected, ${un(n3)} found`)];
              if (2 !== n3.length) return [new it(o3, n3, `array length 2 expected, length ${n3.length} found`)];
              if (u2) {
                if ("object" !== un(n3[0])) return [new it(o3, n3, `object expected, ${un(n3[0])} found`)];
                if (void 0 === n3[0].zoom) return [new it(o3, n3, "object stop key must have zoom")];
                if (void 0 === n3[0].value) return [new it(o3, n3, "object stop key must have value")];
                if (s2 && s2 > On(n3[0].zoom)) return [new it(o3, n3[0].zoom, "stop zoom values must appear in ascending order")];
                On(n3[0].zoom) !== s2 && (s2 = On(n3[0].zoom), i2 = void 0, a2 = {}), r3 = r3.concat(Rn({ key: `${o3}[0]`, value: n3[0], valueSpec: { zoom: {} }, validateSpec: t5.validateSpec, style: t5.style, styleSpec: t5.styleSpec, objectElementValidators: { zoom: qn, value: p2 } }));
              } else r3 = r3.concat(p2({ key: `${o3}[0]`, value: n3[0], valueSpec: {}, validateSpec: t5.validateSpec, style: t5.style, styleSpec: t5.styleSpec }, n3));
              return vn(jn(n3[1])) ? r3.concat([new it(`${o3}[1]`, n3[1], "expressions are not allowed in function stops.")]) : r3.concat(t5.validateSpec({ key: `${o3}[1]`, value: n3[1], valueSpec: e2, validateSpec: t5.validateSpec, style: t5.style, styleSpec: t5.styleSpec }));
            }
            function p2(t5, s3) {
              const o3 = un(t5.value), l3 = On(t5.value), u3 = null !== t5.value ? t5.value : s3;
              if (n2) {
                if (o3 !== n2) return [new it(t5.key, u3, `${o3} stop domain type must match previous stop domain type ${n2}`)];
              } else n2 = o3;
              if ("number" !== o3 && "string" !== o3 && "boolean" !== o3) return [new it(t5.key, u3, "stop domain value must be a number, string, or boolean")];
              if ("number" !== o3 && "categorical" !== r2) {
                let n3 = `number expected, ${o3} found`;
                return an(e2) && void 0 === r2 && (n3 += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'), [new it(t5.key, u3, n3)];
              }
              return "categorical" !== r2 || "number" !== o3 || isFinite(l3) && Math.floor(l3) === l3 ? "categorical" !== r2 && "number" === o3 && void 0 !== i2 && l3 < i2 ? [new it(t5.key, u3, "stop domain values must appear in ascending order")] : (i2 = l3, "categorical" === r2 && l3 in a2 ? [new it(t5.key, u3, "stop domain values must be unique")] : (a2[l3] = true, [])) : [new it(t5.key, u3, `integer expected, found ${l3}`)];
            }
          }
          function Zn2(t4) {
            const e2 = ("property" === t4.expressionContext ? An : bn)(jn(t4.value), t4.valueSpec);
            if ("error" === e2.result) return e2.value.map((e3) => new it(`${t4.key}${e3.key}`, t4.value, e3.message));
            const r2 = e2.value.expression || e2.value._styleExpression.expression;
            if ("property" === t4.expressionContext && "text-font" === t4.propertyKey && !r2.outputDefined()) return [new it(t4.key, t4.value, `Invalid data expression for "${t4.propertyKey}". Output values must be contained as literals within the expression.`)];
            if ("property" === t4.expressionContext && "layout" === t4.propertyType && !en(r2)) return [new it(t4.key, t4.value, '"feature-state" data expressions are not supported with layout properties.')];
            if ("filter" === t4.expressionContext && !en(r2)) return [new it(t4.key, t4.value, '"feature-state" data expressions are not supported with filters.')];
            if (t4.expressionContext && 0 === t4.expressionContext.indexOf("cluster")) {
              if (!rn(r2, ["zoom", "feature-state"])) return [new it(t4.key, t4.value, '"zoom" and "feature-state" expressions are not supported with cluster properties.')];
              if ("cluster-initial" === t4.expressionContext && !tn(r2)) return [new it(t4.key, t4.value, "Feature data expressions are not supported with initial expression part of cluster properties.")];
            }
            return [];
          }
          function Gn(t4) {
            const e2 = t4.key, r2 = t4.value, n2 = t4.valueSpec, i2 = [];
            return Array.isArray(n2.values) ? -1 === n2.values.indexOf(On(r2)) && i2.push(new it(e2, r2, `expected one of [${n2.values.join(", ")}], ${JSON.stringify(r2)} found`)) : -1 === Object.keys(n2.values).indexOf(On(r2)) && i2.push(new it(e2, r2, `expected one of [${Object.keys(n2.values).join(", ")}], ${JSON.stringify(r2)} found`)), i2;
          }
          function Kn(t4) {
            return Mn(jn(t4.value)) ? Zn2(st({}, t4, { expressionContext: "filter", valueSpec: { value: "boolean" } })) : Xn2(t4);
          }
          function Xn2(t4) {
            const e2 = t4.value, r2 = t4.key;
            if ("array" !== un(e2)) return [new it(r2, e2, `array expected, ${un(e2)} found`)];
            const n2 = t4.styleSpec;
            let i2, s2 = [];
            if (e2.length < 1) return [new it(r2, e2, "filter array must have at least 1 element")];
            switch (s2 = s2.concat(Gn({ key: `${r2}[0]`, value: e2[0], valueSpec: n2.filter_operator, style: t4.style, styleSpec: t4.styleSpec })), On(e2[0])) {
              case "<":
              case "<=":
              case ">":
              case ">=":
                e2.length >= 2 && "$type" === On(e2[1]) && s2.push(new it(r2, e2, `"$type" cannot be use with operator "${e2[0]}"`));
              case "==":
              case "!=":
                3 !== e2.length && s2.push(new it(r2, e2, `filter array for operator "${e2[0]}" must have 3 elements`));
              case "in":
              case "!in":
                e2.length >= 2 && (i2 = un(e2[1]), "string" !== i2 && s2.push(new it(`${r2}[1]`, e2[1], `string expected, ${i2} found`)));
                for (let a2 = 2; a2 < e2.length; a2++) i2 = un(e2[a2]), "$type" === On(e2[1]) ? s2 = s2.concat(Gn({ key: `${r2}[${a2}]`, value: e2[a2], valueSpec: n2.geometry_type, style: t4.style, styleSpec: t4.styleSpec })) : "string" !== i2 && "number" !== i2 && "boolean" !== i2 && s2.push(new it(`${r2}[${a2}]`, e2[a2], `string, number, or boolean expected, ${i2} found`));
                break;
              case "any":
              case "all":
              case "none":
                for (let n3 = 1; n3 < e2.length; n3++) s2 = s2.concat(Xn2({ key: `${r2}[${n3}]`, value: e2[n3], style: t4.style, styleSpec: t4.styleSpec }));
                break;
              case "has":
              case "!has":
                i2 = un(e2[1]), 2 !== e2.length ? s2.push(new it(r2, e2, `filter array for "${e2[0]}" operator must have 2 elements`)) : "string" !== i2 && s2.push(new it(`${r2}[1]`, e2[1], `string expected, ${i2} found`));
            }
            return s2;
          }
          function Hn(t4, e2) {
            const r2 = t4.key, n2 = t4.validateSpec, i2 = t4.style, s2 = t4.styleSpec, a2 = t4.value, o2 = t4.objectKey, l2 = s2[`${e2}_${t4.layerType}`];
            if (!l2) return [];
            const u2 = o2.match(/^(.*)-transition$/);
            if ("paint" === e2 && u2 && l2[u2[1]] && l2[u2[1]].transition) return n2({ key: r2, value: a2, valueSpec: s2.transition, style: i2, styleSpec: s2 });
            const c2 = t4.valueSpec || l2[o2];
            if (!c2) return [new it(r2, a2, `unknown property "${o2}"`)];
            let h2;
            if ("string" === un(a2) && an(c2) && !c2.tokens && (h2 = /^{([^}]+)}$/.exec(a2))) return [new it(r2, a2, `"${o2}" does not support interpolation syntax
Use an identity property function instead: \`{ "type": "identity", "property": ${JSON.stringify(h2[1])} }\`.`)];
            const p2 = [];
            return "symbol" === t4.layerType && ("text-field" === o2 && i2 && !i2.glyphs && p2.push(new it(r2, a2, 'use of "text-field" requires a style "glyphs" property')), "text-font" === o2 && cn(jn(a2)) && "identity" === On(a2.type) && p2.push(new it(r2, a2, '"text-font" does not support identity functions'))), p2.concat(n2({ key: t4.key, value: a2, valueSpec: c2, style: i2, styleSpec: s2, expressionContext: "property", propertyType: e2, propertyKey: o2 }));
          }
          function Yn2(t4) {
            return Hn(t4, "paint");
          }
          function Jn(t4) {
            return Hn(t4, "layout");
          }
          function Wn(t4) {
            let e2 = [];
            const r2 = t4.value, n2 = t4.key, i2 = t4.style, s2 = t4.styleSpec;
            r2.type || r2.ref || e2.push(new it(n2, r2, 'either "type" or "ref" is required'));
            let a2 = On(r2.type);
            const o2 = On(r2.ref);
            if (r2.id) {
              const s3 = On(r2.id);
              for (let a3 = 0; a3 < t4.arrayIndex; a3++) {
                const t5 = i2.layers[a3];
                On(t5.id) === s3 && e2.push(new it(n2, r2.id, `duplicate layer id "${r2.id}", previously used at line ${t5.id.__line__}`));
              }
            }
            if ("ref" in r2) {
              let t5;
              ["type", "source", "source-layer", "filter", "layout"].forEach((t6) => {
                t6 in r2 && e2.push(new it(n2, r2[t6], `"${t6}" is prohibited for ref layers`));
              }), i2.layers.forEach((e3) => {
                On(e3.id) === o2 && (t5 = e3);
              }), t5 ? t5.ref ? e2.push(new it(n2, r2.ref, "ref cannot reference another ref layer")) : a2 = On(t5.type) : e2.push(new it(n2, r2.ref, `ref layer "${o2}" not found`));
            } else if ("background" !== a2) if (r2.source) {
              const t5 = i2.sources && i2.sources[r2.source], s3 = t5 && On(t5.type);
              t5 ? "vector" === s3 && "raster" === a2 ? e2.push(new it(n2, r2.source, `layer "${r2.id}" requires a raster source`)) : "raster-dem" !== s3 && "hillshade" === a2 ? e2.push(new it(n2, r2.source, `layer "${r2.id}" requires a raster-dem source`)) : "raster" === s3 && "raster" !== a2 ? e2.push(new it(n2, r2.source, `layer "${r2.id}" requires a vector source`)) : "vector" !== s3 || r2["source-layer"] ? "raster-dem" === s3 && "hillshade" !== a2 ? e2.push(new it(n2, r2.source, "raster-dem source can only be used with layer type 'hillshade'.")) : "line" !== a2 || !r2.paint || !r2.paint["line-gradient"] || "geojson" === s3 && t5.lineMetrics || e2.push(new it(n2, r2, `layer "${r2.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)) : e2.push(new it(n2, r2, `layer "${r2.id}" must specify a "source-layer"`)) : e2.push(new it(n2, r2.source, `source "${r2.source}" not found`));
            } else e2.push(new it(n2, r2, 'missing required property "source"'));
            return e2 = e2.concat(Rn({ key: n2, value: r2, valueSpec: s2.layer, style: t4.style, styleSpec: t4.styleSpec, validateSpec: t4.validateSpec, objectElementValidators: { "*": () => [], type: () => t4.validateSpec({ key: `${n2}.type`, value: r2.type, valueSpec: s2.layer.type, style: t4.style, styleSpec: t4.styleSpec, validateSpec: t4.validateSpec, object: r2, objectKey: "type" }), filter: Kn, layout: (t5) => Rn({ layer: r2, key: t5.key, value: t5.value, style: t5.style, styleSpec: t5.styleSpec, validateSpec: t5.validateSpec, objectElementValidators: { "*": (t6) => Jn(st({ layerType: a2 }, t6)) } }), paint: (t5) => Rn({ layer: r2, key: t5.key, value: t5.value, style: t5.style, styleSpec: t5.styleSpec, validateSpec: t5.validateSpec, objectElementValidators: { "*": (t6) => Yn2(st({ layerType: a2 }, t6)) } }) } })), e2;
          }
          function Qn(t4) {
            const e2 = t4.value, r2 = t4.key, n2 = un(e2);
            return "string" !== n2 ? [new it(r2, e2, `string expected, ${n2} found`)] : [];
          }
          const ti = { promoteId: function({ key: t4, value: e2 }) {
            if ("string" === un(e2)) return Qn({ key: t4, value: e2 });
            {
              const r2 = [];
              for (const n2 in e2) r2.push(...Qn({ key: `${t4}.${n2}`, value: e2[n2] }));
              return r2;
            }
          } };
          function ei(t4) {
            const e2 = t4.value, r2 = t4.key, n2 = t4.styleSpec, i2 = t4.style, s2 = t4.validateSpec;
            if (!e2.type) return [new it(r2, e2, '"type" is required')];
            const a2 = On(e2.type);
            let o2;
            switch (a2) {
              case "vector":
              case "raster":
                return o2 = Rn({ key: r2, value: e2, valueSpec: n2[`source_${a2.replace("-", "_")}`], style: t4.style, styleSpec: n2, objectElementValidators: ti, validateSpec: s2 }), o2;
              case "raster-dem":
                return o2 = function(t5) {
                  var e3;
                  const r3 = null !== (e3 = t5.sourceName) && void 0 !== e3 ? e3 : "", n3 = t5.value, i3 = t5.styleSpec, s3 = i3.source_raster_dem, a3 = t5.style;
                  let o3 = [];
                  const l2 = un(n3);
                  if (void 0 === n3) return o3;
                  if ("object" !== l2) return o3.push(new it("source_raster_dem", n3, `object expected, ${l2} found`)), o3;
                  const u2 = "custom" === On(n3.encoding), c2 = ["redFactor", "greenFactor", "blueFactor", "baseShift"], h2 = t5.value.encoding ? `"${t5.value.encoding}"` : "Default";
                  for (const e4 in n3) !u2 && c2.includes(e4) ? o3.push(new it(e4, n3[e4], `In "${r3}": "${e4}" is only valid when "encoding" is set to "custom". ${h2} encoding found`)) : s3[e4] ? o3 = o3.concat(t5.validateSpec({ key: e4, value: n3[e4], valueSpec: s3[e4], validateSpec: t5.validateSpec, style: a3, styleSpec: i3 })) : o3.push(new it(e4, n3[e4], `unknown property "${e4}"`));
                  return o3;
                }({ sourceName: r2, value: e2, style: t4.style, styleSpec: n2, validateSpec: s2 }), o2;
              case "geojson":
                if (o2 = Rn({ key: r2, value: e2, valueSpec: n2.source_geojson, style: i2, styleSpec: n2, validateSpec: s2, objectElementValidators: ti }), e2.cluster) for (const t5 in e2.clusterProperties) {
                  const [n3, i3] = e2.clusterProperties[t5], a3 = "string" == typeof n3 ? [n3, ["accumulated"], ["get", t5]] : n3;
                  o2.push(...Zn2({ key: `${r2}.${t5}.map`, value: i3, validateSpec: s2, expressionContext: "cluster-map" })), o2.push(...Zn2({ key: `${r2}.${t5}.reduce`, value: a3, validateSpec: s2, expressionContext: "cluster-reduce" }));
                }
                return o2;
              case "video":
                return Rn({ key: r2, value: e2, valueSpec: n2.source_video, style: i2, validateSpec: s2, styleSpec: n2 });
              case "image":
                return Rn({ key: r2, value: e2, valueSpec: n2.source_image, style: i2, validateSpec: s2, styleSpec: n2 });
              case "canvas":
                return [new it(r2, null, "Please use runtime APIs to add canvas sources, rather than including them in stylesheets.", "source.canvas")];
              default:
                return Gn({ key: `${r2}.type`, value: e2.type, valueSpec: { values: ["vector", "raster", "raster-dem", "geojson", "video", "image"] }, style: i2, validateSpec: s2, styleSpec: n2 });
            }
          }
          function ri(t4) {
            const e2 = t4.value, r2 = t4.styleSpec, n2 = r2.light, i2 = t4.style;
            let s2 = [];
            const a2 = un(e2);
            if (void 0 === e2) return s2;
            if ("object" !== a2) return s2 = s2.concat([new it("light", e2, `object expected, ${a2} found`)]), s2;
            for (const a3 in e2) {
              const o2 = a3.match(/^(.*)-transition$/);
              s2 = s2.concat(o2 && n2[o2[1]] && n2[o2[1]].transition ? t4.validateSpec({ key: a3, value: e2[a3], valueSpec: r2.transition, validateSpec: t4.validateSpec, style: i2, styleSpec: r2 }) : n2[a3] ? t4.validateSpec({ key: a3, value: e2[a3], valueSpec: n2[a3], validateSpec: t4.validateSpec, style: i2, styleSpec: r2 }) : [new it(a3, e2[a3], `unknown property "${a3}"`)]);
            }
            return s2;
          }
          function ni(t4) {
            const e2 = t4.value, r2 = t4.styleSpec, n2 = r2.sky, i2 = t4.style, s2 = un(e2);
            if (void 0 === e2) return [];
            if ("object" !== s2) return [new it("sky", e2, `object expected, ${s2} found`)];
            let a2 = [];
            for (const s3 in e2) a2 = a2.concat(n2[s3] ? t4.validateSpec({ key: s3, value: e2[s3], valueSpec: n2[s3], style: i2, styleSpec: r2 }) : [new it(s3, e2[s3], `unknown property "${s3}"`)]);
            return a2;
          }
          function ii(t4) {
            const e2 = t4.value, r2 = t4.styleSpec, n2 = r2.terrain, i2 = t4.style;
            let s2 = [];
            const a2 = un(e2);
            if (void 0 === e2) return s2;
            if ("object" !== a2) return s2 = s2.concat([new it("terrain", e2, `object expected, ${a2} found`)]), s2;
            for (const a3 in e2) s2 = s2.concat(n2[a3] ? t4.validateSpec({ key: a3, value: e2[a3], valueSpec: n2[a3], validateSpec: t4.validateSpec, style: i2, styleSpec: r2 }) : [new it(a3, e2[a3], `unknown property "${a3}"`)]);
            return s2;
          }
          function si(t4) {
            let e2 = [];
            const r2 = t4.value, n2 = t4.key;
            if (Array.isArray(r2)) {
              const i2 = [], s2 = [];
              for (const a2 in r2) r2[a2].id && i2.includes(r2[a2].id) && e2.push(new it(n2, r2, `all the sprites' ids must be unique, but ${r2[a2].id} is duplicated`)), i2.push(r2[a2].id), r2[a2].url && s2.includes(r2[a2].url) && e2.push(new it(n2, r2, `all the sprites' URLs must be unique, but ${r2[a2].url} is duplicated`)), s2.push(r2[a2].url), e2 = e2.concat(Rn({ key: `${n2}[${a2}]`, value: r2[a2], valueSpec: { id: { type: "string", required: true }, url: { type: "string", required: true } }, validateSpec: t4.validateSpec }));
              return e2;
            }
            return Qn({ key: n2, value: r2 });
          }
          const ai = { "*": () => [], array: Un, boolean: function(t4) {
            const e2 = t4.value, r2 = t4.key, n2 = un(e2);
            return "boolean" !== n2 ? [new it(r2, e2, `boolean expected, ${n2} found`)] : [];
          }, number: qn, color: function(t4) {
            const e2 = t4.key, r2 = t4.value, n2 = un(r2);
            return "string" !== n2 ? [new it(e2, r2, `color expected, ${n2} found`)] : Kt.parse(String(r2)) ? [] : [new it(e2, r2, `color expected, "${r2}" found`)];
          }, constants: Dn, enum: Gn, filter: Kn, function: Nn, layer: Wn, object: Rn, source: ei, light: ri, sky: ni, terrain: ii, projection: function(t4) {
            const e2 = t4.value, r2 = t4.styleSpec, n2 = r2.projection, i2 = t4.style, s2 = un(e2);
            if (void 0 === e2) return [];
            if ("object" !== s2) return [new it("projection", e2, `object expected, ${s2} found`)];
            let a2 = [];
            for (const s3 in e2) a2 = a2.concat(n2[s3] ? t4.validateSpec({ key: s3, value: e2[s3], valueSpec: n2[s3], style: i2, styleSpec: r2 }) : [new it(s3, e2[s3], `unknown property "${s3}"`)]);
            return a2;
          }, string: Qn, formatted: function(t4) {
            return 0 === Qn(t4).length ? [] : Zn2(t4);
          }, resolvedImage: function(t4) {
            return 0 === Qn(t4).length ? [] : Zn2(t4);
          }, padding: function(t4) {
            const e2 = t4.key, r2 = t4.value;
            if ("array" === un(r2)) {
              if (r2.length < 1 || r2.length > 4) return [new it(e2, r2, `padding requires 1 to 4 values; ${r2.length} values found`)];
              const n2 = { type: "number" };
              let i2 = [];
              for (let s2 = 0; s2 < r2.length; s2++) i2 = i2.concat(t4.validateSpec({ key: `${e2}[${s2}]`, value: r2[s2], validateSpec: t4.validateSpec, valueSpec: n2 }));
              return i2;
            }
            return qn({ key: e2, value: r2, valueSpec: {} });
          }, variableAnchorOffsetCollection: function(t4) {
            const e2 = t4.key, r2 = t4.value, n2 = un(r2), i2 = t4.styleSpec;
            if ("array" !== n2 || r2.length < 1 || r2.length % 2 != 0) return [new it(e2, r2, "variableAnchorOffsetCollection requires a non-empty array of even length")];
            let s2 = [];
            for (let n3 = 0; n3 < r2.length; n3 += 2) s2 = s2.concat(Gn({ key: `${e2}[${n3}]`, value: r2[n3], valueSpec: i2.layout_symbol["text-anchor"] })), s2 = s2.concat(Un({ key: `${e2}[${n3 + 1}]`, value: r2[n3 + 1], valueSpec: { length: 2, value: "number" }, validateSpec: t4.validateSpec, style: t4.style, styleSpec: i2 }));
            return s2;
          }, sprite: si };
          function oi(t4) {
            const e2 = t4.value, r2 = t4.valueSpec, n2 = t4.styleSpec;
            return t4.validateSpec = oi, r2.expression && cn(On(e2)) ? Nn(t4) : r2.expression && vn(jn(e2)) ? Zn2(t4) : r2.type && ai[r2.type] ? ai[r2.type](t4) : Rn(st({}, t4, { valueSpec: r2.type ? n2[r2.type] : r2 }));
          }
          function li(t4) {
            const e2 = t4.value, r2 = t4.key, n2 = Qn(t4);
            return n2.length || (-1 === e2.indexOf("{fontstack}") && n2.push(new it(r2, e2, '"glyphs" url must include a "{fontstack}" token')), -1 === e2.indexOf("{range}") && n2.push(new it(r2, e2, '"glyphs" url must include a "{range}" token'))), n2;
          }
          function ui(t4, e2 = G) {
            let r2 = [];
            return r2 = r2.concat(oi({ key: "", value: t4, valueSpec: e2.$root, styleSpec: e2, style: t4, validateSpec: oi, objectElementValidators: { glyphs: li, "*": () => [] } })), t4.constants && (r2 = r2.concat(Dn({ key: "constants", value: t4.constants, style: t4, styleSpec: e2, validateSpec: oi }))), hi(r2);
          }
          function ci(t4) {
            return function(e2) {
              return t4(__spreadProps(__spreadValues({}, e2), { validateSpec: oi }));
            };
          }
          function hi(t4) {
            return [].concat(t4).sort((t5, e2) => t5.line - e2.line);
          }
          function pi(t4) {
            return function(...e2) {
              return hi(t4.apply(this, e2));
            };
          }
          ui.source = pi(ci(ei)), ui.sprite = pi(ci(si)), ui.glyphs = pi(ci(li)), ui.light = pi(ci(ri)), ui.sky = pi(ci(ni)), ui.terrain = pi(ci(ii)), ui.layer = pi(ci(Wn)), ui.filter = pi(ci(Kn)), ui.paintProperty = pi(ci(Yn2)), ui.layoutProperty = pi(ci(Jn));
          const fi = ui, di = fi.light, yi = fi.sky, mi = fi.paintProperty, gi = fi.layoutProperty;
          function xi(t4, e2) {
            let r2 = false;
            if (e2 && e2.length) for (const n2 of e2) t4.fire(new N(new Error(n2.message))), r2 = true;
            return r2;
          }
          class vi {
            constructor(t4, e2, r2) {
              const n2 = this.cells = [];
              if (t4 instanceof ArrayBuffer) {
                this.arrayBuffer = t4;
                const i3 = new Int32Array(this.arrayBuffer);
                t4 = i3[0], this.d = (e2 = i3[1]) + 2 * (r2 = i3[2]);
                for (let t5 = 0; t5 < this.d * this.d; t5++) {
                  const e3 = i3[3 + t5], r3 = i3[3 + t5 + 1];
                  n2.push(e3 === r3 ? null : i3.subarray(e3, r3));
                }
                const s2 = i3[3 + n2.length + 1];
                this.keys = i3.subarray(i3[3 + n2.length], s2), this.bboxes = i3.subarray(s2), this.insert = this._insertReadonly;
              } else {
                this.d = e2 + 2 * r2;
                for (let t5 = 0; t5 < this.d * this.d; t5++) n2.push([]);
                this.keys = [], this.bboxes = [];
              }
              this.n = e2, this.extent = t4, this.padding = r2, this.scale = e2 / t4, this.uid = 0;
              const i2 = r2 / e2 * t4;
              this.min = -i2, this.max = t4 + i2;
            }
            insert(t4, e2, r2, n2, i2) {
              this._forEachCell(e2, r2, n2, i2, this._insertCell, this.uid++, void 0, void 0), this.keys.push(t4), this.bboxes.push(e2), this.bboxes.push(r2), this.bboxes.push(n2), this.bboxes.push(i2);
            }
            _insertReadonly() {
              throw new Error("Cannot insert into a GridIndex created from an ArrayBuffer.");
            }
            _insertCell(t4, e2, r2, n2, i2, s2) {
              this.cells[i2].push(s2);
            }
            query(t4, e2, r2, n2, i2) {
              const s2 = this.min, a2 = this.max;
              if (t4 <= s2 && e2 <= s2 && a2 <= r2 && a2 <= n2 && !i2) return Array.prototype.slice.call(this.keys);
              {
                const s3 = [];
                return this._forEachCell(t4, e2, r2, n2, this._queryCell, s3, {}, i2), s3;
              }
            }
            _queryCell(t4, e2, r2, n2, i2, s2, a2, o2) {
              const l2 = this.cells[i2];
              if (null !== l2) {
                const i3 = this.keys, u2 = this.bboxes;
                for (let c2 = 0; c2 < l2.length; c2++) {
                  const h2 = l2[c2];
                  if (void 0 === a2[h2]) {
                    const l3 = 4 * h2;
                    (o2 ? o2(u2[l3 + 0], u2[l3 + 1], u2[l3 + 2], u2[l3 + 3]) : t4 <= u2[l3 + 2] && e2 <= u2[l3 + 3] && r2 >= u2[l3 + 0] && n2 >= u2[l3 + 1]) ? (a2[h2] = true, s2.push(i3[h2])) : a2[h2] = false;
                  }
                }
              }
            }
            _forEachCell(t4, e2, r2, n2, i2, s2, a2, o2) {
              const l2 = this._convertToCellCoord(t4), u2 = this._convertToCellCoord(e2), c2 = this._convertToCellCoord(r2), h2 = this._convertToCellCoord(n2);
              for (let p2 = l2; p2 <= c2; p2++) for (let l3 = u2; l3 <= h2; l3++) {
                const u3 = this.d * l3 + p2;
                if ((!o2 || o2(this._convertFromCellCoord(p2), this._convertFromCellCoord(l3), this._convertFromCellCoord(p2 + 1), this._convertFromCellCoord(l3 + 1))) && i2.call(this, t4, e2, r2, n2, u3, s2, a2, o2)) return;
              }
            }
            _convertFromCellCoord(t4) {
              return (t4 - this.padding) / this.scale;
            }
            _convertToCellCoord(t4) {
              return Math.max(0, Math.min(this.d - 1, Math.floor(t4 * this.scale) + this.padding));
            }
            toArrayBuffer() {
              if (this.arrayBuffer) return this.arrayBuffer;
              const t4 = this.cells, e2 = 3 + this.cells.length + 1 + 1;
              let r2 = 0;
              for (let t5 = 0; t5 < this.cells.length; t5++) r2 += this.cells[t5].length;
              const n2 = new Int32Array(e2 + r2 + this.keys.length + this.bboxes.length);
              n2[0] = this.extent, n2[1] = this.n, n2[2] = this.padding;
              let i2 = e2;
              for (let e3 = 0; e3 < t4.length; e3++) {
                const r3 = t4[e3];
                n2[3 + e3] = i2, n2.set(r3, i2), i2 += r3.length;
              }
              return n2[3 + t4.length] = i2, n2.set(this.keys, i2), i2 += this.keys.length, n2[3 + t4.length + 1] = i2, n2.set(this.bboxes, i2), i2 += this.bboxes.length, n2.buffer;
            }
            static serialize(t4, e2) {
              const r2 = t4.toArrayBuffer();
              return e2 && e2.push(r2), { buffer: r2 };
            }
            static deserialize(t4) {
              return new vi(t4.buffer);
            }
          }
          const bi = {};
          function wi(t4, e2, r2 = {}) {
            if (bi[t4]) throw new Error(`${t4} is already registered.`);
            Object.defineProperty(e2, "_classRegistryKey", { value: t4, writeable: false }), bi[t4] = { klass: e2, omit: r2.omit || [], shallow: r2.shallow || [] };
          }
          wi("Object", Object), wi("TransferableGridIndex", vi), wi("Color", Kt), wi("Error", Error), wi("AJAXError", L), wi("ResolvedImage", te), wi("StylePropertyFunction", Sn), wi("StyleExpression", xn, { omit: ["_evaluator"] }), wi("ZoomDependentExpression", _n), wi("ZoomConstantExpression", wn), wi("CompoundExpression", Xr, { omit: ["_evaluate"] });
          for (const t4 in Kr) Kr[t4]._classRegistryKey || wi(`Expression_${t4}`, Kr[t4]);
          function _i(t4) {
            return t4 && "undefined" != typeof ArrayBuffer && (t4 instanceof ArrayBuffer || t4.constructor && "ArrayBuffer" === t4.constructor.name);
          }
          function Ai(t4) {
            return t4.$name || t4.constructor._classRegistryKey;
          }
          function Si(t4) {
            return !function(t5) {
              if (null === t5 || "object" != typeof t5) return false;
              const e2 = Ai(t5);
              return !(!e2 || "Object" === e2);
            }(t4) && (null == t4 || "boolean" == typeof t4 || "number" == typeof t4 || "string" == typeof t4 || t4 instanceof Boolean || t4 instanceof Number || t4 instanceof String || t4 instanceof Date || t4 instanceof RegExp || t4 instanceof Blob || t4 instanceof Error || _i(t4) || I(t4) || ArrayBuffer.isView(t4) || t4 instanceof ImageData);
          }
          function ki(t4, e2) {
            if (Si(t4)) return (_i(t4) || I(t4)) && e2 && e2.push(t4), ArrayBuffer.isView(t4) && e2 && e2.push(t4.buffer), t4 instanceof ImageData && e2 && e2.push(t4.data.buffer), t4;
            if (Array.isArray(t4)) {
              const r3 = [];
              for (const n3 of t4) r3.push(ki(n3, e2));
              return r3;
            }
            if ("object" != typeof t4) throw new Error("can't serialize object of type " + typeof t4);
            const r2 = Ai(t4);
            if (!r2) throw new Error(`can't serialize object of unregistered class ${t4.constructor.name}`);
            if (!bi[r2]) throw new Error(`${r2} is not registered.`);
            const { klass: n2 } = bi[r2], i2 = n2.serialize ? n2.serialize(t4, e2) : {};
            if (n2.serialize) {
              if (e2 && i2 === e2[e2.length - 1]) throw new Error("statically serialized object won't survive transfer of $name property");
            } else {
              for (const n3 in t4) {
                if (!t4.hasOwnProperty(n3)) continue;
                if (bi[r2].omit.indexOf(n3) >= 0) continue;
                const s2 = t4[n3];
                i2[n3] = bi[r2].shallow.indexOf(n3) >= 0 ? s2 : ki(s2, e2);
              }
              t4 instanceof Error && (i2.message = t4.message);
            }
            if (i2.$name) throw new Error("$name property is reserved for worker serialization logic.");
            return "Object" !== r2 && (i2.$name = r2), i2;
          }
          function Mi(t4) {
            if (Si(t4)) return t4;
            if (Array.isArray(t4)) return t4.map(Mi);
            if ("object" != typeof t4) throw new Error("can't deserialize object of type " + typeof t4);
            const e2 = Ai(t4) || "Object";
            if (!bi[e2]) throw new Error(`can't deserialize unregistered class ${e2}`);
            const { klass: r2 } = bi[e2];
            if (!r2) throw new Error(`can't deserialize unregistered class ${e2}`);
            if (r2.deserialize) return r2.deserialize(t4);
            const n2 = Object.create(r2.prototype);
            for (const r3 of Object.keys(t4)) {
              if ("$name" === r3) continue;
              const i2 = t4[r3];
              n2[r3] = bi[e2].shallow.indexOf(r3) >= 0 ? i2 : Mi(i2);
            }
            return n2;
          }
          class Ii {
            constructor() {
              this.first = true;
            }
            update(t4, e2) {
              const r2 = Math.floor(t4);
              return this.first ? (this.first = false, this.lastIntegerZoom = r2, this.lastIntegerZoomTime = 0, this.lastZoom = t4, this.lastFloorZoom = r2, true) : (this.lastFloorZoom > r2 ? (this.lastIntegerZoom = r2 + 1, this.lastIntegerZoomTime = e2) : this.lastFloorZoom < r2 && (this.lastIntegerZoom = r2, this.lastIntegerZoomTime = e2), t4 !== this.lastZoom && (this.lastZoom = t4, this.lastFloorZoom = r2, true));
            }
          }
          const zi = { "Latin-1 Supplement": (t4) => t4 >= 128 && t4 <= 255, "Hangul Jamo": (t4) => t4 >= 4352 && t4 <= 4607, Khmer: (t4) => t4 >= 6016 && t4 <= 6143, "General Punctuation": (t4) => t4 >= 8192 && t4 <= 8303, "Letterlike Symbols": (t4) => t4 >= 8448 && t4 <= 8527, "Number Forms": (t4) => t4 >= 8528 && t4 <= 8591, "Miscellaneous Technical": (t4) => t4 >= 8960 && t4 <= 9215, "Control Pictures": (t4) => t4 >= 9216 && t4 <= 9279, "Optical Character Recognition": (t4) => t4 >= 9280 && t4 <= 9311, "Enclosed Alphanumerics": (t4) => t4 >= 9312 && t4 <= 9471, "Geometric Shapes": (t4) => t4 >= 9632 && t4 <= 9727, "Miscellaneous Symbols": (t4) => t4 >= 9728 && t4 <= 9983, "Miscellaneous Symbols and Arrows": (t4) => t4 >= 11008 && t4 <= 11263, "Ideographic Description Characters": (t4) => t4 >= 12272 && t4 <= 12287, "CJK Symbols and Punctuation": (t4) => t4 >= 12288 && t4 <= 12351, Katakana: (t4) => t4 >= 12448 && t4 <= 12543, Kanbun: (t4) => t4 >= 12688 && t4 <= 12703, "CJK Strokes": (t4) => t4 >= 12736 && t4 <= 12783, "Enclosed CJK Letters and Months": (t4) => t4 >= 12800 && t4 <= 13055, "CJK Compatibility": (t4) => t4 >= 13056 && t4 <= 13311, "Yijing Hexagram Symbols": (t4) => t4 >= 19904 && t4 <= 19967, "Private Use Area": (t4) => t4 >= 57344 && t4 <= 63743, "Vertical Forms": (t4) => t4 >= 65040 && t4 <= 65055, "CJK Compatibility Forms": (t4) => t4 >= 65072 && t4 <= 65103, "Small Form Variants": (t4) => t4 >= 65104 && t4 <= 65135, "Halfwidth and Fullwidth Forms": (t4) => t4 >= 65280 && t4 <= 65519 };
          function Pi(t4) {
            for (const e2 of t4) if (Ti(e2.charCodeAt(0))) return true;
            return false;
          }
          function Ci(t4) {
            for (const e2 of t4) if (!Ei(e2.charCodeAt(0))) return false;
            return true;
          }
          function Bi(t4) {
            const e2 = t4.map((t5) => {
              try {
                return new RegExp(`\\p{sc=${t5}}`, "u").source;
              } catch (t6) {
                return null;
              }
            }).filter((t5) => t5);
            return new RegExp(e2.join("|"), "u");
          }
          const Vi = Bi(["Arab", "Dupl", "Mong", "Ougr", "Syrc"]);
          function Ei(t4) {
            return !Vi.test(String.fromCodePoint(t4));
          }
          const Fi = Bi(["Bopo", "Hani", "Hira", "Kana", "Kits", "Nshu", "Tang", "Yiii"]);
          function Ti(t4) {
            return !(746 !== t4 && 747 !== t4 && (t4 < 4352 || !(zi["CJK Compatibility Forms"](t4) && !(t4 >= 65097 && t4 <= 65103) || zi["CJK Compatibility"](t4) || zi["CJK Strokes"](t4) || !(!zi["CJK Symbols and Punctuation"](t4) || t4 >= 12296 && t4 <= 12305 || t4 >= 12308 && t4 <= 12319 || 12336 === t4) || zi["Enclosed CJK Letters and Months"](t4) || zi["Ideographic Description Characters"](t4) || zi.Kanbun(t4) || zi.Katakana(t4) && 12540 !== t4 || !(!zi["Halfwidth and Fullwidth Forms"](t4) || 65288 === t4 || 65289 === t4 || 65293 === t4 || t4 >= 65306 && t4 <= 65310 || 65339 === t4 || 65341 === t4 || 65343 === t4 || t4 >= 65371 && t4 <= 65503 || 65507 === t4 || t4 >= 65512 && t4 <= 65519) || !(!zi["Small Form Variants"](t4) || t4 >= 65112 && t4 <= 65118 || t4 >= 65123 && t4 <= 65126) || zi["Vertical Forms"](t4) || zi["Yijing Hexagram Symbols"](t4) || new RegExp("\\p{sc=Cans}", "u").test(String.fromCodePoint(t4)) || new RegExp("\\p{sc=Hang}", "u").test(String.fromCodePoint(t4)) || Fi.test(String.fromCodePoint(t4)))));
          }
          function $i(t4) {
            return !(Ti(t4) || function(t5) {
              return !!(zi["Latin-1 Supplement"](t5) && (167 === t5 || 169 === t5 || 174 === t5 || 177 === t5 || 188 === t5 || 189 === t5 || 190 === t5 || 215 === t5 || 247 === t5) || zi["General Punctuation"](t5) && (8214 === t5 || 8224 === t5 || 8225 === t5 || 8240 === t5 || 8241 === t5 || 8251 === t5 || 8252 === t5 || 8258 === t5 || 8263 === t5 || 8264 === t5 || 8265 === t5 || 8273 === t5) || zi["Letterlike Symbols"](t5) || zi["Number Forms"](t5) || zi["Miscellaneous Technical"](t5) && (t5 >= 8960 && t5 <= 8967 || t5 >= 8972 && t5 <= 8991 || t5 >= 8996 && t5 <= 9e3 || 9003 === t5 || t5 >= 9085 && t5 <= 9114 || t5 >= 9150 && t5 <= 9165 || 9167 === t5 || t5 >= 9169 && t5 <= 9179 || t5 >= 9186 && t5 <= 9215) || zi["Control Pictures"](t5) && 9251 !== t5 || zi["Optical Character Recognition"](t5) || zi["Enclosed Alphanumerics"](t5) || zi["Geometric Shapes"](t5) || zi["Miscellaneous Symbols"](t5) && !(t5 >= 9754 && t5 <= 9759) || zi["Miscellaneous Symbols and Arrows"](t5) && (t5 >= 11026 && t5 <= 11055 || t5 >= 11088 && t5 <= 11097 || t5 >= 11192 && t5 <= 11243) || zi["CJK Symbols and Punctuation"](t5) || zi.Katakana(t5) || zi["Private Use Area"](t5) || zi["CJK Compatibility Forms"](t5) || zi["Small Form Variants"](t5) || zi["Halfwidth and Fullwidth Forms"](t5) || 8734 === t5 || 8756 === t5 || 8757 === t5 || t5 >= 9984 && t5 <= 10087 || t5 >= 10102 && t5 <= 10131 || 65532 === t5 || 65533 === t5);
            }(t4));
          }
          const Li = Bi(["Adlm", "Arab", "Armi", "Avst", "Chrs", "Cprt", "Egyp", "Elym", "Gara", "Hatr", "Hebr", "Hung", "Khar", "Lydi", "Mand", "Mani", "Mend", "Merc", "Mero", "Narb", "Nbat", "Nkoo", "Orkh", "Palm", "Phli", "Phlp", "Phnx", "Prti", "Rohg", "Samr", "Sarb", "Sogo", "Syrc", "Thaa", "Todr", "Yezi"]);
          function Di(t4) {
            return Li.test(String.fromCodePoint(t4));
          }
          function Oi(t4, e2) {
            return !(!e2 && Di(t4) || t4 >= 2304 && t4 <= 3583 || t4 >= 3840 && t4 <= 4255 || zi.Khmer(t4));
          }
          function ji(t4) {
            for (const e2 of t4) if (Di(e2.charCodeAt(0))) return true;
            return false;
          }
          const Ri = new class {
            constructor() {
              this.applyArabicShaping = null, this.processBidirectionalText = null, this.processStyledBidirectionalText = null, this.pluginStatus = "unavailable", this.pluginURL = null;
            }
            setState(t4) {
              this.pluginStatus = t4.pluginStatus, this.pluginURL = t4.pluginURL;
            }
            getState() {
              return { pluginStatus: this.pluginStatus, pluginURL: this.pluginURL };
            }
            setMethods(t4) {
              this.applyArabicShaping = t4.applyArabicShaping, this.processBidirectionalText = t4.processBidirectionalText, this.processStyledBidirectionalText = t4.processStyledBidirectionalText;
            }
            isParsed() {
              return null != this.applyArabicShaping && null != this.processBidirectionalText && null != this.processStyledBidirectionalText;
            }
            getPluginURL() {
              return this.pluginURL;
            }
            getRTLTextPluginStatus() {
              return this.pluginStatus;
            }
          }();
          class Ui {
            constructor(t4, e2) {
              this.zoom = t4, e2 ? (this.now = e2.now, this.fadeDuration = e2.fadeDuration, this.zoomHistory = e2.zoomHistory, this.transition = e2.transition) : (this.now = 0, this.fadeDuration = 0, this.zoomHistory = new Ii(), this.transition = {});
            }
            isSupportedScript(t4) {
              return function(t5, e2) {
                for (const r2 of t5) if (!Oi(r2.charCodeAt(0), e2)) return false;
                return true;
              }(t4, "loaded" === Ri.getRTLTextPluginStatus());
            }
            crossFadingFactor() {
              return 0 === this.fadeDuration ? 1 : Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1);
            }
            getCrossfadeParameters() {
              const t4 = this.zoom, e2 = t4 - Math.floor(t4), r2 = this.crossFadingFactor();
              return t4 > this.zoomHistory.lastIntegerZoom ? { fromScale: 2, toScale: 1, t: e2 + (1 - e2) * r2 } : { fromScale: 0.5, toScale: 1, t: 1 - (1 - r2) * e2 };
            }
          }
          class qi {
            constructor(t4, e2) {
              this.property = t4, this.value = e2, this.expression = function(t5, e3) {
                if (cn(t5)) return new Sn(t5, e3);
                if (vn(t5)) {
                  const r2 = An(t5, e3);
                  if ("error" === r2.result) throw new Error(r2.value.map((t6) => `${t6.key}: ${t6.message}`).join(", "));
                  return r2.value;
                }
                {
                  let r2 = t5;
                  return "color" === e3.type && "string" == typeof t5 ? r2 = Kt.parse(t5) : "padding" !== e3.type || "number" != typeof t5 && !Array.isArray(t5) ? "variableAnchorOffsetCollection" === e3.type && Array.isArray(t5) && (r2 = Qt.parse(t5)) : r2 = Jt.parse(t5), { kind: "constant", evaluate: () => r2 };
                }
              }(void 0 === e2 ? t4.specification.default : e2, t4.specification);
            }
            isDataDriven() {
              return "source" === this.expression.kind || "composite" === this.expression.kind;
            }
            possiblyEvaluate(t4, e2, r2) {
              return this.property.possiblyEvaluate(this, t4, e2, r2);
            }
          }
          class Ni {
            constructor(t4) {
              this.property = t4, this.value = new qi(t4, void 0);
            }
            transitioned(t4, e2) {
              return new Gi(this.property, this.value, e2, g({}, t4.transition, this.transition), t4.now);
            }
            untransitioned() {
              return new Gi(this.property, this.value, null, {}, 0);
            }
          }
          class Zi {
            constructor(t4) {
              this._properties = t4, this._values = Object.create(t4.defaultTransitionablePropertyValues);
            }
            getValue(t4) {
              return w(this._values[t4].value.value);
            }
            setValue(t4, e2) {
              Object.prototype.hasOwnProperty.call(this._values, t4) || (this._values[t4] = new Ni(this._values[t4].property)), this._values[t4].value = new qi(this._values[t4].property, null === e2 ? void 0 : w(e2));
            }
            getTransition(t4) {
              return w(this._values[t4].transition);
            }
            setTransition(t4, e2) {
              Object.prototype.hasOwnProperty.call(this._values, t4) || (this._values[t4] = new Ni(this._values[t4].property)), this._values[t4].transition = w(e2) || void 0;
            }
            serialize() {
              const t4 = {};
              for (const e2 of Object.keys(this._values)) {
                const r2 = this.getValue(e2);
                void 0 !== r2 && (t4[e2] = r2);
                const n2 = this.getTransition(e2);
                void 0 !== n2 && (t4[`${e2}-transition`] = n2);
              }
              return t4;
            }
            transitioned(t4, e2) {
              const r2 = new Ki(this._properties);
              for (const n2 of Object.keys(this._values)) r2._values[n2] = this._values[n2].transitioned(t4, e2._values[n2]);
              return r2;
            }
            untransitioned() {
              const t4 = new Ki(this._properties);
              for (const e2 of Object.keys(this._values)) t4._values[e2] = this._values[e2].untransitioned();
              return t4;
            }
          }
          class Gi {
            constructor(t4, e2, r2, n2, i2) {
              this.property = t4, this.value = e2, this.begin = i2 + n2.delay || 0, this.end = this.begin + n2.duration || 0, t4.specification.transition && (n2.delay || n2.duration) && (this.prior = r2);
            }
            possiblyEvaluate(t4, e2, r2) {
              const n2 = t4.now || 0, i2 = this.value.possiblyEvaluate(t4, e2, r2), s2 = this.prior;
              if (s2) {
                if (n2 > this.end) return this.prior = null, i2;
                if (this.value.isDataDriven()) return this.prior = null, i2;
                if (n2 < this.begin) return s2.possiblyEvaluate(t4, e2, r2);
                {
                  const a2 = (n2 - this.begin) / (this.end - this.begin);
                  return this.property.interpolate(s2.possiblyEvaluate(t4, e2, r2), i2, function(t5) {
                    if (t5 <= 0) return 0;
                    if (t5 >= 1) return 1;
                    const e3 = t5 * t5, r3 = e3 * t5;
                    return 4 * (t5 < 0.5 ? r3 : 3 * (t5 - e3) + r3 - 0.75);
                  }(a2));
                }
              }
              return i2;
            }
          }
          class Ki {
            constructor(t4) {
              this._properties = t4, this._values = Object.create(t4.defaultTransitioningPropertyValues);
            }
            possiblyEvaluate(t4, e2, r2) {
              const n2 = new Yi(this._properties);
              for (const i2 of Object.keys(this._values)) n2._values[i2] = this._values[i2].possiblyEvaluate(t4, e2, r2);
              return n2;
            }
            hasTransition() {
              for (const t4 of Object.keys(this._values)) if (this._values[t4].prior) return true;
              return false;
            }
          }
          class Xi {
            constructor(t4) {
              this._properties = t4, this._values = Object.create(t4.defaultPropertyValues);
            }
            hasValue(t4) {
              return void 0 !== this._values[t4].value;
            }
            getValue(t4) {
              return w(this._values[t4].value);
            }
            setValue(t4, e2) {
              this._values[t4] = new qi(this._values[t4].property, null === e2 ? void 0 : w(e2));
            }
            serialize() {
              const t4 = {};
              for (const e2 of Object.keys(this._values)) {
                const r2 = this.getValue(e2);
                void 0 !== r2 && (t4[e2] = r2);
              }
              return t4;
            }
            possiblyEvaluate(t4, e2, r2) {
              const n2 = new Yi(this._properties);
              for (const i2 of Object.keys(this._values)) n2._values[i2] = this._values[i2].possiblyEvaluate(t4, e2, r2);
              return n2;
            }
          }
          class Hi {
            constructor(t4, e2, r2) {
              this.property = t4, this.value = e2, this.parameters = r2;
            }
            isConstant() {
              return "constant" === this.value.kind;
            }
            constantOr(t4) {
              return "constant" === this.value.kind ? this.value.value : t4;
            }
            evaluate(t4, e2, r2, n2) {
              return this.property.evaluate(this.value, this.parameters, t4, e2, r2, n2);
            }
          }
          class Yi {
            constructor(t4) {
              this._properties = t4, this._values = Object.create(t4.defaultPossiblyEvaluatedValues);
            }
            get(t4) {
              return this._values[t4];
            }
          }
          class Ji {
            constructor(t4) {
              this.specification = t4;
            }
            possiblyEvaluate(t4, e2) {
              if (t4.isDataDriven()) throw new Error("Value should not be data driven");
              return t4.expression.evaluate(e2);
            }
            interpolate(t4, e2, r2) {
              const n2 = Ce[this.specification.type];
              return n2 ? n2(t4, e2, r2) : t4;
            }
          }
          class Wi {
            constructor(t4, e2) {
              this.specification = t4, this.overrides = e2;
            }
            possiblyEvaluate(t4, e2, r2, n2) {
              return new Hi(this, "constant" === t4.expression.kind || "camera" === t4.expression.kind ? { kind: "constant", value: t4.expression.evaluate(e2, null, {}, r2, n2) } : t4.expression, e2);
            }
            interpolate(t4, e2, r2) {
              if ("constant" !== t4.value.kind || "constant" !== e2.value.kind) return t4;
              if (void 0 === t4.value.value || void 0 === e2.value.value) return new Hi(this, { kind: "constant", value: void 0 }, t4.parameters);
              const n2 = Ce[this.specification.type];
              if (n2) {
                const i2 = n2(t4.value.value, e2.value.value, r2);
                return new Hi(this, { kind: "constant", value: i2 }, t4.parameters);
              }
              return t4;
            }
            evaluate(t4, e2, r2, n2, i2, s2) {
              return "constant" === t4.kind ? t4.value : t4.evaluate(e2, r2, n2, i2, s2);
            }
          }
          class Qi extends Wi {
            possiblyEvaluate(t4, e2, r2, n2) {
              if (void 0 === t4.value) return new Hi(this, { kind: "constant", value: void 0 }, e2);
              if ("constant" === t4.expression.kind) {
                const i2 = t4.expression.evaluate(e2, null, {}, r2, n2), s2 = "resolvedImage" === t4.property.specification.type && "string" != typeof i2 ? i2.name : i2, a2 = this._calculate(s2, s2, s2, e2);
                return new Hi(this, { kind: "constant", value: a2 }, e2);
              }
              if ("camera" === t4.expression.kind) {
                const r3 = this._calculate(t4.expression.evaluate({ zoom: e2.zoom - 1 }), t4.expression.evaluate({ zoom: e2.zoom }), t4.expression.evaluate({ zoom: e2.zoom + 1 }), e2);
                return new Hi(this, { kind: "constant", value: r3 }, e2);
              }
              return new Hi(this, t4.expression, e2);
            }
            evaluate(t4, e2, r2, n2, i2, s2) {
              if ("source" === t4.kind) {
                const a2 = t4.evaluate(e2, r2, n2, i2, s2);
                return this._calculate(a2, a2, a2, e2);
              }
              return "composite" === t4.kind ? this._calculate(t4.evaluate({ zoom: Math.floor(e2.zoom) - 1 }, r2, n2), t4.evaluate({ zoom: Math.floor(e2.zoom) }, r2, n2), t4.evaluate({ zoom: Math.floor(e2.zoom) + 1 }, r2, n2), e2) : t4.value;
            }
            _calculate(t4, e2, r2, n2) {
              return n2.zoom > n2.zoomHistory.lastIntegerZoom ? { from: t4, to: e2 } : { from: r2, to: e2 };
            }
            interpolate(t4) {
              return t4;
            }
          }
          class ts {
            constructor(t4) {
              this.specification = t4;
            }
            possiblyEvaluate(t4, e2, r2, n2) {
              if (void 0 !== t4.value) {
                if ("constant" === t4.expression.kind) {
                  const i2 = t4.expression.evaluate(e2, null, {}, r2, n2);
                  return this._calculate(i2, i2, i2, e2);
                }
                return this._calculate(t4.expression.evaluate(new Ui(Math.floor(e2.zoom - 1), e2)), t4.expression.evaluate(new Ui(Math.floor(e2.zoom), e2)), t4.expression.evaluate(new Ui(Math.floor(e2.zoom + 1), e2)), e2);
              }
            }
            _calculate(t4, e2, r2, n2) {
              return n2.zoom > n2.zoomHistory.lastIntegerZoom ? { from: t4, to: e2 } : { from: r2, to: e2 };
            }
            interpolate(t4) {
              return t4;
            }
          }
          class es {
            constructor(t4) {
              this.specification = t4;
            }
            possiblyEvaluate(t4, e2, r2, n2) {
              return !!t4.expression.evaluate(e2, null, {}, r2, n2);
            }
            interpolate() {
              return false;
            }
          }
          class rs {
            constructor(t4) {
              this.properties = t4, this.defaultPropertyValues = {}, this.defaultTransitionablePropertyValues = {}, this.defaultTransitioningPropertyValues = {}, this.defaultPossiblyEvaluatedValues = {}, this.overridableProperties = [];
              for (const e2 in t4) {
                const r2 = t4[e2];
                r2.specification.overridable && this.overridableProperties.push(e2);
                const n2 = this.defaultPropertyValues[e2] = new qi(r2, void 0), i2 = this.defaultTransitionablePropertyValues[e2] = new Ni(r2);
                this.defaultTransitioningPropertyValues[e2] = i2.untransitioned(), this.defaultPossiblyEvaluatedValues[e2] = n2.possiblyEvaluate({});
              }
            }
          }
          wi("DataDrivenProperty", Wi), wi("DataConstantProperty", Ji), wi("CrossFadedDataDrivenProperty", Qi), wi("CrossFadedProperty", ts), wi("ColorRampProperty", es);
          const ns = "-transition";
          class is extends Z {
            constructor(t4, e2) {
              if (super(), this.id = t4.id, this.type = t4.type, this._featureFilter = { filter: () => true, needGeometry: false }, "custom" !== t4.type && (this.metadata = t4.metadata, this.minzoom = t4.minzoom, this.maxzoom = t4.maxzoom, "background" !== t4.type && (this.source = t4.source, this.sourceLayer = t4["source-layer"], this.filter = t4.filter), e2.layout && (this._unevaluatedLayout = new Xi(e2.layout)), e2.paint)) {
                this._transitionablePaint = new Zi(e2.paint);
                for (const e3 in t4.paint) this.setPaintProperty(e3, t4.paint[e3], { validate: false });
                for (const e3 in t4.layout) this.setLayoutProperty(e3, t4.layout[e3], { validate: false });
                this._transitioningPaint = this._transitionablePaint.untransitioned(), this.paint = new Yi(e2.paint);
              }
            }
            getCrossfadeParameters() {
              return this._crossfadeParameters;
            }
            getLayoutProperty(t4) {
              return "visibility" === t4 ? this.visibility : this._unevaluatedLayout.getValue(t4);
            }
            setLayoutProperty(t4, e2, r2 = {}) {
              null != e2 && this._validate(gi, `layers.${this.id}.layout.${t4}`, t4, e2, r2) || ("visibility" !== t4 ? this._unevaluatedLayout.setValue(t4, e2) : this.visibility = e2);
            }
            getPaintProperty(t4) {
              return t4.endsWith(ns) ? this._transitionablePaint.getTransition(t4.slice(0, -11)) : this._transitionablePaint.getValue(t4);
            }
            setPaintProperty(t4, e2, r2 = {}) {
              if (null != e2 && this._validate(mi, `layers.${this.id}.paint.${t4}`, t4, e2, r2)) return false;
              if (t4.endsWith(ns)) return this._transitionablePaint.setTransition(t4.slice(0, -11), e2 || void 0), false;
              {
                const r3 = this._transitionablePaint._values[t4], n2 = "cross-faded-data-driven" === r3.property.specification["property-type"], i2 = r3.value.isDataDriven(), s2 = r3.value;
                this._transitionablePaint.setValue(t4, e2), this._handleSpecialPaintPropertyUpdate(t4);
                const a2 = this._transitionablePaint._values[t4].value;
                return a2.isDataDriven() || i2 || n2 || this._handleOverridablePaintPropertyUpdate(t4, s2, a2);
              }
            }
            _handleSpecialPaintPropertyUpdate(t4) {
            }
            _handleOverridablePaintPropertyUpdate(t4, e2, r2) {
              return false;
            }
            isHidden(t4) {
              return !!(this.minzoom && t4 < this.minzoom) || !!(this.maxzoom && t4 >= this.maxzoom) || "none" === this.visibility;
            }
            updateTransitions(t4) {
              this._transitioningPaint = this._transitionablePaint.transitioned(t4, this._transitioningPaint);
            }
            hasTransition() {
              return this._transitioningPaint.hasTransition();
            }
            recalculate(t4, e2) {
              t4.getCrossfadeParameters && (this._crossfadeParameters = t4.getCrossfadeParameters()), this._unevaluatedLayout && (this.layout = this._unevaluatedLayout.possiblyEvaluate(t4, void 0, e2)), this.paint = this._transitioningPaint.possiblyEvaluate(t4, void 0, e2);
            }
            serialize() {
              const t4 = { id: this.id, type: this.type, source: this.source, "source-layer": this.sourceLayer, metadata: this.metadata, minzoom: this.minzoom, maxzoom: this.maxzoom, filter: this.filter, layout: this._unevaluatedLayout && this._unevaluatedLayout.serialize(), paint: this._transitionablePaint && this._transitionablePaint.serialize() };
              return this.visibility && (t4.layout = t4.layout || {}, t4.layout.visibility = this.visibility), b(t4, (t5, e2) => !(void 0 === t5 || "layout" === e2 && !Object.keys(t5).length || "paint" === e2 && !Object.keys(t5).length));
            }
            _validate(t4, e2, r2, n2, i2 = {}) {
              return (!i2 || false !== i2.validate) && xi(this, t4.call(fi, { key: e2, layerType: this.type, objectKey: r2, value: n2, styleSpec: G, style: { glyphs: true, sprite: true } }));
            }
            is3D() {
              return false;
            }
            isTileClipped() {
              return false;
            }
            hasOffscreenPass() {
              return false;
            }
            resize() {
            }
            isStateDependent() {
              for (const t4 in this.paint._values) {
                const e2 = this.paint.get(t4);
                if (e2 instanceof Hi && an(e2.property.specification) && ("source" === e2.value.kind || "composite" === e2.value.kind) && e2.value.isStateDependent) return true;
              }
              return false;
            }
          }
          const ss = { Int8: Int8Array, Uint8: Uint8Array, Int16: Int16Array, Uint16: Uint16Array, Int32: Int32Array, Uint32: Uint32Array, Float32: Float32Array };
          class as {
            constructor(t4, e2) {
              this._structArray = t4, this._pos1 = e2 * this.size, this._pos2 = this._pos1 / 2, this._pos4 = this._pos1 / 4, this._pos8 = this._pos1 / 8;
            }
          }
          class os {
            constructor() {
              this.isTransferred = false, this.capacity = -1, this.resize(0);
            }
            static serialize(t4, e2) {
              return t4._trim(), e2 && (t4.isTransferred = true, e2.push(t4.arrayBuffer)), { length: t4.length, arrayBuffer: t4.arrayBuffer };
            }
            static deserialize(t4) {
              const e2 = Object.create(this.prototype);
              return e2.arrayBuffer = t4.arrayBuffer, e2.length = t4.length, e2.capacity = t4.arrayBuffer.byteLength / e2.bytesPerElement, e2._refreshViews(), e2;
            }
            _trim() {
              this.length !== this.capacity && (this.capacity = this.length, this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement), this._refreshViews());
            }
            clear() {
              this.length = 0;
            }
            resize(t4) {
              this.reserve(t4), this.length = t4;
            }
            reserve(t4) {
              if (t4 > this.capacity) {
                this.capacity = Math.max(t4, Math.floor(5 * this.capacity), 128), this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);
                const e2 = this.uint8;
                this._refreshViews(), e2 && this.uint8.set(e2);
              }
            }
            _refreshViews() {
              throw new Error("_refreshViews() must be implemented by each concrete StructArray layout");
            }
          }
          function ls(t4, e2 = 1) {
            let r2 = 0, n2 = 0;
            return { members: t4.map((t5) => {
              const i2 = ss[t5.type].BYTES_PER_ELEMENT, s2 = r2 = us(r2, Math.max(e2, i2)), a2 = t5.components || 1;
              return n2 = Math.max(n2, i2), r2 += i2 * a2, { name: t5.name, type: t5.type, components: a2, offset: s2 };
            }), size: us(r2, Math.max(n2, e2)), alignment: e2 };
          }
          function us(t4, e2) {
            return Math.ceil(t4 / e2) * e2;
          }
          class cs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2) {
              const r2 = this.length;
              return this.resize(r2 + 1), this.emplace(r2, t4, e2);
            }
            emplace(t4, e2, r2) {
              const n2 = 2 * t4;
              return this.int16[n2 + 0] = e2, this.int16[n2 + 1] = r2, t4;
            }
          }
          cs.prototype.bytesPerElement = 4, wi("StructArrayLayout2i4", cs);
          class hs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2) {
              const n2 = this.length;
              return this.resize(n2 + 1), this.emplace(n2, t4, e2, r2);
            }
            emplace(t4, e2, r2, n2) {
              const i2 = 3 * t4;
              return this.int16[i2 + 0] = e2, this.int16[i2 + 1] = r2, this.int16[i2 + 2] = n2, t4;
            }
          }
          hs.prototype.bytesPerElement = 6, wi("StructArrayLayout3i6", hs);
          class ps extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2) {
              const i2 = this.length;
              return this.resize(i2 + 1), this.emplace(i2, t4, e2, r2, n2);
            }
            emplace(t4, e2, r2, n2, i2) {
              const s2 = 4 * t4;
              return this.int16[s2 + 0] = e2, this.int16[s2 + 1] = r2, this.int16[s2 + 2] = n2, this.int16[s2 + 3] = i2, t4;
            }
          }
          ps.prototype.bytesPerElement = 8, wi("StructArrayLayout4i8", ps);
          class fs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2) {
              const a2 = this.length;
              return this.resize(a2 + 1), this.emplace(a2, t4, e2, r2, n2, i2, s2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2) {
              const o2 = 6 * t4;
              return this.int16[o2 + 0] = e2, this.int16[o2 + 1] = r2, this.int16[o2 + 2] = n2, this.int16[o2 + 3] = i2, this.int16[o2 + 4] = s2, this.int16[o2 + 5] = a2, t4;
            }
          }
          fs.prototype.bytesPerElement = 12, wi("StructArrayLayout2i4i12", fs);
          class ds extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2) {
              const a2 = this.length;
              return this.resize(a2 + 1), this.emplace(a2, t4, e2, r2, n2, i2, s2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2) {
              const o2 = 4 * t4, l2 = 8 * t4;
              return this.int16[o2 + 0] = e2, this.int16[o2 + 1] = r2, this.uint8[l2 + 4] = n2, this.uint8[l2 + 5] = i2, this.uint8[l2 + 6] = s2, this.uint8[l2 + 7] = a2, t4;
            }
          }
          ds.prototype.bytesPerElement = 8, wi("StructArrayLayout2i4ub8", ds);
          class ys extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2) {
              const r2 = this.length;
              return this.resize(r2 + 1), this.emplace(r2, t4, e2);
            }
            emplace(t4, e2, r2) {
              const n2 = 2 * t4;
              return this.float32[n2 + 0] = e2, this.float32[n2 + 1] = r2, t4;
            }
          }
          ys.prototype.bytesPerElement = 8, wi("StructArrayLayout2f8", ys);
          class ms extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2) {
              const c2 = this.length;
              return this.resize(c2 + 1), this.emplace(c2, t4, e2, r2, n2, i2, s2, a2, o2, l2, u2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2) {
              const h2 = 10 * t4;
              return this.uint16[h2 + 0] = e2, this.uint16[h2 + 1] = r2, this.uint16[h2 + 2] = n2, this.uint16[h2 + 3] = i2, this.uint16[h2 + 4] = s2, this.uint16[h2 + 5] = a2, this.uint16[h2 + 6] = o2, this.uint16[h2 + 7] = l2, this.uint16[h2 + 8] = u2, this.uint16[h2 + 9] = c2, t4;
            }
          }
          ms.prototype.bytesPerElement = 20, wi("StructArrayLayout10ui20", ms);
          class gs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2) {
              const p2 = this.length;
              return this.resize(p2 + 1), this.emplace(p2, t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2) {
              const f2 = 12 * t4;
              return this.int16[f2 + 0] = e2, this.int16[f2 + 1] = r2, this.int16[f2 + 2] = n2, this.int16[f2 + 3] = i2, this.uint16[f2 + 4] = s2, this.uint16[f2 + 5] = a2, this.uint16[f2 + 6] = o2, this.uint16[f2 + 7] = l2, this.int16[f2 + 8] = u2, this.int16[f2 + 9] = c2, this.int16[f2 + 10] = h2, this.int16[f2 + 11] = p2, t4;
            }
          }
          gs.prototype.bytesPerElement = 24, wi("StructArrayLayout4i4ui4i24", gs);
          class xs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2) {
              const n2 = this.length;
              return this.resize(n2 + 1), this.emplace(n2, t4, e2, r2);
            }
            emplace(t4, e2, r2, n2) {
              const i2 = 3 * t4;
              return this.float32[i2 + 0] = e2, this.float32[i2 + 1] = r2, this.float32[i2 + 2] = n2, t4;
            }
          }
          xs.prototype.bytesPerElement = 12, wi("StructArrayLayout3f12", xs);
          class vs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer);
            }
            emplaceBack(t4) {
              const e2 = this.length;
              return this.resize(e2 + 1), this.emplace(e2, t4);
            }
            emplace(t4, e2) {
              return this.uint32[1 * t4 + 0] = e2, t4;
            }
          }
          vs.prototype.bytesPerElement = 4, wi("StructArrayLayout1ul4", vs);
          class bs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2, a2, o2, l2) {
              const u2 = this.length;
              return this.resize(u2 + 1), this.emplace(u2, t4, e2, r2, n2, i2, s2, a2, o2, l2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2) {
              const c2 = 10 * t4, h2 = 5 * t4;
              return this.int16[c2 + 0] = e2, this.int16[c2 + 1] = r2, this.int16[c2 + 2] = n2, this.int16[c2 + 3] = i2, this.int16[c2 + 4] = s2, this.int16[c2 + 5] = a2, this.uint32[h2 + 3] = o2, this.uint16[c2 + 8] = l2, this.uint16[c2 + 9] = u2, t4;
            }
          }
          bs.prototype.bytesPerElement = 20, wi("StructArrayLayout6i1ul2ui20", bs);
          class ws extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2) {
              const a2 = this.length;
              return this.resize(a2 + 1), this.emplace(a2, t4, e2, r2, n2, i2, s2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2) {
              const o2 = 6 * t4;
              return this.int16[o2 + 0] = e2, this.int16[o2 + 1] = r2, this.int16[o2 + 2] = n2, this.int16[o2 + 3] = i2, this.int16[o2 + 4] = s2, this.int16[o2 + 5] = a2, t4;
            }
          }
          ws.prototype.bytesPerElement = 12, wi("StructArrayLayout2i2i2i12", ws);
          class _s extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2) {
              const s2 = this.length;
              return this.resize(s2 + 1), this.emplace(s2, t4, e2, r2, n2, i2);
            }
            emplace(t4, e2, r2, n2, i2, s2) {
              const a2 = 4 * t4, o2 = 8 * t4;
              return this.float32[a2 + 0] = e2, this.float32[a2 + 1] = r2, this.float32[a2 + 2] = n2, this.int16[o2 + 6] = i2, this.int16[o2 + 7] = s2, t4;
            }
          }
          _s.prototype.bytesPerElement = 16, wi("StructArrayLayout2f1f2i16", _s);
          class As extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2) {
              const a2 = this.length;
              return this.resize(a2 + 1), this.emplace(a2, t4, e2, r2, n2, i2, s2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2) {
              const o2 = 16 * t4, l2 = 4 * t4, u2 = 8 * t4;
              return this.uint8[o2 + 0] = e2, this.uint8[o2 + 1] = r2, this.float32[l2 + 1] = n2, this.float32[l2 + 2] = i2, this.int16[u2 + 6] = s2, this.int16[u2 + 7] = a2, t4;
            }
          }
          As.prototype.bytesPerElement = 16, wi("StructArrayLayout2ub2f2i16", As);
          class Ss extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2) {
              const n2 = this.length;
              return this.resize(n2 + 1), this.emplace(n2, t4, e2, r2);
            }
            emplace(t4, e2, r2, n2) {
              const i2 = 3 * t4;
              return this.uint16[i2 + 0] = e2, this.uint16[i2 + 1] = r2, this.uint16[i2 + 2] = n2, t4;
            }
          }
          Ss.prototype.bytesPerElement = 6, wi("StructArrayLayout3ui6", Ss);
          class ks extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2, m2) {
              const g2 = this.length;
              return this.resize(g2 + 1), this.emplace(g2, t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2, m2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2, m2, g2) {
              const x2 = 24 * t4, v2 = 12 * t4, b2 = 48 * t4;
              return this.int16[x2 + 0] = e2, this.int16[x2 + 1] = r2, this.uint16[x2 + 2] = n2, this.uint16[x2 + 3] = i2, this.uint32[v2 + 2] = s2, this.uint32[v2 + 3] = a2, this.uint32[v2 + 4] = o2, this.uint16[x2 + 10] = l2, this.uint16[x2 + 11] = u2, this.uint16[x2 + 12] = c2, this.float32[v2 + 7] = h2, this.float32[v2 + 8] = p2, this.uint8[b2 + 36] = f2, this.uint8[b2 + 37] = d2, this.uint8[b2 + 38] = y2, this.uint32[v2 + 10] = m2, this.int16[x2 + 22] = g2, t4;
            }
          }
          ks.prototype.bytesPerElement = 48, wi("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48", ks);
          class Ms extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2, m2, g2, x2, v2, b2, w2, _2, A3, S2, k2, M2, I2) {
              const z2 = this.length;
              return this.resize(z2 + 1), this.emplace(z2, t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2, m2, g2, x2, v2, b2, w2, _2, A3, S2, k2, M2, I2);
            }
            emplace(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2, m2, g2, x2, v2, b2, w2, _2, A3, S2, k2, M2, I2, z2) {
              const P2 = 32 * t4, C3 = 16 * t4;
              return this.int16[P2 + 0] = e2, this.int16[P2 + 1] = r2, this.int16[P2 + 2] = n2, this.int16[P2 + 3] = i2, this.int16[P2 + 4] = s2, this.int16[P2 + 5] = a2, this.int16[P2 + 6] = o2, this.int16[P2 + 7] = l2, this.uint16[P2 + 8] = u2, this.uint16[P2 + 9] = c2, this.uint16[P2 + 10] = h2, this.uint16[P2 + 11] = p2, this.uint16[P2 + 12] = f2, this.uint16[P2 + 13] = d2, this.uint16[P2 + 14] = y2, this.uint16[P2 + 15] = m2, this.uint16[P2 + 16] = g2, this.uint16[P2 + 17] = x2, this.uint16[P2 + 18] = v2, this.uint16[P2 + 19] = b2, this.uint16[P2 + 20] = w2, this.uint16[P2 + 21] = _2, this.uint16[P2 + 22] = A3, this.uint32[C3 + 12] = S2, this.float32[C3 + 13] = k2, this.float32[C3 + 14] = M2, this.uint16[P2 + 30] = I2, this.uint16[P2 + 31] = z2, t4;
            }
          }
          Ms.prototype.bytesPerElement = 64, wi("StructArrayLayout8i15ui1ul2f2ui64", Ms);
          class Is extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
            }
            emplaceBack(t4) {
              const e2 = this.length;
              return this.resize(e2 + 1), this.emplace(e2, t4);
            }
            emplace(t4, e2) {
              return this.float32[1 * t4 + 0] = e2, t4;
            }
          }
          Is.prototype.bytesPerElement = 4, wi("StructArrayLayout1f4", Is);
          class zs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2) {
              const n2 = this.length;
              return this.resize(n2 + 1), this.emplace(n2, t4, e2, r2);
            }
            emplace(t4, e2, r2, n2) {
              const i2 = 3 * t4;
              return this.uint16[6 * t4 + 0] = e2, this.float32[i2 + 1] = r2, this.float32[i2 + 2] = n2, t4;
            }
          }
          zs.prototype.bytesPerElement = 12, wi("StructArrayLayout1ui2f12", zs);
          class Ps extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2) {
              const n2 = this.length;
              return this.resize(n2 + 1), this.emplace(n2, t4, e2, r2);
            }
            emplace(t4, e2, r2, n2) {
              const i2 = 4 * t4;
              return this.uint32[2 * t4 + 0] = e2, this.uint16[i2 + 2] = r2, this.uint16[i2 + 3] = n2, t4;
            }
          }
          Ps.prototype.bytesPerElement = 8, wi("StructArrayLayout1ul2ui8", Ps);
          class Cs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2) {
              const r2 = this.length;
              return this.resize(r2 + 1), this.emplace(r2, t4, e2);
            }
            emplace(t4, e2, r2) {
              const n2 = 2 * t4;
              return this.uint16[n2 + 0] = e2, this.uint16[n2 + 1] = r2, t4;
            }
          }
          Cs.prototype.bytesPerElement = 4, wi("StructArrayLayout2ui4", Cs);
          class Bs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
            }
            emplaceBack(t4) {
              const e2 = this.length;
              return this.resize(e2 + 1), this.emplace(e2, t4);
            }
            emplace(t4, e2) {
              return this.uint16[1 * t4 + 0] = e2, t4;
            }
          }
          Bs.prototype.bytesPerElement = 2, wi("StructArrayLayout1ui2", Bs);
          class Vs extends os {
            _refreshViews() {
              this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
            }
            emplaceBack(t4, e2, r2, n2) {
              const i2 = this.length;
              return this.resize(i2 + 1), this.emplace(i2, t4, e2, r2, n2);
            }
            emplace(t4, e2, r2, n2, i2) {
              const s2 = 4 * t4;
              return this.float32[s2 + 0] = e2, this.float32[s2 + 1] = r2, this.float32[s2 + 2] = n2, this.float32[s2 + 3] = i2, t4;
            }
          }
          Vs.prototype.bytesPerElement = 16, wi("StructArrayLayout4f16", Vs);
          class Es extends as {
            get anchorPointX() {
              return this._structArray.int16[this._pos2 + 0];
            }
            get anchorPointY() {
              return this._structArray.int16[this._pos2 + 1];
            }
            get x1() {
              return this._structArray.int16[this._pos2 + 2];
            }
            get y1() {
              return this._structArray.int16[this._pos2 + 3];
            }
            get x2() {
              return this._structArray.int16[this._pos2 + 4];
            }
            get y2() {
              return this._structArray.int16[this._pos2 + 5];
            }
            get featureIndex() {
              return this._structArray.uint32[this._pos4 + 3];
            }
            get sourceLayerIndex() {
              return this._structArray.uint16[this._pos2 + 8];
            }
            get bucketIndex() {
              return this._structArray.uint16[this._pos2 + 9];
            }
            get anchorPoint() {
              return new s(this.anchorPointX, this.anchorPointY);
            }
          }
          Es.prototype.size = 20;
          class Fs extends bs {
            get(t4) {
              return new Es(this, t4);
            }
          }
          wi("CollisionBoxArray", Fs);
          class Ts extends as {
            get anchorX() {
              return this._structArray.int16[this._pos2 + 0];
            }
            get anchorY() {
              return this._structArray.int16[this._pos2 + 1];
            }
            get glyphStartIndex() {
              return this._structArray.uint16[this._pos2 + 2];
            }
            get numGlyphs() {
              return this._structArray.uint16[this._pos2 + 3];
            }
            get vertexStartIndex() {
              return this._structArray.uint32[this._pos4 + 2];
            }
            get lineStartIndex() {
              return this._structArray.uint32[this._pos4 + 3];
            }
            get lineLength() {
              return this._structArray.uint32[this._pos4 + 4];
            }
            get segment() {
              return this._structArray.uint16[this._pos2 + 10];
            }
            get lowerSize() {
              return this._structArray.uint16[this._pos2 + 11];
            }
            get upperSize() {
              return this._structArray.uint16[this._pos2 + 12];
            }
            get lineOffsetX() {
              return this._structArray.float32[this._pos4 + 7];
            }
            get lineOffsetY() {
              return this._structArray.float32[this._pos4 + 8];
            }
            get writingMode() {
              return this._structArray.uint8[this._pos1 + 36];
            }
            get placedOrientation() {
              return this._structArray.uint8[this._pos1 + 37];
            }
            set placedOrientation(t4) {
              this._structArray.uint8[this._pos1 + 37] = t4;
            }
            get hidden() {
              return this._structArray.uint8[this._pos1 + 38];
            }
            set hidden(t4) {
              this._structArray.uint8[this._pos1 + 38] = t4;
            }
            get crossTileID() {
              return this._structArray.uint32[this._pos4 + 10];
            }
            set crossTileID(t4) {
              this._structArray.uint32[this._pos4 + 10] = t4;
            }
            get associatedIconIndex() {
              return this._structArray.int16[this._pos2 + 22];
            }
          }
          Ts.prototype.size = 48;
          class $s extends ks {
            get(t4) {
              return new Ts(this, t4);
            }
          }
          wi("PlacedSymbolArray", $s);
          class Ls extends as {
            get anchorX() {
              return this._structArray.int16[this._pos2 + 0];
            }
            get anchorY() {
              return this._structArray.int16[this._pos2 + 1];
            }
            get rightJustifiedTextSymbolIndex() {
              return this._structArray.int16[this._pos2 + 2];
            }
            get centerJustifiedTextSymbolIndex() {
              return this._structArray.int16[this._pos2 + 3];
            }
            get leftJustifiedTextSymbolIndex() {
              return this._structArray.int16[this._pos2 + 4];
            }
            get verticalPlacedTextSymbolIndex() {
              return this._structArray.int16[this._pos2 + 5];
            }
            get placedIconSymbolIndex() {
              return this._structArray.int16[this._pos2 + 6];
            }
            get verticalPlacedIconSymbolIndex() {
              return this._structArray.int16[this._pos2 + 7];
            }
            get key() {
              return this._structArray.uint16[this._pos2 + 8];
            }
            get textBoxStartIndex() {
              return this._structArray.uint16[this._pos2 + 9];
            }
            get textBoxEndIndex() {
              return this._structArray.uint16[this._pos2 + 10];
            }
            get verticalTextBoxStartIndex() {
              return this._structArray.uint16[this._pos2 + 11];
            }
            get verticalTextBoxEndIndex() {
              return this._structArray.uint16[this._pos2 + 12];
            }
            get iconBoxStartIndex() {
              return this._structArray.uint16[this._pos2 + 13];
            }
            get iconBoxEndIndex() {
              return this._structArray.uint16[this._pos2 + 14];
            }
            get verticalIconBoxStartIndex() {
              return this._structArray.uint16[this._pos2 + 15];
            }
            get verticalIconBoxEndIndex() {
              return this._structArray.uint16[this._pos2 + 16];
            }
            get featureIndex() {
              return this._structArray.uint16[this._pos2 + 17];
            }
            get numHorizontalGlyphVertices() {
              return this._structArray.uint16[this._pos2 + 18];
            }
            get numVerticalGlyphVertices() {
              return this._structArray.uint16[this._pos2 + 19];
            }
            get numIconVertices() {
              return this._structArray.uint16[this._pos2 + 20];
            }
            get numVerticalIconVertices() {
              return this._structArray.uint16[this._pos2 + 21];
            }
            get useRuntimeCollisionCircles() {
              return this._structArray.uint16[this._pos2 + 22];
            }
            get crossTileID() {
              return this._structArray.uint32[this._pos4 + 12];
            }
            set crossTileID(t4) {
              this._structArray.uint32[this._pos4 + 12] = t4;
            }
            get textBoxScale() {
              return this._structArray.float32[this._pos4 + 13];
            }
            get collisionCircleDiameter() {
              return this._structArray.float32[this._pos4 + 14];
            }
            get textAnchorOffsetStartIndex() {
              return this._structArray.uint16[this._pos2 + 30];
            }
            get textAnchorOffsetEndIndex() {
              return this._structArray.uint16[this._pos2 + 31];
            }
          }
          Ls.prototype.size = 64;
          class Ds extends Ms {
            get(t4) {
              return new Ls(this, t4);
            }
          }
          wi("SymbolInstanceArray", Ds);
          class Os extends Is {
            getoffsetX(t4) {
              return this.float32[1 * t4 + 0];
            }
          }
          wi("GlyphOffsetArray", Os);
          class js extends hs {
            getx(t4) {
              return this.int16[3 * t4 + 0];
            }
            gety(t4) {
              return this.int16[3 * t4 + 1];
            }
            gettileUnitDistanceFromAnchor(t4) {
              return this.int16[3 * t4 + 2];
            }
          }
          wi("SymbolLineVertexArray", js);
          class Rs extends as {
            get textAnchor() {
              return this._structArray.uint16[this._pos2 + 0];
            }
            get textOffset0() {
              return this._structArray.float32[this._pos4 + 1];
            }
            get textOffset1() {
              return this._structArray.float32[this._pos4 + 2];
            }
          }
          Rs.prototype.size = 12;
          class Us extends zs {
            get(t4) {
              return new Rs(this, t4);
            }
          }
          wi("TextAnchorOffsetArray", Us);
          class qs extends as {
            get featureIndex() {
              return this._structArray.uint32[this._pos4 + 0];
            }
            get sourceLayerIndex() {
              return this._structArray.uint16[this._pos2 + 2];
            }
            get bucketIndex() {
              return this._structArray.uint16[this._pos2 + 3];
            }
          }
          qs.prototype.size = 8;
          class Ns extends Ps {
            get(t4) {
              return new qs(this, t4);
            }
          }
          wi("FeatureIndexArray", Ns);
          class Zs extends cs {
          }
          class Gs extends cs {
          }
          class Ks extends cs {
          }
          class Xs extends fs {
          }
          class Hs extends ds {
          }
          class Ys extends ys {
          }
          class Js extends ms {
          }
          class Ws extends gs {
          }
          class Qs extends xs {
          }
          class ta extends vs {
          }
          class ea extends ws {
          }
          class ra extends As {
          }
          class na extends Ss {
          }
          class ia extends Cs {
          }
          const sa = ls([{ name: "a_pos", components: 2, type: "Int16" }], 4), { members: aa } = sa;
          class oa {
            constructor(t4 = []) {
              this.segments = t4;
            }
            prepareSegment(t4, e2, r2, n2) {
              let i2 = this.segments[this.segments.length - 1];
              return t4 > oa.MAX_VERTEX_ARRAY_LENGTH && A2(`Max vertices per segment is ${oa.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t4}`), (!i2 || i2.vertexLength + t4 > oa.MAX_VERTEX_ARRAY_LENGTH || i2.sortKey !== n2) && (i2 = { vertexOffset: e2.length, primitiveOffset: r2.length, vertexLength: 0, primitiveLength: 0 }, void 0 !== n2 && (i2.sortKey = n2), this.segments.push(i2)), i2;
            }
            get() {
              return this.segments;
            }
            destroy() {
              for (const t4 of this.segments) for (const e2 in t4.vaos) t4.vaos[e2].destroy();
            }
            static simpleSegment(t4, e2, r2, n2) {
              return new oa([{ vertexOffset: t4, primitiveOffset: e2, vertexLength: r2, primitiveLength: n2, vaos: {}, sortKey: 0 }]);
            }
          }
          function la(t4, e2) {
            return 256 * (t4 = y(Math.floor(t4), 0, 255)) + y(Math.floor(e2), 0, 255);
          }
          oa.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1, wi("SegmentVector", oa);
          const ua = ls([{ name: "a_pattern_from", components: 4, type: "Uint16" }, { name: "a_pattern_to", components: 4, type: "Uint16" }, { name: "a_pixel_ratio_from", components: 1, type: "Uint16" }, { name: "a_pixel_ratio_to", components: 1, type: "Uint16" }]);
          var ca = { exports: {} }, ha = { exports: {} };
          ha.exports = function(t4, e2) {
            var r2, n2, i2, s2, a2, o2, l2, u2;
            for (n2 = t4.length - (r2 = 3 & t4.length), i2 = e2, a2 = 3432918353, o2 = 461845907, u2 = 0; u2 < n2; ) l2 = 255 & t4.charCodeAt(u2) | (255 & t4.charCodeAt(++u2)) << 8 | (255 & t4.charCodeAt(++u2)) << 16 | (255 & t4.charCodeAt(++u2)) << 24, ++u2, i2 = 27492 + (65535 & (s2 = 5 * (65535 & (i2 = (i2 ^= l2 = (65535 & (l2 = (l2 = (65535 & l2) * a2 + (((l2 >>> 16) * a2 & 65535) << 16) & 4294967295) << 15 | l2 >>> 17)) * o2 + (((l2 >>> 16) * o2 & 65535) << 16) & 4294967295) << 13 | i2 >>> 19)) + ((5 * (i2 >>> 16) & 65535) << 16) & 4294967295)) + ((58964 + (s2 >>> 16) & 65535) << 16);
            switch (l2 = 0, r2) {
              case 3:
                l2 ^= (255 & t4.charCodeAt(u2 + 2)) << 16;
              case 2:
                l2 ^= (255 & t4.charCodeAt(u2 + 1)) << 8;
              case 1:
                i2 ^= l2 = (65535 & (l2 = (l2 = (65535 & (l2 ^= 255 & t4.charCodeAt(u2))) * a2 + (((l2 >>> 16) * a2 & 65535) << 16) & 4294967295) << 15 | l2 >>> 17)) * o2 + (((l2 >>> 16) * o2 & 65535) << 16) & 4294967295;
            }
            return i2 ^= t4.length, i2 = 2246822507 * (65535 & (i2 ^= i2 >>> 16)) + ((2246822507 * (i2 >>> 16) & 65535) << 16) & 4294967295, i2 = 3266489909 * (65535 & (i2 ^= i2 >>> 13)) + ((3266489909 * (i2 >>> 16) & 65535) << 16) & 4294967295, (i2 ^= i2 >>> 16) >>> 0;
          };
          var pa = ha.exports, fa = { exports: {} };
          fa.exports = function(t4, e2) {
            for (var r2, n2 = t4.length, i2 = e2 ^ n2, s2 = 0; n2 >= 4; ) r2 = 1540483477 * (65535 & (r2 = 255 & t4.charCodeAt(s2) | (255 & t4.charCodeAt(++s2)) << 8 | (255 & t4.charCodeAt(++s2)) << 16 | (255 & t4.charCodeAt(++s2)) << 24)) + ((1540483477 * (r2 >>> 16) & 65535) << 16), i2 = 1540483477 * (65535 & i2) + ((1540483477 * (i2 >>> 16) & 65535) << 16) ^ (r2 = 1540483477 * (65535 & (r2 ^= r2 >>> 24)) + ((1540483477 * (r2 >>> 16) & 65535) << 16)), n2 -= 4, ++s2;
            switch (n2) {
              case 3:
                i2 ^= (255 & t4.charCodeAt(s2 + 2)) << 16;
              case 2:
                i2 ^= (255 & t4.charCodeAt(s2 + 1)) << 8;
              case 1:
                i2 = 1540483477 * (65535 & (i2 ^= 255 & t4.charCodeAt(s2))) + ((1540483477 * (i2 >>> 16) & 65535) << 16);
            }
            return i2 = 1540483477 * (65535 & (i2 ^= i2 >>> 13)) + ((1540483477 * (i2 >>> 16) & 65535) << 16), (i2 ^= i2 >>> 15) >>> 0;
          };
          var da = pa, ya = fa.exports;
          ca.exports = da, ca.exports.murmur3 = da, ca.exports.murmur2 = ya;
          var ma = r(ca.exports);
          class ga {
            constructor() {
              this.ids = [], this.positions = [], this.indexed = false;
            }
            add(t4, e2, r2, n2) {
              this.ids.push(xa(t4)), this.positions.push(e2, r2, n2);
            }
            getPositions(t4) {
              if (!this.indexed) throw new Error("Trying to get index, but feature positions are not indexed");
              const e2 = xa(t4);
              let r2 = 0, n2 = this.ids.length - 1;
              for (; r2 < n2; ) {
                const t5 = r2 + n2 >> 1;
                this.ids[t5] >= e2 ? n2 = t5 : r2 = t5 + 1;
              }
              const i2 = [];
              for (; this.ids[r2] === e2; ) i2.push({ index: this.positions[3 * r2], start: this.positions[3 * r2 + 1], end: this.positions[3 * r2 + 2] }), r2++;
              return i2;
            }
            static serialize(t4, e2) {
              const r2 = new Float64Array(t4.ids), n2 = new Uint32Array(t4.positions);
              return va(r2, n2, 0, r2.length - 1), e2 && e2.push(r2.buffer, n2.buffer), { ids: r2, positions: n2 };
            }
            static deserialize(t4) {
              const e2 = new ga();
              return e2.ids = t4.ids, e2.positions = t4.positions, e2.indexed = true, e2;
            }
          }
          function xa(t4) {
            const e2 = +t4;
            return !isNaN(e2) && e2 <= Number.MAX_SAFE_INTEGER ? e2 : ma(String(t4));
          }
          function va(t4, e2, r2, n2) {
            for (; r2 < n2; ) {
              const i2 = t4[r2 + n2 >> 1];
              let s2 = r2 - 1, a2 = n2 + 1;
              for (; ; ) {
                do {
                  s2++;
                } while (t4[s2] < i2);
                do {
                  a2--;
                } while (t4[a2] > i2);
                if (s2 >= a2) break;
                ba(t4, s2, a2), ba(e2, 3 * s2, 3 * a2), ba(e2, 3 * s2 + 1, 3 * a2 + 1), ba(e2, 3 * s2 + 2, 3 * a2 + 2);
              }
              a2 - r2 < n2 - a2 ? (va(t4, e2, r2, a2), r2 = a2 + 1) : (va(t4, e2, a2 + 1, n2), n2 = a2);
            }
          }
          function ba(t4, e2, r2) {
            const n2 = t4[e2];
            t4[e2] = t4[r2], t4[r2] = n2;
          }
          wi("FeaturePositionMap", ga);
          class wa {
            constructor(t4, e2) {
              this.gl = t4.gl, this.location = e2;
            }
          }
          class _a extends wa {
            constructor(t4, e2) {
              super(t4, e2), this.current = 0;
            }
            set(t4) {
              this.current !== t4 && (this.current = t4, this.gl.uniform1f(this.location, t4));
            }
          }
          class Aa extends wa {
            constructor(t4, e2) {
              super(t4, e2), this.current = [0, 0, 0, 0];
            }
            set(t4) {
              t4[0] === this.current[0] && t4[1] === this.current[1] && t4[2] === this.current[2] && t4[3] === this.current[3] || (this.current = t4, this.gl.uniform4f(this.location, t4[0], t4[1], t4[2], t4[3]));
            }
          }
          class Sa extends wa {
            constructor(t4, e2) {
              super(t4, e2), this.current = Kt.transparent;
            }
            set(t4) {
              t4.r === this.current.r && t4.g === this.current.g && t4.b === this.current.b && t4.a === this.current.a || (this.current = t4, this.gl.uniform4f(this.location, t4.r, t4.g, t4.b, t4.a));
            }
          }
          const ka = new Float32Array(16);
          function Ma(t4) {
            return [la(255 * t4.r, 255 * t4.g), la(255 * t4.b, 255 * t4.a)];
          }
          class Ia {
            constructor(t4, e2, r2) {
              this.value = t4, this.uniformNames = e2.map((t5) => `u_${t5}`), this.type = r2;
            }
            setUniform(t4, e2, r2) {
              t4.set(r2.constantOr(this.value));
            }
            getBinding(t4, e2, r2) {
              return "color" === this.type ? new Sa(t4, e2) : new _a(t4, e2);
            }
          }
          class za {
            constructor(t4, e2) {
              this.uniformNames = e2.map((t5) => `u_${t5}`), this.patternFrom = null, this.patternTo = null, this.pixelRatioFrom = 1, this.pixelRatioTo = 1;
            }
            setConstantPatternPositions(t4, e2) {
              this.pixelRatioFrom = e2.pixelRatio, this.pixelRatioTo = t4.pixelRatio, this.patternFrom = e2.tlbr, this.patternTo = t4.tlbr;
            }
            setUniform(t4, e2, r2, n2) {
              const i2 = "u_pattern_to" === n2 ? this.patternTo : "u_pattern_from" === n2 ? this.patternFrom : "u_pixel_ratio_to" === n2 ? this.pixelRatioTo : "u_pixel_ratio_from" === n2 ? this.pixelRatioFrom : null;
              i2 && t4.set(i2);
            }
            getBinding(t4, e2, r2) {
              return "u_pattern" === r2.substr(0, 9) ? new Aa(t4, e2) : new _a(t4, e2);
            }
          }
          class Pa {
            constructor(t4, e2, r2, n2) {
              this.expression = t4, this.type = r2, this.maxValue = 0, this.paintVertexAttributes = e2.map((t5) => ({ name: `a_${t5}`, type: "Float32", components: "color" === r2 ? 2 : 1, offset: 0 })), this.paintVertexArray = new n2();
            }
            populatePaintArray(t4, e2, r2, n2, i2) {
              const s2 = this.paintVertexArray.length, a2 = this.expression.evaluate(new Ui(0), e2, {}, n2, [], i2);
              this.paintVertexArray.resize(t4), this._setPaintValue(s2, t4, a2);
            }
            updatePaintArray(t4, e2, r2, n2) {
              const i2 = this.expression.evaluate({ zoom: 0 }, r2, n2);
              this._setPaintValue(t4, e2, i2);
            }
            _setPaintValue(t4, e2, r2) {
              if ("color" === this.type) {
                const n2 = Ma(r2);
                for (let r3 = t4; r3 < e2; r3++) this.paintVertexArray.emplace(r3, n2[0], n2[1]);
              } else {
                for (let n2 = t4; n2 < e2; n2++) this.paintVertexArray.emplace(n2, r2);
                this.maxValue = Math.max(this.maxValue, Math.abs(r2));
              }
            }
            upload(t4) {
              this.paintVertexArray && this.paintVertexArray.arrayBuffer && (this.paintVertexBuffer && this.paintVertexBuffer.buffer ? this.paintVertexBuffer.updateData(this.paintVertexArray) : this.paintVertexBuffer = t4.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent));
            }
            destroy() {
              this.paintVertexBuffer && this.paintVertexBuffer.destroy();
            }
          }
          class Ca {
            constructor(t4, e2, r2, n2, i2, s2) {
              this.expression = t4, this.uniformNames = e2.map((t5) => `u_${t5}_t`), this.type = r2, this.useIntegerZoom = n2, this.zoom = i2, this.maxValue = 0, this.paintVertexAttributes = e2.map((t5) => ({ name: `a_${t5}`, type: "Float32", components: "color" === r2 ? 4 : 2, offset: 0 })), this.paintVertexArray = new s2();
            }
            populatePaintArray(t4, e2, r2, n2, i2) {
              const s2 = this.expression.evaluate(new Ui(this.zoom), e2, {}, n2, [], i2), a2 = this.expression.evaluate(new Ui(this.zoom + 1), e2, {}, n2, [], i2), o2 = this.paintVertexArray.length;
              this.paintVertexArray.resize(t4), this._setPaintValue(o2, t4, s2, a2);
            }
            updatePaintArray(t4, e2, r2, n2) {
              const i2 = this.expression.evaluate({ zoom: this.zoom }, r2, n2), s2 = this.expression.evaluate({ zoom: this.zoom + 1 }, r2, n2);
              this._setPaintValue(t4, e2, i2, s2);
            }
            _setPaintValue(t4, e2, r2, n2) {
              if ("color" === this.type) {
                const i2 = Ma(r2), s2 = Ma(n2);
                for (let r3 = t4; r3 < e2; r3++) this.paintVertexArray.emplace(r3, i2[0], i2[1], s2[0], s2[1]);
              } else {
                for (let i2 = t4; i2 < e2; i2++) this.paintVertexArray.emplace(i2, r2, n2);
                this.maxValue = Math.max(this.maxValue, Math.abs(r2), Math.abs(n2));
              }
            }
            upload(t4) {
              this.paintVertexArray && this.paintVertexArray.arrayBuffer && (this.paintVertexBuffer && this.paintVertexBuffer.buffer ? this.paintVertexBuffer.updateData(this.paintVertexArray) : this.paintVertexBuffer = t4.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent));
            }
            destroy() {
              this.paintVertexBuffer && this.paintVertexBuffer.destroy();
            }
            setUniform(t4, e2) {
              const r2 = this.useIntegerZoom ? Math.floor(e2.zoom) : e2.zoom, n2 = y(this.expression.interpolationFactor(r2, this.zoom, this.zoom + 1), 0, 1);
              t4.set(n2);
            }
            getBinding(t4, e2, r2) {
              return new _a(t4, e2);
            }
          }
          class Ba {
            constructor(t4, e2, r2, n2, i2, s2) {
              this.expression = t4, this.type = e2, this.useIntegerZoom = r2, this.zoom = n2, this.layerId = s2, this.zoomInPaintVertexArray = new i2(), this.zoomOutPaintVertexArray = new i2();
            }
            populatePaintArray(t4, e2, r2) {
              const n2 = this.zoomInPaintVertexArray.length;
              this.zoomInPaintVertexArray.resize(t4), this.zoomOutPaintVertexArray.resize(t4), this._setPaintValues(n2, t4, e2.patterns && e2.patterns[this.layerId], r2);
            }
            updatePaintArray(t4, e2, r2, n2, i2) {
              this._setPaintValues(t4, e2, r2.patterns && r2.patterns[this.layerId], i2);
            }
            _setPaintValues(t4, e2, r2, n2) {
              if (!n2 || !r2) return;
              const { min: i2, mid: s2, max: a2 } = r2, o2 = n2[i2], l2 = n2[s2], u2 = n2[a2];
              if (o2 && l2 && u2) for (let r3 = t4; r3 < e2; r3++) this.zoomInPaintVertexArray.emplace(r3, l2.tl[0], l2.tl[1], l2.br[0], l2.br[1], o2.tl[0], o2.tl[1], o2.br[0], o2.br[1], l2.pixelRatio, o2.pixelRatio), this.zoomOutPaintVertexArray.emplace(r3, l2.tl[0], l2.tl[1], l2.br[0], l2.br[1], u2.tl[0], u2.tl[1], u2.br[0], u2.br[1], l2.pixelRatio, u2.pixelRatio);
            }
            upload(t4) {
              this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer && (this.zoomInPaintVertexBuffer = t4.createVertexBuffer(this.zoomInPaintVertexArray, ua.members, this.expression.isStateDependent), this.zoomOutPaintVertexBuffer = t4.createVertexBuffer(this.zoomOutPaintVertexArray, ua.members, this.expression.isStateDependent));
            }
            destroy() {
              this.zoomOutPaintVertexBuffer && this.zoomOutPaintVertexBuffer.destroy(), this.zoomInPaintVertexBuffer && this.zoomInPaintVertexBuffer.destroy();
            }
          }
          class Va {
            constructor(t4, e2, r2) {
              this.binders = {}, this._buffers = [];
              const n2 = [];
              for (const i2 in t4.paint._values) {
                if (!r2(i2)) continue;
                const s2 = t4.paint.get(i2);
                if (!(s2 instanceof Hi && an(s2.property.specification))) continue;
                const a2 = Fa(i2, t4.type), o2 = s2.value, l2 = s2.property.specification.type, u2 = s2.property.useIntegerZoom, c2 = s2.property.specification["property-type"], h2 = "cross-faded" === c2 || "cross-faded-data-driven" === c2;
                if ("constant" === o2.kind) this.binders[i2] = h2 ? new za(o2.value, a2) : new Ia(o2.value, a2, l2), n2.push(`/u_${i2}`);
                else if ("source" === o2.kind || h2) {
                  const r3 = Ta(i2, l2, "source");
                  this.binders[i2] = h2 ? new Ba(o2, l2, u2, e2, r3, t4.id) : new Pa(o2, a2, l2, r3), n2.push(`/a_${i2}`);
                } else {
                  const t5 = Ta(i2, l2, "composite");
                  this.binders[i2] = new Ca(o2, a2, l2, u2, e2, t5), n2.push(`/z_${i2}`);
                }
              }
              this.cacheKey = n2.sort().join("");
            }
            getMaxValue(t4) {
              const e2 = this.binders[t4];
              return e2 instanceof Pa || e2 instanceof Ca ? e2.maxValue : 0;
            }
            populatePaintArrays(t4, e2, r2, n2, i2) {
              for (const s2 in this.binders) {
                const a2 = this.binders[s2];
                (a2 instanceof Pa || a2 instanceof Ca || a2 instanceof Ba) && a2.populatePaintArray(t4, e2, r2, n2, i2);
              }
            }
            setConstantPatternPositions(t4, e2) {
              for (const r2 in this.binders) {
                const n2 = this.binders[r2];
                n2 instanceof za && n2.setConstantPatternPositions(t4, e2);
              }
            }
            updatePaintArrays(t4, e2, r2, n2, i2) {
              let s2 = false;
              for (const a2 in t4) {
                const o2 = e2.getPositions(a2);
                for (const e3 of o2) {
                  const o3 = r2.feature(e3.index);
                  for (const r3 in this.binders) {
                    const l2 = this.binders[r3];
                    if ((l2 instanceof Pa || l2 instanceof Ca || l2 instanceof Ba) && true === l2.expression.isStateDependent) {
                      const u2 = n2.paint.get(r3);
                      l2.expression = u2.value, l2.updatePaintArray(e3.start, e3.end, o3, t4[a2], i2), s2 = true;
                    }
                  }
                }
              }
              return s2;
            }
            defines() {
              const t4 = [];
              for (const e2 in this.binders) {
                const r2 = this.binders[e2];
                (r2 instanceof Ia || r2 instanceof za) && t4.push(...r2.uniformNames.map((t5) => `#define HAS_UNIFORM_${t5}`));
              }
              return t4;
            }
            getBinderAttributes() {
              const t4 = [];
              for (const e2 in this.binders) {
                const r2 = this.binders[e2];
                if (r2 instanceof Pa || r2 instanceof Ca) for (let e3 = 0; e3 < r2.paintVertexAttributes.length; e3++) t4.push(r2.paintVertexAttributes[e3].name);
                else if (r2 instanceof Ba) for (let e3 = 0; e3 < ua.members.length; e3++) t4.push(ua.members[e3].name);
              }
              return t4;
            }
            getBinderUniforms() {
              const t4 = [];
              for (const e2 in this.binders) {
                const r2 = this.binders[e2];
                if (r2 instanceof Ia || r2 instanceof za || r2 instanceof Ca) for (const e3 of r2.uniformNames) t4.push(e3);
              }
              return t4;
            }
            getPaintVertexBuffers() {
              return this._buffers;
            }
            getUniforms(t4, e2) {
              const r2 = [];
              for (const n2 in this.binders) {
                const i2 = this.binders[n2];
                if (i2 instanceof Ia || i2 instanceof za || i2 instanceof Ca) {
                  for (const s2 of i2.uniformNames) if (e2[s2]) {
                    const a2 = i2.getBinding(t4, e2[s2], s2);
                    r2.push({ name: s2, property: n2, binding: a2 });
                  }
                }
              }
              return r2;
            }
            setUniforms(t4, e2, r2, n2) {
              for (const { name: t5, property: i2, binding: s2 } of e2) this.binders[i2].setUniform(s2, n2, r2.get(i2), t5);
            }
            updatePaintBuffers(t4) {
              this._buffers = [];
              for (const e2 in this.binders) {
                const r2 = this.binders[e2];
                if (t4 && r2 instanceof Ba) {
                  const e3 = 2 === t4.fromScale ? r2.zoomInPaintVertexBuffer : r2.zoomOutPaintVertexBuffer;
                  e3 && this._buffers.push(e3);
                } else (r2 instanceof Pa || r2 instanceof Ca) && r2.paintVertexBuffer && this._buffers.push(r2.paintVertexBuffer);
              }
            }
            upload(t4) {
              for (const e2 in this.binders) {
                const r2 = this.binders[e2];
                (r2 instanceof Pa || r2 instanceof Ca || r2 instanceof Ba) && r2.upload(t4);
              }
              this.updatePaintBuffers();
            }
            destroy() {
              for (const t4 in this.binders) {
                const e2 = this.binders[t4];
                (e2 instanceof Pa || e2 instanceof Ca || e2 instanceof Ba) && e2.destroy();
              }
            }
          }
          class Ea {
            constructor(t4, e2, r2 = () => true) {
              this.programConfigurations = {};
              for (const n2 of t4) this.programConfigurations[n2.id] = new Va(n2, e2, r2);
              this.needsUpload = false, this._featureMap = new ga(), this._bufferOffset = 0;
            }
            populatePaintArrays(t4, e2, r2, n2, i2, s2) {
              for (const r3 in this.programConfigurations) this.programConfigurations[r3].populatePaintArrays(t4, e2, n2, i2, s2);
              void 0 !== e2.id && this._featureMap.add(e2.id, r2, this._bufferOffset, t4), this._bufferOffset = t4, this.needsUpload = true;
            }
            updatePaintArrays(t4, e2, r2, n2) {
              for (const i2 of r2) this.needsUpload = this.programConfigurations[i2.id].updatePaintArrays(t4, this._featureMap, e2, i2, n2) || this.needsUpload;
            }
            get(t4) {
              return this.programConfigurations[t4];
            }
            upload(t4) {
              if (this.needsUpload) {
                for (const e2 in this.programConfigurations) this.programConfigurations[e2].upload(t4);
                this.needsUpload = false;
              }
            }
            destroy() {
              for (const t4 in this.programConfigurations) this.programConfigurations[t4].destroy();
            }
          }
          function Fa(t4, e2) {
            return { "text-opacity": ["opacity"], "icon-opacity": ["opacity"], "text-color": ["fill_color"], "icon-color": ["fill_color"], "text-halo-color": ["halo_color"], "icon-halo-color": ["halo_color"], "text-halo-blur": ["halo_blur"], "icon-halo-blur": ["halo_blur"], "text-halo-width": ["halo_width"], "icon-halo-width": ["halo_width"], "line-gap-width": ["gapwidth"], "line-pattern": ["pattern_to", "pattern_from", "pixel_ratio_to", "pixel_ratio_from"], "fill-pattern": ["pattern_to", "pattern_from", "pixel_ratio_to", "pixel_ratio_from"], "fill-extrusion-pattern": ["pattern_to", "pattern_from", "pixel_ratio_to", "pixel_ratio_from"] }[t4] || [t4.replace(`${e2}-`, "").replace(/-/g, "_")];
          }
          function Ta(t4, e2, r2) {
            const n2 = { color: { source: ys, composite: Vs }, number: { source: Is, composite: ys } }, i2 = function(t5) {
              return { "line-pattern": { source: Js, composite: Js }, "fill-pattern": { source: Js, composite: Js }, "fill-extrusion-pattern": { source: Js, composite: Js } }[t5];
            }(t4);
            return i2 && i2[r2] || n2[e2][r2];
          }
          wi("ConstantBinder", Ia), wi("CrossFadedConstantBinder", za), wi("SourceExpressionBinder", Pa), wi("CrossFadedCompositeBinder", Ba), wi("CompositeExpressionBinder", Ca), wi("ProgramConfiguration", Va, { omit: ["_buffers"] }), wi("ProgramConfigurationSet", Ea);
          const $a = 8192, La = Math.pow(2, 14) - 1, Da = -La - 1;
          function Oa(t4) {
            const e2 = $a / t4.extent, r2 = t4.loadGeometry();
            for (let t5 = 0; t5 < r2.length; t5++) {
              const n2 = r2[t5];
              for (let t6 = 0; t6 < n2.length; t6++) {
                const r3 = n2[t6], i2 = Math.round(r3.x * e2), s2 = Math.round(r3.y * e2);
                r3.x = y(i2, Da, La), r3.y = y(s2, Da, La), (i2 < r3.x || i2 > r3.x + 1 || s2 < r3.y || s2 > r3.y + 1) && A2("Geometry exceeds allowed extent, reduce your vector tile buffer size");
              }
            }
            return r2;
          }
          function ja(t4, e2) {
            return { type: t4.type, id: t4.id, properties: t4.properties, geometry: e2 ? Oa(t4) : [] };
          }
          function Ra(t4, e2, r2, n2, i2) {
            t4.emplaceBack(2 * e2 + (n2 + 1) / 2, 2 * r2 + (i2 + 1) / 2);
          }
          class Ua {
            constructor(t4) {
              this.zoom = t4.zoom, this.overscaling = t4.overscaling, this.layers = t4.layers, this.layerIds = this.layers.map((t5) => t5.id), this.index = t4.index, this.hasPattern = false, this.layoutVertexArray = new Gs(), this.indexArray = new na(), this.segments = new oa(), this.programConfigurations = new Ea(t4.layers, t4.zoom), this.stateDependentLayerIds = this.layers.filter((t5) => t5.isStateDependent()).map((t5) => t5.id);
            }
            populate(t4, e2, r2) {
              const n2 = this.layers[0], i2 = [];
              let s2 = null, a2 = false;
              "circle" === n2.type && (s2 = n2.layout.get("circle-sort-key"), a2 = !s2.isConstant());
              for (const { feature: e3, id: n3, index: o2, sourceLayerIndex: l2 } of t4) {
                const t5 = this.layers[0]._featureFilter.needGeometry, u2 = ja(e3, t5);
                if (!this.layers[0]._featureFilter.filter(new Ui(this.zoom), u2, r2)) continue;
                const c2 = a2 ? s2.evaluate(u2, {}, r2) : void 0, h2 = { id: n3, properties: e3.properties, type: e3.type, sourceLayerIndex: l2, index: o2, geometry: t5 ? u2.geometry : Oa(e3), patterns: {}, sortKey: c2 };
                i2.push(h2);
              }
              a2 && i2.sort((t5, e3) => t5.sortKey - e3.sortKey);
              for (const n3 of i2) {
                const { geometry: i3, index: s3, sourceLayerIndex: a3 } = n3, o2 = t4[s3].feature;
                this.addFeature(n3, i3, s3, r2), e2.featureIndex.insert(o2, i3, s3, a3, this.index);
              }
            }
            update(t4, e2, r2) {
              this.stateDependentLayers.length && this.programConfigurations.updatePaintArrays(t4, e2, this.stateDependentLayers, r2);
            }
            isEmpty() {
              return 0 === this.layoutVertexArray.length;
            }
            uploadPending() {
              return !this.uploaded || this.programConfigurations.needsUpload;
            }
            upload(t4) {
              this.uploaded || (this.layoutVertexBuffer = t4.createVertexBuffer(this.layoutVertexArray, aa), this.indexBuffer = t4.createIndexBuffer(this.indexArray)), this.programConfigurations.upload(t4), this.uploaded = true;
            }
            destroy() {
              this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy());
            }
            addFeature(t4, e2, r2, n2) {
              for (const r3 of e2) for (const e3 of r3) {
                const r4 = e3.x, n3 = e3.y;
                if (r4 < 0 || r4 >= $a || n3 < 0 || n3 >= $a) continue;
                const i2 = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, t4.sortKey), s2 = i2.vertexLength;
                Ra(this.layoutVertexArray, r4, n3, -1, -1), Ra(this.layoutVertexArray, r4, n3, 1, -1), Ra(this.layoutVertexArray, r4, n3, 1, 1), Ra(this.layoutVertexArray, r4, n3, -1, 1), this.indexArray.emplaceBack(s2, s2 + 1, s2 + 2), this.indexArray.emplaceBack(s2, s2 + 3, s2 + 2), i2.vertexLength += 4, i2.primitiveLength += 2;
              }
              this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, t4, r2, {}, n2);
            }
          }
          function qa(t4, e2) {
            for (let r2 = 0; r2 < t4.length; r2++) if (Wa(e2, t4[r2])) return true;
            for (let r2 = 0; r2 < e2.length; r2++) if (Wa(t4, e2[r2])) return true;
            return !!Ka(t4, e2);
          }
          function Na(t4, e2, r2) {
            return !!Wa(t4, e2) || !!Ha(e2, t4, r2);
          }
          function Za(t4, e2) {
            if (1 === t4.length) return Ja(e2, t4[0]);
            for (let r2 = 0; r2 < e2.length; r2++) {
              const n2 = e2[r2];
              for (let e3 = 0; e3 < n2.length; e3++) if (Wa(t4, n2[e3])) return true;
            }
            for (let r2 = 0; r2 < t4.length; r2++) if (Ja(e2, t4[r2])) return true;
            for (let r2 = 0; r2 < e2.length; r2++) if (Ka(t4, e2[r2])) return true;
            return false;
          }
          function Ga(t4, e2, r2) {
            if (t4.length > 1) {
              if (Ka(t4, e2)) return true;
              for (let n2 = 0; n2 < e2.length; n2++) if (Ha(e2[n2], t4, r2)) return true;
            }
            for (let n2 = 0; n2 < t4.length; n2++) if (Ha(t4[n2], e2, r2)) return true;
            return false;
          }
          function Ka(t4, e2) {
            if (0 === t4.length || 0 === e2.length) return false;
            for (let r2 = 0; r2 < t4.length - 1; r2++) {
              const n2 = t4[r2], i2 = t4[r2 + 1];
              for (let t5 = 0; t5 < e2.length - 1; t5++) if (Xa(n2, i2, e2[t5], e2[t5 + 1])) return true;
            }
            return false;
          }
          function Xa(t4, e2, r2, n2) {
            return S(t4, r2, n2) !== S(e2, r2, n2) && S(t4, e2, r2) !== S(t4, e2, n2);
          }
          function Ha(t4, e2, r2) {
            const n2 = r2 * r2;
            if (1 === e2.length) return t4.distSqr(e2[0]) < n2;
            for (let r3 = 1; r3 < e2.length; r3++) if (Ya(t4, e2[r3 - 1], e2[r3]) < n2) return true;
            return false;
          }
          function Ya(t4, e2, r2) {
            const n2 = e2.distSqr(r2);
            if (0 === n2) return t4.distSqr(e2);
            const i2 = ((t4.x - e2.x) * (r2.x - e2.x) + (t4.y - e2.y) * (r2.y - e2.y)) / n2;
            return t4.distSqr(i2 < 0 ? e2 : i2 > 1 ? r2 : r2.sub(e2)._mult(i2)._add(e2));
          }
          function Ja(t4, e2) {
            let r2, n2, i2, s2 = false;
            for (let a2 = 0; a2 < t4.length; a2++) {
              r2 = t4[a2];
              for (let t5 = 0, a3 = r2.length - 1; t5 < r2.length; a3 = t5++) n2 = r2[t5], i2 = r2[a3], n2.y > e2.y != i2.y > e2.y && e2.x < (i2.x - n2.x) * (e2.y - n2.y) / (i2.y - n2.y) + n2.x && (s2 = !s2);
            }
            return s2;
          }
          function Wa(t4, e2) {
            let r2 = false;
            for (let n2 = 0, i2 = t4.length - 1; n2 < t4.length; i2 = n2++) {
              const s2 = t4[n2], a2 = t4[i2];
              s2.y > e2.y != a2.y > e2.y && e2.x < (a2.x - s2.x) * (e2.y - s2.y) / (a2.y - s2.y) + s2.x && (r2 = !r2);
            }
            return r2;
          }
          function Qa(t4, e2, r2) {
            const n2 = r2[0], i2 = r2[2];
            if (t4.x < n2.x && e2.x < n2.x || t4.x > i2.x && e2.x > i2.x || t4.y < n2.y && e2.y < n2.y || t4.y > i2.y && e2.y > i2.y) return false;
            const s2 = S(t4, e2, r2[0]);
            return s2 !== S(t4, e2, r2[1]) || s2 !== S(t4, e2, r2[2]) || s2 !== S(t4, e2, r2[3]);
          }
          function to(t4, e2, r2) {
            const n2 = e2.paint.get(t4).value;
            return "constant" === n2.kind ? n2.value : r2.programConfigurations.get(e2.id).getMaxValue(t4);
          }
          function eo(t4) {
            return Math.sqrt(t4[0] * t4[0] + t4[1] * t4[1]);
          }
          function ro(t4, e2, r2, n2, i2) {
            if (!e2[0] && !e2[1]) return t4;
            const a2 = s.convert(e2)._mult(i2);
            "viewport" === r2 && a2._rotate(-n2);
            const o2 = [];
            for (let e3 = 0; e3 < t4.length; e3++) o2.push(t4[e3].sub(a2));
            return o2;
          }
          let no, io;
          wi("CircleBucket", Ua, { omit: ["layers"] });
          var so = { get paint() {
            return io = io || new rs({ "circle-radius": new Wi(G.paint_circle["circle-radius"]), "circle-color": new Wi(G.paint_circle["circle-color"]), "circle-blur": new Wi(G.paint_circle["circle-blur"]), "circle-opacity": new Wi(G.paint_circle["circle-opacity"]), "circle-translate": new Ji(G.paint_circle["circle-translate"]), "circle-translate-anchor": new Ji(G.paint_circle["circle-translate-anchor"]), "circle-pitch-scale": new Ji(G.paint_circle["circle-pitch-scale"]), "circle-pitch-alignment": new Ji(G.paint_circle["circle-pitch-alignment"]), "circle-stroke-width": new Wi(G.paint_circle["circle-stroke-width"]), "circle-stroke-color": new Wi(G.paint_circle["circle-stroke-color"]), "circle-stroke-opacity": new Wi(G.paint_circle["circle-stroke-opacity"]) });
          }, get layout() {
            return no = no || new rs({ "circle-sort-key": new Wi(G.layout_circle["circle-sort-key"]) });
          } }, ao = 1e-6, oo = "undefined" != typeof Float32Array ? Float32Array : Array;
          function lo(t4) {
            return t4[0] = 1, t4[1] = 0, t4[2] = 0, t4[3] = 0, t4[4] = 0, t4[5] = 1, t4[6] = 0, t4[7] = 0, t4[8] = 0, t4[9] = 0, t4[10] = 1, t4[11] = 0, t4[12] = 0, t4[13] = 0, t4[14] = 0, t4[15] = 1, t4;
          }
          function uo(t4, e2, r2) {
            var n2 = e2[0], i2 = e2[1], s2 = e2[2], a2 = e2[3], o2 = e2[4], l2 = e2[5], u2 = e2[6], c2 = e2[7], h2 = e2[8], p2 = e2[9], f2 = e2[10], d2 = e2[11], y2 = e2[12], m2 = e2[13], g2 = e2[14], x2 = e2[15], v2 = r2[0], b2 = r2[1], w2 = r2[2], _2 = r2[3];
            return t4[0] = v2 * n2 + b2 * o2 + w2 * h2 + _2 * y2, t4[1] = v2 * i2 + b2 * l2 + w2 * p2 + _2 * m2, t4[2] = v2 * s2 + b2 * u2 + w2 * f2 + _2 * g2, t4[3] = v2 * a2 + b2 * c2 + w2 * d2 + _2 * x2, t4[4] = (v2 = r2[4]) * n2 + (b2 = r2[5]) * o2 + (w2 = r2[6]) * h2 + (_2 = r2[7]) * y2, t4[5] = v2 * i2 + b2 * l2 + w2 * p2 + _2 * m2, t4[6] = v2 * s2 + b2 * u2 + w2 * f2 + _2 * g2, t4[7] = v2 * a2 + b2 * c2 + w2 * d2 + _2 * x2, t4[8] = (v2 = r2[8]) * n2 + (b2 = r2[9]) * o2 + (w2 = r2[10]) * h2 + (_2 = r2[11]) * y2, t4[9] = v2 * i2 + b2 * l2 + w2 * p2 + _2 * m2, t4[10] = v2 * s2 + b2 * u2 + w2 * f2 + _2 * g2, t4[11] = v2 * a2 + b2 * c2 + w2 * d2 + _2 * x2, t4[12] = (v2 = r2[12]) * n2 + (b2 = r2[13]) * o2 + (w2 = r2[14]) * h2 + (_2 = r2[15]) * y2, t4[13] = v2 * i2 + b2 * l2 + w2 * p2 + _2 * m2, t4[14] = v2 * s2 + b2 * u2 + w2 * f2 + _2 * g2, t4[15] = v2 * a2 + b2 * c2 + w2 * d2 + _2 * x2, t4;
          }
          Math.hypot || (Math.hypot = function() {
            for (var t4 = 0, e2 = arguments.length; e2--; ) t4 += arguments[e2] * arguments[e2];
            return Math.sqrt(t4);
          });
          var co, ho = uo;
          function po(t4, e2, r2) {
            var n2 = e2[0], i2 = e2[1], s2 = e2[2], a2 = e2[3];
            return t4[0] = r2[0] * n2 + r2[4] * i2 + r2[8] * s2 + r2[12] * a2, t4[1] = r2[1] * n2 + r2[5] * i2 + r2[9] * s2 + r2[13] * a2, t4[2] = r2[2] * n2 + r2[6] * i2 + r2[10] * s2 + r2[14] * a2, t4[3] = r2[3] * n2 + r2[7] * i2 + r2[11] * s2 + r2[15] * a2, t4;
          }
          co = new oo(4), oo != Float32Array && (co[0] = 0, co[1] = 0, co[2] = 0, co[3] = 0);
          class fo extends is {
            constructor(t4) {
              super(t4, so);
            }
            createBucket(t4) {
              return new Ua(t4);
            }
            queryRadius(t4) {
              const e2 = t4;
              return to("circle-radius", this, e2) + to("circle-stroke-width", this, e2) + eo(this.paint.get("circle-translate"));
            }
            queryIntersectsFeature(t4, e2, r2, n2, i2, s2, a2, o2) {
              const l2 = ro(t4, this.paint.get("circle-translate"), this.paint.get("circle-translate-anchor"), s2.angle, a2), u2 = this.paint.get("circle-radius").evaluate(e2, r2) + this.paint.get("circle-stroke-width").evaluate(e2, r2), c2 = "map" === this.paint.get("circle-pitch-alignment"), h2 = c2 ? l2 : function(t5, e3) {
                return t5.map((t6) => yo(t6, e3));
              }(l2, o2), p2 = c2 ? u2 * a2 : u2;
              for (const t5 of n2) for (const e3 of t5) {
                const t6 = c2 ? e3 : yo(e3, o2);
                let r3 = p2;
                const n3 = po([], [e3.x, e3.y, 0, 1], o2);
                if ("viewport" === this.paint.get("circle-pitch-scale") && "map" === this.paint.get("circle-pitch-alignment") ? r3 *= n3[3] / s2.cameraToCenterDistance : "map" === this.paint.get("circle-pitch-scale") && "viewport" === this.paint.get("circle-pitch-alignment") && (r3 *= s2.cameraToCenterDistance / n3[3]), Na(h2, t6, r3)) return true;
              }
              return false;
            }
          }
          function yo(t4, e2) {
            const r2 = po([], [t4.x, t4.y, 0, 1], e2);
            return new s(r2[0] / r2[3], r2[1] / r2[3]);
          }
          class mo extends Ua {
          }
          let go;
          wi("HeatmapBucket", mo, { omit: ["layers"] });
          var xo = { get paint() {
            return go = go || new rs({ "heatmap-radius": new Wi(G.paint_heatmap["heatmap-radius"]), "heatmap-weight": new Wi(G.paint_heatmap["heatmap-weight"]), "heatmap-intensity": new Ji(G.paint_heatmap["heatmap-intensity"]), "heatmap-color": new es(G.paint_heatmap["heatmap-color"]), "heatmap-opacity": new Ji(G.paint_heatmap["heatmap-opacity"]) });
          } };
          function vo(t4, { width: e2, height: r2 }, n2, i2) {
            if (i2) {
              if (i2 instanceof Uint8ClampedArray) i2 = new Uint8Array(i2.buffer);
              else if (i2.length !== e2 * r2 * n2) throw new RangeError(`mismatched image size. expected: ${i2.length} but got: ${e2 * r2 * n2}`);
            } else i2 = new Uint8Array(e2 * r2 * n2);
            return t4.width = e2, t4.height = r2, t4.data = i2, t4;
          }
          function bo(t4, { width: e2, height: r2 }, n2) {
            if (e2 === t4.width && r2 === t4.height) return;
            const i2 = vo({}, { width: e2, height: r2 }, n2);
            wo(t4, i2, { x: 0, y: 0 }, { x: 0, y: 0 }, { width: Math.min(t4.width, e2), height: Math.min(t4.height, r2) }, n2), t4.width = e2, t4.height = r2, t4.data = i2.data;
          }
          function wo(t4, e2, r2, n2, i2, s2) {
            if (0 === i2.width || 0 === i2.height) return e2;
            if (i2.width > t4.width || i2.height > t4.height || r2.x > t4.width - i2.width || r2.y > t4.height - i2.height) throw new RangeError("out of range source coordinates for image copy");
            if (i2.width > e2.width || i2.height > e2.height || n2.x > e2.width - i2.width || n2.y > e2.height - i2.height) throw new RangeError("out of range destination coordinates for image copy");
            const a2 = t4.data, o2 = e2.data;
            if (a2 === o2) throw new Error("srcData equals dstData, so image is already copied");
            for (let l2 = 0; l2 < i2.height; l2++) {
              const u2 = ((r2.y + l2) * t4.width + r2.x) * s2, c2 = ((n2.y + l2) * e2.width + n2.x) * s2;
              for (let t5 = 0; t5 < i2.width * s2; t5++) o2[c2 + t5] = a2[u2 + t5];
            }
            return e2;
          }
          class _o {
            constructor(t4, e2) {
              vo(this, t4, 1, e2);
            }
            resize(t4) {
              bo(this, t4, 1);
            }
            clone() {
              return new _o({ width: this.width, height: this.height }, new Uint8Array(this.data));
            }
            static copy(t4, e2, r2, n2, i2) {
              wo(t4, e2, r2, n2, i2, 1);
            }
          }
          class Ao {
            constructor(t4, e2) {
              vo(this, t4, 4, e2);
            }
            resize(t4) {
              bo(this, t4, 4);
            }
            replace(t4, e2) {
              e2 ? this.data.set(t4) : this.data = t4 instanceof Uint8ClampedArray ? new Uint8Array(t4.buffer) : t4;
            }
            clone() {
              return new Ao({ width: this.width, height: this.height }, new Uint8Array(this.data));
            }
            static copy(t4, e2, r2, n2, i2) {
              wo(t4, e2, r2, n2, i2, 4);
            }
          }
          function So(t4) {
            const e2 = {}, r2 = t4.resolution || 256, n2 = t4.clips ? t4.clips.length : 1, i2 = t4.image || new Ao({ width: r2, height: n2 });
            if (Math.log(r2) / Math.LN2 % 1 != 0) throw new Error(`width is not a power of 2 - ${r2}`);
            const s2 = (r3, n3, s3) => {
              e2[t4.evaluationKey] = s3;
              const a2 = t4.expression.evaluate(e2);
              i2.data[r3 + n3 + 0] = Math.floor(255 * a2.r / a2.a), i2.data[r3 + n3 + 1] = Math.floor(255 * a2.g / a2.a), i2.data[r3 + n3 + 2] = Math.floor(255 * a2.b / a2.a), i2.data[r3 + n3 + 3] = Math.floor(255 * a2.a);
            };
            if (t4.clips) for (let e3 = 0, i3 = 0; e3 < n2; ++e3, i3 += 4 * r2) for (let n3 = 0, a2 = 0; n3 < r2; n3++, a2 += 4) {
              const o2 = n3 / (r2 - 1), { start: l2, end: u2 } = t4.clips[e3];
              s2(i3, a2, l2 * (1 - o2) + u2 * o2);
            }
            else for (let t5 = 0, e3 = 0; t5 < r2; t5++, e3 += 4) s2(0, e3, t5 / (r2 - 1));
            return i2;
          }
          wi("AlphaImage", _o), wi("RGBAImage", Ao);
          const ko = "big-fb";
          class Mo extends is {
            createBucket(t4) {
              return new mo(t4);
            }
            constructor(t4) {
              super(t4, xo), this.heatmapFbos = /* @__PURE__ */ new Map(), this._updateColorRamp();
            }
            _handleSpecialPaintPropertyUpdate(t4) {
              "heatmap-color" === t4 && this._updateColorRamp();
            }
            _updateColorRamp() {
              this.colorRamp = So({ expression: this._transitionablePaint._values["heatmap-color"].value.expression, evaluationKey: "heatmapDensity", image: this.colorRamp }), this.colorRampTexture = null;
            }
            resize() {
              this.heatmapFbos.has(ko) && this.heatmapFbos.delete(ko);
            }
            queryRadius() {
              return 0;
            }
            queryIntersectsFeature() {
              return false;
            }
            hasOffscreenPass() {
              return 0 !== this.paint.get("heatmap-opacity") && "none" !== this.visibility;
            }
          }
          let Io;
          var zo = { get paint() {
            return Io = Io || new rs({ "hillshade-illumination-direction": new Ji(G.paint_hillshade["hillshade-illumination-direction"]), "hillshade-illumination-anchor": new Ji(G.paint_hillshade["hillshade-illumination-anchor"]), "hillshade-exaggeration": new Ji(G.paint_hillshade["hillshade-exaggeration"]), "hillshade-shadow-color": new Ji(G.paint_hillshade["hillshade-shadow-color"]), "hillshade-highlight-color": new Ji(G.paint_hillshade["hillshade-highlight-color"]), "hillshade-accent-color": new Ji(G.paint_hillshade["hillshade-accent-color"]) });
          } };
          class Po extends is {
            constructor(t4) {
              super(t4, zo);
            }
            hasOffscreenPass() {
              return 0 !== this.paint.get("hillshade-exaggeration") && "none" !== this.visibility;
            }
          }
          const Co = ls([{ name: "a_pos", components: 2, type: "Int16" }], 4), { members: Bo } = Co;
          function Vo(t4, e2, r2 = 2) {
            const n2 = e2 && e2.length, i2 = n2 ? e2[0] * r2 : t4.length;
            let s2 = Eo(t4, 0, i2, r2, true);
            const a2 = [];
            if (!s2 || s2.next === s2.prev) return a2;
            let o2, l2, u2;
            if (n2 && (s2 = function(t5, e3, r3, n3) {
              const i3 = [];
              for (let r4 = 0, s3 = e3.length; r4 < s3; r4++) {
                const a3 = Eo(t5, e3[r4] * n3, r4 < s3 - 1 ? e3[r4 + 1] * n3 : t5.length, n3, false);
                a3 === a3.next && (a3.steiner = true), i3.push(No(a3));
              }
              i3.sort(jo);
              for (let t6 = 0; t6 < i3.length; t6++) r3 = Ro(i3[t6], r3);
              return r3;
            }(t4, e2, s2, r2)), t4.length > 80 * r2) {
              o2 = 1 / 0, l2 = 1 / 0;
              let e3 = -1 / 0, n3 = -1 / 0;
              for (let s3 = r2; s3 < i2; s3 += r2) {
                const r3 = t4[s3], i3 = t4[s3 + 1];
                r3 < o2 && (o2 = r3), i3 < l2 && (l2 = i3), r3 > e3 && (e3 = r3), i3 > n3 && (n3 = i3);
              }
              u2 = Math.max(e3 - o2, n3 - l2), u2 = 0 !== u2 ? 32767 / u2 : 0;
            }
            return To(s2, a2, r2, o2, l2, u2, 0), a2;
          }
          function Eo(t4, e2, r2, n2, i2) {
            let s2;
            if (i2 === function(t5, e3, r3, n3) {
              let i3 = 0;
              for (let s3 = e3, a2 = r3 - n3; s3 < r3; s3 += n3) i3 += (t5[a2] - t5[s3]) * (t5[s3 + 1] + t5[a2 + 1]), a2 = s3;
              return i3;
            }(t4, e2, r2, n2) > 0) for (let i3 = e2; i3 < r2; i3 += n2) s2 = tl(i3 / n2 | 0, t4[i3], t4[i3 + 1], s2);
            else for (let i3 = r2 - n2; i3 >= e2; i3 -= n2) s2 = tl(i3 / n2 | 0, t4[i3], t4[i3 + 1], s2);
            return s2 && Xo(s2, s2.next) && (el(s2), s2 = s2.next), s2;
          }
          function Fo(t4, e2) {
            if (!t4) return t4;
            e2 || (e2 = t4);
            let r2, n2 = t4;
            do {
              if (r2 = false, n2.steiner || !Xo(n2, n2.next) && 0 !== Ko(n2.prev, n2, n2.next)) n2 = n2.next;
              else {
                if (el(n2), n2 = e2 = n2.prev, n2 === n2.next) break;
                r2 = true;
              }
            } while (r2 || n2 !== e2);
            return e2;
          }
          function To(t4, e2, r2, n2, i2, s2, a2) {
            if (!t4) return;
            !a2 && s2 && function(t5, e3, r3, n3) {
              let i3 = t5;
              do {
                0 === i3.z && (i3.z = qo(i3.x, i3.y, e3, r3, n3)), i3.prevZ = i3.prev, i3.nextZ = i3.next, i3 = i3.next;
              } while (i3 !== t5);
              i3.prevZ.nextZ = null, i3.prevZ = null, function(t6) {
                let e4, r4 = 1;
                do {
                  let n4, i4 = t6;
                  t6 = null;
                  let s3 = null;
                  for (e4 = 0; i4; ) {
                    e4++;
                    let a3 = i4, o3 = 0;
                    for (let t7 = 0; t7 < r4 && (o3++, a3 = a3.nextZ, a3); t7++) ;
                    let l2 = r4;
                    for (; o3 > 0 || l2 > 0 && a3; ) 0 !== o3 && (0 === l2 || !a3 || i4.z <= a3.z) ? (n4 = i4, i4 = i4.nextZ, o3--) : (n4 = a3, a3 = a3.nextZ, l2--), s3 ? s3.nextZ = n4 : t6 = n4, n4.prevZ = s3, s3 = n4;
                    i4 = a3;
                  }
                  s3.nextZ = null, r4 *= 2;
                } while (e4 > 1);
              }(i3);
            }(t4, n2, i2, s2);
            let o2 = t4;
            for (; t4.prev !== t4.next; ) {
              const l2 = t4.prev, u2 = t4.next;
              if (s2 ? Lo(t4, n2, i2, s2) : $o(t4)) e2.push(l2.i, t4.i, u2.i), el(t4), t4 = u2.next, o2 = u2.next;
              else if ((t4 = u2) === o2) {
                a2 ? 1 === a2 ? To(t4 = Do(Fo(t4), e2), e2, r2, n2, i2, s2, 2) : 2 === a2 && Oo(t4, e2, r2, n2, i2, s2) : To(Fo(t4), e2, r2, n2, i2, s2, 1);
                break;
              }
            }
          }
          function $o(t4) {
            const e2 = t4.prev, r2 = t4, n2 = t4.next;
            if (Ko(e2, r2, n2) >= 0) return false;
            const i2 = e2.x, s2 = r2.x, a2 = n2.x, o2 = e2.y, l2 = r2.y, u2 = n2.y, c2 = i2 < s2 ? i2 < a2 ? i2 : a2 : s2 < a2 ? s2 : a2, h2 = o2 < l2 ? o2 < u2 ? o2 : u2 : l2 < u2 ? l2 : u2, p2 = i2 > s2 ? i2 > a2 ? i2 : a2 : s2 > a2 ? s2 : a2, f2 = o2 > l2 ? o2 > u2 ? o2 : u2 : l2 > u2 ? l2 : u2;
            let d2 = n2.next;
            for (; d2 !== e2; ) {
              if (d2.x >= c2 && d2.x <= p2 && d2.y >= h2 && d2.y <= f2 && Zo(i2, o2, s2, l2, a2, u2, d2.x, d2.y) && Ko(d2.prev, d2, d2.next) >= 0) return false;
              d2 = d2.next;
            }
            return true;
          }
          function Lo(t4, e2, r2, n2) {
            const i2 = t4.prev, s2 = t4, a2 = t4.next;
            if (Ko(i2, s2, a2) >= 0) return false;
            const o2 = i2.x, l2 = s2.x, u2 = a2.x, c2 = i2.y, h2 = s2.y, p2 = a2.y, f2 = o2 < l2 ? o2 < u2 ? o2 : u2 : l2 < u2 ? l2 : u2, d2 = c2 < h2 ? c2 < p2 ? c2 : p2 : h2 < p2 ? h2 : p2, y2 = o2 > l2 ? o2 > u2 ? o2 : u2 : l2 > u2 ? l2 : u2, m2 = c2 > h2 ? c2 > p2 ? c2 : p2 : h2 > p2 ? h2 : p2, g2 = qo(f2, d2, e2, r2, n2), x2 = qo(y2, m2, e2, r2, n2);
            let v2 = t4.prevZ, b2 = t4.nextZ;
            for (; v2 && v2.z >= g2 && b2 && b2.z <= x2; ) {
              if (v2.x >= f2 && v2.x <= y2 && v2.y >= d2 && v2.y <= m2 && v2 !== i2 && v2 !== a2 && Zo(o2, c2, l2, h2, u2, p2, v2.x, v2.y) && Ko(v2.prev, v2, v2.next) >= 0) return false;
              if (v2 = v2.prevZ, b2.x >= f2 && b2.x <= y2 && b2.y >= d2 && b2.y <= m2 && b2 !== i2 && b2 !== a2 && Zo(o2, c2, l2, h2, u2, p2, b2.x, b2.y) && Ko(b2.prev, b2, b2.next) >= 0) return false;
              b2 = b2.nextZ;
            }
            for (; v2 && v2.z >= g2; ) {
              if (v2.x >= f2 && v2.x <= y2 && v2.y >= d2 && v2.y <= m2 && v2 !== i2 && v2 !== a2 && Zo(o2, c2, l2, h2, u2, p2, v2.x, v2.y) && Ko(v2.prev, v2, v2.next) >= 0) return false;
              v2 = v2.prevZ;
            }
            for (; b2 && b2.z <= x2; ) {
              if (b2.x >= f2 && b2.x <= y2 && b2.y >= d2 && b2.y <= m2 && b2 !== i2 && b2 !== a2 && Zo(o2, c2, l2, h2, u2, p2, b2.x, b2.y) && Ko(b2.prev, b2, b2.next) >= 0) return false;
              b2 = b2.nextZ;
            }
            return true;
          }
          function Do(t4, e2) {
            let r2 = t4;
            do {
              const n2 = r2.prev, i2 = r2.next.next;
              !Xo(n2, i2) && Ho(n2, r2, r2.next, i2) && Wo(n2, i2) && Wo(i2, n2) && (e2.push(n2.i, r2.i, i2.i), el(r2), el(r2.next), r2 = t4 = i2), r2 = r2.next;
            } while (r2 !== t4);
            return Fo(r2);
          }
          function Oo(t4, e2, r2, n2, i2, s2) {
            let a2 = t4;
            do {
              let t5 = a2.next.next;
              for (; t5 !== a2.prev; ) {
                if (a2.i !== t5.i && Go(a2, t5)) {
                  let o2 = Qo(a2, t5);
                  return a2 = Fo(a2, a2.next), o2 = Fo(o2, o2.next), To(a2, e2, r2, n2, i2, s2, 0), void To(o2, e2, r2, n2, i2, s2, 0);
                }
                t5 = t5.next;
              }
              a2 = a2.next;
            } while (a2 !== t4);
          }
          function jo(t4, e2) {
            return t4.x - e2.x;
          }
          function Ro(t4, e2) {
            const r2 = function(t5, e3) {
              let r3 = e3;
              const n3 = t5.x, i2 = t5.y;
              let s2, a2 = -1 / 0;
              do {
                if (i2 <= r3.y && i2 >= r3.next.y && r3.next.y !== r3.y) {
                  const t6 = r3.x + (i2 - r3.y) * (r3.next.x - r3.x) / (r3.next.y - r3.y);
                  if (t6 <= n3 && t6 > a2 && (a2 = t6, s2 = r3.x < r3.next.x ? r3 : r3.next, t6 === n3)) return s2;
                }
                r3 = r3.next;
              } while (r3 !== e3);
              if (!s2) return null;
              const o2 = s2, l2 = s2.x, u2 = s2.y;
              let c2 = 1 / 0;
              r3 = s2;
              do {
                if (n3 >= r3.x && r3.x >= l2 && n3 !== r3.x && Zo(i2 < u2 ? n3 : a2, i2, l2, u2, i2 < u2 ? a2 : n3, i2, r3.x, r3.y)) {
                  const e4 = Math.abs(i2 - r3.y) / (n3 - r3.x);
                  Wo(r3, t5) && (e4 < c2 || e4 === c2 && (r3.x > s2.x || r3.x === s2.x && Uo(s2, r3))) && (s2 = r3, c2 = e4);
                }
                r3 = r3.next;
              } while (r3 !== o2);
              return s2;
            }(t4, e2);
            if (!r2) return e2;
            const n2 = Qo(r2, t4);
            return Fo(n2, n2.next), Fo(r2, r2.next);
          }
          function Uo(t4, e2) {
            return Ko(t4.prev, t4, e2.prev) < 0 && Ko(e2.next, t4, t4.next) < 0;
          }
          function qo(t4, e2, r2, n2, i2) {
            return (t4 = 1431655765 & ((t4 = 858993459 & ((t4 = 252645135 & ((t4 = 16711935 & ((t4 = (t4 - r2) * i2 | 0) | t4 << 8)) | t4 << 4)) | t4 << 2)) | t4 << 1)) | (e2 = 1431655765 & ((e2 = 858993459 & ((e2 = 252645135 & ((e2 = 16711935 & ((e2 = (e2 - n2) * i2 | 0) | e2 << 8)) | e2 << 4)) | e2 << 2)) | e2 << 1)) << 1;
          }
          function No(t4) {
            let e2 = t4, r2 = t4;
            do {
              (e2.x < r2.x || e2.x === r2.x && e2.y < r2.y) && (r2 = e2), e2 = e2.next;
            } while (e2 !== t4);
            return r2;
          }
          function Zo(t4, e2, r2, n2, i2, s2, a2, o2) {
            return (i2 - a2) * (e2 - o2) >= (t4 - a2) * (s2 - o2) && (t4 - a2) * (n2 - o2) >= (r2 - a2) * (e2 - o2) && (r2 - a2) * (s2 - o2) >= (i2 - a2) * (n2 - o2);
          }
          function Go(t4, e2) {
            return t4.next.i !== e2.i && t4.prev.i !== e2.i && !function(t5, e3) {
              let r2 = t5;
              do {
                if (r2.i !== t5.i && r2.next.i !== t5.i && r2.i !== e3.i && r2.next.i !== e3.i && Ho(r2, r2.next, t5, e3)) return true;
                r2 = r2.next;
              } while (r2 !== t5);
              return false;
            }(t4, e2) && (Wo(t4, e2) && Wo(e2, t4) && function(t5, e3) {
              let r2 = t5, n2 = false;
              const i2 = (t5.x + e3.x) / 2, s2 = (t5.y + e3.y) / 2;
              do {
                r2.y > s2 != r2.next.y > s2 && r2.next.y !== r2.y && i2 < (r2.next.x - r2.x) * (s2 - r2.y) / (r2.next.y - r2.y) + r2.x && (n2 = !n2), r2 = r2.next;
              } while (r2 !== t5);
              return n2;
            }(t4, e2) && (Ko(t4.prev, t4, e2.prev) || Ko(t4, e2.prev, e2)) || Xo(t4, e2) && Ko(t4.prev, t4, t4.next) > 0 && Ko(e2.prev, e2, e2.next) > 0);
          }
          function Ko(t4, e2, r2) {
            return (e2.y - t4.y) * (r2.x - e2.x) - (e2.x - t4.x) * (r2.y - e2.y);
          }
          function Xo(t4, e2) {
            return t4.x === e2.x && t4.y === e2.y;
          }
          function Ho(t4, e2, r2, n2) {
            const i2 = Jo(Ko(t4, e2, r2)), s2 = Jo(Ko(t4, e2, n2)), a2 = Jo(Ko(r2, n2, t4)), o2 = Jo(Ko(r2, n2, e2));
            return i2 !== s2 && a2 !== o2 || !(0 !== i2 || !Yo(t4, r2, e2)) || !(0 !== s2 || !Yo(t4, n2, e2)) || !(0 !== a2 || !Yo(r2, t4, n2)) || !(0 !== o2 || !Yo(r2, e2, n2));
          }
          function Yo(t4, e2, r2) {
            return e2.x <= Math.max(t4.x, r2.x) && e2.x >= Math.min(t4.x, r2.x) && e2.y <= Math.max(t4.y, r2.y) && e2.y >= Math.min(t4.y, r2.y);
          }
          function Jo(t4) {
            return t4 > 0 ? 1 : t4 < 0 ? -1 : 0;
          }
          function Wo(t4, e2) {
            return Ko(t4.prev, t4, t4.next) < 0 ? Ko(t4, e2, t4.next) >= 0 && Ko(t4, t4.prev, e2) >= 0 : Ko(t4, e2, t4.prev) < 0 || Ko(t4, t4.next, e2) < 0;
          }
          function Qo(t4, e2) {
            const r2 = rl(t4.i, t4.x, t4.y), n2 = rl(e2.i, e2.x, e2.y), i2 = t4.next, s2 = e2.prev;
            return t4.next = e2, e2.prev = t4, r2.next = i2, i2.prev = r2, n2.next = r2, r2.prev = n2, s2.next = n2, n2.prev = s2, n2;
          }
          function tl(t4, e2, r2, n2) {
            const i2 = rl(t4, e2, r2);
            return n2 ? (i2.next = n2.next, i2.prev = n2, n2.next.prev = i2, n2.next = i2) : (i2.prev = i2, i2.next = i2), i2;
          }
          function el(t4) {
            t4.next.prev = t4.prev, t4.prev.next = t4.next, t4.prevZ && (t4.prevZ.nextZ = t4.nextZ), t4.nextZ && (t4.nextZ.prevZ = t4.prevZ);
          }
          function rl(t4, e2, r2) {
            return { i: t4, x: e2, y: r2, prev: null, next: null, z: 0, prevZ: null, nextZ: null, steiner: false };
          }
          function nl(t4, e2, r2) {
            const n2 = r2.patternDependencies;
            let i2 = false;
            for (const r3 of e2) {
              const e3 = r3.paint.get(`${t4}-pattern`);
              e3.isConstant() || (i2 = true);
              const s2 = e3.constantOr(null);
              s2 && (i2 = true, n2[s2.to] = true, n2[s2.from] = true);
            }
            return i2;
          }
          function il(t4, e2, r2, n2, i2) {
            const s2 = i2.patternDependencies;
            for (const a2 of e2) {
              const e3 = a2.paint.get(`${t4}-pattern`).value;
              if ("constant" !== e3.kind) {
                let t5 = e3.evaluate({ zoom: n2 - 1 }, r2, {}, i2.availableImages), o2 = e3.evaluate({ zoom: n2 }, r2, {}, i2.availableImages), l2 = e3.evaluate({ zoom: n2 + 1 }, r2, {}, i2.availableImages);
                t5 = t5 && t5.name ? t5.name : t5, o2 = o2 && o2.name ? o2.name : o2, l2 = l2 && l2.name ? l2.name : l2, s2[t5] = true, s2[o2] = true, s2[l2] = true, r2.patterns[a2.id] = { min: t5, mid: o2, max: l2 };
              }
            }
            return r2;
          }
          class sl {
            constructor(t4) {
              this.zoom = t4.zoom, this.overscaling = t4.overscaling, this.layers = t4.layers, this.layerIds = this.layers.map((t5) => t5.id), this.index = t4.index, this.hasPattern = false, this.patternFeatures = [], this.layoutVertexArray = new Ks(), this.indexArray = new na(), this.indexArray2 = new ia(), this.programConfigurations = new Ea(t4.layers, t4.zoom), this.segments = new oa(), this.segments2 = new oa(), this.stateDependentLayerIds = this.layers.filter((t5) => t5.isStateDependent()).map((t5) => t5.id);
            }
            populate(t4, e2, r2) {
              this.hasPattern = nl("fill", this.layers, e2);
              const n2 = this.layers[0].layout.get("fill-sort-key"), i2 = !n2.isConstant(), s2 = [];
              for (const { feature: a2, id: o2, index: l2, sourceLayerIndex: u2 } of t4) {
                const t5 = this.layers[0]._featureFilter.needGeometry, c2 = ja(a2, t5);
                if (!this.layers[0]._featureFilter.filter(new Ui(this.zoom), c2, r2)) continue;
                const h2 = i2 ? n2.evaluate(c2, {}, r2, e2.availableImages) : void 0, p2 = { id: o2, properties: a2.properties, type: a2.type, sourceLayerIndex: u2, index: l2, geometry: t5 ? c2.geometry : Oa(a2), patterns: {}, sortKey: h2 };
                s2.push(p2);
              }
              i2 && s2.sort((t5, e3) => t5.sortKey - e3.sortKey);
              for (const n3 of s2) {
                const { geometry: i3, index: s3, sourceLayerIndex: a2 } = n3;
                if (this.hasPattern) {
                  const t5 = il("fill", this.layers, n3, this.zoom, e2);
                  this.patternFeatures.push(t5);
                } else this.addFeature(n3, i3, s3, r2, {});
                e2.featureIndex.insert(t4[s3].feature, i3, s3, a2, this.index);
              }
            }
            update(t4, e2, r2) {
              this.stateDependentLayers.length && this.programConfigurations.updatePaintArrays(t4, e2, this.stateDependentLayers, r2);
            }
            addFeatures(t4, e2, r2) {
              for (const t5 of this.patternFeatures) this.addFeature(t5, t5.geometry, t5.index, e2, r2);
            }
            isEmpty() {
              return 0 === this.layoutVertexArray.length;
            }
            uploadPending() {
              return !this.uploaded || this.programConfigurations.needsUpload;
            }
            upload(t4) {
              this.uploaded || (this.layoutVertexBuffer = t4.createVertexBuffer(this.layoutVertexArray, Bo), this.indexBuffer = t4.createIndexBuffer(this.indexArray), this.indexBuffer2 = t4.createIndexBuffer(this.indexArray2)), this.programConfigurations.upload(t4), this.uploaded = true;
            }
            destroy() {
              this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.indexBuffer2.destroy(), this.programConfigurations.destroy(), this.segments.destroy(), this.segments2.destroy());
            }
            addFeature(t4, e2, r2, n2, i2) {
              for (const t5 of xr(e2, 500)) {
                let e3 = 0;
                for (const r4 of t5) e3 += r4.length;
                const r3 = this.segments.prepareSegment(e3, this.layoutVertexArray, this.indexArray), n3 = r3.vertexLength, i3 = [], s2 = [];
                for (const e4 of t5) {
                  if (0 === e4.length) continue;
                  e4 !== t5[0] && s2.push(i3.length / 2);
                  const r4 = this.segments2.prepareSegment(e4.length, this.layoutVertexArray, this.indexArray2), n4 = r4.vertexLength;
                  this.layoutVertexArray.emplaceBack(e4[0].x, e4[0].y), this.indexArray2.emplaceBack(n4 + e4.length - 1, n4), i3.push(e4[0].x), i3.push(e4[0].y);
                  for (let t6 = 1; t6 < e4.length; t6++) this.layoutVertexArray.emplaceBack(e4[t6].x, e4[t6].y), this.indexArray2.emplaceBack(n4 + t6 - 1, n4 + t6), i3.push(e4[t6].x), i3.push(e4[t6].y);
                  r4.vertexLength += e4.length, r4.primitiveLength += e4.length;
                }
                const a2 = Vo(i3, s2);
                for (let t6 = 0; t6 < a2.length; t6 += 3) this.indexArray.emplaceBack(n3 + a2[t6], n3 + a2[t6 + 1], n3 + a2[t6 + 2]);
                r3.vertexLength += e3, r3.primitiveLength += a2.length / 3;
              }
              this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, t4, r2, i2, n2);
            }
          }
          let al, ol;
          wi("FillBucket", sl, { omit: ["layers", "patternFeatures"] });
          var ll = { get paint() {
            return ol = ol || new rs({ "fill-antialias": new Ji(G.paint_fill["fill-antialias"]), "fill-opacity": new Wi(G.paint_fill["fill-opacity"]), "fill-color": new Wi(G.paint_fill["fill-color"]), "fill-outline-color": new Wi(G.paint_fill["fill-outline-color"]), "fill-translate": new Ji(G.paint_fill["fill-translate"]), "fill-translate-anchor": new Ji(G.paint_fill["fill-translate-anchor"]), "fill-pattern": new Qi(G.paint_fill["fill-pattern"]) });
          }, get layout() {
            return al = al || new rs({ "fill-sort-key": new Wi(G.layout_fill["fill-sort-key"]) });
          } };
          class ul extends is {
            constructor(t4) {
              super(t4, ll);
            }
            recalculate(t4, e2) {
              super.recalculate(t4, e2);
              const r2 = this.paint._values["fill-outline-color"];
              "constant" === r2.value.kind && void 0 === r2.value.value && (this.paint._values["fill-outline-color"] = this.paint._values["fill-color"]);
            }
            createBucket(t4) {
              return new sl(t4);
            }
            queryRadius() {
              return eo(this.paint.get("fill-translate"));
            }
            queryIntersectsFeature(t4, e2, r2, n2, i2, s2, a2) {
              return Za(ro(t4, this.paint.get("fill-translate"), this.paint.get("fill-translate-anchor"), s2.angle, a2), n2);
            }
            isTileClipped() {
              return true;
            }
          }
          const cl = ls([{ name: "a_pos", components: 2, type: "Int16" }, { name: "a_normal_ed", components: 4, type: "Int16" }], 4), hl = ls([{ name: "a_centroid", components: 2, type: "Int16" }], 4), { members: pl } = cl;
          var fl = {}, dl = n, yl = ml;
          function ml(t4, e2, r2, n2, i2) {
            this.properties = {}, this.extent = r2, this.type = 0, this._pbf = t4, this._geometry = -1, this._keys = n2, this._values = i2, t4.readFields(gl2, this, e2);
          }
          function gl2(t4, e2, r2) {
            1 == t4 ? e2.id = r2.readVarint() : 2 == t4 ? function(t5, e3) {
              for (var r3 = t5.readVarint() + t5.pos; t5.pos < r3; ) {
                var n2 = e3._keys[t5.readVarint()], i2 = e3._values[t5.readVarint()];
                e3.properties[n2] = i2;
              }
            }(r2, e2) : 3 == t4 ? e2.type = r2.readVarint() : 4 == t4 && (e2._geometry = r2.pos);
          }
          function xl(t4) {
            for (var e2, r2, n2 = 0, i2 = 0, s2 = t4.length, a2 = s2 - 1; i2 < s2; a2 = i2++) n2 += ((r2 = t4[a2]).x - (e2 = t4[i2]).x) * (e2.y + r2.y);
            return n2;
          }
          ml.types = ["Unknown", "Point", "LineString", "Polygon"], ml.prototype.loadGeometry = function() {
            var t4 = this._pbf;
            t4.pos = this._geometry;
            for (var e2, r2 = t4.readVarint() + t4.pos, n2 = 1, i2 = 0, s2 = 0, a2 = 0, o2 = []; t4.pos < r2; ) {
              if (i2 <= 0) {
                var l2 = t4.readVarint();
                n2 = 7 & l2, i2 = l2 >> 3;
              }
              if (i2--, 1 === n2 || 2 === n2) s2 += t4.readSVarint(), a2 += t4.readSVarint(), 1 === n2 && (e2 && o2.push(e2), e2 = []), e2.push(new dl(s2, a2));
              else {
                if (7 !== n2) throw new Error("unknown command " + n2);
                e2 && e2.push(e2[0].clone());
              }
            }
            return e2 && o2.push(e2), o2;
          }, ml.prototype.bbox = function() {
            var t4 = this._pbf;
            t4.pos = this._geometry;
            for (var e2 = t4.readVarint() + t4.pos, r2 = 1, n2 = 0, i2 = 0, s2 = 0, a2 = 1 / 0, o2 = -1 / 0, l2 = 1 / 0, u2 = -1 / 0; t4.pos < e2; ) {
              if (n2 <= 0) {
                var c2 = t4.readVarint();
                r2 = 7 & c2, n2 = c2 >> 3;
              }
              if (n2--, 1 === r2 || 2 === r2) (i2 += t4.readSVarint()) < a2 && (a2 = i2), i2 > o2 && (o2 = i2), (s2 += t4.readSVarint()) < l2 && (l2 = s2), s2 > u2 && (u2 = s2);
              else if (7 !== r2) throw new Error("unknown command " + r2);
            }
            return [a2, l2, o2, u2];
          }, ml.prototype.toGeoJSON = function(t4, e2, r2) {
            var n2, i2, s2 = this.extent * Math.pow(2, r2), a2 = this.extent * t4, o2 = this.extent * e2, l2 = this.loadGeometry(), u2 = ml.types[this.type];
            function c2(t5) {
              for (var e3 = 0; e3 < t5.length; e3++) {
                var r3 = t5[e3];
                t5[e3] = [360 * (r3.x + a2) / s2 - 180, 360 / Math.PI * Math.atan(Math.exp((180 - 360 * (r3.y + o2) / s2) * Math.PI / 180)) - 90];
              }
            }
            switch (this.type) {
              case 1:
                var h2 = [];
                for (n2 = 0; n2 < l2.length; n2++) h2[n2] = l2[n2][0];
                c2(l2 = h2);
                break;
              case 2:
                for (n2 = 0; n2 < l2.length; n2++) c2(l2[n2]);
                break;
              case 3:
                for (l2 = function(t5) {
                  var e3 = t5.length;
                  if (e3 <= 1) return [t5];
                  for (var r3, n3, i3 = [], s3 = 0; s3 < e3; s3++) {
                    var a3 = xl(t5[s3]);
                    0 !== a3 && (void 0 === n3 && (n3 = a3 < 0), n3 === a3 < 0 ? (r3 && i3.push(r3), r3 = [t5[s3]]) : r3.push(t5[s3]));
                  }
                  return r3 && i3.push(r3), i3;
                }(l2), n2 = 0; n2 < l2.length; n2++) for (i2 = 0; i2 < l2[n2].length; i2++) c2(l2[n2][i2]);
            }
            1 === l2.length ? l2 = l2[0] : u2 = "Multi" + u2;
            var p2 = { type: "Feature", geometry: { type: u2, coordinates: l2 }, properties: this.properties };
            return "id" in this && (p2.id = this.id), p2;
          };
          var vl = yl, bl = wl;
          function wl(t4, e2) {
            this.version = 1, this.name = null, this.extent = 4096, this.length = 0, this._pbf = t4, this._keys = [], this._values = [], this._features = [], t4.readFields(_l, this, e2), this.length = this._features.length;
          }
          function _l(t4, e2, r2) {
            15 === t4 ? e2.version = r2.readVarint() : 1 === t4 ? e2.name = r2.readString() : 5 === t4 ? e2.extent = r2.readVarint() : 2 === t4 ? e2._features.push(r2.pos) : 3 === t4 ? e2._keys.push(r2.readString()) : 4 === t4 && e2._values.push(function(t5) {
              for (var e3 = null, r3 = t5.readVarint() + t5.pos; t5.pos < r3; ) {
                var n2 = t5.readVarint() >> 3;
                e3 = 1 === n2 ? t5.readString() : 2 === n2 ? t5.readFloat() : 3 === n2 ? t5.readDouble() : 4 === n2 ? t5.readVarint64() : 5 === n2 ? t5.readVarint() : 6 === n2 ? t5.readSVarint() : 7 === n2 ? t5.readBoolean() : null;
              }
              return e3;
            }(r2));
          }
          wl.prototype.feature = function(t4) {
            if (t4 < 0 || t4 >= this._features.length) throw new Error("feature index out of bounds");
            this._pbf.pos = this._features[t4];
            var e2 = this._pbf.readVarint() + this._pbf.pos;
            return new vl(this._pbf, e2, this.extent, this._keys, this._values);
          };
          var Al = bl;
          function Sl(t4, e2, r2) {
            if (3 === t4) {
              var n2 = new Al(r2, r2.readVarint() + r2.pos);
              n2.length && (e2[n2.name] = n2);
            }
          }
          fl.VectorTile = function(t4, e2) {
            this.layers = t4.readFields(Sl, {}, e2);
          }, fl.VectorTileFeature = yl, fl.VectorTileLayer = bl;
          const kl = fl.VectorTileFeature.types, Ml = Math.pow(2, 13);
          function Il(t4, e2, r2, n2, i2, s2, a2, o2) {
            t4.emplaceBack(e2, r2, 2 * Math.floor(n2 * Ml) + a2, i2 * Ml * 2, s2 * Ml * 2, Math.round(o2));
          }
          class zl {
            constructor(t4) {
              this.zoom = t4.zoom, this.overscaling = t4.overscaling, this.layers = t4.layers, this.layerIds = this.layers.map((t5) => t5.id), this.index = t4.index, this.hasPattern = false, this.layoutVertexArray = new Xs(), this.centroidVertexArray = new Zs(), this.indexArray = new na(), this.programConfigurations = new Ea(t4.layers, t4.zoom), this.segments = new oa(), this.stateDependentLayerIds = this.layers.filter((t5) => t5.isStateDependent()).map((t5) => t5.id);
            }
            populate(t4, e2, r2) {
              this.features = [], this.hasPattern = nl("fill-extrusion", this.layers, e2);
              for (const { feature: n2, id: i2, index: s2, sourceLayerIndex: a2 } of t4) {
                const t5 = this.layers[0]._featureFilter.needGeometry, o2 = ja(n2, t5);
                if (!this.layers[0]._featureFilter.filter(new Ui(this.zoom), o2, r2)) continue;
                const l2 = { id: i2, sourceLayerIndex: a2, index: s2, geometry: t5 ? o2.geometry : Oa(n2), properties: n2.properties, type: n2.type, patterns: {} };
                this.hasPattern ? this.features.push(il("fill-extrusion", this.layers, l2, this.zoom, e2)) : this.addFeature(l2, l2.geometry, s2, r2, {}), e2.featureIndex.insert(n2, l2.geometry, s2, a2, this.index, true);
              }
            }
            addFeatures(t4, e2, r2) {
              for (const t5 of this.features) {
                const { geometry: n2 } = t5;
                this.addFeature(t5, n2, t5.index, e2, r2);
              }
            }
            update(t4, e2, r2) {
              this.stateDependentLayers.length && this.programConfigurations.updatePaintArrays(t4, e2, this.stateDependentLayers, r2);
            }
            isEmpty() {
              return 0 === this.layoutVertexArray.length && 0 === this.centroidVertexArray.length;
            }
            uploadPending() {
              return !this.uploaded || this.programConfigurations.needsUpload;
            }
            upload(t4) {
              this.uploaded || (this.layoutVertexBuffer = t4.createVertexBuffer(this.layoutVertexArray, pl), this.centroidVertexBuffer = t4.createVertexBuffer(this.centroidVertexArray, hl.members, true), this.indexBuffer = t4.createIndexBuffer(this.indexArray)), this.programConfigurations.upload(t4), this.uploaded = true;
            }
            destroy() {
              this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy(), this.centroidVertexBuffer.destroy());
            }
            addFeature(t4, e2, r2, n2, i2) {
              for (const r3 of xr(e2, 500)) {
                const e3 = { x: 0, y: 0, vertexCount: 0 };
                let n3 = 0;
                for (const t5 of r3) n3 += t5.length;
                let i3 = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);
                for (const t5 of r3) {
                  if (0 === t5.length) continue;
                  if (Cl(t5)) continue;
                  let r4 = 0;
                  for (let n4 = 0; n4 < t5.length; n4++) {
                    const s3 = t5[n4];
                    if (n4 >= 1) {
                      const a3 = t5[n4 - 1];
                      if (!Pl(s3, a3)) {
                        i3.vertexLength + 4 > oa.MAX_VERTEX_ARRAY_LENGTH && (i3 = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray));
                        const t6 = s3.sub(a3)._perp()._unit(), n5 = a3.dist(s3);
                        r4 + n5 > 32768 && (r4 = 0), Il(this.layoutVertexArray, s3.x, s3.y, t6.x, t6.y, 0, 0, r4), Il(this.layoutVertexArray, s3.x, s3.y, t6.x, t6.y, 0, 1, r4), e3.x += 2 * s3.x, e3.y += 2 * s3.y, e3.vertexCount += 2, r4 += n5, Il(this.layoutVertexArray, a3.x, a3.y, t6.x, t6.y, 0, 0, r4), Il(this.layoutVertexArray, a3.x, a3.y, t6.x, t6.y, 0, 1, r4), e3.x += 2 * a3.x, e3.y += 2 * a3.y, e3.vertexCount += 2;
                        const o3 = i3.vertexLength;
                        this.indexArray.emplaceBack(o3, o3 + 2, o3 + 1), this.indexArray.emplaceBack(o3 + 1, o3 + 2, o3 + 3), i3.vertexLength += 4, i3.primitiveLength += 2;
                      }
                    }
                  }
                }
                if (i3.vertexLength + n3 > oa.MAX_VERTEX_ARRAY_LENGTH && (i3 = this.segments.prepareSegment(n3, this.layoutVertexArray, this.indexArray)), "Polygon" !== kl[t4.type]) continue;
                const s2 = [], a2 = [], o2 = i3.vertexLength;
                for (const t5 of r3) if (0 !== t5.length) {
                  t5 !== r3[0] && a2.push(s2.length / 2);
                  for (let r4 = 0; r4 < t5.length; r4++) {
                    const n4 = t5[r4];
                    Il(this.layoutVertexArray, n4.x, n4.y, 0, 0, 1, 1, 0), e3.x += n4.x, e3.y += n4.y, e3.vertexCount += 1, s2.push(n4.x), s2.push(n4.y);
                  }
                }
                const l2 = Vo(s2, a2);
                for (let t5 = 0; t5 < l2.length; t5 += 3) this.indexArray.emplaceBack(o2 + l2[t5], o2 + l2[t5 + 2], o2 + l2[t5 + 1]);
                i3.primitiveLength += l2.length / 3, i3.vertexLength += n3;
                for (let t5 = 0; t5 < e3.vertexCount; t5++) {
                  const t6 = Math.floor(e3.x / e3.vertexCount), r4 = Math.floor(e3.y / e3.vertexCount);
                  this.centroidVertexArray.emplaceBack(t6, r4);
                }
              }
              this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, t4, r2, i2, n2);
            }
          }
          function Pl(t4, e2) {
            return t4.x === e2.x && (t4.x < 0 || t4.x > $a) || t4.y === e2.y && (t4.y < 0 || t4.y > $a);
          }
          function Cl(t4) {
            return t4.every((t5) => t5.x < 0) || t4.every((t5) => t5.x > $a) || t4.every((t5) => t5.y < 0) || t4.every((t5) => t5.y > $a);
          }
          let Bl;
          wi("FillExtrusionBucket", zl, { omit: ["layers", "features"] });
          var Vl = { get paint() {
            return Bl = Bl || new rs({ "fill-extrusion-opacity": new Ji(G["paint_fill-extrusion"]["fill-extrusion-opacity"]), "fill-extrusion-color": new Wi(G["paint_fill-extrusion"]["fill-extrusion-color"]), "fill-extrusion-translate": new Ji(G["paint_fill-extrusion"]["fill-extrusion-translate"]), "fill-extrusion-translate-anchor": new Ji(G["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]), "fill-extrusion-pattern": new Qi(G["paint_fill-extrusion"]["fill-extrusion-pattern"]), "fill-extrusion-height": new Wi(G["paint_fill-extrusion"]["fill-extrusion-height"]), "fill-extrusion-base": new Wi(G["paint_fill-extrusion"]["fill-extrusion-base"]), "fill-extrusion-vertical-gradient": new Ji(G["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]) });
          } };
          class El extends is {
            constructor(t4) {
              super(t4, Vl);
            }
            createBucket(t4) {
              return new zl(t4);
            }
            queryRadius() {
              return eo(this.paint.get("fill-extrusion-translate"));
            }
            is3D() {
              return true;
            }
            queryIntersectsFeature(t4, e2, r2, n2, i2, a2, o2, l2) {
              const u2 = ro(t4, this.paint.get("fill-extrusion-translate"), this.paint.get("fill-extrusion-translate-anchor"), a2.angle, o2), c2 = this.paint.get("fill-extrusion-height").evaluate(e2, r2), h2 = this.paint.get("fill-extrusion-base").evaluate(e2, r2), p2 = function(t5, e3, r3, n3) {
                const i3 = [];
                for (const r4 of t5) {
                  const t6 = [r4.x, r4.y, 0, 1];
                  po(t6, t6, e3), i3.push(new s(t6[0] / t6[3], t6[1] / t6[3]));
                }
                return i3;
              }(u2, l2), f2 = function(t5, e3, r3, n3) {
                const i3 = [], a3 = [], o3 = n3[8] * e3, l3 = n3[9] * e3, u3 = n3[10] * e3, c3 = n3[11] * e3, h3 = n3[8] * r3, p3 = n3[9] * r3, f3 = n3[10] * r3, d2 = n3[11] * r3;
                for (const e4 of t5) {
                  const t6 = [], r4 = [];
                  for (const i4 of e4) {
                    const e5 = i4.x, a4 = i4.y, y2 = n3[0] * e5 + n3[4] * a4 + n3[12], m2 = n3[1] * e5 + n3[5] * a4 + n3[13], g2 = n3[2] * e5 + n3[6] * a4 + n3[14], x2 = n3[3] * e5 + n3[7] * a4 + n3[15], v2 = g2 + u3, b2 = x2 + c3, w2 = y2 + h3, _2 = m2 + p3, A3 = g2 + f3, S2 = x2 + d2, k2 = new s((y2 + o3) / b2, (m2 + l3) / b2);
                    k2.z = v2 / b2, t6.push(k2);
                    const M2 = new s(w2 / S2, _2 / S2);
                    M2.z = A3 / S2, r4.push(M2);
                  }
                  i3.push(t6), a3.push(r4);
                }
                return [i3, a3];
              }(n2, h2, c2, l2);
              return function(t5, e3, r3) {
                let n3 = 1 / 0;
                Za(r3, e3) && (n3 = Tl(r3, e3[0]));
                for (let i3 = 0; i3 < e3.length; i3++) {
                  const s2 = e3[i3], a3 = t5[i3];
                  for (let t6 = 0; t6 < s2.length - 1; t6++) {
                    const e4 = s2[t6], i4 = [e4, s2[t6 + 1], a3[t6 + 1], a3[t6], e4];
                    qa(r3, i4) && (n3 = Math.min(n3, Tl(r3, i4)));
                  }
                }
                return n3 !== 1 / 0 && n3;
              }(f2[0], f2[1], p2);
            }
          }
          function Fl(t4, e2) {
            return t4.x * e2.x + t4.y * e2.y;
          }
          function Tl(t4, e2) {
            if (1 === t4.length) {
              let r2 = 0;
              const n2 = e2[r2++];
              let i2;
              for (; !i2 || n2.equals(i2); ) if (i2 = e2[r2++], !i2) return 1 / 0;
              for (; r2 < e2.length; r2++) {
                const s2 = e2[r2], a2 = t4[0], o2 = i2.sub(n2), l2 = s2.sub(n2), u2 = a2.sub(n2), c2 = Fl(o2, o2), h2 = Fl(o2, l2), p2 = Fl(l2, l2), f2 = Fl(u2, o2), d2 = Fl(u2, l2), y2 = c2 * p2 - h2 * h2, m2 = (p2 * f2 - h2 * d2) / y2, g2 = (c2 * d2 - h2 * f2) / y2, x2 = n2.z * (1 - m2 - g2) + i2.z * m2 + s2.z * g2;
                if (isFinite(x2)) return x2;
              }
              return 1 / 0;
            }
            {
              let t5 = 1 / 0;
              for (const r2 of e2) t5 = Math.min(t5, r2.z);
              return t5;
            }
          }
          const $l = ls([{ name: "a_pos_normal", components: 2, type: "Int16" }, { name: "a_data", components: 4, type: "Uint8" }], 4), { members: Ll } = $l, Dl = ls([{ name: "a_uv_x", components: 1, type: "Float32" }, { name: "a_split_index", components: 1, type: "Float32" }]), { members: Ol } = Dl, jl = fl.VectorTileFeature.types, Rl = Math.cos(Math.PI / 180 * 37.5), Ul = Math.pow(2, 14) / 0.5;
          class ql {
            constructor(t4) {
              this.zoom = t4.zoom, this.overscaling = t4.overscaling, this.layers = t4.layers, this.layerIds = this.layers.map((t5) => t5.id), this.index = t4.index, this.hasPattern = false, this.patternFeatures = [], this.lineClipsArray = [], this.gradients = {}, this.layers.forEach((t5) => {
                this.gradients[t5.id] = {};
              }), this.layoutVertexArray = new Hs(), this.layoutVertexArray2 = new Ys(), this.indexArray = new na(), this.programConfigurations = new Ea(t4.layers, t4.zoom), this.segments = new oa(), this.maxLineLength = 0, this.stateDependentLayerIds = this.layers.filter((t5) => t5.isStateDependent()).map((t5) => t5.id);
            }
            populate(t4, e2, r2) {
              this.hasPattern = nl("line", this.layers, e2);
              const n2 = this.layers[0].layout.get("line-sort-key"), i2 = !n2.isConstant(), s2 = [];
              for (const { feature: e3, id: a2, index: o2, sourceLayerIndex: l2 } of t4) {
                const t5 = this.layers[0]._featureFilter.needGeometry, u2 = ja(e3, t5);
                if (!this.layers[0]._featureFilter.filter(new Ui(this.zoom), u2, r2)) continue;
                const c2 = i2 ? n2.evaluate(u2, {}, r2) : void 0, h2 = { id: a2, properties: e3.properties, type: e3.type, sourceLayerIndex: l2, index: o2, geometry: t5 ? u2.geometry : Oa(e3), patterns: {}, sortKey: c2 };
                s2.push(h2);
              }
              i2 && s2.sort((t5, e3) => t5.sortKey - e3.sortKey);
              for (const n3 of s2) {
                const { geometry: i3, index: s3, sourceLayerIndex: a2 } = n3;
                if (this.hasPattern) {
                  const t5 = il("line", this.layers, n3, this.zoom, e2);
                  this.patternFeatures.push(t5);
                } else this.addFeature(n3, i3, s3, r2, {});
                e2.featureIndex.insert(t4[s3].feature, i3, s3, a2, this.index);
              }
            }
            update(t4, e2, r2) {
              this.stateDependentLayers.length && this.programConfigurations.updatePaintArrays(t4, e2, this.stateDependentLayers, r2);
            }
            addFeatures(t4, e2, r2) {
              for (const t5 of this.patternFeatures) this.addFeature(t5, t5.geometry, t5.index, e2, r2);
            }
            isEmpty() {
              return 0 === this.layoutVertexArray.length;
            }
            uploadPending() {
              return !this.uploaded || this.programConfigurations.needsUpload;
            }
            upload(t4) {
              this.uploaded || (0 !== this.layoutVertexArray2.length && (this.layoutVertexBuffer2 = t4.createVertexBuffer(this.layoutVertexArray2, Ol)), this.layoutVertexBuffer = t4.createVertexBuffer(this.layoutVertexArray, Ll), this.indexBuffer = t4.createIndexBuffer(this.indexArray)), this.programConfigurations.upload(t4), this.uploaded = true;
            }
            destroy() {
              this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy());
            }
            lineFeatureClips(t4) {
              if (t4.properties && Object.prototype.hasOwnProperty.call(t4.properties, "mapbox_clip_start") && Object.prototype.hasOwnProperty.call(t4.properties, "mapbox_clip_end")) return { start: +t4.properties.mapbox_clip_start, end: +t4.properties.mapbox_clip_end };
            }
            addFeature(t4, e2, r2, n2, i2) {
              const s2 = this.layers[0].layout, a2 = s2.get("line-join").evaluate(t4, {}), o2 = s2.get("line-cap"), l2 = s2.get("line-miter-limit"), u2 = s2.get("line-round-limit");
              this.lineClips = this.lineFeatureClips(t4);
              for (const r3 of e2) this.addLine(r3, t4, a2, o2, l2, u2);
              this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, t4, r2, i2, n2);
            }
            addLine(t4, e2, r2, n2, i2, s2) {
              if (this.distance = 0, this.scaledDistance = 0, this.totalDistance = 0, this.lineClips) {
                this.lineClipsArray.push(this.lineClips);
                for (let e3 = 0; e3 < t4.length - 1; e3++) this.totalDistance += t4[e3].dist(t4[e3 + 1]);
                this.updateScaledDistance(), this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);
              }
              const a2 = "Polygon" === jl[e2.type];
              let o2 = t4.length;
              for (; o2 >= 2 && t4[o2 - 1].equals(t4[o2 - 2]); ) o2--;
              let l2 = 0;
              for (; l2 < o2 - 1 && t4[l2].equals(t4[l2 + 1]); ) l2++;
              if (o2 < (a2 ? 3 : 2)) return;
              "bevel" === r2 && (i2 = 1.05);
              const u2 = this.overscaling <= 16 ? 15 * $a / (512 * this.overscaling) : 0, c2 = this.segments.prepareSegment(10 * o2, this.layoutVertexArray, this.indexArray);
              let h2, p2, f2, d2, y2;
              this.e1 = this.e2 = -1, a2 && (h2 = t4[o2 - 2], y2 = t4[l2].sub(h2)._unit()._perp());
              for (let e3 = l2; e3 < o2; e3++) {
                if (f2 = e3 === o2 - 1 ? a2 ? t4[l2 + 1] : void 0 : t4[e3 + 1], f2 && t4[e3].equals(f2)) continue;
                y2 && (d2 = y2), h2 && (p2 = h2), h2 = t4[e3], y2 = f2 ? f2.sub(h2)._unit()._perp() : d2, d2 = d2 || y2;
                let m2 = d2.add(y2);
                0 === m2.x && 0 === m2.y || m2._unit();
                const g2 = d2.x * y2.x + d2.y * y2.y, x2 = m2.x * y2.x + m2.y * y2.y, v2 = 0 !== x2 ? 1 / x2 : 1 / 0, b2 = 2 * Math.sqrt(2 - 2 * x2), w2 = x2 < Rl && p2 && f2, _2 = d2.x * y2.y - d2.y * y2.x > 0;
                if (w2 && e3 > l2) {
                  const t5 = h2.dist(p2);
                  if (t5 > 2 * u2) {
                    const e4 = h2.sub(h2.sub(p2)._mult(u2 / t5)._round());
                    this.updateDistance(p2, e4), this.addCurrentVertex(e4, d2, 0, 0, c2), p2 = e4;
                  }
                }
                const A3 = p2 && f2;
                let S2 = A3 ? r2 : a2 ? "butt" : n2;
                if (A3 && "round" === S2 && (v2 < s2 ? S2 = "miter" : v2 <= 2 && (S2 = "fakeround")), "miter" === S2 && v2 > i2 && (S2 = "bevel"), "bevel" === S2 && (v2 > 2 && (S2 = "flipbevel"), v2 < i2 && (S2 = "miter")), p2 && this.updateDistance(p2, h2), "miter" === S2) m2._mult(v2), this.addCurrentVertex(h2, m2, 0, 0, c2);
                else if ("flipbevel" === S2) {
                  if (v2 > 100) m2 = y2.mult(-1);
                  else {
                    const t5 = v2 * d2.add(y2).mag() / d2.sub(y2).mag();
                    m2._perp()._mult(t5 * (_2 ? -1 : 1));
                  }
                  this.addCurrentVertex(h2, m2, 0, 0, c2), this.addCurrentVertex(h2, m2.mult(-1), 0, 0, c2);
                } else if ("bevel" === S2 || "fakeround" === S2) {
                  const t5 = -Math.sqrt(v2 * v2 - 1), e4 = _2 ? t5 : 0, r3 = _2 ? 0 : t5;
                  if (p2 && this.addCurrentVertex(h2, d2, e4, r3, c2), "fakeround" === S2) {
                    const t6 = Math.round(180 * b2 / Math.PI / 20);
                    for (let e5 = 1; e5 < t6; e5++) {
                      let r4 = e5 / t6;
                      if (0.5 !== r4) {
                        const t7 = r4 - 0.5;
                        r4 += r4 * t7 * (r4 - 1) * ((1.0904 + g2 * (g2 * (3.55645 - 1.43519 * g2) - 3.2452)) * t7 * t7 + (0.848013 + g2 * (0.215638 * g2 - 1.06021)));
                      }
                      const n3 = y2.sub(d2)._mult(r4)._add(d2)._unit()._mult(_2 ? -1 : 1);
                      this.addHalfVertex(h2, n3.x, n3.y, false, _2, 0, c2);
                    }
                  }
                  f2 && this.addCurrentVertex(h2, y2, -e4, -r3, c2);
                } else if ("butt" === S2) this.addCurrentVertex(h2, m2, 0, 0, c2);
                else if ("square" === S2) {
                  const t5 = p2 ? 1 : -1;
                  this.addCurrentVertex(h2, m2, t5, t5, c2);
                } else "round" === S2 && (p2 && (this.addCurrentVertex(h2, d2, 0, 0, c2), this.addCurrentVertex(h2, d2, 1, 1, c2, true)), f2 && (this.addCurrentVertex(h2, y2, -1, -1, c2, true), this.addCurrentVertex(h2, y2, 0, 0, c2)));
                if (w2 && e3 < o2 - 1) {
                  const t5 = h2.dist(f2);
                  if (t5 > 2 * u2) {
                    const e4 = h2.add(f2.sub(h2)._mult(u2 / t5)._round());
                    this.updateDistance(h2, e4), this.addCurrentVertex(e4, y2, 0, 0, c2), h2 = e4;
                  }
                }
              }
            }
            addCurrentVertex(t4, e2, r2, n2, i2, s2 = false) {
              const a2 = e2.y * n2 - e2.x, o2 = -e2.y - e2.x * n2;
              this.addHalfVertex(t4, e2.x + e2.y * r2, e2.y - e2.x * r2, s2, false, r2, i2), this.addHalfVertex(t4, a2, o2, s2, true, -n2, i2), this.distance > Ul / 2 && 0 === this.totalDistance && (this.distance = 0, this.updateScaledDistance(), this.addCurrentVertex(t4, e2, r2, n2, i2, s2));
            }
            addHalfVertex({ x: t4, y: e2 }, r2, n2, i2, s2, a2, o2) {
              const l2 = 0.5 * (this.lineClips ? this.scaledDistance * (Ul - 1) : this.scaledDistance);
              this.layoutVertexArray.emplaceBack((t4 << 1) + (i2 ? 1 : 0), (e2 << 1) + (s2 ? 1 : 0), Math.round(63 * r2) + 128, Math.round(63 * n2) + 128, 1 + (0 === a2 ? 0 : a2 < 0 ? -1 : 1) | (63 & l2) << 2, l2 >> 6), this.lineClips && this.layoutVertexArray2.emplaceBack((this.scaledDistance - this.lineClips.start) / (this.lineClips.end - this.lineClips.start), this.lineClipsArray.length);
              const u2 = o2.vertexLength++;
              this.e1 >= 0 && this.e2 >= 0 && (this.indexArray.emplaceBack(this.e1, this.e2, u2), o2.primitiveLength++), s2 ? this.e2 = u2 : this.e1 = u2;
            }
            updateScaledDistance() {
              this.scaledDistance = this.lineClips ? this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance : this.distance;
            }
            updateDistance(t4, e2) {
              this.distance += t4.dist(e2), this.updateScaledDistance();
            }
          }
          let Nl, Zl;
          wi("LineBucket", ql, { omit: ["layers", "patternFeatures"] });
          var Gl = { get paint() {
            return Zl = Zl || new rs({ "line-opacity": new Wi(G.paint_line["line-opacity"]), "line-color": new Wi(G.paint_line["line-color"]), "line-translate": new Ji(G.paint_line["line-translate"]), "line-translate-anchor": new Ji(G.paint_line["line-translate-anchor"]), "line-width": new Wi(G.paint_line["line-width"]), "line-gap-width": new Wi(G.paint_line["line-gap-width"]), "line-offset": new Wi(G.paint_line["line-offset"]), "line-blur": new Wi(G.paint_line["line-blur"]), "line-dasharray": new ts(G.paint_line["line-dasharray"]), "line-pattern": new Qi(G.paint_line["line-pattern"]), "line-gradient": new es(G.paint_line["line-gradient"]) });
          }, get layout() {
            return Nl = Nl || new rs({ "line-cap": new Ji(G.layout_line["line-cap"]), "line-join": new Wi(G.layout_line["line-join"]), "line-miter-limit": new Ji(G.layout_line["line-miter-limit"]), "line-round-limit": new Ji(G.layout_line["line-round-limit"]), "line-sort-key": new Wi(G.layout_line["line-sort-key"]) });
          } };
          class Kl extends Wi {
            possiblyEvaluate(t4, e2) {
              return e2 = new Ui(Math.floor(e2.zoom), { now: e2.now, fadeDuration: e2.fadeDuration, zoomHistory: e2.zoomHistory, transition: e2.transition }), super.possiblyEvaluate(t4, e2);
            }
            evaluate(t4, e2, r2, n2) {
              return e2 = g({}, e2, { zoom: Math.floor(e2.zoom) }), super.evaluate(t4, e2, r2, n2);
            }
          }
          let Xl;
          class Hl extends is {
            constructor(t4) {
              super(t4, Gl), this.gradientVersion = 0, Xl || (Xl = new Kl(Gl.paint.properties["line-width"].specification), Xl.useIntegerZoom = true);
            }
            _handleSpecialPaintPropertyUpdate(t4) {
              if ("line-gradient" === t4) {
                const t5 = this.gradientExpression();
                this.stepInterpolant = !!function(t6) {
                  return void 0 !== t6._styleExpression;
                }(t5) && t5._styleExpression.expression instanceof Ae, this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER;
              }
            }
            gradientExpression() {
              return this._transitionablePaint._values["line-gradient"].value.expression;
            }
            recalculate(t4, e2) {
              super.recalculate(t4, e2), this.paint._values["line-floorwidth"] = Xl.possiblyEvaluate(this._transitioningPaint._values["line-width"].value, t4);
            }
            createBucket(t4) {
              return new ql(t4);
            }
            queryRadius(t4) {
              const e2 = t4, r2 = Yl(to("line-width", this, e2), to("line-gap-width", this, e2)), n2 = to("line-offset", this, e2);
              return r2 / 2 + Math.abs(n2) + eo(this.paint.get("line-translate"));
            }
            queryIntersectsFeature(t4, e2, r2, n2, i2, a2, o2) {
              const l2 = ro(t4, this.paint.get("line-translate"), this.paint.get("line-translate-anchor"), a2.angle, o2), u2 = o2 / 2 * Yl(this.paint.get("line-width").evaluate(e2, r2), this.paint.get("line-gap-width").evaluate(e2, r2)), c2 = this.paint.get("line-offset").evaluate(e2, r2);
              return c2 && (n2 = function(t5, e3) {
                const r3 = [];
                for (let n3 = 0; n3 < t5.length; n3++) {
                  const i3 = t5[n3], a3 = [];
                  for (let t6 = 0; t6 < i3.length; t6++) {
                    const r4 = i3[t6 - 1], n4 = i3[t6], o3 = i3[t6 + 1], l3 = 0 === t6 ? new s(0, 0) : n4.sub(r4)._unit()._perp(), u3 = t6 === i3.length - 1 ? new s(0, 0) : o3.sub(n4)._unit()._perp(), c3 = l3._add(u3)._unit(), h2 = c3.x * u3.x + c3.y * u3.y;
                    0 !== h2 && c3._mult(1 / h2), a3.push(c3._mult(e3)._add(n4));
                  }
                  r3.push(a3);
                }
                return r3;
              }(n2, c2 * o2)), function(t5, e3, r3) {
                for (let n3 = 0; n3 < e3.length; n3++) {
                  const i3 = e3[n3];
                  if (t5.length >= 3) {
                    for (let e4 = 0; e4 < i3.length; e4++) if (Wa(t5, i3[e4])) return true;
                  }
                  if (Ga(t5, i3, r3)) return true;
                }
                return false;
              }(l2, n2, u2);
            }
            isTileClipped() {
              return true;
            }
          }
          function Yl(t4, e2) {
            return e2 > 0 ? e2 + 2 * t4 : t4;
          }
          const Jl = ls([{ name: "a_pos_offset", components: 4, type: "Int16" }, { name: "a_data", components: 4, type: "Uint16" }, { name: "a_pixeloffset", components: 4, type: "Int16" }], 4), Wl = ls([{ name: "a_projected_pos", components: 3, type: "Float32" }], 4);
          ls([{ name: "a_fade_opacity", components: 1, type: "Uint32" }], 4);
          const Ql = ls([{ name: "a_placed", components: 2, type: "Uint8" }, { name: "a_shift", components: 2, type: "Float32" }, { name: "a_box_real", components: 2, type: "Int16" }]);
          ls([{ type: "Int16", name: "anchorPointX" }, { type: "Int16", name: "anchorPointY" }, { type: "Int16", name: "x1" }, { type: "Int16", name: "y1" }, { type: "Int16", name: "x2" }, { type: "Int16", name: "y2" }, { type: "Uint32", name: "featureIndex" }, { type: "Uint16", name: "sourceLayerIndex" }, { type: "Uint16", name: "bucketIndex" }]);
          const tu = ls([{ name: "a_pos", components: 2, type: "Int16" }, { name: "a_anchor_pos", components: 2, type: "Int16" }, { name: "a_extrude", components: 2, type: "Int16" }], 4), eu = ls([{ name: "a_pos", components: 2, type: "Float32" }, { name: "a_radius", components: 1, type: "Float32" }, { name: "a_flags", components: 2, type: "Int16" }], 4);
          function ru(t4, e2, r2) {
            return t4.sections.forEach((t5) => {
              t5.text = function(t6, e3, r3) {
                const n2 = e3.layout.get("text-transform").evaluate(r3, {});
                return "uppercase" === n2 ? t6 = t6.toLocaleUpperCase() : "lowercase" === n2 && (t6 = t6.toLocaleLowerCase()), Ri.applyArabicShaping && (t6 = Ri.applyArabicShaping(t6)), t6;
              }(t5.text, e2, r2);
            }), t4;
          }
          ls([{ name: "triangle", components: 3, type: "Uint16" }]), ls([{ type: "Int16", name: "anchorX" }, { type: "Int16", name: "anchorY" }, { type: "Uint16", name: "glyphStartIndex" }, { type: "Uint16", name: "numGlyphs" }, { type: "Uint32", name: "vertexStartIndex" }, { type: "Uint32", name: "lineStartIndex" }, { type: "Uint32", name: "lineLength" }, { type: "Uint16", name: "segment" }, { type: "Uint16", name: "lowerSize" }, { type: "Uint16", name: "upperSize" }, { type: "Float32", name: "lineOffsetX" }, { type: "Float32", name: "lineOffsetY" }, { type: "Uint8", name: "writingMode" }, { type: "Uint8", name: "placedOrientation" }, { type: "Uint8", name: "hidden" }, { type: "Uint32", name: "crossTileID" }, { type: "Int16", name: "associatedIconIndex" }]), ls([{ type: "Int16", name: "anchorX" }, { type: "Int16", name: "anchorY" }, { type: "Int16", name: "rightJustifiedTextSymbolIndex" }, { type: "Int16", name: "centerJustifiedTextSymbolIndex" }, { type: "Int16", name: "leftJustifiedTextSymbolIndex" }, { type: "Int16", name: "verticalPlacedTextSymbolIndex" }, { type: "Int16", name: "placedIconSymbolIndex" }, { type: "Int16", name: "verticalPlacedIconSymbolIndex" }, { type: "Uint16", name: "key" }, { type: "Uint16", name: "textBoxStartIndex" }, { type: "Uint16", name: "textBoxEndIndex" }, { type: "Uint16", name: "verticalTextBoxStartIndex" }, { type: "Uint16", name: "verticalTextBoxEndIndex" }, { type: "Uint16", name: "iconBoxStartIndex" }, { type: "Uint16", name: "iconBoxEndIndex" }, { type: "Uint16", name: "verticalIconBoxStartIndex" }, { type: "Uint16", name: "verticalIconBoxEndIndex" }, { type: "Uint16", name: "featureIndex" }, { type: "Uint16", name: "numHorizontalGlyphVertices" }, { type: "Uint16", name: "numVerticalGlyphVertices" }, { type: "Uint16", name: "numIconVertices" }, { type: "Uint16", name: "numVerticalIconVertices" }, { type: "Uint16", name: "useRuntimeCollisionCircles" }, { type: "Uint32", name: "crossTileID" }, { type: "Float32", name: "textBoxScale" }, { type: "Float32", name: "collisionCircleDiameter" }, { type: "Uint16", name: "textAnchorOffsetStartIndex" }, { type: "Uint16", name: "textAnchorOffsetEndIndex" }]), ls([{ type: "Float32", name: "offsetX" }]), ls([{ type: "Int16", name: "x" }, { type: "Int16", name: "y" }, { type: "Int16", name: "tileUnitDistanceFromAnchor" }]), ls([{ type: "Uint16", name: "textAnchor" }, { type: "Float32", components: 2, name: "textOffset" }]);
          const nu = { "!": "\uFE15", "#": "\uFF03", $: "\uFF04", "%": "\uFF05", "&": "\uFF06", "(": "\uFE35", ")": "\uFE36", "*": "\uFF0A", "+": "\uFF0B", ",": "\uFE10", "-": "\uFE32", ".": "\u30FB", "/": "\uFF0F", ":": "\uFE13", ";": "\uFE14", "<": "\uFE3F", "=": "\uFF1D", ">": "\uFE40", "?": "\uFE16", "@": "\uFF20", "[": "\uFE47", "\\": "\uFF3C", "]": "\uFE48", "^": "\uFF3E", _: "\uFE33", "`": "\uFF40", "{": "\uFE37", "|": "\u2015", "}": "\uFE38", "~": "\uFF5E", "\xA2": "\uFFE0", "\xA3": "\uFFE1", "\xA5": "\uFFE5", "\xA6": "\uFFE4", "\xAC": "\uFFE2", "\xAF": "\uFFE3", "\u2013": "\uFE32", "\u2014": "\uFE31", "\u2018": "\uFE43", "\u2019": "\uFE44", "\u201C": "\uFE41", "\u201D": "\uFE42", "\u2026": "\uFE19", "\u2027": "\u30FB", "\u20A9": "\uFFE6", "\u3001": "\uFE11", "\u3002": "\uFE12", "\u3008": "\uFE3F", "\u3009": "\uFE40", "\u300A": "\uFE3D", "\u300B": "\uFE3E", "\u300C": "\uFE41", "\u300D": "\uFE42", "\u300E": "\uFE43", "\u300F": "\uFE44", "\u3010": "\uFE3B", "\u3011": "\uFE3C", "\u3014": "\uFE39", "\u3015": "\uFE3A", "\u3016": "\uFE17", "\u3017": "\uFE18", "\uFF01": "\uFE15", "\uFF08": "\uFE35", "\uFF09": "\uFE36", "\uFF0C": "\uFE10", "\uFF0D": "\uFE32", "\uFF0E": "\u30FB", "\uFF1A": "\uFE13", "\uFF1B": "\uFE14", "\uFF1C": "\uFE3F", "\uFF1E": "\uFE40", "\uFF1F": "\uFE16", "\uFF3B": "\uFE47", "\uFF3D": "\uFE48", "\uFF3F": "\uFE33", "\uFF5B": "\uFE37", "\uFF5C": "\u2015", "\uFF5D": "\uFE38", "\uFF5F": "\uFE35", "\uFF60": "\uFE36", "\uFF61": "\uFE12", "\uFF62": "\uFE41", "\uFF63": "\uFE42" };
          var iu = 24, su = lu, au = function(t4, e2, r2, n2, i2) {
            var s2, a2, o2 = 8 * i2 - n2 - 1, l2 = (1 << o2) - 1, u2 = l2 >> 1, c2 = -7, h2 = r2 ? i2 - 1 : 0, p2 = r2 ? -1 : 1, f2 = t4[e2 + h2];
            for (h2 += p2, s2 = f2 & (1 << -c2) - 1, f2 >>= -c2, c2 += o2; c2 > 0; s2 = 256 * s2 + t4[e2 + h2], h2 += p2, c2 -= 8) ;
            for (a2 = s2 & (1 << -c2) - 1, s2 >>= -c2, c2 += n2; c2 > 0; a2 = 256 * a2 + t4[e2 + h2], h2 += p2, c2 -= 8) ;
            if (0 === s2) s2 = 1 - u2;
            else {
              if (s2 === l2) return a2 ? NaN : 1 / 0 * (f2 ? -1 : 1);
              a2 += Math.pow(2, n2), s2 -= u2;
            }
            return (f2 ? -1 : 1) * a2 * Math.pow(2, s2 - n2);
          }, ou = function(t4, e2, r2, n2, i2, s2) {
            var a2, o2, l2, u2 = 8 * s2 - i2 - 1, c2 = (1 << u2) - 1, h2 = c2 >> 1, p2 = 23 === i2 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, f2 = n2 ? 0 : s2 - 1, d2 = n2 ? 1 : -1, y2 = e2 < 0 || 0 === e2 && 1 / e2 < 0 ? 1 : 0;
            for (e2 = Math.abs(e2), isNaN(e2) || e2 === 1 / 0 ? (o2 = isNaN(e2) ? 1 : 0, a2 = c2) : (a2 = Math.floor(Math.log(e2) / Math.LN2), e2 * (l2 = Math.pow(2, -a2)) < 1 && (a2--, l2 *= 2), (e2 += a2 + h2 >= 1 ? p2 / l2 : p2 * Math.pow(2, 1 - h2)) * l2 >= 2 && (a2++, l2 /= 2), a2 + h2 >= c2 ? (o2 = 0, a2 = c2) : a2 + h2 >= 1 ? (o2 = (e2 * l2 - 1) * Math.pow(2, i2), a2 += h2) : (o2 = e2 * Math.pow(2, h2 - 1) * Math.pow(2, i2), a2 = 0)); i2 >= 8; t4[r2 + f2] = 255 & o2, f2 += d2, o2 /= 256, i2 -= 8) ;
            for (a2 = a2 << i2 | o2, u2 += i2; u2 > 0; t4[r2 + f2] = 255 & a2, f2 += d2, a2 /= 256, u2 -= 8) ;
            t4[r2 + f2 - d2] |= 128 * y2;
          };
          function lu(t4) {
            this.buf = ArrayBuffer.isView && ArrayBuffer.isView(t4) ? t4 : new Uint8Array(t4 || 0), this.pos = 0, this.type = 0, this.length = this.buf.length;
          }
          lu.Varint = 0, lu.Fixed64 = 1, lu.Bytes = 2, lu.Fixed32 = 5;
          var uu = 4294967296, cu = 1 / uu, hu = "undefined" == typeof TextDecoder ? null : new TextDecoder("utf-8");
          function pu(t4) {
            return t4.type === lu.Bytes ? t4.readVarint() + t4.pos : t4.pos + 1;
          }
          function fu(t4, e2, r2) {
            return r2 ? 4294967296 * e2 + (t4 >>> 0) : 4294967296 * (e2 >>> 0) + (t4 >>> 0);
          }
          function du(t4, e2, r2) {
            var n2 = e2 <= 16383 ? 1 : e2 <= 2097151 ? 2 : e2 <= 268435455 ? 3 : Math.floor(Math.log(e2) / (7 * Math.LN2));
            r2.realloc(n2);
            for (var i2 = r2.pos - 1; i2 >= t4; i2--) r2.buf[i2 + n2] = r2.buf[i2];
          }
          function yu(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeVarint(t4[r2]);
          }
          function mu(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeSVarint(t4[r2]);
          }
          function gu(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeFloat(t4[r2]);
          }
          function xu(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeDouble(t4[r2]);
          }
          function vu(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeBoolean(t4[r2]);
          }
          function bu(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeFixed32(t4[r2]);
          }
          function wu(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeSFixed32(t4[r2]);
          }
          function _u(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeFixed64(t4[r2]);
          }
          function Au(t4, e2) {
            for (var r2 = 0; r2 < t4.length; r2++) e2.writeSFixed64(t4[r2]);
          }
          function Su(t4, e2) {
            return (t4[e2] | t4[e2 + 1] << 8 | t4[e2 + 2] << 16) + 16777216 * t4[e2 + 3];
          }
          function ku(t4, e2, r2) {
            t4[r2] = e2, t4[r2 + 1] = e2 >>> 8, t4[r2 + 2] = e2 >>> 16, t4[r2 + 3] = e2 >>> 24;
          }
          function Mu(t4, e2) {
            return (t4[e2] | t4[e2 + 1] << 8 | t4[e2 + 2] << 16) + (t4[e2 + 3] << 24);
          }
          lu.prototype = { destroy: function() {
            this.buf = null;
          }, readFields: function(t4, e2, r2) {
            for (r2 = r2 || this.length; this.pos < r2; ) {
              var n2 = this.readVarint(), i2 = n2 >> 3, s2 = this.pos;
              this.type = 7 & n2, t4(i2, e2, this), this.pos === s2 && this.skip(n2);
            }
            return e2;
          }, readMessage: function(t4, e2) {
            return this.readFields(t4, e2, this.readVarint() + this.pos);
          }, readFixed32: function() {
            var t4 = Su(this.buf, this.pos);
            return this.pos += 4, t4;
          }, readSFixed32: function() {
            var t4 = Mu(this.buf, this.pos);
            return this.pos += 4, t4;
          }, readFixed64: function() {
            var t4 = Su(this.buf, this.pos) + Su(this.buf, this.pos + 4) * uu;
            return this.pos += 8, t4;
          }, readSFixed64: function() {
            var t4 = Su(this.buf, this.pos) + Mu(this.buf, this.pos + 4) * uu;
            return this.pos += 8, t4;
          }, readFloat: function() {
            var t4 = au(this.buf, this.pos, true, 23, 4);
            return this.pos += 4, t4;
          }, readDouble: function() {
            var t4 = au(this.buf, this.pos, true, 52, 8);
            return this.pos += 8, t4;
          }, readVarint: function(t4) {
            var e2, r2, n2 = this.buf;
            return e2 = 127 & (r2 = n2[this.pos++]), r2 < 128 ? e2 : (e2 |= (127 & (r2 = n2[this.pos++])) << 7, r2 < 128 ? e2 : (e2 |= (127 & (r2 = n2[this.pos++])) << 14, r2 < 128 ? e2 : (e2 |= (127 & (r2 = n2[this.pos++])) << 21, r2 < 128 ? e2 : function(t5, e3, r3) {
              var n3, i2, s2 = r3.buf;
              if (n3 = (112 & (i2 = s2[r3.pos++])) >> 4, i2 < 128) return fu(t5, n3, e3);
              if (n3 |= (127 & (i2 = s2[r3.pos++])) << 3, i2 < 128) return fu(t5, n3, e3);
              if (n3 |= (127 & (i2 = s2[r3.pos++])) << 10, i2 < 128) return fu(t5, n3, e3);
              if (n3 |= (127 & (i2 = s2[r3.pos++])) << 17, i2 < 128) return fu(t5, n3, e3);
              if (n3 |= (127 & (i2 = s2[r3.pos++])) << 24, i2 < 128) return fu(t5, n3, e3);
              if (n3 |= (1 & (i2 = s2[r3.pos++])) << 31, i2 < 128) return fu(t5, n3, e3);
              throw new Error("Expected varint not more than 10 bytes");
            }(e2 |= (15 & (r2 = n2[this.pos])) << 28, t4, this))));
          }, readVarint64: function() {
            return this.readVarint(true);
          }, readSVarint: function() {
            var t4 = this.readVarint();
            return t4 % 2 == 1 ? (t4 + 1) / -2 : t4 / 2;
          }, readBoolean: function() {
            return Boolean(this.readVarint());
          }, readString: function() {
            var t4 = this.readVarint() + this.pos, e2 = this.pos;
            return this.pos = t4, t4 - e2 >= 12 && hu ? function(t5, e3, r2) {
              return hu.decode(t5.subarray(e3, r2));
            }(this.buf, e2, t4) : function(t5, e3, r2) {
              for (var n2 = "", i2 = e3; i2 < r2; ) {
                var s2, a2, o2, l2 = t5[i2], u2 = null, c2 = l2 > 239 ? 4 : l2 > 223 ? 3 : l2 > 191 ? 2 : 1;
                if (i2 + c2 > r2) break;
                1 === c2 ? l2 < 128 && (u2 = l2) : 2 === c2 ? 128 == (192 & (s2 = t5[i2 + 1])) && (u2 = (31 & l2) << 6 | 63 & s2) <= 127 && (u2 = null) : 3 === c2 ? (a2 = t5[i2 + 2], 128 == (192 & (s2 = t5[i2 + 1])) && 128 == (192 & a2) && ((u2 = (15 & l2) << 12 | (63 & s2) << 6 | 63 & a2) <= 2047 || u2 >= 55296 && u2 <= 57343) && (u2 = null)) : 4 === c2 && (a2 = t5[i2 + 2], o2 = t5[i2 + 3], 128 == (192 & (s2 = t5[i2 + 1])) && 128 == (192 & a2) && 128 == (192 & o2) && ((u2 = (15 & l2) << 18 | (63 & s2) << 12 | (63 & a2) << 6 | 63 & o2) <= 65535 || u2 >= 1114112) && (u2 = null)), null === u2 ? (u2 = 65533, c2 = 1) : u2 > 65535 && (u2 -= 65536, n2 += String.fromCharCode(u2 >>> 10 & 1023 | 55296), u2 = 56320 | 1023 & u2), n2 += String.fromCharCode(u2), i2 += c2;
              }
              return n2;
            }(this.buf, e2, t4);
          }, readBytes: function() {
            var t4 = this.readVarint() + this.pos, e2 = this.buf.subarray(this.pos, t4);
            return this.pos = t4, e2;
          }, readPackedVarint: function(t4, e2) {
            if (this.type !== lu.Bytes) return t4.push(this.readVarint(e2));
            var r2 = pu(this);
            for (t4 = t4 || []; this.pos < r2; ) t4.push(this.readVarint(e2));
            return t4;
          }, readPackedSVarint: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readSVarint());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readSVarint());
            return t4;
          }, readPackedBoolean: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readBoolean());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readBoolean());
            return t4;
          }, readPackedFloat: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readFloat());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readFloat());
            return t4;
          }, readPackedDouble: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readDouble());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readDouble());
            return t4;
          }, readPackedFixed32: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readFixed32());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readFixed32());
            return t4;
          }, readPackedSFixed32: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readSFixed32());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readSFixed32());
            return t4;
          }, readPackedFixed64: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readFixed64());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readFixed64());
            return t4;
          }, readPackedSFixed64: function(t4) {
            if (this.type !== lu.Bytes) return t4.push(this.readSFixed64());
            var e2 = pu(this);
            for (t4 = t4 || []; this.pos < e2; ) t4.push(this.readSFixed64());
            return t4;
          }, skip: function(t4) {
            var e2 = 7 & t4;
            if (e2 === lu.Varint) for (; this.buf[this.pos++] > 127; ) ;
            else if (e2 === lu.Bytes) this.pos = this.readVarint() + this.pos;
            else if (e2 === lu.Fixed32) this.pos += 4;
            else {
              if (e2 !== lu.Fixed64) throw new Error("Unimplemented type: " + e2);
              this.pos += 8;
            }
          }, writeTag: function(t4, e2) {
            this.writeVarint(t4 << 3 | e2);
          }, realloc: function(t4) {
            for (var e2 = this.length || 16; e2 < this.pos + t4; ) e2 *= 2;
            if (e2 !== this.length) {
              var r2 = new Uint8Array(e2);
              r2.set(this.buf), this.buf = r2, this.length = e2;
            }
          }, finish: function() {
            return this.length = this.pos, this.pos = 0, this.buf.subarray(0, this.length);
          }, writeFixed32: function(t4) {
            this.realloc(4), ku(this.buf, t4, this.pos), this.pos += 4;
          }, writeSFixed32: function(t4) {
            this.realloc(4), ku(this.buf, t4, this.pos), this.pos += 4;
          }, writeFixed64: function(t4) {
            this.realloc(8), ku(this.buf, -1 & t4, this.pos), ku(this.buf, Math.floor(t4 * cu), this.pos + 4), this.pos += 8;
          }, writeSFixed64: function(t4) {
            this.realloc(8), ku(this.buf, -1 & t4, this.pos), ku(this.buf, Math.floor(t4 * cu), this.pos + 4), this.pos += 8;
          }, writeVarint: function(t4) {
            (t4 = +t4 || 0) > 268435455 || t4 < 0 ? function(t5, e2) {
              var r2, n2;
              if (t5 >= 0 ? (r2 = t5 % 4294967296 | 0, n2 = t5 / 4294967296 | 0) : (n2 = ~(-t5 / 4294967296), 4294967295 ^ (r2 = ~(-t5 % 4294967296)) ? r2 = r2 + 1 | 0 : (r2 = 0, n2 = n2 + 1 | 0)), t5 >= 18446744073709552e3 || t5 < -18446744073709552e3) throw new Error("Given varint doesn't fit into 10 bytes");
              e2.realloc(10), function(t6, e3, r3) {
                r3.buf[r3.pos++] = 127 & t6 | 128, t6 >>>= 7, r3.buf[r3.pos++] = 127 & t6 | 128, t6 >>>= 7, r3.buf[r3.pos++] = 127 & t6 | 128, t6 >>>= 7, r3.buf[r3.pos++] = 127 & t6 | 128, r3.buf[r3.pos] = 127 & (t6 >>>= 7);
              }(r2, 0, e2), function(t6, e3) {
                var r3 = (7 & t6) << 4;
                e3.buf[e3.pos++] |= r3 | ((t6 >>>= 3) ? 128 : 0), t6 && (e3.buf[e3.pos++] = 127 & t6 | ((t6 >>>= 7) ? 128 : 0), t6 && (e3.buf[e3.pos++] = 127 & t6 | ((t6 >>>= 7) ? 128 : 0), t6 && (e3.buf[e3.pos++] = 127 & t6 | ((t6 >>>= 7) ? 128 : 0), t6 && (e3.buf[e3.pos++] = 127 & t6 | ((t6 >>>= 7) ? 128 : 0), t6 && (e3.buf[e3.pos++] = 127 & t6)))));
              }(n2, e2);
            }(t4, this) : (this.realloc(4), this.buf[this.pos++] = 127 & t4 | (t4 > 127 ? 128 : 0), t4 <= 127 || (this.buf[this.pos++] = 127 & (t4 >>>= 7) | (t4 > 127 ? 128 : 0), t4 <= 127 || (this.buf[this.pos++] = 127 & (t4 >>>= 7) | (t4 > 127 ? 128 : 0), t4 <= 127 || (this.buf[this.pos++] = t4 >>> 7 & 127))));
          }, writeSVarint: function(t4) {
            this.writeVarint(t4 < 0 ? 2 * -t4 - 1 : 2 * t4);
          }, writeBoolean: function(t4) {
            this.writeVarint(Boolean(t4));
          }, writeString: function(t4) {
            t4 = String(t4), this.realloc(4 * t4.length), this.pos++;
            var e2 = this.pos;
            this.pos = function(t5, e3, r3) {
              for (var n2, i2, s2 = 0; s2 < e3.length; s2++) {
                if ((n2 = e3.charCodeAt(s2)) > 55295 && n2 < 57344) {
                  if (!i2) {
                    n2 > 56319 || s2 + 1 === e3.length ? (t5[r3++] = 239, t5[r3++] = 191, t5[r3++] = 189) : i2 = n2;
                    continue;
                  }
                  if (n2 < 56320) {
                    t5[r3++] = 239, t5[r3++] = 191, t5[r3++] = 189, i2 = n2;
                    continue;
                  }
                  n2 = i2 - 55296 << 10 | n2 - 56320 | 65536, i2 = null;
                } else i2 && (t5[r3++] = 239, t5[r3++] = 191, t5[r3++] = 189, i2 = null);
                n2 < 128 ? t5[r3++] = n2 : (n2 < 2048 ? t5[r3++] = n2 >> 6 | 192 : (n2 < 65536 ? t5[r3++] = n2 >> 12 | 224 : (t5[r3++] = n2 >> 18 | 240, t5[r3++] = n2 >> 12 & 63 | 128), t5[r3++] = n2 >> 6 & 63 | 128), t5[r3++] = 63 & n2 | 128);
              }
              return r3;
            }(this.buf, t4, this.pos);
            var r2 = this.pos - e2;
            r2 >= 128 && du(e2, r2, this), this.pos = e2 - 1, this.writeVarint(r2), this.pos += r2;
          }, writeFloat: function(t4) {
            this.realloc(4), ou(this.buf, t4, this.pos, true, 23, 4), this.pos += 4;
          }, writeDouble: function(t4) {
            this.realloc(8), ou(this.buf, t4, this.pos, true, 52, 8), this.pos += 8;
          }, writeBytes: function(t4) {
            var e2 = t4.length;
            this.writeVarint(e2), this.realloc(e2);
            for (var r2 = 0; r2 < e2; r2++) this.buf[this.pos++] = t4[r2];
          }, writeRawMessage: function(t4, e2) {
            this.pos++;
            var r2 = this.pos;
            t4(e2, this);
            var n2 = this.pos - r2;
            n2 >= 128 && du(r2, n2, this), this.pos = r2 - 1, this.writeVarint(n2), this.pos += n2;
          }, writeMessage: function(t4, e2, r2) {
            this.writeTag(t4, lu.Bytes), this.writeRawMessage(e2, r2);
          }, writePackedVarint: function(t4, e2) {
            e2.length && this.writeMessage(t4, yu, e2);
          }, writePackedSVarint: function(t4, e2) {
            e2.length && this.writeMessage(t4, mu, e2);
          }, writePackedBoolean: function(t4, e2) {
            e2.length && this.writeMessage(t4, vu, e2);
          }, writePackedFloat: function(t4, e2) {
            e2.length && this.writeMessage(t4, gu, e2);
          }, writePackedDouble: function(t4, e2) {
            e2.length && this.writeMessage(t4, xu, e2);
          }, writePackedFixed32: function(t4, e2) {
            e2.length && this.writeMessage(t4, bu, e2);
          }, writePackedSFixed32: function(t4, e2) {
            e2.length && this.writeMessage(t4, wu, e2);
          }, writePackedFixed64: function(t4, e2) {
            e2.length && this.writeMessage(t4, _u, e2);
          }, writePackedSFixed64: function(t4, e2) {
            e2.length && this.writeMessage(t4, Au, e2);
          }, writeBytesField: function(t4, e2) {
            this.writeTag(t4, lu.Bytes), this.writeBytes(e2);
          }, writeFixed32Field: function(t4, e2) {
            this.writeTag(t4, lu.Fixed32), this.writeFixed32(e2);
          }, writeSFixed32Field: function(t4, e2) {
            this.writeTag(t4, lu.Fixed32), this.writeSFixed32(e2);
          }, writeFixed64Field: function(t4, e2) {
            this.writeTag(t4, lu.Fixed64), this.writeFixed64(e2);
          }, writeSFixed64Field: function(t4, e2) {
            this.writeTag(t4, lu.Fixed64), this.writeSFixed64(e2);
          }, writeVarintField: function(t4, e2) {
            this.writeTag(t4, lu.Varint), this.writeVarint(e2);
          }, writeSVarintField: function(t4, e2) {
            this.writeTag(t4, lu.Varint), this.writeSVarint(e2);
          }, writeStringField: function(t4, e2) {
            this.writeTag(t4, lu.Bytes), this.writeString(e2);
          }, writeFloatField: function(t4, e2) {
            this.writeTag(t4, lu.Fixed32), this.writeFloat(e2);
          }, writeDoubleField: function(t4, e2) {
            this.writeTag(t4, lu.Fixed64), this.writeDouble(e2);
          }, writeBooleanField: function(t4, e2) {
            this.writeVarintField(t4, Boolean(e2));
          } };
          var Iu = r(su);
          const zu = 3;
          function Pu(t4, e2, r2) {
            1 === t4 && r2.readMessage(Cu, e2);
          }
          function Cu(t4, e2, r2) {
            if (3 === t4) {
              const { id: t5, bitmap: n2, width: i2, height: s2, left: a2, top: o2, advance: l2 } = r2.readMessage(Bu, {});
              e2.push({ id: t5, bitmap: new _o({ width: i2 + 2 * zu, height: s2 + 2 * zu }, n2), metrics: { width: i2, height: s2, left: a2, top: o2, advance: l2 } });
            }
          }
          function Bu(t4, e2, r2) {
            1 === t4 ? e2.id = r2.readVarint() : 2 === t4 ? e2.bitmap = r2.readBytes() : 3 === t4 ? e2.width = r2.readVarint() : 4 === t4 ? e2.height = r2.readVarint() : 5 === t4 ? e2.left = r2.readSVarint() : 6 === t4 ? e2.top = r2.readSVarint() : 7 === t4 && (e2.advance = r2.readVarint());
          }
          const Vu = zu;
          function Eu(t4) {
            let e2 = 0, r2 = 0;
            for (const n3 of t4) e2 += n3.w * n3.h, r2 = Math.max(r2, n3.w);
            t4.sort((t5, e3) => e3.h - t5.h);
            const n2 = [{ x: 0, y: 0, w: Math.max(Math.ceil(Math.sqrt(e2 / 0.95)), r2), h: 1 / 0 }];
            let i2 = 0, s2 = 0;
            for (const e3 of t4) for (let t5 = n2.length - 1; t5 >= 0; t5--) {
              const r3 = n2[t5];
              if (!(e3.w > r3.w || e3.h > r3.h)) {
                if (e3.x = r3.x, e3.y = r3.y, s2 = Math.max(s2, e3.y + e3.h), i2 = Math.max(i2, e3.x + e3.w), e3.w === r3.w && e3.h === r3.h) {
                  const e4 = n2.pop();
                  t5 < n2.length && (n2[t5] = e4);
                } else e3.h === r3.h ? (r3.x += e3.w, r3.w -= e3.w) : e3.w === r3.w ? (r3.y += e3.h, r3.h -= e3.h) : (n2.push({ x: r3.x + e3.w, y: r3.y, w: r3.w - e3.w, h: e3.h }), r3.y += e3.h, r3.h -= e3.h);
                break;
              }
            }
            return { w: i2, h: s2, fill: e2 / (i2 * s2) || 0 };
          }
          const Fu = 1;
          class Tu {
            constructor(t4, { pixelRatio: e2, version: r2, stretchX: n2, stretchY: i2, content: s2, textFitWidth: a2, textFitHeight: o2 }) {
              this.paddedRect = t4, this.pixelRatio = e2, this.stretchX = n2, this.stretchY = i2, this.content = s2, this.version = r2, this.textFitWidth = a2, this.textFitHeight = o2;
            }
            get tl() {
              return [this.paddedRect.x + Fu, this.paddedRect.y + Fu];
            }
            get br() {
              return [this.paddedRect.x + this.paddedRect.w - Fu, this.paddedRect.y + this.paddedRect.h - Fu];
            }
            get tlbr() {
              return this.tl.concat(this.br);
            }
            get displaySize() {
              return [(this.paddedRect.w - 2 * Fu) / this.pixelRatio, (this.paddedRect.h - 2 * Fu) / this.pixelRatio];
            }
          }
          class $u {
            constructor(t4, e2) {
              const r2 = {}, n2 = {};
              this.haveRenderCallbacks = [];
              const i2 = [];
              this.addImages(t4, r2, i2), this.addImages(e2, n2, i2);
              const { w: s2, h: a2 } = Eu(i2), o2 = new Ao({ width: s2 || 1, height: a2 || 1 });
              for (const e3 in t4) {
                const n3 = t4[e3], i3 = r2[e3].paddedRect;
                Ao.copy(n3.data, o2, { x: 0, y: 0 }, { x: i3.x + Fu, y: i3.y + Fu }, n3.data);
              }
              for (const t5 in e2) {
                const r3 = e2[t5], i3 = n2[t5].paddedRect, s3 = i3.x + Fu, a3 = i3.y + Fu, l2 = r3.data.width, u2 = r3.data.height;
                Ao.copy(r3.data, o2, { x: 0, y: 0 }, { x: s3, y: a3 }, r3.data), Ao.copy(r3.data, o2, { x: 0, y: u2 - 1 }, { x: s3, y: a3 - 1 }, { width: l2, height: 1 }), Ao.copy(r3.data, o2, { x: 0, y: 0 }, { x: s3, y: a3 + u2 }, { width: l2, height: 1 }), Ao.copy(r3.data, o2, { x: l2 - 1, y: 0 }, { x: s3 - 1, y: a3 }, { width: 1, height: u2 }), Ao.copy(r3.data, o2, { x: 0, y: 0 }, { x: s3 + l2, y: a3 }, { width: 1, height: u2 });
              }
              this.image = o2, this.iconPositions = r2, this.patternPositions = n2;
            }
            addImages(t4, e2, r2) {
              for (const n2 in t4) {
                const i2 = t4[n2], s2 = { x: 0, y: 0, w: i2.data.width + 2 * Fu, h: i2.data.height + 2 * Fu };
                r2.push(s2), e2[n2] = new Tu(s2, i2), i2.hasRenderCallback && this.haveRenderCallbacks.push(n2);
              }
            }
            patchUpdatedImages(t4, e2) {
              t4.dispatchRenderCallbacks(this.haveRenderCallbacks);
              for (const r2 in t4.updatedImages) this.patchUpdatedImage(this.iconPositions[r2], t4.getImage(r2), e2), this.patchUpdatedImage(this.patternPositions[r2], t4.getImage(r2), e2);
            }
            patchUpdatedImage(t4, e2, r2) {
              if (!t4 || !e2) return;
              if (t4.version === e2.version) return;
              t4.version = e2.version;
              const [n2, i2] = t4.tl;
              r2.update(e2.data, void 0, { x: n2, y: i2 });
            }
          }
          var Lu;
          wi("ImagePosition", Tu), wi("ImageAtlas", $u), t.ah = void 0, (Lu = t.ah || (t.ah = {}))[Lu.none = 0] = "none", Lu[Lu.horizontal = 1] = "horizontal", Lu[Lu.vertical = 2] = "vertical", Lu[Lu.horizontalOnly = 3] = "horizontalOnly";
          const Du = -17;
          class Ou {
            constructor() {
              this.scale = 1, this.fontStack = "", this.imageName = null;
            }
            static forText(t4, e2) {
              const r2 = new Ou();
              return r2.scale = t4 || 1, r2.fontStack = e2, r2;
            }
            static forImage(t4) {
              const e2 = new Ou();
              return e2.imageName = t4, e2;
            }
          }
          class ju {
            constructor() {
              this.text = "", this.sectionIndex = [], this.sections = [], this.imageSectionID = null;
            }
            static fromFeature(t4, e2) {
              const r2 = new ju();
              for (let n2 = 0; n2 < t4.sections.length; n2++) {
                const i2 = t4.sections[n2];
                i2.image ? r2.addImageSection(i2) : r2.addTextSection(i2, e2);
              }
              return r2;
            }
            length() {
              return this.text.length;
            }
            getSection(t4) {
              return this.sections[this.sectionIndex[t4]];
            }
            getSectionIndex(t4) {
              return this.sectionIndex[t4];
            }
            getCharCode(t4) {
              return this.text.charCodeAt(t4);
            }
            verticalizePunctuation() {
              this.text = function(t4) {
                let e2 = "";
                for (let r2 = 0; r2 < t4.length; r2++) {
                  const n2 = t4.charCodeAt(r2 + 1) || null, i2 = t4.charCodeAt(r2 - 1) || null;
                  e2 += n2 && $i(n2) && !nu[t4[r2 + 1]] || i2 && $i(i2) && !nu[t4[r2 - 1]] || !nu[t4[r2]] ? t4[r2] : nu[t4[r2]];
                }
                return e2;
              }(this.text);
            }
            trim() {
              let t4 = 0;
              for (let e3 = 0; e3 < this.text.length && Uu[this.text.charCodeAt(e3)]; e3++) t4++;
              let e2 = this.text.length;
              for (let r2 = this.text.length - 1; r2 >= 0 && r2 >= t4 && Uu[this.text.charCodeAt(r2)]; r2--) e2--;
              this.text = this.text.substring(t4, e2), this.sectionIndex = this.sectionIndex.slice(t4, e2);
            }
            substring(t4, e2) {
              const r2 = new ju();
              return r2.text = this.text.substring(t4, e2), r2.sectionIndex = this.sectionIndex.slice(t4, e2), r2.sections = this.sections, r2;
            }
            toString() {
              return this.text;
            }
            getMaxScale() {
              return this.sectionIndex.reduce((t4, e2) => Math.max(t4, this.sections[e2].scale), 0);
            }
            addTextSection(t4, e2) {
              this.text += t4.text, this.sections.push(Ou.forText(t4.scale, t4.fontStack || e2));
              const r2 = this.sections.length - 1;
              for (let e3 = 0; e3 < t4.text.length; ++e3) this.sectionIndex.push(r2);
            }
            addImageSection(t4) {
              const e2 = t4.image ? t4.image.name : "";
              if (0 === e2.length) return void A2("Can't add FormattedSection with an empty image.");
              const r2 = this.getNextImageSectionCharCode();
              r2 ? (this.text += String.fromCharCode(r2), this.sections.push(Ou.forImage(e2)), this.sectionIndex.push(this.sections.length - 1)) : A2("Reached maximum number of images 6401");
            }
            getNextImageSectionCharCode() {
              return this.imageSectionID ? this.imageSectionID >= 63743 ? null : ++this.imageSectionID : (this.imageSectionID = 57344, this.imageSectionID);
            }
          }
          function Ru(e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2) {
            const m2 = ju.fromFeature(e2, s2);
            let g2;
            p2 === t.ah.vertical && m2.verticalizePunctuation();
            const { processBidirectionalText: x2, processStyledBidirectionalText: v2 } = Ri;
            if (x2 && 1 === m2.sections.length) {
              g2 = [];
              const t4 = x2(m2.toString(), Yu(m2, c2, a2, r2, i2, d2));
              for (const e3 of t4) {
                const t5 = new ju();
                t5.text = e3, t5.sections = m2.sections;
                for (let r3 = 0; r3 < e3.length; r3++) t5.sectionIndex.push(0);
                g2.push(t5);
              }
            } else if (v2) {
              g2 = [];
              const t4 = v2(m2.text, m2.sectionIndex, Yu(m2, c2, a2, r2, i2, d2));
              for (const e3 of t4) {
                const t5 = new ju();
                t5.text = e3[0], t5.sectionIndex = e3[1], t5.sections = m2.sections, g2.push(t5);
              }
            } else g2 = function(t4, e3) {
              const r3 = [], n3 = t4.text;
              let i3 = 0;
              for (const n4 of e3) r3.push(t4.substring(i3, n4)), i3 = n4;
              return i3 < n3.length && r3.push(t4.substring(i3, n3.length)), r3;
            }(m2, Yu(m2, c2, a2, r2, i2, d2));
            const b2 = [], w2 = { positionedLines: b2, text: m2.toString(), top: h2[1], bottom: h2[1], left: h2[0], right: h2[0], writingMode: p2, iconsInText: false, verticalizable: false };
            return function(e3, r3, n3, i3, s3, a3, o3, l3, u3, c3, h3, p3) {
              let f3 = 0, d3 = Du, y3 = 0, m3 = 0;
              const g3 = "right" === l3 ? 1 : "left" === l3 ? 0 : 0.5;
              let x3 = 0;
              for (const o4 of s3) {
                o4.trim();
                const s4 = o4.getMaxScale(), l4 = (s4 - 1) * iu, b4 = { positionedGlyphs: [], lineOffset: 0 };
                e3.positionedLines[x3] = b4;
                const w4 = b4.positionedGlyphs;
                let _3 = 0;
                if (!o4.length()) {
                  d3 += a3, ++x3;
                  continue;
                }
                for (let a4 = 0; a4 < o4.length(); a4++) {
                  const y4 = o4.getSection(a4), m4 = o4.getSectionIndex(a4), g4 = o4.getCharCode(a4);
                  let x4 = 0, b5 = null, A4 = null, S2 = null, k2 = iu;
                  const M2 = !(u3 === t.ah.horizontal || !h3 && !Ti(g4) || h3 && (Uu[g4] || (v3 = g4, new RegExp("\\p{sc=Arab}", "u").test(String.fromCodePoint(v3)))));
                  if (y4.imageName) {
                    const t4 = i3[y4.imageName];
                    if (!t4) continue;
                    S2 = y4.imageName, e3.iconsInText = e3.iconsInText || true, A4 = t4.paddedRect;
                    const r4 = t4.displaySize;
                    y4.scale = y4.scale * iu / p3, b5 = { width: r4[0], height: r4[1], left: Fu, top: -Vu, advance: M2 ? r4[1] : r4[0] }, x4 = l4 + (iu - r4[1] * y4.scale), k2 = b5.advance;
                    const n4 = M2 ? r4[0] * y4.scale - iu * s4 : r4[1] * y4.scale - iu * s4;
                    n4 > 0 && n4 > _3 && (_3 = n4);
                  } else {
                    const t4 = n3[y4.fontStack], e4 = t4 && t4[g4];
                    if (e4 && e4.rect) A4 = e4.rect, b5 = e4.metrics;
                    else {
                      const t5 = r3[y4.fontStack], e5 = t5 && t5[g4];
                      if (!e5) continue;
                      b5 = e5.metrics;
                    }
                    x4 = (s4 - y4.scale) * iu;
                  }
                  M2 ? (e3.verticalizable = true, w4.push({ glyph: g4, imageName: S2, x: f3, y: d3 + x4, vertical: M2, scale: y4.scale, fontStack: y4.fontStack, sectionIndex: m4, metrics: b5, rect: A4 }), f3 += k2 * y4.scale + c3) : (w4.push({ glyph: g4, imageName: S2, x: f3, y: d3 + x4, vertical: M2, scale: y4.scale, fontStack: y4.fontStack, sectionIndex: m4, metrics: b5, rect: A4 }), f3 += b5.advance * y4.scale + c3);
                }
                0 !== w4.length && (y3 = Math.max(f3 - c3, y3), Wu(w4, 0, w4.length - 1, g3, _3)), f3 = 0;
                const A3 = a3 * s4 + _3;
                b4.lineOffset = Math.max(_3, l4), d3 += A3, m3 = Math.max(A3, m3), ++x3;
              }
              var v3;
              const b3 = d3 - Du, { horizontalAlign: w3, verticalAlign: _2 } = Ju(o3);
              (function(t4, e4, r4, n4, i4, s4, a4, o4, l4) {
                const u4 = (e4 - r4) * i4;
                let c4 = 0;
                c4 = s4 !== a4 ? -o4 * n4 - Du : (-n4 * l4 + 0.5) * a4;
                for (const e5 of t4) for (const t5 of e5.positionedGlyphs) t5.x += u4, t5.y += c4;
              })(e3.positionedLines, g3, w3, _2, y3, m3, a3, b3, s3.length), e3.top += -_2 * b3, e3.bottom = e3.top + b3, e3.left += -w3 * y3, e3.right = e3.left + y3;
            }(w2, r2, n2, i2, g2, o2, l2, u2, p2, c2, f2, y2), !function(t4) {
              for (const e3 of t4) if (0 !== e3.positionedGlyphs.length) return false;
              return true;
            }(b2) && w2;
          }
          const Uu = { 9: true, 10: true, 11: true, 12: true, 13: true, 32: true }, qu = { 10: true, 32: true, 38: true, 41: true, 43: true, 45: true, 47: true, 173: true, 183: true, 8203: true, 8208: true, 8211: true, 8231: true }, Nu = { 40: true };
          function Zu(t4, e2, r2, n2, i2, s2) {
            if (e2.imageName) {
              const t5 = n2[e2.imageName];
              return t5 ? t5.displaySize[0] * e2.scale * iu / s2 + i2 : 0;
            }
            {
              const n3 = r2[e2.fontStack], s3 = n3 && n3[t4];
              return s3 ? s3.metrics.advance * e2.scale + i2 : 0;
            }
          }
          function Gu(t4, e2, r2, n2) {
            const i2 = Math.pow(t4 - e2, 2);
            return n2 ? t4 < e2 ? i2 / 2 : 2 * i2 : i2 + Math.abs(r2) * r2;
          }
          function Ku(t4, e2, r2) {
            let n2 = 0;
            return 10 === t4 && (n2 -= 1e4), r2 && (n2 += 150), 40 !== t4 && 65288 !== t4 || (n2 += 50), 41 !== e2 && 65289 !== e2 || (n2 += 50), n2;
          }
          function Xu(t4, e2, r2, n2, i2, s2) {
            let a2 = null, o2 = Gu(e2, r2, i2, s2);
            for (const t5 of n2) {
              const n3 = Gu(e2 - t5.x, r2, i2, s2) + t5.badness;
              n3 <= o2 && (a2 = t5, o2 = n3);
            }
            return { index: t4, x: e2, priorBreak: a2, badness: o2 };
          }
          function Hu(t4) {
            return t4 ? Hu(t4.priorBreak).concat(t4.index) : [];
          }
          function Yu(t4, e2, r2, n2, i2, s2) {
            if (!t4) return [];
            const a2 = [], o2 = function(t5, e3, r3, n3, i3, s3) {
              let a3 = 0;
              for (let r4 = 0; r4 < t5.length(); r4++) {
                const o3 = t5.getSection(r4);
                a3 += Zu(t5.getCharCode(r4), o3, n3, i3, e3, s3);
              }
              return a3 / Math.max(1, Math.ceil(a3 / r3));
            }(t4, e2, r2, n2, i2, s2), l2 = t4.text.indexOf("\u200B") >= 0;
            let u2 = 0;
            for (let r3 = 0; r3 < t4.length(); r3++) {
              const h2 = t4.getSection(r3), p2 = t4.getCharCode(r3);
              if (Uu[p2] || (u2 += Zu(p2, h2, n2, i2, e2, s2)), r3 < t4.length() - 1) {
                const e3 = !((c2 = p2) < 11904) && (!!zi["CJK Compatibility Forms"](c2) || !!zi["CJK Compatibility"](c2) || !!zi["CJK Strokes"](c2) || !!zi["CJK Symbols and Punctuation"](c2) || !!zi["Enclosed CJK Letters and Months"](c2) || !!zi["Halfwidth and Fullwidth Forms"](c2) || !!zi["Ideographic Description Characters"](c2) || !!zi["Vertical Forms"](c2) || Fi.test(String.fromCodePoint(c2)));
                (qu[p2] || e3 || h2.imageName || r3 !== t4.length() - 2 && Nu[t4.getCharCode(r3 + 1)]) && a2.push(Xu(r3 + 1, u2, o2, a2, Ku(p2, t4.getCharCode(r3 + 1), e3 && l2), false));
              }
            }
            var c2;
            return Hu(Xu(t4.length(), u2, o2, a2, 0, true));
          }
          function Ju(t4) {
            let e2 = 0.5, r2 = 0.5;
            switch (t4) {
              case "right":
              case "top-right":
              case "bottom-right":
                e2 = 1;
                break;
              case "left":
              case "top-left":
              case "bottom-left":
                e2 = 0;
            }
            switch (t4) {
              case "bottom":
              case "bottom-right":
              case "bottom-left":
                r2 = 1;
                break;
              case "top":
              case "top-right":
              case "top-left":
                r2 = 0;
            }
            return { horizontalAlign: e2, verticalAlign: r2 };
          }
          function Wu(t4, e2, r2, n2, i2) {
            if (!n2 && !i2) return;
            const s2 = t4[r2], a2 = (t4[r2].x + s2.metrics.advance * s2.scale) * n2;
            for (let n3 = e2; n3 <= r2; n3++) t4[n3].x -= a2, t4[n3].y += i2;
          }
          function Qu(t4, e2, r2) {
            const { horizontalAlign: n2, verticalAlign: i2 } = Ju(r2), s2 = e2[0] - t4.displaySize[0] * n2, a2 = e2[1] - t4.displaySize[1] * i2;
            return { image: t4, top: a2, bottom: a2 + t4.displaySize[1], left: s2, right: s2 + t4.displaySize[0] };
          }
          function tc(t4) {
            var e2, r2;
            let n2 = t4.left, i2 = t4.top, s2 = t4.right - n2, a2 = t4.bottom - i2;
            const o2 = null !== (e2 = t4.image.textFitWidth) && void 0 !== e2 ? e2 : "stretchOrShrink", l2 = null !== (r2 = t4.image.textFitHeight) && void 0 !== r2 ? r2 : "stretchOrShrink", u2 = (t4.image.content[2] - t4.image.content[0]) / (t4.image.content[3] - t4.image.content[1]);
            if ("proportional" === l2) {
              if ("stretchOnly" === o2 && s2 / a2 < u2 || "proportional" === o2) {
                const t5 = Math.ceil(a2 * u2);
                n2 *= t5 / s2, s2 = t5;
              }
            } else if ("proportional" === o2 && "stretchOnly" === l2 && 0 !== u2 && s2 / a2 > u2) {
              const t5 = Math.ceil(s2 / u2);
              i2 *= t5 / a2, a2 = t5;
            }
            return { x1: n2, y1: i2, x2: n2 + s2, y2: i2 + a2 };
          }
          function ec(t4, e2, r2, n2, i2, s2) {
            const a2 = t4.image;
            let o2;
            if (a2.content) {
              const t5 = a2.content, e3 = a2.pixelRatio || 1;
              o2 = [t5[0] / e3, t5[1] / e3, a2.displaySize[0] - t5[2] / e3, a2.displaySize[1] - t5[3] / e3];
            }
            const l2 = e2.left * s2, u2 = e2.right * s2;
            let c2, h2, p2, f2;
            "width" === r2 || "both" === r2 ? (f2 = i2[0] + l2 - n2[3], h2 = i2[0] + u2 + n2[1]) : (f2 = i2[0] + (l2 + u2 - a2.displaySize[0]) / 2, h2 = f2 + a2.displaySize[0]);
            const d2 = e2.top * s2, y2 = e2.bottom * s2;
            return "height" === r2 || "both" === r2 ? (c2 = i2[1] + d2 - n2[0], p2 = i2[1] + y2 + n2[2]) : (c2 = i2[1] + (d2 + y2 - a2.displaySize[1]) / 2, p2 = c2 + a2.displaySize[1]), { image: a2, top: c2, right: h2, bottom: p2, left: f2, collisionPadding: o2 };
          }
          const rc = 255, nc = 128, ic = rc * nc;
          function sc(t4, e2) {
            const { expression: r2 } = e2;
            if ("constant" === r2.kind) return { kind: "constant", layoutSize: r2.evaluate(new Ui(t4 + 1)) };
            if ("source" === r2.kind) return { kind: "source" };
            {
              const { zoomStops: e3, interpolationType: n2 } = r2;
              let i2 = 0;
              for (; i2 < e3.length && e3[i2] <= t4; ) i2++;
              i2 = Math.max(0, i2 - 1);
              let s2 = i2;
              for (; s2 < e3.length && e3[s2] < t4 + 1; ) s2++;
              s2 = Math.min(e3.length - 1, s2);
              const a2 = e3[i2], o2 = e3[s2];
              return "composite" === r2.kind ? { kind: "composite", minZoom: a2, maxZoom: o2, interpolationType: n2 } : { kind: "camera", minZoom: a2, maxZoom: o2, minSize: r2.evaluate(new Ui(a2)), maxSize: r2.evaluate(new Ui(o2)), interpolationType: n2 };
            }
          }
          function ac(t4, e2, r2) {
            let n2 = "never";
            const i2 = t4.get(e2);
            return i2 ? n2 = i2 : t4.get(r2) && (n2 = "always"), n2;
          }
          const oc = fl.VectorTileFeature.types, lc = [{ name: "a_fade_opacity", components: 1, type: "Uint8", offset: 0 }];
          function uc(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2) {
            const f2 = o2 ? Math.min(ic, Math.round(o2[0])) : 0, d2 = o2 ? Math.min(ic, Math.round(o2[1])) : 0;
            t4.emplaceBack(e2, r2, Math.round(32 * n2), Math.round(32 * i2), s2, a2, (f2 << 1) + (l2 ? 1 : 0), d2, 16 * u2, 16 * c2, 256 * h2, 256 * p2);
          }
          function cc(t4, e2, r2) {
            t4.emplaceBack(e2.x, e2.y, r2), t4.emplaceBack(e2.x, e2.y, r2), t4.emplaceBack(e2.x, e2.y, r2), t4.emplaceBack(e2.x, e2.y, r2);
          }
          function hc(t4) {
            for (const e2 of t4.sections) if (ji(e2.text)) return true;
            return false;
          }
          class pc {
            constructor(t4) {
              this.layoutVertexArray = new Ws(), this.indexArray = new na(), this.programConfigurations = t4, this.segments = new oa(), this.dynamicLayoutVertexArray = new Qs(), this.opacityVertexArray = new ta(), this.hasVisibleVertices = false, this.placedSymbolArray = new $s();
            }
            isEmpty() {
              return 0 === this.layoutVertexArray.length && 0 === this.indexArray.length && 0 === this.dynamicLayoutVertexArray.length && 0 === this.opacityVertexArray.length;
            }
            upload(t4, e2, r2, n2) {
              this.isEmpty() || (r2 && (this.layoutVertexBuffer = t4.createVertexBuffer(this.layoutVertexArray, Jl.members), this.indexBuffer = t4.createIndexBuffer(this.indexArray, e2), this.dynamicLayoutVertexBuffer = t4.createVertexBuffer(this.dynamicLayoutVertexArray, Wl.members, true), this.opacityVertexBuffer = t4.createVertexBuffer(this.opacityVertexArray, lc, true), this.opacityVertexBuffer.itemSize = 1), (r2 || n2) && this.programConfigurations.upload(t4));
            }
            destroy() {
              this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy(), this.dynamicLayoutVertexBuffer.destroy(), this.opacityVertexBuffer.destroy());
            }
          }
          wi("SymbolBuffers", pc);
          class fc {
            constructor(t4, e2, r2) {
              this.layoutVertexArray = new t4(), this.layoutAttributes = e2, this.indexArray = new r2(), this.segments = new oa(), this.collisionVertexArray = new ra();
            }
            upload(t4) {
              this.layoutVertexBuffer = t4.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes), this.indexBuffer = t4.createIndexBuffer(this.indexArray), this.collisionVertexBuffer = t4.createVertexBuffer(this.collisionVertexArray, Ql.members, true);
            }
            destroy() {
              this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.segments.destroy(), this.collisionVertexBuffer.destroy());
            }
          }
          wi("CollisionBuffers", fc);
          class dc {
            constructor(e2) {
              this.collisionBoxArray = e2.collisionBoxArray, this.zoom = e2.zoom, this.overscaling = e2.overscaling, this.layers = e2.layers, this.layerIds = this.layers.map((t4) => t4.id), this.index = e2.index, this.pixelRatio = e2.pixelRatio, this.sourceLayerIndex = e2.sourceLayerIndex, this.hasPattern = false, this.hasRTLText = false, this.sortKeyRanges = [], this.collisionCircleArray = [], this.placementInvProjMatrix = lo([]), this.placementViewportMatrix = lo([]);
              const r2 = this.layers[0]._unevaluatedLayout._values;
              this.textSizeData = sc(this.zoom, r2["text-size"]), this.iconSizeData = sc(this.zoom, r2["icon-size"]);
              const n2 = this.layers[0].layout, i2 = n2.get("symbol-sort-key"), s2 = n2.get("symbol-z-order");
              this.canOverlap = "never" !== ac(n2, "text-overlap", "text-allow-overlap") || "never" !== ac(n2, "icon-overlap", "icon-allow-overlap") || n2.get("text-ignore-placement") || n2.get("icon-ignore-placement"), this.sortFeaturesByKey = "viewport-y" !== s2 && !i2.isConstant(), this.sortFeaturesByY = ("viewport-y" === s2 || "auto" === s2 && !this.sortFeaturesByKey) && this.canOverlap, "point" === n2.get("symbol-placement") && (this.writingModes = n2.get("text-writing-mode").map((e3) => t.ah[e3])), this.stateDependentLayerIds = this.layers.filter((t4) => t4.isStateDependent()).map((t4) => t4.id), this.sourceID = e2.sourceID;
            }
            createArrays() {
              this.text = new pc(new Ea(this.layers, this.zoom, (t4) => /^text/.test(t4))), this.icon = new pc(new Ea(this.layers, this.zoom, (t4) => /^icon/.test(t4))), this.glyphOffsetArray = new Os(), this.lineVertexArray = new js(), this.symbolInstances = new Ds(), this.textAnchorOffsets = new Us();
            }
            calculateGlyphDependencies(t4, e2, r2, n2, i2) {
              for (let s2 = 0; s2 < t4.length; s2++) if (e2[t4.charCodeAt(s2)] = true, (r2 || n2) && i2) {
                const r3 = nu[t4.charAt(s2)];
                r3 && (e2[r3.charCodeAt(0)] = true);
              }
            }
            populate(e2, r2, n2) {
              const i2 = this.layers[0], s2 = i2.layout, a2 = s2.get("text-font"), o2 = s2.get("text-field"), l2 = s2.get("icon-image"), u2 = ("constant" !== o2.value.kind || o2.value.value instanceof Yt && !o2.value.value.isEmpty() || o2.value.value.toString().length > 0) && ("constant" !== a2.value.kind || a2.value.value.length > 0), c2 = "constant" !== l2.value.kind || !!l2.value.value || Object.keys(l2.parameters).length > 0, h2 = s2.get("symbol-sort-key");
              if (this.features = [], !u2 && !c2) return;
              const p2 = r2.iconDependencies, f2 = r2.glyphDependencies, d2 = r2.availableImages, y2 = new Ui(this.zoom);
              for (const { feature: r3, id: o3, index: l3, sourceLayerIndex: m2 } of e2) {
                const e3 = i2._featureFilter.needGeometry, g2 = ja(r3, e3);
                if (!i2._featureFilter.filter(y2, g2, n2)) continue;
                let x2, v2;
                if (e3 || (g2.geometry = Oa(r3)), u2) {
                  const t4 = i2.getValueAndResolveTokens("text-field", g2, n2, d2), e4 = Yt.factory(t4), r4 = this.hasRTLText = this.hasRTLText || hc(e4);
                  (!r4 || "unavailable" === Ri.getRTLTextPluginStatus() || r4 && Ri.isParsed()) && (x2 = ru(e4, i2, g2));
                }
                if (c2) {
                  const t4 = i2.getValueAndResolveTokens("icon-image", g2, n2, d2);
                  v2 = t4 instanceof te ? t4 : te.fromString(t4);
                }
                if (!x2 && !v2) continue;
                const b2 = this.sortFeaturesByKey ? h2.evaluate(g2, {}, n2) : void 0;
                if (this.features.push({ id: o3, text: x2, icon: v2, index: l3, sourceLayerIndex: m2, geometry: g2.geometry, properties: r3.properties, type: oc[r3.type], sortKey: b2 }), v2 && (p2[v2.name] = true), x2) {
                  const e4 = a2.evaluate(g2, {}, n2).join(","), r4 = "viewport" !== s2.get("text-rotation-alignment") && "point" !== s2.get("symbol-placement");
                  this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(t.ah.vertical) >= 0;
                  for (const t4 of x2.sections) if (t4.image) p2[t4.image.name] = true;
                  else {
                    const n3 = Pi(x2.toString()), i3 = t4.fontStack || e4, s3 = f2[i3] = f2[i3] || {};
                    this.calculateGlyphDependencies(t4.text, s3, r4, this.allowVerticalPlacement, n3);
                  }
                }
              }
              "line" === s2.get("symbol-placement") && (this.features = function(t4) {
                const e3 = {}, r3 = {}, n3 = [];
                let i3 = 0;
                function s3(e4) {
                  n3.push(t4[e4]), i3++;
                }
                function a3(t5, e4, i4) {
                  const s4 = r3[t5];
                  return delete r3[t5], r3[e4] = s4, n3[s4].geometry[0].pop(), n3[s4].geometry[0] = n3[s4].geometry[0].concat(i4[0]), s4;
                }
                function o3(t5, r4, i4) {
                  const s4 = e3[r4];
                  return delete e3[r4], e3[t5] = s4, n3[s4].geometry[0].shift(), n3[s4].geometry[0] = i4[0].concat(n3[s4].geometry[0]), s4;
                }
                function l3(t5, e4, r4) {
                  const n4 = r4 ? e4[0][e4[0].length - 1] : e4[0][0];
                  return `${t5}:${n4.x}:${n4.y}`;
                }
                for (let u3 = 0; u3 < t4.length; u3++) {
                  const c3 = t4[u3], h3 = c3.geometry, p3 = c3.text ? c3.text.toString() : null;
                  if (!p3) {
                    s3(u3);
                    continue;
                  }
                  const f3 = l3(p3, h3), d3 = l3(p3, h3, true);
                  if (f3 in r3 && d3 in e3 && r3[f3] !== e3[d3]) {
                    const t5 = o3(f3, d3, h3), i4 = a3(f3, d3, n3[t5].geometry);
                    delete e3[f3], delete r3[d3], r3[l3(p3, n3[i4].geometry, true)] = i4, n3[t5].geometry = null;
                  } else f3 in r3 ? a3(f3, d3, h3) : d3 in e3 ? o3(f3, d3, h3) : (s3(u3), e3[f3] = i3 - 1, r3[d3] = i3 - 1);
                }
                return n3.filter((t5) => t5.geometry);
              }(this.features)), this.sortFeaturesByKey && this.features.sort((t4, e3) => t4.sortKey - e3.sortKey);
            }
            update(t4, e2, r2) {
              this.stateDependentLayers.length && (this.text.programConfigurations.updatePaintArrays(t4, e2, this.layers, r2), this.icon.programConfigurations.updatePaintArrays(t4, e2, this.layers, r2));
            }
            isEmpty() {
              return 0 === this.symbolInstances.length && !this.hasRTLText;
            }
            uploadPending() {
              return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload;
            }
            upload(t4) {
              !this.uploaded && this.hasDebugData() && (this.textCollisionBox.upload(t4), this.iconCollisionBox.upload(t4)), this.text.upload(t4, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload), this.icon.upload(t4, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload), this.uploaded = true;
            }
            destroyDebugData() {
              this.textCollisionBox.destroy(), this.iconCollisionBox.destroy();
            }
            destroy() {
              this.text.destroy(), this.icon.destroy(), this.hasDebugData() && this.destroyDebugData();
            }
            addToLineVertexArray(t4, e2) {
              const r2 = this.lineVertexArray.length;
              if (void 0 !== t4.segment) {
                let r3 = t4.dist(e2[t4.segment + 1]), n2 = t4.dist(e2[t4.segment]);
                const i2 = {};
                for (let n3 = t4.segment + 1; n3 < e2.length; n3++) i2[n3] = { x: e2[n3].x, y: e2[n3].y, tileUnitDistanceFromAnchor: r3 }, n3 < e2.length - 1 && (r3 += e2[n3 + 1].dist(e2[n3]));
                for (let r4 = t4.segment || 0; r4 >= 0; r4--) i2[r4] = { x: e2[r4].x, y: e2[r4].y, tileUnitDistanceFromAnchor: n2 }, r4 > 0 && (n2 += e2[r4 - 1].dist(e2[r4]));
                for (let t5 = 0; t5 < e2.length; t5++) {
                  const e3 = i2[t5];
                  this.lineVertexArray.emplaceBack(e3.x, e3.y, e3.tileUnitDistanceFromAnchor);
                }
              }
              return { lineStartIndex: r2, lineLength: this.lineVertexArray.length - r2 };
            }
            addSymbols(e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2, p2) {
              const f2 = e2.indexArray, d2 = e2.layoutVertexArray, y2 = e2.segments.prepareSegment(4 * r2.length, d2, f2, this.canOverlap ? a2.sortKey : void 0), m2 = this.glyphOffsetArray.length, g2 = y2.vertexLength, x2 = this.allowVerticalPlacement && o2 === t.ah.vertical ? Math.PI / 2 : 0, v2 = a2.text && a2.text.sections;
              for (let t4 = 0; t4 < r2.length; t4++) {
                const { tl: i3, tr: s3, bl: o3, br: u3, tex: c3, pixelOffsetTL: h3, pixelOffsetBR: m3, minFontScaleX: g3, minFontScaleY: b2, glyphOffset: w2, isSDF: _2, sectionIndex: A3 } = r2[t4], S2 = y2.vertexLength, k2 = w2[1];
                uc(d2, l2.x, l2.y, i3.x, k2 + i3.y, c3.x, c3.y, n2, _2, h3.x, h3.y, g3, b2), uc(d2, l2.x, l2.y, s3.x, k2 + s3.y, c3.x + c3.w, c3.y, n2, _2, m3.x, h3.y, g3, b2), uc(d2, l2.x, l2.y, o3.x, k2 + o3.y, c3.x, c3.y + c3.h, n2, _2, h3.x, m3.y, g3, b2), uc(d2, l2.x, l2.y, u3.x, k2 + u3.y, c3.x + c3.w, c3.y + c3.h, n2, _2, m3.x, m3.y, g3, b2), cc(e2.dynamicLayoutVertexArray, l2, x2), f2.emplaceBack(S2, S2 + 1, S2 + 2), f2.emplaceBack(S2 + 1, S2 + 2, S2 + 3), y2.vertexLength += 4, y2.primitiveLength += 2, this.glyphOffsetArray.emplaceBack(w2[0]), t4 !== r2.length - 1 && A3 === r2[t4 + 1].sectionIndex || e2.programConfigurations.populatePaintArrays(d2.length, a2, a2.index, {}, p2, v2 && v2[A3]);
              }
              e2.placedSymbolArray.emplaceBack(l2.x, l2.y, m2, this.glyphOffsetArray.length - m2, g2, u2, c2, l2.segment, n2 ? n2[0] : 0, n2 ? n2[1] : 0, i2[0], i2[1], o2, 0, false, 0, h2);
            }
            _addCollisionDebugVertex(t4, e2, r2, n2, i2, s2) {
              return e2.emplaceBack(0, 0), t4.emplaceBack(r2.x, r2.y, n2, i2, Math.round(s2.x), Math.round(s2.y));
            }
            addCollisionDebugVertices(t4, e2, r2, n2, i2, a2, o2) {
              const l2 = i2.segments.prepareSegment(4, i2.layoutVertexArray, i2.indexArray), u2 = l2.vertexLength, c2 = i2.layoutVertexArray, h2 = i2.collisionVertexArray, p2 = o2.anchorX, f2 = o2.anchorY;
              this._addCollisionDebugVertex(c2, h2, a2, p2, f2, new s(t4, e2)), this._addCollisionDebugVertex(c2, h2, a2, p2, f2, new s(r2, e2)), this._addCollisionDebugVertex(c2, h2, a2, p2, f2, new s(r2, n2)), this._addCollisionDebugVertex(c2, h2, a2, p2, f2, new s(t4, n2)), l2.vertexLength += 4;
              const d2 = i2.indexArray;
              d2.emplaceBack(u2, u2 + 1), d2.emplaceBack(u2 + 1, u2 + 2), d2.emplaceBack(u2 + 2, u2 + 3), d2.emplaceBack(u2 + 3, u2), l2.primitiveLength += 4;
            }
            addDebugCollisionBoxes(t4, e2, r2, n2) {
              for (let i2 = t4; i2 < e2; i2++) {
                const t5 = this.collisionBoxArray.get(i2);
                this.addCollisionDebugVertices(t5.x1, t5.y1, t5.x2, t5.y2, n2 ? this.textCollisionBox : this.iconCollisionBox, t5.anchorPoint, r2);
              }
            }
            generateCollisionDebugBuffers() {
              this.hasDebugData() && this.destroyDebugData(), this.textCollisionBox = new fc(ea, tu.members, ia), this.iconCollisionBox = new fc(ea, tu.members, ia);
              for (let t4 = 0; t4 < this.symbolInstances.length; t4++) {
                const e2 = this.symbolInstances.get(t4);
                this.addDebugCollisionBoxes(e2.textBoxStartIndex, e2.textBoxEndIndex, e2, true), this.addDebugCollisionBoxes(e2.verticalTextBoxStartIndex, e2.verticalTextBoxEndIndex, e2, true), this.addDebugCollisionBoxes(e2.iconBoxStartIndex, e2.iconBoxEndIndex, e2, false), this.addDebugCollisionBoxes(e2.verticalIconBoxStartIndex, e2.verticalIconBoxEndIndex, e2, false);
              }
            }
            _deserializeCollisionBoxesForSymbol(t4, e2, r2, n2, i2, s2, a2, o2, l2) {
              const u2 = {};
              for (let n3 = e2; n3 < r2; n3++) {
                const e3 = t4.get(n3);
                u2.textBox = { x1: e3.x1, y1: e3.y1, x2: e3.x2, y2: e3.y2, anchorPointX: e3.anchorPointX, anchorPointY: e3.anchorPointY }, u2.textFeatureIndex = e3.featureIndex;
                break;
              }
              for (let e3 = n2; e3 < i2; e3++) {
                const r3 = t4.get(e3);
                u2.verticalTextBox = { x1: r3.x1, y1: r3.y1, x2: r3.x2, y2: r3.y2, anchorPointX: r3.anchorPointX, anchorPointY: r3.anchorPointY }, u2.verticalTextFeatureIndex = r3.featureIndex;
                break;
              }
              for (let e3 = s2; e3 < a2; e3++) {
                const r3 = t4.get(e3);
                u2.iconBox = { x1: r3.x1, y1: r3.y1, x2: r3.x2, y2: r3.y2, anchorPointX: r3.anchorPointX, anchorPointY: r3.anchorPointY }, u2.iconFeatureIndex = r3.featureIndex;
                break;
              }
              for (let e3 = o2; e3 < l2; e3++) {
                const r3 = t4.get(e3);
                u2.verticalIconBox = { x1: r3.x1, y1: r3.y1, x2: r3.x2, y2: r3.y2, anchorPointX: r3.anchorPointX, anchorPointY: r3.anchorPointY }, u2.verticalIconFeatureIndex = r3.featureIndex;
                break;
              }
              return u2;
            }
            deserializeCollisionBoxes(t4) {
              this.collisionArrays = [];
              for (let e2 = 0; e2 < this.symbolInstances.length; e2++) {
                const r2 = this.symbolInstances.get(e2);
                this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(t4, r2.textBoxStartIndex, r2.textBoxEndIndex, r2.verticalTextBoxStartIndex, r2.verticalTextBoxEndIndex, r2.iconBoxStartIndex, r2.iconBoxEndIndex, r2.verticalIconBoxStartIndex, r2.verticalIconBoxEndIndex));
              }
            }
            hasTextData() {
              return this.text.segments.get().length > 0;
            }
            hasIconData() {
              return this.icon.segments.get().length > 0;
            }
            hasDebugData() {
              return this.textCollisionBox && this.iconCollisionBox;
            }
            hasTextCollisionBoxData() {
              return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;
            }
            hasIconCollisionBoxData() {
              return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0;
            }
            addIndicesForPlacedSymbol(t4, e2) {
              const r2 = t4.placedSymbolArray.get(e2), n2 = r2.vertexStartIndex + 4 * r2.numGlyphs;
              for (let e3 = r2.vertexStartIndex; e3 < n2; e3 += 4) t4.indexArray.emplaceBack(e3, e3 + 1, e3 + 2), t4.indexArray.emplaceBack(e3 + 1, e3 + 2, e3 + 3);
            }
            getSortedSymbolIndexes(t4) {
              if (this.sortedAngle === t4 && void 0 !== this.symbolInstanceIndexes) return this.symbolInstanceIndexes;
              const e2 = Math.sin(t4), r2 = Math.cos(t4), n2 = [], i2 = [], s2 = [];
              for (let t5 = 0; t5 < this.symbolInstances.length; ++t5) {
                s2.push(t5);
                const a2 = this.symbolInstances.get(t5);
                n2.push(0 | Math.round(e2 * a2.anchorX + r2 * a2.anchorY)), i2.push(a2.featureIndex);
              }
              return s2.sort((t5, e3) => n2[t5] - n2[e3] || i2[e3] - i2[t5]), s2;
            }
            addToSortKeyRanges(t4, e2) {
              const r2 = this.sortKeyRanges[this.sortKeyRanges.length - 1];
              r2 && r2.sortKey === e2 ? r2.symbolInstanceEnd = t4 + 1 : this.sortKeyRanges.push({ sortKey: e2, symbolInstanceStart: t4, symbolInstanceEnd: t4 + 1 });
            }
            sortFeatures(t4) {
              if (this.sortFeaturesByY && this.sortedAngle !== t4 && !(this.text.segments.get().length > 1 || this.icon.segments.get().length > 1)) {
                this.symbolInstanceIndexes = this.getSortedSymbolIndexes(t4), this.sortedAngle = t4, this.text.indexArray.clear(), this.icon.indexArray.clear(), this.featureSortOrder = [];
                for (const t5 of this.symbolInstanceIndexes) {
                  const e2 = this.symbolInstances.get(t5);
                  this.featureSortOrder.push(e2.featureIndex), [e2.rightJustifiedTextSymbolIndex, e2.centerJustifiedTextSymbolIndex, e2.leftJustifiedTextSymbolIndex].forEach((t6, e3, r2) => {
                    t6 >= 0 && r2.indexOf(t6) === e3 && this.addIndicesForPlacedSymbol(this.text, t6);
                  }), e2.verticalPlacedTextSymbolIndex >= 0 && this.addIndicesForPlacedSymbol(this.text, e2.verticalPlacedTextSymbolIndex), e2.placedIconSymbolIndex >= 0 && this.addIndicesForPlacedSymbol(this.icon, e2.placedIconSymbolIndex), e2.verticalPlacedIconSymbolIndex >= 0 && this.addIndicesForPlacedSymbol(this.icon, e2.verticalPlacedIconSymbolIndex);
                }
                this.text.indexBuffer && this.text.indexBuffer.updateData(this.text.indexArray), this.icon.indexBuffer && this.icon.indexBuffer.updateData(this.icon.indexArray);
              }
            }
          }
          let yc, mc;
          wi("SymbolBucket", dc, { omit: ["layers", "collisionBoxArray", "features", "compareText"] }), dc.MAX_GLYPHS = 65535, dc.addDynamicAttributes = cc;
          var gc = { get paint() {
            return mc = mc || new rs({ "icon-opacity": new Wi(G.paint_symbol["icon-opacity"]), "icon-color": new Wi(G.paint_symbol["icon-color"]), "icon-halo-color": new Wi(G.paint_symbol["icon-halo-color"]), "icon-halo-width": new Wi(G.paint_symbol["icon-halo-width"]), "icon-halo-blur": new Wi(G.paint_symbol["icon-halo-blur"]), "icon-translate": new Ji(G.paint_symbol["icon-translate"]), "icon-translate-anchor": new Ji(G.paint_symbol["icon-translate-anchor"]), "text-opacity": new Wi(G.paint_symbol["text-opacity"]), "text-color": new Wi(G.paint_symbol["text-color"], { runtimeType: pt, getOverride: (t4) => t4.textColor, hasOverride: (t4) => !!t4.textColor }), "text-halo-color": new Wi(G.paint_symbol["text-halo-color"]), "text-halo-width": new Wi(G.paint_symbol["text-halo-width"]), "text-halo-blur": new Wi(G.paint_symbol["text-halo-blur"]), "text-translate": new Ji(G.paint_symbol["text-translate"]), "text-translate-anchor": new Ji(G.paint_symbol["text-translate-anchor"]) });
          }, get layout() {
            return yc = yc || new rs({ "symbol-placement": new Ji(G.layout_symbol["symbol-placement"]), "symbol-spacing": new Ji(G.layout_symbol["symbol-spacing"]), "symbol-avoid-edges": new Ji(G.layout_symbol["symbol-avoid-edges"]), "symbol-sort-key": new Wi(G.layout_symbol["symbol-sort-key"]), "symbol-z-order": new Ji(G.layout_symbol["symbol-z-order"]), "icon-allow-overlap": new Ji(G.layout_symbol["icon-allow-overlap"]), "icon-overlap": new Ji(G.layout_symbol["icon-overlap"]), "icon-ignore-placement": new Ji(G.layout_symbol["icon-ignore-placement"]), "icon-optional": new Ji(G.layout_symbol["icon-optional"]), "icon-rotation-alignment": new Ji(G.layout_symbol["icon-rotation-alignment"]), "icon-size": new Wi(G.layout_symbol["icon-size"]), "icon-text-fit": new Ji(G.layout_symbol["icon-text-fit"]), "icon-text-fit-padding": new Ji(G.layout_symbol["icon-text-fit-padding"]), "icon-image": new Wi(G.layout_symbol["icon-image"]), "icon-rotate": new Wi(G.layout_symbol["icon-rotate"]), "icon-padding": new Wi(G.layout_symbol["icon-padding"]), "icon-keep-upright": new Ji(G.layout_symbol["icon-keep-upright"]), "icon-offset": new Wi(G.layout_symbol["icon-offset"]), "icon-anchor": new Wi(G.layout_symbol["icon-anchor"]), "icon-pitch-alignment": new Ji(G.layout_symbol["icon-pitch-alignment"]), "text-pitch-alignment": new Ji(G.layout_symbol["text-pitch-alignment"]), "text-rotation-alignment": new Ji(G.layout_symbol["text-rotation-alignment"]), "text-field": new Wi(G.layout_symbol["text-field"]), "text-font": new Wi(G.layout_symbol["text-font"]), "text-size": new Wi(G.layout_symbol["text-size"]), "text-max-width": new Wi(G.layout_symbol["text-max-width"]), "text-line-height": new Ji(G.layout_symbol["text-line-height"]), "text-letter-spacing": new Wi(G.layout_symbol["text-letter-spacing"]), "text-justify": new Wi(G.layout_symbol["text-justify"]), "text-radial-offset": new Wi(G.layout_symbol["text-radial-offset"]), "text-variable-anchor": new Ji(G.layout_symbol["text-variable-anchor"]), "text-variable-anchor-offset": new Wi(G.layout_symbol["text-variable-anchor-offset"]), "text-anchor": new Wi(G.layout_symbol["text-anchor"]), "text-max-angle": new Ji(G.layout_symbol["text-max-angle"]), "text-writing-mode": new Ji(G.layout_symbol["text-writing-mode"]), "text-rotate": new Wi(G.layout_symbol["text-rotate"]), "text-padding": new Ji(G.layout_symbol["text-padding"]), "text-keep-upright": new Ji(G.layout_symbol["text-keep-upright"]), "text-transform": new Wi(G.layout_symbol["text-transform"]), "text-offset": new Wi(G.layout_symbol["text-offset"]), "text-allow-overlap": new Ji(G.layout_symbol["text-allow-overlap"]), "text-overlap": new Ji(G.layout_symbol["text-overlap"]), "text-ignore-placement": new Ji(G.layout_symbol["text-ignore-placement"]), "text-optional": new Ji(G.layout_symbol["text-optional"]) });
          } };
          class xc {
            constructor(t4) {
              if (void 0 === t4.property.overrides) throw new Error("overrides must be provided to instantiate FormatSectionOverride class");
              this.type = t4.property.overrides ? t4.property.overrides.runtimeType : lt, this.defaultValue = t4;
            }
            evaluate(t4) {
              if (t4.formattedSection) {
                const e2 = this.defaultValue.property.overrides;
                if (e2 && e2.hasOverride(t4.formattedSection)) return e2.getOverride(t4.formattedSection);
              }
              return t4.feature && t4.featureState ? this.defaultValue.evaluate(t4.feature, t4.featureState) : this.defaultValue.property.specification.default;
            }
            eachChild(t4) {
              this.defaultValue.isConstant() || t4(this.defaultValue.value._styleExpression.expression);
            }
            outputDefined() {
              return false;
            }
            serialize() {
              return null;
            }
          }
          wi("FormatSectionOverride", xc, { omit: ["defaultValue"] });
          class vc extends is {
            constructor(t4) {
              super(t4, gc);
            }
            recalculate(t4, e2) {
              if (super.recalculate(t4, e2), "auto" === this.layout.get("icon-rotation-alignment") && (this.layout._values["icon-rotation-alignment"] = "point" !== this.layout.get("symbol-placement") ? "map" : "viewport"), "auto" === this.layout.get("text-rotation-alignment") && (this.layout._values["text-rotation-alignment"] = "point" !== this.layout.get("symbol-placement") ? "map" : "viewport"), "auto" === this.layout.get("text-pitch-alignment") && (this.layout._values["text-pitch-alignment"] = "map" === this.layout.get("text-rotation-alignment") ? "map" : "viewport"), "auto" === this.layout.get("icon-pitch-alignment") && (this.layout._values["icon-pitch-alignment"] = this.layout.get("icon-rotation-alignment")), "point" === this.layout.get("symbol-placement")) {
                const t5 = this.layout.get("text-writing-mode");
                if (t5) {
                  const e3 = [];
                  for (const r2 of t5) e3.indexOf(r2) < 0 && e3.push(r2);
                  this.layout._values["text-writing-mode"] = e3;
                } else this.layout._values["text-writing-mode"] = ["horizontal"];
              }
              this._setPaintOverrides();
            }
            getValueAndResolveTokens(t4, e2, r2, n2) {
              const i2 = this.layout.get(t4).evaluate(e2, {}, r2, n2), s2 = this._unevaluatedLayout._values[t4];
              return s2.isDataDriven() || vn(s2.value) || !i2 ? i2 : function(t5, e3) {
                return e3.replace(/{([^{}]+)}/g, (e4, r3) => t5 && r3 in t5 ? String(t5[r3]) : "");
              }(e2.properties, i2);
            }
            createBucket(t4) {
              return new dc(t4);
            }
            queryRadius() {
              return 0;
            }
            queryIntersectsFeature() {
              throw new Error("Should take a different path in FeatureIndex");
            }
            _setPaintOverrides() {
              for (const t4 of gc.paint.overridableProperties) {
                if (!vc.hasPaintOverride(this.layout, t4)) continue;
                const e2 = this.paint.get(t4), r2 = new xc(e2), n2 = new xn(r2, e2.property.specification);
                let i2 = null;
                i2 = "constant" === e2.value.kind || "source" === e2.value.kind ? new wn("source", n2) : new _n("composite", n2, e2.value.zoomStops), this.paint._values[t4] = new Hi(e2.property, i2, e2.parameters);
              }
            }
            _handleOverridablePaintPropertyUpdate(t4, e2, r2) {
              return !(!this.layout || e2.isDataDriven() || r2.isDataDriven()) && vc.hasPaintOverride(this.layout, t4);
            }
            static hasPaintOverride(t4, e2) {
              const r2 = t4.get("text-field"), n2 = gc.paint.properties[e2];
              let i2 = false;
              const s2 = (t5) => {
                for (const e3 of t5) if (n2.overrides && n2.overrides.hasOverride(e3)) return void (i2 = true);
              };
              if ("constant" === r2.value.kind && r2.value.value instanceof Yt) s2(r2.value.value.sections);
              else if ("source" === r2.value.kind) {
                const t5 = (e4) => {
                  i2 || (e4 instanceof se && ne(e4.value) === mt ? s2(e4.value.sections) : e4 instanceof Ze ? s2(e4.sections) : e4.eachChild(t5));
                }, e3 = r2.value;
                e3._styleExpression && t5(e3._styleExpression.expression);
              }
              return i2;
            }
          }
          let bc;
          var wc = { get paint() {
            return bc = bc || new rs({ "background-color": new Ji(G.paint_background["background-color"]), "background-pattern": new ts(G.paint_background["background-pattern"]), "background-opacity": new Ji(G.paint_background["background-opacity"]) });
          } };
          class _c extends is {
            constructor(t4) {
              super(t4, wc);
            }
          }
          let Ac;
          var Sc = { get paint() {
            return Ac = Ac || new rs({ "raster-opacity": new Ji(G.paint_raster["raster-opacity"]), "raster-hue-rotate": new Ji(G.paint_raster["raster-hue-rotate"]), "raster-brightness-min": new Ji(G.paint_raster["raster-brightness-min"]), "raster-brightness-max": new Ji(G.paint_raster["raster-brightness-max"]), "raster-saturation": new Ji(G.paint_raster["raster-saturation"]), "raster-contrast": new Ji(G.paint_raster["raster-contrast"]), "raster-resampling": new Ji(G.paint_raster["raster-resampling"]), "raster-fade-duration": new Ji(G.paint_raster["raster-fade-duration"]) });
          } };
          class kc extends is {
            constructor(t4) {
              super(t4, Sc);
            }
          }
          class Mc extends is {
            constructor(t4) {
              super(t4, {}), this.onAdd = (t5) => {
                this.implementation.onAdd && this.implementation.onAdd(t5, t5.painter.context.gl);
              }, this.onRemove = (t5) => {
                this.implementation.onRemove && this.implementation.onRemove(t5, t5.painter.context.gl);
              }, this.implementation = t4;
            }
            is3D() {
              return "3d" === this.implementation.renderingMode;
            }
            hasOffscreenPass() {
              return void 0 !== this.implementation.prerender;
            }
            recalculate() {
            }
            updateTransitions() {
            }
            hasTransition() {
              return false;
            }
            serialize() {
              throw new Error("Custom layers cannot be serialized");
            }
          }
          class Ic {
            constructor(t4) {
              this._methodToThrottle = t4, this._triggered = false, "undefined" != typeof MessageChannel && (this._channel = new MessageChannel(), this._channel.port2.onmessage = () => {
                this._triggered = false, this._methodToThrottle();
              });
            }
            trigger() {
              this._triggered || (this._triggered = true, this._channel ? this._channel.port1.postMessage(true) : setTimeout(() => {
                this._triggered = false, this._methodToThrottle();
              }, 0));
            }
            remove() {
              delete this._channel, this._methodToThrottle = () => {
              };
            }
          }
          const zc = 63710088e-1;
          class Pc {
            constructor(t4, e2) {
              if (isNaN(t4) || isNaN(e2)) throw new Error(`Invalid LngLat object: (${t4}, ${e2})`);
              if (this.lng = +t4, this.lat = +e2, this.lat > 90 || this.lat < -90) throw new Error("Invalid LngLat latitude value: must be between -90 and 90");
            }
            wrap() {
              return new Pc(m(this.lng, -180, 180), this.lat);
            }
            toArray() {
              return [this.lng, this.lat];
            }
            toString() {
              return `LngLat(${this.lng}, ${this.lat})`;
            }
            distanceTo(t4) {
              const e2 = Math.PI / 180, r2 = this.lat * e2, n2 = t4.lat * e2, i2 = Math.sin(r2) * Math.sin(n2) + Math.cos(r2) * Math.cos(n2) * Math.cos((t4.lng - this.lng) * e2);
              return zc * Math.acos(Math.min(i2, 1));
            }
            static convert(t4) {
              if (t4 instanceof Pc) return t4;
              if (Array.isArray(t4) && (2 === t4.length || 3 === t4.length)) return new Pc(Number(t4[0]), Number(t4[1]));
              if (!Array.isArray(t4) && "object" == typeof t4 && null !== t4) return new Pc(Number("lng" in t4 ? t4.lng : t4.lon), Number(t4.lat));
              throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]");
            }
          }
          const Cc = 2 * Math.PI * zc;
          function Bc(t4) {
            return Cc * Math.cos(t4 * Math.PI / 180);
          }
          function Vc(t4) {
            return (180 + t4) / 360;
          }
          function Ec(t4) {
            return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + t4 * Math.PI / 360))) / 360;
          }
          function Fc(t4, e2) {
            return t4 / Bc(e2);
          }
          function Tc(t4) {
            return 360 / Math.PI * Math.atan(Math.exp((180 - 360 * t4) * Math.PI / 180)) - 90;
          }
          class $c {
            constructor(t4, e2, r2 = 0) {
              this.x = +t4, this.y = +e2, this.z = +r2;
            }
            static fromLngLat(t4, e2 = 0) {
              const r2 = Pc.convert(t4);
              return new $c(Vc(r2.lng), Ec(r2.lat), Fc(e2, r2.lat));
            }
            toLngLat() {
              return new Pc(360 * this.x - 180, Tc(this.y));
            }
            toAltitude() {
              return this.z * Bc(Tc(this.y));
            }
            meterInMercatorCoordinateUnits() {
              return 1 / Cc * (t4 = Tc(this.y), 1 / Math.cos(t4 * Math.PI / 180));
              var t4;
            }
          }
          function Lc(t4, e2, r2) {
            var n2 = 2 * Math.PI * 6378137 / 256 / Math.pow(2, r2);
            return [t4 * n2 - 2 * Math.PI * 6378137 / 2, e2 * n2 - 2 * Math.PI * 6378137 / 2];
          }
          class Dc {
            constructor(t4, e2, r2) {
              if (!function(t5, e3, r3) {
                return !(t5 < 0 || t5 > 25 || r3 < 0 || r3 >= Math.pow(2, t5) || e3 < 0 || e3 >= Math.pow(2, t5));
              }(t4, e2, r2)) throw new Error(`x=${e2}, y=${r2}, z=${t4} outside of bounds. 0<=x<${Math.pow(2, t4)}, 0<=y<${Math.pow(2, t4)} 0<=z<=25 `);
              this.z = t4, this.x = e2, this.y = r2, this.key = Rc(0, t4, t4, e2, r2);
            }
            equals(t4) {
              return this.z === t4.z && this.x === t4.x && this.y === t4.y;
            }
            url(t4, e2, r2) {
              const n2 = (s2 = this.y, a2 = this.z, o2 = Lc(256 * (i2 = this.x), 256 * (s2 = Math.pow(2, a2) - s2 - 1), a2), l2 = Lc(256 * (i2 + 1), 256 * (s2 + 1), a2), o2[0] + "," + o2[1] + "," + l2[0] + "," + l2[1]);
              var i2, s2, a2, o2, l2;
              const u2 = function(t5, e3, r3) {
                let n3, i3 = "";
                for (let s3 = t5; s3 > 0; s3--) n3 = 1 << s3 - 1, i3 += (e3 & n3 ? 1 : 0) + (r3 & n3 ? 2 : 0);
                return i3;
              }(this.z, this.x, this.y);
              return t4[(this.x + this.y) % t4.length].replace(/{prefix}/g, (this.x % 16).toString(16) + (this.y % 16).toString(16)).replace(/{z}/g, String(this.z)).replace(/{x}/g, String(this.x)).replace(/{y}/g, String("tms" === r2 ? Math.pow(2, this.z) - this.y - 1 : this.y)).replace(/{ratio}/g, e2 > 1 ? "@2x" : "").replace(/{quadkey}/g, u2).replace(/{bbox-epsg-3857}/g, n2);
            }
            isChildOf(t4) {
              const e2 = this.z - t4.z;
              return e2 > 0 && t4.x === this.x >> e2 && t4.y === this.y >> e2;
            }
            getTilePoint(t4) {
              const e2 = Math.pow(2, this.z);
              return new s((t4.x * e2 - this.x) * $a, (t4.y * e2 - this.y) * $a);
            }
            toString() {
              return `${this.z}/${this.x}/${this.y}`;
            }
          }
          class Oc {
            constructor(t4, e2) {
              this.wrap = t4, this.canonical = e2, this.key = Rc(t4, e2.z, e2.z, e2.x, e2.y);
            }
          }
          class jc {
            constructor(t4, e2, r2, n2, i2) {
              if (t4 < r2) throw new Error(`overscaledZ should be >= z; overscaledZ = ${t4}; z = ${r2}`);
              this.overscaledZ = t4, this.wrap = e2, this.canonical = new Dc(r2, +n2, +i2), this.key = Rc(e2, t4, r2, n2, i2);
            }
            clone() {
              return new jc(this.overscaledZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);
            }
            equals(t4) {
              return this.overscaledZ === t4.overscaledZ && this.wrap === t4.wrap && this.canonical.equals(t4.canonical);
            }
            scaledTo(t4) {
              if (t4 > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${t4}; overscaledZ = ${this.overscaledZ}`);
              const e2 = this.canonical.z - t4;
              return t4 > this.canonical.z ? new jc(t4, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y) : new jc(t4, this.wrap, t4, this.canonical.x >> e2, this.canonical.y >> e2);
            }
            calculateScaledKey(t4, e2) {
              if (t4 > this.overscaledZ) throw new Error(`targetZ > this.overscaledZ; targetZ = ${t4}; overscaledZ = ${this.overscaledZ}`);
              const r2 = this.canonical.z - t4;
              return t4 > this.canonical.z ? Rc(this.wrap * +e2, t4, this.canonical.z, this.canonical.x, this.canonical.y) : Rc(this.wrap * +e2, t4, t4, this.canonical.x >> r2, this.canonical.y >> r2);
            }
            isChildOf(t4) {
              if (t4.wrap !== this.wrap) return false;
              const e2 = this.canonical.z - t4.canonical.z;
              return 0 === t4.overscaledZ || t4.overscaledZ < this.overscaledZ && t4.canonical.x === this.canonical.x >> e2 && t4.canonical.y === this.canonical.y >> e2;
            }
            children(t4) {
              if (this.overscaledZ >= t4) return [new jc(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];
              const e2 = this.canonical.z + 1, r2 = 2 * this.canonical.x, n2 = 2 * this.canonical.y;
              return [new jc(e2, this.wrap, e2, r2, n2), new jc(e2, this.wrap, e2, r2 + 1, n2), new jc(e2, this.wrap, e2, r2, n2 + 1), new jc(e2, this.wrap, e2, r2 + 1, n2 + 1)];
            }
            isLessThan(t4) {
              return this.wrap < t4.wrap || !(this.wrap > t4.wrap) && (this.overscaledZ < t4.overscaledZ || !(this.overscaledZ > t4.overscaledZ) && (this.canonical.x < t4.canonical.x || !(this.canonical.x > t4.canonical.x) && this.canonical.y < t4.canonical.y));
            }
            wrapped() {
              return new jc(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);
            }
            unwrapTo(t4) {
              return new jc(this.overscaledZ, t4, this.canonical.z, this.canonical.x, this.canonical.y);
            }
            overscaleFactor() {
              return Math.pow(2, this.overscaledZ - this.canonical.z);
            }
            toUnwrapped() {
              return new Oc(this.wrap, this.canonical);
            }
            toString() {
              return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`;
            }
            getTilePoint(t4) {
              return this.canonical.getTilePoint(new $c(t4.x - this.wrap, t4.y));
            }
          }
          function Rc(t4, e2, r2, n2, i2) {
            (t4 *= 2) < 0 && (t4 = -1 * t4 - 1);
            const s2 = 1 << r2;
            return (s2 * s2 * t4 + s2 * i2 + n2).toString(36) + r2.toString(36) + e2.toString(36);
          }
          wi("CanonicalTileID", Dc), wi("OverscaledTileID", jc, { omit: ["posMatrix"] });
          class Uc {
            constructor(t4, e2, r2, n2 = 1, i2 = 1, s2 = 1, a2 = 0) {
              if (this.uid = t4, e2.height !== e2.width) throw new RangeError("DEM tiles must be square");
              if (r2 && !["mapbox", "terrarium", "custom"].includes(r2)) return void A2(`"${r2}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`);
              this.stride = e2.height;
              const o2 = this.dim = e2.height - 2;
              switch (this.data = new Uint32Array(e2.data.buffer), r2) {
                case "terrarium":
                  this.redFactor = 256, this.greenFactor = 1, this.blueFactor = 1 / 256, this.baseShift = 32768;
                  break;
                case "custom":
                  this.redFactor = n2, this.greenFactor = i2, this.blueFactor = s2, this.baseShift = a2;
                  break;
                default:
                  this.redFactor = 6553.6, this.greenFactor = 25.6, this.blueFactor = 0.1, this.baseShift = 1e4;
              }
              for (let t5 = 0; t5 < o2; t5++) this.data[this._idx(-1, t5)] = this.data[this._idx(0, t5)], this.data[this._idx(o2, t5)] = this.data[this._idx(o2 - 1, t5)], this.data[this._idx(t5, -1)] = this.data[this._idx(t5, 0)], this.data[this._idx(t5, o2)] = this.data[this._idx(t5, o2 - 1)];
              this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)], this.data[this._idx(o2, -1)] = this.data[this._idx(o2 - 1, 0)], this.data[this._idx(-1, o2)] = this.data[this._idx(0, o2 - 1)], this.data[this._idx(o2, o2)] = this.data[this._idx(o2 - 1, o2 - 1)], this.min = Number.MAX_SAFE_INTEGER, this.max = Number.MIN_SAFE_INTEGER;
              for (let t5 = 0; t5 < o2; t5++) for (let e3 = 0; e3 < o2; e3++) {
                const r3 = this.get(t5, e3);
                r3 > this.max && (this.max = r3), r3 < this.min && (this.min = r3);
              }
            }
            get(t4, e2) {
              const r2 = new Uint8Array(this.data.buffer), n2 = 4 * this._idx(t4, e2);
              return this.unpack(r2[n2], r2[n2 + 1], r2[n2 + 2]);
            }
            getUnpackVector() {
              return [this.redFactor, this.greenFactor, this.blueFactor, this.baseShift];
            }
            _idx(t4, e2) {
              if (t4 < -1 || t4 >= this.dim + 1 || e2 < -1 || e2 >= this.dim + 1) throw new RangeError("out of range source coordinates for DEM data");
              return (e2 + 1) * this.stride + (t4 + 1);
            }
            unpack(t4, e2, r2) {
              return t4 * this.redFactor + e2 * this.greenFactor + r2 * this.blueFactor - this.baseShift;
            }
            getPixels() {
              return new Ao({ width: this.stride, height: this.stride }, new Uint8Array(this.data.buffer));
            }
            backfillBorder(t4, e2, r2) {
              if (this.dim !== t4.dim) throw new Error("dem dimension mismatch");
              let n2 = e2 * this.dim, i2 = e2 * this.dim + this.dim, s2 = r2 * this.dim, a2 = r2 * this.dim + this.dim;
              switch (e2) {
                case -1:
                  n2 = i2 - 1;
                  break;
                case 1:
                  i2 = n2 + 1;
              }
              switch (r2) {
                case -1:
                  s2 = a2 - 1;
                  break;
                case 1:
                  a2 = s2 + 1;
              }
              const o2 = -e2 * this.dim, l2 = -r2 * this.dim;
              for (let e3 = s2; e3 < a2; e3++) for (let r3 = n2; r3 < i2; r3++) this.data[this._idx(r3, e3)] = t4.data[this._idx(r3 + o2, e3 + l2)];
            }
          }
          wi("DEMData", Uc);
          class qc {
            constructor(t4) {
              this._stringToNumber = {}, this._numberToString = [];
              for (let e2 = 0; e2 < t4.length; e2++) {
                const r2 = t4[e2];
                this._stringToNumber[r2] = e2, this._numberToString[e2] = r2;
              }
            }
            encode(t4) {
              return this._stringToNumber[t4];
            }
            decode(t4) {
              if (t4 >= this._numberToString.length) throw new Error(`Out of bounds. Index requested n=${t4} can't be >= this._numberToString.length ${this._numberToString.length}`);
              return this._numberToString[t4];
            }
          }
          class Nc {
            constructor(t4, e2, r2, n2, i2) {
              this.type = "Feature", this._vectorTileFeature = t4, t4._z = e2, t4._x = r2, t4._y = n2, this.properties = t4.properties, this.id = i2;
            }
            get geometry() {
              return void 0 === this._geometry && (this._geometry = this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x, this._vectorTileFeature._y, this._vectorTileFeature._z).geometry), this._geometry;
            }
            set geometry(t4) {
              this._geometry = t4;
            }
            toJSON() {
              const t4 = { geometry: this.geometry };
              for (const e2 in this) "_geometry" !== e2 && "_vectorTileFeature" !== e2 && (t4[e2] = this[e2]);
              return t4;
            }
          }
          class Zc {
            constructor(t4, e2) {
              this.tileID = t4, this.x = t4.canonical.x, this.y = t4.canonical.y, this.z = t4.canonical.z, this.grid = new vi($a, 16, 0), this.grid3D = new vi($a, 16, 0), this.featureIndexArray = new Ns(), this.promoteId = e2;
            }
            insert(t4, e2, r2, n2, i2, s2) {
              const a2 = this.featureIndexArray.length;
              this.featureIndexArray.emplaceBack(r2, n2, i2);
              const o2 = s2 ? this.grid3D : this.grid;
              for (let t5 = 0; t5 < e2.length; t5++) {
                const r3 = e2[t5], n3 = [1 / 0, 1 / 0, -1 / 0, -1 / 0];
                for (let t6 = 0; t6 < r3.length; t6++) {
                  const e3 = r3[t6];
                  n3[0] = Math.min(n3[0], e3.x), n3[1] = Math.min(n3[1], e3.y), n3[2] = Math.max(n3[2], e3.x), n3[3] = Math.max(n3[3], e3.y);
                }
                n3[0] < $a && n3[1] < $a && n3[2] >= 0 && n3[3] >= 0 && o2.insert(a2, n3[0], n3[1], n3[2], n3[3]);
              }
            }
            loadVTLayers() {
              return this.vtLayers || (this.vtLayers = new fl.VectorTile(new Iu(this.rawTileData)).layers, this.sourceLayerCoder = new qc(this.vtLayers ? Object.keys(this.vtLayers).sort() : ["_geojsonTileLayer"])), this.vtLayers;
            }
            query(t4, e2, r2, n2) {
              this.loadVTLayers();
              const i2 = t4.params || {}, a2 = $a / t4.tileSize / t4.scale, o2 = zn(i2.filter), l2 = t4.queryGeometry, u2 = t4.queryPadding * a2, c2 = Kc(l2), h2 = this.grid.query(c2.minX - u2, c2.minY - u2, c2.maxX + u2, c2.maxY + u2), p2 = Kc(t4.cameraQueryGeometry), f2 = this.grid3D.query(p2.minX - u2, p2.minY - u2, p2.maxX + u2, p2.maxY + u2, (e3, r3, n3, i3) => function(t5, e4, r4, n4, i4) {
                for (const s2 of t5) if (e4 <= s2.x && r4 <= s2.y && n4 >= s2.x && i4 >= s2.y) return true;
                const a3 = [new s(e4, r4), new s(e4, i4), new s(n4, i4), new s(n4, r4)];
                if (t5.length > 2) {
                  for (const e5 of a3) if (Wa(t5, e5)) return true;
                }
                for (let e5 = 0; e5 < t5.length - 1; e5++) if (Qa(t5[e5], t5[e5 + 1], a3)) return true;
                return false;
              }(t4.cameraQueryGeometry, e3 - u2, r3 - u2, n3 + u2, i3 + u2));
              for (const t5 of f2) h2.push(t5);
              h2.sort(Xc);
              const d2 = {};
              let y2;
              for (let s2 = 0; s2 < h2.length; s2++) {
                const u3 = h2[s2];
                if (u3 === y2) continue;
                y2 = u3;
                const c3 = this.featureIndexArray.get(u3);
                let p3 = null;
                this.loadMatchingFeature(d2, c3.bucketIndex, c3.sourceLayerIndex, c3.featureIndex, o2, i2.layers, i2.availableImages, e2, r2, n2, (e3, r3, n3) => (p3 || (p3 = Oa(e3)), r3.queryIntersectsFeature(l2, e3, n3, p3, this.z, t4.transform, a2, t4.pixelPosMatrix)));
              }
              return d2;
            }
            loadMatchingFeature(t4, e2, r2, n2, i2, s2, a2, o2, l2, u2, c2) {
              const h2 = this.bucketLayerIDs[e2];
              if (s2 && !function(t5, e3) {
                for (let r3 = 0; r3 < t5.length; r3++) if (e3.indexOf(t5[r3]) >= 0) return true;
                return false;
              }(s2, h2)) return;
              const p2 = this.sourceLayerCoder.decode(r2), f2 = this.vtLayers[p2].feature(n2);
              if (i2.needGeometry) {
                const t5 = ja(f2, true);
                if (!i2.filter(new Ui(this.tileID.overscaledZ), t5, this.tileID.canonical)) return;
              } else if (!i2.filter(new Ui(this.tileID.overscaledZ), f2)) return;
              const d2 = this.getId(f2, p2);
              for (let e3 = 0; e3 < h2.length; e3++) {
                const r3 = h2[e3];
                if (s2 && s2.indexOf(r3) < 0) continue;
                const i3 = o2[r3];
                if (!i3) continue;
                let p3 = {};
                d2 && u2 && (p3 = u2.getState(i3.sourceLayer || "_geojsonTileLayer", d2));
                const y2 = g({}, l2[r3]);
                y2.paint = Gc(y2.paint, i3.paint, f2, p3, a2), y2.layout = Gc(y2.layout, i3.layout, f2, p3, a2);
                const m2 = !c2 || c2(f2, i3, p3);
                if (!m2) continue;
                const x2 = new Nc(f2, this.z, this.x, this.y, d2);
                x2.layer = y2;
                let v2 = t4[r3];
                void 0 === v2 && (v2 = t4[r3] = []), v2.push({ featureIndex: n2, feature: x2, intersectionZ: m2 });
              }
            }
            lookupSymbolFeatures(t4, e2, r2, n2, i2, s2, a2, o2) {
              const l2 = {};
              this.loadVTLayers();
              const u2 = zn(i2);
              for (const i3 of t4) this.loadMatchingFeature(l2, r2, n2, i3, u2, s2, a2, o2, e2);
              return l2;
            }
            hasLayer(t4) {
              for (const e2 of this.bucketLayerIDs) for (const r2 of e2) if (t4 === r2) return true;
              return false;
            }
            getId(t4, e2) {
              let r2 = t4.id;
              return this.promoteId && (r2 = t4.properties["string" == typeof this.promoteId ? this.promoteId : this.promoteId[e2]], "boolean" == typeof r2 && (r2 = Number(r2))), r2;
            }
          }
          function Gc(t4, e2, r2, n2, i2) {
            return v(t4, (t5, s2) => {
              const a2 = e2 instanceof Yi ? e2.get(s2) : null;
              return a2 && a2.evaluate ? a2.evaluate(r2, n2, i2) : a2;
            });
          }
          function Kc(t4) {
            let e2 = 1 / 0, r2 = 1 / 0, n2 = -1 / 0, i2 = -1 / 0;
            for (const s2 of t4) e2 = Math.min(e2, s2.x), r2 = Math.min(r2, s2.y), n2 = Math.max(n2, s2.x), i2 = Math.max(i2, s2.y);
            return { minX: e2, minY: r2, maxX: n2, maxY: i2 };
          }
          function Xc(t4, e2) {
            return e2 - t4;
          }
          function Hc(t4, e2, r2, n2, i2) {
            const a2 = [];
            for (let o2 = 0; o2 < t4.length; o2++) {
              const l2 = t4[o2];
              let u2;
              for (let t5 = 0; t5 < l2.length - 1; t5++) {
                let o3 = l2[t5], c2 = l2[t5 + 1];
                o3.x < e2 && c2.x < e2 || (o3.x < e2 ? o3 = new s(e2, o3.y + (e2 - o3.x) / (c2.x - o3.x) * (c2.y - o3.y))._round() : c2.x < e2 && (c2 = new s(e2, o3.y + (e2 - o3.x) / (c2.x - o3.x) * (c2.y - o3.y))._round()), o3.y < r2 && c2.y < r2 || (o3.y < r2 ? o3 = new s(o3.x + (r2 - o3.y) / (c2.y - o3.y) * (c2.x - o3.x), r2)._round() : c2.y < r2 && (c2 = new s(o3.x + (r2 - o3.y) / (c2.y - o3.y) * (c2.x - o3.x), r2)._round()), o3.x >= n2 && c2.x >= n2 || (o3.x >= n2 ? o3 = new s(n2, o3.y + (n2 - o3.x) / (c2.x - o3.x) * (c2.y - o3.y))._round() : c2.x >= n2 && (c2 = new s(n2, o3.y + (n2 - o3.x) / (c2.x - o3.x) * (c2.y - o3.y))._round()), o3.y >= i2 && c2.y >= i2 || (o3.y >= i2 ? o3 = new s(o3.x + (i2 - o3.y) / (c2.y - o3.y) * (c2.x - o3.x), i2)._round() : c2.y >= i2 && (c2 = new s(o3.x + (i2 - o3.y) / (c2.y - o3.y) * (c2.x - o3.x), i2)._round()), u2 && o3.equals(u2[u2.length - 1]) || (u2 = [o3], a2.push(u2)), u2.push(c2)))));
              }
            }
            return a2;
          }
          wi("FeatureIndex", Zc, { omit: ["rawTileData", "sourceLayerCoder"] });
          class Yc extends s {
            constructor(t4, e2, r2, n2) {
              super(t4, e2), this.angle = r2, void 0 !== n2 && (this.segment = n2);
            }
            clone() {
              return new Yc(this.x, this.y, this.angle, this.segment);
            }
          }
          function Jc(t4, e2, r2, n2, i2) {
            if (void 0 === e2.segment || 0 === r2) return true;
            let s2 = e2, a2 = e2.segment + 1, o2 = 0;
            for (; o2 > -r2 / 2; ) {
              if (a2--, a2 < 0) return false;
              o2 -= t4[a2].dist(s2), s2 = t4[a2];
            }
            o2 += t4[a2].dist(t4[a2 + 1]), a2++;
            const l2 = [];
            let u2 = 0;
            for (; o2 < r2 / 2; ) {
              const e3 = t4[a2], r3 = t4[a2 + 1];
              if (!r3) return false;
              let s3 = t4[a2 - 1].angleTo(e3) - e3.angleTo(r3);
              for (s3 = Math.abs((s3 + 3 * Math.PI) % (2 * Math.PI) - Math.PI), l2.push({ distance: o2, angleDelta: s3 }), u2 += s3; o2 - l2[0].distance > n2; ) u2 -= l2.shift().angleDelta;
              if (u2 > i2) return false;
              a2++, o2 += e3.dist(r3);
            }
            return true;
          }
          function Wc(t4) {
            let e2 = 0;
            for (let r2 = 0; r2 < t4.length - 1; r2++) e2 += t4[r2].dist(t4[r2 + 1]);
            return e2;
          }
          function Qc(t4, e2, r2) {
            return t4 ? 0.6 * e2 * r2 : 0;
          }
          function th(t4, e2) {
            return Math.max(t4 ? t4.right - t4.left : 0, e2 ? e2.right - e2.left : 0);
          }
          function eh(t4, e2, r2, n2, i2, s2) {
            const a2 = Qc(r2, i2, s2), o2 = th(r2, n2) * s2;
            let l2 = 0;
            const u2 = Wc(t4) / 2;
            for (let r3 = 0; r3 < t4.length - 1; r3++) {
              const n3 = t4[r3], i3 = t4[r3 + 1], s3 = n3.dist(i3);
              if (l2 + s3 > u2) {
                const c2 = (u2 - l2) / s3, h2 = Ce.number(n3.x, i3.x, c2), p2 = Ce.number(n3.y, i3.y, c2), f2 = new Yc(h2, p2, i3.angleTo(n3), r3);
                return f2._round(), !a2 || Jc(t4, f2, o2, a2, e2) ? f2 : void 0;
              }
              l2 += s3;
            }
          }
          function rh(t4, e2, r2, n2, i2, s2, a2, o2, l2) {
            const u2 = Qc(n2, s2, a2), c2 = th(n2, i2), h2 = c2 * a2, p2 = 0 === t4[0].x || t4[0].x === l2 || 0 === t4[0].y || t4[0].y === l2;
            return e2 - h2 < e2 / 4 && (e2 = h2 + e2 / 4), nh(t4, p2 ? e2 / 2 * o2 % e2 : (c2 / 2 + 2 * s2) * a2 * o2 % e2, e2, u2, r2, h2, p2, false, l2);
          }
          function nh(t4, e2, r2, n2, i2, s2, a2, o2, l2) {
            const u2 = s2 / 2, c2 = Wc(t4);
            let h2 = 0, p2 = e2 - r2, f2 = [];
            for (let e3 = 0; e3 < t4.length - 1; e3++) {
              const a3 = t4[e3], o3 = t4[e3 + 1], d2 = a3.dist(o3), y2 = o3.angleTo(a3);
              for (; p2 + r2 < h2 + d2; ) {
                p2 += r2;
                const m2 = (p2 - h2) / d2, g2 = Ce.number(a3.x, o3.x, m2), x2 = Ce.number(a3.y, o3.y, m2);
                if (g2 >= 0 && g2 < l2 && x2 >= 0 && x2 < l2 && p2 - u2 >= 0 && p2 + u2 <= c2) {
                  const r3 = new Yc(g2, x2, y2, e3);
                  r3._round(), n2 && !Jc(t4, r3, s2, n2, i2) || f2.push(r3);
                }
              }
              h2 += d2;
            }
            return o2 || f2.length || a2 || (f2 = nh(t4, h2 / 2, r2, n2, i2, s2, a2, true, l2)), f2;
          }
          wi("Anchor", Yc);
          const ih = Fu;
          function sh(t4, e2, r2, n2) {
            const i2 = [], a2 = t4.image, o2 = a2.pixelRatio, l2 = a2.paddedRect.w - 2 * ih, u2 = a2.paddedRect.h - 2 * ih;
            let c2 = { x1: t4.left, y1: t4.top, x2: t4.right, y2: t4.bottom };
            const h2 = a2.stretchX || [[0, l2]], p2 = a2.stretchY || [[0, u2]], f2 = (t5, e3) => t5 + e3[1] - e3[0], d2 = h2.reduce(f2, 0), y2 = p2.reduce(f2, 0), m2 = l2 - d2, g2 = u2 - y2;
            let x2 = 0, v2 = d2, b2 = 0, w2 = y2, _2 = 0, A3 = m2, S2 = 0, k2 = g2;
            if (a2.content && n2) {
              const e3 = a2.content, r3 = e3[2] - e3[0], n3 = e3[3] - e3[1];
              (a2.textFitWidth || a2.textFitHeight) && (c2 = tc(t4)), x2 = ah(h2, 0, e3[0]), b2 = ah(p2, 0, e3[1]), v2 = ah(h2, e3[0], e3[2]), w2 = ah(p2, e3[1], e3[3]), _2 = e3[0] - x2, S2 = e3[1] - b2, A3 = r3 - v2, k2 = n3 - w2;
            }
            const M2 = c2.x1, I2 = c2.y1, z2 = c2.x2 - M2, P2 = c2.y2 - I2, C3 = (t5, n3, i3, l3) => {
              const u3 = lh(t5.stretch - x2, v2, z2, M2), c3 = uh(t5.fixed - _2, A3, t5.stretch, d2), h3 = lh(n3.stretch - b2, w2, P2, I2), p3 = uh(n3.fixed - S2, k2, n3.stretch, y2), f3 = lh(i3.stretch - x2, v2, z2, M2), m3 = uh(i3.fixed - _2, A3, i3.stretch, d2), g3 = lh(l3.stretch - b2, w2, P2, I2), C4 = uh(l3.fixed - S2, k2, l3.stretch, y2), B3 = new s(u3, h3), V2 = new s(f3, h3), E3 = new s(f3, g3), F2 = new s(u3, g3), T2 = new s(c3 / o2, p3 / o2), $2 = new s(m3 / o2, C4 / o2), L2 = e2 * Math.PI / 180;
              if (L2) {
                const t6 = Math.sin(L2), e3 = Math.cos(L2), r3 = [e3, -t6, t6, e3];
                B3._matMult(r3), V2._matMult(r3), F2._matMult(r3), E3._matMult(r3);
              }
              const D3 = t5.stretch + t5.fixed, O2 = n3.stretch + n3.fixed;
              return { tl: B3, tr: V2, bl: F2, br: E3, tex: { x: a2.paddedRect.x + ih + D3, y: a2.paddedRect.y + ih + O2, w: i3.stretch + i3.fixed - D3, h: l3.stretch + l3.fixed - O2 }, writingMode: void 0, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL: T2, pixelOffsetBR: $2, minFontScaleX: A3 / o2 / z2, minFontScaleY: k2 / o2 / P2, isSDF: r2 };
            };
            if (n2 && (a2.stretchX || a2.stretchY)) {
              const t5 = oh(h2, m2, d2), e3 = oh(p2, g2, y2);
              for (let r3 = 0; r3 < t5.length - 1; r3++) {
                const n3 = t5[r3], s2 = t5[r3 + 1];
                for (let t6 = 0; t6 < e3.length - 1; t6++) i2.push(C3(n3, e3[t6], s2, e3[t6 + 1]));
              }
            } else i2.push(C3({ fixed: 0, stretch: -1 }, { fixed: 0, stretch: -1 }, { fixed: 0, stretch: l2 + 1 }, { fixed: 0, stretch: u2 + 1 }));
            return i2;
          }
          function ah(t4, e2, r2) {
            let n2 = 0;
            for (const i2 of t4) n2 += Math.max(e2, Math.min(r2, i2[1])) - Math.max(e2, Math.min(r2, i2[0]));
            return n2;
          }
          function oh(t4, e2, r2) {
            const n2 = [{ fixed: -ih, stretch: 0 }];
            for (const [e3, r3] of t4) {
              const t5 = n2[n2.length - 1];
              n2.push({ fixed: e3 - t5.stretch, stretch: t5.stretch }), n2.push({ fixed: e3 - t5.stretch, stretch: t5.stretch + (r3 - e3) });
            }
            return n2.push({ fixed: e2 + ih, stretch: r2 }), n2;
          }
          function lh(t4, e2, r2, n2) {
            return t4 / e2 * r2 + n2;
          }
          function uh(t4, e2, r2, n2) {
            return t4 - e2 * r2 / n2;
          }
          class ch {
            constructor(t4, e2, r2, n2, i2, a2, o2, l2, u2, c2) {
              var h2;
              if (this.boxStartIndex = t4.length, u2) {
                let t5 = a2.top, e3 = a2.bottom;
                const r3 = a2.collisionPadding;
                r3 && (t5 -= r3[1], e3 += r3[3]);
                let n3 = e3 - t5;
                n3 > 0 && (n3 = Math.max(10, n3), this.circleDiameter = n3);
              } else {
                const u3 = (null === (h2 = a2.image) || void 0 === h2 ? void 0 : h2.content) && (a2.image.textFitWidth || a2.image.textFitHeight) ? tc(a2) : { x1: a2.left, y1: a2.top, x2: a2.right, y2: a2.bottom };
                u3.y1 = u3.y1 * o2 - l2[0], u3.y2 = u3.y2 * o2 + l2[2], u3.x1 = u3.x1 * o2 - l2[3], u3.x2 = u3.x2 * o2 + l2[1];
                const p2 = a2.collisionPadding;
                if (p2 && (u3.x1 -= p2[0] * o2, u3.y1 -= p2[1] * o2, u3.x2 += p2[2] * o2, u3.y2 += p2[3] * o2), c2) {
                  const t5 = new s(u3.x1, u3.y1), e3 = new s(u3.x2, u3.y1), r3 = new s(u3.x1, u3.y2), n3 = new s(u3.x2, u3.y2), i3 = c2 * Math.PI / 180;
                  t5._rotate(i3), e3._rotate(i3), r3._rotate(i3), n3._rotate(i3), u3.x1 = Math.min(t5.x, e3.x, r3.x, n3.x), u3.x2 = Math.max(t5.x, e3.x, r3.x, n3.x), u3.y1 = Math.min(t5.y, e3.y, r3.y, n3.y), u3.y2 = Math.max(t5.y, e3.y, r3.y, n3.y);
                }
                t4.emplaceBack(e2.x, e2.y, u3.x1, u3.y1, u3.x2, u3.y2, r2, n2, i2);
              }
              this.boxEndIndex = t4.length;
            }
          }
          class hh {
            constructor(t4 = [], e2 = (t5, e3) => t5 < e3 ? -1 : t5 > e3 ? 1 : 0) {
              if (this.data = t4, this.length = this.data.length, this.compare = e2, this.length > 0) for (let t5 = (this.length >> 1) - 1; t5 >= 0; t5--) this._down(t5);
            }
            push(t4) {
              this.data.push(t4), this._up(this.length++);
            }
            pop() {
              if (0 === this.length) return;
              const t4 = this.data[0], e2 = this.data.pop();
              return --this.length > 0 && (this.data[0] = e2, this._down(0)), t4;
            }
            peek() {
              return this.data[0];
            }
            _up(t4) {
              const { data: e2, compare: r2 } = this, n2 = e2[t4];
              for (; t4 > 0; ) {
                const i2 = t4 - 1 >> 1, s2 = e2[i2];
                if (r2(n2, s2) >= 0) break;
                e2[t4] = s2, t4 = i2;
              }
              e2[t4] = n2;
            }
            _down(t4) {
              const { data: e2, compare: r2 } = this, n2 = this.length >> 1, i2 = e2[t4];
              for (; t4 < n2; ) {
                let n3 = 1 + (t4 << 1);
                const s2 = n3 + 1;
                if (s2 < this.length && r2(e2[s2], e2[n3]) < 0 && (n3 = s2), r2(e2[n3], i2) >= 0) break;
                e2[t4] = e2[n3], t4 = n3;
              }
              e2[t4] = i2;
            }
          }
          function ph(t4, e2 = 1, r2 = false) {
            let n2 = 1 / 0, i2 = 1 / 0, a2 = -1 / 0, o2 = -1 / 0;
            const l2 = t4[0];
            for (let t5 = 0; t5 < l2.length; t5++) {
              const e3 = l2[t5];
              (!t5 || e3.x < n2) && (n2 = e3.x), (!t5 || e3.y < i2) && (i2 = e3.y), (!t5 || e3.x > a2) && (a2 = e3.x), (!t5 || e3.y > o2) && (o2 = e3.y);
            }
            const u2 = Math.min(a2 - n2, o2 - i2);
            let c2 = u2 / 2;
            const h2 = new hh([], fh);
            if (0 === u2) return new s(n2, i2);
            for (let e3 = n2; e3 < a2; e3 += u2) for (let r3 = i2; r3 < o2; r3 += u2) h2.push(new dh(e3 + c2, r3 + c2, c2, t4));
            let p2 = function(t5) {
              let e3 = 0, r3 = 0, n3 = 0;
              const i3 = t5[0];
              for (let t6 = 0, s2 = i3.length, a3 = s2 - 1; t6 < s2; a3 = t6++) {
                const s3 = i3[t6], o3 = i3[a3], l3 = s3.x * o3.y - o3.x * s3.y;
                r3 += (s3.x + o3.x) * l3, n3 += (s3.y + o3.y) * l3, e3 += 3 * l3;
              }
              return new dh(r3 / e3, n3 / e3, 0, t5);
            }(t4), f2 = h2.length;
            for (; h2.length; ) {
              const n3 = h2.pop();
              (n3.d > p2.d || !p2.d) && (p2 = n3, r2 && console.log("found best %d after %d probes", Math.round(1e4 * n3.d) / 1e4, f2)), n3.max - p2.d <= e2 || (c2 = n3.h / 2, h2.push(new dh(n3.p.x - c2, n3.p.y - c2, c2, t4)), h2.push(new dh(n3.p.x + c2, n3.p.y - c2, c2, t4)), h2.push(new dh(n3.p.x - c2, n3.p.y + c2, c2, t4)), h2.push(new dh(n3.p.x + c2, n3.p.y + c2, c2, t4)), f2 += 4);
            }
            return r2 && (console.log(`num probes: ${f2}`), console.log(`best distance: ${p2.d}`)), p2.p;
          }
          function fh(t4, e2) {
            return e2.max - t4.max;
          }
          function dh(t4, e2, r2, n2) {
            this.p = new s(t4, e2), this.h = r2, this.d = function(t5, e3) {
              let r3 = false, n3 = 1 / 0;
              for (let i2 = 0; i2 < e3.length; i2++) {
                const s2 = e3[i2];
                for (let e4 = 0, i3 = s2.length, a2 = i3 - 1; e4 < i3; a2 = e4++) {
                  const i4 = s2[e4], o2 = s2[a2];
                  i4.y > t5.y != o2.y > t5.y && t5.x < (o2.x - i4.x) * (t5.y - i4.y) / (o2.y - i4.y) + i4.x && (r3 = !r3), n3 = Math.min(n3, Ya(t5, i4, o2));
                }
              }
              return (r3 ? 1 : -1) * Math.sqrt(n3);
            }(this.p, n2), this.max = this.d + this.h * Math.SQRT2;
          }
          var yh;
          t.aq = void 0, (yh = t.aq || (t.aq = {}))[yh.center = 1] = "center", yh[yh.left = 2] = "left", yh[yh.right = 3] = "right", yh[yh.top = 4] = "top", yh[yh.bottom = 5] = "bottom", yh[yh["top-left"] = 6] = "top-left", yh[yh["top-right"] = 7] = "top-right", yh[yh["bottom-left"] = 8] = "bottom-left", yh[yh["bottom-right"] = 9] = "bottom-right";
          const mh = 7, gh = Number.POSITIVE_INFINITY;
          function xh(t4, e2) {
            return e2[1] !== gh ? function(t5, e3, r2) {
              let n2 = 0, i2 = 0;
              switch (e3 = Math.abs(e3), r2 = Math.abs(r2), t5) {
                case "top-right":
                case "top-left":
                case "top":
                  i2 = r2 - mh;
                  break;
                case "bottom-right":
                case "bottom-left":
                case "bottom":
                  i2 = -r2 + mh;
              }
              switch (t5) {
                case "top-right":
                case "bottom-right":
                case "right":
                  n2 = -e3;
                  break;
                case "top-left":
                case "bottom-left":
                case "left":
                  n2 = e3;
              }
              return [n2, i2];
            }(t4, e2[0], e2[1]) : function(t5, e3) {
              let r2 = 0, n2 = 0;
              e3 < 0 && (e3 = 0);
              const i2 = e3 / Math.SQRT2;
              switch (t5) {
                case "top-right":
                case "top-left":
                  n2 = i2 - mh;
                  break;
                case "bottom-right":
                case "bottom-left":
                  n2 = -i2 + mh;
                  break;
                case "bottom":
                  n2 = -e3 + mh;
                  break;
                case "top":
                  n2 = e3 - mh;
              }
              switch (t5) {
                case "top-right":
                case "bottom-right":
                  r2 = -i2;
                  break;
                case "top-left":
                case "bottom-left":
                  r2 = i2;
                  break;
                case "left":
                  r2 = e3;
                  break;
                case "right":
                  r2 = -e3;
              }
              return [r2, n2];
            }(t4, e2[0]);
          }
          function vh(t4, e2, r2) {
            var n2;
            const i2 = t4.layout, s2 = null === (n2 = i2.get("text-variable-anchor-offset")) || void 0 === n2 ? void 0 : n2.evaluate(e2, {}, r2);
            if (s2) {
              const t5 = s2.values, e3 = [];
              for (let r3 = 0; r3 < t5.length; r3 += 2) {
                const n3 = e3[r3] = t5[r3], i3 = t5[r3 + 1].map((t6) => t6 * iu);
                n3.startsWith("top") ? i3[1] -= mh : n3.startsWith("bottom") && (i3[1] += mh), e3[r3 + 1] = i3;
              }
              return new Qt(e3);
            }
            const a2 = i2.get("text-variable-anchor");
            if (a2) {
              let n3;
              n3 = void 0 !== t4._unevaluatedLayout.getValue("text-radial-offset") ? [i2.get("text-radial-offset").evaluate(e2, {}, r2) * iu, gh] : i2.get("text-offset").evaluate(e2, {}, r2).map((t5) => t5 * iu);
              const s3 = [];
              for (const t5 of a2) s3.push(t5, xh(t5, n3));
              return new Qt(s3);
            }
            return null;
          }
          function bh(t4) {
            switch (t4) {
              case "right":
              case "top-right":
              case "bottom-right":
                return "right";
              case "left":
              case "top-left":
              case "bottom-left":
                return "left";
            }
            return "center";
          }
          function wh(e2, r2, n2, i2, s2, a2, o2, l2, u2, c2, h2) {
            let p2 = a2.textMaxSize.evaluate(r2, {});
            void 0 === p2 && (p2 = o2);
            const f2 = e2.layers[0].layout, d2 = f2.get("icon-offset").evaluate(r2, {}, h2), y2 = Ah(n2.horizontal), m2 = o2 / 24, g2 = e2.tilePixelRatio * m2, x2 = e2.tilePixelRatio * p2 / 24, v2 = e2.tilePixelRatio * l2, b2 = e2.tilePixelRatio * f2.get("symbol-spacing"), w2 = f2.get("text-padding") * e2.tilePixelRatio, _2 = function(t4, e3, r3, n3 = 1) {
              const i3 = t4.get("icon-padding").evaluate(e3, {}, r3), s3 = i3 && i3.values;
              return [s3[0] * n3, s3[1] * n3, s3[2] * n3, s3[3] * n3];
            }(f2, r2, h2, e2.tilePixelRatio), S2 = f2.get("text-max-angle") / 180 * Math.PI, k2 = "viewport" !== f2.get("text-rotation-alignment") && "point" !== f2.get("symbol-placement"), M2 = "map" === f2.get("icon-rotation-alignment") && "point" !== f2.get("symbol-placement"), I2 = f2.get("symbol-placement"), z2 = b2 / 2, P2 = f2.get("icon-text-fit");
            let C3;
            i2 && "none" !== P2 && (e2.allowVerticalPlacement && n2.vertical && (C3 = ec(i2, n2.vertical, P2, f2.get("icon-text-fit-padding"), d2, m2)), y2 && (i2 = ec(i2, y2, P2, f2.get("icon-text-fit-padding"), d2, m2)));
            const B3 = (l3, p3) => {
              p3.x < 0 || p3.x >= $a || p3.y < 0 || p3.y >= $a || function(e3, r3, n3, i3, s3, a3, o3, l4, u3, c3, h3, p4, f3, d3, y3, m3, g3, x3, v3, b3, w3, _3, S3, k3, M3) {
                const I3 = e3.addToLineVertexArray(r3, n3);
                let z3, P3, C4, B4, V2 = 0, E3 = 0, F2 = 0, T2 = 0, $2 = -1, L2 = -1;
                const D3 = {};
                let O2 = ma("");
                if (e3.allowVerticalPlacement && i3.vertical) {
                  const t4 = l4.layout.get("text-rotate").evaluate(w3, {}, k3) + 90;
                  C4 = new ch(u3, r3, c3, h3, p4, i3.vertical, f3, d3, y3, t4), o3 && (B4 = new ch(u3, r3, c3, h3, p4, o3, g3, x3, y3, t4));
                }
                if (s3) {
                  const n4 = l4.layout.get("icon-rotate").evaluate(w3, {}), i4 = "none" !== l4.layout.get("icon-text-fit"), a4 = sh(s3, n4, S3, i4), f4 = o3 ? sh(o3, n4, S3, i4) : void 0;
                  P3 = new ch(u3, r3, c3, h3, p4, s3, g3, x3, false, n4), V2 = 4 * a4.length;
                  const d4 = e3.iconSizeData;
                  let y4 = null;
                  "source" === d4.kind ? (y4 = [nc * l4.layout.get("icon-size").evaluate(w3, {})], y4[0] > ic && A2(`${e3.layerIds[0]}: Value for "icon-size" is >= ${rc}. Reduce your "icon-size".`)) : "composite" === d4.kind && (y4 = [nc * _3.compositeIconSizes[0].evaluate(w3, {}, k3), nc * _3.compositeIconSizes[1].evaluate(w3, {}, k3)], (y4[0] > ic || y4[1] > ic) && A2(`${e3.layerIds[0]}: Value for "icon-size" is >= ${rc}. Reduce your "icon-size".`)), e3.addSymbols(e3.icon, a4, y4, b3, v3, w3, t.ah.none, r3, I3.lineStartIndex, I3.lineLength, -1, k3), $2 = e3.icon.placedSymbolArray.length - 1, f4 && (E3 = 4 * f4.length, e3.addSymbols(e3.icon, f4, y4, b3, v3, w3, t.ah.vertical, r3, I3.lineStartIndex, I3.lineLength, -1, k3), L2 = e3.icon.placedSymbolArray.length - 1);
                }
                const j2 = Object.keys(i3.horizontal);
                for (const n4 of j2) {
                  const s4 = i3.horizontal[n4];
                  if (!z3) {
                    O2 = ma(s4.text);
                    const t4 = l4.layout.get("text-rotate").evaluate(w3, {}, k3);
                    z3 = new ch(u3, r3, c3, h3, p4, s4, f3, d3, y3, t4);
                  }
                  const o4 = 1 === s4.positionedLines.length;
                  if (F2 += _h(e3, r3, s4, a3, l4, y3, w3, m3, I3, i3.vertical ? t.ah.horizontal : t.ah.horizontalOnly, o4 ? j2 : [n4], D3, $2, _3, k3), o4) break;
                }
                i3.vertical && (T2 += _h(e3, r3, i3.vertical, a3, l4, y3, w3, m3, I3, t.ah.vertical, ["vertical"], D3, L2, _3, k3));
                const R2 = z3 ? z3.boxStartIndex : e3.collisionBoxArray.length, U2 = z3 ? z3.boxEndIndex : e3.collisionBoxArray.length, q2 = C4 ? C4.boxStartIndex : e3.collisionBoxArray.length, N2 = C4 ? C4.boxEndIndex : e3.collisionBoxArray.length, Z2 = P3 ? P3.boxStartIndex : e3.collisionBoxArray.length, G2 = P3 ? P3.boxEndIndex : e3.collisionBoxArray.length, K3 = B4 ? B4.boxStartIndex : e3.collisionBoxArray.length, X2 = B4 ? B4.boxEndIndex : e3.collisionBoxArray.length;
                let H2 = -1;
                const Y2 = (t4, e4) => t4 && t4.circleDiameter ? Math.max(t4.circleDiameter, e4) : e4;
                H2 = Y2(z3, H2), H2 = Y2(C4, H2), H2 = Y2(P3, H2), H2 = Y2(B4, H2);
                const J2 = H2 > -1 ? 1 : 0;
                J2 && (H2 *= M3 / iu), e3.glyphOffsetArray.length >= dc.MAX_GLYPHS && A2("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"), void 0 !== w3.sortKey && e3.addToSortKeyRanges(e3.symbolInstances.length, w3.sortKey);
                const W2 = vh(l4, w3, k3), [Q2, tt2] = function(e4, r4) {
                  const n4 = e4.length, i4 = null == r4 ? void 0 : r4.values;
                  if ((null == i4 ? void 0 : i4.length) > 0) for (let r5 = 0; r5 < i4.length; r5 += 2) {
                    const n5 = i4[r5 + 1];
                    e4.emplaceBack(t.aq[i4[r5]], n5[0], n5[1]);
                  }
                  return [n4, e4.length];
                }(e3.textAnchorOffsets, W2);
                e3.symbolInstances.emplaceBack(r3.x, r3.y, D3.right >= 0 ? D3.right : -1, D3.center >= 0 ? D3.center : -1, D3.left >= 0 ? D3.left : -1, D3.vertical || -1, $2, L2, O2, R2, U2, q2, N2, Z2, G2, K3, X2, c3, F2, T2, V2, E3, J2, 0, f3, H2, Q2, tt2);
              }(e2, p3, l3, n2, i2, s2, C3, e2.layers[0], e2.collisionBoxArray, r2.index, r2.sourceLayerIndex, e2.index, g2, [w2, w2, w2, w2], k2, u2, v2, _2, M2, d2, r2, a2, c2, h2, o2);
            };
            if ("line" === I2) for (const t4 of Hc(r2.geometry, 0, 0, $a, $a)) {
              const r3 = rh(t4, b2, S2, n2.vertical || y2, i2, 24, x2, e2.overscaling, $a);
              for (const n3 of r3) y2 && Sh(e2, y2.text, z2, n3) || B3(t4, n3);
            }
            else if ("line-center" === I2) {
              for (const t4 of r2.geometry) if (t4.length > 1) {
                const e3 = eh(t4, S2, n2.vertical || y2, i2, 24, x2);
                e3 && B3(t4, e3);
              }
            } else if ("Polygon" === r2.type) for (const t4 of xr(r2.geometry, 0)) {
              const e3 = ph(t4, 16);
              B3(t4[0], new Yc(e3.x, e3.y, 0));
            }
            else if ("LineString" === r2.type) for (const t4 of r2.geometry) B3(t4, new Yc(t4[0].x, t4[0].y, 0));
            else if ("Point" === r2.type) for (const t4 of r2.geometry) for (const e3 of t4) B3([e3], new Yc(e3.x, e3.y, 0));
          }
          function _h(t4, e2, r2, n2, i2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2) {
            const m2 = function(t5, e3, r3, n3, i3, a3, o3, l3) {
              const u3 = n3.layout.get("text-rotate").evaluate(a3, {}) * Math.PI / 180, c3 = [];
              for (const t6 of e3.positionedLines) for (const n4 of t6.positionedGlyphs) {
                if (!n4.rect) continue;
                const a4 = n4.rect || {};
                let h3 = Vu + 1, p3 = true, f3 = 1, d3 = 0;
                const y3 = (i3 || l3) && n4.vertical, m3 = n4.metrics.advance * n4.scale / 2;
                if (l3 && e3.verticalizable && (d3 = t6.lineOffset / 2 - (n4.imageName ? -(iu - n4.metrics.width * n4.scale) / 2 : (n4.scale - 1) * iu)), n4.imageName) {
                  const t7 = o3[n4.imageName];
                  p3 = t7.sdf, f3 = t7.pixelRatio, h3 = Fu / f3;
                }
                const g3 = i3 ? [n4.x + m3, n4.y] : [0, 0];
                let x3 = i3 ? [0, 0] : [n4.x + m3 + r3[0], n4.y + r3[1] - d3], v2 = [0, 0];
                y3 && (v2 = x3, x3 = [0, 0]);
                const b2 = n4.metrics.isDoubleResolution ? 2 : 1, w2 = (n4.metrics.left - h3) * n4.scale - m3 + x3[0], _2 = (-n4.metrics.top - h3) * n4.scale + x3[1], A3 = w2 + a4.w / b2 * n4.scale / f3, S2 = _2 + a4.h / b2 * n4.scale / f3, k2 = new s(w2, _2), M2 = new s(A3, _2), I2 = new s(w2, S2), z2 = new s(A3, S2);
                if (y3) {
                  const t7 = new s(-m3, m3 - Du), e4 = -Math.PI / 2, r4 = iu / 2 - m3, i4 = new s(5 - Du - r4, -(n4.imageName ? r4 : 0)), a5 = new s(...v2);
                  k2._rotateAround(e4, t7)._add(i4)._add(a5), M2._rotateAround(e4, t7)._add(i4)._add(a5), I2._rotateAround(e4, t7)._add(i4)._add(a5), z2._rotateAround(e4, t7)._add(i4)._add(a5);
                }
                if (u3) {
                  const t7 = Math.sin(u3), e4 = Math.cos(u3), r4 = [e4, -t7, t7, e4];
                  k2._matMult(r4), M2._matMult(r4), I2._matMult(r4), z2._matMult(r4);
                }
                const P2 = new s(0, 0), C3 = new s(0, 0);
                c3.push({ tl: k2, tr: M2, bl: I2, br: z2, tex: a4, writingMode: e3.writingMode, glyphOffset: g3, sectionIndex: n4.sectionIndex, isSDF: p3, pixelOffsetTL: P2, pixelOffsetBR: C3, minFontScaleX: 0, minFontScaleY: 0 });
              }
              return c3;
            }(0, r2, l2, i2, a2, o2, n2, t4.allowVerticalPlacement), g2 = t4.textSizeData;
            let x2 = null;
            "source" === g2.kind ? (x2 = [nc * i2.layout.get("text-size").evaluate(o2, {})], x2[0] > ic && A2(`${t4.layerIds[0]}: Value for "text-size" is >= ${rc}. Reduce your "text-size".`)) : "composite" === g2.kind && (x2 = [nc * d2.compositeTextSizes[0].evaluate(o2, {}, y2), nc * d2.compositeTextSizes[1].evaluate(o2, {}, y2)], (x2[0] > ic || x2[1] > ic) && A2(`${t4.layerIds[0]}: Value for "text-size" is >= ${rc}. Reduce your "text-size".`)), t4.addSymbols(t4.text, m2, x2, l2, a2, o2, c2, e2, u2.lineStartIndex, u2.lineLength, f2, y2);
            for (const e3 of h2) p2[e3] = t4.text.placedSymbolArray.length - 1;
            return 4 * m2.length;
          }
          function Ah(t4) {
            for (const e2 in t4) return t4[e2];
            return null;
          }
          function Sh(t4, e2, r2, n2) {
            const i2 = t4.compareText;
            if (e2 in i2) {
              const t5 = i2[e2];
              for (let e3 = t5.length - 1; e3 >= 0; e3--) if (n2.dist(t5[e3]) < r2) return true;
            } else i2[e2] = [];
            return i2[e2].push(n2), false;
          }
          const kh = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
          class Mh {
            static from(t4) {
              if (!(t4 instanceof ArrayBuffer)) throw new Error("Data must be an instance of ArrayBuffer.");
              const [e2, r2] = new Uint8Array(t4, 0, 2);
              if (219 !== e2) throw new Error("Data does not appear to be in a KDBush format.");
              const n2 = r2 >> 4;
              if (1 !== n2) throw new Error(`Got v${n2} data when expected v1.`);
              const i2 = kh[15 & r2];
              if (!i2) throw new Error("Unrecognized array type.");
              const [s2] = new Uint16Array(t4, 2, 1), [a2] = new Uint32Array(t4, 4, 1);
              return new Mh(a2, s2, i2, t4);
            }
            constructor(t4, e2 = 64, r2 = Float64Array, n2) {
              if (isNaN(t4) || t4 < 0) throw new Error(`Unpexpected numItems value: ${t4}.`);
              this.numItems = +t4, this.nodeSize = Math.min(Math.max(+e2, 2), 65535), this.ArrayType = r2, this.IndexArrayType = t4 < 65536 ? Uint16Array : Uint32Array;
              const i2 = kh.indexOf(this.ArrayType), s2 = 2 * t4 * this.ArrayType.BYTES_PER_ELEMENT, a2 = t4 * this.IndexArrayType.BYTES_PER_ELEMENT, o2 = (8 - a2 % 8) % 8;
              if (i2 < 0) throw new Error(`Unexpected typed array class: ${r2}.`);
              n2 && n2 instanceof ArrayBuffer ? (this.data = n2, this.ids = new this.IndexArrayType(this.data, 8, t4), this.coords = new this.ArrayType(this.data, 8 + a2 + o2, 2 * t4), this._pos = 2 * t4, this._finished = true) : (this.data = new ArrayBuffer(8 + s2 + a2 + o2), this.ids = new this.IndexArrayType(this.data, 8, t4), this.coords = new this.ArrayType(this.data, 8 + a2 + o2, 2 * t4), this._pos = 0, this._finished = false, new Uint8Array(this.data, 0, 2).set([219, 16 + i2]), new Uint16Array(this.data, 2, 1)[0] = e2, new Uint32Array(this.data, 4, 1)[0] = t4);
            }
            add(t4, e2) {
              const r2 = this._pos >> 1;
              return this.ids[r2] = r2, this.coords[this._pos++] = t4, this.coords[this._pos++] = e2, r2;
            }
            finish() {
              const t4 = this._pos >> 1;
              if (t4 !== this.numItems) throw new Error(`Added ${t4} items when expected ${this.numItems}.`);
              return Ih(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0), this._finished = true, this;
            }
            range(t4, e2, r2, n2) {
              if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
              const { ids: i2, coords: s2, nodeSize: a2 } = this, o2 = [0, i2.length - 1, 0], l2 = [];
              for (; o2.length; ) {
                const u2 = o2.pop() || 0, c2 = o2.pop() || 0, h2 = o2.pop() || 0;
                if (c2 - h2 <= a2) {
                  for (let a3 = h2; a3 <= c2; a3++) {
                    const o3 = s2[2 * a3], u3 = s2[2 * a3 + 1];
                    o3 >= t4 && o3 <= r2 && u3 >= e2 && u3 <= n2 && l2.push(i2[a3]);
                  }
                  continue;
                }
                const p2 = h2 + c2 >> 1, f2 = s2[2 * p2], d2 = s2[2 * p2 + 1];
                f2 >= t4 && f2 <= r2 && d2 >= e2 && d2 <= n2 && l2.push(i2[p2]), (0 === u2 ? t4 <= f2 : e2 <= d2) && (o2.push(h2), o2.push(p2 - 1), o2.push(1 - u2)), (0 === u2 ? r2 >= f2 : n2 >= d2) && (o2.push(p2 + 1), o2.push(c2), o2.push(1 - u2));
              }
              return l2;
            }
            within(t4, e2, r2) {
              if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
              const { ids: n2, coords: i2, nodeSize: s2 } = this, a2 = [0, n2.length - 1, 0], o2 = [], l2 = r2 * r2;
              for (; a2.length; ) {
                const u2 = a2.pop() || 0, c2 = a2.pop() || 0, h2 = a2.pop() || 0;
                if (c2 - h2 <= s2) {
                  for (let r3 = h2; r3 <= c2; r3++) Bh(i2[2 * r3], i2[2 * r3 + 1], t4, e2) <= l2 && o2.push(n2[r3]);
                  continue;
                }
                const p2 = h2 + c2 >> 1, f2 = i2[2 * p2], d2 = i2[2 * p2 + 1];
                Bh(f2, d2, t4, e2) <= l2 && o2.push(n2[p2]), (0 === u2 ? t4 - r2 <= f2 : e2 - r2 <= d2) && (a2.push(h2), a2.push(p2 - 1), a2.push(1 - u2)), (0 === u2 ? t4 + r2 >= f2 : e2 + r2 >= d2) && (a2.push(p2 + 1), a2.push(c2), a2.push(1 - u2));
              }
              return o2;
            }
          }
          function Ih(t4, e2, r2, n2, i2, s2) {
            if (i2 - n2 <= r2) return;
            const a2 = n2 + i2 >> 1;
            zh(t4, e2, a2, n2, i2, s2), Ih(t4, e2, r2, n2, a2 - 1, 1 - s2), Ih(t4, e2, r2, a2 + 1, i2, 1 - s2);
          }
          function zh(t4, e2, r2, n2, i2, s2) {
            for (; i2 > n2; ) {
              if (i2 - n2 > 600) {
                const a3 = i2 - n2 + 1, o3 = r2 - n2 + 1, l3 = Math.log(a3), u2 = 0.5 * Math.exp(2 * l3 / 3), c2 = 0.5 * Math.sqrt(l3 * u2 * (a3 - u2) / a3) * (o3 - a3 / 2 < 0 ? -1 : 1);
                zh(t4, e2, r2, Math.max(n2, Math.floor(r2 - o3 * u2 / a3 + c2)), Math.min(i2, Math.floor(r2 + (a3 - o3) * u2 / a3 + c2)), s2);
              }
              const a2 = e2[2 * r2 + s2];
              let o2 = n2, l2 = i2;
              for (Ph(t4, e2, n2, r2), e2[2 * i2 + s2] > a2 && Ph(t4, e2, n2, i2); o2 < l2; ) {
                for (Ph(t4, e2, o2, l2), o2++, l2--; e2[2 * o2 + s2] < a2; ) o2++;
                for (; e2[2 * l2 + s2] > a2; ) l2--;
              }
              e2[2 * n2 + s2] === a2 ? Ph(t4, e2, n2, l2) : (l2++, Ph(t4, e2, l2, i2)), l2 <= r2 && (n2 = l2 + 1), r2 <= l2 && (i2 = l2 - 1);
            }
          }
          function Ph(t4, e2, r2, n2) {
            Ch(t4, r2, n2), Ch(e2, 2 * r2, 2 * n2), Ch(e2, 2 * r2 + 1, 2 * n2 + 1);
          }
          function Ch(t4, e2, r2) {
            const n2 = t4[e2];
            t4[e2] = t4[r2], t4[r2] = n2;
          }
          function Bh(t4, e2, r2, n2) {
            const i2 = t4 - r2, s2 = e2 - n2;
            return i2 * i2 + s2 * s2;
          }
          var Vh;
          t.bg = void 0, (Vh = t.bg || (t.bg = {})).create = "create", Vh.load = "load", Vh.fullLoad = "fullLoad";
          let Eh = null, Fh = [];
          const Th = 1e3 / 60, $h = "loadTime", Lh = "fullLoadTime", Dh = { mark(t4) {
            performance.mark(t4);
          }, frame(t4) {
            const e2 = t4;
            null != Eh && Fh.push(e2 - Eh), Eh = e2;
          }, clearMetrics() {
            Eh = null, Fh = [], performance.clearMeasures($h), performance.clearMeasures(Lh);
            for (const e2 in t.bg) performance.clearMarks(t.bg[e2]);
          }, getPerformanceMetrics() {
            performance.measure($h, t.bg.create, t.bg.load), performance.measure(Lh, t.bg.create, t.bg.fullLoad);
            const e2 = performance.getEntriesByName($h)[0].duration, r2 = performance.getEntriesByName(Lh)[0].duration, n2 = Fh.length, i2 = 1 / (Fh.reduce((t4, e3) => t4 + e3, 0) / n2 / 1e3), s2 = Fh.filter((t4) => t4 > Th).reduce((t4, e3) => t4 + (e3 - Th) / Th, 0);
            return { loadTime: e2, fullLoadTime: r2, fps: i2, percentDroppedFrames: s2 / (n2 + s2) * 100, totalFrames: n2 };
          } };
          t.$ = class extends ps {
          }, t.A = oo, t.B = yi, t.C = function(t4) {
            if (null == M) {
              const e2 = t4.navigator ? t4.navigator.userAgent : null;
              M = !!t4.safari || !(!e2 || !(/\b(iPad|iPhone|iPod)\b/.test(e2) || e2.match("Safari") && !e2.match("Chrome")));
            }
            return M;
          }, t.D = Ji, t.E = Z, t.F = class {
            constructor(t4, e2) {
              this.target = t4, this.mapId = e2, this.resolveRejects = {}, this.tasks = {}, this.taskQueue = [], this.abortControllers = {}, this.messageHandlers = {}, this.invoker = new Ic(() => this.process()), this.subscription = function(t5, e3, r2, n2) {
                return t5.addEventListener(e3, r2, false), { unsubscribe: () => {
                  t5.removeEventListener(e3, r2, false);
                } };
              }(this.target, "message", (t5) => this.receive(t5)), this.globalScope = k(self) ? t4 : window;
            }
            registerMessageHandler(t4, e2) {
              this.messageHandlers[t4] = e2;
            }
            sendAsync(t4, e2) {
              return new Promise((r2, n2) => {
                const i2 = Math.round(1e18 * Math.random()).toString(36).substring(0, 10);
                this.resolveRejects[i2] = { resolve: r2, reject: n2 }, e2 && e2.signal.addEventListener("abort", () => {
                  delete this.resolveRejects[i2];
                  const e3 = { id: i2, type: "<cancel>", origin: location.origin, targetMapId: t4.targetMapId, sourceMapId: this.mapId };
                  this.target.postMessage(e3);
                }, { once: true });
                const s2 = [], a2 = Object.assign(Object.assign({}, t4), { id: i2, sourceMapId: this.mapId, origin: location.origin, data: ki(t4.data, s2) });
                this.target.postMessage(a2, { transfer: s2 });
              });
            }
            receive(t4) {
              const e2 = t4.data, r2 = e2.id;
              if (!("file://" !== e2.origin && "file://" !== location.origin && "resource://android" !== e2.origin && "resource://android" !== location.origin && e2.origin !== location.origin || e2.targetMapId && this.mapId !== e2.targetMapId)) {
                if ("<cancel>" === e2.type) {
                  delete this.tasks[r2];
                  const t5 = this.abortControllers[r2];
                  return delete this.abortControllers[r2], void (t5 && t5.abort());
                }
                if (k(self) || e2.mustQueue) return this.tasks[r2] = e2, this.taskQueue.push(r2), void this.invoker.trigger();
                this.processTask(r2, e2);
              }
            }
            process() {
              if (0 === this.taskQueue.length) return;
              const t4 = this.taskQueue.shift(), e2 = this.tasks[t4];
              delete this.tasks[t4], this.taskQueue.length > 0 && this.invoker.trigger(), e2 && this.processTask(t4, e2);
            }
            processTask(t4, r2) {
              return e(this, void 0, void 0, function* () {
                if ("<response>" === r2.type) {
                  const e3 = this.resolveRejects[t4];
                  if (delete this.resolveRejects[t4], !e3) return;
                  return void (r2.error ? e3.reject(Mi(r2.error)) : e3.resolve(Mi(r2.data)));
                }
                if (!this.messageHandlers[r2.type]) return void this.completeTask(t4, new Error(`Could not find a registered handler for ${r2.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));
                const e2 = Mi(r2.data), n2 = new AbortController();
                this.abortControllers[t4] = n2;
                try {
                  const i2 = yield this.messageHandlers[r2.type](r2.sourceMapId, e2, n2);
                  this.completeTask(t4, null, i2);
                } catch (e3) {
                  this.completeTask(t4, e3);
                }
              });
            }
            completeTask(t4, e2, r2) {
              const n2 = [];
              delete this.abortControllers[t4];
              const i2 = { id: t4, type: "<response>", sourceMapId: this.mapId, origin: location.origin, error: e2 ? ki(e2) : null, data: ki(r2, n2) };
              this.target.postMessage(i2, { transfer: n2 });
            }
            remove() {
              this.invoker.remove(), this.subscription.unsubscribe();
            }
          }, t.G = $, t.H = function() {
            var t4 = new oo(16);
            return oo != Float32Array && (t4[1] = 0, t4[2] = 0, t4[3] = 0, t4[4] = 0, t4[6] = 0, t4[7] = 0, t4[8] = 0, t4[9] = 0, t4[11] = 0, t4[12] = 0, t4[13] = 0, t4[14] = 0), t4[0] = 1, t4[5] = 1, t4[10] = 1, t4[15] = 1, t4;
          }, t.I = Tu, t.J = function(t4, e2, r2) {
            var n2, i2, s2, a2, o2, l2, u2, c2, h2, p2, f2, d2, y2 = r2[0], m2 = r2[1], g2 = r2[2];
            return e2 === t4 ? (t4[12] = e2[0] * y2 + e2[4] * m2 + e2[8] * g2 + e2[12], t4[13] = e2[1] * y2 + e2[5] * m2 + e2[9] * g2 + e2[13], t4[14] = e2[2] * y2 + e2[6] * m2 + e2[10] * g2 + e2[14], t4[15] = e2[3] * y2 + e2[7] * m2 + e2[11] * g2 + e2[15]) : (i2 = e2[1], s2 = e2[2], a2 = e2[3], o2 = e2[4], l2 = e2[5], u2 = e2[6], c2 = e2[7], h2 = e2[8], p2 = e2[9], f2 = e2[10], d2 = e2[11], t4[0] = n2 = e2[0], t4[1] = i2, t4[2] = s2, t4[3] = a2, t4[4] = o2, t4[5] = l2, t4[6] = u2, t4[7] = c2, t4[8] = h2, t4[9] = p2, t4[10] = f2, t4[11] = d2, t4[12] = n2 * y2 + o2 * m2 + h2 * g2 + e2[12], t4[13] = i2 * y2 + l2 * m2 + p2 * g2 + e2[13], t4[14] = s2 * y2 + u2 * m2 + f2 * g2 + e2[14], t4[15] = a2 * y2 + c2 * m2 + d2 * g2 + e2[15]), t4;
          }, t.K = function(t4, e2, r2) {
            var n2 = r2[0], i2 = r2[1], s2 = r2[2];
            return t4[0] = e2[0] * n2, t4[1] = e2[1] * n2, t4[2] = e2[2] * n2, t4[3] = e2[3] * n2, t4[4] = e2[4] * i2, t4[5] = e2[5] * i2, t4[6] = e2[6] * i2, t4[7] = e2[7] * i2, t4[8] = e2[8] * s2, t4[9] = e2[9] * s2, t4[10] = e2[10] * s2, t4[11] = e2[11] * s2, t4[12] = e2[12], t4[13] = e2[13], t4[14] = e2[14], t4[15] = e2[15], t4;
          }, t.L = uo, t.M = function(t4, e2) {
            const r2 = {};
            for (let n2 = 0; n2 < e2.length; n2++) {
              const i2 = e2[n2];
              i2 in t4 && (r2[i2] = t4[i2]);
            }
            return r2;
          }, t.N = Pc, t.O = Vc, t.P = s, t.Q = Ec, t.R = Ao, t.S = jc, t.T = Zi, t.U = h, t.V = p, t.W = P, t.X = $a, t.Y = ls, t.Z = $c, t._ = e, t.a = F, t.a$ = function(t4, e2) {
            var r2 = t4[0], n2 = t4[1], i2 = t4[2], s2 = t4[3], a2 = t4[4], o2 = t4[5], l2 = t4[6], u2 = t4[7], c2 = t4[8], h2 = t4[9], p2 = t4[10], f2 = t4[11], d2 = t4[12], y2 = t4[13], m2 = t4[14], g2 = t4[15], x2 = e2[0], v2 = e2[1], b2 = e2[2], w2 = e2[3], _2 = e2[4], A3 = e2[5], S2 = e2[6], k2 = e2[7], M2 = e2[8], I2 = e2[9], z2 = e2[10], P2 = e2[11], C3 = e2[12], B3 = e2[13], V2 = e2[14], E3 = e2[15];
            return Math.abs(r2 - x2) <= ao * Math.max(1, Math.abs(r2), Math.abs(x2)) && Math.abs(n2 - v2) <= ao * Math.max(1, Math.abs(n2), Math.abs(v2)) && Math.abs(i2 - b2) <= ao * Math.max(1, Math.abs(i2), Math.abs(b2)) && Math.abs(s2 - w2) <= ao * Math.max(1, Math.abs(s2), Math.abs(w2)) && Math.abs(a2 - _2) <= ao * Math.max(1, Math.abs(a2), Math.abs(_2)) && Math.abs(o2 - A3) <= ao * Math.max(1, Math.abs(o2), Math.abs(A3)) && Math.abs(l2 - S2) <= ao * Math.max(1, Math.abs(l2), Math.abs(S2)) && Math.abs(u2 - k2) <= ao * Math.max(1, Math.abs(u2), Math.abs(k2)) && Math.abs(c2 - M2) <= ao * Math.max(1, Math.abs(c2), Math.abs(M2)) && Math.abs(h2 - I2) <= ao * Math.max(1, Math.abs(h2), Math.abs(I2)) && Math.abs(p2 - z2) <= ao * Math.max(1, Math.abs(p2), Math.abs(z2)) && Math.abs(f2 - P2) <= ao * Math.max(1, Math.abs(f2), Math.abs(P2)) && Math.abs(d2 - C3) <= ao * Math.max(1, Math.abs(d2), Math.abs(C3)) && Math.abs(y2 - B3) <= ao * Math.max(1, Math.abs(y2), Math.abs(B3)) && Math.abs(m2 - V2) <= ao * Math.max(1, Math.abs(m2), Math.abs(V2)) && Math.abs(g2 - E3) <= ao * Math.max(1, Math.abs(g2), Math.abs(E3));
          }, t.a0 = oa, t.a1 = Dc, t.a2 = it, t.a3 = (t4) => {
            const e2 = window.document.createElement("video");
            return e2.muted = true, new Promise((r2) => {
              e2.onloadstart = () => {
                r2(e2);
              };
              for (const r3 of t4) {
                const t5 = window.document.createElement("source");
                j(r3) || (e2.crossOrigin = "Anonymous"), t5.src = r3, e2.appendChild(t5);
              }
            });
          }, t.a4 = function() {
            return x++;
          }, t.a5 = Fs, t.a6 = dc, t.a7 = zn, t.a8 = ja, t.a9 = Nc, t.aA = function(t4) {
            if ("custom" === t4.type) return new Mc(t4);
            switch (t4.type) {
              case "background":
                return new _c(t4);
              case "circle":
                return new fo(t4);
              case "fill":
                return new ul(t4);
              case "fill-extrusion":
                return new El(t4);
              case "heatmap":
                return new Mo(t4);
              case "hillshade":
                return new Po(t4);
              case "line":
                return new Hl(t4);
              case "raster":
                return new kc(t4);
              case "symbol":
                return new vc(t4);
            }
          }, t.aB = w, t.aC = function(t4, e2) {
            if (!t4) return [{ command: "setStyle", args: [e2] }];
            let r2 = [];
            try {
              if (!H(t4.version, e2.version)) return [{ command: "setStyle", args: [e2] }];
              H(t4.center, e2.center) || r2.push({ command: "setCenter", args: [e2.center] }), H(t4.zoom, e2.zoom) || r2.push({ command: "setZoom", args: [e2.zoom] }), H(t4.bearing, e2.bearing) || r2.push({ command: "setBearing", args: [e2.bearing] }), H(t4.pitch, e2.pitch) || r2.push({ command: "setPitch", args: [e2.pitch] }), H(t4.sprite, e2.sprite) || r2.push({ command: "setSprite", args: [e2.sprite] }), H(t4.glyphs, e2.glyphs) || r2.push({ command: "setGlyphs", args: [e2.glyphs] }), H(t4.transition, e2.transition) || r2.push({ command: "setTransition", args: [e2.transition] }), H(t4.light, e2.light) || r2.push({ command: "setLight", args: [e2.light] }), H(t4.terrain, e2.terrain) || r2.push({ command: "setTerrain", args: [e2.terrain] }), H(t4.sky, e2.sky) || r2.push({ command: "setSky", args: [e2.sky] }), H(t4.projection, e2.projection) || r2.push({ command: "setProjection", args: [e2.projection] });
              const n2 = {}, i2 = [];
              !function(t5, e3, r3, n3) {
                let i3;
                for (i3 in e3 = e3 || {}, t5 = t5 || {}) Object.prototype.hasOwnProperty.call(t5, i3) && (Object.prototype.hasOwnProperty.call(e3, i3) || W(i3, r3, n3));
                for (i3 in e3) Object.prototype.hasOwnProperty.call(e3, i3) && (Object.prototype.hasOwnProperty.call(t5, i3) ? H(t5[i3], e3[i3]) || ("geojson" === t5[i3].type && "geojson" === e3[i3].type && tt(t5, e3, i3) ? Y(r3, { command: "setGeoJSONSourceData", args: [i3, e3[i3].data] }) : Q(i3, e3, r3, n3)) : J(i3, e3, r3));
              }(t4.sources, e2.sources, i2, n2);
              const s2 = [];
              t4.layers && t4.layers.forEach((t5) => {
                "source" in t5 && n2[t5.source] ? r2.push({ command: "removeLayer", args: [t5.id] }) : s2.push(t5);
              }), r2 = r2.concat(i2), function(t5, e3, r3) {
                e3 = e3 || [];
                const n3 = (t5 = t5 || []).map(rt), i3 = e3.map(rt), s3 = t5.reduce(nt, {}), a2 = e3.reduce(nt, {}), o2 = n3.slice(), l2 = /* @__PURE__ */ Object.create(null);
                let u2, c2, h2, p2, f2;
                for (let t6 = 0, e4 = 0; t6 < n3.length; t6++) u2 = n3[t6], Object.prototype.hasOwnProperty.call(a2, u2) ? e4++ : (Y(r3, { command: "removeLayer", args: [u2] }), o2.splice(o2.indexOf(u2, e4), 1));
                for (let t6 = 0, e4 = 0; t6 < i3.length; t6++) u2 = i3[i3.length - 1 - t6], o2[o2.length - 1 - t6] !== u2 && (Object.prototype.hasOwnProperty.call(s3, u2) ? (Y(r3, { command: "removeLayer", args: [u2] }), o2.splice(o2.lastIndexOf(u2, o2.length - e4), 1)) : e4++, p2 = o2[o2.length - t6], Y(r3, { command: "addLayer", args: [a2[u2], p2] }), o2.splice(o2.length - t6, 0, u2), l2[u2] = true);
                for (let t6 = 0; t6 < i3.length; t6++) if (u2 = i3[t6], c2 = s3[u2], h2 = a2[u2], !l2[u2] && !H(c2, h2)) if (H(c2.source, h2.source) && H(c2["source-layer"], h2["source-layer"]) && H(c2.type, h2.type)) {
                  for (f2 in et(c2.layout, h2.layout, r3, u2, null, "setLayoutProperty"), et(c2.paint, h2.paint, r3, u2, null, "setPaintProperty"), H(c2.filter, h2.filter) || Y(r3, { command: "setFilter", args: [u2, h2.filter] }), H(c2.minzoom, h2.minzoom) && H(c2.maxzoom, h2.maxzoom) || Y(r3, { command: "setLayerZoomRange", args: [u2, h2.minzoom, h2.maxzoom] }), c2) Object.prototype.hasOwnProperty.call(c2, f2) && "layout" !== f2 && "paint" !== f2 && "filter" !== f2 && "metadata" !== f2 && "minzoom" !== f2 && "maxzoom" !== f2 && (0 === f2.indexOf("paint.") ? et(c2[f2], h2[f2], r3, u2, f2.slice(6), "setPaintProperty") : H(c2[f2], h2[f2]) || Y(r3, { command: "setLayerProperty", args: [u2, f2, h2[f2]] }));
                  for (f2 in h2) Object.prototype.hasOwnProperty.call(h2, f2) && !Object.prototype.hasOwnProperty.call(c2, f2) && "layout" !== f2 && "paint" !== f2 && "filter" !== f2 && "metadata" !== f2 && "minzoom" !== f2 && "maxzoom" !== f2 && (0 === f2.indexOf("paint.") ? et(c2[f2], h2[f2], r3, u2, f2.slice(6), "setPaintProperty") : H(c2[f2], h2[f2]) || Y(r3, { command: "setLayerProperty", args: [u2, f2, h2[f2]] }));
                } else Y(r3, { command: "removeLayer", args: [u2] }), p2 = o2[o2.lastIndexOf(u2) + 1], Y(r3, { command: "addLayer", args: [h2, p2] });
              }(s2, e2.layers, r2);
            } catch (t5) {
              console.warn("Unable to compute style diff:", t5), r2 = [{ command: "setStyle", args: [e2] }];
            }
            return r2;
          }, t.aD = function(t4) {
            const e2 = [], r2 = t4.id;
            return void 0 === r2 && e2.push({ message: `layers.${r2}: missing required property "id"` }), void 0 === t4.render && e2.push({ message: `layers.${r2}: missing required method "render"` }), t4.renderingMode && "2d" !== t4.renderingMode && "3d" !== t4.renderingMode && e2.push({ message: `layers.${r2}: property "renderingMode" must be either "2d" or "3d"` }), e2;
          }, t.aE = function t4(e2, r2) {
            if (Array.isArray(e2)) {
              if (!Array.isArray(r2) || e2.length !== r2.length) return false;
              for (let n2 = 0; n2 < e2.length; n2++) if (!t4(e2[n2], r2[n2])) return false;
              return true;
            }
            if ("object" == typeof e2 && null !== e2 && null !== r2) {
              if ("object" != typeof r2) return false;
              if (Object.keys(e2).length !== Object.keys(r2).length) return false;
              for (const n2 in e2) if (!t4(e2[n2], r2[n2])) return false;
              return true;
            }
            return e2 === r2;
          }, t.aF = v, t.aG = b, t.aH = class extends wa {
            constructor(t4, e2) {
              super(t4, e2), this.current = 0;
            }
            set(t4) {
              this.current !== t4 && (this.current = t4, this.gl.uniform1i(this.location, t4));
            }
          }, t.aI = _a, t.aJ = class extends wa {
            constructor(t4, e2) {
              super(t4, e2), this.current = ka;
            }
            set(t4) {
              if (t4[12] !== this.current[12] || t4[0] !== this.current[0]) return this.current = t4, void this.gl.uniformMatrix4fv(this.location, false, t4);
              for (let e2 = 1; e2 < 16; e2++) if (t4[e2] !== this.current[e2]) {
                this.current = t4, this.gl.uniformMatrix4fv(this.location, false, t4);
                break;
              }
            }
          }, t.aK = Aa, t.aL = Sa, t.aM = Kt, t.aN = class extends wa {
            constructor(t4, e2) {
              super(t4, e2), this.current = [0, 0, 0];
            }
            set(t4) {
              t4[0] === this.current[0] && t4[1] === this.current[1] && t4[2] === this.current[2] || (this.current = t4, this.gl.uniform3f(this.location, t4[0], t4[1], t4[2]));
            }
          }, t.aO = class extends wa {
            constructor(t4, e2) {
              super(t4, e2), this.current = [0, 0];
            }
            set(t4) {
              t4[0] === this.current[0] && t4[1] === this.current[1] || (this.current = t4, this.gl.uniform2f(this.location, t4[0], t4[1]));
            }
          }, t.aP = function(t4, e2, r2, n2, i2, s2, a2) {
            var o2 = 1 / (e2 - r2), l2 = 1 / (n2 - i2), u2 = 1 / (s2 - a2);
            return t4[0] = -2 * o2, t4[1] = 0, t4[2] = 0, t4[3] = 0, t4[4] = 0, t4[5] = -2 * l2, t4[6] = 0, t4[7] = 0, t4[8] = 0, t4[9] = 0, t4[10] = 2 * u2, t4[11] = 0, t4[12] = (e2 + r2) * o2, t4[13] = (i2 + n2) * l2, t4[14] = (a2 + s2) * u2, t4[15] = 1, t4;
          }, t.aQ = ho, t.aR = class extends _s {
          }, t.aS = eu, t.aT = class extends Ss {
          }, t.aU = ko, t.aV = function(t4) {
            return t4 <= 1 ? 1 : Math.pow(2, Math.ceil(Math.log(t4) / Math.LN2));
          }, t.aW = So, t.aX = Zs, t.aY = na, t.aZ = class extends Bs {
          }, t.a_ = function(t4, e2) {
            return t4[0] === e2[0] && t4[1] === e2[1] && t4[2] === e2[2] && t4[3] === e2[3] && t4[4] === e2[4] && t4[5] === e2[5] && t4[6] === e2[6] && t4[7] === e2[7] && t4[8] === e2[8] && t4[9] === e2[9] && t4[10] === e2[10] && t4[11] === e2[11] && t4[12] === e2[12] && t4[13] === e2[13] && t4[14] === e2[14] && t4[15] === e2[15];
          }, t.aa = function(t4) {
            const e2 = {};
            if (t4.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g, (t5, r2, n2, i2) => {
              const s2 = n2 || i2;
              return e2[r2] = !s2 || s2.toLowerCase(), "";
            }), e2["max-age"]) {
              const t5 = parseInt(e2["max-age"], 10);
              isNaN(t5) ? delete e2["max-age"] : e2["max-age"] = t5;
            }
            return e2;
          }, t.ab = function(t4, e2) {
            const r2 = [];
            for (const n2 in t4) n2 in e2 || r2.push(n2);
            return r2;
          }, t.ac = y, t.ad = function(t4, e2, r2) {
            var n2 = Math.sin(r2), i2 = Math.cos(r2), s2 = e2[0], a2 = e2[1], o2 = e2[2], l2 = e2[3], u2 = e2[4], c2 = e2[5], h2 = e2[6], p2 = e2[7];
            return e2 !== t4 && (t4[8] = e2[8], t4[9] = e2[9], t4[10] = e2[10], t4[11] = e2[11], t4[12] = e2[12], t4[13] = e2[13], t4[14] = e2[14], t4[15] = e2[15]), t4[0] = s2 * i2 + u2 * n2, t4[1] = a2 * i2 + c2 * n2, t4[2] = o2 * i2 + h2 * n2, t4[3] = l2 * i2 + p2 * n2, t4[4] = u2 * i2 - s2 * n2, t4[5] = c2 * i2 - a2 * n2, t4[6] = h2 * i2 - o2 * n2, t4[7] = p2 * i2 - l2 * n2, t4;
          }, t.ae = function(t4) {
            var e2 = new oo(16);
            return e2[0] = t4[0], e2[1] = t4[1], e2[2] = t4[2], e2[3] = t4[3], e2[4] = t4[4], e2[5] = t4[5], e2[6] = t4[6], e2[7] = t4[7], e2[8] = t4[8], e2[9] = t4[9], e2[10] = t4[10], e2[11] = t4[11], e2[12] = t4[12], e2[13] = t4[13], e2[14] = t4[14], e2[15] = t4[15], e2;
          }, t.af = po, t.ag = function(t4, e2) {
            let r2 = 0, n2 = 0;
            if ("constant" === t4.kind) n2 = t4.layoutSize;
            else if ("source" !== t4.kind) {
              const { interpolationType: i2, minZoom: s2, maxZoom: a2 } = t4, o2 = i2 ? y(Be.interpolationFactor(i2, e2, s2, a2), 0, 1) : 0;
              "camera" === t4.kind ? n2 = Ce.number(t4.minSize, t4.maxSize, o2) : r2 = o2;
            }
            return { uSizeT: r2, uSize: n2 };
          }, t.ai = function(t4, { uSize: e2, uSizeT: r2 }, { lowerSize: n2, upperSize: i2 }) {
            return "source" === t4.kind ? n2 / nc : "composite" === t4.kind ? Ce.number(n2 / nc, i2 / nc, r2) : e2;
          }, t.aj = cc, t.ak = function(t4, e2, r2, n2) {
            const i2 = e2.y - t4.y, a2 = e2.x - t4.x, o2 = n2.y - r2.y, l2 = n2.x - r2.x, u2 = o2 * a2 - l2 * i2;
            if (0 === u2) return null;
            const c2 = (l2 * (t4.y - r2.y) - o2 * (t4.x - r2.x)) / u2;
            return new s(t4.x + c2 * a2, t4.y + c2 * i2);
          }, t.al = Hc, t.am = qa, t.an = lo, t.ao = function(t4) {
            let e2 = 1 / 0, r2 = 1 / 0, n2 = -1 / 0, i2 = -1 / 0;
            for (const s2 of t4) e2 = Math.min(e2, s2.x), r2 = Math.min(r2, s2.y), n2 = Math.max(n2, s2.x), i2 = Math.max(i2, s2.y);
            return [e2, r2, n2, i2];
          }, t.ap = iu, t.ar = ac, t.as = function(t4, e2) {
            var r2 = e2[0], n2 = e2[1], i2 = e2[2], s2 = e2[3], a2 = e2[4], o2 = e2[5], l2 = e2[6], u2 = e2[7], c2 = e2[8], h2 = e2[9], p2 = e2[10], f2 = e2[11], d2 = e2[12], y2 = e2[13], m2 = e2[14], g2 = e2[15], x2 = r2 * o2 - n2 * a2, v2 = r2 * l2 - i2 * a2, b2 = r2 * u2 - s2 * a2, w2 = n2 * l2 - i2 * o2, _2 = n2 * u2 - s2 * o2, A3 = i2 * u2 - s2 * l2, S2 = c2 * y2 - h2 * d2, k2 = c2 * m2 - p2 * d2, M2 = c2 * g2 - f2 * d2, I2 = h2 * m2 - p2 * y2, z2 = h2 * g2 - f2 * y2, P2 = p2 * g2 - f2 * m2, C3 = x2 * P2 - v2 * z2 + b2 * I2 + w2 * M2 - _2 * k2 + A3 * S2;
            return C3 ? (t4[0] = (o2 * P2 - l2 * z2 + u2 * I2) * (C3 = 1 / C3), t4[1] = (i2 * z2 - n2 * P2 - s2 * I2) * C3, t4[2] = (y2 * A3 - m2 * _2 + g2 * w2) * C3, t4[3] = (p2 * _2 - h2 * A3 - f2 * w2) * C3, t4[4] = (l2 * M2 - a2 * P2 - u2 * k2) * C3, t4[5] = (r2 * P2 - i2 * M2 + s2 * k2) * C3, t4[6] = (m2 * b2 - d2 * A3 - g2 * v2) * C3, t4[7] = (c2 * A3 - p2 * b2 + f2 * v2) * C3, t4[8] = (a2 * z2 - o2 * M2 + u2 * S2) * C3, t4[9] = (n2 * M2 - r2 * z2 - s2 * S2) * C3, t4[10] = (d2 * _2 - y2 * b2 + g2 * x2) * C3, t4[11] = (h2 * b2 - c2 * _2 - f2 * x2) * C3, t4[12] = (o2 * k2 - a2 * I2 - l2 * S2) * C3, t4[13] = (r2 * I2 - n2 * k2 + i2 * S2) * C3, t4[14] = (y2 * v2 - d2 * w2 - m2 * x2) * C3, t4[15] = (c2 * w2 - h2 * v2 + p2 * x2) * C3, t4) : null;
          }, t.at = bh, t.au = Ju, t.av = Mh, t.aw = function() {
            const t4 = {}, e2 = G.$version;
            for (const r2 in G.$root) {
              const n2 = G.$root[r2];
              if (n2.required) {
                let i2 = null;
                i2 = "version" === r2 ? e2 : "array" === n2.type ? [] : {}, null != i2 && (t4[r2] = i2);
              }
            }
            return t4;
          }, t.ax = Ii, t.ay = D2, t.az = function(t4) {
            t4 = t4.slice();
            const e2 = /* @__PURE__ */ Object.create(null);
            for (let r2 = 0; r2 < t4.length; r2++) e2[t4[r2].id] = t4[r2];
            for (let r2 = 0; r2 < t4.length; r2++) "ref" in t4[r2] && (t4[r2] = X(t4[r2], e2[t4[r2].ref]));
            return t4;
          }, t.b = I, t.b0 = function(t4, e2) {
            return t4[0] = e2[0], t4[1] = e2[1], t4[2] = e2[2], t4[3] = e2[3], t4[4] = e2[4], t4[5] = e2[5], t4[6] = e2[6], t4[7] = e2[7], t4[8] = e2[8], t4[9] = e2[9], t4[10] = e2[10], t4[11] = e2[11], t4[12] = e2[12], t4[13] = e2[13], t4[14] = e2[14], t4[15] = e2[15], t4;
          }, t.b1 = function(t4, e2, r2) {
            return t4[0] = e2[0] * r2[0], t4[1] = e2[1] * r2[1], t4[2] = e2[2] * r2[2], t4[3] = e2[3] * r2[3], t4;
          }, t.b2 = function(t4, e2) {
            return t4[0] * e2[0] + t4[1] * e2[1] + t4[2] * e2[2] + t4[3] * e2[3];
          }, t.b3 = m, t.b4 = Oc, t.b5 = Fc, t.b6 = function(t4, e2, r2, n2, i2) {
            var s2, a2 = 1 / Math.tan(e2 / 2);
            return t4[0] = a2 / r2, t4[1] = 0, t4[2] = 0, t4[3] = 0, t4[4] = 0, t4[5] = a2, t4[6] = 0, t4[7] = 0, t4[8] = 0, t4[9] = 0, t4[11] = -1, t4[12] = 0, t4[13] = 0, t4[15] = 0, null != i2 && i2 !== 1 / 0 ? (t4[10] = (i2 + n2) * (s2 = 1 / (n2 - i2)), t4[14] = 2 * i2 * n2 * s2) : (t4[10] = -1, t4[14] = -2 * n2), t4;
          }, t.b7 = function(t4, e2, r2) {
            var n2 = Math.sin(r2), i2 = Math.cos(r2), s2 = e2[4], a2 = e2[5], o2 = e2[6], l2 = e2[7], u2 = e2[8], c2 = e2[9], h2 = e2[10], p2 = e2[11];
            return e2 !== t4 && (t4[0] = e2[0], t4[1] = e2[1], t4[2] = e2[2], t4[3] = e2[3], t4[12] = e2[12], t4[13] = e2[13], t4[14] = e2[14], t4[15] = e2[15]), t4[4] = s2 * i2 + u2 * n2, t4[5] = a2 * i2 + c2 * n2, t4[6] = o2 * i2 + h2 * n2, t4[7] = l2 * i2 + p2 * n2, t4[8] = u2 * i2 - s2 * n2, t4[9] = c2 * i2 - a2 * n2, t4[10] = h2 * i2 - o2 * n2, t4[11] = p2 * i2 - l2 * n2, t4;
          }, t.b8 = f, t.b9 = d, t.bA = su, t.bB = function(t4) {
            return t4.message === V;
          }, t.bC = bn, t.bD = Ri, t.ba = function(t4) {
            return t4 * Math.PI / 180;
          }, t.bb = function(t4, e2) {
            const { x: r2, y: n2 } = $c.fromLngLat(e2);
            return !(t4 < 0 || t4 > 25 || n2 < 0 || n2 >= 1 || r2 < 0 || r2 >= 1);
          }, t.bc = function(t4, e2) {
            return t4[0] = e2[0], t4[1] = 0, t4[2] = 0, t4[3] = 0, t4[4] = 0, t4[5] = e2[1], t4[6] = 0, t4[7] = 0, t4[8] = 0, t4[9] = 0, t4[10] = e2[2], t4[11] = 0, t4[12] = 0, t4[13] = 0, t4[14] = 0, t4[15] = 1, t4;
          }, t.bd = class extends hs {
          }, t.be = zc, t.bf = Dh, t.bh = L, t.bi = function(t4, e2) {
            F.REGISTERED_PROTOCOLS[t4] = e2;
          }, t.bj = function(t4) {
            delete F.REGISTERED_PROTOCOLS[t4];
          }, t.bk = function(t4, e2) {
            const r2 = {};
            for (let n3 = 0; n3 < t4.length; n3++) {
              const i2 = e2 && e2[t4[n3].id] || Ln(t4[n3]);
              e2 && (e2[t4[n3].id] = i2);
              let s2 = r2[i2];
              s2 || (s2 = r2[i2] = []), s2.push(t4[n3]);
            }
            const n2 = [];
            for (const t5 in r2) n2.push(r2[t5]);
            return n2;
          }, t.bl = wi, t.bm = qc, t.bn = Zc, t.bo = $u, t.bp = function(e2) {
            e2.bucket.createArrays(), e2.bucket.tilePixelRatio = $a / (512 * e2.bucket.overscaling), e2.bucket.compareText = {}, e2.bucket.iconsNeedLinear = false;
            const r2 = e2.bucket.layers[0], n2 = r2.layout, i2 = r2._unevaluatedLayout._values, s2 = { layoutIconSize: i2["icon-size"].possiblyEvaluate(new Ui(e2.bucket.zoom + 1), e2.canonical), layoutTextSize: i2["text-size"].possiblyEvaluate(new Ui(e2.bucket.zoom + 1), e2.canonical), textMaxSize: i2["text-size"].possiblyEvaluate(new Ui(18)) };
            if ("composite" === e2.bucket.textSizeData.kind) {
              const { minZoom: t4, maxZoom: r3 } = e2.bucket.textSizeData;
              s2.compositeTextSizes = [i2["text-size"].possiblyEvaluate(new Ui(t4), e2.canonical), i2["text-size"].possiblyEvaluate(new Ui(r3), e2.canonical)];
            }
            if ("composite" === e2.bucket.iconSizeData.kind) {
              const { minZoom: t4, maxZoom: r3 } = e2.bucket.iconSizeData;
              s2.compositeIconSizes = [i2["icon-size"].possiblyEvaluate(new Ui(t4), e2.canonical), i2["icon-size"].possiblyEvaluate(new Ui(r3), e2.canonical)];
            }
            const a2 = n2.get("text-line-height") * iu, o2 = "viewport" !== n2.get("text-rotation-alignment") && "point" !== n2.get("symbol-placement"), l2 = n2.get("text-keep-upright"), u2 = n2.get("text-size");
            for (const i3 of e2.bucket.features) {
              const c2 = n2.get("text-font").evaluate(i3, {}, e2.canonical).join(","), h2 = u2.evaluate(i3, {}, e2.canonical), p2 = s2.layoutTextSize.evaluate(i3, {}, e2.canonical), f2 = s2.layoutIconSize.evaluate(i3, {}, e2.canonical), d2 = { horizontal: {}, vertical: void 0 }, y2 = i3.text;
              let m2, g2 = [0, 0];
              if (y2) {
                const s3 = y2.toString(), u3 = n2.get("text-letter-spacing").evaluate(i3, {}, e2.canonical) * iu, f3 = Ci(s3) ? u3 : 0, m3 = n2.get("text-anchor").evaluate(i3, {}, e2.canonical), x3 = vh(r2, i3, e2.canonical);
                if (!x3) {
                  const t4 = n2.get("text-radial-offset").evaluate(i3, {}, e2.canonical);
                  g2 = t4 ? xh(m3, [t4 * iu, gh]) : n2.get("text-offset").evaluate(i3, {}, e2.canonical).map((t5) => t5 * iu);
                }
                let v3 = o2 ? "center" : n2.get("text-justify").evaluate(i3, {}, e2.canonical);
                const b2 = "point" === n2.get("symbol-placement") ? n2.get("text-max-width").evaluate(i3, {}, e2.canonical) * iu : 1 / 0, w2 = () => {
                  e2.bucket.allowVerticalPlacement && Pi(s3) && (d2.vertical = Ru(y2, e2.glyphMap, e2.glyphPositions, e2.imagePositions, c2, b2, a2, m3, "left", f3, g2, t.ah.vertical, true, p2, h2));
                };
                if (!o2 && x3) {
                  const r3 = /* @__PURE__ */ new Set();
                  if ("auto" === v3) for (let t4 = 0; t4 < x3.values.length; t4 += 2) r3.add(bh(x3.values[t4]));
                  else r3.add(v3);
                  let n3 = false;
                  for (const i4 of r3) if (!d2.horizontal[i4]) if (n3) d2.horizontal[i4] = d2.horizontal[0];
                  else {
                    const r4 = Ru(y2, e2.glyphMap, e2.glyphPositions, e2.imagePositions, c2, b2, a2, "center", i4, f3, g2, t.ah.horizontal, false, p2, h2);
                    r4 && (d2.horizontal[i4] = r4, n3 = 1 === r4.positionedLines.length);
                  }
                  w2();
                } else {
                  "auto" === v3 && (v3 = bh(m3));
                  const r3 = Ru(y2, e2.glyphMap, e2.glyphPositions, e2.imagePositions, c2, b2, a2, m3, v3, f3, g2, t.ah.horizontal, false, p2, h2);
                  r3 && (d2.horizontal[v3] = r3), w2(), Pi(s3) && o2 && l2 && (d2.vertical = Ru(y2, e2.glyphMap, e2.glyphPositions, e2.imagePositions, c2, b2, a2, m3, v3, f3, g2, t.ah.vertical, false, p2, h2));
                }
              }
              let x2 = false;
              if (i3.icon && i3.icon.name) {
                const t4 = e2.imageMap[i3.icon.name];
                t4 && (m2 = Qu(e2.imagePositions[i3.icon.name], n2.get("icon-offset").evaluate(i3, {}, e2.canonical), n2.get("icon-anchor").evaluate(i3, {}, e2.canonical)), x2 = !!t4.sdf, void 0 === e2.bucket.sdfIcons ? e2.bucket.sdfIcons = x2 : e2.bucket.sdfIcons !== x2 && A2("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"), (t4.pixelRatio !== e2.bucket.pixelRatio || 0 !== n2.get("icon-rotate").constantOr(1)) && (e2.bucket.iconsNeedLinear = true));
              }
              const v2 = Ah(d2.horizontal) || d2.vertical;
              e2.bucket.iconsInText = !!v2 && v2.iconsInText, (v2 || m2) && wh(e2.bucket, i3, d2, m2, e2.imageMap, s2, p2, f2, g2, x2, e2.canonical);
            }
            e2.showCollisionBoxes && e2.bucket.generateCollisionDebugBuffers();
          }, t.bq = ql, t.br = sl, t.bs = zl, t.bt = fl, t.bu = Iu, t.bv = class {
            constructor(t4) {
              this._marks = { start: [t4.url, "start"].join("#"), end: [t4.url, "end"].join("#"), measure: t4.url.toString() }, performance.mark(this._marks.start);
            }
            finish() {
              performance.mark(this._marks.end);
              let t4 = performance.getEntriesByName(this._marks.measure);
              return 0 === t4.length && (performance.measure(this._marks.measure, this._marks.start, this._marks.end), t4 = performance.getEntriesByName(this._marks.measure), performance.clearMarks(this._marks.start), performance.clearMarks(this._marks.end), performance.clearMeasures(this._marks.measure)), t4;
            }
          }, t.bw = function(t4, r2, n2, i2, s2) {
            return e(this, void 0, void 0, function* () {
              if (p()) try {
                return yield P(t4, r2, n2, i2, s2);
              } catch (t5) {
              }
              return function(t5, e2, r3, n3, i3) {
                const s3 = t5.width, a2 = t5.height;
                C2 && B2 || (C2 = new OffscreenCanvas(s3, a2), B2 = C2.getContext("2d", { willReadFrequently: true })), C2.width = s3, C2.height = a2, B2.drawImage(t5, 0, 0, s3, a2);
                const o2 = B2.getImageData(e2, r3, n3, i3);
                return B2.clearRect(0, 0, s3, a2), o2.data;
              }(t4, r2, n2, i2, s2);
            });
          }, t.bx = Uc, t.by = r, t.bz = n, t.c = E2, t.d = (t4) => e(void 0, void 0, void 0, function* () {
            if (0 === t4.byteLength) return createImageBitmap(new ImageData(1, 1));
            const e2 = new Blob([new Uint8Array(t4)], { type: "image/png" });
            try {
              return createImageBitmap(e2);
            } catch (t5) {
              throw new Error(`Could not load image because of ${t5.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`);
            }
          }), t.e = g, t.f = (t4) => new Promise((e2, r2) => {
            const n2 = new Image();
            n2.onload = () => {
              e2(n2), URL.revokeObjectURL(n2.src), n2.onload = null, window.requestAnimationFrame(() => {
                n2.src = z;
              });
            }, n2.onerror = () => r2(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));
            const i2 = new Blob([new Uint8Array(t4)], { type: "image/png" });
            n2.src = t4.byteLength ? URL.createObjectURL(i2) : z;
          }), t.g = T, t.h = (t4, e2) => O(g(t4, { type: "json" }), e2), t.i = k, t.j = N, t.k = q, t.l = (t4, e2) => O(g(t4, { type: "arrayBuffer" }), e2), t.m = O, t.n = function(t4) {
            return new Iu(t4).readFields(Pu, []);
          }, t.o = _o, t.p = Eu, t.q = rs, t.r = di, t.s = j, t.t = xi, t.u = fi, t.v = G, t.w = A2, t.x = function([t4, e2, r2]) {
            return e2 += 90, e2 *= Math.PI / 180, r2 *= Math.PI / 180, { x: t4 * Math.cos(e2) * Math.sin(r2), y: t4 * Math.sin(e2) * Math.sin(r2), z: t4 * Math.cos(r2) };
          }, t.y = Ce, t.z = Ui;
        });
        define2("worker", ["./shared"], function(e) {
          "use strict";
          class t {
            constructor(e2) {
              this.keyCache = {}, e2 && this.replace(e2);
            }
            replace(e2) {
              this._layerConfigs = {}, this._layers = {}, this.update(e2, []);
            }
            update(t4, o2) {
              for (const o3 of t4) {
                this._layerConfigs[o3.id] = o3;
                const t5 = this._layers[o3.id] = e.aA(o3);
                t5._featureFilter = e.a7(t5.filter), this.keyCache[o3.id] && delete this.keyCache[o3.id];
              }
              for (const e2 of o2) delete this.keyCache[e2], delete this._layerConfigs[e2], delete this._layers[e2];
              this.familiesBySource = {};
              const i2 = e.bk(Object.values(this._layerConfigs), this.keyCache);
              for (const e2 of i2) {
                const t5 = e2.map((e3) => this._layers[e3.id]), o3 = t5[0];
                if ("none" === o3.visibility) continue;
                const i3 = o3.source || "";
                let s2 = this.familiesBySource[i3];
                s2 || (s2 = this.familiesBySource[i3] = {});
                const r2 = o3.sourceLayer || "_geojsonTileLayer";
                let n2 = s2[r2];
                n2 || (n2 = s2[r2] = []), n2.push(t5);
              }
            }
          }
          class o {
            constructor(t4) {
              const o2 = {}, i2 = [];
              for (const e2 in t4) {
                const s3 = t4[e2], r3 = o2[e2] = {};
                for (const e3 in s3) {
                  const t5 = s3[+e3];
                  if (!t5 || 0 === t5.bitmap.width || 0 === t5.bitmap.height) continue;
                  const o3 = { x: 0, y: 0, w: t5.bitmap.width + 2, h: t5.bitmap.height + 2 };
                  i2.push(o3), r3[e3] = { rect: o3, metrics: t5.metrics };
                }
              }
              const { w: s2, h: r2 } = e.p(i2), n2 = new e.o({ width: s2 || 1, height: r2 || 1 });
              for (const i3 in t4) {
                const s3 = t4[i3];
                for (const t5 in s3) {
                  const r3 = s3[+t5];
                  if (!r3 || 0 === r3.bitmap.width || 0 === r3.bitmap.height) continue;
                  const a2 = o2[i3][t5].rect;
                  e.o.copy(r3.bitmap, n2, { x: 0, y: 0 }, { x: a2.x + 1, y: a2.y + 1 }, r3.bitmap);
                }
              }
              this.image = n2, this.positions = o2;
            }
          }
          e.bl("GlyphAtlas", o);
          class i {
            constructor(t4) {
              this.tileID = new e.S(t4.tileID.overscaledZ, t4.tileID.wrap, t4.tileID.canonical.z, t4.tileID.canonical.x, t4.tileID.canonical.y), this.uid = t4.uid, this.zoom = t4.zoom, this.pixelRatio = t4.pixelRatio, this.tileSize = t4.tileSize, this.source = t4.source, this.overscaling = this.tileID.overscaleFactor(), this.showCollisionBoxes = t4.showCollisionBoxes, this.collectResourceTiming = !!t4.collectResourceTiming, this.returnDependencies = !!t4.returnDependencies, this.promoteId = t4.promoteId, this.inFlightDependencies = [];
            }
            parse(t4, i2, r2, n2) {
              return e._(this, void 0, void 0, function* () {
                this.status = "parsing", this.data = t4, this.collisionBoxArray = new e.a5();
                const a2 = new e.bm(Object.keys(t4.layers).sort()), l2 = new e.bn(this.tileID, this.promoteId);
                l2.bucketLayerIDs = [];
                const c2 = {}, u2 = { featureIndex: l2, iconDependencies: {}, patternDependencies: {}, glyphDependencies: {}, availableImages: r2 }, h2 = i2.familiesBySource[this.source];
                for (const o2 in h2) {
                  const i3 = t4.layers[o2];
                  if (!i3) continue;
                  1 === i3.version && e.w(`Vector tile source "${this.source}" layer "${o2}" does not use vector tile spec v2 and therefore may have some rendering errors.`);
                  const n3 = a2.encode(o2), d3 = [];
                  for (let e2 = 0; e2 < i3.length; e2++) {
                    const t5 = i3.feature(e2), s2 = l2.getId(t5, o2);
                    d3.push({ feature: t5, id: s2, index: e2, sourceLayerIndex: n3 });
                  }
                  for (const t5 of h2[o2]) {
                    const o3 = t5[0];
                    o3.source !== this.source && e.w(`layer.source = ${o3.source} does not equal this.source = ${this.source}`), o3.minzoom && this.zoom < Math.floor(o3.minzoom) || o3.maxzoom && this.zoom >= o3.maxzoom || "none" !== o3.visibility && (s(t5, this.zoom, r2), (c2[o3.id] = o3.createBucket({ index: l2.bucketLayerIDs.length, layers: t5, zoom: this.zoom, pixelRatio: this.pixelRatio, overscaling: this.overscaling, collisionBoxArray: this.collisionBoxArray, sourceLayerIndex: n3, sourceID: this.source })).populate(d3, u2, this.tileID.canonical), l2.bucketLayerIDs.push(t5.map((e2) => e2.id)));
                  }
                }
                const d2 = e.aF(u2.glyphDependencies, (e2) => Object.keys(e2).map(Number));
                this.inFlightDependencies.forEach((e2) => null == e2 ? void 0 : e2.abort()), this.inFlightDependencies = [];
                let f2 = Promise.resolve({});
                if (Object.keys(d2).length) {
                  const e2 = new AbortController();
                  this.inFlightDependencies.push(e2), f2 = n2.sendAsync({ type: "GG", data: { stacks: d2, source: this.source, tileID: this.tileID, type: "glyphs" } }, e2);
                }
                const g2 = Object.keys(u2.iconDependencies);
                let p2 = Promise.resolve({});
                if (g2.length) {
                  const e2 = new AbortController();
                  this.inFlightDependencies.push(e2), p2 = n2.sendAsync({ type: "GI", data: { icons: g2, source: this.source, tileID: this.tileID, type: "icons" } }, e2);
                }
                const m2 = Object.keys(u2.patternDependencies);
                let y2 = Promise.resolve({});
                if (m2.length) {
                  const e2 = new AbortController();
                  this.inFlightDependencies.push(e2), y2 = n2.sendAsync({ type: "GI", data: { icons: m2, source: this.source, tileID: this.tileID, type: "patterns" } }, e2);
                }
                const [v2, w2, x2] = yield Promise.all([f2, p2, y2]), b2 = new o(v2), S2 = new e.bo(w2, x2);
                for (const t5 in c2) {
                  const o2 = c2[t5];
                  o2 instanceof e.a6 ? (s(o2.layers, this.zoom, r2), e.bp({ bucket: o2, glyphMap: v2, glyphPositions: b2.positions, imageMap: w2, imagePositions: S2.iconPositions, showCollisionBoxes: this.showCollisionBoxes, canonical: this.tileID.canonical })) : o2.hasPattern && (o2 instanceof e.bq || o2 instanceof e.br || o2 instanceof e.bs) && (s(o2.layers, this.zoom, r2), o2.addFeatures(u2, this.tileID.canonical, S2.patternPositions));
                }
                return this.status = "done", { buckets: Object.values(c2).filter((e2) => !e2.isEmpty()), featureIndex: l2, collisionBoxArray: this.collisionBoxArray, glyphAtlasImage: b2.image, imageAtlas: S2, glyphMap: this.returnDependencies ? v2 : null, iconMap: this.returnDependencies ? w2 : null, glyphPositions: this.returnDependencies ? b2.positions : null };
              });
            }
          }
          function s(t4, o2, i2) {
            const s2 = new e.z(o2);
            for (const e2 of t4) e2.recalculate(s2, i2);
          }
          class r {
            constructor(e2, t4, o2) {
              this.actor = e2, this.layerIndex = t4, this.availableImages = o2, this.fetching = {}, this.loading = {}, this.loaded = {};
            }
            loadVectorTile(t4, o2) {
              return e._(this, void 0, void 0, function* () {
                const i2 = yield e.l(t4.request, o2);
                try {
                  return { vectorTile: new e.bt.VectorTile(new e.bu(i2.data)), rawData: i2.data, cacheControl: i2.cacheControl, expires: i2.expires };
                } catch (e2) {
                  const o3 = new Uint8Array(i2.data);
                  let s2 = `Unable to parse the tile at ${t4.request.url}, `;
                  throw s2 += 31 === o3[0] && 139 === o3[1] ? "please make sure the data is not gzipped and that you have configured the relevant header in the server" : `got error: ${e2.message}`, new Error(s2);
                }
              });
            }
            loadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const o2 = t4.uid, s2 = !!(t4 && t4.request && t4.request.collectResourceTiming) && new e.bv(t4.request), r2 = new i(t4);
                this.loading[o2] = r2;
                const n2 = new AbortController();
                r2.abort = n2;
                try {
                  const i2 = yield this.loadVectorTile(t4, n2);
                  if (delete this.loading[o2], !i2) return null;
                  const a2 = i2.rawData, l2 = {};
                  i2.expires && (l2.expires = i2.expires), i2.cacheControl && (l2.cacheControl = i2.cacheControl);
                  const c2 = {};
                  if (s2) {
                    const e2 = s2.finish();
                    e2 && (c2.resourceTiming = JSON.parse(JSON.stringify(e2)));
                  }
                  r2.vectorTile = i2.vectorTile;
                  const u2 = r2.parse(i2.vectorTile, this.layerIndex, this.availableImages, this.actor);
                  this.loaded[o2] = r2, this.fetching[o2] = { rawTileData: a2, cacheControl: l2, resourceTiming: c2 };
                  try {
                    const t5 = yield u2;
                    return e.e({ rawTileData: a2.slice(0) }, t5, l2, c2);
                  } finally {
                    delete this.fetching[o2];
                  }
                } catch (e2) {
                  throw delete this.loading[o2], r2.status = "done", this.loaded[o2] = r2, e2;
                }
              });
            }
            reloadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const o2 = t4.uid;
                if (!this.loaded || !this.loaded[o2]) throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");
                const i2 = this.loaded[o2];
                if (i2.showCollisionBoxes = t4.showCollisionBoxes, "parsing" === i2.status) {
                  const t5 = yield i2.parse(i2.vectorTile, this.layerIndex, this.availableImages, this.actor);
                  let s2;
                  if (this.fetching[o2]) {
                    const { rawTileData: i3, cacheControl: r2, resourceTiming: n2 } = this.fetching[o2];
                    delete this.fetching[o2], s2 = e.e({ rawTileData: i3.slice(0) }, t5, r2, n2);
                  } else s2 = t5;
                  return s2;
                }
                if ("done" === i2.status && i2.vectorTile) return i2.parse(i2.vectorTile, this.layerIndex, this.availableImages, this.actor);
              });
            }
            abortTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const e2 = this.loading, o2 = t4.uid;
                e2 && e2[o2] && e2[o2].abort && (e2[o2].abort.abort(), delete e2[o2]);
              });
            }
            removeTile(t4) {
              return e._(this, void 0, void 0, function* () {
                this.loaded && this.loaded[t4.uid] && delete this.loaded[t4.uid];
              });
            }
          }
          class n {
            constructor() {
              this.loaded = {};
            }
            loadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const { uid: o2, encoding: i2, rawImageData: s2, redFactor: r2, greenFactor: n2, blueFactor: a2, baseShift: l2 } = t4, c2 = s2.width + 2, u2 = s2.height + 2, h2 = e.b(s2) ? new e.R({ width: c2, height: u2 }, yield e.bw(s2, -1, -1, c2, u2)) : s2, d2 = new e.bx(o2, h2, i2, r2, n2, a2, l2);
                return this.loaded = this.loaded || {}, this.loaded[o2] = d2, d2;
              });
            }
            removeTile(e2) {
              const t4 = this.loaded, o2 = e2.uid;
              t4 && t4[o2] && delete t4[o2];
            }
          }
          function a(e2, t4) {
            if (0 !== e2.length) {
              l(e2[0], t4);
              for (var o2 = 1; o2 < e2.length; o2++) l(e2[o2], !t4);
            }
          }
          function l(e2, t4) {
            for (var o2 = 0, i2 = 0, s2 = 0, r2 = e2.length, n2 = r2 - 1; s2 < r2; n2 = s2++) {
              var a2 = (e2[s2][0] - e2[n2][0]) * (e2[n2][1] + e2[s2][1]), l2 = o2 + a2;
              i2 += Math.abs(o2) >= Math.abs(a2) ? o2 - l2 + a2 : a2 - l2 + o2, o2 = l2;
            }
            o2 + i2 >= 0 != !!t4 && e2.reverse();
          }
          var c = e.by(function e2(t4, o2) {
            var i2, s2 = t4 && t4.type;
            if ("FeatureCollection" === s2) for (i2 = 0; i2 < t4.features.length; i2++) e2(t4.features[i2], o2);
            else if ("GeometryCollection" === s2) for (i2 = 0; i2 < t4.geometries.length; i2++) e2(t4.geometries[i2], o2);
            else if ("Feature" === s2) e2(t4.geometry, o2);
            else if ("Polygon" === s2) a(t4.coordinates, o2);
            else if ("MultiPolygon" === s2) for (i2 = 0; i2 < t4.coordinates.length; i2++) a(t4.coordinates[i2], o2);
            return t4;
          });
          const u = e.bt.VectorTileFeature.prototype.toGeoJSON;
          var h = { exports: {} }, d = e.bz, f = e.bt.VectorTileFeature, g = p;
          function p(e2, t4) {
            this.options = t4 || {}, this.features = e2, this.length = e2.length;
          }
          function m(e2, t4) {
            this.id = "number" == typeof e2.id ? e2.id : void 0, this.type = e2.type, this.rawGeometry = 1 === e2.type ? [e2.geometry] : e2.geometry, this.properties = e2.tags, this.extent = t4 || 4096;
          }
          p.prototype.feature = function(e2) {
            return new m(this.features[e2], this.options.extent);
          }, m.prototype.loadGeometry = function() {
            var e2 = this.rawGeometry;
            this.geometry = [];
            for (var t4 = 0; t4 < e2.length; t4++) {
              for (var o2 = e2[t4], i2 = [], s2 = 0; s2 < o2.length; s2++) i2.push(new d(o2[s2][0], o2[s2][1]));
              this.geometry.push(i2);
            }
            return this.geometry;
          }, m.prototype.bbox = function() {
            this.geometry || this.loadGeometry();
            for (var e2 = this.geometry, t4 = 1 / 0, o2 = -1 / 0, i2 = 1 / 0, s2 = -1 / 0, r2 = 0; r2 < e2.length; r2++) for (var n2 = e2[r2], a2 = 0; a2 < n2.length; a2++) {
              var l2 = n2[a2];
              t4 = Math.min(t4, l2.x), o2 = Math.max(o2, l2.x), i2 = Math.min(i2, l2.y), s2 = Math.max(s2, l2.y);
            }
            return [t4, i2, o2, s2];
          }, m.prototype.toGeoJSON = f.prototype.toGeoJSON;
          var y = e.bA, v = g;
          function w(e2) {
            var t4 = new y();
            return function(e3, t5) {
              for (var o2 in e3.layers) t5.writeMessage(3, x, e3.layers[o2]);
            }(e2, t4), t4.finish();
          }
          function x(e2, t4) {
            var o2;
            t4.writeVarintField(15, e2.version || 1), t4.writeStringField(1, e2.name || ""), t4.writeVarintField(5, e2.extent || 4096);
            var i2 = { keys: [], values: [], keycache: {}, valuecache: {} };
            for (o2 = 0; o2 < e2.length; o2++) i2.feature = e2.feature(o2), t4.writeMessage(2, b, i2);
            var s2 = i2.keys;
            for (o2 = 0; o2 < s2.length; o2++) t4.writeStringField(3, s2[o2]);
            var r2 = i2.values;
            for (o2 = 0; o2 < r2.length; o2++) t4.writeMessage(4, P, r2[o2]);
          }
          function b(e2, t4) {
            var o2 = e2.feature;
            void 0 !== o2.id && t4.writeVarintField(1, o2.id), t4.writeMessage(2, S, e2), t4.writeVarintField(3, o2.type), t4.writeMessage(4, I, o2);
          }
          function S(e2, t4) {
            var o2 = e2.feature, i2 = e2.keys, s2 = e2.values, r2 = e2.keycache, n2 = e2.valuecache;
            for (var a2 in o2.properties) {
              var l2 = o2.properties[a2], c2 = r2[a2];
              if (null !== l2) {
                void 0 === c2 && (i2.push(a2), r2[a2] = c2 = i2.length - 1), t4.writeVarint(c2);
                var u2 = typeof l2;
                "string" !== u2 && "boolean" !== u2 && "number" !== u2 && (l2 = JSON.stringify(l2));
                var h2 = u2 + ":" + l2, d2 = n2[h2];
                void 0 === d2 && (s2.push(l2), n2[h2] = d2 = s2.length - 1), t4.writeVarint(d2);
              }
            }
          }
          function _(e2, t4) {
            return (t4 << 3) + (7 & e2);
          }
          function M(e2) {
            return e2 << 1 ^ e2 >> 31;
          }
          function I(e2, t4) {
            for (var o2 = e2.loadGeometry(), i2 = e2.type, s2 = 0, r2 = 0, n2 = o2.length, a2 = 0; a2 < n2; a2++) {
              var l2 = o2[a2], c2 = 1;
              1 === i2 && (c2 = l2.length), t4.writeVarint(_(1, c2));
              for (var u2 = 3 === i2 ? l2.length - 1 : l2.length, h2 = 0; h2 < u2; h2++) {
                1 === h2 && 1 !== i2 && t4.writeVarint(_(2, u2 - 1));
                var d2 = l2[h2].x - s2, f2 = l2[h2].y - r2;
                t4.writeVarint(M(d2)), t4.writeVarint(M(f2)), s2 += d2, r2 += f2;
              }
              3 === i2 && t4.writeVarint(_(7, 1));
            }
          }
          function P(e2, t4) {
            var o2 = typeof e2;
            "string" === o2 ? t4.writeStringField(1, e2) : "boolean" === o2 ? t4.writeBooleanField(7, e2) : "number" === o2 && (e2 % 1 != 0 ? t4.writeDoubleField(3, e2) : e2 < 0 ? t4.writeSVarintField(6, e2) : t4.writeVarintField(5, e2));
          }
          h.exports = w, h.exports.fromVectorTileJs = w, h.exports.fromGeojsonVt = function(e2, t4) {
            t4 = t4 || {};
            var o2 = {};
            for (var i2 in e2) o2[i2] = new v(e2[i2].features, t4), o2[i2].name = i2, o2[i2].version = t4.version, o2[i2].extent = t4.extent;
            return w({ layers: o2 });
          }, h.exports.GeoJSONWrapper = v;
          var k = e.by(h.exports);
          const T = { minZoom: 0, maxZoom: 16, minPoints: 2, radius: 40, extent: 512, nodeSize: 64, log: false, generateId: false, reduce: null, map: (e2) => e2 }, D2 = Math.fround || (C2 = new Float32Array(1), (e2) => (C2[0] = +e2, C2[0]));
          var C2;
          const L = 3, O = 5, F = 6;
          class z {
            constructor(e2) {
              this.options = Object.assign(Object.create(T), e2), this.trees = new Array(this.options.maxZoom + 1), this.stride = this.options.reduce ? 7 : 6, this.clusterProps = [];
            }
            load(e2) {
              const { log: t4, minZoom: o2, maxZoom: i2 } = this.options;
              t4 && console.time("total time");
              const s2 = `prepare ${e2.length} points`;
              t4 && console.time(s2), this.points = e2;
              const r2 = [];
              for (let t5 = 0; t5 < e2.length; t5++) {
                const o3 = e2[t5];
                if (!o3.geometry) continue;
                const [i3, s3] = o3.geometry.coordinates, n3 = D2(G(i3)), a2 = D2(j(s3));
                r2.push(n3, a2, 1 / 0, t5, -1, 1), this.options.reduce && r2.push(0);
              }
              let n2 = this.trees[i2 + 1] = this._createTree(r2);
              t4 && console.timeEnd(s2);
              for (let e3 = i2; e3 >= o2; e3--) {
                const o3 = +Date.now();
                n2 = this.trees[e3] = this._createTree(this._cluster(n2, e3)), t4 && console.log("z%d: %d clusters in %dms", e3, n2.numItems, +Date.now() - o3);
              }
              return t4 && console.timeEnd("total time"), this;
            }
            getClusters(e2, t4) {
              let o2 = ((e2[0] + 180) % 360 + 360) % 360 - 180;
              const i2 = Math.max(-90, Math.min(90, e2[1]));
              let s2 = 180 === e2[2] ? 180 : ((e2[2] + 180) % 360 + 360) % 360 - 180;
              const r2 = Math.max(-90, Math.min(90, e2[3]));
              if (e2[2] - e2[0] >= 360) o2 = -180, s2 = 180;
              else if (o2 > s2) {
                const e3 = this.getClusters([o2, i2, 180, r2], t4), n3 = this.getClusters([-180, i2, s2, r2], t4);
                return e3.concat(n3);
              }
              const n2 = this.trees[this._limitZoom(t4)], a2 = n2.range(G(o2), j(r2), G(s2), j(i2)), l2 = n2.data, c2 = [];
              for (const e3 of a2) {
                const t5 = this.stride * e3;
                c2.push(l2[t5 + O] > 1 ? A2(l2, t5, this.clusterProps) : this.points[l2[t5 + L]]);
              }
              return c2;
            }
            getChildren(e2) {
              const t4 = this._getOriginId(e2), o2 = this._getOriginZoom(e2), i2 = "No cluster with the specified id.", s2 = this.trees[o2];
              if (!s2) throw new Error(i2);
              const r2 = s2.data;
              if (t4 * this.stride >= r2.length) throw new Error(i2);
              const n2 = this.options.radius / (this.options.extent * Math.pow(2, o2 - 1)), a2 = s2.within(r2[t4 * this.stride], r2[t4 * this.stride + 1], n2), l2 = [];
              for (const t5 of a2) {
                const o3 = t5 * this.stride;
                r2[o3 + 4] === e2 && l2.push(r2[o3 + O] > 1 ? A2(r2, o3, this.clusterProps) : this.points[r2[o3 + L]]);
              }
              if (0 === l2.length) throw new Error(i2);
              return l2;
            }
            getLeaves(e2, t4, o2) {
              const i2 = [];
              return this._appendLeaves(i2, e2, t4 = t4 || 10, o2 = o2 || 0, 0), i2;
            }
            getTile(e2, t4, o2) {
              const i2 = this.trees[this._limitZoom(e2)], s2 = Math.pow(2, e2), { extent: r2, radius: n2 } = this.options, a2 = n2 / r2, l2 = (o2 - a2) / s2, c2 = (o2 + 1 + a2) / s2, u2 = { features: [] };
              return this._addTileFeatures(i2.range((t4 - a2) / s2, l2, (t4 + 1 + a2) / s2, c2), i2.data, t4, o2, s2, u2), 0 === t4 && this._addTileFeatures(i2.range(1 - a2 / s2, l2, 1, c2), i2.data, s2, o2, s2, u2), t4 === s2 - 1 && this._addTileFeatures(i2.range(0, l2, a2 / s2, c2), i2.data, -1, o2, s2, u2), u2.features.length ? u2 : null;
            }
            getClusterExpansionZoom(e2) {
              let t4 = this._getOriginZoom(e2) - 1;
              for (; t4 <= this.options.maxZoom; ) {
                const o2 = this.getChildren(e2);
                if (t4++, 1 !== o2.length) break;
                e2 = o2[0].properties.cluster_id;
              }
              return t4;
            }
            _appendLeaves(e2, t4, o2, i2, s2) {
              const r2 = this.getChildren(t4);
              for (const t5 of r2) {
                const r3 = t5.properties;
                if (r3 && r3.cluster ? s2 + r3.point_count <= i2 ? s2 += r3.point_count : s2 = this._appendLeaves(e2, r3.cluster_id, o2, i2, s2) : s2 < i2 ? s2++ : e2.push(t5), e2.length === o2) break;
              }
              return s2;
            }
            _createTree(t4) {
              const o2 = new e.av(t4.length / this.stride | 0, this.options.nodeSize, Float32Array);
              for (let e2 = 0; e2 < t4.length; e2 += this.stride) o2.add(t4[e2], t4[e2 + 1]);
              return o2.finish(), o2.data = t4, o2;
            }
            _addTileFeatures(e2, t4, o2, i2, s2, r2) {
              for (const n2 of e2) {
                const e3 = n2 * this.stride, a2 = t4[e3 + O] > 1;
                let l2, c2, u2;
                if (a2) l2 = E2(t4, e3, this.clusterProps), c2 = t4[e3], u2 = t4[e3 + 1];
                else {
                  const o3 = this.points[t4[e3 + L]];
                  l2 = o3.properties;
                  const [i3, s3] = o3.geometry.coordinates;
                  c2 = G(i3), u2 = j(s3);
                }
                const h2 = { type: 1, geometry: [[Math.round(this.options.extent * (c2 * s2 - o2)), Math.round(this.options.extent * (u2 * s2 - i2))]], tags: l2 };
                let d2;
                d2 = a2 || this.options.generateId ? t4[e3 + L] : this.points[t4[e3 + L]].id, void 0 !== d2 && (h2.id = d2), r2.features.push(h2);
              }
            }
            _limitZoom(e2) {
              return Math.max(this.options.minZoom, Math.min(Math.floor(+e2), this.options.maxZoom + 1));
            }
            _cluster(e2, t4) {
              const { radius: o2, extent: i2, reduce: s2, minPoints: r2 } = this.options, n2 = o2 / (i2 * Math.pow(2, t4)), a2 = e2.data, l2 = [], c2 = this.stride;
              for (let o3 = 0; o3 < a2.length; o3 += c2) {
                if (a2[o3 + 2] <= t4) continue;
                a2[o3 + 2] = t4;
                const i3 = a2[o3], u2 = a2[o3 + 1], h2 = e2.within(a2[o3], a2[o3 + 1], n2), d2 = a2[o3 + O];
                let f2 = d2;
                for (const e3 of h2) {
                  const o4 = e3 * c2;
                  a2[o4 + 2] > t4 && (f2 += a2[o4 + O]);
                }
                if (f2 > d2 && f2 >= r2) {
                  let e3, r3 = i3 * d2, n3 = u2 * d2, g2 = -1;
                  const p2 = ((o3 / c2 | 0) << 5) + (t4 + 1) + this.points.length;
                  for (const i4 of h2) {
                    const l3 = i4 * c2;
                    if (a2[l3 + 2] <= t4) continue;
                    a2[l3 + 2] = t4;
                    const u3 = a2[l3 + O];
                    r3 += a2[l3] * u3, n3 += a2[l3 + 1] * u3, a2[l3 + 4] = p2, s2 && (e3 || (e3 = this._map(a2, o3, true), g2 = this.clusterProps.length, this.clusterProps.push(e3)), s2(e3, this._map(a2, l3)));
                  }
                  a2[o3 + 4] = p2, l2.push(r3 / f2, n3 / f2, 1 / 0, p2, -1, f2), s2 && l2.push(g2);
                } else {
                  for (let e3 = 0; e3 < c2; e3++) l2.push(a2[o3 + e3]);
                  if (f2 > 1) for (const e3 of h2) {
                    const o4 = e3 * c2;
                    if (!(a2[o4 + 2] <= t4)) {
                      a2[o4 + 2] = t4;
                      for (let e4 = 0; e4 < c2; e4++) l2.push(a2[o4 + e4]);
                    }
                  }
                }
              }
              return l2;
            }
            _getOriginId(e2) {
              return e2 - this.points.length >> 5;
            }
            _getOriginZoom(e2) {
              return (e2 - this.points.length) % 32;
            }
            _map(e2, t4, o2) {
              if (e2[t4 + O] > 1) {
                const i3 = this.clusterProps[e2[t4 + F]];
                return o2 ? Object.assign({}, i3) : i3;
              }
              const i2 = this.points[e2[t4 + L]].properties, s2 = this.options.map(i2);
              return o2 && s2 === i2 ? Object.assign({}, s2) : s2;
            }
          }
          function A2(e2, t4, o2) {
            return { type: "Feature", id: e2[t4 + L], properties: E2(e2, t4, o2), geometry: { type: "Point", coordinates: [(i2 = e2[t4], 360 * (i2 - 0.5)), R(e2[t4 + 1])] } };
            var i2;
          }
          function E2(e2, t4, o2) {
            const i2 = e2[t4 + O], s2 = i2 >= 1e4 ? `${Math.round(i2 / 1e3)}k` : i2 >= 1e3 ? Math.round(i2 / 100) / 10 + "k" : i2, r2 = e2[t4 + F], n2 = -1 === r2 ? {} : Object.assign({}, o2[r2]);
            return Object.assign(n2, { cluster: true, cluster_id: e2[t4 + L], point_count: i2, point_count_abbreviated: s2 });
          }
          function G(e2) {
            return e2 / 360 + 0.5;
          }
          function j(e2) {
            const t4 = Math.sin(e2 * Math.PI / 180), o2 = 0.5 - 0.25 * Math.log((1 + t4) / (1 - t4)) / Math.PI;
            return o2 < 0 ? 0 : o2 > 1 ? 1 : o2;
          }
          function R(e2) {
            const t4 = (180 - 360 * e2) * Math.PI / 180;
            return 360 * Math.atan(Math.exp(t4)) / Math.PI - 90;
          }
          function Z(e2, t4, o2, i2) {
            let s2 = i2;
            const r2 = t4 + (o2 - t4 >> 1);
            let n2, a2 = o2 - t4;
            const l2 = e2[t4], c2 = e2[t4 + 1], u2 = e2[o2], h2 = e2[o2 + 1];
            for (let i3 = t4 + 3; i3 < o2; i3 += 3) {
              const t5 = N(e2[i3], e2[i3 + 1], l2, c2, u2, h2);
              if (t5 > s2) n2 = i3, s2 = t5;
              else if (t5 === s2) {
                const e3 = Math.abs(i3 - r2);
                e3 < a2 && (n2 = i3, a2 = e3);
              }
            }
            s2 > i2 && (n2 - t4 > 3 && Z(e2, t4, n2, i2), e2[n2 + 2] = s2, o2 - n2 > 3 && Z(e2, n2, o2, i2));
          }
          function N(e2, t4, o2, i2, s2, r2) {
            let n2 = s2 - o2, a2 = r2 - i2;
            if (0 !== n2 || 0 !== a2) {
              const l2 = ((e2 - o2) * n2 + (t4 - i2) * a2) / (n2 * n2 + a2 * a2);
              l2 > 1 ? (o2 = s2, i2 = r2) : l2 > 0 && (o2 += n2 * l2, i2 += a2 * l2);
            }
            return n2 = e2 - o2, a2 = t4 - i2, n2 * n2 + a2 * a2;
          }
          function J(e2, t4, o2, i2) {
            const s2 = { id: null == e2 ? null : e2, type: t4, geometry: o2, tags: i2, minX: 1 / 0, minY: 1 / 0, maxX: -1 / 0, maxY: -1 / 0 };
            if ("Point" === t4 || "MultiPoint" === t4 || "LineString" === t4) W(s2, o2);
            else if ("Polygon" === t4) W(s2, o2[0]);
            else if ("MultiLineString" === t4) for (const e3 of o2) W(s2, e3);
            else if ("MultiPolygon" === t4) for (const e3 of o2) W(s2, e3[0]);
            return s2;
          }
          function W(e2, t4) {
            for (let o2 = 0; o2 < t4.length; o2 += 3) e2.minX = Math.min(e2.minX, t4[o2]), e2.minY = Math.min(e2.minY, t4[o2 + 1]), e2.maxX = Math.max(e2.maxX, t4[o2]), e2.maxY = Math.max(e2.maxY, t4[o2 + 1]);
          }
          function Y(e2, t4, o2, i2) {
            if (!t4.geometry) return;
            const s2 = t4.geometry.coordinates;
            if (s2 && 0 === s2.length) return;
            const r2 = t4.geometry.type, n2 = Math.pow(o2.tolerance / ((1 << o2.maxZoom) * o2.extent), 2);
            let a2 = [], l2 = t4.id;
            if (o2.promoteId ? l2 = t4.properties[o2.promoteId] : o2.generateId && (l2 = i2 || 0), "Point" === r2) V(s2, a2);
            else if ("MultiPoint" === r2) for (const e3 of s2) V(e3, a2);
            else if ("LineString" === r2) X(s2, a2, n2, false);
            else if ("MultiLineString" === r2) {
              if (o2.lineMetrics) {
                for (const o3 of s2) a2 = [], X(o3, a2, n2, false), e2.push(J(l2, "LineString", a2, t4.properties));
                return;
              }
              q(s2, a2, n2, false);
            } else if ("Polygon" === r2) q(s2, a2, n2, true);
            else {
              if ("MultiPolygon" !== r2) {
                if ("GeometryCollection" === r2) {
                  for (const s3 of t4.geometry.geometries) Y(e2, { id: l2, geometry: s3, properties: t4.properties }, o2, i2);
                  return;
                }
                throw new Error("Input data is not a valid GeoJSON object.");
              }
              for (const e3 of s2) {
                const t5 = [];
                q(e3, t5, n2, true), a2.push(t5);
              }
            }
            e2.push(J(l2, r2, a2, t4.properties));
          }
          function V(e2, t4) {
            t4.push(H(e2[0]), B2(e2[1]), 0);
          }
          function X(e2, t4, o2, i2) {
            let s2, r2, n2 = 0;
            for (let o3 = 0; o3 < e2.length; o3++) {
              const a3 = H(e2[o3][0]), l2 = B2(e2[o3][1]);
              t4.push(a3, l2, 0), o3 > 0 && (n2 += i2 ? (s2 * l2 - a3 * r2) / 2 : Math.sqrt(Math.pow(a3 - s2, 2) + Math.pow(l2 - r2, 2))), s2 = a3, r2 = l2;
            }
            const a2 = t4.length - 3;
            t4[2] = 1, Z(t4, 0, a2, o2), t4[a2 + 2] = 1, t4.size = Math.abs(n2), t4.start = 0, t4.end = t4.size;
          }
          function q(e2, t4, o2, i2) {
            for (let s2 = 0; s2 < e2.length; s2++) {
              const r2 = [];
              X(e2[s2], r2, o2, i2), t4.push(r2);
            }
          }
          function H(e2) {
            return e2 / 360 + 0.5;
          }
          function B2(e2) {
            const t4 = Math.sin(e2 * Math.PI / 180), o2 = 0.5 - 0.25 * Math.log((1 + t4) / (1 - t4)) / Math.PI;
            return o2 < 0 ? 0 : o2 > 1 ? 1 : o2;
          }
          function U(e2, t4, o2, i2, s2, r2, n2, a2) {
            if (i2 /= t4, r2 >= (o2 /= t4) && n2 < i2) return e2;
            if (n2 < o2 || r2 >= i2) return null;
            const l2 = [];
            for (const t5 of e2) {
              const e3 = t5.geometry;
              let r3 = t5.type;
              const n3 = 0 === s2 ? t5.minX : t5.minY, c2 = 0 === s2 ? t5.maxX : t5.maxY;
              if (n3 >= o2 && c2 < i2) {
                l2.push(t5);
                continue;
              }
              if (c2 < o2 || n3 >= i2) continue;
              let u2 = [];
              if ("Point" === r3 || "MultiPoint" === r3) $(e3, u2, o2, i2, s2);
              else if ("LineString" === r3) K2(e3, u2, o2, i2, s2, false, a2.lineMetrics);
              else if ("MultiLineString" === r3) ee(e3, u2, o2, i2, s2, false);
              else if ("Polygon" === r3) ee(e3, u2, o2, i2, s2, true);
              else if ("MultiPolygon" === r3) for (const t6 of e3) {
                const e4 = [];
                ee(t6, e4, o2, i2, s2, true), e4.length && u2.push(e4);
              }
              if (u2.length) {
                if (a2.lineMetrics && "LineString" === r3) {
                  for (const e4 of u2) l2.push(J(t5.id, r3, e4, t5.tags));
                  continue;
                }
                "LineString" !== r3 && "MultiLineString" !== r3 || (1 === u2.length ? (r3 = "LineString", u2 = u2[0]) : r3 = "MultiLineString"), "Point" !== r3 && "MultiPoint" !== r3 || (r3 = 3 === u2.length ? "Point" : "MultiPoint"), l2.push(J(t5.id, r3, u2, t5.tags));
              }
            }
            return l2.length ? l2 : null;
          }
          function $(e2, t4, o2, i2, s2) {
            for (let r2 = 0; r2 < e2.length; r2 += 3) {
              const n2 = e2[r2 + s2];
              n2 >= o2 && n2 <= i2 && te(t4, e2[r2], e2[r2 + 1], e2[r2 + 2]);
            }
          }
          function K2(e2, t4, o2, i2, s2, r2, n2) {
            let a2 = Q(e2);
            const l2 = 0 === s2 ? oe : ie;
            let c2, u2, h2 = e2.start;
            for (let d3 = 0; d3 < e2.length - 3; d3 += 3) {
              const f3 = e2[d3], g3 = e2[d3 + 1], p3 = e2[d3 + 2], m2 = e2[d3 + 3], y2 = e2[d3 + 4], v2 = 0 === s2 ? f3 : g3, w2 = 0 === s2 ? m2 : y2;
              let x2 = false;
              n2 && (c2 = Math.sqrt(Math.pow(f3 - m2, 2) + Math.pow(g3 - y2, 2))), v2 < o2 ? w2 > o2 && (u2 = l2(a2, f3, g3, m2, y2, o2), n2 && (a2.start = h2 + c2 * u2)) : v2 > i2 ? w2 < i2 && (u2 = l2(a2, f3, g3, m2, y2, i2), n2 && (a2.start = h2 + c2 * u2)) : te(a2, f3, g3, p3), w2 < o2 && v2 >= o2 && (u2 = l2(a2, f3, g3, m2, y2, o2), x2 = true), w2 > i2 && v2 <= i2 && (u2 = l2(a2, f3, g3, m2, y2, i2), x2 = true), !r2 && x2 && (n2 && (a2.end = h2 + c2 * u2), t4.push(a2), a2 = Q(e2)), n2 && (h2 += c2);
            }
            let d2 = e2.length - 3;
            const f2 = e2[d2], g2 = e2[d2 + 1], p2 = 0 === s2 ? f2 : g2;
            p2 >= o2 && p2 <= i2 && te(a2, f2, g2, e2[d2 + 2]), d2 = a2.length - 3, r2 && d2 >= 3 && (a2[d2] !== a2[0] || a2[d2 + 1] !== a2[1]) && te(a2, a2[0], a2[1], a2[2]), a2.length && t4.push(a2);
          }
          function Q(e2) {
            const t4 = [];
            return t4.size = e2.size, t4.start = e2.start, t4.end = e2.end, t4;
          }
          function ee(e2, t4, o2, i2, s2, r2) {
            for (const n2 of e2) K2(n2, t4, o2, i2, s2, r2, false);
          }
          function te(e2, t4, o2, i2) {
            e2.push(t4, o2, i2);
          }
          function oe(e2, t4, o2, i2, s2, r2) {
            const n2 = (r2 - t4) / (i2 - t4);
            return te(e2, r2, o2 + (s2 - o2) * n2, 1), n2;
          }
          function ie(e2, t4, o2, i2, s2, r2) {
            const n2 = (r2 - o2) / (s2 - o2);
            return te(e2, t4 + (i2 - t4) * n2, r2, 1), n2;
          }
          function se(e2, t4) {
            const o2 = [];
            for (let i2 = 0; i2 < e2.length; i2++) {
              const s2 = e2[i2], r2 = s2.type;
              let n2;
              if ("Point" === r2 || "MultiPoint" === r2 || "LineString" === r2) n2 = re(s2.geometry, t4);
              else if ("MultiLineString" === r2 || "Polygon" === r2) {
                n2 = [];
                for (const e3 of s2.geometry) n2.push(re(e3, t4));
              } else if ("MultiPolygon" === r2) {
                n2 = [];
                for (const e3 of s2.geometry) {
                  const o3 = [];
                  for (const i3 of e3) o3.push(re(i3, t4));
                  n2.push(o3);
                }
              }
              o2.push(J(s2.id, r2, n2, s2.tags));
            }
            return o2;
          }
          function re(e2, t4) {
            const o2 = [];
            o2.size = e2.size, void 0 !== e2.start && (o2.start = e2.start, o2.end = e2.end);
            for (let i2 = 0; i2 < e2.length; i2 += 3) o2.push(e2[i2] + t4, e2[i2 + 1], e2[i2 + 2]);
            return o2;
          }
          function ne(e2, t4) {
            if (e2.transformed) return e2;
            const o2 = 1 << e2.z, i2 = e2.x, s2 = e2.y;
            for (const r2 of e2.features) {
              const e3 = r2.geometry, n2 = r2.type;
              if (r2.geometry = [], 1 === n2) for (let n3 = 0; n3 < e3.length; n3 += 2) r2.geometry.push(ae(e3[n3], e3[n3 + 1], t4, o2, i2, s2));
              else for (let n3 = 0; n3 < e3.length; n3++) {
                const a2 = [];
                for (let r3 = 0; r3 < e3[n3].length; r3 += 2) a2.push(ae(e3[n3][r3], e3[n3][r3 + 1], t4, o2, i2, s2));
                r2.geometry.push(a2);
              }
            }
            return e2.transformed = true, e2;
          }
          function ae(e2, t4, o2, i2, s2, r2) {
            return [Math.round(o2 * (e2 * i2 - s2)), Math.round(o2 * (t4 * i2 - r2))];
          }
          function le(e2, t4, o2, i2, s2) {
            const r2 = t4 === s2.maxZoom ? 0 : s2.tolerance / ((1 << t4) * s2.extent), n2 = { features: [], numPoints: 0, numSimplified: 0, numFeatures: e2.length, source: null, x: o2, y: i2, z: t4, transformed: false, minX: 2, minY: 1, maxX: -1, maxY: 0 };
            for (const t5 of e2) ce(n2, t5, r2, s2);
            return n2;
          }
          function ce(e2, t4, o2, i2) {
            const s2 = t4.geometry, r2 = t4.type, n2 = [];
            if (e2.minX = Math.min(e2.minX, t4.minX), e2.minY = Math.min(e2.minY, t4.minY), e2.maxX = Math.max(e2.maxX, t4.maxX), e2.maxY = Math.max(e2.maxY, t4.maxY), "Point" === r2 || "MultiPoint" === r2) for (let t5 = 0; t5 < s2.length; t5 += 3) n2.push(s2[t5], s2[t5 + 1]), e2.numPoints++, e2.numSimplified++;
            else if ("LineString" === r2) ue(n2, s2, e2, o2, false, false);
            else if ("MultiLineString" === r2 || "Polygon" === r2) for (let t5 = 0; t5 < s2.length; t5++) ue(n2, s2[t5], e2, o2, "Polygon" === r2, 0 === t5);
            else if ("MultiPolygon" === r2) for (let t5 = 0; t5 < s2.length; t5++) {
              const i3 = s2[t5];
              for (let t6 = 0; t6 < i3.length; t6++) ue(n2, i3[t6], e2, o2, true, 0 === t6);
            }
            if (n2.length) {
              let o3 = t4.tags || null;
              if ("LineString" === r2 && i2.lineMetrics) {
                o3 = {};
                for (const e3 in t4.tags) o3[e3] = t4.tags[e3];
                o3.mapbox_clip_start = s2.start / s2.size, o3.mapbox_clip_end = s2.end / s2.size;
              }
              const a2 = { geometry: n2, type: "Polygon" === r2 || "MultiPolygon" === r2 ? 3 : "LineString" === r2 || "MultiLineString" === r2 ? 2 : 1, tags: o3 };
              null !== t4.id && (a2.id = t4.id), e2.features.push(a2);
            }
          }
          function ue(e2, t4, o2, i2, s2, r2) {
            const n2 = i2 * i2;
            if (i2 > 0 && t4.size < (s2 ? n2 : i2)) return void (o2.numPoints += t4.length / 3);
            const a2 = [];
            for (let e3 = 0; e3 < t4.length; e3 += 3) (0 === i2 || t4[e3 + 2] > n2) && (o2.numSimplified++, a2.push(t4[e3], t4[e3 + 1])), o2.numPoints++;
            s2 && function(e3, t5) {
              let o3 = 0;
              for (let t6 = 0, i3 = e3.length, s3 = i3 - 2; t6 < i3; s3 = t6, t6 += 2) o3 += (e3[t6] - e3[s3]) * (e3[t6 + 1] + e3[s3 + 1]);
              if (o3 > 0 === t5) for (let t6 = 0, o4 = e3.length; t6 < o4 / 2; t6 += 2) {
                const i3 = e3[t6], s3 = e3[t6 + 1];
                e3[t6] = e3[o4 - 2 - t6], e3[t6 + 1] = e3[o4 - 1 - t6], e3[o4 - 2 - t6] = i3, e3[o4 - 1 - t6] = s3;
              }
            }(a2, r2), e2.push(a2);
          }
          const he = { maxZoom: 14, indexMaxZoom: 5, indexMaxPoints: 1e5, tolerance: 3, extent: 4096, buffer: 64, lineMetrics: false, promoteId: null, generateId: false, debug: 0 };
          class de {
            constructor(e2, t4) {
              const o2 = (t4 = this.options = function(e3, t5) {
                for (const o3 in t5) e3[o3] = t5[o3];
                return e3;
              }(Object.create(he), t4)).debug;
              if (o2 && console.time("preprocess data"), t4.maxZoom < 0 || t4.maxZoom > 24) throw new Error("maxZoom should be in the 0-24 range");
              if (t4.promoteId && t4.generateId) throw new Error("promoteId and generateId cannot be used together.");
              let i2 = function(e3, t5) {
                const o3 = [];
                if ("FeatureCollection" === e3.type) for (let i3 = 0; i3 < e3.features.length; i3++) Y(o3, e3.features[i3], t5, i3);
                else Y(o3, "Feature" === e3.type ? e3 : { geometry: e3 }, t5);
                return o3;
              }(e2, t4);
              this.tiles = {}, this.tileCoords = [], o2 && (console.timeEnd("preprocess data"), console.log("index: maxZoom: %d, maxPoints: %d", t4.indexMaxZoom, t4.indexMaxPoints), console.time("generate tiles"), this.stats = {}, this.total = 0), i2 = function(e3, t5) {
                const o3 = t5.buffer / t5.extent;
                let i3 = e3;
                const s2 = U(e3, 1, -1 - o3, o3, 0, -1, 2, t5), r2 = U(e3, 1, 1 - o3, 2 + o3, 0, -1, 2, t5);
                return (s2 || r2) && (i3 = U(e3, 1, -o3, 1 + o3, 0, -1, 2, t5) || [], s2 && (i3 = se(s2, 1).concat(i3)), r2 && (i3 = i3.concat(se(r2, -1)))), i3;
              }(i2, t4), i2.length && this.splitTile(i2, 0, 0, 0), o2 && (i2.length && console.log("features: %d, points: %d", this.tiles[0].numFeatures, this.tiles[0].numPoints), console.timeEnd("generate tiles"), console.log("tiles generated:", this.total, JSON.stringify(this.stats)));
            }
            splitTile(e2, t4, o2, i2, s2, r2, n2) {
              const a2 = [e2, t4, o2, i2], l2 = this.options, c2 = l2.debug;
              for (; a2.length; ) {
                i2 = a2.pop(), o2 = a2.pop(), t4 = a2.pop(), e2 = a2.pop();
                const u2 = 1 << t4, h2 = fe(t4, o2, i2);
                let d2 = this.tiles[h2];
                if (!d2 && (c2 > 1 && console.time("creation"), d2 = this.tiles[h2] = le(e2, t4, o2, i2, l2), this.tileCoords.push({ z: t4, x: o2, y: i2 }), c2)) {
                  c2 > 1 && (console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)", t4, o2, i2, d2.numFeatures, d2.numPoints, d2.numSimplified), console.timeEnd("creation"));
                  const e3 = `z${t4}`;
                  this.stats[e3] = (this.stats[e3] || 0) + 1, this.total++;
                }
                if (d2.source = e2, null == s2) {
                  if (t4 === l2.indexMaxZoom || d2.numPoints <= l2.indexMaxPoints) continue;
                } else {
                  if (t4 === l2.maxZoom || t4 === s2) continue;
                  if (null != s2) {
                    const e3 = s2 - t4;
                    if (o2 !== r2 >> e3 || i2 !== n2 >> e3) continue;
                  }
                }
                if (d2.source = null, 0 === e2.length) continue;
                c2 > 1 && console.time("clipping");
                const f2 = 0.5 * l2.buffer / l2.extent, g2 = 0.5 - f2, p2 = 0.5 + f2, m2 = 1 + f2;
                let y2 = null, v2 = null, w2 = null, x2 = null, b2 = U(e2, u2, o2 - f2, o2 + p2, 0, d2.minX, d2.maxX, l2), S2 = U(e2, u2, o2 + g2, o2 + m2, 0, d2.minX, d2.maxX, l2);
                e2 = null, b2 && (y2 = U(b2, u2, i2 - f2, i2 + p2, 1, d2.minY, d2.maxY, l2), v2 = U(b2, u2, i2 + g2, i2 + m2, 1, d2.minY, d2.maxY, l2), b2 = null), S2 && (w2 = U(S2, u2, i2 - f2, i2 + p2, 1, d2.minY, d2.maxY, l2), x2 = U(S2, u2, i2 + g2, i2 + m2, 1, d2.minY, d2.maxY, l2), S2 = null), c2 > 1 && console.timeEnd("clipping"), a2.push(y2 || [], t4 + 1, 2 * o2, 2 * i2), a2.push(v2 || [], t4 + 1, 2 * o2, 2 * i2 + 1), a2.push(w2 || [], t4 + 1, 2 * o2 + 1, 2 * i2), a2.push(x2 || [], t4 + 1, 2 * o2 + 1, 2 * i2 + 1);
              }
            }
            getTile(e2, t4, o2) {
              e2 = +e2, t4 = +t4, o2 = +o2;
              const i2 = this.options, { extent: s2, debug: r2 } = i2;
              if (e2 < 0 || e2 > 24) return null;
              const n2 = 1 << e2, a2 = fe(e2, t4 = t4 + n2 & n2 - 1, o2);
              if (this.tiles[a2]) return ne(this.tiles[a2], s2);
              r2 > 1 && console.log("drilling down to z%d-%d-%d", e2, t4, o2);
              let l2, c2 = e2, u2 = t4, h2 = o2;
              for (; !l2 && c2 > 0; ) c2--, u2 >>= 1, h2 >>= 1, l2 = this.tiles[fe(c2, u2, h2)];
              return l2 && l2.source ? (r2 > 1 && (console.log("found parent tile z%d-%d-%d", c2, u2, h2), console.time("drilling down")), this.splitTile(l2.source, c2, u2, h2, e2, t4, o2), r2 > 1 && console.timeEnd("drilling down"), this.tiles[a2] ? ne(this.tiles[a2], s2) : null) : null;
            }
          }
          function fe(e2, t4, o2) {
            return 32 * ((1 << e2) * o2 + t4) + e2;
          }
          function ge(e2, t4) {
            return t4 ? e2.properties[t4] : e2.id;
          }
          function pe(e2, t4) {
            if (null == e2) return true;
            if ("Feature" === e2.type) return null != ge(e2, t4);
            if ("FeatureCollection" === e2.type) {
              const o2 = /* @__PURE__ */ new Set();
              for (const i2 of e2.features) {
                const e3 = ge(i2, t4);
                if (null == e3) return false;
                if (o2.has(e3)) return false;
                o2.add(e3);
              }
              return true;
            }
            return false;
          }
          function me(e2, t4) {
            const o2 = /* @__PURE__ */ new Map();
            if (null == e2) ;
            else if ("Feature" === e2.type) o2.set(ge(e2, t4), e2);
            else for (const i2 of e2.features) o2.set(ge(i2, t4), i2);
            return o2;
          }
          class ye extends r {
            constructor() {
              super(...arguments), this._dataUpdateable = /* @__PURE__ */ new Map();
            }
            loadVectorTile(t4, o2) {
              return e._(this, void 0, void 0, function* () {
                const o3 = t4.tileID.canonical;
                if (!this._geoJSONIndex) throw new Error("Unable to parse the data into a cluster or geojson");
                const i2 = this._geoJSONIndex.getTile(o3.z, o3.x, o3.y);
                if (!i2) return null;
                const s2 = new class {
                  constructor(t5) {
                    this.layers = { _geojsonTileLayer: this }, this.name = "_geojsonTileLayer", this.extent = e.X, this.length = t5.length, this._features = t5;
                  }
                  feature(t5) {
                    return new class {
                      constructor(t6) {
                        this._feature = t6, this.extent = e.X, this.type = t6.type, this.properties = t6.tags, "id" in t6 && !isNaN(t6.id) && (this.id = parseInt(t6.id, 10));
                      }
                      loadGeometry() {
                        if (1 === this._feature.type) {
                          const t6 = [];
                          for (const o4 of this._feature.geometry) t6.push([new e.P(o4[0], o4[1])]);
                          return t6;
                        }
                        {
                          const t6 = [];
                          for (const o4 of this._feature.geometry) {
                            const i3 = [];
                            for (const t7 of o4) i3.push(new e.P(t7[0], t7[1]));
                            t6.push(i3);
                          }
                          return t6;
                        }
                      }
                      toGeoJSON(e2, t6, o4) {
                        return u.call(this, e2, t6, o4);
                      }
                    }(this._features[t5]);
                  }
                }(i2.features);
                let r2 = k(s2);
                return 0 === r2.byteOffset && r2.byteLength === r2.buffer.byteLength || (r2 = new Uint8Array(r2)), { vectorTile: s2, rawData: r2.buffer };
              });
            }
            loadData(t4) {
              return e._(this, void 0, void 0, function* () {
                var o2;
                null === (o2 = this._pendingRequest) || void 0 === o2 || o2.abort();
                const i2 = !!(t4 && t4.request && t4.request.collectResourceTiming) && new e.bv(t4.request);
                this._pendingRequest = new AbortController();
                try {
                  this._pendingData = this.loadAndProcessGeoJSON(t4, this._pendingRequest), this._geoJSONIndex = t4.cluster ? new z(function({ superclusterOptions: t5, clusterProperties: o4 }) {
                    if (!o4 || !t5) return t5;
                    const i3 = {}, s3 = {}, r2 = { accumulated: null, zoom: 0 }, n2 = { properties: null }, a2 = Object.keys(o4);
                    for (const t6 of a2) {
                      const [r3, n3] = o4[t6], a3 = e.bC(n3), l2 = e.bC("string" == typeof r3 ? [r3, ["accumulated"], ["get", t6]] : r3);
                      i3[t6] = a3.value, s3[t6] = l2.value;
                    }
                    return t5.map = (e2) => {
                      n2.properties = e2;
                      const t6 = {};
                      for (const e3 of a2) t6[e3] = i3[e3].evaluate(r2, n2);
                      return t6;
                    }, t5.reduce = (e2, t6) => {
                      n2.properties = t6;
                      for (const t7 of a2) r2.accumulated = e2[t7], e2[t7] = s3[t7].evaluate(r2, n2);
                    }, t5;
                  }(t4)).load((yield this._pendingData).features) : (s2 = yield this._pendingData, new de(s2, t4.geojsonVtOptions)), this.loaded = {};
                  const o3 = {};
                  if (i2) {
                    const e2 = i2.finish();
                    e2 && (o3.resourceTiming = {}, o3.resourceTiming[t4.source] = JSON.parse(JSON.stringify(e2)));
                  }
                  return o3;
                } catch (t5) {
                  if (delete this._pendingRequest, e.bB(t5)) return { abandoned: true };
                  throw t5;
                }
                var s2;
              });
            }
            getData() {
              return e._(this, void 0, void 0, function* () {
                return this._pendingData;
              });
            }
            reloadTile(e2) {
              const t4 = this.loaded;
              return t4 && t4[e2.uid] ? super.reloadTile(e2) : this.loadTile(e2);
            }
            loadAndProcessGeoJSON(t4, o2) {
              return e._(this, void 0, void 0, function* () {
                let i2 = yield this.loadGeoJSON(t4, o2);
                if (delete this._pendingRequest, "object" != typeof i2) throw new Error(`Input data given to '${t4.source}' is not a valid GeoJSON object.`);
                if (c(i2, true), t4.filter) {
                  const o3 = e.bC(t4.filter, { type: "boolean", "property-type": "data-driven", overridable: false, transition: false });
                  if ("error" === o3.result) throw new Error(o3.value.map((e2) => `${e2.key}: ${e2.message}`).join(", "));
                  const s2 = i2.features.filter((e2) => o3.value.evaluate({ zoom: 0 }, e2));
                  i2 = { type: "FeatureCollection", features: s2 };
                }
                return i2;
              });
            }
            loadGeoJSON(t4, o2) {
              return e._(this, void 0, void 0, function* () {
                const { promoteId: i2 } = t4;
                if (t4.request) {
                  const s2 = yield e.h(t4.request, o2);
                  return this._dataUpdateable = pe(s2.data, i2) ? me(s2.data, i2) : void 0, s2.data;
                }
                if ("string" == typeof t4.data) try {
                  const e2 = JSON.parse(t4.data);
                  return this._dataUpdateable = pe(e2, i2) ? me(e2, i2) : void 0, e2;
                } catch (e2) {
                  throw new Error(`Input data given to '${t4.source}' is not a valid GeoJSON object.`);
                }
                if (!t4.dataDiff) throw new Error(`Input data given to '${t4.source}' is not a valid GeoJSON object.`);
                if (!this._dataUpdateable) throw new Error(`Cannot update existing geojson data in ${t4.source}`);
                return function(e2, t5, o3) {
                  var i3, s2, r2, n2;
                  if (t5.removeAll && e2.clear(), t5.remove) for (const o4 of t5.remove) e2.delete(o4);
                  if (t5.add) for (const i4 of t5.add) {
                    const t6 = ge(i4, o3);
                    null != t6 && e2.set(t6, i4);
                  }
                  if (t5.update) for (const o4 of t5.update) {
                    let t6 = e2.get(o4.id);
                    if (null == t6) continue;
                    const a2 = !o4.removeAllProperties && ((null === (i3 = o4.removeProperties) || void 0 === i3 ? void 0 : i3.length) > 0 || (null === (s2 = o4.addOrUpdateProperties) || void 0 === s2 ? void 0 : s2.length) > 0);
                    if ((o4.newGeometry || o4.removeAllProperties || a2) && (t6 = Object.assign({}, t6), e2.set(o4.id, t6), a2 && (t6.properties = Object.assign({}, t6.properties))), o4.newGeometry && (t6.geometry = o4.newGeometry), o4.removeAllProperties) t6.properties = {};
                    else if ((null === (r2 = o4.removeProperties) || void 0 === r2 ? void 0 : r2.length) > 0) for (const e3 of o4.removeProperties) Object.prototype.hasOwnProperty.call(t6.properties, e3) && delete t6.properties[e3];
                    if ((null === (n2 = o4.addOrUpdateProperties) || void 0 === n2 ? void 0 : n2.length) > 0) for (const { key: e3, value: i4 } of o4.addOrUpdateProperties) t6.properties[e3] = i4;
                  }
                }(this._dataUpdateable, t4.dataDiff, i2), { type: "FeatureCollection", features: Array.from(this._dataUpdateable.values()) };
              });
            }
            removeSource(t4) {
              return e._(this, void 0, void 0, function* () {
                this._pendingRequest && this._pendingRequest.abort();
              });
            }
            getClusterExpansionZoom(e2) {
              return this._geoJSONIndex.getClusterExpansionZoom(e2.clusterId);
            }
            getClusterChildren(e2) {
              return this._geoJSONIndex.getChildren(e2.clusterId);
            }
            getClusterLeaves(e2) {
              return this._geoJSONIndex.getLeaves(e2.clusterId, e2.limit, e2.offset);
            }
          }
          class ve {
            constructor(t4) {
              this.self = t4, this.actor = new e.F(t4), this.layerIndexes = {}, this.availableImages = {}, this.workerSources = {}, this.demWorkerSources = {}, this.externalWorkerSourceTypes = {}, this.self.registerWorkerSource = (e2, t5) => {
                if (this.externalWorkerSourceTypes[e2]) throw new Error(`Worker source with name "${e2}" already registered.`);
                this.externalWorkerSourceTypes[e2] = t5;
              }, this.self.addProtocol = e.bi, this.self.removeProtocol = e.bj, this.self.registerRTLTextPlugin = (t5) => {
                if (e.bD.isParsed()) throw new Error("RTL text plugin already registered.");
                e.bD.setMethods(t5);
              }, this.actor.registerMessageHandler("LDT", (e2, t5) => this._getDEMWorkerSource(e2, t5.source).loadTile(t5)), this.actor.registerMessageHandler("RDT", (t5, o2) => e._(this, void 0, void 0, function* () {
                this._getDEMWorkerSource(t5, o2.source).removeTile(o2);
              })), this.actor.registerMessageHandler("GCEZ", (t5, o2) => e._(this, void 0, void 0, function* () {
                return this._getWorkerSource(t5, o2.type, o2.source).getClusterExpansionZoom(o2);
              })), this.actor.registerMessageHandler("GCC", (t5, o2) => e._(this, void 0, void 0, function* () {
                return this._getWorkerSource(t5, o2.type, o2.source).getClusterChildren(o2);
              })), this.actor.registerMessageHandler("GCL", (t5, o2) => e._(this, void 0, void 0, function* () {
                return this._getWorkerSource(t5, o2.type, o2.source).getClusterLeaves(o2);
              })), this.actor.registerMessageHandler("LD", (e2, t5) => this._getWorkerSource(e2, t5.type, t5.source).loadData(t5)), this.actor.registerMessageHandler("GD", (e2, t5) => this._getWorkerSource(e2, t5.type, t5.source).getData()), this.actor.registerMessageHandler("LT", (e2, t5) => this._getWorkerSource(e2, t5.type, t5.source).loadTile(t5)), this.actor.registerMessageHandler("RT", (e2, t5) => this._getWorkerSource(e2, t5.type, t5.source).reloadTile(t5)), this.actor.registerMessageHandler("AT", (e2, t5) => this._getWorkerSource(e2, t5.type, t5.source).abortTile(t5)), this.actor.registerMessageHandler("RMT", (e2, t5) => this._getWorkerSource(e2, t5.type, t5.source).removeTile(t5)), this.actor.registerMessageHandler("RS", (t5, o2) => e._(this, void 0, void 0, function* () {
                if (!this.workerSources[t5] || !this.workerSources[t5][o2.type] || !this.workerSources[t5][o2.type][o2.source]) return;
                const e2 = this.workerSources[t5][o2.type][o2.source];
                delete this.workerSources[t5][o2.type][o2.source], void 0 !== e2.removeSource && e2.removeSource(o2);
              })), this.actor.registerMessageHandler("RM", (t5) => e._(this, void 0, void 0, function* () {
                delete this.layerIndexes[t5], delete this.availableImages[t5], delete this.workerSources[t5], delete this.demWorkerSources[t5];
              })), this.actor.registerMessageHandler("SR", (t5, o2) => e._(this, void 0, void 0, function* () {
                this.referrer = o2;
              })), this.actor.registerMessageHandler("SRPS", (e2, t5) => this._syncRTLPluginState(e2, t5)), this.actor.registerMessageHandler("IS", (t5, o2) => e._(this, void 0, void 0, function* () {
                this.self.importScripts(o2);
              })), this.actor.registerMessageHandler("SI", (e2, t5) => this._setImages(e2, t5)), this.actor.registerMessageHandler("UL", (t5, o2) => e._(this, void 0, void 0, function* () {
                this._getLayerIndex(t5).update(o2.layers, o2.removedIds);
              })), this.actor.registerMessageHandler("SL", (t5, o2) => e._(this, void 0, void 0, function* () {
                this._getLayerIndex(t5).replace(o2);
              }));
            }
            _setImages(t4, o2) {
              return e._(this, void 0, void 0, function* () {
                this.availableImages[t4] = o2;
                for (const e2 in this.workerSources[t4]) {
                  const i2 = this.workerSources[t4][e2];
                  for (const e3 in i2) i2[e3].availableImages = o2;
                }
              });
            }
            _syncRTLPluginState(t4, o2) {
              return e._(this, void 0, void 0, function* () {
                if (e.bD.isParsed()) return e.bD.getState();
                if ("loading" !== o2.pluginStatus) return e.bD.setState(o2), o2;
                const t5 = o2.pluginURL;
                if (this.self.importScripts(t5), e.bD.isParsed()) {
                  const o3 = { pluginStatus: "loaded", pluginURL: t5 };
                  return e.bD.setState(o3), o3;
                }
                throw e.bD.setState({ pluginStatus: "error", pluginURL: "" }), new Error(`RTL Text Plugin failed to import scripts from ${t5}`);
              });
            }
            _getAvailableImages(e2) {
              let t4 = this.availableImages[e2];
              return t4 || (t4 = []), t4;
            }
            _getLayerIndex(e2) {
              let o2 = this.layerIndexes[e2];
              return o2 || (o2 = this.layerIndexes[e2] = new t()), o2;
            }
            _getWorkerSource(e2, t4, o2) {
              if (this.workerSources[e2] || (this.workerSources[e2] = {}), this.workerSources[e2][t4] || (this.workerSources[e2][t4] = {}), !this.workerSources[e2][t4][o2]) {
                const i2 = { sendAsync: (t5, o3) => (t5.targetMapId = e2, this.actor.sendAsync(t5, o3)) };
                switch (t4) {
                  case "vector":
                    this.workerSources[e2][t4][o2] = new r(i2, this._getLayerIndex(e2), this._getAvailableImages(e2));
                    break;
                  case "geojson":
                    this.workerSources[e2][t4][o2] = new ye(i2, this._getLayerIndex(e2), this._getAvailableImages(e2));
                    break;
                  default:
                    this.workerSources[e2][t4][o2] = new this.externalWorkerSourceTypes[t4](i2, this._getLayerIndex(e2), this._getAvailableImages(e2));
                }
              }
              return this.workerSources[e2][t4][o2];
            }
            _getDEMWorkerSource(e2, t4) {
              return this.demWorkerSources[e2] || (this.demWorkerSources[e2] = {}), this.demWorkerSources[e2][t4] || (this.demWorkerSources[e2][t4] = new n()), this.demWorkerSources[e2][t4];
            }
          }
          return e.i(self) && (self.worker = new ve(self)), ve;
        });
        define2("index", ["exports", "./shared"], function(t, e) {
          "use strict";
          var i = "4.7.1";
          let a, s;
          const o = { now: "undefined" != typeof performance && performance && performance.now ? performance.now.bind(performance) : Date.now.bind(Date), frameAsync: (t4) => new Promise((i2, a2) => {
            const s2 = requestAnimationFrame(i2);
            t4.signal.addEventListener("abort", () => {
              cancelAnimationFrame(s2), a2(e.c());
            });
          }), getImageData(t4, e2 = 0) {
            return this.getImageCanvasContext(t4).getImageData(-e2, -e2, t4.width + 2 * e2, t4.height + 2 * e2);
          }, getImageCanvasContext(t4) {
            const e2 = window.document.createElement("canvas"), i2 = e2.getContext("2d", { willReadFrequently: true });
            if (!i2) throw new Error("failed to create canvas 2d context");
            return e2.width = t4.width, e2.height = t4.height, i2.drawImage(t4, 0, 0, t4.width, t4.height), i2;
          }, resolveURL: (t4) => (a || (a = document.createElement("a")), a.href = t4, a.href), hardwareConcurrency: "undefined" != typeof navigator && navigator.hardwareConcurrency || 4, get prefersReducedMotion() {
            return !!matchMedia && (null == s && (s = matchMedia("(prefers-reduced-motion: reduce)")), s.matches);
          } };
          class r {
            static testProp(t4) {
              if (!r.docStyle) return t4[0];
              for (let e2 = 0; e2 < t4.length; e2++) if (t4[e2] in r.docStyle) return t4[e2];
              return t4[0];
            }
            static create(t4, e2, i2) {
              const a2 = window.document.createElement(t4);
              return void 0 !== e2 && (a2.className = e2), i2 && i2.appendChild(a2), a2;
            }
            static createNS(t4, e2) {
              return window.document.createElementNS(t4, e2);
            }
            static disableDrag() {
              r.docStyle && r.selectProp && (r.userSelect = r.docStyle[r.selectProp], r.docStyle[r.selectProp] = "none");
            }
            static enableDrag() {
              r.docStyle && r.selectProp && (r.docStyle[r.selectProp] = r.userSelect);
            }
            static setTransform(t4, e2) {
              t4.style[r.transformProp] = e2;
            }
            static addEventListener(t4, e2, i2, a2 = {}) {
              t4.addEventListener(e2, i2, "passive" in a2 ? a2 : a2.capture);
            }
            static removeEventListener(t4, e2, i2, a2 = {}) {
              t4.removeEventListener(e2, i2, "passive" in a2 ? a2 : a2.capture);
            }
            static suppressClickInternal(t4) {
              t4.preventDefault(), t4.stopPropagation(), window.removeEventListener("click", r.suppressClickInternal, true);
            }
            static suppressClick() {
              window.addEventListener("click", r.suppressClickInternal, true), window.setTimeout(() => {
                window.removeEventListener("click", r.suppressClickInternal, true);
              }, 0);
            }
            static getScale(t4) {
              const e2 = t4.getBoundingClientRect();
              return { x: e2.width / t4.offsetWidth || 1, y: e2.height / t4.offsetHeight || 1, boundingClientRect: e2 };
            }
            static getPoint(t4, i2, a2) {
              const s2 = i2.boundingClientRect;
              return new e.P((a2.clientX - s2.left) / i2.x - t4.clientLeft, (a2.clientY - s2.top) / i2.y - t4.clientTop);
            }
            static mousePos(t4, e2) {
              const i2 = r.getScale(t4);
              return r.getPoint(t4, i2, e2);
            }
            static touchPos(t4, e2) {
              const i2 = [], a2 = r.getScale(t4);
              for (let s2 = 0; s2 < e2.length; s2++) i2.push(r.getPoint(t4, a2, e2[s2]));
              return i2;
            }
            static mouseButton(t4) {
              return t4.button;
            }
            static remove(t4) {
              t4.parentNode && t4.parentNode.removeChild(t4);
            }
          }
          r.docStyle = "undefined" != typeof window && window.document && window.document.documentElement.style, r.selectProp = r.testProp(["userSelect", "MozUserSelect", "WebkitUserSelect", "msUserSelect"]), r.transformProp = r.testProp(["transform", "WebkitTransform"]);
          const n = { supported: false, testSupport: function(t4) {
            !c && h && (u ? d(t4) : l = t4);
          } };
          let l, h, c = false, u = false;
          function d(t4) {
            const e2 = t4.createTexture();
            t4.bindTexture(t4.TEXTURE_2D, e2);
            try {
              if (t4.texImage2D(t4.TEXTURE_2D, 0, t4.RGBA, t4.RGBA, t4.UNSIGNED_BYTE, h), t4.isContextLost()) return;
              n.supported = true;
            } catch (t5) {
            }
            t4.deleteTexture(e2), c = true;
          }
          var _;
          "undefined" != typeof document && (h = document.createElement("img"), h.onload = () => {
            l && d(l), l = null, u = true;
          }, h.onerror = () => {
            c = true, l = null;
          }, h.src = "data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="), function(t4) {
            let i2, a2, s2, o2;
            t4.resetRequestQueue = () => {
              i2 = [], a2 = 0, s2 = 0, o2 = {};
            }, t4.addThrottleControl = (t5) => {
              const e2 = s2++;
              return o2[e2] = t5, e2;
            }, t4.removeThrottleControl = (t5) => {
              delete o2[t5], l2();
            }, t4.getImage = (t5, a3, s3 = true) => new Promise((o3, r3) => {
              n.supported && (t5.headers || (t5.headers = {}), t5.headers.accept = "image/webp,*/*"), e.e(t5, { type: "image" }), i2.push({ abortController: a3, requestParameters: t5, supportImageRefresh: s3, state: "queued", onError: (t6) => {
                r3(t6);
              }, onSuccess: (t6) => {
                o3(t6);
              } }), l2();
            });
            const r2 = (t5) => e._(this, void 0, void 0, function* () {
              t5.state = "running";
              const { requestParameters: i3, supportImageRefresh: s3, onError: o3, onSuccess: r3, abortController: n2 } = t5, c2 = false === s3 && !e.i(self) && !e.g(i3.url) && (!i3.headers || Object.keys(i3.headers).reduce((t6, e2) => t6 && "accept" === e2, true));
              a2++;
              const u2 = c2 ? h2(i3, n2) : e.m(i3, n2);
              try {
                const i4 = yield u2;
                delete t5.abortController, t5.state = "completed", i4.data instanceof HTMLImageElement || e.b(i4.data) ? r3(i4) : i4.data && r3({ data: yield (d2 = i4.data, "function" == typeof createImageBitmap ? e.d(d2) : e.f(d2)), cacheControl: i4.cacheControl, expires: i4.expires });
              } catch (e2) {
                delete t5.abortController, o3(e2);
              } finally {
                a2--, l2();
              }
              var d2;
            }), l2 = () => {
              const t5 = (() => {
                for (const t6 of Object.keys(o2)) if (o2[t6]()) return true;
                return false;
              })() ? e.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME : e.a.MAX_PARALLEL_IMAGE_REQUESTS;
              for (let e2 = a2; e2 < t5 && i2.length > 0; e2++) {
                const t6 = i2.shift();
                t6.abortController.signal.aborted ? e2-- : r2(t6);
              }
            }, h2 = (t5, i3) => new Promise((a3, s3) => {
              const o3 = new Image(), r3 = t5.url, n2 = t5.credentials;
              n2 && "include" === n2 ? o3.crossOrigin = "use-credentials" : (n2 && "same-origin" === n2 || !e.s(r3)) && (o3.crossOrigin = "anonymous"), i3.signal.addEventListener("abort", () => {
                o3.src = "", s3(e.c());
              }), o3.fetchPriority = "high", o3.onload = () => {
                o3.onerror = o3.onload = null, a3({ data: o3 });
              }, o3.onerror = () => {
                o3.onerror = o3.onload = null, i3.signal.aborted || s3(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));
              }, o3.src = r3;
            });
          }(_ || (_ = {})), _.resetRequestQueue();
          class p {
            constructor(t4) {
              this._transformRequestFn = t4;
            }
            transformRequest(t4, e2) {
              return this._transformRequestFn && this._transformRequestFn(t4, e2) || { url: t4 };
            }
            setTransformRequest(t4) {
              this._transformRequestFn = t4;
            }
          }
          function m(t4) {
            var i2 = new e.A(3);
            return i2[0] = t4[0], i2[1] = t4[1], i2[2] = t4[2], i2;
          }
          var f, g = function(t4, e2, i2) {
            return t4[0] = e2[0] - i2[0], t4[1] = e2[1] - i2[1], t4[2] = e2[2] - i2[2], t4;
          };
          f = new e.A(3), e.A != Float32Array && (f[0] = 0, f[1] = 0, f[2] = 0);
          var v = function(t4) {
            var e2 = t4[0], i2 = t4[1];
            return e2 * e2 + i2 * i2;
          };
          function x(t4) {
            const e2 = [];
            if ("string" == typeof t4) e2.push({ id: "default", url: t4 });
            else if (t4 && t4.length > 0) {
              const i2 = [];
              for (const { id: a2, url: s2 } of t4) {
                const t5 = `${a2}${s2}`;
                -1 === i2.indexOf(t5) && (i2.push(t5), e2.push({ id: a2, url: s2 }));
              }
            }
            return e2;
          }
          function y(t4, e2, i2) {
            const a2 = t4.split("?");
            return a2[0] += `${e2}${i2}`, a2.join("?");
          }
          !function() {
            var t4 = new e.A(2);
            e.A != Float32Array && (t4[0] = 0, t4[1] = 0);
          }();
          class b {
            constructor(t4, e2, i2, a2) {
              this.context = t4, this.format = i2, this.texture = t4.gl.createTexture(), this.update(e2, a2);
            }
            update(t4, i2, a2) {
              const { width: s2, height: o2 } = t4, r2 = !(this.size && this.size[0] === s2 && this.size[1] === o2 || a2), { context: n2 } = this, { gl: l2 } = n2;
              if (this.useMipmap = Boolean(i2 && i2.useMipmap), l2.bindTexture(l2.TEXTURE_2D, this.texture), n2.pixelStoreUnpackFlipY.set(false), n2.pixelStoreUnpack.set(1), n2.pixelStoreUnpackPremultiplyAlpha.set(this.format === l2.RGBA && (!i2 || false !== i2.premultiply)), r2) this.size = [s2, o2], t4 instanceof HTMLImageElement || t4 instanceof HTMLCanvasElement || t4 instanceof HTMLVideoElement || t4 instanceof ImageData || e.b(t4) ? l2.texImage2D(l2.TEXTURE_2D, 0, this.format, this.format, l2.UNSIGNED_BYTE, t4) : l2.texImage2D(l2.TEXTURE_2D, 0, this.format, s2, o2, 0, this.format, l2.UNSIGNED_BYTE, t4.data);
              else {
                const { x: i3, y: r3 } = a2 || { x: 0, y: 0 };
                t4 instanceof HTMLImageElement || t4 instanceof HTMLCanvasElement || t4 instanceof HTMLVideoElement || t4 instanceof ImageData || e.b(t4) ? l2.texSubImage2D(l2.TEXTURE_2D, 0, i3, r3, l2.RGBA, l2.UNSIGNED_BYTE, t4) : l2.texSubImage2D(l2.TEXTURE_2D, 0, i3, r3, s2, o2, l2.RGBA, l2.UNSIGNED_BYTE, t4.data);
              }
              this.useMipmap && this.isSizePowerOfTwo() && l2.generateMipmap(l2.TEXTURE_2D);
            }
            bind(t4, e2, i2) {
              const { context: a2 } = this, { gl: s2 } = a2;
              s2.bindTexture(s2.TEXTURE_2D, this.texture), i2 !== s2.LINEAR_MIPMAP_NEAREST || this.isSizePowerOfTwo() || (i2 = s2.LINEAR), t4 !== this.filter && (s2.texParameteri(s2.TEXTURE_2D, s2.TEXTURE_MAG_FILTER, t4), s2.texParameteri(s2.TEXTURE_2D, s2.TEXTURE_MIN_FILTER, i2 || t4), this.filter = t4), e2 !== this.wrap && (s2.texParameteri(s2.TEXTURE_2D, s2.TEXTURE_WRAP_S, e2), s2.texParameteri(s2.TEXTURE_2D, s2.TEXTURE_WRAP_T, e2), this.wrap = e2);
            }
            isSizePowerOfTwo() {
              return this.size[0] === this.size[1] && Math.log(this.size[0]) / Math.LN2 % 1 == 0;
            }
            destroy() {
              const { gl: t4 } = this.context;
              t4.deleteTexture(this.texture), this.texture = null;
            }
          }
          function w(t4) {
            const { userImage: e2 } = t4;
            return !!(e2 && e2.render && e2.render()) && (t4.data.replace(new Uint8Array(e2.data.buffer)), true);
          }
          class T extends e.E {
            constructor() {
              super(), this.images = {}, this.updatedImages = {}, this.callbackDispatchedThisFrame = {}, this.loaded = false, this.requestors = [], this.patterns = {}, this.atlasImage = new e.R({ width: 1, height: 1 }), this.dirty = true;
            }
            isLoaded() {
              return this.loaded;
            }
            setLoaded(t4) {
              if (this.loaded !== t4 && (this.loaded = t4, t4)) {
                for (const { ids: t5, promiseResolve: e2 } of this.requestors) e2(this._getImagesForIds(t5));
                this.requestors = [];
              }
            }
            getImage(t4) {
              const i2 = this.images[t4];
              if (i2 && !i2.data && i2.spriteData) {
                const t5 = i2.spriteData;
                i2.data = new e.R({ width: t5.width, height: t5.height }, t5.context.getImageData(t5.x, t5.y, t5.width, t5.height).data), i2.spriteData = null;
              }
              return i2;
            }
            addImage(t4, e2) {
              if (this.images[t4]) throw new Error(`Image id ${t4} already exist, use updateImage instead`);
              this._validate(t4, e2) && (this.images[t4] = e2);
            }
            _validate(t4, i2) {
              let a2 = true;
              const s2 = i2.data || i2.spriteData;
              return this._validateStretch(i2.stretchX, s2 && s2.width) || (this.fire(new e.j(new Error(`Image "${t4}" has invalid "stretchX" value`))), a2 = false), this._validateStretch(i2.stretchY, s2 && s2.height) || (this.fire(new e.j(new Error(`Image "${t4}" has invalid "stretchY" value`))), a2 = false), this._validateContent(i2.content, i2) || (this.fire(new e.j(new Error(`Image "${t4}" has invalid "content" value`))), a2 = false), a2;
            }
            _validateStretch(t4, e2) {
              if (!t4) return true;
              let i2 = 0;
              for (const a2 of t4) {
                if (a2[0] < i2 || a2[1] < a2[0] || e2 < a2[1]) return false;
                i2 = a2[1];
              }
              return true;
            }
            _validateContent(t4, e2) {
              if (!t4) return true;
              if (4 !== t4.length) return false;
              const i2 = e2.spriteData, a2 = i2 && i2.width || e2.data.width, s2 = i2 && i2.height || e2.data.height;
              return !(t4[0] < 0 || a2 < t4[0] || t4[1] < 0 || s2 < t4[1] || t4[2] < 0 || a2 < t4[2] || t4[3] < 0 || s2 < t4[3] || t4[2] < t4[0] || t4[3] < t4[1]);
            }
            updateImage(t4, e2, i2 = true) {
              const a2 = this.getImage(t4);
              if (i2 && (a2.data.width !== e2.data.width || a2.data.height !== e2.data.height)) throw new Error(`size mismatch between old image (${a2.data.width}x${a2.data.height}) and new image (${e2.data.width}x${e2.data.height}).`);
              e2.version = a2.version + 1, this.images[t4] = e2, this.updatedImages[t4] = true;
            }
            removeImage(t4) {
              const e2 = this.images[t4];
              delete this.images[t4], delete this.patterns[t4], e2.userImage && e2.userImage.onRemove && e2.userImage.onRemove();
            }
            listImages() {
              return Object.keys(this.images);
            }
            getImages(t4) {
              return new Promise((e2, i2) => {
                let a2 = true;
                if (!this.isLoaded()) for (const e3 of t4) this.images[e3] || (a2 = false);
                this.isLoaded() || a2 ? e2(this._getImagesForIds(t4)) : this.requestors.push({ ids: t4, promiseResolve: e2 });
              });
            }
            _getImagesForIds(t4) {
              const i2 = {};
              for (const a2 of t4) {
                let t5 = this.getImage(a2);
                t5 || (this.fire(new e.k("styleimagemissing", { id: a2 })), t5 = this.getImage(a2)), t5 ? i2[a2] = { data: t5.data.clone(), pixelRatio: t5.pixelRatio, sdf: t5.sdf, version: t5.version, stretchX: t5.stretchX, stretchY: t5.stretchY, content: t5.content, textFitWidth: t5.textFitWidth, textFitHeight: t5.textFitHeight, hasRenderCallback: Boolean(t5.userImage && t5.userImage.render) } : e.w(`Image "${a2}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);
              }
              return i2;
            }
            getPixelSize() {
              const { width: t4, height: e2 } = this.atlasImage;
              return { width: t4, height: e2 };
            }
            getPattern(t4) {
              const i2 = this.patterns[t4], a2 = this.getImage(t4);
              if (!a2) return null;
              if (i2 && i2.position.version === a2.version) return i2.position;
              if (i2) i2.position.version = a2.version;
              else {
                const i3 = { w: a2.data.width + 2, h: a2.data.height + 2, x: 0, y: 0 }, s2 = new e.I(i3, a2);
                this.patterns[t4] = { bin: i3, position: s2 };
              }
              return this._updatePatternAtlas(), this.patterns[t4].position;
            }
            bind(t4) {
              const e2 = t4.gl;
              this.atlasTexture ? this.dirty && (this.atlasTexture.update(this.atlasImage), this.dirty = false) : this.atlasTexture = new b(t4, this.atlasImage, e2.RGBA), this.atlasTexture.bind(e2.LINEAR, e2.CLAMP_TO_EDGE);
            }
            _updatePatternAtlas() {
              const t4 = [];
              for (const e2 in this.patterns) t4.push(this.patterns[e2].bin);
              const { w: i2, h: a2 } = e.p(t4), s2 = this.atlasImage;
              s2.resize({ width: i2 || 1, height: a2 || 1 });
              for (const t5 in this.patterns) {
                const { bin: i3 } = this.patterns[t5], a3 = i3.x + 1, o2 = i3.y + 1, r2 = this.getImage(t5).data, n2 = r2.width, l2 = r2.height;
                e.R.copy(r2, s2, { x: 0, y: 0 }, { x: a3, y: o2 }, { width: n2, height: l2 }), e.R.copy(r2, s2, { x: 0, y: l2 - 1 }, { x: a3, y: o2 - 1 }, { width: n2, height: 1 }), e.R.copy(r2, s2, { x: 0, y: 0 }, { x: a3, y: o2 + l2 }, { width: n2, height: 1 }), e.R.copy(r2, s2, { x: n2 - 1, y: 0 }, { x: a3 - 1, y: o2 }, { width: 1, height: l2 }), e.R.copy(r2, s2, { x: 0, y: 0 }, { x: a3 + n2, y: o2 }, { width: 1, height: l2 });
              }
              this.dirty = true;
            }
            beginFrame() {
              this.callbackDispatchedThisFrame = {};
            }
            dispatchRenderCallbacks(t4) {
              for (const i2 of t4) {
                if (this.callbackDispatchedThisFrame[i2]) continue;
                this.callbackDispatchedThisFrame[i2] = true;
                const t5 = this.getImage(i2);
                t5 || e.w(`Image with ID: "${i2}" was not found`), w(t5) && this.updateImage(i2, t5);
              }
            }
          }
          const I = 1e20;
          function E2(t4, e2, i2, a2, s2, o2, r2, n2, l2) {
            for (let h2 = e2; h2 < e2 + a2; h2++) P(t4, i2 * o2 + h2, o2, s2, r2, n2, l2);
            for (let h2 = i2; h2 < i2 + s2; h2++) P(t4, h2 * o2 + e2, 1, a2, r2, n2, l2);
          }
          function P(t4, e2, i2, a2, s2, o2, r2) {
            o2[0] = 0, r2[0] = -I, r2[1] = I, s2[0] = t4[e2];
            for (let n2 = 1, l2 = 0, h2 = 0; n2 < a2; n2++) {
              s2[n2] = t4[e2 + n2 * i2];
              const a3 = n2 * n2;
              do {
                const t5 = o2[l2];
                h2 = (s2[n2] - s2[t5] + a3 - t5 * t5) / (n2 - t5) / 2;
              } while (h2 <= r2[l2] && --l2 > -1);
              l2++, o2[l2] = n2, r2[l2] = h2, r2[l2 + 1] = I;
            }
            for (let n2 = 0, l2 = 0; n2 < a2; n2++) {
              for (; r2[l2 + 1] < n2; ) l2++;
              const a3 = o2[l2], h2 = n2 - a3;
              t4[e2 + n2 * i2] = s2[a3] + h2 * h2;
            }
          }
          class C2 {
            constructor(t4, e2) {
              this.requestManager = t4, this.localIdeographFontFamily = e2, this.entries = {};
            }
            setURL(t4) {
              this.url = t4;
            }
            getGlyphs(t4) {
              return e._(this, void 0, void 0, function* () {
                const e2 = [];
                for (const i3 in t4) for (const a3 of t4[i3]) e2.push(this._getAndCacheGlyphsPromise(i3, a3));
                const i2 = yield Promise.all(e2), a2 = {};
                for (const { stack: t5, id: e3, glyph: s2 } of i2) a2[t5] || (a2[t5] = {}), a2[t5][e3] = s2 && { id: s2.id, bitmap: s2.bitmap.clone(), metrics: s2.metrics };
                return a2;
              });
            }
            _getAndCacheGlyphsPromise(t4, i2) {
              return e._(this, void 0, void 0, function* () {
                let e2 = this.entries[t4];
                e2 || (e2 = this.entries[t4] = { glyphs: {}, requests: {}, ranges: {} });
                let a2 = e2.glyphs[i2];
                if (void 0 !== a2) return { stack: t4, id: i2, glyph: a2 };
                if (a2 = this._tinySDF(e2, t4, i2), a2) return e2.glyphs[i2] = a2, { stack: t4, id: i2, glyph: a2 };
                const s2 = Math.floor(i2 / 256);
                if (256 * s2 > 65535) throw new Error("glyphs > 65535 not supported");
                if (e2.ranges[s2]) return { stack: t4, id: i2, glyph: a2 };
                if (!this.url) throw new Error("glyphsUrl is not set");
                if (!e2.requests[s2]) {
                  const i3 = C2.loadGlyphRange(t4, s2, this.url, this.requestManager);
                  e2.requests[s2] = i3;
                }
                const o2 = yield e2.requests[s2];
                for (const t5 in o2) this._doesCharSupportLocalGlyph(+t5) || (e2.glyphs[+t5] = o2[+t5]);
                return e2.ranges[s2] = true, { stack: t4, id: i2, glyph: o2[i2] || null };
              });
            }
            _doesCharSupportLocalGlyph(t4) {
              return !!this.localIdeographFontFamily && new RegExp("\\p{Ideo}|\\p{sc=Hang}|\\p{sc=Hira}|\\p{sc=Kana}", "u").test(String.fromCodePoint(t4));
            }
            _tinySDF(t4, i2, a2) {
              const s2 = this.localIdeographFontFamily;
              if (!s2) return;
              if (!this._doesCharSupportLocalGlyph(a2)) return;
              let o2 = t4.tinySDF;
              if (!o2) {
                let e2 = "400";
                /bold/i.test(i2) ? e2 = "900" : /medium/i.test(i2) ? e2 = "500" : /light/i.test(i2) && (e2 = "200"), o2 = t4.tinySDF = new C2.TinySDF({ fontSize: 48, buffer: 6, radius: 16, cutoff: 0.25, fontFamily: s2, fontWeight: e2 });
              }
              const r2 = o2.draw(String.fromCharCode(a2));
              return { id: a2, bitmap: new e.o({ width: r2.width || 60, height: r2.height || 60 }, r2.data), metrics: { width: r2.glyphWidth / 2 || 24, height: r2.glyphHeight / 2 || 24, left: r2.glyphLeft / 2 + 0.5 || 0, top: r2.glyphTop / 2 - 27.5 || -8, advance: r2.glyphAdvance / 2 || 24, isDoubleResolution: true } };
            }
          }
          C2.loadGlyphRange = function(t4, i2, a2, s2) {
            return e._(this, void 0, void 0, function* () {
              const o2 = 256 * i2, r2 = o2 + 255, n2 = s2.transformRequest(a2.replace("{fontstack}", t4).replace("{range}", `${o2}-${r2}`), "Glyphs"), l2 = yield e.l(n2, new AbortController());
              if (!l2 || !l2.data) throw new Error(`Could not load glyph range. range: ${i2}, ${o2}-${r2}`);
              const h2 = {};
              for (const t5 of e.n(l2.data)) h2[t5.id] = t5;
              return h2;
            });
          }, C2.TinySDF = class {
            constructor({ fontSize: t4 = 24, buffer: e2 = 3, radius: i2 = 8, cutoff: a2 = 0.25, fontFamily: s2 = "sans-serif", fontWeight: o2 = "normal", fontStyle: r2 = "normal" } = {}) {
              this.buffer = e2, this.cutoff = a2, this.radius = i2;
              const n2 = this.size = t4 + 4 * e2, l2 = this._createCanvas(n2), h2 = this.ctx = l2.getContext("2d", { willReadFrequently: true });
              h2.font = `${r2} ${o2} ${t4}px ${s2}`, h2.textBaseline = "alphabetic", h2.textAlign = "left", h2.fillStyle = "black", this.gridOuter = new Float64Array(n2 * n2), this.gridInner = new Float64Array(n2 * n2), this.f = new Float64Array(n2), this.z = new Float64Array(n2 + 1), this.v = new Uint16Array(n2);
            }
            _createCanvas(t4) {
              const e2 = document.createElement("canvas");
              return e2.width = e2.height = t4, e2;
            }
            draw(t4) {
              const { width: e2, actualBoundingBoxAscent: i2, actualBoundingBoxDescent: a2, actualBoundingBoxLeft: s2, actualBoundingBoxRight: o2 } = this.ctx.measureText(t4), r2 = Math.ceil(i2), n2 = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(o2 - s2))), l2 = Math.min(this.size - this.buffer, r2 + Math.ceil(a2)), h2 = n2 + 2 * this.buffer, c2 = l2 + 2 * this.buffer, u2 = Math.max(h2 * c2, 0), d2 = new Uint8ClampedArray(u2), _2 = { data: d2, width: h2, height: c2, glyphWidth: n2, glyphHeight: l2, glyphTop: r2, glyphLeft: 0, glyphAdvance: e2 };
              if (0 === n2 || 0 === l2) return _2;
              const { ctx: p2, buffer: m2, gridInner: f2, gridOuter: g2 } = this;
              p2.clearRect(m2, m2, n2, l2), p2.fillText(t4, m2, m2 + r2);
              const v2 = p2.getImageData(m2, m2, n2, l2);
              g2.fill(I, 0, u2), f2.fill(0, 0, u2);
              for (let t5 = 0; t5 < l2; t5++) for (let e3 = 0; e3 < n2; e3++) {
                const i3 = v2.data[4 * (t5 * n2 + e3) + 3] / 255;
                if (0 === i3) continue;
                const a3 = (t5 + m2) * h2 + e3 + m2;
                if (1 === i3) g2[a3] = 0, f2[a3] = I;
                else {
                  const t6 = 0.5 - i3;
                  g2[a3] = t6 > 0 ? t6 * t6 : 0, f2[a3] = t6 < 0 ? t6 * t6 : 0;
                }
              }
              E2(g2, 0, 0, h2, c2, h2, this.f, this.v, this.z), E2(f2, m2, m2, n2, l2, h2, this.f, this.v, this.z);
              for (let t5 = 0; t5 < u2; t5++) {
                const e3 = Math.sqrt(g2[t5]) - Math.sqrt(f2[t5]);
                d2[t5] = Math.round(255 - 255 * (e3 / this.radius + this.cutoff));
              }
              return _2;
            }
          };
          class S {
            constructor() {
              this.specification = e.v.light.position;
            }
            possiblyEvaluate(t4, i2) {
              return e.x(t4.expression.evaluate(i2));
            }
            interpolate(t4, i2, a2) {
              return { x: e.y.number(t4.x, i2.x, a2), y: e.y.number(t4.y, i2.y, a2), z: e.y.number(t4.z, i2.z, a2) };
            }
          }
          let z;
          class D2 extends e.E {
            constructor(t4) {
              super(), z = z || new e.q({ anchor: new e.D(e.v.light.anchor), position: new S(), color: new e.D(e.v.light.color), intensity: new e.D(e.v.light.intensity) }), this._transitionable = new e.T(z), this.setLight(t4), this._transitioning = this._transitionable.untransitioned();
            }
            getLight() {
              return this._transitionable.serialize();
            }
            setLight(t4, i2 = {}) {
              if (!this._validate(e.r, t4, i2)) for (const e2 in t4) {
                const i3 = t4[e2];
                e2.endsWith("-transition") ? this._transitionable.setTransition(e2.slice(0, -11), i3) : this._transitionable.setValue(e2, i3);
              }
            }
            updateTransitions(t4) {
              this._transitioning = this._transitionable.transitioned(t4, this._transitioning);
            }
            hasTransition() {
              return this._transitioning.hasTransition();
            }
            recalculate(t4) {
              this.properties = this._transitioning.possiblyEvaluate(t4);
            }
            _validate(t4, i2, a2) {
              return (!a2 || false !== a2.validate) && e.t(this, t4.call(e.u, { value: i2, style: { glyphs: true, sprite: true }, styleSpec: e.v }));
            }
          }
          const M = new e.q({ "sky-color": new e.D(e.v.sky["sky-color"]), "horizon-color": new e.D(e.v.sky["horizon-color"]), "fog-color": new e.D(e.v.sky["fog-color"]), "fog-ground-blend": new e.D(e.v.sky["fog-ground-blend"]), "horizon-fog-blend": new e.D(e.v.sky["horizon-fog-blend"]), "sky-horizon-blend": new e.D(e.v.sky["sky-horizon-blend"]), "atmosphere-blend": new e.D(e.v.sky["atmosphere-blend"]) });
          class A2 extends e.E {
            constructor(t4) {
              super(), this._transitionable = new e.T(M), this.setSky(t4), this._transitioning = this._transitionable.untransitioned(), this.recalculate(new e.z(0));
            }
            setSky(t4, i2 = {}) {
              if (!this._validate(e.B, t4, i2)) {
                t4 || (t4 = { "sky-color": "transparent", "horizon-color": "transparent", "fog-color": "transparent", "fog-ground-blend": 1, "atmosphere-blend": 0 });
                for (const e2 in t4) {
                  const i3 = t4[e2];
                  e2.endsWith("-transition") ? this._transitionable.setTransition(e2.slice(0, -11), i3) : this._transitionable.setValue(e2, i3);
                }
              }
            }
            getSky() {
              return this._transitionable.serialize();
            }
            updateTransitions(t4) {
              this._transitioning = this._transitionable.transitioned(t4, this._transitioning);
            }
            hasTransition() {
              return this._transitioning.hasTransition();
            }
            recalculate(t4) {
              this.properties = this._transitioning.possiblyEvaluate(t4);
            }
            _validate(t4, i2, a2 = {}) {
              return false !== (null == a2 ? void 0 : a2.validate) && e.t(this, t4.call(e.u, e.e({ value: i2, style: { glyphs: true, sprite: true }, styleSpec: e.v })));
            }
            calculateFogBlendOpacity(t4) {
              return t4 < 60 ? 0 : t4 < 70 ? (t4 - 60) / 10 : 1;
            }
          }
          class R {
            constructor(t4, e2) {
              this.width = t4, this.height = e2, this.nextRow = 0, this.data = new Uint8Array(this.width * this.height), this.dashEntry = {};
            }
            getDash(t4, e2) {
              const i2 = t4.join(",") + String(e2);
              return this.dashEntry[i2] || (this.dashEntry[i2] = this.addDash(t4, e2)), this.dashEntry[i2];
            }
            getDashRanges(t4, e2, i2) {
              const a2 = [];
              let s2 = t4.length % 2 == 1 ? -t4[t4.length - 1] * i2 : 0, o2 = t4[0] * i2, r2 = true;
              a2.push({ left: s2, right: o2, isDash: r2, zeroLength: 0 === t4[0] });
              let n2 = t4[0];
              for (let e3 = 1; e3 < t4.length; e3++) {
                r2 = !r2;
                const l2 = t4[e3];
                s2 = n2 * i2, n2 += l2, o2 = n2 * i2, a2.push({ left: s2, right: o2, isDash: r2, zeroLength: 0 === l2 });
              }
              return a2;
            }
            addRoundDash(t4, e2, i2) {
              const a2 = e2 / 2;
              for (let e3 = -i2; e3 <= i2; e3++) {
                const s2 = this.width * (this.nextRow + i2 + e3);
                let o2 = 0, r2 = t4[o2];
                for (let n2 = 0; n2 < this.width; n2++) {
                  n2 / r2.right > 1 && (r2 = t4[++o2]);
                  const l2 = Math.abs(n2 - r2.left), h2 = Math.abs(n2 - r2.right), c2 = Math.min(l2, h2);
                  let u2;
                  const d2 = e3 / i2 * (a2 + 1);
                  if (r2.isDash) {
                    const t5 = a2 - Math.abs(d2);
                    u2 = Math.sqrt(c2 * c2 + t5 * t5);
                  } else u2 = a2 - Math.sqrt(c2 * c2 + d2 * d2);
                  this.data[s2 + n2] = Math.max(0, Math.min(255, u2 + 128));
                }
              }
            }
            addRegularDash(t4) {
              for (let e3 = t4.length - 1; e3 >= 0; --e3) {
                const i3 = t4[e3], a3 = t4[e3 + 1];
                i3.zeroLength ? t4.splice(e3, 1) : a3 && a3.isDash === i3.isDash && (a3.left = i3.left, t4.splice(e3, 1));
              }
              const e2 = t4[0], i2 = t4[t4.length - 1];
              e2.isDash === i2.isDash && (e2.left = i2.left - this.width, i2.right = e2.right + this.width);
              const a2 = this.width * this.nextRow;
              let s2 = 0, o2 = t4[s2];
              for (let e3 = 0; e3 < this.width; e3++) {
                e3 / o2.right > 1 && (o2 = t4[++s2]);
                const i3 = Math.abs(e3 - o2.left), r2 = Math.abs(e3 - o2.right), n2 = Math.min(i3, r2);
                this.data[a2 + e3] = Math.max(0, Math.min(255, (o2.isDash ? n2 : -n2) + 128));
              }
            }
            addDash(t4, i2) {
              const a2 = i2 ? 7 : 0, s2 = 2 * a2 + 1;
              if (this.nextRow + s2 > this.height) return e.w("LineAtlas out of space"), null;
              let o2 = 0;
              for (let e2 = 0; e2 < t4.length; e2++) o2 += t4[e2];
              if (0 !== o2) {
                const e2 = this.width / o2, s3 = this.getDashRanges(t4, this.width, e2);
                i2 ? this.addRoundDash(s3, e2, a2) : this.addRegularDash(s3);
              }
              const r2 = { y: (this.nextRow + a2 + 0.5) / this.height, height: 2 * a2 / this.height, width: o2 };
              return this.nextRow += s2, this.dirty = true, r2;
            }
            bind(t4) {
              const e2 = t4.gl;
              this.texture ? (e2.bindTexture(e2.TEXTURE_2D, this.texture), this.dirty && (this.dirty = false, e2.texSubImage2D(e2.TEXTURE_2D, 0, 0, 0, this.width, this.height, e2.ALPHA, e2.UNSIGNED_BYTE, this.data))) : (this.texture = e2.createTexture(), e2.bindTexture(e2.TEXTURE_2D, this.texture), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_WRAP_S, e2.REPEAT), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_WRAP_T, e2.REPEAT), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_MIN_FILTER, e2.LINEAR), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_MAG_FILTER, e2.LINEAR), e2.texImage2D(e2.TEXTURE_2D, 0, e2.ALPHA, this.width, this.height, 0, e2.ALPHA, e2.UNSIGNED_BYTE, this.data));
            }
          }
          const k = "maplibre_preloaded_worker_pool";
          class L {
            constructor() {
              this.active = {};
            }
            acquire(t4) {
              if (!this.workers) for (this.workers = []; this.workers.length < L.workerCount; ) this.workers.push(new Worker(e.a.WORKER_URL));
              return this.active[t4] = true, this.workers.slice();
            }
            release(t4) {
              delete this.active[t4], 0 === this.numActive() && (this.workers.forEach((t5) => {
                t5.terminate();
              }), this.workers = null);
            }
            isPreloaded() {
              return !!this.active[k];
            }
            numActive() {
              return Object.keys(this.active).length;
            }
          }
          const F = Math.floor(o.hardwareConcurrency / 2);
          let B2, O;
          function N() {
            return B2 || (B2 = new L()), B2;
          }
          L.workerCount = e.C(globalThis) ? Math.max(Math.min(F, 3), 1) : 1;
          class U {
            constructor(t4, i2) {
              this.workerPool = t4, this.actors = [], this.currentActor = 0, this.id = i2;
              const a2 = this.workerPool.acquire(i2);
              for (let t5 = 0; t5 < a2.length; t5++) {
                const s2 = new e.F(a2[t5], i2);
                s2.name = `Worker ${t5}`, this.actors.push(s2);
              }
              if (!this.actors.length) throw new Error("No actors found");
            }
            broadcast(t4, e2) {
              const i2 = [];
              for (const a2 of this.actors) i2.push(a2.sendAsync({ type: t4, data: e2 }));
              return Promise.all(i2);
            }
            getActor() {
              return this.currentActor = (this.currentActor + 1) % this.actors.length, this.actors[this.currentActor];
            }
            remove(t4 = true) {
              this.actors.forEach((t5) => {
                t5.remove();
              }), this.actors = [], t4 && this.workerPool.release(this.id);
            }
            registerMessageHandler(t4, e2) {
              for (const i2 of this.actors) i2.registerMessageHandler(t4, e2);
            }
          }
          function j() {
            return O || (O = new U(N(), e.G), O.registerMessageHandler("GR", (t4, i2, a2) => e.m(i2, a2))), O;
          }
          function Z(t4, i2) {
            const a2 = e.H();
            return e.J(a2, a2, [1, 1, 0]), e.K(a2, a2, [0.5 * t4.width, 0.5 * t4.height, 1]), e.L(a2, a2, t4.calculatePosMatrix(i2.toUnwrapped()));
          }
          function q(t4, e2, i2, a2, s2, o2) {
            const r2 = function(t5, e3, i3) {
              if (t5) for (const a3 of t5) {
                const t6 = e3[a3];
                if (t6 && t6.source === i3 && "fill-extrusion" === t6.type) return true;
              }
              else for (const t6 in e3) {
                const a3 = e3[t6];
                if (a3.source === i3 && "fill-extrusion" === a3.type) return true;
              }
              return false;
            }(s2 && s2.layers, e2, t4.id), n2 = o2.maxPitchScaleFactor(), l2 = t4.tilesIn(a2, n2, r2);
            l2.sort(V);
            const h2 = [];
            for (const a3 of l2) h2.push({ wrappedTileID: a3.tileID.wrapped().key, queryResults: a3.tile.queryRenderedFeatures(e2, i2, t4._state, a3.queryGeometry, a3.cameraQueryGeometry, a3.scale, s2, o2, n2, Z(t4.transform, a3.tileID)) });
            const c2 = function(t5) {
              const e3 = {}, i3 = {};
              for (const a3 of t5) {
                const t6 = a3.queryResults, s3 = a3.wrappedTileID, o3 = i3[s3] = i3[s3] || {};
                for (const i4 in t6) {
                  const a4 = t6[i4], s4 = o3[i4] = o3[i4] || {}, r3 = e3[i4] = e3[i4] || [];
                  for (const t7 of a4) s4[t7.featureIndex] || (s4[t7.featureIndex] = true, r3.push(t7));
                }
              }
              return e3;
            }(h2);
            for (const e3 in c2) c2[e3].forEach((e4) => {
              const i3 = e4.feature, a3 = t4.getFeatureState(i3.layer["source-layer"], i3.id);
              i3.source = i3.layer.source, i3.layer["source-layer"] && (i3.sourceLayer = i3.layer["source-layer"]), i3.state = a3;
            });
            return c2;
          }
          function V(t4, e2) {
            const i2 = t4.tileID, a2 = e2.tileID;
            return i2.overscaledZ - a2.overscaledZ || i2.canonical.y - a2.canonical.y || i2.wrap - a2.wrap || i2.canonical.x - a2.canonical.x;
          }
          function G(t4, i2, a2) {
            return e._(this, void 0, void 0, function* () {
              let s2 = t4;
              if (t4.url ? s2 = (yield e.h(i2.transformRequest(t4.url, "Source"), a2)).data : yield o.frameAsync(a2), !s2) return null;
              const r2 = e.M(e.e(s2, t4), ["tiles", "minzoom", "maxzoom", "attribution", "bounds", "scheme", "tileSize", "encoding"]);
              return "vector_layers" in s2 && s2.vector_layers && (r2.vectorLayerIds = s2.vector_layers.map((t5) => t5.id)), r2;
            });
          }
          class H {
            constructor(t4, e2) {
              t4 && (e2 ? this.setSouthWest(t4).setNorthEast(e2) : Array.isArray(t4) && (4 === t4.length ? this.setSouthWest([t4[0], t4[1]]).setNorthEast([t4[2], t4[3]]) : this.setSouthWest(t4[0]).setNorthEast(t4[1])));
            }
            setNorthEast(t4) {
              return this._ne = t4 instanceof e.N ? new e.N(t4.lng, t4.lat) : e.N.convert(t4), this;
            }
            setSouthWest(t4) {
              return this._sw = t4 instanceof e.N ? new e.N(t4.lng, t4.lat) : e.N.convert(t4), this;
            }
            extend(t4) {
              const i2 = this._sw, a2 = this._ne;
              let s2, o2;
              if (t4 instanceof e.N) s2 = t4, o2 = t4;
              else {
                if (!(t4 instanceof H)) return Array.isArray(t4) ? 4 === t4.length || t4.every(Array.isArray) ? this.extend(H.convert(t4)) : this.extend(e.N.convert(t4)) : t4 && ("lng" in t4 || "lon" in t4) && "lat" in t4 ? this.extend(e.N.convert(t4)) : this;
                if (s2 = t4._sw, o2 = t4._ne, !s2 || !o2) return this;
              }
              return i2 || a2 ? (i2.lng = Math.min(s2.lng, i2.lng), i2.lat = Math.min(s2.lat, i2.lat), a2.lng = Math.max(o2.lng, a2.lng), a2.lat = Math.max(o2.lat, a2.lat)) : (this._sw = new e.N(s2.lng, s2.lat), this._ne = new e.N(o2.lng, o2.lat)), this;
            }
            getCenter() {
              return new e.N((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);
            }
            getSouthWest() {
              return this._sw;
            }
            getNorthEast() {
              return this._ne;
            }
            getNorthWest() {
              return new e.N(this.getWest(), this.getNorth());
            }
            getSouthEast() {
              return new e.N(this.getEast(), this.getSouth());
            }
            getWest() {
              return this._sw.lng;
            }
            getSouth() {
              return this._sw.lat;
            }
            getEast() {
              return this._ne.lng;
            }
            getNorth() {
              return this._ne.lat;
            }
            toArray() {
              return [this._sw.toArray(), this._ne.toArray()];
            }
            toString() {
              return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`;
            }
            isEmpty() {
              return !(this._sw && this._ne);
            }
            contains(t4) {
              const { lng: i2, lat: a2 } = e.N.convert(t4);
              let s2 = this._sw.lng <= i2 && i2 <= this._ne.lng;
              return this._sw.lng > this._ne.lng && (s2 = this._sw.lng >= i2 && i2 >= this._ne.lng), this._sw.lat <= a2 && a2 <= this._ne.lat && s2;
            }
            static convert(t4) {
              return t4 instanceof H ? t4 : t4 ? new H(t4) : t4;
            }
            static fromLngLat(t4, i2 = 0) {
              const a2 = 360 * i2 / 40075017, s2 = a2 / Math.cos(Math.PI / 180 * t4.lat);
              return new H(new e.N(t4.lng - s2, t4.lat - a2), new e.N(t4.lng + s2, t4.lat + a2));
            }
            adjustAntiMeridian() {
              const t4 = new e.N(this._sw.lng, this._sw.lat), i2 = new e.N(this._ne.lng, this._ne.lat);
              return new H(t4, t4.lng > i2.lng ? new e.N(i2.lng + 360, i2.lat) : i2);
            }
          }
          class W {
            constructor(t4, e2, i2) {
              this.bounds = H.convert(this.validateBounds(t4)), this.minzoom = e2 || 0, this.maxzoom = i2 || 24;
            }
            validateBounds(t4) {
              return Array.isArray(t4) && 4 === t4.length ? [Math.max(-180, t4[0]), Math.max(-90, t4[1]), Math.min(180, t4[2]), Math.min(90, t4[3])] : [-180, -90, 180, 90];
            }
            contains(t4) {
              const i2 = Math.pow(2, t4.z), a2 = Math.floor(e.O(this.bounds.getWest()) * i2), s2 = Math.floor(e.Q(this.bounds.getNorth()) * i2), o2 = Math.ceil(e.O(this.bounds.getEast()) * i2), r2 = Math.ceil(e.Q(this.bounds.getSouth()) * i2);
              return t4.x >= a2 && t4.x < o2 && t4.y >= s2 && t4.y < r2;
            }
          }
          class $ extends e.E {
            constructor(t4, i2, a2, s2) {
              if (super(), this.id = t4, this.dispatcher = a2, this.type = "vector", this.minzoom = 0, this.maxzoom = 22, this.scheme = "xyz", this.tileSize = 512, this.reparseOverscaled = true, this.isTileClipped = true, this._loaded = false, e.e(this, e.M(i2, ["url", "scheme", "tileSize", "promoteId"])), this._options = e.e({ type: "vector" }, i2), this._collectResourceTiming = i2.collectResourceTiming, 512 !== this.tileSize) throw new Error("vector tile sources must have a tileSize of 512");
              this.setEventedParent(s2);
            }
            load() {
              return e._(this, void 0, void 0, function* () {
                this._loaded = false, this.fire(new e.k("dataloading", { dataType: "source" })), this._tileJSONRequest = new AbortController();
                try {
                  const t4 = yield G(this._options, this.map._requestManager, this._tileJSONRequest);
                  this._tileJSONRequest = null, this._loaded = true, this.map.style.sourceCaches[this.id].clearTiles(), t4 && (e.e(this, t4), t4.bounds && (this.tileBounds = new W(t4.bounds, this.minzoom, this.maxzoom)), this.fire(new e.k("data", { dataType: "source", sourceDataType: "metadata" })), this.fire(new e.k("data", { dataType: "source", sourceDataType: "content" })));
                } catch (t4) {
                  this._tileJSONRequest = null, this.fire(new e.j(t4));
                }
              });
            }
            loaded() {
              return this._loaded;
            }
            hasTile(t4) {
              return !this.tileBounds || this.tileBounds.contains(t4.canonical);
            }
            onAdd(t4) {
              this.map = t4, this.load();
            }
            setSourceProperty(t4) {
              this._tileJSONRequest && this._tileJSONRequest.abort(), t4(), this.load();
            }
            setTiles(t4) {
              return this.setSourceProperty(() => {
                this._options.tiles = t4;
              }), this;
            }
            setUrl(t4) {
              return this.setSourceProperty(() => {
                this.url = t4, this._options.url = t4;
              }), this;
            }
            onRemove() {
              this._tileJSONRequest && (this._tileJSONRequest.abort(), this._tileJSONRequest = null);
            }
            serialize() {
              return e.e({}, this._options);
            }
            loadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const e2 = t4.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme), i2 = { request: this.map._requestManager.transformRequest(e2, "Tile"), uid: t4.uid, tileID: t4.tileID, zoom: t4.tileID.overscaledZ, tileSize: this.tileSize * t4.tileID.overscaleFactor(), type: this.type, source: this.id, pixelRatio: this.map.getPixelRatio(), showCollisionBoxes: this.map.showCollisionBoxes, promoteId: this.promoteId };
                i2.request.collectResourceTiming = this._collectResourceTiming;
                let a2 = "RT";
                if (t4.actor && "expired" !== t4.state) {
                  if ("loading" === t4.state) return new Promise((e3, i3) => {
                    t4.reloadPromise = { resolve: e3, reject: i3 };
                  });
                } else t4.actor = this.dispatcher.getActor(), a2 = "LT";
                t4.abortController = new AbortController();
                try {
                  const e3 = yield t4.actor.sendAsync({ type: a2, data: i2 }, t4.abortController);
                  if (delete t4.abortController, t4.aborted) return;
                  this._afterTileLoadWorkerResponse(t4, e3);
                } catch (e3) {
                  if (delete t4.abortController, t4.aborted) return;
                  if (e3 && 404 !== e3.status) throw e3;
                  this._afterTileLoadWorkerResponse(t4, null);
                }
              });
            }
            _afterTileLoadWorkerResponse(t4, e2) {
              if (e2 && e2.resourceTiming && (t4.resourceTiming = e2.resourceTiming), e2 && this.map._refreshExpiredTiles && t4.setExpiryData(e2), t4.loadVectorData(e2, this.map.painter), t4.reloadPromise) {
                const e3 = t4.reloadPromise;
                t4.reloadPromise = null, this.loadTile(t4).then(e3.resolve).catch(e3.reject);
              }
            }
            abortTile(t4) {
              return e._(this, void 0, void 0, function* () {
                t4.abortController && (t4.abortController.abort(), delete t4.abortController), t4.actor && (yield t4.actor.sendAsync({ type: "AT", data: { uid: t4.uid, type: this.type, source: this.id } }));
              });
            }
            unloadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                t4.unloadVectorData(), t4.actor && (yield t4.actor.sendAsync({ type: "RMT", data: { uid: t4.uid, type: this.type, source: this.id } }));
              });
            }
            hasTransition() {
              return false;
            }
          }
          class X extends e.E {
            constructor(t4, i2, a2, s2) {
              super(), this.id = t4, this.dispatcher = a2, this.setEventedParent(s2), this.type = "raster", this.minzoom = 0, this.maxzoom = 22, this.roundZoom = true, this.scheme = "xyz", this.tileSize = 512, this._loaded = false, this._options = e.e({ type: "raster" }, i2), e.e(this, e.M(i2, ["url", "scheme", "tileSize"]));
            }
            load() {
              return e._(this, void 0, void 0, function* () {
                this._loaded = false, this.fire(new e.k("dataloading", { dataType: "source" })), this._tileJSONRequest = new AbortController();
                try {
                  const t4 = yield G(this._options, this.map._requestManager, this._tileJSONRequest);
                  this._tileJSONRequest = null, this._loaded = true, t4 && (e.e(this, t4), t4.bounds && (this.tileBounds = new W(t4.bounds, this.minzoom, this.maxzoom)), this.fire(new e.k("data", { dataType: "source", sourceDataType: "metadata" })), this.fire(new e.k("data", { dataType: "source", sourceDataType: "content" })));
                } catch (t4) {
                  this._tileJSONRequest = null, this.fire(new e.j(t4));
                }
              });
            }
            loaded() {
              return this._loaded;
            }
            onAdd(t4) {
              this.map = t4, this.load();
            }
            onRemove() {
              this._tileJSONRequest && (this._tileJSONRequest.abort(), this._tileJSONRequest = null);
            }
            setSourceProperty(t4) {
              this._tileJSONRequest && (this._tileJSONRequest.abort(), this._tileJSONRequest = null), t4(), this.load();
            }
            setTiles(t4) {
              return this.setSourceProperty(() => {
                this._options.tiles = t4;
              }), this;
            }
            setUrl(t4) {
              return this.setSourceProperty(() => {
                this.url = t4, this._options.url = t4;
              }), this;
            }
            serialize() {
              return e.e({}, this._options);
            }
            hasTile(t4) {
              return !this.tileBounds || this.tileBounds.contains(t4.canonical);
            }
            loadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const e2 = t4.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);
                t4.abortController = new AbortController();
                try {
                  const i2 = yield _.getImage(this.map._requestManager.transformRequest(e2, "Tile"), t4.abortController, this.map._refreshExpiredTiles);
                  if (delete t4.abortController, t4.aborted) return void (t4.state = "unloaded");
                  if (i2 && i2.data) {
                    this.map._refreshExpiredTiles && i2.cacheControl && i2.expires && t4.setExpiryData({ cacheControl: i2.cacheControl, expires: i2.expires });
                    const e3 = this.map.painter.context, a2 = e3.gl, s2 = i2.data;
                    t4.texture = this.map.painter.getTileTexture(s2.width), t4.texture ? t4.texture.update(s2, { useMipmap: true }) : (t4.texture = new b(e3, s2, a2.RGBA, { useMipmap: true }), t4.texture.bind(a2.LINEAR, a2.CLAMP_TO_EDGE, a2.LINEAR_MIPMAP_NEAREST)), t4.state = "loaded";
                  }
                } catch (e3) {
                  if (delete t4.abortController, t4.aborted) t4.state = "unloaded";
                  else if (e3) throw t4.state = "errored", e3;
                }
              });
            }
            abortTile(t4) {
              return e._(this, void 0, void 0, function* () {
                t4.abortController && (t4.abortController.abort(), delete t4.abortController);
              });
            }
            unloadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                t4.texture && this.map.painter.saveTileTexture(t4.texture);
              });
            }
            hasTransition() {
              return false;
            }
          }
          class K2 extends X {
            constructor(t4, i2, a2, s2) {
              super(t4, i2, a2, s2), this.type = "raster-dem", this.maxzoom = 22, this._options = e.e({ type: "raster-dem" }, i2), this.encoding = i2.encoding || "mapbox", this.redFactor = i2.redFactor, this.greenFactor = i2.greenFactor, this.blueFactor = i2.blueFactor, this.baseShift = i2.baseShift;
            }
            loadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const i2 = t4.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme), a2 = this.map._requestManager.transformRequest(i2, "Tile");
                t4.neighboringTiles = this._getNeighboringTiles(t4.tileID), t4.abortController = new AbortController();
                try {
                  const i3 = yield _.getImage(a2, t4.abortController, this.map._refreshExpiredTiles);
                  if (delete t4.abortController, t4.aborted) return void (t4.state = "unloaded");
                  if (i3 && i3.data) {
                    const a3 = i3.data;
                    this.map._refreshExpiredTiles && i3.cacheControl && i3.expires && t4.setExpiryData({ cacheControl: i3.cacheControl, expires: i3.expires });
                    const s2 = e.b(a3) && e.U() ? a3 : yield this.readImageNow(a3), o2 = { type: this.type, uid: t4.uid, source: this.id, rawImageData: s2, encoding: this.encoding, redFactor: this.redFactor, greenFactor: this.greenFactor, blueFactor: this.blueFactor, baseShift: this.baseShift };
                    if (!t4.actor || "expired" === t4.state) {
                      t4.actor = this.dispatcher.getActor();
                      const e2 = yield t4.actor.sendAsync({ type: "LDT", data: o2 });
                      t4.dem = e2, t4.needsHillshadePrepare = true, t4.needsTerrainPrepare = true, t4.state = "loaded";
                    }
                  }
                } catch (e2) {
                  if (delete t4.abortController, t4.aborted) t4.state = "unloaded";
                  else if (e2) throw t4.state = "errored", e2;
                }
              });
            }
            readImageNow(t4) {
              return e._(this, void 0, void 0, function* () {
                if ("undefined" != typeof VideoFrame && e.V()) {
                  const i2 = t4.width + 2, a2 = t4.height + 2;
                  try {
                    return new e.R({ width: i2, height: a2 }, yield e.W(t4, -1, -1, i2, a2));
                  } catch (t5) {
                  }
                }
                return o.getImageData(t4, 1);
              });
            }
            _getNeighboringTiles(t4) {
              const i2 = t4.canonical, a2 = Math.pow(2, i2.z), s2 = (i2.x - 1 + a2) % a2, o2 = 0 === i2.x ? t4.wrap - 1 : t4.wrap, r2 = (i2.x + 1 + a2) % a2, n2 = i2.x + 1 === a2 ? t4.wrap + 1 : t4.wrap, l2 = {};
              return l2[new e.S(t4.overscaledZ, o2, i2.z, s2, i2.y).key] = { backfilled: false }, l2[new e.S(t4.overscaledZ, n2, i2.z, r2, i2.y).key] = { backfilled: false }, i2.y > 0 && (l2[new e.S(t4.overscaledZ, o2, i2.z, s2, i2.y - 1).key] = { backfilled: false }, l2[new e.S(t4.overscaledZ, t4.wrap, i2.z, i2.x, i2.y - 1).key] = { backfilled: false }, l2[new e.S(t4.overscaledZ, n2, i2.z, r2, i2.y - 1).key] = { backfilled: false }), i2.y + 1 < a2 && (l2[new e.S(t4.overscaledZ, o2, i2.z, s2, i2.y + 1).key] = { backfilled: false }, l2[new e.S(t4.overscaledZ, t4.wrap, i2.z, i2.x, i2.y + 1).key] = { backfilled: false }, l2[new e.S(t4.overscaledZ, n2, i2.z, r2, i2.y + 1).key] = { backfilled: false }), l2;
            }
            unloadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                t4.demTexture && this.map.painter.saveTileTexture(t4.demTexture), t4.fbo && (t4.fbo.destroy(), delete t4.fbo), t4.dem && delete t4.dem, delete t4.neighboringTiles, t4.state = "unloaded", t4.actor && (yield t4.actor.sendAsync({ type: "RDT", data: { type: this.type, uid: t4.uid, source: this.id } }));
              });
            }
          }
          class J extends e.E {
            constructor(t4, i2, a2, s2) {
              super(), this.id = t4, this.type = "geojson", this.minzoom = 0, this.maxzoom = 18, this.tileSize = 512, this.isTileClipped = true, this.reparseOverscaled = true, this._removed = false, this._pendingLoads = 0, this.actor = a2.getActor(), this.setEventedParent(s2), this._data = i2.data, this._options = e.e({}, i2), this._collectResourceTiming = i2.collectResourceTiming, void 0 !== i2.maxzoom && (this.maxzoom = i2.maxzoom), i2.type && (this.type = i2.type), i2.attribution && (this.attribution = i2.attribution), this.promoteId = i2.promoteId;
              const o2 = e.X / this.tileSize;
              void 0 !== i2.clusterMaxZoom && this.maxzoom <= i2.clusterMaxZoom && e.w(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${i2.clusterMaxZoom}".`), this.workerOptions = e.e({ source: this.id, cluster: i2.cluster || false, geojsonVtOptions: { buffer: (void 0 !== i2.buffer ? i2.buffer : 128) * o2, tolerance: (void 0 !== i2.tolerance ? i2.tolerance : 0.375) * o2, extent: e.X, maxZoom: this.maxzoom, lineMetrics: i2.lineMetrics || false, generateId: i2.generateId || false }, superclusterOptions: { maxZoom: void 0 !== i2.clusterMaxZoom ? i2.clusterMaxZoom : this.maxzoom - 1, minPoints: Math.max(2, i2.clusterMinPoints || 2), extent: e.X, radius: (i2.clusterRadius || 50) * o2, log: false, generateId: i2.generateId || false }, clusterProperties: i2.clusterProperties, filter: i2.filter }, i2.workerOptions), "string" == typeof this.promoteId && (this.workerOptions.promoteId = this.promoteId);
            }
            load() {
              return e._(this, void 0, void 0, function* () {
                yield this._updateWorkerData();
              });
            }
            onAdd(t4) {
              this.map = t4, this.load();
            }
            setData(t4) {
              return this._data = t4, this._updateWorkerData(), this;
            }
            updateData(t4) {
              return this._updateWorkerData(t4), this;
            }
            getData() {
              return e._(this, void 0, void 0, function* () {
                const t4 = e.e({ type: this.type }, this.workerOptions);
                return this.actor.sendAsync({ type: "GD", data: t4 });
              });
            }
            setClusterOptions(t4) {
              return this.workerOptions.cluster = t4.cluster, t4 && (void 0 !== t4.clusterRadius && (this.workerOptions.superclusterOptions.radius = t4.clusterRadius), void 0 !== t4.clusterMaxZoom && (this.workerOptions.superclusterOptions.maxZoom = t4.clusterMaxZoom)), this._updateWorkerData(), this;
            }
            getClusterExpansionZoom(t4) {
              return this.actor.sendAsync({ type: "GCEZ", data: { type: this.type, clusterId: t4, source: this.id } });
            }
            getClusterChildren(t4) {
              return this.actor.sendAsync({ type: "GCC", data: { type: this.type, clusterId: t4, source: this.id } });
            }
            getClusterLeaves(t4, e2, i2) {
              return this.actor.sendAsync({ type: "GCL", data: { type: this.type, source: this.id, clusterId: t4, limit: e2, offset: i2 } });
            }
            _updateWorkerData(t4) {
              return e._(this, void 0, void 0, function* () {
                const i2 = e.e({ type: this.type }, this.workerOptions);
                t4 ? i2.dataDiff = t4 : "string" == typeof this._data ? (i2.request = this.map._requestManager.transformRequest(o.resolveURL(this._data), "Source"), i2.request.collectResourceTiming = this._collectResourceTiming) : i2.data = JSON.stringify(this._data), this._pendingLoads++, this.fire(new e.k("dataloading", { dataType: "source" }));
                try {
                  const t5 = yield this.actor.sendAsync({ type: "LD", data: i2 });
                  if (this._pendingLoads--, this._removed || t5.abandoned) return void this.fire(new e.k("dataabort", { dataType: "source" }));
                  let a2 = null;
                  t5.resourceTiming && t5.resourceTiming[this.id] && (a2 = t5.resourceTiming[this.id].slice(0));
                  const s2 = { dataType: "source" };
                  this._collectResourceTiming && a2 && a2.length > 0 && e.e(s2, { resourceTiming: a2 }), this.fire(new e.k("data", Object.assign(Object.assign({}, s2), { sourceDataType: "metadata" }))), this.fire(new e.k("data", Object.assign(Object.assign({}, s2), { sourceDataType: "content" })));
                } catch (t5) {
                  if (this._pendingLoads--, this._removed) return void this.fire(new e.k("dataabort", { dataType: "source" }));
                  this.fire(new e.j(t5));
                }
              });
            }
            loaded() {
              return 0 === this._pendingLoads;
            }
            loadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                const e2 = t4.actor ? "RT" : "LT";
                t4.actor = this.actor;
                const i2 = { type: this.type, uid: t4.uid, tileID: t4.tileID, zoom: t4.tileID.overscaledZ, maxZoom: this.maxzoom, tileSize: this.tileSize, source: this.id, pixelRatio: this.map.getPixelRatio(), showCollisionBoxes: this.map.showCollisionBoxes, promoteId: this.promoteId };
                t4.abortController = new AbortController();
                const a2 = yield this.actor.sendAsync({ type: e2, data: i2 }, t4.abortController);
                delete t4.abortController, t4.unloadVectorData(), t4.aborted || t4.loadVectorData(a2, this.map.painter, "RT" === e2);
              });
            }
            abortTile(t4) {
              return e._(this, void 0, void 0, function* () {
                t4.abortController && (t4.abortController.abort(), delete t4.abortController), t4.aborted = true;
              });
            }
            unloadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                t4.unloadVectorData(), yield this.actor.sendAsync({ type: "RMT", data: { uid: t4.uid, type: this.type, source: this.id } });
              });
            }
            onRemove() {
              this._removed = true, this.actor.sendAsync({ type: "RS", data: { type: this.type, source: this.id } });
            }
            serialize() {
              return e.e({}, this._options, { type: this.type, data: this._data });
            }
            hasTransition() {
              return false;
            }
          }
          var Y = e.Y([{ name: "a_pos", type: "Int16", components: 2 }, { name: "a_texture_pos", type: "Int16", components: 2 }]);
          class Q extends e.E {
            constructor(t4, e2, i2, a2) {
              super(), this.id = t4, this.dispatcher = i2, this.coordinates = e2.coordinates, this.type = "image", this.minzoom = 0, this.maxzoom = 22, this.tileSize = 512, this.tiles = {}, this._loaded = false, this.setEventedParent(a2), this.options = e2;
            }
            load(t4) {
              return e._(this, void 0, void 0, function* () {
                this._loaded = false, this.fire(new e.k("dataloading", { dataType: "source" })), this.url = this.options.url, this._request = new AbortController();
                try {
                  const e2 = yield _.getImage(this.map._requestManager.transformRequest(this.url, "Image"), this._request);
                  this._request = null, this._loaded = true, e2 && e2.data && (this.image = e2.data, t4 && (this.coordinates = t4), this._finishLoading());
                } catch (t5) {
                  this._request = null, this._loaded = true, this.fire(new e.j(t5));
                }
              });
            }
            loaded() {
              return this._loaded;
            }
            updateImage(t4) {
              return t4.url ? (this._request && (this._request.abort(), this._request = null), this.options.url = t4.url, this.load(t4.coordinates).finally(() => {
                this.texture = null;
              }), this) : this;
            }
            _finishLoading() {
              this.map && (this.setCoordinates(this.coordinates), this.fire(new e.k("data", { dataType: "source", sourceDataType: "metadata" })));
            }
            onAdd(t4) {
              this.map = t4, this.load();
            }
            onRemove() {
              this._request && (this._request.abort(), this._request = null);
            }
            setCoordinates(t4) {
              this.coordinates = t4;
              const i2 = t4.map(e.Z.fromLngLat);
              this.tileID = function(t5) {
                let i3 = 1 / 0, a3 = 1 / 0, s2 = -1 / 0, o2 = -1 / 0;
                for (const e2 of t5) i3 = Math.min(i3, e2.x), a3 = Math.min(a3, e2.y), s2 = Math.max(s2, e2.x), o2 = Math.max(o2, e2.y);
                const r2 = Math.max(s2 - i3, o2 - a3), n2 = Math.max(0, Math.floor(-Math.log(r2) / Math.LN2)), l2 = Math.pow(2, n2);
                return new e.a1(n2, Math.floor((i3 + s2) / 2 * l2), Math.floor((a3 + o2) / 2 * l2));
              }(i2), this.minzoom = this.maxzoom = this.tileID.z;
              const a2 = i2.map((t5) => this.tileID.getTilePoint(t5)._round());
              return this._boundsArray = new e.$(), this._boundsArray.emplaceBack(a2[0].x, a2[0].y, 0, 0), this._boundsArray.emplaceBack(a2[1].x, a2[1].y, e.X, 0), this._boundsArray.emplaceBack(a2[3].x, a2[3].y, 0, e.X), this._boundsArray.emplaceBack(a2[2].x, a2[2].y, e.X, e.X), this.boundsBuffer && (this.boundsBuffer.destroy(), delete this.boundsBuffer), this.fire(new e.k("data", { dataType: "source", sourceDataType: "content" })), this;
            }
            prepare() {
              if (0 === Object.keys(this.tiles).length || !this.image) return;
              const t4 = this.map.painter.context, i2 = t4.gl;
              this.boundsBuffer || (this.boundsBuffer = t4.createVertexBuffer(this._boundsArray, Y.members)), this.boundsSegments || (this.boundsSegments = e.a0.simpleSegment(0, 0, 4, 2)), this.texture || (this.texture = new b(t4, this.image, i2.RGBA), this.texture.bind(i2.LINEAR, i2.CLAMP_TO_EDGE));
              let a2 = false;
              for (const t5 in this.tiles) {
                const e2 = this.tiles[t5];
                "loaded" !== e2.state && (e2.state = "loaded", e2.texture = this.texture, a2 = true);
              }
              a2 && this.fire(new e.k("data", { dataType: "source", sourceDataType: "idle", sourceId: this.id }));
            }
            loadTile(t4) {
              return e._(this, void 0, void 0, function* () {
                this.tileID && this.tileID.equals(t4.tileID.canonical) ? (this.tiles[String(t4.tileID.wrap)] = t4, t4.buckets = {}) : t4.state = "errored";
              });
            }
            serialize() {
              return { type: "image", url: this.options.url, coordinates: this.coordinates };
            }
            hasTransition() {
              return false;
            }
          }
          class tt extends Q {
            constructor(t4, e2, i2, a2) {
              super(t4, e2, i2, a2), this.roundZoom = true, this.type = "video", this.options = e2;
            }
            load() {
              return e._(this, void 0, void 0, function* () {
                this._loaded = false;
                const t4 = this.options;
                this.urls = [];
                for (const e2 of t4.urls) this.urls.push(this.map._requestManager.transformRequest(e2, "Source").url);
                try {
                  const t5 = yield e.a3(this.urls);
                  if (this._loaded = true, !t5) return;
                  this.video = t5, this.video.loop = true, this.video.addEventListener("playing", () => {
                    this.map.triggerRepaint();
                  }), this.map && this.video.play(), this._finishLoading();
                } catch (t5) {
                  this.fire(new e.j(t5));
                }
              });
            }
            pause() {
              this.video && this.video.pause();
            }
            play() {
              this.video && this.video.play();
            }
            seek(t4) {
              if (this.video) {
                const i2 = this.video.seekable;
                t4 < i2.start(0) || t4 > i2.end(0) ? this.fire(new e.j(new e.a2(`sources.${this.id}`, null, `Playback for this video can be set only between the ${i2.start(0)} and ${i2.end(0)}-second mark.`))) : this.video.currentTime = t4;
              }
            }
            getVideo() {
              return this.video;
            }
            onAdd(t4) {
              this.map || (this.map = t4, this.load(), this.video && (this.video.play(), this.setCoordinates(this.coordinates)));
            }
            prepare() {
              if (0 === Object.keys(this.tiles).length || this.video.readyState < 2) return;
              const t4 = this.map.painter.context, i2 = t4.gl;
              this.boundsBuffer || (this.boundsBuffer = t4.createVertexBuffer(this._boundsArray, Y.members)), this.boundsSegments || (this.boundsSegments = e.a0.simpleSegment(0, 0, 4, 2)), this.texture ? this.video.paused || (this.texture.bind(i2.LINEAR, i2.CLAMP_TO_EDGE), i2.texSubImage2D(i2.TEXTURE_2D, 0, 0, 0, i2.RGBA, i2.UNSIGNED_BYTE, this.video)) : (this.texture = new b(t4, this.video, i2.RGBA), this.texture.bind(i2.LINEAR, i2.CLAMP_TO_EDGE));
              let a2 = false;
              for (const t5 in this.tiles) {
                const e2 = this.tiles[t5];
                "loaded" !== e2.state && (e2.state = "loaded", e2.texture = this.texture, a2 = true);
              }
              a2 && this.fire(new e.k("data", { dataType: "source", sourceDataType: "idle", sourceId: this.id }));
            }
            serialize() {
              return { type: "video", urls: this.urls, coordinates: this.coordinates };
            }
            hasTransition() {
              return this.video && !this.video.paused;
            }
          }
          class et extends Q {
            constructor(t4, i2, a2, s2) {
              super(t4, i2, a2, s2), i2.coordinates ? Array.isArray(i2.coordinates) && 4 === i2.coordinates.length && !i2.coordinates.some((t5) => !Array.isArray(t5) || 2 !== t5.length || t5.some((t6) => "number" != typeof t6)) || this.fire(new e.j(new e.a2(`sources.${t4}`, null, '"coordinates" property must be an array of 4 longitude/latitude array pairs'))) : this.fire(new e.j(new e.a2(`sources.${t4}`, null, 'missing required property "coordinates"'))), i2.animate && "boolean" != typeof i2.animate && this.fire(new e.j(new e.a2(`sources.${t4}`, null, 'optional "animate" property must be a boolean value'))), i2.canvas ? "string" == typeof i2.canvas || i2.canvas instanceof HTMLCanvasElement || this.fire(new e.j(new e.a2(`sources.${t4}`, null, '"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))) : this.fire(new e.j(new e.a2(`sources.${t4}`, null, 'missing required property "canvas"'))), this.options = i2, this.animate = void 0 === i2.animate || i2.animate;
            }
            load() {
              return e._(this, void 0, void 0, function* () {
                this._loaded = true, this.canvas || (this.canvas = this.options.canvas instanceof HTMLCanvasElement ? this.options.canvas : document.getElementById(this.options.canvas)), this.width = this.canvas.width, this.height = this.canvas.height, this._hasInvalidDimensions() ? this.fire(new e.j(new Error("Canvas dimensions cannot be less than or equal to zero."))) : (this.play = function() {
                  this._playing = true, this.map.triggerRepaint();
                }, this.pause = function() {
                  this._playing && (this.prepare(), this._playing = false);
                }, this._finishLoading());
              });
            }
            getCanvas() {
              return this.canvas;
            }
            onAdd(t4) {
              this.map = t4, this.load(), this.canvas && this.animate && this.play();
            }
            onRemove() {
              this.pause();
            }
            prepare() {
              let t4 = false;
              if (this.canvas.width !== this.width && (this.width = this.canvas.width, t4 = true), this.canvas.height !== this.height && (this.height = this.canvas.height, t4 = true), this._hasInvalidDimensions()) return;
              if (0 === Object.keys(this.tiles).length) return;
              const i2 = this.map.painter.context, a2 = i2.gl;
              this.boundsBuffer || (this.boundsBuffer = i2.createVertexBuffer(this._boundsArray, Y.members)), this.boundsSegments || (this.boundsSegments = e.a0.simpleSegment(0, 0, 4, 2)), this.texture ? (t4 || this._playing) && this.texture.update(this.canvas, { premultiply: true }) : this.texture = new b(i2, this.canvas, a2.RGBA, { premultiply: true });
              let s2 = false;
              for (const t5 in this.tiles) {
                const e2 = this.tiles[t5];
                "loaded" !== e2.state && (e2.state = "loaded", e2.texture = this.texture, s2 = true);
              }
              s2 && this.fire(new e.k("data", { dataType: "source", sourceDataType: "idle", sourceId: this.id }));
            }
            serialize() {
              return { type: "canvas", coordinates: this.coordinates };
            }
            hasTransition() {
              return this._playing;
            }
            _hasInvalidDimensions() {
              for (const t4 of [this.canvas.width, this.canvas.height]) if (isNaN(t4) || t4 <= 0) return true;
              return false;
            }
          }
          const it = {}, at = (t4) => {
            switch (t4) {
              case "geojson":
                return J;
              case "image":
                return Q;
              case "raster":
                return X;
              case "raster-dem":
                return K2;
              case "vector":
                return $;
              case "video":
                return tt;
              case "canvas":
                return et;
            }
            return it[t4];
          }, st = "RTLPluginLoaded";
          class ot extends e.E {
            constructor() {
              super(...arguments), this.status = "unavailable", this.url = null, this.dispatcher = j();
            }
            _syncState(t4) {
              return this.status = t4, this.dispatcher.broadcast("SRPS", { pluginStatus: t4, pluginURL: this.url }).catch((t5) => {
                throw this.status = "error", t5;
              });
            }
            getRTLTextPluginStatus() {
              return this.status;
            }
            clearRTLTextPlugin() {
              this.status = "unavailable", this.url = null;
            }
            setRTLTextPlugin(t4) {
              return e._(this, arguments, void 0, function* (t5, e2 = false) {
                if (this.url) throw new Error("setRTLTextPlugin cannot be called multiple times.");
                if (this.url = o.resolveURL(t5), !this.url) throw new Error(`requested url ${t5} is invalid`);
                if ("unavailable" === this.status) {
                  if (!e2) return this._requestImport();
                  this.status = "deferred", this._syncState(this.status);
                } else if ("requested" === this.status) return this._requestImport();
              });
            }
            _requestImport() {
              return e._(this, void 0, void 0, function* () {
                yield this._syncState("loading"), this.status = "loaded", this.fire(new e.k(st));
              });
            }
            lazyLoad() {
              "unavailable" === this.status ? this.status = "requested" : "deferred" === this.status && this._requestImport();
            }
          }
          let rt = null;
          function nt() {
            return rt || (rt = new ot()), rt;
          }
          class lt {
            constructor(t4, i2) {
              this.timeAdded = 0, this.fadeEndTime = 0, this.tileID = t4, this.uid = e.a4(), this.uses = 0, this.tileSize = i2, this.buckets = {}, this.expirationTime = null, this.queryPadding = 0, this.hasSymbolBuckets = false, this.hasRTLText = false, this.dependencies = {}, this.rtt = [], this.rttCoords = {}, this.expiredRequestCount = 0, this.state = "loading";
            }
            registerFadeDuration(t4) {
              const e2 = t4 + this.timeAdded;
              e2 < this.fadeEndTime || (this.fadeEndTime = e2);
            }
            wasRequested() {
              return "errored" === this.state || "loaded" === this.state || "reloading" === this.state;
            }
            clearTextures(t4) {
              this.demTexture && t4.saveTileTexture(this.demTexture), this.demTexture = null;
            }
            loadVectorData(t4, i2, a2) {
              if (this.hasData() && this.unloadVectorData(), this.state = "loaded", t4) {
                t4.featureIndex && (this.latestFeatureIndex = t4.featureIndex, t4.rawTileData ? (this.latestRawTileData = t4.rawTileData, this.latestFeatureIndex.rawTileData = t4.rawTileData) : this.latestRawTileData && (this.latestFeatureIndex.rawTileData = this.latestRawTileData)), this.collisionBoxArray = t4.collisionBoxArray, this.buckets = function(t5, e2) {
                  const i3 = {};
                  if (!e2) return i3;
                  for (const a3 of t5) {
                    const t6 = a3.layerIds.map((t7) => e2.getLayer(t7)).filter(Boolean);
                    if (0 !== t6.length) {
                      a3.layers = t6, a3.stateDependentLayerIds && (a3.stateDependentLayers = a3.stateDependentLayerIds.map((e3) => t6.filter((t7) => t7.id === e3)[0]));
                      for (const e3 of t6) i3[e3.id] = a3;
                    }
                  }
                  return i3;
                }(t4.buckets, i2.style), this.hasSymbolBuckets = false;
                for (const t5 in this.buckets) {
                  const i3 = this.buckets[t5];
                  if (i3 instanceof e.a6) {
                    if (this.hasSymbolBuckets = true, !a2) break;
                    i3.justReloaded = true;
                  }
                }
                if (this.hasRTLText = false, this.hasSymbolBuckets) for (const t5 in this.buckets) {
                  const i3 = this.buckets[t5];
                  if (i3 instanceof e.a6 && i3.hasRTLText) {
                    this.hasRTLText = true, nt().lazyLoad();
                    break;
                  }
                }
                this.queryPadding = 0;
                for (const t5 in this.buckets) {
                  const e2 = this.buckets[t5];
                  this.queryPadding = Math.max(this.queryPadding, i2.style.getLayer(t5).queryRadius(e2));
                }
                t4.imageAtlas && (this.imageAtlas = t4.imageAtlas), t4.glyphAtlasImage && (this.glyphAtlasImage = t4.glyphAtlasImage);
              } else this.collisionBoxArray = new e.a5();
            }
            unloadVectorData() {
              for (const t4 in this.buckets) this.buckets[t4].destroy();
              this.buckets = {}, this.imageAtlasTexture && this.imageAtlasTexture.destroy(), this.imageAtlas && (this.imageAtlas = null), this.glyphAtlasTexture && this.glyphAtlasTexture.destroy(), this.latestFeatureIndex = null, this.state = "unloaded";
            }
            getBucket(t4) {
              return this.buckets[t4.id];
            }
            upload(t4) {
              for (const e3 in this.buckets) {
                const i2 = this.buckets[e3];
                i2.uploadPending() && i2.upload(t4);
              }
              const e2 = t4.gl;
              this.imageAtlas && !this.imageAtlas.uploaded && (this.imageAtlasTexture = new b(t4, this.imageAtlas.image, e2.RGBA), this.imageAtlas.uploaded = true), this.glyphAtlasImage && (this.glyphAtlasTexture = new b(t4, this.glyphAtlasImage, e2.ALPHA), this.glyphAtlasImage = null);
            }
            prepare(t4) {
              this.imageAtlas && this.imageAtlas.patchUpdatedImages(t4, this.imageAtlasTexture);
            }
            queryRenderedFeatures(t4, e2, i2, a2, s2, o2, r2, n2, l2, h2) {
              return this.latestFeatureIndex && this.latestFeatureIndex.rawTileData ? this.latestFeatureIndex.query({ queryGeometry: a2, cameraQueryGeometry: s2, scale: o2, tileSize: this.tileSize, pixelPosMatrix: h2, transform: n2, params: r2, queryPadding: this.queryPadding * l2 }, t4, e2, i2) : {};
            }
            querySourceFeatures(t4, i2) {
              const a2 = this.latestFeatureIndex;
              if (!a2 || !a2.rawTileData) return;
              const s2 = a2.loadVTLayers(), o2 = i2 && i2.sourceLayer ? i2.sourceLayer : "", r2 = s2._geojsonTileLayer || s2[o2];
              if (!r2) return;
              const n2 = e.a7(i2 && i2.filter), { z: l2, x: h2, y: c2 } = this.tileID.canonical, u2 = { z: l2, x: h2, y: c2 };
              for (let i3 = 0; i3 < r2.length; i3++) {
                const s3 = r2.feature(i3);
                if (n2.needGeometry) {
                  const t5 = e.a8(s3, true);
                  if (!n2.filter(new e.z(this.tileID.overscaledZ), t5, this.tileID.canonical)) continue;
                } else if (!n2.filter(new e.z(this.tileID.overscaledZ), s3)) continue;
                const d2 = a2.getId(s3, o2), _2 = new e.a9(s3, l2, h2, c2, d2);
                _2.tile = u2, t4.push(_2);
              }
            }
            hasData() {
              return "loaded" === this.state || "reloading" === this.state || "expired" === this.state;
            }
            patternsLoaded() {
              return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;
            }
            setExpiryData(t4) {
              const i2 = this.expirationTime;
              if (t4.cacheControl) {
                const i3 = e.aa(t4.cacheControl);
                i3["max-age"] && (this.expirationTime = Date.now() + 1e3 * i3["max-age"]);
              } else t4.expires && (this.expirationTime = new Date(t4.expires).getTime());
              if (this.expirationTime) {
                const t5 = Date.now();
                let e2 = false;
                if (this.expirationTime > t5) e2 = false;
                else if (i2) if (this.expirationTime < i2) e2 = true;
                else {
                  const a2 = this.expirationTime - i2;
                  a2 ? this.expirationTime = t5 + Math.max(a2, 3e4) : e2 = true;
                }
                else e2 = true;
                e2 ? (this.expiredRequestCount++, this.state = "expired") : this.expiredRequestCount = 0;
              }
            }
            getExpiryTimeout() {
              if (this.expirationTime) return this.expiredRequestCount ? 1e3 * (1 << Math.min(this.expiredRequestCount - 1, 31)) : Math.min(this.expirationTime - (/* @__PURE__ */ new Date()).getTime(), Math.pow(2, 31) - 1);
            }
            setFeatureState(t4, e2) {
              if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData || 0 === Object.keys(t4).length) return;
              const i2 = this.latestFeatureIndex.loadVTLayers();
              for (const a2 in this.buckets) {
                if (!e2.style.hasLayer(a2)) continue;
                const s2 = this.buckets[a2], o2 = s2.layers[0].sourceLayer || "_geojsonTileLayer", r2 = i2[o2], n2 = t4[o2];
                if (!r2 || !n2 || 0 === Object.keys(n2).length) continue;
                s2.update(n2, r2, this.imageAtlas && this.imageAtlas.patternPositions || {});
                const l2 = e2 && e2.style && e2.style.getLayer(a2);
                l2 && (this.queryPadding = Math.max(this.queryPadding, l2.queryRadius(s2)));
              }
            }
            holdingForFade() {
              return void 0 !== this.symbolFadeHoldUntil;
            }
            symbolFadeFinished() {
              return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < o.now();
            }
            clearFadeHold() {
              this.symbolFadeHoldUntil = void 0;
            }
            setHoldDuration(t4) {
              this.symbolFadeHoldUntil = o.now() + t4;
            }
            setDependencies(t4, e2) {
              const i2 = {};
              for (const t5 of e2) i2[t5] = true;
              this.dependencies[t4] = i2;
            }
            hasDependency(t4, e2) {
              for (const i2 of t4) {
                const t5 = this.dependencies[i2];
                if (t5) {
                  for (const i3 of e2) if (t5[i3]) return true;
                }
              }
              return false;
            }
          }
          class ht {
            constructor(t4, e2) {
              this.max = t4, this.onRemove = e2, this.reset();
            }
            reset() {
              for (const t4 in this.data) for (const e2 of this.data[t4]) e2.timeout && clearTimeout(e2.timeout), this.onRemove(e2.value);
              return this.data = {}, this.order = [], this;
            }
            add(t4, e2, i2) {
              const a2 = t4.wrapped().key;
              void 0 === this.data[a2] && (this.data[a2] = []);
              const s2 = { value: e2, timeout: void 0 };
              if (void 0 !== i2 && (s2.timeout = setTimeout(() => {
                this.remove(t4, s2);
              }, i2)), this.data[a2].push(s2), this.order.push(a2), this.order.length > this.max) {
                const t5 = this._getAndRemoveByKey(this.order[0]);
                t5 && this.onRemove(t5);
              }
              return this;
            }
            has(t4) {
              return t4.wrapped().key in this.data;
            }
            getAndRemove(t4) {
              return this.has(t4) ? this._getAndRemoveByKey(t4.wrapped().key) : null;
            }
            _getAndRemoveByKey(t4) {
              const e2 = this.data[t4].shift();
              return e2.timeout && clearTimeout(e2.timeout), 0 === this.data[t4].length && delete this.data[t4], this.order.splice(this.order.indexOf(t4), 1), e2.value;
            }
            getByKey(t4) {
              const e2 = this.data[t4];
              return e2 ? e2[0].value : null;
            }
            get(t4) {
              return this.has(t4) ? this.data[t4.wrapped().key][0].value : null;
            }
            remove(t4, e2) {
              if (!this.has(t4)) return this;
              const i2 = t4.wrapped().key, a2 = void 0 === e2 ? 0 : this.data[i2].indexOf(e2), s2 = this.data[i2][a2];
              return this.data[i2].splice(a2, 1), s2.timeout && clearTimeout(s2.timeout), 0 === this.data[i2].length && delete this.data[i2], this.onRemove(s2.value), this.order.splice(this.order.indexOf(i2), 1), this;
            }
            setMaxSize(t4) {
              for (this.max = t4; this.order.length > this.max; ) {
                const t5 = this._getAndRemoveByKey(this.order[0]);
                t5 && this.onRemove(t5);
              }
              return this;
            }
            filter(t4) {
              const e2 = [];
              for (const i2 in this.data) for (const a2 of this.data[i2]) t4(a2.value) || e2.push(a2);
              for (const t5 of e2) this.remove(t5.value.tileID, t5);
            }
          }
          class ct {
            constructor() {
              this.state = {}, this.stateChanges = {}, this.deletedStates = {};
            }
            updateState(t4, i2, a2) {
              const s2 = String(i2);
              if (this.stateChanges[t4] = this.stateChanges[t4] || {}, this.stateChanges[t4][s2] = this.stateChanges[t4][s2] || {}, e.e(this.stateChanges[t4][s2], a2), null === this.deletedStates[t4]) {
                this.deletedStates[t4] = {};
                for (const e2 in this.state[t4]) e2 !== s2 && (this.deletedStates[t4][e2] = null);
              } else if (this.deletedStates[t4] && null === this.deletedStates[t4][s2]) {
                this.deletedStates[t4][s2] = {};
                for (const e2 in this.state[t4][s2]) a2[e2] || (this.deletedStates[t4][s2][e2] = null);
              } else for (const e2 in a2) this.deletedStates[t4] && this.deletedStates[t4][s2] && null === this.deletedStates[t4][s2][e2] && delete this.deletedStates[t4][s2][e2];
            }
            removeFeatureState(t4, e2, i2) {
              if (null === this.deletedStates[t4]) return;
              const a2 = String(e2);
              if (this.deletedStates[t4] = this.deletedStates[t4] || {}, i2 && void 0 !== e2) null !== this.deletedStates[t4][a2] && (this.deletedStates[t4][a2] = this.deletedStates[t4][a2] || {}, this.deletedStates[t4][a2][i2] = null);
              else if (void 0 !== e2) if (this.stateChanges[t4] && this.stateChanges[t4][a2]) for (i2 in this.deletedStates[t4][a2] = {}, this.stateChanges[t4][a2]) this.deletedStates[t4][a2][i2] = null;
              else this.deletedStates[t4][a2] = null;
              else this.deletedStates[t4] = null;
            }
            getState(t4, i2) {
              const a2 = String(i2), s2 = e.e({}, (this.state[t4] || {})[a2], (this.stateChanges[t4] || {})[a2]);
              if (null === this.deletedStates[t4]) return {};
              if (this.deletedStates[t4]) {
                const e2 = this.deletedStates[t4][i2];
                if (null === e2) return {};
                for (const t5 in e2) delete s2[t5];
              }
              return s2;
            }
            initializeTileState(t4, e2) {
              t4.setFeatureState(this.state, e2);
            }
            coalesceChanges(t4, i2) {
              const a2 = {};
              for (const t5 in this.stateChanges) {
                this.state[t5] = this.state[t5] || {};
                const i3 = {};
                for (const a3 in this.stateChanges[t5]) this.state[t5][a3] || (this.state[t5][a3] = {}), e.e(this.state[t5][a3], this.stateChanges[t5][a3]), i3[a3] = this.state[t5][a3];
                a2[t5] = i3;
              }
              for (const t5 in this.deletedStates) {
                this.state[t5] = this.state[t5] || {};
                const i3 = {};
                if (null === this.deletedStates[t5]) for (const e2 in this.state[t5]) i3[e2] = {}, this.state[t5][e2] = {};
                else for (const e2 in this.deletedStates[t5]) {
                  if (null === this.deletedStates[t5][e2]) this.state[t5][e2] = {};
                  else for (const i4 of Object.keys(this.deletedStates[t5][e2])) delete this.state[t5][e2][i4];
                  i3[e2] = this.state[t5][e2];
                }
                a2[t5] = a2[t5] || {}, e.e(a2[t5], i3);
              }
              if (this.stateChanges = {}, this.deletedStates = {}, 0 !== Object.keys(a2).length) for (const e2 in t4) t4[e2].setFeatureState(a2, i2);
            }
          }
          class ut extends e.E {
            constructor(t4, e2, i2) {
              super(), this.id = t4, this.dispatcher = i2, this.on("data", (t5) => this._dataHandler(t5)), this.on("dataloading", () => {
                this._sourceErrored = false;
              }), this.on("error", () => {
                this._sourceErrored = this._source.loaded();
              }), this._source = ((t5, e3, i3, a2) => {
                const s2 = new (at(e3.type))(t5, e3, i3, a2);
                if (s2.id !== t5) throw new Error(`Expected Source id to be ${t5} instead of ${s2.id}`);
                return s2;
              })(t4, e2, i2, this), this._tiles = {}, this._cache = new ht(0, (t5) => this._unloadTile(t5)), this._timers = {}, this._cacheTimers = {}, this._maxTileCacheSize = null, this._maxTileCacheZoomLevels = null, this._loadedParentTiles = {}, this._coveredTiles = {}, this._state = new ct(), this._didEmitContent = false, this._updated = false;
            }
            onAdd(t4) {
              this.map = t4, this._maxTileCacheSize = t4 ? t4._maxTileCacheSize : null, this._maxTileCacheZoomLevels = t4 ? t4._maxTileCacheZoomLevels : null, this._source && this._source.onAdd && this._source.onAdd(t4);
            }
            onRemove(t4) {
              this.clearTiles(), this._source && this._source.onRemove && this._source.onRemove(t4);
            }
            loaded() {
              if (this._sourceErrored) return true;
              if (!this._sourceLoaded) return false;
              if (!this._source.loaded()) return false;
              if (!(void 0 === this.used && void 0 === this.usedForTerrain || this.used || this.usedForTerrain)) return true;
              if (!this._updated) return false;
              for (const t4 in this._tiles) {
                const e2 = this._tiles[t4];
                if ("loaded" !== e2.state && "errored" !== e2.state) return false;
              }
              return true;
            }
            getSource() {
              return this._source;
            }
            pause() {
              this._paused = true;
            }
            resume() {
              if (!this._paused) return;
              const t4 = this._shouldReloadOnResume;
              this._paused = false, this._shouldReloadOnResume = false, t4 && this.reload(), this.transform && this.update(this.transform, this.terrain);
            }
            _loadTile(t4, i2, a2) {
              return e._(this, void 0, void 0, function* () {
                try {
                  yield this._source.loadTile(t4), this._tileLoaded(t4, i2, a2);
                } catch (i3) {
                  t4.state = "errored", 404 !== i3.status ? this._source.fire(new e.j(i3, { tile: t4 })) : this.update(this.transform, this.terrain);
                }
              });
            }
            _unloadTile(t4) {
              this._source.unloadTile && this._source.unloadTile(t4);
            }
            _abortTile(t4) {
              this._source.abortTile && this._source.abortTile(t4), this._source.fire(new e.k("dataabort", { tile: t4, coord: t4.tileID, dataType: "source" }));
            }
            serialize() {
              return this._source.serialize();
            }
            prepare(t4) {
              this._source.prepare && this._source.prepare(), this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null);
              for (const e2 in this._tiles) {
                const i2 = this._tiles[e2];
                i2.upload(t4), i2.prepare(this.map.style.imageManager);
              }
            }
            getIds() {
              return Object.values(this._tiles).map((t4) => t4.tileID).sort(dt).map((t4) => t4.key);
            }
            getRenderableIds(t4) {
              const i2 = [];
              for (const e2 in this._tiles) this._isIdRenderable(e2, t4) && i2.push(this._tiles[e2]);
              return t4 ? i2.sort((t5, i3) => {
                const a2 = t5.tileID, s2 = i3.tileID, o2 = new e.P(a2.canonical.x, a2.canonical.y)._rotate(this.transform.angle), r2 = new e.P(s2.canonical.x, s2.canonical.y)._rotate(this.transform.angle);
                return a2.overscaledZ - s2.overscaledZ || r2.y - o2.y || r2.x - o2.x;
              }).map((t5) => t5.tileID.key) : i2.map((t5) => t5.tileID).sort(dt).map((t5) => t5.key);
            }
            hasRenderableParent(t4) {
              const e2 = this.findLoadedParent(t4, 0);
              return !!e2 && this._isIdRenderable(e2.tileID.key);
            }
            _isIdRenderable(t4, e2) {
              return this._tiles[t4] && this._tiles[t4].hasData() && !this._coveredTiles[t4] && (e2 || !this._tiles[t4].holdingForFade());
            }
            reload() {
              if (this._paused) this._shouldReloadOnResume = true;
              else {
                this._cache.reset();
                for (const t4 in this._tiles) "errored" !== this._tiles[t4].state && this._reloadTile(t4, "reloading");
              }
            }
            _reloadTile(t4, i2) {
              return e._(this, void 0, void 0, function* () {
                const e2 = this._tiles[t4];
                e2 && ("loading" !== e2.state && (e2.state = i2), yield this._loadTile(e2, t4, i2));
              });
            }
            _tileLoaded(t4, i2, a2) {
              t4.timeAdded = o.now(), "expired" === a2 && (t4.refreshedUponExpiration = true), this._setTileReloadTimer(i2, t4), "raster-dem" === this.getSource().type && t4.dem && this._backfillDEM(t4), this._state.initializeTileState(t4, this.map ? this.map.painter : null), t4.aborted || this._source.fire(new e.k("data", { dataType: "source", tile: t4, coord: t4.tileID }));
            }
            _backfillDEM(t4) {
              const e2 = this.getRenderableIds();
              for (let a2 = 0; a2 < e2.length; a2++) {
                const s2 = e2[a2];
                if (t4.neighboringTiles && t4.neighboringTiles[s2]) {
                  const e3 = this.getTileByID(s2);
                  i2(t4, e3), i2(e3, t4);
                }
              }
              function i2(t5, e3) {
                t5.needsHillshadePrepare = true, t5.needsTerrainPrepare = true;
                let i3 = e3.tileID.canonical.x - t5.tileID.canonical.x;
                const a2 = e3.tileID.canonical.y - t5.tileID.canonical.y, s2 = Math.pow(2, t5.tileID.canonical.z), o2 = e3.tileID.key;
                0 === i3 && 0 === a2 || Math.abs(a2) > 1 || (Math.abs(i3) > 1 && (1 === Math.abs(i3 + s2) ? i3 += s2 : 1 === Math.abs(i3 - s2) && (i3 -= s2)), e3.dem && t5.dem && (t5.dem.backfillBorder(e3.dem, i3, a2), t5.neighboringTiles && t5.neighboringTiles[o2] && (t5.neighboringTiles[o2].backfilled = true)));
              }
            }
            getTile(t4) {
              return this.getTileByID(t4.key);
            }
            getTileByID(t4) {
              return this._tiles[t4];
            }
            _retainLoadedChildren(t4, e2, i2, a2) {
              for (const s2 in this._tiles) {
                let o2 = this._tiles[s2];
                if (a2[s2] || !o2.hasData() || o2.tileID.overscaledZ <= e2 || o2.tileID.overscaledZ > i2) continue;
                let r2 = o2.tileID;
                for (; o2 && o2.tileID.overscaledZ > e2 + 1; ) {
                  const t5 = o2.tileID.scaledTo(o2.tileID.overscaledZ - 1);
                  o2 = this._tiles[t5.key], o2 && o2.hasData() && (r2 = t5);
                }
                let n2 = r2;
                for (; n2.overscaledZ > e2; ) if (n2 = n2.scaledTo(n2.overscaledZ - 1), t4[n2.key]) {
                  a2[r2.key] = r2;
                  break;
                }
              }
            }
            findLoadedParent(t4, e2) {
              if (t4.key in this._loadedParentTiles) {
                const i2 = this._loadedParentTiles[t4.key];
                return i2 && i2.tileID.overscaledZ >= e2 ? i2 : null;
              }
              for (let i2 = t4.overscaledZ - 1; i2 >= e2; i2--) {
                const e3 = t4.scaledTo(i2), a2 = this._getLoadedTile(e3);
                if (a2) return a2;
              }
            }
            findLoadedSibling(t4) {
              return this._getLoadedTile(t4);
            }
            _getLoadedTile(t4) {
              const e2 = this._tiles[t4.key];
              return e2 && e2.hasData() ? e2 : this._cache.getByKey(t4.wrapped().key);
            }
            updateCacheSize(t4) {
              const i2 = Math.ceil(t4.width / this._source.tileSize) + 1, a2 = Math.ceil(t4.height / this._source.tileSize) + 1, s2 = Math.floor(i2 * a2 * (null === this._maxTileCacheZoomLevels ? e.a.MAX_TILE_CACHE_ZOOM_LEVELS : this._maxTileCacheZoomLevels)), o2 = "number" == typeof this._maxTileCacheSize ? Math.min(this._maxTileCacheSize, s2) : s2;
              this._cache.setMaxSize(o2);
            }
            handleWrapJump(t4) {
              const e2 = Math.round((t4 - (void 0 === this._prevLng ? t4 : this._prevLng)) / 360);
              if (this._prevLng = t4, e2) {
                const t5 = {};
                for (const i2 in this._tiles) {
                  const a2 = this._tiles[i2];
                  a2.tileID = a2.tileID.unwrapTo(a2.tileID.wrap + e2), t5[a2.tileID.key] = a2;
                }
                this._tiles = t5;
                for (const t6 in this._timers) clearTimeout(this._timers[t6]), delete this._timers[t6];
                for (const t6 in this._tiles) this._setTileReloadTimer(t6, this._tiles[t6]);
              }
            }
            _updateCoveredAndRetainedTiles(t4, e2, i2, a2, s2, r2) {
              const n2 = {}, l2 = {}, h2 = Object.keys(t4), c2 = o.now();
              for (const i3 of h2) {
                const a3 = t4[i3], s3 = this._tiles[i3];
                if (!s3 || 0 !== s3.fadeEndTime && s3.fadeEndTime <= c2) continue;
                const o2 = this.findLoadedParent(a3, e2), r3 = this.findLoadedSibling(a3), h3 = o2 || r3 || null;
                h3 && (this._addTile(h3.tileID), n2[h3.tileID.key] = h3.tileID), l2[i3] = a3;
              }
              this._retainLoadedChildren(l2, a2, i2, t4);
              for (const e3 in n2) t4[e3] || (this._coveredTiles[e3] = true, t4[e3] = n2[e3]);
              if (r2) {
                const e3 = {}, i3 = {};
                for (const t5 of s2) this._tiles[t5.key].hasData() ? e3[t5.key] = t5 : i3[t5.key] = t5;
                for (const a3 in i3) {
                  const s3 = i3[a3].children(this._source.maxzoom);
                  this._tiles[s3[0].key] && this._tiles[s3[1].key] && this._tiles[s3[2].key] && this._tiles[s3[3].key] && (e3[s3[0].key] = t4[s3[0].key] = s3[0], e3[s3[1].key] = t4[s3[1].key] = s3[1], e3[s3[2].key] = t4[s3[2].key] = s3[2], e3[s3[3].key] = t4[s3[3].key] = s3[3], delete i3[a3]);
                }
                for (const a3 in i3) {
                  const s3 = i3[a3], o2 = this.findLoadedParent(s3, this._source.minzoom), r3 = this.findLoadedSibling(s3), n3 = o2 || r3 || null;
                  if (n3) {
                    e3[n3.tileID.key] = t4[n3.tileID.key] = n3.tileID;
                    for (const t5 in e3) e3[t5].isChildOf(n3.tileID) && delete e3[t5];
                  }
                }
                for (const t5 in this._tiles) e3[t5] || (this._coveredTiles[t5] = true);
              }
            }
            update(t4, i2) {
              if (!this._sourceLoaded || this._paused) return;
              let a2;
              this.transform = t4, this.terrain = i2, this.updateCacheSize(t4), this.handleWrapJump(this.transform.center.lng), this._coveredTiles = {}, this.used || this.usedForTerrain ? this._source.tileID ? a2 = t4.getVisibleUnwrappedCoordinates(this._source.tileID).map((t5) => new e.S(t5.canonical.z, t5.wrap, t5.canonical.z, t5.canonical.x, t5.canonical.y)) : (a2 = t4.coveringTiles({ tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize, minzoom: this._source.minzoom, maxzoom: this._source.maxzoom, roundZoom: !this.usedForTerrain && this._source.roundZoom, reparseOverscaled: this._source.reparseOverscaled, terrain: i2 }), this._source.hasTile && (a2 = a2.filter((t5) => this._source.hasTile(t5)))) : a2 = [];
              const s2 = t4.coveringZoomLevel(this._source), o2 = Math.max(s2 - ut.maxOverzooming, this._source.minzoom), r2 = Math.max(s2 + ut.maxUnderzooming, this._source.minzoom);
              if (this.usedForTerrain) {
                const t5 = {};
                for (const e2 of a2) if (e2.canonical.z > this._source.minzoom) {
                  const i3 = e2.scaledTo(e2.canonical.z - 1);
                  t5[i3.key] = i3;
                  const a3 = e2.scaledTo(Math.max(this._source.minzoom, Math.min(e2.canonical.z, 5)));
                  t5[a3.key] = a3;
                }
                a2 = a2.concat(Object.values(t5));
              }
              const n2 = 0 === a2.length && !this._updated && this._didEmitContent;
              this._updated = true, n2 && this.fire(new e.k("data", { sourceDataType: "idle", dataType: "source", sourceId: this.id }));
              const l2 = this._updateRetainedTiles(a2, s2);
              _t(this._source.type) && this._updateCoveredAndRetainedTiles(l2, o2, r2, s2, a2, i2);
              for (const t5 in l2) this._tiles[t5].clearFadeHold();
              const h2 = e.ab(this._tiles, l2);
              for (const t5 of h2) {
                const e2 = this._tiles[t5];
                e2.hasSymbolBuckets && !e2.holdingForFade() ? e2.setHoldDuration(this.map._fadeDuration) : e2.hasSymbolBuckets && !e2.symbolFadeFinished() || this._removeTile(t5);
              }
              this._updateLoadedParentTileCache(), this._updateLoadedSiblingTileCache();
            }
            releaseSymbolFadeTiles() {
              for (const t4 in this._tiles) this._tiles[t4].holdingForFade() && this._removeTile(t4);
            }
            _updateRetainedTiles(t4, e2) {
              var i2;
              const a2 = {}, s2 = {}, o2 = Math.max(e2 - ut.maxOverzooming, this._source.minzoom), r2 = Math.max(e2 + ut.maxUnderzooming, this._source.minzoom), n2 = {};
              for (const i3 of t4) {
                const t5 = this._addTile(i3);
                a2[i3.key] = i3, t5.hasData() || e2 < this._source.maxzoom && (n2[i3.key] = i3);
              }
              this._retainLoadedChildren(n2, e2, r2, a2);
              for (const r3 of t4) {
                let t5 = this._tiles[r3.key];
                if (t5.hasData()) continue;
                if (e2 + 1 > this._source.maxzoom) {
                  const t6 = r3.children(this._source.maxzoom)[0], e3 = this.getTile(t6);
                  if (e3 && e3.hasData()) {
                    a2[t6.key] = t6;
                    continue;
                  }
                } else {
                  const t6 = r3.children(this._source.maxzoom);
                  if (a2[t6[0].key] && a2[t6[1].key] && a2[t6[2].key] && a2[t6[3].key]) continue;
                }
                let n3 = t5.wasRequested();
                for (let e3 = r3.overscaledZ - 1; e3 >= o2; --e3) {
                  const o3 = r3.scaledTo(e3);
                  if (s2[o3.key]) break;
                  if (s2[o3.key] = true, t5 = this.getTile(o3), !t5 && n3 && (t5 = this._addTile(o3)), t5) {
                    const e4 = t5.hasData();
                    if ((e4 || !(null === (i2 = this.map) || void 0 === i2 ? void 0 : i2.cancelPendingTileRequestsWhileZooming) || n3) && (a2[o3.key] = o3), n3 = t5.wasRequested(), e4) break;
                  }
                }
              }
              return a2;
            }
            _updateLoadedParentTileCache() {
              this._loadedParentTiles = {};
              for (const t4 in this._tiles) {
                const e2 = [];
                let i2, a2 = this._tiles[t4].tileID;
                for (; a2.overscaledZ > 0; ) {
                  if (a2.key in this._loadedParentTiles) {
                    i2 = this._loadedParentTiles[a2.key];
                    break;
                  }
                  e2.push(a2.key);
                  const t5 = a2.scaledTo(a2.overscaledZ - 1);
                  if (i2 = this._getLoadedTile(t5), i2) break;
                  a2 = t5;
                }
                for (const t5 of e2) this._loadedParentTiles[t5] = i2;
              }
            }
            _updateLoadedSiblingTileCache() {
              this._loadedSiblingTiles = {};
              for (const t4 in this._tiles) {
                const e2 = this._tiles[t4].tileID, i2 = this._getLoadedTile(e2);
                this._loadedSiblingTiles[e2.key] = i2;
              }
            }
            _addTile(t4) {
              let i2 = this._tiles[t4.key];
              if (i2) return i2;
              i2 = this._cache.getAndRemove(t4), i2 && (this._setTileReloadTimer(t4.key, i2), i2.tileID = t4, this._state.initializeTileState(i2, this.map ? this.map.painter : null), this._cacheTimers[t4.key] && (clearTimeout(this._cacheTimers[t4.key]), delete this._cacheTimers[t4.key], this._setTileReloadTimer(t4.key, i2)));
              const a2 = i2;
              return i2 || (i2 = new lt(t4, this._source.tileSize * t4.overscaleFactor()), this._loadTile(i2, t4.key, i2.state)), i2.uses++, this._tiles[t4.key] = i2, a2 || this._source.fire(new e.k("dataloading", { tile: i2, coord: i2.tileID, dataType: "source" })), i2;
            }
            _setTileReloadTimer(t4, e2) {
              t4 in this._timers && (clearTimeout(this._timers[t4]), delete this._timers[t4]);
              const i2 = e2.getExpiryTimeout();
              i2 && (this._timers[t4] = setTimeout(() => {
                this._reloadTile(t4, "expired"), delete this._timers[t4];
              }, i2));
            }
            _removeTile(t4) {
              const e2 = this._tiles[t4];
              e2 && (e2.uses--, delete this._tiles[t4], this._timers[t4] && (clearTimeout(this._timers[t4]), delete this._timers[t4]), e2.uses > 0 || (e2.hasData() && "reloading" !== e2.state ? this._cache.add(e2.tileID, e2, e2.getExpiryTimeout()) : (e2.aborted = true, this._abortTile(e2), this._unloadTile(e2))));
            }
            _dataHandler(t4) {
              const e2 = t4.sourceDataType;
              "source" === t4.dataType && "metadata" === e2 && (this._sourceLoaded = true), this._sourceLoaded && !this._paused && "source" === t4.dataType && "content" === e2 && (this.reload(), this.transform && this.update(this.transform, this.terrain), this._didEmitContent = true);
            }
            clearTiles() {
              this._shouldReloadOnResume = false, this._paused = false;
              for (const t4 in this._tiles) this._removeTile(t4);
              this._cache.reset();
            }
            tilesIn(t4, i2, a2) {
              const s2 = [], o2 = this.transform;
              if (!o2) return s2;
              const r2 = a2 ? o2.getCameraQueryGeometry(t4) : t4, n2 = t4.map((t5) => o2.pointCoordinate(t5, this.terrain)), l2 = r2.map((t5) => o2.pointCoordinate(t5, this.terrain)), h2 = this.getIds();
              let c2 = 1 / 0, u2 = 1 / 0, d2 = -1 / 0, _2 = -1 / 0;
              for (const t5 of l2) c2 = Math.min(c2, t5.x), u2 = Math.min(u2, t5.y), d2 = Math.max(d2, t5.x), _2 = Math.max(_2, t5.y);
              for (let t5 = 0; t5 < h2.length; t5++) {
                const a3 = this._tiles[h2[t5]];
                if (a3.holdingForFade()) continue;
                const r3 = a3.tileID, p2 = Math.pow(2, o2.zoom - a3.tileID.overscaledZ), m2 = i2 * a3.queryPadding * e.X / a3.tileSize / p2, f2 = [r3.getTilePoint(new e.Z(c2, u2)), r3.getTilePoint(new e.Z(d2, _2))];
                if (f2[0].x - m2 < e.X && f2[0].y - m2 < e.X && f2[1].x + m2 >= 0 && f2[1].y + m2 >= 0) {
                  const t6 = n2.map((t7) => r3.getTilePoint(t7)), e2 = l2.map((t7) => r3.getTilePoint(t7));
                  s2.push({ tile: a3, tileID: r3, queryGeometry: t6, cameraQueryGeometry: e2, scale: p2 });
                }
              }
              return s2;
            }
            getVisibleCoordinates(t4) {
              const e2 = this.getRenderableIds(t4).map((t5) => this._tiles[t5].tileID);
              for (const t5 of e2) t5.posMatrix = this.transform.calculatePosMatrix(t5.toUnwrapped());
              return e2;
            }
            hasTransition() {
              if (this._source.hasTransition()) return true;
              if (_t(this._source.type)) {
                const t4 = o.now();
                for (const e2 in this._tiles) if (this._tiles[e2].fadeEndTime >= t4) return true;
              }
              return false;
            }
            setFeatureState(t4, e2, i2) {
              this._state.updateState(t4 = t4 || "_geojsonTileLayer", e2, i2);
            }
            removeFeatureState(t4, e2, i2) {
              this._state.removeFeatureState(t4 = t4 || "_geojsonTileLayer", e2, i2);
            }
            getFeatureState(t4, e2) {
              return this._state.getState(t4 = t4 || "_geojsonTileLayer", e2);
            }
            setDependencies(t4, e2, i2) {
              const a2 = this._tiles[t4];
              a2 && a2.setDependencies(e2, i2);
            }
            reloadTilesForDependencies(t4, e2) {
              for (const i2 in this._tiles) this._tiles[i2].hasDependency(t4, e2) && this._reloadTile(i2, "reloading");
              this._cache.filter((i2) => !i2.hasDependency(t4, e2));
            }
          }
          function dt(t4, e2) {
            const i2 = Math.abs(2 * t4.wrap) - +(t4.wrap < 0), a2 = Math.abs(2 * e2.wrap) - +(e2.wrap < 0);
            return t4.overscaledZ - e2.overscaledZ || a2 - i2 || e2.canonical.y - t4.canonical.y || e2.canonical.x - t4.canonical.x;
          }
          function _t(t4) {
            return "raster" === t4 || "image" === t4 || "video" === t4;
          }
          ut.maxOverzooming = 10, ut.maxUnderzooming = 3;
          class pt {
            constructor(t4, e2) {
              this.reset(t4, e2);
            }
            reset(t4, e2) {
              this.points = t4 || [], this._distances = [0];
              for (let t5 = 1; t5 < this.points.length; t5++) this._distances[t5] = this._distances[t5 - 1] + this.points[t5].dist(this.points[t5 - 1]);
              this.length = this._distances[this._distances.length - 1], this.padding = Math.min(e2 || 0, 0.5 * this.length), this.paddedLength = this.length - 2 * this.padding;
            }
            lerp(t4) {
              if (1 === this.points.length) return this.points[0];
              t4 = e.ac(t4, 0, 1);
              let i2 = 1, a2 = this._distances[i2];
              const s2 = t4 * this.paddedLength + this.padding;
              for (; a2 < s2 && i2 < this._distances.length; ) a2 = this._distances[++i2];
              const o2 = i2 - 1, r2 = this._distances[o2], n2 = a2 - r2, l2 = n2 > 0 ? (s2 - r2) / n2 : 0;
              return this.points[o2].mult(1 - l2).add(this.points[i2].mult(l2));
            }
          }
          function mt(t4, e2) {
            let i2 = true;
            return "always" === t4 || "never" !== t4 && "never" !== e2 || (i2 = false), i2;
          }
          class ft {
            constructor(t4, e2, i2) {
              const a2 = this.boxCells = [], s2 = this.circleCells = [];
              this.xCellCount = Math.ceil(t4 / i2), this.yCellCount = Math.ceil(e2 / i2);
              for (let t5 = 0; t5 < this.xCellCount * this.yCellCount; t5++) a2.push([]), s2.push([]);
              this.circleKeys = [], this.boxKeys = [], this.bboxes = [], this.circles = [], this.width = t4, this.height = e2, this.xScale = this.xCellCount / t4, this.yScale = this.yCellCount / e2, this.boxUid = 0, this.circleUid = 0;
            }
            keysLength() {
              return this.boxKeys.length + this.circleKeys.length;
            }
            insert(t4, e2, i2, a2, s2) {
              this._forEachCell(e2, i2, a2, s2, this._insertBoxCell, this.boxUid++), this.boxKeys.push(t4), this.bboxes.push(e2), this.bboxes.push(i2), this.bboxes.push(a2), this.bboxes.push(s2);
            }
            insertCircle(t4, e2, i2, a2) {
              this._forEachCell(e2 - a2, i2 - a2, e2 + a2, i2 + a2, this._insertCircleCell, this.circleUid++), this.circleKeys.push(t4), this.circles.push(e2), this.circles.push(i2), this.circles.push(a2);
            }
            _insertBoxCell(t4, e2, i2, a2, s2, o2) {
              this.boxCells[s2].push(o2);
            }
            _insertCircleCell(t4, e2, i2, a2, s2, o2) {
              this.circleCells[s2].push(o2);
            }
            _query(t4, e2, i2, a2, s2, o2, r2) {
              if (i2 < 0 || t4 > this.width || a2 < 0 || e2 > this.height) return [];
              const n2 = [];
              if (t4 <= 0 && e2 <= 0 && this.width <= i2 && this.height <= a2) {
                if (s2) return [{ key: null, x1: t4, y1: e2, x2: i2, y2: a2 }];
                for (let t5 = 0; t5 < this.boxKeys.length; t5++) n2.push({ key: this.boxKeys[t5], x1: this.bboxes[4 * t5], y1: this.bboxes[4 * t5 + 1], x2: this.bboxes[4 * t5 + 2], y2: this.bboxes[4 * t5 + 3] });
                for (let t5 = 0; t5 < this.circleKeys.length; t5++) {
                  const e3 = this.circles[3 * t5], i3 = this.circles[3 * t5 + 1], a3 = this.circles[3 * t5 + 2];
                  n2.push({ key: this.circleKeys[t5], x1: e3 - a3, y1: i3 - a3, x2: e3 + a3, y2: i3 + a3 });
                }
              } else this._forEachCell(t4, e2, i2, a2, this._queryCell, n2, { hitTest: s2, overlapMode: o2, seenUids: { box: {}, circle: {} } }, r2);
              return n2;
            }
            query(t4, e2, i2, a2) {
              return this._query(t4, e2, i2, a2, false, null);
            }
            hitTest(t4, e2, i2, a2, s2, o2) {
              return this._query(t4, e2, i2, a2, true, s2, o2).length > 0;
            }
            hitTestCircle(t4, e2, i2, a2, s2) {
              const o2 = t4 - i2, r2 = t4 + i2, n2 = e2 - i2, l2 = e2 + i2;
              if (r2 < 0 || o2 > this.width || l2 < 0 || n2 > this.height) return false;
              const h2 = [];
              return this._forEachCell(o2, n2, r2, l2, this._queryCellCircle, h2, { hitTest: true, overlapMode: a2, circle: { x: t4, y: e2, radius: i2 }, seenUids: { box: {}, circle: {} } }, s2), h2.length > 0;
            }
            _queryCell(t4, e2, i2, a2, s2, o2, r2, n2) {
              const { seenUids: l2, hitTest: h2, overlapMode: c2 } = r2, u2 = this.boxCells[s2];
              if (null !== u2) {
                const s3 = this.bboxes;
                for (const r3 of u2) if (!l2.box[r3]) {
                  l2.box[r3] = true;
                  const u3 = 4 * r3, d3 = this.boxKeys[r3];
                  if (t4 <= s3[u3 + 2] && e2 <= s3[u3 + 3] && i2 >= s3[u3 + 0] && a2 >= s3[u3 + 1] && (!n2 || n2(d3)) && (!h2 || !mt(c2, d3.overlapMode)) && (o2.push({ key: d3, x1: s3[u3], y1: s3[u3 + 1], x2: s3[u3 + 2], y2: s3[u3 + 3] }), h2)) return true;
                }
              }
              const d2 = this.circleCells[s2];
              if (null !== d2) {
                const s3 = this.circles;
                for (const r3 of d2) if (!l2.circle[r3]) {
                  l2.circle[r3] = true;
                  const u3 = 3 * r3, d3 = this.circleKeys[r3];
                  if (this._circleAndRectCollide(s3[u3], s3[u3 + 1], s3[u3 + 2], t4, e2, i2, a2) && (!n2 || n2(d3)) && (!h2 || !mt(c2, d3.overlapMode))) {
                    const t5 = s3[u3], e3 = s3[u3 + 1], i3 = s3[u3 + 2];
                    if (o2.push({ key: d3, x1: t5 - i3, y1: e3 - i3, x2: t5 + i3, y2: e3 + i3 }), h2) return true;
                  }
                }
              }
              return false;
            }
            _queryCellCircle(t4, e2, i2, a2, s2, o2, r2, n2) {
              const { circle: l2, seenUids: h2, overlapMode: c2 } = r2, u2 = this.boxCells[s2];
              if (null !== u2) {
                const t5 = this.bboxes;
                for (const e3 of u2) if (!h2.box[e3]) {
                  h2.box[e3] = true;
                  const i3 = 4 * e3, a3 = this.boxKeys[e3];
                  if (this._circleAndRectCollide(l2.x, l2.y, l2.radius, t5[i3 + 0], t5[i3 + 1], t5[i3 + 2], t5[i3 + 3]) && (!n2 || n2(a3)) && !mt(c2, a3.overlapMode)) return o2.push(true), true;
                }
              }
              const d2 = this.circleCells[s2];
              if (null !== d2) {
                const t5 = this.circles;
                for (const e3 of d2) if (!h2.circle[e3]) {
                  h2.circle[e3] = true;
                  const i3 = 3 * e3, a3 = this.circleKeys[e3];
                  if (this._circlesCollide(t5[i3], t5[i3 + 1], t5[i3 + 2], l2.x, l2.y, l2.radius) && (!n2 || n2(a3)) && !mt(c2, a3.overlapMode)) return o2.push(true), true;
                }
              }
            }
            _forEachCell(t4, e2, i2, a2, s2, o2, r2, n2) {
              const l2 = this._convertToXCellCoord(t4), h2 = this._convertToYCellCoord(e2), c2 = this._convertToXCellCoord(i2), u2 = this._convertToYCellCoord(a2);
              for (let d2 = l2; d2 <= c2; d2++) for (let l3 = h2; l3 <= u2; l3++) if (s2.call(this, t4, e2, i2, a2, this.xCellCount * l3 + d2, o2, r2, n2)) return;
            }
            _convertToXCellCoord(t4) {
              return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(t4 * this.xScale)));
            }
            _convertToYCellCoord(t4) {
              return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(t4 * this.yScale)));
            }
            _circlesCollide(t4, e2, i2, a2, s2, o2) {
              const r2 = a2 - t4, n2 = s2 - e2, l2 = i2 + o2;
              return l2 * l2 > r2 * r2 + n2 * n2;
            }
            _circleAndRectCollide(t4, e2, i2, a2, s2, o2, r2) {
              const n2 = (o2 - a2) / 2, l2 = Math.abs(t4 - (a2 + n2));
              if (l2 > n2 + i2) return false;
              const h2 = (r2 - s2) / 2, c2 = Math.abs(e2 - (s2 + h2));
              if (c2 > h2 + i2) return false;
              if (l2 <= n2 || c2 <= h2) return true;
              const u2 = l2 - n2, d2 = c2 - h2;
              return u2 * u2 + d2 * d2 <= i2 * i2;
            }
          }
          function gt(t4, i2, a2, s2, o2) {
            const r2 = e.H();
            return i2 ? (e.K(r2, r2, [1 / o2, 1 / o2, 1]), a2 || e.ad(r2, r2, s2.angle)) : e.L(r2, s2.labelPlaneMatrix, t4), r2;
          }
          function vt(t4, i2, a2, s2, o2) {
            if (i2) {
              const i3 = e.ae(t4);
              return e.K(i3, i3, [o2, o2, 1]), a2 || e.ad(i3, i3, -s2.angle), i3;
            }
            return s2.glCoordMatrix;
          }
          function xt(t4, i2, a2, s2) {
            let o2;
            s2 ? (o2 = [t4, i2, s2(t4, i2), 1], e.af(o2, o2, a2)) : (o2 = [t4, i2, 0, 1], kt(o2, o2, a2));
            const r2 = o2[3];
            return { point: new e.P(o2[0] / r2, o2[1] / r2), signedDistanceFromCamera: r2, isOccluded: false };
          }
          function yt(t4, e2) {
            return 0.5 + t4 / e2 * 0.5;
          }
          function bt(t4, e2) {
            return t4.x >= -e2[0] && t4.x <= e2[0] && t4.y >= -e2[1] && t4.y <= e2[1];
          }
          function wt(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, p2, m2) {
            const f2 = s2 ? t4.textSizeData : t4.iconSizeData, g2 = e.ag(f2, a2.transform.zoom), v2 = [256 / a2.width * 2 + 1, 256 / a2.height * 2 + 1], x2 = s2 ? t4.text.dynamicLayoutVertexArray : t4.icon.dynamicLayoutVertexArray;
            x2.clear();
            const y2 = t4.lineVertexArray, b2 = s2 ? t4.text.placedSymbolArray : t4.icon.placedSymbolArray, w2 = a2.transform.width / a2.transform.height;
            let T2 = false;
            for (let s3 = 0; s3 < b2.length; s3++) {
              const I2 = b2.get(s3);
              if (I2.hidden || I2.writingMode === e.ah.vertical && !T2) {
                Rt(I2.numGlyphs, x2);
                continue;
              }
              T2 = false;
              const E3 = xt(I2.anchorX, I2.anchorY, i2, m2);
              if (!bt(E3.point, v2)) {
                Rt(I2.numGlyphs, x2);
                continue;
              }
              const P2 = yt(a2.transform.cameraToCenterDistance, E3.signedDistanceFromCamera), C3 = e.ai(f2, g2, I2), S2 = n2 ? C3 / P2 : C3 * P2, z2 = { getElevation: m2, labelPlaneMatrix: o2, lineVertexArray: y2, pitchWithMap: n2, projectionCache: { projections: {}, offsets: {}, cachedAnchorPoint: void 0, anyProjectionOccluded: false }, projection: c2, tileAnchorPoint: new e.P(I2.anchorX, I2.anchorY), unwrappedTileID: u2, width: d2, height: _2, translation: p2 }, D3 = Et(z2, I2, S2, false, l2, i2, r2, t4.glyphOffsetArray, x2, w2, h2);
              T2 = D3.useVertical, (D3.notEnoughRoom || T2 || D3.needsFlipping && Et(z2, I2, S2, true, l2, i2, r2, t4.glyphOffsetArray, x2, w2, h2).notEnoughRoom) && Rt(I2.numGlyphs, x2);
            }
            s2 ? t4.text.dynamicLayoutVertexBuffer.updateData(x2) : t4.icon.dynamicLayoutVertexBuffer.updateData(x2);
          }
          function Tt(t4, e2, i2, a2, s2, o2, r2, n2) {
            const l2 = o2.glyphStartIndex + o2.numGlyphs, h2 = o2.lineStartIndex, c2 = o2.lineStartIndex + o2.lineLength, u2 = e2.getoffsetX(o2.glyphStartIndex), d2 = e2.getoffsetX(l2 - 1), _2 = Mt(t4 * u2, i2, a2, s2, o2.segment, h2, c2, n2, r2);
            if (!_2) return null;
            const p2 = Mt(t4 * d2, i2, a2, s2, o2.segment, h2, c2, n2, r2);
            return p2 ? n2.projectionCache.anyProjectionOccluded ? null : { first: _2, last: p2 } : null;
          }
          function It(t4, i2, a2, s2) {
            return t4 === e.ah.horizontal && Math.abs(a2.y - i2.y) > Math.abs(a2.x - i2.x) * s2 ? { useVertical: true } : (t4 === e.ah.vertical ? i2.y < a2.y : i2.x > a2.x) ? { needsFlipping: true } : null;
          }
          function Et(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2) {
            const d2 = a2 / 24, _2 = i2.lineOffsetX * d2, p2 = i2.lineOffsetY * d2;
            let m2;
            if (i2.numGlyphs > 1) {
              const e2 = i2.glyphStartIndex + i2.numGlyphs, a3 = i2.lineStartIndex, r3 = i2.lineStartIndex + i2.lineLength, h3 = Tt(d2, l2, _2, p2, s2, i2, u2, t4);
              if (!h3) return { notEnoughRoom: true };
              const f2 = xt(h3.first.point.x, h3.first.point.y, n2, t4.getElevation).point, g2 = xt(h3.last.point.x, h3.last.point.y, n2, t4.getElevation).point;
              if (o2 && !s2) {
                const t5 = It(i2.writingMode, f2, g2, c2);
                if (t5) return t5;
              }
              m2 = [h3.first];
              for (let o3 = i2.glyphStartIndex + 1; o3 < e2 - 1; o3++) m2.push(Mt(d2 * l2.getoffsetX(o3), _2, p2, s2, i2.segment, a3, r3, t4, u2));
              m2.push(h3.last);
            } else {
              if (o2 && !s2) {
                const a4 = xt(t4.tileAnchorPoint.x, t4.tileAnchorPoint.y, r2, t4.getElevation).point, s3 = i2.lineStartIndex + i2.segment + 1, o3 = new e.P(t4.lineVertexArray.getx(s3), t4.lineVertexArray.gety(s3)), n3 = xt(o3.x, o3.y, r2, t4.getElevation), l3 = n3.signedDistanceFromCamera > 0 ? n3.point : function(t5, e2, i3, a5, s4, o4) {
                  return Pt(t5, e2, i3, 1, s4, o4);
                }(t4.tileAnchorPoint, o3, a4, 0, r2, t4), h3 = It(i2.writingMode, a4, l3, c2);
                if (h3) return h3;
              }
              const a3 = Mt(d2 * l2.getoffsetX(i2.glyphStartIndex), _2, p2, s2, i2.segment, i2.lineStartIndex, i2.lineStartIndex + i2.lineLength, t4, u2);
              if (!a3 || t4.projectionCache.anyProjectionOccluded) return { notEnoughRoom: true };
              m2 = [a3];
            }
            for (const t5 of m2) e.aj(h2, t5.point, t5.angle);
            return {};
          }
          function Pt(t4, e2, i2, a2, s2, o2) {
            const r2 = t4.add(t4.sub(e2)._unit()), n2 = void 0 !== s2 ? xt(r2.x, r2.y, s2, o2.getElevation).point : St(r2.x, r2.y, o2).point, l2 = i2.sub(n2);
            return i2.add(l2._mult(a2 / l2.mag()));
          }
          function Ct(t4, i2, a2) {
            const s2 = i2.projectionCache;
            if (s2.projections[t4]) return s2.projections[t4];
            const o2 = new e.P(i2.lineVertexArray.getx(t4), i2.lineVertexArray.gety(t4)), r2 = St(o2.x, o2.y, i2);
            if (r2.signedDistanceFromCamera > 0) return s2.projections[t4] = r2.point, s2.anyProjectionOccluded = s2.anyProjectionOccluded || r2.isOccluded, r2.point;
            const n2 = t4 - a2.direction;
            return function(t5, e2, i3, a3, s3) {
              return Pt(t5, e2, i3, a3, void 0, s3);
            }(0 === a2.distanceFromAnchor ? i2.tileAnchorPoint : new e.P(i2.lineVertexArray.getx(n2), i2.lineVertexArray.gety(n2)), o2, a2.previousVertex, a2.absOffsetX - a2.distanceFromAnchor + 1, i2);
          }
          function St(t4, e2, i2) {
            const a2 = t4 + i2.translation[0], s2 = e2 + i2.translation[1];
            let o2;
            return !i2.pitchWithMap && i2.projection.useSpecialProjectionForSymbols ? (o2 = i2.projection.projectTileCoordinates(a2, s2, i2.unwrappedTileID, i2.getElevation), o2.point.x = (0.5 * o2.point.x + 0.5) * i2.width, o2.point.y = (0.5 * -o2.point.y + 0.5) * i2.height) : (o2 = xt(a2, s2, i2.labelPlaneMatrix, i2.getElevation), o2.isOccluded = false), o2;
          }
          function zt(t4, e2, i2) {
            return t4._unit()._perp()._mult(e2 * i2);
          }
          function Dt(t4, i2, a2, s2, o2, r2, n2, l2, h2) {
            if (l2.projectionCache.offsets[t4]) return l2.projectionCache.offsets[t4];
            const c2 = a2.add(i2);
            if (t4 + h2.direction < s2 || t4 + h2.direction >= o2) return l2.projectionCache.offsets[t4] = c2, c2;
            const u2 = Ct(t4 + h2.direction, l2, h2), d2 = zt(u2.sub(a2), n2, h2.direction), _2 = a2.add(d2), p2 = u2.add(d2);
            return l2.projectionCache.offsets[t4] = e.ak(r2, c2, _2, p2) || c2, l2.projectionCache.offsets[t4];
          }
          function Mt(t4, e2, i2, a2, s2, o2, r2, n2, l2) {
            const h2 = a2 ? t4 - e2 : t4 + e2;
            let c2 = h2 > 0 ? 1 : -1, u2 = 0;
            a2 && (c2 *= -1, u2 = Math.PI), c2 < 0 && (u2 += Math.PI);
            let d2, _2 = c2 > 0 ? o2 + s2 : o2 + s2 + 1;
            n2.projectionCache.cachedAnchorPoint ? d2 = n2.projectionCache.cachedAnchorPoint : (d2 = St(n2.tileAnchorPoint.x, n2.tileAnchorPoint.y, n2).point, n2.projectionCache.cachedAnchorPoint = d2);
            let p2, m2, f2 = d2, g2 = d2, v2 = 0, x2 = 0;
            const y2 = Math.abs(h2), b2 = [];
            let w2;
            for (; v2 + x2 <= y2; ) {
              if (_2 += c2, _2 < o2 || _2 >= r2) return null;
              v2 += x2, g2 = f2, m2 = p2;
              const t5 = { absOffsetX: y2, direction: c2, distanceFromAnchor: v2, previousVertex: g2 };
              if (f2 = Ct(_2, n2, t5), 0 === i2) b2.push(g2), w2 = f2.sub(g2);
              else {
                let e3;
                const a3 = f2.sub(g2);
                e3 = 0 === a3.mag() ? zt(Ct(_2 + c2, n2, t5).sub(f2), i2, c2) : zt(a3, i2, c2), m2 || (m2 = g2.add(e3)), p2 = Dt(_2, e3, f2, o2, r2, m2, i2, n2, t5), b2.push(m2), w2 = p2.sub(m2);
              }
              x2 = w2.mag();
            }
            const T2 = w2._mult((y2 - v2) / x2)._add(m2 || g2), I2 = u2 + Math.atan2(f2.y - g2.y, f2.x - g2.x);
            return b2.push(T2), { point: T2, angle: l2 ? I2 : 0, path: b2 };
          }
          const At = new Float32Array([-1 / 0, -1 / 0, 0, -1 / 0, -1 / 0, 0, -1 / 0, -1 / 0, 0, -1 / 0, -1 / 0, 0]);
          function Rt(t4, e2) {
            for (let i2 = 0; i2 < t4; i2++) {
              const t5 = e2.length;
              e2.resize(t5 + 4), e2.float32.set(At, 3 * t5);
            }
          }
          function kt(t4, e2, i2) {
            const a2 = e2[0], s2 = e2[1];
            return t4[0] = i2[0] * a2 + i2[4] * s2 + i2[12], t4[1] = i2[1] * a2 + i2[5] * s2 + i2[13], t4[3] = i2[3] * a2 + i2[7] * s2 + i2[15], t4;
          }
          const Lt = 100;
          class Ft {
            constructor(t4, e2, i2 = new ft(t4.width + 200, t4.height + 200, 25), a2 = new ft(t4.width + 200, t4.height + 200, 25)) {
              this.transform = t4, this.mapProjection = e2, this.grid = i2, this.ignoredGrid = a2, this.pitchFactor = Math.cos(t4._pitch) * t4.cameraToCenterDistance, this.screenRightBoundary = t4.width + Lt, this.screenBottomBoundary = t4.height + Lt, this.gridRightBoundary = t4.width + 200, this.gridBottomBoundary = t4.height + 200, this.perspectiveRatioCutoff = 0.6;
            }
            placeCollisionBox(t4, e2, i2, a2, s2, o2, r2, n2, l2, h2, c2) {
              const u2 = t4.anchorPointX + n2[0], d2 = t4.anchorPointY + n2[1], _2 = this.projectAndGetPerspectiveRatio(a2, u2, d2, s2, h2), p2 = i2 * _2.perspectiveRatio;
              let m2;
              if (o2 || r2) m2 = this._projectCollisionBox(t4, p2, a2, s2, o2, r2, n2, _2, h2, c2);
              else {
                const e3 = _2.point.x + (c2 ? c2.x * p2 : 0), i3 = _2.point.y + (c2 ? c2.y * p2 : 0);
                m2 = { allPointsOccluded: false, box: [e3 + t4.x1 * p2, i3 + t4.y1 * p2, e3 + t4.x2 * p2, i3 + t4.y2 * p2] };
              }
              const [f2, g2, v2, x2] = m2.box;
              return this.mapProjection.useSpecialProjectionForSymbols && (o2 ? m2.allPointsOccluded : this.mapProjection.isOccluded(u2, d2, s2)) || _2.perspectiveRatio < this.perspectiveRatioCutoff || !this.isInsideGrid(f2, g2, v2, x2) || "always" !== e2 && this.grid.hitTest(f2, g2, v2, x2, e2, l2) ? { box: [f2, g2, v2, x2], placeable: false, offscreen: false } : { box: [f2, g2, v2, x2], placeable: true, offscreen: this.isOffscreen(f2, g2, v2, x2) };
            }
            placeCollisionCircles(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, p2, m2, f2) {
              const g2 = [], v2 = new e.P(i2.anchorX, i2.anchorY), x2 = this.getPerspectiveRatio(r2, v2.x, v2.y, n2, f2), y2 = (u2 ? o2 / x2 : o2 * x2) / e.ap, b2 = { getElevation: f2, labelPlaneMatrix: l2, lineVertexArray: a2, pitchWithMap: u2, projectionCache: { projections: {}, offsets: {}, cachedAnchorPoint: void 0, anyProjectionOccluded: false }, projection: this.mapProjection, tileAnchorPoint: v2, unwrappedTileID: n2, width: this.transform.width, height: this.transform.height, translation: m2 }, w2 = Tt(y2, s2, i2.lineOffsetX * y2, i2.lineOffsetY * y2, false, i2, false, b2);
              let T2 = false, I2 = false, E3 = true;
              if (w2) {
                const i3 = 0.5 * _2 * x2 + p2, a3 = new e.P(-100, -100), s3 = new e.P(this.screenRightBoundary, this.screenBottomBoundary), o3 = new pt(), r3 = w2.first, n3 = w2.last;
                let l3 = [];
                for (let t5 = r3.path.length - 1; t5 >= 1; t5--) l3.push(r3.path[t5]);
                for (let t5 = 1; t5 < n3.path.length; t5++) l3.push(n3.path[t5]);
                const u3 = 2.5 * i3;
                if (h2) {
                  const t5 = this.projectPathToScreenSpace(l3, b2, h2);
                  l3 = t5.some((t6) => t6.signedDistanceFromCamera <= 0) ? [] : t5.map((t6) => t6.point);
                }
                let m3 = [];
                if (l3.length > 0) {
                  const t5 = l3[0].clone(), i4 = l3[0].clone();
                  for (let e2 = 1; e2 < l3.length; e2++) t5.x = Math.min(t5.x, l3[e2].x), t5.y = Math.min(t5.y, l3[e2].y), i4.x = Math.max(i4.x, l3[e2].x), i4.y = Math.max(i4.y, l3[e2].y);
                  m3 = t5.x >= a3.x && i4.x <= s3.x && t5.y >= a3.y && i4.y <= s3.y ? [l3] : i4.x < a3.x || t5.x > s3.x || i4.y < a3.y || t5.y > s3.y ? [] : e.al([l3], a3.x, a3.y, s3.x, s3.y);
                }
                for (const e2 of m3) {
                  o3.reset(e2, 0.25 * i3);
                  let a4 = 0;
                  a4 = o3.length <= 0.5 * i3 ? 1 : Math.ceil(o3.paddedLength / u3) + 1;
                  for (let e3 = 0; e3 < a4; e3++) {
                    const s4 = e3 / Math.max(a4 - 1, 1), r4 = o3.lerp(s4), n4 = r4.x + Lt, l4 = r4.y + Lt;
                    g2.push(n4, l4, i3, 0);
                    const h3 = n4 - i3, u4 = l4 - i3, _3 = n4 + i3, p3 = l4 + i3;
                    if (E3 = E3 && this.isOffscreen(h3, u4, _3, p3), I2 = I2 || this.isInsideGrid(h3, u4, _3, p3), "always" !== t4 && this.grid.hitTestCircle(n4, l4, i3, t4, d2) && (T2 = true, !c2)) return { circles: [], offscreen: false, collisionDetected: T2 };
                  }
                }
              }
              return { circles: !c2 && T2 || !I2 || x2 < this.perspectiveRatioCutoff ? [] : g2, offscreen: E3, collisionDetected: T2 };
            }
            projectPathToScreenSpace(t4, e2, i2) {
              return t4.map((t5) => xt(t5.x, t5.y, i2, e2.getElevation));
            }
            queryRenderedSymbols(t4) {
              if (0 === t4.length || 0 === this.grid.keysLength() && 0 === this.ignoredGrid.keysLength()) return {};
              const i2 = [];
              let a2 = 1 / 0, s2 = 1 / 0, o2 = -1 / 0, r2 = -1 / 0;
              for (const n3 of t4) {
                const t5 = new e.P(n3.x + Lt, n3.y + Lt);
                a2 = Math.min(a2, t5.x), s2 = Math.min(s2, t5.y), o2 = Math.max(o2, t5.x), r2 = Math.max(r2, t5.y), i2.push(t5);
              }
              const n2 = this.grid.query(a2, s2, o2, r2).concat(this.ignoredGrid.query(a2, s2, o2, r2)), l2 = {}, h2 = {};
              for (const t5 of n2) {
                const a3 = t5.key;
                if (void 0 === l2[a3.bucketInstanceId] && (l2[a3.bucketInstanceId] = {}), l2[a3.bucketInstanceId][a3.featureIndex]) continue;
                const s3 = [new e.P(t5.x1, t5.y1), new e.P(t5.x2, t5.y1), new e.P(t5.x2, t5.y2), new e.P(t5.x1, t5.y2)];
                e.am(i2, s3) && (l2[a3.bucketInstanceId][a3.featureIndex] = true, void 0 === h2[a3.bucketInstanceId] && (h2[a3.bucketInstanceId] = []), h2[a3.bucketInstanceId].push(a3.featureIndex));
              }
              return h2;
            }
            insertCollisionBox(t4, e2, i2, a2, s2, o2) {
              (i2 ? this.ignoredGrid : this.grid).insert({ bucketInstanceId: a2, featureIndex: s2, collisionGroupID: o2, overlapMode: e2 }, t4[0], t4[1], t4[2], t4[3]);
            }
            insertCollisionCircles(t4, e2, i2, a2, s2, o2) {
              const r2 = i2 ? this.ignoredGrid : this.grid, n2 = { bucketInstanceId: a2, featureIndex: s2, collisionGroupID: o2, overlapMode: e2 };
              for (let e3 = 0; e3 < t4.length; e3 += 4) r2.insertCircle(n2, t4[e3], t4[e3 + 1], t4[e3 + 2]);
            }
            projectAndGetPerspectiveRatio(t4, i2, a2, s2, o2) {
              let r2;
              o2 ? (r2 = [i2, a2, o2(i2, a2), 1], e.af(r2, r2, t4)) : (r2 = [i2, a2, 0, 1], kt(r2, r2, t4));
              const n2 = r2[3];
              return { point: new e.P((r2[0] / n2 + 1) / 2 * this.transform.width + Lt, (-r2[1] / n2 + 1) / 2 * this.transform.height + Lt), perspectiveRatio: 0.5 + this.transform.cameraToCenterDistance / n2 * 0.5, isOccluded: false, signedDistanceFromCamera: n2 };
            }
            getPerspectiveRatio(t4, e2, i2, a2, s2) {
              const o2 = this.mapProjection.useSpecialProjectionForSymbols ? this.mapProjection.projectTileCoordinates(e2, i2, a2, s2) : xt(e2, i2, t4, s2);
              return 0.5 + this.transform.cameraToCenterDistance / o2.signedDistanceFromCamera * 0.5;
            }
            isOffscreen(t4, e2, i2, a2) {
              return i2 < Lt || t4 >= this.screenRightBoundary || a2 < Lt || e2 > this.screenBottomBoundary;
            }
            isInsideGrid(t4, e2, i2, a2) {
              return i2 >= 0 && t4 < this.gridRightBoundary && a2 >= 0 && e2 < this.gridBottomBoundary;
            }
            getViewportMatrix() {
              const t4 = e.an([]);
              return e.J(t4, t4, [-100, -100, 0]), t4;
            }
            _projectCollisionBox(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2) {
              let u2 = new e.P(1, 0), d2 = new e.P(0, 1);
              const _2 = new e.P(t4.anchorPointX + n2[0], t4.anchorPointY + n2[1]);
              if (r2 && !o2) {
                const t5 = this.projectAndGetPerspectiveRatio(a2, _2.x + 1, _2.y, s2, h2).point.sub(l2.point).unit(), i3 = Math.atan(t5.y / t5.x) + (t5.x < 0 ? Math.PI : 0), o3 = Math.sin(i3), r3 = Math.cos(i3);
                u2 = new e.P(r3, o3), d2 = new e.P(-o3, r3);
              } else if (!r2 && o2) {
                const t5 = -this.transform.angle, i3 = Math.sin(t5), a3 = Math.cos(t5);
                u2 = new e.P(a3, i3), d2 = new e.P(-i3, a3);
              }
              let p2 = l2.point, m2 = i2;
              if (o2) {
                p2 = _2;
                const t5 = this.transform.zoom - Math.floor(this.transform.zoom);
                m2 = Math.pow(2, -t5), m2 *= this.mapProjection.getPitchedTextCorrection(this.transform, _2, s2), c2 || (m2 *= e.ac(0.5 + l2.signedDistanceFromCamera / this.transform.cameraToCenterDistance * 0.5, 0, 4));
              }
              c2 && (p2 = p2.add(u2.mult(c2.x * m2)).add(d2.mult(c2.y * m2)));
              const f2 = t4.x1 * m2, g2 = t4.x2 * m2, v2 = (f2 + g2) / 2, x2 = t4.y1 * m2, y2 = t4.y2 * m2, b2 = (x2 + y2) / 2, w2 = [{ offsetX: f2, offsetY: x2 }, { offsetX: v2, offsetY: x2 }, { offsetX: g2, offsetY: x2 }, { offsetX: g2, offsetY: b2 }, { offsetX: g2, offsetY: y2 }, { offsetX: v2, offsetY: y2 }, { offsetX: f2, offsetY: y2 }, { offsetX: f2, offsetY: b2 }];
              let T2 = [];
              for (const { offsetX: t5, offsetY: i3 } of w2) T2.push(new e.P(p2.x + u2.x * t5 + d2.x * i3, p2.y + u2.y * t5 + d2.y * i3));
              let I2 = false;
              if (o2) {
                const t5 = T2.map((t6) => this.projectAndGetPerspectiveRatio(a2, t6.x, t6.y, s2, h2));
                I2 = t5.some((t6) => !t6.isOccluded), T2 = t5.map((t6) => t6.point);
              } else I2 = true;
              return { box: e.ao(T2), allPointsOccluded: !I2 };
            }
          }
          function Bt(t4, i2, a2) {
            return i2 * (e.X / (t4.tileSize * Math.pow(2, a2 - t4.tileID.overscaledZ)));
          }
          class Ot {
            constructor(t4, e2, i2, a2) {
              this.opacity = t4 ? Math.max(0, Math.min(1, t4.opacity + (t4.placed ? e2 : -e2))) : a2 && i2 ? 1 : 0, this.placed = i2;
            }
            isHidden() {
              return 0 === this.opacity && !this.placed;
            }
          }
          class Nt {
            constructor(t4, e2, i2, a2, s2) {
              this.text = new Ot(t4 ? t4.text : null, e2, i2, s2), this.icon = new Ot(t4 ? t4.icon : null, e2, a2, s2);
            }
            isHidden() {
              return this.text.isHidden() && this.icon.isHidden();
            }
          }
          class Ut {
            constructor(t4, e2, i2) {
              this.text = t4, this.icon = e2, this.skipFade = i2;
            }
          }
          class jt {
            constructor() {
              this.invProjMatrix = e.H(), this.viewportMatrix = e.H(), this.circles = [];
            }
          }
          class Zt {
            constructor(t4, e2, i2, a2, s2) {
              this.bucketInstanceId = t4, this.featureIndex = e2, this.sourceLayerIndex = i2, this.bucketIndex = a2, this.tileID = s2;
            }
          }
          class qt {
            constructor(t4) {
              this.crossSourceCollisions = t4, this.maxGroupID = 0, this.collisionGroups = {};
            }
            get(t4) {
              if (this.crossSourceCollisions) return { ID: 0, predicate: null };
              if (!this.collisionGroups[t4]) {
                const e2 = ++this.maxGroupID;
                this.collisionGroups[t4] = { ID: e2, predicate: (t5) => t5.collisionGroupID === e2 };
              }
              return this.collisionGroups[t4];
            }
          }
          function Vt(t4, i2, a2, s2, o2) {
            const { horizontalAlign: r2, verticalAlign: n2 } = e.au(t4);
            return new e.P(-(r2 - 0.5) * i2 + s2[0] * o2, -(n2 - 0.5) * a2 + s2[1] * o2);
          }
          class Gt {
            constructor(t4, e2, i2, a2, s2, o2) {
              this.transform = t4.clone(), this.terrain = i2, this.collisionIndex = new Ft(this.transform, e2), this.placements = {}, this.opacities = {}, this.variableOffsets = {}, this.stale = false, this.commitTime = 0, this.fadeDuration = a2, this.retainedQueryData = {}, this.collisionGroups = new qt(s2), this.collisionCircleArrays = {}, this.collisionBoxArrays = /* @__PURE__ */ new Map(), this.prevPlacement = o2, o2 && (o2.prevPlacement = void 0), this.placedOrientations = {};
            }
            _getTerrainElevationFunc(t4) {
              const e2 = this.terrain;
              return e2 ? (i2, a2) => e2.getElevation(t4, i2, a2) : null;
            }
            getBucketParts(t4, i2, a2, s2) {
              const o2 = a2.getBucket(i2), r2 = a2.latestFeatureIndex;
              if (!o2 || !r2 || i2.id !== o2.layerIds[0]) return;
              const n2 = a2.collisionBoxArray, l2 = o2.layers[0].layout, h2 = o2.layers[0].paint, c2 = Math.pow(2, this.transform.zoom - a2.tileID.overscaledZ), u2 = a2.tileSize / e.X, d2 = a2.tileID.toUnwrapped(), _2 = this.transform.calculatePosMatrix(d2), p2 = "map" === l2.get("text-pitch-alignment"), m2 = "map" === l2.get("text-rotation-alignment"), f2 = Bt(a2, 1, this.transform.zoom), g2 = this.collisionIndex.mapProjection.translatePosition(this.transform, a2, h2.get("text-translate"), h2.get("text-translate-anchor")), v2 = this.collisionIndex.mapProjection.translatePosition(this.transform, a2, h2.get("icon-translate"), h2.get("icon-translate-anchor")), x2 = gt(_2, p2, m2, this.transform, f2);
              let y2 = null;
              if (p2) {
                const t5 = vt(_2, p2, m2, this.transform, f2);
                y2 = e.L([], this.transform.labelPlaneMatrix, t5);
              }
              this.retainedQueryData[o2.bucketInstanceId] = new Zt(o2.bucketInstanceId, r2, o2.sourceLayerIndex, o2.index, a2.tileID);
              const b2 = { bucket: o2, layout: l2, translationText: g2, translationIcon: v2, posMatrix: _2, unwrappedTileID: d2, textLabelPlaneMatrix: x2, labelToScreenMatrix: y2, scale: c2, textPixelRatio: u2, holdingForFade: a2.holdingForFade(), collisionBoxArray: n2, partiallyEvaluatedTextSize: e.ag(o2.textSizeData, this.transform.zoom), collisionGroup: this.collisionGroups.get(o2.sourceID) };
              if (s2) for (const e2 of o2.sortKeyRanges) {
                const { sortKey: i3, symbolInstanceStart: a3, symbolInstanceEnd: s3 } = e2;
                t4.push({ sortKey: i3, symbolInstanceStart: a3, symbolInstanceEnd: s3, parameters: b2 });
              }
              else t4.push({ symbolInstanceStart: 0, symbolInstanceEnd: o2.symbolInstances.length, parameters: b2 });
            }
            attemptAnchorPlacement(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, p2, m2, f2, g2, v2, x2) {
              const y2 = e.aq[t4.textAnchor], b2 = [t4.textOffset0, t4.textOffset1], w2 = Vt(y2, a2, s2, b2, o2), T2 = this.collisionIndex.placeCollisionBox(i2, d2, l2, h2, c2, n2, r2, f2, u2.predicate, x2, w2);
              if ((!v2 || this.collisionIndex.placeCollisionBox(v2, d2, l2, h2, c2, n2, r2, g2, u2.predicate, x2, w2).placeable) && T2.placeable) {
                let t5;
                if (this.prevPlacement && this.prevPlacement.variableOffsets[_2.crossTileID] && this.prevPlacement.placements[_2.crossTileID] && this.prevPlacement.placements[_2.crossTileID].text && (t5 = this.prevPlacement.variableOffsets[_2.crossTileID].anchor), 0 === _2.crossTileID) throw new Error("symbolInstance.crossTileID can't be 0");
                return this.variableOffsets[_2.crossTileID] = { textOffset: b2, width: a2, height: s2, anchor: y2, textBoxScale: o2, prevAnchor: t5 }, this.markUsedJustification(p2, y2, _2, m2), p2.allowVerticalPlacement && (this.markUsedOrientation(p2, m2, _2), this.placedOrientations[_2.crossTileID] = m2), { shift: w2, placedGlyphBoxes: T2 };
              }
            }
            placeLayerBucketPart(t4, i2, a2) {
              const { bucket: s2, layout: o2, translationText: r2, translationIcon: n2, posMatrix: l2, unwrappedTileID: h2, textLabelPlaneMatrix: c2, labelToScreenMatrix: u2, textPixelRatio: d2, holdingForFade: _2, collisionBoxArray: p2, partiallyEvaluatedTextSize: m2, collisionGroup: f2 } = t4.parameters, g2 = o2.get("text-optional"), v2 = o2.get("icon-optional"), x2 = e.ar(o2, "text-overlap", "text-allow-overlap"), y2 = "always" === x2, b2 = e.ar(o2, "icon-overlap", "icon-allow-overlap"), w2 = "always" === b2, T2 = "map" === o2.get("text-rotation-alignment"), I2 = "map" === o2.get("text-pitch-alignment"), E3 = "none" !== o2.get("icon-text-fit"), P2 = "viewport-y" === o2.get("symbol-z-order"), C3 = y2 && (w2 || !s2.hasIconData() || v2), S2 = w2 && (y2 || !s2.hasTextData() || g2);
              !s2.collisionArrays && p2 && s2.deserializeCollisionBoxes(p2);
              const z2 = this._getTerrainElevationFunc(this.retainedQueryData[s2.bucketInstanceId].tileID), D3 = (t5, p3, w3) => {
                var P3, D4;
                if (i2[t5.crossTileID]) return;
                if (_2) return void (this.placements[t5.crossTileID] = new Ut(false, false, false));
                let M2 = false, A3 = false, R2 = true, k2 = null, L2 = { box: null, placeable: false, offscreen: null }, F2 = { box: null, placeable: false, offscreen: null }, B3 = null, O2 = null, N2 = null, U2 = 0, j2 = 0, Z2 = 0;
                p3.textFeatureIndex ? U2 = p3.textFeatureIndex : t5.useRuntimeCollisionCircles && (U2 = t5.featureIndex), p3.verticalTextFeatureIndex && (j2 = p3.verticalTextFeatureIndex);
                const q2 = p3.textBox;
                if (q2) {
                  const i3 = (i4) => {
                    let a3 = e.ah.horizontal;
                    if (s2.allowVerticalPlacement && !i4 && this.prevPlacement) {
                      const e2 = this.prevPlacement.placedOrientations[t5.crossTileID];
                      e2 && (this.placedOrientations[t5.crossTileID] = e2, a3 = e2, this.markUsedOrientation(s2, a3, t5));
                    }
                    return a3;
                  }, o3 = (i4, a3) => {
                    if (s2.allowVerticalPlacement && t5.numVerticalGlyphVertices > 0 && p3.verticalTextBox) {
                      for (const t6 of s2.writingModes) if (t6 === e.ah.vertical ? (L2 = a3(), F2 = L2) : L2 = i4(), L2 && L2.placeable) break;
                    } else L2 = i4();
                  }, c3 = t5.textAnchorOffsetStartIndex, u3 = t5.textAnchorOffsetEndIndex;
                  if (u3 === c3) {
                    const a3 = (e2, i4) => {
                      const a4 = this.collisionIndex.placeCollisionBox(e2, x2, d2, l2, h2, I2, T2, r2, f2.predicate, z2);
                      return a4 && a4.placeable && (this.markUsedOrientation(s2, i4, t5), this.placedOrientations[t5.crossTileID] = i4), a4;
                    };
                    o3(() => a3(q2, e.ah.horizontal), () => {
                      const i4 = p3.verticalTextBox;
                      return s2.allowVerticalPlacement && t5.numVerticalGlyphVertices > 0 && i4 ? a3(i4, e.ah.vertical) : { box: null, offscreen: null };
                    }), i3(L2 && L2.placeable);
                  } else {
                    let _3 = e.aq[null === (D4 = null === (P3 = this.prevPlacement) || void 0 === P3 ? void 0 : P3.variableOffsets[t5.crossTileID]) || void 0 === D4 ? void 0 : D4.anchor];
                    const m3 = (i4, o4, p4) => {
                      const m4 = i4.x2 - i4.x1, g4 = i4.y2 - i4.y1, v3 = t5.textBoxScale, y3 = E3 && "never" === b2 ? o4 : null;
                      let w4 = null, P4 = "never" === x2 ? 1 : 2, C4 = "never";
                      _3 && P4++;
                      for (let e2 = 0; e2 < P4; e2++) {
                        for (let e3 = c3; e3 < u3; e3++) {
                          const a3 = s2.textAnchorOffsets.get(e3);
                          if (_3 && a3.textAnchor !== _3) continue;
                          const o5 = this.attemptAnchorPlacement(a3, i4, m4, g4, v3, T2, I2, d2, l2, h2, f2, C4, t5, s2, p4, r2, n2, y3, z2);
                          if (o5 && (w4 = o5.placedGlyphBoxes, w4 && w4.placeable)) return M2 = true, k2 = o5.shift, w4;
                        }
                        _3 ? _3 = null : C4 = x2;
                      }
                      return a2 && !w4 && (w4 = { box: this.collisionIndex.placeCollisionBox(q2, "always", d2, l2, h2, I2, T2, r2, f2.predicate, z2, new e.P(0, 0)).box, offscreen: false, placeable: false }), w4;
                    };
                    o3(() => m3(q2, p3.iconBox, e.ah.horizontal), () => {
                      const i4 = p3.verticalTextBox;
                      return s2.allowVerticalPlacement && (!L2 || !L2.placeable) && t5.numVerticalGlyphVertices > 0 && i4 ? m3(i4, p3.verticalIconBox, e.ah.vertical) : { box: null, occluded: true, offscreen: null };
                    }), L2 && (M2 = L2.placeable, R2 = L2.offscreen);
                    const g3 = i3(L2 && L2.placeable);
                    if (!M2 && this.prevPlacement) {
                      const e2 = this.prevPlacement.variableOffsets[t5.crossTileID];
                      e2 && (this.variableOffsets[t5.crossTileID] = e2, this.markUsedJustification(s2, e2.anchor, t5, g3));
                    }
                  }
                }
                if (B3 = L2, M2 = B3 && B3.placeable, R2 = B3 && B3.offscreen, t5.useRuntimeCollisionCircles) {
                  const i3 = s2.text.placedSymbolArray.get(t5.centerJustifiedTextSymbolIndex), n3 = e.ai(s2.textSizeData, m2, i3), d3 = o2.get("text-padding");
                  O2 = this.collisionIndex.placeCollisionCircles(x2, i3, s2.lineVertexArray, s2.glyphOffsetArray, n3, l2, h2, c2, u2, a2, I2, f2.predicate, t5.collisionCircleDiameter, d3, r2, z2), O2.circles.length && O2.collisionDetected && !a2 && e.w("Collisions detected, but collision boxes are not shown"), M2 = y2 || O2.circles.length > 0 && !O2.collisionDetected, R2 = R2 && O2.offscreen;
                }
                if (p3.iconFeatureIndex && (Z2 = p3.iconFeatureIndex), p3.iconBox) {
                  const t6 = (t7) => this.collisionIndex.placeCollisionBox(t7, b2, d2, l2, h2, I2, T2, n2, f2.predicate, z2, E3 && k2 ? k2 : void 0);
                  F2 && F2.placeable && p3.verticalIconBox ? (N2 = t6(p3.verticalIconBox), A3 = N2.placeable) : (N2 = t6(p3.iconBox), A3 = N2.placeable), R2 = R2 && N2.offscreen;
                }
                const V2 = g2 || 0 === t5.numHorizontalGlyphVertices && 0 === t5.numVerticalGlyphVertices, G2 = v2 || 0 === t5.numIconVertices;
                V2 || G2 ? G2 ? V2 || (A3 = A3 && M2) : M2 = A3 && M2 : A3 = M2 = A3 && M2;
                const H2 = A3 && N2.placeable;
                if (M2 && B3.placeable && this.collisionIndex.insertCollisionBox(B3.box, x2, o2.get("text-ignore-placement"), s2.bucketInstanceId, F2 && F2.placeable && j2 ? j2 : U2, f2.ID), H2 && this.collisionIndex.insertCollisionBox(N2.box, b2, o2.get("icon-ignore-placement"), s2.bucketInstanceId, Z2, f2.ID), O2 && M2 && this.collisionIndex.insertCollisionCircles(O2.circles, x2, o2.get("text-ignore-placement"), s2.bucketInstanceId, U2, f2.ID), a2 && this.storeCollisionData(s2.bucketInstanceId, w3, p3, B3, N2, O2), 0 === t5.crossTileID) throw new Error("symbolInstance.crossTileID can't be 0");
                if (0 === s2.bucketInstanceId) throw new Error("bucket.bucketInstanceId can't be 0");
                this.placements[t5.crossTileID] = new Ut(M2 || C3, A3 || S2, R2 || s2.justReloaded), i2[t5.crossTileID] = true;
              };
              if (P2) {
                if (0 !== t4.symbolInstanceStart) throw new Error("bucket.bucketInstanceId should be 0");
                const e2 = s2.getSortedSymbolIndexes(this.transform.angle);
                for (let t5 = e2.length - 1; t5 >= 0; --t5) {
                  const i3 = e2[t5];
                  D3(s2.symbolInstances.get(i3), s2.collisionArrays[i3], i3);
                }
              } else for (let e2 = t4.symbolInstanceStart; e2 < t4.symbolInstanceEnd; e2++) D3(s2.symbolInstances.get(e2), s2.collisionArrays[e2], e2);
              if (a2 && s2.bucketInstanceId in this.collisionCircleArrays) {
                const t5 = this.collisionCircleArrays[s2.bucketInstanceId];
                e.as(t5.invProjMatrix, l2), t5.viewportMatrix = this.collisionIndex.getViewportMatrix();
              }
              s2.justReloaded = false;
            }
            storeCollisionData(t4, e2, i2, a2, s2, o2) {
              if (i2.textBox || i2.iconBox) {
                let o3, r2;
                this.collisionBoxArrays.has(t4) ? o3 = this.collisionBoxArrays.get(t4) : (o3 = /* @__PURE__ */ new Map(), this.collisionBoxArrays.set(t4, o3)), o3.has(e2) ? r2 = o3.get(e2) : (r2 = { text: null, icon: null }, o3.set(e2, r2)), i2.textBox && (r2.text = a2.box), i2.iconBox && (r2.icon = s2.box);
              }
              if (o2) {
                let e3 = this.collisionCircleArrays[t4];
                void 0 === e3 && (e3 = this.collisionCircleArrays[t4] = new jt());
                for (let t5 = 0; t5 < o2.circles.length; t5 += 4) e3.circles.push(o2.circles[t5 + 0]), e3.circles.push(o2.circles[t5 + 1]), e3.circles.push(o2.circles[t5 + 2]), e3.circles.push(o2.collisionDetected ? 1 : 0);
              }
            }
            markUsedJustification(t4, i2, a2, s2) {
              let o2;
              o2 = s2 === e.ah.vertical ? a2.verticalPlacedTextSymbolIndex : { left: a2.leftJustifiedTextSymbolIndex, center: a2.centerJustifiedTextSymbolIndex, right: a2.rightJustifiedTextSymbolIndex }[e.at(i2)];
              const r2 = [a2.leftJustifiedTextSymbolIndex, a2.centerJustifiedTextSymbolIndex, a2.rightJustifiedTextSymbolIndex, a2.verticalPlacedTextSymbolIndex];
              for (const e2 of r2) e2 >= 0 && (t4.text.placedSymbolArray.get(e2).crossTileID = o2 >= 0 && e2 !== o2 ? 0 : a2.crossTileID);
            }
            markUsedOrientation(t4, i2, a2) {
              const s2 = i2 === e.ah.horizontal || i2 === e.ah.horizontalOnly ? i2 : 0, o2 = i2 === e.ah.vertical ? i2 : 0, r2 = [a2.leftJustifiedTextSymbolIndex, a2.centerJustifiedTextSymbolIndex, a2.rightJustifiedTextSymbolIndex];
              for (const e2 of r2) t4.text.placedSymbolArray.get(e2).placedOrientation = s2;
              a2.verticalPlacedTextSymbolIndex && (t4.text.placedSymbolArray.get(a2.verticalPlacedTextSymbolIndex).placedOrientation = o2);
            }
            commit(t4) {
              this.commitTime = t4, this.zoomAtLastRecencyCheck = this.transform.zoom;
              const e2 = this.prevPlacement;
              let i2 = false;
              this.prevZoomAdjustment = e2 ? e2.zoomAdjustment(this.transform.zoom) : 0;
              const a2 = e2 ? e2.symbolFadeChange(t4) : 1, s2 = e2 ? e2.opacities : {}, o2 = e2 ? e2.variableOffsets : {}, r2 = e2 ? e2.placedOrientations : {};
              for (const t5 in this.placements) {
                const e3 = this.placements[t5], o3 = s2[t5];
                o3 ? (this.opacities[t5] = new Nt(o3, a2, e3.text, e3.icon), i2 = i2 || e3.text !== o3.text.placed || e3.icon !== o3.icon.placed) : (this.opacities[t5] = new Nt(null, a2, e3.text, e3.icon, e3.skipFade), i2 = i2 || e3.text || e3.icon);
              }
              for (const t5 in s2) {
                const e3 = s2[t5];
                if (!this.opacities[t5]) {
                  const s3 = new Nt(e3, a2, false, false);
                  s3.isHidden() || (this.opacities[t5] = s3, i2 = i2 || e3.text.placed || e3.icon.placed);
                }
              }
              for (const t5 in o2) this.variableOffsets[t5] || !this.opacities[t5] || this.opacities[t5].isHidden() || (this.variableOffsets[t5] = o2[t5]);
              for (const t5 in r2) this.placedOrientations[t5] || !this.opacities[t5] || this.opacities[t5].isHidden() || (this.placedOrientations[t5] = r2[t5]);
              if (e2 && void 0 === e2.lastPlacementChangeTime) throw new Error("Last placement time for previous placement is not defined");
              i2 ? this.lastPlacementChangeTime = t4 : "number" != typeof this.lastPlacementChangeTime && (this.lastPlacementChangeTime = e2 ? e2.lastPlacementChangeTime : t4);
            }
            updateLayerOpacities(t4, e2) {
              const i2 = {};
              for (const a2 of e2) {
                const e3 = a2.getBucket(t4);
                e3 && a2.latestFeatureIndex && t4.id === e3.layerIds[0] && this.updateBucketOpacities(e3, a2.tileID, i2, a2.collisionBoxArray);
              }
            }
            updateBucketOpacities(t4, i2, a2, s2) {
              t4.hasTextData() && (t4.text.opacityVertexArray.clear(), t4.text.hasVisibleVertices = false), t4.hasIconData() && (t4.icon.opacityVertexArray.clear(), t4.icon.hasVisibleVertices = false), t4.hasIconCollisionBoxData() && t4.iconCollisionBox.collisionVertexArray.clear(), t4.hasTextCollisionBoxData() && t4.textCollisionBox.collisionVertexArray.clear();
              const o2 = t4.layers[0], r2 = o2.layout, n2 = new Nt(null, 0, false, false, true), l2 = r2.get("text-allow-overlap"), h2 = r2.get("icon-allow-overlap"), c2 = o2._unevaluatedLayout.hasValue("text-variable-anchor") || o2._unevaluatedLayout.hasValue("text-variable-anchor-offset"), u2 = "map" === r2.get("text-rotation-alignment"), d2 = "map" === r2.get("text-pitch-alignment"), _2 = "none" !== r2.get("icon-text-fit"), p2 = new Nt(null, 0, l2 && (h2 || !t4.hasIconData() || r2.get("icon-optional")), h2 && (l2 || !t4.hasTextData() || r2.get("text-optional")), true);
              !t4.collisionArrays && s2 && (t4.hasIconCollisionBoxData() || t4.hasTextCollisionBoxData()) && t4.deserializeCollisionBoxes(s2);
              const m2 = (t5, e2, i3) => {
                for (let a3 = 0; a3 < e2 / 4; a3++) t5.opacityVertexArray.emplaceBack(i3);
                t5.hasVisibleVertices = t5.hasVisibleVertices || i3 !== ee;
              }, f2 = this.collisionBoxArrays.get(t4.bucketInstanceId);
              for (let i3 = 0; i3 < t4.symbolInstances.length; i3++) {
                const s3 = t4.symbolInstances.get(i3), { numHorizontalGlyphVertices: o3, numVerticalGlyphVertices: r3, crossTileID: l3 } = s3;
                let h3 = this.opacities[l3];
                a2[l3] ? h3 = n2 : h3 || (h3 = p2, this.opacities[l3] = h3), a2[l3] = true;
                const g2 = s3.numIconVertices > 0, v2 = this.placedOrientations[s3.crossTileID], x2 = v2 === e.ah.vertical, y2 = v2 === e.ah.horizontal || v2 === e.ah.horizontalOnly;
                if (o3 > 0 || r3 > 0) {
                  const e2 = te(h3.text);
                  m2(t4.text, o3, x2 ? ee : e2), m2(t4.text, r3, y2 ? ee : e2);
                  const i4 = h3.text.isHidden();
                  [s3.rightJustifiedTextSymbolIndex, s3.centerJustifiedTextSymbolIndex, s3.leftJustifiedTextSymbolIndex].forEach((e3) => {
                    e3 >= 0 && (t4.text.placedSymbolArray.get(e3).hidden = i4 || x2 ? 1 : 0);
                  }), s3.verticalPlacedTextSymbolIndex >= 0 && (t4.text.placedSymbolArray.get(s3.verticalPlacedTextSymbolIndex).hidden = i4 || y2 ? 1 : 0);
                  const a3 = this.variableOffsets[s3.crossTileID];
                  a3 && this.markUsedJustification(t4, a3.anchor, s3, v2);
                  const n3 = this.placedOrientations[s3.crossTileID];
                  n3 && (this.markUsedJustification(t4, "left", s3, n3), this.markUsedOrientation(t4, n3, s3));
                }
                if (g2) {
                  const e2 = te(h3.icon), i4 = !(_2 && s3.verticalPlacedIconSymbolIndex && x2);
                  s3.placedIconSymbolIndex >= 0 && (m2(t4.icon, s3.numIconVertices, i4 ? e2 : ee), t4.icon.placedSymbolArray.get(s3.placedIconSymbolIndex).hidden = h3.icon.isHidden()), s3.verticalPlacedIconSymbolIndex >= 0 && (m2(t4.icon, s3.numVerticalIconVertices, i4 ? ee : e2), t4.icon.placedSymbolArray.get(s3.verticalPlacedIconSymbolIndex).hidden = h3.icon.isHidden());
                }
                const b2 = f2 && f2.has(i3) ? f2.get(i3) : { text: null, icon: null };
                if (t4.hasIconCollisionBoxData() || t4.hasTextCollisionBoxData()) {
                  const a3 = t4.collisionArrays[i3];
                  if (a3) {
                    let i4 = new e.P(0, 0);
                    if (a3.textBox || a3.verticalTextBox) {
                      let e2 = true;
                      if (c2) {
                        const t5 = this.variableOffsets[l3];
                        t5 ? (i4 = Vt(t5.anchor, t5.width, t5.height, t5.textOffset, t5.textBoxScale), u2 && i4._rotate(d2 ? this.transform.angle : -this.transform.angle)) : e2 = false;
                      }
                      if (a3.textBox || a3.verticalTextBox) {
                        let s4;
                        a3.textBox && (s4 = x2), a3.verticalTextBox && (s4 = y2), Ht(t4.textCollisionBox.collisionVertexArray, h3.text.placed, !e2 || s4, b2.text, i4.x, i4.y);
                      }
                    }
                    if (a3.iconBox || a3.verticalIconBox) {
                      const e2 = Boolean(!y2 && a3.verticalIconBox);
                      let s4;
                      a3.iconBox && (s4 = e2), a3.verticalIconBox && (s4 = !e2), Ht(t4.iconCollisionBox.collisionVertexArray, h3.icon.placed, s4, b2.icon, _2 ? i4.x : 0, _2 ? i4.y : 0);
                    }
                  }
                }
              }
              if (t4.sortFeatures(this.transform.angle), this.retainedQueryData[t4.bucketInstanceId] && (this.retainedQueryData[t4.bucketInstanceId].featureSortOrder = t4.featureSortOrder), t4.hasTextData() && t4.text.opacityVertexBuffer && t4.text.opacityVertexBuffer.updateData(t4.text.opacityVertexArray), t4.hasIconData() && t4.icon.opacityVertexBuffer && t4.icon.opacityVertexBuffer.updateData(t4.icon.opacityVertexArray), t4.hasIconCollisionBoxData() && t4.iconCollisionBox.collisionVertexBuffer && t4.iconCollisionBox.collisionVertexBuffer.updateData(t4.iconCollisionBox.collisionVertexArray), t4.hasTextCollisionBoxData() && t4.textCollisionBox.collisionVertexBuffer && t4.textCollisionBox.collisionVertexBuffer.updateData(t4.textCollisionBox.collisionVertexArray), t4.text.opacityVertexArray.length !== t4.text.layoutVertexArray.length / 4) throw new Error(`bucket.text.opacityVertexArray.length (= ${t4.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${t4.text.layoutVertexArray.length}) / 4`);
              if (t4.icon.opacityVertexArray.length !== t4.icon.layoutVertexArray.length / 4) throw new Error(`bucket.icon.opacityVertexArray.length (= ${t4.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${t4.icon.layoutVertexArray.length}) / 4`);
              if (t4.bucketInstanceId in this.collisionCircleArrays) {
                const e2 = this.collisionCircleArrays[t4.bucketInstanceId];
                t4.placementInvProjMatrix = e2.invProjMatrix, t4.placementViewportMatrix = e2.viewportMatrix, t4.collisionCircleArray = e2.circles, delete this.collisionCircleArrays[t4.bucketInstanceId];
              }
            }
            symbolFadeChange(t4) {
              return 0 === this.fadeDuration ? 1 : (t4 - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment;
            }
            zoomAdjustment(t4) {
              return Math.max(0, (this.transform.zoom - t4) / 1.5);
            }
            hasTransitions(t4) {
              return this.stale || t4 - this.lastPlacementChangeTime < this.fadeDuration;
            }
            stillRecent(t4, e2) {
              const i2 = this.zoomAtLastRecencyCheck === e2 ? 1 - this.zoomAdjustment(e2) : 1;
              return this.zoomAtLastRecencyCheck = e2, this.commitTime + this.fadeDuration * i2 > t4;
            }
            setStale() {
              this.stale = true;
            }
          }
          function Ht(t4, e2, i2, a2, s2, o2) {
            a2 && 0 !== a2.length || (a2 = [0, 0, 0, 0]);
            const r2 = a2[0] - Lt, n2 = a2[1] - Lt, l2 = a2[2] - Lt, h2 = a2[3] - Lt;
            t4.emplaceBack(e2 ? 1 : 0, i2 ? 1 : 0, s2 || 0, o2 || 0, r2, n2), t4.emplaceBack(e2 ? 1 : 0, i2 ? 1 : 0, s2 || 0, o2 || 0, l2, n2), t4.emplaceBack(e2 ? 1 : 0, i2 ? 1 : 0, s2 || 0, o2 || 0, l2, h2), t4.emplaceBack(e2 ? 1 : 0, i2 ? 1 : 0, s2 || 0, o2 || 0, r2, h2);
          }
          const Wt = Math.pow(2, 25), $t = Math.pow(2, 24), Xt = Math.pow(2, 17), Kt = Math.pow(2, 16), Jt = Math.pow(2, 9), Yt = Math.pow(2, 8), Qt = Math.pow(2, 1);
          function te(t4) {
            if (0 === t4.opacity && !t4.placed) return 0;
            if (1 === t4.opacity && t4.placed) return 4294967295;
            const e2 = t4.placed ? 1 : 0, i2 = Math.floor(127 * t4.opacity);
            return i2 * Wt + e2 * $t + i2 * Xt + e2 * Kt + i2 * Jt + e2 * Yt + i2 * Qt + e2;
          }
          const ee = 0;
          function ie() {
            return { isOccluded: (t4, e2, i2) => false, getPitchedTextCorrection: (t4, e2, i2) => 1, get useSpecialProjectionForSymbols() {
              return false;
            }, projectTileCoordinates(t4, e2, i2, a2) {
              throw new Error("Not implemented.");
            }, translatePosition: (t4, e2, i2, a2) => function(t5, e3, i3, a3, s2 = false) {
              if (!i3[0] && !i3[1]) return [0, 0];
              const o2 = s2 ? "map" === a3 ? t5.angle : 0 : "viewport" === a3 ? -t5.angle : 0;
              if (o2) {
                const t6 = Math.sin(o2), e4 = Math.cos(o2);
                i3 = [i3[0] * e4 - i3[1] * t6, i3[0] * t6 + i3[1] * e4];
              }
              return [s2 ? i3[0] : Bt(e3, i3[0], t5.zoom), s2 ? i3[1] : Bt(e3, i3[1], t5.zoom)];
            }(t4, e2, i2, a2), getCircleRadiusCorrection: (t4) => 1 };
          }
          class ae {
            constructor(t4) {
              this._sortAcrossTiles = "viewport-y" !== t4.layout.get("symbol-z-order") && !t4.layout.get("symbol-sort-key").isConstant(), this._currentTileIndex = 0, this._currentPartIndex = 0, this._seenCrossTileIDs = {}, this._bucketParts = [];
            }
            continuePlacement(t4, e2, i2, a2, s2) {
              const o2 = this._bucketParts;
              for (; this._currentTileIndex < t4.length; ) if (e2.getBucketParts(o2, a2, t4[this._currentTileIndex], this._sortAcrossTiles), this._currentTileIndex++, s2()) return true;
              for (this._sortAcrossTiles && (this._sortAcrossTiles = false, o2.sort((t5, e3) => t5.sortKey - e3.sortKey)); this._currentPartIndex < o2.length; ) if (e2.placeLayerBucketPart(o2[this._currentPartIndex], this._seenCrossTileIDs, i2), this._currentPartIndex++, s2()) return true;
              return false;
            }
          }
          class se {
            constructor(t4, e2, i2, a2, s2, o2, r2, n2) {
              this.placement = new Gt(t4, ie(), e2, o2, r2, n2), this._currentPlacementIndex = i2.length - 1, this._forceFullPlacement = a2, this._showCollisionBoxes = s2, this._done = false;
            }
            isDone() {
              return this._done;
            }
            continuePlacement(t4, e2, i2) {
              const a2 = o.now(), s2 = () => !this._forceFullPlacement && o.now() - a2 > 2;
              for (; this._currentPlacementIndex >= 0; ) {
                const a3 = e2[t4[this._currentPlacementIndex]], o2 = this.placement.collisionIndex.transform.zoom;
                if ("symbol" === a3.type && (!a3.minzoom || a3.minzoom <= o2) && (!a3.maxzoom || a3.maxzoom > o2)) {
                  if (this._inProgressLayer || (this._inProgressLayer = new ae(a3)), this._inProgressLayer.continuePlacement(i2[a3.source], this.placement, this._showCollisionBoxes, a3, s2)) return;
                  delete this._inProgressLayer;
                }
                this._currentPlacementIndex--;
              }
              this._done = true;
            }
            commit(t4) {
              return this.placement.commit(t4), this.placement;
            }
          }
          const oe = 512 / e.X / 2;
          class re {
            constructor(t4, i2, a2) {
              this.tileID = t4, this.bucketInstanceId = a2, this._symbolsByKey = {};
              const s2 = /* @__PURE__ */ new Map();
              for (let t5 = 0; t5 < i2.length; t5++) {
                const e2 = i2.get(t5), a3 = e2.key, o2 = s2.get(a3);
                o2 ? o2.push(e2) : s2.set(a3, [e2]);
              }
              for (const [t5, i3] of s2) {
                const a3 = { positions: i3.map((t6) => ({ x: Math.floor(t6.anchorX * oe), y: Math.floor(t6.anchorY * oe) })), crossTileIDs: i3.map((t6) => t6.crossTileID) };
                if (a3.positions.length > 128) {
                  const t6 = new e.av(a3.positions.length, 16, Uint16Array);
                  for (const { x: e2, y: i4 } of a3.positions) t6.add(e2, i4);
                  t6.finish(), delete a3.positions, a3.index = t6;
                }
                this._symbolsByKey[t5] = a3;
              }
            }
            getScaledCoordinates(t4, i2) {
              const { x: a2, y: s2, z: o2 } = this.tileID.canonical, { x: r2, y: n2, z: l2 } = i2.canonical, h2 = oe / Math.pow(2, l2 - o2), c2 = (n2 * e.X + t4.anchorY) * h2, u2 = s2 * e.X * oe;
              return { x: Math.floor((r2 * e.X + t4.anchorX) * h2 - a2 * e.X * oe), y: Math.floor(c2 - u2) };
            }
            findMatches(t4, e2, i2) {
              const a2 = this.tileID.canonical.z < e2.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - e2.canonical.z);
              for (let s2 = 0; s2 < t4.length; s2++) {
                const o2 = t4.get(s2);
                if (o2.crossTileID) continue;
                const r2 = this._symbolsByKey[o2.key];
                if (!r2) continue;
                const n2 = this.getScaledCoordinates(o2, e2);
                if (r2.index) {
                  const t5 = r2.index.range(n2.x - a2, n2.y - a2, n2.x + a2, n2.y + a2).sort();
                  for (const e3 of t5) {
                    const t6 = r2.crossTileIDs[e3];
                    if (!i2[t6]) {
                      i2[t6] = true, o2.crossTileID = t6;
                      break;
                    }
                  }
                } else if (r2.positions) for (let t5 = 0; t5 < r2.positions.length; t5++) {
                  const e3 = r2.positions[t5], s3 = r2.crossTileIDs[t5];
                  if (Math.abs(e3.x - n2.x) <= a2 && Math.abs(e3.y - n2.y) <= a2 && !i2[s3]) {
                    i2[s3] = true, o2.crossTileID = s3;
                    break;
                  }
                }
              }
            }
            getCrossTileIDsLists() {
              return Object.values(this._symbolsByKey).map(({ crossTileIDs: t4 }) => t4);
            }
          }
          class ne {
            constructor() {
              this.maxCrossTileID = 0;
            }
            generate() {
              return ++this.maxCrossTileID;
            }
          }
          class le {
            constructor() {
              this.indexes = {}, this.usedCrossTileIDs = {}, this.lng = 0;
            }
            handleWrapJump(t4) {
              const e2 = Math.round((t4 - this.lng) / 360);
              if (0 !== e2) for (const t5 in this.indexes) {
                const i2 = this.indexes[t5], a2 = {};
                for (const t6 in i2) {
                  const s2 = i2[t6];
                  s2.tileID = s2.tileID.unwrapTo(s2.tileID.wrap + e2), a2[s2.tileID.key] = s2;
                }
                this.indexes[t5] = a2;
              }
              this.lng = t4;
            }
            addBucket(t4, e2, i2) {
              if (this.indexes[t4.overscaledZ] && this.indexes[t4.overscaledZ][t4.key]) {
                if (this.indexes[t4.overscaledZ][t4.key].bucketInstanceId === e2.bucketInstanceId) return false;
                this.removeBucketCrossTileIDs(t4.overscaledZ, this.indexes[t4.overscaledZ][t4.key]);
              }
              for (let t5 = 0; t5 < e2.symbolInstances.length; t5++) e2.symbolInstances.get(t5).crossTileID = 0;
              this.usedCrossTileIDs[t4.overscaledZ] || (this.usedCrossTileIDs[t4.overscaledZ] = {});
              const a2 = this.usedCrossTileIDs[t4.overscaledZ];
              for (const i3 in this.indexes) {
                const s2 = this.indexes[i3];
                if (Number(i3) > t4.overscaledZ) for (const i4 in s2) {
                  const o2 = s2[i4];
                  o2.tileID.isChildOf(t4) && o2.findMatches(e2.symbolInstances, t4, a2);
                }
                else {
                  const o2 = s2[t4.scaledTo(Number(i3)).key];
                  o2 && o2.findMatches(e2.symbolInstances, t4, a2);
                }
              }
              for (let t5 = 0; t5 < e2.symbolInstances.length; t5++) {
                const s2 = e2.symbolInstances.get(t5);
                s2.crossTileID || (s2.crossTileID = i2.generate(), a2[s2.crossTileID] = true);
              }
              return void 0 === this.indexes[t4.overscaledZ] && (this.indexes[t4.overscaledZ] = {}), this.indexes[t4.overscaledZ][t4.key] = new re(t4, e2.symbolInstances, e2.bucketInstanceId), true;
            }
            removeBucketCrossTileIDs(t4, e2) {
              for (const i2 of e2.getCrossTileIDsLists()) for (const e3 of i2) delete this.usedCrossTileIDs[t4][e3];
            }
            removeStaleBuckets(t4) {
              let e2 = false;
              for (const i2 in this.indexes) {
                const a2 = this.indexes[i2];
                for (const s2 in a2) t4[a2[s2].bucketInstanceId] || (this.removeBucketCrossTileIDs(i2, a2[s2]), delete a2[s2], e2 = true);
              }
              return e2;
            }
          }
          class he {
            constructor() {
              this.layerIndexes = {}, this.crossTileIDs = new ne(), this.maxBucketInstanceId = 0, this.bucketsInCurrentPlacement = {};
            }
            addLayer(t4, e2, i2) {
              let a2 = this.layerIndexes[t4.id];
              void 0 === a2 && (a2 = this.layerIndexes[t4.id] = new le());
              let s2 = false;
              const o2 = {};
              a2.handleWrapJump(i2);
              for (const i3 of e2) {
                const e3 = i3.getBucket(t4);
                e3 && t4.id === e3.layerIds[0] && (e3.bucketInstanceId || (e3.bucketInstanceId = ++this.maxBucketInstanceId), a2.addBucket(i3.tileID, e3, this.crossTileIDs) && (s2 = true), o2[e3.bucketInstanceId] = true);
              }
              return a2.removeStaleBuckets(o2) && (s2 = true), s2;
            }
            pruneUnusedLayers(t4) {
              const e2 = {};
              t4.forEach((t5) => {
                e2[t5] = true;
              });
              for (const t5 in this.layerIndexes) e2[t5] || delete this.layerIndexes[t5];
            }
          }
          const ce = (t4, i2) => e.t(t4, i2 && i2.filter((t5) => "source.canvas" !== t5.identifier)), ue = e.aw();
          class de extends e.E {
            constructor(t4, i2 = {}) {
              super(), this._rtlPluginLoaded = () => {
                for (const t5 in this.sourceCaches) {
                  const e2 = this.sourceCaches[t5].getSource().type;
                  "vector" !== e2 && "geojson" !== e2 || this.sourceCaches[t5].reload();
                }
              }, this.map = t4, this.dispatcher = new U(N(), t4._getMapId()), this.dispatcher.registerMessageHandler("GG", (t5, e2) => this.getGlyphs(t5, e2)), this.dispatcher.registerMessageHandler("GI", (t5, e2) => this.getImages(t5, e2)), this.imageManager = new T(), this.imageManager.setEventedParent(this), this.glyphManager = new C2(t4._requestManager, i2.localIdeographFontFamily), this.lineAtlas = new R(256, 512), this.crossTileSymbolIndex = new he(), this._spritesImagesIds = {}, this._layers = {}, this._order = [], this.sourceCaches = {}, this.zoomHistory = new e.ax(), this._loaded = false, this._availableImages = [], this._resetUpdates(), this.dispatcher.broadcast("SR", e.ay()), nt().on(st, this._rtlPluginLoaded), this.on("data", (t5) => {
                if ("source" !== t5.dataType || "metadata" !== t5.sourceDataType) return;
                const e2 = this.sourceCaches[t5.sourceId];
                if (!e2) return;
                const i3 = e2.getSource();
                if (i3 && i3.vectorLayerIds) for (const t6 in this._layers) {
                  const e3 = this._layers[t6];
                  e3.source === i3.id && this._validateLayer(e3);
                }
              });
            }
            loadURL(t4, i2 = {}, a2) {
              this.fire(new e.k("dataloading", { dataType: "style" })), i2.validate = "boolean" != typeof i2.validate || i2.validate;
              const s2 = this.map._requestManager.transformRequest(t4, "Style");
              this._loadStyleRequest = new AbortController();
              const o2 = this._loadStyleRequest;
              e.h(s2, this._loadStyleRequest).then((t5) => {
                this._loadStyleRequest = null, this._load(t5.data, i2, a2);
              }).catch((t5) => {
                this._loadStyleRequest = null, t5 && !o2.signal.aborted && this.fire(new e.j(t5));
              });
            }
            loadJSON(t4, i2 = {}, a2) {
              this.fire(new e.k("dataloading", { dataType: "style" })), this._frameRequest = new AbortController(), o.frameAsync(this._frameRequest).then(() => {
                this._frameRequest = null, i2.validate = false !== i2.validate, this._load(t4, i2, a2);
              }).catch(() => {
              });
            }
            loadEmpty() {
              this.fire(new e.k("dataloading", { dataType: "style" })), this._load(ue, { validate: false });
            }
            _load(t4, i2, a2) {
              var s2;
              const o2 = i2.transformStyle ? i2.transformStyle(a2, t4) : t4;
              if (!i2.validate || !ce(this, e.u(o2))) {
                this._loaded = true, this.stylesheet = o2;
                for (const t5 in o2.sources) this.addSource(t5, o2.sources[t5], { validate: false });
                o2.sprite ? this._loadSprite(o2.sprite) : this.imageManager.setLoaded(true), this.glyphManager.setURL(o2.glyphs), this._createLayers(), this.light = new D2(this.stylesheet.light), this.sky = new A2(this.stylesheet.sky), this.map.setTerrain(null !== (s2 = this.stylesheet.terrain) && void 0 !== s2 ? s2 : null), this.fire(new e.k("data", { dataType: "style" })), this.fire(new e.k("style.load"));
              }
            }
            _createLayers() {
              const t4 = e.az(this.stylesheet.layers);
              this.dispatcher.broadcast("SL", t4), this._order = t4.map((t5) => t5.id), this._layers = {}, this._serializedLayers = null;
              for (const i2 of t4) {
                const t5 = e.aA(i2);
                t5.setEventedParent(this, { layer: { id: i2.id } }), this._layers[i2.id] = t5;
              }
            }
            _loadSprite(t4, i2 = false, a2 = void 0) {
              let s2;
              this.imageManager.setLoaded(false), this._spriteRequest = new AbortController(), function(t5, i3, a3, s3) {
                return e._(this, void 0, void 0, function* () {
                  const r2 = x(t5), n2 = a3 > 1 ? "@2x" : "", l2 = {}, h2 = {};
                  for (const { id: t6, url: a4 } of r2) {
                    const o2 = i3.transformRequest(y(a4, n2, ".json"), "SpriteJSON");
                    l2[t6] = e.h(o2, s3);
                    const r3 = i3.transformRequest(y(a4, n2, ".png"), "SpriteImage");
                    h2[t6] = _.getImage(r3, s3);
                  }
                  return yield Promise.all([...Object.values(l2), ...Object.values(h2)]), function(t6, i4) {
                    return e._(this, void 0, void 0, function* () {
                      const e2 = {};
                      for (const a4 in t6) {
                        e2[a4] = {};
                        const s4 = o.getImageCanvasContext((yield i4[a4]).data), r3 = (yield t6[a4]).data;
                        for (const t7 in r3) {
                          const { width: i5, height: o2, x: n3, y: l3, sdf: h3, pixelRatio: c2, stretchX: u2, stretchY: d2, content: _2, textFitWidth: p2, textFitHeight: m2 } = r3[t7];
                          e2[a4][t7] = { data: null, pixelRatio: c2, sdf: h3, stretchX: u2, stretchY: d2, content: _2, textFitWidth: p2, textFitHeight: m2, spriteData: { width: i5, height: o2, x: n3, y: l3, context: s4 } };
                        }
                      }
                      return e2;
                    });
                  }(l2, h2);
                });
              }(t4, this.map._requestManager, this.map.getPixelRatio(), this._spriteRequest).then((t5) => {
                if (this._spriteRequest = null, t5) for (const e2 in t5) {
                  this._spritesImagesIds[e2] = [];
                  const a3 = this._spritesImagesIds[e2] ? this._spritesImagesIds[e2].filter((e3) => !(e3 in t5)) : [];
                  for (const t6 of a3) this.imageManager.removeImage(t6), this._changedImages[t6] = true;
                  for (const a4 in t5[e2]) {
                    const s3 = "default" === e2 ? a4 : `${e2}:${a4}`;
                    this._spritesImagesIds[e2].push(s3), s3 in this.imageManager.images ? this.imageManager.updateImage(s3, t5[e2][a4], false) : this.imageManager.addImage(s3, t5[e2][a4]), i2 && (this._changedImages[s3] = true);
                  }
                }
              }).catch((t5) => {
                this._spriteRequest = null, s2 = t5, this.fire(new e.j(s2));
              }).finally(() => {
                this.imageManager.setLoaded(true), this._availableImages = this.imageManager.listImages(), i2 && (this._changed = true), this.dispatcher.broadcast("SI", this._availableImages), this.fire(new e.k("data", { dataType: "style" })), a2 && a2(s2);
              });
            }
            _unloadSprite() {
              for (const t4 of Object.values(this._spritesImagesIds).flat()) this.imageManager.removeImage(t4), this._changedImages[t4] = true;
              this._spritesImagesIds = {}, this._availableImages = this.imageManager.listImages(), this._changed = true, this.dispatcher.broadcast("SI", this._availableImages), this.fire(new e.k("data", { dataType: "style" }));
            }
            _validateLayer(t4) {
              const i2 = this.sourceCaches[t4.source];
              if (!i2) return;
              const a2 = t4.sourceLayer;
              if (!a2) return;
              const s2 = i2.getSource();
              ("geojson" === s2.type || s2.vectorLayerIds && -1 === s2.vectorLayerIds.indexOf(a2)) && this.fire(new e.j(new Error(`Source layer "${a2}" does not exist on source "${s2.id}" as specified by style layer "${t4.id}".`)));
            }
            loaded() {
              if (!this._loaded) return false;
              if (Object.keys(this._updatedSources).length) return false;
              for (const t4 in this.sourceCaches) if (!this.sourceCaches[t4].loaded()) return false;
              return !!this.imageManager.isLoaded();
            }
            _serializeByIds(t4, i2 = false) {
              const a2 = this._serializedAllLayers();
              if (!t4 || 0 === t4.length) return Object.values(i2 ? e.aB(a2) : a2);
              const s2 = [];
              for (const o2 of t4) if (a2[o2]) {
                const t5 = i2 ? e.aB(a2[o2]) : a2[o2];
                s2.push(t5);
              }
              return s2;
            }
            _serializedAllLayers() {
              let t4 = this._serializedLayers;
              if (t4) return t4;
              t4 = this._serializedLayers = {};
              const e2 = Object.keys(this._layers);
              for (const i2 of e2) {
                const e3 = this._layers[i2];
                "custom" !== e3.type && (t4[i2] = e3.serialize());
              }
              return t4;
            }
            hasTransitions() {
              if (this.light && this.light.hasTransition()) return true;
              if (this.sky && this.sky.hasTransition()) return true;
              for (const t4 in this.sourceCaches) if (this.sourceCaches[t4].hasTransition()) return true;
              for (const t4 in this._layers) if (this._layers[t4].hasTransition()) return true;
              return false;
            }
            _checkLoaded() {
              if (!this._loaded) throw new Error("Style is not done loading.");
            }
            update(t4) {
              if (!this._loaded) return;
              const i2 = this._changed;
              if (i2) {
                const e2 = Object.keys(this._updatedLayers), i3 = Object.keys(this._removedLayers);
                (e2.length || i3.length) && this._updateWorkerLayers(e2, i3);
                for (const t5 in this._updatedSources) {
                  const e3 = this._updatedSources[t5];
                  if ("reload" === e3) this._reloadSource(t5);
                  else {
                    if ("clear" !== e3) throw new Error(`Invalid action ${e3}`);
                    this._clearSource(t5);
                  }
                }
                this._updateTilesForChangedImages(), this._updateTilesForChangedGlyphs();
                for (const e3 in this._updatedPaintProps) this._layers[e3].updateTransitions(t4);
                this.light.updateTransitions(t4), this.sky.updateTransitions(t4), this._resetUpdates();
              }
              const a2 = {};
              for (const t5 in this.sourceCaches) {
                const e2 = this.sourceCaches[t5];
                a2[t5] = e2.used, e2.used = false;
              }
              for (const e2 of this._order) {
                const i3 = this._layers[e2];
                i3.recalculate(t4, this._availableImages), !i3.isHidden(t4.zoom) && i3.source && (this.sourceCaches[i3.source].used = true);
              }
              for (const t5 in a2) {
                const i3 = this.sourceCaches[t5];
                !!a2[t5] != !!i3.used && i3.fire(new e.k("data", { sourceDataType: "visibility", dataType: "source", sourceId: t5 }));
              }
              this.light.recalculate(t4), this.sky.recalculate(t4), this.z = t4.zoom, i2 && this.fire(new e.k("data", { dataType: "style" }));
            }
            _updateTilesForChangedImages() {
              const t4 = Object.keys(this._changedImages);
              if (t4.length) {
                for (const e2 in this.sourceCaches) this.sourceCaches[e2].reloadTilesForDependencies(["icons", "patterns"], t4);
                this._changedImages = {};
              }
            }
            _updateTilesForChangedGlyphs() {
              if (this._glyphsDidChange) {
                for (const t4 in this.sourceCaches) this.sourceCaches[t4].reloadTilesForDependencies(["glyphs"], [""]);
                this._glyphsDidChange = false;
              }
            }
            _updateWorkerLayers(t4, e2) {
              this.dispatcher.broadcast("UL", { layers: this._serializeByIds(t4, false), removedIds: e2 });
            }
            _resetUpdates() {
              this._changed = false, this._updatedLayers = {}, this._removedLayers = {}, this._updatedSources = {}, this._updatedPaintProps = {}, this._changedImages = {}, this._glyphsDidChange = false;
            }
            setState(t4, i2 = {}) {
              var a2;
              this._checkLoaded();
              const s2 = this.serialize();
              if (t4 = i2.transformStyle ? i2.transformStyle(s2, t4) : t4, (null === (a2 = i2.validate) || void 0 === a2 || a2) && ce(this, e.u(t4))) return false;
              (t4 = e.aB(t4)).layers = e.az(t4.layers);
              const o2 = e.aC(s2, t4), r2 = this._getOperationsToPerform(o2);
              if (r2.unimplemented.length > 0) throw new Error(`Unimplemented: ${r2.unimplemented.join(", ")}.`);
              if (0 === r2.operations.length) return false;
              for (const t5 of r2.operations) t5();
              return this.stylesheet = t4, this._serializedLayers = null, true;
            }
            _getOperationsToPerform(t4) {
              const e2 = [], i2 = [];
              for (const a2 of t4) switch (a2.command) {
                case "setCenter":
                case "setZoom":
                case "setBearing":
                case "setPitch":
                  continue;
                case "addLayer":
                  e2.push(() => this.addLayer.apply(this, a2.args));
                  break;
                case "removeLayer":
                  e2.push(() => this.removeLayer.apply(this, a2.args));
                  break;
                case "setPaintProperty":
                  e2.push(() => this.setPaintProperty.apply(this, a2.args));
                  break;
                case "setLayoutProperty":
                  e2.push(() => this.setLayoutProperty.apply(this, a2.args));
                  break;
                case "setFilter":
                  e2.push(() => this.setFilter.apply(this, a2.args));
                  break;
                case "addSource":
                  e2.push(() => this.addSource.apply(this, a2.args));
                  break;
                case "removeSource":
                  e2.push(() => this.removeSource.apply(this, a2.args));
                  break;
                case "setLayerZoomRange":
                  e2.push(() => this.setLayerZoomRange.apply(this, a2.args));
                  break;
                case "setLight":
                  e2.push(() => this.setLight.apply(this, a2.args));
                  break;
                case "setGeoJSONSourceData":
                  e2.push(() => this.setGeoJSONSourceData.apply(this, a2.args));
                  break;
                case "setGlyphs":
                  e2.push(() => this.setGlyphs.apply(this, a2.args));
                  break;
                case "setSprite":
                  e2.push(() => this.setSprite.apply(this, a2.args));
                  break;
                case "setSky":
                  e2.push(() => this.setSky.apply(this, a2.args));
                  break;
                case "setTerrain":
                  e2.push(() => this.map.setTerrain.apply(this, a2.args));
                  break;
                case "setTransition":
                  e2.push(() => {
                  });
                  break;
                default:
                  i2.push(a2.command);
              }
              return { operations: e2, unimplemented: i2 };
            }
            addImage(t4, i2) {
              if (this.getImage(t4)) return this.fire(new e.j(new Error(`An image named "${t4}" already exists.`)));
              this.imageManager.addImage(t4, i2), this._afterImageUpdated(t4);
            }
            updateImage(t4, e2) {
              this.imageManager.updateImage(t4, e2);
            }
            getImage(t4) {
              return this.imageManager.getImage(t4);
            }
            removeImage(t4) {
              if (!this.getImage(t4)) return this.fire(new e.j(new Error(`An image named "${t4}" does not exist.`)));
              this.imageManager.removeImage(t4), this._afterImageUpdated(t4);
            }
            _afterImageUpdated(t4) {
              this._availableImages = this.imageManager.listImages(), this._changedImages[t4] = true, this._changed = true, this.dispatcher.broadcast("SI", this._availableImages), this.fire(new e.k("data", { dataType: "style" }));
            }
            listImages() {
              return this._checkLoaded(), this.imageManager.listImages();
            }
            addSource(t4, i2, a2 = {}) {
              if (this._checkLoaded(), void 0 !== this.sourceCaches[t4]) throw new Error(`Source "${t4}" already exists.`);
              if (!i2.type) throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i2).join(", ")}.`);
              if (["vector", "raster", "geojson", "video", "image"].indexOf(i2.type) >= 0 && this._validate(e.u.source, `sources.${t4}`, i2, null, a2)) return;
              this.map && this.map._collectResourceTiming && (i2.collectResourceTiming = true);
              const s2 = this.sourceCaches[t4] = new ut(t4, i2, this.dispatcher);
              s2.style = this, s2.setEventedParent(this, () => ({ isSourceLoaded: s2.loaded(), source: s2.serialize(), sourceId: t4 })), s2.onAdd(this.map), this._changed = true;
            }
            removeSource(t4) {
              if (this._checkLoaded(), void 0 === this.sourceCaches[t4]) throw new Error("There is no source with this ID");
              for (const i3 in this._layers) if (this._layers[i3].source === t4) return this.fire(new e.j(new Error(`Source "${t4}" cannot be removed while layer "${i3}" is using it.`)));
              const i2 = this.sourceCaches[t4];
              delete this.sourceCaches[t4], delete this._updatedSources[t4], i2.fire(new e.k("data", { sourceDataType: "metadata", dataType: "source", sourceId: t4 })), i2.setEventedParent(null), i2.onRemove(this.map), this._changed = true;
            }
            setGeoJSONSourceData(t4, e2) {
              if (this._checkLoaded(), void 0 === this.sourceCaches[t4]) throw new Error(`There is no source with this ID=${t4}`);
              const i2 = this.sourceCaches[t4].getSource();
              if ("geojson" !== i2.type) throw new Error(`geojsonSource.type is ${i2.type}, which is !== 'geojson`);
              i2.setData(e2), this._changed = true;
            }
            getSource(t4) {
              return this.sourceCaches[t4] && this.sourceCaches[t4].getSource();
            }
            addLayer(t4, i2, a2 = {}) {
              this._checkLoaded();
              const s2 = t4.id;
              if (this.getLayer(s2)) return void this.fire(new e.j(new Error(`Layer "${s2}" already exists on this map.`)));
              let o2;
              if ("custom" === t4.type) {
                if (ce(this, e.aD(t4))) return;
                o2 = e.aA(t4);
              } else {
                if ("source" in t4 && "object" == typeof t4.source && (this.addSource(s2, t4.source), t4 = e.aB(t4), t4 = e.e(t4, { source: s2 })), this._validate(e.u.layer, `layers.${s2}`, t4, { arrayIndex: -1 }, a2)) return;
                o2 = e.aA(t4), this._validateLayer(o2), o2.setEventedParent(this, { layer: { id: s2 } });
              }
              const r2 = i2 ? this._order.indexOf(i2) : this._order.length;
              if (i2 && -1 === r2) this.fire(new e.j(new Error(`Cannot add layer "${s2}" before non-existing layer "${i2}".`)));
              else {
                if (this._order.splice(r2, 0, s2), this._layerOrderChanged = true, this._layers[s2] = o2, this._removedLayers[s2] && o2.source && "custom" !== o2.type) {
                  const t5 = this._removedLayers[s2];
                  delete this._removedLayers[s2], t5.type !== o2.type ? this._updatedSources[o2.source] = "clear" : (this._updatedSources[o2.source] = "reload", this.sourceCaches[o2.source].pause());
                }
                this._updateLayer(o2), o2.onAdd && o2.onAdd(this.map);
              }
            }
            moveLayer(t4, i2) {
              if (this._checkLoaded(), this._changed = true, !this._layers[t4]) return void this.fire(new e.j(new Error(`The layer '${t4}' does not exist in the map's style and cannot be moved.`)));
              if (t4 === i2) return;
              const a2 = this._order.indexOf(t4);
              this._order.splice(a2, 1);
              const s2 = i2 ? this._order.indexOf(i2) : this._order.length;
              i2 && -1 === s2 ? this.fire(new e.j(new Error(`Cannot move layer "${t4}" before non-existing layer "${i2}".`))) : (this._order.splice(s2, 0, t4), this._layerOrderChanged = true);
            }
            removeLayer(t4) {
              this._checkLoaded();
              const i2 = this._layers[t4];
              if (!i2) return void this.fire(new e.j(new Error(`Cannot remove non-existing layer "${t4}".`)));
              i2.setEventedParent(null);
              const a2 = this._order.indexOf(t4);
              this._order.splice(a2, 1), this._layerOrderChanged = true, this._changed = true, this._removedLayers[t4] = i2, delete this._layers[t4], this._serializedLayers && delete this._serializedLayers[t4], delete this._updatedLayers[t4], delete this._updatedPaintProps[t4], i2.onRemove && i2.onRemove(this.map);
            }
            getLayer(t4) {
              return this._layers[t4];
            }
            getLayersOrder() {
              return [...this._order];
            }
            hasLayer(t4) {
              return t4 in this._layers;
            }
            setLayerZoomRange(t4, i2, a2) {
              this._checkLoaded();
              const s2 = this.getLayer(t4);
              s2 ? s2.minzoom === i2 && s2.maxzoom === a2 || (null != i2 && (s2.minzoom = i2), null != a2 && (s2.maxzoom = a2), this._updateLayer(s2)) : this.fire(new e.j(new Error(`Cannot set the zoom range of non-existing layer "${t4}".`)));
            }
            setFilter(t4, i2, a2 = {}) {
              this._checkLoaded();
              const s2 = this.getLayer(t4);
              if (s2) {
                if (!e.aE(s2.filter, i2)) return null == i2 ? (s2.filter = void 0, void this._updateLayer(s2)) : void (this._validate(e.u.filter, `layers.${s2.id}.filter`, i2, null, a2) || (s2.filter = e.aB(i2), this._updateLayer(s2)));
              } else this.fire(new e.j(new Error(`Cannot filter non-existing layer "${t4}".`)));
            }
            getFilter(t4) {
              return e.aB(this.getLayer(t4).filter);
            }
            setLayoutProperty(t4, i2, a2, s2 = {}) {
              this._checkLoaded();
              const o2 = this.getLayer(t4);
              o2 ? e.aE(o2.getLayoutProperty(i2), a2) || (o2.setLayoutProperty(i2, a2, s2), this._updateLayer(o2)) : this.fire(new e.j(new Error(`Cannot style non-existing layer "${t4}".`)));
            }
            getLayoutProperty(t4, i2) {
              const a2 = this.getLayer(t4);
              if (a2) return a2.getLayoutProperty(i2);
              this.fire(new e.j(new Error(`Cannot get style of non-existing layer "${t4}".`)));
            }
            setPaintProperty(t4, i2, a2, s2 = {}) {
              this._checkLoaded();
              const o2 = this.getLayer(t4);
              o2 ? e.aE(o2.getPaintProperty(i2), a2) || (o2.setPaintProperty(i2, a2, s2) && this._updateLayer(o2), this._changed = true, this._updatedPaintProps[t4] = true, this._serializedLayers = null) : this.fire(new e.j(new Error(`Cannot style non-existing layer "${t4}".`)));
            }
            getPaintProperty(t4, e2) {
              return this.getLayer(t4).getPaintProperty(e2);
            }
            setFeatureState(t4, i2) {
              this._checkLoaded();
              const a2 = t4.source, s2 = t4.sourceLayer, o2 = this.sourceCaches[a2];
              if (void 0 === o2) return void this.fire(new e.j(new Error(`The source '${a2}' does not exist in the map's style.`)));
              const r2 = o2.getSource().type;
              "geojson" === r2 && s2 ? this.fire(new e.j(new Error("GeoJSON sources cannot have a sourceLayer parameter."))) : "vector" !== r2 || s2 ? (void 0 === t4.id && this.fire(new e.j(new Error("The feature id parameter must be provided."))), o2.setFeatureState(s2, t4.id, i2)) : this.fire(new e.j(new Error("The sourceLayer parameter must be provided for vector source types.")));
            }
            removeFeatureState(t4, i2) {
              this._checkLoaded();
              const a2 = t4.source, s2 = this.sourceCaches[a2];
              if (void 0 === s2) return void this.fire(new e.j(new Error(`The source '${a2}' does not exist in the map's style.`)));
              const o2 = s2.getSource().type, r2 = "vector" === o2 ? t4.sourceLayer : void 0;
              "vector" !== o2 || r2 ? i2 && "string" != typeof t4.id && "number" != typeof t4.id ? this.fire(new e.j(new Error("A feature id is required to remove its specific state property."))) : s2.removeFeatureState(r2, t4.id, i2) : this.fire(new e.j(new Error("The sourceLayer parameter must be provided for vector source types.")));
            }
            getFeatureState(t4) {
              this._checkLoaded();
              const i2 = t4.source, a2 = t4.sourceLayer, s2 = this.sourceCaches[i2];
              if (void 0 !== s2) return "vector" !== s2.getSource().type || a2 ? (void 0 === t4.id && this.fire(new e.j(new Error("The feature id parameter must be provided."))), s2.getFeatureState(a2, t4.id)) : void this.fire(new e.j(new Error("The sourceLayer parameter must be provided for vector source types.")));
              this.fire(new e.j(new Error(`The source '${i2}' does not exist in the map's style.`)));
            }
            getTransition() {
              return e.e({ duration: 300, delay: 0 }, this.stylesheet && this.stylesheet.transition);
            }
            serialize() {
              if (!this._loaded) return;
              const t4 = e.aF(this.sourceCaches, (t5) => t5.serialize()), i2 = this._serializeByIds(this._order, true), a2 = this.map.getTerrain() || void 0, s2 = this.stylesheet;
              return e.aG({ version: s2.version, name: s2.name, metadata: s2.metadata, light: s2.light, sky: s2.sky, center: s2.center, zoom: s2.zoom, bearing: s2.bearing, pitch: s2.pitch, sprite: s2.sprite, glyphs: s2.glyphs, transition: s2.transition, sources: t4, layers: i2, terrain: a2 }, (t5) => void 0 !== t5);
            }
            _updateLayer(t4) {
              this._updatedLayers[t4.id] = true, t4.source && !this._updatedSources[t4.source] && "raster" !== this.sourceCaches[t4.source].getSource().type && (this._updatedSources[t4.source] = "reload", this.sourceCaches[t4.source].pause()), this._serializedLayers = null, this._changed = true;
            }
            _flattenAndSortRenderedFeatures(t4) {
              const e2 = (t5) => "fill-extrusion" === this._layers[t5].type, i2 = {}, a2 = [];
              for (let s3 = this._order.length - 1; s3 >= 0; s3--) {
                const o2 = this._order[s3];
                if (e2(o2)) {
                  i2[o2] = s3;
                  for (const e3 of t4) {
                    const t5 = e3[o2];
                    if (t5) for (const e4 of t5) a2.push(e4);
                  }
                }
              }
              a2.sort((t5, e3) => e3.intersectionZ - t5.intersectionZ);
              const s2 = [];
              for (let o2 = this._order.length - 1; o2 >= 0; o2--) {
                const r2 = this._order[o2];
                if (e2(r2)) for (let t5 = a2.length - 1; t5 >= 0; t5--) {
                  const e3 = a2[t5].feature;
                  if (i2[e3.layer.id] < o2) break;
                  s2.push(e3), a2.pop();
                }
                else for (const e3 of t4) {
                  const t5 = e3[r2];
                  if (t5) for (const e4 of t5) s2.push(e4.feature);
                }
              }
              return s2;
            }
            queryRenderedFeatures(t4, i2, a2) {
              i2 && i2.filter && this._validate(e.u.filter, "queryRenderedFeatures.filter", i2.filter, null, i2);
              const s2 = {};
              if (i2 && i2.layers) {
                if (!Array.isArray(i2.layers)) return this.fire(new e.j(new Error("parameters.layers must be an Array."))), [];
                for (const t5 of i2.layers) {
                  const i3 = this._layers[t5];
                  if (!i3) return this.fire(new e.j(new Error(`The layer '${t5}' does not exist in the map's style and cannot be queried for features.`))), [];
                  s2[i3.source] = true;
                }
              }
              const o2 = [];
              i2.availableImages = this._availableImages;
              const r2 = this._serializedAllLayers();
              for (const e2 in this.sourceCaches) i2.layers && !s2[e2] || o2.push(q(this.sourceCaches[e2], this._layers, r2, t4, i2, a2));
              return this.placement && o2.push(function(t5, e2, i3, a3, s3, o3, r3) {
                const n2 = {}, l2 = o3.queryRenderedSymbols(a3), h2 = [];
                for (const t6 of Object.keys(l2).map(Number)) h2.push(r3[t6]);
                h2.sort(V);
                for (const i4 of h2) {
                  const a4 = i4.featureIndex.lookupSymbolFeatures(l2[i4.bucketInstanceId], e2, i4.bucketIndex, i4.sourceLayerIndex, s3.filter, s3.layers, s3.availableImages, t5);
                  for (const t6 in a4) {
                    const e3 = n2[t6] = n2[t6] || [], s4 = a4[t6];
                    s4.sort((t7, e4) => {
                      const a5 = i4.featureSortOrder;
                      if (a5) {
                        const i5 = a5.indexOf(t7.featureIndex);
                        return a5.indexOf(e4.featureIndex) - i5;
                      }
                      return e4.featureIndex - t7.featureIndex;
                    });
                    for (const t7 of s4) e3.push(t7);
                  }
                }
                for (const e3 in n2) n2[e3].forEach((a4) => {
                  const s4 = a4.feature, o4 = i3[t5[e3].source].getFeatureState(s4.layer["source-layer"], s4.id);
                  s4.source = s4.layer.source, s4.layer["source-layer"] && (s4.sourceLayer = s4.layer["source-layer"]), s4.state = o4;
                });
                return n2;
              }(this._layers, r2, this.sourceCaches, t4, i2, this.placement.collisionIndex, this.placement.retainedQueryData)), this._flattenAndSortRenderedFeatures(o2);
            }
            querySourceFeatures(t4, i2) {
              i2 && i2.filter && this._validate(e.u.filter, "querySourceFeatures.filter", i2.filter, null, i2);
              const a2 = this.sourceCaches[t4];
              return a2 ? function(t5, e2) {
                const i3 = t5.getRenderableIds().map((e3) => t5.getTileByID(e3)), a3 = [], s2 = {};
                for (let t6 = 0; t6 < i3.length; t6++) {
                  const o2 = i3[t6], r2 = o2.tileID.canonical.key;
                  s2[r2] || (s2[r2] = true, o2.querySourceFeatures(a3, e2));
                }
                return a3;
              }(a2, i2) : [];
            }
            getLight() {
              return this.light.getLight();
            }
            setLight(t4, i2 = {}) {
              this._checkLoaded();
              const a2 = this.light.getLight();
              let s2 = false;
              for (const i3 in t4) if (!e.aE(t4[i3], a2[i3])) {
                s2 = true;
                break;
              }
              if (!s2) return;
              const r2 = { now: o.now(), transition: e.e({ duration: 300, delay: 0 }, this.stylesheet.transition) };
              this.light.setLight(t4, i2), this.light.updateTransitions(r2);
            }
            getSky() {
              var t4;
              return null === (t4 = this.stylesheet) || void 0 === t4 ? void 0 : t4.sky;
            }
            setSky(t4, i2 = {}) {
              const a2 = this.getSky();
              let s2 = false;
              if (!t4 && !a2) return;
              if (t4 && !a2) s2 = true;
              else if (!t4 && a2) s2 = true;
              else for (const i3 in t4) if (!e.aE(t4[i3], a2[i3])) {
                s2 = true;
                break;
              }
              if (!s2) return;
              const r2 = { now: o.now(), transition: e.e({ duration: 300, delay: 0 }, this.stylesheet.transition) };
              this.stylesheet.sky = t4, this.sky.setSky(t4, i2), this.sky.updateTransitions(r2);
            }
            _validate(t4, i2, a2, s2, o2 = {}) {
              return (!o2 || false !== o2.validate) && ce(this, t4.call(e.u, e.e({ key: i2, style: this.serialize(), value: a2, styleSpec: e.v }, s2)));
            }
            _remove(t4 = true) {
              this._frameRequest && (this._frameRequest.abort(), this._frameRequest = null), this._loadStyleRequest && (this._loadStyleRequest.abort(), this._loadStyleRequest = null), this._spriteRequest && (this._spriteRequest.abort(), this._spriteRequest = null), nt().off(st, this._rtlPluginLoaded);
              for (const t5 in this._layers) this._layers[t5].setEventedParent(null);
              for (const t5 in this.sourceCaches) {
                const e2 = this.sourceCaches[t5];
                e2.setEventedParent(null), e2.onRemove(this.map);
              }
              this.imageManager.setEventedParent(null), this.setEventedParent(null), t4 && this.dispatcher.broadcast("RM", void 0), this.dispatcher.remove(t4);
            }
            _clearSource(t4) {
              this.sourceCaches[t4].clearTiles();
            }
            _reloadSource(t4) {
              this.sourceCaches[t4].resume(), this.sourceCaches[t4].reload();
            }
            _updateSources(t4) {
              for (const e2 in this.sourceCaches) this.sourceCaches[e2].update(t4, this.map.terrain);
            }
            _generateCollisionBoxes() {
              for (const t4 in this.sourceCaches) this._reloadSource(t4);
            }
            _updatePlacement(t4, e2, i2, a2, s2 = false) {
              let r2 = false, n2 = false;
              const l2 = {};
              for (const e3 of this._order) {
                const i3 = this._layers[e3];
                if ("symbol" !== i3.type) continue;
                if (!l2[i3.source]) {
                  const t5 = this.sourceCaches[i3.source];
                  l2[i3.source] = t5.getRenderableIds(true).map((e4) => t5.getTileByID(e4)).sort((t6, e4) => e4.tileID.overscaledZ - t6.tileID.overscaledZ || (t6.tileID.isLessThan(e4.tileID) ? -1 : 1));
                }
                const a3 = this.crossTileSymbolIndex.addLayer(i3, l2[i3.source], t4.center.lng);
                r2 = r2 || a3;
              }
              if (this.crossTileSymbolIndex.pruneUnusedLayers(this._order), ((s2 = s2 || this._layerOrderChanged || 0 === i2) || !this.pauseablePlacement || this.pauseablePlacement.isDone() && !this.placement.stillRecent(o.now(), t4.zoom)) && (this.pauseablePlacement = new se(t4, this.map.terrain, this._order, s2, e2, i2, a2, this.placement), this._layerOrderChanged = false), this.pauseablePlacement.isDone() ? this.placement.setStale() : (this.pauseablePlacement.continuePlacement(this._order, this._layers, l2), this.pauseablePlacement.isDone() && (this.placement = this.pauseablePlacement.commit(o.now()), n2 = true), r2 && this.pauseablePlacement.placement.setStale()), n2 || r2) for (const t5 of this._order) {
                const e3 = this._layers[t5];
                "symbol" === e3.type && this.placement.updateLayerOpacities(e3, l2[e3.source]);
              }
              return !this.pauseablePlacement.isDone() || this.placement.hasTransitions(o.now());
            }
            _releaseSymbolFadeTiles() {
              for (const t4 in this.sourceCaches) this.sourceCaches[t4].releaseSymbolFadeTiles();
            }
            getImages(t4, i2) {
              return e._(this, void 0, void 0, function* () {
                const t5 = yield this.imageManager.getImages(i2.icons);
                this._updateTilesForChangedImages();
                const e2 = this.sourceCaches[i2.source];
                return e2 && e2.setDependencies(i2.tileID.key, i2.type, i2.icons), t5;
              });
            }
            getGlyphs(t4, i2) {
              return e._(this, void 0, void 0, function* () {
                const t5 = yield this.glyphManager.getGlyphs(i2.stacks), e2 = this.sourceCaches[i2.source];
                return e2 && e2.setDependencies(i2.tileID.key, i2.type, [""]), t5;
              });
            }
            getGlyphsUrl() {
              return this.stylesheet.glyphs || null;
            }
            setGlyphs(t4, i2 = {}) {
              this._checkLoaded(), t4 && this._validate(e.u.glyphs, "glyphs", t4, null, i2) || (this._glyphsDidChange = true, this.stylesheet.glyphs = t4, this.glyphManager.entries = {}, this.glyphManager.setURL(t4));
            }
            addSprite(t4, i2, a2 = {}, s2) {
              this._checkLoaded();
              const o2 = [{ id: t4, url: i2 }], r2 = [...x(this.stylesheet.sprite), ...o2];
              this._validate(e.u.sprite, "sprite", r2, null, a2) || (this.stylesheet.sprite = r2, this._loadSprite(o2, true, s2));
            }
            removeSprite(t4) {
              this._checkLoaded();
              const i2 = x(this.stylesheet.sprite);
              if (i2.find((e2) => e2.id === t4)) {
                if (this._spritesImagesIds[t4]) for (const e2 of this._spritesImagesIds[t4]) this.imageManager.removeImage(e2), this._changedImages[e2] = true;
                i2.splice(i2.findIndex((e2) => e2.id === t4), 1), this.stylesheet.sprite = i2.length > 0 ? i2 : void 0, delete this._spritesImagesIds[t4], this._availableImages = this.imageManager.listImages(), this._changed = true, this.dispatcher.broadcast("SI", this._availableImages), this.fire(new e.k("data", { dataType: "style" }));
              } else this.fire(new e.j(new Error(`Sprite "${t4}" doesn't exists on this map.`)));
            }
            getSprite() {
              return x(this.stylesheet.sprite);
            }
            setSprite(t4, i2 = {}, a2) {
              this._checkLoaded(), t4 && this._validate(e.u.sprite, "sprite", t4, null, i2) || (this.stylesheet.sprite = t4, t4 ? this._loadSprite(t4, true, a2) : (this._unloadSprite(), a2 && a2(null)));
            }
          }
          var _e = e.Y([{ name: "a_pos", type: "Int16", components: 2 }]);
          const pe = { prelude: me("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\n", "#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture2D(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture2D(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}"), background: me("uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"), backgroundPattern: me("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"), circle: me("varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;varying float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);float ele=get_elevation(circle_center);v_visibility=calculate_visibility(u_matrix*vec4(circle_center,ele,1.0));if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,ele,1);} else {gl_Position=u_matrix*vec4(circle_center,ele,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"), clippingMask: me("void main() {gl_FragColor=vec4(1.0);}", "attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"), heatmap: me("uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,get_elevation(floor(a_pos*0.5)),1);gl_Position=u_matrix*pos;}"), heatmapTexture: me("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"), collisionBox: me("varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}", "attribute vec2 a_anchor_pos;attribute vec2 a_placed;attribute vec2 a_box_real;uniform mat4 u_matrix;uniform vec2 u_pixel_extrude_scale;varying float v_placed;varying float v_notUsed;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"), collisionCircle: me("varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}", "attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd  =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz  /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"), debug: me("uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}", "attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,get_elevation(a_pos),1);}"), fill: me("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"), fillOutline: me("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"), fillOutlinePattern: me("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"), fillPattern: me("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"), fillExtrusion: me("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"), fillExtrusionPattern: me("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;\n#ifdef TERRAIN3D\nattribute vec2 a_centroid;\n#endif\nvarying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"), hillshadePrepare: me("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"), hillshade: me("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"), line: me("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"), lineGradient: me("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,v_uv);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;attribute float a_uv_x;attribute float a_split_index;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp vec2 v_uv;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"), linePattern: me("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"), lineSDF: me("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"), raster: me("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"), symbolIcon: me("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_tex;varying float v_fade_opacity;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"), symbolSDF: me("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec2 v_data0;varying vec3 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"), symbolTextAndIcon: me("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}", "attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;varying vec4 v_data0;varying vec4 v_data1;vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_matrix*vec4(posInTile,elevation,1.0);}\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"), terrain: me("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;varying vec2 v_texture_pos;varying float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture2D(u_texture,v_texture_pos);if (v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);gl_FragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {gl_FragColor=surface_color;}}", "attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform mat4 u_fog_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;varying float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"), terrainDepth: me("varying float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {gl_FragColor=pack(v_depth);}", "attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);v_depth=gl_Position.z/gl_Position.w;}"), terrainCoords: me("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;varying vec2 v_texture_pos;void main() {vec4 rgba=texture2D(u_texture,v_texture_pos);gl_FragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}", "attribute vec3 a_pos3d;uniform mat4 u_matrix;uniform float u_ele_delta;varying vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=u_matrix*vec4(a_pos3d.xy,ele-ele_delta,1.0);}"), sky: me("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform float u_horizon;uniform float u_sky_horizon_blend;void main() {float y=gl_FragCoord.y;if (y > u_horizon) {float blend=y-u_horizon;if (blend < u_sky_horizon_blend) {gl_FragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {gl_FragColor=u_sky_color;}}}", "attribute vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}") };
          function me(t4, e2) {
            const i2 = /#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g, a2 = e2.match(/attribute ([\w]+) ([\w]+)/g), s2 = t4.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g), o2 = e2.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g), r2 = o2 ? o2.concat(s2) : s2, n2 = {};
            return { fragmentSource: t4 = t4.replace(i2, (t5, e3, i3, a3, s3) => (n2[s3] = true, "define" === e3 ? `
#ifndef HAS_UNIFORM_u_${s3}
varying ${i3} ${a3} ${s3};
#else
uniform ${i3} ${a3} u_${s3};
#endif
` : `
#ifdef HAS_UNIFORM_u_${s3}
    ${i3} ${a3} ${s3} = u_${s3};
#endif
`)), vertexSource: e2 = e2.replace(i2, (t5, e3, i3, a3, s3) => {
              const o3 = "float" === a3 ? "vec2" : "vec4", r3 = s3.match(/color/) ? "color" : o3;
              return n2[s3] ? "define" === e3 ? `
#ifndef HAS_UNIFORM_u_${s3}
uniform lowp float u_${s3}_t;
attribute ${i3} ${o3} a_${s3};
varying ${i3} ${a3} ${s3};
#else
uniform ${i3} ${a3} u_${s3};
#endif
` : "vec4" === r3 ? `
#ifndef HAS_UNIFORM_u_${s3}
    ${s3} = a_${s3};
#else
    ${i3} ${a3} ${s3} = u_${s3};
#endif
` : `
#ifndef HAS_UNIFORM_u_${s3}
    ${s3} = unpack_mix_${r3}(a_${s3}, u_${s3}_t);
#else
    ${i3} ${a3} ${s3} = u_${s3};
#endif
` : "define" === e3 ? `
#ifndef HAS_UNIFORM_u_${s3}
uniform lowp float u_${s3}_t;
attribute ${i3} ${o3} a_${s3};
#else
uniform ${i3} ${a3} u_${s3};
#endif
` : "vec4" === r3 ? `
#ifndef HAS_UNIFORM_u_${s3}
    ${i3} ${a3} ${s3} = a_${s3};
#else
    ${i3} ${a3} ${s3} = u_${s3};
#endif
` : `
#ifndef HAS_UNIFORM_u_${s3}
    ${i3} ${a3} ${s3} = unpack_mix_${r3}(a_${s3}, u_${s3}_t);
#else
    ${i3} ${a3} ${s3} = u_${s3};
#endif
`;
            }), staticAttributes: a2, staticUniforms: r2 };
          }
          class fe {
            constructor() {
              this.boundProgram = null, this.boundLayoutVertexBuffer = null, this.boundPaintVertexBuffers = [], this.boundIndexBuffer = null, this.boundVertexOffset = null, this.boundDynamicVertexBuffer = null, this.vao = null;
            }
            bind(t4, e2, i2, a2, s2, o2, r2, n2, l2) {
              this.context = t4;
              let h2 = this.boundPaintVertexBuffers.length !== a2.length;
              for (let t5 = 0; !h2 && t5 < a2.length; t5++) this.boundPaintVertexBuffers[t5] !== a2[t5] && (h2 = true);
              !this.vao || this.boundProgram !== e2 || this.boundLayoutVertexBuffer !== i2 || h2 || this.boundIndexBuffer !== s2 || this.boundVertexOffset !== o2 || this.boundDynamicVertexBuffer !== r2 || this.boundDynamicVertexBuffer2 !== n2 || this.boundDynamicVertexBuffer3 !== l2 ? this.freshBind(e2, i2, a2, s2, o2, r2, n2, l2) : (t4.bindVertexArray.set(this.vao), r2 && r2.bind(), s2 && s2.dynamicDraw && s2.bind(), n2 && n2.bind(), l2 && l2.bind());
            }
            freshBind(t4, e2, i2, a2, s2, o2, r2, n2) {
              const l2 = t4.numAttributes, h2 = this.context, c2 = h2.gl;
              this.vao && this.destroy(), this.vao = h2.createVertexArray(), h2.bindVertexArray.set(this.vao), this.boundProgram = t4, this.boundLayoutVertexBuffer = e2, this.boundPaintVertexBuffers = i2, this.boundIndexBuffer = a2, this.boundVertexOffset = s2, this.boundDynamicVertexBuffer = o2, this.boundDynamicVertexBuffer2 = r2, this.boundDynamicVertexBuffer3 = n2, e2.enableAttributes(c2, t4);
              for (const e3 of i2) e3.enableAttributes(c2, t4);
              o2 && o2.enableAttributes(c2, t4), r2 && r2.enableAttributes(c2, t4), n2 && n2.enableAttributes(c2, t4), e2.bind(), e2.setVertexAttribPointers(c2, t4, s2);
              for (const e3 of i2) e3.bind(), e3.setVertexAttribPointers(c2, t4, s2);
              o2 && (o2.bind(), o2.setVertexAttribPointers(c2, t4, s2)), a2 && a2.bind(), r2 && (r2.bind(), r2.setVertexAttribPointers(c2, t4, s2)), n2 && (n2.bind(), n2.setVertexAttribPointers(c2, t4, s2)), h2.currentNumAttributes = l2;
            }
            destroy() {
              this.vao && (this.context.deleteVertexArray(this.vao), this.vao = null);
            }
          }
          const ge = (t4, i2, a2, s2, o2) => ({ u_matrix: t4, u_texture: 0, u_ele_delta: i2, u_fog_matrix: a2, u_fog_color: s2 ? s2.properties.get("fog-color") : e.aM.white, u_fog_ground_blend: s2 ? s2.properties.get("fog-ground-blend") : 1, u_fog_ground_blend_opacity: s2 ? s2.calculateFogBlendOpacity(o2) : 0, u_horizon_color: s2 ? s2.properties.get("horizon-color") : e.aM.white, u_horizon_fog_blend: s2 ? s2.properties.get("horizon-fog-blend") : 1 });
          function ve(t4) {
            const e2 = [];
            for (let i2 = 0; i2 < t4.length; i2++) {
              if (null === t4[i2]) continue;
              const a2 = t4[i2].split(" ");
              e2.push(a2.pop());
            }
            return e2;
          }
          class xe {
            constructor(t4, i2, a2, s2, o2, r2) {
              const n2 = t4.gl;
              this.program = n2.createProgram();
              const l2 = ve(i2.staticAttributes), h2 = a2 ? a2.getBinderAttributes() : [], c2 = l2.concat(h2), u2 = pe.prelude.staticUniforms ? ve(pe.prelude.staticUniforms) : [], d2 = i2.staticUniforms ? ve(i2.staticUniforms) : [], _2 = a2 ? a2.getBinderUniforms() : [], p2 = u2.concat(d2).concat(_2), m2 = [];
              for (const t5 of p2) m2.indexOf(t5) < 0 && m2.push(t5);
              const f2 = a2 ? a2.defines() : [];
              o2 && f2.push("#define OVERDRAW_INSPECTOR;"), r2 && f2.push("#define TERRAIN3D;");
              const g2 = f2.concat(pe.prelude.fragmentSource, i2.fragmentSource).join("\n"), v2 = f2.concat(pe.prelude.vertexSource, i2.vertexSource).join("\n"), x2 = n2.createShader(n2.FRAGMENT_SHADER);
              if (n2.isContextLost()) return void (this.failedToCreate = true);
              if (n2.shaderSource(x2, g2), n2.compileShader(x2), !n2.getShaderParameter(x2, n2.COMPILE_STATUS)) throw new Error(`Could not compile fragment shader: ${n2.getShaderInfoLog(x2)}`);
              n2.attachShader(this.program, x2);
              const y2 = n2.createShader(n2.VERTEX_SHADER);
              if (n2.isContextLost()) return void (this.failedToCreate = true);
              if (n2.shaderSource(y2, v2), n2.compileShader(y2), !n2.getShaderParameter(y2, n2.COMPILE_STATUS)) throw new Error(`Could not compile vertex shader: ${n2.getShaderInfoLog(y2)}`);
              n2.attachShader(this.program, y2), this.attributes = {};
              const b2 = {};
              this.numAttributes = c2.length;
              for (let t5 = 0; t5 < this.numAttributes; t5++) c2[t5] && (n2.bindAttribLocation(this.program, t5, c2[t5]), this.attributes[c2[t5]] = t5);
              if (n2.linkProgram(this.program), !n2.getProgramParameter(this.program, n2.LINK_STATUS)) throw new Error(`Program failed to link: ${n2.getProgramInfoLog(this.program)}`);
              n2.deleteShader(y2), n2.deleteShader(x2);
              for (let t5 = 0; t5 < m2.length; t5++) {
                const e2 = m2[t5];
                if (e2 && !b2[e2]) {
                  const t6 = n2.getUniformLocation(this.program, e2);
                  t6 && (b2[e2] = t6);
                }
              }
              this.fixedUniforms = s2(t4, b2), this.terrainUniforms = ((t5, i3) => ({ u_depth: new e.aH(t5, i3.u_depth), u_terrain: new e.aH(t5, i3.u_terrain), u_terrain_dim: new e.aI(t5, i3.u_terrain_dim), u_terrain_matrix: new e.aJ(t5, i3.u_terrain_matrix), u_terrain_unpack: new e.aK(t5, i3.u_terrain_unpack), u_terrain_exaggeration: new e.aI(t5, i3.u_terrain_exaggeration) }))(t4, b2), this.binderUniforms = a2 ? a2.getUniforms(t4, b2) : [];
            }
            draw(t4, e2, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, p2, m2, f2, g2) {
              const v2 = t4.gl;
              if (this.failedToCreate) return;
              if (t4.program.set(this.program), t4.setDepthMode(i2), t4.setStencilMode(a2), t4.setColorMode(s2), t4.setCullFace(o2), n2) {
                t4.activeTexture.set(v2.TEXTURE2), v2.bindTexture(v2.TEXTURE_2D, n2.depthTexture), t4.activeTexture.set(v2.TEXTURE3), v2.bindTexture(v2.TEXTURE_2D, n2.texture);
                for (const t5 in this.terrainUniforms) this.terrainUniforms[t5].set(n2[t5]);
              }
              for (const t5 in this.fixedUniforms) this.fixedUniforms[t5].set(r2[t5]);
              p2 && p2.setUniforms(t4, this.binderUniforms, d2, { zoom: _2 });
              let x2 = 0;
              switch (e2) {
                case v2.LINES:
                  x2 = 2;
                  break;
                case v2.TRIANGLES:
                  x2 = 3;
                  break;
                case v2.LINE_STRIP:
                  x2 = 1;
              }
              for (const i3 of u2.get()) {
                const a3 = i3.vaos || (i3.vaos = {});
                (a3[l2] || (a3[l2] = new fe())).bind(t4, this, h2, p2 ? p2.getPaintVertexBuffers() : [], c2, i3.vertexOffset, m2, f2, g2), v2.drawElements(e2, i3.primitiveLength * x2, v2.UNSIGNED_SHORT, i3.primitiveOffset * x2 * 2);
              }
            }
          }
          function ye(t4, e2, i2) {
            const a2 = 1 / Bt(i2, 1, e2.transform.tileZoom), s2 = Math.pow(2, i2.tileID.overscaledZ), o2 = i2.tileSize * Math.pow(2, e2.transform.tileZoom) / s2, r2 = o2 * (i2.tileID.canonical.x + i2.tileID.wrap * s2), n2 = o2 * i2.tileID.canonical.y;
            return { u_image: 0, u_texsize: i2.imageAtlasTexture.size, u_scale: [a2, t4.fromScale, t4.toScale], u_fade: t4.t, u_pixel_coord_upper: [r2 >> 16, n2 >> 16], u_pixel_coord_lower: [65535 & r2, 65535 & n2] };
          }
          const be = (t4, i2, a2, s2) => {
            const o2 = i2.style.light, r2 = o2.properties.get("position"), n2 = [r2.x, r2.y, r2.z], l2 = function() {
              var t5 = new e.A(9);
              return e.A != Float32Array && (t5[1] = 0, t5[2] = 0, t5[3] = 0, t5[5] = 0, t5[6] = 0, t5[7] = 0), t5[0] = 1, t5[4] = 1, t5[8] = 1, t5;
            }();
            "viewport" === o2.properties.get("anchor") && function(t5, e2) {
              var i3 = Math.sin(e2), a3 = Math.cos(e2);
              t5[0] = a3, t5[1] = i3, t5[2] = 0, t5[3] = -i3, t5[4] = a3, t5[5] = 0, t5[6] = 0, t5[7] = 0, t5[8] = 1;
            }(l2, -i2.transform.angle), function(t5, e2, i3) {
              var a3 = e2[0], s3 = e2[1], o3 = e2[2];
              t5[0] = a3 * i3[0] + s3 * i3[3] + o3 * i3[6], t5[1] = a3 * i3[1] + s3 * i3[4] + o3 * i3[7], t5[2] = a3 * i3[2] + s3 * i3[5] + o3 * i3[8];
            }(n2, n2, l2);
            const h2 = o2.properties.get("color");
            return { u_matrix: t4, u_lightpos: n2, u_lightintensity: o2.properties.get("intensity"), u_lightcolor: [h2.r, h2.g, h2.b], u_vertical_gradient: +a2, u_opacity: s2 };
          }, we = (t4, i2, a2, s2, o2, r2, n2) => e.e(be(t4, i2, a2, s2), ye(r2, i2, n2), { u_height_factor: -Math.pow(2, o2.overscaledZ) / n2.tileSize / 8 }), Te = (t4) => ({ u_matrix: t4 }), Ie = (t4, i2, a2, s2) => e.e(Te(t4), ye(a2, i2, s2)), Ee = (t4, e2) => ({ u_matrix: t4, u_world: e2 }), Pe = (t4, i2, a2, s2, o2) => e.e(Ie(t4, i2, a2, s2), { u_world: o2 }), Ce = (t4, e2, i2, a2) => {
            const s2 = t4.transform;
            let o2, r2;
            if ("map" === a2.paint.get("circle-pitch-alignment")) {
              const t5 = Bt(i2, 1, s2.zoom);
              o2 = true, r2 = [t5, t5];
            } else o2 = false, r2 = s2.pixelsToGLUnits;
            return { u_camera_to_center_distance: s2.cameraToCenterDistance, u_scale_with_map: +("map" === a2.paint.get("circle-pitch-scale")), u_matrix: t4.translatePosMatrix(e2.posMatrix, i2, a2.paint.get("circle-translate"), a2.paint.get("circle-translate-anchor")), u_pitch_with_map: +o2, u_device_pixel_ratio: t4.pixelRatio, u_extrude_scale: r2 };
          }, Se = (t4, e2, i2) => ({ u_matrix: t4, u_inv_matrix: e2, u_camera_to_center_distance: i2.cameraToCenterDistance, u_viewport_size: [i2.width, i2.height] }), ze = (t4, e2, i2 = 1) => ({ u_matrix: t4, u_color: e2, u_overlay: 0, u_overlay_scale: i2 }), De = (t4) => ({ u_matrix: t4 }), Me = (t4, e2, i2, a2) => ({ u_matrix: t4, u_extrude_scale: Bt(e2, 1, i2), u_intensity: a2 }), Ae = (t4, i2, a2, s2) => {
            const o2 = e.H();
            e.aP(o2, 0, t4.width, t4.height, 0, 0, 1);
            const r2 = t4.context.gl;
            return { u_matrix: o2, u_world: [r2.drawingBufferWidth, r2.drawingBufferHeight], u_image: a2, u_color_ramp: s2, u_opacity: i2.paint.get("heatmap-opacity") };
          };
          function Re(t4, i2) {
            const a2 = Math.pow(2, i2.canonical.z), s2 = i2.canonical.y;
            return [new e.Z(0, s2 / a2).toLngLat().lat, new e.Z(0, (s2 + 1) / a2).toLngLat().lat];
          }
          const ke = (t4, e2, i2, a2) => {
            const s2 = t4.transform;
            return { u_matrix: Ne(t4, e2, i2, a2), u_ratio: 1 / Bt(e2, 1, s2.zoom), u_device_pixel_ratio: t4.pixelRatio, u_units_to_pixels: [1 / s2.pixelsToGLUnits[0], 1 / s2.pixelsToGLUnits[1]] };
          }, Le = (t4, i2, a2, s2, o2) => e.e(ke(t4, i2, a2, o2), { u_image: 0, u_image_height: s2 }), Fe = (t4, e2, i2, a2, s2) => {
            const o2 = t4.transform, r2 = Oe(e2, o2);
            return { u_matrix: Ne(t4, e2, i2, s2), u_texsize: e2.imageAtlasTexture.size, u_ratio: 1 / Bt(e2, 1, o2.zoom), u_device_pixel_ratio: t4.pixelRatio, u_image: 0, u_scale: [r2, a2.fromScale, a2.toScale], u_fade: a2.t, u_units_to_pixels: [1 / o2.pixelsToGLUnits[0], 1 / o2.pixelsToGLUnits[1]] };
          }, Be = (t4, i2, a2, s2, o2, r2) => {
            const n2 = t4.lineAtlas, l2 = Oe(i2, t4.transform), h2 = "round" === a2.layout.get("line-cap"), c2 = n2.getDash(s2.from, h2), u2 = n2.getDash(s2.to, h2), d2 = c2.width * o2.fromScale, _2 = u2.width * o2.toScale;
            return e.e(ke(t4, i2, a2, r2), { u_patternscale_a: [l2 / d2, -c2.height / 2], u_patternscale_b: [l2 / _2, -u2.height / 2], u_sdfgamma: n2.width / (256 * Math.min(d2, _2) * t4.pixelRatio) / 2, u_image: 0, u_tex_y_a: c2.y, u_tex_y_b: u2.y, u_mix: o2.t });
          };
          function Oe(t4, e2) {
            return 1 / Bt(t4, 1, e2.tileZoom);
          }
          function Ne(t4, e2, i2, a2) {
            return t4.translatePosMatrix(a2 ? a2.posMatrix : e2.tileID.posMatrix, e2, i2.paint.get("line-translate"), i2.paint.get("line-translate-anchor"));
          }
          const Ue = (t4, e2, i2, a2, s2) => {
            return { u_matrix: t4, u_tl_parent: e2, u_scale_parent: i2, u_buffer_scale: 1, u_fade_t: a2.mix, u_opacity: a2.opacity * s2.paint.get("raster-opacity"), u_image0: 0, u_image1: 1, u_brightness_low: s2.paint.get("raster-brightness-min"), u_brightness_high: s2.paint.get("raster-brightness-max"), u_saturation_factor: (r2 = s2.paint.get("raster-saturation"), r2 > 0 ? 1 - 1 / (1.001 - r2) : -r2), u_contrast_factor: (o2 = s2.paint.get("raster-contrast"), o2 > 0 ? 1 / (1 - o2) : 1 + o2), u_spin_weights: je(s2.paint.get("raster-hue-rotate")) };
            var o2, r2;
          };
          function je(t4) {
            t4 *= Math.PI / 180;
            const e2 = Math.sin(t4), i2 = Math.cos(t4);
            return [(2 * i2 + 1) / 3, (-Math.sqrt(3) * e2 - i2 + 1) / 3, (Math.sqrt(3) * e2 - i2 + 1) / 3];
          }
          const Ze = (t4, e2, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2) => {
            const p2 = r2.transform;
            return { u_is_size_zoom_constant: +("constant" === t4 || "source" === t4), u_is_size_feature_constant: +("constant" === t4 || "camera" === t4), u_size_t: e2 ? e2.uSizeT : 0, u_size: e2 ? e2.uSize : 0, u_camera_to_center_distance: p2.cameraToCenterDistance, u_pitch: p2.pitch / 360 * 2 * Math.PI, u_rotate_symbol: +i2, u_aspect_ratio: p2.width / p2.height, u_fade_change: r2.options.fadeDuration ? r2.symbolFadeChange : 1, u_matrix: n2, u_label_plane_matrix: l2, u_coord_matrix: h2, u_is_text: +u2, u_pitch_with_map: +a2, u_is_along_line: s2, u_is_variable_anchor: o2, u_texsize: d2, u_texture: 0, u_translation: c2, u_pitched_scale: _2 };
          }, qe = (t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, p2, m2) => {
            const f2 = n2.transform;
            return e.e(Ze(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, m2), { u_gamma_scale: s2 ? Math.cos(f2._pitch) * f2.cameraToCenterDistance : 1, u_device_pixel_ratio: n2.pixelRatio, u_is_halo: +p2 });
          }, Ve = (t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, p2) => e.e(qe(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, true, d2, true, p2), { u_texsize_icon: _2, u_texture_icon: 1 }), Ge = (t4, e2, i2) => ({ u_matrix: t4, u_opacity: e2, u_color: i2 }), He = (t4, i2, a2, s2, o2, r2) => e.e(function(t5, e2, i3, a3) {
            const s3 = i3.imageManager.getPattern(t5.from.toString()), o3 = i3.imageManager.getPattern(t5.to.toString()), { width: r3, height: n2 } = i3.imageManager.getPixelSize(), l2 = Math.pow(2, a3.tileID.overscaledZ), h2 = a3.tileSize * Math.pow(2, i3.transform.tileZoom) / l2, c2 = h2 * (a3.tileID.canonical.x + a3.tileID.wrap * l2), u2 = h2 * a3.tileID.canonical.y;
            return { u_image: 0, u_pattern_tl_a: s3.tl, u_pattern_br_a: s3.br, u_pattern_tl_b: o3.tl, u_pattern_br_b: o3.br, u_texsize: [r3, n2], u_mix: e2.t, u_pattern_size_a: s3.displaySize, u_pattern_size_b: o3.displaySize, u_scale_a: e2.fromScale, u_scale_b: e2.toScale, u_tile_units_to_pixels: 1 / Bt(a3, 1, i3.transform.tileZoom), u_pixel_coord_upper: [c2 >> 16, u2 >> 16], u_pixel_coord_lower: [65535 & c2, 65535 & u2] };
          }(s2, r2, a2, o2), { u_matrix: t4, u_opacity: i2 }), We = { fillExtrusion: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_lightpos: new e.aN(t4, i2.u_lightpos), u_lightintensity: new e.aI(t4, i2.u_lightintensity), u_lightcolor: new e.aN(t4, i2.u_lightcolor), u_vertical_gradient: new e.aI(t4, i2.u_vertical_gradient), u_opacity: new e.aI(t4, i2.u_opacity) }), fillExtrusionPattern: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_lightpos: new e.aN(t4, i2.u_lightpos), u_lightintensity: new e.aI(t4, i2.u_lightintensity), u_lightcolor: new e.aN(t4, i2.u_lightcolor), u_vertical_gradient: new e.aI(t4, i2.u_vertical_gradient), u_height_factor: new e.aI(t4, i2.u_height_factor), u_image: new e.aH(t4, i2.u_image), u_texsize: new e.aO(t4, i2.u_texsize), u_pixel_coord_upper: new e.aO(t4, i2.u_pixel_coord_upper), u_pixel_coord_lower: new e.aO(t4, i2.u_pixel_coord_lower), u_scale: new e.aN(t4, i2.u_scale), u_fade: new e.aI(t4, i2.u_fade), u_opacity: new e.aI(t4, i2.u_opacity) }), fill: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix) }), fillPattern: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_image: new e.aH(t4, i2.u_image), u_texsize: new e.aO(t4, i2.u_texsize), u_pixel_coord_upper: new e.aO(t4, i2.u_pixel_coord_upper), u_pixel_coord_lower: new e.aO(t4, i2.u_pixel_coord_lower), u_scale: new e.aN(t4, i2.u_scale), u_fade: new e.aI(t4, i2.u_fade) }), fillOutline: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_world: new e.aO(t4, i2.u_world) }), fillOutlinePattern: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_world: new e.aO(t4, i2.u_world), u_image: new e.aH(t4, i2.u_image), u_texsize: new e.aO(t4, i2.u_texsize), u_pixel_coord_upper: new e.aO(t4, i2.u_pixel_coord_upper), u_pixel_coord_lower: new e.aO(t4, i2.u_pixel_coord_lower), u_scale: new e.aN(t4, i2.u_scale), u_fade: new e.aI(t4, i2.u_fade) }), circle: (t4, i2) => ({ u_camera_to_center_distance: new e.aI(t4, i2.u_camera_to_center_distance), u_scale_with_map: new e.aH(t4, i2.u_scale_with_map), u_pitch_with_map: new e.aH(t4, i2.u_pitch_with_map), u_extrude_scale: new e.aO(t4, i2.u_extrude_scale), u_device_pixel_ratio: new e.aI(t4, i2.u_device_pixel_ratio), u_matrix: new e.aJ(t4, i2.u_matrix) }), collisionBox: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_pixel_extrude_scale: new e.aO(t4, i2.u_pixel_extrude_scale) }), collisionCircle: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_inv_matrix: new e.aJ(t4, i2.u_inv_matrix), u_camera_to_center_distance: new e.aI(t4, i2.u_camera_to_center_distance), u_viewport_size: new e.aO(t4, i2.u_viewport_size) }), debug: (t4, i2) => ({ u_color: new e.aL(t4, i2.u_color), u_matrix: new e.aJ(t4, i2.u_matrix), u_overlay: new e.aH(t4, i2.u_overlay), u_overlay_scale: new e.aI(t4, i2.u_overlay_scale) }), clippingMask: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix) }), heatmap: (t4, i2) => ({ u_extrude_scale: new e.aI(t4, i2.u_extrude_scale), u_intensity: new e.aI(t4, i2.u_intensity), u_matrix: new e.aJ(t4, i2.u_matrix) }), heatmapTexture: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_world: new e.aO(t4, i2.u_world), u_image: new e.aH(t4, i2.u_image), u_color_ramp: new e.aH(t4, i2.u_color_ramp), u_opacity: new e.aI(t4, i2.u_opacity) }), hillshade: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_image: new e.aH(t4, i2.u_image), u_latrange: new e.aO(t4, i2.u_latrange), u_light: new e.aO(t4, i2.u_light), u_shadow: new e.aL(t4, i2.u_shadow), u_highlight: new e.aL(t4, i2.u_highlight), u_accent: new e.aL(t4, i2.u_accent) }), hillshadePrepare: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_image: new e.aH(t4, i2.u_image), u_dimension: new e.aO(t4, i2.u_dimension), u_zoom: new e.aI(t4, i2.u_zoom), u_unpack: new e.aK(t4, i2.u_unpack) }), line: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_ratio: new e.aI(t4, i2.u_ratio), u_device_pixel_ratio: new e.aI(t4, i2.u_device_pixel_ratio), u_units_to_pixels: new e.aO(t4, i2.u_units_to_pixels) }), lineGradient: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_ratio: new e.aI(t4, i2.u_ratio), u_device_pixel_ratio: new e.aI(t4, i2.u_device_pixel_ratio), u_units_to_pixels: new e.aO(t4, i2.u_units_to_pixels), u_image: new e.aH(t4, i2.u_image), u_image_height: new e.aI(t4, i2.u_image_height) }), linePattern: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_texsize: new e.aO(t4, i2.u_texsize), u_ratio: new e.aI(t4, i2.u_ratio), u_device_pixel_ratio: new e.aI(t4, i2.u_device_pixel_ratio), u_image: new e.aH(t4, i2.u_image), u_units_to_pixels: new e.aO(t4, i2.u_units_to_pixels), u_scale: new e.aN(t4, i2.u_scale), u_fade: new e.aI(t4, i2.u_fade) }), lineSDF: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_ratio: new e.aI(t4, i2.u_ratio), u_device_pixel_ratio: new e.aI(t4, i2.u_device_pixel_ratio), u_units_to_pixels: new e.aO(t4, i2.u_units_to_pixels), u_patternscale_a: new e.aO(t4, i2.u_patternscale_a), u_patternscale_b: new e.aO(t4, i2.u_patternscale_b), u_sdfgamma: new e.aI(t4, i2.u_sdfgamma), u_image: new e.aH(t4, i2.u_image), u_tex_y_a: new e.aI(t4, i2.u_tex_y_a), u_tex_y_b: new e.aI(t4, i2.u_tex_y_b), u_mix: new e.aI(t4, i2.u_mix) }), raster: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_tl_parent: new e.aO(t4, i2.u_tl_parent), u_scale_parent: new e.aI(t4, i2.u_scale_parent), u_buffer_scale: new e.aI(t4, i2.u_buffer_scale), u_fade_t: new e.aI(t4, i2.u_fade_t), u_opacity: new e.aI(t4, i2.u_opacity), u_image0: new e.aH(t4, i2.u_image0), u_image1: new e.aH(t4, i2.u_image1), u_brightness_low: new e.aI(t4, i2.u_brightness_low), u_brightness_high: new e.aI(t4, i2.u_brightness_high), u_saturation_factor: new e.aI(t4, i2.u_saturation_factor), u_contrast_factor: new e.aI(t4, i2.u_contrast_factor), u_spin_weights: new e.aN(t4, i2.u_spin_weights) }), symbolIcon: (t4, i2) => ({ u_is_size_zoom_constant: new e.aH(t4, i2.u_is_size_zoom_constant), u_is_size_feature_constant: new e.aH(t4, i2.u_is_size_feature_constant), u_size_t: new e.aI(t4, i2.u_size_t), u_size: new e.aI(t4, i2.u_size), u_camera_to_center_distance: new e.aI(t4, i2.u_camera_to_center_distance), u_pitch: new e.aI(t4, i2.u_pitch), u_rotate_symbol: new e.aH(t4, i2.u_rotate_symbol), u_aspect_ratio: new e.aI(t4, i2.u_aspect_ratio), u_fade_change: new e.aI(t4, i2.u_fade_change), u_matrix: new e.aJ(t4, i2.u_matrix), u_label_plane_matrix: new e.aJ(t4, i2.u_label_plane_matrix), u_coord_matrix: new e.aJ(t4, i2.u_coord_matrix), u_is_text: new e.aH(t4, i2.u_is_text), u_pitch_with_map: new e.aH(t4, i2.u_pitch_with_map), u_is_along_line: new e.aH(t4, i2.u_is_along_line), u_is_variable_anchor: new e.aH(t4, i2.u_is_variable_anchor), u_texsize: new e.aO(t4, i2.u_texsize), u_texture: new e.aH(t4, i2.u_texture), u_translation: new e.aO(t4, i2.u_translation), u_pitched_scale: new e.aI(t4, i2.u_pitched_scale) }), symbolSDF: (t4, i2) => ({ u_is_size_zoom_constant: new e.aH(t4, i2.u_is_size_zoom_constant), u_is_size_feature_constant: new e.aH(t4, i2.u_is_size_feature_constant), u_size_t: new e.aI(t4, i2.u_size_t), u_size: new e.aI(t4, i2.u_size), u_camera_to_center_distance: new e.aI(t4, i2.u_camera_to_center_distance), u_pitch: new e.aI(t4, i2.u_pitch), u_rotate_symbol: new e.aH(t4, i2.u_rotate_symbol), u_aspect_ratio: new e.aI(t4, i2.u_aspect_ratio), u_fade_change: new e.aI(t4, i2.u_fade_change), u_matrix: new e.aJ(t4, i2.u_matrix), u_label_plane_matrix: new e.aJ(t4, i2.u_label_plane_matrix), u_coord_matrix: new e.aJ(t4, i2.u_coord_matrix), u_is_text: new e.aH(t4, i2.u_is_text), u_pitch_with_map: new e.aH(t4, i2.u_pitch_with_map), u_is_along_line: new e.aH(t4, i2.u_is_along_line), u_is_variable_anchor: new e.aH(t4, i2.u_is_variable_anchor), u_texsize: new e.aO(t4, i2.u_texsize), u_texture: new e.aH(t4, i2.u_texture), u_gamma_scale: new e.aI(t4, i2.u_gamma_scale), u_device_pixel_ratio: new e.aI(t4, i2.u_device_pixel_ratio), u_is_halo: new e.aH(t4, i2.u_is_halo), u_translation: new e.aO(t4, i2.u_translation), u_pitched_scale: new e.aI(t4, i2.u_pitched_scale) }), symbolTextAndIcon: (t4, i2) => ({ u_is_size_zoom_constant: new e.aH(t4, i2.u_is_size_zoom_constant), u_is_size_feature_constant: new e.aH(t4, i2.u_is_size_feature_constant), u_size_t: new e.aI(t4, i2.u_size_t), u_size: new e.aI(t4, i2.u_size), u_camera_to_center_distance: new e.aI(t4, i2.u_camera_to_center_distance), u_pitch: new e.aI(t4, i2.u_pitch), u_rotate_symbol: new e.aH(t4, i2.u_rotate_symbol), u_aspect_ratio: new e.aI(t4, i2.u_aspect_ratio), u_fade_change: new e.aI(t4, i2.u_fade_change), u_matrix: new e.aJ(t4, i2.u_matrix), u_label_plane_matrix: new e.aJ(t4, i2.u_label_plane_matrix), u_coord_matrix: new e.aJ(t4, i2.u_coord_matrix), u_is_text: new e.aH(t4, i2.u_is_text), u_pitch_with_map: new e.aH(t4, i2.u_pitch_with_map), u_is_along_line: new e.aH(t4, i2.u_is_along_line), u_is_variable_anchor: new e.aH(t4, i2.u_is_variable_anchor), u_texsize: new e.aO(t4, i2.u_texsize), u_texsize_icon: new e.aO(t4, i2.u_texsize_icon), u_texture: new e.aH(t4, i2.u_texture), u_texture_icon: new e.aH(t4, i2.u_texture_icon), u_gamma_scale: new e.aI(t4, i2.u_gamma_scale), u_device_pixel_ratio: new e.aI(t4, i2.u_device_pixel_ratio), u_is_halo: new e.aH(t4, i2.u_is_halo), u_translation: new e.aO(t4, i2.u_translation), u_pitched_scale: new e.aI(t4, i2.u_pitched_scale) }), background: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_opacity: new e.aI(t4, i2.u_opacity), u_color: new e.aL(t4, i2.u_color) }), backgroundPattern: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_opacity: new e.aI(t4, i2.u_opacity), u_image: new e.aH(t4, i2.u_image), u_pattern_tl_a: new e.aO(t4, i2.u_pattern_tl_a), u_pattern_br_a: new e.aO(t4, i2.u_pattern_br_a), u_pattern_tl_b: new e.aO(t4, i2.u_pattern_tl_b), u_pattern_br_b: new e.aO(t4, i2.u_pattern_br_b), u_texsize: new e.aO(t4, i2.u_texsize), u_mix: new e.aI(t4, i2.u_mix), u_pattern_size_a: new e.aO(t4, i2.u_pattern_size_a), u_pattern_size_b: new e.aO(t4, i2.u_pattern_size_b), u_scale_a: new e.aI(t4, i2.u_scale_a), u_scale_b: new e.aI(t4, i2.u_scale_b), u_pixel_coord_upper: new e.aO(t4, i2.u_pixel_coord_upper), u_pixel_coord_lower: new e.aO(t4, i2.u_pixel_coord_lower), u_tile_units_to_pixels: new e.aI(t4, i2.u_tile_units_to_pixels) }), terrain: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_texture: new e.aH(t4, i2.u_texture), u_ele_delta: new e.aI(t4, i2.u_ele_delta), u_fog_matrix: new e.aJ(t4, i2.u_fog_matrix), u_fog_color: new e.aL(t4, i2.u_fog_color), u_fog_ground_blend: new e.aI(t4, i2.u_fog_ground_blend), u_fog_ground_blend_opacity: new e.aI(t4, i2.u_fog_ground_blend_opacity), u_horizon_color: new e.aL(t4, i2.u_horizon_color), u_horizon_fog_blend: new e.aI(t4, i2.u_horizon_fog_blend) }), terrainDepth: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_ele_delta: new e.aI(t4, i2.u_ele_delta) }), terrainCoords: (t4, i2) => ({ u_matrix: new e.aJ(t4, i2.u_matrix), u_texture: new e.aH(t4, i2.u_texture), u_terrain_coords_id: new e.aI(t4, i2.u_terrain_coords_id), u_ele_delta: new e.aI(t4, i2.u_ele_delta) }), sky: (t4, i2) => ({ u_sky_color: new e.aL(t4, i2.u_sky_color), u_horizon_color: new e.aL(t4, i2.u_horizon_color), u_horizon: new e.aI(t4, i2.u_horizon), u_sky_horizon_blend: new e.aI(t4, i2.u_sky_horizon_blend) }) };
          class $e {
            constructor(t4, e2, i2) {
              this.context = t4;
              const a2 = t4.gl;
              this.buffer = a2.createBuffer(), this.dynamicDraw = Boolean(i2), this.context.unbindVAO(), t4.bindElementBuffer.set(this.buffer), a2.bufferData(a2.ELEMENT_ARRAY_BUFFER, e2.arrayBuffer, this.dynamicDraw ? a2.DYNAMIC_DRAW : a2.STATIC_DRAW), this.dynamicDraw || delete e2.arrayBuffer;
            }
            bind() {
              this.context.bindElementBuffer.set(this.buffer);
            }
            updateData(t4) {
              const e2 = this.context.gl;
              if (!this.dynamicDraw) throw new Error("Attempted to update data while not in dynamic mode.");
              this.context.unbindVAO(), this.bind(), e2.bufferSubData(e2.ELEMENT_ARRAY_BUFFER, 0, t4.arrayBuffer);
            }
            destroy() {
              this.buffer && (this.context.gl.deleteBuffer(this.buffer), delete this.buffer);
            }
          }
          const Xe = { Int8: "BYTE", Uint8: "UNSIGNED_BYTE", Int16: "SHORT", Uint16: "UNSIGNED_SHORT", Int32: "INT", Uint32: "UNSIGNED_INT", Float32: "FLOAT" };
          class Ke {
            constructor(t4, e2, i2, a2) {
              this.length = e2.length, this.attributes = i2, this.itemSize = e2.bytesPerElement, this.dynamicDraw = a2, this.context = t4;
              const s2 = t4.gl;
              this.buffer = s2.createBuffer(), t4.bindVertexBuffer.set(this.buffer), s2.bufferData(s2.ARRAY_BUFFER, e2.arrayBuffer, this.dynamicDraw ? s2.DYNAMIC_DRAW : s2.STATIC_DRAW), this.dynamicDraw || delete e2.arrayBuffer;
            }
            bind() {
              this.context.bindVertexBuffer.set(this.buffer);
            }
            updateData(t4) {
              if (t4.length !== this.length) throw new Error(`Length of new data is ${t4.length}, which doesn't match current length of ${this.length}`);
              const e2 = this.context.gl;
              this.bind(), e2.bufferSubData(e2.ARRAY_BUFFER, 0, t4.arrayBuffer);
            }
            enableAttributes(t4, e2) {
              for (let i2 = 0; i2 < this.attributes.length; i2++) {
                const a2 = e2.attributes[this.attributes[i2].name];
                void 0 !== a2 && t4.enableVertexAttribArray(a2);
              }
            }
            setVertexAttribPointers(t4, e2, i2) {
              for (let a2 = 0; a2 < this.attributes.length; a2++) {
                const s2 = this.attributes[a2], o2 = e2.attributes[s2.name];
                void 0 !== o2 && t4.vertexAttribPointer(o2, s2.components, t4[Xe[s2.type]], false, this.itemSize, s2.offset + this.itemSize * (i2 || 0));
              }
            }
            destroy() {
              this.buffer && (this.context.gl.deleteBuffer(this.buffer), delete this.buffer);
            }
          }
          const Je = /* @__PURE__ */ new WeakMap();
          function Ye(t4) {
            var e2;
            if (Je.has(t4)) return Je.get(t4);
            {
              const i2 = null === (e2 = t4.getParameter(t4.VERSION)) || void 0 === e2 ? void 0 : e2.startsWith("WebGL 2.0");
              return Je.set(t4, i2), i2;
            }
          }
          class Qe {
            constructor(t4) {
              this.gl = t4.gl, this.default = this.getDefault(), this.current = this.default, this.dirty = false;
            }
            get() {
              return this.current;
            }
            set(t4) {
            }
            getDefault() {
              return this.default;
            }
            setDefault() {
              this.set(this.default);
            }
          }
          class ti extends Qe {
            getDefault() {
              return e.aM.transparent;
            }
            set(t4) {
              const e2 = this.current;
              (t4.r !== e2.r || t4.g !== e2.g || t4.b !== e2.b || t4.a !== e2.a || this.dirty) && (this.gl.clearColor(t4.r, t4.g, t4.b, t4.a), this.current = t4, this.dirty = false);
            }
          }
          class ei extends Qe {
            getDefault() {
              return 1;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.clearDepth(t4), this.current = t4, this.dirty = false);
            }
          }
          class ii extends Qe {
            getDefault() {
              return 0;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.clearStencil(t4), this.current = t4, this.dirty = false);
            }
          }
          class ai extends Qe {
            getDefault() {
              return [true, true, true, true];
            }
            set(t4) {
              const e2 = this.current;
              (t4[0] !== e2[0] || t4[1] !== e2[1] || t4[2] !== e2[2] || t4[3] !== e2[3] || this.dirty) && (this.gl.colorMask(t4[0], t4[1], t4[2], t4[3]), this.current = t4, this.dirty = false);
            }
          }
          class si extends Qe {
            getDefault() {
              return true;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.depthMask(t4), this.current = t4, this.dirty = false);
            }
          }
          class oi extends Qe {
            getDefault() {
              return 255;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.stencilMask(t4), this.current = t4, this.dirty = false);
            }
          }
          class ri extends Qe {
            getDefault() {
              return { func: this.gl.ALWAYS, ref: 0, mask: 255 };
            }
            set(t4) {
              const e2 = this.current;
              (t4.func !== e2.func || t4.ref !== e2.ref || t4.mask !== e2.mask || this.dirty) && (this.gl.stencilFunc(t4.func, t4.ref, t4.mask), this.current = t4, this.dirty = false);
            }
          }
          class ni extends Qe {
            getDefault() {
              const t4 = this.gl;
              return [t4.KEEP, t4.KEEP, t4.KEEP];
            }
            set(t4) {
              const e2 = this.current;
              (t4[0] !== e2[0] || t4[1] !== e2[1] || t4[2] !== e2[2] || this.dirty) && (this.gl.stencilOp(t4[0], t4[1], t4[2]), this.current = t4, this.dirty = false);
            }
          }
          class li extends Qe {
            getDefault() {
              return false;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              t4 ? e2.enable(e2.STENCIL_TEST) : e2.disable(e2.STENCIL_TEST), this.current = t4, this.dirty = false;
            }
          }
          class hi extends Qe {
            getDefault() {
              return [0, 1];
            }
            set(t4) {
              const e2 = this.current;
              (t4[0] !== e2[0] || t4[1] !== e2[1] || this.dirty) && (this.gl.depthRange(t4[0], t4[1]), this.current = t4, this.dirty = false);
            }
          }
          class ci extends Qe {
            getDefault() {
              return false;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              t4 ? e2.enable(e2.DEPTH_TEST) : e2.disable(e2.DEPTH_TEST), this.current = t4, this.dirty = false;
            }
          }
          class ui extends Qe {
            getDefault() {
              return this.gl.LESS;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.depthFunc(t4), this.current = t4, this.dirty = false);
            }
          }
          class di extends Qe {
            getDefault() {
              return false;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              t4 ? e2.enable(e2.BLEND) : e2.disable(e2.BLEND), this.current = t4, this.dirty = false;
            }
          }
          class _i extends Qe {
            getDefault() {
              const t4 = this.gl;
              return [t4.ONE, t4.ZERO];
            }
            set(t4) {
              const e2 = this.current;
              (t4[0] !== e2[0] || t4[1] !== e2[1] || this.dirty) && (this.gl.blendFunc(t4[0], t4[1]), this.current = t4, this.dirty = false);
            }
          }
          class pi extends Qe {
            getDefault() {
              return e.aM.transparent;
            }
            set(t4) {
              const e2 = this.current;
              (t4.r !== e2.r || t4.g !== e2.g || t4.b !== e2.b || t4.a !== e2.a || this.dirty) && (this.gl.blendColor(t4.r, t4.g, t4.b, t4.a), this.current = t4, this.dirty = false);
            }
          }
          class mi extends Qe {
            getDefault() {
              return this.gl.FUNC_ADD;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.blendEquation(t4), this.current = t4, this.dirty = false);
            }
          }
          class fi extends Qe {
            getDefault() {
              return false;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              t4 ? e2.enable(e2.CULL_FACE) : e2.disable(e2.CULL_FACE), this.current = t4, this.dirty = false;
            }
          }
          class gi extends Qe {
            getDefault() {
              return this.gl.BACK;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.cullFace(t4), this.current = t4, this.dirty = false);
            }
          }
          class vi extends Qe {
            getDefault() {
              return this.gl.CCW;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.frontFace(t4), this.current = t4, this.dirty = false);
            }
          }
          class xi extends Qe {
            getDefault() {
              return null;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.useProgram(t4), this.current = t4, this.dirty = false);
            }
          }
          class yi extends Qe {
            getDefault() {
              return this.gl.TEXTURE0;
            }
            set(t4) {
              (t4 !== this.current || this.dirty) && (this.gl.activeTexture(t4), this.current = t4, this.dirty = false);
            }
          }
          class bi extends Qe {
            getDefault() {
              const t4 = this.gl;
              return [0, 0, t4.drawingBufferWidth, t4.drawingBufferHeight];
            }
            set(t4) {
              const e2 = this.current;
              (t4[0] !== e2[0] || t4[1] !== e2[1] || t4[2] !== e2[2] || t4[3] !== e2[3] || this.dirty) && (this.gl.viewport(t4[0], t4[1], t4[2], t4[3]), this.current = t4, this.dirty = false);
            }
          }
          class wi extends Qe {
            getDefault() {
              return null;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              e2.bindFramebuffer(e2.FRAMEBUFFER, t4), this.current = t4, this.dirty = false;
            }
          }
          class Ti extends Qe {
            getDefault() {
              return null;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              e2.bindRenderbuffer(e2.RENDERBUFFER, t4), this.current = t4, this.dirty = false;
            }
          }
          class Ii extends Qe {
            getDefault() {
              return null;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              e2.bindTexture(e2.TEXTURE_2D, t4), this.current = t4, this.dirty = false;
            }
          }
          class Ei extends Qe {
            getDefault() {
              return null;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              e2.bindBuffer(e2.ARRAY_BUFFER, t4), this.current = t4, this.dirty = false;
            }
          }
          class Pi extends Qe {
            getDefault() {
              return null;
            }
            set(t4) {
              const e2 = this.gl;
              e2.bindBuffer(e2.ELEMENT_ARRAY_BUFFER, t4), this.current = t4, this.dirty = false;
            }
          }
          class Ci extends Qe {
            getDefault() {
              return null;
            }
            set(t4) {
              var e2;
              if (t4 === this.current && !this.dirty) return;
              const i2 = this.gl;
              Ye(i2) ? i2.bindVertexArray(t4) : null === (e2 = i2.getExtension("OES_vertex_array_object")) || void 0 === e2 || e2.bindVertexArrayOES(t4), this.current = t4, this.dirty = false;
            }
          }
          class Si extends Qe {
            getDefault() {
              return 4;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              e2.pixelStorei(e2.UNPACK_ALIGNMENT, t4), this.current = t4, this.dirty = false;
            }
          }
          class zi extends Qe {
            getDefault() {
              return false;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              e2.pixelStorei(e2.UNPACK_PREMULTIPLY_ALPHA_WEBGL, t4), this.current = t4, this.dirty = false;
            }
          }
          class Di extends Qe {
            getDefault() {
              return false;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              const e2 = this.gl;
              e2.pixelStorei(e2.UNPACK_FLIP_Y_WEBGL, t4), this.current = t4, this.dirty = false;
            }
          }
          class Mi extends Qe {
            constructor(t4, e2) {
              super(t4), this.context = t4, this.parent = e2;
            }
            getDefault() {
              return null;
            }
          }
          class Ai extends Mi {
            setDirty() {
              this.dirty = true;
            }
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              this.context.bindFramebuffer.set(this.parent);
              const e2 = this.gl;
              e2.framebufferTexture2D(e2.FRAMEBUFFER, e2.COLOR_ATTACHMENT0, e2.TEXTURE_2D, t4, 0), this.current = t4, this.dirty = false;
            }
          }
          class Ri extends Mi {
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              this.context.bindFramebuffer.set(this.parent);
              const e2 = this.gl;
              e2.framebufferRenderbuffer(e2.FRAMEBUFFER, e2.DEPTH_ATTACHMENT, e2.RENDERBUFFER, t4), this.current = t4, this.dirty = false;
            }
          }
          class ki extends Mi {
            set(t4) {
              if (t4 === this.current && !this.dirty) return;
              this.context.bindFramebuffer.set(this.parent);
              const e2 = this.gl;
              e2.framebufferRenderbuffer(e2.FRAMEBUFFER, e2.DEPTH_STENCIL_ATTACHMENT, e2.RENDERBUFFER, t4), this.current = t4, this.dirty = false;
            }
          }
          class Li {
            constructor(t4, e2, i2, a2, s2) {
              this.context = t4, this.width = e2, this.height = i2;
              const o2 = t4.gl, r2 = this.framebuffer = o2.createFramebuffer();
              if (this.colorAttachment = new Ai(t4, r2), a2) this.depthAttachment = s2 ? new ki(t4, r2) : new Ri(t4, r2);
              else if (s2) throw new Error("Stencil cannot be set without depth");
              if (o2.checkFramebufferStatus(o2.FRAMEBUFFER) !== o2.FRAMEBUFFER_COMPLETE) throw new Error("Framebuffer is not complete");
            }
            destroy() {
              const t4 = this.context.gl, e2 = this.colorAttachment.get();
              if (e2 && t4.deleteTexture(e2), this.depthAttachment) {
                const e3 = this.depthAttachment.get();
                e3 && t4.deleteRenderbuffer(e3);
              }
              t4.deleteFramebuffer(this.framebuffer);
            }
          }
          class Fi {
            constructor(t4, e2, i2) {
              this.blendFunction = t4, this.blendColor = e2, this.mask = i2;
            }
          }
          Fi.Replace = [1, 0], Fi.disabled = new Fi(Fi.Replace, e.aM.transparent, [false, false, false, false]), Fi.unblended = new Fi(Fi.Replace, e.aM.transparent, [true, true, true, true]), Fi.alphaBlended = new Fi([1, 771], e.aM.transparent, [true, true, true, true]);
          class Bi {
            constructor(t4) {
              var e2, i2;
              if (this.gl = t4, this.clearColor = new ti(this), this.clearDepth = new ei(this), this.clearStencil = new ii(this), this.colorMask = new ai(this), this.depthMask = new si(this), this.stencilMask = new oi(this), this.stencilFunc = new ri(this), this.stencilOp = new ni(this), this.stencilTest = new li(this), this.depthRange = new hi(this), this.depthTest = new ci(this), this.depthFunc = new ui(this), this.blend = new di(this), this.blendFunc = new _i(this), this.blendColor = new pi(this), this.blendEquation = new mi(this), this.cullFace = new fi(this), this.cullFaceSide = new gi(this), this.frontFace = new vi(this), this.program = new xi(this), this.activeTexture = new yi(this), this.viewport = new bi(this), this.bindFramebuffer = new wi(this), this.bindRenderbuffer = new Ti(this), this.bindTexture = new Ii(this), this.bindVertexBuffer = new Ei(this), this.bindElementBuffer = new Pi(this), this.bindVertexArray = new Ci(this), this.pixelStoreUnpack = new Si(this), this.pixelStoreUnpackPremultiplyAlpha = new zi(this), this.pixelStoreUnpackFlipY = new Di(this), this.extTextureFilterAnisotropic = t4.getExtension("EXT_texture_filter_anisotropic") || t4.getExtension("MOZ_EXT_texture_filter_anisotropic") || t4.getExtension("WEBKIT_EXT_texture_filter_anisotropic"), this.extTextureFilterAnisotropic && (this.extTextureFilterAnisotropicMax = t4.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)), this.maxTextureSize = t4.getParameter(t4.MAX_TEXTURE_SIZE), Ye(t4)) {
                this.HALF_FLOAT = t4.HALF_FLOAT;
                const a2 = t4.getExtension("EXT_color_buffer_half_float");
                this.RGBA16F = null !== (e2 = t4.RGBA16F) && void 0 !== e2 ? e2 : null == a2 ? void 0 : a2.RGBA16F_EXT, this.RGB16F = null !== (i2 = t4.RGB16F) && void 0 !== i2 ? i2 : null == a2 ? void 0 : a2.RGB16F_EXT, t4.getExtension("EXT_color_buffer_float");
              } else {
                t4.getExtension("EXT_color_buffer_half_float"), t4.getExtension("OES_texture_half_float_linear");
                const e3 = t4.getExtension("OES_texture_half_float");
                this.HALF_FLOAT = null == e3 ? void 0 : e3.HALF_FLOAT_OES;
              }
            }
            setDefault() {
              this.unbindVAO(), this.clearColor.setDefault(), this.clearDepth.setDefault(), this.clearStencil.setDefault(), this.colorMask.setDefault(), this.depthMask.setDefault(), this.stencilMask.setDefault(), this.stencilFunc.setDefault(), this.stencilOp.setDefault(), this.stencilTest.setDefault(), this.depthRange.setDefault(), this.depthTest.setDefault(), this.depthFunc.setDefault(), this.blend.setDefault(), this.blendFunc.setDefault(), this.blendColor.setDefault(), this.blendEquation.setDefault(), this.cullFace.setDefault(), this.cullFaceSide.setDefault(), this.frontFace.setDefault(), this.program.setDefault(), this.activeTexture.setDefault(), this.bindFramebuffer.setDefault(), this.pixelStoreUnpack.setDefault(), this.pixelStoreUnpackPremultiplyAlpha.setDefault(), this.pixelStoreUnpackFlipY.setDefault();
            }
            setDirty() {
              this.clearColor.dirty = true, this.clearDepth.dirty = true, this.clearStencil.dirty = true, this.colorMask.dirty = true, this.depthMask.dirty = true, this.stencilMask.dirty = true, this.stencilFunc.dirty = true, this.stencilOp.dirty = true, this.stencilTest.dirty = true, this.depthRange.dirty = true, this.depthTest.dirty = true, this.depthFunc.dirty = true, this.blend.dirty = true, this.blendFunc.dirty = true, this.blendColor.dirty = true, this.blendEquation.dirty = true, this.cullFace.dirty = true, this.cullFaceSide.dirty = true, this.frontFace.dirty = true, this.program.dirty = true, this.activeTexture.dirty = true, this.viewport.dirty = true, this.bindFramebuffer.dirty = true, this.bindRenderbuffer.dirty = true, this.bindTexture.dirty = true, this.bindVertexBuffer.dirty = true, this.bindElementBuffer.dirty = true, this.bindVertexArray.dirty = true, this.pixelStoreUnpack.dirty = true, this.pixelStoreUnpackPremultiplyAlpha.dirty = true, this.pixelStoreUnpackFlipY.dirty = true;
            }
            createIndexBuffer(t4, e2) {
              return new $e(this, t4, e2);
            }
            createVertexBuffer(t4, e2, i2) {
              return new Ke(this, t4, e2, i2);
            }
            createRenderbuffer(t4, e2, i2) {
              const a2 = this.gl, s2 = a2.createRenderbuffer();
              return this.bindRenderbuffer.set(s2), a2.renderbufferStorage(a2.RENDERBUFFER, t4, e2, i2), this.bindRenderbuffer.set(null), s2;
            }
            createFramebuffer(t4, e2, i2, a2) {
              return new Li(this, t4, e2, i2, a2);
            }
            clear({ color: t4, depth: e2, stencil: i2 }) {
              const a2 = this.gl;
              let s2 = 0;
              t4 && (s2 |= a2.COLOR_BUFFER_BIT, this.clearColor.set(t4), this.colorMask.set([true, true, true, true])), void 0 !== e2 && (s2 |= a2.DEPTH_BUFFER_BIT, this.depthRange.set([0, 1]), this.clearDepth.set(e2), this.depthMask.set(true)), void 0 !== i2 && (s2 |= a2.STENCIL_BUFFER_BIT, this.clearStencil.set(i2), this.stencilMask.set(255)), a2.clear(s2);
            }
            setCullFace(t4) {
              false === t4.enable ? this.cullFace.set(false) : (this.cullFace.set(true), this.cullFaceSide.set(t4.mode), this.frontFace.set(t4.frontFace));
            }
            setDepthMode(t4) {
              t4.func !== this.gl.ALWAYS || t4.mask ? (this.depthTest.set(true), this.depthFunc.set(t4.func), this.depthMask.set(t4.mask), this.depthRange.set(t4.range)) : this.depthTest.set(false);
            }
            setStencilMode(t4) {
              t4.test.func !== this.gl.ALWAYS || t4.mask ? (this.stencilTest.set(true), this.stencilMask.set(t4.mask), this.stencilOp.set([t4.fail, t4.depthFail, t4.pass]), this.stencilFunc.set({ func: t4.test.func, ref: t4.ref, mask: t4.test.mask })) : this.stencilTest.set(false);
            }
            setColorMode(t4) {
              e.aE(t4.blendFunction, Fi.Replace) ? this.blend.set(false) : (this.blend.set(true), this.blendFunc.set(t4.blendFunction), this.blendColor.set(t4.blendColor)), this.colorMask.set(t4.mask);
            }
            createVertexArray() {
              var t4;
              return Ye(this.gl) ? this.gl.createVertexArray() : null === (t4 = this.gl.getExtension("OES_vertex_array_object")) || void 0 === t4 ? void 0 : t4.createVertexArrayOES();
            }
            deleteVertexArray(t4) {
              var e2;
              return Ye(this.gl) ? this.gl.deleteVertexArray(t4) : null === (e2 = this.gl.getExtension("OES_vertex_array_object")) || void 0 === e2 ? void 0 : e2.deleteVertexArrayOES(t4);
            }
            unbindVAO() {
              this.bindVertexArray.set(null);
            }
          }
          class Oi {
            constructor(t4, e2, i2) {
              this.func = t4, this.mask = e2, this.range = i2;
            }
          }
          Oi.ReadOnly = false, Oi.ReadWrite = true, Oi.disabled = new Oi(519, Oi.ReadOnly, [0, 1]);
          const Ni = 7680;
          class Ui {
            constructor(t4, e2, i2, a2, s2, o2) {
              this.test = t4, this.ref = e2, this.mask = i2, this.fail = a2, this.depthFail = s2, this.pass = o2;
            }
          }
          Ui.disabled = new Ui({ func: 519, mask: 0 }, 0, 0, Ni, Ni, Ni);
          class ji {
            constructor(t4, e2, i2) {
              this.enable = t4, this.mode = e2, this.frontFace = i2;
            }
          }
          let Zi;
          function qi(t4, i2, a2, s2, o2) {
            const r2 = t4.context, n2 = r2.gl, l2 = t4.useProgram("collisionBox"), h2 = [];
            let c2 = 0, u2 = 0;
            for (let _3 = 0; _3 < s2.length; _3++) {
              const p3 = s2[_3], m3 = i2.getTile(p3).getBucket(a2);
              if (!m3) continue;
              const f3 = o2 ? m3.textCollisionBox : m3.iconCollisionBox, g3 = m3.collisionCircleArray;
              if (g3.length > 0) {
                const i3 = e.H();
                e.aQ(i3, m3.placementInvProjMatrix, t4.transform.glCoordMatrix), e.aQ(i3, i3, m3.placementViewportMatrix), h2.push({ circleArray: g3, circleOffset: u2, transform: p3.posMatrix, invTransform: i3, coord: p3 }), c2 += g3.length / 4, u2 = c2;
              }
              f3 && l2.draw(r2, n2.LINES, Oi.disabled, Ui.disabled, t4.colorModeForRenderPass(), ji.disabled, { u_matrix: p3.posMatrix, u_pixel_extrude_scale: [1 / (d2 = t4.transform).width, 1 / d2.height] }, t4.style.map.terrain && t4.style.map.terrain.getTerrainData(p3), a2.id, f3.layoutVertexBuffer, f3.indexBuffer, f3.segments, null, t4.transform.zoom, null, null, f3.collisionVertexBuffer);
            }
            var d2;
            if (!o2 || !h2.length) return;
            const _2 = t4.useProgram("collisionCircle"), p2 = new e.aR();
            p2.resize(4 * c2), p2._trim();
            let m2 = 0;
            for (const t5 of h2) for (let e2 = 0; e2 < t5.circleArray.length / 4; e2++) {
              const i3 = 4 * e2, a3 = t5.circleArray[i3 + 0], s3 = t5.circleArray[i3 + 1], o3 = t5.circleArray[i3 + 2], r3 = t5.circleArray[i3 + 3];
              p2.emplace(m2++, a3, s3, o3, r3, 0), p2.emplace(m2++, a3, s3, o3, r3, 1), p2.emplace(m2++, a3, s3, o3, r3, 2), p2.emplace(m2++, a3, s3, o3, r3, 3);
            }
            (!Zi || Zi.length < 2 * c2) && (Zi = function(t5) {
              const i3 = 2 * t5, a3 = new e.aT();
              a3.resize(i3), a3._trim();
              for (let t6 = 0; t6 < i3; t6++) {
                const e2 = 6 * t6;
                a3.uint16[e2 + 0] = 4 * t6 + 0, a3.uint16[e2 + 1] = 4 * t6 + 1, a3.uint16[e2 + 2] = 4 * t6 + 2, a3.uint16[e2 + 3] = 4 * t6 + 2, a3.uint16[e2 + 4] = 4 * t6 + 3, a3.uint16[e2 + 5] = 4 * t6 + 0;
              }
              return a3;
            }(c2));
            const f2 = r2.createIndexBuffer(Zi, true), g2 = r2.createVertexBuffer(p2, e.aS.members, true);
            for (const i3 of h2) {
              const s3 = Se(i3.transform, i3.invTransform, t4.transform);
              _2.draw(r2, n2.TRIANGLES, Oi.disabled, Ui.disabled, t4.colorModeForRenderPass(), ji.disabled, s3, t4.style.map.terrain && t4.style.map.terrain.getTerrainData(i3.coord), a2.id, g2, f2, e.a0.simpleSegment(0, 2 * i3.circleOffset, i3.circleArray.length, i3.circleArray.length / 2), null, t4.transform.zoom, null, null, null);
            }
            g2.destroy(), f2.destroy();
          }
          ji.disabled = new ji(false, 1029, 2305), ji.backCCW = new ji(true, 1029, 2305);
          const Vi = e.an(new Float32Array(16));
          function Gi(t4, i2, a2, s2, o2, r2) {
            const { horizontalAlign: n2, verticalAlign: l2 } = e.au(t4);
            return new e.P((-(n2 - 0.5) * i2 / o2 + s2[0]) * r2, (-(l2 - 0.5) * a2 / o2 + s2[1]) * r2);
          }
          function Hi(t4, i2, a2, s2, o2, r2) {
            const n2 = i2.tileAnchorPoint.add(new e.P(i2.translation[0], i2.translation[1]));
            if (i2.pitchWithMap) {
              let t5 = s2.mult(r2);
              a2 || (t5 = t5.rotate(-o2));
              const e2 = n2.add(t5);
              return xt(e2.x, e2.y, i2.labelPlaneMatrix, i2.getElevation).point;
            }
            if (a2) {
              const e2 = St(i2.tileAnchorPoint.x + 1, i2.tileAnchorPoint.y, i2).point.sub(t4), a3 = Math.atan(e2.y / e2.x) + (e2.x < 0 ? Math.PI : 0);
              return t4.add(s2.rotate(a3));
            }
            return t4.add(s2);
          }
          function Wi(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2, _2, p2) {
            const m2 = t4.text.placedSymbolArray, f2 = t4.text.dynamicLayoutVertexArray, g2 = t4.icon.dynamicLayoutVertexArray, v2 = {};
            f2.clear();
            for (let g3 = 0; g3 < m2.length; g3++) {
              const x2 = m2.get(g3), y2 = x2.hidden || !x2.crossTileID || t4.allowVerticalPlacement && !x2.placedOrientation ? null : s2[x2.crossTileID];
              if (y2) {
                const s3 = new e.P(x2.anchorX, x2.anchorY), m3 = { getElevation: p2, width: o2.width, height: o2.height, labelPlaneMatrix: r2, lineVertexArray: null, pitchWithMap: a2, projection: u2, projectionCache: null, tileAnchorPoint: s3, translation: d2, unwrappedTileID: _2 }, g4 = a2 ? xt(s3.x, s3.y, n2, p2) : St(s3.x, s3.y, m3), b2 = yt(o2.cameraToCenterDistance, g4.signedDistanceFromCamera);
                let w2 = e.ai(t4.textSizeData, h2, x2) * b2 / e.ap;
                a2 && (w2 *= t4.tilePixelRatio / l2);
                const { width: T2, height: I2, anchor: E3, textOffset: P2, textBoxScale: C3 } = y2, S2 = Gi(E3, T2, I2, P2, C3, w2), z2 = u2.getPitchedTextCorrection(o2, s3.add(new e.P(d2[0], d2[1])), _2), D3 = Hi(g4.point, m3, i2, S2, o2.angle, z2), M2 = t4.allowVerticalPlacement && x2.placedOrientation === e.ah.vertical ? Math.PI / 2 : 0;
                for (let t5 = 0; t5 < x2.numGlyphs; t5++) e.aj(f2, D3, M2);
                c2 && x2.associatedIconIndex >= 0 && (v2[x2.associatedIconIndex] = { shiftedAnchor: D3, angle: M2 });
              } else Rt(x2.numGlyphs, f2);
            }
            if (c2) {
              g2.clear();
              const i3 = t4.icon.placedSymbolArray;
              for (let t5 = 0; t5 < i3.length; t5++) {
                const a3 = i3.get(t5);
                if (a3.hidden) Rt(a3.numGlyphs, g2);
                else {
                  const i4 = v2[t5];
                  if (i4) for (let t6 = 0; t6 < a3.numGlyphs; t6++) e.aj(g2, i4.shiftedAnchor, i4.angle);
                  else Rt(a3.numGlyphs, g2);
                }
              }
              t4.icon.dynamicLayoutVertexBuffer.updateData(g2);
            }
            t4.text.dynamicLayoutVertexBuffer.updateData(f2);
          }
          function $i(t4, e2, i2) {
            return i2.iconsInText && e2 ? "symbolTextAndIcon" : t4 ? "symbolSDF" : "symbolIcon";
          }
          function Xi(t4, i2, a2, s2, o2, r2, n2, l2, h2, c2, u2, d2) {
            const _2 = t4.context, p2 = _2.gl, m2 = t4.transform, f2 = ie(), g2 = "map" === l2, v2 = "map" === h2, x2 = "viewport" !== l2 && "point" !== a2.layout.get("symbol-placement"), y2 = g2 && !v2 && !x2, b2 = !v2 && x2, w2 = !a2.layout.get("symbol-sort-key").isConstant();
            let T2 = false;
            const I2 = t4.depthModeForSublayer(0, Oi.ReadOnly), E3 = a2._unevaluatedLayout.hasValue("text-variable-anchor") || a2._unevaluatedLayout.hasValue("text-variable-anchor-offset"), P2 = [], C3 = f2.getCircleRadiusCorrection(m2);
            for (const l3 of s2) {
              const s3 = i2.getTile(l3), h3 = s3.getBucket(a2);
              if (!h3) continue;
              const u3 = o2 ? h3.text : h3.icon;
              if (!u3 || !u3.segments.get().length || !u3.hasVisibleVertices) continue;
              const d3 = u3.programConfigurations.get(a2.id), _3 = o2 || h3.sdfIcons, I3 = o2 ? h3.textSizeData : h3.iconSizeData, S2 = v2 || 0 !== m2.pitch, z2 = t4.useProgram($i(_3, o2, h3), d3), D3 = e.ag(I3, m2.zoom), M2 = t4.style.map.terrain && t4.style.map.terrain.getTerrainData(l3);
              let A3, R2, k2, L2, F2 = [0, 0], B3 = null;
              if (o2) R2 = s3.glyphAtlasTexture, k2 = p2.LINEAR, A3 = s3.glyphAtlasTexture.size, h3.iconsInText && (F2 = s3.imageAtlasTexture.size, B3 = s3.imageAtlasTexture, L2 = S2 || t4.options.rotating || t4.options.zooming || "composite" === I3.kind || "camera" === I3.kind ? p2.LINEAR : p2.NEAREST);
              else {
                const e2 = 1 !== a2.layout.get("icon-size").constantOr(0) || h3.iconsNeedLinear;
                R2 = s3.imageAtlasTexture, k2 = _3 || t4.options.rotating || t4.options.zooming || e2 || S2 ? p2.LINEAR : p2.NEAREST, A3 = s3.imageAtlasTexture.size;
              }
              const O2 = Bt(s3, 1, t4.transform.zoom), N2 = b2 ? l3.posMatrix : Vi, U2 = gt(N2, v2, g2, t4.transform, O2), j2 = vt(N2, v2, g2, t4.transform, O2), Z2 = vt(l3.posMatrix, v2, g2, t4.transform, O2), q2 = f2.translatePosition(t4.transform, s3, r2, n2), V2 = E3 && h3.hasTextData(), G2 = "none" !== a2.layout.get("icon-text-fit") && V2 && h3.hasIconData();
              if (x2) {
                const e2 = t4.style.map.terrain ? (e3, i4) => t4.style.map.terrain.getElevation(l3, e3, i4) : null, i3 = "map" === a2.layout.get("text-rotation-alignment");
                wt(h3, l3.posMatrix, t4, o2, U2, Z2, v2, c2, i3, f2, l3.toUnwrapped(), m2.width, m2.height, q2, e2);
              }
              const H2 = l3.posMatrix, W2 = o2 && E3 || G2, $2 = x2 || W2 ? Vi : U2, X2 = j2, K3 = _3 && 0 !== a2.paint.get(o2 ? "text-halo-width" : "icon-halo-width").constantOr(1);
              let J2;
              J2 = _3 ? h3.iconsInText ? Ve(I3.kind, D3, y2, v2, x2, W2, t4, H2, $2, X2, q2, A3, F2, C3) : qe(I3.kind, D3, y2, v2, x2, W2, t4, H2, $2, X2, q2, o2, A3, true, C3) : Ze(I3.kind, D3, y2, v2, x2, W2, t4, H2, $2, X2, q2, o2, A3, C3);
              const Y2 = { program: z2, buffers: u3, uniformValues: J2, atlasTexture: R2, atlasTextureIcon: B3, atlasInterpolation: k2, atlasInterpolationIcon: L2, isSDF: _3, hasHalo: K3 };
              if (w2 && h3.canOverlap) {
                T2 = true;
                const t5 = u3.segments.get();
                for (const i3 of t5) P2.push({ segments: new e.a0([i3]), sortKey: i3.sortKey, state: Y2, terrainData: M2 });
              } else P2.push({ segments: u3.segments, sortKey: 0, state: Y2, terrainData: M2 });
            }
            T2 && P2.sort((t5, e2) => t5.sortKey - e2.sortKey);
            for (const e2 of P2) {
              const i3 = e2.state;
              if (_2.activeTexture.set(p2.TEXTURE0), i3.atlasTexture.bind(i3.atlasInterpolation, p2.CLAMP_TO_EDGE), i3.atlasTextureIcon && (_2.activeTexture.set(p2.TEXTURE1), i3.atlasTextureIcon && i3.atlasTextureIcon.bind(i3.atlasInterpolationIcon, p2.CLAMP_TO_EDGE)), i3.isSDF) {
                const s3 = i3.uniformValues;
                i3.hasHalo && (s3.u_is_halo = 1, Ki(i3.buffers, e2.segments, a2, t4, i3.program, I2, u2, d2, s3, e2.terrainData)), s3.u_is_halo = 0;
              }
              Ki(i3.buffers, e2.segments, a2, t4, i3.program, I2, u2, d2, i3.uniformValues, e2.terrainData);
            }
          }
          function Ki(t4, e2, i2, a2, s2, o2, r2, n2, l2, h2) {
            const c2 = a2.context;
            s2.draw(c2, c2.gl.TRIANGLES, o2, r2, n2, ji.disabled, l2, h2, i2.id, t4.layoutVertexBuffer, t4.indexBuffer, e2, i2.paint, a2.transform.zoom, t4.programConfigurations.get(i2.id), t4.dynamicLayoutVertexBuffer, t4.opacityVertexBuffer);
          }
          function Ji(t4, i2, a2, s2) {
            const o2 = t4.context, r2 = o2.gl, n2 = Ui.disabled, l2 = new Fi([r2.ONE, r2.ONE], e.aM.transparent, [true, true, true, true]), h2 = i2.getBucket(a2);
            if (!h2) return;
            const c2 = s2.key;
            let u2 = a2.heatmapFbos.get(c2);
            u2 || (u2 = Qi(o2, i2.tileSize, i2.tileSize), a2.heatmapFbos.set(c2, u2)), o2.bindFramebuffer.set(u2.framebuffer), o2.viewport.set([0, 0, i2.tileSize, i2.tileSize]), o2.clear({ color: e.aM.transparent });
            const d2 = h2.programConfigurations.get(a2.id), _2 = t4.useProgram("heatmap", d2), p2 = t4.style.map.terrain.getTerrainData(s2);
            _2.draw(o2, r2.TRIANGLES, Oi.disabled, n2, l2, ji.disabled, Me(s2.posMatrix, i2, t4.transform.zoom, a2.paint.get("heatmap-intensity")), p2, a2.id, h2.layoutVertexBuffer, h2.indexBuffer, h2.segments, a2.paint, t4.transform.zoom, d2);
          }
          function Yi(t4, e2, i2) {
            const a2 = t4.context, s2 = a2.gl;
            a2.setColorMode(t4.colorModeForRenderPass());
            const o2 = ta(a2, e2), r2 = i2.key, n2 = e2.heatmapFbos.get(r2);
            n2 && (a2.activeTexture.set(s2.TEXTURE0), s2.bindTexture(s2.TEXTURE_2D, n2.colorAttachment.get()), a2.activeTexture.set(s2.TEXTURE1), o2.bind(s2.LINEAR, s2.CLAMP_TO_EDGE), t4.useProgram("heatmapTexture").draw(a2, s2.TRIANGLES, Oi.disabled, Ui.disabled, t4.colorModeForRenderPass(), ji.disabled, Ae(t4, e2, 0, 1), null, e2.id, t4.rasterBoundsBuffer, t4.quadTriangleIndexBuffer, t4.rasterBoundsSegments, e2.paint, t4.transform.zoom), n2.destroy(), e2.heatmapFbos.delete(r2));
          }
          function Qi(t4, e2, i2) {
            var a2, s2;
            const o2 = t4.gl, r2 = o2.createTexture();
            o2.bindTexture(o2.TEXTURE_2D, r2), o2.texParameteri(o2.TEXTURE_2D, o2.TEXTURE_WRAP_S, o2.CLAMP_TO_EDGE), o2.texParameteri(o2.TEXTURE_2D, o2.TEXTURE_WRAP_T, o2.CLAMP_TO_EDGE), o2.texParameteri(o2.TEXTURE_2D, o2.TEXTURE_MIN_FILTER, o2.LINEAR), o2.texParameteri(o2.TEXTURE_2D, o2.TEXTURE_MAG_FILTER, o2.LINEAR);
            const n2 = null !== (a2 = t4.HALF_FLOAT) && void 0 !== a2 ? a2 : o2.UNSIGNED_BYTE, l2 = null !== (s2 = t4.RGBA16F) && void 0 !== s2 ? s2 : o2.RGBA;
            o2.texImage2D(o2.TEXTURE_2D, 0, l2, e2, i2, 0, o2.RGBA, n2, null);
            const h2 = t4.createFramebuffer(e2, i2, false, false);
            return h2.colorAttachment.set(r2), h2;
          }
          function ta(t4, e2) {
            return e2.colorRampTexture || (e2.colorRampTexture = new b(t4, e2.colorRamp, t4.gl.RGBA)), e2.colorRampTexture;
          }
          function ea(t4, e2, i2, a2, s2) {
            if (!i2 || !a2 || !a2.imageAtlas) return;
            const o2 = a2.imageAtlas.patternPositions;
            let r2 = o2[i2.to.toString()], n2 = o2[i2.from.toString()];
            if (!r2 && n2 && (r2 = n2), !n2 && r2 && (n2 = r2), !r2 || !n2) {
              const t5 = s2.getPaintProperty(e2);
              r2 = o2[t5], n2 = o2[t5];
            }
            r2 && n2 && t4.setConstantPatternPositions(r2, n2);
          }
          function ia(t4, e2, i2, a2, s2, o2, r2) {
            const n2 = t4.context.gl, l2 = "fill-pattern", h2 = i2.paint.get(l2), c2 = h2 && h2.constantOr(1), u2 = i2.getCrossfadeParameters();
            let d2, _2, p2, m2, f2;
            r2 ? (_2 = c2 && !i2.getPaintProperty("fill-outline-color") ? "fillOutlinePattern" : "fillOutline", d2 = n2.LINES) : (_2 = c2 ? "fillPattern" : "fill", d2 = n2.TRIANGLES);
            const g2 = h2.constantOr(null);
            for (const h3 of a2) {
              const a3 = e2.getTile(h3);
              if (c2 && !a3.patternsLoaded()) continue;
              const v2 = a3.getBucket(i2);
              if (!v2) continue;
              const x2 = v2.programConfigurations.get(i2.id), y2 = t4.useProgram(_2, x2), b2 = t4.style.map.terrain && t4.style.map.terrain.getTerrainData(h3);
              c2 && (t4.context.activeTexture.set(n2.TEXTURE0), a3.imageAtlasTexture.bind(n2.LINEAR, n2.CLAMP_TO_EDGE), x2.updatePaintBuffers(u2)), ea(x2, l2, g2, a3, i2);
              const w2 = b2 ? h3 : null, T2 = t4.translatePosMatrix(w2 ? w2.posMatrix : h3.posMatrix, a3, i2.paint.get("fill-translate"), i2.paint.get("fill-translate-anchor"));
              if (r2) {
                m2 = v2.indexBuffer2, f2 = v2.segments2;
                const e3 = [n2.drawingBufferWidth, n2.drawingBufferHeight];
                p2 = "fillOutlinePattern" === _2 && c2 ? Pe(T2, t4, u2, a3, e3) : Ee(T2, e3);
              } else m2 = v2.indexBuffer, f2 = v2.segments, p2 = c2 ? Ie(T2, t4, u2, a3) : Te(T2);
              y2.draw(t4.context, d2, s2, t4.stencilModeForClipping(h3), o2, ji.disabled, p2, b2, i2.id, v2.layoutVertexBuffer, m2, f2, i2.paint, t4.transform.zoom, x2);
            }
          }
          function aa(t4, e2, i2, a2, s2, o2, r2) {
            const n2 = t4.context, l2 = n2.gl, h2 = "fill-extrusion-pattern", c2 = i2.paint.get(h2), u2 = c2.constantOr(1), d2 = i2.getCrossfadeParameters(), _2 = i2.paint.get("fill-extrusion-opacity"), p2 = c2.constantOr(null);
            for (const c3 of a2) {
              const a3 = e2.getTile(c3), m2 = a3.getBucket(i2);
              if (!m2) continue;
              const f2 = t4.style.map.terrain && t4.style.map.terrain.getTerrainData(c3), g2 = m2.programConfigurations.get(i2.id), v2 = t4.useProgram(u2 ? "fillExtrusionPattern" : "fillExtrusion", g2);
              u2 && (t4.context.activeTexture.set(l2.TEXTURE0), a3.imageAtlasTexture.bind(l2.LINEAR, l2.CLAMP_TO_EDGE), g2.updatePaintBuffers(d2)), ea(g2, h2, p2, a3, i2);
              const x2 = t4.translatePosMatrix(c3.posMatrix, a3, i2.paint.get("fill-extrusion-translate"), i2.paint.get("fill-extrusion-translate-anchor")), y2 = i2.paint.get("fill-extrusion-vertical-gradient"), b2 = u2 ? we(x2, t4, y2, _2, c3, d2, a3) : be(x2, t4, y2, _2);
              v2.draw(n2, n2.gl.TRIANGLES, s2, o2, r2, ji.backCCW, b2, f2, i2.id, m2.layoutVertexBuffer, m2.indexBuffer, m2.segments, i2.paint, t4.transform.zoom, g2, t4.style.map.terrain && m2.centroidVertexBuffer);
            }
          }
          function sa(t4, e2, i2, a2, s2, o2, r2) {
            const n2 = t4.context, l2 = n2.gl, h2 = i2.fbo;
            if (!h2) return;
            const c2 = t4.useProgram("hillshade"), u2 = t4.style.map.terrain && t4.style.map.terrain.getTerrainData(e2);
            n2.activeTexture.set(l2.TEXTURE0), l2.bindTexture(l2.TEXTURE_2D, h2.colorAttachment.get()), c2.draw(n2, l2.TRIANGLES, s2, o2, r2, ji.disabled, ((t5, e3, i3, a3) => {
              const s3 = i3.paint.get("hillshade-shadow-color"), o3 = i3.paint.get("hillshade-highlight-color"), r3 = i3.paint.get("hillshade-accent-color");
              let n3 = i3.paint.get("hillshade-illumination-direction") * (Math.PI / 180);
              "viewport" === i3.paint.get("hillshade-illumination-anchor") && (n3 -= t5.transform.angle);
              const l3 = !t5.options.moving;
              return { u_matrix: a3 ? a3.posMatrix : t5.transform.calculatePosMatrix(e3.tileID.toUnwrapped(), l3), u_image: 0, u_latrange: Re(0, e3.tileID), u_light: [i3.paint.get("hillshade-exaggeration"), n3], u_shadow: s3, u_highlight: o3, u_accent: r3 };
            })(t4, i2, a2, u2 ? e2 : null), u2, a2.id, t4.rasterBoundsBuffer, t4.quadTriangleIndexBuffer, t4.rasterBoundsSegments);
          }
          function oa(t4, i2, a2, s2, o2, r2) {
            const n2 = t4.context, l2 = n2.gl, h2 = i2.dem;
            if (h2 && h2.data) {
              const c2 = h2.dim, u2 = h2.stride, d2 = h2.getPixels();
              if (n2.activeTexture.set(l2.TEXTURE1), n2.pixelStoreUnpackPremultiplyAlpha.set(false), i2.demTexture = i2.demTexture || t4.getTileTexture(u2), i2.demTexture) {
                const t5 = i2.demTexture;
                t5.update(d2, { premultiply: false }), t5.bind(l2.NEAREST, l2.CLAMP_TO_EDGE);
              } else i2.demTexture = new b(n2, d2, l2.RGBA, { premultiply: false }), i2.demTexture.bind(l2.NEAREST, l2.CLAMP_TO_EDGE);
              n2.activeTexture.set(l2.TEXTURE0);
              let _2 = i2.fbo;
              if (!_2) {
                const t5 = new b(n2, { width: c2, height: c2, data: null }, l2.RGBA);
                t5.bind(l2.LINEAR, l2.CLAMP_TO_EDGE), _2 = i2.fbo = n2.createFramebuffer(c2, c2, true, false), _2.colorAttachment.set(t5.texture);
              }
              n2.bindFramebuffer.set(_2.framebuffer), n2.viewport.set([0, 0, c2, c2]), t4.useProgram("hillshadePrepare").draw(n2, l2.TRIANGLES, s2, o2, r2, ji.disabled, ((t5, i3) => {
                const a3 = i3.stride, s3 = e.H();
                return e.aP(s3, 0, e.X, -e.X, 0, 0, 1), e.J(s3, s3, [0, -e.X, 0]), { u_matrix: s3, u_image: 1, u_dimension: [a3, a3], u_zoom: t5.overscaledZ, u_unpack: i3.getUnpackVector() };
              })(i2.tileID, h2), null, a2.id, t4.rasterBoundsBuffer, t4.quadTriangleIndexBuffer, t4.rasterBoundsSegments), i2.needsHillshadePrepare = false;
            }
          }
          function ra(t4, i2, a2, s2, r2, n2) {
            const l2 = s2.paint.get("raster-fade-duration");
            if (!n2 && l2 > 0) {
              const s3 = o.now(), n3 = (s3 - t4.timeAdded) / l2, h2 = i2 ? (s3 - i2.timeAdded) / l2 : -1, c2 = a2.getSource(), u2 = r2.coveringZoomLevel({ tileSize: c2.tileSize, roundZoom: c2.roundZoom }), d2 = !i2 || Math.abs(i2.tileID.overscaledZ - u2) > Math.abs(t4.tileID.overscaledZ - u2), _2 = d2 && t4.refreshedUponExpiration ? 1 : e.ac(d2 ? n3 : 1 - h2, 0, 1);
              return t4.refreshedUponExpiration && n3 >= 1 && (t4.refreshedUponExpiration = false), i2 ? { opacity: 1, mix: 1 - _2 } : { opacity: _2, mix: 0 };
            }
            return { opacity: 1, mix: 0 };
          }
          const na = new e.aM(1, 0, 0, 1), la = new e.aM(0, 1, 0, 1), ha = new e.aM(0, 0, 1, 1), ca = new e.aM(1, 0, 1, 1), ua = new e.aM(0, 1, 1, 1);
          function da(t4, e2, i2, a2) {
            pa(t4, 0, e2 + i2 / 2, t4.transform.width, i2, a2);
          }
          function _a(t4, e2, i2, a2) {
            pa(t4, e2 - i2 / 2, 0, i2, t4.transform.height, a2);
          }
          function pa(t4, e2, i2, a2, s2, o2) {
            const r2 = t4.context, n2 = r2.gl;
            n2.enable(n2.SCISSOR_TEST), n2.scissor(e2 * t4.pixelRatio, i2 * t4.pixelRatio, a2 * t4.pixelRatio, s2 * t4.pixelRatio), r2.clear({ color: o2 }), n2.disable(n2.SCISSOR_TEST);
          }
          function ma(t4, i2, a2) {
            const s2 = t4.context, o2 = s2.gl, r2 = a2.posMatrix, n2 = t4.useProgram("debug"), l2 = Oi.disabled, h2 = Ui.disabled, c2 = t4.colorModeForRenderPass(), u2 = "$debug", d2 = t4.style.map.terrain && t4.style.map.terrain.getTerrainData(a2);
            s2.activeTexture.set(o2.TEXTURE0);
            const _2 = i2.getTileByID(a2.key).latestRawTileData, p2 = Math.floor((_2 && _2.byteLength || 0) / 1024), m2 = i2.getTile(a2).tileSize, f2 = 512 / Math.min(m2, 512) * (a2.overscaledZ / t4.transform.zoom) * 0.5;
            let g2 = a2.canonical.toString();
            a2.overscaledZ !== a2.canonical.z && (g2 += ` => ${a2.overscaledZ}`), function(t5, e2) {
              t5.initDebugOverlayCanvas();
              const i3 = t5.debugOverlayCanvas, a3 = t5.context.gl, s3 = t5.debugOverlayCanvas.getContext("2d");
              s3.clearRect(0, 0, i3.width, i3.height), s3.shadowColor = "white", s3.shadowBlur = 2, s3.lineWidth = 1.5, s3.strokeStyle = "white", s3.textBaseline = "top", s3.font = "bold 36px Open Sans, sans-serif", s3.fillText(e2, 5, 5), s3.strokeText(e2, 5, 5), t5.debugOverlayTexture.update(i3), t5.debugOverlayTexture.bind(a3.LINEAR, a3.CLAMP_TO_EDGE);
            }(t4, `${g2} ${p2}kB`), n2.draw(s2, o2.TRIANGLES, l2, h2, Fi.alphaBlended, ji.disabled, ze(r2, e.aM.transparent, f2), null, u2, t4.debugBuffer, t4.quadTriangleIndexBuffer, t4.debugSegments), n2.draw(s2, o2.LINE_STRIP, l2, h2, c2, ji.disabled, ze(r2, e.aM.red), d2, u2, t4.debugBuffer, t4.tileBorderIndexBuffer, t4.debugSegments);
          }
          function fa(t4, e2, i2) {
            const a2 = t4.context, s2 = a2.gl, o2 = t4.colorModeForRenderPass(), r2 = new Oi(s2.LEQUAL, Oi.ReadWrite, t4.depthRangeFor3D), n2 = t4.useProgram("terrain"), l2 = e2.getTerrainMesh();
            a2.bindFramebuffer.set(null), a2.viewport.set([0, 0, t4.width, t4.height]);
            for (const h2 of i2) {
              const i3 = t4.renderToTexture.getTexture(h2), c2 = e2.getTerrainData(h2.tileID);
              a2.activeTexture.set(s2.TEXTURE0), s2.bindTexture(s2.TEXTURE_2D, i3.texture);
              const u2 = t4.transform.calculatePosMatrix(h2.tileID.toUnwrapped()), d2 = e2.getMeshFrameDelta(t4.transform.zoom), _2 = t4.transform.calculateFogMatrix(h2.tileID.toUnwrapped()), p2 = ge(u2, d2, _2, t4.style.sky, t4.transform.pitch);
              n2.draw(a2, s2.TRIANGLES, r2, Ui.disabled, o2, ji.backCCW, p2, c2, "terrain", l2.vertexBuffer, l2.indexBuffer, l2.segments);
            }
          }
          class ga {
            constructor(t4, e2, i2) {
              this.vertexBuffer = t4, this.indexBuffer = e2, this.segments = i2;
            }
            destroy() {
              this.vertexBuffer.destroy(), this.indexBuffer.destroy(), this.segments.destroy(), this.vertexBuffer = null, this.indexBuffer = null, this.segments = null;
            }
          }
          class va {
            constructor(t4, i2) {
              this.context = new Bi(t4), this.transform = i2, this._tileTextures = {}, this.terrainFacilitator = { dirty: true, matrix: e.an(new Float64Array(16)), renderTime: 0 }, this.setup(), this.numSublayers = ut.maxUnderzooming + ut.maxOverzooming + 1, this.depthEpsilon = 1 / Math.pow(2, 16), this.crossTileSymbolIndex = new he();
            }
            resize(t4, e2, i2) {
              if (this.width = Math.floor(t4 * i2), this.height = Math.floor(e2 * i2), this.pixelRatio = i2, this.context.viewport.set([0, 0, this.width, this.height]), this.style) for (const t5 of this.style._order) this.style._layers[t5].resize();
            }
            setup() {
              const t4 = this.context, i2 = new e.aX();
              i2.emplaceBack(0, 0), i2.emplaceBack(e.X, 0), i2.emplaceBack(0, e.X), i2.emplaceBack(e.X, e.X), this.tileExtentBuffer = t4.createVertexBuffer(i2, _e.members), this.tileExtentSegments = e.a0.simpleSegment(0, 0, 4, 2);
              const a2 = new e.aX();
              a2.emplaceBack(0, 0), a2.emplaceBack(e.X, 0), a2.emplaceBack(0, e.X), a2.emplaceBack(e.X, e.X), this.debugBuffer = t4.createVertexBuffer(a2, _e.members), this.debugSegments = e.a0.simpleSegment(0, 0, 4, 5);
              const s2 = new e.$();
              s2.emplaceBack(0, 0, 0, 0), s2.emplaceBack(e.X, 0, e.X, 0), s2.emplaceBack(0, e.X, 0, e.X), s2.emplaceBack(e.X, e.X, e.X, e.X), this.rasterBoundsBuffer = t4.createVertexBuffer(s2, Y.members), this.rasterBoundsSegments = e.a0.simpleSegment(0, 0, 4, 2);
              const o2 = new e.aX();
              o2.emplaceBack(0, 0), o2.emplaceBack(1, 0), o2.emplaceBack(0, 1), o2.emplaceBack(1, 1), this.viewportBuffer = t4.createVertexBuffer(o2, _e.members), this.viewportSegments = e.a0.simpleSegment(0, 0, 4, 2);
              const r2 = new e.aZ();
              r2.emplaceBack(0), r2.emplaceBack(1), r2.emplaceBack(3), r2.emplaceBack(2), r2.emplaceBack(0), this.tileBorderIndexBuffer = t4.createIndexBuffer(r2);
              const n2 = new e.aY();
              n2.emplaceBack(0, 1, 2), n2.emplaceBack(2, 1, 3), this.quadTriangleIndexBuffer = t4.createIndexBuffer(n2);
              const l2 = this.context.gl;
              this.stencilClearMode = new Ui({ func: l2.ALWAYS, mask: 0 }, 0, 255, l2.ZERO, l2.ZERO, l2.ZERO);
            }
            clearStencil() {
              const t4 = this.context, i2 = t4.gl;
              this.nextStencilID = 1, this.currentStencilSource = void 0;
              const a2 = e.H();
              e.aP(a2, 0, this.width, this.height, 0, 0, 1), e.K(a2, a2, [i2.drawingBufferWidth, i2.drawingBufferHeight, 0]), this.useProgram("clippingMask").draw(t4, i2.TRIANGLES, Oi.disabled, this.stencilClearMode, Fi.disabled, ji.disabled, De(a2), null, "$clipping", this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments);
            }
            _renderTileClippingMasks(t4, e2) {
              if (this.currentStencilSource === t4.source || !t4.isTileClipped() || !e2 || !e2.length) return;
              this.currentStencilSource = t4.source;
              const i2 = this.context, a2 = i2.gl;
              this.nextStencilID + e2.length > 256 && this.clearStencil(), i2.setColorMode(Fi.disabled), i2.setDepthMode(Oi.disabled);
              const s2 = this.useProgram("clippingMask");
              this._tileClippingMaskIDs = {};
              for (const t5 of e2) {
                const e3 = this._tileClippingMaskIDs[t5.key] = this.nextStencilID++, o2 = this.style.map.terrain && this.style.map.terrain.getTerrainData(t5);
                s2.draw(i2, a2.TRIANGLES, Oi.disabled, new Ui({ func: a2.ALWAYS, mask: 0 }, e3, 255, a2.KEEP, a2.KEEP, a2.REPLACE), Fi.disabled, ji.disabled, De(t5.posMatrix), o2, "$clipping", this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments);
              }
            }
            stencilModeFor3D() {
              this.currentStencilSource = void 0, this.nextStencilID + 1 > 256 && this.clearStencil();
              const t4 = this.nextStencilID++, e2 = this.context.gl;
              return new Ui({ func: e2.NOTEQUAL, mask: 255 }, t4, 255, e2.KEEP, e2.KEEP, e2.REPLACE);
            }
            stencilModeForClipping(t4) {
              const e2 = this.context.gl;
              return new Ui({ func: e2.EQUAL, mask: 255 }, this._tileClippingMaskIDs[t4.key], 0, e2.KEEP, e2.KEEP, e2.REPLACE);
            }
            stencilConfigForOverlap(t4) {
              const e2 = this.context.gl, i2 = t4.sort((t5, e3) => e3.overscaledZ - t5.overscaledZ), a2 = i2[i2.length - 1].overscaledZ, s2 = i2[0].overscaledZ - a2 + 1;
              if (s2 > 1) {
                this.currentStencilSource = void 0, this.nextStencilID + s2 > 256 && this.clearStencil();
                const t5 = {};
                for (let i3 = 0; i3 < s2; i3++) t5[i3 + a2] = new Ui({ func: e2.GEQUAL, mask: 255 }, i3 + this.nextStencilID, 255, e2.KEEP, e2.KEEP, e2.REPLACE);
                return this.nextStencilID += s2, [t5, i2];
              }
              return [{ [a2]: Ui.disabled }, i2];
            }
            colorModeForRenderPass() {
              const t4 = this.context.gl;
              if (this._showOverdrawInspector) {
                const i2 = 1 / 8;
                return new Fi([t4.CONSTANT_COLOR, t4.ONE], new e.aM(i2, i2, i2, 0), [true, true, true, true]);
              }
              return "opaque" === this.renderPass ? Fi.unblended : Fi.alphaBlended;
            }
            depthModeForSublayer(t4, e2, i2) {
              if (!this.opaquePassEnabledForLayer()) return Oi.disabled;
              const a2 = 1 - ((1 + this.currentLayer) * this.numSublayers + t4) * this.depthEpsilon;
              return new Oi(i2 || this.context.gl.LEQUAL, e2, [a2, a2]);
            }
            opaquePassEnabledForLayer() {
              return this.currentLayer < this.opaquePassCutoff;
            }
            render(t4, i2) {
              this.style = t4, this.options = i2, this.lineAtlas = t4.lineAtlas, this.imageManager = t4.imageManager, this.glyphManager = t4.glyphManager, this.symbolFadeChange = t4.placement.symbolFadeChange(o.now()), this.imageManager.beginFrame();
              const a2 = this.style._order, s2 = this.style.sourceCaches, r2 = {}, n2 = {}, l2 = {};
              for (const t5 in s2) {
                const e2 = s2[t5];
                e2.used && e2.prepare(this.context), r2[t5] = e2.getVisibleCoordinates(), n2[t5] = r2[t5].slice().reverse(), l2[t5] = e2.getVisibleCoordinates(true).reverse();
              }
              this.opaquePassCutoff = 1 / 0;
              for (let t5 = 0; t5 < a2.length; t5++) if (this.style._layers[a2[t5]].is3D()) {
                this.opaquePassCutoff = t5;
                break;
              }
              this.maybeDrawDepthAndCoords(false), this.renderToTexture && (this.renderToTexture.prepareForRender(this.style, this.transform.zoom), this.opaquePassCutoff = 0), this.renderPass = "offscreen";
              for (const t5 of a2) {
                const e2 = this.style._layers[t5];
                if (!e2.hasOffscreenPass() || e2.isHidden(this.transform.zoom)) continue;
                const i3 = n2[e2.source];
                ("custom" === e2.type || i3.length) && this.renderLayer(this, s2[e2.source], e2, i3);
              }
              if (this.context.bindFramebuffer.set(null), this.context.clear({ color: i2.showOverdrawInspector ? e.aM.black : e.aM.transparent, depth: 1 }), this.clearStencil(), this.style.sky && function(t5, i3) {
                const a3 = t5.context, s3 = a3.gl, o2 = ((t6, e2, i4) => ({ u_sky_color: t6.properties.get("sky-color"), u_horizon_color: t6.properties.get("horizon-color"), u_horizon: (e2.height / 2 + e2.getHorizon()) * i4, u_sky_horizon_blend: t6.properties.get("sky-horizon-blend") * e2.height / 2 * i4 }))(i3, t5.style.map.transform, t5.pixelRatio), r3 = new Oi(s3.LEQUAL, Oi.ReadWrite, [0, 1]), n3 = Ui.disabled, l3 = t5.colorModeForRenderPass(), h2 = t5.useProgram("sky");
                if (!i3.mesh) {
                  const t6 = new e.aX();
                  t6.emplaceBack(-1, -1), t6.emplaceBack(1, -1), t6.emplaceBack(1, 1), t6.emplaceBack(-1, 1);
                  const s4 = new e.aY();
                  s4.emplaceBack(0, 1, 2), s4.emplaceBack(0, 2, 3), i3.mesh = new ga(a3.createVertexBuffer(t6, _e.members), a3.createIndexBuffer(s4), e.a0.simpleSegment(0, 0, t6.length, s4.length));
                }
                h2.draw(a3, s3.TRIANGLES, r3, n3, l3, ji.disabled, o2, void 0, "sky", i3.mesh.vertexBuffer, i3.mesh.indexBuffer, i3.mesh.segments);
              }(this, this.style.sky), this._showOverdrawInspector = i2.showOverdrawInspector, this.depthRangeFor3D = [0, 1 - (t4._order.length + 2) * this.numSublayers * this.depthEpsilon], !this.renderToTexture) for (this.renderPass = "opaque", this.currentLayer = a2.length - 1; this.currentLayer >= 0; this.currentLayer--) {
                const t5 = this.style._layers[a2[this.currentLayer]], e2 = s2[t5.source], i3 = r2[t5.source];
                this._renderTileClippingMasks(t5, i3), this.renderLayer(this, e2, t5, i3);
              }
              for (this.renderPass = "translucent", this.currentLayer = 0; this.currentLayer < a2.length; this.currentLayer++) {
                const t5 = this.style._layers[a2[this.currentLayer]], e2 = s2[t5.source];
                if (this.renderToTexture && this.renderToTexture.renderLayer(t5)) continue;
                const i3 = ("symbol" === t5.type ? l2 : n2)[t5.source];
                this._renderTileClippingMasks(t5, r2[t5.source]), this.renderLayer(this, e2, t5, i3);
              }
              if (this.options.showTileBoundaries) {
                const t5 = function(t6, e2) {
                  let i3 = null;
                  const a3 = Object.values(t6._layers).flatMap((i4) => i4.source && !i4.isHidden(e2) ? [t6.sourceCaches[i4.source]] : []), s3 = a3.filter((t7) => "vector" === t7.getSource().type), o2 = a3.filter((t7) => "vector" !== t7.getSource().type), r3 = (t7) => {
                    (!i3 || i3.getSource().maxzoom < t7.getSource().maxzoom) && (i3 = t7);
                  };
                  return s3.forEach((t7) => r3(t7)), i3 || o2.forEach((t7) => r3(t7)), i3;
                }(this.style, this.transform.zoom);
                t5 && function(t6, e2, i3) {
                  for (let a3 = 0; a3 < i3.length; a3++) ma(t6, e2, i3[a3]);
                }(this, t5, t5.getVisibleCoordinates());
              }
              this.options.showPadding && function(t5) {
                const e2 = t5.transform.padding;
                da(t5, t5.transform.height - (e2.top || 0), 3, na), da(t5, e2.bottom || 0, 3, la), _a(t5, e2.left || 0, 3, ha), _a(t5, t5.transform.width - (e2.right || 0), 3, ca);
                const i3 = t5.transform.centerPoint;
                !function(t6, e3, i4, a3) {
                  pa(t6, e3 - 1, i4 - 10, 2, 20, a3), pa(t6, e3 - 10, i4 - 1, 20, 2, a3);
                }(t5, i3.x, t5.transform.height - i3.y, ua);
              }(this), this.context.setDefault();
            }
            maybeDrawDepthAndCoords(t4) {
              if (!this.style || !this.style.map || !this.style.map.terrain) return;
              const i2 = this.terrainFacilitator.matrix, a2 = this.transform.modelViewProjectionMatrix;
              let s2 = this.terrainFacilitator.dirty;
              s2 || (s2 = t4 ? !e.a_(i2, a2) : !e.a$(i2, a2)), s2 || (s2 = this.style.map.terrain.sourceCache.tilesAfterTime(this.terrainFacilitator.renderTime).length > 0), s2 && (e.b0(i2, a2), this.terrainFacilitator.renderTime = Date.now(), this.terrainFacilitator.dirty = false, function(t5, i3) {
                const a3 = t5.context, s3 = a3.gl, o2 = Fi.unblended, r2 = new Oi(s3.LEQUAL, Oi.ReadWrite, [0, 1]), n2 = i3.getTerrainMesh(), l2 = i3.sourceCache.getRenderableTiles(), h2 = t5.useProgram("terrainDepth");
                a3.bindFramebuffer.set(i3.getFramebuffer("depth").framebuffer), a3.viewport.set([0, 0, t5.width / devicePixelRatio, t5.height / devicePixelRatio]), a3.clear({ color: e.aM.transparent, depth: 1 });
                for (const e2 of l2) {
                  const l3 = i3.getTerrainData(e2.tileID), c2 = { u_matrix: t5.transform.calculatePosMatrix(e2.tileID.toUnwrapped()), u_ele_delta: i3.getMeshFrameDelta(t5.transform.zoom) };
                  h2.draw(a3, s3.TRIANGLES, r2, Ui.disabled, o2, ji.backCCW, c2, l3, "terrain", n2.vertexBuffer, n2.indexBuffer, n2.segments);
                }
                a3.bindFramebuffer.set(null), a3.viewport.set([0, 0, t5.width, t5.height]);
              }(this, this.style.map.terrain), function(t5, i3) {
                const a3 = t5.context, s3 = a3.gl, o2 = Fi.unblended, r2 = new Oi(s3.LEQUAL, Oi.ReadWrite, [0, 1]), n2 = i3.getTerrainMesh(), l2 = i3.getCoordsTexture(), h2 = i3.sourceCache.getRenderableTiles(), c2 = t5.useProgram("terrainCoords");
                a3.bindFramebuffer.set(i3.getFramebuffer("coords").framebuffer), a3.viewport.set([0, 0, t5.width / devicePixelRatio, t5.height / devicePixelRatio]), a3.clear({ color: e.aM.transparent, depth: 1 }), i3.coordsIndex = [];
                for (const e2 of h2) {
                  const h3 = i3.getTerrainData(e2.tileID);
                  a3.activeTexture.set(s3.TEXTURE0), s3.bindTexture(s3.TEXTURE_2D, l2.texture);
                  const u2 = { u_matrix: t5.transform.calculatePosMatrix(e2.tileID.toUnwrapped()), u_terrain_coords_id: (255 - i3.coordsIndex.length) / 255, u_texture: 0, u_ele_delta: i3.getMeshFrameDelta(t5.transform.zoom) };
                  c2.draw(a3, s3.TRIANGLES, r2, Ui.disabled, o2, ji.backCCW, u2, h3, "terrain", n2.vertexBuffer, n2.indexBuffer, n2.segments), i3.coordsIndex.push(e2.tileID.key);
                }
                a3.bindFramebuffer.set(null), a3.viewport.set([0, 0, t5.width, t5.height]);
              }(this, this.style.map.terrain));
            }
            renderLayer(t4, i2, a2, s2) {
              if (!a2.isHidden(this.transform.zoom) && ("background" === a2.type || "custom" === a2.type || (s2 || []).length)) switch (this.id = a2.id, a2.type) {
                case "symbol":
                  !function(t5, i3, a3, s3, o2) {
                    if ("translucent" !== t5.renderPass) return;
                    const r2 = Ui.disabled, n2 = t5.colorModeForRenderPass();
                    (a3._unevaluatedLayout.hasValue("text-variable-anchor") || a3._unevaluatedLayout.hasValue("text-variable-anchor-offset")) && function(t6, i4, a4, s4, o3, r3, n3, l2, h2) {
                      const c2 = i4.transform, u2 = ie(), d2 = "map" === o3, _2 = "map" === r3;
                      for (const o4 of t6) {
                        const t7 = s4.getTile(o4), r4 = t7.getBucket(a4);
                        if (!r4 || !r4.text || !r4.text.segments.get().length) continue;
                        const p2 = e.ag(r4.textSizeData, c2.zoom), m2 = Bt(t7, 1, i4.transform.zoom), f2 = gt(o4.posMatrix, _2, d2, i4.transform, m2), g2 = "none" !== a4.layout.get("icon-text-fit") && r4.hasIconData();
                        if (p2) {
                          const e2 = Math.pow(2, c2.zoom - t7.tileID.overscaledZ), a5 = i4.style.map.terrain ? (t8, e3) => i4.style.map.terrain.getElevation(o4, t8, e3) : null, s5 = u2.translatePosition(c2, t7, n3, l2);
                          Wi(r4, d2, _2, h2, c2, f2, o4.posMatrix, e2, p2, g2, u2, s5, o4.toUnwrapped(), a5);
                        }
                      }
                    }(s3, t5, a3, i3, a3.layout.get("text-rotation-alignment"), a3.layout.get("text-pitch-alignment"), a3.paint.get("text-translate"), a3.paint.get("text-translate-anchor"), o2), 0 !== a3.paint.get("icon-opacity").constantOr(1) && Xi(t5, i3, a3, s3, false, a3.paint.get("icon-translate"), a3.paint.get("icon-translate-anchor"), a3.layout.get("icon-rotation-alignment"), a3.layout.get("icon-pitch-alignment"), a3.layout.get("icon-keep-upright"), r2, n2), 0 !== a3.paint.get("text-opacity").constantOr(1) && Xi(t5, i3, a3, s3, true, a3.paint.get("text-translate"), a3.paint.get("text-translate-anchor"), a3.layout.get("text-rotation-alignment"), a3.layout.get("text-pitch-alignment"), a3.layout.get("text-keep-upright"), r2, n2), i3.map.showCollisionBoxes && (qi(t5, i3, a3, s3, true), qi(t5, i3, a3, s3, false));
                  }(t4, i2, a2, s2, this.style.placement.variableOffsets);
                  break;
                case "circle":
                  !function(t5, i3, a3, s3) {
                    if ("translucent" !== t5.renderPass) return;
                    const o2 = a3.paint.get("circle-opacity"), r2 = a3.paint.get("circle-stroke-width"), n2 = a3.paint.get("circle-stroke-opacity"), l2 = !a3.layout.get("circle-sort-key").isConstant();
                    if (0 === o2.constantOr(1) && (0 === r2.constantOr(1) || 0 === n2.constantOr(1))) return;
                    const h2 = t5.context, c2 = h2.gl, u2 = t5.depthModeForSublayer(0, Oi.ReadOnly), d2 = Ui.disabled, _2 = t5.colorModeForRenderPass(), p2 = [];
                    for (let o3 = 0; o3 < s3.length; o3++) {
                      const r3 = s3[o3], n3 = i3.getTile(r3), h3 = n3.getBucket(a3);
                      if (!h3) continue;
                      const c3 = h3.programConfigurations.get(a3.id), u3 = t5.useProgram("circle", c3), d3 = h3.layoutVertexBuffer, _3 = h3.indexBuffer, m2 = t5.style.map.terrain && t5.style.map.terrain.getTerrainData(r3), f2 = { programConfiguration: c3, program: u3, layoutVertexBuffer: d3, indexBuffer: _3, uniformValues: Ce(t5, r3, n3, a3), terrainData: m2 };
                      if (l2) {
                        const t6 = h3.segments.get();
                        for (const i4 of t6) p2.push({ segments: new e.a0([i4]), sortKey: i4.sortKey, state: f2 });
                      } else p2.push({ segments: h3.segments, sortKey: 0, state: f2 });
                    }
                    l2 && p2.sort((t6, e2) => t6.sortKey - e2.sortKey);
                    for (const e2 of p2) {
                      const { programConfiguration: i4, program: s4, layoutVertexBuffer: o3, indexBuffer: r3, uniformValues: n3, terrainData: l3 } = e2.state;
                      s4.draw(h2, c2.TRIANGLES, u2, d2, _2, ji.disabled, n3, l3, a3.id, o3, r3, e2.segments, a3.paint, t5.transform.zoom, i4);
                    }
                  }(t4, i2, a2, s2);
                  break;
                case "heatmap":
                  !function(t5, i3, a3, s3) {
                    if (0 === a3.paint.get("heatmap-opacity")) return;
                    const o2 = t5.context;
                    if (t5.style.map.terrain) {
                      for (const e2 of s3) {
                        const s4 = i3.getTile(e2);
                        i3.hasRenderableParent(e2) || ("offscreen" === t5.renderPass ? Ji(t5, s4, a3, e2) : "translucent" === t5.renderPass && Yi(t5, a3, e2));
                      }
                      o2.viewport.set([0, 0, t5.width, t5.height]);
                    } else "offscreen" === t5.renderPass ? function(t6, i4, a4, s4) {
                      const o3 = t6.context, r2 = o3.gl, n2 = Ui.disabled, l2 = new Fi([r2.ONE, r2.ONE], e.aM.transparent, [true, true, true, true]);
                      (function(t7, i5, a5) {
                        const s5 = t7.gl;
                        t7.activeTexture.set(s5.TEXTURE1), t7.viewport.set([0, 0, i5.width / 4, i5.height / 4]);
                        let o4 = a5.heatmapFbos.get(e.aU);
                        o4 ? (s5.bindTexture(s5.TEXTURE_2D, o4.colorAttachment.get()), t7.bindFramebuffer.set(o4.framebuffer)) : (o4 = Qi(t7, i5.width / 4, i5.height / 4), a5.heatmapFbos.set(e.aU, o4));
                      })(o3, t6, a4), o3.clear({ color: e.aM.transparent });
                      for (let e2 = 0; e2 < s4.length; e2++) {
                        const h2 = s4[e2];
                        if (i4.hasRenderableParent(h2)) continue;
                        const c2 = i4.getTile(h2), u2 = c2.getBucket(a4);
                        if (!u2) continue;
                        const d2 = u2.programConfigurations.get(a4.id), _2 = t6.useProgram("heatmap", d2), { zoom: p2 } = t6.transform;
                        _2.draw(o3, r2.TRIANGLES, Oi.disabled, n2, l2, ji.disabled, Me(h2.posMatrix, c2, p2, a4.paint.get("heatmap-intensity")), null, a4.id, u2.layoutVertexBuffer, u2.indexBuffer, u2.segments, a4.paint, t6.transform.zoom, d2);
                      }
                      o3.viewport.set([0, 0, t6.width, t6.height]);
                    }(t5, i3, a3, s3) : "translucent" === t5.renderPass && function(t6, i4) {
                      const a4 = t6.context, s4 = a4.gl;
                      a4.setColorMode(t6.colorModeForRenderPass());
                      const o3 = i4.heatmapFbos.get(e.aU);
                      o3 && (a4.activeTexture.set(s4.TEXTURE0), s4.bindTexture(s4.TEXTURE_2D, o3.colorAttachment.get()), a4.activeTexture.set(s4.TEXTURE1), ta(a4, i4).bind(s4.LINEAR, s4.CLAMP_TO_EDGE), t6.useProgram("heatmapTexture").draw(a4, s4.TRIANGLES, Oi.disabled, Ui.disabled, t6.colorModeForRenderPass(), ji.disabled, Ae(t6, i4, 0, 1), null, i4.id, t6.viewportBuffer, t6.quadTriangleIndexBuffer, t6.viewportSegments, i4.paint, t6.transform.zoom));
                    }(t5, a3);
                  }(t4, i2, a2, s2);
                  break;
                case "line":
                  !function(t5, i3, a3, s3) {
                    if ("translucent" !== t5.renderPass) return;
                    const o2 = a3.paint.get("line-opacity"), r2 = a3.paint.get("line-width");
                    if (0 === o2.constantOr(1) || 0 === r2.constantOr(1)) return;
                    const n2 = t5.depthModeForSublayer(0, Oi.ReadOnly), l2 = t5.colorModeForRenderPass(), h2 = a3.paint.get("line-dasharray"), c2 = a3.paint.get("line-pattern"), u2 = c2.constantOr(1), d2 = a3.paint.get("line-gradient"), _2 = a3.getCrossfadeParameters(), p2 = u2 ? "linePattern" : h2 ? "lineSDF" : d2 ? "lineGradient" : "line", m2 = t5.context, f2 = m2.gl;
                    let g2 = true;
                    for (const o3 of s3) {
                      const s4 = i3.getTile(o3);
                      if (u2 && !s4.patternsLoaded()) continue;
                      const r3 = s4.getBucket(a3);
                      if (!r3) continue;
                      const v2 = r3.programConfigurations.get(a3.id), x2 = t5.context.program.get(), y2 = t5.useProgram(p2, v2), w2 = g2 || y2.program !== x2, T2 = t5.style.map.terrain && t5.style.map.terrain.getTerrainData(o3), I2 = c2.constantOr(null);
                      if (I2 && s4.imageAtlas) {
                        const t6 = s4.imageAtlas, e2 = t6.patternPositions[I2.to.toString()], i4 = t6.patternPositions[I2.from.toString()];
                        e2 && i4 && v2.setConstantPatternPositions(e2, i4);
                      }
                      const E3 = T2 ? o3 : null, P2 = u2 ? Fe(t5, s4, a3, _2, E3) : h2 ? Be(t5, s4, a3, h2, _2, E3) : d2 ? Le(t5, s4, a3, r3.lineClipsArray.length, E3) : ke(t5, s4, a3, E3);
                      if (u2) m2.activeTexture.set(f2.TEXTURE0), s4.imageAtlasTexture.bind(f2.LINEAR, f2.CLAMP_TO_EDGE), v2.updatePaintBuffers(_2);
                      else if (h2 && (w2 || t5.lineAtlas.dirty)) m2.activeTexture.set(f2.TEXTURE0), t5.lineAtlas.bind(m2);
                      else if (d2) {
                        const s5 = r3.gradients[a3.id];
                        let n3 = s5.texture;
                        if (a3.gradientVersion !== s5.version) {
                          let l3 = 256;
                          if (a3.stepInterpolant) {
                            const a4 = i3.getSource().maxzoom, s6 = o3.canonical.z === a4 ? Math.ceil(1 << t5.transform.maxZoom - o3.canonical.z) : 1;
                            l3 = e.ac(e.aV(r3.maxLineLength / e.X * 1024 * s6), 256, m2.maxTextureSize);
                          }
                          s5.gradient = e.aW({ expression: a3.gradientExpression(), evaluationKey: "lineProgress", resolution: l3, image: s5.gradient || void 0, clips: r3.lineClipsArray }), s5.texture ? s5.texture.update(s5.gradient) : s5.texture = new b(m2, s5.gradient, f2.RGBA), s5.version = a3.gradientVersion, n3 = s5.texture;
                        }
                        m2.activeTexture.set(f2.TEXTURE0), n3.bind(a3.stepInterpolant ? f2.NEAREST : f2.LINEAR, f2.CLAMP_TO_EDGE);
                      }
                      y2.draw(m2, f2.TRIANGLES, n2, t5.stencilModeForClipping(o3), l2, ji.disabled, P2, T2, a3.id, r3.layoutVertexBuffer, r3.indexBuffer, r3.segments, a3.paint, t5.transform.zoom, v2, r3.layoutVertexBuffer2), g2 = false;
                    }
                  }(t4, i2, a2, s2);
                  break;
                case "fill":
                  !function(t5, i3, a3, s3) {
                    const o2 = a3.paint.get("fill-color"), r2 = a3.paint.get("fill-opacity");
                    if (0 === r2.constantOr(1)) return;
                    const n2 = t5.colorModeForRenderPass(), l2 = a3.paint.get("fill-pattern"), h2 = t5.opaquePassEnabledForLayer() && !l2.constantOr(1) && 1 === o2.constantOr(e.aM.transparent).a && 1 === r2.constantOr(0) ? "opaque" : "translucent";
                    if (t5.renderPass === h2) {
                      const e2 = t5.depthModeForSublayer(1, "opaque" === t5.renderPass ? Oi.ReadWrite : Oi.ReadOnly);
                      ia(t5, i3, a3, s3, e2, n2, false);
                    }
                    if ("translucent" === t5.renderPass && a3.paint.get("fill-antialias")) {
                      const e2 = t5.depthModeForSublayer(a3.getPaintProperty("fill-outline-color") ? 2 : 0, Oi.ReadOnly);
                      ia(t5, i3, a3, s3, e2, n2, true);
                    }
                  }(t4, i2, a2, s2);
                  break;
                case "fill-extrusion":
                  !function(t5, e2, i3, a3) {
                    const s3 = i3.paint.get("fill-extrusion-opacity");
                    if (0 !== s3 && "translucent" === t5.renderPass) {
                      const o2 = new Oi(t5.context.gl.LEQUAL, Oi.ReadWrite, t5.depthRangeFor3D);
                      if (1 !== s3 || i3.paint.get("fill-extrusion-pattern").constantOr(1)) aa(t5, e2, i3, a3, o2, Ui.disabled, Fi.disabled), aa(t5, e2, i3, a3, o2, t5.stencilModeFor3D(), t5.colorModeForRenderPass());
                      else {
                        const s4 = t5.colorModeForRenderPass();
                        aa(t5, e2, i3, a3, o2, Ui.disabled, s4);
                      }
                    }
                  }(t4, i2, a2, s2);
                  break;
                case "hillshade":
                  !function(t5, e2, i3, a3) {
                    if ("offscreen" !== t5.renderPass && "translucent" !== t5.renderPass) return;
                    const s3 = t5.context, o2 = t5.depthModeForSublayer(0, Oi.ReadOnly), r2 = t5.colorModeForRenderPass(), [n2, l2] = "translucent" === t5.renderPass ? t5.stencilConfigForOverlap(a3) : [{}, a3];
                    for (const a4 of l2) {
                      const s4 = e2.getTile(a4);
                      void 0 !== s4.needsHillshadePrepare && s4.needsHillshadePrepare && "offscreen" === t5.renderPass ? oa(t5, s4, i3, o2, Ui.disabled, r2) : "translucent" === t5.renderPass && sa(t5, a4, s4, i3, o2, n2[a4.overscaledZ], r2);
                    }
                    s3.viewport.set([0, 0, t5.width, t5.height]);
                  }(t4, i2, a2, s2);
                  break;
                case "raster":
                  !function(t5, e2, i3, a3) {
                    if ("translucent" !== t5.renderPass) return;
                    if (0 === i3.paint.get("raster-opacity")) return;
                    if (!a3.length) return;
                    const s3 = t5.context, o2 = s3.gl, r2 = e2.getSource(), n2 = t5.useProgram("raster"), l2 = t5.colorModeForRenderPass(), [h2, c2] = r2 instanceof Q ? [{}, a3] : t5.stencilConfigForOverlap(a3), u2 = c2[c2.length - 1].overscaledZ, d2 = !t5.options.moving;
                    for (const a4 of c2) {
                      const c3 = t5.depthModeForSublayer(a4.overscaledZ - u2, 1 === i3.paint.get("raster-opacity") ? Oi.ReadWrite : Oi.ReadOnly, o2.LESS), _2 = e2.getTile(a4);
                      _2.registerFadeDuration(i3.paint.get("raster-fade-duration"));
                      const p2 = e2.findLoadedParent(a4, 0), m2 = e2.findLoadedSibling(a4), f2 = ra(_2, p2 || m2 || null, e2, i3, t5.transform, t5.style.map.terrain);
                      let g2, v2;
                      const x2 = "nearest" === i3.paint.get("raster-resampling") ? o2.NEAREST : o2.LINEAR;
                      s3.activeTexture.set(o2.TEXTURE0), _2.texture.bind(x2, o2.CLAMP_TO_EDGE, o2.LINEAR_MIPMAP_NEAREST), s3.activeTexture.set(o2.TEXTURE1), p2 ? (p2.texture.bind(x2, o2.CLAMP_TO_EDGE, o2.LINEAR_MIPMAP_NEAREST), g2 = Math.pow(2, p2.tileID.overscaledZ - _2.tileID.overscaledZ), v2 = [_2.tileID.canonical.x * g2 % 1, _2.tileID.canonical.y * g2 % 1]) : _2.texture.bind(x2, o2.CLAMP_TO_EDGE, o2.LINEAR_MIPMAP_NEAREST), _2.texture.useMipmap && s3.extTextureFilterAnisotropic && t5.transform.pitch > 20 && o2.texParameterf(o2.TEXTURE_2D, s3.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, s3.extTextureFilterAnisotropicMax);
                      const y2 = t5.style.map.terrain && t5.style.map.terrain.getTerrainData(a4), b2 = y2 ? a4 : null, w2 = b2 ? b2.posMatrix : t5.transform.calculatePosMatrix(a4.toUnwrapped(), d2), T2 = Ue(w2, v2 || [0, 0], g2 || 1, f2, i3);
                      r2 instanceof Q ? n2.draw(s3, o2.TRIANGLES, c3, Ui.disabled, l2, ji.disabled, T2, y2, i3.id, r2.boundsBuffer, t5.quadTriangleIndexBuffer, r2.boundsSegments) : n2.draw(s3, o2.TRIANGLES, c3, h2[a4.overscaledZ], l2, ji.disabled, T2, y2, i3.id, t5.rasterBoundsBuffer, t5.quadTriangleIndexBuffer, t5.rasterBoundsSegments);
                    }
                  }(t4, i2, a2, s2);
                  break;
                case "background":
                  !function(t5, e2, i3, a3) {
                    const s3 = i3.paint.get("background-color"), o2 = i3.paint.get("background-opacity");
                    if (0 === o2) return;
                    const r2 = t5.context, n2 = r2.gl, l2 = t5.transform, h2 = l2.tileSize, c2 = i3.paint.get("background-pattern");
                    if (t5.isPatternMissing(c2)) return;
                    const u2 = !c2 && 1 === s3.a && 1 === o2 && t5.opaquePassEnabledForLayer() ? "opaque" : "translucent";
                    if (t5.renderPass !== u2) return;
                    const d2 = Ui.disabled, _2 = t5.depthModeForSublayer(0, "opaque" === u2 ? Oi.ReadWrite : Oi.ReadOnly), p2 = t5.colorModeForRenderPass(), m2 = t5.useProgram(c2 ? "backgroundPattern" : "background"), f2 = a3 || l2.coveringTiles({ tileSize: h2, terrain: t5.style.map.terrain });
                    c2 && (r2.activeTexture.set(n2.TEXTURE0), t5.imageManager.bind(t5.context));
                    const g2 = i3.getCrossfadeParameters();
                    for (const e3 of f2) {
                      const l3 = a3 ? e3.posMatrix : t5.transform.calculatePosMatrix(e3.toUnwrapped()), u3 = c2 ? He(l3, o2, t5, c2, { tileID: e3, tileSize: h2 }, g2) : Ge(l3, o2, s3), f3 = t5.style.map.terrain && t5.style.map.terrain.getTerrainData(e3);
                      m2.draw(r2, n2.TRIANGLES, _2, d2, p2, ji.disabled, u3, f3, i3.id, t5.tileExtentBuffer, t5.quadTriangleIndexBuffer, t5.tileExtentSegments);
                    }
                  }(t4, 0, a2, s2);
                  break;
                case "custom":
                  !function(t5, e2, i3) {
                    const a3 = t5.context, s3 = i3.implementation;
                    if ("offscreen" === t5.renderPass) {
                      const e3 = s3.prerender;
                      e3 && (t5.setCustomLayerDefaults(), a3.setColorMode(t5.colorModeForRenderPass()), e3.call(s3, a3.gl, t5.transform.customLayerMatrix()), a3.setDirty(), t5.setBaseState());
                    } else if ("translucent" === t5.renderPass) {
                      t5.setCustomLayerDefaults(), a3.setColorMode(t5.colorModeForRenderPass()), a3.setStencilMode(Ui.disabled);
                      const e3 = "3d" === s3.renderingMode ? new Oi(t5.context.gl.LEQUAL, Oi.ReadWrite, t5.depthRangeFor3D) : t5.depthModeForSublayer(0, Oi.ReadOnly);
                      a3.setDepthMode(e3), s3.render(a3.gl, t5.transform.customLayerMatrix(), { farZ: t5.transform.farZ, nearZ: t5.transform.nearZ, fov: t5.transform._fov, modelViewProjectionMatrix: t5.transform.modelViewProjectionMatrix, projectionMatrix: t5.transform.projectionMatrix }), a3.setDirty(), t5.setBaseState(), a3.bindFramebuffer.set(null);
                    }
                  }(t4, 0, a2);
              }
            }
            translatePosMatrix(t4, i2, a2, s2, o2) {
              if (!a2[0] && !a2[1]) return t4;
              const r2 = o2 ? "map" === s2 ? this.transform.angle : 0 : "viewport" === s2 ? -this.transform.angle : 0;
              if (r2) {
                const t5 = Math.sin(r2), e2 = Math.cos(r2);
                a2 = [a2[0] * e2 - a2[1] * t5, a2[0] * t5 + a2[1] * e2];
              }
              const n2 = [o2 ? a2[0] : Bt(i2, a2[0], this.transform.zoom), o2 ? a2[1] : Bt(i2, a2[1], this.transform.zoom), 0], l2 = new Float32Array(16);
              return e.J(l2, t4, n2), l2;
            }
            saveTileTexture(t4) {
              const e2 = this._tileTextures[t4.size[0]];
              e2 ? e2.push(t4) : this._tileTextures[t4.size[0]] = [t4];
            }
            getTileTexture(t4) {
              const e2 = this._tileTextures[t4];
              return e2 && e2.length > 0 ? e2.pop() : null;
            }
            isPatternMissing(t4) {
              if (!t4) return false;
              if (!t4.from || !t4.to) return true;
              const e2 = this.imageManager.getPattern(t4.from.toString()), i2 = this.imageManager.getPattern(t4.to.toString());
              return !e2 || !i2;
            }
            useProgram(t4, e2) {
              this.cache = this.cache || {};
              const i2 = t4 + (e2 ? e2.cacheKey : "") + (this._showOverdrawInspector ? "/overdraw" : "") + (this.style.map.terrain ? "/terrain" : "");
              return this.cache[i2] || (this.cache[i2] = new xe(this.context, pe[t4], e2, We[t4], this._showOverdrawInspector, this.style.map.terrain)), this.cache[i2];
            }
            setCustomLayerDefaults() {
              this.context.unbindVAO(), this.context.cullFace.setDefault(), this.context.activeTexture.setDefault(), this.context.pixelStoreUnpack.setDefault(), this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(), this.context.pixelStoreUnpackFlipY.setDefault();
            }
            setBaseState() {
              const t4 = this.context.gl;
              this.context.cullFace.set(false), this.context.viewport.set([0, 0, this.width, this.height]), this.context.blendEquation.set(t4.FUNC_ADD);
            }
            initDebugOverlayCanvas() {
              null == this.debugOverlayCanvas && (this.debugOverlayCanvas = document.createElement("canvas"), this.debugOverlayCanvas.width = 512, this.debugOverlayCanvas.height = 512, this.debugOverlayTexture = new b(this.context, this.debugOverlayCanvas, this.context.gl.RGBA));
            }
            destroy() {
              this.debugOverlayTexture && this.debugOverlayTexture.destroy();
            }
            overLimit() {
              const { drawingBufferWidth: t4, drawingBufferHeight: e2 } = this.context.gl;
              return this.width !== t4 || this.height !== e2;
            }
          }
          class xa {
            constructor(t4, e2) {
              this.points = t4, this.planes = e2;
            }
            static fromInvProjectionMatrix(t4, i2, a2) {
              const s2 = Math.pow(2, a2), o2 = [[-1, 1, -1, 1], [1, 1, -1, 1], [1, -1, -1, 1], [-1, -1, -1, 1], [-1, 1, 1, 1], [1, 1, 1, 1], [1, -1, 1, 1], [-1, -1, 1, 1]].map((a3) => {
                const o3 = 1 / (a3 = e.af([], a3, t4))[3] / i2 * s2;
                return e.b1(a3, a3, [o3, o3, 1 / a3[3], o3]);
              }), r2 = [[0, 1, 2], [6, 5, 4], [0, 3, 7], [2, 1, 5], [3, 2, 6], [0, 4, 5]].map((t5) => {
                const e2 = function(t6, e3) {
                  var i4 = e3[0], a4 = e3[1], s4 = e3[2], o3 = i4 * i4 + a4 * a4 + s4 * s4;
                  return o3 > 0 && (o3 = 1 / Math.sqrt(o3)), t6[0] = e3[0] * o3, t6[1] = e3[1] * o3, t6[2] = e3[2] * o3, t6;
                }([], function(t6, e3, i4) {
                  var a4 = e3[0], s4 = e3[1], o3 = e3[2], r3 = i4[0], n2 = i4[1], l2 = i4[2];
                  return t6[0] = s4 * l2 - o3 * n2, t6[1] = o3 * r3 - a4 * l2, t6[2] = a4 * n2 - s4 * r3, t6;
                }([], g([], o2[t5[0]], o2[t5[1]]), g([], o2[t5[2]], o2[t5[1]]))), i3 = -((a3 = e2)[0] * (s3 = o2[t5[1]])[0] + a3[1] * s3[1] + a3[2] * s3[2]);
                var a3, s3;
                return e2.concat(i3);
              });
              return new xa(o2, r2);
            }
          }
          class ya {
            constructor(t4, e2) {
              this.min = t4, this.max = e2, this.center = function(t5, e3, i2) {
                return t5[0] = 0.5 * e3[0], t5[1] = 0.5 * e3[1], t5[2] = 0.5 * e3[2], t5;
              }([], function(t5, e3, i2) {
                return t5[0] = e3[0] + i2[0], t5[1] = e3[1] + i2[1], t5[2] = e3[2] + i2[2], t5;
              }([], this.min, this.max));
            }
            quadrant(t4) {
              const e2 = [t4 % 2 == 0, t4 < 2], i2 = m(this.min), a2 = m(this.max);
              for (let t5 = 0; t5 < e2.length; t5++) i2[t5] = e2[t5] ? this.min[t5] : this.center[t5], a2[t5] = e2[t5] ? this.center[t5] : this.max[t5];
              return a2[2] = this.max[2], new ya(i2, a2);
            }
            distanceX(t4) {
              return Math.max(Math.min(this.max[0], t4[0]), this.min[0]) - t4[0];
            }
            distanceY(t4) {
              return Math.max(Math.min(this.max[1], t4[1]), this.min[1]) - t4[1];
            }
            intersects(t4) {
              const i2 = [[this.min[0], this.min[1], this.min[2], 1], [this.max[0], this.min[1], this.min[2], 1], [this.max[0], this.max[1], this.min[2], 1], [this.min[0], this.max[1], this.min[2], 1], [this.min[0], this.min[1], this.max[2], 1], [this.max[0], this.min[1], this.max[2], 1], [this.max[0], this.max[1], this.max[2], 1], [this.min[0], this.max[1], this.max[2], 1]];
              let a2 = true;
              for (let s2 = 0; s2 < t4.planes.length; s2++) {
                const o2 = t4.planes[s2];
                let r2 = 0;
                for (let t5 = 0; t5 < i2.length; t5++) e.b2(o2, i2[t5]) >= 0 && r2++;
                if (0 === r2) return 0;
                r2 !== i2.length && (a2 = false);
              }
              if (a2) return 2;
              for (let e2 = 0; e2 < 3; e2++) {
                let i3 = Number.MAX_VALUE, a3 = -Number.MAX_VALUE;
                for (let s2 = 0; s2 < t4.points.length; s2++) {
                  const o2 = t4.points[s2][e2] - this.min[e2];
                  i3 = Math.min(i3, o2), a3 = Math.max(a3, o2);
                }
                if (a3 < 0 || i3 > this.max[e2] - this.min[e2]) return 0;
              }
              return 1;
            }
          }
          class ba {
            constructor(t4 = 0, e2 = 0, i2 = 0, a2 = 0) {
              if (isNaN(t4) || t4 < 0 || isNaN(e2) || e2 < 0 || isNaN(i2) || i2 < 0 || isNaN(a2) || a2 < 0) throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");
              this.top = t4, this.bottom = e2, this.left = i2, this.right = a2;
            }
            interpolate(t4, i2, a2) {
              return null != i2.top && null != t4.top && (this.top = e.y.number(t4.top, i2.top, a2)), null != i2.bottom && null != t4.bottom && (this.bottom = e.y.number(t4.bottom, i2.bottom, a2)), null != i2.left && null != t4.left && (this.left = e.y.number(t4.left, i2.left, a2)), null != i2.right && null != t4.right && (this.right = e.y.number(t4.right, i2.right, a2)), this;
            }
            getCenter(t4, i2) {
              const a2 = e.ac((this.left + t4 - this.right) / 2, 0, t4), s2 = e.ac((this.top + i2 - this.bottom) / 2, 0, i2);
              return new e.P(a2, s2);
            }
            equals(t4) {
              return this.top === t4.top && this.bottom === t4.bottom && this.left === t4.left && this.right === t4.right;
            }
            clone() {
              return new ba(this.top, this.bottom, this.left, this.right);
            }
            toJSON() {
              return { top: this.top, bottom: this.bottom, left: this.left, right: this.right };
            }
          }
          const wa = 85.051129;
          class Ta {
            constructor(t4, i2, a2, s2, o2) {
              this.tileSize = 512, this._renderWorldCopies = void 0 === o2 || !!o2, this._minZoom = t4 || 0, this._maxZoom = i2 || 22, this._minPitch = null == a2 ? 0 : a2, this._maxPitch = null == s2 ? 60 : s2, this.setMaxBounds(), this.width = 0, this.height = 0, this._center = new e.N(0, 0), this._elevation = 0, this.zoom = 0, this.angle = 0, this._fov = 0.6435011087932844, this._pitch = 0, this._unmodified = true, this._edgeInsets = new ba(), this._posMatrixCache = {}, this._alignedPosMatrixCache = {}, this._fogMatrixCache = {}, this.minElevationForCurrentTile = 0;
            }
            clone() {
              const t4 = new Ta(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies);
              return t4.apply(this), t4;
            }
            apply(t4) {
              this.tileSize = t4.tileSize, this.latRange = t4.latRange, this.lngRange = t4.lngRange, this.width = t4.width, this.height = t4.height, this._center = t4._center, this._elevation = t4._elevation, this.minElevationForCurrentTile = t4.minElevationForCurrentTile, this.zoom = t4.zoom, this.angle = t4.angle, this._fov = t4._fov, this._pitch = t4._pitch, this._unmodified = t4._unmodified, this._edgeInsets = t4._edgeInsets.clone(), this._calcMatrices();
            }
            get minZoom() {
              return this._minZoom;
            }
            set minZoom(t4) {
              this._minZoom !== t4 && (this._minZoom = t4, this.zoom = Math.max(this.zoom, t4));
            }
            get maxZoom() {
              return this._maxZoom;
            }
            set maxZoom(t4) {
              this._maxZoom !== t4 && (this._maxZoom = t4, this.zoom = Math.min(this.zoom, t4));
            }
            get minPitch() {
              return this._minPitch;
            }
            set minPitch(t4) {
              this._minPitch !== t4 && (this._minPitch = t4, this.pitch = Math.max(this.pitch, t4));
            }
            get maxPitch() {
              return this._maxPitch;
            }
            set maxPitch(t4) {
              this._maxPitch !== t4 && (this._maxPitch = t4, this.pitch = Math.min(this.pitch, t4));
            }
            get renderWorldCopies() {
              return this._renderWorldCopies;
            }
            set renderWorldCopies(t4) {
              void 0 === t4 ? t4 = true : null === t4 && (t4 = false), this._renderWorldCopies = t4;
            }
            get worldSize() {
              return this.tileSize * this.scale;
            }
            get centerOffset() {
              return this.centerPoint._sub(this.size._div(2));
            }
            get size() {
              return new e.P(this.width, this.height);
            }
            get bearing() {
              return -this.angle / Math.PI * 180;
            }
            set bearing(t4) {
              const i2 = -e.b3(t4, -180, 180) * Math.PI / 180;
              this.angle !== i2 && (this._unmodified = false, this.angle = i2, this._calcMatrices(), this.rotationMatrix = function() {
                var t5 = new e.A(4);
                return e.A != Float32Array && (t5[1] = 0, t5[2] = 0), t5[0] = 1, t5[3] = 1, t5;
              }(), function(t5, e2, i3) {
                var a2 = e2[0], s2 = e2[1], o2 = e2[2], r2 = e2[3], n2 = Math.sin(i3), l2 = Math.cos(i3);
                t5[0] = a2 * l2 + o2 * n2, t5[1] = s2 * l2 + r2 * n2, t5[2] = a2 * -n2 + o2 * l2, t5[3] = s2 * -n2 + r2 * l2;
              }(this.rotationMatrix, this.rotationMatrix, this.angle));
            }
            get pitch() {
              return this._pitch / Math.PI * 180;
            }
            set pitch(t4) {
              const i2 = e.ac(t4, this.minPitch, this.maxPitch) / 180 * Math.PI;
              this._pitch !== i2 && (this._unmodified = false, this._pitch = i2, this._calcMatrices());
            }
            get fov() {
              return this._fov / Math.PI * 180;
            }
            set fov(t4) {
              t4 = Math.max(0.01, Math.min(60, t4)), this._fov !== t4 && (this._unmodified = false, this._fov = t4 / 180 * Math.PI, this._calcMatrices());
            }
            get zoom() {
              return this._zoom;
            }
            set zoom(t4) {
              const e2 = Math.min(Math.max(t4, this.minZoom), this.maxZoom);
              this._zoom !== e2 && (this._unmodified = false, this._zoom = e2, this.tileZoom = Math.max(0, Math.floor(e2)), this.scale = this.zoomScale(e2), this._constrain(), this._calcMatrices());
            }
            get center() {
              return this._center;
            }
            set center(t4) {
              t4.lat === this._center.lat && t4.lng === this._center.lng || (this._unmodified = false, this._center = t4, this._constrain(), this._calcMatrices());
            }
            get elevation() {
              return this._elevation;
            }
            set elevation(t4) {
              t4 !== this._elevation && (this._elevation = t4, this._constrain(), this._calcMatrices());
            }
            get padding() {
              return this._edgeInsets.toJSON();
            }
            set padding(t4) {
              this._edgeInsets.equals(t4) || (this._unmodified = false, this._edgeInsets.interpolate(this._edgeInsets, t4, 1), this._calcMatrices());
            }
            get centerPoint() {
              return this._edgeInsets.getCenter(this.width, this.height);
            }
            isPaddingEqual(t4) {
              return this._edgeInsets.equals(t4);
            }
            interpolatePadding(t4, e2, i2) {
              this._unmodified = false, this._edgeInsets.interpolate(t4, e2, i2), this._constrain(), this._calcMatrices();
            }
            coveringZoomLevel(t4) {
              const e2 = (t4.roundZoom ? Math.round : Math.floor)(this.zoom + this.scaleZoom(this.tileSize / t4.tileSize));
              return Math.max(0, e2);
            }
            getVisibleUnwrappedCoordinates(t4) {
              const i2 = [new e.b4(0, t4)];
              if (this._renderWorldCopies) {
                const a2 = this.pointCoordinate(new e.P(0, 0)), s2 = this.pointCoordinate(new e.P(this.width, 0)), o2 = this.pointCoordinate(new e.P(this.width, this.height)), r2 = this.pointCoordinate(new e.P(0, this.height)), n2 = Math.floor(Math.min(a2.x, s2.x, o2.x, r2.x)), l2 = Math.floor(Math.max(a2.x, s2.x, o2.x, r2.x)), h2 = 1;
                for (let a3 = n2 - h2; a3 <= l2 + h2; a3++) 0 !== a3 && i2.push(new e.b4(a3, t4));
              }
              return i2;
            }
            coveringTiles(t4) {
              var i2, a2;
              let s2 = this.coveringZoomLevel(t4);
              const o2 = s2;
              if (void 0 !== t4.minzoom && s2 < t4.minzoom) return [];
              void 0 !== t4.maxzoom && s2 > t4.maxzoom && (s2 = t4.maxzoom);
              const r2 = this.pointCoordinate(this.getCameraPoint()), n2 = e.Z.fromLngLat(this.center), l2 = Math.pow(2, s2), h2 = [l2 * r2.x, l2 * r2.y, 0], c2 = [l2 * n2.x, l2 * n2.y, 0], u2 = xa.fromInvProjectionMatrix(this.invModelViewProjectionMatrix, this.worldSize, s2);
              let d2 = t4.minzoom || 0;
              !t4.terrain && this.pitch <= 60 && this._edgeInsets.top < 0.1 && (d2 = s2);
              const _2 = t4.terrain ? 2 / Math.min(this.tileSize, t4.tileSize) * this.tileSize : 3, p2 = (t5) => ({ aabb: new ya([t5 * l2, 0, 0], [(t5 + 1) * l2, l2, 0]), zoom: 0, x: 0, y: 0, wrap: t5, fullyVisible: false }), m2 = [], f2 = [], g2 = s2, x2 = t4.reparseOverscaled ? o2 : s2;
              if (this._renderWorldCopies) for (let t5 = 1; t5 <= 3; t5++) m2.push(p2(-t5)), m2.push(p2(t5));
              for (m2.push(p2(0)); m2.length > 0; ) {
                const s3 = m2.pop(), o3 = s3.x, r3 = s3.y;
                let n3 = s3.fullyVisible;
                if (!n3) {
                  const t5 = s3.aabb.intersects(u2);
                  if (0 === t5) continue;
                  n3 = 2 === t5;
                }
                const l3 = t4.terrain ? h2 : c2, p3 = s3.aabb.distanceX(l3), y2 = s3.aabb.distanceY(l3), b2 = Math.max(Math.abs(p3), Math.abs(y2));
                if (s3.zoom === g2 || b2 > _2 + (1 << g2 - s3.zoom) - 2 && s3.zoom >= d2) {
                  const t5 = g2 - s3.zoom, i3 = h2[0] - 0.5 - (o3 << t5), a3 = h2[1] - 0.5 - (r3 << t5);
                  f2.push({ tileID: new e.S(s3.zoom === g2 ? x2 : s3.zoom, s3.wrap, s3.zoom, o3, r3), distanceSq: v([c2[0] - 0.5 - o3, c2[1] - 0.5 - r3]), tileDistanceToCamera: Math.sqrt(i3 * i3 + a3 * a3) });
                } else for (let l4 = 0; l4 < 4; l4++) {
                  const h3 = (o3 << 1) + l4 % 2, c3 = (r3 << 1) + (l4 >> 1), u3 = s3.zoom + 1;
                  let d3 = s3.aabb.quadrant(l4);
                  if (t4.terrain) {
                    const o4 = new e.S(u3, s3.wrap, u3, h3, c3), r4 = t4.terrain.getMinMaxElevation(o4), n4 = null !== (i2 = r4.minElevation) && void 0 !== i2 ? i2 : this.elevation, l5 = null !== (a2 = r4.maxElevation) && void 0 !== a2 ? a2 : this.elevation;
                    d3 = new ya([d3.min[0], d3.min[1], n4], [d3.max[0], d3.max[1], l5]);
                  }
                  m2.push({ aabb: d3, zoom: u3, x: h3, y: c3, wrap: s3.wrap, fullyVisible: n3 });
                }
              }
              return f2.sort((t5, e2) => t5.distanceSq - e2.distanceSq).map((t5) => t5.tileID);
            }
            resize(t4, e2) {
              this.width = t4, this.height = e2, this.pixelsToGLUnits = [2 / t4, -2 / e2], this._constrain(), this._calcMatrices();
            }
            get unmodified() {
              return this._unmodified;
            }
            zoomScale(t4) {
              return Math.pow(2, t4);
            }
            scaleZoom(t4) {
              return Math.log(t4) / Math.LN2;
            }
            project(t4) {
              const i2 = e.ac(t4.lat, -85.051129, wa);
              return new e.P(e.O(t4.lng) * this.worldSize, e.Q(i2) * this.worldSize);
            }
            unproject(t4) {
              return new e.Z(t4.x / this.worldSize, t4.y / this.worldSize).toLngLat();
            }
            get point() {
              return this.project(this.center);
            }
            getCameraPosition() {
              return { lngLat: this.pointLocation(this.getCameraPoint()), altitude: Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter + this.elevation };
            }
            recalculateZoom(t4) {
              const i2 = this.elevation, a2 = Math.cos(this._pitch) * this.cameraToCenterDistance / this._pixelPerMeter, s2 = this.pointLocation(this.centerPoint, t4), o2 = t4.getElevationForLngLatZoom(s2, this.tileZoom);
              if (!(this.elevation - o2)) return;
              const r2 = a2 + i2 - o2, n2 = Math.cos(this._pitch) * this.cameraToCenterDistance / r2 / e.b5(1, s2.lat), l2 = this.scaleZoom(n2 / this.tileSize);
              this._elevation = o2, this._center = s2, this.zoom = l2;
            }
            setLocationAtPoint(t4, i2) {
              const a2 = this.pointCoordinate(i2), s2 = this.pointCoordinate(this.centerPoint), o2 = this.locationCoordinate(t4), r2 = new e.Z(o2.x - (a2.x - s2.x), o2.y - (a2.y - s2.y));
              this.center = this.coordinateLocation(r2), this._renderWorldCopies && (this.center = this.center.wrap());
            }
            locationPoint(t4, e2) {
              return e2 ? this.coordinatePoint(this.locationCoordinate(t4), e2.getElevationForLngLatZoom(t4, this.tileZoom), this.pixelMatrix3D) : this.coordinatePoint(this.locationCoordinate(t4));
            }
            pointLocation(t4, e2) {
              return this.coordinateLocation(this.pointCoordinate(t4, e2));
            }
            locationCoordinate(t4) {
              return e.Z.fromLngLat(t4);
            }
            coordinateLocation(t4) {
              return t4 && t4.toLngLat();
            }
            pointCoordinate(t4, i2) {
              if (i2) {
                const e2 = i2.pointCoordinate(t4);
                if (null != e2) return e2;
              }
              const a2 = [t4.x, t4.y, 0, 1], s2 = [t4.x, t4.y, 1, 1];
              e.af(a2, a2, this.pixelMatrixInverse), e.af(s2, s2, this.pixelMatrixInverse);
              const o2 = a2[3], r2 = s2[3], n2 = a2[1] / o2, l2 = s2[1] / r2, h2 = a2[2] / o2, c2 = s2[2] / r2, u2 = h2 === c2 ? 0 : (0 - h2) / (c2 - h2);
              return new e.Z(e.y.number(a2[0] / o2, s2[0] / r2, u2) / this.worldSize, e.y.number(n2, l2, u2) / this.worldSize);
            }
            coordinatePoint(t4, i2 = 0, a2 = this.pixelMatrix) {
              const s2 = [t4.x * this.worldSize, t4.y * this.worldSize, i2, 1];
              return e.af(s2, s2, a2), new e.P(s2[0] / s2[3], s2[1] / s2[3]);
            }
            getBounds() {
              const t4 = Math.max(0, this.height / 2 - this.getHorizon());
              return new H().extend(this.pointLocation(new e.P(0, t4))).extend(this.pointLocation(new e.P(this.width, t4))).extend(this.pointLocation(new e.P(this.width, this.height))).extend(this.pointLocation(new e.P(0, this.height)));
            }
            getMaxBounds() {
              return this.latRange && 2 === this.latRange.length && this.lngRange && 2 === this.lngRange.length ? new H([this.lngRange[0], this.latRange[0]], [this.lngRange[1], this.latRange[1]]) : null;
            }
            getHorizon() {
              return Math.tan(Math.PI / 2 - this._pitch) * this.cameraToCenterDistance * 0.85;
            }
            setMaxBounds(t4) {
              t4 ? (this.lngRange = [t4.getWest(), t4.getEast()], this.latRange = [t4.getSouth(), t4.getNorth()], this._constrain()) : (this.lngRange = null, this.latRange = [-85.051129, wa]);
            }
            calculateTileMatrix(t4) {
              const i2 = t4.canonical, a2 = this.worldSize / this.zoomScale(i2.z), s2 = i2.x + Math.pow(2, i2.z) * t4.wrap, o2 = e.an(new Float64Array(16));
              return e.J(o2, o2, [s2 * a2, i2.y * a2, 0]), e.K(o2, o2, [a2 / e.X, a2 / e.X, 1]), o2;
            }
            calculatePosMatrix(t4, i2 = false) {
              const a2 = t4.key, s2 = i2 ? this._alignedPosMatrixCache : this._posMatrixCache;
              if (s2[a2]) return s2[a2];
              const o2 = this.calculateTileMatrix(t4);
              return e.L(o2, i2 ? this.alignedModelViewProjectionMatrix : this.modelViewProjectionMatrix, o2), s2[a2] = new Float32Array(o2), s2[a2];
            }
            calculateFogMatrix(t4) {
              const i2 = t4.key, a2 = this._fogMatrixCache;
              if (a2[i2]) return a2[i2];
              const s2 = this.calculateTileMatrix(t4);
              return e.L(s2, this.fogMatrix, s2), a2[i2] = new Float32Array(s2), a2[i2];
            }
            customLayerMatrix() {
              return this.mercatorMatrix.slice();
            }
            getConstrained(t4, i2) {
              i2 = e.ac(+i2, this.minZoom, this.maxZoom);
              const a2 = { center: new e.N(t4.lng, t4.lat), zoom: i2 };
              let s2 = this.lngRange;
              if (!this._renderWorldCopies && null === s2) {
                const t5 = 180 - 1e-10;
                s2 = [-t5, t5];
              }
              const o2 = this.tileSize * this.zoomScale(a2.zoom);
              let r2 = 0, n2 = o2, l2 = 0, h2 = o2, c2 = 0, u2 = 0;
              const { x: d2, y: _2 } = this.size;
              if (this.latRange) {
                const t5 = this.latRange;
                r2 = e.Q(t5[1]) * o2, n2 = e.Q(t5[0]) * o2, n2 - r2 < _2 && (c2 = _2 / (n2 - r2));
              }
              s2 && (l2 = e.b3(e.O(s2[0]) * o2, 0, o2), h2 = e.b3(e.O(s2[1]) * o2, 0, o2), h2 < l2 && (h2 += o2), h2 - l2 < d2 && (u2 = d2 / (h2 - l2)));
              const { x: p2, y: m2 } = this.project.call({ worldSize: o2 }, t4);
              let f2, g2;
              const v2 = Math.max(u2 || 0, c2 || 0);
              if (v2) {
                const t5 = new e.P(u2 ? (h2 + l2) / 2 : p2, c2 ? (n2 + r2) / 2 : m2);
                return a2.center = this.unproject.call({ worldSize: o2 }, t5).wrap(), a2.zoom += this.scaleZoom(v2), a2;
              }
              if (this.latRange) {
                const t5 = _2 / 2;
                m2 - t5 < r2 && (g2 = r2 + t5), m2 + t5 > n2 && (g2 = n2 - t5);
              }
              if (s2) {
                const t5 = (l2 + h2) / 2;
                let i3 = p2;
                this._renderWorldCopies && (i3 = e.b3(p2, t5 - o2 / 2, t5 + o2 / 2));
                const a3 = d2 / 2;
                i3 - a3 < l2 && (f2 = l2 + a3), i3 + a3 > h2 && (f2 = h2 - a3);
              }
              if (void 0 !== f2 || void 0 !== g2) {
                const t5 = new e.P(null != f2 ? f2 : p2, null != g2 ? g2 : m2);
                a2.center = this.unproject.call({ worldSize: o2 }, t5).wrap();
              }
              return a2;
            }
            _constrain() {
              if (!this.center || !this.width || !this.height || this._constraining) return;
              this._constraining = true;
              const t4 = this._unmodified, { center: e2, zoom: i2 } = this.getConstrained(this.center, this.zoom);
              this.center = e2, this.zoom = i2, this._unmodified = t4, this._constraining = false;
            }
            _calcMatrices() {
              if (!this.height) return;
              const t4 = this.centerOffset, i2 = this.point.x, a2 = this.point.y;
              this.cameraToCenterDistance = 0.5 / Math.tan(this._fov / 2) * this.height, this._pixelPerMeter = e.b5(1, this.center.lat) * this.worldSize;
              let s2 = e.an(new Float64Array(16));
              e.K(s2, s2, [this.width / 2, -this.height / 2, 1]), e.J(s2, s2, [1, -1, 0]), this.labelPlaneMatrix = s2, s2 = e.an(new Float64Array(16)), e.K(s2, s2, [1, -1, 1]), e.J(s2, s2, [-1, -1, 0]), e.K(s2, s2, [2 / this.width, 2 / this.height, 1]), this.glCoordMatrix = s2;
              const o2 = this.cameraToCenterDistance + this._elevation * this._pixelPerMeter / Math.cos(this._pitch), r2 = Math.min(this.elevation, this.minElevationForCurrentTile), n2 = o2 - r2 * this._pixelPerMeter / Math.cos(this._pitch), l2 = r2 < 0 ? n2 : o2, h2 = Math.PI / 2 + this._pitch, c2 = this._fov * (0.5 + t4.y / this.height), u2 = Math.sin(c2) * l2 / Math.sin(e.ac(Math.PI - h2 - c2, 0.01, Math.PI - 0.01)), d2 = this.getHorizon(), _2 = 2 * Math.atan(d2 / this.cameraToCenterDistance) * (0.5 + t4.y / (2 * d2)), p2 = Math.sin(_2) * l2 / Math.sin(e.ac(Math.PI - h2 - _2, 0.01, Math.PI - 0.01)), m2 = Math.min(u2, p2);
              this.farZ = 1.01 * (Math.cos(Math.PI / 2 - this._pitch) * m2 + l2), this.nearZ = this.height / 50, s2 = new Float64Array(16), e.b6(s2, this._fov, this.width / this.height, this.nearZ, this.farZ), s2[8] = 2 * -t4.x / this.width, s2[9] = 2 * t4.y / this.height, this.projectionMatrix = e.ae(s2), e.K(s2, s2, [1, -1, 1]), e.J(s2, s2, [0, 0, -this.cameraToCenterDistance]), e.b7(s2, s2, this._pitch), e.ad(s2, s2, this.angle), e.J(s2, s2, [-i2, -a2, 0]), this.mercatorMatrix = e.K([], s2, [this.worldSize, this.worldSize, this.worldSize]), e.K(s2, s2, [1, 1, this._pixelPerMeter]), this.pixelMatrix = e.L(new Float64Array(16), this.labelPlaneMatrix, s2), e.J(s2, s2, [0, 0, -this.elevation]), this.modelViewProjectionMatrix = s2, this.invModelViewProjectionMatrix = e.as([], s2), this.fogMatrix = new Float64Array(16), e.b6(this.fogMatrix, this._fov, this.width / this.height, o2, this.farZ), this.fogMatrix[8] = 2 * -t4.x / this.width, this.fogMatrix[9] = 2 * t4.y / this.height, e.K(this.fogMatrix, this.fogMatrix, [1, -1, 1]), e.J(this.fogMatrix, this.fogMatrix, [0, 0, -this.cameraToCenterDistance]), e.b7(this.fogMatrix, this.fogMatrix, this._pitch), e.ad(this.fogMatrix, this.fogMatrix, this.angle), e.J(this.fogMatrix, this.fogMatrix, [-i2, -a2, 0]), e.K(this.fogMatrix, this.fogMatrix, [1, 1, this._pixelPerMeter]), e.J(this.fogMatrix, this.fogMatrix, [0, 0, -this.elevation]), this.pixelMatrix3D = e.L(new Float64Array(16), this.labelPlaneMatrix, s2);
              const f2 = this.width % 2 / 2, g2 = this.height % 2 / 2, v2 = Math.cos(this.angle), x2 = Math.sin(this.angle), y2 = i2 - Math.round(i2) + v2 * f2 + x2 * g2, b2 = a2 - Math.round(a2) + v2 * g2 + x2 * f2, w2 = new Float64Array(s2);
              if (e.J(w2, w2, [y2 > 0.5 ? y2 - 1 : y2, b2 > 0.5 ? b2 - 1 : b2, 0]), this.alignedModelViewProjectionMatrix = w2, s2 = e.as(new Float64Array(16), this.pixelMatrix), !s2) throw new Error("failed to invert matrix");
              this.pixelMatrixInverse = s2, this._posMatrixCache = {}, this._alignedPosMatrixCache = {}, this._fogMatrixCache = {};
            }
            maxPitchScaleFactor() {
              if (!this.pixelMatrixInverse) return 1;
              const t4 = this.pointCoordinate(new e.P(0, 0)), i2 = [t4.x * this.worldSize, t4.y * this.worldSize, 0, 1];
              return e.af(i2, i2, this.pixelMatrix)[3] / this.cameraToCenterDistance;
            }
            getCameraPoint() {
              const t4 = Math.tan(this._pitch) * (this.cameraToCenterDistance || 1);
              return this.centerPoint.add(new e.P(0, t4));
            }
            getCameraQueryGeometry(t4) {
              const i2 = this.getCameraPoint();
              if (1 === t4.length) return [t4[0], i2];
              {
                let a2 = i2.x, s2 = i2.y, o2 = i2.x, r2 = i2.y;
                for (const e2 of t4) a2 = Math.min(a2, e2.x), s2 = Math.min(s2, e2.y), o2 = Math.max(o2, e2.x), r2 = Math.max(r2, e2.y);
                return [new e.P(a2, s2), new e.P(o2, s2), new e.P(o2, r2), new e.P(a2, r2), new e.P(a2, s2)];
              }
            }
            lngLatToCameraDepth(t4, i2) {
              const a2 = this.locationCoordinate(t4), s2 = [a2.x * this.worldSize, a2.y * this.worldSize, i2, 1];
              return e.af(s2, s2, this.modelViewProjectionMatrix), s2[2] / s2[3];
            }
          }
          function Ia(t4, e2) {
            let i2, a2 = false, s2 = null, o2 = null;
            const r2 = () => {
              s2 = null, a2 && (t4.apply(o2, i2), s2 = setTimeout(r2, e2), a2 = false);
            };
            return (...t5) => (a2 = true, o2 = this, i2 = t5, s2 || r2(), s2);
          }
          class Ea {
            constructor(t4) {
              this._getCurrentHash = () => {
                const t5 = window.location.hash.replace("#", "");
                if (this._hashName) {
                  let e2;
                  return t5.split("&").map((t6) => t6.split("=")).forEach((t6) => {
                    t6[0] === this._hashName && (e2 = t6);
                  }), (e2 && e2[1] || "").split("/");
                }
                return t5.split("/");
              }, this._onHashChange = () => {
                const t5 = this._getCurrentHash();
                if (t5.length >= 3 && !t5.some((t6) => isNaN(t6))) {
                  const e2 = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(t5[3] || 0) : this._map.getBearing();
                  return this._map.jumpTo({ center: [+t5[2], +t5[1]], zoom: +t5[0], bearing: e2, pitch: +(t5[4] || 0) }), true;
                }
                return false;
              }, this._updateHashUnthrottled = () => {
                const t5 = window.location.href.replace(/(#.*)?$/, this.getHashString());
                window.history.replaceState(window.history.state, null, t5);
              }, this._removeHash = () => {
                const t5 = this._getCurrentHash();
                if (0 === t5.length) return;
                const e2 = t5.join("/");
                let i2 = e2;
                i2.split("&").length > 0 && (i2 = i2.split("&")[0]), this._hashName && (i2 = `${this._hashName}=${e2}`);
                let a2 = window.location.hash.replace(i2, "");
                a2.startsWith("#&") ? a2 = a2.slice(0, 1) + a2.slice(2) : "#" === a2 && (a2 = "");
                let s2 = window.location.href.replace(/(#.+)?$/, a2);
                s2 = s2.replace("&&", "&"), window.history.replaceState(window.history.state, null, s2);
              }, this._updateHash = Ia(this._updateHashUnthrottled, 300), this._hashName = t4 && encodeURIComponent(t4);
            }
            addTo(t4) {
              return this._map = t4, addEventListener("hashchange", this._onHashChange, false), this._map.on("moveend", this._updateHash), this;
            }
            remove() {
              return removeEventListener("hashchange", this._onHashChange, false), this._map.off("moveend", this._updateHash), clearTimeout(this._updateHash()), this._removeHash(), delete this._map, this;
            }
            getHashString(t4) {
              const e2 = this._map.getCenter(), i2 = Math.round(100 * this._map.getZoom()) / 100, a2 = Math.ceil((i2 * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), s2 = Math.pow(10, a2), o2 = Math.round(e2.lng * s2) / s2, r2 = Math.round(e2.lat * s2) / s2, n2 = this._map.getBearing(), l2 = this._map.getPitch();
              let h2 = "";
              if (h2 += t4 ? `/${o2}/${r2}/${i2}` : `${i2}/${r2}/${o2}`, (n2 || l2) && (h2 += "/" + Math.round(10 * n2) / 10), l2 && (h2 += `/${Math.round(l2)}`), this._hashName) {
                const t5 = this._hashName;
                let e3 = false;
                const i3 = window.location.hash.slice(1).split("&").map((i4) => {
                  const a3 = i4.split("=")[0];
                  return a3 === t5 ? (e3 = true, `${a3}=${h2}`) : i4;
                }).filter((t6) => t6);
                return e3 || i3.push(`${t5}=${h2}`), `#${i3.join("&")}`;
              }
              return `#${h2}`;
            }
          }
          const Pa = { linearity: 0.3, easing: e.b8(0, 0, 0.3, 1) }, Ca = e.e({ deceleration: 2500, maxSpeed: 1400 }, Pa), Sa = e.e({ deceleration: 20, maxSpeed: 1400 }, Pa), za = e.e({ deceleration: 1e3, maxSpeed: 360 }, Pa), Da = e.e({ deceleration: 1e3, maxSpeed: 90 }, Pa);
          class Ma {
            constructor(t4) {
              this._map = t4, this.clear();
            }
            clear() {
              this._inertiaBuffer = [];
            }
            record(t4) {
              this._drainInertiaBuffer(), this._inertiaBuffer.push({ time: o.now(), settings: t4 });
            }
            _drainInertiaBuffer() {
              const t4 = this._inertiaBuffer, e2 = o.now();
              for (; t4.length > 0 && e2 - t4[0].time > 160; ) t4.shift();
            }
            _onMoveEnd(t4) {
              if (this._drainInertiaBuffer(), this._inertiaBuffer.length < 2) return;
              const i2 = { zoom: 0, bearing: 0, pitch: 0, pan: new e.P(0, 0), pinchAround: void 0, around: void 0 };
              for (const { settings: t5 } of this._inertiaBuffer) i2.zoom += t5.zoomDelta || 0, i2.bearing += t5.bearingDelta || 0, i2.pitch += t5.pitchDelta || 0, t5.panDelta && i2.pan._add(t5.panDelta), t5.around && (i2.around = t5.around), t5.pinchAround && (i2.pinchAround = t5.pinchAround);
              const a2 = this._inertiaBuffer[this._inertiaBuffer.length - 1].time - this._inertiaBuffer[0].time, s2 = {};
              if (i2.pan.mag()) {
                const o2 = Ra(i2.pan.mag(), a2, e.e({}, Ca, t4 || {}));
                s2.offset = i2.pan.mult(o2.amount / i2.pan.mag()), s2.center = this._map.transform.center, Aa(s2, o2);
              }
              if (i2.zoom) {
                const t5 = Ra(i2.zoom, a2, Sa);
                s2.zoom = this._map.transform.zoom + t5.amount, Aa(s2, t5);
              }
              if (i2.bearing) {
                const t5 = Ra(i2.bearing, a2, za);
                s2.bearing = this._map.transform.bearing + e.ac(t5.amount, -179, 179), Aa(s2, t5);
              }
              if (i2.pitch) {
                const t5 = Ra(i2.pitch, a2, Da);
                s2.pitch = this._map.transform.pitch + t5.amount, Aa(s2, t5);
              }
              if (s2.zoom || s2.bearing) {
                const t5 = void 0 === i2.pinchAround ? i2.around : i2.pinchAround;
                s2.around = t5 ? this._map.unproject(t5) : this._map.getCenter();
              }
              return this.clear(), e.e(s2, { noMoveStart: true });
            }
          }
          function Aa(t4, e2) {
            (!t4.duration || t4.duration < e2.duration) && (t4.duration = e2.duration, t4.easing = e2.easing);
          }
          function Ra(t4, i2, a2) {
            const { maxSpeed: s2, linearity: o2, deceleration: r2 } = a2, n2 = e.ac(t4 * o2 / (i2 / 1e3), -s2, s2), l2 = Math.abs(n2) / (r2 * o2);
            return { easing: a2.easing, duration: 1e3 * l2, amount: n2 * (l2 / 2) };
          }
          class ka extends e.k {
            preventDefault() {
              this._defaultPrevented = true;
            }
            get defaultPrevented() {
              return this._defaultPrevented;
            }
            constructor(t4, i2, a2, s2 = {}) {
              const o2 = r.mousePos(i2.getCanvas(), a2), n2 = i2.unproject(o2);
              super(t4, e.e({ point: o2, lngLat: n2, originalEvent: a2 }, s2)), this._defaultPrevented = false, this.target = i2;
            }
          }
          class La extends e.k {
            preventDefault() {
              this._defaultPrevented = true;
            }
            get defaultPrevented() {
              return this._defaultPrevented;
            }
            constructor(t4, i2, a2) {
              const s2 = "touchend" === t4 ? a2.changedTouches : a2.touches, o2 = r.touchPos(i2.getCanvasContainer(), s2), n2 = o2.map((t5) => i2.unproject(t5)), l2 = o2.reduce((t5, e2, i3, a3) => t5.add(e2.div(a3.length)), new e.P(0, 0));
              super(t4, { points: o2, point: l2, lngLats: n2, lngLat: i2.unproject(l2), originalEvent: a2 }), this._defaultPrevented = false;
            }
          }
          class Fa extends e.k {
            preventDefault() {
              this._defaultPrevented = true;
            }
            get defaultPrevented() {
              return this._defaultPrevented;
            }
            constructor(t4, e2, i2) {
              super(t4, { originalEvent: i2 }), this._defaultPrevented = false;
            }
          }
          class Ba {
            constructor(t4, e2) {
              this._map = t4, this._clickTolerance = e2.clickTolerance;
            }
            reset() {
              delete this._mousedownPos;
            }
            wheel(t4) {
              return this._firePreventable(new Fa(t4.type, this._map, t4));
            }
            mousedown(t4, e2) {
              return this._mousedownPos = e2, this._firePreventable(new ka(t4.type, this._map, t4));
            }
            mouseup(t4) {
              this._map.fire(new ka(t4.type, this._map, t4));
            }
            click(t4, e2) {
              this._mousedownPos && this._mousedownPos.dist(e2) >= this._clickTolerance || this._map.fire(new ka(t4.type, this._map, t4));
            }
            dblclick(t4) {
              return this._firePreventable(new ka(t4.type, this._map, t4));
            }
            mouseover(t4) {
              this._map.fire(new ka(t4.type, this._map, t4));
            }
            mouseout(t4) {
              this._map.fire(new ka(t4.type, this._map, t4));
            }
            touchstart(t4) {
              return this._firePreventable(new La(t4.type, this._map, t4));
            }
            touchmove(t4) {
              this._map.fire(new La(t4.type, this._map, t4));
            }
            touchend(t4) {
              this._map.fire(new La(t4.type, this._map, t4));
            }
            touchcancel(t4) {
              this._map.fire(new La(t4.type, this._map, t4));
            }
            _firePreventable(t4) {
              if (this._map.fire(t4), t4.defaultPrevented) return {};
            }
            isEnabled() {
              return true;
            }
            isActive() {
              return false;
            }
            enable() {
            }
            disable() {
            }
          }
          class Oa {
            constructor(t4) {
              this._map = t4;
            }
            reset() {
              this._delayContextMenu = false, this._ignoreContextMenu = true, delete this._contextMenuEvent;
            }
            mousemove(t4) {
              this._map.fire(new ka(t4.type, this._map, t4));
            }
            mousedown() {
              this._delayContextMenu = true, this._ignoreContextMenu = false;
            }
            mouseup() {
              this._delayContextMenu = false, this._contextMenuEvent && (this._map.fire(new ka("contextmenu", this._map, this._contextMenuEvent)), delete this._contextMenuEvent);
            }
            contextmenu(t4) {
              this._delayContextMenu ? this._contextMenuEvent = t4 : this._ignoreContextMenu || this._map.fire(new ka(t4.type, this._map, t4)), this._map.listens("contextmenu") && t4.preventDefault();
            }
            isEnabled() {
              return true;
            }
            isActive() {
              return false;
            }
            enable() {
            }
            disable() {
            }
          }
          class Na {
            constructor(t4) {
              this._map = t4;
            }
            get transform() {
              return this._map._requestedCameraState || this._map.transform;
            }
            get center() {
              return { lng: this.transform.center.lng, lat: this.transform.center.lat };
            }
            get zoom() {
              return this.transform.zoom;
            }
            get pitch() {
              return this.transform.pitch;
            }
            get bearing() {
              return this.transform.bearing;
            }
            unproject(t4) {
              return this.transform.pointLocation(e.P.convert(t4), this._map.terrain);
            }
          }
          class Ua {
            constructor(t4, e2) {
              this._map = t4, this._tr = new Na(t4), this._el = t4.getCanvasContainer(), this._container = t4.getContainer(), this._clickTolerance = e2.clickTolerance || 1;
            }
            isEnabled() {
              return !!this._enabled;
            }
            isActive() {
              return !!this._active;
            }
            enable() {
              this.isEnabled() || (this._enabled = true);
            }
            disable() {
              this.isEnabled() && (this._enabled = false);
            }
            mousedown(t4, e2) {
              this.isEnabled() && t4.shiftKey && 0 === t4.button && (r.disableDrag(), this._startPos = this._lastPos = e2, this._active = true);
            }
            mousemoveWindow(t4, e2) {
              if (!this._active) return;
              const i2 = e2;
              if (this._lastPos.equals(i2) || !this._box && i2.dist(this._startPos) < this._clickTolerance) return;
              const a2 = this._startPos;
              this._lastPos = i2, this._box || (this._box = r.create("div", "maplibregl-boxzoom", this._container), this._container.classList.add("maplibregl-crosshair"), this._fireEvent("boxzoomstart", t4));
              const s2 = Math.min(a2.x, i2.x), o2 = Math.max(a2.x, i2.x), n2 = Math.min(a2.y, i2.y), l2 = Math.max(a2.y, i2.y);
              r.setTransform(this._box, `translate(${s2}px,${n2}px)`), this._box.style.width = o2 - s2 + "px", this._box.style.height = l2 - n2 + "px";
            }
            mouseupWindow(t4, i2) {
              if (!this._active) return;
              if (0 !== t4.button) return;
              const a2 = this._startPos, s2 = i2;
              if (this.reset(), r.suppressClick(), a2.x !== s2.x || a2.y !== s2.y) return this._map.fire(new e.k("boxzoomend", { originalEvent: t4 })), { cameraAnimation: (t5) => t5.fitScreenCoordinates(a2, s2, this._tr.bearing, { linear: true }) };
              this._fireEvent("boxzoomcancel", t4);
            }
            keydown(t4) {
              this._active && 27 === t4.keyCode && (this.reset(), this._fireEvent("boxzoomcancel", t4));
            }
            reset() {
              this._active = false, this._container.classList.remove("maplibregl-crosshair"), this._box && (r.remove(this._box), this._box = null), r.enableDrag(), delete this._startPos, delete this._lastPos;
            }
            _fireEvent(t4, i2) {
              return this._map.fire(new e.k(t4, { originalEvent: i2 }));
            }
          }
          function ja(t4, e2) {
            if (t4.length !== e2.length) throw new Error(`The number of touches and points are not equal - touches ${t4.length}, points ${e2.length}`);
            const i2 = {};
            for (let a2 = 0; a2 < t4.length; a2++) i2[t4[a2].identifier] = e2[a2];
            return i2;
          }
          class Za {
            constructor(t4) {
              this.reset(), this.numTouches = t4.numTouches;
            }
            reset() {
              delete this.centroid, delete this.startTime, delete this.touches, this.aborted = false;
            }
            touchstart(t4, i2, a2) {
              (this.centroid || a2.length > this.numTouches) && (this.aborted = true), this.aborted || (void 0 === this.startTime && (this.startTime = t4.timeStamp), a2.length === this.numTouches && (this.centroid = function(t5) {
                const i3 = new e.P(0, 0);
                for (const e2 of t5) i3._add(e2);
                return i3.div(t5.length);
              }(i2), this.touches = ja(a2, i2)));
            }
            touchmove(t4, e2, i2) {
              if (this.aborted || !this.centroid) return;
              const a2 = ja(i2, e2);
              for (const t5 in this.touches) {
                const e3 = a2[t5];
                (!e3 || e3.dist(this.touches[t5]) > 30) && (this.aborted = true);
              }
            }
            touchend(t4, e2, i2) {
              if ((!this.centroid || t4.timeStamp - this.startTime > 500) && (this.aborted = true), 0 === i2.length) {
                const t5 = !this.aborted && this.centroid;
                if (this.reset(), t5) return t5;
              }
            }
          }
          class qa {
            constructor(t4) {
              this.singleTap = new Za(t4), this.numTaps = t4.numTaps, this.reset();
            }
            reset() {
              this.lastTime = 1 / 0, delete this.lastTap, this.count = 0, this.singleTap.reset();
            }
            touchstart(t4, e2, i2) {
              this.singleTap.touchstart(t4, e2, i2);
            }
            touchmove(t4, e2, i2) {
              this.singleTap.touchmove(t4, e2, i2);
            }
            touchend(t4, e2, i2) {
              const a2 = this.singleTap.touchend(t4, e2, i2);
              if (a2) {
                const e3 = t4.timeStamp - this.lastTime < 500, i3 = !this.lastTap || this.lastTap.dist(a2) < 30;
                if (e3 && i3 || this.reset(), this.count++, this.lastTime = t4.timeStamp, this.lastTap = a2, this.count === this.numTaps) return this.reset(), a2;
              }
            }
          }
          class Va {
            constructor(t4) {
              this._tr = new Na(t4), this._zoomIn = new qa({ numTouches: 1, numTaps: 2 }), this._zoomOut = new qa({ numTouches: 2, numTaps: 1 }), this.reset();
            }
            reset() {
              this._active = false, this._zoomIn.reset(), this._zoomOut.reset();
            }
            touchstart(t4, e2, i2) {
              this._zoomIn.touchstart(t4, e2, i2), this._zoomOut.touchstart(t4, e2, i2);
            }
            touchmove(t4, e2, i2) {
              this._zoomIn.touchmove(t4, e2, i2), this._zoomOut.touchmove(t4, e2, i2);
            }
            touchend(t4, e2, i2) {
              const a2 = this._zoomIn.touchend(t4, e2, i2), s2 = this._zoomOut.touchend(t4, e2, i2), o2 = this._tr;
              return a2 ? (this._active = true, t4.preventDefault(), setTimeout(() => this.reset(), 0), { cameraAnimation: (e3) => e3.easeTo({ duration: 300, zoom: o2.zoom + 1, around: o2.unproject(a2) }, { originalEvent: t4 }) }) : s2 ? (this._active = true, t4.preventDefault(), setTimeout(() => this.reset(), 0), { cameraAnimation: (e3) => e3.easeTo({ duration: 300, zoom: o2.zoom - 1, around: o2.unproject(s2) }, { originalEvent: t4 }) }) : void 0;
            }
            touchcancel() {
              this.reset();
            }
            enable() {
              this._enabled = true;
            }
            disable() {
              this._enabled = false, this.reset();
            }
            isEnabled() {
              return this._enabled;
            }
            isActive() {
              return this._active;
            }
          }
          class Ga {
            constructor(t4) {
              this._enabled = !!t4.enable, this._moveStateManager = t4.moveStateManager, this._clickTolerance = t4.clickTolerance || 1, this._moveFunction = t4.move, this._activateOnStart = !!t4.activateOnStart, t4.assignEvents(this), this.reset();
            }
            reset(t4) {
              this._active = false, this._moved = false, delete this._lastPoint, this._moveStateManager.endMove(t4);
            }
            _move(...t4) {
              const e2 = this._moveFunction(...t4);
              if (e2.bearingDelta || e2.pitchDelta || e2.around || e2.panDelta) return this._active = true, e2;
            }
            dragStart(t4, e2) {
              this.isEnabled() && !this._lastPoint && this._moveStateManager.isValidStartEvent(t4) && (this._moveStateManager.startMove(t4), this._lastPoint = e2.length ? e2[0] : e2, this._activateOnStart && this._lastPoint && (this._active = true));
            }
            dragMove(t4, e2) {
              if (!this.isEnabled()) return;
              const i2 = this._lastPoint;
              if (!i2) return;
              if (t4.preventDefault(), !this._moveStateManager.isValidMoveEvent(t4)) return void this.reset(t4);
              const a2 = e2.length ? e2[0] : e2;
              return !this._moved && a2.dist(i2) < this._clickTolerance ? void 0 : (this._moved = true, this._lastPoint = a2, this._move(i2, a2));
            }
            dragEnd(t4) {
              this.isEnabled() && this._lastPoint && this._moveStateManager.isValidEndEvent(t4) && (this._moved && r.suppressClick(), this.reset(t4));
            }
            enable() {
              this._enabled = true;
            }
            disable() {
              this._enabled = false, this.reset();
            }
            isEnabled() {
              return this._enabled;
            }
            isActive() {
              return this._active;
            }
            getClickTolerance() {
              return this._clickTolerance;
            }
          }
          const Ha = { 0: 1, 2: 2 };
          class Wa {
            constructor(t4) {
              this._correctEvent = t4.checkCorrectEvent;
            }
            startMove(t4) {
              const e2 = r.mouseButton(t4);
              this._eventButton = e2;
            }
            endMove(t4) {
              delete this._eventButton;
            }
            isValidStartEvent(t4) {
              return this._correctEvent(t4);
            }
            isValidMoveEvent(t4) {
              return !function(t5, e2) {
                const i2 = Ha[e2];
                return void 0 === t5.buttons || (t5.buttons & i2) !== i2;
              }(t4, this._eventButton);
            }
            isValidEndEvent(t4) {
              return r.mouseButton(t4) === this._eventButton;
            }
          }
          class $a {
            constructor() {
              this._firstTouch = void 0;
            }
            _isOneFingerTouch(t4) {
              return 1 === t4.targetTouches.length;
            }
            _isSameTouchEvent(t4) {
              return t4.targetTouches[0].identifier === this._firstTouch;
            }
            startMove(t4) {
              this._firstTouch = t4.targetTouches[0].identifier;
            }
            endMove(t4) {
              delete this._firstTouch;
            }
            isValidStartEvent(t4) {
              return this._isOneFingerTouch(t4);
            }
            isValidMoveEvent(t4) {
              return this._isOneFingerTouch(t4) && this._isSameTouchEvent(t4);
            }
            isValidEndEvent(t4) {
              return this._isOneFingerTouch(t4) && this._isSameTouchEvent(t4);
            }
          }
          const Xa = (t4) => {
            t4.mousedown = t4.dragStart, t4.mousemoveWindow = t4.dragMove, t4.mouseup = t4.dragEnd, t4.contextmenu = (t5) => {
              t5.preventDefault();
            };
          }, Ka = ({ enable: t4, clickTolerance: e2, bearingDegreesPerPixelMoved: i2 = 0.8 }) => {
            const a2 = new Wa({ checkCorrectEvent: (t5) => 0 === r.mouseButton(t5) && t5.ctrlKey || 2 === r.mouseButton(t5) });
            return new Ga({ clickTolerance: e2, move: (t5, e3) => ({ bearingDelta: (e3.x - t5.x) * i2 }), moveStateManager: a2, enable: t4, assignEvents: Xa });
          }, Ja = ({ enable: t4, clickTolerance: e2, pitchDegreesPerPixelMoved: i2 = -0.5 }) => {
            const a2 = new Wa({ checkCorrectEvent: (t5) => 0 === r.mouseButton(t5) && t5.ctrlKey || 2 === r.mouseButton(t5) });
            return new Ga({ clickTolerance: e2, move: (t5, e3) => ({ pitchDelta: (e3.y - t5.y) * i2 }), moveStateManager: a2, enable: t4, assignEvents: Xa });
          };
          class Ya {
            constructor(t4, e2) {
              this._clickTolerance = t4.clickTolerance || 1, this._map = e2, this.reset();
            }
            reset() {
              this._active = false, this._touches = {}, this._sum = new e.P(0, 0);
            }
            _shouldBePrevented(t4) {
              return t4 < (this._map.cooperativeGestures.isEnabled() ? 2 : 1);
            }
            touchstart(t4, e2, i2) {
              return this._calculateTransform(t4, e2, i2);
            }
            touchmove(t4, e2, i2) {
              if (this._active) {
                if (!this._shouldBePrevented(i2.length)) return t4.preventDefault(), this._calculateTransform(t4, e2, i2);
                this._map.cooperativeGestures.notifyGestureBlocked("touch_pan", t4);
              }
            }
            touchend(t4, e2, i2) {
              this._calculateTransform(t4, e2, i2), this._active && this._shouldBePrevented(i2.length) && this.reset();
            }
            touchcancel() {
              this.reset();
            }
            _calculateTransform(t4, i2, a2) {
              a2.length > 0 && (this._active = true);
              const s2 = ja(a2, i2), o2 = new e.P(0, 0), r2 = new e.P(0, 0);
              let n2 = 0;
              for (const t5 in s2) {
                const e2 = s2[t5], i3 = this._touches[t5];
                i3 && (o2._add(e2), r2._add(e2.sub(i3)), n2++, s2[t5] = e2);
              }
              if (this._touches = s2, this._shouldBePrevented(n2) || !r2.mag()) return;
              const l2 = r2.div(n2);
              return this._sum._add(l2), this._sum.mag() < this._clickTolerance ? void 0 : { around: o2.div(n2), panDelta: l2 };
            }
            enable() {
              this._enabled = true;
            }
            disable() {
              this._enabled = false, this.reset();
            }
            isEnabled() {
              return this._enabled;
            }
            isActive() {
              return this._active;
            }
          }
          class Qa {
            constructor() {
              this.reset();
            }
            reset() {
              this._active = false, delete this._firstTwoTouches;
            }
            touchstart(t4, e2, i2) {
              this._firstTwoTouches || i2.length < 2 || (this._firstTwoTouches = [i2[0].identifier, i2[1].identifier], this._start([e2[0], e2[1]]));
            }
            touchmove(t4, e2, i2) {
              if (!this._firstTwoTouches) return;
              t4.preventDefault();
              const [a2, s2] = this._firstTwoTouches, o2 = ts(i2, e2, a2), r2 = ts(i2, e2, s2);
              if (!o2 || !r2) return;
              const n2 = this._aroundCenter ? null : o2.add(r2).div(2);
              return this._move([o2, r2], n2, t4);
            }
            touchend(t4, e2, i2) {
              if (!this._firstTwoTouches) return;
              const [a2, s2] = this._firstTwoTouches, o2 = ts(i2, e2, a2), n2 = ts(i2, e2, s2);
              o2 && n2 || (this._active && r.suppressClick(), this.reset());
            }
            touchcancel() {
              this.reset();
            }
            enable(t4) {
              this._enabled = true, this._aroundCenter = !!t4 && "center" === t4.around;
            }
            disable() {
              this._enabled = false, this.reset();
            }
            isEnabled() {
              return !!this._enabled;
            }
            isActive() {
              return !!this._active;
            }
          }
          function ts(t4, e2, i2) {
            for (let a2 = 0; a2 < t4.length; a2++) if (t4[a2].identifier === i2) return e2[a2];
          }
          function es(t4, e2) {
            return Math.log(t4 / e2) / Math.LN2;
          }
          class is extends Qa {
            reset() {
              super.reset(), delete this._distance, delete this._startDistance;
            }
            _start(t4) {
              this._startDistance = this._distance = t4[0].dist(t4[1]);
            }
            _move(t4, e2) {
              const i2 = this._distance;
              if (this._distance = t4[0].dist(t4[1]), this._active || !(Math.abs(es(this._distance, this._startDistance)) < 0.1)) return this._active = true, { zoomDelta: es(this._distance, i2), pinchAround: e2 };
            }
          }
          function as(t4, e2) {
            return 180 * t4.angleWith(e2) / Math.PI;
          }
          class ss extends Qa {
            reset() {
              super.reset(), delete this._minDiameter, delete this._startVector, delete this._vector;
            }
            _start(t4) {
              this._startVector = this._vector = t4[0].sub(t4[1]), this._minDiameter = t4[0].dist(t4[1]);
            }
            _move(t4, e2, i2) {
              const a2 = this._vector;
              if (this._vector = t4[0].sub(t4[1]), this._active || !this._isBelowThreshold(this._vector)) return this._active = true, { bearingDelta: as(this._vector, a2), pinchAround: e2 };
            }
            _isBelowThreshold(t4) {
              this._minDiameter = Math.min(this._minDiameter, t4.mag());
              const e2 = 25 / (Math.PI * this._minDiameter) * 360, i2 = as(t4, this._startVector);
              return Math.abs(i2) < e2;
            }
          }
          function os(t4) {
            return Math.abs(t4.y) > Math.abs(t4.x);
          }
          class rs extends Qa {
            constructor(t4) {
              super(), this._currentTouchCount = 0, this._map = t4;
            }
            reset() {
              super.reset(), this._valid = void 0, delete this._firstMove, delete this._lastPoints;
            }
            touchstart(t4, e2, i2) {
              super.touchstart(t4, e2, i2), this._currentTouchCount = i2.length;
            }
            _start(t4) {
              this._lastPoints = t4, os(t4[0].sub(t4[1])) && (this._valid = false);
            }
            _move(t4, e2, i2) {
              if (this._map.cooperativeGestures.isEnabled() && this._currentTouchCount < 3) return;
              const a2 = t4[0].sub(this._lastPoints[0]), s2 = t4[1].sub(this._lastPoints[1]);
              return this._valid = this.gestureBeginsVertically(a2, s2, i2.timeStamp), this._valid ? (this._lastPoints = t4, this._active = true, { pitchDelta: (a2.y + s2.y) / 2 * -0.5 }) : void 0;
            }
            gestureBeginsVertically(t4, e2, i2) {
              if (void 0 !== this._valid) return this._valid;
              const a2 = t4.mag() >= 2, s2 = e2.mag() >= 2;
              if (!a2 && !s2) return;
              if (!a2 || !s2) return void 0 === this._firstMove && (this._firstMove = i2), i2 - this._firstMove < 100 && void 0;
              const o2 = t4.y > 0 == e2.y > 0;
              return os(t4) && os(e2) && o2;
            }
          }
          const ns = { panStep: 100, bearingStep: 15, pitchStep: 10 };
          class ls {
            constructor(t4) {
              this._tr = new Na(t4);
              const e2 = ns;
              this._panStep = e2.panStep, this._bearingStep = e2.bearingStep, this._pitchStep = e2.pitchStep, this._rotationDisabled = false;
            }
            reset() {
              this._active = false;
            }
            keydown(t4) {
              if (t4.altKey || t4.ctrlKey || t4.metaKey) return;
              let e2 = 0, i2 = 0, a2 = 0, s2 = 0, o2 = 0;
              switch (t4.keyCode) {
                case 61:
                case 107:
                case 171:
                case 187:
                  e2 = 1;
                  break;
                case 189:
                case 109:
                case 173:
                  e2 = -1;
                  break;
                case 37:
                  t4.shiftKey ? i2 = -1 : (t4.preventDefault(), s2 = -1);
                  break;
                case 39:
                  t4.shiftKey ? i2 = 1 : (t4.preventDefault(), s2 = 1);
                  break;
                case 38:
                  t4.shiftKey ? a2 = 1 : (t4.preventDefault(), o2 = -1);
                  break;
                case 40:
                  t4.shiftKey ? a2 = -1 : (t4.preventDefault(), o2 = 1);
                  break;
                default:
                  return;
              }
              return this._rotationDisabled && (i2 = 0, a2 = 0), { cameraAnimation: (r2) => {
                const n2 = this._tr;
                r2.easeTo({ duration: 300, easeId: "keyboardHandler", easing: hs, zoom: e2 ? Math.round(n2.zoom) + e2 * (t4.shiftKey ? 2 : 1) : n2.zoom, bearing: n2.bearing + i2 * this._bearingStep, pitch: n2.pitch + a2 * this._pitchStep, offset: [-s2 * this._panStep, -o2 * this._panStep], center: n2.center }, { originalEvent: t4 });
              } };
            }
            enable() {
              this._enabled = true;
            }
            disable() {
              this._enabled = false, this.reset();
            }
            isEnabled() {
              return this._enabled;
            }
            isActive() {
              return this._active;
            }
            disableRotation() {
              this._rotationDisabled = true;
            }
            enableRotation() {
              this._rotationDisabled = false;
            }
          }
          function hs(t4) {
            return t4 * (2 - t4);
          }
          const cs = 4.000244140625;
          class us {
            constructor(t4, e2) {
              this._onTimeout = (t5) => {
                this._type = "wheel", this._delta -= this._lastValue, this._active || this._start(t5);
              }, this._map = t4, this._tr = new Na(t4), this._triggerRenderFrame = e2, this._delta = 0, this._defaultZoomRate = 0.01, this._wheelZoomRate = 0.0022222222222222222;
            }
            setZoomRate(t4) {
              this._defaultZoomRate = t4;
            }
            setWheelZoomRate(t4) {
              this._wheelZoomRate = t4;
            }
            isEnabled() {
              return !!this._enabled;
            }
            isActive() {
              return !!this._active || void 0 !== this._finishTimeout;
            }
            isZooming() {
              return !!this._zooming;
            }
            enable(t4) {
              this.isEnabled() || (this._enabled = true, this._aroundCenter = !!t4 && "center" === t4.around);
            }
            disable() {
              this.isEnabled() && (this._enabled = false);
            }
            _shouldBePrevented(t4) {
              return !!this._map.cooperativeGestures.isEnabled() && !(t4.ctrlKey || this._map.cooperativeGestures.isBypassed(t4));
            }
            wheel(t4) {
              if (!this.isEnabled()) return;
              if (this._shouldBePrevented(t4)) return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom", t4);
              let e2 = t4.deltaMode === WheelEvent.DOM_DELTA_LINE ? 40 * t4.deltaY : t4.deltaY;
              const i2 = o.now(), a2 = i2 - (this._lastWheelEventTime || 0);
              this._lastWheelEventTime = i2, 0 !== e2 && e2 % cs == 0 ? this._type = "wheel" : 0 !== e2 && Math.abs(e2) < 4 ? this._type = "trackpad" : a2 > 400 ? (this._type = null, this._lastValue = e2, this._timeout = setTimeout(this._onTimeout, 40, t4)) : this._type || (this._type = Math.abs(a2 * e2) < 200 ? "trackpad" : "wheel", this._timeout && (clearTimeout(this._timeout), this._timeout = null, e2 += this._lastValue)), t4.shiftKey && e2 && (e2 /= 4), this._type && (this._lastWheelEvent = t4, this._delta -= e2, this._active || this._start(t4)), t4.preventDefault();
            }
            _start(t4) {
              if (!this._delta) return;
              this._frameId && (this._frameId = null), this._active = true, this.isZooming() || (this._zooming = true), this._finishTimeout && (clearTimeout(this._finishTimeout), delete this._finishTimeout);
              const i2 = r.mousePos(this._map.getCanvas(), t4), a2 = this._tr;
              this._around = i2.y > a2.transform.height / 2 - a2.transform.getHorizon() ? e.N.convert(this._aroundCenter ? a2.center : a2.unproject(i2)) : e.N.convert(a2.center), this._aroundPoint = a2.transform.locationPoint(this._around), this._frameId || (this._frameId = true, this._triggerRenderFrame());
            }
            renderFrame() {
              if (!this._frameId) return;
              if (this._frameId = null, !this.isActive()) return;
              const t4 = this._tr.transform;
              if (0 !== this._delta) {
                const e2 = "wheel" === this._type && Math.abs(this._delta) > cs ? this._wheelZoomRate : this._defaultZoomRate;
                let i3 = 2 / (1 + Math.exp(-Math.abs(this._delta * e2)));
                this._delta < 0 && 0 !== i3 && (i3 = 1 / i3);
                const a3 = "number" == typeof this._targetZoom ? t4.zoomScale(this._targetZoom) : t4.scale;
                this._targetZoom = Math.min(t4.maxZoom, Math.max(t4.minZoom, t4.scaleZoom(a3 * i3))), "wheel" === this._type && (this._startZoom = t4.zoom, this._easing = this._smoothOutEasing(200)), this._delta = 0;
              }
              const i2 = "number" == typeof this._targetZoom ? this._targetZoom : t4.zoom, a2 = this._startZoom, s2 = this._easing;
              let r2, n2 = false;
              const l2 = o.now() - this._lastWheelEventTime;
              if ("wheel" === this._type && a2 && s2 && l2) {
                const t5 = Math.min(l2 / 200, 1), o2 = s2(t5);
                r2 = e.y.number(a2, i2, o2), t5 < 1 ? this._frameId || (this._frameId = true) : n2 = true;
              } else r2 = i2, n2 = true;
              return this._active = true, n2 && (this._active = false, this._finishTimeout = setTimeout(() => {
                this._zooming = false, this._triggerRenderFrame(), delete this._targetZoom, delete this._finishTimeout;
              }, 200)), { noInertia: true, needsRenderFrame: !n2, zoomDelta: r2 - t4.zoom, around: this._aroundPoint, originalEvent: this._lastWheelEvent };
            }
            _smoothOutEasing(t4) {
              let i2 = e.b9;
              if (this._prevEase) {
                const t5 = this._prevEase, a2 = (o.now() - t5.start) / t5.duration, s2 = t5.easing(a2 + 0.01) - t5.easing(a2), r2 = 0.27 / Math.sqrt(s2 * s2 + 1e-4) * 0.01, n2 = Math.sqrt(0.0729 - r2 * r2);
                i2 = e.b8(r2, n2, 0.25, 1);
              }
              return this._prevEase = { start: o.now(), duration: t4, easing: i2 }, i2;
            }
            reset() {
              this._active = false, this._zooming = false, delete this._targetZoom, this._finishTimeout && (clearTimeout(this._finishTimeout), delete this._finishTimeout);
            }
          }
          class ds {
            constructor(t4, e2) {
              this._clickZoom = t4, this._tapZoom = e2;
            }
            enable() {
              this._clickZoom.enable(), this._tapZoom.enable();
            }
            disable() {
              this._clickZoom.disable(), this._tapZoom.disable();
            }
            isEnabled() {
              return this._clickZoom.isEnabled() && this._tapZoom.isEnabled();
            }
            isActive() {
              return this._clickZoom.isActive() || this._tapZoom.isActive();
            }
          }
          class _s {
            constructor(t4) {
              this._tr = new Na(t4), this.reset();
            }
            reset() {
              this._active = false;
            }
            dblclick(t4, e2) {
              return t4.preventDefault(), { cameraAnimation: (i2) => {
                i2.easeTo({ duration: 300, zoom: this._tr.zoom + (t4.shiftKey ? -1 : 1), around: this._tr.unproject(e2) }, { originalEvent: t4 });
              } };
            }
            enable() {
              this._enabled = true;
            }
            disable() {
              this._enabled = false, this.reset();
            }
            isEnabled() {
              return this._enabled;
            }
            isActive() {
              return this._active;
            }
          }
          class ps {
            constructor() {
              this._tap = new qa({ numTouches: 1, numTaps: 1 }), this.reset();
            }
            reset() {
              this._active = false, delete this._swipePoint, delete this._swipeTouch, delete this._tapTime, delete this._tapPoint, this._tap.reset();
            }
            touchstart(t4, e2, i2) {
              if (!this._swipePoint) if (this._tapTime) {
                const a2 = e2[0], s2 = t4.timeStamp - this._tapTime < 500, o2 = this._tapPoint.dist(a2) < 30;
                s2 && o2 ? i2.length > 0 && (this._swipePoint = a2, this._swipeTouch = i2[0].identifier) : this.reset();
              } else this._tap.touchstart(t4, e2, i2);
            }
            touchmove(t4, e2, i2) {
              if (this._tapTime) {
                if (this._swipePoint) {
                  if (i2[0].identifier !== this._swipeTouch) return;
                  const a2 = e2[0], s2 = a2.y - this._swipePoint.y;
                  return this._swipePoint = a2, t4.preventDefault(), this._active = true, { zoomDelta: s2 / 128 };
                }
              } else this._tap.touchmove(t4, e2, i2);
            }
            touchend(t4, e2, i2) {
              if (this._tapTime) this._swipePoint && 0 === i2.length && this.reset();
              else {
                const a2 = this._tap.touchend(t4, e2, i2);
                a2 && (this._tapTime = t4.timeStamp, this._tapPoint = a2);
              }
            }
            touchcancel() {
              this.reset();
            }
            enable() {
              this._enabled = true;
            }
            disable() {
              this._enabled = false, this.reset();
            }
            isEnabled() {
              return this._enabled;
            }
            isActive() {
              return this._active;
            }
          }
          class ms {
            constructor(t4, e2, i2) {
              this._el = t4, this._mousePan = e2, this._touchPan = i2;
            }
            enable(t4) {
              this._inertiaOptions = t4 || {}, this._mousePan.enable(), this._touchPan.enable(), this._el.classList.add("maplibregl-touch-drag-pan");
            }
            disable() {
              this._mousePan.disable(), this._touchPan.disable(), this._el.classList.remove("maplibregl-touch-drag-pan");
            }
            isEnabled() {
              return this._mousePan.isEnabled() && this._touchPan.isEnabled();
            }
            isActive() {
              return this._mousePan.isActive() || this._touchPan.isActive();
            }
          }
          class fs {
            constructor(t4, e2, i2) {
              this._pitchWithRotate = t4.pitchWithRotate, this._mouseRotate = e2, this._mousePitch = i2;
            }
            enable() {
              this._mouseRotate.enable(), this._pitchWithRotate && this._mousePitch.enable();
            }
            disable() {
              this._mouseRotate.disable(), this._mousePitch.disable();
            }
            isEnabled() {
              return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled());
            }
            isActive() {
              return this._mouseRotate.isActive() || this._mousePitch.isActive();
            }
          }
          class gs {
            constructor(t4, e2, i2, a2) {
              this._el = t4, this._touchZoom = e2, this._touchRotate = i2, this._tapDragZoom = a2, this._rotationDisabled = false, this._enabled = true;
            }
            enable(t4) {
              this._touchZoom.enable(t4), this._rotationDisabled || this._touchRotate.enable(t4), this._tapDragZoom.enable(), this._el.classList.add("maplibregl-touch-zoom-rotate");
            }
            disable() {
              this._touchZoom.disable(), this._touchRotate.disable(), this._tapDragZoom.disable(), this._el.classList.remove("maplibregl-touch-zoom-rotate");
            }
            isEnabled() {
              return this._touchZoom.isEnabled() && (this._rotationDisabled || this._touchRotate.isEnabled()) && this._tapDragZoom.isEnabled();
            }
            isActive() {
              return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive();
            }
            disableRotation() {
              this._rotationDisabled = true, this._touchRotate.disable();
            }
            enableRotation() {
              this._rotationDisabled = false, this._touchZoom.isEnabled() && this._touchRotate.enable();
            }
          }
          class vs {
            constructor(t4, e2) {
              this._bypassKey = -1 !== navigator.userAgent.indexOf("Mac") ? "metaKey" : "ctrlKey", this._map = t4, this._options = e2, this._enabled = false;
            }
            isActive() {
              return false;
            }
            reset() {
            }
            _setupUI() {
              if (this._container) return;
              const t4 = this._map.getCanvasContainer();
              t4.classList.add("maplibregl-cooperative-gestures"), this._container = r.create("div", "maplibregl-cooperative-gesture-screen", t4);
              let e2 = this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");
              "metaKey" === this._bypassKey && (e2 = this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));
              const i2 = this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"), a2 = document.createElement("div");
              a2.className = "maplibregl-desktop-message", a2.textContent = e2, this._container.appendChild(a2);
              const s2 = document.createElement("div");
              s2.className = "maplibregl-mobile-message", s2.textContent = i2, this._container.appendChild(s2), this._container.setAttribute("aria-hidden", "true");
            }
            _destroyUI() {
              this._container && (r.remove(this._container), this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")), delete this._container;
            }
            enable() {
              this._setupUI(), this._enabled = true;
            }
            disable() {
              this._enabled = false, this._destroyUI();
            }
            isEnabled() {
              return this._enabled;
            }
            isBypassed(t4) {
              return t4[this._bypassKey];
            }
            notifyGestureBlocked(t4, i2) {
              this._enabled && (this._map.fire(new e.k("cooperativegestureprevented", { gestureType: t4, originalEvent: i2 })), this._container.classList.add("maplibregl-show"), setTimeout(() => {
                this._container.classList.remove("maplibregl-show");
              }, 100));
            }
          }
          const xs = (t4) => t4.zoom || t4.drag || t4.pitch || t4.rotate;
          class ys extends e.k {
          }
          function bs(t4) {
            return t4.panDelta && t4.panDelta.mag() || t4.zoomDelta || t4.bearingDelta || t4.pitchDelta;
          }
          class ws {
            constructor(t4, e2) {
              this.handleWindowEvent = (t5) => {
                this.handleEvent(t5, `${t5.type}Window`);
              }, this.handleEvent = (t5, e3) => {
                if ("blur" === t5.type) return void this.stop(true);
                this._updatingCamera = true;
                const i3 = "renderFrame" === t5.type ? void 0 : t5, a2 = { needsRenderFrame: false }, s2 = {}, o2 = {}, n2 = t5.touches, l2 = n2 ? this._getMapTouches(n2) : void 0, h2 = l2 ? r.touchPos(this._map.getCanvas(), l2) : r.mousePos(this._map.getCanvas(), t5);
                for (const { handlerName: r2, handler: n3, allowed: c3 } of this._handlers) {
                  if (!n3.isEnabled()) continue;
                  let u3;
                  this._blockedByActive(o2, c3, r2) ? n3.reset() : n3[e3 || t5.type] && (u3 = n3[e3 || t5.type](t5, h2, l2), this.mergeHandlerResult(a2, s2, u3, r2, i3), u3 && u3.needsRenderFrame && this._triggerRenderFrame()), (u3 || n3.isActive()) && (o2[r2] = n3);
                }
                const c2 = {};
                for (const t6 in this._previousActiveHandlers) o2[t6] || (c2[t6] = i3);
                this._previousActiveHandlers = o2, (Object.keys(c2).length || bs(a2)) && (this._changes.push([a2, s2, c2]), this._triggerRenderFrame()), (Object.keys(o2).length || bs(a2)) && this._map._stop(true), this._updatingCamera = false;
                const { cameraAnimation: u2 } = a2;
                u2 && (this._inertia.clear(), this._fireEvents({}, {}, true), this._changes = [], u2(this._map));
              }, this._map = t4, this._el = this._map.getCanvasContainer(), this._handlers = [], this._handlersById = {}, this._changes = [], this._inertia = new Ma(t4), this._bearingSnap = e2.bearingSnap, this._previousActiveHandlers = {}, this._eventsInProgress = {}, this._addDefaultHandlers(e2);
              const i2 = this._el;
              this._listeners = [[i2, "touchstart", { passive: true }], [i2, "touchmove", { passive: false }], [i2, "touchend", void 0], [i2, "touchcancel", void 0], [i2, "mousedown", void 0], [i2, "mousemove", void 0], [i2, "mouseup", void 0], [document, "mousemove", { capture: true }], [document, "mouseup", void 0], [i2, "mouseover", void 0], [i2, "mouseout", void 0], [i2, "dblclick", void 0], [i2, "click", void 0], [i2, "keydown", { capture: false }], [i2, "keyup", void 0], [i2, "wheel", { passive: false }], [i2, "contextmenu", void 0], [window, "blur", void 0]];
              for (const [t5, e3, i3] of this._listeners) r.addEventListener(t5, e3, t5 === document ? this.handleWindowEvent : this.handleEvent, i3);
            }
            destroy() {
              for (const [t4, e2, i2] of this._listeners) r.removeEventListener(t4, e2, t4 === document ? this.handleWindowEvent : this.handleEvent, i2);
            }
            _addDefaultHandlers(t4) {
              const e2 = this._map, i2 = e2.getCanvasContainer();
              this._add("mapEvent", new Ba(e2, t4));
              const a2 = e2.boxZoom = new Ua(e2, t4);
              this._add("boxZoom", a2), t4.interactive && t4.boxZoom && a2.enable();
              const s2 = e2.cooperativeGestures = new vs(e2, t4.cooperativeGestures);
              this._add("cooperativeGestures", s2), t4.cooperativeGestures && s2.enable();
              const o2 = new Va(e2), n2 = new _s(e2);
              e2.doubleClickZoom = new ds(n2, o2), this._add("tapZoom", o2), this._add("clickZoom", n2), t4.interactive && t4.doubleClickZoom && e2.doubleClickZoom.enable();
              const l2 = new ps();
              this._add("tapDragZoom", l2);
              const h2 = e2.touchPitch = new rs(e2);
              this._add("touchPitch", h2), t4.interactive && t4.touchPitch && e2.touchPitch.enable(t4.touchPitch);
              const c2 = Ka(t4), u2 = Ja(t4);
              e2.dragRotate = new fs(t4, c2, u2), this._add("mouseRotate", c2, ["mousePitch"]), this._add("mousePitch", u2, ["mouseRotate"]), t4.interactive && t4.dragRotate && e2.dragRotate.enable();
              const d2 = (({ enable: t5, clickTolerance: e3 }) => {
                const i3 = new Wa({ checkCorrectEvent: (t6) => 0 === r.mouseButton(t6) && !t6.ctrlKey });
                return new Ga({ clickTolerance: e3, move: (t6, e4) => ({ around: e4, panDelta: e4.sub(t6) }), activateOnStart: true, moveStateManager: i3, enable: t5, assignEvents: Xa });
              })(t4), _2 = new Ya(t4, e2);
              e2.dragPan = new ms(i2, d2, _2), this._add("mousePan", d2), this._add("touchPan", _2, ["touchZoom", "touchRotate"]), t4.interactive && t4.dragPan && e2.dragPan.enable(t4.dragPan);
              const p2 = new ss(), m2 = new is();
              e2.touchZoomRotate = new gs(i2, m2, p2, l2), this._add("touchRotate", p2, ["touchPan", "touchZoom"]), this._add("touchZoom", m2, ["touchPan", "touchRotate"]), t4.interactive && t4.touchZoomRotate && e2.touchZoomRotate.enable(t4.touchZoomRotate);
              const f2 = e2.scrollZoom = new us(e2, () => this._triggerRenderFrame());
              this._add("scrollZoom", f2, ["mousePan"]), t4.interactive && t4.scrollZoom && e2.scrollZoom.enable(t4.scrollZoom);
              const g2 = e2.keyboard = new ls(e2);
              this._add("keyboard", g2), t4.interactive && t4.keyboard && e2.keyboard.enable(), this._add("blockableMapEvent", new Oa(e2));
            }
            _add(t4, e2, i2) {
              this._handlers.push({ handlerName: t4, handler: e2, allowed: i2 }), this._handlersById[t4] = e2;
            }
            stop(t4) {
              if (!this._updatingCamera) {
                for (const { handler: t5 } of this._handlers) t5.reset();
                this._inertia.clear(), this._fireEvents({}, {}, t4), this._changes = [];
              }
            }
            isActive() {
              for (const { handler: t4 } of this._handlers) if (t4.isActive()) return true;
              return false;
            }
            isZooming() {
              return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();
            }
            isRotating() {
              return !!this._eventsInProgress.rotate;
            }
            isMoving() {
              return Boolean(xs(this._eventsInProgress)) || this.isZooming();
            }
            _blockedByActive(t4, e2, i2) {
              for (const a2 in t4) if (a2 !== i2 && (!e2 || e2.indexOf(a2) < 0)) return true;
              return false;
            }
            _getMapTouches(t4) {
              const e2 = [];
              for (const i2 of t4) this._el.contains(i2.target) && e2.push(i2);
              return e2;
            }
            mergeHandlerResult(t4, i2, a2, s2, o2) {
              if (!a2) return;
              e.e(t4, a2);
              const r2 = { handlerName: s2, originalEvent: a2.originalEvent || o2 };
              void 0 !== a2.zoomDelta && (i2.zoom = r2), void 0 !== a2.panDelta && (i2.drag = r2), void 0 !== a2.pitchDelta && (i2.pitch = r2), void 0 !== a2.bearingDelta && (i2.rotate = r2);
            }
            _applyChanges() {
              const t4 = {}, i2 = {}, a2 = {};
              for (const [s2, o2, r2] of this._changes) s2.panDelta && (t4.panDelta = (t4.panDelta || new e.P(0, 0))._add(s2.panDelta)), s2.zoomDelta && (t4.zoomDelta = (t4.zoomDelta || 0) + s2.zoomDelta), s2.bearingDelta && (t4.bearingDelta = (t4.bearingDelta || 0) + s2.bearingDelta), s2.pitchDelta && (t4.pitchDelta = (t4.pitchDelta || 0) + s2.pitchDelta), void 0 !== s2.around && (t4.around = s2.around), void 0 !== s2.pinchAround && (t4.pinchAround = s2.pinchAround), s2.noInertia && (t4.noInertia = s2.noInertia), e.e(i2, o2), e.e(a2, r2);
              this._updateMapTransform(t4, i2, a2), this._changes = [];
            }
            _updateMapTransform(t4, e2, i2) {
              const a2 = this._map, s2 = a2._getTransformForUpdate(), o2 = a2.terrain;
              if (!(bs(t4) || o2 && this._terrainMovement)) return this._fireEvents(e2, i2, true);
              let { panDelta: r2, zoomDelta: n2, bearingDelta: l2, pitchDelta: h2, around: c2, pinchAround: u2 } = t4;
              void 0 !== u2 && (c2 = u2), a2._stop(true), c2 = c2 || a2.transform.centerPoint;
              const d2 = s2.pointLocation(r2 ? c2.sub(r2) : c2);
              l2 && (s2.bearing += l2), h2 && (s2.pitch += h2), n2 && (s2.zoom += n2), o2 ? this._terrainMovement || !e2.drag && !e2.zoom ? e2.drag && this._terrainMovement ? s2.center = s2.pointLocation(s2.centerPoint.sub(r2)) : s2.setLocationAtPoint(d2, c2) : (this._terrainMovement = true, this._map._elevationFreeze = true, s2.setLocationAtPoint(d2, c2)) : s2.setLocationAtPoint(d2, c2), a2._applyUpdatedTransform(s2), this._map._update(), t4.noInertia || this._inertia.record(t4), this._fireEvents(e2, i2, true);
            }
            _fireEvents(t4, i2, a2) {
              const s2 = xs(this._eventsInProgress), r2 = xs(t4), n2 = {};
              for (const e2 in t4) {
                const { originalEvent: i3 } = t4[e2];
                this._eventsInProgress[e2] || (n2[`${e2}start`] = i3), this._eventsInProgress[e2] = t4[e2];
              }
              !s2 && r2 && this._fireEvent("movestart", r2.originalEvent);
              for (const t5 in n2) this._fireEvent(t5, n2[t5]);
              r2 && this._fireEvent("move", r2.originalEvent);
              for (const e2 in t4) {
                const { originalEvent: i3 } = t4[e2];
                this._fireEvent(e2, i3);
              }
              const l2 = {};
              let h2;
              for (const t5 in this._eventsInProgress) {
                const { handlerName: e2, originalEvent: a3 } = this._eventsInProgress[t5];
                this._handlersById[e2].isActive() || (delete this._eventsInProgress[t5], h2 = i2[e2] || a3, l2[`${t5}end`] = h2);
              }
              for (const t5 in l2) this._fireEvent(t5, l2[t5]);
              const c2 = xs(this._eventsInProgress), u2 = (s2 || r2) && !c2;
              if (u2 && this._terrainMovement) {
                this._map._elevationFreeze = false, this._terrainMovement = false;
                const t5 = this._map._getTransformForUpdate();
                t5.recalculateZoom(this._map.terrain), this._map._applyUpdatedTransform(t5);
              }
              if (a2 && u2) {
                this._updatingCamera = true;
                const t5 = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions), i3 = (t6) => 0 !== t6 && -this._bearingSnap < t6 && t6 < this._bearingSnap;
                !t5 || !t5.essential && o.prefersReducedMotion ? (this._map.fire(new e.k("moveend", { originalEvent: h2 })), i3(this._map.getBearing()) && this._map.resetNorth()) : (i3(t5.bearing || this._map.getBearing()) && (t5.bearing = 0), t5.freezeElevation = true, this._map.easeTo(t5, { originalEvent: h2 })), this._updatingCamera = false;
              }
            }
            _fireEvent(t4, i2) {
              this._map.fire(new e.k(t4, i2 ? { originalEvent: i2 } : {}));
            }
            _requestFrame() {
              return this._map.triggerRepaint(), this._map._renderTaskQueue.add((t4) => {
                delete this._frameId, this.handleEvent(new ys("renderFrame", { timeStamp: t4 })), this._applyChanges();
              });
            }
            _triggerRenderFrame() {
              void 0 === this._frameId && (this._frameId = this._requestFrame());
            }
          }
          class Ts extends e.E {
            constructor(t4, e2) {
              super(), this._renderFrameCallback = () => {
                const t5 = Math.min((o.now() - this._easeStart) / this._easeOptions.duration, 1);
                this._onEaseFrame(this._easeOptions.easing(t5)), t5 < 1 && this._easeFrameId ? this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback) : this.stop();
              }, this._moving = false, this._zooming = false, this.transform = t4, this._bearingSnap = e2.bearingSnap, this.on("moveend", () => {
                delete this._requestedCameraState;
              });
            }
            getCenter() {
              return new e.N(this.transform.center.lng, this.transform.center.lat);
            }
            setCenter(t4, e2) {
              return this.jumpTo({ center: t4 }, e2);
            }
            panBy(t4, i2, a2) {
              return t4 = e.P.convert(t4).mult(-1), this.panTo(this.transform.center, e.e({ offset: t4 }, i2), a2);
            }
            panTo(t4, i2, a2) {
              return this.easeTo(e.e({ center: t4 }, i2), a2);
            }
            getZoom() {
              return this.transform.zoom;
            }
            setZoom(t4, e2) {
              return this.jumpTo({ zoom: t4 }, e2), this;
            }
            zoomTo(t4, i2, a2) {
              return this.easeTo(e.e({ zoom: t4 }, i2), a2);
            }
            zoomIn(t4, e2) {
              return this.zoomTo(this.getZoom() + 1, t4, e2), this;
            }
            zoomOut(t4, e2) {
              return this.zoomTo(this.getZoom() - 1, t4, e2), this;
            }
            getBearing() {
              return this.transform.bearing;
            }
            setBearing(t4, e2) {
              return this.jumpTo({ bearing: t4 }, e2), this;
            }
            getPadding() {
              return this.transform.padding;
            }
            setPadding(t4, e2) {
              return this.jumpTo({ padding: t4 }, e2), this;
            }
            rotateTo(t4, i2, a2) {
              return this.easeTo(e.e({ bearing: t4 }, i2), a2);
            }
            resetNorth(t4, i2) {
              return this.rotateTo(0, e.e({ duration: 1e3 }, t4), i2), this;
            }
            resetNorthPitch(t4, i2) {
              return this.easeTo(e.e({ bearing: 0, pitch: 0, duration: 1e3 }, t4), i2), this;
            }
            snapToNorth(t4, e2) {
              return Math.abs(this.getBearing()) < this._bearingSnap ? this.resetNorth(t4, e2) : this;
            }
            getPitch() {
              return this.transform.pitch;
            }
            setPitch(t4, e2) {
              return this.jumpTo({ pitch: t4 }, e2), this;
            }
            cameraForBounds(t4, e2) {
              t4 = H.convert(t4).adjustAntiMeridian();
              const i2 = e2 && e2.bearing || 0;
              return this._cameraForBoxAndBearing(t4.getNorthWest(), t4.getSouthEast(), i2, e2);
            }
            _cameraForBoxAndBearing(t4, i2, a2, s2) {
              const o2 = { top: 0, bottom: 0, right: 0, left: 0 };
              if ("number" == typeof (s2 = e.e({ padding: o2, offset: [0, 0], maxZoom: this.transform.maxZoom }, s2)).padding) {
                const t5 = s2.padding;
                s2.padding = { top: t5, bottom: t5, right: t5, left: t5 };
              }
              s2.padding = e.e(o2, s2.padding);
              const r2 = this.transform, n2 = r2.padding, l2 = new H(t4, i2), h2 = r2.project(l2.getNorthWest()), c2 = r2.project(l2.getNorthEast()), u2 = r2.project(l2.getSouthEast()), d2 = r2.project(l2.getSouthWest()), _2 = e.ba(-a2), p2 = h2.rotate(_2), m2 = c2.rotate(_2), f2 = u2.rotate(_2), g2 = d2.rotate(_2), v2 = new e.P(Math.max(p2.x, m2.x, g2.x, f2.x), Math.max(p2.y, m2.y, g2.y, f2.y)), x2 = new e.P(Math.min(p2.x, m2.x, g2.x, f2.x), Math.min(p2.y, m2.y, g2.y, f2.y)), y2 = v2.sub(x2), b2 = (r2.width - (n2.left + n2.right + s2.padding.left + s2.padding.right)) / y2.x, w2 = (r2.height - (n2.top + n2.bottom + s2.padding.top + s2.padding.bottom)) / y2.y;
              if (w2 < 0 || b2 < 0) return void e.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");
              const T2 = Math.min(r2.scaleZoom(r2.scale * Math.min(b2, w2)), s2.maxZoom), I2 = e.P.convert(s2.offset), E3 = new e.P((s2.padding.left - s2.padding.right) / 2, (s2.padding.top - s2.padding.bottom) / 2).rotate(e.ba(a2)), P2 = I2.add(E3).mult(r2.scale / r2.zoomScale(T2));
              return { center: r2.unproject(h2.add(u2).div(2).sub(P2)), zoom: T2, bearing: a2 };
            }
            fitBounds(t4, e2, i2) {
              return this._fitInternal(this.cameraForBounds(t4, e2), e2, i2);
            }
            fitScreenCoordinates(t4, i2, a2, s2, o2) {
              return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(e.P.convert(t4)), this.transform.pointLocation(e.P.convert(i2)), a2, s2), s2, o2);
            }
            _fitInternal(t4, i2, a2) {
              return t4 ? (delete (i2 = e.e(t4, i2)).padding, i2.linear ? this.easeTo(i2, a2) : this.flyTo(i2, a2)) : this;
            }
            jumpTo(t4, i2) {
              this.stop();
              const a2 = this._getTransformForUpdate();
              let s2 = false, o2 = false, r2 = false;
              return "zoom" in t4 && a2.zoom !== +t4.zoom && (s2 = true, a2.zoom = +t4.zoom), void 0 !== t4.center && (a2.center = e.N.convert(t4.center)), "bearing" in t4 && a2.bearing !== +t4.bearing && (o2 = true, a2.bearing = +t4.bearing), "pitch" in t4 && a2.pitch !== +t4.pitch && (r2 = true, a2.pitch = +t4.pitch), null == t4.padding || a2.isPaddingEqual(t4.padding) || (a2.padding = t4.padding), this._applyUpdatedTransform(a2), this.fire(new e.k("movestart", i2)).fire(new e.k("move", i2)), s2 && this.fire(new e.k("zoomstart", i2)).fire(new e.k("zoom", i2)).fire(new e.k("zoomend", i2)), o2 && this.fire(new e.k("rotatestart", i2)).fire(new e.k("rotate", i2)).fire(new e.k("rotateend", i2)), r2 && this.fire(new e.k("pitchstart", i2)).fire(new e.k("pitch", i2)).fire(new e.k("pitchend", i2)), this.fire(new e.k("moveend", i2));
            }
            calculateCameraOptionsFromTo(t4, i2, a2, s2 = 0) {
              const o2 = e.Z.fromLngLat(t4, i2), r2 = e.Z.fromLngLat(a2, s2), n2 = r2.x - o2.x, l2 = r2.y - o2.y, h2 = r2.z - o2.z, c2 = Math.hypot(n2, l2, h2);
              if (0 === c2) throw new Error("Can't calculate camera options with same From and To");
              const u2 = Math.hypot(n2, l2), d2 = this.transform.scaleZoom(this.transform.cameraToCenterDistance / c2 / this.transform.tileSize), _2 = 180 * Math.atan2(n2, -l2) / Math.PI;
              let p2 = 180 * Math.acos(u2 / c2) / Math.PI;
              return p2 = h2 < 0 ? 90 - p2 : 90 + p2, { center: r2.toLngLat(), zoom: d2, pitch: p2, bearing: _2 };
            }
            easeTo(t4, i2) {
              var a2;
              this._stop(false, t4.easeId), (false === (t4 = e.e({ offset: [0, 0], duration: 500, easing: e.b9 }, t4)).animate || !t4.essential && o.prefersReducedMotion) && (t4.duration = 0);
              const s2 = this._getTransformForUpdate(), r2 = s2.zoom, n2 = s2.bearing, l2 = s2.pitch, h2 = s2.padding, c2 = "bearing" in t4 ? this._normalizeBearing(t4.bearing, n2) : n2, u2 = "pitch" in t4 ? +t4.pitch : l2, d2 = "padding" in t4 ? t4.padding : s2.padding, _2 = e.P.convert(t4.offset);
              let p2 = s2.centerPoint.add(_2);
              const m2 = s2.pointLocation(p2), { center: f2, zoom: g2 } = s2.getConstrained(e.N.convert(t4.center || m2), null !== (a2 = t4.zoom) && void 0 !== a2 ? a2 : r2);
              this._normalizeCenter(f2, s2);
              const v2 = s2.project(m2), x2 = s2.project(f2).sub(v2), y2 = s2.zoomScale(g2 - r2);
              let b2, w2;
              t4.around && (b2 = e.N.convert(t4.around), w2 = s2.locationPoint(b2));
              const T2 = { moving: this._moving, zooming: this._zooming, rotating: this._rotating, pitching: this._pitching };
              return this._zooming = this._zooming || g2 !== r2, this._rotating = this._rotating || n2 !== c2, this._pitching = this._pitching || u2 !== l2, this._padding = !s2.isPaddingEqual(d2), this._easeId = t4.easeId, this._prepareEase(i2, t4.noMoveStart, T2), this.terrain && this._prepareElevation(f2), this._ease((a3) => {
                if (this._zooming && (s2.zoom = e.y.number(r2, g2, a3)), this._rotating && (s2.bearing = e.y.number(n2, c2, a3)), this._pitching && (s2.pitch = e.y.number(l2, u2, a3)), this._padding && (s2.interpolatePadding(h2, d2, a3), p2 = s2.centerPoint.add(_2)), this.terrain && !t4.freezeElevation && this._updateElevation(a3), b2) s2.setLocationAtPoint(b2, w2);
                else {
                  const t5 = s2.zoomScale(s2.zoom - r2), e2 = g2 > r2 ? Math.min(2, y2) : Math.max(0.5, y2), i3 = Math.pow(e2, 1 - a3), o2 = s2.unproject(v2.add(x2.mult(a3 * i3)).mult(t5));
                  s2.setLocationAtPoint(s2.renderWorldCopies ? o2.wrap() : o2, p2);
                }
                this._applyUpdatedTransform(s2), this._fireMoveEvents(i2);
              }, (e2) => {
                this.terrain && t4.freezeElevation && this._finalizeElevation(), this._afterEase(i2, e2);
              }, t4), this;
            }
            _prepareEase(t4, i2, a2 = {}) {
              this._moving = true, i2 || a2.moving || this.fire(new e.k("movestart", t4)), this._zooming && !a2.zooming && this.fire(new e.k("zoomstart", t4)), this._rotating && !a2.rotating && this.fire(new e.k("rotatestart", t4)), this._pitching && !a2.pitching && this.fire(new e.k("pitchstart", t4));
            }
            _prepareElevation(t4) {
              this._elevationCenter = t4, this._elevationStart = this.transform.elevation, this._elevationTarget = this.terrain.getElevationForLngLatZoom(t4, this.transform.tileZoom), this._elevationFreeze = true;
            }
            _updateElevation(t4) {
              this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom);
              const i2 = this.terrain.getElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom);
              if (t4 < 1 && i2 !== this._elevationTarget) {
                const e2 = this._elevationTarget - this._elevationStart;
                this._elevationStart += t4 * (e2 - (i2 - (e2 * t4 + this._elevationStart)) / (1 - t4)), this._elevationTarget = i2;
              }
              this.transform.elevation = e.y.number(this._elevationStart, this._elevationTarget, t4);
            }
            _finalizeElevation() {
              this._elevationFreeze = false, this.transform.recalculateZoom(this.terrain);
            }
            _getTransformForUpdate() {
              return this.transformCameraUpdate || this.terrain ? (this._requestedCameraState || (this._requestedCameraState = this.transform.clone()), this._requestedCameraState) : this.transform;
            }
            _elevateCameraIfInsideTerrain(t4) {
              const e2 = t4.getCameraPosition(), i2 = this.terrain.getElevationForLngLatZoom(e2.lngLat, t4.zoom);
              if (e2.altitude < i2) {
                const a2 = this.calculateCameraOptionsFromTo(e2.lngLat, i2, t4.center, t4.elevation);
                return { pitch: a2.pitch, zoom: a2.zoom };
              }
              return {};
            }
            _applyUpdatedTransform(t4) {
              const e2 = [];
              if (this.terrain && e2.push((t5) => this._elevateCameraIfInsideTerrain(t5)), this.transformCameraUpdate && e2.push((t5) => this.transformCameraUpdate(t5)), !e2.length) return;
              const i2 = t4.clone();
              for (const t5 of e2) {
                const e3 = i2.clone(), { center: a2, zoom: s2, pitch: o2, bearing: r2, elevation: n2 } = t5(e3);
                a2 && (e3.center = a2), void 0 !== s2 && (e3.zoom = s2), void 0 !== o2 && (e3.pitch = o2), void 0 !== r2 && (e3.bearing = r2), void 0 !== n2 && (e3.elevation = n2), i2.apply(e3);
              }
              this.transform.apply(i2);
            }
            _fireMoveEvents(t4) {
              this.fire(new e.k("move", t4)), this._zooming && this.fire(new e.k("zoom", t4)), this._rotating && this.fire(new e.k("rotate", t4)), this._pitching && this.fire(new e.k("pitch", t4));
            }
            _afterEase(t4, i2) {
              if (this._easeId && i2 && this._easeId === i2) return;
              delete this._easeId;
              const a2 = this._zooming, s2 = this._rotating, o2 = this._pitching;
              this._moving = false, this._zooming = false, this._rotating = false, this._pitching = false, this._padding = false, a2 && this.fire(new e.k("zoomend", t4)), s2 && this.fire(new e.k("rotateend", t4)), o2 && this.fire(new e.k("pitchend", t4)), this.fire(new e.k("moveend", t4));
            }
            flyTo(t4, i2) {
              var a2;
              if (!t4.essential && o.prefersReducedMotion) {
                const a3 = e.M(t4, ["center", "zoom", "bearing", "pitch", "around"]);
                return this.jumpTo(a3, i2);
              }
              this.stop(), t4 = e.e({ offset: [0, 0], speed: 1.2, curve: 1.42, easing: e.b9 }, t4);
              const s2 = this._getTransformForUpdate(), r2 = s2.zoom, n2 = s2.bearing, l2 = s2.pitch, h2 = s2.padding, c2 = "bearing" in t4 ? this._normalizeBearing(t4.bearing, n2) : n2, u2 = "pitch" in t4 ? +t4.pitch : l2, d2 = "padding" in t4 ? t4.padding : s2.padding, _2 = e.P.convert(t4.offset);
              let p2 = s2.centerPoint.add(_2);
              const m2 = s2.pointLocation(p2), { center: f2, zoom: g2 } = s2.getConstrained(e.N.convert(t4.center || m2), null !== (a2 = t4.zoom) && void 0 !== a2 ? a2 : r2);
              this._normalizeCenter(f2, s2);
              const v2 = s2.zoomScale(g2 - r2), x2 = s2.project(m2), y2 = s2.project(f2).sub(x2);
              let b2 = t4.curve;
              const w2 = Math.max(s2.width, s2.height), T2 = w2 / v2, I2 = y2.mag();
              if ("minZoom" in t4) {
                const i3 = e.ac(Math.min(t4.minZoom, r2, g2), s2.minZoom, s2.maxZoom), a3 = w2 / s2.zoomScale(i3 - r2);
                b2 = Math.sqrt(a3 / I2 * 2);
              }
              const E3 = b2 * b2;
              function P2(t5) {
                const e2 = (T2 * T2 - w2 * w2 + (t5 ? -1 : 1) * E3 * E3 * I2 * I2) / (2 * (t5 ? T2 : w2) * E3 * I2);
                return Math.log(Math.sqrt(e2 * e2 + 1) - e2);
              }
              function C3(t5) {
                return (Math.exp(t5) - Math.exp(-t5)) / 2;
              }
              function S2(t5) {
                return (Math.exp(t5) + Math.exp(-t5)) / 2;
              }
              const z2 = P2(false);
              let D3 = function(t5) {
                return S2(z2) / S2(z2 + b2 * t5);
              }, M2 = function(t5) {
                return w2 * ((S2(z2) * (C3(e2 = z2 + b2 * t5) / S2(e2)) - C3(z2)) / E3) / I2;
                var e2;
              }, A3 = (P2(true) - z2) / b2;
              if (Math.abs(I2) < 1e-6 || !isFinite(A3)) {
                if (Math.abs(w2 - T2) < 1e-6) return this.easeTo(t4, i2);
                const e2 = T2 < w2 ? -1 : 1;
                A3 = Math.abs(Math.log(T2 / w2)) / b2, M2 = () => 0, D3 = (t5) => Math.exp(e2 * b2 * t5);
              }
              return t4.duration = "duration" in t4 ? +t4.duration : 1e3 * A3 / ("screenSpeed" in t4 ? +t4.screenSpeed / b2 : +t4.speed), t4.maxDuration && t4.duration > t4.maxDuration && (t4.duration = 0), this._zooming = true, this._rotating = n2 !== c2, this._pitching = u2 !== l2, this._padding = !s2.isPaddingEqual(d2), this._prepareEase(i2, false), this.terrain && this._prepareElevation(f2), this._ease((a3) => {
                const o2 = a3 * A3, m3 = 1 / D3(o2);
                s2.zoom = 1 === a3 ? g2 : r2 + s2.scaleZoom(m3), this._rotating && (s2.bearing = e.y.number(n2, c2, a3)), this._pitching && (s2.pitch = e.y.number(l2, u2, a3)), this._padding && (s2.interpolatePadding(h2, d2, a3), p2 = s2.centerPoint.add(_2)), this.terrain && !t4.freezeElevation && this._updateElevation(a3);
                const v3 = 1 === a3 ? f2 : s2.unproject(x2.add(y2.mult(M2(o2))).mult(m3));
                s2.setLocationAtPoint(s2.renderWorldCopies ? v3.wrap() : v3, p2), this._applyUpdatedTransform(s2), this._fireMoveEvents(i2);
              }, () => {
                this.terrain && t4.freezeElevation && this._finalizeElevation(), this._afterEase(i2);
              }, t4), this;
            }
            isEasing() {
              return !!this._easeFrameId;
            }
            stop() {
              return this._stop();
            }
            _stop(t4, e2) {
              var i2;
              if (this._easeFrameId && (this._cancelRenderFrame(this._easeFrameId), delete this._easeFrameId, delete this._onEaseFrame), this._onEaseEnd) {
                const t5 = this._onEaseEnd;
                delete this._onEaseEnd, t5.call(this, e2);
              }
              return t4 || null === (i2 = this.handlers) || void 0 === i2 || i2.stop(false), this;
            }
            _ease(t4, e2, i2) {
              false === i2.animate || 0 === i2.duration ? (t4(1), e2()) : (this._easeStart = o.now(), this._easeOptions = i2, this._onEaseFrame = t4, this._onEaseEnd = e2, this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback));
            }
            _normalizeBearing(t4, i2) {
              t4 = e.b3(t4, -180, 180);
              const a2 = Math.abs(t4 - i2);
              return Math.abs(t4 - 360 - i2) < a2 && (t4 -= 360), Math.abs(t4 + 360 - i2) < a2 && (t4 += 360), t4;
            }
            _normalizeCenter(t4, e2) {
              if (!e2.renderWorldCopies || e2.lngRange) return;
              const i2 = t4.lng - e2.center.lng;
              t4.lng += i2 > 180 ? -360 : i2 < -180 ? 360 : 0;
            }
            queryTerrainElevation(t4) {
              return this.terrain ? this.terrain.getElevationForLngLatZoom(e.N.convert(t4), this.transform.tileZoom) - this.transform.elevation : null;
            }
          }
          const Is = { compact: true, customAttribution: '<a href="https://maplibre.org/" target="_blank">MapLibre</a>' };
          class Es {
            constructor(t4 = Is) {
              this._toggleAttribution = () => {
                this._container.classList.contains("maplibregl-compact") && (this._container.classList.contains("maplibregl-compact-show") ? (this._container.setAttribute("open", ""), this._container.classList.remove("maplibregl-compact-show")) : (this._container.classList.add("maplibregl-compact-show"), this._container.removeAttribute("open")));
              }, this._updateData = (t5) => {
                !t5 || "metadata" !== t5.sourceDataType && "visibility" !== t5.sourceDataType && "style" !== t5.dataType && "terrain" !== t5.type || this._updateAttributions();
              }, this._updateCompact = () => {
                this._map.getCanvasContainer().offsetWidth <= 640 || this._compact ? false === this._compact ? this._container.setAttribute("open", "") : this._container.classList.contains("maplibregl-compact") || this._container.classList.contains("maplibregl-attrib-empty") || (this._container.setAttribute("open", ""), this._container.classList.add("maplibregl-compact", "maplibregl-compact-show")) : (this._container.setAttribute("open", ""), this._container.classList.contains("maplibregl-compact") && this._container.classList.remove("maplibregl-compact", "maplibregl-compact-show"));
              }, this._updateCompactMinimize = () => {
                this._container.classList.contains("maplibregl-compact") && this._container.classList.contains("maplibregl-compact-show") && this._container.classList.remove("maplibregl-compact-show");
              }, this.options = t4;
            }
            getDefaultPosition() {
              return "bottom-right";
            }
            onAdd(t4) {
              return this._map = t4, this._compact = this.options.compact, this._container = r.create("details", "maplibregl-ctrl maplibregl-ctrl-attrib"), this._compactButton = r.create("summary", "maplibregl-ctrl-attrib-button", this._container), this._compactButton.addEventListener("click", this._toggleAttribution), this._setElementTitle(this._compactButton, "ToggleAttribution"), this._innerContainer = r.create("div", "maplibregl-ctrl-attrib-inner", this._container), this._updateAttributions(), this._updateCompact(), this._map.on("styledata", this._updateData), this._map.on("sourcedata", this._updateData), this._map.on("terrain", this._updateData), this._map.on("resize", this._updateCompact), this._map.on("drag", this._updateCompactMinimize), this._container;
            }
            onRemove() {
              r.remove(this._container), this._map.off("styledata", this._updateData), this._map.off("sourcedata", this._updateData), this._map.off("terrain", this._updateData), this._map.off("resize", this._updateCompact), this._map.off("drag", this._updateCompactMinimize), this._map = void 0, this._compact = void 0, this._attribHTML = void 0;
            }
            _setElementTitle(t4, e2) {
              const i2 = this._map._getUIString(`AttributionControl.${e2}`);
              t4.title = i2, t4.setAttribute("aria-label", i2);
            }
            _updateAttributions() {
              if (!this._map.style) return;
              let t4 = [];
              if (this.options.customAttribution && (Array.isArray(this.options.customAttribution) ? t4 = t4.concat(this.options.customAttribution.map((t5) => "string" != typeof t5 ? "" : t5)) : "string" == typeof this.options.customAttribution && t4.push(this.options.customAttribution)), this._map.style.stylesheet) {
                const t5 = this._map.style.stylesheet;
                this.styleOwner = t5.owner, this.styleId = t5.id;
              }
              const e2 = this._map.style.sourceCaches;
              for (const i3 in e2) {
                const a2 = e2[i3];
                if (a2.used || a2.usedForTerrain) {
                  const e3 = a2.getSource();
                  e3.attribution && t4.indexOf(e3.attribution) < 0 && t4.push(e3.attribution);
                }
              }
              t4 = t4.filter((t5) => String(t5).trim()), t4.sort((t5, e3) => t5.length - e3.length), t4 = t4.filter((e3, i3) => {
                for (let a2 = i3 + 1; a2 < t4.length; a2++) if (t4[a2].indexOf(e3) >= 0) return false;
                return true;
              });
              const i2 = t4.join(" | ");
              i2 !== this._attribHTML && (this._attribHTML = i2, t4.length ? (this._innerContainer.innerHTML = i2, this._container.classList.remove("maplibregl-attrib-empty")) : this._container.classList.add("maplibregl-attrib-empty"), this._updateCompact(), this._editLink = null);
            }
          }
          class Ps {
            constructor(t4 = {}) {
              this._updateCompact = () => {
                const t5 = this._container.children;
                if (t5.length) {
                  const e2 = t5[0];
                  this._map.getCanvasContainer().offsetWidth <= 640 || this._compact ? false !== this._compact && e2.classList.add("maplibregl-compact") : e2.classList.remove("maplibregl-compact");
                }
              }, this.options = t4;
            }
            getDefaultPosition() {
              return "bottom-left";
            }
            onAdd(t4) {
              this._map = t4, this._compact = this.options && this.options.compact, this._container = r.create("div", "maplibregl-ctrl");
              const e2 = r.create("a", "maplibregl-ctrl-logo");
              return e2.target = "_blank", e2.rel = "noopener nofollow", e2.href = "https://maplibre.org/", e2.setAttribute("aria-label", this._map._getUIString("LogoControl.Title")), e2.setAttribute("rel", "noopener nofollow"), this._container.appendChild(e2), this._container.style.display = "block", this._map.on("resize", this._updateCompact), this._updateCompact(), this._container;
            }
            onRemove() {
              r.remove(this._container), this._map.off("resize", this._updateCompact), this._map = void 0, this._compact = void 0;
            }
          }
          class Cs {
            constructor() {
              this._queue = [], this._id = 0, this._cleared = false, this._currentlyRunning = false;
            }
            add(t4) {
              const e2 = ++this._id;
              return this._queue.push({ callback: t4, id: e2, cancelled: false }), e2;
            }
            remove(t4) {
              const e2 = this._currentlyRunning, i2 = e2 ? this._queue.concat(e2) : this._queue;
              for (const e3 of i2) if (e3.id === t4) return void (e3.cancelled = true);
            }
            run(t4 = 0) {
              if (this._currentlyRunning) throw new Error("Attempting to run(), but is already running.");
              const e2 = this._currentlyRunning = this._queue;
              this._queue = [];
              for (const i2 of e2) if (!i2.cancelled && (i2.callback(t4), this._cleared)) break;
              this._cleared = false, this._currentlyRunning = false;
            }
            clear() {
              this._currentlyRunning && (this._cleared = true), this._queue = [];
            }
          }
          var Ss = e.Y([{ name: "a_pos3d", type: "Int16", components: 3 }]);
          class zs extends e.E {
            constructor(t4) {
              super(), this.sourceCache = t4, this._tiles = {}, this._renderableTilesKeys = [], this._sourceTileCache = {}, this.minzoom = 0, this.maxzoom = 22, this.tileSize = 512, this.deltaZoom = 1, t4.usedForTerrain = true, t4.tileSize = this.tileSize * 2 ** this.deltaZoom;
            }
            destruct() {
              this.sourceCache.usedForTerrain = false, this.sourceCache.tileSize = null;
            }
            update(t4, i2) {
              this.sourceCache.update(t4, i2), this._renderableTilesKeys = [];
              const a2 = {};
              for (const s2 of t4.coveringTiles({ tileSize: this.tileSize, minzoom: this.minzoom, maxzoom: this.maxzoom, reparseOverscaled: false, terrain: i2 })) a2[s2.key] = true, this._renderableTilesKeys.push(s2.key), this._tiles[s2.key] || (s2.posMatrix = new Float64Array(16), e.aP(s2.posMatrix, 0, e.X, 0, e.X, 0, 1), this._tiles[s2.key] = new lt(s2, this.tileSize));
              for (const t5 in this._tiles) a2[t5] || delete this._tiles[t5];
            }
            freeRtt(t4) {
              for (const e2 in this._tiles) {
                const i2 = this._tiles[e2];
                (!t4 || i2.tileID.equals(t4) || i2.tileID.isChildOf(t4) || t4.isChildOf(i2.tileID)) && (i2.rtt = []);
              }
            }
            getRenderableTiles() {
              return this._renderableTilesKeys.map((t4) => this.getTileByID(t4));
            }
            getTileByID(t4) {
              return this._tiles[t4];
            }
            getTerrainCoords(t4) {
              const i2 = {};
              for (const a2 of this._renderableTilesKeys) {
                const s2 = this._tiles[a2].tileID;
                if (s2.canonical.equals(t4.canonical)) {
                  const s3 = t4.clone();
                  s3.posMatrix = new Float64Array(16), e.aP(s3.posMatrix, 0, e.X, 0, e.X, 0, 1), i2[a2] = s3;
                } else if (s2.canonical.isChildOf(t4.canonical)) {
                  const o2 = t4.clone();
                  o2.posMatrix = new Float64Array(16);
                  const r2 = s2.canonical.z - t4.canonical.z, n2 = s2.canonical.x - (s2.canonical.x >> r2 << r2), l2 = s2.canonical.y - (s2.canonical.y >> r2 << r2), h2 = e.X >> r2;
                  e.aP(o2.posMatrix, 0, h2, 0, h2, 0, 1), e.J(o2.posMatrix, o2.posMatrix, [-n2 * h2, -l2 * h2, 0]), i2[a2] = o2;
                } else if (t4.canonical.isChildOf(s2.canonical)) {
                  const o2 = t4.clone();
                  o2.posMatrix = new Float64Array(16);
                  const r2 = t4.canonical.z - s2.canonical.z, n2 = t4.canonical.x - (t4.canonical.x >> r2 << r2), l2 = t4.canonical.y - (t4.canonical.y >> r2 << r2), h2 = e.X >> r2;
                  e.aP(o2.posMatrix, 0, e.X, 0, e.X, 0, 1), e.J(o2.posMatrix, o2.posMatrix, [n2 * h2, l2 * h2, 0]), e.K(o2.posMatrix, o2.posMatrix, [1 / 2 ** r2, 1 / 2 ** r2, 0]), i2[a2] = o2;
                }
              }
              return i2;
            }
            getSourceTile(t4, e2) {
              const i2 = this.sourceCache._source;
              let a2 = t4.overscaledZ - this.deltaZoom;
              if (a2 > i2.maxzoom && (a2 = i2.maxzoom), a2 < i2.minzoom) return null;
              this._sourceTileCache[t4.key] || (this._sourceTileCache[t4.key] = t4.scaledTo(a2).key);
              let s2 = this.sourceCache.getTileByID(this._sourceTileCache[t4.key]);
              if ((!s2 || !s2.dem) && e2) for (; a2 >= i2.minzoom && (!s2 || !s2.dem); ) s2 = this.sourceCache.getTileByID(t4.scaledTo(a2--).key);
              return s2;
            }
            tilesAfterTime(t4 = Date.now()) {
              return Object.values(this._tiles).filter((e2) => e2.timeAdded >= t4);
            }
          }
          class Ds {
            constructor(t4, e2, i2) {
              this.painter = t4, this.sourceCache = new zs(e2), this.options = i2, this.exaggeration = "number" == typeof i2.exaggeration ? i2.exaggeration : 1, this.qualityFactor = 2, this.meshSize = 128, this._demMatrixCache = {}, this.coordsIndex = [], this._coordsTextureSize = 1024;
            }
            getDEMElevation(t4, i2, a2, s2 = e.X) {
              var o2;
              if (!(i2 >= 0 && i2 < s2 && a2 >= 0 && a2 < s2)) return 0;
              const r2 = this.getTerrainData(t4), n2 = null === (o2 = r2.tile) || void 0 === o2 ? void 0 : o2.dem;
              if (!n2) return 0;
              const l2 = function(t5, e2, i3) {
                var a3 = e2[0], s3 = e2[1];
                return t5[0] = i3[0] * a3 + i3[4] * s3 + i3[12], t5[1] = i3[1] * a3 + i3[5] * s3 + i3[13], t5;
              }([], [i2 / s2 * e.X, a2 / s2 * e.X], r2.u_terrain_matrix), h2 = [l2[0] * n2.dim, l2[1] * n2.dim], c2 = Math.floor(h2[0]), u2 = Math.floor(h2[1]), d2 = h2[0] - c2, _2 = h2[1] - u2;
              return n2.get(c2, u2) * (1 - d2) * (1 - _2) + n2.get(c2 + 1, u2) * d2 * (1 - _2) + n2.get(c2, u2 + 1) * (1 - d2) * _2 + n2.get(c2 + 1, u2 + 1) * d2 * _2;
            }
            getElevationForLngLatZoom(t4, i2) {
              if (!e.bb(i2, t4.wrap())) return 0;
              const { tileID: a2, mercatorX: s2, mercatorY: o2 } = this._getOverscaledTileIDFromLngLatZoom(t4, i2);
              return this.getElevation(a2, s2 % e.X, o2 % e.X, e.X);
            }
            getElevation(t4, i2, a2, s2 = e.X) {
              return this.getDEMElevation(t4, i2, a2, s2) * this.exaggeration;
            }
            getTerrainData(t4) {
              if (!this._emptyDemTexture) {
                const t5 = this.painter.context, i3 = new e.R({ width: 1, height: 1 }, new Uint8Array(4));
                this._emptyDepthTexture = new b(t5, i3, t5.gl.RGBA, { premultiply: false }), this._emptyDemUnpack = [0, 0, 0, 0], this._emptyDemTexture = new b(t5, new e.R({ width: 1, height: 1 }), t5.gl.RGBA, { premultiply: false }), this._emptyDemTexture.bind(t5.gl.NEAREST, t5.gl.CLAMP_TO_EDGE), this._emptyDemMatrix = e.an([]);
              }
              const i2 = this.sourceCache.getSourceTile(t4, true);
              if (i2 && i2.dem && (!i2.demTexture || i2.needsTerrainPrepare)) {
                const t5 = this.painter.context;
                i2.demTexture = this.painter.getTileTexture(i2.dem.stride), i2.demTexture ? i2.demTexture.update(i2.dem.getPixels(), { premultiply: false }) : i2.demTexture = new b(t5, i2.dem.getPixels(), t5.gl.RGBA, { premultiply: false }), i2.demTexture.bind(t5.gl.NEAREST, t5.gl.CLAMP_TO_EDGE), i2.needsTerrainPrepare = false;
              }
              const a2 = i2 && i2 + i2.tileID.key + t4.key;
              if (a2 && !this._demMatrixCache[a2]) {
                const a3 = this.sourceCache.sourceCache._source.maxzoom;
                let s2 = t4.canonical.z - i2.tileID.canonical.z;
                t4.overscaledZ > t4.canonical.z && (t4.canonical.z >= a3 ? s2 = t4.canonical.z - a3 : e.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));
                const o2 = t4.canonical.x - (t4.canonical.x >> s2 << s2), r2 = t4.canonical.y - (t4.canonical.y >> s2 << s2), n2 = e.bc(new Float64Array(16), [1 / (e.X << s2), 1 / (e.X << s2), 0]);
                e.J(n2, n2, [o2 * e.X, r2 * e.X, 0]), this._demMatrixCache[t4.key] = { matrix: n2, coord: t4 };
              }
              return { u_depth: 2, u_terrain: 3, u_terrain_dim: i2 && i2.dem && i2.dem.dim || 1, u_terrain_matrix: a2 ? this._demMatrixCache[t4.key].matrix : this._emptyDemMatrix, u_terrain_unpack: i2 && i2.dem && i2.dem.getUnpackVector() || this._emptyDemUnpack, u_terrain_exaggeration: this.exaggeration, texture: (i2 && i2.demTexture || this._emptyDemTexture).texture, depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture, tile: i2 };
            }
            getFramebuffer(t4) {
              const e2 = this.painter, i2 = e2.width / devicePixelRatio, a2 = e2.height / devicePixelRatio;
              return !this._fbo || this._fbo.width === i2 && this._fbo.height === a2 || (this._fbo.destroy(), this._fboCoordsTexture.destroy(), this._fboDepthTexture.destroy(), delete this._fbo, delete this._fboDepthTexture, delete this._fboCoordsTexture), this._fboCoordsTexture || (this._fboCoordsTexture = new b(e2.context, { width: i2, height: a2, data: null }, e2.context.gl.RGBA, { premultiply: false }), this._fboCoordsTexture.bind(e2.context.gl.NEAREST, e2.context.gl.CLAMP_TO_EDGE)), this._fboDepthTexture || (this._fboDepthTexture = new b(e2.context, { width: i2, height: a2, data: null }, e2.context.gl.RGBA, { premultiply: false }), this._fboDepthTexture.bind(e2.context.gl.NEAREST, e2.context.gl.CLAMP_TO_EDGE)), this._fbo || (this._fbo = e2.context.createFramebuffer(i2, a2, true, false), this._fbo.depthAttachment.set(e2.context.createRenderbuffer(e2.context.gl.DEPTH_COMPONENT16, i2, a2))), this._fbo.colorAttachment.set("coords" === t4 ? this._fboCoordsTexture.texture : this._fboDepthTexture.texture), this._fbo;
            }
            getCoordsTexture() {
              const t4 = this.painter.context;
              if (this._coordsTexture) return this._coordsTexture;
              const i2 = new Uint8Array(this._coordsTextureSize * this._coordsTextureSize * 4);
              for (let t5 = 0, e2 = 0; t5 < this._coordsTextureSize; t5++) for (let a3 = 0; a3 < this._coordsTextureSize; a3++, e2 += 4) i2[e2 + 0] = 255 & a3, i2[e2 + 1] = 255 & t5, i2[e2 + 2] = a3 >> 8 << 4 | t5 >> 8, i2[e2 + 3] = 0;
              const a2 = new e.R({ width: this._coordsTextureSize, height: this._coordsTextureSize }, new Uint8Array(i2.buffer)), s2 = new b(t4, a2, t4.gl.RGBA, { premultiply: false });
              return s2.bind(t4.gl.NEAREST, t4.gl.CLAMP_TO_EDGE), this._coordsTexture = s2, s2;
            }
            pointCoordinate(t4) {
              this.painter.maybeDrawDepthAndCoords(true);
              const i2 = new Uint8Array(4), a2 = this.painter.context, s2 = a2.gl, o2 = Math.round(t4.x * this.painter.pixelRatio / devicePixelRatio), r2 = Math.round(t4.y * this.painter.pixelRatio / devicePixelRatio), n2 = Math.round(this.painter.height / devicePixelRatio);
              a2.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer), s2.readPixels(o2, n2 - r2 - 1, 1, 1, s2.RGBA, s2.UNSIGNED_BYTE, i2), a2.bindFramebuffer.set(null);
              const l2 = i2[0] + (i2[2] >> 4 << 8), h2 = i2[1] + ((15 & i2[2]) << 8), c2 = this.coordsIndex[255 - i2[3]], u2 = c2 && this.sourceCache.getTileByID(c2);
              if (!u2) return null;
              const d2 = this._coordsTextureSize, _2 = (1 << u2.tileID.canonical.z) * d2;
              return new e.Z((u2.tileID.canonical.x * d2 + l2) / _2 + u2.tileID.wrap, (u2.tileID.canonical.y * d2 + h2) / _2, this.getElevation(u2.tileID, l2, h2, d2));
            }
            depthAtPoint(t4) {
              const e2 = new Uint8Array(4), i2 = this.painter.context, a2 = i2.gl;
              return i2.bindFramebuffer.set(this.getFramebuffer("depth").framebuffer), a2.readPixels(t4.x, this.painter.height / devicePixelRatio - t4.y - 1, 1, 1, a2.RGBA, a2.UNSIGNED_BYTE, e2), i2.bindFramebuffer.set(null), (e2[0] / 16777216 + e2[1] / 65536 + e2[2] / 256 + e2[3]) / 256;
            }
            getTerrainMesh() {
              if (this._mesh) return this._mesh;
              const t4 = this.painter.context, i2 = new e.bd(), a2 = new e.aY(), s2 = this.meshSize, o2 = e.X / s2, r2 = s2 * s2;
              for (let t5 = 0; t5 <= s2; t5++) for (let e2 = 0; e2 <= s2; e2++) i2.emplaceBack(e2 * o2, t5 * o2, 0);
              for (let t5 = 0; t5 < r2; t5 += s2 + 1) for (let e2 = 0; e2 < s2; e2++) a2.emplaceBack(e2 + t5, s2 + e2 + t5 + 1, s2 + e2 + t5 + 2), a2.emplaceBack(e2 + t5, s2 + e2 + t5 + 2, e2 + t5 + 1);
              const n2 = i2.length, l2 = n2 + 2 * (s2 + 1);
              for (const t5 of [0, 1]) for (let a3 = 0; a3 <= s2; a3++) for (const s3 of [0, 1]) i2.emplaceBack(a3 * o2, t5 * e.X, s3);
              for (let t5 = 0; t5 < 2 * s2; t5 += 2) a2.emplaceBack(l2 + t5, l2 + t5 + 1, l2 + t5 + 3), a2.emplaceBack(l2 + t5, l2 + t5 + 3, l2 + t5 + 2), a2.emplaceBack(n2 + t5, n2 + t5 + 3, n2 + t5 + 1), a2.emplaceBack(n2 + t5, n2 + t5 + 2, n2 + t5 + 3);
              const h2 = i2.length, c2 = h2 + 2 * (s2 + 1);
              for (const t5 of [0, 1]) for (let a3 = 0; a3 <= s2; a3++) for (const s3 of [0, 1]) i2.emplaceBack(t5 * e.X, a3 * o2, s3);
              for (let t5 = 0; t5 < 2 * s2; t5 += 2) a2.emplaceBack(h2 + t5, h2 + t5 + 1, h2 + t5 + 3), a2.emplaceBack(h2 + t5, h2 + t5 + 3, h2 + t5 + 2), a2.emplaceBack(c2 + t5, c2 + t5 + 3, c2 + t5 + 1), a2.emplaceBack(c2 + t5, c2 + t5 + 2, c2 + t5 + 3);
              return this._mesh = new ga(t4.createVertexBuffer(i2, Ss.members), t4.createIndexBuffer(a2), e.a0.simpleSegment(0, 0, i2.length, a2.length)), this._mesh;
            }
            getMeshFrameDelta(t4) {
              return 2 * Math.PI * e.be / Math.pow(2, t4) / 5;
            }
            getMinTileElevationForLngLatZoom(t4, e2) {
              var i2;
              const { tileID: a2 } = this._getOverscaledTileIDFromLngLatZoom(t4, e2);
              return null !== (i2 = this.getMinMaxElevation(a2).minElevation) && void 0 !== i2 ? i2 : 0;
            }
            getMinMaxElevation(t4) {
              const e2 = this.getTerrainData(t4).tile, i2 = { minElevation: null, maxElevation: null };
              return e2 && e2.dem && (i2.minElevation = e2.dem.min * this.exaggeration, i2.maxElevation = e2.dem.max * this.exaggeration), i2;
            }
            _getOverscaledTileIDFromLngLatZoom(t4, i2) {
              const a2 = e.Z.fromLngLat(t4.wrap()), s2 = (1 << i2) * e.X, o2 = a2.x * s2, r2 = a2.y * s2, n2 = Math.floor(o2 / e.X), l2 = Math.floor(r2 / e.X);
              return { tileID: new e.S(i2, 0, i2, n2, l2), mercatorX: o2, mercatorY: r2 };
            }
          }
          class Ms {
            constructor(t4, e2, i2) {
              this._context = t4, this._size = e2, this._tileSize = i2, this._objects = [], this._recentlyUsed = [], this._stamp = 0;
            }
            destruct() {
              for (const t4 of this._objects) t4.texture.destroy(), t4.fbo.destroy();
            }
            _createObject(t4) {
              const e2 = this._context.createFramebuffer(this._tileSize, this._tileSize, true, true), i2 = new b(this._context, { width: this._tileSize, height: this._tileSize, data: null }, this._context.gl.RGBA);
              return i2.bind(this._context.gl.LINEAR, this._context.gl.CLAMP_TO_EDGE), e2.depthAttachment.set(this._context.createRenderbuffer(this._context.gl.DEPTH_STENCIL, this._tileSize, this._tileSize)), e2.colorAttachment.set(i2.texture), { id: t4, fbo: e2, texture: i2, stamp: -1, inUse: false };
            }
            getObjectForId(t4) {
              return this._objects[t4];
            }
            useObject(t4) {
              t4.inUse = true, this._recentlyUsed = this._recentlyUsed.filter((e2) => t4.id !== e2), this._recentlyUsed.push(t4.id);
            }
            stampObject(t4) {
              t4.stamp = ++this._stamp;
            }
            getOrCreateFreeObject() {
              for (const t5 of this._recentlyUsed) if (!this._objects[t5].inUse) return this._objects[t5];
              if (this._objects.length >= this._size) throw new Error("No free RenderPool available, call freeAllObjects() required!");
              const t4 = this._createObject(this._objects.length);
              return this._objects.push(t4), t4;
            }
            freeObject(t4) {
              t4.inUse = false;
            }
            freeAllObjects() {
              for (const t4 of this._objects) this.freeObject(t4);
            }
            isFull() {
              return !(this._objects.length < this._size) && false === this._objects.some((t4) => !t4.inUse);
            }
          }
          const As = { background: true, fill: true, line: true, raster: true, hillshade: true };
          class Rs {
            constructor(t4, e2) {
              this.painter = t4, this.terrain = e2, this.pool = new Ms(t4.context, 30, e2.sourceCache.tileSize * e2.qualityFactor);
            }
            destruct() {
              this.pool.destruct();
            }
            getTexture(t4) {
              return this.pool.getObjectForId(t4.rtt[this._stacks.length - 1].id).texture;
            }
            prepareForRender(t4, e2) {
              this._stacks = [], this._prevType = null, this._rttTiles = [], this._renderableTiles = this.terrain.sourceCache.getRenderableTiles(), this._renderableLayerIds = t4._order.filter((i2) => !t4._layers[i2].isHidden(e2)), this._coordsDescendingInv = {};
              for (const e3 in t4.sourceCaches) {
                this._coordsDescendingInv[e3] = {};
                const i2 = t4.sourceCaches[e3].getVisibleCoordinates();
                for (const t5 of i2) {
                  const i3 = this.terrain.sourceCache.getTerrainCoords(t5);
                  for (const t6 in i3) this._coordsDescendingInv[e3][t6] || (this._coordsDescendingInv[e3][t6] = []), this._coordsDescendingInv[e3][t6].push(i3[t6]);
                }
              }
              this._coordsDescendingInvStr = {};
              for (const e3 of t4._order) {
                const i2 = t4._layers[e3], a2 = i2.source;
                if (As[i2.type] && !this._coordsDescendingInvStr[a2]) {
                  this._coordsDescendingInvStr[a2] = {};
                  for (const t5 in this._coordsDescendingInv[a2]) this._coordsDescendingInvStr[a2][t5] = this._coordsDescendingInv[a2][t5].map((t6) => t6.key).sort().join();
                }
              }
              for (const t5 of this._renderableTiles) for (const e3 in this._coordsDescendingInvStr) {
                const i2 = this._coordsDescendingInvStr[e3][t5.tileID.key];
                i2 && i2 !== t5.rttCoords[e3] && (t5.rtt = []);
              }
            }
            renderLayer(t4) {
              if (t4.isHidden(this.painter.transform.zoom)) return false;
              const i2 = t4.type, a2 = this.painter, s2 = this._renderableLayerIds[this._renderableLayerIds.length - 1] === t4.id;
              if (As[i2] && (this._prevType && As[this._prevType] || this._stacks.push([]), this._prevType = i2, this._stacks[this._stacks.length - 1].push(t4.id), !s2)) return true;
              if (As[this._prevType] || As[i2] && s2) {
                this._prevType = i2;
                const t5 = this._stacks.length - 1, s3 = this._stacks[t5] || [];
                for (const i3 of this._renderableTiles) {
                  if (this.pool.isFull() && (fa(this.painter, this.terrain, this._rttTiles), this._rttTiles = [], this.pool.freeAllObjects()), this._rttTiles.push(i3), i3.rtt[t5]) {
                    const e2 = this.pool.getObjectForId(i3.rtt[t5].id);
                    if (e2.stamp === i3.rtt[t5].stamp) {
                      this.pool.useObject(e2);
                      continue;
                    }
                  }
                  const o2 = this.pool.getOrCreateFreeObject();
                  this.pool.useObject(o2), this.pool.stampObject(o2), i3.rtt[t5] = { id: o2.id, stamp: o2.stamp }, a2.context.bindFramebuffer.set(o2.fbo.framebuffer), a2.context.clear({ color: e.aM.transparent, stencil: 0 }), a2.currentStencilSource = void 0;
                  for (let t6 = 0; t6 < s3.length; t6++) {
                    const e2 = a2.style._layers[s3[t6]], r2 = e2.source ? this._coordsDescendingInv[e2.source][i3.tileID.key] : [i3.tileID];
                    a2.context.viewport.set([0, 0, o2.fbo.width, o2.fbo.height]), a2._renderTileClippingMasks(e2, r2), a2.renderLayer(a2, a2.style.sourceCaches[e2.source], e2, r2), e2.source && (i3.rttCoords[e2.source] = this._coordsDescendingInvStr[e2.source][i3.tileID.key]);
                  }
                }
                return fa(this.painter, this.terrain, this._rttTiles), this._rttTiles = [], this.pool.freeAllObjects(), As[i2];
              }
              return false;
            }
          }
          const ks = { "AttributionControl.ToggleAttribution": "Toggle attribution", "AttributionControl.MapFeedback": "Map feedback", "FullscreenControl.Enter": "Enter fullscreen", "FullscreenControl.Exit": "Exit fullscreen", "GeolocateControl.FindMyLocation": "Find my location", "GeolocateControl.LocationNotAvailable": "Location not available", "LogoControl.Title": "MapLibre logo", "Map.Title": "Map", "Marker.Title": "Map marker", "NavigationControl.ResetBearing": "Reset bearing to north", "NavigationControl.ZoomIn": "Zoom in", "NavigationControl.ZoomOut": "Zoom out", "Popup.Close": "Close popup", "ScaleControl.Feet": "ft", "ScaleControl.Meters": "m", "ScaleControl.Kilometers": "km", "ScaleControl.Miles": "mi", "ScaleControl.NauticalMiles": "nm", "TerrainControl.Enable": "Enable terrain", "TerrainControl.Disable": "Disable terrain", "CooperativeGesturesHandler.WindowsHelpText": "Use Ctrl + scroll to zoom the map", "CooperativeGesturesHandler.MacHelpText": "Use \u2318 + scroll to zoom the map", "CooperativeGesturesHandler.MobileHelpText": "Use two fingers to move the map" }, Ls = i, Fs = { hash: false, interactive: true, bearingSnap: 7, attributionControl: Is, maplibreLogo: false, failIfMajorPerformanceCaveat: false, preserveDrawingBuffer: false, refreshExpiredTiles: true, scrollZoom: true, minZoom: -2, maxZoom: 22, minPitch: 0, maxPitch: 60, boxZoom: true, dragRotate: true, dragPan: true, keyboard: true, doubleClickZoom: true, touchZoomRotate: true, touchPitch: true, cooperativeGestures: false, trackResize: true, center: [0, 0], zoom: 0, bearing: 0, pitch: 0, renderWorldCopies: true, maxTileCacheSize: null, maxTileCacheZoomLevels: e.a.MAX_TILE_CACHE_ZOOM_LEVELS, transformRequest: null, transformCameraUpdate: null, fadeDuration: 300, crossSourceCollisions: true, clickTolerance: 3, localIdeographFontFamily: "sans-serif", pitchWithRotate: true, validateStyle: true, maxCanvasSize: [4096, 4096], cancelPendingTileRequestsWhileZooming: true }, Bs = (t4) => {
            t4.touchstart = t4.dragStart, t4.touchmoveWindow = t4.dragMove, t4.touchend = t4.dragEnd;
          }, Os = { showCompass: true, showZoom: true, visualizePitch: false };
          class Ns {
            constructor(t4, i2, a2 = false) {
              this.mousedown = (t5) => {
                this.startMouse(e.e({}, t5, { ctrlKey: true, preventDefault: () => t5.preventDefault() }), r.mousePos(this.element, t5)), r.addEventListener(window, "mousemove", this.mousemove), r.addEventListener(window, "mouseup", this.mouseup);
              }, this.mousemove = (t5) => {
                this.moveMouse(t5, r.mousePos(this.element, t5));
              }, this.mouseup = (t5) => {
                this.mouseRotate.dragEnd(t5), this.mousePitch && this.mousePitch.dragEnd(t5), this.offTemp();
              }, this.touchstart = (t5) => {
                1 !== t5.targetTouches.length ? this.reset() : (this._startPos = this._lastPos = r.touchPos(this.element, t5.targetTouches)[0], this.startTouch(t5, this._startPos), r.addEventListener(window, "touchmove", this.touchmove, { passive: false }), r.addEventListener(window, "touchend", this.touchend));
              }, this.touchmove = (t5) => {
                1 !== t5.targetTouches.length ? this.reset() : (this._lastPos = r.touchPos(this.element, t5.targetTouches)[0], this.moveTouch(t5, this._lastPos));
              }, this.touchend = (t5) => {
                0 === t5.targetTouches.length && this._startPos && this._lastPos && this._startPos.dist(this._lastPos) < this._clickTolerance && this.element.click(), delete this._startPos, delete this._lastPos, this.offTemp();
              }, this.reset = () => {
                this.mouseRotate.reset(), this.mousePitch && this.mousePitch.reset(), this.touchRotate.reset(), this.touchPitch && this.touchPitch.reset(), delete this._startPos, delete this._lastPos, this.offTemp();
              }, this._clickTolerance = 10;
              const s2 = t4.dragRotate._mouseRotate.getClickTolerance(), o2 = t4.dragRotate._mousePitch.getClickTolerance();
              this.element = i2, this.mouseRotate = Ka({ clickTolerance: s2, enable: true }), this.touchRotate = (({ enable: t5, clickTolerance: e2, bearingDegreesPerPixelMoved: i3 = 0.8 }) => {
                const a3 = new $a();
                return new Ga({ clickTolerance: e2, move: (t6, e3) => ({ bearingDelta: (e3.x - t6.x) * i3 }), moveStateManager: a3, enable: t5, assignEvents: Bs });
              })({ clickTolerance: s2, enable: true }), this.map = t4, a2 && (this.mousePitch = Ja({ clickTolerance: o2, enable: true }), this.touchPitch = (({ enable: t5, clickTolerance: e2, pitchDegreesPerPixelMoved: i3 = -0.5 }) => {
                const a3 = new $a();
                return new Ga({ clickTolerance: e2, move: (t6, e3) => ({ pitchDelta: (e3.y - t6.y) * i3 }), moveStateManager: a3, enable: t5, assignEvents: Bs });
              })({ clickTolerance: o2, enable: true })), r.addEventListener(i2, "mousedown", this.mousedown), r.addEventListener(i2, "touchstart", this.touchstart, { passive: false }), r.addEventListener(i2, "touchcancel", this.reset);
            }
            startMouse(t4, e2) {
              this.mouseRotate.dragStart(t4, e2), this.mousePitch && this.mousePitch.dragStart(t4, e2), r.disableDrag();
            }
            startTouch(t4, e2) {
              this.touchRotate.dragStart(t4, e2), this.touchPitch && this.touchPitch.dragStart(t4, e2), r.disableDrag();
            }
            moveMouse(t4, e2) {
              const i2 = this.map, { bearingDelta: a2 } = this.mouseRotate.dragMove(t4, e2) || {};
              if (a2 && i2.setBearing(i2.getBearing() + a2), this.mousePitch) {
                const { pitchDelta: a3 } = this.mousePitch.dragMove(t4, e2) || {};
                a3 && i2.setPitch(i2.getPitch() + a3);
              }
            }
            moveTouch(t4, e2) {
              const i2 = this.map, { bearingDelta: a2 } = this.touchRotate.dragMove(t4, e2) || {};
              if (a2 && i2.setBearing(i2.getBearing() + a2), this.touchPitch) {
                const { pitchDelta: a3 } = this.touchPitch.dragMove(t4, e2) || {};
                a3 && i2.setPitch(i2.getPitch() + a3);
              }
            }
            off() {
              const t4 = this.element;
              r.removeEventListener(t4, "mousedown", this.mousedown), r.removeEventListener(t4, "touchstart", this.touchstart, { passive: false }), r.removeEventListener(window, "touchmove", this.touchmove, { passive: false }), r.removeEventListener(window, "touchend", this.touchend), r.removeEventListener(t4, "touchcancel", this.reset), this.offTemp();
            }
            offTemp() {
              r.enableDrag(), r.removeEventListener(window, "mousemove", this.mousemove), r.removeEventListener(window, "mouseup", this.mouseup), r.removeEventListener(window, "touchmove", this.touchmove, { passive: false }), r.removeEventListener(window, "touchend", this.touchend);
            }
          }
          let Us;
          function js(t4, i2, a2) {
            const s2 = new e.N(t4.lng, t4.lat);
            if (t4 = new e.N(t4.lng, t4.lat), i2) {
              const s3 = new e.N(t4.lng - 360, t4.lat), o2 = new e.N(t4.lng + 360, t4.lat), r2 = a2.locationPoint(t4).distSqr(i2);
              a2.locationPoint(s3).distSqr(i2) < r2 ? t4 = s3 : a2.locationPoint(o2).distSqr(i2) < r2 && (t4 = o2);
            }
            for (; Math.abs(t4.lng - a2.center.lng) > 180; ) {
              const e2 = a2.locationPoint(t4);
              if (e2.x >= 0 && e2.y >= 0 && e2.x <= a2.width && e2.y <= a2.height) break;
              t4.lng > a2.center.lng ? t4.lng -= 360 : t4.lng += 360;
            }
            return t4.lng !== s2.lng && a2.locationPoint(t4).y > a2.height / 2 - a2.getHorizon() ? t4 : s2;
          }
          const Zs = { center: "translate(-50%,-50%)", top: "translate(-50%,0)", "top-left": "translate(0,0)", "top-right": "translate(-100%,0)", bottom: "translate(-50%,-100%)", "bottom-left": "translate(0,-100%)", "bottom-right": "translate(-100%,-100%)", left: "translate(0,-50%)", right: "translate(-100%,-50%)" };
          function qs(t4, e2, i2) {
            const a2 = t4.classList;
            for (const t5 in Zs) a2.remove(`maplibregl-${i2}-anchor-${t5}`);
            a2.add(`maplibregl-${i2}-anchor-${e2}`);
          }
          class Vs extends e.E {
            constructor(t4) {
              if (super(), this._onKeyPress = (t5) => {
                const e2 = t5.code, i2 = t5.charCode || t5.keyCode;
                "Space" !== e2 && "Enter" !== e2 && 32 !== i2 && 13 !== i2 || this.togglePopup();
              }, this._onMapClick = (t5) => {
                const e2 = t5.originalEvent.target, i2 = this._element;
                this._popup && (e2 === i2 || i2.contains(e2)) && this.togglePopup();
              }, this._update = (t5) => {
                var e2;
                if (!this._map) return;
                const i2 = this._map.loaded() && !this._map.isMoving();
                ("terrain" === (null == t5 ? void 0 : t5.type) || "render" === (null == t5 ? void 0 : t5.type) && !i2) && this._map.once("render", this._update), this._lngLat = this._map.transform.renderWorldCopies ? js(this._lngLat, this._flatPos, this._map.transform) : null === (e2 = this._lngLat) || void 0 === e2 ? void 0 : e2.wrap(), this._flatPos = this._pos = this._map.project(this._lngLat)._add(this._offset), this._map.terrain && (this._flatPos = this._map.transform.locationPoint(this._lngLat)._add(this._offset));
                let a2 = "";
                "viewport" === this._rotationAlignment || "auto" === this._rotationAlignment ? a2 = `rotateZ(${this._rotation}deg)` : "map" === this._rotationAlignment && (a2 = `rotateZ(${this._rotation - this._map.getBearing()}deg)`);
                let s2 = "";
                "viewport" === this._pitchAlignment || "auto" === this._pitchAlignment ? s2 = "rotateX(0deg)" : "map" === this._pitchAlignment && (s2 = `rotateX(${this._map.getPitch()}deg)`), this._subpixelPositioning || t5 && "moveend" !== t5.type || (this._pos = this._pos.round()), r.setTransform(this._element, `${Zs[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${s2} ${a2}`), o.frameAsync(new AbortController()).then(() => {
                  this._updateOpacity(t5 && "moveend" === t5.type);
                }).catch(() => {
                });
              }, this._onMove = (t5) => {
                if (!this._isDragging) {
                  const e2 = this._clickTolerance || this._map._clickTolerance;
                  this._isDragging = t5.point.dist(this._pointerdownPos) >= e2;
                }
                this._isDragging && (this._pos = t5.point.sub(this._positionDelta), this._lngLat = this._map.unproject(this._pos), this.setLngLat(this._lngLat), this._element.style.pointerEvents = "none", "pending" === this._state && (this._state = "active", this.fire(new e.k("dragstart"))), this.fire(new e.k("drag")));
              }, this._onUp = () => {
                this._element.style.pointerEvents = "auto", this._positionDelta = null, this._pointerdownPos = null, this._isDragging = false, this._map.off("mousemove", this._onMove), this._map.off("touchmove", this._onMove), "active" === this._state && this.fire(new e.k("dragend")), this._state = "inactive";
              }, this._addDragHandler = (t5) => {
                this._element.contains(t5.originalEvent.target) && (t5.preventDefault(), this._positionDelta = t5.point.sub(this._pos).add(this._offset), this._pointerdownPos = t5.point, this._state = "pending", this._map.on("mousemove", this._onMove), this._map.on("touchmove", this._onMove), this._map.once("mouseup", this._onUp), this._map.once("touchend", this._onUp));
              }, this._anchor = t4 && t4.anchor || "center", this._color = t4 && t4.color || "#3FB1CE", this._scale = t4 && t4.scale || 1, this._draggable = t4 && t4.draggable || false, this._clickTolerance = t4 && t4.clickTolerance || 0, this._subpixelPositioning = t4 && t4.subpixelPositioning || false, this._isDragging = false, this._state = "inactive", this._rotation = t4 && t4.rotation || 0, this._rotationAlignment = t4 && t4.rotationAlignment || "auto", this._pitchAlignment = t4 && t4.pitchAlignment && "auto" !== t4.pitchAlignment ? t4.pitchAlignment : this._rotationAlignment, this.setOpacity(), this.setOpacity(null == t4 ? void 0 : t4.opacity, null == t4 ? void 0 : t4.opacityWhenCovered), t4 && t4.element) this._element = t4.element, this._offset = e.P.convert(t4 && t4.offset || [0, 0]);
              else {
                this._defaultMarker = true, this._element = r.create("div");
                const i2 = r.createNS("http://www.w3.org/2000/svg", "svg"), a2 = 41, s2 = 27;
                i2.setAttributeNS(null, "display", "block"), i2.setAttributeNS(null, "height", `${a2}px`), i2.setAttributeNS(null, "width", `${s2}px`), i2.setAttributeNS(null, "viewBox", `0 0 ${s2} ${a2}`);
                const o2 = r.createNS("http://www.w3.org/2000/svg", "g");
                o2.setAttributeNS(null, "stroke", "none"), o2.setAttributeNS(null, "stroke-width", "1"), o2.setAttributeNS(null, "fill", "none"), o2.setAttributeNS(null, "fill-rule", "evenodd");
                const n2 = r.createNS("http://www.w3.org/2000/svg", "g");
                n2.setAttributeNS(null, "fill-rule", "nonzero");
                const l2 = r.createNS("http://www.w3.org/2000/svg", "g");
                l2.setAttributeNS(null, "transform", "translate(3.0, 29.0)"), l2.setAttributeNS(null, "fill", "#000000");
                const h2 = [{ rx: "10.5", ry: "5.25002273" }, { rx: "10.5", ry: "5.25002273" }, { rx: "9.5", ry: "4.77275007" }, { rx: "8.5", ry: "4.29549936" }, { rx: "7.5", ry: "3.81822308" }, { rx: "6.5", ry: "3.34094679" }, { rx: "5.5", ry: "2.86367051" }, { rx: "4.5", ry: "2.38636864" }];
                for (const t5 of h2) {
                  const e2 = r.createNS("http://www.w3.org/2000/svg", "ellipse");
                  e2.setAttributeNS(null, "opacity", "0.04"), e2.setAttributeNS(null, "cx", "10.5"), e2.setAttributeNS(null, "cy", "5.80029008"), e2.setAttributeNS(null, "rx", t5.rx), e2.setAttributeNS(null, "ry", t5.ry), l2.appendChild(e2);
                }
                const c2 = r.createNS("http://www.w3.org/2000/svg", "g");
                c2.setAttributeNS(null, "fill", this._color);
                const u2 = r.createNS("http://www.w3.org/2000/svg", "path");
                u2.setAttributeNS(null, "d", "M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"), c2.appendChild(u2);
                const d2 = r.createNS("http://www.w3.org/2000/svg", "g");
                d2.setAttributeNS(null, "opacity", "0.25"), d2.setAttributeNS(null, "fill", "#000000");
                const _2 = r.createNS("http://www.w3.org/2000/svg", "path");
                _2.setAttributeNS(null, "d", "M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"), d2.appendChild(_2);
                const p2 = r.createNS("http://www.w3.org/2000/svg", "g");
                p2.setAttributeNS(null, "transform", "translate(6.0, 7.0)"), p2.setAttributeNS(null, "fill", "#FFFFFF");
                const m2 = r.createNS("http://www.w3.org/2000/svg", "g");
                m2.setAttributeNS(null, "transform", "translate(8.0, 8.0)");
                const f2 = r.createNS("http://www.w3.org/2000/svg", "circle");
                f2.setAttributeNS(null, "fill", "#000000"), f2.setAttributeNS(null, "opacity", "0.25"), f2.setAttributeNS(null, "cx", "5.5"), f2.setAttributeNS(null, "cy", "5.5"), f2.setAttributeNS(null, "r", "5.4999962");
                const g2 = r.createNS("http://www.w3.org/2000/svg", "circle");
                g2.setAttributeNS(null, "fill", "#FFFFFF"), g2.setAttributeNS(null, "cx", "5.5"), g2.setAttributeNS(null, "cy", "5.5"), g2.setAttributeNS(null, "r", "5.4999962"), m2.appendChild(f2), m2.appendChild(g2), n2.appendChild(l2), n2.appendChild(c2), n2.appendChild(d2), n2.appendChild(p2), n2.appendChild(m2), i2.appendChild(n2), i2.setAttributeNS(null, "height", a2 * this._scale + "px"), i2.setAttributeNS(null, "width", s2 * this._scale + "px"), this._element.appendChild(i2), this._offset = e.P.convert(t4 && t4.offset || [0, -14]);
              }
              if (this._element.classList.add("maplibregl-marker"), this._element.addEventListener("dragstart", (t5) => {
                t5.preventDefault();
              }), this._element.addEventListener("mousedown", (t5) => {
                t5.preventDefault();
              }), qs(this._element, this._anchor, "marker"), t4 && t4.className) for (const e2 of t4.className.split(" ")) this._element.classList.add(e2);
              this._popup = null;
            }
            addTo(t4) {
              return this.remove(), this._map = t4, this._element.setAttribute("aria-label", t4._getUIString("Marker.Title")), t4.getCanvasContainer().appendChild(this._element), t4.on("move", this._update), t4.on("moveend", this._update), t4.on("terrain", this._update), this.setDraggable(this._draggable), this._update(), this._map.on("click", this._onMapClick), this;
            }
            remove() {
              return this._opacityTimeout && (clearTimeout(this._opacityTimeout), delete this._opacityTimeout), this._map && (this._map.off("click", this._onMapClick), this._map.off("move", this._update), this._map.off("moveend", this._update), this._map.off("terrain", this._update), this._map.off("mousedown", this._addDragHandler), this._map.off("touchstart", this._addDragHandler), this._map.off("mouseup", this._onUp), this._map.off("touchend", this._onUp), this._map.off("mousemove", this._onMove), this._map.off("touchmove", this._onMove), delete this._map), r.remove(this._element), this._popup && this._popup.remove(), this;
            }
            getLngLat() {
              return this._lngLat;
            }
            setLngLat(t4) {
              return this._lngLat = e.N.convert(t4), this._pos = null, this._popup && this._popup.setLngLat(this._lngLat), this._update(), this;
            }
            getElement() {
              return this._element;
            }
            setPopup(t4) {
              if (this._popup && (this._popup.remove(), this._popup = null, this._element.removeEventListener("keypress", this._onKeyPress), this._originalTabIndex || this._element.removeAttribute("tabindex")), t4) {
                if (!("offset" in t4.options)) {
                  const e2 = 38.1, i2 = 13.5, a2 = Math.abs(i2) / Math.SQRT2;
                  t4.options.offset = this._defaultMarker ? { top: [0, 0], "top-left": [0, 0], "top-right": [0, 0], bottom: [0, -e2], "bottom-left": [a2, -1 * (e2 - i2 + a2)], "bottom-right": [-a2, -1 * (e2 - i2 + a2)], left: [i2, -1 * (e2 - i2)], right: [-i2, -1 * (e2 - i2)] } : this._offset;
                }
                this._popup = t4, this._originalTabIndex = this._element.getAttribute("tabindex"), this._originalTabIndex || this._element.setAttribute("tabindex", "0"), this._element.addEventListener("keypress", this._onKeyPress);
              }
              return this;
            }
            setSubpixelPositioning(t4) {
              return this._subpixelPositioning = t4, this;
            }
            getPopup() {
              return this._popup;
            }
            togglePopup() {
              const t4 = this._popup;
              return this._element.style.opacity === this._opacityWhenCovered ? this : t4 ? (t4.isOpen() ? t4.remove() : (t4.setLngLat(this._lngLat), t4.addTo(this._map)), this) : this;
            }
            _updateOpacity(t4 = false) {
              var i2, a2;
              if (!(null === (i2 = this._map) || void 0 === i2 ? void 0 : i2.terrain)) return void (this._element.style.opacity !== this._opacity && (this._element.style.opacity = this._opacity));
              if (t4) this._opacityTimeout = null;
              else {
                if (this._opacityTimeout) return;
                this._opacityTimeout = setTimeout(() => {
                  this._opacityTimeout = null;
                }, 100);
              }
              const s2 = this._map, o2 = s2.terrain.depthAtPoint(this._pos), r2 = s2.terrain.getElevationForLngLatZoom(this._lngLat, s2.transform.tileZoom);
              if (s2.transform.lngLatToCameraDepth(this._lngLat, r2) - o2 < 6e-3) return void (this._element.style.opacity = this._opacity);
              const n2 = -this._offset.y / s2.transform._pixelPerMeter, l2 = Math.sin(s2.getPitch() * Math.PI / 180) * n2, h2 = s2.terrain.depthAtPoint(new e.P(this._pos.x, this._pos.y - this._offset.y)), c2 = s2.transform.lngLatToCameraDepth(this._lngLat, r2 + l2) - h2 > 6e-3;
              (null === (a2 = this._popup) || void 0 === a2 ? void 0 : a2.isOpen()) && c2 && this._popup.remove(), this._element.style.opacity = c2 ? this._opacityWhenCovered : this._opacity;
            }
            getOffset() {
              return this._offset;
            }
            setOffset(t4) {
              return this._offset = e.P.convert(t4), this._update(), this;
            }
            addClassName(t4) {
              this._element.classList.add(t4);
            }
            removeClassName(t4) {
              this._element.classList.remove(t4);
            }
            toggleClassName(t4) {
              return this._element.classList.toggle(t4);
            }
            setDraggable(t4) {
              return this._draggable = !!t4, this._map && (t4 ? (this._map.on("mousedown", this._addDragHandler), this._map.on("touchstart", this._addDragHandler)) : (this._map.off("mousedown", this._addDragHandler), this._map.off("touchstart", this._addDragHandler))), this;
            }
            isDraggable() {
              return this._draggable;
            }
            setRotation(t4) {
              return this._rotation = t4 || 0, this._update(), this;
            }
            getRotation() {
              return this._rotation;
            }
            setRotationAlignment(t4) {
              return this._rotationAlignment = t4 || "auto", this._update(), this;
            }
            getRotationAlignment() {
              return this._rotationAlignment;
            }
            setPitchAlignment(t4) {
              return this._pitchAlignment = t4 && "auto" !== t4 ? t4 : this._rotationAlignment, this._update(), this;
            }
            getPitchAlignment() {
              return this._pitchAlignment;
            }
            setOpacity(t4, e2) {
              return void 0 === t4 && void 0 === e2 && (this._opacity = "1", this._opacityWhenCovered = "0.2"), void 0 !== t4 && (this._opacity = t4), void 0 !== e2 && (this._opacityWhenCovered = e2), this._map && this._updateOpacity(true), this;
            }
          }
          const Gs = { positionOptions: { enableHighAccuracy: false, maximumAge: 0, timeout: 6e3 }, fitBoundsOptions: { maxZoom: 15 }, trackUserLocation: false, showAccuracyCircle: true, showUserLocation: true };
          let Hs = 0, Ws = false;
          const $s = { maxWidth: 100, unit: "metric" };
          function Xs(t4, e2, i2) {
            const a2 = i2 && i2.maxWidth || 100, s2 = t4._container.clientHeight / 2, o2 = t4.unproject([0, s2]), r2 = t4.unproject([a2, s2]), n2 = o2.distanceTo(r2);
            if (i2 && "imperial" === i2.unit) {
              const i3 = 3.2808 * n2;
              i3 > 5280 ? Ks(e2, a2, i3 / 5280, t4._getUIString("ScaleControl.Miles")) : Ks(e2, a2, i3, t4._getUIString("ScaleControl.Feet"));
            } else i2 && "nautical" === i2.unit ? Ks(e2, a2, n2 / 1852, t4._getUIString("ScaleControl.NauticalMiles")) : n2 >= 1e3 ? Ks(e2, a2, n2 / 1e3, t4._getUIString("ScaleControl.Kilometers")) : Ks(e2, a2, n2, t4._getUIString("ScaleControl.Meters"));
          }
          function Ks(t4, e2, i2, a2) {
            const s2 = function(t5) {
              const e3 = Math.pow(10, `${Math.floor(t5)}`.length - 1);
              let i3 = t5 / e3;
              return i3 = i3 >= 10 ? 10 : i3 >= 5 ? 5 : i3 >= 3 ? 3 : i3 >= 2 ? 2 : i3 >= 1 ? 1 : function(t6) {
                const e4 = Math.pow(10, Math.ceil(-Math.log(t6) / Math.LN10));
                return Math.round(t6 * e4) / e4;
              }(i3), e3 * i3;
            }(i2);
            t4.style.width = e2 * (s2 / i2) + "px", t4.innerHTML = `${s2}&nbsp;${a2}`;
          }
          const Js = { closeButton: true, closeOnClick: true, focusAfterOpen: true, className: "", maxWidth: "240px", subpixelPositioning: false }, Ys = ["a[href]", "[tabindex]:not([tabindex='-1'])", "[contenteditable]:not([contenteditable='false'])", "button:not([disabled])", "input:not([disabled])", "select:not([disabled])", "textarea:not([disabled])"].join(", ");
          function Qs(t4) {
            if (t4) {
              if ("number" == typeof t4) {
                const i2 = Math.round(Math.abs(t4) / Math.SQRT2);
                return { center: new e.P(0, 0), top: new e.P(0, t4), "top-left": new e.P(i2, i2), "top-right": new e.P(-i2, i2), bottom: new e.P(0, -t4), "bottom-left": new e.P(i2, -i2), "bottom-right": new e.P(-i2, -i2), left: new e.P(t4, 0), right: new e.P(-t4, 0) };
              }
              if (t4 instanceof e.P || Array.isArray(t4)) {
                const i2 = e.P.convert(t4);
                return { center: i2, top: i2, "top-left": i2, "top-right": i2, bottom: i2, "bottom-left": i2, "bottom-right": i2, left: i2, right: i2 };
              }
              return { center: e.P.convert(t4.center || [0, 0]), top: e.P.convert(t4.top || [0, 0]), "top-left": e.P.convert(t4["top-left"] || [0, 0]), "top-right": e.P.convert(t4["top-right"] || [0, 0]), bottom: e.P.convert(t4.bottom || [0, 0]), "bottom-left": e.P.convert(t4["bottom-left"] || [0, 0]), "bottom-right": e.P.convert(t4["bottom-right"] || [0, 0]), left: e.P.convert(t4.left || [0, 0]), right: e.P.convert(t4.right || [0, 0]) };
            }
            return Qs(new e.P(0, 0));
          }
          const to = i;
          t.AJAXError = e.bh, t.Evented = e.E, t.LngLat = e.N, t.MercatorCoordinate = e.Z, t.Point = e.P, t.addProtocol = e.bi, t.config = e.a, t.removeProtocol = e.bj, t.AttributionControl = Es, t.BoxZoomHandler = Ua, t.CanvasSource = et, t.CooperativeGesturesHandler = vs, t.DoubleClickZoomHandler = ds, t.DragPanHandler = ms, t.DragRotateHandler = fs, t.EdgeInsets = ba, t.FullscreenControl = class extends e.E {
            constructor(t4 = {}) {
              super(), this._onFullscreenChange = () => {
                var t5;
                let e2 = window.document.fullscreenElement || window.document.mozFullScreenElement || window.document.webkitFullscreenElement || window.document.msFullscreenElement;
                for (; null === (t5 = null == e2 ? void 0 : e2.shadowRoot) || void 0 === t5 ? void 0 : t5.fullscreenElement; ) e2 = e2.shadowRoot.fullscreenElement;
                e2 === this._container !== this._fullscreen && this._handleFullscreenChange();
              }, this._onClickFullscreen = () => {
                this._isFullscreen() ? this._exitFullscreen() : this._requestFullscreen();
              }, this._fullscreen = false, t4 && t4.container && (t4.container instanceof HTMLElement ? this._container = t4.container : e.w("Full screen control 'container' must be a DOM element.")), "onfullscreenchange" in document ? this._fullscreenchange = "fullscreenchange" : "onmozfullscreenchange" in document ? this._fullscreenchange = "mozfullscreenchange" : "onwebkitfullscreenchange" in document ? this._fullscreenchange = "webkitfullscreenchange" : "onmsfullscreenchange" in document && (this._fullscreenchange = "MSFullscreenChange");
            }
            onAdd(t4) {
              return this._map = t4, this._container || (this._container = this._map.getContainer()), this._controlContainer = r.create("div", "maplibregl-ctrl maplibregl-ctrl-group"), this._setupUI(), this._controlContainer;
            }
            onRemove() {
              r.remove(this._controlContainer), this._map = null, window.document.removeEventListener(this._fullscreenchange, this._onFullscreenChange);
            }
            _setupUI() {
              const t4 = this._fullscreenButton = r.create("button", "maplibregl-ctrl-fullscreen", this._controlContainer);
              r.create("span", "maplibregl-ctrl-icon", t4).setAttribute("aria-hidden", "true"), t4.type = "button", this._updateTitle(), this._fullscreenButton.addEventListener("click", this._onClickFullscreen), window.document.addEventListener(this._fullscreenchange, this._onFullscreenChange);
            }
            _updateTitle() {
              const t4 = this._getTitle();
              this._fullscreenButton.setAttribute("aria-label", t4), this._fullscreenButton.title = t4;
            }
            _getTitle() {
              return this._map._getUIString(this._isFullscreen() ? "FullscreenControl.Exit" : "FullscreenControl.Enter");
            }
            _isFullscreen() {
              return this._fullscreen;
            }
            _handleFullscreenChange() {
              this._fullscreen = !this._fullscreen, this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"), this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"), this._updateTitle(), this._fullscreen ? (this.fire(new e.k("fullscreenstart")), this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled(), this._map.cooperativeGestures.disable()) : (this.fire(new e.k("fullscreenend")), this._prevCooperativeGesturesEnabled && this._map.cooperativeGestures.enable());
            }
            _exitFullscreen() {
              window.document.exitFullscreen ? window.document.exitFullscreen() : window.document.mozCancelFullScreen ? window.document.mozCancelFullScreen() : window.document.msExitFullscreen ? window.document.msExitFullscreen() : window.document.webkitCancelFullScreen ? window.document.webkitCancelFullScreen() : this._togglePseudoFullScreen();
            }
            _requestFullscreen() {
              this._container.requestFullscreen ? this._container.requestFullscreen() : this._container.mozRequestFullScreen ? this._container.mozRequestFullScreen() : this._container.msRequestFullscreen ? this._container.msRequestFullscreen() : this._container.webkitRequestFullscreen ? this._container.webkitRequestFullscreen() : this._togglePseudoFullScreen();
            }
            _togglePseudoFullScreen() {
              this._container.classList.toggle("maplibregl-pseudo-fullscreen"), this._handleFullscreenChange(), this._map.resize();
            }
          }, t.GeoJSONSource = J, t.GeolocateControl = class extends e.E {
            constructor(t4) {
              super(), this._onSuccess = (t5) => {
                if (this._map) {
                  if (this._isOutOfMapMaxBounds(t5)) return this._setErrorState(), this.fire(new e.k("outofmaxbounds", t5)), this._updateMarker(), void this._finish();
                  if (this.options.trackUserLocation) switch (this._lastKnownPosition = t5, this._watchState) {
                    case "WAITING_ACTIVE":
                    case "ACTIVE_LOCK":
                    case "ACTIVE_ERROR":
                      this._watchState = "ACTIVE_LOCK", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");
                      break;
                    case "BACKGROUND":
                    case "BACKGROUND_ERROR":
                      this._watchState = "BACKGROUND", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");
                      break;
                    default:
                      throw new Error(`Unexpected watchState ${this._watchState}`);
                  }
                  this.options.showUserLocation && "OFF" !== this._watchState && this._updateMarker(t5), this.options.trackUserLocation && "ACTIVE_LOCK" !== this._watchState || this._updateCamera(t5), this.options.showUserLocation && this._dotElement.classList.remove("maplibregl-user-location-dot-stale"), this.fire(new e.k("geolocate", t5)), this._finish();
                }
              }, this._updateCamera = (t5) => {
                const i2 = new e.N(t5.coords.longitude, t5.coords.latitude), a2 = t5.coords.accuracy, s2 = this._map.getBearing(), o2 = e.e({ bearing: s2 }, this.options.fitBoundsOptions), r2 = H.fromLngLat(i2, a2);
                this._map.fitBounds(r2, o2, { geolocateSource: true });
              }, this._updateMarker = (t5) => {
                if (t5) {
                  const i2 = new e.N(t5.coords.longitude, t5.coords.latitude);
                  this._accuracyCircleMarker.setLngLat(i2).addTo(this._map), this._userLocationDotMarker.setLngLat(i2).addTo(this._map), this._accuracy = t5.coords.accuracy, this.options.showUserLocation && this.options.showAccuracyCircle && this._updateCircleRadius();
                } else this._userLocationDotMarker.remove(), this._accuracyCircleMarker.remove();
              }, this._onZoom = () => {
                this.options.showUserLocation && this.options.showAccuracyCircle && this._updateCircleRadius();
              }, this._onError = (t5) => {
                if (this._map) {
                  if (this.options.trackUserLocation) if (1 === t5.code) {
                    this._watchState = "OFF", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"), this._geolocateButton.disabled = true;
                    const t6 = this._map._getUIString("GeolocateControl.LocationNotAvailable");
                    this._geolocateButton.title = t6, this._geolocateButton.setAttribute("aria-label", t6), void 0 !== this._geolocationWatchID && this._clearWatch();
                  } else {
                    if (3 === t5.code && Ws) return;
                    this._setErrorState();
                  }
                  "OFF" !== this._watchState && this.options.showUserLocation && this._dotElement.classList.add("maplibregl-user-location-dot-stale"), this.fire(new e.k("error", t5)), this._finish();
                }
              }, this._finish = () => {
                this._timeoutId && clearTimeout(this._timeoutId), this._timeoutId = void 0;
              }, this._setupUI = () => {
                this._map && (this._container.addEventListener("contextmenu", (t5) => t5.preventDefault()), this._geolocateButton = r.create("button", "maplibregl-ctrl-geolocate", this._container), r.create("span", "maplibregl-ctrl-icon", this._geolocateButton).setAttribute("aria-hidden", "true"), this._geolocateButton.type = "button", this._geolocateButton.disabled = true);
              }, this._finishSetupUI = (t5) => {
                if (this._map) {
                  if (false === t5) {
                    e.w("Geolocation support is not available so the GeolocateControl will be disabled.");
                    const t6 = this._map._getUIString("GeolocateControl.LocationNotAvailable");
                    this._geolocateButton.disabled = true, this._geolocateButton.title = t6, this._geolocateButton.setAttribute("aria-label", t6);
                  } else {
                    const t6 = this._map._getUIString("GeolocateControl.FindMyLocation");
                    this._geolocateButton.disabled = false, this._geolocateButton.title = t6, this._geolocateButton.setAttribute("aria-label", t6);
                  }
                  this.options.trackUserLocation && (this._geolocateButton.setAttribute("aria-pressed", "false"), this._watchState = "OFF"), this.options.showUserLocation && (this._dotElement = r.create("div", "maplibregl-user-location-dot"), this._userLocationDotMarker = new Vs({ element: this._dotElement }), this._circleElement = r.create("div", "maplibregl-user-location-accuracy-circle"), this._accuracyCircleMarker = new Vs({ element: this._circleElement, pitchAlignment: "map" }), this.options.trackUserLocation && (this._watchState = "OFF"), this._map.on("zoom", this._onZoom)), this._geolocateButton.addEventListener("click", () => this.trigger()), this._setup = true, this.options.trackUserLocation && this._map.on("movestart", (t6) => {
                    t6.geolocateSource || "ACTIVE_LOCK" !== this._watchState || t6.originalEvent && "resize" === t6.originalEvent.type || (this._watchState = "BACKGROUND", this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"), this.fire(new e.k("trackuserlocationend")), this.fire(new e.k("userlocationlostfocus")));
                  });
                }
              }, this.options = e.e({}, Gs, t4);
            }
            onAdd(t4) {
              return this._map = t4, this._container = r.create("div", "maplibregl-ctrl maplibregl-ctrl-group"), this._setupUI(), function() {
                return e._(this, arguments, void 0, function* (t5 = false) {
                  if (void 0 !== Us && !t5) return Us;
                  if (void 0 === window.navigator.permissions) return Us = !!window.navigator.geolocation, Us;
                  try {
                    const t6 = yield window.navigator.permissions.query({ name: "geolocation" });
                    Us = "denied" !== t6.state;
                  } catch (t6) {
                    Us = !!window.navigator.geolocation;
                  }
                  return Us;
                });
              }().then((t5) => this._finishSetupUI(t5)), this._container;
            }
            onRemove() {
              void 0 !== this._geolocationWatchID && (window.navigator.geolocation.clearWatch(this._geolocationWatchID), this._geolocationWatchID = void 0), this.options.showUserLocation && this._userLocationDotMarker && this._userLocationDotMarker.remove(), this.options.showAccuracyCircle && this._accuracyCircleMarker && this._accuracyCircleMarker.remove(), r.remove(this._container), this._map.off("zoom", this._onZoom), this._map = void 0, Hs = 0, Ws = false;
            }
            _isOutOfMapMaxBounds(t4) {
              const e2 = this._map.getMaxBounds(), i2 = t4.coords;
              return e2 && (i2.longitude < e2.getWest() || i2.longitude > e2.getEast() || i2.latitude < e2.getSouth() || i2.latitude > e2.getNorth());
            }
            _setErrorState() {
              switch (this._watchState) {
                case "WAITING_ACTIVE":
                  this._watchState = "ACTIVE_ERROR", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");
                  break;
                case "ACTIVE_LOCK":
                  this._watchState = "ACTIVE_ERROR", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");
                  break;
                case "BACKGROUND":
                  this._watchState = "BACKGROUND_ERROR", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");
                  break;
                case "ACTIVE_ERROR":
                  break;
                default:
                  throw new Error(`Unexpected watchState ${this._watchState}`);
              }
            }
            _updateCircleRadius() {
              const t4 = this._map.getBounds(), e2 = t4.getSouthEast(), i2 = t4.getNorthEast(), a2 = e2.distanceTo(i2), s2 = Math.ceil(this._accuracy / (a2 / this._map._container.clientHeight) * 2);
              this._circleElement.style.width = `${s2}px`, this._circleElement.style.height = `${s2}px`;
            }
            trigger() {
              if (!this._setup) return e.w("Geolocate control triggered before added to a map"), false;
              if (this.options.trackUserLocation) {
                switch (this._watchState) {
                  case "OFF":
                    this._watchState = "WAITING_ACTIVE", this.fire(new e.k("trackuserlocationstart"));
                    break;
                  case "WAITING_ACTIVE":
                  case "ACTIVE_LOCK":
                  case "ACTIVE_ERROR":
                  case "BACKGROUND_ERROR":
                    Hs--, Ws = false, this._watchState = "OFF", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"), this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"), this.fire(new e.k("trackuserlocationend"));
                    break;
                  case "BACKGROUND":
                    this._watchState = "ACTIVE_LOCK", this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"), this._lastKnownPosition && this._updateCamera(this._lastKnownPosition), this.fire(new e.k("trackuserlocationstart")), this.fire(new e.k("userlocationfocus"));
                    break;
                  default:
                    throw new Error(`Unexpected watchState ${this._watchState}`);
                }
                switch (this._watchState) {
                  case "WAITING_ACTIVE":
                    this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"), this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");
                    break;
                  case "ACTIVE_LOCK":
                    this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");
                    break;
                  case "OFF":
                    break;
                  default:
                    throw new Error(`Unexpected watchState ${this._watchState}`);
                }
                if ("OFF" === this._watchState && void 0 !== this._geolocationWatchID) this._clearWatch();
                else if (void 0 === this._geolocationWatchID) {
                  let t4;
                  this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"), this._geolocateButton.setAttribute("aria-pressed", "true"), Hs++, Hs > 1 ? (t4 = { maximumAge: 6e5, timeout: 0 }, Ws = true) : (t4 = this.options.positionOptions, Ws = false), this._geolocationWatchID = window.navigator.geolocation.watchPosition(this._onSuccess, this._onError, t4);
                }
              } else window.navigator.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions), this._timeoutId = setTimeout(this._finish, 1e4);
              return true;
            }
            _clearWatch() {
              window.navigator.geolocation.clearWatch(this._geolocationWatchID), this._geolocationWatchID = void 0, this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"), this._geolocateButton.setAttribute("aria-pressed", "false"), this.options.showUserLocation && this._updateMarker(null);
            }
          }, t.Hash = Ea, t.ImageSource = Q, t.KeyboardHandler = ls, t.LngLatBounds = H, t.LogoControl = Ps, t.Map = class extends Ts {
            constructor(t4) {
              e.bf.mark(e.bg.create);
              const i2 = Object.assign(Object.assign({}, Fs), t4);
              if (null != i2.minZoom && null != i2.maxZoom && i2.minZoom > i2.maxZoom) throw new Error("maxZoom must be greater than or equal to minZoom");
              if (null != i2.minPitch && null != i2.maxPitch && i2.minPitch > i2.maxPitch) throw new Error("maxPitch must be greater than or equal to minPitch");
              if (null != i2.minPitch && i2.minPitch < 0) throw new Error("minPitch must be greater than or equal to 0");
              if (null != i2.maxPitch && i2.maxPitch > 85) throw new Error("maxPitch must be less than or equal to 85");
              if (super(new Ta(i2.minZoom, i2.maxZoom, i2.minPitch, i2.maxPitch, i2.renderWorldCopies), { bearingSnap: i2.bearingSnap }), this._idleTriggered = false, this._crossFadingFactor = 1, this._renderTaskQueue = new Cs(), this._controls = [], this._mapId = e.a4(), this._contextLost = (t5) => {
                t5.preventDefault(), this._frameRequest && (this._frameRequest.abort(), this._frameRequest = null), this.fire(new e.k("webglcontextlost", { originalEvent: t5 }));
              }, this._contextRestored = (t5) => {
                this._setupPainter(), this.resize(), this._update(), this.fire(new e.k("webglcontextrestored", { originalEvent: t5 }));
              }, this._onMapScroll = (t5) => {
                if (t5.target === this._container) return this._container.scrollTop = 0, this._container.scrollLeft = 0, false;
              }, this._onWindowOnline = () => {
                this._update();
              }, this._interactive = i2.interactive, this._maxTileCacheSize = i2.maxTileCacheSize, this._maxTileCacheZoomLevels = i2.maxTileCacheZoomLevels, this._failIfMajorPerformanceCaveat = true === i2.failIfMajorPerformanceCaveat, this._preserveDrawingBuffer = true === i2.preserveDrawingBuffer, this._antialias = true === i2.antialias, this._trackResize = true === i2.trackResize, this._bearingSnap = i2.bearingSnap, this._refreshExpiredTiles = true === i2.refreshExpiredTiles, this._fadeDuration = i2.fadeDuration, this._crossSourceCollisions = true === i2.crossSourceCollisions, this._collectResourceTiming = true === i2.collectResourceTiming, this._locale = Object.assign(Object.assign({}, ks), i2.locale), this._clickTolerance = i2.clickTolerance, this._overridePixelRatio = i2.pixelRatio, this._maxCanvasSize = i2.maxCanvasSize, this.transformCameraUpdate = i2.transformCameraUpdate, this.cancelPendingTileRequestsWhileZooming = true === i2.cancelPendingTileRequestsWhileZooming, this._imageQueueHandle = _.addThrottleControl(() => this.isMoving()), this._requestManager = new p(i2.transformRequest), "string" == typeof i2.container) {
                if (this._container = document.getElementById(i2.container), !this._container) throw new Error(`Container '${i2.container}' not found.`);
              } else {
                if (!(i2.container instanceof HTMLElement)) throw new Error("Invalid type: 'container' must be a String or HTMLElement.");
                this._container = i2.container;
              }
              if (i2.maxBounds && this.setMaxBounds(i2.maxBounds), this._setupContainer(), this._setupPainter(), this.on("move", () => this._update(false)).on("moveend", () => this._update(false)).on("zoom", () => this._update(true)).on("terrain", () => {
                this.painter.terrainFacilitator.dirty = true, this._update(true);
              }).once("idle", () => {
                this._idleTriggered = true;
              }), "undefined" != typeof window) {
                addEventListener("online", this._onWindowOnline, false);
                let t5 = false;
                const e2 = Ia((t6) => {
                  this._trackResize && !this._removed && (this.resize(t6), this.redraw());
                }, 50);
                this._resizeObserver = new ResizeObserver((i3) => {
                  t5 ? e2(i3) : t5 = true;
                }), this._resizeObserver.observe(this._container);
              }
              this.handlers = new ws(this, i2), this._hash = i2.hash && new Ea("string" == typeof i2.hash && i2.hash || void 0).addTo(this), this._hash && this._hash._onHashChange() || (this.jumpTo({ center: i2.center, zoom: i2.zoom, bearing: i2.bearing, pitch: i2.pitch }), i2.bounds && (this.resize(), this.fitBounds(i2.bounds, e.e({}, i2.fitBoundsOptions, { duration: 0 })))), this.resize(), this._localIdeographFontFamily = i2.localIdeographFontFamily, this._validateStyle = i2.validateStyle, i2.style && this.setStyle(i2.style, { localIdeographFontFamily: i2.localIdeographFontFamily }), i2.attributionControl && this.addControl(new Es("boolean" == typeof i2.attributionControl ? void 0 : i2.attributionControl)), i2.maplibreLogo && this.addControl(new Ps(), i2.logoPosition), this.on("style.load", () => {
                this.transform.unmodified && this.jumpTo(this.style.stylesheet);
              }), this.on("data", (t5) => {
                this._update("style" === t5.dataType), this.fire(new e.k(`${t5.dataType}data`, t5));
              }), this.on("dataloading", (t5) => {
                this.fire(new e.k(`${t5.dataType}dataloading`, t5));
              }), this.on("dataabort", (t5) => {
                this.fire(new e.k("sourcedataabort", t5));
              });
            }
            _getMapId() {
              return this._mapId;
            }
            addControl(t4, i2) {
              if (void 0 === i2 && (i2 = t4.getDefaultPosition ? t4.getDefaultPosition() : "top-right"), !t4 || !t4.onAdd) return this.fire(new e.j(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));
              const a2 = t4.onAdd(this);
              this._controls.push(t4);
              const s2 = this._controlPositions[i2];
              return -1 !== i2.indexOf("bottom") ? s2.insertBefore(a2, s2.firstChild) : s2.appendChild(a2), this;
            }
            removeControl(t4) {
              if (!t4 || !t4.onRemove) return this.fire(new e.j(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));
              const i2 = this._controls.indexOf(t4);
              return i2 > -1 && this._controls.splice(i2, 1), t4.onRemove(this), this;
            }
            hasControl(t4) {
              return this._controls.indexOf(t4) > -1;
            }
            calculateCameraOptionsFromTo(t4, e2, i2, a2) {
              return null == a2 && this.terrain && (a2 = this.terrain.getElevationForLngLatZoom(i2, this.transform.tileZoom)), super.calculateCameraOptionsFromTo(t4, e2, i2, a2);
            }
            resize(t4) {
              var i2;
              const a2 = this._containerDimensions(), s2 = a2[0], o2 = a2[1], r2 = this._getClampedPixelRatio(s2, o2);
              if (this._resizeCanvas(s2, o2, r2), this.painter.resize(s2, o2, r2), this.painter.overLimit()) {
                const t5 = this.painter.context.gl;
                this._maxCanvasSize = [t5.drawingBufferWidth, t5.drawingBufferHeight];
                const e2 = this._getClampedPixelRatio(s2, o2);
                this._resizeCanvas(s2, o2, e2), this.painter.resize(s2, o2, e2);
              }
              this.transform.resize(s2, o2), null === (i2 = this._requestedCameraState) || void 0 === i2 || i2.resize(s2, o2);
              const n2 = !this._moving;
              return n2 && (this.stop(), this.fire(new e.k("movestart", t4)).fire(new e.k("move", t4))), this.fire(new e.k("resize", t4)), n2 && this.fire(new e.k("moveend", t4)), this;
            }
            _getClampedPixelRatio(t4, e2) {
              const { 0: i2, 1: a2 } = this._maxCanvasSize, s2 = this.getPixelRatio(), o2 = t4 * s2, r2 = e2 * s2;
              return Math.min(o2 > i2 ? i2 / o2 : 1, r2 > a2 ? a2 / r2 : 1) * s2;
            }
            getPixelRatio() {
              var t4;
              return null !== (t4 = this._overridePixelRatio) && void 0 !== t4 ? t4 : devicePixelRatio;
            }
            setPixelRatio(t4) {
              this._overridePixelRatio = t4, this.resize();
            }
            getBounds() {
              return this.transform.getBounds();
            }
            getMaxBounds() {
              return this.transform.getMaxBounds();
            }
            setMaxBounds(t4) {
              return this.transform.setMaxBounds(H.convert(t4)), this._update();
            }
            setMinZoom(t4) {
              if ((t4 = null == t4 ? -2 : t4) >= -2 && t4 <= this.transform.maxZoom) return this.transform.minZoom = t4, this._update(), this.getZoom() < t4 && this.setZoom(t4), this;
              throw new Error("minZoom must be between -2 and the current maxZoom, inclusive");
            }
            getMinZoom() {
              return this.transform.minZoom;
            }
            setMaxZoom(t4) {
              if ((t4 = null == t4 ? 22 : t4) >= this.transform.minZoom) return this.transform.maxZoom = t4, this._update(), this.getZoom() > t4 && this.setZoom(t4), this;
              throw new Error("maxZoom must be greater than the current minZoom");
            }
            getMaxZoom() {
              return this.transform.maxZoom;
            }
            setMinPitch(t4) {
              if ((t4 = null == t4 ? 0 : t4) < 0) throw new Error("minPitch must be greater than or equal to 0");
              if (t4 >= 0 && t4 <= this.transform.maxPitch) return this.transform.minPitch = t4, this._update(), this.getPitch() < t4 && this.setPitch(t4), this;
              throw new Error("minPitch must be between 0 and the current maxPitch, inclusive");
            }
            getMinPitch() {
              return this.transform.minPitch;
            }
            setMaxPitch(t4) {
              if ((t4 = null == t4 ? 60 : t4) > 85) throw new Error("maxPitch must be less than or equal to 85");
              if (t4 >= this.transform.minPitch) return this.transform.maxPitch = t4, this._update(), this.getPitch() > t4 && this.setPitch(t4), this;
              throw new Error("maxPitch must be greater than the current minPitch");
            }
            getMaxPitch() {
              return this.transform.maxPitch;
            }
            getRenderWorldCopies() {
              return this.transform.renderWorldCopies;
            }
            setRenderWorldCopies(t4) {
              return this.transform.renderWorldCopies = t4, this._update();
            }
            project(t4) {
              return this.transform.locationPoint(e.N.convert(t4), this.style && this.terrain);
            }
            unproject(t4) {
              return this.transform.pointLocation(e.P.convert(t4), this.terrain);
            }
            isMoving() {
              var t4;
              return this._moving || (null === (t4 = this.handlers) || void 0 === t4 ? void 0 : t4.isMoving());
            }
            isZooming() {
              var t4;
              return this._zooming || (null === (t4 = this.handlers) || void 0 === t4 ? void 0 : t4.isZooming());
            }
            isRotating() {
              var t4;
              return this._rotating || (null === (t4 = this.handlers) || void 0 === t4 ? void 0 : t4.isRotating());
            }
            _createDelegatedListener(t4, e2, i2) {
              if ("mouseenter" === t4 || "mouseover" === t4) {
                let a2 = false;
                const s2 = (s3) => {
                  const o2 = e2.filter((t5) => this.getLayer(t5)), r2 = 0 !== o2.length ? this.queryRenderedFeatures(s3.point, { layers: o2 }) : [];
                  r2.length ? a2 || (a2 = true, i2.call(this, new ka(t4, this, s3.originalEvent, { features: r2 }))) : a2 = false;
                };
                return { layers: e2, listener: i2, delegates: { mousemove: s2, mouseout: () => {
                  a2 = false;
                } } };
              }
              if ("mouseleave" === t4 || "mouseout" === t4) {
                let a2 = false;
                const s2 = (s3) => {
                  const o3 = e2.filter((t5) => this.getLayer(t5));
                  (0 !== o3.length ? this.queryRenderedFeatures(s3.point, { layers: o3 }) : []).length ? a2 = true : a2 && (a2 = false, i2.call(this, new ka(t4, this, s3.originalEvent)));
                }, o2 = (e3) => {
                  a2 && (a2 = false, i2.call(this, new ka(t4, this, e3.originalEvent)));
                };
                return { layers: e2, listener: i2, delegates: { mousemove: s2, mouseout: o2 } };
              }
              {
                const a2 = (t5) => {
                  const a3 = e2.filter((t6) => this.getLayer(t6)), s2 = 0 !== a3.length ? this.queryRenderedFeatures(t5.point, { layers: a3 }) : [];
                  s2.length && (t5.features = s2, i2.call(this, t5), delete t5.features);
                };
                return { layers: e2, listener: i2, delegates: { [t4]: a2 } };
              }
            }
            _saveDelegatedListener(t4, e2) {
              this._delegatedListeners = this._delegatedListeners || {}, this._delegatedListeners[t4] = this._delegatedListeners[t4] || [], this._delegatedListeners[t4].push(e2);
            }
            _removeDelegatedListener(t4, e2, i2) {
              if (!this._delegatedListeners || !this._delegatedListeners[t4]) return;
              const a2 = this._delegatedListeners[t4];
              for (let t5 = 0; t5 < a2.length; t5++) {
                const s2 = a2[t5];
                if (s2.listener === i2 && s2.layers.length === e2.length && s2.layers.every((t6) => e2.includes(t6))) {
                  for (const t6 in s2.delegates) this.off(t6, s2.delegates[t6]);
                  return void a2.splice(t5, 1);
                }
              }
            }
            on(t4, e2, i2) {
              if (void 0 === i2) return super.on(t4, e2);
              const a2 = this._createDelegatedListener(t4, "string" == typeof e2 ? [e2] : e2, i2);
              this._saveDelegatedListener(t4, a2);
              for (const t5 in a2.delegates) this.on(t5, a2.delegates[t5]);
              return this;
            }
            once(t4, e2, i2) {
              if (void 0 === i2) return super.once(t4, e2);
              const a2 = "string" == typeof e2 ? [e2] : e2, s2 = this._createDelegatedListener(t4, a2, i2);
              for (const e3 in s2.delegates) {
                const o2 = s2.delegates[e3];
                s2.delegates[e3] = (...e4) => {
                  this._removeDelegatedListener(t4, a2, i2), o2(...e4);
                };
              }
              this._saveDelegatedListener(t4, s2);
              for (const t5 in s2.delegates) this.once(t5, s2.delegates[t5]);
              return this;
            }
            off(t4, e2, i2) {
              return void 0 === i2 ? super.off(t4, e2) : (this._removeDelegatedListener(t4, "string" == typeof e2 ? [e2] : e2, i2), this);
            }
            queryRenderedFeatures(t4, i2) {
              if (!this.style) return [];
              let a2;
              const s2 = t4 instanceof e.P || Array.isArray(t4), o2 = s2 ? t4 : [[0, 0], [this.transform.width, this.transform.height]];
              if (i2 = i2 || (s2 ? {} : t4) || {}, o2 instanceof e.P || "number" == typeof o2[0]) a2 = [e.P.convert(o2)];
              else {
                const t5 = e.P.convert(o2[0]), i3 = e.P.convert(o2[1]);
                a2 = [t5, new e.P(i3.x, t5.y), i3, new e.P(t5.x, i3.y), t5];
              }
              return this.style.queryRenderedFeatures(a2, i2, this.transform);
            }
            querySourceFeatures(t4, e2) {
              return this.style.querySourceFeatures(t4, e2);
            }
            setStyle(t4, i2) {
              return false !== (i2 = e.e({}, { localIdeographFontFamily: this._localIdeographFontFamily, validate: this._validateStyle }, i2)).diff && i2.localIdeographFontFamily === this._localIdeographFontFamily && this.style && t4 ? (this._diffStyle(t4, i2), this) : (this._localIdeographFontFamily = i2.localIdeographFontFamily, this._updateStyle(t4, i2));
            }
            setTransformRequest(t4) {
              return this._requestManager.setTransformRequest(t4), this;
            }
            _getUIString(t4) {
              const e2 = this._locale[t4];
              if (null == e2) throw new Error(`Missing UI string '${t4}'`);
              return e2;
            }
            _updateStyle(t4, e2) {
              if (e2.transformStyle && this.style && !this.style._loaded) return void this.style.once("style.load", () => this._updateStyle(t4, e2));
              const i2 = this.style && e2.transformStyle ? this.style.serialize() : void 0;
              return this.style && (this.style.setEventedParent(null), this.style._remove(!t4)), t4 ? (this.style = new de(this, e2 || {}), this.style.setEventedParent(this, { style: this.style }), "string" == typeof t4 ? this.style.loadURL(t4, e2, i2) : this.style.loadJSON(t4, e2, i2), this) : (delete this.style, this);
            }
            _lazyInitEmptyStyle() {
              this.style || (this.style = new de(this, {}), this.style.setEventedParent(this, { style: this.style }), this.style.loadEmpty());
            }
            _diffStyle(t4, i2) {
              if ("string" == typeof t4) {
                const a2 = this._requestManager.transformRequest(t4, "Style");
                e.h(a2, new AbortController()).then((t5) => {
                  this._updateDiff(t5.data, i2);
                }).catch((t5) => {
                  t5 && this.fire(new e.j(t5));
                });
              } else "object" == typeof t4 && this._updateDiff(t4, i2);
            }
            _updateDiff(t4, i2) {
              try {
                this.style.setState(t4, i2) && this._update(true);
              } catch (a2) {
                e.w(`Unable to perform style diff: ${a2.message || a2.error || a2}.  Rebuilding the style from scratch.`), this._updateStyle(t4, i2);
              }
            }
            getStyle() {
              if (this.style) return this.style.serialize();
            }
            isStyleLoaded() {
              return this.style ? this.style.loaded() : e.w("There is no style added to the map.");
            }
            addSource(t4, e2) {
              return this._lazyInitEmptyStyle(), this.style.addSource(t4, e2), this._update(true);
            }
            isSourceLoaded(t4) {
              const i2 = this.style && this.style.sourceCaches[t4];
              if (void 0 !== i2) return i2.loaded();
              this.fire(new e.j(new Error(`There is no source with ID '${t4}'`)));
            }
            setTerrain(t4) {
              if (this.style._checkLoaded(), this._terrainDataCallback && this.style.off("data", this._terrainDataCallback), t4) {
                const i2 = this.style.sourceCaches[t4.source];
                if (!i2) throw new Error(`cannot load terrain, because there exists no source with ID: ${t4.source}`);
                null === this.terrain && i2.reload();
                for (const i3 in this.style._layers) {
                  const a2 = this.style._layers[i3];
                  "hillshade" === a2.type && a2.source === t4.source && e.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");
                }
                this.terrain = new Ds(this.painter, i2, t4), this.painter.renderToTexture = new Rs(this.painter, this.terrain), this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom), this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom), this._terrainDataCallback = (e2) => {
                  "style" === e2.dataType ? this.terrain.sourceCache.freeRtt() : "source" === e2.dataType && e2.tile && (e2.sourceId !== t4.source || this._elevationFreeze || (this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom), this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom)), this.terrain.sourceCache.freeRtt(e2.tile.tileID));
                }, this.style.on("data", this._terrainDataCallback);
              } else this.terrain && this.terrain.sourceCache.destruct(), this.terrain = null, this.painter.renderToTexture && this.painter.renderToTexture.destruct(), this.painter.renderToTexture = null, this.transform.minElevationForCurrentTile = 0, this.transform.elevation = 0;
              return this.fire(new e.k("terrain", { terrain: t4 })), this;
            }
            getTerrain() {
              var t4, e2;
              return null !== (e2 = null === (t4 = this.terrain) || void 0 === t4 ? void 0 : t4.options) && void 0 !== e2 ? e2 : null;
            }
            areTilesLoaded() {
              const t4 = this.style && this.style.sourceCaches;
              for (const e2 in t4) {
                const i2 = t4[e2]._tiles;
                for (const t5 in i2) {
                  const e3 = i2[t5];
                  if ("loaded" !== e3.state && "errored" !== e3.state) return false;
                }
              }
              return true;
            }
            removeSource(t4) {
              return this.style.removeSource(t4), this._update(true);
            }
            getSource(t4) {
              return this.style.getSource(t4);
            }
            addImage(t4, i2, a2 = {}) {
              const { pixelRatio: s2 = 1, sdf: r2 = false, stretchX: n2, stretchY: l2, content: h2, textFitWidth: c2, textFitHeight: u2 } = a2;
              if (this._lazyInitEmptyStyle(), !(i2 instanceof HTMLImageElement || e.b(i2))) {
                if (void 0 === i2.width || void 0 === i2.height) return this.fire(new e.j(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));
                {
                  const { width: a3, height: o2, data: d2 } = i2, _2 = i2;
                  return this.style.addImage(t4, { data: new e.R({ width: a3, height: o2 }, new Uint8Array(d2)), pixelRatio: s2, stretchX: n2, stretchY: l2, content: h2, textFitWidth: c2, textFitHeight: u2, sdf: r2, version: 0, userImage: _2 }), _2.onAdd && _2.onAdd(this, t4), this;
                }
              }
              {
                const { width: a3, height: d2, data: _2 } = o.getImageData(i2);
                this.style.addImage(t4, { data: new e.R({ width: a3, height: d2 }, _2), pixelRatio: s2, stretchX: n2, stretchY: l2, content: h2, textFitWidth: c2, textFitHeight: u2, sdf: r2, version: 0 });
              }
            }
            updateImage(t4, i2) {
              const a2 = this.style.getImage(t4);
              if (!a2) return this.fire(new e.j(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));
              const s2 = i2 instanceof HTMLImageElement || e.b(i2) ? o.getImageData(i2) : i2, { width: r2, height: n2, data: l2 } = s2;
              if (void 0 === r2 || void 0 === n2) return this.fire(new e.j(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));
              if (r2 !== a2.data.width || n2 !== a2.data.height) return this.fire(new e.j(new Error("The width and height of the updated image must be that same as the previous version of the image")));
              const h2 = !(i2 instanceof HTMLImageElement || e.b(i2));
              return a2.data.replace(l2, h2), this.style.updateImage(t4, a2), this;
            }
            getImage(t4) {
              return this.style.getImage(t4);
            }
            hasImage(t4) {
              return t4 ? !!this.style.getImage(t4) : (this.fire(new e.j(new Error("Missing required image id"))), false);
            }
            removeImage(t4) {
              this.style.removeImage(t4);
            }
            loadImage(t4) {
              return _.getImage(this._requestManager.transformRequest(t4, "Image"), new AbortController());
            }
            listImages() {
              return this.style.listImages();
            }
            addLayer(t4, e2) {
              return this._lazyInitEmptyStyle(), this.style.addLayer(t4, e2), this._update(true);
            }
            moveLayer(t4, e2) {
              return this.style.moveLayer(t4, e2), this._update(true);
            }
            removeLayer(t4) {
              return this.style.removeLayer(t4), this._update(true);
            }
            getLayer(t4) {
              return this.style.getLayer(t4);
            }
            getLayersOrder() {
              return this.style.getLayersOrder();
            }
            setLayerZoomRange(t4, e2, i2) {
              return this.style.setLayerZoomRange(t4, e2, i2), this._update(true);
            }
            setFilter(t4, e2, i2 = {}) {
              return this.style.setFilter(t4, e2, i2), this._update(true);
            }
            getFilter(t4) {
              return this.style.getFilter(t4);
            }
            setPaintProperty(t4, e2, i2, a2 = {}) {
              return this.style.setPaintProperty(t4, e2, i2, a2), this._update(true);
            }
            getPaintProperty(t4, e2) {
              return this.style.getPaintProperty(t4, e2);
            }
            setLayoutProperty(t4, e2, i2, a2 = {}) {
              return this.style.setLayoutProperty(t4, e2, i2, a2), this._update(true);
            }
            getLayoutProperty(t4, e2) {
              return this.style.getLayoutProperty(t4, e2);
            }
            setGlyphs(t4, e2 = {}) {
              return this._lazyInitEmptyStyle(), this.style.setGlyphs(t4, e2), this._update(true);
            }
            getGlyphs() {
              return this.style.getGlyphsUrl();
            }
            addSprite(t4, e2, i2 = {}) {
              return this._lazyInitEmptyStyle(), this.style.addSprite(t4, e2, i2, (t5) => {
                t5 || this._update(true);
              }), this;
            }
            removeSprite(t4) {
              return this._lazyInitEmptyStyle(), this.style.removeSprite(t4), this._update(true);
            }
            getSprite() {
              return this.style.getSprite();
            }
            setSprite(t4, e2 = {}) {
              return this._lazyInitEmptyStyle(), this.style.setSprite(t4, e2, (t5) => {
                t5 || this._update(true);
              }), this;
            }
            setLight(t4, e2 = {}) {
              return this._lazyInitEmptyStyle(), this.style.setLight(t4, e2), this._update(true);
            }
            getLight() {
              return this.style.getLight();
            }
            setSky(t4) {
              return this._lazyInitEmptyStyle(), this.style.setSky(t4), this._update(true);
            }
            getSky() {
              return this.style.getSky();
            }
            setFeatureState(t4, e2) {
              return this.style.setFeatureState(t4, e2), this._update();
            }
            removeFeatureState(t4, e2) {
              return this.style.removeFeatureState(t4, e2), this._update();
            }
            getFeatureState(t4) {
              return this.style.getFeatureState(t4);
            }
            getContainer() {
              return this._container;
            }
            getCanvasContainer() {
              return this._canvasContainer;
            }
            getCanvas() {
              return this._canvas;
            }
            _containerDimensions() {
              let t4 = 0, e2 = 0;
              return this._container && (t4 = this._container.clientWidth || 400, e2 = this._container.clientHeight || 300), [t4, e2];
            }
            _setupContainer() {
              const t4 = this._container;
              t4.classList.add("maplibregl-map");
              const e2 = this._canvasContainer = r.create("div", "maplibregl-canvas-container", t4);
              this._interactive && e2.classList.add("maplibregl-interactive"), this._canvas = r.create("canvas", "maplibregl-canvas", e2), this._canvas.addEventListener("webglcontextlost", this._contextLost, false), this._canvas.addEventListener("webglcontextrestored", this._contextRestored, false), this._canvas.setAttribute("tabindex", this._interactive ? "0" : "-1"), this._canvas.setAttribute("aria-label", this._getUIString("Map.Title")), this._canvas.setAttribute("role", "region");
              const i2 = this._containerDimensions(), a2 = this._getClampedPixelRatio(i2[0], i2[1]);
              this._resizeCanvas(i2[0], i2[1], a2);
              const s2 = this._controlContainer = r.create("div", "maplibregl-control-container", t4), o2 = this._controlPositions = {};
              ["top-left", "top-right", "bottom-left", "bottom-right"].forEach((t5) => {
                o2[t5] = r.create("div", `maplibregl-ctrl-${t5} `, s2);
              }), this._container.addEventListener("scroll", this._onMapScroll, false);
            }
            _resizeCanvas(t4, e2, i2) {
              this._canvas.width = Math.floor(i2 * t4), this._canvas.height = Math.floor(i2 * e2), this._canvas.style.width = `${t4}px`, this._canvas.style.height = `${e2}px`;
            }
            _setupPainter() {
              const t4 = { alpha: true, stencil: true, depth: true, failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat, preserveDrawingBuffer: this._preserveDrawingBuffer, antialias: this._antialias || false };
              let e2 = null;
              this._canvas.addEventListener("webglcontextcreationerror", (i3) => {
                e2 = { requestedAttributes: t4 }, i3 && (e2.statusMessage = i3.statusMessage, e2.type = i3.type);
              }, { once: true });
              const i2 = this._canvas.getContext("webgl2", t4) || this._canvas.getContext("webgl", t4);
              if (!i2) {
                const t5 = "Failed to initialize WebGL";
                throw e2 ? (e2.message = t5, new Error(JSON.stringify(e2))) : new Error(t5);
              }
              this.painter = new va(i2, this.transform), n.testSupport(i2);
            }
            loaded() {
              return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();
            }
            _update(t4) {
              return this.style && this.style._loaded ? (this._styleDirty = this._styleDirty || t4, this._sourcesDirty = true, this.triggerRepaint(), this) : this;
            }
            _requestRenderFrame(t4) {
              return this._update(), this._renderTaskQueue.add(t4);
            }
            _cancelRenderFrame(t4) {
              this._renderTaskQueue.remove(t4);
            }
            _render(t4) {
              const i2 = this._idleTriggered ? this._fadeDuration : 0;
              if (this.painter.context.setDirty(), this.painter.setBaseState(), this._renderTaskQueue.run(t4), this._removed) return;
              let a2 = false;
              if (this.style && this._styleDirty) {
                this._styleDirty = false;
                const t5 = this.transform.zoom, s3 = o.now();
                this.style.zoomHistory.update(t5, s3);
                const r2 = new e.z(t5, { now: s3, fadeDuration: i2, zoomHistory: this.style.zoomHistory, transition: this.style.getTransition() }), n2 = r2.crossFadingFactor();
                1 === n2 && n2 === this._crossFadingFactor || (a2 = true, this._crossFadingFactor = n2), this.style.update(r2);
              }
              this.style && this._sourcesDirty && (this._sourcesDirty = false, this.style._updateSources(this.transform)), this.terrain ? (this.terrain.sourceCache.update(this.transform, this.terrain), this.transform.minElevationForCurrentTile = this.terrain.getMinTileElevationForLngLatZoom(this.transform.center, this.transform.tileZoom), this._elevationFreeze || (this.transform.elevation = this.terrain.getElevationForLngLatZoom(this.transform.center, this.transform.tileZoom))) : (this.transform.minElevationForCurrentTile = 0, this.transform.elevation = 0), this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, i2, this._crossSourceCollisions), this.painter.render(this.style, { showTileBoundaries: this.showTileBoundaries, showOverdrawInspector: this._showOverdrawInspector, rotating: this.isRotating(), zooming: this.isZooming(), moving: this.isMoving(), fadeDuration: i2, showPadding: this.showPadding }), this.fire(new e.k("render")), this.loaded() && !this._loaded && (this._loaded = true, e.bf.mark(e.bg.load), this.fire(new e.k("load"))), this.style && (this.style.hasTransitions() || a2) && (this._styleDirty = true), this.style && !this._placementDirty && this.style._releaseSymbolFadeTiles();
              const s2 = this._sourcesDirty || this._styleDirty || this._placementDirty;
              return s2 || this._repaint ? this.triggerRepaint() : !this.isMoving() && this.loaded() && this.fire(new e.k("idle")), !this._loaded || this._fullyLoaded || s2 || (this._fullyLoaded = true, e.bf.mark(e.bg.fullLoad)), this;
            }
            redraw() {
              return this.style && (this._frameRequest && (this._frameRequest.abort(), this._frameRequest = null), this._render(0)), this;
            }
            remove() {
              var t4;
              this._hash && this._hash.remove();
              for (const t5 of this._controls) t5.onRemove(this);
              this._controls = [], this._frameRequest && (this._frameRequest.abort(), this._frameRequest = null), this._renderTaskQueue.clear(), this.painter.destroy(), this.handlers.destroy(), delete this.handlers, this.setStyle(null), "undefined" != typeof window && removeEventListener("online", this._onWindowOnline, false), _.removeThrottleControl(this._imageQueueHandle), null === (t4 = this._resizeObserver) || void 0 === t4 || t4.disconnect();
              const i2 = this.painter.context.gl.getExtension("WEBGL_lose_context");
              (null == i2 ? void 0 : i2.loseContext) && i2.loseContext(), this._canvas.removeEventListener("webglcontextrestored", this._contextRestored, false), this._canvas.removeEventListener("webglcontextlost", this._contextLost, false), r.remove(this._canvasContainer), r.remove(this._controlContainer), this._container.classList.remove("maplibregl-map"), e.bf.clearMetrics(), this._removed = true, this.fire(new e.k("remove"));
            }
            triggerRepaint() {
              this.style && !this._frameRequest && (this._frameRequest = new AbortController(), o.frameAsync(this._frameRequest).then((t4) => {
                e.bf.frame(t4), this._frameRequest = null, this._render(t4);
              }).catch(() => {
              }));
            }
            get showTileBoundaries() {
              return !!this._showTileBoundaries;
            }
            set showTileBoundaries(t4) {
              this._showTileBoundaries !== t4 && (this._showTileBoundaries = t4, this._update());
            }
            get showPadding() {
              return !!this._showPadding;
            }
            set showPadding(t4) {
              this._showPadding !== t4 && (this._showPadding = t4, this._update());
            }
            get showCollisionBoxes() {
              return !!this._showCollisionBoxes;
            }
            set showCollisionBoxes(t4) {
              this._showCollisionBoxes !== t4 && (this._showCollisionBoxes = t4, t4 ? this.style._generateCollisionBoxes() : this._update());
            }
            get showOverdrawInspector() {
              return !!this._showOverdrawInspector;
            }
            set showOverdrawInspector(t4) {
              this._showOverdrawInspector !== t4 && (this._showOverdrawInspector = t4, this._update());
            }
            get repaint() {
              return !!this._repaint;
            }
            set repaint(t4) {
              this._repaint !== t4 && (this._repaint = t4, this.triggerRepaint());
            }
            get vertices() {
              return !!this._vertices;
            }
            set vertices(t4) {
              this._vertices = t4, this._update();
            }
            get version() {
              return Ls;
            }
            getCameraTargetElevation() {
              return this.transform.elevation;
            }
          }, t.MapMouseEvent = ka, t.MapTouchEvent = La, t.MapWheelEvent = Fa, t.Marker = Vs, t.NavigationControl = class {
            constructor(t4) {
              this._updateZoomButtons = () => {
                const t5 = this._map.getZoom(), e2 = t5 === this._map.getMaxZoom(), i2 = t5 === this._map.getMinZoom();
                this._zoomInButton.disabled = e2, this._zoomOutButton.disabled = i2, this._zoomInButton.setAttribute("aria-disabled", e2.toString()), this._zoomOutButton.setAttribute("aria-disabled", i2.toString());
              }, this._rotateCompassArrow = () => {
                const t5 = this.options.visualizePitch ? `scale(${1 / Math.pow(Math.cos(this._map.transform.pitch * (Math.PI / 180)), 0.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle * (180 / Math.PI)}deg)` : `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`;
                this._compassIcon.style.transform = t5;
              }, this._setButtonTitle = (t5, e2) => {
                const i2 = this._map._getUIString(`NavigationControl.${e2}`);
                t5.title = i2, t5.setAttribute("aria-label", i2);
              }, this.options = e.e({}, Os, t4), this._container = r.create("div", "maplibregl-ctrl maplibregl-ctrl-group"), this._container.addEventListener("contextmenu", (t5) => t5.preventDefault()), this.options.showZoom && (this._zoomInButton = this._createButton("maplibregl-ctrl-zoom-in", (t5) => this._map.zoomIn({}, { originalEvent: t5 })), r.create("span", "maplibregl-ctrl-icon", this._zoomInButton).setAttribute("aria-hidden", "true"), this._zoomOutButton = this._createButton("maplibregl-ctrl-zoom-out", (t5) => this._map.zoomOut({}, { originalEvent: t5 })), r.create("span", "maplibregl-ctrl-icon", this._zoomOutButton).setAttribute("aria-hidden", "true")), this.options.showCompass && (this._compass = this._createButton("maplibregl-ctrl-compass", (t5) => {
                this.options.visualizePitch ? this._map.resetNorthPitch({}, { originalEvent: t5 }) : this._map.resetNorth({}, { originalEvent: t5 });
              }), this._compassIcon = r.create("span", "maplibregl-ctrl-icon", this._compass), this._compassIcon.setAttribute("aria-hidden", "true"));
            }
            onAdd(t4) {
              return this._map = t4, this.options.showZoom && (this._setButtonTitle(this._zoomInButton, "ZoomIn"), this._setButtonTitle(this._zoomOutButton, "ZoomOut"), this._map.on("zoom", this._updateZoomButtons), this._updateZoomButtons()), this.options.showCompass && (this._setButtonTitle(this._compass, "ResetBearing"), this.options.visualizePitch && this._map.on("pitch", this._rotateCompassArrow), this._map.on("rotate", this._rotateCompassArrow), this._rotateCompassArrow(), this._handler = new Ns(this._map, this._compass, this.options.visualizePitch)), this._container;
            }
            onRemove() {
              r.remove(this._container), this.options.showZoom && this._map.off("zoom", this._updateZoomButtons), this.options.showCompass && (this.options.visualizePitch && this._map.off("pitch", this._rotateCompassArrow), this._map.off("rotate", this._rotateCompassArrow), this._handler.off(), delete this._handler), delete this._map;
            }
            _createButton(t4, e2) {
              const i2 = r.create("button", t4, this._container);
              return i2.type = "button", i2.addEventListener("click", e2), i2;
            }
          }, t.Popup = class extends e.E {
            constructor(t4) {
              super(), this.remove = () => (this._content && r.remove(this._content), this._container && (r.remove(this._container), delete this._container), this._map && (this._map.off("move", this._update), this._map.off("move", this._onClose), this._map.off("click", this._onClose), this._map.off("remove", this.remove), this._map.off("mousemove", this._onMouseMove), this._map.off("mouseup", this._onMouseUp), this._map.off("drag", this._onDrag), this._map._canvasContainer.classList.remove("maplibregl-track-pointer"), delete this._map, this.fire(new e.k("close"))), this), this._onMouseUp = (t5) => {
                this._update(t5.point);
              }, this._onMouseMove = (t5) => {
                this._update(t5.point);
              }, this._onDrag = (t5) => {
                this._update(t5.point);
              }, this._update = (t5) => {
                var e2;
                if (!this._map || !this._lngLat && !this._trackPointer || !this._content) return;
                if (!this._container) {
                  if (this._container = r.create("div", "maplibregl-popup", this._map.getContainer()), this._tip = r.create("div", "maplibregl-popup-tip", this._container), this._container.appendChild(this._content), this.options.className) for (const t6 of this.options.className.split(" ")) this._container.classList.add(t6);
                  this._closeButton && this._closeButton.setAttribute("aria-label", this._map._getUIString("Popup.Close")), this._trackPointer && this._container.classList.add("maplibregl-popup-track-pointer");
                }
                if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth && (this._container.style.maxWidth = this.options.maxWidth), this._lngLat = this._map.transform.renderWorldCopies && !this._trackPointer ? js(this._lngLat, this._flatPos, this._map.transform) : null === (e2 = this._lngLat) || void 0 === e2 ? void 0 : e2.wrap(), this._trackPointer && !t5) return;
                const i2 = this._flatPos = this._pos = this._trackPointer && t5 ? t5 : this._map.project(this._lngLat);
                this._map.terrain && (this._flatPos = this._trackPointer && t5 ? t5 : this._map.transform.locationPoint(this._lngLat));
                let a2 = this.options.anchor;
                const s2 = Qs(this.options.offset);
                if (!a2) {
                  const t6 = this._container.offsetWidth, e3 = this._container.offsetHeight;
                  let o3;
                  o3 = i2.y + s2.bottom.y < e3 ? ["top"] : i2.y > this._map.transform.height - e3 ? ["bottom"] : [], i2.x < t6 / 2 ? o3.push("left") : i2.x > this._map.transform.width - t6 / 2 && o3.push("right"), a2 = 0 === o3.length ? "bottom" : o3.join("-");
                }
                let o2 = i2.add(s2[a2]);
                this.options.subpixelPositioning || (o2 = o2.round()), r.setTransform(this._container, `${Zs[a2]} translate(${o2.x}px,${o2.y}px)`), qs(this._container, a2, "popup");
              }, this._onClose = () => {
                this.remove();
              }, this.options = e.e(Object.create(Js), t4);
            }
            addTo(t4) {
              return this._map && this.remove(), this._map = t4, this.options.closeOnClick && this._map.on("click", this._onClose), this.options.closeOnMove && this._map.on("move", this._onClose), this._map.on("remove", this.remove), this._update(), this._focusFirstElement(), this._trackPointer ? (this._map.on("mousemove", this._onMouseMove), this._map.on("mouseup", this._onMouseUp), this._container && this._container.classList.add("maplibregl-popup-track-pointer"), this._map._canvasContainer.classList.add("maplibregl-track-pointer")) : this._map.on("move", this._update), this.fire(new e.k("open")), this;
            }
            isOpen() {
              return !!this._map;
            }
            getLngLat() {
              return this._lngLat;
            }
            setLngLat(t4) {
              return this._lngLat = e.N.convert(t4), this._pos = null, this._flatPos = null, this._trackPointer = false, this._update(), this._map && (this._map.on("move", this._update), this._map.off("mousemove", this._onMouseMove), this._container && this._container.classList.remove("maplibregl-popup-track-pointer"), this._map._canvasContainer.classList.remove("maplibregl-track-pointer")), this;
            }
            trackPointer() {
              return this._trackPointer = true, this._pos = null, this._flatPos = null, this._update(), this._map && (this._map.off("move", this._update), this._map.on("mousemove", this._onMouseMove), this._map.on("drag", this._onDrag), this._container && this._container.classList.add("maplibregl-popup-track-pointer"), this._map._canvasContainer.classList.add("maplibregl-track-pointer")), this;
            }
            getElement() {
              return this._container;
            }
            setText(t4) {
              return this.setDOMContent(document.createTextNode(t4));
            }
            setHTML(t4) {
              const e2 = document.createDocumentFragment(), i2 = document.createElement("body");
              let a2;
              for (i2.innerHTML = t4; a2 = i2.firstChild, a2; ) e2.appendChild(a2);
              return this.setDOMContent(e2);
            }
            getMaxWidth() {
              var t4;
              return null === (t4 = this._container) || void 0 === t4 ? void 0 : t4.style.maxWidth;
            }
            setMaxWidth(t4) {
              return this.options.maxWidth = t4, this._update(), this;
            }
            setDOMContent(t4) {
              if (this._content) for (; this._content.hasChildNodes(); ) this._content.firstChild && this._content.removeChild(this._content.firstChild);
              else this._content = r.create("div", "maplibregl-popup-content", this._container);
              return this._content.appendChild(t4), this._createCloseButton(), this._update(), this._focusFirstElement(), this;
            }
            addClassName(t4) {
              return this._container && this._container.classList.add(t4), this;
            }
            removeClassName(t4) {
              return this._container && this._container.classList.remove(t4), this;
            }
            setOffset(t4) {
              return this.options.offset = t4, this._update(), this;
            }
            toggleClassName(t4) {
              if (this._container) return this._container.classList.toggle(t4);
            }
            setSubpixelPositioning(t4) {
              this.options.subpixelPositioning = t4;
            }
            _createCloseButton() {
              this.options.closeButton && (this._closeButton = r.create("button", "maplibregl-popup-close-button", this._content), this._closeButton.type = "button", this._closeButton.innerHTML = "&#215;", this._closeButton.addEventListener("click", this._onClose));
            }
            _focusFirstElement() {
              if (!this.options.focusAfterOpen || !this._container) return;
              const t4 = this._container.querySelector(Ys);
              t4 && t4.focus();
            }
          }, t.RasterDEMTileSource = K2, t.RasterTileSource = X, t.ScaleControl = class {
            constructor(t4) {
              this._onMove = () => {
                Xs(this._map, this._container, this.options);
              }, this.setUnit = (t5) => {
                this.options.unit = t5, Xs(this._map, this._container, this.options);
              }, this.options = Object.assign(Object.assign({}, $s), t4);
            }
            getDefaultPosition() {
              return "bottom-left";
            }
            onAdd(t4) {
              return this._map = t4, this._container = r.create("div", "maplibregl-ctrl maplibregl-ctrl-scale", t4.getContainer()), this._map.on("move", this._onMove), this._onMove(), this._container;
            }
            onRemove() {
              r.remove(this._container), this._map.off("move", this._onMove), this._map = void 0;
            }
          }, t.ScrollZoomHandler = us, t.Style = de, t.TerrainControl = class {
            constructor(t4) {
              this._toggleTerrain = () => {
                this._map.getTerrain() ? this._map.setTerrain(null) : this._map.setTerrain(this.options), this._updateTerrainIcon();
              }, this._updateTerrainIcon = () => {
                this._terrainButton.classList.remove("maplibregl-ctrl-terrain"), this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"), this._map.terrain ? (this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"), this._terrainButton.title = this._map._getUIString("TerrainControl.Disable")) : (this._terrainButton.classList.add("maplibregl-ctrl-terrain"), this._terrainButton.title = this._map._getUIString("TerrainControl.Enable"));
              }, this.options = t4;
            }
            onAdd(t4) {
              return this._map = t4, this._container = r.create("div", "maplibregl-ctrl maplibregl-ctrl-group"), this._terrainButton = r.create("button", "maplibregl-ctrl-terrain", this._container), r.create("span", "maplibregl-ctrl-icon", this._terrainButton).setAttribute("aria-hidden", "true"), this._terrainButton.type = "button", this._terrainButton.addEventListener("click", this._toggleTerrain), this._updateTerrainIcon(), this._map.on("terrain", this._updateTerrainIcon), this._container;
            }
            onRemove() {
              r.remove(this._container), this._map.off("terrain", this._updateTerrainIcon), this._map = void 0;
            }
          }, t.TwoFingersTouchPitchHandler = rs, t.TwoFingersTouchRotateHandler = ss, t.TwoFingersTouchZoomHandler = is, t.TwoFingersTouchZoomRotateHandler = gs, t.VectorTileSource = $, t.VideoSource = tt, t.addSourceType = (t4, i2) => e._(void 0, void 0, void 0, function* () {
            if (at(t4)) throw new Error(`A source type called "${t4}" already exists.`);
            ((t5, e2) => {
              it[t5] = e2;
            })(t4, i2);
          }), t.clearPrewarmedResources = function() {
            const t4 = B2;
            t4 && (t4.isPreloaded() && 1 === t4.numActive() ? (t4.release(k), B2 = null) : console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));
          }, t.getMaxParallelImageRequests = function() {
            return e.a.MAX_PARALLEL_IMAGE_REQUESTS;
          }, t.getRTLTextPluginStatus = function() {
            return nt().getRTLTextPluginStatus();
          }, t.getVersion = function() {
            return to;
          }, t.getWorkerCount = function() {
            return L.workerCount;
          }, t.getWorkerUrl = function() {
            return e.a.WORKER_URL;
          }, t.importScriptInWorkers = function(t4) {
            return j().broadcast("IS", t4);
          }, t.prewarm = function() {
            N().acquire(k);
          }, t.setMaxParallelImageRequests = function(t4) {
            e.a.MAX_PARALLEL_IMAGE_REQUESTS = t4;
          }, t.setRTLTextPlugin = function(t4, e2) {
            return nt().setRTLTextPlugin(t4, e2);
          }, t.setWorkerCount = function(t4) {
            L.workerCount = t4;
          }, t.setWorkerUrl = function(t4) {
            e.a.WORKER_URL = t4;
          };
        });
        var maplibregl$1 = maplibregl;
        return maplibregl$1;
      });
    }
  });

  // src/plots/map/layers.js
  var require_layers2 = __commonJS({
    "src/plots/map/layers.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var sanitizeHTML = require_svg_text_utils().sanitizeHTML;
      var convertTextOpts = require_convert_text_opts2();
      var constants = require_constants27();
      function MapLayer(subplot, index) {
        this.subplot = subplot;
        this.uid = subplot.uid + "-" + index;
        this.index = index;
        this.idSource = "source-" + this.uid;
        this.idLayer = constants.layoutLayerPrefix + this.uid;
        this.sourceType = null;
        this.source = null;
        this.layerType = null;
        this.below = null;
        this.visible = false;
      }
      var proto = MapLayer.prototype;
      proto.update = function update(opts) {
        if (!this.visible) {
          this.updateSource(opts);
          this.updateLayer(opts);
        } else if (this.needsNewImage(opts)) {
          this.updateImage(opts);
        } else if (this.needsNewSource(opts)) {
          this.removeLayer();
          this.updateSource(opts);
          this.updateLayer(opts);
        } else if (this.needsNewLayer(opts)) {
          this.updateLayer(opts);
        } else {
          this.updateStyle(opts);
        }
        this.visible = isVisible(opts);
      };
      proto.needsNewImage = function(opts) {
        var map = this.subplot.map;
        return map.getSource(this.idSource) && this.sourceType === "image" && opts.sourcetype === "image" && (this.source !== opts.source || JSON.stringify(this.coordinates) !== JSON.stringify(opts.coordinates));
      };
      proto.needsNewSource = function(opts) {
        return this.sourceType !== opts.sourcetype || JSON.stringify(this.source) !== JSON.stringify(opts.source) || this.layerType !== opts.type;
      };
      proto.needsNewLayer = function(opts) {
        return this.layerType !== opts.type || this.below !== this.subplot.belowLookup["layout-" + this.index];
      };
      proto.lookupBelow = function() {
        return this.subplot.belowLookup["layout-" + this.index];
      };
      proto.updateImage = function(opts) {
        var map = this.subplot.map;
        map.getSource(this.idSource).updateImage({
          url: opts.source,
          coordinates: opts.coordinates
        });
        var _below = this.findFollowingMapLayerId(this.lookupBelow());
        if (_below !== null) {
          this.subplot.map.moveLayer(this.idLayer, _below);
        }
      };
      proto.updateSource = function(opts) {
        var map = this.subplot.map;
        if (map.getSource(this.idSource)) map.removeSource(this.idSource);
        this.sourceType = opts.sourcetype;
        this.source = opts.source;
        if (!isVisible(opts)) return;
        var sourceOpts = convertSourceOpts(opts);
        map.addSource(this.idSource, sourceOpts);
      };
      proto.findFollowingMapLayerId = function(below) {
        if (below === "traces") {
          var mapLayers = this.subplot.getMapLayers();
          for (var i = 0; i < mapLayers.length; i++) {
            var layerId = mapLayers[i].id;
            if (typeof layerId === "string" && layerId.indexOf(constants.traceLayerPrefix) === 0) {
              below = layerId;
              break;
            }
          }
        }
        return below;
      };
      proto.updateLayer = function(opts) {
        var subplot = this.subplot;
        var convertedOpts = convertOpts(opts);
        var below = this.lookupBelow();
        var _below = this.findFollowingMapLayerId(below);
        this.removeLayer();
        if (isVisible(opts)) {
          subplot.addLayer({
            id: this.idLayer,
            source: this.idSource,
            "source-layer": opts.sourcelayer || "",
            type: opts.type,
            minzoom: opts.minzoom,
            maxzoom: opts.maxzoom,
            layout: convertedOpts.layout,
            paint: convertedOpts.paint
          }, _below);
        }
        this.layerType = opts.type;
        this.below = below;
      };
      proto.updateStyle = function(opts) {
        if (isVisible(opts)) {
          var convertedOpts = convertOpts(opts);
          this.subplot.setOptions(this.idLayer, "setLayoutProperty", convertedOpts.layout);
          this.subplot.setOptions(this.idLayer, "setPaintProperty", convertedOpts.paint);
        }
      };
      proto.removeLayer = function() {
        var map = this.subplot.map;
        if (map.getLayer(this.idLayer)) {
          map.removeLayer(this.idLayer);
        }
      };
      proto.dispose = function() {
        var map = this.subplot.map;
        if (map.getLayer(this.idLayer)) map.removeLayer(this.idLayer);
        if (map.getSource(this.idSource)) map.removeSource(this.idSource);
      };
      function isVisible(opts) {
        if (!opts.visible) return false;
        var source = opts.source;
        if (Array.isArray(source) && source.length > 0) {
          for (var i = 0; i < source.length; i++) {
            if (typeof source[i] !== "string" || source[i].length === 0) {
              return false;
            }
          }
          return true;
        }
        return Lib.isPlainObject(source) || typeof source === "string" && source.length > 0;
      }
      function convertOpts(opts) {
        var layout = {};
        var paint = {};
        switch (opts.type) {
          case "circle":
            Lib.extendFlat(paint, {
              "circle-radius": opts.circle.radius,
              "circle-color": opts.color,
              "circle-opacity": opts.opacity
            });
            break;
          case "line":
            Lib.extendFlat(paint, {
              "line-width": opts.line.width,
              "line-color": opts.color,
              "line-opacity": opts.opacity,
              "line-dasharray": opts.line.dash
            });
            break;
          case "fill":
            Lib.extendFlat(paint, {
              "fill-color": opts.color,
              "fill-outline-color": opts.fill.outlinecolor,
              "fill-opacity": opts.opacity
              // no way to pass specify outline width at the moment
            });
            break;
          case "symbol":
            var symbol = opts.symbol;
            var textOpts = convertTextOpts(symbol.textposition, symbol.iconsize);
            Lib.extendFlat(layout, {
              "icon-image": symbol.icon + "-15",
              "icon-size": symbol.iconsize / 10,
              "text-field": symbol.text,
              "text-size": symbol.textfont.size,
              "text-anchor": textOpts.anchor,
              "text-offset": textOpts.offset,
              "symbol-placement": symbol.placement
              // TODO font family
              // 'text-font': symbol.textfont.family.split(', '),
            });
            Lib.extendFlat(paint, {
              "icon-color": opts.color,
              "text-color": symbol.textfont.color,
              "text-opacity": opts.opacity
            });
            break;
          case "raster":
            Lib.extendFlat(paint, {
              "raster-fade-duration": 0,
              "raster-opacity": opts.opacity
            });
            break;
        }
        return {
          layout,
          paint
        };
      }
      function convertSourceOpts(opts) {
        var sourceType = opts.sourcetype;
        var source = opts.source;
        var sourceOpts = { type: sourceType };
        var field;
        if (sourceType === "geojson") {
          field = "data";
        } else if (sourceType === "vector") {
          field = typeof source === "string" ? "url" : "tiles";
        } else if (sourceType === "raster") {
          field = "tiles";
          sourceOpts.tileSize = 256;
        } else if (sourceType === "image") {
          field = "url";
          sourceOpts.coordinates = opts.coordinates;
        }
        sourceOpts[field] = source;
        if (opts.sourceattribution) {
          sourceOpts.attribution = sanitizeHTML(opts.sourceattribution);
        }
        return sourceOpts;
      }
      module.exports = function createMapLayer(subplot, index, opts) {
        var mapLayer = new MapLayer(subplot, index);
        mapLayer.update(opts);
        return mapLayer;
      };
    }
  });

  // src/plots/map/map.js
  var require_map2 = __commonJS({
    "src/plots/map/map.js"(exports, module) {
      "use strict";
      var maplibregl = require_maplibre_gl2();
      var Lib = require_lib();
      var geoUtils = require_geo_location_utils();
      var Registry = require_registry();
      var Axes = require_axes();
      var dragElement = require_dragelement();
      var Fx = require_fx();
      var dragHelpers = require_helpers5();
      var drawMode = dragHelpers.drawMode;
      var selectMode = dragHelpers.selectMode;
      var prepSelect = require_selections().prepSelect;
      var clearOutline = require_selections().clearOutline;
      var clearSelectionsCache = require_selections().clearSelectionsCache;
      var selectOnClick = require_selections().selectOnClick;
      var constants = require_constants27();
      var createMapLayer = require_layers2();
      function Map2(gd, id) {
        this.id = id;
        this.gd = gd;
        var fullLayout = gd._fullLayout;
        var context = gd._context;
        this.container = fullLayout._glcontainer.node();
        this.isStatic = context.staticPlot;
        this.uid = fullLayout._uid + "-" + this.id;
        this.div = null;
        this.xaxis = null;
        this.yaxis = null;
        this.createFramework(fullLayout);
        this.map = null;
        this.styleObj = null;
        this.traceHash = {};
        this.layerList = [];
        this.belowLookup = {};
        this.dragging = false;
        this.wheeling = false;
      }
      var proto = Map2.prototype;
      proto.plot = function(calcData, fullLayout, promises) {
        var self2 = this;
        var promise;
        if (!self2.map) {
          promise = new Promise(function(resolve, reject) {
            self2.createMap(calcData, fullLayout, resolve, reject);
          });
        } else {
          promise = new Promise(function(resolve, reject) {
            self2.updateMap(calcData, fullLayout, resolve, reject);
          });
        }
        promises.push(promise);
      };
      proto.createMap = function(calcData, fullLayout, resolve, reject) {
        var self2 = this;
        var opts = fullLayout[self2.id];
        var styleObj = self2.styleObj = getStyleObj(opts.style);
        var bounds = opts.bounds;
        var maxBounds = bounds ? [[bounds.west, bounds.south], [bounds.east, bounds.north]] : null;
        var map = self2.map = new maplibregl.Map({
          container: self2.div,
          style: styleObj.style,
          center: convertCenter(opts.center),
          zoom: opts.zoom,
          bearing: opts.bearing,
          pitch: opts.pitch,
          maxBounds,
          interactive: !self2.isStatic,
          preserveDrawingBuffer: self2.isStatic,
          doubleClickZoom: false,
          boxZoom: false,
          attributionControl: false
        }).addControl(new maplibregl.AttributionControl({
          compact: true
        }));
        var requestedIcons = {};
        map.on("styleimagemissing", function(e) {
          var id = e.id;
          if (!requestedIcons[id] && id.includes("-15")) {
            requestedIcons[id] = true;
            var img = new Image(15, 15);
            img.onload = function() {
              map.addImage(id, img);
            };
            img.crossOrigin = "Anonymous";
            img.src = "https://unpkg.com/maki@2.1.0/icons/" + id + ".svg";
          }
        });
        map.setTransformRequest(function(url) {
          url = url.replace("https://fonts.openmaptiles.org/Open Sans Extrabold", "https://fonts.openmaptiles.org/Open Sans Extra Bold");
          url = url.replace("https://tiles.basemaps.cartocdn.com/fonts/Open Sans Extrabold", "https://fonts.openmaptiles.org/Open Sans Extra Bold");
          url = url.replace("https://fonts.openmaptiles.org/Open Sans Regular,Arial Unicode MS Regular", "https://fonts.openmaptiles.org/Klokantech Noto Sans Regular");
          return {
            url
          };
        });
        map._canvas.style.left = "0px";
        map._canvas.style.top = "0px";
        self2.rejectOnError(reject);
        if (!self2.isStatic) {
          self2.initFx(calcData, fullLayout);
        }
        var promises = [];
        promises.push(new Promise(function(resolve2) {
          map.once("load", resolve2);
        }));
        promises = promises.concat(geoUtils.fetchTraceGeoData(calcData));
        Promise.all(promises).then(function() {
          self2.fillBelowLookup(calcData, fullLayout);
          self2.updateData(calcData);
          self2.updateLayout(fullLayout);
          self2.resolveOnRender(resolve);
        }).catch(reject);
      };
      proto.updateMap = function(calcData, fullLayout, resolve, reject) {
        var self2 = this;
        var map = self2.map;
        var opts = fullLayout[this.id];
        self2.rejectOnError(reject);
        var promises = [];
        var styleObj = getStyleObj(opts.style);
        if (JSON.stringify(self2.styleObj) !== JSON.stringify(styleObj)) {
          self2.styleObj = styleObj;
          map.setStyle(styleObj.style);
          self2.traceHash = {};
          promises.push(new Promise(function(resolve2) {
            map.once("styledata", resolve2);
          }));
        }
        promises = promises.concat(geoUtils.fetchTraceGeoData(calcData));
        Promise.all(promises).then(function() {
          self2.fillBelowLookup(calcData, fullLayout);
          self2.updateData(calcData);
          self2.updateLayout(fullLayout);
          self2.resolveOnRender(resolve);
        }).catch(reject);
      };
      proto.fillBelowLookup = function(calcData, fullLayout) {
        var opts = fullLayout[this.id];
        var layers = opts.layers;
        var i, val;
        var belowLookup = this.belowLookup = {};
        var hasTraceAtTop = false;
        for (i = 0; i < calcData.length; i++) {
          var trace = calcData[i][0].trace;
          var _module = trace._module;
          if (typeof trace.below === "string") {
            val = trace.below;
          } else if (_module.getBelow) {
            val = _module.getBelow(trace, this);
          }
          if (val === "") {
            hasTraceAtTop = true;
          }
          belowLookup["trace-" + trace.uid] = val || "";
        }
        for (i = 0; i < layers.length; i++) {
          var item = layers[i];
          if (typeof item.below === "string") {
            val = item.below;
          } else if (hasTraceAtTop) {
            val = "traces";
          } else {
            val = "";
          }
          belowLookup["layout-" + i] = val;
        }
        var val2list = {};
        var k, id;
        for (k in belowLookup) {
          val = belowLookup[k];
          if (val2list[val]) {
            val2list[val].push(k);
          } else {
            val2list[val] = [k];
          }
        }
        for (val in val2list) {
          var list = val2list[val];
          if (list.length > 1) {
            for (i = 0; i < list.length; i++) {
              k = list[i];
              if (k.indexOf("trace-") === 0) {
                id = k.split("trace-")[1];
                if (this.traceHash[id]) {
                  this.traceHash[id].below = null;
                }
              } else if (k.indexOf("layout-") === 0) {
                id = k.split("layout-")[1];
                if (this.layerList[id]) {
                  this.layerList[id].below = null;
                }
              }
            }
          }
        }
      };
      var traceType2orderIndex = {
        choroplethmap: 0,
        densitymap: 1,
        scattermap: 2
      };
      proto.updateData = function(calcData) {
        var traceHash = this.traceHash;
        var traceObj, trace, i, j;
        var calcDataSorted = calcData.slice().sort(function(a, b) {
          return traceType2orderIndex[a[0].trace.type] - traceType2orderIndex[b[0].trace.type];
        });
        for (i = 0; i < calcDataSorted.length; i++) {
          var calcTrace = calcDataSorted[i];
          trace = calcTrace[0].trace;
          traceObj = traceHash[trace.uid];
          var didUpdate = false;
          if (traceObj) {
            if (traceObj.type === trace.type) {
              traceObj.update(calcTrace);
              didUpdate = true;
            } else {
              traceObj.dispose();
            }
          }
          if (!didUpdate && trace._module) {
            traceHash[trace.uid] = trace._module.plot(this, calcTrace);
          }
        }
        var ids = Object.keys(traceHash);
        idLoop:
          for (i = 0; i < ids.length; i++) {
            var id = ids[i];
            for (j = 0; j < calcData.length; j++) {
              trace = calcData[j][0].trace;
              if (id === trace.uid) continue idLoop;
            }
            traceObj = traceHash[id];
            traceObj.dispose();
            delete traceHash[id];
          }
      };
      proto.updateLayout = function(fullLayout) {
        var map = this.map;
        var opts = fullLayout[this.id];
        if (!this.dragging && !this.wheeling) {
          map.setCenter(convertCenter(opts.center));
          map.setZoom(opts.zoom);
          map.setBearing(opts.bearing);
          map.setPitch(opts.pitch);
        }
        this.updateLayers(fullLayout);
        this.updateFramework(fullLayout);
        this.updateFx(fullLayout);
        this.map.resize();
        if (this.gd._context._scrollZoom.map) {
          map.scrollZoom.enable();
        } else {
          map.scrollZoom.disable();
        }
      };
      proto.resolveOnRender = function(resolve) {
        var map = this.map;
        map.on("render", function onRender() {
          if (map.loaded()) {
            map.off("render", onRender);
            setTimeout(resolve, 10);
          }
        });
      };
      proto.rejectOnError = function(reject) {
        var map = this.map;
        function handler() {
          reject(new Error(constants.mapOnErrorMsg));
        }
        map.once("error", handler);
        map.once("style.error", handler);
        map.once("source.error", handler);
        map.once("tile.error", handler);
        map.once("layer.error", handler);
      };
      proto.createFramework = function(fullLayout) {
        var self2 = this;
        var div = self2.div = document.createElement("div");
        div.id = self2.uid;
        div.style.position = "absolute";
        self2.container.appendChild(div);
        self2.xaxis = {
          _id: "x",
          c2p: function(v) {
            return self2.project(v).x;
          }
        };
        self2.yaxis = {
          _id: "y",
          c2p: function(v) {
            return self2.project(v).y;
          }
        };
        self2.updateFramework(fullLayout);
        self2.mockAxis = {
          type: "linear",
          showexponent: "all",
          exponentformat: "B"
        };
        Axes.setConvert(self2.mockAxis, fullLayout);
      };
      proto.initFx = function(calcData, fullLayout) {
        var self2 = this;
        var gd = self2.gd;
        var map = self2.map;
        map.on("moveend", function(evt) {
          if (!self2.map) return;
          var fullLayoutNow = gd._fullLayout;
          if (evt.originalEvent || self2.wheeling) {
            var optsNow = fullLayoutNow[self2.id];
            Registry.call("_storeDirectGUIEdit", gd.layout, fullLayoutNow._preGUI, self2.getViewEdits(optsNow));
            var viewNow = self2.getView();
            optsNow._input.center = optsNow.center = viewNow.center;
            optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
            optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
            optsNow._input.pitch = optsNow.pitch = viewNow.pitch;
            gd.emit("plotly_relayout", self2.getViewEditsWithDerived(viewNow));
          }
          if (evt.originalEvent && evt.originalEvent.type === "mouseup") {
            self2.dragging = false;
          } else if (self2.wheeling) {
            self2.wheeling = false;
          }
          if (fullLayoutNow && fullLayoutNow._rehover) {
            fullLayoutNow._rehover();
          }
        });
        map.on("wheel", function() {
          self2.wheeling = true;
        });
        map.on("mousemove", function(evt) {
          var bb = self2.div.getBoundingClientRect();
          var xy = [
            evt.originalEvent.offsetX,
            evt.originalEvent.offsetY
          ];
          evt.target.getBoundingClientRect = function() {
            return bb;
          };
          self2.xaxis.p2c = function() {
            return map.unproject(xy).lng;
          };
          self2.yaxis.p2c = function() {
            return map.unproject(xy).lat;
          };
          gd._fullLayout._rehover = function() {
            if (gd._fullLayout._hoversubplot === self2.id && gd._fullLayout[self2.id]) {
              Fx.hover(gd, evt, self2.id);
            }
          };
          Fx.hover(gd, evt, self2.id);
          gd._fullLayout._hoversubplot = self2.id;
        });
        function unhover() {
          Fx.loneUnhover(fullLayout._hoverlayer);
        }
        map.on("dragstart", function() {
          self2.dragging = true;
          unhover();
        });
        map.on("zoomstart", unhover);
        map.on("mouseout", function() {
          gd._fullLayout._hoversubplot = null;
        });
        function emitUpdate() {
          var viewNow = self2.getView();
          gd.emit("plotly_relayouting", self2.getViewEditsWithDerived(viewNow));
        }
        map.on("drag", emitUpdate);
        map.on("zoom", emitUpdate);
        map.on("dblclick", function() {
          var optsNow = gd._fullLayout[self2.id];
          Registry.call("_storeDirectGUIEdit", gd.layout, gd._fullLayout._preGUI, self2.getViewEdits(optsNow));
          var viewInitial = self2.viewInitial;
          map.setCenter(convertCenter(viewInitial.center));
          map.setZoom(viewInitial.zoom);
          map.setBearing(viewInitial.bearing);
          map.setPitch(viewInitial.pitch);
          var viewNow = self2.getView();
          optsNow._input.center = optsNow.center = viewNow.center;
          optsNow._input.zoom = optsNow.zoom = viewNow.zoom;
          optsNow._input.bearing = optsNow.bearing = viewNow.bearing;
          optsNow._input.pitch = optsNow.pitch = viewNow.pitch;
          gd.emit("plotly_doubleclick", null);
          gd.emit("plotly_relayout", self2.getViewEditsWithDerived(viewNow));
        });
        self2.clearOutline = function() {
          clearSelectionsCache(self2.dragOptions);
          clearOutline(self2.dragOptions.gd);
        };
        self2.onClickInPanFn = function(dragOptions) {
          return function(evt) {
            var clickMode = gd._fullLayout.clickmode;
            if (clickMode.indexOf("select") > -1) {
              selectOnClick(evt.originalEvent, gd, [self2.xaxis], [self2.yaxis], self2.id, dragOptions);
            }
            if (clickMode.indexOf("event") > -1) {
              Fx.click(gd, evt.originalEvent);
            }
          };
        };
      };
      proto.updateFx = function(fullLayout) {
        var self2 = this;
        var map = self2.map;
        var gd = self2.gd;
        if (self2.isStatic) return;
        function invert(pxpy) {
          var obj = self2.map.unproject(pxpy);
          return [obj.lng, obj.lat];
        }
        var dragMode = fullLayout.dragmode;
        var fillRangeItems;
        fillRangeItems = function(eventData, poly) {
          if (poly.isRect) {
            var ranges = eventData.range = {};
            ranges[self2.id] = [
              invert([poly.xmin, poly.ymin]),
              invert([poly.xmax, poly.ymax])
            ];
          } else {
            var dataPts = eventData.lassoPoints = {};
            dataPts[self2.id] = poly.map(invert);
          }
        };
        var oldDragOptions = self2.dragOptions;
        self2.dragOptions = Lib.extendDeep(oldDragOptions || {}, {
          dragmode: fullLayout.dragmode,
          element: self2.div,
          gd,
          plotinfo: {
            id: self2.id,
            domain: fullLayout[self2.id].domain,
            xaxis: self2.xaxis,
            yaxis: self2.yaxis,
            fillRangeItems
          },
          xaxes: [self2.xaxis],
          yaxes: [self2.yaxis],
          subplot: self2.id
        });
        map.off("click", self2.onClickInPanHandler);
        if (selectMode(dragMode) || drawMode(dragMode)) {
          map.dragPan.disable();
          map.on("zoomstart", self2.clearOutline);
          self2.dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, self2.dragOptions, dragMode);
          };
          dragElement.init(self2.dragOptions);
        } else {
          map.dragPan.enable();
          map.off("zoomstart", self2.clearOutline);
          self2.div.onmousedown = null;
          self2.div.ontouchstart = null;
          self2.div.removeEventListener("touchstart", self2.div._ontouchstart);
          self2.onClickInPanHandler = self2.onClickInPanFn(self2.dragOptions);
          map.on("click", self2.onClickInPanHandler);
        }
      };
      proto.updateFramework = function(fullLayout) {
        var domain = fullLayout[this.id].domain;
        var size = fullLayout._size;
        var style = this.div.style;
        style.width = size.w * (domain.x[1] - domain.x[0]) + "px";
        style.height = size.h * (domain.y[1] - domain.y[0]) + "px";
        style.left = size.l + domain.x[0] * size.w + "px";
        style.top = size.t + (1 - domain.y[1]) * size.h + "px";
        this.xaxis._offset = size.l + domain.x[0] * size.w;
        this.xaxis._length = size.w * (domain.x[1] - domain.x[0]);
        this.yaxis._offset = size.t + (1 - domain.y[1]) * size.h;
        this.yaxis._length = size.h * (domain.y[1] - domain.y[0]);
      };
      proto.updateLayers = function(fullLayout) {
        var opts = fullLayout[this.id];
        var layers = opts.layers;
        var layerList = this.layerList;
        var i;
        if (layers.length !== layerList.length) {
          for (i = 0; i < layerList.length; i++) {
            layerList[i].dispose();
          }
          layerList = this.layerList = [];
          for (i = 0; i < layers.length; i++) {
            layerList.push(createMapLayer(this, i, layers[i]));
          }
        } else {
          for (i = 0; i < layers.length; i++) {
            layerList[i].update(layers[i]);
          }
        }
      };
      proto.destroy = function() {
        if (this.map) {
          this.map.remove();
          this.map = null;
          this.container.removeChild(this.div);
        }
      };
      proto.toImage = function() {
        this.map.stop();
        return this.map.getCanvas().toDataURL();
      };
      proto.setOptions = function(id, methodName, opts) {
        for (var k in opts) {
          this.map[methodName](id, k, opts[k]);
        }
      };
      proto.getMapLayers = function() {
        return this.map.getStyle().layers;
      };
      proto.addLayer = function(opts, below) {
        var map = this.map;
        if (typeof below === "string") {
          if (below === "") {
            map.addLayer(opts, below);
            return;
          }
          var mapLayers = this.getMapLayers();
          for (var i = 0; i < mapLayers.length; i++) {
            if (below === mapLayers[i].id) {
              map.addLayer(opts, below);
              return;
            }
          }
          Lib.warn([
            "Trying to add layer with *below* value",
            below,
            "referencing a layer that does not exist",
            "or that does not yet exist."
          ].join(" "));
        }
        map.addLayer(opts);
      };
      proto.project = function(v) {
        return this.map.project(new maplibregl.LngLat(v[0], v[1]));
      };
      proto.getView = function() {
        var map = this.map;
        var mapCenter = map.getCenter();
        var lon = mapCenter.lng;
        var lat = mapCenter.lat;
        var center = { lon, lat };
        var canvas = map.getCanvas();
        var w = parseInt(canvas.style.width);
        var h = parseInt(canvas.style.height);
        return {
          center,
          zoom: map.getZoom(),
          bearing: map.getBearing(),
          pitch: map.getPitch(),
          _derived: {
            coordinates: [
              map.unproject([0, 0]).toArray(),
              map.unproject([w, 0]).toArray(),
              map.unproject([w, h]).toArray(),
              map.unproject([0, h]).toArray()
            ]
          }
        };
      };
      proto.getViewEdits = function(cont) {
        var id = this.id;
        var keys = ["center", "zoom", "bearing", "pitch"];
        var obj = {};
        for (var i = 0; i < keys.length; i++) {
          var k = keys[i];
          obj[id + "." + k] = cont[k];
        }
        return obj;
      };
      proto.getViewEditsWithDerived = function(cont) {
        var id = this.id;
        var obj = this.getViewEdits(cont);
        obj[id + "._derived"] = cont._derived;
        return obj;
      };
      function getStyleObj(val) {
        var styleObj = {};
        if (Lib.isPlainObject(val)) {
          styleObj.id = val.id;
          styleObj.style = val;
        } else if (typeof val === "string") {
          styleObj.id = val;
          if (constants.stylesMap[val]) {
            styleObj.style = constants.stylesMap[val];
          } else {
            styleObj.style = val;
          }
        } else {
          styleObj.id = constants.styleValueDflt;
          styleObj.style = convertStyleVal(constants.styleValueDflt);
        }
        styleObj.transition = { duration: 0, delay: 0 };
        return styleObj;
      }
      function convertStyleVal(val) {
        return constants.styleUrlPrefix + val + "-" + constants.styleUrlSuffix;
      }
      function convertCenter(center) {
        return [center.lon, center.lat];
      }
      module.exports = Map2;
    }
  });

  // src/plots/map/layout_defaults.js
  var require_layout_defaults18 = __commonJS({
    "src/plots/map/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleSubplotDefaults = require_subplot_defaults();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var layoutAttributes = require_layout_attributes20();
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        handleSubplotDefaults(layoutIn, layoutOut, fullData, {
          type: "map",
          attributes: layoutAttributes,
          handleDefaults,
          partition: "y"
        });
      };
      function handleDefaults(containerIn, containerOut, coerce) {
        coerce("style");
        coerce("center.lon");
        coerce("center.lat");
        coerce("zoom");
        coerce("bearing");
        coerce("pitch");
        var west = coerce("bounds.west");
        var east = coerce("bounds.east");
        var south = coerce("bounds.south");
        var north = coerce("bounds.north");
        if (west === void 0 || east === void 0 || south === void 0 || north === void 0) {
          delete containerOut.bounds;
        }
        handleArrayContainerDefaults(containerIn, containerOut, {
          name: "layers",
          handleItemDefaults: handleLayerDefaults
        });
        containerOut._input = containerIn;
      }
      function handleLayerDefaults(layerIn, layerOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(layerIn, layerOut, layoutAttributes.layers, attr, dflt);
        }
        var visible = coerce("visible");
        if (visible) {
          var sourceType = coerce("sourcetype");
          var mustBeRasterLayer = sourceType === "raster" || sourceType === "image";
          coerce("source");
          coerce("sourceattribution");
          if (sourceType === "vector") {
            coerce("sourcelayer");
          }
          if (sourceType === "image") {
            coerce("coordinates");
          }
          var typeDflt;
          if (mustBeRasterLayer) typeDflt = "raster";
          var type = coerce("type", typeDflt);
          if (mustBeRasterLayer && type !== "raster") {
            type = layerOut.type = "raster";
            Lib.log("Source types *raster* and *image* must drawn *raster* layer type.");
          }
          coerce("below");
          coerce("color");
          coerce("opacity");
          coerce("minzoom");
          coerce("maxzoom");
          if (type === "circle") {
            coerce("circle.radius");
          }
          if (type === "line") {
            coerce("line.width");
            coerce("line.dash");
          }
          if (type === "fill") {
            coerce("fill.outlinecolor");
          }
          if (type === "symbol") {
            coerce("symbol.icon");
            coerce("symbol.iconsize");
            coerce("symbol.text");
            Lib.coerceFont(coerce, "symbol.textfont", void 0, {
              noFontVariant: true,
              noFontShadow: true,
              noFontLineposition: true,
              noFontTextcase: true
            });
            coerce("symbol.textposition");
            coerce("symbol.placement");
          }
        }
      }
    }
  });

  // src/plots/map/index.js
  var require_map3 = __commonJS({
    "src/plots/map/index.js"(exports) {
      "use strict";
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var strScale = Lib.strScale;
      var getSubplotCalcData = require_get_data().getSubplotCalcData;
      var xmlnsNamespaces = require_xmlns_namespaces();
      var d3 = require_d3();
      var Drawing = require_drawing();
      var svgTextUtils = require_svg_text_utils();
      var Map2 = require_map2();
      var MAP = "map";
      exports.name = MAP;
      exports.attr = "subplot";
      exports.idRoot = MAP;
      exports.idRegex = exports.attrRegex = Lib.counterRegex(MAP);
      exports.attributes = {
        subplot: {
          valType: "subplotid",
          dflt: "map",
          editType: "calc"
        }
      };
      exports.layoutAttributes = require_layout_attributes20();
      exports.supplyLayoutDefaults = require_layout_defaults18();
      exports.plot = function plot(gd) {
        var fullLayout = gd._fullLayout;
        var calcData = gd.calcdata;
        var mapIds = fullLayout._subplots[MAP];
        for (var i = 0; i < mapIds.length; i++) {
          var id = mapIds[i];
          var subplotCalcData = getSubplotCalcData(calcData, MAP, id);
          var opts = fullLayout[id];
          var map = opts._subplot;
          if (!map) {
            map = new Map2(gd, id);
            fullLayout[id]._subplot = map;
          }
          if (!map.viewInitial) {
            map.viewInitial = {
              center: Lib.extendFlat({}, opts.center),
              zoom: opts.zoom,
              bearing: opts.bearing,
              pitch: opts.pitch
            };
          }
          map.plot(subplotCalcData, fullLayout, gd._promises);
        }
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldMapKeys = oldFullLayout._subplots[MAP] || [];
        for (var i = 0; i < oldMapKeys.length; i++) {
          var oldMapKey = oldMapKeys[i];
          if (!newFullLayout[oldMapKey] && !!oldFullLayout[oldMapKey]._subplot) {
            oldFullLayout[oldMapKey]._subplot.destroy();
          }
        }
      };
      exports.toSVG = function(gd) {
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[MAP];
        var size = fullLayout._size;
        for (var i = 0; i < subplotIds.length; i++) {
          var opts = fullLayout[subplotIds[i]];
          var domain = opts.domain;
          var map = opts._subplot;
          var imageData = map.toImage("png");
          var image = fullLayout._glimages.append("svg:image");
          image.attr({
            xmlns: xmlnsNamespaces.svg,
            "xlink:href": imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: "none"
          });
          var subplotDiv = d3.select(opts._subplot.div);
          var attributions = subplotDiv.select(".maplibregl-ctrl-attrib").text().replace("Improve this map", "");
          var attributionGroup = fullLayout._glimages.append("g");
          var attributionText = attributionGroup.append("text");
          attributionText.text(attributions).classed("static-attribution", true).attr({
            "font-size": 12,
            "font-family": "Arial",
            color: "rgba(0, 0, 0, 0.75)",
            "text-anchor": "end",
            "data-unformatted": attributions
          });
          var bBox = Drawing.bBox(attributionText.node());
          var maxWidth = size.w * (domain.x[1] - domain.x[0]);
          if (bBox.width > maxWidth / 2) {
            var multilineAttributions = attributions.split("|").join("<br>");
            attributionText.text(multilineAttributions).attr("data-unformatted", multilineAttributions).call(svgTextUtils.convertToTspans, gd);
            bBox = Drawing.bBox(attributionText.node());
          }
          attributionText.attr("transform", strTranslate(-3, -bBox.height + 8));
          attributionGroup.insert("rect", ".static-attribution").attr({
            x: -bBox.width - 6,
            y: -bBox.height - 3,
            width: bBox.width + 6,
            height: bBox.height + 3,
            fill: "rgba(255, 255, 255, 0.75)"
          });
          var scaleRatio = 1;
          if (bBox.width + 6 > maxWidth) scaleRatio = maxWidth / (bBox.width + 6);
          var offset = [size.l + size.w * domain.x[1], size.t + size.h * (1 - domain.y[0])];
          attributionGroup.attr("transform", strTranslate(offset[0], offset[1]) + strScale(scaleRatio));
        }
      };
      exports.updateFx = function(gd) {
        var fullLayout = gd._fullLayout;
        var subplotIds = fullLayout._subplots[MAP];
        for (var i = 0; i < subplotIds.length; i++) {
          var subplotObj = fullLayout[subplotIds[i]]._subplot;
          subplotObj.updateFx(fullLayout);
        }
      };
    }
  });

  // src/traces/scattermap/index.js
  var require_scattermap = __commonJS({
    "src/traces/scattermap/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes57(),
        supplyDefaults: require_defaults53(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels6(),
        calc: require_calc27(),
        plot: require_plot26(),
        hoverPoints: require_hover20().hoverPoints,
        eventData: require_event_data13(),
        selectPoints: require_select10(),
        styleOnSelect: function(_, cd) {
          if (cd) {
            var trace = cd[0].trace;
            trace._glTrace.update(cd);
          }
        },
        moduleType: "trace",
        name: "scattermap",
        basePlotModule: require_map3(),
        categories: ["map", "gl", "symbols", "showLegend", "scatter-like"],
        meta: {}
      };
    }
  });

  // lib/scattermap.js
  var require_scattermap2 = __commonJS({
    "lib/scattermap.js"(exports, module) {
      "use strict";
      module.exports = require_scattermap();
    }
  });

  // src/traces/choroplethmap/attributes.js
  var require_attributes58 = __commonJS({
    "src/traces/choroplethmap/attributes.js"(exports, module) {
      "use strict";
      var choroplethAttrs = require_attributes49();
      var colorScaleAttrs = require_attributes8();
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var baseAttrs = require_attributes2();
      var extendFlat = require_extend().extendFlat;
      module.exports = extendFlat(
        {
          locations: {
            valType: "data_array",
            editType: "calc"
          },
          // TODO
          // Maybe start with only one value (that we could name e.g. 'geojson-id'),
          // but eventually:
          // - we could also support for our own dist/topojson/*
          //   .. and locationmode: choroplethAttrs.locationmode,
          z: {
            valType: "data_array",
            editType: "calc"
          },
          // TODO maybe we could also set a "key" to dig out values out of the
          // GeoJSON feature `properties` fields?
          geojson: {
            valType: "any",
            editType: "calc"
          },
          featureidkey: extendFlat({}, choroplethAttrs.featureidkey, {}),
          // TODO agree on name / behaviour
          //
          // 'below' is used currently for layout.map.layers,
          // even though it's not very plotly-esque.
          //
          // Note also, that the map-gl style don't all have the same layers,
          // see https://codepen.io/etpinard/pen/ydVMwM for full list
          below: {
            valType: "string",
            editType: "plot"
          },
          text: choroplethAttrs.text,
          hovertext: choroplethAttrs.hovertext,
          marker: {
            line: {
              color: extendFlat({}, choroplethAttrs.marker.line.color, { editType: "plot" }),
              width: extendFlat({}, choroplethAttrs.marker.line.width, { editType: "plot" }),
              editType: "calc"
            },
            // TODO maybe having a dflt less than 1, together with `below:''` would be better?
            opacity: extendFlat({}, choroplethAttrs.marker.opacity, { editType: "plot" }),
            editType: "calc"
          },
          selected: {
            marker: {
              opacity: extendFlat({}, choroplethAttrs.selected.marker.opacity, { editType: "plot" }),
              editType: "plot"
            },
            editType: "plot"
          },
          unselected: {
            marker: {
              opacity: extendFlat({}, choroplethAttrs.unselected.marker.opacity, { editType: "plot" }),
              editType: "plot"
            },
            editType: "plot"
          },
          hoverinfo: choroplethAttrs.hoverinfo,
          hovertemplate: hovertemplateAttrs({}, { keys: ["properties"] }),
          hovertemplatefallback: templatefallbackAttrs(),
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
        },
        colorScaleAttrs("", {
          cLetter: "z",
          editTypeOverride: "calc"
        })
      );
    }
  });

  // src/traces/choroplethmap/defaults.js
  var require_defaults54 = __commonJS({
    "src/traces/choroplethmap/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes58();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var locations = coerce("locations");
        var z = coerce("z");
        var geojson = coerce("geojson");
        if (!Lib.isArrayOrTypedArray(locations) || !locations.length || !Lib.isArrayOrTypedArray(z) || !z.length || !(typeof geojson === "string" && geojson !== "" || Lib.isPlainObject(geojson))) {
          traceOut.visible = false;
          return;
        }
        coerce("featureidkey");
        traceOut._length = Math.min(locations.length, z.length);
        coerce("below");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        var mlw = coerce("marker.line.width");
        if (mlw) coerce("marker.line.color");
        coerce("marker.opacity");
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "z" });
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/choroplethmap/convert.js
  var require_convert15 = __commonJS({
    "src/traces/choroplethmap/convert.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Colorscale = require_colorscale();
      var Drawing = require_drawing();
      var makeBlank = require_geojson_utils().makeBlank;
      var geoUtils = require_geo_location_utils();
      function convert(calcTrace) {
        var trace = calcTrace[0].trace;
        var isVisible = trace.visible === true && trace._length !== 0;
        var fill = {
          layout: { visibility: "none" },
          paint: {}
        };
        var line = {
          layout: { visibility: "none" },
          paint: {}
        };
        var opts = trace._opts = {
          fill,
          line,
          geojson: makeBlank()
        };
        if (!isVisible) return opts;
        var features = geoUtils.extractTraceFeature(calcTrace);
        if (!features) return opts;
        var sclFunc = Colorscale.makeColorScaleFuncFromTrace(trace);
        var marker = trace.marker;
        var markerLine = marker.line || {};
        var opacityFn;
        if (Lib.isArrayOrTypedArray(marker.opacity)) {
          opacityFn = function(d) {
            var mo = d.mo;
            return isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
          };
        }
        var lineColorFn;
        if (Lib.isArrayOrTypedArray(markerLine.color)) {
          lineColorFn = function(d) {
            return d.mlc;
          };
        }
        var lineWidthFn;
        if (Lib.isArrayOrTypedArray(markerLine.width)) {
          lineWidthFn = function(d) {
            return d.mlw;
          };
        }
        for (var i = 0; i < calcTrace.length; i++) {
          var cdi = calcTrace[i];
          var fOut = cdi.fOut;
          if (fOut) {
            var props = fOut.properties;
            props.fc = sclFunc(cdi.z);
            if (opacityFn) props.mo = opacityFn(cdi);
            if (lineColorFn) props.mlc = lineColorFn(cdi);
            if (lineWidthFn) props.mlw = lineWidthFn(cdi);
            cdi.ct = props.ct;
            cdi._polygons = geoUtils.feature2polygons(fOut);
          }
        }
        var opacitySetting = opacityFn ? { type: "identity", property: "mo" } : marker.opacity;
        Lib.extendFlat(fill.paint, {
          "fill-color": { type: "identity", property: "fc" },
          "fill-opacity": opacitySetting
        });
        Lib.extendFlat(line.paint, {
          "line-color": lineColorFn ? { type: "identity", property: "mlc" } : markerLine.color,
          "line-width": lineWidthFn ? { type: "identity", property: "mlw" } : markerLine.width,
          "line-opacity": opacitySetting
        });
        fill.layout.visibility = "visible";
        line.layout.visibility = "visible";
        opts.geojson = { type: "FeatureCollection", features };
        convertOnSelect(calcTrace);
        return opts;
      }
      function convertOnSelect(calcTrace) {
        var trace = calcTrace[0].trace;
        var opts = trace._opts;
        var opacitySetting;
        if (trace.selectedpoints) {
          var fns = Drawing.makeSelectedPointStyleFns(trace);
          for (var i = 0; i < calcTrace.length; i++) {
            var cdi = calcTrace[i];
            if (cdi.fOut) {
              cdi.fOut.properties.mo2 = fns.selectedOpacityFn(cdi);
            }
          }
          opacitySetting = { type: "identity", property: "mo2" };
        } else {
          opacitySetting = Lib.isArrayOrTypedArray(trace.marker.opacity) ? { type: "identity", property: "mo" } : trace.marker.opacity;
        }
        Lib.extendFlat(opts.fill.paint, { "fill-opacity": opacitySetting });
        Lib.extendFlat(opts.line.paint, { "line-opacity": opacitySetting });
        return opts;
      }
      module.exports = {
        convert,
        convertOnSelect
      };
    }
  });

  // src/traces/choroplethmap/plot.js
  var require_plot27 = __commonJS({
    "src/traces/choroplethmap/plot.js"(exports, module) {
      "use strict";
      var convert = require_convert15().convert;
      var convertOnSelect = require_convert15().convertOnSelect;
      var LAYER_PREFIX = require_constants27().traceLayerPrefix;
      function ChoroplethMap(subplot, uid) {
        this.type = "choroplethmap";
        this.subplot = subplot;
        this.uid = uid;
        this.sourceId = "source-" + uid;
        this.layerList = [
          ["fill", LAYER_PREFIX + uid + "-fill"],
          ["line", LAYER_PREFIX + uid + "-line"]
        ];
        this.below = null;
      }
      var proto = ChoroplethMap.prototype;
      proto.update = function(calcTrace) {
        this._update(convert(calcTrace));
        calcTrace[0].trace._glTrace = this;
      };
      proto.updateOnSelect = function(calcTrace) {
        this._update(convertOnSelect(calcTrace));
      };
      proto._update = function(optsAll) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var below = subplot.belowLookup["trace-" + this.uid];
        subplot.map.getSource(this.sourceId).setData(optsAll.geojson);
        if (below !== this.below) {
          this._removeLayers();
          this._addLayers(optsAll, below);
          this.below = below;
        }
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var id = item[1];
          var opts = optsAll[k];
          subplot.setOptions(id, "setLayoutProperty", opts.layout);
          if (opts.layout.visibility === "visible") {
            subplot.setOptions(id, "setPaintProperty", opts.paint);
          }
        }
      };
      proto._addLayers = function(optsAll, below) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var sourceId = this.sourceId;
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var opts = optsAll[k];
          subplot.addLayer({
            type: k,
            id: item[1],
            source: sourceId,
            layout: opts.layout,
            paint: opts.paint
          }, below);
        }
      };
      proto._removeLayers = function() {
        var map = this.subplot.map;
        var layerList = this.layerList;
        for (var i = layerList.length - 1; i >= 0; i--) {
          map.removeLayer(layerList[i][1]);
        }
      };
      proto.dispose = function() {
        var map = this.subplot.map;
        this._removeLayers();
        map.removeSource(this.sourceId);
      };
      module.exports = function createChoroplethMap(subplot, calcTrace) {
        var trace = calcTrace[0].trace;
        var choroplethMap = new ChoroplethMap(subplot, trace.uid);
        var sourceId = choroplethMap.sourceId;
        var optsAll = convert(calcTrace);
        var below = choroplethMap.below = subplot.belowLookup["trace-" + trace.uid];
        subplot.map.addSource(sourceId, {
          type: "geojson",
          data: optsAll.geojson
        });
        choroplethMap._addLayers(optsAll, below);
        calcTrace[0].trace._glTrace = choroplethMap;
        return choroplethMap;
      };
    }
  });

  // src/traces/choroplethmap/index.js
  var require_choroplethmap = __commonJS({
    "src/traces/choroplethmap/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes58(),
        supplyDefaults: require_defaults54(),
        colorbar: require_colorbar2(),
        calc: require_calc28(),
        plot: require_plot27(),
        hoverPoints: require_hover15(),
        eventData: require_event_data10(),
        selectPoints: require_select6(),
        styleOnSelect: function(_, cd) {
          if (cd) {
            var trace = cd[0].trace;
            trace._glTrace.updateOnSelect(cd);
          }
        },
        getBelow: function(trace, subplot) {
          var mapLayers = subplot.getMapLayers();
          for (var i = mapLayers.length - 2; i >= 0; i--) {
            var layerId = mapLayers[i].id;
            if (typeof layerId === "string" && layerId.indexOf("water") === 0) {
              for (var j = i + 1; j < mapLayers.length; j++) {
                layerId = mapLayers[j].id;
                if (typeof layerId === "string" && layerId.indexOf("plotly-") === -1) {
                  return layerId;
                }
              }
            }
          }
        },
        moduleType: "trace",
        name: "choroplethmap",
        basePlotModule: require_map3(),
        categories: ["map", "gl", "noOpacity", "showLegend"],
        meta: {
          hr_name: "choropleth_map"
        }
      };
    }
  });

  // lib/choroplethmap.js
  var require_choroplethmap2 = __commonJS({
    "lib/choroplethmap.js"(exports, module) {
      "use strict";
      module.exports = require_choroplethmap();
    }
  });

  // src/traces/densitymap/attributes.js
  var require_attributes59 = __commonJS({
    "src/traces/densitymap/attributes.js"(exports, module) {
      "use strict";
      var colorScaleAttrs = require_attributes8();
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var baseAttrs = require_attributes2();
      var scatterMapAttrs = require_attributes57();
      var extendFlat = require_extend().extendFlat;
      module.exports = extendFlat(
        {
          lon: scatterMapAttrs.lon,
          lat: scatterMapAttrs.lat,
          z: {
            valType: "data_array",
            editType: "calc"
          },
          radius: {
            valType: "number",
            editType: "plot",
            arrayOk: true,
            min: 1,
            dflt: 30
          },
          below: {
            valType: "string",
            editType: "plot"
          },
          text: scatterMapAttrs.text,
          hovertext: scatterMapAttrs.hovertext,
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
            flags: ["lon", "lat", "z", "text", "name"]
          }),
          hovertemplate: hovertemplateAttrs(),
          hovertemplatefallback: templatefallbackAttrs(),
          showlegend: extendFlat({}, baseAttrs.showlegend, { dflt: false })
        },
        colorScaleAttrs("", {
          cLetter: "z",
          editTypeOverride: "calc"
        })
      );
    }
  });

  // src/traces/densitymap/defaults.js
  var require_defaults55 = __commonJS({
    "src/traces/densitymap/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var colorscaleDefaults = require_defaults2();
      var attributes = require_attributes59();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var lon = coerce("lon") || [];
        var lat = coerce("lat") || [];
        var len = Math.min(lon.length, lat.length);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        coerce("z");
        coerce("radius");
        coerce("below");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        colorscaleDefaults(traceIn, traceOut, layout, coerce, { prefix: "", cLetter: "z" });
      };
    }
  });

  // src/traces/densitymap/calc.js
  var require_calc34 = __commonJS({
    "src/traces/densitymap/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var BADNUM = require_numerical().BADNUM;
      var colorscaleCalc = require_calc();
      var _ = require_lib()._;
      module.exports = function calc(gd, trace) {
        var len = trace._length;
        var calcTrace = new Array(len);
        var z = trace.z;
        var hasZ = isArrayOrTypedArray(z) && z.length;
        for (var i = 0; i < len; i++) {
          var cdi = calcTrace[i] = {};
          var lon = trace.lon[i];
          var lat = trace.lat[i];
          cdi.lonlat = isNumeric(lon) && isNumeric(lat) ? [+lon, +lat] : [BADNUM, BADNUM];
          if (hasZ) {
            var zi = z[i];
            cdi.z = isNumeric(zi) ? zi : BADNUM;
          }
        }
        colorscaleCalc(gd, trace, {
          vals: hasZ ? z : [0, 1],
          containerStr: "",
          cLetter: "z"
        });
        if (len) {
          calcTrace[0].t = {
            labels: {
              lat: _(gd, "lat:") + " ",
              lon: _(gd, "lon:") + " "
            }
          };
        }
        return calcTrace;
      };
    }
  });

  // src/traces/densitymap/convert.js
  var require_convert16 = __commonJS({
    "src/traces/densitymap/convert.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Color2 = require_color();
      var Colorscale = require_colorscale();
      var BADNUM = require_numerical().BADNUM;
      var makeBlank = require_geojson_utils().makeBlank;
      module.exports = function convert(calcTrace) {
        var trace = calcTrace[0].trace;
        var isVisible = trace.visible === true && trace._length !== 0;
        var heatmap = {
          layout: { visibility: "none" },
          paint: {}
        };
        var opts = trace._opts = {
          heatmap,
          geojson: makeBlank()
        };
        if (!isVisible) return opts;
        var features = [];
        var i;
        var z = trace.z;
        var radius = trace.radius;
        var hasZ = Lib.isArrayOrTypedArray(z) && z.length;
        var hasArrayRadius = Lib.isArrayOrTypedArray(radius);
        for (i = 0; i < calcTrace.length; i++) {
          var cdi = calcTrace[i];
          var lonlat = cdi.lonlat;
          if (lonlat[0] !== BADNUM) {
            var props = {};
            if (hasZ) {
              var zi = cdi.z;
              props.z = zi !== BADNUM ? zi : 0;
            }
            if (hasArrayRadius) {
              props.r = isNumeric(radius[i]) && radius[i] > 0 ? +radius[i] : 0;
            }
            features.push({
              type: "Feature",
              geometry: { type: "Point", coordinates: lonlat },
              properties: props
            });
          }
        }
        var cOpts = Colorscale.extractOpts(trace);
        var scl = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : cOpts.colorscale;
        var scl01 = scl[0][1];
        var color0 = Color2.opacity(scl01) < 1 ? scl01 : Color2.addOpacity(scl01, 0);
        var heatmapColor = [
          "interpolate",
          ["linear"],
          ["heatmap-density"],
          0,
          color0
        ];
        for (i = 1; i < scl.length; i++) {
          heatmapColor.push(scl[i][0], scl[i][1]);
        }
        var zExp = [
          "interpolate",
          ["linear"],
          ["get", "z"],
          cOpts.min,
          0,
          cOpts.max,
          1
        ];
        Lib.extendFlat(opts.heatmap.paint, {
          "heatmap-weight": hasZ ? zExp : 1 / (cOpts.max - cOpts.min),
          "heatmap-color": heatmapColor,
          "heatmap-radius": hasArrayRadius ? { type: "identity", property: "r" } : trace.radius,
          "heatmap-opacity": trace.opacity
        });
        opts.geojson = { type: "FeatureCollection", features };
        opts.heatmap.layout.visibility = "visible";
        return opts;
      };
    }
  });

  // src/traces/densitymap/plot.js
  var require_plot28 = __commonJS({
    "src/traces/densitymap/plot.js"(exports, module) {
      "use strict";
      var convert = require_convert16();
      var LAYER_PREFIX = require_constants27().traceLayerPrefix;
      function DensityMap(subplot, uid) {
        this.type = "densitymap";
        this.subplot = subplot;
        this.uid = uid;
        this.sourceId = "source-" + uid;
        this.layerList = [
          ["heatmap", LAYER_PREFIX + uid + "-heatmap"]
        ];
        this.below = null;
      }
      var proto = DensityMap.prototype;
      proto.update = function(calcTrace) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var optsAll = convert(calcTrace);
        var below = subplot.belowLookup["trace-" + this.uid];
        subplot.map.getSource(this.sourceId).setData(optsAll.geojson);
        if (below !== this.below) {
          this._removeLayers();
          this._addLayers(optsAll, below);
          this.below = below;
        }
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var id = item[1];
          var opts = optsAll[k];
          subplot.setOptions(id, "setLayoutProperty", opts.layout);
          if (opts.layout.visibility === "visible") {
            subplot.setOptions(id, "setPaintProperty", opts.paint);
          }
        }
      };
      proto._addLayers = function(optsAll, below) {
        var subplot = this.subplot;
        var layerList = this.layerList;
        var sourceId = this.sourceId;
        for (var i = 0; i < layerList.length; i++) {
          var item = layerList[i];
          var k = item[0];
          var opts = optsAll[k];
          subplot.addLayer({
            type: k,
            id: item[1],
            source: sourceId,
            layout: opts.layout,
            paint: opts.paint
          }, below);
        }
      };
      proto._removeLayers = function() {
        var map = this.subplot.map;
        var layerList = this.layerList;
        for (var i = layerList.length - 1; i >= 0; i--) {
          map.removeLayer(layerList[i][1]);
        }
      };
      proto.dispose = function() {
        var map = this.subplot.map;
        this._removeLayers();
        map.removeSource(this.sourceId);
      };
      module.exports = function createDensityMap(subplot, calcTrace) {
        var trace = calcTrace[0].trace;
        var densityMap = new DensityMap(subplot, trace.uid);
        var sourceId = densityMap.sourceId;
        var optsAll = convert(calcTrace);
        var below = densityMap.below = subplot.belowLookup["trace-" + trace.uid];
        subplot.map.addSource(sourceId, {
          type: "geojson",
          data: optsAll.geojson
        });
        densityMap._addLayers(optsAll, below);
        return densityMap;
      };
    }
  });

  // src/traces/densitymap/hover.js
  var require_hover21 = __commonJS({
    "src/traces/densitymap/hover.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var scatterMapHoverPoints = require_hover20().hoverPoints;
      var getExtraText = require_hover20().getExtraText;
      module.exports = function hoverPoints(pointData, xval, yval) {
        var pts = scatterMapHoverPoints(pointData, xval, yval);
        if (!pts) return;
        var newPointData = pts[0];
        var cd = newPointData.cd;
        var trace = cd[0].trace;
        var di = cd[newPointData.index];
        delete newPointData.color;
        if ("z" in di) {
          var ax = newPointData.subplot.mockAxis;
          newPointData.z = di.z;
          newPointData.zLabel = Axes.tickText(ax, ax.c2l(di.z), "hover").text;
        }
        newPointData.extraText = getExtraText(trace, di, cd[0].t.labels);
        return [newPointData];
      };
    }
  });

  // src/traces/densitymap/event_data.js
  var require_event_data14 = __commonJS({
    "src/traces/densitymap/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt) {
        out.lon = pt.lon;
        out.lat = pt.lat;
        out.z = pt.z;
        return out;
      };
    }
  });

  // src/traces/densitymap/index.js
  var require_densitymap = __commonJS({
    "src/traces/densitymap/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes59(),
        supplyDefaults: require_defaults55(),
        colorbar: require_colorbar2(),
        formatLabels: require_format_labels6(),
        calc: require_calc34(),
        plot: require_plot28(),
        hoverPoints: require_hover21(),
        eventData: require_event_data14(),
        getBelow: function(trace, subplot) {
          var mapLayers = subplot.getMapLayers();
          for (var i = 0; i < mapLayers.length; i++) {
            var layer = mapLayers[i];
            var layerId = layer.id;
            if (layer.type === "symbol" && typeof layerId === "string" && layerId.indexOf("plotly-") === -1) {
              return layerId;
            }
          }
        },
        moduleType: "trace",
        name: "densitymap",
        basePlotModule: require_map3(),
        categories: ["map", "gl", "showLegend"],
        meta: {
          hr_name: "density_map"
        }
      };
    }
  });

  // lib/densitymap.js
  var require_densitymap2 = __commonJS({
    "lib/densitymap.js"(exports, module) {
      "use strict";
      module.exports = require_densitymap();
    }
  });

  // src/traces/sankey/attributes.js
  var require_attributes60 = __commonJS({
    "src/traces/sankey/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var baseAttrs = require_attributes2();
      var colorAttrs = require_attributes3();
      var fxAttrs = require_attributes();
      var domainAttrs = require_domain().attributes;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorAttributes = require_attributes8();
      var templatedArray = require_plot_template().templatedArray;
      var descriptionOnlyNumbers = require_axis_format_attributes().descriptionOnlyNumbers;
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var attrs = module.exports = overrideAll(
        {
          hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
            flags: [],
            arrayOk: false
          }),
          hoverlabel: fxAttrs.hoverlabel,
          domain: domainAttrs({ name: "sankey", trace: true }),
          orientation: {
            valType: "enumerated",
            values: ["v", "h"],
            dflt: "h"
          },
          valueformat: {
            valType: "string",
            dflt: ".3s",
            description: descriptionOnlyNumbers("value")
          },
          valuesuffix: {
            valType: "string",
            dflt: ""
          },
          arrangement: {
            valType: "enumerated",
            values: ["snap", "perpendicular", "freeform", "fixed"],
            dflt: "snap"
          },
          textfont: fontAttrs({
            autoShadowDflt: true
          }),
          // Remove top-level customdata
          customdata: void 0,
          node: {
            label: {
              valType: "data_array",
              dflt: []
            },
            groups: {
              valType: "info_array",
              impliedEdits: { x: [], y: [] },
              dimensions: 2,
              freeLength: true,
              dflt: [],
              items: { valType: "number", editType: "calc" }
            },
            x: {
              valType: "data_array",
              dflt: []
            },
            y: {
              valType: "data_array",
              dflt: []
            },
            color: {
              valType: "color",
              arrayOk: true
            },
            customdata: {
              valType: "data_array",
              editType: "calc"
            },
            line: {
              color: {
                valType: "color",
                dflt: colorAttrs.defaultLine,
                arrayOk: true
              },
              width: {
                valType: "number",
                min: 0,
                dflt: 0.5,
                arrayOk: true
              }
            },
            pad: {
              valType: "number",
              arrayOk: false,
              min: 0,
              dflt: 20
            },
            thickness: {
              valType: "number",
              arrayOk: false,
              min: 1,
              dflt: 20
            },
            hoverinfo: {
              valType: "enumerated",
              values: ["all", "none", "skip"],
              dflt: "all"
            },
            hoverlabel: fxAttrs.hoverlabel,
            // needs editType override,
            hovertemplate: hovertemplateAttrs(
              {},
              {
                keys: ["value", "label"]
              }
            ),
            hovertemplatefallback: templatefallbackAttrs(),
            align: {
              valType: "enumerated",
              values: ["justify", "left", "right", "center"],
              dflt: "justify"
            }
          },
          link: {
            arrowlen: {
              valType: "number",
              min: 0,
              dflt: 0
            },
            label: {
              valType: "data_array",
              dflt: []
            },
            color: {
              valType: "color",
              arrayOk: true
            },
            hovercolor: {
              valType: "color",
              arrayOk: true
            },
            customdata: {
              valType: "data_array",
              editType: "calc"
            },
            line: {
              color: {
                valType: "color",
                dflt: colorAttrs.defaultLine,
                arrayOk: true
              },
              width: {
                valType: "number",
                min: 0,
                dflt: 0,
                arrayOk: true
              }
            },
            source: {
              valType: "data_array",
              dflt: []
            },
            target: {
              valType: "data_array",
              dflt: []
            },
            value: {
              valType: "data_array",
              dflt: []
            },
            hoverinfo: {
              valType: "enumerated",
              values: ["all", "none", "skip"],
              dflt: "all"
            },
            hoverlabel: fxAttrs.hoverlabel,
            // needs editType override,
            hovertemplate: hovertemplateAttrs(
              {},
              {
                keys: ["value", "label"]
              }
            ),
            hovertemplatefallback: templatefallbackAttrs(),
            colorscales: templatedArray("concentrationscales", {
              editType: "calc",
              label: {
                valType: "string",
                editType: "calc",
                dflt: ""
              },
              cmax: {
                valType: "number",
                editType: "calc",
                dflt: 1
              },
              cmin: {
                valType: "number",
                editType: "calc",
                dflt: 0
              },
              colorscale: extendFlat(colorAttributes().colorscale, {
                dflt: [
                  [0, "white"],
                  [1, "black"]
                ]
              })
            })
          }
        },
        "calc",
        "nested"
      );
    }
  });

  // src/traces/sankey/defaults.js
  var require_defaults56 = __commonJS({
    "src/traces/sankey/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes60();
      var Color2 = require_color();
      var tinycolor = require_tinycolor();
      var handleDomainDefaults = require_domain().defaults;
      var handleHoverLabelDefaults = require_hoverlabel_defaults();
      var Template = require_plot_template();
      var handleArrayContainerDefaults = require_array_container_defaults();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var hoverlabelDefault = Lib.extendDeep(layout.hoverlabel, traceIn.hoverlabel);
        var nodeIn = traceIn.node;
        var nodeOut = Template.newContainer(traceOut, "node");
        function coerceNode(attr, dflt) {
          return Lib.coerce(nodeIn, nodeOut, attributes.node, attr, dflt);
        }
        coerceNode("label");
        coerceNode("groups");
        coerceNode("x");
        coerceNode("y");
        coerceNode("pad");
        coerceNode("thickness");
        coerceNode("line.color");
        coerceNode("line.width");
        coerceNode("hoverinfo", traceIn.hoverinfo);
        handleHoverLabelDefaults(nodeIn, nodeOut, coerceNode, hoverlabelDefault);
        coerceNode("hovertemplate");
        coerceNode("align");
        var colors = layout.colorway;
        var defaultNodePalette = function(i) {
          return colors[i % colors.length];
        };
        coerceNode("color", nodeOut.label.map(function(d, i) {
          return Color2.addOpacity(defaultNodePalette(i), 0.8);
        }));
        coerceNode("customdata");
        var linkIn = traceIn.link || {};
        var linkOut = Template.newContainer(traceOut, "link");
        function coerceLink(attr, dflt) {
          return Lib.coerce(linkIn, linkOut, attributes.link, attr, dflt);
        }
        coerceLink("label");
        coerceLink("arrowlen");
        coerceLink("source");
        coerceLink("target");
        coerceLink("value");
        coerceLink("line.color");
        coerceLink("line.width");
        coerceLink("hoverinfo", traceIn.hoverinfo);
        handleHoverLabelDefaults(linkIn, linkOut, coerceLink, hoverlabelDefault);
        coerceLink("hovertemplate");
        var darkBG = tinycolor(layout.paper_bgcolor).getLuminance() < 0.333;
        var defaultLinkColor = darkBG ? "rgba(255, 255, 255, 0.6)" : "rgba(0, 0, 0, 0.2)";
        var linkColor = coerceLink("color", defaultLinkColor);
        function makeDefaultHoverColor(_linkColor) {
          var tc = tinycolor(_linkColor);
          if (!tc.isValid()) {
            return _linkColor;
          }
          var alpha = tc.getAlpha();
          if (alpha <= 0.8) {
            tc.setAlpha(alpha + 0.2);
          } else {
            tc = darkBG ? tc.brighten() : tc.darken();
          }
          return tc.toRgbString();
        }
        coerceLink(
          "hovercolor",
          Array.isArray(linkColor) ? linkColor.map(makeDefaultHoverColor) : makeDefaultHoverColor(linkColor)
        );
        coerceLink("customdata");
        handleArrayContainerDefaults(linkIn, linkOut, {
          name: "colorscales",
          handleItemDefaults: concentrationscalesDefaults
        });
        handleDomainDefaults(traceOut, layout, coerce);
        coerce("orientation");
        coerce("valueformat");
        coerce("valuesuffix");
        var dfltArrangement;
        if (nodeOut.x.length && nodeOut.y.length) {
          dfltArrangement = "freeform";
        }
        coerce("arrangement", dfltArrangement);
        Lib.coerceFont(coerce, "textfont", layout.font, { autoShadowDflt: true });
        traceOut._length = null;
      };
      function concentrationscalesDefaults(In, Out) {
        function coerce(attr, dflt) {
          return Lib.coerce(In, Out, attributes.link.colorscales, attr, dflt);
        }
        coerce("label");
        coerce("cmin");
        coerce("cmax");
        coerce("colorscale");
      }
    }
  });

  // node_modules/strongly-connected-components/scc.js
  var require_scc = __commonJS({
    "node_modules/strongly-connected-components/scc.js"(exports, module) {
      "use strict";
      module.exports = stronglyConnectedComponents;
      function stronglyConnectedComponents(adjList) {
        var numVertices = adjList.length;
        var index = new Array(numVertices);
        var lowValue = new Array(numVertices);
        var active = new Array(numVertices);
        var child = new Array(numVertices);
        var scc = new Array(numVertices);
        var sccLinks = new Array(numVertices);
        for (var i = 0; i < numVertices; ++i) {
          index[i] = -1;
          lowValue[i] = 0;
          active[i] = false;
          child[i] = 0;
          scc[i] = -1;
          sccLinks[i] = [];
        }
        var count = 0;
        var components = [];
        var sccAdjList = [];
        function strongConnect(v) {
          var S = [v], T = [v];
          index[v] = lowValue[v] = count;
          active[v] = true;
          count += 1;
          while (T.length > 0) {
            v = T[T.length - 1];
            var e2 = adjList[v];
            if (child[v] < e2.length) {
              for (var i2 = child[v]; i2 < e2.length; ++i2) {
                var u = e2[i2];
                if (index[u] < 0) {
                  index[u] = lowValue[u] = count;
                  active[u] = true;
                  count += 1;
                  S.push(u);
                  T.push(u);
                  break;
                } else if (active[u]) {
                  lowValue[v] = Math.min(lowValue[v], lowValue[u]) | 0;
                }
                if (scc[u] >= 0) {
                  sccLinks[v].push(scc[u]);
                }
              }
              child[v] = i2;
            } else {
              if (lowValue[v] === index[v]) {
                var component = [];
                var links = [], linkCount = 0;
                for (var i2 = S.length - 1; i2 >= 0; --i2) {
                  var w = S[i2];
                  active[w] = false;
                  component.push(w);
                  links.push(sccLinks[w]);
                  linkCount += sccLinks[w].length;
                  scc[w] = components.length;
                  if (w === v) {
                    S.length = i2;
                    break;
                  }
                }
                components.push(component);
                var allLinks = new Array(linkCount);
                for (var i2 = 0; i2 < links.length; i2++) {
                  for (var j2 = 0; j2 < links[i2].length; j2++) {
                    allLinks[--linkCount] = links[i2][j2];
                  }
                }
                sccAdjList.push(allLinks);
              }
              T.pop();
            }
          }
        }
        for (var i = 0; i < numVertices; ++i) {
          if (index[i] < 0) {
            strongConnect(i);
          }
        }
        var newE;
        for (var i = 0; i < sccAdjList.length; i++) {
          var e = sccAdjList[i];
          if (e.length === 0) continue;
          e.sort(function(a, b) {
            return a - b;
          });
          newE = [e[0]];
          for (var j = 1; j < e.length; j++) {
            if (e[j] !== e[j - 1]) {
              newE.push(e[j]);
            }
          }
          sccAdjList[i] = newE;
        }
        return { components, adjacencyList: sccAdjList };
      }
    }
  });

  // src/traces/sankey/calc.js
  var require_calc35 = __commonJS({
    "src/traces/sankey/calc.js"(exports, module) {
      "use strict";
      var tarjan = require_scc();
      var Lib = require_lib();
      var wrap = require_gup().wrap;
      var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
      var isIndex = Lib.isIndex;
      var Colorscale = require_colorscale();
      function convertToD3Sankey(trace) {
        var nodeSpec = trace.node;
        var linkSpec = trace.link;
        var links = [];
        var hasLinkColorArray = isArrayOrTypedArray(linkSpec.color);
        var hasLinkHoverColorArray = isArrayOrTypedArray(linkSpec.hovercolor);
        var hasLinkCustomdataArray = isArrayOrTypedArray(linkSpec.customdata);
        var linkedNodes = {};
        var components = {};
        var componentCount = linkSpec.colorscales.length;
        var i;
        for (i = 0; i < componentCount; i++) {
          var cscale = linkSpec.colorscales[i];
          var specs = Colorscale.extractScale(cscale, { cLetter: "c" });
          var scale = Colorscale.makeColorScaleFunc(specs);
          components[cscale.label] = scale;
        }
        var maxNodeId = 0;
        for (i = 0; i < linkSpec.value.length; i++) {
          if (linkSpec.source[i] > maxNodeId) maxNodeId = linkSpec.source[i];
          if (linkSpec.target[i] > maxNodeId) maxNodeId = linkSpec.target[i];
        }
        var nodeCount = maxNodeId + 1;
        trace.node._count = nodeCount;
        var j;
        var groups = trace.node.groups;
        var groupLookup = {};
        for (i = 0; i < groups.length; i++) {
          var group = groups[i];
          for (j = 0; j < group.length; j++) {
            var nodeIndex = group[j];
            var groupIndex = nodeCount + i;
            if (groupLookup.hasOwnProperty(nodeIndex)) {
              Lib.warn("Node " + nodeIndex + " is already part of a group.");
            } else {
              groupLookup[nodeIndex] = groupIndex;
            }
          }
        }
        var groupedLinks = {
          source: [],
          target: []
        };
        for (i = 0; i < linkSpec.value.length; i++) {
          var val = linkSpec.value[i];
          var source = linkSpec.source[i];
          var target = linkSpec.target[i];
          if (!(val > 0 && isIndex(source, nodeCount) && isIndex(target, nodeCount))) {
            continue;
          }
          if (groupLookup.hasOwnProperty(source) && groupLookup.hasOwnProperty(target) && groupLookup[source] === groupLookup[target]) {
            continue;
          }
          if (groupLookup.hasOwnProperty(target)) {
            target = groupLookup[target];
          }
          if (groupLookup.hasOwnProperty(source)) {
            source = groupLookup[source];
          }
          source = +source;
          target = +target;
          linkedNodes[source] = linkedNodes[target] = true;
          var label = "";
          if (linkSpec.label && linkSpec.label[i]) label = linkSpec.label[i];
          var concentrationscale = null;
          if (label && components.hasOwnProperty(label)) concentrationscale = components[label];
          links.push({
            pointNumber: i,
            label,
            color: hasLinkColorArray ? linkSpec.color[i] : linkSpec.color,
            hovercolor: hasLinkHoverColorArray ? linkSpec.hovercolor[i] : linkSpec.hovercolor,
            customdata: hasLinkCustomdataArray ? linkSpec.customdata[i] : linkSpec.customdata,
            concentrationscale,
            source,
            target,
            value: +val
          });
          groupedLinks.source.push(source);
          groupedLinks.target.push(target);
        }
        var totalCount = nodeCount + groups.length;
        var hasNodeColorArray = isArrayOrTypedArray(nodeSpec.color);
        var hasNodeCustomdataArray = isArrayOrTypedArray(nodeSpec.customdata);
        var nodes = [];
        for (i = 0; i < totalCount; i++) {
          if (!linkedNodes[i]) continue;
          var l = nodeSpec.label[i];
          nodes.push({
            group: i > nodeCount - 1,
            childrenNodes: [],
            pointNumber: i,
            label: l,
            color: hasNodeColorArray ? nodeSpec.color[i] : nodeSpec.color,
            customdata: hasNodeCustomdataArray ? nodeSpec.customdata[i] : nodeSpec.customdata
          });
        }
        var circular = false;
        if (circularityPresent(totalCount, groupedLinks.source, groupedLinks.target)) {
          circular = true;
        }
        return {
          circular,
          links,
          nodes,
          // Data structure for groups
          groups,
          groupLookup
        };
      }
      function circularityPresent(nodeLen, sources, targets) {
        var nodes = Lib.init2dArray(nodeLen, 0);
        for (var i = 0; i < Math.min(sources.length, targets.length); i++) {
          if (Lib.isIndex(sources[i], nodeLen) && Lib.isIndex(targets[i], nodeLen)) {
            if (sources[i] === targets[i]) {
              return true;
            }
            nodes[sources[i]].push(targets[i]);
          }
        }
        var scc = tarjan(nodes);
        return scc.components.some(function(c) {
          return c.length > 1;
        });
      }
      module.exports = function calc(gd, trace) {
        var result = convertToD3Sankey(trace);
        return wrap({
          circular: result.circular,
          _nodes: result.nodes,
          _links: result.links,
          // Data structure for grouping
          _groups: result.groups,
          _groupLookup: result.groupLookup
        });
      };
    }
  });

  // node_modules/d3-quadtree/dist/d3-quadtree.js
  var require_d3_quadtree = __commonJS({
    "node_modules/d3-quadtree/dist/d3-quadtree.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}));
      })(exports, function(exports2) {
        "use strict";
        function tree_add(d) {
          var x = +this._x.call(null, d), y = +this._y.call(null, d);
          return add(this.cover(x, y), x, y, d);
        }
        function add(tree, x, y, d) {
          if (isNaN(x) || isNaN(y)) return tree;
          var parent, node = tree._root, leaf = { data: d }, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1, xm, ym, xp, yp, right, bottom, i, j;
          if (!node) return tree._root = leaf, tree;
          while (node.length) {
            if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm;
            else x1 = xm;
            if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym;
            else y1 = ym;
            if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
          }
          xp = +tree._x.call(null, node.data);
          yp = +tree._y.call(null, node.data);
          if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;
          do {
            parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
            if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm;
            else x1 = xm;
            if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym;
            else y1 = ym;
          } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | xp >= xm));
          return parent[j] = node, parent[i] = leaf, tree;
        }
        function addAll(data) {
          var d, i, n = data.length, x, y, xz = new Array(n), yz = new Array(n), x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
          for (i = 0; i < n; ++i) {
            if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
            xz[i] = x;
            yz[i] = y;
            if (x < x0) x0 = x;
            if (x > x1) x1 = x;
            if (y < y0) y0 = y;
            if (y > y1) y1 = y;
          }
          if (x0 > x1 || y0 > y1) return this;
          this.cover(x0, y0).cover(x1, y1);
          for (i = 0; i < n; ++i) {
            add(this, xz[i], yz[i], data[i]);
          }
          return this;
        }
        function tree_cover(x, y) {
          if (isNaN(x = +x) || isNaN(y = +y)) return this;
          var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1;
          if (isNaN(x0)) {
            x1 = (x0 = Math.floor(x)) + 1;
            y1 = (y0 = Math.floor(y)) + 1;
          } else {
            var z = x1 - x0, node = this._root, parent, i;
            while (x0 > x || x >= x1 || y0 > y || y >= y1) {
              i = (y < y0) << 1 | x < x0;
              parent = new Array(4), parent[i] = node, node = parent, z *= 2;
              switch (i) {
                case 0:
                  x1 = x0 + z, y1 = y0 + z;
                  break;
                case 1:
                  x0 = x1 - z, y1 = y0 + z;
                  break;
                case 2:
                  x1 = x0 + z, y0 = y1 - z;
                  break;
                case 3:
                  x0 = x1 - z, y0 = y1 - z;
                  break;
              }
            }
            if (this._root && this._root.length) this._root = node;
          }
          this._x0 = x0;
          this._y0 = y0;
          this._x1 = x1;
          this._y1 = y1;
          return this;
        }
        function tree_data() {
          var data = [];
          this.visit(function(node) {
            if (!node.length) do
              data.push(node.data);
            while (node = node.next);
          });
          return data;
        }
        function tree_extent(_) {
          return arguments.length ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1]) : isNaN(this._x0) ? void 0 : [[this._x0, this._y0], [this._x1, this._y1]];
        }
        function Quad(node, x0, y0, x1, y1) {
          this.node = node;
          this.x0 = x0;
          this.y0 = y0;
          this.x1 = x1;
          this.y1 = y1;
        }
        function tree_find(x, y, radius) {
          var data, x0 = this._x0, y0 = this._y0, x1, y1, x2, y2, x3 = this._x1, y3 = this._y1, quads = [], node = this._root, q, i;
          if (node) quads.push(new Quad(node, x0, y0, x3, y3));
          if (radius == null) radius = Infinity;
          else {
            x0 = x - radius, y0 = y - radius;
            x3 = x + radius, y3 = y + radius;
            radius *= radius;
          }
          while (q = quads.pop()) {
            if (!(node = q.node) || (x1 = q.x0) > x3 || (y1 = q.y0) > y3 || (x2 = q.x1) < x0 || (y2 = q.y1) < y0) continue;
            if (node.length) {
              var xm = (x1 + x2) / 2, ym = (y1 + y2) / 2;
              quads.push(
                new Quad(node[3], xm, ym, x2, y2),
                new Quad(node[2], x1, ym, xm, y2),
                new Quad(node[1], xm, y1, x2, ym),
                new Quad(node[0], x1, y1, xm, ym)
              );
              if (i = (y >= ym) << 1 | x >= xm) {
                q = quads[quads.length - 1];
                quads[quads.length - 1] = quads[quads.length - 1 - i];
                quads[quads.length - 1 - i] = q;
              }
            } else {
              var dx = x - +this._x.call(null, node.data), dy = y - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
              if (d2 < radius) {
                var d = Math.sqrt(radius = d2);
                x0 = x - d, y0 = y - d;
                x3 = x + d, y3 = y + d;
                data = node.data;
              }
            }
          }
          return data;
        }
        function tree_remove(d) {
          if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this;
          var parent, node = this._root, retainer, previous, next, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1, x, y, xm, ym, right, bottom, i, j;
          if (!node) return this;
          if (node.length) while (true) {
            if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm;
            else x1 = xm;
            if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym;
            else y1 = ym;
            if (!(parent = node, node = node[i = bottom << 1 | right])) return this;
            if (!node.length) break;
            if (parent[i + 1 & 3] || parent[i + 2 & 3] || parent[i + 3 & 3]) retainer = parent, j = i;
          }
          while (node.data !== d) if (!(previous = node, node = node.next)) return this;
          if (next = node.next) delete node.next;
          if (previous) return next ? previous.next = next : delete previous.next, this;
          if (!parent) return this._root = next, this;
          next ? parent[i] = next : delete parent[i];
          if ((node = parent[0] || parent[1] || parent[2] || parent[3]) && node === (parent[3] || parent[2] || parent[1] || parent[0]) && !node.length) {
            if (retainer) retainer[j] = node;
            else this._root = node;
          }
          return this;
        }
        function removeAll(data) {
          for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
          return this;
        }
        function tree_root() {
          return this._root;
        }
        function tree_size() {
          var size = 0;
          this.visit(function(node) {
            if (!node.length) do
              ++size;
            while (node = node.next);
          });
          return size;
        }
        function tree_visit(callback) {
          var quads = [], q, node = this._root, child, x0, y0, x1, y1;
          if (node) quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1));
          while (q = quads.pop()) {
            if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
              var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
              if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
              if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
              if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
              if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
            }
          }
          return this;
        }
        function tree_visitAfter(callback) {
          var quads = [], next = [], q;
          if (this._root) quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1));
          while (q = quads.pop()) {
            var node = q.node;
            if (node.length) {
              var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
              if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));
              if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));
              if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));
              if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));
            }
            next.push(q);
          }
          while (q = next.pop()) {
            callback(q.node, q.x0, q.y0, q.x1, q.y1);
          }
          return this;
        }
        function defaultX(d) {
          return d[0];
        }
        function tree_x(_) {
          return arguments.length ? (this._x = _, this) : this._x;
        }
        function defaultY(d) {
          return d[1];
        }
        function tree_y(_) {
          return arguments.length ? (this._y = _, this) : this._y;
        }
        function quadtree(nodes, x, y) {
          var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);
          return nodes == null ? tree : tree.addAll(nodes);
        }
        function Quadtree(x, y, x0, y0, x1, y1) {
          this._x = x;
          this._y = y;
          this._x0 = x0;
          this._y0 = y0;
          this._x1 = x1;
          this._y1 = y1;
          this._root = void 0;
        }
        function leaf_copy(leaf) {
          var copy = { data: leaf.data }, next = copy;
          while (leaf = leaf.next) next = next.next = { data: leaf.data };
          return copy;
        }
        var treeProto = quadtree.prototype = Quadtree.prototype;
        treeProto.copy = function() {
          var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child;
          if (!node) return copy;
          if (!node.length) return copy._root = leaf_copy(node), copy;
          nodes = [{ source: node, target: copy._root = new Array(4) }];
          while (node = nodes.pop()) {
            for (var i = 0; i < 4; ++i) {
              if (child = node.source[i]) {
                if (child.length) nodes.push({ source: child, target: node.target[i] = new Array(4) });
                else node.target[i] = leaf_copy(child);
              }
            }
          }
          return copy;
        };
        treeProto.add = tree_add;
        treeProto.addAll = addAll;
        treeProto.cover = tree_cover;
        treeProto.data = tree_data;
        treeProto.extent = tree_extent;
        treeProto.find = tree_find;
        treeProto.remove = tree_remove;
        treeProto.removeAll = removeAll;
        treeProto.root = tree_root;
        treeProto.size = tree_size;
        treeProto.visit = tree_visit;
        treeProto.visitAfter = tree_visitAfter;
        treeProto.x = tree_x;
        treeProto.y = tree_y;
        exports2.quadtree = quadtree;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-collection/dist/d3-collection.js
  var require_d3_collection = __commonJS({
    "node_modules/d3-collection/dist/d3-collection.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : factory(global2.d3 = global2.d3 || {});
      })(exports, function(exports2) {
        "use strict";
        var prefix = "$";
        function Map2() {
        }
        Map2.prototype = map.prototype = {
          constructor: Map2,
          has: function(key) {
            return prefix + key in this;
          },
          get: function(key) {
            return this[prefix + key];
          },
          set: function(key, value) {
            this[prefix + key] = value;
            return this;
          },
          remove: function(key) {
            var property = prefix + key;
            return property in this && delete this[property];
          },
          clear: function() {
            for (var property in this) if (property[0] === prefix) delete this[property];
          },
          keys: function() {
            var keys2 = [];
            for (var property in this) if (property[0] === prefix) keys2.push(property.slice(1));
            return keys2;
          },
          values: function() {
            var values2 = [];
            for (var property in this) if (property[0] === prefix) values2.push(this[property]);
            return values2;
          },
          entries: function() {
            var entries2 = [];
            for (var property in this) if (property[0] === prefix) entries2.push({ key: property.slice(1), value: this[property] });
            return entries2;
          },
          size: function() {
            var size = 0;
            for (var property in this) if (property[0] === prefix) ++size;
            return size;
          },
          empty: function() {
            for (var property in this) if (property[0] === prefix) return false;
            return true;
          },
          each: function(f) {
            for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this);
          }
        };
        function map(object, f) {
          var map2 = new Map2();
          if (object instanceof Map2) object.each(function(value, key2) {
            map2.set(key2, value);
          });
          else if (Array.isArray(object)) {
            var i = -1, n = object.length, o;
            if (f == null) while (++i < n) map2.set(i, object[i]);
            else while (++i < n) map2.set(f(o = object[i], i, object), o);
          } else if (object) for (var key in object) map2.set(key, object[key]);
          return map2;
        }
        function nest() {
          var keys2 = [], sortKeys = [], sortValues, rollup, nest2;
          function apply(array, depth, createResult, setResult) {
            if (depth >= keys2.length) {
              if (sortValues != null) array.sort(sortValues);
              return rollup != null ? rollup(array) : array;
            }
            var i = -1, n = array.length, key = keys2[depth++], keyValue, value, valuesByKey = map(), values2, result = createResult();
            while (++i < n) {
              if (values2 = valuesByKey.get(keyValue = key(value = array[i]) + "")) {
                values2.push(value);
              } else {
                valuesByKey.set(keyValue, [value]);
              }
            }
            valuesByKey.each(function(values3, key2) {
              setResult(result, key2, apply(values3, depth, createResult, setResult));
            });
            return result;
          }
          function entries2(map$$1, depth) {
            if (++depth > keys2.length) return map$$1;
            var array, sortKey = sortKeys[depth - 1];
            if (rollup != null && depth >= keys2.length) array = map$$1.entries();
            else array = [], map$$1.each(function(v, k) {
              array.push({ key: k, values: entries2(v, depth) });
            });
            return sortKey != null ? array.sort(function(a, b) {
              return sortKey(a.key, b.key);
            }) : array;
          }
          return nest2 = {
            object: function(array) {
              return apply(array, 0, createObject, setObject);
            },
            map: function(array) {
              return apply(array, 0, createMap, setMap);
            },
            entries: function(array) {
              return entries2(apply(array, 0, createMap, setMap), 0);
            },
            key: function(d) {
              keys2.push(d);
              return nest2;
            },
            sortKeys: function(order) {
              sortKeys[keys2.length - 1] = order;
              return nest2;
            },
            sortValues: function(order) {
              sortValues = order;
              return nest2;
            },
            rollup: function(f) {
              rollup = f;
              return nest2;
            }
          };
        }
        function createObject() {
          return {};
        }
        function setObject(object, key, value) {
          object[key] = value;
        }
        function createMap() {
          return map();
        }
        function setMap(map$$1, key, value) {
          map$$1.set(key, value);
        }
        function Set2() {
        }
        var proto = map.prototype;
        Set2.prototype = set.prototype = {
          constructor: Set2,
          has: proto.has,
          add: function(value) {
            value += "";
            this[prefix + value] = value;
            return this;
          },
          remove: proto.remove,
          clear: proto.clear,
          values: proto.keys,
          size: proto.size,
          empty: proto.empty,
          each: proto.each
        };
        function set(object, f) {
          var set2 = new Set2();
          if (object instanceof Set2) object.each(function(value) {
            set2.add(value);
          });
          else if (object) {
            var i = -1, n = object.length;
            if (f == null) while (++i < n) set2.add(object[i]);
            else while (++i < n) set2.add(f(object[i], i, object));
          }
          return set2;
        }
        function keys(map2) {
          var keys2 = [];
          for (var key in map2) keys2.push(key);
          return keys2;
        }
        function values(map2) {
          var values2 = [];
          for (var key in map2) values2.push(map2[key]);
          return values2;
        }
        function entries(map2) {
          var entries2 = [];
          for (var key in map2) entries2.push({ key, value: map2[key] });
          return entries2;
        }
        exports2.nest = nest;
        exports2.set = set;
        exports2.map = map;
        exports2.keys = keys;
        exports2.values = values;
        exports2.entries = entries;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-dispatch/dist/d3-dispatch.js
  var require_d3_dispatch = __commonJS({
    "node_modules/d3-dispatch/dist/d3-dispatch.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}));
      })(exports, function(exports2) {
        "use strict";
        var noop = { value: function() {
        } };
        function dispatch() {
          for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
            if (!(t = arguments[i] + "") || t in _ || /[\s.]/.test(t)) throw new Error("illegal type: " + t);
            _[t] = [];
          }
          return new Dispatch(_);
        }
        function Dispatch(_) {
          this._ = _;
        }
        function parseTypenames(typenames, types) {
          return typenames.trim().split(/^|\s+/).map(function(t) {
            var name2 = "", i = t.indexOf(".");
            if (i >= 0) name2 = t.slice(i + 1), t = t.slice(0, i);
            if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
            return { type: t, name: name2 };
          });
        }
        Dispatch.prototype = dispatch.prototype = {
          constructor: Dispatch,
          on: function(typename, callback) {
            var _ = this._, T = parseTypenames(typename + "", _), t, i = -1, n = T.length;
            if (arguments.length < 2) {
              while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
              return;
            }
            if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
            while (++i < n) {
              if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
              else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
            }
            return this;
          },
          copy: function() {
            var copy = {}, _ = this._;
            for (var t in _) copy[t] = _[t].slice();
            return new Dispatch(copy);
          },
          call: function(type, that) {
            if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
            if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
            for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
          },
          apply: function(type, that, args) {
            if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
            for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
          }
        };
        function get(type, name2) {
          for (var i = 0, n = type.length, c; i < n; ++i) {
            if ((c = type[i]).name === name2) {
              return c.value;
            }
          }
        }
        function set(type, name2, callback) {
          for (var i = 0, n = type.length; i < n; ++i) {
            if (type[i].name === name2) {
              type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
              break;
            }
          }
          if (callback != null) type.push({ name: name2, value: callback });
          return type;
        }
        exports2.dispatch = dispatch;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-timer/dist/d3-timer.js
  var require_d3_timer = __commonJS({
    "node_modules/d3-timer/dist/d3-timer.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}));
      })(exports, function(exports2) {
        "use strict";
        var frame = 0, timeout = 0, interval = 0, pokeDelay = 1e3, taskHead, taskTail, clockLast = 0, clockNow = 0, clockSkew = 0, clock = typeof performance === "object" && performance.now ? performance : Date, setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) {
          setTimeout(f, 17);
        };
        function now() {
          return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
        }
        function clearNow() {
          clockNow = 0;
        }
        function Timer() {
          this._call = this._time = this._next = null;
        }
        Timer.prototype = timer.prototype = {
          constructor: Timer,
          restart: function(callback, delay, time) {
            if (typeof callback !== "function") throw new TypeError("callback is not a function");
            time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
            if (!this._next && taskTail !== this) {
              if (taskTail) taskTail._next = this;
              else taskHead = this;
              taskTail = this;
            }
            this._call = callback;
            this._time = time;
            sleep();
          },
          stop: function() {
            if (this._call) {
              this._call = null;
              this._time = Infinity;
              sleep();
            }
          }
        };
        function timer(callback, delay, time) {
          var t = new Timer();
          t.restart(callback, delay, time);
          return t;
        }
        function timerFlush() {
          now();
          ++frame;
          var t = taskHead, e;
          while (t) {
            if ((e = clockNow - t._time) >= 0) t._call.call(null, e);
            t = t._next;
          }
          --frame;
        }
        function wake() {
          clockNow = (clockLast = clock.now()) + clockSkew;
          frame = timeout = 0;
          try {
            timerFlush();
          } finally {
            frame = 0;
            nap();
            clockNow = 0;
          }
        }
        function poke() {
          var now2 = clock.now(), delay = now2 - clockLast;
          if (delay > pokeDelay) clockSkew -= delay, clockLast = now2;
        }
        function nap() {
          var t02, t12 = taskHead, t22, time = Infinity;
          while (t12) {
            if (t12._call) {
              if (time > t12._time) time = t12._time;
              t02 = t12, t12 = t12._next;
            } else {
              t22 = t12._next, t12._next = null;
              t12 = t02 ? t02._next = t22 : taskHead = t22;
            }
          }
          taskTail = t02;
          sleep(time);
        }
        function sleep(time) {
          if (frame) return;
          if (timeout) timeout = clearTimeout(timeout);
          var delay = time - clockNow;
          if (delay > 24) {
            if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);
            if (interval) interval = clearInterval(interval);
          } else {
            if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
            frame = 1, setFrame(wake);
          }
        }
        function timeout$1(callback, delay, time) {
          var t = new Timer();
          delay = delay == null ? 0 : +delay;
          t.restart(function(elapsed) {
            t.stop();
            callback(elapsed + delay);
          }, delay, time);
          return t;
        }
        function interval$1(callback, delay, time) {
          var t = new Timer(), total = delay;
          if (delay == null) return t.restart(callback, delay, time), t;
          delay = +delay, time = time == null ? now() : +time;
          t.restart(function tick(elapsed) {
            elapsed += total;
            t.restart(tick, total += delay, time);
            callback(elapsed);
          }, delay, time);
          return t;
        }
        exports2.interval = interval$1;
        exports2.now = now;
        exports2.timeout = timeout$1;
        exports2.timer = timer;
        exports2.timerFlush = timerFlush;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-force/dist/d3-force.js
  var require_d3_force = __commonJS({
    "node_modules/d3-force/dist/d3-force.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require_d3_quadtree(), require_d3_collection(), require_d3_dispatch(), require_d3_timer()) : typeof define === "function" && false ? define(["exports", "d3-quadtree", "d3-collection", "d3-dispatch", "d3-timer"], factory) : factory(global2.d3 = global2.d3 || {}, global2.d3, global2.d3, global2.d3, global2.d3);
      })(exports, function(exports2, d3Quadtree, d3Collection, d3Dispatch, d3Timer) {
        "use strict";
        function center(x2, y2) {
          var nodes;
          if (x2 == null) x2 = 0;
          if (y2 == null) y2 = 0;
          function force() {
            var i, n = nodes.length, node, sx = 0, sy = 0;
            for (i = 0; i < n; ++i) {
              node = nodes[i], sx += node.x, sy += node.y;
            }
            for (sx = sx / n - x2, sy = sy / n - y2, i = 0; i < n; ++i) {
              node = nodes[i], node.x -= sx, node.y -= sy;
            }
          }
          force.initialize = function(_) {
            nodes = _;
          };
          force.x = function(_) {
            return arguments.length ? (x2 = +_, force) : x2;
          };
          force.y = function(_) {
            return arguments.length ? (y2 = +_, force) : y2;
          };
          return force;
        }
        function constant(x2) {
          return function() {
            return x2;
          };
        }
        function jiggle() {
          return (Math.random() - 0.5) * 1e-6;
        }
        function x(d) {
          return d.x + d.vx;
        }
        function y(d) {
          return d.y + d.vy;
        }
        function collide(radius) {
          var nodes, radii, strength = 1, iterations = 1;
          if (typeof radius !== "function") radius = constant(radius == null ? 1 : +radius);
          function force() {
            var i, n = nodes.length, tree, node, xi, yi, ri, ri2;
            for (var k = 0; k < iterations; ++k) {
              tree = d3Quadtree.quadtree(nodes, x, y).visitAfter(prepare);
              for (i = 0; i < n; ++i) {
                node = nodes[i];
                ri = radii[node.index], ri2 = ri * ri;
                xi = node.x + node.vx;
                yi = node.y + node.vy;
                tree.visit(apply);
              }
            }
            function apply(quad, x0, y0, x1, y1) {
              var data = quad.data, rj = quad.r, r = ri + rj;
              if (data) {
                if (data.index > node.index) {
                  var x2 = xi - data.x - data.vx, y2 = yi - data.y - data.vy, l = x2 * x2 + y2 * y2;
                  if (l < r * r) {
                    if (x2 === 0) x2 = jiggle(), l += x2 * x2;
                    if (y2 === 0) y2 = jiggle(), l += y2 * y2;
                    l = (r - (l = Math.sqrt(l))) / l * strength;
                    node.vx += (x2 *= l) * (r = (rj *= rj) / (ri2 + rj));
                    node.vy += (y2 *= l) * r;
                    data.vx -= x2 * (r = 1 - r);
                    data.vy -= y2 * r;
                  }
                }
                return;
              }
              return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
            }
          }
          function prepare(quad) {
            if (quad.data) return quad.r = radii[quad.data.index];
            for (var i = quad.r = 0; i < 4; ++i) {
              if (quad[i] && quad[i].r > quad.r) {
                quad.r = quad[i].r;
              }
            }
          }
          function initialize() {
            if (!nodes) return;
            var i, n = nodes.length, node;
            radii = new Array(n);
            for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);
          }
          force.initialize = function(_) {
            nodes = _;
            initialize();
          };
          force.iterations = function(_) {
            return arguments.length ? (iterations = +_, force) : iterations;
          };
          force.strength = function(_) {
            return arguments.length ? (strength = +_, force) : strength;
          };
          force.radius = function(_) {
            return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
          };
          return force;
        }
        function index(d) {
          return d.index;
        }
        function find(nodeById, nodeId) {
          var node = nodeById.get(nodeId);
          if (!node) throw new Error("missing: " + nodeId);
          return node;
        }
        function link(links) {
          var id = index, strength = defaultStrength, strengths, distance = constant(30), distances, nodes, count, bias, iterations = 1;
          if (links == null) links = [];
          function defaultStrength(link2) {
            return 1 / Math.min(count[link2.source.index], count[link2.target.index]);
          }
          function force(alpha) {
            for (var k = 0, n = links.length; k < iterations; ++k) {
              for (var i = 0, link2, source, target, x2, y2, l, b; i < n; ++i) {
                link2 = links[i], source = link2.source, target = link2.target;
                x2 = target.x + target.vx - source.x - source.vx || jiggle();
                y2 = target.y + target.vy - source.y - source.vy || jiggle();
                l = Math.sqrt(x2 * x2 + y2 * y2);
                l = (l - distances[i]) / l * alpha * strengths[i];
                x2 *= l, y2 *= l;
                target.vx -= x2 * (b = bias[i]);
                target.vy -= y2 * b;
                source.vx += x2 * (b = 1 - b);
                source.vy += y2 * b;
              }
            }
          }
          function initialize() {
            if (!nodes) return;
            var i, n = nodes.length, m = links.length, nodeById = d3Collection.map(nodes, id), link2;
            for (i = 0, count = new Array(n); i < m; ++i) {
              link2 = links[i], link2.index = i;
              if (typeof link2.source !== "object") link2.source = find(nodeById, link2.source);
              if (typeof link2.target !== "object") link2.target = find(nodeById, link2.target);
              count[link2.source.index] = (count[link2.source.index] || 0) + 1;
              count[link2.target.index] = (count[link2.target.index] || 0) + 1;
            }
            for (i = 0, bias = new Array(m); i < m; ++i) {
              link2 = links[i], bias[i] = count[link2.source.index] / (count[link2.source.index] + count[link2.target.index]);
            }
            strengths = new Array(m), initializeStrength();
            distances = new Array(m), initializeDistance();
          }
          function initializeStrength() {
            if (!nodes) return;
            for (var i = 0, n = links.length; i < n; ++i) {
              strengths[i] = +strength(links[i], i, links);
            }
          }
          function initializeDistance() {
            if (!nodes) return;
            for (var i = 0, n = links.length; i < n; ++i) {
              distances[i] = +distance(links[i], i, links);
            }
          }
          force.initialize = function(_) {
            nodes = _;
            initialize();
          };
          force.links = function(_) {
            return arguments.length ? (links = _, initialize(), force) : links;
          };
          force.id = function(_) {
            return arguments.length ? (id = _, force) : id;
          };
          force.iterations = function(_) {
            return arguments.length ? (iterations = +_, force) : iterations;
          };
          force.strength = function(_) {
            return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
          };
          force.distance = function(_) {
            return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
          };
          return force;
        }
        function x$1(d) {
          return d.x;
        }
        function y$1(d) {
          return d.y;
        }
        var initialRadius = 10, initialAngle = Math.PI * (3 - Math.sqrt(5));
        function simulation(nodes) {
          var simulation2, alpha = 1, alphaMin = 1e-3, alphaDecay = 1 - Math.pow(alphaMin, 1 / 300), alphaTarget = 0, velocityDecay = 0.6, forces = d3Collection.map(), stepper = d3Timer.timer(step), event = d3Dispatch.dispatch("tick", "end");
          if (nodes == null) nodes = [];
          function step() {
            tick();
            event.call("tick", simulation2);
            if (alpha < alphaMin) {
              stepper.stop();
              event.call("end", simulation2);
            }
          }
          function tick(iterations) {
            var i, n = nodes.length, node;
            if (iterations === void 0) iterations = 1;
            for (var k = 0; k < iterations; ++k) {
              alpha += (alphaTarget - alpha) * alphaDecay;
              forces.each(function(force) {
                force(alpha);
              });
              for (i = 0; i < n; ++i) {
                node = nodes[i];
                if (node.fx == null) node.x += node.vx *= velocityDecay;
                else node.x = node.fx, node.vx = 0;
                if (node.fy == null) node.y += node.vy *= velocityDecay;
                else node.y = node.fy, node.vy = 0;
              }
            }
            return simulation2;
          }
          function initializeNodes() {
            for (var i = 0, n = nodes.length, node; i < n; ++i) {
              node = nodes[i], node.index = i;
              if (node.fx != null) node.x = node.fx;
              if (node.fy != null) node.y = node.fy;
              if (isNaN(node.x) || isNaN(node.y)) {
                var radius = initialRadius * Math.sqrt(i), angle = i * initialAngle;
                node.x = radius * Math.cos(angle);
                node.y = radius * Math.sin(angle);
              }
              if (isNaN(node.vx) || isNaN(node.vy)) {
                node.vx = node.vy = 0;
              }
            }
          }
          function initializeForce(force) {
            if (force.initialize) force.initialize(nodes);
            return force;
          }
          initializeNodes();
          return simulation2 = {
            tick,
            restart: function() {
              return stepper.restart(step), simulation2;
            },
            stop: function() {
              return stepper.stop(), simulation2;
            },
            nodes: function(_) {
              return arguments.length ? (nodes = _, initializeNodes(), forces.each(initializeForce), simulation2) : nodes;
            },
            alpha: function(_) {
              return arguments.length ? (alpha = +_, simulation2) : alpha;
            },
            alphaMin: function(_) {
              return arguments.length ? (alphaMin = +_, simulation2) : alphaMin;
            },
            alphaDecay: function(_) {
              return arguments.length ? (alphaDecay = +_, simulation2) : +alphaDecay;
            },
            alphaTarget: function(_) {
              return arguments.length ? (alphaTarget = +_, simulation2) : alphaTarget;
            },
            velocityDecay: function(_) {
              return arguments.length ? (velocityDecay = 1 - _, simulation2) : 1 - velocityDecay;
            },
            force: function(name2, _) {
              return arguments.length > 1 ? (_ == null ? forces.remove(name2) : forces.set(name2, initializeForce(_)), simulation2) : forces.get(name2);
            },
            find: function(x2, y2, radius) {
              var i = 0, n = nodes.length, dx, dy, d2, node, closest;
              if (radius == null) radius = Infinity;
              else radius *= radius;
              for (i = 0; i < n; ++i) {
                node = nodes[i];
                dx = x2 - node.x;
                dy = y2 - node.y;
                d2 = dx * dx + dy * dy;
                if (d2 < radius) closest = node, radius = d2;
              }
              return closest;
            },
            on: function(name2, _) {
              return arguments.length > 1 ? (event.on(name2, _), simulation2) : event.on(name2);
            }
          };
        }
        function manyBody() {
          var nodes, node, alpha, strength = constant(-30), strengths, distanceMin2 = 1, distanceMax2 = Infinity, theta2 = 0.81;
          function force(_) {
            var i, n = nodes.length, tree = d3Quadtree.quadtree(nodes, x$1, y$1).visitAfter(accumulate);
            for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);
          }
          function initialize() {
            if (!nodes) return;
            var i, n = nodes.length, node2;
            strengths = new Array(n);
            for (i = 0; i < n; ++i) node2 = nodes[i], strengths[node2.index] = +strength(node2, i, nodes);
          }
          function accumulate(quad) {
            var strength2 = 0, q, c, weight = 0, x2, y2, i;
            if (quad.length) {
              for (x2 = y2 = i = 0; i < 4; ++i) {
                if ((q = quad[i]) && (c = Math.abs(q.value))) {
                  strength2 += q.value, weight += c, x2 += c * q.x, y2 += c * q.y;
                }
              }
              quad.x = x2 / weight;
              quad.y = y2 / weight;
            } else {
              q = quad;
              q.x = q.data.x;
              q.y = q.data.y;
              do
                strength2 += strengths[q.data.index];
              while (q = q.next);
            }
            quad.value = strength2;
          }
          function apply(quad, x1, _, x2) {
            if (!quad.value) return true;
            var x3 = quad.x - node.x, y2 = quad.y - node.y, w = x2 - x1, l = x3 * x3 + y2 * y2;
            if (w * w / theta2 < l) {
              if (l < distanceMax2) {
                if (x3 === 0) x3 = jiggle(), l += x3 * x3;
                if (y2 === 0) y2 = jiggle(), l += y2 * y2;
                if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
                node.vx += x3 * quad.value * alpha / l;
                node.vy += y2 * quad.value * alpha / l;
              }
              return true;
            } else if (quad.length || l >= distanceMax2) return;
            if (quad.data !== node || quad.next) {
              if (x3 === 0) x3 = jiggle(), l += x3 * x3;
              if (y2 === 0) y2 = jiggle(), l += y2 * y2;
              if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
            }
            do
              if (quad.data !== node) {
                w = strengths[quad.data.index] * alpha / l;
                node.vx += x3 * w;
                node.vy += y2 * w;
              }
            while (quad = quad.next);
          }
          force.initialize = function(_) {
            nodes = _;
            initialize();
          };
          force.strength = function(_) {
            return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
          };
          force.distanceMin = function(_) {
            return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
          };
          force.distanceMax = function(_) {
            return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
          };
          force.theta = function(_) {
            return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
          };
          return force;
        }
        function radial(radius, x2, y2) {
          var nodes, strength = constant(0.1), strengths, radiuses;
          if (typeof radius !== "function") radius = constant(+radius);
          if (x2 == null) x2 = 0;
          if (y2 == null) y2 = 0;
          function force(alpha) {
            for (var i = 0, n = nodes.length; i < n; ++i) {
              var node = nodes[i], dx = node.x - x2 || 1e-6, dy = node.y - y2 || 1e-6, r = Math.sqrt(dx * dx + dy * dy), k = (radiuses[i] - r) * strengths[i] * alpha / r;
              node.vx += dx * k;
              node.vy += dy * k;
            }
          }
          function initialize() {
            if (!nodes) return;
            var i, n = nodes.length;
            strengths = new Array(n);
            radiuses = new Array(n);
            for (i = 0; i < n; ++i) {
              radiuses[i] = +radius(nodes[i], i, nodes);
              strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
            }
          }
          force.initialize = function(_) {
            nodes = _, initialize();
          };
          force.strength = function(_) {
            return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
          };
          force.radius = function(_) {
            return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
          };
          force.x = function(_) {
            return arguments.length ? (x2 = +_, force) : x2;
          };
          force.y = function(_) {
            return arguments.length ? (y2 = +_, force) : y2;
          };
          return force;
        }
        function x$2(x2) {
          var strength = constant(0.1), nodes, strengths, xz;
          if (typeof x2 !== "function") x2 = constant(x2 == null ? 0 : +x2);
          function force(alpha) {
            for (var i = 0, n = nodes.length, node; i < n; ++i) {
              node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;
            }
          }
          function initialize() {
            if (!nodes) return;
            var i, n = nodes.length;
            strengths = new Array(n);
            xz = new Array(n);
            for (i = 0; i < n; ++i) {
              strengths[i] = isNaN(xz[i] = +x2(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
            }
          }
          force.initialize = function(_) {
            nodes = _;
            initialize();
          };
          force.strength = function(_) {
            return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
          };
          force.x = function(_) {
            return arguments.length ? (x2 = typeof _ === "function" ? _ : constant(+_), initialize(), force) : x2;
          };
          return force;
        }
        function y$2(y2) {
          var strength = constant(0.1), nodes, strengths, yz;
          if (typeof y2 !== "function") y2 = constant(y2 == null ? 0 : +y2);
          function force(alpha) {
            for (var i = 0, n = nodes.length, node; i < n; ++i) {
              node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
            }
          }
          function initialize() {
            if (!nodes) return;
            var i, n = nodes.length;
            strengths = new Array(n);
            yz = new Array(n);
            for (i = 0; i < n; ++i) {
              strengths[i] = isNaN(yz[i] = +y2(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
            }
          }
          force.initialize = function(_) {
            nodes = _;
            initialize();
          };
          force.strength = function(_) {
            return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
          };
          force.y = function(_) {
            return arguments.length ? (y2 = typeof _ === "function" ? _ : constant(+_), initialize(), force) : y2;
          };
          return force;
        }
        exports2.forceCenter = center;
        exports2.forceCollide = collide;
        exports2.forceLink = link;
        exports2.forceManyBody = manyBody;
        exports2.forceRadial = radial;
        exports2.forceSimulation = simulation;
        exports2.forceX = x$2;
        exports2.forceY = y$2;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-path/dist/d3-path.js
  var require_d3_path = __commonJS({
    "node_modules/d3-path/dist/d3-path.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && false ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}));
      })(exports, function(exports2) {
        "use strict";
        var pi = Math.PI, tau = 2 * pi, epsilon = 1e-6, tauEpsilon = tau - epsilon;
        function Path() {
          this._x0 = this._y0 = // start of current subpath
          this._x1 = this._y1 = null;
          this._ = "";
        }
        function path() {
          return new Path();
        }
        Path.prototype = path.prototype = {
          constructor: Path,
          moveTo: function(x, y) {
            this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
          },
          closePath: function() {
            if (this._x1 !== null) {
              this._x1 = this._x0, this._y1 = this._y0;
              this._ += "Z";
            }
          },
          lineTo: function(x, y) {
            this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
          },
          quadraticCurveTo: function(x1, y1, x, y) {
            this._ += "Q" + +x1 + "," + +y1 + "," + (this._x1 = +x) + "," + (this._y1 = +y);
          },
          bezierCurveTo: function(x1, y1, x2, y2, x, y) {
            this._ += "C" + +x1 + "," + +y1 + "," + +x2 + "," + +y2 + "," + (this._x1 = +x) + "," + (this._y1 = +y);
          },
          arcTo: function(x1, y1, x2, y2, r) {
            x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
            var x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01;
            if (r < 0) throw new Error("negative radius: " + r);
            if (this._x1 === null) {
              this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
            } else if (!(l01_2 > epsilon)) ;
            else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {
              this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
            } else {
              var x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21;
              if (Math.abs(t01 - 1) > epsilon) {
                this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
              }
              this._ += "A" + r + "," + r + ",0,0," + +(y01 * x20 > x01 * y20) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
            }
          },
          arc: function(x, y, r, a0, a1, ccw) {
            x = +x, y = +y, r = +r, ccw = !!ccw;
            var dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x + dx, y0 = y + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
            if (r < 0) throw new Error("negative radius: " + r);
            if (this._x1 === null) {
              this._ += "M" + x0 + "," + y0;
            } else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {
              this._ += "L" + x0 + "," + y0;
            }
            if (!r) return;
            if (da < 0) da = da % tau + tau;
            if (da > tauEpsilon) {
              this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
            } else if (da > epsilon) {
              this._ += "A" + r + "," + r + ",0," + +(da >= pi) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1));
            }
          },
          rect: function(x, y, w, h) {
            this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + +w + "v" + +h + "h" + -w + "Z";
          },
          toString: function() {
            return this._;
          }
        };
        exports2.path = path;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/d3-shape/dist/d3-shape.js
  var require_d3_shape = __commonJS({
    "node_modules/d3-shape/dist/d3-shape.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require_d3_path()) : typeof define === "function" && false ? define(["exports", "d3-path"], factory) : (global2 = global2 || self, factory(global2.d3 = global2.d3 || {}, global2.d3));
      })(exports, function(exports2, d3Path) {
        "use strict";
        function constant(x2) {
          return function constant2() {
            return x2;
          };
        }
        var abs = Math.abs;
        var atan2 = Math.atan2;
        var cos = Math.cos;
        var max = Math.max;
        var min = Math.min;
        var sin = Math.sin;
        var sqrt = Math.sqrt;
        var epsilon = 1e-12;
        var pi = Math.PI;
        var halfPi = pi / 2;
        var tau = 2 * pi;
        function acos(x2) {
          return x2 > 1 ? 0 : x2 < -1 ? pi : Math.acos(x2);
        }
        function asin(x2) {
          return x2 >= 1 ? halfPi : x2 <= -1 ? -halfPi : Math.asin(x2);
        }
        function arcInnerRadius(d) {
          return d.innerRadius;
        }
        function arcOuterRadius(d) {
          return d.outerRadius;
        }
        function arcStartAngle(d) {
          return d.startAngle;
        }
        function arcEndAngle(d) {
          return d.endAngle;
        }
        function arcPadAngle(d) {
          return d && d.padAngle;
        }
        function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
          var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t = y32 * x10 - x32 * y10;
          if (t * t < epsilon) return;
          t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
          return [x0 + t * x10, y0 + t * y10];
        }
        function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
          var x01 = x0 - x1, y01 = y0 - y1, lo = (cw ? rc : -rc) / sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r = r1 - rc, D2 = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * sqrt(max(0, r * r * d2 - D2 * D2)), cx0 = (D2 * dy - dx * d) / d2, cy0 = (-D2 * dx - dy * d) / d2, cx1 = (D2 * dy + dx * d) / d2, cy1 = (-D2 * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00;
          if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
          return {
            cx: cx0,
            cy: cy0,
            x01: -ox,
            y01: -oy,
            x11: cx0 * (r1 / r - 1),
            y11: cy0 * (r1 / r - 1)
          };
        }
        function arc() {
          var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context = null;
          function arc2() {
            var buffer, r, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi, a1 = endAngle.apply(this, arguments) - halfPi, da = abs(a1 - a0), cw = a1 > a0;
            if (!context) context = buffer = d3Path.path();
            if (r1 < r0) r = r1, r1 = r0, r0 = r;
            if (!(r1 > epsilon)) context.moveTo(0, 0);
            else if (da > tau - epsilon) {
              context.moveTo(r1 * cos(a0), r1 * sin(a0));
              context.arc(0, 0, r1, a0, a1, !cw);
              if (r0 > epsilon) {
                context.moveTo(r0 * cos(a1), r0 * sin(a1));
                context.arc(0, 0, r0, a1, a0, cw);
              }
            } else {
              var a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da, da1 = da, ap = padAngle.apply(this, arguments) / 2, rp = ap > epsilon && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)), rc = min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t02, t12;
              if (rp > epsilon) {
                var p0 = asin(rp / r0 * sin(ap)), p1 = asin(rp / r1 * sin(ap));
                if ((da0 -= p0 * 2) > epsilon) p0 *= cw ? 1 : -1, a00 += p0, a10 -= p0;
                else da0 = 0, a00 = a10 = (a0 + a1) / 2;
                if ((da1 -= p1 * 2) > epsilon) p1 *= cw ? 1 : -1, a01 += p1, a11 -= p1;
                else da1 = 0, a01 = a11 = (a0 + a1) / 2;
              }
              var x01 = r1 * cos(a01), y01 = r1 * sin(a01), x10 = r0 * cos(a10), y10 = r0 * sin(a10);
              if (rc > epsilon) {
                var x11 = r1 * cos(a11), y11 = r1 * sin(a11), x00 = r0 * cos(a00), y00 = r0 * sin(a00), oc;
                if (da < pi && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {
                  var ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2), lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
                  rc0 = min(rc, (r0 - lc) / (kc - 1));
                  rc1 = min(rc, (r1 - lc) / (kc + 1));
                }
              }
              if (!(da1 > epsilon)) context.moveTo(x01, y01);
              else if (rc1 > epsilon) {
                t02 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
                t12 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
                context.moveTo(t02.cx + t02.x01, t02.cy + t02.y01);
                if (rc1 < rc) context.arc(t02.cx, t02.cy, rc1, atan2(t02.y01, t02.x01), atan2(t12.y01, t12.x01), !cw);
                else {
                  context.arc(t02.cx, t02.cy, rc1, atan2(t02.y01, t02.x01), atan2(t02.y11, t02.x11), !cw);
                  context.arc(0, 0, r1, atan2(t02.cy + t02.y11, t02.cx + t02.x11), atan2(t12.cy + t12.y11, t12.cx + t12.x11), !cw);
                  context.arc(t12.cx, t12.cy, rc1, atan2(t12.y11, t12.x11), atan2(t12.y01, t12.x01), !cw);
                }
              } else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);
              if (!(r0 > epsilon) || !(da0 > epsilon)) context.lineTo(x10, y10);
              else if (rc0 > epsilon) {
                t02 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
                t12 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
                context.lineTo(t02.cx + t02.x01, t02.cy + t02.y01);
                if (rc0 < rc) context.arc(t02.cx, t02.cy, rc0, atan2(t02.y01, t02.x01), atan2(t12.y01, t12.x01), !cw);
                else {
                  context.arc(t02.cx, t02.cy, rc0, atan2(t02.y01, t02.x01), atan2(t02.y11, t02.x11), !cw);
                  context.arc(0, 0, r0, atan2(t02.cy + t02.y11, t02.cx + t02.x11), atan2(t12.cy + t12.y11, t12.cx + t12.x11), cw);
                  context.arc(t12.cx, t12.cy, rc0, atan2(t12.y11, t12.x11), atan2(t12.y01, t12.x01), !cw);
                }
              } else context.arc(0, 0, r0, a10, a00, cw);
            }
            context.closePath();
            if (buffer) return context = null, buffer + "" || null;
          }
          arc2.centroid = function() {
            var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a2 = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;
            return [cos(a2) * r, sin(a2) * r];
          };
          arc2.innerRadius = function(_) {
            return arguments.length ? (innerRadius = typeof _ === "function" ? _ : constant(+_), arc2) : innerRadius;
          };
          arc2.outerRadius = function(_) {
            return arguments.length ? (outerRadius = typeof _ === "function" ? _ : constant(+_), arc2) : outerRadius;
          };
          arc2.cornerRadius = function(_) {
            return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : constant(+_), arc2) : cornerRadius;
          };
          arc2.padRadius = function(_) {
            return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : constant(+_), arc2) : padRadius;
          };
          arc2.startAngle = function(_) {
            return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), arc2) : startAngle;
          };
          arc2.endAngle = function(_) {
            return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), arc2) : endAngle;
          };
          arc2.padAngle = function(_) {
            return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), arc2) : padAngle;
          };
          arc2.context = function(_) {
            return arguments.length ? (context = _ == null ? null : _, arc2) : context;
          };
          return arc2;
        }
        function Linear(context) {
          this._context = context;
        }
        Linear.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._point = 0;
          },
          lineEnd: function() {
            if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
                break;
              case 1:
                this._point = 2;
              // proceed
              default:
                this._context.lineTo(x2, y2);
                break;
            }
          }
        };
        function curveLinear(context) {
          return new Linear(context);
        }
        function x(p) {
          return p[0];
        }
        function y(p) {
          return p[1];
        }
        function line() {
          var x$1 = x, y$1 = y, defined = constant(true), context = null, curve = curveLinear, output = null;
          function line2(data) {
            var i, n = data.length, d, defined0 = false, buffer;
            if (context == null) output = curve(buffer = d3Path.path());
            for (i = 0; i <= n; ++i) {
              if (!(i < n && defined(d = data[i], i, data)) === defined0) {
                if (defined0 = !defined0) output.lineStart();
                else output.lineEnd();
              }
              if (defined0) output.point(+x$1(d, i, data), +y$1(d, i, data));
            }
            if (buffer) return output = null, buffer + "" || null;
          }
          line2.x = function(_) {
            return arguments.length ? (x$1 = typeof _ === "function" ? _ : constant(+_), line2) : x$1;
          };
          line2.y = function(_) {
            return arguments.length ? (y$1 = typeof _ === "function" ? _ : constant(+_), line2) : y$1;
          };
          line2.defined = function(_) {
            return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), line2) : defined;
          };
          line2.curve = function(_) {
            return arguments.length ? (curve = _, context != null && (output = curve(context)), line2) : curve;
          };
          line2.context = function(_) {
            return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line2) : context;
          };
          return line2;
        }
        function area() {
          var x0 = x, x1 = null, y0 = constant(0), y1 = y, defined = constant(true), context = null, curve = curveLinear, output = null;
          function area2(data) {
            var i, j, k2, n = data.length, d, defined0 = false, buffer, x0z = new Array(n), y0z = new Array(n);
            if (context == null) output = curve(buffer = d3Path.path());
            for (i = 0; i <= n; ++i) {
              if (!(i < n && defined(d = data[i], i, data)) === defined0) {
                if (defined0 = !defined0) {
                  j = i;
                  output.areaStart();
                  output.lineStart();
                } else {
                  output.lineEnd();
                  output.lineStart();
                  for (k2 = i - 1; k2 >= j; --k2) {
                    output.point(x0z[k2], y0z[k2]);
                  }
                  output.lineEnd();
                  output.areaEnd();
                }
              }
              if (defined0) {
                x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
                output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
              }
            }
            if (buffer) return output = null, buffer + "" || null;
          }
          function arealine() {
            return line().defined(defined).curve(curve).context(context);
          }
          area2.x = function(_) {
            return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), x1 = null, area2) : x0;
          };
          area2.x0 = function(_) {
            return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), area2) : x0;
          };
          area2.x1 = function(_) {
            return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area2) : x1;
          };
          area2.y = function(_) {
            return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), y1 = null, area2) : y0;
          };
          area2.y0 = function(_) {
            return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), area2) : y0;
          };
          area2.y1 = function(_) {
            return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area2) : y1;
          };
          area2.lineX0 = area2.lineY0 = function() {
            return arealine().x(x0).y(y0);
          };
          area2.lineY1 = function() {
            return arealine().x(x0).y(y1);
          };
          area2.lineX1 = function() {
            return arealine().x(x1).y(y0);
          };
          area2.defined = function(_) {
            return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), area2) : defined;
          };
          area2.curve = function(_) {
            return arguments.length ? (curve = _, context != null && (output = curve(context)), area2) : curve;
          };
          area2.context = function(_) {
            return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area2) : context;
          };
          return area2;
        }
        function descending(a2, b) {
          return b < a2 ? -1 : b > a2 ? 1 : b >= a2 ? 0 : NaN;
        }
        function identity2(d) {
          return d;
        }
        function pie() {
          var value = identity2, sortValues = descending, sort = null, startAngle = constant(0), endAngle = constant(tau), padAngle = constant(0);
          function pie2(data) {
            var i, n = data.length, j, k2, sum2 = 0, index = new Array(n), arcs = new Array(n), a0 = +startAngle.apply(this, arguments), da = Math.min(tau, Math.max(-tau, endAngle.apply(this, arguments) - a0)), a1, p = Math.min(Math.abs(da) / n, padAngle.apply(this, arguments)), pa = p * (da < 0 ? -1 : 1), v;
            for (i = 0; i < n; ++i) {
              if ((v = arcs[index[i] = i] = +value(data[i], i, data)) > 0) {
                sum2 += v;
              }
            }
            if (sortValues != null) index.sort(function(i2, j2) {
              return sortValues(arcs[i2], arcs[j2]);
            });
            else if (sort != null) index.sort(function(i2, j2) {
              return sort(data[i2], data[j2]);
            });
            for (i = 0, k2 = sum2 ? (da - n * pa) / sum2 : 0; i < n; ++i, a0 = a1) {
              j = index[i], v = arcs[j], a1 = a0 + (v > 0 ? v * k2 : 0) + pa, arcs[j] = {
                data: data[j],
                index: i,
                value: v,
                startAngle: a0,
                endAngle: a1,
                padAngle: p
              };
            }
            return arcs;
          }
          pie2.value = function(_) {
            return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), pie2) : value;
          };
          pie2.sortValues = function(_) {
            return arguments.length ? (sortValues = _, sort = null, pie2) : sortValues;
          };
          pie2.sort = function(_) {
            return arguments.length ? (sort = _, sortValues = null, pie2) : sort;
          };
          pie2.startAngle = function(_) {
            return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), pie2) : startAngle;
          };
          pie2.endAngle = function(_) {
            return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), pie2) : endAngle;
          };
          pie2.padAngle = function(_) {
            return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), pie2) : padAngle;
          };
          return pie2;
        }
        var curveRadialLinear = curveRadial(curveLinear);
        function Radial(curve) {
          this._curve = curve;
        }
        Radial.prototype = {
          areaStart: function() {
            this._curve.areaStart();
          },
          areaEnd: function() {
            this._curve.areaEnd();
          },
          lineStart: function() {
            this._curve.lineStart();
          },
          lineEnd: function() {
            this._curve.lineEnd();
          },
          point: function(a2, r) {
            this._curve.point(r * Math.sin(a2), r * -Math.cos(a2));
          }
        };
        function curveRadial(curve) {
          function radial(context) {
            return new Radial(curve(context));
          }
          radial._curve = curve;
          return radial;
        }
        function lineRadial(l) {
          var c2 = l.curve;
          l.angle = l.x, delete l.x;
          l.radius = l.y, delete l.y;
          l.curve = function(_) {
            return arguments.length ? c2(curveRadial(_)) : c2()._curve;
          };
          return l;
        }
        function lineRadial$1() {
          return lineRadial(line().curve(curveRadialLinear));
        }
        function areaRadial() {
          var a2 = area().curve(curveRadialLinear), c2 = a2.curve, x0 = a2.lineX0, x1 = a2.lineX1, y0 = a2.lineY0, y1 = a2.lineY1;
          a2.angle = a2.x, delete a2.x;
          a2.startAngle = a2.x0, delete a2.x0;
          a2.endAngle = a2.x1, delete a2.x1;
          a2.radius = a2.y, delete a2.y;
          a2.innerRadius = a2.y0, delete a2.y0;
          a2.outerRadius = a2.y1, delete a2.y1;
          a2.lineStartAngle = function() {
            return lineRadial(x0());
          }, delete a2.lineX0;
          a2.lineEndAngle = function() {
            return lineRadial(x1());
          }, delete a2.lineX1;
          a2.lineInnerRadius = function() {
            return lineRadial(y0());
          }, delete a2.lineY0;
          a2.lineOuterRadius = function() {
            return lineRadial(y1());
          }, delete a2.lineY1;
          a2.curve = function(_) {
            return arguments.length ? c2(curveRadial(_)) : c2()._curve;
          };
          return a2;
        }
        function pointRadial(x2, y2) {
          return [(y2 = +y2) * Math.cos(x2 -= Math.PI / 2), y2 * Math.sin(x2)];
        }
        var slice = Array.prototype.slice;
        function linkSource(d) {
          return d.source;
        }
        function linkTarget(d) {
          return d.target;
        }
        function link(curve) {
          var source = linkSource, target = linkTarget, x$1 = x, y$1 = y, context = null;
          function link2() {
            var buffer, argv = slice.call(arguments), s2 = source.apply(this, argv), t = target.apply(this, argv);
            if (!context) context = buffer = d3Path.path();
            curve(context, +x$1.apply(this, (argv[0] = s2, argv)), +y$1.apply(this, argv), +x$1.apply(this, (argv[0] = t, argv)), +y$1.apply(this, argv));
            if (buffer) return context = null, buffer + "" || null;
          }
          link2.source = function(_) {
            return arguments.length ? (source = _, link2) : source;
          };
          link2.target = function(_) {
            return arguments.length ? (target = _, link2) : target;
          };
          link2.x = function(_) {
            return arguments.length ? (x$1 = typeof _ === "function" ? _ : constant(+_), link2) : x$1;
          };
          link2.y = function(_) {
            return arguments.length ? (y$1 = typeof _ === "function" ? _ : constant(+_), link2) : y$1;
          };
          link2.context = function(_) {
            return arguments.length ? (context = _ == null ? null : _, link2) : context;
          };
          return link2;
        }
        function curveHorizontal(context, x0, y0, x1, y1) {
          context.moveTo(x0, y0);
          context.bezierCurveTo(x0 = (x0 + x1) / 2, y0, x0, y1, x1, y1);
        }
        function curveVertical(context, x0, y0, x1, y1) {
          context.moveTo(x0, y0);
          context.bezierCurveTo(x0, y0 = (y0 + y1) / 2, x1, y0, x1, y1);
        }
        function curveRadial$1(context, x0, y0, x1, y1) {
          var p0 = pointRadial(x0, y0), p1 = pointRadial(x0, y0 = (y0 + y1) / 2), p2 = pointRadial(x1, y0), p3 = pointRadial(x1, y1);
          context.moveTo(p0[0], p0[1]);
          context.bezierCurveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
        }
        function linkHorizontal() {
          return link(curveHorizontal);
        }
        function linkVertical() {
          return link(curveVertical);
        }
        function linkRadial() {
          var l = link(curveRadial$1);
          l.angle = l.x, delete l.x;
          l.radius = l.y, delete l.y;
          return l;
        }
        var circle = {
          draw: function(context, size) {
            var r = Math.sqrt(size / pi);
            context.moveTo(r, 0);
            context.arc(0, 0, r, 0, tau);
          }
        };
        var cross = {
          draw: function(context, size) {
            var r = Math.sqrt(size / 5) / 2;
            context.moveTo(-3 * r, -r);
            context.lineTo(-r, -r);
            context.lineTo(-r, -3 * r);
            context.lineTo(r, -3 * r);
            context.lineTo(r, -r);
            context.lineTo(3 * r, -r);
            context.lineTo(3 * r, r);
            context.lineTo(r, r);
            context.lineTo(r, 3 * r);
            context.lineTo(-r, 3 * r);
            context.lineTo(-r, r);
            context.lineTo(-3 * r, r);
            context.closePath();
          }
        };
        var tan30 = Math.sqrt(1 / 3), tan30_2 = tan30 * 2;
        var diamond = {
          draw: function(context, size) {
            var y2 = Math.sqrt(size / tan30_2), x2 = y2 * tan30;
            context.moveTo(0, -y2);
            context.lineTo(x2, 0);
            context.lineTo(0, y2);
            context.lineTo(-x2, 0);
            context.closePath();
          }
        };
        var ka = 0.8908130915292852, kr = Math.sin(pi / 10) / Math.sin(7 * pi / 10), kx = Math.sin(tau / 10) * kr, ky = -Math.cos(tau / 10) * kr;
        var star = {
          draw: function(context, size) {
            var r = Math.sqrt(size * ka), x2 = kx * r, y2 = ky * r;
            context.moveTo(0, -r);
            context.lineTo(x2, y2);
            for (var i = 1; i < 5; ++i) {
              var a2 = tau * i / 5, c2 = Math.cos(a2), s2 = Math.sin(a2);
              context.lineTo(s2 * r, -c2 * r);
              context.lineTo(c2 * x2 - s2 * y2, s2 * x2 + c2 * y2);
            }
            context.closePath();
          }
        };
        var square = {
          draw: function(context, size) {
            var w = Math.sqrt(size), x2 = -w / 2;
            context.rect(x2, x2, w, w);
          }
        };
        var sqrt3 = Math.sqrt(3);
        var triangle = {
          draw: function(context, size) {
            var y2 = -Math.sqrt(size / (sqrt3 * 3));
            context.moveTo(0, y2 * 2);
            context.lineTo(-sqrt3 * y2, -y2);
            context.lineTo(sqrt3 * y2, -y2);
            context.closePath();
          }
        };
        var c = -0.5, s = Math.sqrt(3) / 2, k = 1 / Math.sqrt(12), a = (k / 2 + 1) * 3;
        var wye = {
          draw: function(context, size) {
            var r = Math.sqrt(size / a), x0 = r / 2, y0 = r * k, x1 = x0, y1 = r * k + r, x2 = -x1, y2 = y1;
            context.moveTo(x0, y0);
            context.lineTo(x1, y1);
            context.lineTo(x2, y2);
            context.lineTo(c * x0 - s * y0, s * x0 + c * y0);
            context.lineTo(c * x1 - s * y1, s * x1 + c * y1);
            context.lineTo(c * x2 - s * y2, s * x2 + c * y2);
            context.lineTo(c * x0 + s * y0, c * y0 - s * x0);
            context.lineTo(c * x1 + s * y1, c * y1 - s * x1);
            context.lineTo(c * x2 + s * y2, c * y2 - s * x2);
            context.closePath();
          }
        };
        var symbols = [
          circle,
          cross,
          diamond,
          square,
          star,
          triangle,
          wye
        ];
        function symbol() {
          var type = constant(circle), size = constant(64), context = null;
          function symbol2() {
            var buffer;
            if (!context) context = buffer = d3Path.path();
            type.apply(this, arguments).draw(context, +size.apply(this, arguments));
            if (buffer) return context = null, buffer + "" || null;
          }
          symbol2.type = function(_) {
            return arguments.length ? (type = typeof _ === "function" ? _ : constant(_), symbol2) : type;
          };
          symbol2.size = function(_) {
            return arguments.length ? (size = typeof _ === "function" ? _ : constant(+_), symbol2) : size;
          };
          symbol2.context = function(_) {
            return arguments.length ? (context = _ == null ? null : _, symbol2) : context;
          };
          return symbol2;
        }
        function noop() {
        }
        function point(that, x2, y2) {
          that._context.bezierCurveTo(
            (2 * that._x0 + that._x1) / 3,
            (2 * that._y0 + that._y1) / 3,
            (that._x0 + 2 * that._x1) / 3,
            (that._y0 + 2 * that._y1) / 3,
            (that._x0 + 4 * that._x1 + x2) / 6,
            (that._y0 + 4 * that._y1 + y2) / 6
          );
        }
        function Basis(context) {
          this._context = context;
        }
        Basis.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x0 = this._x1 = this._y0 = this._y1 = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            switch (this._point) {
              case 3:
                point(this, this._x1, this._y1);
              // proceed
              case 2:
                this._context.lineTo(this._x1, this._y1);
                break;
            }
            if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
                break;
              case 1:
                this._point = 2;
                break;
              case 2:
                this._point = 3;
                this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6);
              // proceed
              default:
                point(this, x2, y2);
                break;
            }
            this._x0 = this._x1, this._x1 = x2;
            this._y0 = this._y1, this._y1 = y2;
          }
        };
        function basis2(context) {
          return new Basis(context);
        }
        function BasisClosed(context) {
          this._context = context;
        }
        BasisClosed.prototype = {
          areaStart: noop,
          areaEnd: noop,
          lineStart: function() {
            this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            switch (this._point) {
              case 1: {
                this._context.moveTo(this._x2, this._y2);
                this._context.closePath();
                break;
              }
              case 2: {
                this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);
                this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);
                this._context.closePath();
                break;
              }
              case 3: {
                this.point(this._x2, this._y2);
                this.point(this._x3, this._y3);
                this.point(this._x4, this._y4);
                break;
              }
            }
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                this._x2 = x2, this._y2 = y2;
                break;
              case 1:
                this._point = 2;
                this._x3 = x2, this._y3 = y2;
                break;
              case 2:
                this._point = 3;
                this._x4 = x2, this._y4 = y2;
                this._context.moveTo((this._x0 + 4 * this._x1 + x2) / 6, (this._y0 + 4 * this._y1 + y2) / 6);
                break;
              default:
                point(this, x2, y2);
                break;
            }
            this._x0 = this._x1, this._x1 = x2;
            this._y0 = this._y1, this._y1 = y2;
          }
        };
        function basisClosed(context) {
          return new BasisClosed(context);
        }
        function BasisOpen(context) {
          this._context = context;
        }
        BasisOpen.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x0 = this._x1 = this._y0 = this._y1 = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                break;
              case 1:
                this._point = 2;
                break;
              case 2:
                this._point = 3;
                var x0 = (this._x0 + 4 * this._x1 + x2) / 6, y0 = (this._y0 + 4 * this._y1 + y2) / 6;
                this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0);
                break;
              case 3:
                this._point = 4;
              // proceed
              default:
                point(this, x2, y2);
                break;
            }
            this._x0 = this._x1, this._x1 = x2;
            this._y0 = this._y1, this._y1 = y2;
          }
        };
        function basisOpen(context) {
          return new BasisOpen(context);
        }
        function Bundle(context, beta) {
          this._basis = new Basis(context);
          this._beta = beta;
        }
        Bundle.prototype = {
          lineStart: function() {
            this._x = [];
            this._y = [];
            this._basis.lineStart();
          },
          lineEnd: function() {
            var x2 = this._x, y2 = this._y, j = x2.length - 1;
            if (j > 0) {
              var x0 = x2[0], y0 = y2[0], dx = x2[j] - x0, dy = y2[j] - y0, i = -1, t;
              while (++i <= j) {
                t = i / j;
                this._basis.point(
                  this._beta * x2[i] + (1 - this._beta) * (x0 + t * dx),
                  this._beta * y2[i] + (1 - this._beta) * (y0 + t * dy)
                );
              }
            }
            this._x = this._y = null;
            this._basis.lineEnd();
          },
          point: function(x2, y2) {
            this._x.push(+x2);
            this._y.push(+y2);
          }
        };
        var bundle = function custom(beta) {
          function bundle2(context) {
            return beta === 1 ? new Basis(context) : new Bundle(context, beta);
          }
          bundle2.beta = function(beta2) {
            return custom(+beta2);
          };
          return bundle2;
        }(0.85);
        function point$1(that, x2, y2) {
          that._context.bezierCurveTo(
            that._x1 + that._k * (that._x2 - that._x0),
            that._y1 + that._k * (that._y2 - that._y0),
            that._x2 + that._k * (that._x1 - x2),
            that._y2 + that._k * (that._y1 - y2),
            that._x2,
            that._y2
          );
        }
        function Cardinal(context, tension) {
          this._context = context;
          this._k = (1 - tension) / 6;
        }
        Cardinal.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            switch (this._point) {
              case 2:
                this._context.lineTo(this._x2, this._y2);
                break;
              case 3:
                point$1(this, this._x1, this._y1);
                break;
            }
            if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
                break;
              case 1:
                this._point = 2;
                this._x1 = x2, this._y1 = y2;
                break;
              case 2:
                this._point = 3;
              // proceed
              default:
                point$1(this, x2, y2);
                break;
            }
            this._x0 = this._x1, this._x1 = this._x2, this._x2 = x2;
            this._y0 = this._y1, this._y1 = this._y2, this._y2 = y2;
          }
        };
        var cardinal = function custom(tension) {
          function cardinal2(context) {
            return new Cardinal(context, tension);
          }
          cardinal2.tension = function(tension2) {
            return custom(+tension2);
          };
          return cardinal2;
        }(0);
        function CardinalClosed(context, tension) {
          this._context = context;
          this._k = (1 - tension) / 6;
        }
        CardinalClosed.prototype = {
          areaStart: noop,
          areaEnd: noop,
          lineStart: function() {
            this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            switch (this._point) {
              case 1: {
                this._context.moveTo(this._x3, this._y3);
                this._context.closePath();
                break;
              }
              case 2: {
                this._context.lineTo(this._x3, this._y3);
                this._context.closePath();
                break;
              }
              case 3: {
                this.point(this._x3, this._y3);
                this.point(this._x4, this._y4);
                this.point(this._x5, this._y5);
                break;
              }
            }
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                this._x3 = x2, this._y3 = y2;
                break;
              case 1:
                this._point = 2;
                this._context.moveTo(this._x4 = x2, this._y4 = y2);
                break;
              case 2:
                this._point = 3;
                this._x5 = x2, this._y5 = y2;
                break;
              default:
                point$1(this, x2, y2);
                break;
            }
            this._x0 = this._x1, this._x1 = this._x2, this._x2 = x2;
            this._y0 = this._y1, this._y1 = this._y2, this._y2 = y2;
          }
        };
        var cardinalClosed = function custom(tension) {
          function cardinal2(context) {
            return new CardinalClosed(context, tension);
          }
          cardinal2.tension = function(tension2) {
            return custom(+tension2);
          };
          return cardinal2;
        }(0);
        function CardinalOpen(context, tension) {
          this._context = context;
          this._k = (1 - tension) / 6;
        }
        CardinalOpen.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                break;
              case 1:
                this._point = 2;
                break;
              case 2:
                this._point = 3;
                this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2);
                break;
              case 3:
                this._point = 4;
              // proceed
              default:
                point$1(this, x2, y2);
                break;
            }
            this._x0 = this._x1, this._x1 = this._x2, this._x2 = x2;
            this._y0 = this._y1, this._y1 = this._y2, this._y2 = y2;
          }
        };
        var cardinalOpen = function custom(tension) {
          function cardinal2(context) {
            return new CardinalOpen(context, tension);
          }
          cardinal2.tension = function(tension2) {
            return custom(+tension2);
          };
          return cardinal2;
        }(0);
        function point$2(that, x2, y2) {
          var x1 = that._x1, y1 = that._y1, x22 = that._x2, y22 = that._y2;
          if (that._l01_a > epsilon) {
            var a2 = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a, n = 3 * that._l01_a * (that._l01_a + that._l12_a);
            x1 = (x1 * a2 - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;
            y1 = (y1 * a2 - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
          }
          if (that._l23_a > epsilon) {
            var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a, m = 3 * that._l23_a * (that._l23_a + that._l12_a);
            x22 = (x22 * b + that._x1 * that._l23_2a - x2 * that._l12_2a) / m;
            y22 = (y22 * b + that._y1 * that._l23_2a - y2 * that._l12_2a) / m;
          }
          that._context.bezierCurveTo(x1, y1, x22, y22, that._x2, that._y2);
        }
        function CatmullRom(context, alpha) {
          this._context = context;
          this._alpha = alpha;
        }
        CatmullRom.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
            this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
          },
          lineEnd: function() {
            switch (this._point) {
              case 2:
                this._context.lineTo(this._x2, this._y2);
                break;
              case 3:
                this.point(this._x2, this._y2);
                break;
            }
            if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            if (this._point) {
              var x23 = this._x2 - x2, y23 = this._y2 - y2;
              this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
            }
            switch (this._point) {
              case 0:
                this._point = 1;
                this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
                break;
              case 1:
                this._point = 2;
                break;
              case 2:
                this._point = 3;
              // proceed
              default:
                point$2(this, x2, y2);
                break;
            }
            this._l01_a = this._l12_a, this._l12_a = this._l23_a;
            this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
            this._x0 = this._x1, this._x1 = this._x2, this._x2 = x2;
            this._y0 = this._y1, this._y1 = this._y2, this._y2 = y2;
          }
        };
        var catmullRom = function custom(alpha) {
          function catmullRom2(context) {
            return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);
          }
          catmullRom2.alpha = function(alpha2) {
            return custom(+alpha2);
          };
          return catmullRom2;
        }(0.5);
        function CatmullRomClosed(context, alpha) {
          this._context = context;
          this._alpha = alpha;
        }
        CatmullRomClosed.prototype = {
          areaStart: noop,
          areaEnd: noop,
          lineStart: function() {
            this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
            this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
          },
          lineEnd: function() {
            switch (this._point) {
              case 1: {
                this._context.moveTo(this._x3, this._y3);
                this._context.closePath();
                break;
              }
              case 2: {
                this._context.lineTo(this._x3, this._y3);
                this._context.closePath();
                break;
              }
              case 3: {
                this.point(this._x3, this._y3);
                this.point(this._x4, this._y4);
                this.point(this._x5, this._y5);
                break;
              }
            }
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            if (this._point) {
              var x23 = this._x2 - x2, y23 = this._y2 - y2;
              this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
            }
            switch (this._point) {
              case 0:
                this._point = 1;
                this._x3 = x2, this._y3 = y2;
                break;
              case 1:
                this._point = 2;
                this._context.moveTo(this._x4 = x2, this._y4 = y2);
                break;
              case 2:
                this._point = 3;
                this._x5 = x2, this._y5 = y2;
                break;
              default:
                point$2(this, x2, y2);
                break;
            }
            this._l01_a = this._l12_a, this._l12_a = this._l23_a;
            this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
            this._x0 = this._x1, this._x1 = this._x2, this._x2 = x2;
            this._y0 = this._y1, this._y1 = this._y2, this._y2 = y2;
          }
        };
        var catmullRomClosed = function custom(alpha) {
          function catmullRom2(context) {
            return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0);
          }
          catmullRom2.alpha = function(alpha2) {
            return custom(+alpha2);
          };
          return catmullRom2;
        }(0.5);
        function CatmullRomOpen(context, alpha) {
          this._context = context;
          this._alpha = alpha;
        }
        CatmullRomOpen.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
            this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
          },
          lineEnd: function() {
            if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            if (this._point) {
              var x23 = this._x2 - x2, y23 = this._y2 - y2;
              this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
            }
            switch (this._point) {
              case 0:
                this._point = 1;
                break;
              case 1:
                this._point = 2;
                break;
              case 2:
                this._point = 3;
                this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2);
                break;
              case 3:
                this._point = 4;
              // proceed
              default:
                point$2(this, x2, y2);
                break;
            }
            this._l01_a = this._l12_a, this._l12_a = this._l23_a;
            this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
            this._x0 = this._x1, this._x1 = this._x2, this._x2 = x2;
            this._y0 = this._y1, this._y1 = this._y2, this._y2 = y2;
          }
        };
        var catmullRomOpen = function custom(alpha) {
          function catmullRom2(context) {
            return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0);
          }
          catmullRom2.alpha = function(alpha2) {
            return custom(+alpha2);
          };
          return catmullRom2;
        }(0.5);
        function LinearClosed(context) {
          this._context = context;
        }
        LinearClosed.prototype = {
          areaStart: noop,
          areaEnd: noop,
          lineStart: function() {
            this._point = 0;
          },
          lineEnd: function() {
            if (this._point) this._context.closePath();
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            if (this._point) this._context.lineTo(x2, y2);
            else this._point = 1, this._context.moveTo(x2, y2);
          }
        };
        function linearClosed(context) {
          return new LinearClosed(context);
        }
        function sign(x2) {
          return x2 < 0 ? -1 : 1;
        }
        function slope3(that, x2, y2) {
          var h0 = that._x1 - that._x0, h1 = x2 - that._x1, s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0), s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0), p = (s0 * h1 + s1 * h0) / (h0 + h1);
          return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
        }
        function slope2(that, t) {
          var h = that._x1 - that._x0;
          return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
        }
        function point$3(that, t02, t12) {
          var x0 = that._x0, y0 = that._y0, x1 = that._x1, y1 = that._y1, dx = (x1 - x0) / 3;
          that._context.bezierCurveTo(x0 + dx, y0 + dx * t02, x1 - dx, y1 - dx * t12, x1, y1);
        }
        function MonotoneX(context) {
          this._context = context;
        }
        MonotoneX.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x0 = this._x1 = this._y0 = this._y1 = this._t0 = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            switch (this._point) {
              case 2:
                this._context.lineTo(this._x1, this._y1);
                break;
              case 3:
                point$3(this, this._t0, slope2(this, this._t0));
                break;
            }
            if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
            this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            var t12 = NaN;
            x2 = +x2, y2 = +y2;
            if (x2 === this._x1 && y2 === this._y1) return;
            switch (this._point) {
              case 0:
                this._point = 1;
                this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
                break;
              case 1:
                this._point = 2;
                break;
              case 2:
                this._point = 3;
                point$3(this, slope2(this, t12 = slope3(this, x2, y2)), t12);
                break;
              default:
                point$3(this, this._t0, t12 = slope3(this, x2, y2));
                break;
            }
            this._x0 = this._x1, this._x1 = x2;
            this._y0 = this._y1, this._y1 = y2;
            this._t0 = t12;
          }
        };
        function MonotoneY(context) {
          this._context = new ReflectContext(context);
        }
        (MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x2, y2) {
          MonotoneX.prototype.point.call(this, y2, x2);
        };
        function ReflectContext(context) {
          this._context = context;
        }
        ReflectContext.prototype = {
          moveTo: function(x2, y2) {
            this._context.moveTo(y2, x2);
          },
          closePath: function() {
            this._context.closePath();
          },
          lineTo: function(x2, y2) {
            this._context.lineTo(y2, x2);
          },
          bezierCurveTo: function(x1, y1, x2, y2, x3, y3) {
            this._context.bezierCurveTo(y1, x1, y2, x2, y3, x3);
          }
        };
        function monotoneX(context) {
          return new MonotoneX(context);
        }
        function monotoneY(context) {
          return new MonotoneY(context);
        }
        function Natural(context) {
          this._context = context;
        }
        Natural.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x = [];
            this._y = [];
          },
          lineEnd: function() {
            var x2 = this._x, y2 = this._y, n = x2.length;
            if (n) {
              this._line ? this._context.lineTo(x2[0], y2[0]) : this._context.moveTo(x2[0], y2[0]);
              if (n === 2) {
                this._context.lineTo(x2[1], y2[1]);
              } else {
                var px = controlPoints(x2), py = controlPoints(y2);
                for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
                  this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x2[i1], y2[i1]);
                }
              }
            }
            if (this._line || this._line !== 0 && n === 1) this._context.closePath();
            this._line = 1 - this._line;
            this._x = this._y = null;
          },
          point: function(x2, y2) {
            this._x.push(+x2);
            this._y.push(+y2);
          }
        };
        function controlPoints(x2) {
          var i, n = x2.length - 1, m, a2 = new Array(n), b = new Array(n), r = new Array(n);
          a2[0] = 0, b[0] = 2, r[0] = x2[0] + 2 * x2[1];
          for (i = 1; i < n - 1; ++i) a2[i] = 1, b[i] = 4, r[i] = 4 * x2[i] + 2 * x2[i + 1];
          a2[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x2[n - 1] + x2[n];
          for (i = 1; i < n; ++i) m = a2[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
          a2[n - 1] = r[n - 1] / b[n - 1];
          for (i = n - 2; i >= 0; --i) a2[i] = (r[i] - a2[i + 1]) / b[i];
          b[n - 1] = (x2[n] + a2[n - 1]) / 2;
          for (i = 0; i < n - 1; ++i) b[i] = 2 * x2[i + 1] - a2[i + 1];
          return [a2, b];
        }
        function natural(context) {
          return new Natural(context);
        }
        function Step(context, t) {
          this._context = context;
          this._t = t;
        }
        Step.prototype = {
          areaStart: function() {
            this._line = 0;
          },
          areaEnd: function() {
            this._line = NaN;
          },
          lineStart: function() {
            this._x = this._y = NaN;
            this._point = 0;
          },
          lineEnd: function() {
            if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
            if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
            if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
          },
          point: function(x2, y2) {
            x2 = +x2, y2 = +y2;
            switch (this._point) {
              case 0:
                this._point = 1;
                this._line ? this._context.lineTo(x2, y2) : this._context.moveTo(x2, y2);
                break;
              case 1:
                this._point = 2;
              // proceed
              default: {
                if (this._t <= 0) {
                  this._context.lineTo(this._x, y2);
                  this._context.lineTo(x2, y2);
                } else {
                  var x1 = this._x * (1 - this._t) + x2 * this._t;
                  this._context.lineTo(x1, this._y);
                  this._context.lineTo(x1, y2);
                }
                break;
              }
            }
            this._x = x2, this._y = y2;
          }
        };
        function step(context) {
          return new Step(context, 0.5);
        }
        function stepBefore(context) {
          return new Step(context, 0);
        }
        function stepAfter(context) {
          return new Step(context, 1);
        }
        function none(series, order) {
          if (!((n = series.length) > 1)) return;
          for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {
            s0 = s1, s1 = series[order[i]];
            for (j = 0; j < m; ++j) {
              s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
            }
          }
        }
        function none$1(series) {
          var n = series.length, o = new Array(n);
          while (--n >= 0) o[n] = n;
          return o;
        }
        function stackValue(d, key) {
          return d[key];
        }
        function stack() {
          var keys = constant([]), order = none$1, offset = none, value = stackValue;
          function stack2(data) {
            var kz = keys.apply(this, arguments), i, m = data.length, n = kz.length, sz = new Array(n), oz;
            for (i = 0; i < n; ++i) {
              for (var ki = kz[i], si = sz[i] = new Array(m), j = 0, sij; j < m; ++j) {
                si[j] = sij = [0, +value(data[j], ki, j, data)];
                sij.data = data[j];
              }
              si.key = ki;
            }
            for (i = 0, oz = order(sz); i < n; ++i) {
              sz[oz[i]].index = i;
            }
            offset(sz, oz);
            return sz;
          }
          stack2.keys = function(_) {
            return arguments.length ? (keys = typeof _ === "function" ? _ : constant(slice.call(_)), stack2) : keys;
          };
          stack2.value = function(_) {
            return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), stack2) : value;
          };
          stack2.order = function(_) {
            return arguments.length ? (order = _ == null ? none$1 : typeof _ === "function" ? _ : constant(slice.call(_)), stack2) : order;
          };
          stack2.offset = function(_) {
            return arguments.length ? (offset = _ == null ? none : _, stack2) : offset;
          };
          return stack2;
        }
        function expand(series, order) {
          if (!((n = series.length) > 0)) return;
          for (var i, n, j = 0, m = series[0].length, y2; j < m; ++j) {
            for (y2 = i = 0; i < n; ++i) y2 += series[i][j][1] || 0;
            if (y2) for (i = 0; i < n; ++i) series[i][j][1] /= y2;
          }
          none(series, order);
        }
        function diverging(series, order) {
          if (!((n = series.length) > 0)) return;
          for (var i, j = 0, d, dy, yp, yn, n, m = series[order[0]].length; j < m; ++j) {
            for (yp = yn = 0, i = 0; i < n; ++i) {
              if ((dy = (d = series[order[i]][j])[1] - d[0]) > 0) {
                d[0] = yp, d[1] = yp += dy;
              } else if (dy < 0) {
                d[1] = yn, d[0] = yn += dy;
              } else {
                d[0] = 0, d[1] = dy;
              }
            }
          }
        }
        function silhouette(series, order) {
          if (!((n = series.length) > 0)) return;
          for (var j = 0, s0 = series[order[0]], n, m = s0.length; j < m; ++j) {
            for (var i = 0, y2 = 0; i < n; ++i) y2 += series[i][j][1] || 0;
            s0[j][1] += s0[j][0] = -y2 / 2;
          }
          none(series, order);
        }
        function wiggle(series, order) {
          if (!((n = series.length) > 0) || !((m = (s0 = series[order[0]]).length) > 0)) return;
          for (var y2 = 0, j = 1, s0, m, n; j < m; ++j) {
            for (var i = 0, s1 = 0, s2 = 0; i < n; ++i) {
              var si = series[order[i]], sij0 = si[j][1] || 0, sij1 = si[j - 1][1] || 0, s3 = (sij0 - sij1) / 2;
              for (var k2 = 0; k2 < i; ++k2) {
                var sk = series[order[k2]], skj0 = sk[j][1] || 0, skj1 = sk[j - 1][1] || 0;
                s3 += skj0 - skj1;
              }
              s1 += sij0, s2 += s3 * sij0;
            }
            s0[j - 1][1] += s0[j - 1][0] = y2;
            if (s1) y2 -= s2 / s1;
          }
          s0[j - 1][1] += s0[j - 1][0] = y2;
          none(series, order);
        }
        function appearance(series) {
          var peaks = series.map(peak);
          return none$1(series).sort(function(a2, b) {
            return peaks[a2] - peaks[b];
          });
        }
        function peak(series) {
          var i = -1, j = 0, n = series.length, vi, vj = -Infinity;
          while (++i < n) if ((vi = +series[i][1]) > vj) vj = vi, j = i;
          return j;
        }
        function ascending(series) {
          var sums = series.map(sum);
          return none$1(series).sort(function(a2, b) {
            return sums[a2] - sums[b];
          });
        }
        function sum(series) {
          var s2 = 0, i = -1, n = series.length, v;
          while (++i < n) if (v = +series[i][1]) s2 += v;
          return s2;
        }
        function descending$1(series) {
          return ascending(series).reverse();
        }
        function insideOut(series) {
          var n = series.length, i, j, sums = series.map(sum), order = appearance(series), top = 0, bottom = 0, tops = [], bottoms = [];
          for (i = 0; i < n; ++i) {
            j = order[i];
            if (top < bottom) {
              top += sums[j];
              tops.push(j);
            } else {
              bottom += sums[j];
              bottoms.push(j);
            }
          }
          return bottoms.reverse().concat(tops);
        }
        function reverse(series) {
          return none$1(series).reverse();
        }
        exports2.arc = arc;
        exports2.area = area;
        exports2.areaRadial = areaRadial;
        exports2.curveBasis = basis2;
        exports2.curveBasisClosed = basisClosed;
        exports2.curveBasisOpen = basisOpen;
        exports2.curveBundle = bundle;
        exports2.curveCardinal = cardinal;
        exports2.curveCardinalClosed = cardinalClosed;
        exports2.curveCardinalOpen = cardinalOpen;
        exports2.curveCatmullRom = catmullRom;
        exports2.curveCatmullRomClosed = catmullRomClosed;
        exports2.curveCatmullRomOpen = catmullRomOpen;
        exports2.curveLinear = curveLinear;
        exports2.curveLinearClosed = linearClosed;
        exports2.curveMonotoneX = monotoneX;
        exports2.curveMonotoneY = monotoneY;
        exports2.curveNatural = natural;
        exports2.curveStep = step;
        exports2.curveStepAfter = stepAfter;
        exports2.curveStepBefore = stepBefore;
        exports2.line = line;
        exports2.lineRadial = lineRadial$1;
        exports2.linkHorizontal = linkHorizontal;
        exports2.linkRadial = linkRadial;
        exports2.linkVertical = linkVertical;
        exports2.pie = pie;
        exports2.pointRadial = pointRadial;
        exports2.radialArea = areaRadial;
        exports2.radialLine = lineRadial$1;
        exports2.stack = stack;
        exports2.stackOffsetDiverging = diverging;
        exports2.stackOffsetExpand = expand;
        exports2.stackOffsetNone = none;
        exports2.stackOffsetSilhouette = silhouette;
        exports2.stackOffsetWiggle = wiggle;
        exports2.stackOrderAppearance = appearance;
        exports2.stackOrderAscending = ascending;
        exports2.stackOrderDescending = descending$1;
        exports2.stackOrderInsideOut = insideOut;
        exports2.stackOrderNone = none$1;
        exports2.stackOrderReverse = reverse;
        exports2.symbol = symbol;
        exports2.symbolCircle = circle;
        exports2.symbolCross = cross;
        exports2.symbolDiamond = diamond;
        exports2.symbolSquare = square;
        exports2.symbolStar = star;
        exports2.symbolTriangle = triangle;
        exports2.symbolWye = wye;
        exports2.symbols = symbols;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/@plotly/d3-sankey/build/d3-sankey.js
  var require_d3_sankey = __commonJS({
    "node_modules/@plotly/d3-sankey/build/d3-sankey.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require_d3_array(), require_d3_collection(), require_d3_shape()) : typeof define === "function" && false ? define(["exports", "d3-array", "d3-collection", "d3-shape"], factory) : factory(global2.d3 = global2.d3 || {}, global2.d3, global2.d3, global2.d3);
      })(exports, function(exports2, d3Array, d3Collection, d3Shape) {
        "use strict";
        function targetDepth(d) {
          return d.target.depth;
        }
        function left(node) {
          return node.depth;
        }
        function right(node, n) {
          return n - 1 - node.height;
        }
        function justify(node, n) {
          return node.sourceLinks.length ? node.depth : n - 1;
        }
        function center(node) {
          return node.targetLinks.length ? node.depth : node.sourceLinks.length ? d3Array.min(node.sourceLinks, targetDepth) - 1 : 0;
        }
        function constant(x) {
          return function() {
            return x;
          };
        }
        function ascendingSourceBreadth(a, b) {
          return ascendingBreadth(a.source, b.source) || a.index - b.index;
        }
        function ascendingTargetBreadth(a, b) {
          return ascendingBreadth(a.target, b.target) || a.index - b.index;
        }
        function ascendingBreadth(a, b) {
          return a.y0 - b.y0;
        }
        function value(d) {
          return d.value;
        }
        function nodeCenter(node) {
          return (node.y0 + node.y1) / 2;
        }
        function weightedSource(link) {
          return nodeCenter(link.source) * link.value;
        }
        function weightedTarget(link) {
          return nodeCenter(link.target) * link.value;
        }
        function defaultId(d) {
          return d.index;
        }
        function defaultNodes(graph) {
          return graph.nodes;
        }
        function defaultLinks(graph) {
          return graph.links;
        }
        function find(nodeById, id) {
          var node = nodeById.get(id);
          if (!node) throw new Error("missing: " + id);
          return node;
        }
        var sankey = function() {
          var x0 = 0, y0 = 0, x1 = 1, y1 = 1, dx = 24, py = 8, id = defaultId, align = justify, nodes = defaultNodes, links = defaultLinks, iterations = 32, maxPaddedSpace = 2 / 3;
          function sankey2() {
            var graph = { nodes: nodes.apply(null, arguments), links: links.apply(null, arguments) };
            computeNodeLinks(graph);
            computeNodeValues(graph);
            computeNodeDepths(graph);
            computeNodeBreadths(graph, iterations);
            computeLinkBreadths(graph);
            return graph;
          }
          sankey2.update = function(graph) {
            computeLinkBreadths(graph);
            return graph;
          };
          sankey2.nodeId = function(_) {
            return arguments.length ? (id = typeof _ === "function" ? _ : constant(_), sankey2) : id;
          };
          sankey2.nodeAlign = function(_) {
            return arguments.length ? (align = typeof _ === "function" ? _ : constant(_), sankey2) : align;
          };
          sankey2.nodeWidth = function(_) {
            return arguments.length ? (dx = +_, sankey2) : dx;
          };
          sankey2.nodePadding = function(_) {
            return arguments.length ? (py = +_, sankey2) : py;
          };
          sankey2.nodes = function(_) {
            return arguments.length ? (nodes = typeof _ === "function" ? _ : constant(_), sankey2) : nodes;
          };
          sankey2.links = function(_) {
            return arguments.length ? (links = typeof _ === "function" ? _ : constant(_), sankey2) : links;
          };
          sankey2.size = function(_) {
            return arguments.length ? (x0 = y0 = 0, x1 = +_[0], y1 = +_[1], sankey2) : [x1 - x0, y1 - y0];
          };
          sankey2.extent = function(_) {
            return arguments.length ? (x0 = +_[0][0], x1 = +_[1][0], y0 = +_[0][1], y1 = +_[1][1], sankey2) : [[x0, y0], [x1, y1]];
          };
          sankey2.iterations = function(_) {
            return arguments.length ? (iterations = +_, sankey2) : iterations;
          };
          function computeNodeLinks(graph) {
            graph.nodes.forEach(function(node, i) {
              node.index = i;
              node.sourceLinks = [];
              node.targetLinks = [];
            });
            var nodeById = d3Collection.map(graph.nodes, id);
            graph.links.forEach(function(link, i) {
              link.index = i;
              var source = link.source, target = link.target;
              if (typeof source !== "object") source = link.source = find(nodeById, source);
              if (typeof target !== "object") target = link.target = find(nodeById, target);
              source.sourceLinks.push(link);
              target.targetLinks.push(link);
            });
          }
          function computeNodeValues(graph) {
            graph.nodes.forEach(function(node) {
              node.value = Math.max(
                d3Array.sum(node.sourceLinks, value),
                d3Array.sum(node.targetLinks, value)
              );
            });
          }
          function computeNodeDepths(graph) {
            var nodes2, next, x;
            for (nodes2 = graph.nodes, next = [], x = 0; nodes2.length; ++x, nodes2 = next, next = []) {
              nodes2.forEach(function(node) {
                node.depth = x;
                node.sourceLinks.forEach(function(link) {
                  if (next.indexOf(link.target) < 0) {
                    next.push(link.target);
                  }
                });
              });
            }
            for (nodes2 = graph.nodes, next = [], x = 0; nodes2.length; ++x, nodes2 = next, next = []) {
              nodes2.forEach(function(node) {
                node.height = x;
                node.targetLinks.forEach(function(link) {
                  if (next.indexOf(link.source) < 0) {
                    next.push(link.source);
                  }
                });
              });
            }
            var kx = (x1 - x0 - dx) / (x - 1);
            graph.nodes.forEach(function(node) {
              node.x1 = (node.x0 = x0 + Math.max(0, Math.min(x - 1, Math.floor(align.call(null, node, x)))) * kx) + dx;
            });
          }
          function computeNodeBreadths(graph) {
            var columns = d3Collection.nest().key(function(d) {
              return d.x0;
            }).sortKeys(d3Array.ascending).entries(graph.nodes).map(function(d) {
              return d.values;
            });
            initializeNodeBreadth();
            resolveCollisions();
            for (var alpha = 1, n = iterations; n > 0; --n) {
              relaxRightToLeft(alpha *= 0.99);
              resolveCollisions();
              relaxLeftToRight(alpha);
              resolveCollisions();
            }
            function initializeNodeBreadth() {
              var L = d3Array.max(columns, function(nodes2) {
                return nodes2.length;
              });
              var maxNodePadding = maxPaddedSpace * (y1 - y0) / (L - 1);
              if (py > maxNodePadding) py = maxNodePadding;
              var ky = d3Array.min(columns, function(nodes2) {
                return (y1 - y0 - (nodes2.length - 1) * py) / d3Array.sum(nodes2, value);
              });
              columns.forEach(function(nodes2) {
                nodes2.forEach(function(node, i) {
                  node.y1 = (node.y0 = i) + node.value * ky;
                });
              });
              graph.links.forEach(function(link) {
                link.width = link.value * ky;
              });
            }
            function relaxLeftToRight(alpha2) {
              columns.forEach(function(nodes2) {
                nodes2.forEach(function(node) {
                  if (node.targetLinks.length) {
                    var dy = (d3Array.sum(node.targetLinks, weightedSource) / d3Array.sum(node.targetLinks, value) - nodeCenter(node)) * alpha2;
                    node.y0 += dy, node.y1 += dy;
                  }
                });
              });
            }
            function relaxRightToLeft(alpha2) {
              columns.slice().reverse().forEach(function(nodes2) {
                nodes2.forEach(function(node) {
                  if (node.sourceLinks.length) {
                    var dy = (d3Array.sum(node.sourceLinks, weightedTarget) / d3Array.sum(node.sourceLinks, value) - nodeCenter(node)) * alpha2;
                    node.y0 += dy, node.y1 += dy;
                  }
                });
              });
            }
            function resolveCollisions() {
              columns.forEach(function(nodes2) {
                var node, dy, y = y0, n2 = nodes2.length, i;
                nodes2.sort(ascendingBreadth);
                for (i = 0; i < n2; ++i) {
                  node = nodes2[i];
                  dy = y - node.y0;
                  if (dy > 0) node.y0 += dy, node.y1 += dy;
                  y = node.y1 + py;
                }
                dy = y - py - y1;
                if (dy > 0) {
                  y = node.y0 -= dy, node.y1 -= dy;
                  for (i = n2 - 2; i >= 0; --i) {
                    node = nodes2[i];
                    dy = node.y1 + py - y;
                    if (dy > 0) node.y0 -= dy, node.y1 -= dy;
                    y = node.y0;
                  }
                }
              });
            }
          }
          function computeLinkBreadths(graph) {
            graph.nodes.forEach(function(node) {
              node.sourceLinks.sort(ascendingTargetBreadth);
              node.targetLinks.sort(ascendingSourceBreadth);
            });
            graph.nodes.forEach(function(node) {
              var y02 = node.y0, y12 = y02;
              node.sourceLinks.forEach(function(link) {
                link.y0 = y02 + link.width / 2, y02 += link.width;
              });
              node.targetLinks.forEach(function(link) {
                link.y1 = y12 + link.width / 2, y12 += link.width;
              });
            });
          }
          return sankey2;
        };
        function horizontalSource(d) {
          return [d.source.x1, d.y0];
        }
        function horizontalTarget(d) {
          return [d.target.x0, d.y1];
        }
        var sankeyLinkHorizontal = function() {
          return d3Shape.linkHorizontal().source(horizontalSource).target(horizontalTarget);
        };
        exports2.sankey = sankey;
        exports2.sankeyCenter = center;
        exports2.sankeyLeft = left;
        exports2.sankeyRight = right;
        exports2.sankeyJustify = justify;
        exports2.sankeyLinkHorizontal = sankeyLinkHorizontal;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // node_modules/elementary-circuits-directed-graph/johnson.js
  var require_johnson = __commonJS({
    "node_modules/elementary-circuits-directed-graph/johnson.js"(exports, module) {
      var tarjan = require_scc();
      module.exports = function findCircuits(edges, cb) {
        var circuits = [];
        var stack = [];
        var blocked = [];
        var B2 = {};
        var Ak = [];
        var s;
        function unblock(u) {
          blocked[u] = false;
          if (B2.hasOwnProperty(u)) {
            Object.keys(B2[u]).forEach(function(w) {
              delete B2[u][w];
              if (blocked[w]) {
                unblock(w);
              }
            });
          }
        }
        function circuit(v) {
          var found = false;
          stack.push(v);
          blocked[v] = true;
          var i2;
          var w;
          for (i2 = 0; i2 < Ak[v].length; i2++) {
            w = Ak[v][i2];
            if (w === s) {
              output(s, stack);
              found = true;
            } else if (!blocked[w]) {
              found = circuit(w);
            }
          }
          if (found) {
            unblock(v);
          } else {
            for (i2 = 0; i2 < Ak[v].length; i2++) {
              w = Ak[v][i2];
              var entry = B2[w];
              if (!entry) {
                entry = {};
                B2[w] = entry;
              }
              entry[w] = true;
            }
          }
          stack.pop();
          return found;
        }
        function output(start, stack2) {
          var cycle = [].concat(stack2).concat(start);
          if (cb) {
            cb(circuit);
          } else {
            circuits.push(cycle);
          }
        }
        function subgraph(minId) {
          for (var i2 = 0; i2 < edges.length; i2++) {
            if (i2 < minId) edges[i2] = [];
            edges[i2] = edges[i2].filter(function(i3) {
              return i3 >= minId;
            });
          }
        }
        function adjacencyStructureSCC(from) {
          subgraph(from);
          var g = edges;
          var sccs = tarjan(g);
          var ccs = sccs.components.filter(function(scc) {
            return scc.length > 1;
          });
          var leastVertex = Infinity;
          var leastVertexComponent;
          for (var i2 = 0; i2 < ccs.length; i2++) {
            for (var j2 = 0; j2 < ccs[i2].length; j2++) {
              if (ccs[i2][j2] < leastVertex) {
                leastVertex = ccs[i2][j2];
                leastVertexComponent = i2;
              }
            }
          }
          var cc = ccs[leastVertexComponent];
          if (!cc) return false;
          var adjList = edges.map(function(l, index) {
            if (cc.indexOf(index) === -1) return [];
            return l.filter(function(i3) {
              return cc.indexOf(i3) !== -1;
            });
          });
          return {
            leastVertex,
            adjList
          };
        }
        s = 0;
        var n = edges.length;
        while (s < n) {
          var p = adjacencyStructureSCC(s);
          s = p.leastVertex;
          Ak = p.adjList;
          if (Ak) {
            for (var i = 0; i < Ak.length; i++) {
              for (var j = 0; j < Ak[i].length; j++) {
                var vertexId = Ak[i][j];
                blocked[+vertexId] = false;
                B2[vertexId] = {};
              }
            }
            circuit(s);
            s = s + 1;
          } else {
            s = n;
          }
        }
        if (cb) {
          return;
        } else {
          return circuits;
        }
      };
    }
  });

  // node_modules/@plotly/d3-sankey-circular/dist/d3-sankey-circular.js
  var require_d3_sankey_circular = __commonJS({
    "node_modules/@plotly/d3-sankey-circular/dist/d3-sankey-circular.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require_d3_array(), require_d3_collection(), require_d3_shape(), require_johnson()) : typeof define === "function" && false ? define(["exports", "d3-array", "d3-collection", "d3-shape", "elementary-circuits-directed-graph"], factory) : factory(global2.d3 = global2.d3 || {}, global2.d3, global2.d3, global2.d3, null);
      })(exports, function(exports2, d3Array, d3Collection, d3Shape, findCircuits) {
        "use strict";
        findCircuits = findCircuits && findCircuits.hasOwnProperty("default") ? findCircuits["default"] : findCircuits;
        function targetDepth(d) {
          return d.target.depth;
        }
        function left(node) {
          return node.depth;
        }
        function right(node, n) {
          return n - 1 - node.height;
        }
        function justify(node, n) {
          return node.sourceLinks.length ? node.depth : n - 1;
        }
        function center(node) {
          return node.targetLinks.length ? node.depth : node.sourceLinks.length ? d3Array.min(node.sourceLinks, targetDepth) - 1 : 0;
        }
        function constant(x) {
          return function() {
            return x;
          };
        }
        var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
          return typeof obj;
        } : function(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
        function ascendingSourceBreadth(a, b) {
          return ascendingBreadth(a.source, b.source) || a.index - b.index;
        }
        function ascendingTargetBreadth(a, b) {
          return ascendingBreadth(a.target, b.target) || a.index - b.index;
        }
        function ascendingBreadth(a, b) {
          if (a.partOfCycle === b.partOfCycle) {
            return a.y0 - b.y0;
          } else {
            if (a.circularLinkType === "top" || b.circularLinkType === "bottom") {
              return -1;
            } else {
              return 1;
            }
          }
        }
        function value(d) {
          return d.value;
        }
        function nodeCenter(node) {
          return (node.y0 + node.y1) / 2;
        }
        function linkSourceCenter(link) {
          return nodeCenter(link.source);
        }
        function linkTargetCenter(link) {
          return nodeCenter(link.target);
        }
        function defaultId(d) {
          return d.index;
        }
        function defaultNodes(graph) {
          return graph.nodes;
        }
        function defaultLinks(graph) {
          return graph.links;
        }
        function find(nodeById, id) {
          var node = nodeById.get(id);
          if (!node) throw new Error("missing: " + id);
          return node;
        }
        function getNodeID(node, id) {
          return id(node);
        }
        var verticalMargin = 25;
        var baseRadius = 10;
        var scale = 0.3;
        function sankeyCircular() {
          var x0 = 0, y0 = 0, x1 = 1, y1 = 1, dx = 24, py, id = defaultId, align = justify, nodes = defaultNodes, links = defaultLinks, iterations = 32, circularLinkGap = 2, paddingRatio, sortNodes = null;
          function sankeyCircular2() {
            var graph = {
              nodes: nodes.apply(null, arguments),
              links: links.apply(null, arguments)
              // Process the graph's nodes and links, setting their positions
              // 1.  Associate the nodes with their respective links, and vice versa
            };
            computeNodeLinks(graph);
            identifyCircles(graph, id, sortNodes);
            computeNodeValues(graph);
            computeNodeDepths(graph);
            selectCircularLinkTypes(graph, id);
            computeNodeBreadths(graph, iterations, id);
            computeLinkBreadths(graph);
            var linkSortingIterations = 4;
            for (var iteration = 0; iteration < linkSortingIterations; iteration++) {
              sortSourceLinks(graph, y1, id);
              sortTargetLinks(graph, y1, id);
              resolveNodeLinkOverlaps(graph, y0, y1, id);
              sortSourceLinks(graph, y1, id);
              sortTargetLinks(graph, y1, id);
            }
            fillHeight(graph, y0, y1);
            addCircularPathData(graph, circularLinkGap, y1, id);
            return graph;
          }
          sankeyCircular2.nodeId = function(_) {
            return arguments.length ? (id = typeof _ === "function" ? _ : constant(_), sankeyCircular2) : id;
          };
          sankeyCircular2.nodeAlign = function(_) {
            return arguments.length ? (align = typeof _ === "function" ? _ : constant(_), sankeyCircular2) : align;
          };
          sankeyCircular2.nodeWidth = function(_) {
            return arguments.length ? (dx = +_, sankeyCircular2) : dx;
          };
          sankeyCircular2.nodePadding = function(_) {
            return arguments.length ? (py = +_, sankeyCircular2) : py;
          };
          sankeyCircular2.nodes = function(_) {
            return arguments.length ? (nodes = typeof _ === "function" ? _ : constant(_), sankeyCircular2) : nodes;
          };
          sankeyCircular2.links = function(_) {
            return arguments.length ? (links = typeof _ === "function" ? _ : constant(_), sankeyCircular2) : links;
          };
          sankeyCircular2.size = function(_) {
            return arguments.length ? (x0 = y0 = 0, x1 = +_[0], y1 = +_[1], sankeyCircular2) : [x1 - x0, y1 - y0];
          };
          sankeyCircular2.extent = function(_) {
            return arguments.length ? (x0 = +_[0][0], x1 = +_[1][0], y0 = +_[0][1], y1 = +_[1][1], sankeyCircular2) : [[x0, y0], [x1, y1]];
          };
          sankeyCircular2.iterations = function(_) {
            return arguments.length ? (iterations = +_, sankeyCircular2) : iterations;
          };
          sankeyCircular2.circularLinkGap = function(_) {
            return arguments.length ? (circularLinkGap = +_, sankeyCircular2) : circularLinkGap;
          };
          sankeyCircular2.nodePaddingRatio = function(_) {
            return arguments.length ? (paddingRatio = +_, sankeyCircular2) : paddingRatio;
          };
          sankeyCircular2.sortNodes = function(_) {
            return arguments.length ? (sortNodes = _, sankeyCircular2) : sortNodes;
          };
          sankeyCircular2.update = function(graph) {
            selectCircularLinkTypes(graph, id);
            computeLinkBreadths(graph);
            graph.links.forEach(function(link) {
              if (link.circular) {
                link.circularLinkType = link.y0 + link.y1 < y1 ? "top" : "bottom";
                link.source.circularLinkType = link.circularLinkType;
                link.target.circularLinkType = link.circularLinkType;
              }
            });
            sortSourceLinks(graph, y1, id, false);
            sortTargetLinks(graph, y1, id);
            addCircularPathData(graph, circularLinkGap, y1, id);
            return graph;
          };
          function computeNodeLinks(graph) {
            graph.nodes.forEach(function(node, i) {
              node.index = i;
              node.sourceLinks = [];
              node.targetLinks = [];
            });
            var nodeById = d3Collection.map(graph.nodes, id);
            graph.links.forEach(function(link, i) {
              link.index = i;
              var source = link.source;
              var target = link.target;
              if ((typeof source === "undefined" ? "undefined" : _typeof(source)) !== "object") {
                source = link.source = find(nodeById, source);
              }
              if ((typeof target === "undefined" ? "undefined" : _typeof(target)) !== "object") {
                target = link.target = find(nodeById, target);
              }
              source.sourceLinks.push(link);
              target.targetLinks.push(link);
            });
            return graph;
          }
          function computeNodeValues(graph) {
            graph.nodes.forEach(function(node) {
              node.partOfCycle = false;
              node.value = Math.max(d3Array.sum(node.sourceLinks, value), d3Array.sum(node.targetLinks, value));
              node.sourceLinks.forEach(function(link) {
                if (link.circular) {
                  node.partOfCycle = true;
                  node.circularLinkType = link.circularLinkType;
                }
              });
              node.targetLinks.forEach(function(link) {
                if (link.circular) {
                  node.partOfCycle = true;
                  node.circularLinkType = link.circularLinkType;
                }
              });
            });
          }
          function getCircleMargins(graph) {
            var totalTopLinksWidth = 0, totalBottomLinksWidth = 0, totalRightLinksWidth = 0, totalLeftLinksWidth = 0;
            var maxColumn = d3Array.max(graph.nodes, function(node) {
              return node.column;
            });
            graph.links.forEach(function(link) {
              if (link.circular) {
                if (link.circularLinkType == "top") {
                  totalTopLinksWidth = totalTopLinksWidth + link.width;
                } else {
                  totalBottomLinksWidth = totalBottomLinksWidth + link.width;
                }
                if (link.target.column == 0) {
                  totalLeftLinksWidth = totalLeftLinksWidth + link.width;
                }
                if (link.source.column == maxColumn) {
                  totalRightLinksWidth = totalRightLinksWidth + link.width;
                }
              }
            });
            totalTopLinksWidth = totalTopLinksWidth > 0 ? totalTopLinksWidth + verticalMargin + baseRadius : totalTopLinksWidth;
            totalBottomLinksWidth = totalBottomLinksWidth > 0 ? totalBottomLinksWidth + verticalMargin + baseRadius : totalBottomLinksWidth;
            totalRightLinksWidth = totalRightLinksWidth > 0 ? totalRightLinksWidth + verticalMargin + baseRadius : totalRightLinksWidth;
            totalLeftLinksWidth = totalLeftLinksWidth > 0 ? totalLeftLinksWidth + verticalMargin + baseRadius : totalLeftLinksWidth;
            return { "top": totalTopLinksWidth, "bottom": totalBottomLinksWidth, "left": totalLeftLinksWidth, "right": totalRightLinksWidth };
          }
          function scaleSankeySize(graph, margin) {
            var maxColumn = d3Array.max(graph.nodes, function(node) {
              return node.column;
            });
            var currentWidth = x1 - x0;
            var currentHeight = y1 - y0;
            var newWidth = currentWidth + margin.right + margin.left;
            var newHeight = currentHeight + margin.top + margin.bottom;
            var scaleX = currentWidth / newWidth;
            var scaleY = currentHeight / newHeight;
            x0 = x0 * scaleX + margin.left;
            x1 = margin.right == 0 ? x1 : x1 * scaleX;
            y0 = y0 * scaleY + margin.top;
            y1 = y1 * scaleY;
            graph.nodes.forEach(function(node) {
              node.x0 = x0 + node.column * ((x1 - x0 - dx) / maxColumn);
              node.x1 = node.x0 + dx;
            });
            return scaleY;
          }
          function computeNodeDepths(graph) {
            var nodes2, next, x;
            for (nodes2 = graph.nodes, next = [], x = 0; nodes2.length; ++x, nodes2 = next, next = []) {
              nodes2.forEach(function(node) {
                node.depth = x;
                node.sourceLinks.forEach(function(link) {
                  if (next.indexOf(link.target) < 0 && !link.circular) {
                    next.push(link.target);
                  }
                });
              });
            }
            for (nodes2 = graph.nodes, next = [], x = 0; nodes2.length; ++x, nodes2 = next, next = []) {
              nodes2.forEach(function(node) {
                node.height = x;
                node.targetLinks.forEach(function(link) {
                  if (next.indexOf(link.source) < 0 && !link.circular) {
                    next.push(link.source);
                  }
                });
              });
            }
            graph.nodes.forEach(function(node) {
              node.column = Math.floor(align.call(null, node, x));
            });
          }
          function computeNodeBreadths(graph, iterations2, id2) {
            var columns = d3Collection.nest().key(function(d) {
              return d.column;
            }).sortKeys(d3Array.ascending).entries(graph.nodes).map(function(d) {
              return d.values;
            });
            initializeNodeBreadth(id2);
            resolveCollisions();
            for (var alpha = 1, n = iterations2; n > 0; --n) {
              relaxLeftAndRight(alpha *= 0.99, id2);
              resolveCollisions();
            }
            function initializeNodeBreadth(id3) {
              if (paddingRatio) {
                var padding = Infinity;
                columns.forEach(function(nodes2) {
                  var thisPadding = y1 * paddingRatio / (nodes2.length + 1);
                  padding = thisPadding < padding ? thisPadding : padding;
                });
                py = padding;
              }
              var ky = d3Array.min(columns, function(nodes2) {
                return (y1 - y0 - (nodes2.length - 1) * py) / d3Array.sum(nodes2, value);
              });
              ky = ky * scale;
              graph.links.forEach(function(link) {
                link.width = link.value * ky;
              });
              var margin = getCircleMargins(graph);
              var ratio = scaleSankeySize(graph, margin);
              ky = ky * ratio;
              graph.links.forEach(function(link) {
                link.width = link.value * ky;
              });
              columns.forEach(function(nodes2) {
                var nodesLength = nodes2.length;
                nodes2.forEach(function(node, i) {
                  if (node.depth == columns.length - 1 && nodesLength == 1) {
                    node.y0 = y1 / 2 - node.value * ky;
                    node.y1 = node.y0 + node.value * ky;
                  } else if (node.depth == 0 && nodesLength == 1) {
                    node.y0 = y1 / 2 - node.value * ky;
                    node.y1 = node.y0 + node.value * ky;
                  } else if (node.partOfCycle) {
                    if (numberOfNonSelfLinkingCycles(node, id3) == 0) {
                      node.y0 = y1 / 2 + i;
                      node.y1 = node.y0 + node.value * ky;
                    } else if (node.circularLinkType == "top") {
                      node.y0 = y0 + i;
                      node.y1 = node.y0 + node.value * ky;
                    } else {
                      node.y0 = y1 - node.value * ky - i;
                      node.y1 = node.y0 + node.value * ky;
                    }
                  } else {
                    if (margin.top == 0 || margin.bottom == 0) {
                      node.y0 = (y1 - y0) / nodesLength * i;
                      node.y1 = node.y0 + node.value * ky;
                    } else {
                      node.y0 = (y1 - y0) / 2 - nodesLength / 2 + i;
                      node.y1 = node.y0 + node.value * ky;
                    }
                  }
                });
              });
            }
            function relaxLeftAndRight(alpha2, id3) {
              var columnsLength = columns.length;
              columns.forEach(function(nodes2) {
                var n2 = nodes2.length;
                var depth = nodes2[0].depth;
                nodes2.forEach(function(node) {
                  var nodeHeight;
                  if (node.sourceLinks.length || node.targetLinks.length) {
                    if (node.partOfCycle && numberOfNonSelfLinkingCycles(node, id3) > 0) ;
                    else if (depth == 0 && n2 == 1) {
                      nodeHeight = node.y1 - node.y0;
                      node.y0 = y1 / 2 - nodeHeight / 2;
                      node.y1 = y1 / 2 + nodeHeight / 2;
                    } else if (depth == columnsLength - 1 && n2 == 1) {
                      nodeHeight = node.y1 - node.y0;
                      node.y0 = y1 / 2 - nodeHeight / 2;
                      node.y1 = y1 / 2 + nodeHeight / 2;
                    } else {
                      var avg = 0;
                      var avgTargetY = d3Array.mean(node.sourceLinks, linkTargetCenter);
                      var avgSourceY = d3Array.mean(node.targetLinks, linkSourceCenter);
                      if (avgTargetY && avgSourceY) {
                        avg = (avgTargetY + avgSourceY) / 2;
                      } else {
                        avg = avgTargetY || avgSourceY;
                      }
                      var dy = (avg - nodeCenter(node)) * alpha2;
                      node.y0 += dy;
                      node.y1 += dy;
                    }
                  }
                });
              });
            }
            function resolveCollisions() {
              columns.forEach(function(nodes2) {
                var node, dy, y = y0, n2 = nodes2.length, i;
                nodes2.sort(ascendingBreadth);
                for (i = 0; i < n2; ++i) {
                  node = nodes2[i];
                  dy = y - node.y0;
                  if (dy > 0) {
                    node.y0 += dy;
                    node.y1 += dy;
                  }
                  y = node.y1 + py;
                }
                dy = y - py - y1;
                if (dy > 0) {
                  y = node.y0 -= dy, node.y1 -= dy;
                  for (i = n2 - 2; i >= 0; --i) {
                    node = nodes2[i];
                    dy = node.y1 + py - y;
                    if (dy > 0) node.y0 -= dy, node.y1 -= dy;
                    y = node.y0;
                  }
                }
              });
            }
          }
          function computeLinkBreadths(graph) {
            graph.nodes.forEach(function(node) {
              node.sourceLinks.sort(ascendingTargetBreadth);
              node.targetLinks.sort(ascendingSourceBreadth);
            });
            graph.nodes.forEach(function(node) {
              var y02 = node.y0;
              var y12 = y02;
              var y0cycle = node.y1;
              var y1cycle = y0cycle;
              node.sourceLinks.forEach(function(link) {
                if (link.circular) {
                  link.y0 = y0cycle - link.width / 2;
                  y0cycle = y0cycle - link.width;
                } else {
                  link.y0 = y02 + link.width / 2;
                  y02 += link.width;
                }
              });
              node.targetLinks.forEach(function(link) {
                if (link.circular) {
                  link.y1 = y1cycle - link.width / 2;
                  y1cycle = y1cycle - link.width;
                } else {
                  link.y1 = y12 + link.width / 2;
                  y12 += link.width;
                }
              });
            });
          }
          return sankeyCircular2;
        }
        function identifyCircles(graph, id, sortNodes) {
          var circularLinkID = 0;
          if (sortNodes === null) {
            var adjList = [];
            for (var i = 0; i < graph.links.length; i++) {
              var link = graph.links[i];
              var source = link.source.index;
              var target = link.target.index;
              if (!adjList[source]) adjList[source] = [];
              if (!adjList[target]) adjList[target] = [];
              if (adjList[source].indexOf(target) === -1) adjList[source].push(target);
            }
            var cycles = findCircuits(adjList);
            cycles.sort(function(a, b) {
              return a.length - b.length;
            });
            var circularLinks = {};
            for (i = 0; i < cycles.length; i++) {
              var cycle = cycles[i];
              var last = cycle.slice(-2);
              if (!circularLinks[last[0]]) circularLinks[last[0]] = {};
              circularLinks[last[0]][last[1]] = true;
            }
            graph.links.forEach(function(link2) {
              var target2 = link2.target.index;
              var source2 = link2.source.index;
              if (target2 === source2 || circularLinks[source2] && circularLinks[source2][target2]) {
                link2.circular = true;
                link2.circularLinkID = circularLinkID;
                circularLinkID = circularLinkID + 1;
              } else {
                link2.circular = false;
              }
            });
          } else {
            graph.links.forEach(function(link2) {
              if (link2.source[sortNodes] < link2.target[sortNodes]) {
                link2.circular = false;
              } else {
                link2.circular = true;
                link2.circularLinkID = circularLinkID;
                circularLinkID = circularLinkID + 1;
              }
            });
          }
        }
        function selectCircularLinkTypes(graph, id) {
          var numberOfTops = 0;
          var numberOfBottoms = 0;
          graph.links.forEach(function(link) {
            if (link.circular) {
              if (link.source.circularLinkType || link.target.circularLinkType) {
                link.circularLinkType = link.source.circularLinkType ? link.source.circularLinkType : link.target.circularLinkType;
              } else {
                link.circularLinkType = numberOfTops < numberOfBottoms ? "top" : "bottom";
              }
              if (link.circularLinkType == "top") {
                numberOfTops = numberOfTops + 1;
              } else {
                numberOfBottoms = numberOfBottoms + 1;
              }
              graph.nodes.forEach(function(node) {
                if (getNodeID(node, id) == getNodeID(link.source, id) || getNodeID(node, id) == getNodeID(link.target, id)) {
                  node.circularLinkType = link.circularLinkType;
                }
              });
            }
          });
          graph.links.forEach(function(link) {
            if (link.circular) {
              if (link.source.circularLinkType == link.target.circularLinkType) {
                link.circularLinkType = link.source.circularLinkType;
              }
              if (selfLinking(link, id)) {
                link.circularLinkType = link.source.circularLinkType;
              }
            }
          });
        }
        function linkAngle(link) {
          var adjacent = Math.abs(link.y1 - link.y0);
          var opposite = Math.abs(link.target.x0 - link.source.x1);
          return Math.atan(opposite / adjacent);
        }
        function circularLinksCross(link1, link2) {
          if (link1.source.column < link2.target.column) {
            return false;
          } else if (link1.target.column > link2.source.column) {
            return false;
          } else {
            return true;
          }
        }
        function numberOfNonSelfLinkingCycles(node, id) {
          var sourceCount = 0;
          node.sourceLinks.forEach(function(l) {
            sourceCount = l.circular && !selfLinking(l, id) ? sourceCount + 1 : sourceCount;
          });
          var targetCount = 0;
          node.targetLinks.forEach(function(l) {
            targetCount = l.circular && !selfLinking(l, id) ? targetCount + 1 : targetCount;
          });
          return sourceCount + targetCount;
        }
        function onlyCircularLink(link) {
          var nodeSourceLinks = link.source.sourceLinks;
          var sourceCount = 0;
          nodeSourceLinks.forEach(function(l) {
            sourceCount = l.circular ? sourceCount + 1 : sourceCount;
          });
          var nodeTargetLinks = link.target.targetLinks;
          var targetCount = 0;
          nodeTargetLinks.forEach(function(l) {
            targetCount = l.circular ? targetCount + 1 : targetCount;
          });
          if (sourceCount > 1 || targetCount > 1) {
            return false;
          } else {
            return true;
          }
        }
        function calcVerticalBuffer(links, circularLinkGap, id) {
          links.sort(sortLinkColumnAscending);
          links.forEach(function(link, i) {
            var buffer = 0;
            if (selfLinking(link, id) && onlyCircularLink(link)) {
              link.circularPathData.verticalBuffer = buffer + link.width / 2;
            } else {
              var j = 0;
              for (j; j < i; j++) {
                if (circularLinksCross(links[i], links[j])) {
                  var bufferOverThisLink = links[j].circularPathData.verticalBuffer + links[j].width / 2 + circularLinkGap;
                  buffer = bufferOverThisLink > buffer ? bufferOverThisLink : buffer;
                }
              }
              link.circularPathData.verticalBuffer = buffer + link.width / 2;
            }
          });
          return links;
        }
        function addCircularPathData(graph, circularLinkGap, y1, id) {
          var buffer = 5;
          var minY = d3Array.min(graph.links, function(link) {
            return link.source.y0;
          });
          graph.links.forEach(function(link) {
            if (link.circular) {
              link.circularPathData = {};
            }
          });
          var topLinks = graph.links.filter(function(l) {
            return l.circularLinkType == "top";
          });
          calcVerticalBuffer(topLinks, circularLinkGap, id);
          var bottomLinks = graph.links.filter(function(l) {
            return l.circularLinkType == "bottom";
          });
          calcVerticalBuffer(bottomLinks, circularLinkGap, id);
          graph.links.forEach(function(link) {
            if (link.circular) {
              link.circularPathData.arcRadius = link.width + baseRadius;
              link.circularPathData.leftNodeBuffer = buffer;
              link.circularPathData.rightNodeBuffer = buffer;
              link.circularPathData.sourceWidth = link.source.x1 - link.source.x0;
              link.circularPathData.sourceX = link.source.x0 + link.circularPathData.sourceWidth;
              link.circularPathData.targetX = link.target.x0;
              link.circularPathData.sourceY = link.y0;
              link.circularPathData.targetY = link.y1;
              if (selfLinking(link, id) && onlyCircularLink(link)) {
                link.circularPathData.leftSmallArcRadius = baseRadius + link.width / 2;
                link.circularPathData.leftLargeArcRadius = baseRadius + link.width / 2;
                link.circularPathData.rightSmallArcRadius = baseRadius + link.width / 2;
                link.circularPathData.rightLargeArcRadius = baseRadius + link.width / 2;
                if (link.circularLinkType == "bottom") {
                  link.circularPathData.verticalFullExtent = link.source.y1 + verticalMargin + link.circularPathData.verticalBuffer;
                  link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.leftLargeArcRadius;
                  link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.rightLargeArcRadius;
                } else {
                  link.circularPathData.verticalFullExtent = link.source.y0 - verticalMargin - link.circularPathData.verticalBuffer;
                  link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.leftLargeArcRadius;
                  link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.rightLargeArcRadius;
                }
              } else {
                var thisColumn = link.source.column;
                var thisCircularLinkType = link.circularLinkType;
                var sameColumnLinks = graph.links.filter(function(l) {
                  return l.source.column == thisColumn && l.circularLinkType == thisCircularLinkType;
                });
                if (link.circularLinkType == "bottom") {
                  sameColumnLinks.sort(sortLinkSourceYDescending);
                } else {
                  sameColumnLinks.sort(sortLinkSourceYAscending);
                }
                var radiusOffset = 0;
                sameColumnLinks.forEach(function(l, i) {
                  if (l.circularLinkID == link.circularLinkID) {
                    link.circularPathData.leftSmallArcRadius = baseRadius + link.width / 2 + radiusOffset;
                    link.circularPathData.leftLargeArcRadius = baseRadius + link.width / 2 + i * circularLinkGap + radiusOffset;
                  }
                  radiusOffset = radiusOffset + l.width;
                });
                thisColumn = link.target.column;
                sameColumnLinks = graph.links.filter(function(l) {
                  return l.target.column == thisColumn && l.circularLinkType == thisCircularLinkType;
                });
                if (link.circularLinkType == "bottom") {
                  sameColumnLinks.sort(sortLinkTargetYDescending);
                } else {
                  sameColumnLinks.sort(sortLinkTargetYAscending);
                }
                radiusOffset = 0;
                sameColumnLinks.forEach(function(l, i) {
                  if (l.circularLinkID == link.circularLinkID) {
                    link.circularPathData.rightSmallArcRadius = baseRadius + link.width / 2 + radiusOffset;
                    link.circularPathData.rightLargeArcRadius = baseRadius + link.width / 2 + i * circularLinkGap + radiusOffset;
                  }
                  radiusOffset = radiusOffset + l.width;
                });
                if (link.circularLinkType == "bottom") {
                  link.circularPathData.verticalFullExtent = Math.max(y1, link.source.y1, link.target.y1) + verticalMargin + link.circularPathData.verticalBuffer;
                  link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.leftLargeArcRadius;
                  link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent - link.circularPathData.rightLargeArcRadius;
                } else {
                  link.circularPathData.verticalFullExtent = minY - verticalMargin - link.circularPathData.verticalBuffer;
                  link.circularPathData.verticalLeftInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.leftLargeArcRadius;
                  link.circularPathData.verticalRightInnerExtent = link.circularPathData.verticalFullExtent + link.circularPathData.rightLargeArcRadius;
                }
              }
              link.circularPathData.leftInnerExtent = link.circularPathData.sourceX + link.circularPathData.leftNodeBuffer;
              link.circularPathData.rightInnerExtent = link.circularPathData.targetX - link.circularPathData.rightNodeBuffer;
              link.circularPathData.leftFullExtent = link.circularPathData.sourceX + link.circularPathData.leftLargeArcRadius + link.circularPathData.leftNodeBuffer;
              link.circularPathData.rightFullExtent = link.circularPathData.targetX - link.circularPathData.rightLargeArcRadius - link.circularPathData.rightNodeBuffer;
            }
            if (link.circular) {
              link.path = createCircularPathString(link);
            } else {
              var normalPath = d3Shape.linkHorizontal().source(function(d) {
                var x = d.source.x0 + (d.source.x1 - d.source.x0);
                var y = d.y0;
                return [x, y];
              }).target(function(d) {
                var x = d.target.x0;
                var y = d.y1;
                return [x, y];
              });
              link.path = normalPath(link);
            }
          });
        }
        function createCircularPathString(link) {
          var pathString = "";
          if (link.circularLinkType == "top") {
            pathString = // start at the right of the source node
            "M" + link.circularPathData.sourceX + " " + link.circularPathData.sourceY + " L" + link.circularPathData.leftInnerExtent + " " + link.circularPathData.sourceY + " A" + link.circularPathData.leftLargeArcRadius + " " + link.circularPathData.leftSmallArcRadius + " 0 0 0 " + // End of arc X //End of arc Y
            link.circularPathData.leftFullExtent + " " + (link.circularPathData.sourceY - link.circularPathData.leftSmallArcRadius) + " L" + link.circularPathData.leftFullExtent + " " + link.circularPathData.verticalLeftInnerExtent + " A" + link.circularPathData.leftLargeArcRadius + " " + link.circularPathData.leftLargeArcRadius + " 0 0 0 " + // End of arc X //End of arc Y
            link.circularPathData.leftInnerExtent + " " + link.circularPathData.verticalFullExtent + " L" + link.circularPathData.rightInnerExtent + " " + link.circularPathData.verticalFullExtent + " A" + link.circularPathData.rightLargeArcRadius + " " + link.circularPathData.rightLargeArcRadius + " 0 0 0 " + // End of arc X //End of arc Y
            link.circularPathData.rightFullExtent + " " + link.circularPathData.verticalRightInnerExtent + " L" + link.circularPathData.rightFullExtent + " " + (link.circularPathData.targetY - link.circularPathData.rightSmallArcRadius) + " A" + link.circularPathData.rightLargeArcRadius + " " + link.circularPathData.rightSmallArcRadius + " 0 0 0 " + // End of arc X //End of arc Y
            link.circularPathData.rightInnerExtent + " " + link.circularPathData.targetY + " L" + link.circularPathData.targetX + " " + link.circularPathData.targetY;
          } else {
            pathString = // start at the right of the source node
            "M" + link.circularPathData.sourceX + " " + link.circularPathData.sourceY + " L" + link.circularPathData.leftInnerExtent + " " + link.circularPathData.sourceY + " A" + link.circularPathData.leftLargeArcRadius + " " + link.circularPathData.leftSmallArcRadius + " 0 0 1 " + // End of arc X //End of arc Y
            link.circularPathData.leftFullExtent + " " + (link.circularPathData.sourceY + link.circularPathData.leftSmallArcRadius) + " L" + link.circularPathData.leftFullExtent + " " + link.circularPathData.verticalLeftInnerExtent + " A" + link.circularPathData.leftLargeArcRadius + " " + link.circularPathData.leftLargeArcRadius + " 0 0 1 " + // End of arc X //End of arc Y
            link.circularPathData.leftInnerExtent + " " + link.circularPathData.verticalFullExtent + " L" + link.circularPathData.rightInnerExtent + " " + link.circularPathData.verticalFullExtent + " A" + link.circularPathData.rightLargeArcRadius + " " + link.circularPathData.rightLargeArcRadius + " 0 0 1 " + // End of arc X //End of arc Y
            link.circularPathData.rightFullExtent + " " + link.circularPathData.verticalRightInnerExtent + " L" + link.circularPathData.rightFullExtent + " " + (link.circularPathData.targetY + link.circularPathData.rightSmallArcRadius) + " A" + link.circularPathData.rightLargeArcRadius + " " + link.circularPathData.rightSmallArcRadius + " 0 0 1 " + // End of arc X //End of arc Y
            link.circularPathData.rightInnerExtent + " " + link.circularPathData.targetY + " L" + link.circularPathData.targetX + " " + link.circularPathData.targetY;
          }
          return pathString;
        }
        function sortLinkColumnAscending(link1, link2) {
          if (linkColumnDistance(link1) == linkColumnDistance(link2)) {
            return link1.circularLinkType == "bottom" ? sortLinkSourceYDescending(link1, link2) : sortLinkSourceYAscending(link1, link2);
          } else {
            return linkColumnDistance(link2) - linkColumnDistance(link1);
          }
        }
        function sortLinkSourceYAscending(link1, link2) {
          return link1.y0 - link2.y0;
        }
        function sortLinkSourceYDescending(link1, link2) {
          return link2.y0 - link1.y0;
        }
        function sortLinkTargetYAscending(link1, link2) {
          return link1.y1 - link2.y1;
        }
        function sortLinkTargetYDescending(link1, link2) {
          return link2.y1 - link1.y1;
        }
        function linkColumnDistance(link) {
          return link.target.column - link.source.column;
        }
        function linkXLength(link) {
          return link.target.x0 - link.source.x1;
        }
        function linkPerpendicularYToLinkSource(longerLink, shorterLink) {
          var angle = linkAngle(longerLink);
          var heightFromY1ToPependicular = linkXLength(shorterLink) / Math.tan(angle);
          var yPerpendicular = incline(longerLink) == "up" ? longerLink.y1 + heightFromY1ToPependicular : longerLink.y1 - heightFromY1ToPependicular;
          return yPerpendicular;
        }
        function linkPerpendicularYToLinkTarget(longerLink, shorterLink) {
          var angle = linkAngle(longerLink);
          var heightFromY1ToPependicular = linkXLength(shorterLink) / Math.tan(angle);
          var yPerpendicular = incline(longerLink) == "up" ? longerLink.y1 - heightFromY1ToPependicular : longerLink.y1 + heightFromY1ToPependicular;
          return yPerpendicular;
        }
        function resolveNodeLinkOverlaps(graph, y0, y1, id) {
          graph.links.forEach(function(link) {
            if (link.circular) {
              return;
            }
            if (link.target.column - link.source.column > 1) {
              var columnToTest = link.source.column + 1;
              var maxColumnToTest = link.target.column - 1;
              var i = 1;
              var numberOfColumnsToTest = maxColumnToTest - columnToTest + 1;
              for (i = 1; columnToTest <= maxColumnToTest; columnToTest++, i++) {
                graph.nodes.forEach(function(node) {
                  if (node.column == columnToTest) {
                    var t = i / (numberOfColumnsToTest + 1);
                    var B0_t = Math.pow(1 - t, 3);
                    var B1_t = 3 * t * Math.pow(1 - t, 2);
                    var B2_t = 3 * Math.pow(t, 2) * (1 - t);
                    var B3_t = Math.pow(t, 3);
                    var py_t = B0_t * link.y0 + B1_t * link.y0 + B2_t * link.y1 + B3_t * link.y1;
                    var linkY0AtColumn = py_t - link.width / 2;
                    var linkY1AtColumn = py_t + link.width / 2;
                    var dy;
                    if (linkY0AtColumn > node.y0 && linkY0AtColumn < node.y1) {
                      dy = node.y1 - linkY0AtColumn + 10;
                      dy = node.circularLinkType == "bottom" ? dy : -dy;
                      node = adjustNodeHeight(node, dy, y0, y1);
                      graph.nodes.forEach(function(otherNode) {
                        if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) {
                          return;
                        }
                        if (nodesOverlap(node, otherNode)) {
                          adjustNodeHeight(otherNode, dy, y0, y1);
                        }
                      });
                    } else if (linkY1AtColumn > node.y0 && linkY1AtColumn < node.y1) {
                      dy = linkY1AtColumn - node.y0 + 10;
                      node = adjustNodeHeight(node, dy, y0, y1);
                      graph.nodes.forEach(function(otherNode) {
                        if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) {
                          return;
                        }
                        if (otherNode.y0 < node.y1 && otherNode.y1 > node.y1) {
                          adjustNodeHeight(otherNode, dy, y0, y1);
                        }
                      });
                    } else if (linkY0AtColumn < node.y0 && linkY1AtColumn > node.y1) {
                      dy = linkY1AtColumn - node.y0 + 10;
                      node = adjustNodeHeight(node, dy, y0, y1);
                      graph.nodes.forEach(function(otherNode) {
                        if (getNodeID(otherNode, id) == getNodeID(node, id) || otherNode.column != node.column) {
                          return;
                        }
                        if (otherNode.y0 < node.y1 && otherNode.y1 > node.y1) {
                          adjustNodeHeight(otherNode, dy, y0, y1);
                        }
                      });
                    }
                  }
                });
              }
            }
          });
        }
        function nodesOverlap(nodeA, nodeB) {
          if (nodeA.y0 > nodeB.y0 && nodeA.y0 < nodeB.y1) {
            return true;
          } else if (nodeA.y1 > nodeB.y0 && nodeA.y1 < nodeB.y1) {
            return true;
          } else if (nodeA.y0 < nodeB.y0 && nodeA.y1 > nodeB.y1) {
            return true;
          } else {
            return false;
          }
        }
        function adjustNodeHeight(node, dy, sankeyY0, sankeyY1) {
          if (node.y0 + dy >= sankeyY0 && node.y1 + dy <= sankeyY1) {
            node.y0 = node.y0 + dy;
            node.y1 = node.y1 + dy;
            node.targetLinks.forEach(function(l) {
              l.y1 = l.y1 + dy;
            });
            node.sourceLinks.forEach(function(l) {
              l.y0 = l.y0 + dy;
            });
          }
          return node;
        }
        function sortSourceLinks(graph, y1, id, moveNodes) {
          graph.nodes.forEach(function(node) {
            if (moveNodes && node.y + (node.y1 - node.y0) > y1) {
              node.y = node.y - (node.y + (node.y1 - node.y0) - y1);
            }
            var nodesSourceLinks = graph.links.filter(function(l) {
              return getNodeID(l.source, id) == getNodeID(node, id);
            });
            var nodeSourceLinksLength = nodesSourceLinks.length;
            if (nodeSourceLinksLength > 1) {
              nodesSourceLinks.sort(function(link1, link2) {
                if (!link1.circular && !link2.circular) {
                  if (link1.target.column == link2.target.column) {
                    return link1.y1 - link2.y1;
                  } else if (!sameInclines(link1, link2)) {
                    return link1.y1 - link2.y1;
                  } else {
                    if (link1.target.column > link2.target.column) {
                      var link2Adj = linkPerpendicularYToLinkTarget(link2, link1);
                      return link1.y1 - link2Adj;
                    }
                    if (link2.target.column > link1.target.column) {
                      var link1Adj = linkPerpendicularYToLinkTarget(link1, link2);
                      return link1Adj - link2.y1;
                    }
                  }
                }
                if (link1.circular && !link2.circular) {
                  return link1.circularLinkType == "top" ? -1 : 1;
                } else if (link2.circular && !link1.circular) {
                  return link2.circularLinkType == "top" ? 1 : -1;
                }
                if (link1.circular && link2.circular) {
                  if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == "top") {
                    if (link1.target.column === link2.target.column) {
                      return link1.target.y1 - link2.target.y1;
                    } else {
                      return link2.target.column - link1.target.column;
                    }
                  } else if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == "bottom") {
                    if (link1.target.column === link2.target.column) {
                      return link2.target.y1 - link1.target.y1;
                    } else {
                      return link1.target.column - link2.target.column;
                    }
                  } else {
                    return link1.circularLinkType == "top" ? -1 : 1;
                  }
                }
              });
            }
            var ySourceOffset = node.y0;
            nodesSourceLinks.forEach(function(link) {
              link.y0 = ySourceOffset + link.width / 2;
              ySourceOffset = ySourceOffset + link.width;
            });
            nodesSourceLinks.forEach(function(link, i) {
              if (link.circularLinkType == "bottom") {
                var j = i + 1;
                var offsetFromBottom = 0;
                for (j; j < nodeSourceLinksLength; j++) {
                  offsetFromBottom = offsetFromBottom + nodesSourceLinks[j].width;
                }
                link.y0 = node.y1 - offsetFromBottom - link.width / 2;
              }
            });
          });
        }
        function sortTargetLinks(graph, y1, id) {
          graph.nodes.forEach(function(node) {
            var nodesTargetLinks = graph.links.filter(function(l) {
              return getNodeID(l.target, id) == getNodeID(node, id);
            });
            var nodesTargetLinksLength = nodesTargetLinks.length;
            if (nodesTargetLinksLength > 1) {
              nodesTargetLinks.sort(function(link1, link2) {
                if (!link1.circular && !link2.circular) {
                  if (link1.source.column == link2.source.column) {
                    return link1.y0 - link2.y0;
                  } else if (!sameInclines(link1, link2)) {
                    return link1.y0 - link2.y0;
                  } else {
                    if (link2.source.column < link1.source.column) {
                      var link2Adj = linkPerpendicularYToLinkSource(link2, link1);
                      return link1.y0 - link2Adj;
                    }
                    if (link1.source.column < link2.source.column) {
                      var link1Adj = linkPerpendicularYToLinkSource(link1, link2);
                      return link1Adj - link2.y0;
                    }
                  }
                }
                if (link1.circular && !link2.circular) {
                  return link1.circularLinkType == "top" ? -1 : 1;
                } else if (link2.circular && !link1.circular) {
                  return link2.circularLinkType == "top" ? 1 : -1;
                }
                if (link1.circular && link2.circular) {
                  if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == "top") {
                    if (link1.source.column === link2.source.column) {
                      return link1.source.y1 - link2.source.y1;
                    } else {
                      return link1.source.column - link2.source.column;
                    }
                  } else if (link1.circularLinkType === link2.circularLinkType && link1.circularLinkType == "bottom") {
                    if (link1.source.column === link2.source.column) {
                      return link1.source.y1 - link2.source.y1;
                    } else {
                      return link2.source.column - link1.source.column;
                    }
                  } else {
                    return link1.circularLinkType == "top" ? -1 : 1;
                  }
                }
              });
            }
            var yTargetOffset = node.y0;
            nodesTargetLinks.forEach(function(link) {
              link.y1 = yTargetOffset + link.width / 2;
              yTargetOffset = yTargetOffset + link.width;
            });
            nodesTargetLinks.forEach(function(link, i) {
              if (link.circularLinkType == "bottom") {
                var j = i + 1;
                var offsetFromBottom = 0;
                for (j; j < nodesTargetLinksLength; j++) {
                  offsetFromBottom = offsetFromBottom + nodesTargetLinks[j].width;
                }
                link.y1 = node.y1 - offsetFromBottom - link.width / 2;
              }
            });
          });
        }
        function sameInclines(link1, link2) {
          return incline(link1) == incline(link2);
        }
        function incline(link) {
          return link.y0 - link.y1 > 0 ? "up" : "down";
        }
        function selfLinking(link, id) {
          return getNodeID(link.source, id) == getNodeID(link.target, id);
        }
        function fillHeight(graph, y0, y1) {
          var nodes = graph.nodes;
          var links = graph.links;
          var top = false;
          var bottom = false;
          links.forEach(function(link) {
            if (link.circularLinkType == "top") {
              top = true;
            } else if (link.circularLinkType == "bottom") {
              bottom = true;
            }
          });
          if (top == false || bottom == false) {
            var minY0 = d3Array.min(nodes, function(node) {
              return node.y0;
            });
            var maxY1 = d3Array.max(nodes, function(node) {
              return node.y1;
            });
            var currentHeight = maxY1 - minY0;
            var chartHeight = y1 - y0;
            var ratio = chartHeight / currentHeight;
            nodes.forEach(function(node) {
              var nodeHeight = (node.y1 - node.y0) * ratio;
              node.y0 = (node.y0 - minY0) * ratio;
              node.y1 = node.y0 + nodeHeight;
            });
            links.forEach(function(link) {
              link.y0 = (link.y0 - minY0) * ratio;
              link.y1 = (link.y1 - minY0) * ratio;
              link.width = link.width * ratio;
            });
          }
        }
        exports2.sankeyCircular = sankeyCircular;
        exports2.sankeyCenter = center;
        exports2.sankeyLeft = left;
        exports2.sankeyRight = right;
        exports2.sankeyJustify = justify;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // src/traces/sankey/constants.js
  var require_constants29 = __commonJS({
    "src/traces/sankey/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        nodeTextOffsetHorizontal: 4,
        nodeTextOffsetVertical: 3,
        nodePadAcross: 10,
        sankeyIterations: 50,
        forceIterations: 5,
        forceTicksPerFrame: 10,
        duration: 500,
        ease: "linear",
        cn: {
          sankey: "sankey",
          sankeyLinks: "sankey-links",
          sankeyLink: "sankey-link",
          sankeyNodeSet: "sankey-node-set",
          sankeyNode: "sankey-node",
          nodeRect: "node-rect",
          nodeLabel: "node-label"
        }
      };
    }
  });

  // src/traces/sankey/render.js
  var require_render = __commonJS({
    "src/traces/sankey/render.js"(exports, module) {
      "use strict";
      var d3Force = require_d3_force();
      var interpolateNumber = (init_src2(), __toCommonJS(src_exports)).interpolateNumber;
      var d3 = require_d3();
      var d3Sankey = require_d3_sankey();
      var d3SankeyCircular = require_d3_sankey_circular();
      var c = require_constants29();
      var tinycolor = require_tinycolor();
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var strTranslate = Lib.strTranslate;
      var strRotate = Lib.strRotate;
      var gup = require_gup();
      var keyFun = gup.keyFun;
      var repeat = gup.repeat;
      var unwrap = gup.unwrap;
      var svgTextUtils = require_svg_text_utils();
      var Registry = require_registry();
      var alignmentConstants = require_alignment();
      var CAP_SHIFT = alignmentConstants.CAP_SHIFT;
      var LINE_SPACING = alignmentConstants.LINE_SPACING;
      var TEXTPAD = 3;
      function sankeyModel(layout, d, traceIndex) {
        var calcData = unwrap(d);
        var trace = calcData.trace;
        var domain = trace.domain;
        var horizontal = trace.orientation === "h";
        var nodePad = trace.node.pad;
        var nodeThickness = trace.node.thickness;
        var nodeAlign = {
          justify: d3Sankey.sankeyJustify,
          left: d3Sankey.sankeyLeft,
          right: d3Sankey.sankeyRight,
          center: d3Sankey.sankeyCenter
        }[trace.node.align];
        var width = layout.width * (domain.x[1] - domain.x[0]);
        var height = layout.height * (domain.y[1] - domain.y[0]);
        var nodes = calcData._nodes;
        var links = calcData._links;
        var circular = calcData.circular;
        var sankey;
        if (circular) {
          sankey = d3SankeyCircular.sankeyCircular().circularLinkGap(0);
        } else {
          sankey = d3Sankey.sankey();
        }
        sankey.iterations(c.sankeyIterations).size(horizontal ? [width, height] : [height, width]).nodeWidth(nodeThickness).nodePadding(nodePad).nodeId(function(d2) {
          return d2.pointNumber;
        }).nodeAlign(nodeAlign).nodes(nodes).links(links);
        var graph = sankey();
        if (sankey.nodePadding() < nodePad) {
          Lib.warn("node.pad was reduced to ", sankey.nodePadding(), " to fit within the figure.");
        }
        var i, j, k;
        for (var nodePointNumber in calcData._groupLookup) {
          var groupIndex = parseInt(calcData._groupLookup[nodePointNumber]);
          var groupingNode;
          for (i = 0; i < graph.nodes.length; i++) {
            if (graph.nodes[i].pointNumber === groupIndex) {
              groupingNode = graph.nodes[i];
              break;
            }
          }
          if (!groupingNode) continue;
          var child = {
            pointNumber: parseInt(nodePointNumber),
            x0: groupingNode.x0,
            x1: groupingNode.x1,
            y0: groupingNode.y0,
            y1: groupingNode.y1,
            partOfGroup: true,
            sourceLinks: [],
            targetLinks: []
          };
          graph.nodes.unshift(child);
          groupingNode.childrenNodes.unshift(child);
        }
        function computeLinkConcentrations() {
          for (i = 0; i < graph.nodes.length; i++) {
            var node = graph.nodes[i];
            var flows = {};
            var flowKey;
            var link;
            for (j = 0; j < node.targetLinks.length; j++) {
              link = node.targetLinks[j];
              flowKey = link.source.pointNumber + ":" + link.target.pointNumber;
              if (!flows.hasOwnProperty(flowKey)) flows[flowKey] = [];
              flows[flowKey].push(link);
            }
            var keys = Object.keys(flows);
            for (j = 0; j < keys.length; j++) {
              flowKey = keys[j];
              var flowLinks = flows[flowKey];
              var total = 0;
              var totalPerLabel = {};
              for (k = 0; k < flowLinks.length; k++) {
                link = flowLinks[k];
                if (!totalPerLabel[link.label]) totalPerLabel[link.label] = 0;
                totalPerLabel[link.label] += link.value;
                total += link.value;
              }
              for (k = 0; k < flowLinks.length; k++) {
                link = flowLinks[k];
                link.flow = {
                  value: total,
                  labelConcentration: totalPerLabel[link.label] / total,
                  concentration: link.value / total,
                  links: flowLinks
                };
                if (link.concentrationscale) {
                  link.color = tinycolor(link.concentrationscale(link.flow.labelConcentration));
                }
              }
            }
            var totalOutflow = 0;
            for (j = 0; j < node.sourceLinks.length; j++) {
              totalOutflow += node.sourceLinks[j].value;
            }
            for (j = 0; j < node.sourceLinks.length; j++) {
              link = node.sourceLinks[j];
              link.concentrationOut = link.value / totalOutflow;
            }
            var totalInflow = 0;
            for (j = 0; j < node.targetLinks.length; j++) {
              totalInflow += node.targetLinks[j].value;
            }
            for (j = 0; j < node.targetLinks.length; j++) {
              link = node.targetLinks[j];
              link.concenrationIn = link.value / totalInflow;
            }
          }
        }
        computeLinkConcentrations();
        function resolveCollisionsTopToBottom(columns2) {
          columns2.forEach(function(nodes2) {
            var node;
            var dy;
            var y = 0;
            var n = nodes2.length;
            var i2;
            nodes2.sort(function(a, b) {
              return a.y0 - b.y0;
            });
            for (i2 = 0; i2 < n; ++i2) {
              node = nodes2[i2];
              if (node.y0 >= y) {
              } else {
                dy = y - node.y0;
                if (dy > 1e-6) node.y0 += dy, node.y1 += dy;
              }
              y = node.y1 + nodePad;
            }
          });
        }
        function snapToColumns(nodes2) {
          var orderedNodes = nodes2.map(function(n, i2) {
            return {
              x0: n.x0,
              index: i2
            };
          }).sort(function(a, b) {
            return a.x0 - b.x0;
          });
          var columns2 = [];
          var colNumber = -1;
          var colX;
          var lastX = -Infinity;
          var dx;
          for (i = 0; i < orderedNodes.length; i++) {
            var node = nodes2[orderedNodes[i].index];
            if (node.x0 > lastX + nodeThickness) {
              colNumber += 1;
              colX = node.x0;
            }
            lastX = node.x0;
            if (!columns2[colNumber]) columns2[colNumber] = [];
            columns2[colNumber].push(node);
            dx = colX - node.x0;
            node.x0 += dx, node.x1 += dx;
          }
          return columns2;
        }
        if (trace.node.x.length && trace.node.y.length) {
          for (i = 0; i < Math.min(trace.node.x.length, trace.node.y.length, graph.nodes.length); i++) {
            if (trace.node.x[i] && trace.node.y[i]) {
              var pos = [trace.node.x[i] * width, trace.node.y[i] * height];
              graph.nodes[i].x0 = pos[0] - nodeThickness / 2;
              graph.nodes[i].x1 = pos[0] + nodeThickness / 2;
              var nodeHeight = graph.nodes[i].y1 - graph.nodes[i].y0;
              graph.nodes[i].y0 = pos[1] - nodeHeight / 2;
              graph.nodes[i].y1 = pos[1] + nodeHeight / 2;
            }
          }
          if (trace.arrangement === "snap") {
            nodes = graph.nodes;
            var columns = snapToColumns(nodes);
            resolveCollisionsTopToBottom(columns);
          }
          sankey.update(graph);
        }
        return {
          circular,
          key: traceIndex,
          trace,
          guid: Lib.randstr(),
          horizontal,
          width,
          height,
          nodePad: trace.node.pad,
          nodeLineColor: trace.node.line.color,
          nodeLineWidth: trace.node.line.width,
          linkLineColor: trace.link.line.color,
          linkLineWidth: trace.link.line.width,
          linkArrowLength: trace.link.arrowlen,
          valueFormat: trace.valueformat,
          valueSuffix: trace.valuesuffix,
          textFont: trace.textfont,
          translateX: domain.x[0] * layout.width + layout.margin.l,
          translateY: layout.height - domain.y[1] * layout.height + layout.margin.t,
          dragParallel: horizontal ? height : width,
          dragPerpendicular: horizontal ? width : height,
          arrangement: trace.arrangement,
          sankey,
          graph,
          forceLayouts: {},
          interactionState: {
            dragInProgress: false,
            hovered: false
          }
        };
      }
      function linkModel(d, l, i) {
        var tc = tinycolor(l.color);
        var htc = tinycolor(l.hovercolor);
        var basicKey = l.source.label + "|" + l.target.label;
        var key = basicKey + "__" + i;
        l.trace = d.trace;
        l.curveNumber = d.trace.index;
        return {
          circular: d.circular,
          key,
          traceId: d.key,
          pointNumber: l.pointNumber,
          link: l,
          tinyColorHue: Color2.tinyRGB(tc),
          tinyColorAlpha: tc.getAlpha(),
          tinyColorHoverHue: Color2.tinyRGB(htc),
          tinyColorHoverAlpha: htc.getAlpha(),
          linkPath,
          linkLineColor: d.linkLineColor,
          linkLineWidth: d.linkLineWidth,
          linkArrowLength: d.linkArrowLength,
          valueFormat: d.valueFormat,
          valueSuffix: d.valueSuffix,
          sankey: d.sankey,
          parent: d,
          interactionState: d.interactionState,
          flow: l.flow
        };
      }
      function createCircularClosedPathString(link, arrowLen) {
        var pathString = "";
        var offset = link.width / 2;
        var coords = link.circularPathData;
        var isSourceBeforeTarget = coords.sourceX + coords.verticalBuffer < coords.targetX;
        var isPathOverlapped = coords.rightFullExtent - coords.rightLargeArcRadius - arrowLen <= coords.leftFullExtent - offset;
        var diff = Math.abs(coords.rightFullExtent - coords.leftFullExtent - offset) < offset;
        if (link.circularLinkType === "top") {
          pathString = // start at the left of the target node
          "M " + (coords.targetX - arrowLen) + " " + (coords.targetY + offset) + " L " + (coords.rightInnerExtent - arrowLen) + " " + (coords.targetY + offset) + "A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightSmallArcRadius + offset) + " 0 0 1 " + (coords.rightFullExtent - offset - arrowLen) + " " + (coords.targetY - coords.rightSmallArcRadius) + "L " + (coords.rightFullExtent - offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          if (isSourceBeforeTarget && isPathOverlapped) {
            pathString += " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightLargeArcRadius + offset) + " 0 0 1 " + (coords.rightFullExtent + offset - arrowLen - (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalRightInnerExtent - (coords.rightLargeArcRadius + offset)) + " L " + (coords.rightFullExtent + offset - (coords.rightLargeArcRadius - offset) - arrowLen) + " " + (coords.verticalRightInnerExtent - (coords.rightLargeArcRadius + offset)) + " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftLargeArcRadius + offset) + " 0 0 1 " + (coords.leftFullExtent + offset) + " " + coords.verticalRightInnerExtent;
          } else if (isSourceBeforeTarget) {
            pathString += " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightLargeArcRadius - offset) + " 0 0 0 " + (coords.rightFullExtent - offset - arrowLen - (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalRightInnerExtent - (coords.rightLargeArcRadius - offset)) + " L " + (coords.leftFullExtent + offset + (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalRightInnerExtent - (coords.rightLargeArcRadius - offset)) + " A " + (coords.leftLargeArcRadius - offset) + " " + (coords.leftLargeArcRadius - offset) + " 0 0 0 " + (coords.leftFullExtent + offset) + " " + coords.verticalLeftInnerExtent;
          } else {
            pathString += " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightLargeArcRadius + offset) + " 0 0 1 " + (coords.rightInnerExtent - arrowLen) + " " + (coords.verticalFullExtent - offset) + " L " + coords.leftInnerExtent + " " + (coords.verticalFullExtent - offset) + " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftLargeArcRadius + offset) + " 0 0 1 " + (coords.leftFullExtent + offset) + " " + coords.verticalLeftInnerExtent;
          }
          pathString += " L " + (coords.leftFullExtent + offset) + " " + (coords.sourceY - coords.leftSmallArcRadius) + " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftSmallArcRadius + offset) + " 0 0 1 " + coords.leftInnerExtent + " " + (coords.sourceY + offset) + " L " + coords.sourceX + " " + (coords.sourceY + offset) + // Walking back
          " L " + coords.sourceX + " " + (coords.sourceY - offset) + " L " + coords.leftInnerExtent + " " + (coords.sourceY - offset) + " A " + (coords.leftLargeArcRadius - offset) + " " + (coords.leftSmallArcRadius - offset) + " 0 0 0 " + (coords.leftFullExtent - offset) + " " + (coords.sourceY - coords.leftSmallArcRadius) + " L " + (coords.leftFullExtent - offset) + " " + coords.verticalLeftInnerExtent;
          if (isSourceBeforeTarget && isPathOverlapped) {
            pathString += " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftSmallArcRadius + offset) + " 0 0 0 " + (coords.leftFullExtent - offset) + " " + (coords.verticalFullExtent + offset) + "L" + (coords.rightFullExtent + offset - arrowLen) + " " + (coords.verticalFullExtent + offset) + " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftSmallArcRadius + offset) + " 0 0 0 " + (coords.rightFullExtent + offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          } else if (isSourceBeforeTarget) {
            pathString += " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftSmallArcRadius + offset) + " 0 0 1 " + (coords.leftFullExtent + offset) + " " + (coords.verticalFullExtent - offset) + " L " + (coords.rightFullExtent - offset - arrowLen) + " " + (coords.verticalFullExtent - offset) + " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftSmallArcRadius + offset) + " 0 0 1 " + (coords.rightFullExtent + offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          } else {
            pathString += " A " + (coords.leftLargeArcRadius - offset) + " " + (coords.leftLargeArcRadius - offset) + " 0 0 0 " + coords.leftInnerExtent + " " + (coords.verticalFullExtent + offset) + " L " + (coords.rightInnerExtent - arrowLen) + " " + (coords.verticalFullExtent + offset) + " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightLargeArcRadius - offset) + " 0 0 0 " + (coords.rightFullExtent + offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          }
          pathString += " L " + (coords.rightFullExtent + offset - arrowLen) + " " + (coords.targetY - coords.rightSmallArcRadius) + " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightSmallArcRadius - offset) + " 0 0 0 " + (coords.rightInnerExtent - arrowLen) + " " + (coords.targetY - offset) + " L " + (coords.targetX - arrowLen) + " " + (coords.targetY - offset) + (arrowLen > 0 ? " L " + coords.targetX + " " + coords.targetY : "") + "Z";
        } else {
          pathString = "M " + (coords.targetX - arrowLen) + " " + (coords.targetY - offset) + "  L " + (coords.rightInnerExtent - arrowLen) + " " + (coords.targetY - offset) + " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightSmallArcRadius + offset) + " 0 0 0 " + (coords.rightFullExtent - offset - arrowLen) + " " + (coords.targetY + coords.rightSmallArcRadius) + " L " + (coords.rightFullExtent - offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          if (isSourceBeforeTarget && isPathOverlapped) {
            pathString += " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightLargeArcRadius + offset) + " 0 0 0 " + (coords.rightInnerExtent - offset - arrowLen) + " " + (coords.verticalFullExtent + offset) + " L " + (coords.rightFullExtent + offset - arrowLen - (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalFullExtent + offset) + " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightLargeArcRadius + offset) + " 0 0 0 " + (coords.leftFullExtent + offset) + " " + coords.verticalLeftInnerExtent;
          } else if (isSourceBeforeTarget) {
            pathString += " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightSmallArcRadius - offset) + " 0 0 1 " + (coords.rightFullExtent - arrowLen - offset - (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalFullExtent - offset) + " L " + (coords.leftFullExtent + offset + (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalFullExtent - offset) + " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightSmallArcRadius - offset) + " 0 0 1 " + (coords.leftFullExtent + offset) + " " + coords.verticalLeftInnerExtent;
          } else {
            pathString += " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightLargeArcRadius + offset) + " 0 0 0 " + (coords.rightInnerExtent - arrowLen) + " " + (coords.verticalFullExtent + offset) + " L " + coords.leftInnerExtent + " " + (coords.verticalFullExtent + offset) + " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftLargeArcRadius + offset) + " 0 0 0 " + (coords.leftFullExtent + offset) + " " + coords.verticalLeftInnerExtent;
          }
          pathString += " L " + (coords.leftFullExtent + offset) + " " + (coords.sourceY + coords.leftSmallArcRadius) + " A " + (coords.leftLargeArcRadius + offset) + " " + (coords.leftSmallArcRadius + offset) + " 0 0 0 " + coords.leftInnerExtent + " " + (coords.sourceY - offset) + " L " + coords.sourceX + " " + (coords.sourceY - offset) + // Walking back
          " L " + coords.sourceX + " " + (coords.sourceY + offset) + " L " + coords.leftInnerExtent + " " + (coords.sourceY + offset) + " A " + (coords.leftLargeArcRadius - offset) + " " + (coords.leftSmallArcRadius - offset) + " 0 0 1 " + (coords.leftFullExtent - offset) + " " + (coords.sourceY + coords.leftSmallArcRadius) + " L " + (coords.leftFullExtent - offset) + " " + coords.verticalLeftInnerExtent;
          if (isSourceBeforeTarget && isPathOverlapped) {
            pathString += " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightSmallArcRadius - offset) + " 0 0 1 " + (coords.leftFullExtent - offset - (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalFullExtent - offset) + " L " + (coords.rightFullExtent + offset - arrowLen + (coords.rightLargeArcRadius - offset)) + " " + (coords.verticalFullExtent - offset) + " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightSmallArcRadius - offset) + " 0 0 1 " + (coords.rightFullExtent + offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          } else if (isSourceBeforeTarget) {
            pathString += " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightLargeArcRadius + offset) + " 0 0 0 " + (coords.leftFullExtent + offset) + " " + (coords.verticalFullExtent + offset) + " L " + (coords.rightFullExtent - arrowLen - offset) + " " + (coords.verticalFullExtent + offset) + " A " + (coords.rightLargeArcRadius + offset) + " " + (coords.rightLargeArcRadius + offset) + " 0 0 0 " + (coords.rightFullExtent + offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          } else {
            pathString += " A " + (coords.leftLargeArcRadius - offset) + " " + (coords.leftLargeArcRadius - offset) + " 0 0 1 " + coords.leftInnerExtent + " " + (coords.verticalFullExtent - offset) + " L " + (coords.rightInnerExtent - arrowLen) + " " + (coords.verticalFullExtent - offset) + " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightLargeArcRadius - offset) + " 0 0 1 " + (coords.rightFullExtent + offset - arrowLen) + " " + coords.verticalRightInnerExtent;
          }
          pathString += " L " + (coords.rightFullExtent + offset - arrowLen) + " " + (coords.targetY + coords.rightSmallArcRadius) + " A " + (coords.rightLargeArcRadius - offset) + " " + (coords.rightSmallArcRadius - offset) + " 0 0 1 " + (coords.rightInnerExtent - arrowLen) + " " + (coords.targetY + offset) + " L " + (coords.targetX - arrowLen) + " " + (coords.targetY + offset) + (arrowLen > 0 ? " L " + coords.targetX + " " + coords.targetY : "") + "Z";
        }
        return pathString;
      }
      function linkPath() {
        var curvature = 0.5;
        function path(d) {
          var arrowLen = d.linkArrowLength;
          if (d.link.circular) {
            return createCircularClosedPathString(d.link, arrowLen);
          } else {
            var maxArrowLength = Math.abs((d.link.target.x0 - d.link.source.x1) / 2);
            if (arrowLen > maxArrowLength) {
              arrowLen = maxArrowLength;
            }
            var x0 = d.link.source.x1;
            var x1 = d.link.target.x0 - arrowLen;
            var xi = interpolateNumber(x0, x1);
            var x2 = xi(curvature);
            var x3 = xi(1 - curvature);
            var y0a = d.link.y0 - d.link.width / 2;
            var y0b = d.link.y0 + d.link.width / 2;
            var y1a = d.link.y1 - d.link.width / 2;
            var y1b = d.link.y1 + d.link.width / 2;
            var start = "M" + x0 + "," + y0a;
            var upperCurve = "C" + x2 + "," + y0a + " " + x3 + "," + y1a + " " + x1 + "," + y1a;
            var lowerCurve = "C" + x3 + "," + y1b + " " + x2 + "," + y0b + " " + x0 + "," + y0b;
            var rightEnd = arrowLen > 0 ? "L" + (x1 + arrowLen) + "," + (y1a + d.link.width / 2) : "";
            rightEnd += "L" + x1 + "," + y1b;
            return start + upperCurve + rightEnd + lowerCurve + "Z";
          }
        }
        return path;
      }
      function nodeModel(d, n) {
        var tc = tinycolor(n.color);
        var zoneThicknessPad = c.nodePadAcross;
        var zoneLengthPad = d.nodePad / 2;
        n.dx = n.x1 - n.x0;
        n.dy = n.y1 - n.y0;
        var visibleThickness = n.dx;
        var visibleLength = Math.max(0.5, n.dy);
        var key = "node_" + n.pointNumber;
        if (n.group) {
          key = Lib.randstr();
        }
        n.trace = d.trace;
        n.curveNumber = d.trace.index;
        return {
          index: n.pointNumber,
          key,
          partOfGroup: n.partOfGroup || false,
          group: n.group,
          traceId: d.key,
          trace: d.trace,
          node: n,
          nodePad: d.nodePad,
          nodeLineColor: d.nodeLineColor,
          nodeLineWidth: d.nodeLineWidth,
          textFont: d.textFont,
          size: d.horizontal ? d.height : d.width,
          visibleWidth: Math.ceil(visibleThickness),
          visibleHeight: visibleLength,
          zoneX: -zoneThicknessPad,
          zoneY: -zoneLengthPad,
          zoneWidth: visibleThickness + 2 * zoneThicknessPad,
          zoneHeight: visibleLength + 2 * zoneLengthPad,
          labelY: d.horizontal ? n.dy / 2 + 1 : n.dx / 2 + 1,
          left: n.originalLayer === 1,
          sizeAcross: d.width,
          forceLayouts: d.forceLayouts,
          horizontal: d.horizontal,
          darkBackground: tc.getBrightness() <= 128,
          tinyColorHue: Color2.tinyRGB(tc),
          tinyColorAlpha: tc.getAlpha(),
          valueFormat: d.valueFormat,
          valueSuffix: d.valueSuffix,
          sankey: d.sankey,
          graph: d.graph,
          arrangement: d.arrangement,
          uniqueNodeLabelPathId: [d.guid, d.key, key].join("_"),
          interactionState: d.interactionState,
          figure: d
        };
      }
      function updateNodePositions(sankeyNode) {
        sankeyNode.attr("transform", function(d) {
          return strTranslate(d.node.x0.toFixed(3), d.node.y0.toFixed(3));
        });
      }
      function updateNodeShapes(sankeyNode) {
        sankeyNode.call(updateNodePositions);
      }
      function updateShapes(sankeyNode, sankeyLink) {
        sankeyNode.call(updateNodeShapes);
        sankeyLink.attr("d", linkPath());
      }
      function sizeNode(rect) {
        rect.attr("width", function(d) {
          return d.node.x1 - d.node.x0;
        }).attr("height", function(d) {
          return d.visibleHeight;
        });
      }
      function salientEnough(d) {
        return d.link.width > 1 || d.linkLineWidth > 0;
      }
      function sankeyTransform(d) {
        var offset = strTranslate(d.translateX, d.translateY);
        return offset + (d.horizontal ? "matrix(1 0 0 1 0 0)" : "matrix(0 1 1 0 0 0)");
      }
      function attachPointerEvents(selection, sankey, eventSet) {
        selection.on(".basic", null).on("mouseover.basic", function(d) {
          if (!d.interactionState.dragInProgress && !d.partOfGroup) {
            eventSet.hover(this, d, sankey);
            d.interactionState.hovered = [this, d];
          }
        }).on("mousemove.basic", function(d) {
          if (!d.interactionState.dragInProgress && !d.partOfGroup) {
            eventSet.follow(this, d);
            d.interactionState.hovered = [this, d];
          }
        }).on("mouseout.basic", function(d) {
          if (!d.interactionState.dragInProgress && !d.partOfGroup) {
            eventSet.unhover(this, d, sankey);
            d.interactionState.hovered = false;
          }
        }).on("click.basic", function(d) {
          if (d.interactionState.hovered) {
            eventSet.unhover(this, d, sankey);
            d.interactionState.hovered = false;
          }
          if (!d.interactionState.dragInProgress && !d.partOfGroup) {
            eventSet.select(this, d, sankey);
          }
        });
      }
      function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) {
        var dragBehavior = d3.behavior.drag().origin(function(d) {
          return {
            x: d.node.x0 + d.visibleWidth / 2,
            y: d.node.y0 + d.visibleHeight / 2
          };
        }).on("dragstart", function(d) {
          if (d.arrangement === "fixed") return;
          Lib.ensureSingle(gd._fullLayout._infolayer, "g", "dragcover", function(s) {
            gd._fullLayout._dragCover = s;
          });
          Lib.raiseToTop(this);
          d.interactionState.dragInProgress = d.node;
          saveCurrentDragPosition(d.node);
          if (d.interactionState.hovered) {
            callbacks.nodeEvents.unhover.apply(0, d.interactionState.hovered);
            d.interactionState.hovered = false;
          }
          if (d.arrangement === "snap") {
            var forceKey = d.traceId + "|" + d.key;
            if (d.forceLayouts[forceKey]) {
              d.forceLayouts[forceKey].alpha(1);
            } else {
              attachForce(sankeyNode, forceKey, d, gd);
            }
            startForce(sankeyNode, sankeyLink, d, forceKey, gd);
          }
        }).on("drag", function(d) {
          if (d.arrangement === "fixed") return;
          var x = d3.event.x;
          var y = d3.event.y;
          if (d.arrangement === "snap") {
            d.node.x0 = x - d.visibleWidth / 2;
            d.node.x1 = x + d.visibleWidth / 2;
            d.node.y0 = y - d.visibleHeight / 2;
            d.node.y1 = y + d.visibleHeight / 2;
          } else {
            if (d.arrangement === "freeform") {
              d.node.x0 = x - d.visibleWidth / 2;
              d.node.x1 = x + d.visibleWidth / 2;
            }
            y = Math.max(0, Math.min(d.size - d.visibleHeight / 2, y));
            d.node.y0 = y - d.visibleHeight / 2;
            d.node.y1 = y + d.visibleHeight / 2;
          }
          saveCurrentDragPosition(d.node);
          if (d.arrangement !== "snap") {
            d.sankey.update(d.graph);
            updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
          }
        }).on("dragend", function(d) {
          if (d.arrangement === "fixed") return;
          d.interactionState.dragInProgress = false;
          for (var i = 0; i < d.node.childrenNodes.length; i++) {
            d.node.childrenNodes[i].x = d.node.x;
            d.node.childrenNodes[i].y = d.node.y;
          }
          if (d.arrangement !== "snap") persistFinalNodePositions(d, gd);
        });
        sankeyNode.on(".drag", null).call(dragBehavior);
      }
      function attachForce(sankeyNode, forceKey, d, gd) {
        switchToForceFormat(d.graph.nodes);
        var nodes = d.graph.nodes.filter(function(n) {
          return n.originalX === d.node.originalX;
        }).filter(function(n) {
          return !n.partOfGroup;
        });
        d.forceLayouts[forceKey] = d3Force.forceSimulation(nodes).alphaDecay(0).force("collide", d3Force.forceCollide().radius(function(n) {
          return n.dy / 2 + d.nodePad / 2;
        }).strength(1).iterations(c.forceIterations)).force("constrain", snappingForce(sankeyNode, forceKey, nodes, d, gd)).stop();
      }
      function startForce(sankeyNode, sankeyLink, d, forceKey, gd) {
        window.requestAnimationFrame(function faster() {
          var i;
          for (i = 0; i < c.forceTicksPerFrame; i++) {
            d.forceLayouts[forceKey].tick();
          }
          var nodes = d.graph.nodes;
          switchToSankeyFormat(nodes);
          d.sankey.update(d.graph);
          updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink);
          if (d.forceLayouts[forceKey].alpha() > 0) {
            window.requestAnimationFrame(faster);
          } else {
            var x = d.node.originalX;
            d.node.x0 = x - d.visibleWidth / 2;
            d.node.x1 = x + d.visibleWidth / 2;
            persistFinalNodePositions(d, gd);
          }
        });
      }
      function snappingForce(sankeyNode, forceKey, nodes, d) {
        return function _snappingForce() {
          var maxVelocity = 0;
          for (var i = 0; i < nodes.length; i++) {
            var n = nodes[i];
            if (n === d.interactionState.dragInProgress) {
              n.x = n.lastDraggedX;
              n.y = n.lastDraggedY;
            } else {
              n.vx = (n.originalX - n.x) / c.forceTicksPerFrame;
              n.y = Math.min(d.size - n.dy / 2, Math.max(n.dy / 2, n.y));
            }
            maxVelocity = Math.max(maxVelocity, Math.abs(n.vx), Math.abs(n.vy));
          }
          if (!d.interactionState.dragInProgress && maxVelocity < 0.1 && d.forceLayouts[forceKey].alpha() > 0) {
            d.forceLayouts[forceKey].alpha(0);
          }
        };
      }
      function persistFinalNodePositions(d, gd) {
        var x = [];
        var y = [];
        for (var i = 0; i < d.graph.nodes.length; i++) {
          var nodeX = (d.graph.nodes[i].x0 + d.graph.nodes[i].x1) / 2;
          var nodeY = (d.graph.nodes[i].y0 + d.graph.nodes[i].y1) / 2;
          x.push(nodeX / d.figure.width);
          y.push(nodeY / d.figure.height);
        }
        Registry.call("_guiRestyle", gd, {
          "node.x": [x],
          "node.y": [y]
        }, d.trace.index).then(function() {
          if (gd._fullLayout._dragCover) gd._fullLayout._dragCover.remove();
        });
      }
      function persistOriginalPlace(nodes) {
        var distinctLayerPositions = [];
        var i;
        for (i = 0; i < nodes.length; i++) {
          nodes[i].originalX = (nodes[i].x0 + nodes[i].x1) / 2;
          nodes[i].originalY = (nodes[i].y0 + nodes[i].y1) / 2;
          if (distinctLayerPositions.indexOf(nodes[i].originalX) === -1) {
            distinctLayerPositions.push(nodes[i].originalX);
          }
        }
        distinctLayerPositions.sort(function(a, b) {
          return a - b;
        });
        for (i = 0; i < nodes.length; i++) {
          nodes[i].originalLayerIndex = distinctLayerPositions.indexOf(nodes[i].originalX);
          nodes[i].originalLayer = nodes[i].originalLayerIndex / (distinctLayerPositions.length - 1);
        }
      }
      function saveCurrentDragPosition(d) {
        d.lastDraggedX = d.x0 + d.dx / 2;
        d.lastDraggedY = d.y0 + d.dy / 2;
      }
      function sameLayer(d) {
        return function(n) {
          return n.node.originalX === d.node.originalX;
        };
      }
      function switchToForceFormat(nodes) {
        for (var i = 0; i < nodes.length; i++) {
          nodes[i].y = (nodes[i].y0 + nodes[i].y1) / 2;
          nodes[i].x = (nodes[i].x0 + nodes[i].x1) / 2;
        }
      }
      function switchToSankeyFormat(nodes) {
        for (var i = 0; i < nodes.length; i++) {
          nodes[i].y0 = nodes[i].y - nodes[i].dy / 2;
          nodes[i].y1 = nodes[i].y0 + nodes[i].dy;
          nodes[i].x0 = nodes[i].x - nodes[i].dx / 2;
          nodes[i].x1 = nodes[i].x0 + nodes[i].dx;
        }
      }
      module.exports = function(gd, svg, calcData, layout, callbacks) {
        var isStatic = gd._context.staticPlot;
        var firstRender = false;
        Lib.ensureSingle(gd._fullLayout._infolayer, "g", "first-render", function() {
          firstRender = true;
        });
        var dragcover = gd._fullLayout._dragCover;
        var styledData = calcData.filter(function(d) {
          return unwrap(d).trace.visible;
        }).map(sankeyModel.bind(null, layout));
        var sankey = svg.selectAll("." + c.cn.sankey).data(styledData, keyFun);
        sankey.exit().remove();
        sankey.enter().append("g").classed(c.cn.sankey, true).style("box-sizing", "content-box").style("position", "absolute").style("left", 0).style("shape-rendering", "geometricPrecision").style("pointer-events", isStatic ? "none" : "auto").attr("transform", sankeyTransform);
        sankey.each(function(d, i) {
          gd._fullData[i]._sankey = d;
          var dragboxClassName = "bgsankey-" + d.trace.uid + "-" + i;
          Lib.ensureSingle(gd._fullLayout._draggers, "rect", dragboxClassName);
          gd._fullData[i]._bgRect = d3.select("." + dragboxClassName);
          gd._fullData[i]._bgRect.style("pointer-events", isStatic ? "none" : "all").attr("width", d.width).attr("height", d.height).attr("x", d.translateX).attr("y", d.translateY).classed("bgsankey", true).style({ fill: "transparent", "stroke-width": 0 });
        });
        sankey.transition().ease(c.ease).duration(c.duration).attr("transform", sankeyTransform);
        var sankeyLinks = sankey.selectAll("." + c.cn.sankeyLinks).data(repeat, keyFun);
        sankeyLinks.enter().append("g").classed(c.cn.sankeyLinks, true).style("fill", "none");
        var sankeyLink = sankeyLinks.selectAll("." + c.cn.sankeyLink).data(function(d) {
          var links = d.graph.links;
          return links.filter(function(l) {
            return l.value;
          }).map(linkModel.bind(null, d));
        }, keyFun);
        sankeyLink.enter().append("path").classed(c.cn.sankeyLink, true).call(attachPointerEvents, sankey, callbacks.linkEvents);
        sankeyLink.style("stroke", function(d) {
          return salientEnough(d) ? Color2.tinyRGB(tinycolor(d.linkLineColor)) : d.tinyColorHue;
        }).style("stroke-opacity", function(d) {
          return salientEnough(d) ? Color2.opacity(d.linkLineColor) : d.tinyColorAlpha;
        }).style("fill", function(d) {
          return d.tinyColorHue;
        }).style("fill-opacity", function(d) {
          return d.tinyColorAlpha;
        }).style("stroke-width", function(d) {
          return salientEnough(d) ? d.linkLineWidth : 1;
        }).attr("d", linkPath());
        sankeyLink.style("opacity", function() {
          return gd._context.staticPlot || firstRender || dragcover ? 1 : 0;
        }).transition().ease(c.ease).duration(c.duration).style("opacity", 1);
        sankeyLink.exit().transition().ease(c.ease).duration(c.duration).style("opacity", 0).remove();
        var sankeyNodeSet = sankey.selectAll("." + c.cn.sankeyNodeSet).data(repeat, keyFun);
        sankeyNodeSet.enter().append("g").classed(c.cn.sankeyNodeSet, true);
        sankeyNodeSet.style("cursor", function(d) {
          switch (d.arrangement) {
            case "fixed":
              return "default";
            case "perpendicular":
              return "ns-resize";
            default:
              return "move";
          }
        });
        var sankeyNode = sankeyNodeSet.selectAll("." + c.cn.sankeyNode).data(function(d) {
          var nodes = d.graph.nodes;
          persistOriginalPlace(nodes);
          return nodes.map(nodeModel.bind(null, d));
        }, keyFun);
        sankeyNode.enter().append("g").classed(c.cn.sankeyNode, true).call(updateNodePositions).style("opacity", function(n) {
          return (gd._context.staticPlot || firstRender) && !n.partOfGroup ? 1 : 0;
        });
        sankeyNode.call(attachPointerEvents, sankey, callbacks.nodeEvents).call(attachDragHandler, sankeyLink, callbacks, gd);
        sankeyNode.transition().ease(c.ease).duration(c.duration).call(updateNodePositions).style("opacity", function(n) {
          return n.partOfGroup ? 0 : 1;
        });
        sankeyNode.exit().transition().ease(c.ease).duration(c.duration).style("opacity", 0).remove();
        var nodeRect = sankeyNode.selectAll("." + c.cn.nodeRect).data(repeat);
        nodeRect.enter().append("rect").classed(c.cn.nodeRect, true).call(sizeNode);
        nodeRect.style("stroke-width", function(d) {
          return d.nodeLineWidth;
        }).style("stroke", function(d) {
          return Color2.tinyRGB(tinycolor(d.nodeLineColor));
        }).style("stroke-opacity", function(d) {
          return Color2.opacity(d.nodeLineColor);
        }).style("fill", function(d) {
          return d.tinyColorHue;
        }).style("fill-opacity", function(d) {
          return d.tinyColorAlpha;
        });
        nodeRect.transition().ease(c.ease).duration(c.duration).call(sizeNode);
        var nodeLabel = sankeyNode.selectAll("." + c.cn.nodeLabel).data(repeat);
        nodeLabel.enter().append("text").classed(c.cn.nodeLabel, true).style("cursor", "default");
        nodeLabel.attr("data-notex", 1).text(function(d) {
          return d.node.label;
        }).each(function(d) {
          var e = d3.select(this);
          Drawing.font(e, d.textFont);
          svgTextUtils.convertToTspans(e, gd);
        }).attr("text-anchor", function(d) {
          return d.horizontal && d.left ? "end" : "start";
        }).attr("transform", function(d) {
          var e = d3.select(this);
          var nLines = svgTextUtils.lineCount(e);
          var blockHeight = d.textFont.size * ((nLines - 1) * LINE_SPACING - CAP_SHIFT);
          var posX = d.nodeLineWidth / 2 + TEXTPAD;
          var posY = ((d.horizontal ? d.visibleHeight : d.visibleWidth) - blockHeight) / 2;
          if (d.horizontal) {
            if (d.left) {
              posX = -posX;
            } else {
              posX += d.visibleWidth;
            }
          }
          var flipText = d.horizontal ? "" : "scale(-1,1)" + strRotate(90);
          return strTranslate(
            d.horizontal ? posX : posY,
            d.horizontal ? posY : posX
          ) + flipText;
        });
        nodeLabel.transition().ease(c.ease).duration(c.duration);
      };
    }
  });

  // src/traces/sankey/plot.js
  var require_plot29 = __commonJS({
    "src/traces/sankey/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      var numberFormat = Lib.numberFormat;
      var render = require_render();
      var Fx = require_fx();
      var Color2 = require_color();
      var cn = require_constants29().cn;
      var _ = Lib._;
      function renderableValuePresent(d) {
        return d !== "";
      }
      function ownTrace(selection, d) {
        return selection.filter(function(s) {
          return s.key === d.traceId;
        });
      }
      function makeTranslucent(element, alpha) {
        d3.select(element).select("path").style("fill-opacity", alpha);
        d3.select(element).select("rect").style("fill-opacity", alpha);
      }
      function makeTextContrasty(element) {
        d3.select(element).select("text.name").style("fill", "black");
      }
      function relatedLinks(d) {
        return function(l) {
          return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
        };
      }
      function relatedNodes(l) {
        return function(d) {
          return d.node.sourceLinks.indexOf(l.link) !== -1 || d.node.targetLinks.indexOf(l.link) !== -1;
        };
      }
      function nodeHoveredStyle(sankeyNode, d, sankey) {
        if (d && sankey) {
          ownTrace(sankey, d).selectAll("." + cn.sankeyLink).filter(relatedLinks(d)).call(linkHoveredStyle.bind(0, d, sankey, false));
        }
      }
      function nodeNonHoveredStyle(sankeyNode, d, sankey) {
        if (d && sankey) {
          ownTrace(sankey, d).selectAll("." + cn.sankeyLink).filter(relatedLinks(d)).call(linkNonHoveredStyle.bind(0, d, sankey, false));
        }
      }
      function linkHoveredStyle(d, sankey, visitNodes, sankeyLink) {
        sankeyLink.style("fill", function(l) {
          if (!l.link.concentrationscale) {
            return l.tinyColorHoverHue;
          }
        }).style("fill-opacity", function(l) {
          if (!l.link.concentrationscale) {
            return l.tinyColorHoverAlpha;
          }
        });
        sankeyLink.each(function(curLink) {
          var label = curLink.link.label;
          if (label !== "") {
            ownTrace(sankey, d).selectAll("." + cn.sankeyLink).filter(function(l) {
              return l.link.label === label;
            }).style("fill", function(l) {
              if (!l.link.concentrationscale) {
                return l.tinyColorHoverHue;
              }
            }).style("fill-opacity", function(l) {
              if (!l.link.concentrationscale) {
                return l.tinyColorHoverAlpha;
              }
            });
          }
        });
        if (visitNodes) {
          ownTrace(sankey, d).selectAll("." + cn.sankeyNode).filter(relatedNodes(d)).call(nodeHoveredStyle);
        }
      }
      function linkNonHoveredStyle(d, sankey, visitNodes, sankeyLink) {
        sankeyLink.style("fill", function(l) {
          return l.tinyColorHue;
        }).style("fill-opacity", function(l) {
          return l.tinyColorAlpha;
        });
        sankeyLink.each(function(curLink) {
          var label = curLink.link.label;
          if (label !== "") {
            ownTrace(sankey, d).selectAll("." + cn.sankeyLink).filter(function(l) {
              return l.link.label === label;
            }).style("fill", function(l) {
              return l.tinyColorHue;
            }).style("fill-opacity", function(l) {
              return l.tinyColorAlpha;
            });
          }
        });
        if (visitNodes) {
          ownTrace(sankey, d).selectAll(cn.sankeyNode).filter(relatedNodes(d)).call(nodeNonHoveredStyle);
        }
      }
      function castHoverOption(trace, attr) {
        var labelOpts = trace.hoverlabel || {};
        var val = Lib.nestedProperty(labelOpts, attr).get();
        return Array.isArray(val) ? false : val;
      }
      module.exports = function plot(gd, calcData) {
        var fullLayout = gd._fullLayout;
        var svg = fullLayout._paper;
        var size = fullLayout._size;
        for (var i = 0; i < gd._fullData.length; i++) {
          if (!gd._fullData[i].visible) continue;
          if (gd._fullData[i].type !== cn.sankey) continue;
          if (!gd._fullData[i]._viewInitial) {
            var node = gd._fullData[i].node;
            gd._fullData[i]._viewInitial = {
              node: {
                groups: node.groups.slice(),
                x: node.x.slice(),
                y: node.y.slice()
              }
            };
          }
        }
        var linkSelect = function(element, d) {
          var evt = d.link;
          evt.originalEvent = d3.event;
          gd._hoverdata = [evt];
          Fx.click(gd, { target: true });
        };
        var linkHover = function(element, d, sankey) {
          if (gd._fullLayout.hovermode === false) return;
          d3.select(element).call(linkHoveredStyle.bind(0, d, sankey, true));
          if (d.link.trace.link.hoverinfo !== "skip") {
            d.link.fullData = d.link.trace;
            gd.emit("plotly_hover", {
              event: d3.event,
              points: [d.link]
            });
          }
        };
        var sourceLabel = _(gd, "source:") + " ";
        var targetLabel = _(gd, "target:") + " ";
        var concentrationLabel = _(gd, "concentration:") + " ";
        var incomingLabel = _(gd, "incoming flow count:") + " ";
        var outgoingLabel = _(gd, "outgoing flow count:") + " ";
        var linkHoverFollow = function(element, d) {
          if (gd._fullLayout.hovermode === false) return;
          var obj = d.link.trace.link;
          if (obj.hoverinfo === "none" || obj.hoverinfo === "skip") return;
          var hoverItems = [];
          function hoverCenterPosition(link2) {
            var hoverCenterX, hoverCenterY;
            if (link2.circular) {
              hoverCenterX = (link2.circularPathData.leftInnerExtent + link2.circularPathData.rightInnerExtent) / 2;
              hoverCenterY = link2.circularPathData.verticalFullExtent;
            } else {
              hoverCenterX = (link2.source.x1 + link2.target.x0) / 2;
              hoverCenterY = (link2.y0 + link2.y1) / 2;
            }
            var center = [hoverCenterX, hoverCenterY];
            if (link2.trace.orientation === "v") center.reverse();
            center[0] += d.parent.translateX;
            center[1] += d.parent.translateY;
            return center;
          }
          var anchorIndex = 0;
          for (var i2 = 0; i2 < d.flow.links.length; i2++) {
            var link = d.flow.links[i2];
            if (gd._fullLayout.hovermode === "closest" && d.link.pointNumber !== link.pointNumber) continue;
            if (d.link.pointNumber === link.pointNumber) anchorIndex = i2;
            link.fullData = link.trace;
            obj = d.link.trace.link;
            var hoverCenter = hoverCenterPosition(link);
            var hovertemplateLabels = { valueLabel: numberFormat(d.valueFormat)(link.value) + d.valueSuffix };
            hoverItems.push({
              x: hoverCenter[0],
              y: hoverCenter[1],
              name: hovertemplateLabels.valueLabel,
              text: [
                link.label || "",
                sourceLabel + link.source.label,
                targetLabel + link.target.label,
                link.concentrationscale ? concentrationLabel + numberFormat("%0.2f")(link.flow.labelConcentration) : ""
              ].filter(renderableValuePresent).join("<br>"),
              color: castHoverOption(obj, "bgcolor") || Color2.addOpacity(link.color, 1),
              borderColor: castHoverOption(obj, "bordercolor"),
              fontFamily: castHoverOption(obj, "font.family"),
              fontSize: castHoverOption(obj, "font.size"),
              fontColor: castHoverOption(obj, "font.color"),
              fontWeight: castHoverOption(obj, "font.weight"),
              fontStyle: castHoverOption(obj, "font.style"),
              fontVariant: castHoverOption(obj, "font.variant"),
              fontTextcase: castHoverOption(obj, "font.textcase"),
              fontLineposition: castHoverOption(obj, "font.lineposition"),
              fontShadow: castHoverOption(obj, "font.shadow"),
              nameLength: castHoverOption(obj, "namelength"),
              textAlign: castHoverOption(obj, "align"),
              idealAlign: d3.event.x < hoverCenter[0] ? "right" : "left",
              hovertemplate: obj.hovertemplate,
              hovertemplateLabels,
              eventData: [link]
            });
          }
          var tooltips = Fx.loneHover(hoverItems, {
            container: fullLayout._hoverlayer.node(),
            outerContainer: fullLayout._paper.node(),
            gd,
            anchorIndex
          });
          tooltips.each(function() {
            var tooltip = this;
            if (!d.link.concentrationscale) {
              makeTranslucent(tooltip, 0.65);
            }
            makeTextContrasty(tooltip);
          });
        };
        var linkUnhover = function(element, d, sankey) {
          if (gd._fullLayout.hovermode === false) return;
          d3.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true));
          if (d.link.trace.link.hoverinfo !== "skip") {
            d.link.fullData = d.link.trace;
            gd.emit("plotly_unhover", {
              event: d3.event,
              points: [d.link]
            });
          }
          Fx.loneUnhover(fullLayout._hoverlayer.node());
        };
        var nodeSelect = function(element, d, sankey) {
          var evt = d.node;
          evt.originalEvent = d3.event;
          gd._hoverdata = [evt];
          d3.select(element).call(nodeNonHoveredStyle, d, sankey);
          Fx.click(gd, { target: true });
        };
        var nodeHover = function(element, d, sankey) {
          if (gd._fullLayout.hovermode === false) return;
          d3.select(element).call(nodeHoveredStyle, d, sankey);
          if (d.node.trace.node.hoverinfo !== "skip") {
            d.node.fullData = d.node.trace;
            gd.emit("plotly_hover", {
              event: d3.event,
              points: [d.node]
            });
          }
        };
        var nodeHoverFollow = function(element, d) {
          if (gd._fullLayout.hovermode === false) return;
          var obj = d.node.trace.node;
          if (obj.hoverinfo === "none" || obj.hoverinfo === "skip") return;
          var nodeRect = d3.select(element).select("." + cn.nodeRect);
          var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect();
          var boundingBox = nodeRect.node().getBoundingClientRect();
          var hoverCenterX0 = boundingBox.left - 2 - rootBBox.left;
          var hoverCenterX1 = boundingBox.right + 2 - rootBBox.left;
          var hoverCenterY = boundingBox.top + boundingBox.height / 4 - rootBBox.top;
          var hovertemplateLabels = { valueLabel: numberFormat(d.valueFormat)(d.node.value) + d.valueSuffix };
          d.node.fullData = d.node.trace;
          gd._fullLayout._calcInverseTransform(gd);
          var scaleX = gd._fullLayout._invScaleX;
          var scaleY = gd._fullLayout._invScaleY;
          var tooltip = Fx.loneHover({
            x0: scaleX * hoverCenterX0,
            x1: scaleX * hoverCenterX1,
            y: scaleY * hoverCenterY,
            name: numberFormat(d.valueFormat)(d.node.value) + d.valueSuffix,
            text: [
              d.node.label,
              incomingLabel + d.node.targetLinks.length,
              outgoingLabel + d.node.sourceLinks.length
            ].filter(renderableValuePresent).join("<br>"),
            color: castHoverOption(obj, "bgcolor") || d.tinyColorHue,
            borderColor: castHoverOption(obj, "bordercolor"),
            fontFamily: castHoverOption(obj, "font.family"),
            fontSize: castHoverOption(obj, "font.size"),
            fontColor: castHoverOption(obj, "font.color"),
            fontWeight: castHoverOption(obj, "font.weight"),
            fontStyle: castHoverOption(obj, "font.style"),
            fontVariant: castHoverOption(obj, "font.variant"),
            fontTextcase: castHoverOption(obj, "font.textcase"),
            fontLineposition: castHoverOption(obj, "font.lineposition"),
            fontShadow: castHoverOption(obj, "font.shadow"),
            nameLength: castHoverOption(obj, "namelength"),
            textAlign: castHoverOption(obj, "align"),
            idealAlign: "left",
            hovertemplate: obj.hovertemplate,
            hovertemplateLabels,
            eventData: [d.node]
          }, {
            container: fullLayout._hoverlayer.node(),
            outerContainer: fullLayout._paper.node(),
            gd
          });
          makeTranslucent(tooltip, 0.85);
          makeTextContrasty(tooltip);
        };
        var nodeUnhover = function(element, d, sankey) {
          if (gd._fullLayout.hovermode === false) return;
          d3.select(element).call(nodeNonHoveredStyle, d, sankey);
          if (d.node.trace.node.hoverinfo !== "skip") {
            d.node.fullData = d.node.trace;
            gd.emit("plotly_unhover", {
              event: d3.event,
              points: [d.node]
            });
          }
          Fx.loneUnhover(fullLayout._hoverlayer.node());
        };
        render(
          gd,
          svg,
          calcData,
          {
            width: size.w,
            height: size.h,
            margin: {
              t: size.t,
              r: size.r,
              b: size.b,
              l: size.l
            }
          },
          {
            linkEvents: {
              hover: linkHover,
              follow: linkHoverFollow,
              unhover: linkUnhover,
              select: linkSelect
            },
            nodeEvents: {
              hover: nodeHover,
              follow: nodeHoverFollow,
              unhover: nodeUnhover,
              select: nodeSelect
            }
          }
        );
      };
    }
  });

  // src/traces/sankey/base_plot.js
  var require_base_plot9 = __commonJS({
    "src/traces/sankey/base_plot.js"(exports) {
      "use strict";
      var overrideAll = require_edit_types().overrideAll;
      var getModuleCalcData = require_get_data().getModuleCalcData;
      var plot = require_plot29();
      var fxAttrs = require_layout_attributes();
      var setCursor = require_setcursor();
      var dragElement = require_dragelement();
      var prepSelect = require_selections().prepSelect;
      var Lib = require_lib();
      var Registry = require_registry();
      var SANKEY = "sankey";
      exports.name = SANKEY;
      exports.baseLayoutAttrOverrides = overrideAll({
        hoverlabel: fxAttrs.hoverlabel
      }, "plot", "nested");
      exports.plot = function(gd) {
        var calcData = getModuleCalcData(gd.calcdata, SANKEY)[0];
        plot(gd, calcData);
        exports.updateFx(gd);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var hadPlot = oldFullLayout._has && oldFullLayout._has(SANKEY);
        var hasPlot = newFullLayout._has && newFullLayout._has(SANKEY);
        if (hadPlot && !hasPlot) {
          oldFullLayout._paperdiv.selectAll(".sankey").remove();
          oldFullLayout._paperdiv.selectAll(".bgsankey").remove();
        }
      };
      exports.updateFx = function(gd) {
        for (var i = 0; i < gd._fullData.length; i++) {
          subplotUpdateFx(gd, i);
        }
      };
      function subplotUpdateFx(gd, index) {
        var trace = gd._fullData[index];
        var fullLayout = gd._fullLayout;
        var dragMode = fullLayout.dragmode;
        var cursor = fullLayout.dragmode === "pan" ? "move" : "crosshair";
        var bgRect = trace._bgRect;
        if (!bgRect) return;
        if (dragMode === "pan" || dragMode === "zoom") return;
        setCursor(bgRect, cursor);
        var xaxis = {
          _id: "x",
          c2p: Lib.identity,
          _offset: trace._sankey.translateX,
          _length: trace._sankey.width
        };
        var yaxis = {
          _id: "y",
          c2p: Lib.identity,
          _offset: trace._sankey.translateY,
          _length: trace._sankey.height
        };
        var dragOptions = {
          gd,
          element: bgRect.node(),
          plotinfo: {
            id: index,
            xaxis,
            yaxis,
            fillRangeItems: Lib.noop
          },
          subplot: index,
          // create mock x/y axes for hover routine
          xaxes: [xaxis],
          yaxes: [yaxis],
          doneFnCompleted: function(selection) {
            var traceNow = gd._fullData[index];
            var newGroups;
            var oldGroups = traceNow.node.groups.slice();
            var newGroup = [];
            function findNode(pt) {
              var nodes = traceNow._sankey.graph.nodes;
              for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].pointNumber === pt) return nodes[i];
              }
            }
            for (var j = 0; j < selection.length; j++) {
              var node = findNode(selection[j].pointNumber);
              if (!node) continue;
              if (node.group) {
                for (var k = 0; k < node.childrenNodes.length; k++) {
                  newGroup.push(node.childrenNodes[k].pointNumber);
                }
                oldGroups[node.pointNumber - traceNow.node._count] = false;
              } else {
                newGroup.push(node.pointNumber);
              }
            }
            newGroups = oldGroups.filter(Boolean).concat([newGroup]);
            Registry.call("_guiRestyle", gd, {
              "node.groups": [newGroups]
            }, index);
          }
        };
        dragOptions.prepFn = function(e, startX, startY) {
          prepSelect(e, startX, startY, dragOptions, dragMode);
        };
        dragElement.init(dragOptions);
      }
    }
  });

  // src/traces/sankey/select.js
  var require_select11 = __commonJS({
    "src/traces/sankey/select.js"(exports, module) {
      "use strict";
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var selection = [];
        var fullData = cd[0].trace;
        var nodes = fullData._sankey.graph.nodes;
        for (var i = 0; i < nodes.length; i++) {
          var node = nodes[i];
          if (node.partOfGroup) continue;
          var pos = [(node.x0 + node.x1) / 2, (node.y0 + node.y1) / 2];
          if (fullData.orientation === "v") pos.reverse();
          if (selectionTester && selectionTester.contains(pos, false, i, searchInfo)) {
            selection.push({
              pointNumber: node.pointNumber
              // TODO: add eventData
            });
          }
        }
        return selection;
      };
    }
  });

  // src/traces/sankey/index.js
  var require_sankey = __commonJS({
    "src/traces/sankey/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes60(),
        supplyDefaults: require_defaults56(),
        calc: require_calc35(),
        plot: require_plot29(),
        moduleType: "trace",
        name: "sankey",
        basePlotModule: require_base_plot9(),
        selectPoints: require_select11(),
        categories: ["noOpacity"],
        meta: {}
      };
    }
  });

  // lib/sankey.js
  var require_sankey2 = __commonJS({
    "lib/sankey.js"(exports, module) {
      "use strict";
      module.exports = require_sankey();
    }
  });

  // src/traces/indicator/base_plot.js
  var require_base_plot10 = __commonJS({
    "src/traces/indicator/base_plot.js"(exports) {
      "use strict";
      var plots = require_plots();
      exports.name = "indicator";
      exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
        plots.plotBasePlot(exports.name, gd, traces, transitionOpts, makeOnCompleteCallback);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        plots.cleanBasePlot(exports.name, newFullData, newFullLayout, oldFullData, oldFullLayout);
      };
    }
  });

  // src/traces/indicator/attributes.js
  var require_attributes61 = __commonJS({
    "src/traces/indicator/attributes.js"(exports, module) {
      "use strict";
      var extendFlat = require_extend().extendFlat;
      var extendDeep = require_extend().extendDeep;
      var overrideAll = require_edit_types().overrideAll;
      var fontAttrs = require_font_attributes();
      var colorAttrs = require_attributes3();
      var domainAttrs = require_domain().attributes;
      var axesAttrs = require_layout_attributes4();
      var templatedArray = require_plot_template().templatedArray;
      var delta = require_delta();
      var descriptionOnlyNumbers = require_axis_format_attributes().descriptionOnlyNumbers;
      var textFontAttrs = fontAttrs({
        editType: "plot",
        colorEditType: "plot"
      });
      var gaugeBarAttrs = {
        color: {
          valType: "color",
          editType: "plot"
        },
        line: {
          color: {
            valType: "color",
            dflt: colorAttrs.defaultLine,
            editType: "plot"
          },
          width: {
            valType: "number",
            min: 0,
            dflt: 0,
            editType: "plot"
          },
          editType: "calc"
        },
        thickness: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 1,
          editType: "plot"
        },
        editType: "calc"
      };
      var rangeAttr = {
        valType: "info_array",
        items: [
          { valType: "number", editType: "plot" },
          { valType: "number", editType: "plot" }
        ],
        editType: "plot"
      };
      var stepsAttrs = templatedArray("step", extendDeep({}, gaugeBarAttrs, {
        range: rangeAttr
      }));
      module.exports = {
        mode: {
          valType: "flaglist",
          editType: "calc",
          flags: ["number", "delta", "gauge"],
          dflt: "number"
        },
        value: {
          valType: "number",
          editType: "calc",
          anim: true
        },
        align: {
          valType: "enumerated",
          values: ["left", "center", "right"],
          editType: "plot"
        },
        // position
        domain: domainAttrs({ name: "indicator", trace: true, editType: "calc" }),
        title: {
          text: {
            valType: "string",
            editType: "plot"
          },
          align: {
            valType: "enumerated",
            values: ["left", "center", "right"],
            editType: "plot"
          },
          font: extendFlat({}, textFontAttrs, {}),
          editType: "plot"
        },
        number: {
          valueformat: {
            valType: "string",
            dflt: "",
            editType: "plot",
            description: descriptionOnlyNumbers("value")
          },
          font: extendFlat({}, textFontAttrs, {}),
          prefix: {
            valType: "string",
            dflt: "",
            editType: "plot"
          },
          suffix: {
            valType: "string",
            dflt: "",
            editType: "plot"
          },
          editType: "plot"
        },
        delta: {
          reference: {
            valType: "number",
            editType: "calc"
          },
          position: {
            valType: "enumerated",
            values: ["top", "bottom", "left", "right"],
            dflt: "bottom",
            editType: "plot"
          },
          relative: {
            valType: "boolean",
            editType: "plot",
            dflt: false
          },
          valueformat: {
            valType: "string",
            editType: "plot",
            description: descriptionOnlyNumbers("value")
          },
          increasing: {
            symbol: {
              valType: "string",
              dflt: delta.INCREASING.SYMBOL,
              editType: "plot"
            },
            color: {
              valType: "color",
              dflt: delta.INCREASING.COLOR,
              editType: "plot"
            },
            // TODO: add attribute to show sign
            editType: "plot"
          },
          decreasing: {
            symbol: {
              valType: "string",
              dflt: delta.DECREASING.SYMBOL,
              editType: "plot"
            },
            color: {
              valType: "color",
              dflt: delta.DECREASING.COLOR,
              editType: "plot"
            },
            // TODO: add attribute to hide sign
            editType: "plot"
          },
          font: extendFlat({}, textFontAttrs, {}),
          prefix: {
            valType: "string",
            dflt: "",
            editType: "plot"
          },
          suffix: {
            valType: "string",
            dflt: "",
            editType: "plot"
          },
          editType: "calc"
        },
        gauge: {
          shape: {
            valType: "enumerated",
            editType: "plot",
            dflt: "angular",
            values: ["angular", "bullet"]
          },
          bar: extendDeep({}, gaugeBarAttrs, {
            color: { dflt: "green" }
          }),
          // Background of the gauge
          bgcolor: {
            valType: "color",
            editType: "plot"
          },
          bordercolor: {
            valType: "color",
            dflt: colorAttrs.defaultLine,
            editType: "plot"
          },
          borderwidth: {
            valType: "number",
            min: 0,
            dflt: 1,
            editType: "plot"
          },
          axis: overrideAll({
            range: rangeAttr,
            visible: extendFlat({}, axesAttrs.visible, {
              dflt: true
            }),
            // tick and title properties named and function exactly as in axes
            tickmode: axesAttrs.minor.tickmode,
            nticks: axesAttrs.nticks,
            tick0: axesAttrs.tick0,
            dtick: axesAttrs.dtick,
            tickvals: axesAttrs.tickvals,
            ticktext: axesAttrs.ticktext,
            ticks: extendFlat({}, axesAttrs.ticks, { dflt: "outside" }),
            ticklen: axesAttrs.ticklen,
            tickwidth: axesAttrs.tickwidth,
            tickcolor: axesAttrs.tickcolor,
            ticklabelstep: axesAttrs.ticklabelstep,
            showticklabels: axesAttrs.showticklabels,
            labelalias: axesAttrs.labelalias,
            tickfont: fontAttrs({}),
            tickangle: axesAttrs.tickangle,
            tickformat: axesAttrs.tickformat,
            tickformatstops: axesAttrs.tickformatstops,
            tickprefix: axesAttrs.tickprefix,
            showtickprefix: axesAttrs.showtickprefix,
            ticksuffix: axesAttrs.ticksuffix,
            showticksuffix: axesAttrs.showticksuffix,
            separatethousands: axesAttrs.separatethousands,
            exponentformat: axesAttrs.exponentformat,
            minexponent: axesAttrs.minexponent,
            showexponent: axesAttrs.showexponent,
            editType: "plot"
          }, "plot"),
          // Steps (or ranges) and thresholds
          steps: stepsAttrs,
          threshold: {
            line: {
              color: extendFlat({}, gaugeBarAttrs.line.color, {}),
              width: extendFlat({}, gaugeBarAttrs.line.width, {
                dflt: 1
              }),
              editType: "plot"
            },
            thickness: extendFlat({}, gaugeBarAttrs.thickness, {
              dflt: 0.85
            }),
            value: {
              valType: "number",
              editType: "calc",
              dflt: false
            },
            editType: "plot"
          },
          editType: "plot"
          // TODO: in future version, add marker: (bar|needle)
        }
      };
    }
  });

  // src/traces/indicator/constants.js
  var require_constants30 = __commonJS({
    "src/traces/indicator/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        // Defaults for delta
        defaultNumberFontSize: 80,
        bulletNumberDomainSize: 0.25,
        bulletPadding: 0.025,
        innerRadius: 0.75,
        valueThickness: 0.5,
        // thickness of value bars relative to full thickness,
        titlePadding: 5,
        horizontalPadding: 10
      };
    }
  });

  // src/traces/indicator/defaults.js
  var require_defaults57 = __commonJS({
    "src/traces/indicator/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes61();
      var handleDomainDefaults = require_domain().defaults;
      var Template = require_plot_template();
      var handleArrayContainerDefaults = require_array_container_defaults();
      var cn = require_constants30();
      var handleTickValueDefaults = require_tick_value_defaults();
      var handleTickMarkDefaults = require_tick_mark_defaults();
      var handleTickLabelDefaults = require_tick_label_defaults();
      var handlePrefixSuffixDefaults = require_prefix_suffix_defaults();
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        handleDomainDefaults(traceOut, layout, coerce);
        coerce("mode");
        traceOut._hasNumber = traceOut.mode.indexOf("number") !== -1;
        traceOut._hasDelta = traceOut.mode.indexOf("delta") !== -1;
        traceOut._hasGauge = traceOut.mode.indexOf("gauge") !== -1;
        var value = coerce("value");
        traceOut._range = [0, typeof value === "number" ? 1.5 * value : 1];
        var auto = new Array(2);
        var bignumberFontSize;
        if (traceOut._hasNumber) {
          coerce("number.valueformat");
          var numberFontDflt = Lib.extendFlat({}, layout.font);
          numberFontDflt.size = void 0;
          Lib.coerceFont(coerce, "number.font", numberFontDflt);
          if (traceOut.number.font.size === void 0) {
            traceOut.number.font.size = cn.defaultNumberFontSize;
            auto[0] = true;
          }
          coerce("number.prefix");
          coerce("number.suffix");
          bignumberFontSize = traceOut.number.font.size;
        }
        var deltaFontSize;
        if (traceOut._hasDelta) {
          var deltaFontDflt = Lib.extendFlat({}, layout.font);
          deltaFontDflt.size = void 0;
          Lib.coerceFont(coerce, "delta.font", deltaFontDflt);
          if (traceOut.delta.font.size === void 0) {
            traceOut.delta.font.size = (traceOut._hasNumber ? 0.5 : 1) * (bignumberFontSize || cn.defaultNumberFontSize);
            auto[1] = true;
          }
          coerce("delta.reference", traceOut.value);
          coerce("delta.relative");
          coerce("delta.valueformat", traceOut.delta.relative ? "2%" : "");
          coerce("delta.increasing.symbol");
          coerce("delta.increasing.color");
          coerce("delta.decreasing.symbol");
          coerce("delta.decreasing.color");
          coerce("delta.position");
          coerce("delta.prefix");
          coerce("delta.suffix");
          deltaFontSize = traceOut.delta.font.size;
        }
        traceOut._scaleNumbers = (!traceOut._hasNumber || auto[0]) && (!traceOut._hasDelta || auto[1]) || false;
        var titleFontDflt = Lib.extendFlat({}, layout.font);
        titleFontDflt.size = 0.25 * (bignumberFontSize || deltaFontSize || cn.defaultNumberFontSize);
        Lib.coerceFont(coerce, "title.font", titleFontDflt);
        coerce("title.text");
        var gaugeIn, gaugeOut, axisIn, axisOut;
        function coerceGauge(attr, dflt) {
          return Lib.coerce(gaugeIn, gaugeOut, attributes.gauge, attr, dflt);
        }
        function coerceGaugeAxis(attr, dflt) {
          return Lib.coerce(axisIn, axisOut, attributes.gauge.axis, attr, dflt);
        }
        if (traceOut._hasGauge) {
          gaugeIn = traceIn.gauge;
          if (!gaugeIn) gaugeIn = {};
          gaugeOut = Template.newContainer(traceOut, "gauge");
          coerceGauge("shape");
          var isBullet = traceOut._isBullet = traceOut.gauge.shape === "bullet";
          if (!isBullet) {
            coerce("title.align", "center");
          }
          var isAngular = traceOut._isAngular = traceOut.gauge.shape === "angular";
          if (!isAngular) {
            coerce("align", "center");
          }
          coerceGauge("bgcolor", layout.paper_bgcolor);
          coerceGauge("borderwidth");
          coerceGauge("bordercolor");
          coerceGauge("bar.color");
          coerceGauge("bar.line.color");
          coerceGauge("bar.line.width");
          var defaultBarThickness = cn.valueThickness * (traceOut.gauge.shape === "bullet" ? 0.5 : 1);
          coerceGauge("bar.thickness", defaultBarThickness);
          handleArrayContainerDefaults(gaugeIn, gaugeOut, {
            name: "steps",
            handleItemDefaults: stepDefaults
          });
          coerceGauge("threshold.value");
          coerceGauge("threshold.thickness");
          coerceGauge("threshold.line.width");
          coerceGauge("threshold.line.color");
          axisIn = {};
          if (gaugeIn) axisIn = gaugeIn.axis || {};
          axisOut = Template.newContainer(gaugeOut, "axis");
          coerceGaugeAxis("visible");
          traceOut._range = coerceGaugeAxis("range", traceOut._range);
          var opts = {
            font: layout.font,
            noAutotickangles: true,
            outerTicks: true,
            noTicklabelshift: true,
            noTicklabelstandoff: true
          };
          handleTickValueDefaults(axisIn, axisOut, coerceGaugeAxis, "linear");
          handlePrefixSuffixDefaults(axisIn, axisOut, coerceGaugeAxis, "linear", opts);
          handleTickLabelDefaults(axisIn, axisOut, coerceGaugeAxis, "linear", opts);
          handleTickMarkDefaults(axisIn, axisOut, coerceGaugeAxis, opts);
        } else {
          coerce("title.align", "center");
          coerce("align", "center");
          traceOut._isAngular = traceOut._isBullet = false;
        }
        traceOut._length = null;
      }
      function stepDefaults(stepIn, stepOut) {
        function coerce(attr, dflt) {
          return Lib.coerce(stepIn, stepOut, attributes.gauge.steps, attr, dflt);
        }
        coerce("color");
        coerce("line.color");
        coerce("line.width");
        coerce("range");
        coerce("thickness");
      }
      module.exports = {
        supplyDefaults
      };
    }
  });

  // src/traces/indicator/calc.js
  var require_calc36 = __commonJS({
    "src/traces/indicator/calc.js"(exports, module) {
      "use strict";
      function calc(gd, trace) {
        var cd = [];
        var lastReading = trace.value;
        if (!(typeof trace._lastValue === "number")) trace._lastValue = trace.value;
        var secondLastReading = trace._lastValue;
        var deltaRef = secondLastReading;
        if (trace._hasDelta && typeof trace.delta.reference === "number") {
          deltaRef = trace.delta.reference;
        }
        cd[0] = {
          y: lastReading,
          lastY: secondLastReading,
          delta: lastReading - deltaRef,
          relativeDelta: (lastReading - deltaRef) / deltaRef
        };
        return cd;
      }
      module.exports = {
        calc
      };
    }
  });

  // src/traces/indicator/plot.js
  var require_plot30 = __commonJS({
    "src/traces/indicator/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var interpolate = (init_src2(), __toCommonJS(src_exports)).interpolate;
      var interpolateNumber = (init_src2(), __toCommonJS(src_exports)).interpolateNumber;
      var Lib = require_lib();
      var strScale = Lib.strScale;
      var strTranslate = Lib.strTranslate;
      var rad2deg = Lib.rad2deg;
      var MID_SHIFT = require_alignment().MID_SHIFT;
      var Drawing = require_drawing();
      var cn = require_constants30();
      var svgTextUtils = require_svg_text_utils();
      var Axes = require_axes();
      var handleAxisDefaults = require_axis_defaults();
      var handleAxisPositionDefaults = require_position_defaults();
      var axisLayoutAttrs = require_layout_attributes4();
      var Color2 = require_color();
      var anchor = {
        left: "start",
        center: "middle",
        right: "end"
      };
      var position = {
        left: 0,
        center: 0.5,
        right: 1
      };
      var SI_PREFIX = /[yzafpnµmkMGTPEZY]/;
      function hasTransition(transitionOpts) {
        return transitionOpts && transitionOpts.duration > 0;
      }
      module.exports = function plot(gd, cdModule, transitionOpts, makeOnCompleteCallback) {
        var fullLayout = gd._fullLayout;
        var onComplete;
        if (hasTransition(transitionOpts)) {
          if (makeOnCompleteCallback) {
            onComplete = makeOnCompleteCallback();
          }
        }
        Lib.makeTraceGroups(fullLayout._indicatorlayer, cdModule, "trace").each(function(cd) {
          var cd0 = cd[0];
          var trace = cd0.trace;
          var plotGroup = d3.select(this);
          var hasGauge = trace._hasGauge;
          var isAngular = trace._isAngular;
          var isBullet = trace._isBullet;
          var domain = trace.domain;
          var size = {
            w: fullLayout._size.w * (domain.x[1] - domain.x[0]),
            h: fullLayout._size.h * (domain.y[1] - domain.y[0]),
            l: fullLayout._size.l + fullLayout._size.w * domain.x[0],
            r: fullLayout._size.r + fullLayout._size.w * (1 - domain.x[1]),
            t: fullLayout._size.t + fullLayout._size.h * (1 - domain.y[1]),
            b: fullLayout._size.b + fullLayout._size.h * domain.y[0]
          };
          var centerX = size.l + size.w / 2;
          var centerY = size.t + size.h / 2;
          var radius = Math.min(size.w / 2, size.h);
          var innerRadius = cn.innerRadius * radius;
          var numbersX, numbersY, numbersScaler;
          var numbersAlign = trace.align || "center";
          numbersY = centerY;
          if (!hasGauge) {
            numbersX = size.l + position[numbersAlign] * size.w;
            numbersScaler = function(el) {
              return fitTextInsideBox(el, size.w, size.h);
            };
          } else {
            if (isAngular) {
              numbersX = centerX;
              numbersY = centerY + radius / 2;
              numbersScaler = function(el) {
                return fitTextInsideCircle(el, 0.9 * innerRadius);
              };
            }
            if (isBullet) {
              var padding = cn.bulletPadding;
              var p = 1 - cn.bulletNumberDomainSize + padding;
              numbersX = size.l + (p + (1 - p) * position[numbersAlign]) * size.w;
              numbersScaler = function(el) {
                return fitTextInsideBox(el, (cn.bulletNumberDomainSize - padding) * size.w, size.h);
              };
            }
          }
          drawNumbers(gd, plotGroup, cd, {
            numbersX,
            numbersY,
            numbersScaler,
            transitionOpts,
            onComplete
          });
          var gaugeBg, gaugeOutline;
          if (hasGauge) {
            gaugeBg = {
              range: trace.gauge.axis.range,
              color: trace.gauge.bgcolor,
              line: {
                color: trace.gauge.bordercolor,
                width: 0
              },
              thickness: 1
            };
            gaugeOutline = {
              range: trace.gauge.axis.range,
              color: "rgba(0, 0, 0, 0)",
              line: {
                color: trace.gauge.bordercolor,
                width: trace.gauge.borderwidth
              },
              thickness: 1
            };
          }
          var angularGauge = plotGroup.selectAll("g.angular").data(isAngular ? cd : []);
          angularGauge.exit().remove();
          var angularaxisLayer = plotGroup.selectAll("g.angularaxis").data(isAngular ? cd : []);
          angularaxisLayer.exit().remove();
          if (isAngular) {
            drawAngularGauge(gd, plotGroup, cd, {
              radius,
              innerRadius,
              gauge: angularGauge,
              layer: angularaxisLayer,
              size,
              gaugeBg,
              gaugeOutline,
              transitionOpts,
              onComplete
            });
          }
          var bulletGauge = plotGroup.selectAll("g.bullet").data(isBullet ? cd : []);
          bulletGauge.exit().remove();
          var bulletaxisLayer = plotGroup.selectAll("g.bulletaxis").data(isBullet ? cd : []);
          bulletaxisLayer.exit().remove();
          if (isBullet) {
            drawBulletGauge(gd, plotGroup, cd, {
              gauge: bulletGauge,
              layer: bulletaxisLayer,
              size,
              gaugeBg,
              gaugeOutline,
              transitionOpts,
              onComplete
            });
          }
          var title = plotGroup.selectAll("text.title").data(cd);
          title.exit().remove();
          title.enter().append("text").classed("title", true);
          title.attr("text-anchor", function() {
            return isBullet ? anchor.right : anchor[trace.title.align];
          }).text(trace.title.text).call(Drawing.font, trace.title.font).call(svgTextUtils.convertToTspans, gd);
          title.attr("transform", function() {
            var titleX = size.l + size.w * position[trace.title.align];
            var titleY;
            var titlePadding = cn.titlePadding;
            var titlebBox = Drawing.bBox(title.node());
            if (hasGauge) {
              if (isAngular) {
                if (trace.gauge.axis.visible) {
                  var bBox = Drawing.bBox(angularaxisLayer.node());
                  titleY = bBox.top - titlePadding - titlebBox.bottom;
                } else {
                  titleY = size.t + size.h / 2 - radius / 2 - titlebBox.bottom - titlePadding;
                }
              }
              if (isBullet) {
                titleY = numbersY - (titlebBox.top + titlebBox.bottom) / 2;
                titleX = size.l - cn.bulletPadding * size.w;
              }
            } else {
              titleY = trace._numbersTop - titlePadding - titlebBox.bottom;
            }
            return strTranslate(titleX, titleY);
          });
        });
      };
      function drawBulletGauge(gd, plotGroup, cd, opts) {
        var trace = cd[0].trace;
        var bullet = opts.gauge;
        var axisLayer = opts.layer;
        var gaugeBg = opts.gaugeBg;
        var gaugeOutline = opts.gaugeOutline;
        var size = opts.size;
        var domain = trace.domain;
        var transitionOpts = opts.transitionOpts;
        var onComplete = opts.onComplete;
        var ax, vals, transFn, tickSign, shift;
        bullet.enter().append("g").classed("bullet", true);
        bullet.attr("transform", strTranslate(size.l, size.t));
        axisLayer.enter().append("g").classed("bulletaxis", true).classed("crisp", true);
        axisLayer.selectAll("g.xbulletaxistick,path,text").remove();
        var bulletHeight = size.h;
        var innerBulletHeight = trace.gauge.bar.thickness * bulletHeight;
        var bulletLeft = domain.x[0];
        var bulletRight = domain.x[0] + (domain.x[1] - domain.x[0]) * (trace._hasNumber || trace._hasDelta ? 1 - cn.bulletNumberDomainSize : 1);
        ax = mockAxis(gd, trace.gauge.axis);
        ax._id = "xbulletaxis";
        ax.domain = [bulletLeft, bulletRight];
        ax.setScale();
        vals = Axes.calcTicks(ax);
        transFn = Axes.makeTransTickFn(ax);
        tickSign = Axes.getTickSigns(ax)[2];
        shift = size.t + size.h;
        if (ax.visible) {
          Axes.drawTicks(gd, ax, {
            vals: ax.ticks === "inside" ? Axes.clipEnds(ax, vals) : vals,
            layer: axisLayer,
            path: Axes.makeTickPath(ax, shift, tickSign),
            transFn
          });
          Axes.drawLabels(gd, ax, {
            vals,
            layer: axisLayer,
            transFn,
            labelFns: Axes.makeLabelFns(ax, shift)
          });
        }
        function drawRect(s) {
          s.attr("width", function(d) {
            return Math.max(0, ax.c2p(d.range[1]) - ax.c2p(d.range[0]));
          }).attr("x", function(d) {
            return ax.c2p(d.range[0]);
          }).attr("y", function(d) {
            return 0.5 * (1 - d.thickness) * bulletHeight;
          }).attr("height", function(d) {
            return d.thickness * bulletHeight;
          });
        }
        var boxes = [gaugeBg].concat(trace.gauge.steps);
        var bgBullet = bullet.selectAll("g.bg-bullet").data(boxes);
        bgBullet.enter().append("g").classed("bg-bullet", true).append("rect");
        bgBullet.select("rect").call(drawRect).call(styleShape);
        bgBullet.exit().remove();
        var fgBullet = bullet.selectAll("g.value-bullet").data([trace.gauge.bar]);
        fgBullet.enter().append("g").classed("value-bullet", true).append("rect");
        fgBullet.select("rect").attr("height", innerBulletHeight).attr("y", (bulletHeight - innerBulletHeight) / 2).call(styleShape);
        if (hasTransition(transitionOpts)) {
          fgBullet.select("rect").transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() {
            onComplete && onComplete();
          }).each("interrupt", function() {
            onComplete && onComplete();
          }).attr("width", Math.max(0, ax.c2p(Math.min(trace.gauge.axis.range[1], cd[0].y))));
        } else {
          fgBullet.select("rect").attr("width", typeof cd[0].y === "number" ? Math.max(0, ax.c2p(Math.min(trace.gauge.axis.range[1], cd[0].y))) : 0);
        }
        fgBullet.exit().remove();
        var data = cd.filter(function() {
          return trace.gauge.threshold.value || trace.gauge.threshold.value === 0;
        });
        var threshold = bullet.selectAll("g.threshold-bullet").data(data);
        threshold.enter().append("g").classed("threshold-bullet", true).append("line");
        threshold.select("line").attr("x1", ax.c2p(trace.gauge.threshold.value)).attr("x2", ax.c2p(trace.gauge.threshold.value)).attr("y1", (1 - trace.gauge.threshold.thickness) / 2 * bulletHeight).attr("y2", (1 - (1 - trace.gauge.threshold.thickness) / 2) * bulletHeight).call(Color2.stroke, trace.gauge.threshold.line.color).style("stroke-width", trace.gauge.threshold.line.width);
        threshold.exit().remove();
        var bulletOutline = bullet.selectAll("g.gauge-outline").data([gaugeOutline]);
        bulletOutline.enter().append("g").classed("gauge-outline", true).append("rect");
        bulletOutline.select("rect").call(drawRect).call(styleShape);
        bulletOutline.exit().remove();
      }
      function drawAngularGauge(gd, plotGroup, cd, opts) {
        var trace = cd[0].trace;
        var size = opts.size;
        var radius = opts.radius;
        var innerRadius = opts.innerRadius;
        var gaugeBg = opts.gaugeBg;
        var gaugeOutline = opts.gaugeOutline;
        var gaugePosition = [size.l + size.w / 2, size.t + size.h / 2 + radius / 2];
        var gauge = opts.gauge;
        var axisLayer = opts.layer;
        var transitionOpts = opts.transitionOpts;
        var onComplete = opts.onComplete;
        var theta = Math.PI / 2;
        function valueToAngle(v2) {
          var min = trace.gauge.axis.range[0];
          var max = trace.gauge.axis.range[1];
          var angle = (v2 - min) / (max - min) * Math.PI - theta;
          if (angle < -theta) return -theta;
          if (angle > theta) return theta;
          return angle;
        }
        function arcPathGenerator(size2) {
          return d3.svg.arc().innerRadius((innerRadius + radius) / 2 - size2 / 2 * (radius - innerRadius)).outerRadius((innerRadius + radius) / 2 + size2 / 2 * (radius - innerRadius)).startAngle(-theta);
        }
        function drawArc(p) {
          p.attr("d", function(d) {
            return arcPathGenerator(d.thickness).startAngle(valueToAngle(d.range[0])).endAngle(valueToAngle(d.range[1]))();
          });
        }
        var ax, vals, transFn, tickSign;
        gauge.enter().append("g").classed("angular", true);
        gauge.attr("transform", strTranslate(gaugePosition[0], gaugePosition[1]));
        axisLayer.enter().append("g").classed("angularaxis", true).classed("crisp", true);
        axisLayer.selectAll("g.xangularaxistick,path,text").remove();
        ax = mockAxis(gd, trace.gauge.axis);
        ax.type = "linear";
        ax.range = trace.gauge.axis.range;
        ax._id = "xangularaxis";
        ax.ticklabeloverflow = "allow";
        ax.setScale();
        var t2g = function(d) {
          return (ax.range[0] - d.x) / (ax.range[1] - ax.range[0]) * Math.PI + Math.PI;
        };
        var labelFns = {};
        var out = Axes.makeLabelFns(ax, 0);
        var labelStandoff = out.labelStandoff;
        labelFns.xFn = function(d) {
          var rad = t2g(d);
          return Math.cos(rad) * labelStandoff;
        };
        labelFns.yFn = function(d) {
          var rad = t2g(d);
          var ff = Math.sin(rad) > 0 ? 0.2 : 1;
          return -Math.sin(rad) * (labelStandoff + d.fontSize * ff) + Math.abs(Math.cos(rad)) * (d.fontSize * MID_SHIFT);
        };
        labelFns.anchorFn = function(d) {
          var rad = t2g(d);
          var cos = Math.cos(rad);
          return Math.abs(cos) < 0.1 ? "middle" : cos > 0 ? "start" : "end";
        };
        labelFns.heightFn = function(d, a, h) {
          var rad = t2g(d);
          return -0.5 * (1 + Math.sin(rad)) * h;
        };
        var _transFn = function(rad) {
          return strTranslate(
            gaugePosition[0] + radius * Math.cos(rad),
            gaugePosition[1] - radius * Math.sin(rad)
          );
        };
        transFn = function(d) {
          return _transFn(t2g(d));
        };
        var transFn2 = function(d) {
          var rad = t2g(d);
          return _transFn(rad) + "rotate(" + -rad2deg(rad) + ")";
        };
        vals = Axes.calcTicks(ax);
        tickSign = Axes.getTickSigns(ax)[2];
        if (ax.visible) {
          tickSign = ax.ticks === "inside" ? -1 : 1;
          var pad = (ax.linewidth || 1) / 2;
          Axes.drawTicks(gd, ax, {
            vals,
            layer: axisLayer,
            path: "M" + tickSign * pad + ",0h" + tickSign * ax.ticklen,
            transFn: transFn2
          });
          Axes.drawLabels(gd, ax, {
            vals,
            layer: axisLayer,
            transFn,
            labelFns
          });
        }
        var arcs = [gaugeBg].concat(trace.gauge.steps);
        var bgArc = gauge.selectAll("g.bg-arc").data(arcs);
        bgArc.enter().append("g").classed("bg-arc", true).append("path");
        bgArc.select("path").call(drawArc).call(styleShape);
        bgArc.exit().remove();
        var valueArcPathGenerator = arcPathGenerator(trace.gauge.bar.thickness);
        var valueArc = gauge.selectAll("g.value-arc").data([trace.gauge.bar]);
        valueArc.enter().append("g").classed("value-arc", true).append("path");
        var valueArcPath = valueArc.select("path");
        if (hasTransition(transitionOpts)) {
          valueArcPath.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() {
            onComplete && onComplete();
          }).each("interrupt", function() {
            onComplete && onComplete();
          }).attrTween("d", arcTween(valueArcPathGenerator, valueToAngle(cd[0].lastY), valueToAngle(cd[0].y)));
          trace._lastValue = cd[0].y;
        } else {
          valueArcPath.attr("d", typeof cd[0].y === "number" ? valueArcPathGenerator.endAngle(valueToAngle(cd[0].y)) : "M0,0Z");
        }
        valueArcPath.call(styleShape);
        valueArc.exit().remove();
        arcs = [];
        var v = trace.gauge.threshold.value;
        if (v || v === 0) {
          arcs.push({
            range: [v, v],
            color: trace.gauge.threshold.color,
            line: {
              color: trace.gauge.threshold.line.color,
              width: trace.gauge.threshold.line.width
            },
            thickness: trace.gauge.threshold.thickness
          });
        }
        var thresholdArc = gauge.selectAll("g.threshold-arc").data(arcs);
        thresholdArc.enter().append("g").classed("threshold-arc", true).append("path");
        thresholdArc.select("path").call(drawArc).call(styleShape);
        thresholdArc.exit().remove();
        var gaugeBorder = gauge.selectAll("g.gauge-outline").data([gaugeOutline]);
        gaugeBorder.enter().append("g").classed("gauge-outline", true).append("path");
        gaugeBorder.select("path").call(drawArc).call(styleShape);
        gaugeBorder.exit().remove();
      }
      function drawNumbers(gd, plotGroup, cd, opts) {
        var trace = cd[0].trace;
        var numbersX = opts.numbersX;
        var numbersY = opts.numbersY;
        var numbersAlign = trace.align || "center";
        var numbersAnchor = anchor[numbersAlign];
        var transitionOpts = opts.transitionOpts;
        var onComplete = opts.onComplete;
        var numbers = Lib.ensureSingle(plotGroup, "g", "numbers");
        var bignumberbBox, deltabBox;
        var numbersbBox;
        var data = [];
        if (trace._hasNumber) data.push("number");
        if (trace._hasDelta) {
          data.push("delta");
          if (trace.delta.position === "left") data.reverse();
        }
        var sel = numbers.selectAll("text").data(data);
        sel.enter().append("text");
        sel.attr("text-anchor", function() {
          return numbersAnchor;
        }).attr("class", function(d) {
          return d;
        }).attr("x", null).attr("y", null).attr("dx", null).attr("dy", null);
        sel.exit().remove();
        function transitionFormat(valueformat, fmt, from, to) {
          if (valueformat.match("s") && // If using SI prefix
          from >= 0 !== to >= 0 && // If sign change
          (!fmt(from).slice(-1).match(SI_PREFIX) && !fmt(to).slice(-1).match(SI_PREFIX))) {
            var transitionValueFormat = valueformat.slice().replace("s", "f").replace(/\d+/, function(m) {
              return parseInt(m) - 1;
            });
            var transitionAx = mockAxis(gd, { tickformat: transitionValueFormat });
            return function(v) {
              if (Math.abs(v) < 1) return Axes.tickText(transitionAx, v).text;
              return fmt(v);
            };
          } else {
            return fmt;
          }
        }
        function drawBignumber() {
          var bignumberAx = mockAxis(gd, { tickformat: trace.number.valueformat }, trace._range);
          bignumberAx.setScale();
          Axes.prepTicks(bignumberAx);
          var bignumberFmt = function(v) {
            return Axes.tickText(bignumberAx, v).text;
          };
          var bignumberSuffix = trace.number.suffix;
          var bignumberPrefix = trace.number.prefix;
          var number = numbers.select("text.number");
          function writeNumber() {
            var txt = typeof cd[0].y === "number" ? bignumberPrefix + bignumberFmt(cd[0].y) + bignumberSuffix : "-";
            number.text(txt).call(Drawing.font, trace.number.font).call(svgTextUtils.convertToTspans, gd);
          }
          if (hasTransition(transitionOpts)) {
            number.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() {
              writeNumber();
              onComplete && onComplete();
            }).each("interrupt", function() {
              writeNumber();
              onComplete && onComplete();
            }).attrTween("text", function() {
              var that = d3.select(this);
              var interpolator = interpolateNumber(cd[0].lastY, cd[0].y);
              trace._lastValue = cd[0].y;
              var transitionFmt = transitionFormat(trace.number.valueformat, bignumberFmt, cd[0].lastY, cd[0].y);
              return function(t) {
                that.text(bignumberPrefix + transitionFmt(interpolator(t)) + bignumberSuffix);
              };
            });
          } else {
            writeNumber();
          }
          bignumberbBox = measureText(bignumberPrefix + bignumberFmt(cd[0].y) + bignumberSuffix, trace.number.font, numbersAnchor, gd);
          return number;
        }
        function drawDelta() {
          var deltaAx = mockAxis(gd, { tickformat: trace.delta.valueformat }, trace._range);
          deltaAx.setScale();
          Axes.prepTicks(deltaAx);
          var deltaFmt = function(v) {
            return Axes.tickText(deltaAx, v).text;
          };
          var deltaSuffix = trace.delta.suffix;
          var deltaPrefix = trace.delta.prefix;
          var deltaValue = function(d) {
            var value = trace.delta.relative ? d.relativeDelta : d.delta;
            return value;
          };
          var deltaFormatText = function(value, numberFmt) {
            if (value === 0 || typeof value !== "number" || isNaN(value)) return "-";
            return (value > 0 ? trace.delta.increasing.symbol : trace.delta.decreasing.symbol) + deltaPrefix + numberFmt(value) + deltaSuffix;
          };
          var deltaFill = function(d) {
            return d.delta >= 0 ? trace.delta.increasing.color : trace.delta.decreasing.color;
          };
          if (trace._deltaLastValue === void 0) {
            trace._deltaLastValue = deltaValue(cd[0]);
          }
          var delta2 = numbers.select("text.delta");
          delta2.call(Drawing.font, trace.delta.font).call(Color2.fill, deltaFill({ delta: trace._deltaLastValue }));
          function writeDelta() {
            delta2.text(deltaFormatText(deltaValue(cd[0]), deltaFmt)).call(Color2.fill, deltaFill(cd[0])).call(svgTextUtils.convertToTspans, gd);
          }
          if (hasTransition(transitionOpts)) {
            delta2.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).tween("text", function() {
              var that = d3.select(this);
              var to = deltaValue(cd[0]);
              var from = trace._deltaLastValue;
              var transitionFmt = transitionFormat(trace.delta.valueformat, deltaFmt, from, to);
              var interpolator = interpolateNumber(from, to);
              trace._deltaLastValue = to;
              return function(t) {
                that.text(deltaFormatText(interpolator(t), transitionFmt));
                that.call(Color2.fill, deltaFill({ delta: interpolator(t) }));
              };
            }).each("end", function() {
              writeDelta();
              onComplete && onComplete();
            }).each("interrupt", function() {
              writeDelta();
              onComplete && onComplete();
            });
          } else {
            writeDelta();
          }
          deltabBox = measureText(deltaFormatText(deltaValue(cd[0]), deltaFmt), trace.delta.font, numbersAnchor, gd);
          return delta2;
        }
        var key = trace.mode + trace.align;
        var delta;
        if (trace._hasDelta) {
          delta = drawDelta();
          key += trace.delta.position + trace.delta.font.size + trace.delta.font.family + trace.delta.valueformat;
          key += trace.delta.increasing.symbol + trace.delta.decreasing.symbol;
          numbersbBox = deltabBox;
        }
        if (trace._hasNumber) {
          drawBignumber();
          key += trace.number.font.size + trace.number.font.family + trace.number.valueformat + trace.number.suffix + trace.number.prefix;
          numbersbBox = bignumberbBox;
        }
        if (trace._hasDelta && trace._hasNumber) {
          var bignumberCenter = [
            (bignumberbBox.left + bignumberbBox.right) / 2,
            (bignumberbBox.top + bignumberbBox.bottom) / 2
          ];
          var deltaCenter = [
            (deltabBox.left + deltabBox.right) / 2,
            (deltabBox.top + deltabBox.bottom) / 2
          ];
          var dx, dy;
          var padding = 0.75 * trace.delta.font.size;
          if (trace.delta.position === "left") {
            dx = cache(trace, "deltaPos", 0, -1 * (bignumberbBox.width * position[trace.align] + deltabBox.width * (1 - position[trace.align]) + padding), key, Math.min);
            dy = bignumberCenter[1] - deltaCenter[1];
            numbersbBox = {
              width: bignumberbBox.width + deltabBox.width + padding,
              height: Math.max(bignumberbBox.height, deltabBox.height),
              left: deltabBox.left + dx,
              right: bignumberbBox.right,
              top: Math.min(bignumberbBox.top, deltabBox.top + dy),
              bottom: Math.max(bignumberbBox.bottom, deltabBox.bottom + dy)
            };
          }
          if (trace.delta.position === "right") {
            dx = cache(trace, "deltaPos", 0, bignumberbBox.width * (1 - position[trace.align]) + deltabBox.width * position[trace.align] + padding, key, Math.max);
            dy = bignumberCenter[1] - deltaCenter[1];
            numbersbBox = {
              width: bignumberbBox.width + deltabBox.width + padding,
              height: Math.max(bignumberbBox.height, deltabBox.height),
              left: bignumberbBox.left,
              right: deltabBox.right + dx,
              top: Math.min(bignumberbBox.top, deltabBox.top + dy),
              bottom: Math.max(bignumberbBox.bottom, deltabBox.bottom + dy)
            };
          }
          if (trace.delta.position === "bottom") {
            dx = null;
            dy = deltabBox.height;
            numbersbBox = {
              width: Math.max(bignumberbBox.width, deltabBox.width),
              height: bignumberbBox.height + deltabBox.height,
              left: Math.min(bignumberbBox.left, deltabBox.left),
              right: Math.max(bignumberbBox.right, deltabBox.right),
              top: bignumberbBox.bottom - bignumberbBox.height,
              bottom: bignumberbBox.bottom + deltabBox.height
            };
          }
          if (trace.delta.position === "top") {
            dx = null;
            dy = bignumberbBox.top;
            numbersbBox = {
              width: Math.max(bignumberbBox.width, deltabBox.width),
              height: bignumberbBox.height + deltabBox.height,
              left: Math.min(bignumberbBox.left, deltabBox.left),
              right: Math.max(bignumberbBox.right, deltabBox.right),
              top: bignumberbBox.bottom - bignumberbBox.height - deltabBox.height,
              bottom: bignumberbBox.bottom
            };
          }
          delta.attr({ dx, dy });
        }
        if (trace._hasNumber || trace._hasDelta) {
          numbers.attr("transform", function() {
            var m = opts.numbersScaler(numbersbBox);
            key += m[2];
            var scaleRatio = cache(trace, "numbersScale", 1, m[0], key, Math.min);
            var translateY;
            if (!trace._scaleNumbers) scaleRatio = 1;
            if (trace._isAngular) {
              translateY = numbersY - scaleRatio * numbersbBox.bottom;
            } else {
              translateY = numbersY - scaleRatio * (numbersbBox.top + numbersbBox.bottom) / 2;
            }
            trace._numbersTop = scaleRatio * numbersbBox.top + translateY;
            var ref = numbersbBox[numbersAlign];
            if (numbersAlign === "center") ref = (numbersbBox.left + numbersbBox.right) / 2;
            var translateX = numbersX - scaleRatio * ref;
            translateX = cache(trace, "numbersTranslate", 0, translateX, key, Math.max);
            return strTranslate(translateX, translateY) + strScale(scaleRatio);
          });
        }
      }
      function styleShape(p) {
        p.each(function(d) {
          Color2.stroke(d3.select(this), d.line.color);
        }).each(function(d) {
          Color2.fill(d3.select(this), d.color);
        }).style("stroke-width", function(d) {
          return d.line.width;
        });
      }
      function arcTween(arc, endAngle, newAngle) {
        return function() {
          var interp = interpolate(endAngle, newAngle);
          return function(t) {
            return arc.endAngle(interp(t))();
          };
        };
      }
      function mockAxis(gd, opts, zrange) {
        var fullLayout = gd._fullLayout;
        var axisIn = Lib.extendFlat({
          type: "linear",
          ticks: "outside",
          range: zrange,
          showline: true
        }, opts);
        var axisOut = {
          type: "linear",
          _id: "x" + opts._id
        };
        var axisOptions = {
          letter: "x",
          font: fullLayout.font,
          noAutotickangles: true,
          noHover: true,
          noTickson: true
        };
        function coerce(attr, dflt) {
          return Lib.coerce(axisIn, axisOut, axisLayoutAttrs, attr, dflt);
        }
        handleAxisDefaults(axisIn, axisOut, coerce, axisOptions, fullLayout);
        handleAxisPositionDefaults(axisIn, axisOut, coerce, axisOptions);
        return axisOut;
      }
      function fitTextInsideBox(textBB, width, height) {
        var ratio = Math.min(width / textBB.width, height / textBB.height);
        return [ratio, textBB, width + "x" + height];
      }
      function fitTextInsideCircle(textBB, radius) {
        var elRadius = Math.sqrt(textBB.width / 2 * (textBB.width / 2) + textBB.height * textBB.height);
        var ratio = radius / elRadius;
        return [ratio, textBB, radius];
      }
      function measureText(txt, font, textAnchor, gd) {
        var element = document.createElementNS("http://www.w3.org/2000/svg", "text");
        var sel = d3.select(element);
        sel.text(txt).attr("x", 0).attr("y", 0).attr("text-anchor", textAnchor).attr("data-unformatted", txt).call(svgTextUtils.convertToTspans, gd).call(Drawing.font, font);
        return Drawing.bBox(sel.node());
      }
      function cache(trace, name2, initialValue, value, key, fn) {
        var objName = "_cache" + name2;
        if (!(trace[objName] && trace[objName].key === key)) {
          trace[objName] = { key, value: initialValue };
        }
        var v = Lib.aggNums(fn, null, [trace[objName].value, value], 2);
        trace[objName].value = v;
        return v;
      }
    }
  });

  // src/traces/indicator/index.js
  var require_indicator = __commonJS({
    "src/traces/indicator/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "indicator",
        basePlotModule: require_base_plot10(),
        categories: ["svg", "noOpacity", "noHover"],
        animatable: true,
        attributes: require_attributes61(),
        supplyDefaults: require_defaults57().supplyDefaults,
        calc: require_calc36().calc,
        plot: require_plot30(),
        meta: {}
      };
    }
  });

  // lib/indicator.js
  var require_indicator2 = __commonJS({
    "lib/indicator.js"(exports, module) {
      "use strict";
      module.exports = require_indicator();
    }
  });

  // src/traces/table/attributes.js
  var require_attributes62 = __commonJS({
    "src/traces/table/attributes.js"(exports, module) {
      "use strict";
      var annAttrs = require_attributes11();
      var extendFlat = require_extend().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var fontAttrs = require_font_attributes();
      var domainAttrs = require_domain().attributes;
      var descriptionOnlyNumbers = require_axis_format_attributes().descriptionOnlyNumbers;
      var attrs = module.exports = overrideAll({
        domain: domainAttrs({ name: "table", trace: true }),
        columnwidth: {
          valType: "number",
          arrayOk: true,
          dflt: null
        },
        columnorder: {
          valType: "data_array"
        },
        header: {
          values: {
            valType: "data_array",
            dflt: []
          },
          format: {
            valType: "data_array",
            dflt: [],
            description: descriptionOnlyNumbers("cell value")
          },
          prefix: {
            valType: "string",
            arrayOk: true,
            dflt: null
          },
          suffix: {
            valType: "string",
            arrayOk: true,
            dflt: null
          },
          height: {
            valType: "number",
            dflt: 28
          },
          align: extendFlat({}, annAttrs.align, { arrayOk: true }),
          line: {
            width: {
              valType: "number",
              arrayOk: true,
              dflt: 1
            },
            color: {
              valType: "color",
              arrayOk: true,
              dflt: "grey"
            }
          },
          fill: {
            color: {
              valType: "color",
              arrayOk: true,
              dflt: "white"
            }
          },
          font: extendFlat({}, fontAttrs({ arrayOk: true }))
        },
        cells: {
          values: {
            valType: "data_array",
            dflt: []
          },
          format: {
            valType: "data_array",
            dflt: [],
            description: descriptionOnlyNumbers("cell value")
          },
          prefix: {
            valType: "string",
            arrayOk: true,
            dflt: null
          },
          suffix: {
            valType: "string",
            arrayOk: true,
            dflt: null
          },
          height: {
            valType: "number",
            dflt: 20
          },
          align: extendFlat({}, annAttrs.align, { arrayOk: true }),
          line: {
            width: {
              valType: "number",
              arrayOk: true,
              dflt: 1
            },
            color: {
              valType: "color",
              arrayOk: true,
              dflt: "grey"
            }
          },
          fill: {
            color: {
              valType: "color",
              arrayOk: true,
              dflt: "white"
            }
          },
          font: extendFlat({}, fontAttrs({ arrayOk: true }))
        }
      }, "calc", "from-root");
    }
  });

  // src/traces/table/defaults.js
  var require_defaults58 = __commonJS({
    "src/traces/table/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attributes = require_attributes62();
      var handleDomainDefaults = require_domain().defaults;
      function defaultColumnOrder(traceOut, coerce) {
        var specifiedColumnOrder = traceOut.columnorder || [];
        var commonLength = traceOut.header.values.length;
        var truncated = specifiedColumnOrder.slice(0, commonLength);
        var sorted = truncated.slice().sort(function(a, b) {
          return a - b;
        });
        var oneStepped = truncated.map(function(d) {
          return sorted.indexOf(d);
        });
        for (var i = oneStepped.length; i < commonLength; i++) {
          oneStepped.push(i);
        }
        coerce("columnorder", oneStepped);
      }
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        handleDomainDefaults(traceOut, layout, coerce);
        coerce("columnwidth");
        coerce("header.values");
        coerce("header.format");
        coerce("header.align");
        coerce("header.prefix");
        coerce("header.suffix");
        coerce("header.height");
        coerce("header.line.width");
        coerce("header.line.color");
        coerce("header.fill.color");
        Lib.coerceFont(coerce, "header.font", layout.font);
        defaultColumnOrder(traceOut, coerce);
        coerce("cells.values");
        coerce("cells.format");
        coerce("cells.align");
        coerce("cells.prefix");
        coerce("cells.suffix");
        coerce("cells.height");
        coerce("cells.line.width");
        coerce("cells.line.color");
        coerce("cells.fill.color");
        Lib.coerceFont(coerce, "cells.font", layout.font);
        traceOut._length = null;
      };
    }
  });

  // src/traces/table/calc.js
  var require_calc37 = __commonJS({
    "src/traces/table/calc.js"(exports, module) {
      "use strict";
      var wrap = require_gup().wrap;
      module.exports = function calc() {
        return wrap({});
      };
    }
  });

  // src/traces/table/constants.js
  var require_constants31 = __commonJS({
    "src/traces/table/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        cellPad: 8,
        columnExtentOffset: 10,
        columnTitleOffset: 28,
        emptyHeaderHeight: 16,
        latexCheck: /^\$.*\$$/,
        goldenRatio: 1.618,
        lineBreaker: "<br>",
        maxDimensionCount: 60,
        overdrag: 45,
        releaseTransitionDuration: 120,
        releaseTransitionEase: "cubic-out",
        scrollbarCaptureWidth: 18,
        scrollbarHideDelay: 1e3,
        scrollbarHideDuration: 1e3,
        scrollbarOffset: 5,
        scrollbarWidth: 8,
        transitionDuration: 100,
        transitionEase: "cubic-out",
        uplift: 5,
        wrapSpacer: " ",
        wrapSplitCharacter: " ",
        cn: {
          // general class names
          table: "table",
          tableControlView: "table-control-view",
          scrollBackground: "scroll-background",
          yColumn: "y-column",
          columnBlock: "column-block",
          scrollAreaClip: "scroll-area-clip",
          scrollAreaClipRect: "scroll-area-clip-rect",
          columnBoundary: "column-boundary",
          columnBoundaryClippath: "column-boundary-clippath",
          columnBoundaryRect: "column-boundary-rect",
          columnCells: "column-cells",
          columnCell: "column-cell",
          cellRect: "cell-rect",
          cellText: "cell-text",
          cellTextHolder: "cell-text-holder",
          // scroll related class names
          scrollbarKit: "scrollbar-kit",
          scrollbar: "scrollbar",
          scrollbarSlider: "scrollbar-slider",
          scrollbarGlyph: "scrollbar-glyph",
          scrollbarCaptureZone: "scrollbar-capture-zone"
        }
      };
    }
  });

  // src/traces/table/data_preparation_helper.js
  var require_data_preparation_helper = __commonJS({
    "src/traces/table/data_preparation_helper.js"(exports, module) {
      "use strict";
      var c = require_constants31();
      var extendFlat = require_extend().extendFlat;
      var isNumeric = require_fast_isnumeric();
      var isTypedArray = require_array().isTypedArray;
      var isArrayOrTypedArray = require_array().isArrayOrTypedArray;
      module.exports = function calc(gd, trace) {
        var cellsValues = squareStringMatrix(trace.cells.values);
        var slicer = function(a) {
          return a.slice(trace.header.values.length, a.length);
        };
        var headerValuesIn = squareStringMatrix(trace.header.values);
        if (headerValuesIn.length && !headerValuesIn[0].length) {
          headerValuesIn[0] = [""];
          headerValuesIn = squareStringMatrix(headerValuesIn);
        }
        var headerValues = headerValuesIn.concat(slicer(cellsValues).map(function() {
          return emptyStrings((headerValuesIn[0] || [""]).length);
        }));
        var domain = trace.domain;
        var groupWidth = Math.floor(gd._fullLayout._size.w * (domain.x[1] - domain.x[0]));
        var groupHeight = Math.floor(gd._fullLayout._size.h * (domain.y[1] - domain.y[0]));
        var headerRowHeights = trace.header.values.length ? headerValues[0].map(function() {
          return trace.header.height;
        }) : [c.emptyHeaderHeight];
        var rowHeights = cellsValues.length ? cellsValues[0].map(function() {
          return trace.cells.height;
        }) : [];
        var headerHeight = headerRowHeights.reduce(sum, 0);
        var scrollHeight = groupHeight - headerHeight;
        var minimumFillHeight = scrollHeight + c.uplift;
        var anchorToRowBlock = makeAnchorToRowBlock(rowHeights, minimumFillHeight);
        var anchorToHeaderRowBlock = makeAnchorToRowBlock(headerRowHeights, headerHeight);
        var headerRowBlocks = makeRowBlock(anchorToHeaderRowBlock, []);
        var rowBlocks = makeRowBlock(anchorToRowBlock, headerRowBlocks);
        var uniqueKeys = {};
        var columnOrder = trace._fullInput.columnorder;
        if (isArrayOrTypedArray(columnOrder)) columnOrder = Array.from(columnOrder);
        columnOrder = columnOrder.concat(slicer(cellsValues.map(function(d, i) {
          return i;
        })));
        var columnWidths = headerValues.map(function(d, i) {
          var value = isArrayOrTypedArray(trace.columnwidth) ? trace.columnwidth[Math.min(i, trace.columnwidth.length - 1)] : trace.columnwidth;
          return isNumeric(value) ? Number(value) : 1;
        });
        var totalColumnWidths = columnWidths.reduce(sum, 0);
        columnWidths = columnWidths.map(function(d) {
          return d / totalColumnWidths * groupWidth;
        });
        var maxLineWidth = Math.max(arrayMax(trace.header.line.width), arrayMax(trace.cells.line.width));
        var calcdata = {
          // include staticPlot in the key so if it changes we delete and redraw
          key: trace.uid + gd._context.staticPlot,
          translateX: domain.x[0] * gd._fullLayout._size.w,
          translateY: gd._fullLayout._size.h * (1 - domain.y[1]),
          size: gd._fullLayout._size,
          width: groupWidth,
          maxLineWidth,
          height: groupHeight,
          columnOrder,
          // will be mutated on column move, todo use in callback
          groupHeight,
          rowBlocks,
          headerRowBlocks,
          scrollY: 0,
          // will be mutated on scroll
          cells: extendFlat({}, trace.cells, { values: cellsValues }),
          headerCells: extendFlat({}, trace.header, { values: headerValues }),
          gdColumns: headerValues.map(function(d) {
            return d[0];
          }),
          gdColumnsOriginalOrder: headerValues.map(function(d) {
            return d[0];
          }),
          prevPages: [0, 0],
          scrollbarState: { scrollbarScrollInProgress: false },
          columns: headerValues.map(function(label, i) {
            var foundKey = uniqueKeys[label];
            uniqueKeys[label] = (foundKey || 0) + 1;
            var key = label + "__" + uniqueKeys[label];
            return {
              key,
              label,
              specIndex: i,
              xIndex: columnOrder[i],
              xScale,
              x: void 0,
              // initialized below
              calcdata: void 0,
              // initialized below
              columnWidth: columnWidths[i]
            };
          })
        };
        calcdata.columns.forEach(function(col) {
          col.calcdata = calcdata;
          col.x = xScale(col);
        });
        return calcdata;
      };
      function arrayMax(maybeArray) {
        if (isArrayOrTypedArray(maybeArray)) {
          var max = 0;
          for (var i = 0; i < maybeArray.length; i++) {
            max = Math.max(max, arrayMax(maybeArray[i]));
          }
          return max;
        }
        return maybeArray;
      }
      function sum(a, b) {
        return a + b;
      }
      function squareStringMatrix(matrixIn) {
        var matrix = matrixIn.slice();
        var minLen = Infinity;
        var maxLen = 0;
        var i;
        for (i = 0; i < matrix.length; i++) {
          if (isTypedArray(matrix[i])) matrix[i] = Array.from(matrix[i]);
          else if (!isArrayOrTypedArray(matrix[i])) matrix[i] = [matrix[i]];
          minLen = Math.min(minLen, matrix[i].length);
          maxLen = Math.max(maxLen, matrix[i].length);
        }
        if (minLen !== maxLen) {
          for (i = 0; i < matrix.length; i++) {
            var padLen = maxLen - matrix[i].length;
            if (padLen) matrix[i] = matrix[i].concat(emptyStrings(padLen));
          }
        }
        return matrix;
      }
      function emptyStrings(len) {
        var padArray = new Array(len);
        for (var j = 0; j < len; j++) padArray[j] = "";
        return padArray;
      }
      function xScale(d) {
        return d.calcdata.columns.reduce(function(prev, next) {
          return next.xIndex < d.xIndex ? prev + next.columnWidth : prev;
        }, 0);
      }
      function makeRowBlock(anchorToRowBlock, auxiliary) {
        var blockAnchorKeys = Object.keys(anchorToRowBlock);
        return blockAnchorKeys.map(function(k) {
          return extendFlat({}, anchorToRowBlock[k], { auxiliaryBlocks: auxiliary });
        });
      }
      function makeAnchorToRowBlock(rowHeights, minimumFillHeight) {
        var anchorToRowBlock = {};
        var currentRowHeight;
        var currentAnchor = 0;
        var currentBlockHeight = 0;
        var currentBlock = makeIdentity();
        var currentFirstRowIndex = 0;
        var blockCounter = 0;
        for (var i = 0; i < rowHeights.length; i++) {
          currentRowHeight = rowHeights[i];
          currentBlock.rows.push({
            rowIndex: i,
            rowHeight: currentRowHeight
          });
          currentBlockHeight += currentRowHeight;
          if (currentBlockHeight >= minimumFillHeight || i === rowHeights.length - 1) {
            anchorToRowBlock[currentAnchor] = currentBlock;
            currentBlock.key = blockCounter++;
            currentBlock.firstRowIndex = currentFirstRowIndex;
            currentBlock.lastRowIndex = i;
            currentBlock = makeIdentity();
            currentAnchor += currentBlockHeight;
            currentFirstRowIndex = i + 1;
            currentBlockHeight = 0;
          }
        }
        return anchorToRowBlock;
      }
      function makeIdentity() {
        return {
          firstRowIndex: null,
          lastRowIndex: null,
          rows: []
        };
      }
    }
  });

  // src/traces/table/data_split_helpers.js
  var require_data_split_helpers = __commonJS({
    "src/traces/table/data_split_helpers.js"(exports) {
      "use strict";
      var extendFlat = require_extend().extendFlat;
      exports.splitToPanels = function(d) {
        var prevPages = [0, 0];
        var headerPanel = extendFlat({}, d, {
          key: "header",
          type: "header",
          page: 0,
          prevPages,
          currentRepaint: [null, null],
          dragHandle: true,
          values: d.calcdata.headerCells.values[d.specIndex],
          rowBlocks: d.calcdata.headerRowBlocks,
          calcdata: extendFlat({}, d.calcdata, { cells: d.calcdata.headerCells })
        });
        var revolverPanel1 = extendFlat({}, d, {
          key: "cells1",
          type: "cells",
          page: 0,
          prevPages,
          currentRepaint: [null, null],
          dragHandle: false,
          values: d.calcdata.cells.values[d.specIndex],
          rowBlocks: d.calcdata.rowBlocks
        });
        var revolverPanel2 = extendFlat({}, d, {
          key: "cells2",
          type: "cells",
          page: 1,
          prevPages,
          currentRepaint: [null, null],
          dragHandle: false,
          values: d.calcdata.cells.values[d.specIndex],
          rowBlocks: d.calcdata.rowBlocks
        });
        return [revolverPanel1, revolverPanel2, headerPanel];
      };
      exports.splitToCells = function(d) {
        var fromTo = rowFromTo(d);
        return (d.values || []).slice(fromTo[0], fromTo[1]).map(function(v, i) {
          var buster = typeof v === "string" && v.match(/[<$&> ]/) ? "_keybuster_" + Math.random() : "";
          return {
            // keyWithinBlock: /*fromTo[0] + */i, // optimized future version - no busting
            // keyWithinBlock: fromTo[0] + i, // initial always-unoptimized version - janky scrolling with 5+ columns
            keyWithinBlock: i + buster,
            // current compromise: regular content is very fast; async content is possible
            key: fromTo[0] + i,
            column: d,
            calcdata: d.calcdata,
            page: d.page,
            rowBlocks: d.rowBlocks,
            value: v
          };
        });
      };
      function rowFromTo(d) {
        var rowBlock = d.rowBlocks[d.page];
        var rowFrom = rowBlock ? rowBlock.rows[0].rowIndex : 0;
        var rowTo = rowBlock ? rowFrom + rowBlock.rows.length : 0;
        return [rowFrom, rowTo];
      }
    }
  });

  // src/traces/table/plot.js
  var require_plot31 = __commonJS({
    "src/traces/table/plot.js"(exports, module) {
      "use strict";
      var c = require_constants31();
      var d3 = require_d3();
      var Lib = require_lib();
      var numberFormat = Lib.numberFormat;
      var gup = require_gup();
      var Drawing = require_drawing();
      var svgUtil = require_svg_text_utils();
      var raiseToTop = require_lib().raiseToTop;
      var strTranslate = require_lib().strTranslate;
      var cancelEeaseColumn = require_lib().cancelTransition;
      var prepareData = require_data_preparation_helper();
      var splitData = require_data_split_helpers();
      var Color2 = require_color();
      module.exports = function plot(gd, wrappedTraceHolders) {
        var dynamic = !gd._context.staticPlot;
        var table = gd._fullLayout._paper.selectAll("." + c.cn.table).data(wrappedTraceHolders.map(function(wrappedTraceHolder) {
          var traceHolder = gup.unwrap(wrappedTraceHolder);
          var trace = traceHolder.trace;
          return prepareData(gd, trace);
        }), gup.keyFun);
        table.exit().remove();
        table.enter().append("g").classed(c.cn.table, true).attr("overflow", "visible").style("box-sizing", "content-box").style("position", "absolute").style("left", 0).style("overflow", "visible").style("shape-rendering", "crispEdges").style("pointer-events", "all");
        table.attr("width", function(d) {
          return d.width + d.size.l + d.size.r;
        }).attr("height", function(d) {
          return d.height + d.size.t + d.size.b;
        }).attr("transform", function(d) {
          return strTranslate(d.translateX, d.translateY);
        });
        var tableControlView = table.selectAll("." + c.cn.tableControlView).data(gup.repeat, gup.keyFun);
        var cvEnter = tableControlView.enter().append("g").classed(c.cn.tableControlView, true).style("box-sizing", "content-box");
        if (dynamic) {
          var wheelEvent = "onwheel" in document ? "wheel" : "mousewheel";
          cvEnter.on("mousemove", function(d) {
            tableControlView.filter(function(dd) {
              return d === dd;
            }).call(renderScrollbarKit, gd);
          }).on(wheelEvent, function(d) {
            if (d.scrollbarState.wheeling) return;
            d.scrollbarState.wheeling = true;
            var newY = d.scrollY + d3.event.deltaY;
            var noChange = makeDragRow(gd, tableControlView, null, newY)(d);
            if (!noChange) {
              d3.event.stopPropagation();
              d3.event.preventDefault();
            }
            d.scrollbarState.wheeling = false;
          }).call(renderScrollbarKit, gd, true);
        }
        tableControlView.attr("transform", function(d) {
          return strTranslate(d.size.l, d.size.t);
        });
        var scrollBackground = tableControlView.selectAll("." + c.cn.scrollBackground).data(gup.repeat, gup.keyFun);
        scrollBackground.enter().append("rect").classed(c.cn.scrollBackground, true).attr("fill", "none");
        scrollBackground.attr("width", function(d) {
          return d.width;
        }).attr("height", function(d) {
          return d.height;
        });
        tableControlView.each(function(d) {
          Drawing.setClipUrl(d3.select(this), scrollAreaBottomClipKey(gd, d), gd);
        });
        var yColumn = tableControlView.selectAll("." + c.cn.yColumn).data(function(vm) {
          return vm.columns;
        }, gup.keyFun);
        yColumn.enter().append("g").classed(c.cn.yColumn, true);
        yColumn.exit().remove();
        yColumn.attr("transform", function(d) {
          return strTranslate(d.x, 0);
        });
        if (dynamic) {
          yColumn.call(
            d3.behavior.drag().origin(function(d) {
              var movedColumn = d3.select(this);
              easeColumn(movedColumn, d, -c.uplift);
              raiseToTop(this);
              d.calcdata.columnDragInProgress = true;
              renderScrollbarKit(tableControlView.filter(function(dd) {
                return d.calcdata.key === dd.key;
              }), gd);
              return d;
            }).on("drag", function(d) {
              var movedColumn = d3.select(this);
              var getter = function(dd) {
                return (d === dd ? d3.event.x : dd.x) + dd.columnWidth / 2;
              };
              d.x = Math.max(-c.overdrag, Math.min(d.calcdata.width + c.overdrag - d.columnWidth, d3.event.x));
              var sortableColumns = flatData(yColumn).filter(function(dd) {
                return dd.calcdata.key === d.calcdata.key;
              });
              var newOrder = sortableColumns.sort(function(a, b) {
                return getter(a) - getter(b);
              });
              newOrder.forEach(function(dd, i) {
                dd.xIndex = i;
                dd.x = d === dd ? dd.x : dd.xScale(dd);
              });
              yColumn.filter(function(dd) {
                return d !== dd;
              }).transition().ease(c.transitionEase).duration(c.transitionDuration).attr("transform", function(d2) {
                return strTranslate(d2.x, 0);
              });
              movedColumn.call(cancelEeaseColumn).attr("transform", strTranslate(d.x, -c.uplift));
            }).on("dragend", function(d) {
              var movedColumn = d3.select(this);
              var p = d.calcdata;
              d.x = d.xScale(d);
              d.calcdata.columnDragInProgress = false;
              easeColumn(movedColumn, d, 0);
              columnMoved(gd, p, p.columns.map(function(dd) {
                return dd.xIndex;
              }));
            })
          );
        }
        yColumn.each(function(d) {
          Drawing.setClipUrl(d3.select(this), columnBoundaryClipKey(gd, d), gd);
        });
        var columnBlock = yColumn.selectAll("." + c.cn.columnBlock).data(splitData.splitToPanels, gup.keyFun);
        columnBlock.enter().append("g").classed(c.cn.columnBlock, true).attr("id", function(d) {
          return d.key;
        });
        columnBlock.style("cursor", function(d) {
          return d.dragHandle ? "ew-resize" : d.calcdata.scrollbarState.barWiggleRoom ? "ns-resize" : "default";
        });
        var headerColumnBlock = columnBlock.filter(headerBlock);
        var cellsColumnBlock = columnBlock.filter(cellsBlock);
        if (dynamic) {
          cellsColumnBlock.call(
            d3.behavior.drag().origin(function(d) {
              d3.event.stopPropagation();
              return d;
            }).on("drag", makeDragRow(gd, tableControlView, -1)).on("dragend", function() {
            })
          );
        }
        renderColumnCellTree(gd, tableControlView, headerColumnBlock, columnBlock);
        renderColumnCellTree(gd, tableControlView, cellsColumnBlock, columnBlock);
        var scrollAreaClip = tableControlView.selectAll("." + c.cn.scrollAreaClip).data(gup.repeat, gup.keyFun);
        scrollAreaClip.enter().append("clipPath").classed(c.cn.scrollAreaClip, true).attr("id", function(d) {
          return scrollAreaBottomClipKey(gd, d);
        });
        var scrollAreaClipRect = scrollAreaClip.selectAll("." + c.cn.scrollAreaClipRect).data(gup.repeat, gup.keyFun);
        scrollAreaClipRect.enter().append("rect").classed(c.cn.scrollAreaClipRect, true).attr("x", -c.overdrag).attr("y", -c.uplift).attr("fill", "none");
        scrollAreaClipRect.attr("width", function(d) {
          return d.width + 2 * c.overdrag;
        }).attr("height", function(d) {
          return d.height + c.uplift;
        });
        var columnBoundary = yColumn.selectAll("." + c.cn.columnBoundary).data(gup.repeat, gup.keyFun);
        columnBoundary.enter().append("g").classed(c.cn.columnBoundary, true);
        var columnBoundaryClippath = yColumn.selectAll("." + c.cn.columnBoundaryClippath).data(gup.repeat, gup.keyFun);
        columnBoundaryClippath.enter().append("clipPath").classed(c.cn.columnBoundaryClippath, true);
        columnBoundaryClippath.attr("id", function(d) {
          return columnBoundaryClipKey(gd, d);
        });
        var columnBoundaryRect = columnBoundaryClippath.selectAll("." + c.cn.columnBoundaryRect).data(gup.repeat, gup.keyFun);
        columnBoundaryRect.enter().append("rect").classed(c.cn.columnBoundaryRect, true).attr("fill", "none");
        columnBoundaryRect.attr("width", function(d) {
          return d.columnWidth + 2 * roundHalfWidth(d);
        }).attr("height", function(d) {
          return d.calcdata.height + 2 * roundHalfWidth(d) + c.uplift;
        }).attr("x", function(d) {
          return -roundHalfWidth(d);
        }).attr("y", function(d) {
          return -roundHalfWidth(d);
        });
        updateBlockYPosition(null, cellsColumnBlock, tableControlView);
      };
      function roundHalfWidth(d) {
        return Math.ceil(d.calcdata.maxLineWidth / 2);
      }
      function scrollAreaBottomClipKey(gd, d) {
        return "clip" + gd._fullLayout._uid + "_scrollAreaBottomClip_" + d.key;
      }
      function columnBoundaryClipKey(gd, d) {
        return "clip" + gd._fullLayout._uid + "_columnBoundaryClippath_" + d.calcdata.key + "_" + d.specIndex;
      }
      function flatData(selection) {
        return [].concat.apply([], selection.map(function(g) {
          return g;
        })).map(function(g) {
          return g.__data__;
        });
      }
      function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) {
        function calcTotalHeight(d) {
          var blocks = d.rowBlocks;
          return firstRowAnchor(blocks, blocks.length - 1) + (blocks.length ? rowsHeight(blocks[blocks.length - 1], Infinity) : 1);
        }
        var scrollbarKit = tableControlView.selectAll("." + c.cn.scrollbarKit).data(gup.repeat, gup.keyFun);
        scrollbarKit.enter().append("g").classed(c.cn.scrollbarKit, true).style("shape-rendering", "geometricPrecision");
        scrollbarKit.each(function(d) {
          var s = d.scrollbarState;
          s.totalHeight = calcTotalHeight(d);
          s.scrollableAreaHeight = d.groupHeight - headerHeight(d);
          s.currentlyVisibleHeight = Math.min(s.totalHeight, s.scrollableAreaHeight);
          s.ratio = s.currentlyVisibleHeight / s.totalHeight;
          s.barLength = Math.max(s.ratio * s.currentlyVisibleHeight, c.goldenRatio * c.scrollbarWidth);
          s.barWiggleRoom = s.currentlyVisibleHeight - s.barLength;
          s.wiggleRoom = Math.max(0, s.totalHeight - s.scrollableAreaHeight);
          s.topY = s.barWiggleRoom === 0 ? 0 : d.scrollY / s.wiggleRoom * s.barWiggleRoom;
          s.bottomY = s.topY + s.barLength;
          s.dragMultiplier = s.wiggleRoom / s.barWiggleRoom;
        }).attr("transform", function(d) {
          var xPosition2 = d.width + c.scrollbarWidth / 2 + c.scrollbarOffset;
          return strTranslate(xPosition2, headerHeight(d));
        });
        var scrollbar = scrollbarKit.selectAll("." + c.cn.scrollbar).data(gup.repeat, gup.keyFun);
        scrollbar.enter().append("g").classed(c.cn.scrollbar, true);
        var scrollbarSlider = scrollbar.selectAll("." + c.cn.scrollbarSlider).data(gup.repeat, gup.keyFun);
        scrollbarSlider.enter().append("g").classed(c.cn.scrollbarSlider, true);
        scrollbarSlider.attr("transform", function(d) {
          return strTranslate(0, d.scrollbarState.topY || 0);
        });
        var scrollbarGlyph = scrollbarSlider.selectAll("." + c.cn.scrollbarGlyph).data(gup.repeat, gup.keyFun);
        scrollbarGlyph.enter().append("line").classed(c.cn.scrollbarGlyph, true).attr("stroke", "black").attr("stroke-width", c.scrollbarWidth).attr("stroke-linecap", "round").attr("y1", c.scrollbarWidth / 2);
        scrollbarGlyph.attr("y2", function(d) {
          return d.scrollbarState.barLength - c.scrollbarWidth / 2;
        }).attr("stroke-opacity", function(d) {
          return d.columnDragInProgress || !d.scrollbarState.barWiggleRoom || bypassVisibleBar ? 0 : 0.4;
        });
        scrollbarGlyph.transition().delay(0).duration(0);
        scrollbarGlyph.transition().delay(c.scrollbarHideDelay).duration(c.scrollbarHideDuration).attr("stroke-opacity", 0);
        var scrollbarCaptureZone = scrollbar.selectAll("." + c.cn.scrollbarCaptureZone).data(gup.repeat, gup.keyFun);
        scrollbarCaptureZone.enter().append("line").classed(c.cn.scrollbarCaptureZone, true).attr("stroke", "white").attr("stroke-opacity", 0.01).attr("stroke-width", c.scrollbarCaptureWidth).attr("stroke-linecap", "butt").attr("y1", 0).on("mousedown", function(d) {
          var y = d3.event.y;
          var bbox = this.getBoundingClientRect();
          var s = d.scrollbarState;
          var pixelVal = y - bbox.top;
          var inverseScale = d3.scale.linear().domain([0, s.scrollableAreaHeight]).range([0, s.totalHeight]).clamp(true);
          if (!(s.topY <= pixelVal && pixelVal <= s.bottomY)) {
            makeDragRow(gd, tableControlView, null, inverseScale(pixelVal - s.barLength / 2))(d);
          }
        }).call(
          d3.behavior.drag().origin(function(d) {
            d3.event.stopPropagation();
            d.scrollbarState.scrollbarScrollInProgress = true;
            return d;
          }).on("drag", makeDragRow(gd, tableControlView)).on("dragend", function() {
          })
        );
        scrollbarCaptureZone.attr("y2", function(d) {
          return d.scrollbarState.scrollableAreaHeight;
        });
        if (gd._context.staticPlot) {
          scrollbarGlyph.remove();
          scrollbarCaptureZone.remove();
        }
      }
      function renderColumnCellTree(gd, tableControlView, columnBlock, allColumnBlock) {
        var columnCells = renderColumnCells(columnBlock);
        var columnCell = renderColumnCell(columnCells);
        supplyStylingValues(columnCell);
        var cellRect = renderCellRect(columnCell);
        sizeAndStyleRect(cellRect);
        var cellTextHolder = renderCellTextHolder(columnCell);
        var cellText = renderCellText(cellTextHolder);
        setFont(cellText);
        populateCellText(cellText, tableControlView, allColumnBlock, gd);
        setCellHeightAndPositionY(columnCell);
      }
      function renderColumnCells(columnBlock) {
        var columnCells = columnBlock.selectAll("." + c.cn.columnCells).data(gup.repeat, gup.keyFun);
        columnCells.enter().append("g").classed(c.cn.columnCells, true);
        columnCells.exit().remove();
        return columnCells;
      }
      function renderColumnCell(columnCells) {
        var columnCell = columnCells.selectAll("." + c.cn.columnCell).data(splitData.splitToCells, function(d) {
          return d.keyWithinBlock;
        });
        columnCell.enter().append("g").classed(c.cn.columnCell, true);
        columnCell.exit().remove();
        return columnCell;
      }
      function renderCellRect(columnCell) {
        var cellRect = columnCell.selectAll("." + c.cn.cellRect).data(gup.repeat, function(d) {
          return d.keyWithinBlock;
        });
        cellRect.enter().append("rect").classed(c.cn.cellRect, true);
        return cellRect;
      }
      function renderCellText(cellTextHolder) {
        var cellText = cellTextHolder.selectAll("." + c.cn.cellText).data(gup.repeat, function(d) {
          return d.keyWithinBlock;
        });
        cellText.enter().append("text").classed(c.cn.cellText, true).style("cursor", function() {
          return "auto";
        }).on("mousedown", function() {
          d3.event.stopPropagation();
        });
        return cellText;
      }
      function renderCellTextHolder(columnCell) {
        var cellTextHolder = columnCell.selectAll("." + c.cn.cellTextHolder).data(gup.repeat, function(d) {
          return d.keyWithinBlock;
        });
        cellTextHolder.enter().append("g").classed(c.cn.cellTextHolder, true).style("shape-rendering", "geometricPrecision");
        return cellTextHolder;
      }
      function supplyStylingValues(columnCell) {
        columnCell.each(function(d, i) {
          var spec = d.calcdata.cells.font;
          var col = d.column.specIndex;
          var font = {
            size: gridPick(spec.size, col, i),
            color: gridPick(spec.color, col, i),
            family: gridPick(spec.family, col, i),
            weight: gridPick(spec.weight, col, i),
            style: gridPick(spec.style, col, i),
            variant: gridPick(spec.variant, col, i),
            textcase: gridPick(spec.textcase, col, i),
            lineposition: gridPick(spec.lineposition, col, i),
            shadow: gridPick(spec.shadow, col, i)
          };
          d.rowNumber = d.key;
          d.align = gridPick(d.calcdata.cells.align, col, i);
          d.cellBorderWidth = gridPick(d.calcdata.cells.line.width, col, i);
          d.font = font;
        });
      }
      function setFont(cellText) {
        cellText.each(function(d) {
          Drawing.font(d3.select(this), d.font);
        });
      }
      function sizeAndStyleRect(cellRect) {
        cellRect.attr("width", function(d) {
          return d.column.columnWidth;
        }).attr("stroke-width", function(d) {
          return d.cellBorderWidth;
        }).each(function(d) {
          var atomicSelection = d3.select(this);
          Color2.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber));
          Color2.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber));
        });
      }
      function populateCellText(cellText, tableControlView, allColumnBlock, gd) {
        cellText.text(function(d) {
          var col = d.column.specIndex;
          var row = d.rowNumber;
          var userSuppliedContent = d.value;
          var stringSupplied = typeof userSuppliedContent === "string";
          var hasBreaks = stringSupplied && userSuppliedContent.match(/<br>/i);
          var userBrokenText = !stringSupplied || hasBreaks;
          d.mayHaveMarkup = stringSupplied && userSuppliedContent.match(/[<&>]/);
          var latex = isLatex(userSuppliedContent);
          d.latex = latex;
          var prefix = latex ? "" : gridPick(d.calcdata.cells.prefix, col, row) || "";
          var suffix = latex ? "" : gridPick(d.calcdata.cells.suffix, col, row) || "";
          var format = latex ? null : gridPick(d.calcdata.cells.format, col, row) || null;
          var prefixSuffixedText = prefix + (format ? numberFormat(format)(d.value) : d.value) + suffix;
          var hasWrapSplitCharacter;
          d.wrappingNeeded = !d.wrapped && !userBrokenText && !latex && (hasWrapSplitCharacter = hasWrapCharacter(prefixSuffixedText));
          d.cellHeightMayIncrease = hasBreaks || latex || d.mayHaveMarkup || (hasWrapSplitCharacter === void 0 ? hasWrapCharacter(prefixSuffixedText) : hasWrapSplitCharacter);
          d.needsConvertToTspans = d.mayHaveMarkup || d.wrappingNeeded || d.latex;
          var textToRender;
          if (d.wrappingNeeded) {
            var hrefPreservedText = c.wrapSplitCharacter === " " ? prefixSuffixedText.replace(/<a href=/ig, "<a_href=") : prefixSuffixedText;
            var fragments = hrefPreservedText.split(c.wrapSplitCharacter);
            var hrefRestoredFragments = c.wrapSplitCharacter === " " ? fragments.map(function(frag) {
              return frag.replace(/<a_href=/ig, "<a href=");
            }) : fragments;
            d.fragments = hrefRestoredFragments.map(function(f) {
              return { text: f, width: null };
            });
            d.fragments.push({ fragment: c.wrapSpacer, width: null });
            textToRender = hrefRestoredFragments.join(c.lineBreaker) + c.lineBreaker + c.wrapSpacer;
          } else {
            delete d.fragments;
            textToRender = prefixSuffixedText;
          }
          return textToRender;
        }).attr("dy", function(d) {
          return d.needsConvertToTspans ? 0 : "0.75em";
        }).each(function(d) {
          var element = this;
          var selection = d3.select(element);
          var renderCallback = d.wrappingNeeded ? wrapTextMaker : updateYPositionMaker;
          if (d.needsConvertToTspans) {
            svgUtil.convertToTspans(selection, gd, renderCallback(allColumnBlock, element, tableControlView, gd, d));
          } else {
            d3.select(element.parentNode).attr("transform", function(d2) {
              return strTranslate(xPosition(d2), c.cellPad);
            }).attr("text-anchor", function(d2) {
              return {
                left: "start",
                center: "middle",
                right: "end"
              }[d2.align];
            });
          }
        });
      }
      function isLatex(content) {
        return typeof content === "string" && content.match(c.latexCheck);
      }
      function hasWrapCharacter(text) {
        return text.indexOf(c.wrapSplitCharacter) !== -1;
      }
      function columnMoved(gd, calcdata, indices) {
        var o = calcdata.gdColumnsOriginalOrder;
        calcdata.gdColumns.sort(function(a, b) {
          return indices[o.indexOf(a)] - indices[o.indexOf(b)];
        });
        calcdata.columnorder = indices;
        gd.emit("plotly_restyle");
      }
      function gridPick(spec, col, row) {
        if (Lib.isArrayOrTypedArray(spec)) {
          var column = spec[Math.min(col, spec.length - 1)];
          if (Lib.isArrayOrTypedArray(column)) {
            return column[Math.min(row, column.length - 1)];
          } else {
            return column;
          }
        } else {
          return spec;
        }
      }
      function easeColumn(selection, d, y) {
        selection.transition().ease(c.releaseTransitionEase).duration(c.releaseTransitionDuration).attr("transform", strTranslate(d.x, y));
      }
      function cellsBlock(d) {
        return d.type === "cells";
      }
      function headerBlock(d) {
        return d.type === "header";
      }
      function headerHeight(d) {
        var headerBlocks = d.rowBlocks.length ? d.rowBlocks[0].auxiliaryBlocks : [];
        return headerBlocks.reduce(function(p, n) {
          return p + rowsHeight(n, Infinity);
        }, 0);
      }
      function findPagesAndCacheHeights(blocks, scrollY, scrollHeight) {
        var pages = [];
        var pTop = 0;
        for (var blockIndex = 0; blockIndex < blocks.length; blockIndex++) {
          var block = blocks[blockIndex];
          var blockRows = block.rows;
          var rowsHeight2 = 0;
          for (var i = 0; i < blockRows.length; i++) {
            rowsHeight2 += blockRows[i].rowHeight;
          }
          block.allRowsHeight = rowsHeight2;
          var pBottom = pTop + rowsHeight2;
          var windowTop = scrollY;
          var windowBottom = windowTop + scrollHeight;
          if (windowTop < pBottom && windowBottom > pTop) {
            pages.push(blockIndex);
          }
          pTop += rowsHeight2;
        }
        return pages;
      }
      function updateBlockYPosition(gd, cellsColumnBlock, tableControlView) {
        var d = flatData(cellsColumnBlock)[0];
        if (d === void 0) return;
        var blocks = d.rowBlocks;
        var calcdata = d.calcdata;
        var bottom = firstRowAnchor(blocks, blocks.length);
        var scrollHeight = d.calcdata.groupHeight - headerHeight(d);
        var scrollY = calcdata.scrollY = Math.max(0, Math.min(bottom - scrollHeight, calcdata.scrollY));
        var pages = findPagesAndCacheHeights(blocks, scrollY, scrollHeight);
        if (pages.length === 1) {
          if (pages[0] === blocks.length - 1) {
            pages.unshift(pages[0] - 1);
          } else {
            pages.push(pages[0] + 1);
          }
        }
        if (pages[0] % 2) {
          pages.reverse();
        }
        cellsColumnBlock.each(function(d2, i) {
          d2.page = pages[i];
          d2.scrollY = scrollY;
        });
        cellsColumnBlock.attr("transform", function(d2) {
          var yTranslate = firstRowAnchor(d2.rowBlocks, d2.page) - d2.scrollY;
          return strTranslate(0, yTranslate);
        });
        if (gd) {
          conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 0);
          conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, d.prevPages, d, 1);
          renderScrollbarKit(tableControlView, gd);
        }
      }
      function makeDragRow(gd, allTableControlView, optionalMultiplier, optionalPosition) {
        return function dragRow(eventD) {
          var d = eventD.calcdata ? eventD.calcdata : eventD;
          var tableControlView = allTableControlView.filter(function(dd) {
            return d.key === dd.key;
          });
          var multiplier = optionalMultiplier || d.scrollbarState.dragMultiplier;
          var initialScrollY = d.scrollY;
          d.scrollY = optionalPosition === void 0 ? d.scrollY + multiplier * d3.event.dy : optionalPosition;
          var cellsColumnBlock = tableControlView.selectAll("." + c.cn.yColumn).selectAll("." + c.cn.columnBlock).filter(cellsBlock);
          updateBlockYPosition(gd, cellsColumnBlock, tableControlView);
          return d.scrollY === initialScrollY;
        };
      }
      function conditionalPanelRerender(gd, tableControlView, cellsColumnBlock, pages, prevPages, d, revolverIndex) {
        var shouldComponentUpdate = pages[revolverIndex] !== prevPages[revolverIndex];
        if (shouldComponentUpdate) {
          clearTimeout(d.currentRepaint[revolverIndex]);
          d.currentRepaint[revolverIndex] = setTimeout(function() {
            var toRerender = cellsColumnBlock.filter(function(d2, i) {
              return i === revolverIndex && pages[i] !== prevPages[i];
            });
            renderColumnCellTree(gd, tableControlView, toRerender, cellsColumnBlock);
            prevPages[revolverIndex] = pages[revolverIndex];
          });
        }
      }
      function wrapTextMaker(columnBlock, element, tableControlView, gd) {
        return function wrapText() {
          var cellTextHolder = d3.select(element.parentNode);
          cellTextHolder.each(function(d) {
            var fragments = d.fragments;
            cellTextHolder.selectAll("tspan.line").each(function(dd, i) {
              fragments[i].width = this.getComputedTextLength();
            });
            var separatorLength = fragments[fragments.length - 1].width;
            var rest = fragments.slice(0, -1);
            var currentRow = [];
            var currentAddition, currentAdditionLength;
            var currentRowLength = 0;
            var rowLengthLimit = d.column.columnWidth - 2 * c.cellPad;
            d.value = "";
            while (rest.length) {
              currentAddition = rest.shift();
              currentAdditionLength = currentAddition.width + separatorLength;
              if (currentRowLength + currentAdditionLength > rowLengthLimit) {
                d.value += currentRow.join(c.wrapSpacer) + c.lineBreaker;
                currentRow = [];
                currentRowLength = 0;
              }
              currentRow.push(currentAddition.text);
              currentRowLength += currentAdditionLength;
            }
            if (currentRowLength) {
              d.value += currentRow.join(c.wrapSpacer);
            }
            d.wrapped = true;
          });
          cellTextHolder.selectAll("tspan.line").remove();
          populateCellText(cellTextHolder.select("." + c.cn.cellText), tableControlView, columnBlock, gd);
          d3.select(element.parentNode.parentNode).call(setCellHeightAndPositionY);
        };
      }
      function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) {
        return function updateYPosition() {
          if (d.settledY) return;
          var cellTextHolder = d3.select(element.parentNode);
          var l = getBlock(d);
          var rowIndex = d.key - l.firstRowIndex;
          var declaredRowHeight = l.rows[rowIndex].rowHeight;
          var requiredHeight = d.cellHeightMayIncrease ? element.parentNode.getBoundingClientRect().height + 2 * c.cellPad : declaredRowHeight;
          var finalHeight = Math.max(requiredHeight, declaredRowHeight);
          var increase = finalHeight - l.rows[rowIndex].rowHeight;
          if (increase) {
            l.rows[rowIndex].rowHeight = finalHeight;
            columnBlock.selectAll("." + c.cn.columnCell).call(setCellHeightAndPositionY);
            updateBlockYPosition(null, columnBlock.filter(cellsBlock), 0);
            renderScrollbarKit(tableControlView, gd, true);
          }
          cellTextHolder.attr("transform", function() {
            var element2 = this;
            var columnCellElement = element2.parentNode;
            var box = columnCellElement.getBoundingClientRect();
            var rectBox = d3.select(element2.parentNode).select("." + c.cn.cellRect).node().getBoundingClientRect();
            var currentTransform = element2.transform.baseVal.consolidate();
            var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : c.cellPad);
            return strTranslate(xPosition(d, d3.select(element2.parentNode).select("." + c.cn.cellTextHolder).node().getBoundingClientRect().width), yPosition);
          });
          d.settledY = true;
        };
      }
      function xPosition(d, optionalWidth) {
        switch (d.align) {
          case "left":
            return c.cellPad;
          case "right":
            return d.column.columnWidth - (optionalWidth || 0) - c.cellPad;
          case "center":
            return (d.column.columnWidth - (optionalWidth || 0)) / 2;
          default:
            return c.cellPad;
        }
      }
      function setCellHeightAndPositionY(columnCell) {
        columnCell.attr("transform", function(d) {
          var headerHeight2 = d.rowBlocks[0].auxiliaryBlocks.reduce(function(p, n) {
            return p + rowsHeight(n, Infinity);
          }, 0);
          var l = getBlock(d);
          var rowAnchor = rowsHeight(l, d.key);
          var yOffset = rowAnchor + headerHeight2;
          return strTranslate(0, yOffset);
        }).selectAll("." + c.cn.cellRect).attr("height", function(d) {
          return getRow(getBlock(d), d.key).rowHeight;
        });
      }
      function firstRowAnchor(blocks, page) {
        var total = 0;
        for (var i = page - 1; i >= 0; i--) {
          total += allRowsHeight(blocks[i]);
        }
        return total;
      }
      function rowsHeight(rowBlock, key) {
        var total = 0;
        for (var i = 0; i < rowBlock.rows.length && rowBlock.rows[i].rowIndex < key; i++) {
          total += rowBlock.rows[i].rowHeight;
        }
        return total;
      }
      function allRowsHeight(rowBlock) {
        var cached = rowBlock.allRowsHeight;
        if (cached !== void 0) {
          return cached;
        }
        var total = 0;
        for (var i = 0; i < rowBlock.rows.length; i++) {
          total += rowBlock.rows[i].rowHeight;
        }
        rowBlock.allRowsHeight = total;
        return total;
      }
      function getBlock(d) {
        return d.rowBlocks[d.page];
      }
      function getRow(l, i) {
        return l.rows[i - l.firstRowIndex];
      }
    }
  });

  // src/traces/table/base_plot.js
  var require_base_plot11 = __commonJS({
    "src/traces/table/base_plot.js"(exports) {
      "use strict";
      var getModuleCalcData = require_get_data().getModuleCalcData;
      var tablePlot = require_plot31();
      var TABLE = "table";
      exports.name = TABLE;
      exports.plot = function(gd) {
        var calcData = getModuleCalcData(gd.calcdata, TABLE)[0];
        if (calcData.length) tablePlot(gd, calcData);
      };
      exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var hadTable = oldFullLayout._has && oldFullLayout._has(TABLE);
        var hasTable = newFullLayout._has && newFullLayout._has(TABLE);
        if (hadTable && !hasTable) {
          oldFullLayout._paperdiv.selectAll(".table").remove();
        }
      };
    }
  });

  // src/traces/table/index.js
  var require_table = __commonJS({
    "src/traces/table/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes62(),
        supplyDefaults: require_defaults58(),
        calc: require_calc37(),
        plot: require_plot31(),
        moduleType: "trace",
        name: "table",
        basePlotModule: require_base_plot11(),
        categories: ["noOpacity"],
        meta: {}
      };
    }
  });

  // lib/table.js
  var require_table2 = __commonJS({
    "lib/table.js"(exports, module) {
      "use strict";
      module.exports = require_table();
    }
  });

  // src/traces/carpet/axis_attributes.js
  var require_axis_attributes2 = __commonJS({
    "src/traces/carpet/axis_attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var colorAttrs = require_attributes3();
      var axesAttrs = require_layout_attributes4();
      var descriptionWithDates = require_axis_format_attributes().descriptionWithDates;
      var overrideAll = require_edit_types().overrideAll;
      var dash = require_attributes4().dash;
      var extendFlat = require_extend().extendFlat;
      module.exports = {
        color: {
          valType: "color",
          editType: "calc"
        },
        smoothing: {
          valType: "number",
          dflt: 1,
          min: 0,
          max: 1.3,
          editType: "calc"
        },
        title: {
          text: {
            valType: "string",
            dflt: "",
            editType: "calc"
          },
          font: fontAttrs({
            editType: "calc"
          }),
          // TODO how is this different than `title.standoff`
          offset: {
            valType: "number",
            dflt: 10,
            editType: "calc"
          },
          editType: "calc"
        },
        type: {
          valType: "enumerated",
          // '-' means we haven't yet run autotype or couldn't find any data
          // it gets turned into linear in gd._fullLayout but not copied back
          // to gd.data like the others are.
          values: ["-", "linear", "date", "category"],
          dflt: "-",
          editType: "calc"
        },
        autotypenumbers: axesAttrs.autotypenumbers,
        autorange: {
          valType: "enumerated",
          values: [true, false, "reversed"],
          dflt: true,
          editType: "calc"
        },
        rangemode: {
          valType: "enumerated",
          values: ["normal", "tozero", "nonnegative"],
          dflt: "normal",
          editType: "calc"
        },
        range: {
          valType: "info_array",
          editType: "calc",
          items: [
            { valType: "any", editType: "calc" },
            { valType: "any", editType: "calc" }
          ]
        },
        fixedrange: {
          valType: "boolean",
          dflt: false,
          editType: "calc"
        },
        cheatertype: {
          valType: "enumerated",
          values: ["index", "value"],
          dflt: "value",
          editType: "calc"
        },
        tickmode: {
          valType: "enumerated",
          values: ["linear", "array"],
          dflt: "array",
          editType: "calc"
        },
        nticks: {
          valType: "integer",
          min: 0,
          dflt: 0,
          editType: "calc"
        },
        tickvals: {
          valType: "data_array",
          editType: "calc"
        },
        ticktext: {
          valType: "data_array",
          editType: "calc"
        },
        showticklabels: {
          valType: "enumerated",
          values: ["start", "end", "both", "none"],
          dflt: "start",
          editType: "calc"
        },
        labelalias: extendFlat({}, axesAttrs.labelalias, { editType: "calc" }),
        tickfont: fontAttrs({
          editType: "calc"
        }),
        tickangle: {
          valType: "angle",
          dflt: "auto",
          editType: "calc"
        },
        tickprefix: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        showtickprefix: {
          valType: "enumerated",
          values: ["all", "first", "last", "none"],
          dflt: "all",
          editType: "calc"
        },
        ticksuffix: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        showticksuffix: {
          valType: "enumerated",
          values: ["all", "first", "last", "none"],
          dflt: "all",
          editType: "calc"
        },
        showexponent: {
          valType: "enumerated",
          values: ["all", "first", "last", "none"],
          dflt: "all",
          editType: "calc"
        },
        exponentformat: {
          valType: "enumerated",
          values: ["none", "e", "E", "power", "SI", "B", "SI extended"],
          dflt: "B",
          editType: "calc"
        },
        minexponent: {
          valType: "number",
          dflt: 3,
          min: 0,
          editType: "calc"
        },
        separatethousands: {
          valType: "boolean",
          dflt: false,
          editType: "calc"
        },
        tickformat: {
          valType: "string",
          dflt: "",
          editType: "calc",
          description: descriptionWithDates("tick label")
        },
        tickformatstops: overrideAll(axesAttrs.tickformatstops, "calc", "from-root"),
        categoryorder: {
          valType: "enumerated",
          values: [
            "trace",
            "category ascending",
            "category descending",
            "array"
            /* , 'value ascending', 'value descending'*/
            // value ascending / descending to be implemented later
          ],
          dflt: "trace",
          editType: "calc"
        },
        categoryarray: {
          valType: "data_array",
          editType: "calc"
        },
        labelpadding: {
          valType: "integer",
          dflt: 10,
          editType: "calc"
        },
        labelprefix: {
          valType: "string",
          editType: "calc"
        },
        labelsuffix: {
          valType: "string",
          dflt: "",
          editType: "calc"
        },
        // lines and grids
        showline: {
          valType: "boolean",
          dflt: false,
          editType: "calc"
        },
        linecolor: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "calc"
        },
        linewidth: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "calc"
        },
        gridcolor: {
          valType: "color",
          editType: "calc"
        },
        gridwidth: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "calc"
        },
        griddash: extendFlat({}, dash, { editType: "calc" }),
        showgrid: {
          valType: "boolean",
          dflt: true,
          editType: "calc"
        },
        minorgridcount: {
          valType: "integer",
          min: 0,
          dflt: 0,
          editType: "calc"
        },
        minorgridwidth: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "calc"
        },
        minorgriddash: extendFlat({}, dash, { editType: "calc" }),
        minorgridcolor: {
          valType: "color",
          dflt: colorAttrs.lightLine,
          editType: "calc"
        },
        startline: {
          valType: "boolean",
          editType: "calc"
        },
        startlinecolor: {
          valType: "color",
          editType: "calc"
        },
        startlinewidth: {
          valType: "number",
          dflt: 1,
          editType: "calc"
        },
        endline: {
          valType: "boolean",
          editType: "calc"
        },
        endlinewidth: {
          valType: "number",
          dflt: 1,
          editType: "calc"
        },
        endlinecolor: {
          valType: "color",
          editType: "calc"
        },
        tick0: {
          valType: "number",
          min: 0,
          dflt: 0,
          editType: "calc"
        },
        dtick: {
          valType: "number",
          min: 0,
          dflt: 1,
          editType: "calc"
        },
        arraytick0: {
          valType: "integer",
          min: 0,
          dflt: 0,
          editType: "calc"
        },
        arraydtick: {
          valType: "integer",
          min: 1,
          dflt: 1,
          editType: "calc"
        },
        editType: "calc"
      };
    }
  });

  // src/traces/carpet/attributes.js
  var require_attributes63 = __commonJS({
    "src/traces/carpet/attributes.js"(exports, module) {
      "use strict";
      var fontAttrs = require_font_attributes();
      var axisAttrs = require_axis_attributes2();
      var colorAttrs = require_attributes3();
      var carpetFont = fontAttrs({
        editType: "calc"
      });
      var zorder = require_attributes12().zorder;
      carpetFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
      carpetFont.size.dflt = 12;
      carpetFont.color.dflt = colorAttrs.defaultLine;
      module.exports = {
        carpet: {
          valType: "string",
          editType: "calc"
        },
        x: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        y: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        a: {
          valType: "data_array",
          editType: "calc"
        },
        a0: {
          valType: "number",
          dflt: 0,
          editType: "calc"
        },
        da: {
          valType: "number",
          dflt: 1,
          editType: "calc"
        },
        b: {
          valType: "data_array",
          editType: "calc"
        },
        b0: {
          valType: "number",
          dflt: 0,
          editType: "calc"
        },
        db: {
          valType: "number",
          dflt: 1,
          editType: "calc"
        },
        cheaterslope: {
          valType: "number",
          dflt: 1,
          editType: "calc"
        },
        aaxis: axisAttrs,
        baxis: axisAttrs,
        font: carpetFont,
        color: {
          valType: "color",
          dflt: colorAttrs.defaultLine,
          editType: "plot"
        },
        zorder
      };
    }
  });

  // src/traces/carpet/xy_defaults.js
  var require_xy_defaults2 = __commonJS({
    "src/traces/carpet/xy_defaults.js"(exports, module) {
      "use strict";
      var isArray1D = require_lib().isArray1D;
      module.exports = function handleXYDefaults(traceIn, traceOut, coerce) {
        var x = coerce("x");
        var hasX = x && x.length;
        var y = coerce("y");
        var hasY = y && y.length;
        if (!hasX && !hasY) return false;
        traceOut._cheater = !x;
        if ((!hasX || isArray1D(x)) && (!hasY || isArray1D(y))) {
          var len = hasX ? x.length : Infinity;
          if (hasY) len = Math.min(len, y.length);
          if (traceOut.a && traceOut.a.length) len = Math.min(len, traceOut.a.length);
          if (traceOut.b && traceOut.b.length) len = Math.min(len, traceOut.b.length);
          traceOut._length = len;
        } else traceOut._length = null;
        return true;
      };
    }
  });

  // src/traces/carpet/axis_defaults.js
  var require_axis_defaults3 = __commonJS({
    "src/traces/carpet/axis_defaults.js"(exports, module) {
      "use strict";
      var carpetAttrs = require_attributes63();
      var addOpacity = require_color().addOpacity;
      var Registry = require_registry();
      var Lib = require_lib();
      var handleTickValueDefaults = require_tick_value_defaults();
      var handleTickLabelDefaults = require_tick_label_defaults();
      var handlePrefixSuffixDefaults = require_prefix_suffix_defaults();
      var handleCategoryOrderDefaults = require_category_order_defaults();
      var setConvert = require_set_convert();
      var autoType = require_axis_autotype();
      module.exports = function handleAxisDefaults(containerIn, containerOut, options) {
        var letter = options.letter;
        var font = options.font || {};
        var attributes = carpetAttrs[letter + "axis"];
        function coerce(attr, dflt) {
          return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
        }
        function coerce2(attr, dflt) {
          return Lib.coerce2(containerIn, containerOut, attributes, attr, dflt);
        }
        if (options.name) {
          containerOut._name = options.name;
          containerOut._id = options.name;
        }
        coerce("autotypenumbers", options.autotypenumbersDflt);
        var axType = coerce("type");
        if (axType === "-") {
          if (options.data) setAutoType(containerOut, options.data);
          if (containerOut.type === "-") {
            containerOut.type = "linear";
          } else {
            axType = containerIn.type = containerOut.type;
          }
        }
        coerce("smoothing");
        coerce("cheatertype");
        coerce("showticklabels");
        coerce("labelprefix", letter + " = ");
        coerce("labelsuffix");
        coerce("showtickprefix");
        coerce("showticksuffix");
        coerce("separatethousands");
        coerce("tickformat");
        coerce("exponentformat");
        coerce("minexponent");
        coerce("showexponent");
        coerce("categoryorder");
        coerce("tickmode");
        coerce("tickvals");
        coerce("ticktext");
        coerce("tick0");
        coerce("dtick");
        if (containerOut.tickmode === "array") {
          coerce("arraytick0");
          coerce("arraydtick");
        }
        coerce("labelpadding");
        containerOut._hovertitle = letter;
        if (axType === "date") {
          var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleDefaults");
          handleCalendarDefaults(containerIn, containerOut, "calendar", options.calendar);
        }
        setConvert(containerOut, options.fullLayout);
        containerOut.c2p = Lib.identity;
        var dfltColor = coerce("color", options.dfltColor);
        var dfltFontColor = dfltColor === containerIn.color ? dfltColor : font.color;
        var title = coerce("title.text");
        if (title) {
          Lib.coerceFont(coerce, "title.font", font, { overrideDflt: {
            size: Lib.bigFont(font.size),
            color: dfltFontColor
          } });
          coerce("title.offset");
        }
        coerce("tickangle");
        var autoRange = coerce("autorange", !containerOut.isValidRange(containerIn.range));
        if (autoRange) coerce("rangemode");
        coerce("range");
        containerOut.cleanRange();
        coerce("fixedrange");
        handleTickValueDefaults(containerIn, containerOut, coerce, axType);
        handlePrefixSuffixDefaults(containerIn, containerOut, coerce, axType, options);
        handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
        handleCategoryOrderDefaults(containerIn, containerOut, coerce, {
          data: options.data,
          dataAttr: letter
        });
        var gridColor = coerce2("gridcolor", addOpacity(dfltColor, 0.3));
        var gridWidth = coerce2("gridwidth");
        var gridDash = coerce2("griddash");
        var showGrid = coerce("showgrid");
        if (!showGrid) {
          delete containerOut.gridcolor;
          delete containerOut.gridwidth;
          delete containerOut.griddash;
        }
        var startLineColor = coerce2("startlinecolor", dfltColor);
        var startLineWidth = coerce2("startlinewidth", gridWidth);
        var showStartLine = coerce("startline", containerOut.showgrid || !!startLineColor || !!startLineWidth);
        if (!showStartLine) {
          delete containerOut.startlinecolor;
          delete containerOut.startlinewidth;
        }
        var endLineColor = coerce2("endlinecolor", dfltColor);
        var endLineWidth = coerce2("endlinewidth", gridWidth);
        var showEndLine = coerce("endline", containerOut.showgrid || !!endLineColor || !!endLineWidth);
        if (!showEndLine) {
          delete containerOut.endlinecolor;
          delete containerOut.endlinewidth;
        }
        if (!showGrid) {
          delete containerOut.gridcolor;
          delete containerOut.gridwidth;
          delete containerOut.griddash;
        } else {
          coerce("minorgridcount");
          coerce("minorgridwidth", gridWidth);
          coerce("minorgriddash", gridDash);
          coerce("minorgridcolor", addOpacity(gridColor, 0.06));
          if (!containerOut.minorgridcount) {
            delete containerOut.minorgridwidth;
            delete containerOut.minorgriddash;
            delete containerOut.minorgridcolor;
          }
        }
        if (containerOut.showticklabels === "none") {
          delete containerOut.tickfont;
          delete containerOut.tickangle;
          delete containerOut.showexponent;
          delete containerOut.exponentformat;
          delete containerOut.minexponent;
          delete containerOut.tickformat;
          delete containerOut.showticksuffix;
          delete containerOut.showtickprefix;
        }
        if (!containerOut.showticksuffix) {
          delete containerOut.ticksuffix;
        }
        if (!containerOut.showtickprefix) {
          delete containerOut.tickprefix;
        }
        coerce("tickmode");
        return containerOut;
      };
      function setAutoType(ax, data) {
        if (ax.type !== "-") return;
        var id = ax._id;
        var axLetter = id.charAt(0);
        var calAttr = axLetter + "calendar";
        var calendar = ax[calAttr];
        ax.type = autoType(data, calendar, {
          autotypenumbers: ax.autotypenumbers
        });
      }
    }
  });

  // src/traces/carpet/ab_defaults.js
  var require_ab_defaults = __commonJS({
    "src/traces/carpet/ab_defaults.js"(exports, module) {
      "use strict";
      var handleAxisDefaults = require_axis_defaults3();
      var Template = require_plot_template();
      module.exports = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) {
        var a = coerce("a");
        if (!a) {
          coerce("da");
          coerce("a0");
        }
        var b = coerce("b");
        if (!b) {
          coerce("db");
          coerce("b0");
        }
        mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor);
      };
      function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) {
        var axesList = ["aaxis", "baxis"];
        axesList.forEach(function(axName) {
          var axLetter = axName.charAt(0);
          var axIn = traceIn[axName] || {};
          var axOut = Template.newContainer(traceOut, axName);
          var defaultOptions = {
            noAutotickangles: true,
            noTicklabelshift: true,
            noTicklabelstandoff: true,
            noTicklabelstep: true,
            tickfont: "x",
            id: axLetter + "axis",
            letter: axLetter,
            font: traceOut.font,
            name: axName,
            data: traceIn[axLetter],
            calendar: traceOut.calendar,
            dfltColor,
            bgColor: fullLayout.paper_bgcolor,
            autotypenumbersDflt: fullLayout.autotypenumbers,
            fullLayout
          };
          handleAxisDefaults(axIn, axOut, defaultOptions);
          axOut._categories = axOut._categories || [];
          if (!traceIn[axName] && axIn.type !== "-") {
            traceIn[axName] = { type: axIn.type };
          }
        });
      }
    }
  });

  // src/traces/carpet/defaults.js
  var require_defaults59 = __commonJS({
    "src/traces/carpet/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleXYDefaults = require_xy_defaults2();
      var handleABDefaults = require_ab_defaults();
      var attributes = require_attributes63();
      var colorAttrs = require_attributes3();
      module.exports = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        traceOut._clipPathId = "clip" + traceOut.uid + "carpet";
        var defaultColor = coerce("color", colorAttrs.defaultLine);
        Lib.coerceFont(coerce, "font", fullLayout.font);
        coerce("carpet");
        handleABDefaults(traceIn, traceOut, fullLayout, coerce, defaultColor);
        if (!traceOut.a || !traceOut.b) {
          traceOut.visible = false;
          return;
        }
        if (traceOut.a.length < 3) {
          traceOut.aaxis.smoothing = 0;
        }
        if (traceOut.b.length < 3) {
          traceOut.baxis.smoothing = 0;
        }
        var validData = handleXYDefaults(traceIn, traceOut, coerce);
        if (!validData) {
          traceOut.visible = false;
        }
        if (traceOut._cheater) {
          coerce("cheaterslope");
        }
        coerce("zorder");
      };
    }
  });

  // src/traces/carpet/map_1d_array.js
  var require_map_1d_array = __commonJS({
    "src/traces/carpet/map_1d_array.js"(exports, module) {
      "use strict";
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      module.exports = function mapArray(out, data, func) {
        var i;
        if (!isArrayOrTypedArray(out)) {
          out = [];
        } else if (out.length > data.length) {
          out = out.slice(0, data.length);
        }
        for (i = 0; i < data.length; i++) {
          out[i] = func(data[i]);
        }
        return out;
      };
    }
  });

  // src/traces/carpet/makepath.js
  var require_makepath = __commonJS({
    "src/traces/carpet/makepath.js"(exports, module) {
      "use strict";
      module.exports = function makePath(xp, yp, isBicubic) {
        if (xp.length === 0) return "";
        var i;
        var path = [];
        var stride = isBicubic ? 3 : 1;
        for (i = 0; i < xp.length; i += stride) {
          path.push(xp[i] + "," + yp[i]);
          if (isBicubic && i < xp.length - stride) {
            path.push("C");
            path.push([
              xp[i + 1] + "," + yp[i + 1],
              xp[i + 2] + "," + yp[i + 2] + " "
            ].join(" "));
          }
        }
        return path.join(isBicubic ? "" : "L");
      };
    }
  });

  // src/traces/carpet/orient_text.js
  var require_orient_text = __commonJS({
    "src/traces/carpet/orient_text.js"(exports, module) {
      "use strict";
      module.exports = function orientText(trace, xaxis, yaxis, xy, dxy, refDxy) {
        var dx = dxy[0] * trace.dpdx(xaxis);
        var dy = dxy[1] * trace.dpdy(yaxis);
        var flip = 1;
        var offsetMultiplier = 1;
        if (refDxy) {
          var l1 = Math.sqrt(dxy[0] * dxy[0] + dxy[1] * dxy[1]);
          var l2 = Math.sqrt(refDxy[0] * refDxy[0] + refDxy[1] * refDxy[1]);
          var dot = (dxy[0] * refDxy[0] + dxy[1] * refDxy[1]) / l1 / l2;
          offsetMultiplier = Math.max(0, dot);
        }
        var angle = Math.atan2(dy, dx) * 180 / Math.PI;
        if (angle < -90) {
          angle += 180;
          flip = -flip;
        } else if (angle > 90) {
          angle -= 180;
          flip = -flip;
        }
        return {
          angle,
          flip,
          p: trace.c2p(xy, xaxis, yaxis),
          offsetMultplier: offsetMultiplier
        };
      };
    }
  });

  // src/traces/carpet/plot.js
  var require_plot32 = __commonJS({
    "src/traces/carpet/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var map1dArray = require_map_1d_array();
      var makepath = require_makepath();
      var orientText = require_orient_text();
      var svgTextUtils = require_svg_text_utils();
      var Lib = require_lib();
      var strRotate = Lib.strRotate;
      var strTranslate = Lib.strTranslate;
      var alignmentConstants = require_alignment();
      module.exports = function plot(gd, plotinfo, cdcarpet, carpetLayer) {
        var isStatic = gd._context.staticPlot;
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        var fullLayout = gd._fullLayout;
        var clipLayer = fullLayout._clips;
        Lib.makeTraceGroups(carpetLayer, cdcarpet, "trace").each(function(cd) {
          var axisLayer = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          var aax = trace.aaxis;
          var bax = trace.baxis;
          var minorLayer = Lib.ensureSingle(axisLayer, "g", "minorlayer");
          var majorLayer = Lib.ensureSingle(axisLayer, "g", "majorlayer");
          var boundaryLayer = Lib.ensureSingle(axisLayer, "g", "boundarylayer");
          var labelLayer = Lib.ensureSingle(axisLayer, "g", "labellayer");
          axisLayer.style("opacity", trace.opacity);
          drawGridLines(xa, ya, majorLayer, aax, "a", aax._gridlines, true, isStatic);
          drawGridLines(xa, ya, majorLayer, bax, "b", bax._gridlines, true, isStatic);
          drawGridLines(xa, ya, minorLayer, aax, "a", aax._minorgridlines, true, isStatic);
          drawGridLines(xa, ya, minorLayer, bax, "b", bax._minorgridlines, true, isStatic);
          drawGridLines(xa, ya, boundaryLayer, aax, "a-boundary", aax._boundarylines, isStatic);
          drawGridLines(xa, ya, boundaryLayer, bax, "b-boundary", bax._boundarylines, isStatic);
          var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, aax._labels, "a-label");
          var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, cd0, labelLayer, bax._labels, "b-label");
          drawAxisTitles(gd, labelLayer, trace, cd0, xa, ya, labelOrientationA, labelOrientationB);
          drawClipPath(trace, cd0, clipLayer, xa, ya);
        });
      };
      function drawClipPath(trace, t, layer, xaxis, yaxis) {
        var seg, xp, yp, i;
        var clip = layer.select("#" + trace._clipPathId);
        if (!clip.size()) {
          clip = layer.append("clipPath").classed("carpetclip", true);
        }
        var path = Lib.ensureSingle(clip, "path", "carpetboundary");
        var segments = t.clipsegments;
        var segs = [];
        for (i = 0; i < segments.length; i++) {
          seg = segments[i];
          xp = map1dArray([], seg.x, xaxis.c2p);
          yp = map1dArray([], seg.y, yaxis.c2p);
          segs.push(makepath(xp, yp, seg.bicubic));
        }
        var clipPathData = "M" + segs.join("L") + "Z";
        clip.attr("id", trace._clipPathId);
        path.attr("d", clipPathData);
      }
      function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines, isStatic) {
        var lineClass = "const-" + axisLetter + "-lines";
        var gridJoin = layer.selectAll("." + lineClass).data(gridlines);
        gridJoin.enter().append("path").classed(lineClass, true).style("vector-effect", isStatic ? "none" : "non-scaling-stroke");
        gridJoin.each(function(d) {
          var gridline = d;
          var x = gridline.x;
          var y = gridline.y;
          var xp = map1dArray([], x, xaxis.c2p);
          var yp = map1dArray([], y, yaxis.c2p);
          var path = "M" + makepath(xp, yp, gridline.smoothing);
          var el = d3.select(this);
          el.attr("d", path).style("stroke-width", gridline.width).style("stroke", gridline.color).style("stroke-dasharray", Drawing.dashStyle(gridline.dash, gridline.width)).style("fill", "none");
        });
        gridJoin.exit().remove();
      }
      function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) {
        var labelJoin = layer.selectAll("text." + labelClass).data(labels);
        labelJoin.enter().append("text").classed(labelClass, true);
        var maxExtent = 0;
        var labelOrientation = {};
        labelJoin.each(function(label, i) {
          var orientation;
          if (label.axis.tickangle === "auto") {
            orientation = orientText(trace, xaxis, yaxis, label.xy, label.dxy);
          } else {
            var angle = (label.axis.tickangle + 180) * Math.PI / 180;
            orientation = orientText(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]);
          }
          if (!i) {
            labelOrientation = { angle: orientation.angle, flip: orientation.flip };
          }
          var direction = (label.endAnchor ? -1 : 1) * orientation.flip;
          var labelEl = d3.select(this).attr({
            "text-anchor": direction > 0 ? "start" : "end",
            "data-notex": 1
          }).call(Drawing.font, label.font).text(label.text).call(svgTextUtils.convertToTspans, gd);
          var bbox = Drawing.bBox(this);
          labelEl.attr(
            "transform",
            // Translate to the correct point:
            strTranslate(orientation.p[0], orientation.p[1]) + // Rotate to line up with grid line tangent:
            strRotate(orientation.angle) + // Adjust the baseline and indentation:
            strTranslate(label.axis.labelpadding * direction, bbox.height * 0.3)
          );
          maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding);
        });
        labelJoin.exit().remove();
        labelOrientation.maxExtent = maxExtent;
        return labelOrientation;
      }
      function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) {
        var a, b, xy, dxy;
        var aMin = Lib.aggNums(Math.min, null, trace.a);
        var aMax = Lib.aggNums(Math.max, null, trace.a);
        var bMin = Lib.aggNums(Math.min, null, trace.b);
        var bMax = Lib.aggNums(Math.max, null, trace.b);
        a = 0.5 * (aMin + aMax);
        b = bMin;
        xy = trace.ab2xy(a, b, true);
        dxy = trace.dxyda_rough(a, b);
        if (labelOrientationA.angle === void 0) {
          Lib.extendFlat(labelOrientationA, orientText(trace, xa, ya, xy, trace.dxydb_rough(a, b)));
        }
        drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, "a-title");
        a = aMin;
        b = 0.5 * (bMin + bMax);
        xy = trace.ab2xy(a, b, true);
        dxy = trace.dxydb_rough(a, b);
        if (labelOrientationB.angle === void 0) {
          Lib.extendFlat(labelOrientationB, orientText(trace, xa, ya, xy, trace.dxyda_rough(a, b)));
        }
        drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, "b-title");
      }
      var lineSpacing = alignmentConstants.LINE_SPACING;
      var midShift = (1 - alignmentConstants.MID_SHIFT) / lineSpacing + 1;
      function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) {
        var data = [];
        if (axis.title.text) data.push(axis.title.text);
        var titleJoin = layer.selectAll("text." + labelClass).data(data);
        var offset = labelOrientation.maxExtent;
        titleJoin.enter().append("text").classed(labelClass, true);
        titleJoin.each(function() {
          var orientation = orientText(trace, xa, ya, xy, dxy);
          if (["start", "both"].indexOf(axis.showticklabels) === -1) {
            offset = 0;
          }
          var titleSize = axis.title.font.size;
          offset += titleSize + axis.title.offset;
          var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0);
          var angleDiff = (labelNorm - orientation.angle + 450) % 360;
          var reverseTitle = angleDiff > 90 && angleDiff < 270;
          var el = d3.select(this);
          el.text(axis.title.text).call(svgTextUtils.convertToTspans, gd);
          if (reverseTitle) {
            offset = (-svgTextUtils.lineCount(el) + midShift) * lineSpacing * titleSize - offset;
          }
          el.attr(
            "transform",
            strTranslate(orientation.p[0], orientation.p[1]) + strRotate(orientation.angle) + strTranslate(0, offset)
          ).attr("text-anchor", "middle").call(Drawing.font, axis.title.font);
        });
        titleJoin.exit().remove();
      }
    }
  });

  // src/traces/carpet/cheater_basis.js
  var require_cheater_basis = __commonJS({
    "src/traces/carpet/cheater_basis.js"(exports, module) {
      "use strict";
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      module.exports = function(a, b, cheaterslope) {
        var i, j, ascal, bscal, aval, bval;
        var data = [];
        var na = isArrayOrTypedArray(a) ? a.length : a;
        var nb = isArrayOrTypedArray(b) ? b.length : b;
        var adata = isArrayOrTypedArray(a) ? a : null;
        var bdata = isArrayOrTypedArray(b) ? b : null;
        if (adata) {
          ascal = (adata.length - 1) / (adata[adata.length - 1] - adata[0]) / (na - 1);
        }
        if (bdata) {
          bscal = (bdata.length - 1) / (bdata[bdata.length - 1] - bdata[0]) / (nb - 1);
        }
        var xval;
        var xmin = Infinity;
        var xmax = -Infinity;
        for (j = 0; j < nb; j++) {
          data[j] = [];
          bval = bdata ? (bdata[j] - bdata[0]) * bscal : j / (nb - 1);
          for (i = 0; i < na; i++) {
            aval = adata ? (adata[i] - adata[0]) * ascal : i / (na - 1);
            xval = aval - bval * cheaterslope;
            xmin = Math.min(xval, xmin);
            xmax = Math.max(xval, xmax);
            data[j][i] = xval;
          }
        }
        var slope = 1 / (xmax - xmin);
        var offset = -xmin * slope;
        for (j = 0; j < nb; j++) {
          for (i = 0; i < na; i++) {
            data[j][i] = slope * data[j][i] + offset;
          }
        }
        return data;
      };
    }
  });

  // src/traces/carpet/array_minmax.js
  var require_array_minmax = __commonJS({
    "src/traces/carpet/array_minmax.js"(exports, module) {
      "use strict";
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      module.exports = function(a) {
        return minMax(a, 0);
      };
      function minMax(a, depth) {
        if (!isArrayOrTypedArray(a) || depth >= 10) {
          return null;
        }
        var min = Infinity;
        var max = -Infinity;
        var n = a.length;
        for (var i = 0; i < n; i++) {
          var datum = a[i];
          if (isArrayOrTypedArray(datum)) {
            var result = minMax(datum, depth + 1);
            if (result) {
              min = Math.min(result[0], min);
              max = Math.max(result[1], max);
            }
          } else {
            min = Math.min(datum, min);
            max = Math.max(datum, max);
          }
        }
        return [min, max];
      }
    }
  });

  // src/traces/carpet/calc_gridlines.js
  var require_calc_gridlines = __commonJS({
    "src/traces/carpet/calc_gridlines.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var extendFlat = require_extend().extendFlat;
      module.exports = function calcGridlines(trace, axisLetter, crossAxisLetter) {
        var i, j, j0;
        var eps, bounds, n1, n2, n, value, v;
        var j1, v0, v1, d;
        var data = trace["_" + axisLetter];
        var axis = trace[axisLetter + "axis"];
        var gridlines = axis._gridlines = [];
        var minorgridlines = axis._minorgridlines = [];
        var boundarylines = axis._boundarylines = [];
        var crossData = trace["_" + crossAxisLetter];
        var crossAxis = trace[crossAxisLetter + "axis"];
        if (axis.tickmode === "array") {
          axis.tickvals = data.slice();
        }
        var xcp = trace._xctrl;
        var ycp = trace._yctrl;
        var nea = xcp[0].length;
        var neb = xcp.length;
        var na = trace._a.length;
        var nb = trace._b.length;
        Axes.prepTicks(axis);
        if (axis.tickmode === "array") delete axis.tickvals;
        var stride = axis.smoothing ? 3 : 1;
        function constructValueGridline(value2) {
          var i2, j2, j02, tj, pxy, i0, ti, xy, dxydi0, dxydi1, dxydj0, dxydj1;
          var xpoints = [];
          var ypoints = [];
          var ret = {};
          if (axisLetter === "b") {
            j2 = trace.b2j(value2);
            j02 = Math.floor(Math.max(0, Math.min(nb - 2, j2)));
            tj = j2 - j02;
            ret.length = nb;
            ret.crossLength = na;
            ret.xy = function(i3) {
              return trace.evalxy([], i3, j2);
            };
            ret.dxy = function(i02, ti2) {
              return trace.dxydi([], i02, j02, ti2, tj);
            };
            for (i2 = 0; i2 < na; i2++) {
              i0 = Math.min(na - 2, i2);
              ti = i2 - i0;
              xy = trace.evalxy([], i2, j2);
              if (crossAxis.smoothing && i2 > 0) {
                dxydi0 = trace.dxydi([], i2 - 1, j02, 0, tj);
                xpoints.push(pxy[0] + dxydi0[0] / 3);
                ypoints.push(pxy[1] + dxydi0[1] / 3);
                dxydi1 = trace.dxydi([], i2 - 1, j02, 1, tj);
                xpoints.push(xy[0] - dxydi1[0] / 3);
                ypoints.push(xy[1] - dxydi1[1] / 3);
              }
              xpoints.push(xy[0]);
              ypoints.push(xy[1]);
              pxy = xy;
            }
          } else {
            i2 = trace.a2i(value2);
            i0 = Math.floor(Math.max(0, Math.min(na - 2, i2)));
            ti = i2 - i0;
            ret.length = na;
            ret.crossLength = nb;
            ret.xy = function(j3) {
              return trace.evalxy([], i2, j3);
            };
            ret.dxy = function(j03, tj2) {
              return trace.dxydj([], i0, j03, ti, tj2);
            };
            for (j2 = 0; j2 < nb; j2++) {
              j02 = Math.min(nb - 2, j2);
              tj = j2 - j02;
              xy = trace.evalxy([], i2, j2);
              if (crossAxis.smoothing && j2 > 0) {
                dxydj0 = trace.dxydj([], i0, j2 - 1, ti, 0);
                xpoints.push(pxy[0] + dxydj0[0] / 3);
                ypoints.push(pxy[1] + dxydj0[1] / 3);
                dxydj1 = trace.dxydj([], i0, j2 - 1, ti, 1);
                xpoints.push(xy[0] - dxydj1[0] / 3);
                ypoints.push(xy[1] - dxydj1[1] / 3);
              }
              xpoints.push(xy[0]);
              ypoints.push(xy[1]);
              pxy = xy;
            }
          }
          ret.axisLetter = axisLetter;
          ret.axis = axis;
          ret.crossAxis = crossAxis;
          ret.value = value2;
          ret.constvar = crossAxisLetter;
          ret.index = n;
          ret.x = xpoints;
          ret.y = ypoints;
          ret.smoothing = crossAxis.smoothing;
          return ret;
        }
        function constructArrayGridline(idx) {
          var j2, i0, j02, ti, tj;
          var xpoints = [];
          var ypoints = [];
          var ret = {};
          ret.length = data.length;
          ret.crossLength = crossData.length;
          if (axisLetter === "b") {
            j02 = Math.max(0, Math.min(nb - 2, idx));
            tj = Math.min(1, Math.max(0, idx - j02));
            ret.xy = function(i2) {
              return trace.evalxy([], i2, idx);
            };
            ret.dxy = function(i02, ti2) {
              return trace.dxydi([], i02, j02, ti2, tj);
            };
            for (j2 = 0; j2 < nea; j2++) {
              xpoints[j2] = xcp[idx * stride][j2];
              ypoints[j2] = ycp[idx * stride][j2];
            }
          } else {
            i0 = Math.max(0, Math.min(na - 2, idx));
            ti = Math.min(1, Math.max(0, idx - i0));
            ret.xy = function(j3) {
              return trace.evalxy([], idx, j3);
            };
            ret.dxy = function(j03, tj2) {
              return trace.dxydj([], i0, j03, ti, tj2);
            };
            for (j2 = 0; j2 < neb; j2++) {
              xpoints[j2] = xcp[j2][idx * stride];
              ypoints[j2] = ycp[j2][idx * stride];
            }
          }
          ret.axisLetter = axisLetter;
          ret.axis = axis;
          ret.crossAxis = crossAxis;
          ret.value = data[idx];
          ret.constvar = crossAxisLetter;
          ret.index = idx;
          ret.x = xpoints;
          ret.y = ypoints;
          ret.smoothing = crossAxis.smoothing;
          return ret;
        }
        if (axis.tickmode === "array") {
          eps = 5e-15;
          bounds = [
            Math.floor((data.length - 1 - axis.arraytick0) / axis.arraydtick * (1 + eps)),
            Math.ceil(-axis.arraytick0 / axis.arraydtick / (1 + eps))
          ].sort(function(a, b) {
            return a - b;
          });
          n1 = bounds[0] - 1;
          n2 = bounds[1] + 1;
          for (n = n1; n < n2; n++) {
            j = axis.arraytick0 + axis.arraydtick * n;
            if (j < 0 || j > data.length - 1) continue;
            gridlines.push(extendFlat(constructArrayGridline(j), {
              color: axis.gridcolor,
              width: axis.gridwidth,
              dash: axis.griddash
            }));
          }
          for (n = n1; n < n2; n++) {
            j0 = axis.arraytick0 + axis.arraydtick * n;
            j1 = Math.min(j0 + axis.arraydtick, data.length - 1);
            if (j0 < 0 || j0 > data.length - 1) continue;
            if (j1 < 0 || j1 > data.length - 1) continue;
            v0 = data[j0];
            v1 = data[j1];
            for (i = 0; i < axis.minorgridcount; i++) {
              d = j1 - j0;
              if (d <= 0) continue;
              v = v0 + (v1 - v0) * (i + 1) / (axis.minorgridcount + 1) * (axis.arraydtick / d);
              if (v < data[0] || v > data[data.length - 1]) continue;
              minorgridlines.push(extendFlat(constructValueGridline(v), {
                color: axis.minorgridcolor,
                width: axis.minorgridwidth,
                dash: axis.minorgriddash
              }));
            }
          }
          if (axis.startline) {
            boundarylines.push(extendFlat(constructArrayGridline(0), {
              color: axis.startlinecolor,
              width: axis.startlinewidth
            }));
          }
          if (axis.endline) {
            boundarylines.push(extendFlat(constructArrayGridline(data.length - 1), {
              color: axis.endlinecolor,
              width: axis.endlinewidth
            }));
          }
        } else {
          eps = 5e-15;
          bounds = [
            Math.floor((data[data.length - 1] - axis.tick0) / axis.dtick * (1 + eps)),
            Math.ceil((data[0] - axis.tick0) / axis.dtick / (1 + eps))
          ].sort(function(a, b) {
            return a - b;
          });
          n1 = bounds[0];
          n2 = bounds[1];
          for (n = n1; n <= n2; n++) {
            value = axis.tick0 + axis.dtick * n;
            gridlines.push(extendFlat(constructValueGridline(value), {
              color: axis.gridcolor,
              width: axis.gridwidth,
              dash: axis.griddash
            }));
          }
          for (n = n1 - 1; n < n2 + 1; n++) {
            value = axis.tick0 + axis.dtick * n;
            for (i = 0; i < axis.minorgridcount; i++) {
              v = value + axis.dtick * (i + 1) / (axis.minorgridcount + 1);
              if (v < data[0] || v > data[data.length - 1]) continue;
              minorgridlines.push(extendFlat(constructValueGridline(v), {
                color: axis.minorgridcolor,
                width: axis.minorgridwidth,
                dash: axis.minorgriddash
              }));
            }
          }
          if (axis.startline) {
            boundarylines.push(extendFlat(constructValueGridline(data[0]), {
              color: axis.startlinecolor,
              width: axis.startlinewidth
            }));
          }
          if (axis.endline) {
            boundarylines.push(extendFlat(constructValueGridline(data[data.length - 1]), {
              color: axis.endlinecolor,
              width: axis.endlinewidth
            }));
          }
        }
      };
    }
  });

  // src/traces/carpet/calc_labels.js
  var require_calc_labels = __commonJS({
    "src/traces/carpet/calc_labels.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var extendFlat = require_extend().extendFlat;
      module.exports = function calcLabels(trace, axis) {
        var i, tobj, prefix, suffix, gridline;
        var labels = axis._labels = [];
        var gridlines = axis._gridlines;
        for (i = 0; i < gridlines.length; i++) {
          gridline = gridlines[i];
          if (["start", "both"].indexOf(axis.showticklabels) !== -1) {
            tobj = Axes.tickText(axis, gridline.value);
            extendFlat(tobj, {
              prefix,
              suffix,
              endAnchor: true,
              xy: gridline.xy(0),
              dxy: gridline.dxy(0, 0),
              axis: gridline.axis,
              length: gridline.crossAxis.length,
              font: gridline.axis.tickfont,
              isFirst: i === 0,
              isLast: i === gridlines.length - 1
            });
            labels.push(tobj);
          }
          if (["end", "both"].indexOf(axis.showticklabels) !== -1) {
            tobj = Axes.tickText(axis, gridline.value);
            extendFlat(tobj, {
              endAnchor: false,
              xy: gridline.xy(gridline.crossLength - 1),
              dxy: gridline.dxy(gridline.crossLength - 2, 1),
              axis: gridline.axis,
              length: gridline.crossAxis.length,
              font: gridline.axis.tickfont,
              isFirst: i === 0,
              isLast: i === gridlines.length - 1
            });
            labels.push(tobj);
          }
        }
      };
    }
  });

  // src/traces/carpet/calc_clippath.js
  var require_calc_clippath = __commonJS({
    "src/traces/carpet/calc_clippath.js"(exports, module) {
      "use strict";
      module.exports = function makeClipPath(xctrl, yctrl, aax, bax) {
        var i, x, y;
        var segments = [];
        var asmoothing = !!aax.smoothing;
        var bsmoothing = !!bax.smoothing;
        var nea1 = xctrl[0].length - 1;
        var neb1 = xctrl.length - 1;
        for (i = 0, x = [], y = []; i <= nea1; i++) {
          x[i] = xctrl[0][i];
          y[i] = yctrl[0][i];
        }
        segments.push({ x, y, bicubic: asmoothing });
        for (i = 0, x = [], y = []; i <= neb1; i++) {
          x[i] = xctrl[i][nea1];
          y[i] = yctrl[i][nea1];
        }
        segments.push({ x, y, bicubic: bsmoothing });
        for (i = nea1, x = [], y = []; i >= 0; i--) {
          x[nea1 - i] = xctrl[neb1][i];
          y[nea1 - i] = yctrl[neb1][i];
        }
        segments.push({ x, y, bicubic: asmoothing });
        for (i = neb1, x = [], y = []; i >= 0; i--) {
          x[neb1 - i] = xctrl[i][0];
          y[neb1 - i] = yctrl[i][0];
        }
        segments.push({ x, y, bicubic: bsmoothing });
        return segments;
      };
    }
  });

  // src/traces/carpet/smooth_fill_2d_array.js
  var require_smooth_fill_2d_array = __commonJS({
    "src/traces/carpet/smooth_fill_2d_array.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      module.exports = function smoothFill2dArray(data, a, b) {
        var i, j, k;
        var ip = [];
        var jp = [];
        var ni = data[0].length;
        var nj = data.length;
        function avgSurrounding(i2, j2) {
          var sum = 0;
          var val;
          var cnt = 0;
          if (i2 > 0 && (val = data[j2][i2 - 1]) !== void 0) {
            cnt++;
            sum += val;
          }
          if (i2 < ni - 1 && (val = data[j2][i2 + 1]) !== void 0) {
            cnt++;
            sum += val;
          }
          if (j2 > 0 && (val = data[j2 - 1][i2]) !== void 0) {
            cnt++;
            sum += val;
          }
          if (j2 < nj - 1 && (val = data[j2 + 1][i2]) !== void 0) {
            cnt++;
            sum += val;
          }
          return sum / Math.max(1, cnt);
        }
        var dmax = 0;
        for (i = 0; i < ni; i++) {
          for (j = 0; j < nj; j++) {
            if (data[j][i] === void 0) {
              ip.push(i);
              jp.push(j);
              data[j][i] = avgSurrounding(i, j);
            }
            dmax = Math.max(dmax, Math.abs(data[j][i]));
          }
        }
        if (!ip.length) return data;
        var dxp, dxm, dap, dam, dbp, dbm, c, d, diff, reldiff, overrelaxation;
        var tol = 1e-5;
        var resid = 0;
        var itermax = 100;
        var iter = 0;
        var n = ip.length;
        do {
          resid = 0;
          for (k = 0; k < n; k++) {
            i = ip[k];
            j = jp[k];
            var boundaryCnt = 0;
            var newVal = 0;
            var d0, d1, x0, x1, i0, j0;
            if (i === 0) {
              i0 = Math.min(ni - 1, 2);
              x0 = a[i0];
              x1 = a[1];
              d0 = data[j][i0];
              d1 = data[j][1];
              newVal += d1 + (d1 - d0) * (a[0] - x1) / (x1 - x0);
              boundaryCnt++;
            } else if (i === ni - 1) {
              i0 = Math.max(0, ni - 3);
              x0 = a[i0];
              x1 = a[ni - 2];
              d0 = data[j][i0];
              d1 = data[j][ni - 2];
              newVal += d1 + (d1 - d0) * (a[ni - 1] - x1) / (x1 - x0);
              boundaryCnt++;
            }
            if ((i === 0 || i === ni - 1) && (j > 0 && j < nj - 1)) {
              dxp = b[j + 1] - b[j];
              dxm = b[j] - b[j - 1];
              newVal += (dxm * data[j + 1][i] + dxp * data[j - 1][i]) / (dxm + dxp);
              boundaryCnt++;
            }
            if (j === 0) {
              j0 = Math.min(nj - 1, 2);
              x0 = b[j0];
              x1 = b[1];
              d0 = data[j0][i];
              d1 = data[1][i];
              newVal += d1 + (d1 - d0) * (b[0] - x1) / (x1 - x0);
              boundaryCnt++;
            } else if (j === nj - 1) {
              j0 = Math.max(0, nj - 3);
              x0 = b[j0];
              x1 = b[nj - 2];
              d0 = data[j0][i];
              d1 = data[nj - 2][i];
              newVal += d1 + (d1 - d0) * (b[nj - 1] - x1) / (x1 - x0);
              boundaryCnt++;
            }
            if ((j === 0 || j === nj - 1) && (i > 0 && i < ni - 1)) {
              dxp = a[i + 1] - a[i];
              dxm = a[i] - a[i - 1];
              newVal += (dxm * data[j][i + 1] + dxp * data[j][i - 1]) / (dxm + dxp);
              boundaryCnt++;
            }
            if (!boundaryCnt) {
              dap = a[i + 1] - a[i];
              dam = a[i] - a[i - 1];
              dbp = b[j + 1] - b[j];
              dbm = b[j] - b[j - 1];
              c = dap * dam * (dap + dam);
              d = dbp * dbm * (dbp + dbm);
              newVal = (c * (dbm * data[j + 1][i] + dbp * data[j - 1][i]) + d * (dam * data[j][i + 1] + dap * data[j][i - 1])) / (d * (dam + dap) + c * (dbm + dbp));
            } else {
              newVal /= boundaryCnt;
            }
            diff = newVal - data[j][i];
            reldiff = diff / dmax;
            resid += reldiff * reldiff;
            overrelaxation = boundaryCnt ? 0 : 0.85;
            data[j][i] += diff * (1 + overrelaxation);
          }
          resid = Math.sqrt(resid);
        } while (iter++ < itermax && resid > tol);
        Lib.log("Smoother converged to", resid, "after", iter, "iterations");
        return data;
      };
    }
  });

  // src/traces/carpet/constants.js
  var require_constants32 = __commonJS({
    "src/traces/carpet/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        RELATIVE_CULL_TOLERANCE: 1e-6
      };
    }
  });

  // src/traces/carpet/catmull_rom.js
  var require_catmull_rom = __commonJS({
    "src/traces/carpet/catmull_rom.js"(exports, module) {
      "use strict";
      var CatmullRomExp = 0.5;
      module.exports = function makeControlPoints(p0, p1, p2, smoothness) {
        var d1x = p0[0] - p1[0];
        var d1y = p0[1] - p1[1];
        var d2x = p2[0] - p1[0];
        var d2y = p2[1] - p1[1];
        var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
        var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
        var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
        var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
        var denom1 = d2a * (d1a + d2a) * 3;
        var denom2 = d1a * (d1a + d2a) * 3;
        return [[
          p1[0] + (denom1 && numx / denom1),
          p1[1] + (denom1 && numy / denom1)
        ], [
          p1[0] - (denom2 && numx / denom2),
          p1[1] - (denom2 && numy / denom2)
        ]];
      };
    }
  });

  // src/traces/carpet/compute_control_points.js
  var require_compute_control_points = __commonJS({
    "src/traces/carpet/compute_control_points.js"(exports, module) {
      "use strict";
      var makeControlPoints = require_catmull_rom();
      var ensureArray = require_lib().ensureArray;
      function inferCubicControlPoint(p0, p2, p3) {
        var p2e0 = -0.5 * p3[0] + 1.5 * p2[0];
        var p2e1 = -0.5 * p3[1] + 1.5 * p2[1];
        return [
          (2 * p2e0 + p0[0]) / 3,
          (2 * p2e1 + p0[1]) / 3
        ];
      }
      module.exports = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) {
        var i, j, ie, je, xej, yej, xj, yj, cp, p1;
        var na = x[0].length;
        var nb = x.length;
        var nea = asmoothing ? 3 * na - 2 : na;
        var neb = bsmoothing ? 3 * nb - 2 : nb;
        xe = ensureArray(xe, neb);
        ye = ensureArray(ye, neb);
        for (ie = 0; ie < neb; ie++) {
          xe[ie] = ensureArray(xe[ie], nea);
          ye[ie] = ensureArray(ye[ie], nea);
        }
        for (j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
          xej = xe[je];
          yej = ye[je];
          xj = x[j];
          yj = y[j];
          for (i = 0, ie = 0; i < na; i++, ie += asmoothing ? 3 : 1) {
            xej[ie] = xj[i];
            yej[ie] = yj[i];
          }
        }
        if (asmoothing) {
          for (j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) {
            for (i = 1, ie = 3; i < na - 1; i++, ie += 3) {
              cp = makeControlPoints(
                [x[j][i - 1], y[j][i - 1]],
                [x[j][i], y[j][i]],
                [x[j][i + 1], y[j][i + 1]],
                asmoothing
              );
              xe[je][ie - 1] = cp[0][0];
              ye[je][ie - 1] = cp[0][1];
              xe[je][ie + 1] = cp[1][0];
              ye[je][ie + 1] = cp[1][1];
            }
            p1 = inferCubicControlPoint(
              [xe[je][0], ye[je][0]],
              [xe[je][2], ye[je][2]],
              [xe[je][3], ye[je][3]]
            );
            xe[je][1] = p1[0];
            ye[je][1] = p1[1];
            p1 = inferCubicControlPoint(
              [xe[je][nea - 1], ye[je][nea - 1]],
              [xe[je][nea - 3], ye[je][nea - 3]],
              [xe[je][nea - 4], ye[je][nea - 4]]
            );
            xe[je][nea - 2] = p1[0];
            ye[je][nea - 2] = p1[1];
          }
        }
        if (bsmoothing) {
          for (ie = 0; ie < nea; ie++) {
            for (je = 3; je < neb - 3; je += 3) {
              cp = makeControlPoints(
                [xe[je - 3][ie], ye[je - 3][ie]],
                [xe[je][ie], ye[je][ie]],
                [xe[je + 3][ie], ye[je + 3][ie]],
                bsmoothing
              );
              xe[je - 1][ie] = cp[0][0];
              ye[je - 1][ie] = cp[0][1];
              xe[je + 1][ie] = cp[1][0];
              ye[je + 1][ie] = cp[1][1];
            }
            p1 = inferCubicControlPoint(
              [xe[0][ie], ye[0][ie]],
              [xe[2][ie], ye[2][ie]],
              [xe[3][ie], ye[3][ie]]
            );
            xe[1][ie] = p1[0];
            ye[1][ie] = p1[1];
            p1 = inferCubicControlPoint(
              [xe[neb - 1][ie], ye[neb - 1][ie]],
              [xe[neb - 3][ie], ye[neb - 3][ie]],
              [xe[neb - 4][ie], ye[neb - 4][ie]]
            );
            xe[neb - 2][ie] = p1[0];
            ye[neb - 2][ie] = p1[1];
          }
        }
        if (asmoothing && bsmoothing) {
          for (je = 1; je < neb; je += (je + 1) % 3 === 0 ? 2 : 1) {
            for (ie = 3; ie < nea - 3; ie += 3) {
              cp = makeControlPoints(
                [xe[je][ie - 3], ye[je][ie - 3]],
                [xe[je][ie], ye[je][ie]],
                [xe[je][ie + 3], ye[je][ie + 3]],
                asmoothing
              );
              xe[je][ie - 1] = 0.5 * (xe[je][ie - 1] + cp[0][0]);
              ye[je][ie - 1] = 0.5 * (ye[je][ie - 1] + cp[0][1]);
              xe[je][ie + 1] = 0.5 * (xe[je][ie + 1] + cp[1][0]);
              ye[je][ie + 1] = 0.5 * (ye[je][ie + 1] + cp[1][1]);
            }
            p1 = inferCubicControlPoint(
              [xe[je][0], ye[je][0]],
              [xe[je][2], ye[je][2]],
              [xe[je][3], ye[je][3]]
            );
            xe[je][1] = 0.5 * (xe[je][1] + p1[0]);
            ye[je][1] = 0.5 * (ye[je][1] + p1[1]);
            p1 = inferCubicControlPoint(
              [xe[je][nea - 1], ye[je][nea - 1]],
              [xe[je][nea - 3], ye[je][nea - 3]],
              [xe[je][nea - 4], ye[je][nea - 4]]
            );
            xe[je][nea - 2] = 0.5 * (xe[je][nea - 2] + p1[0]);
            ye[je][nea - 2] = 0.5 * (ye[je][nea - 2] + p1[1]);
          }
        }
        return [xe, ye];
      };
    }
  });

  // src/traces/carpet/create_spline_evaluator.js
  var require_create_spline_evaluator = __commonJS({
    "src/traces/carpet/create_spline_evaluator.js"(exports, module) {
      "use strict";
      module.exports = function(arrays, na, nb, asmoothing, bsmoothing) {
        var imax = na - 2;
        var jmax = nb - 2;
        if (asmoothing && bsmoothing) {
          return function(out, i, j) {
            if (!out) out = [];
            var f0, f1, f2, f3, ak, k;
            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));
            i0 *= 3;
            j0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ou3 * ak[j0][i0] + 3 * (ou2 * u * ak[j0][i0 + 1] + ou * u2 * ak[j0][i0 + 2]) + u3 * ak[j0][i0 + 3];
              f1 = ou3 * ak[j0 + 1][i0] + 3 * (ou2 * u * ak[j0 + 1][i0 + 1] + ou * u2 * ak[j0 + 1][i0 + 2]) + u3 * ak[j0 + 1][i0 + 3];
              f2 = ou3 * ak[j0 + 2][i0] + 3 * (ou2 * u * ak[j0 + 2][i0 + 1] + ou * u2 * ak[j0 + 2][i0 + 2]) + u3 * ak[j0 + 2][i0 + 3];
              f3 = ou3 * ak[j0 + 3][i0] + 3 * (ou2 * u * ak[j0 + 3][i0 + 1] + ou * u2 * ak[j0 + 3][i0 + 2]) + u3 * ak[j0 + 3][i0 + 3];
              out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
          };
        } else if (asmoothing) {
          return function(out, i, j) {
            if (!out) out = [];
            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));
            var f0, f1, f2, f3, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            var ov = 1 - v;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ov * ak[j0][i0] + v * ak[j0 + 1][i0];
              f1 = ov * ak[j0][i0 + 1] + v * ak[j0 + 1][i0 + 1];
              f2 = ov * ak[j0][i0 + 2] + v * ak[j0 + 1][i0 + 1];
              f3 = ov * ak[j0][i0 + 3] + v * ak[j0 + 1][i0 + 1];
              out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
            }
            return out;
          };
        } else if (bsmoothing) {
          return function(out, i, j) {
            if (!out) out = [];
            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));
            var f0, f1, f2, f3, k, ak;
            j0 *= 3;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            var ou = 1 - u;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
              f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];
              f2 = ou * ak[j0 + 2][i0] + u * ak[j0 + 2][i0 + 1];
              f3 = ou * ak[j0 + 3][i0] + u * ak[j0 + 3][i0 + 1];
              out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
          };
        } else {
          return function(out, i, j) {
            if (!out) out = [];
            var i0 = Math.max(0, Math.min(Math.floor(i), imax));
            var j0 = Math.max(0, Math.min(Math.floor(j), jmax));
            var u = Math.max(0, Math.min(1, i - i0));
            var v = Math.max(0, Math.min(1, j - j0));
            var f0, f1, k, ak;
            var ov = 1 - v;
            var ou = 1 - u;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ou * ak[j0][i0] + u * ak[j0][i0 + 1];
              f1 = ou * ak[j0 + 1][i0] + u * ak[j0 + 1][i0 + 1];
              out[k] = ov * f0 + v * f1;
            }
            return out;
          };
        }
      };
    }
  });

  // src/traces/carpet/create_i_derivative_evaluator.js
  var require_create_i_derivative_evaluator = __commonJS({
    "src/traces/carpet/create_i_derivative_evaluator.js"(exports, module) {
      "use strict";
      module.exports = function(arrays, asmoothing, bsmoothing) {
        if (asmoothing && bsmoothing) {
          return function(out, i0, j0, u, v) {
            if (!out) out = [];
            var f0, f1, f2, f3, ak, k;
            i0 *= 3;
            j0 *= 3;
            var u2 = u * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ouu2 = ou * u * 2;
            var a = -3 * ou2;
            var b = 3 * (ou2 - ouu2);
            var c = 3 * (ouu2 - u2);
            var d = 3 * u2;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = a * ak[j0][i0] + b * ak[j0][i0 + 1] + c * ak[j0][i0 + 2] + d * ak[j0][i0 + 3];
              f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];
              f2 = a * ak[j0 + 2][i0] + b * ak[j0 + 2][i0 + 1] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 2][i0 + 3];
              f3 = a * ak[j0 + 3][i0] + b * ak[j0 + 3][i0 + 1] + c * ak[j0 + 3][i0 + 2] + d * ak[j0 + 3][i0 + 3];
              out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
          };
        } else if (asmoothing) {
          return function(out, i0, j0, u, v) {
            if (!out) out = [];
            var f0, f1, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ouu2 = ou * u * 2;
            var a = -3 * ou2;
            var b = 3 * (ou2 - ouu2);
            var c = 3 * (ouu2 - u2);
            var d = 3 * u2;
            var ov = 1 - v;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = a * ak[j0][i0] + b * ak[j0][i0 + 1] + c * ak[j0][i0 + 2] + d * ak[j0][i0 + 3];
              f1 = a * ak[j0 + 1][i0] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 1][i0 + 2] + d * ak[j0 + 1][i0 + 3];
              out[k] = ov * f0 + v * f1;
            }
            return out;
          };
        } else if (bsmoothing) {
          return function(out, i0, j0, u, v) {
            if (!out) out = [];
            var f0, f1, f2, f3, k, ak;
            j0 *= 3;
            var v2 = v * v;
            var v3 = v2 * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ov3 = ov2 * ov;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ak[j0][i0 + 1] - ak[j0][i0];
              f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];
              f2 = ak[j0 + 2][i0 + 1] - ak[j0 + 2][i0];
              f3 = ak[j0 + 3][i0 + 1] - ak[j0 + 3][i0];
              out[k] = ov3 * f0 + 3 * (ov2 * v * f1 + ov * v2 * f2) + v3 * f3;
            }
            return out;
          };
        } else {
          return function(out, i0, j0, u, v) {
            if (!out) out = [];
            var f0, f1, k, ak;
            var ov = 1 - v;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ak[j0][i0 + 1] - ak[j0][i0];
              f1 = ak[j0 + 1][i0 + 1] - ak[j0 + 1][i0];
              out[k] = ov * f0 + v * f1;
            }
            return out;
          };
        }
      };
    }
  });

  // src/traces/carpet/create_j_derivative_evaluator.js
  var require_create_j_derivative_evaluator = __commonJS({
    "src/traces/carpet/create_j_derivative_evaluator.js"(exports, module) {
      "use strict";
      module.exports = function(arrays, asmoothing, bsmoothing) {
        if (asmoothing && bsmoothing) {
          return function(out, i0, j0, u, v) {
            if (!out) out = [];
            var f0, f1, f2, f3, ak, k;
            i0 *= 3;
            j0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            var v2 = v * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ovv2 = ov * v * 2;
            var a = -3 * ov2;
            var b = 3 * (ov2 - ovv2);
            var c = 3 * (ovv2 - v2);
            var d = 3 * v2;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
              f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];
              f2 = a * ak[j0][i0 + 2] + b * ak[j0 + 1][i0 + 2] + c * ak[j0 + 2][i0 + 2] + d * ak[j0 + 3][i0 + 2];
              f3 = a * ak[j0][i0 + 3] + b * ak[j0 + 1][i0 + 3] + c * ak[j0 + 2][i0 + 3] + d * ak[j0 + 3][i0 + 3];
              out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
            }
            return out;
          };
        } else if (asmoothing) {
          return function(out, i0, j0, v, u) {
            if (!out) out = [];
            var f0, f1, f2, f3, k, ak;
            i0 *= 3;
            var u2 = u * u;
            var u3 = u2 * u;
            var ou = 1 - u;
            var ou2 = ou * ou;
            var ou3 = ou2 * ou;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ak[j0 + 1][i0] - ak[j0][i0];
              f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];
              f2 = ak[j0 + 1][i0 + 2] - ak[j0][i0 + 2];
              f3 = ak[j0 + 1][i0 + 3] - ak[j0][i0 + 3];
              out[k] = ou3 * f0 + 3 * (ou2 * u * f1 + ou * u2 * f2) + u3 * f3;
            }
            return out;
          };
        } else if (bsmoothing) {
          return function(out, i0, j0, u, v) {
            if (!out) out = [];
            var f0, f1, k, ak;
            j0 *= 3;
            var ou = 1 - u;
            var v2 = v * v;
            var ov = 1 - v;
            var ov2 = ov * ov;
            var ovv2 = ov * v * 2;
            var a = -3 * ov2;
            var b = 3 * (ov2 - ovv2);
            var c = 3 * (ovv2 - v2);
            var d = 3 * v2;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = a * ak[j0][i0] + b * ak[j0 + 1][i0] + c * ak[j0 + 2][i0] + d * ak[j0 + 3][i0];
              f1 = a * ak[j0][i0 + 1] + b * ak[j0 + 1][i0 + 1] + c * ak[j0 + 2][i0 + 1] + d * ak[j0 + 3][i0 + 1];
              out[k] = ou * f0 + u * f1;
            }
            return out;
          };
        } else {
          return function(out, i0, j0, v, u) {
            if (!out) out = [];
            var f0, f1, k, ak;
            var ov = 1 - v;
            for (k = 0; k < arrays.length; k++) {
              ak = arrays[k];
              f0 = ak[j0 + 1][i0] - ak[j0][i0];
              f1 = ak[j0 + 1][i0 + 1] - ak[j0][i0 + 1];
              out[k] = ov * f0 + v * f1;
            }
            return out;
          };
        }
      };
    }
  });

  // src/traces/carpet/set_convert.js
  var require_set_convert2 = __commonJS({
    "src/traces/carpet/set_convert.js"(exports, module) {
      "use strict";
      var constants = require_constants32();
      var search = require_search().findBin;
      var computeControlPoints = require_compute_control_points();
      var createSplineEvaluator = require_create_spline_evaluator();
      var createIDerivativeEvaluator = require_create_i_derivative_evaluator();
      var createJDerivativeEvaluator = require_create_j_derivative_evaluator();
      module.exports = function setConvert(trace) {
        var a = trace._a;
        var b = trace._b;
        var na = a.length;
        var nb = b.length;
        var aax = trace.aaxis;
        var bax = trace.baxis;
        var amin = a[0];
        var amax = a[na - 1];
        var bmin = b[0];
        var bmax = b[nb - 1];
        var arange = a[a.length - 1] - a[0];
        var brange = b[b.length - 1] - b[0];
        var atol = arange * constants.RELATIVE_CULL_TOLERANCE;
        var btol = brange * constants.RELATIVE_CULL_TOLERANCE;
        amin -= atol;
        amax += atol;
        bmin -= btol;
        bmax += btol;
        trace.isVisible = function(a2, b2) {
          return a2 > amin && a2 < amax && b2 > bmin && b2 < bmax;
        };
        trace.isOccluded = function(a2, b2) {
          return a2 < amin || a2 > amax || b2 < bmin || b2 > bmax;
        };
        trace.setScale = function() {
          var x = trace._x;
          var y = trace._y;
          var result = computeControlPoints(trace._xctrl, trace._yctrl, x, y, aax.smoothing, bax.smoothing);
          trace._xctrl = result[0];
          trace._yctrl = result[1];
          trace.evalxy = createSplineEvaluator([trace._xctrl, trace._yctrl], na, nb, aax.smoothing, bax.smoothing);
          trace.dxydi = createIDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
          trace.dxydj = createJDerivativeEvaluator([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing);
        };
        trace.i2a = function(i) {
          var i0 = Math.max(0, Math.floor(i[0]), na - 2);
          var ti = i[0] - i0;
          return (1 - ti) * a[i0] + ti * a[i0 + 1];
        };
        trace.j2b = function(j) {
          var j0 = Math.max(0, Math.floor(j[1]), na - 2);
          var tj = j[1] - j0;
          return (1 - tj) * b[j0] + tj * b[j0 + 1];
        };
        trace.ij2ab = function(ij) {
          return [trace.i2a(ij[0]), trace.j2b(ij[1])];
        };
        trace.a2i = function(aval) {
          var i0 = Math.max(0, Math.min(search(aval, a), na - 2));
          var a0 = a[i0];
          var a1 = a[i0 + 1];
          return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0)));
        };
        trace.b2j = function(bval) {
          var j0 = Math.max(0, Math.min(search(bval, b), nb - 2));
          var b0 = b[j0];
          var b1 = b[j0 + 1];
          return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0)));
        };
        trace.ab2ij = function(ab) {
          return [trace.a2i(ab[0]), trace.b2j(ab[1])];
        };
        trace.i2c = function(i, j) {
          return trace.evalxy([], i, j);
        };
        trace.ab2xy = function(aval, bval, extrapolate) {
          if (!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) {
            return [false, false];
          }
          var i = trace.a2i(aval);
          var j = trace.b2j(bval);
          var pt = trace.evalxy([], i, j);
          if (extrapolate) {
            var iex = 0;
            var jex = 0;
            var der = [];
            var i0, ti, j0, tj;
            if (aval < a[0]) {
              i0 = 0;
              ti = 0;
              iex = (aval - a[0]) / (a[1] - a[0]);
            } else if (aval > a[na - 1]) {
              i0 = na - 2;
              ti = 1;
              iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]);
            } else {
              i0 = Math.max(0, Math.min(na - 2, Math.floor(i)));
              ti = i - i0;
            }
            if (bval < b[0]) {
              j0 = 0;
              tj = 0;
              jex = (bval - b[0]) / (b[1] - b[0]);
            } else if (bval > b[nb - 1]) {
              j0 = nb - 2;
              tj = 1;
              jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]);
            } else {
              j0 = Math.max(0, Math.min(nb - 2, Math.floor(j)));
              tj = j - j0;
            }
            if (iex) {
              trace.dxydi(der, i0, j0, ti, tj);
              pt[0] += der[0] * iex;
              pt[1] += der[1] * iex;
            }
            if (jex) {
              trace.dxydj(der, i0, j0, ti, tj);
              pt[0] += der[0] * jex;
              pt[1] += der[1] * jex;
            }
          }
          return pt;
        };
        trace.c2p = function(xy, xa, ya) {
          return [xa.c2p(xy[0]), ya.c2p(xy[1])];
        };
        trace.p2x = function(p, xa, ya) {
          return [xa.p2c(p[0]), ya.p2c(p[1])];
        };
        trace.dadi = function(i) {
          var i0 = Math.max(0, Math.min(a.length - 2, i));
          return a[i0 + 1] - a[i0];
        };
        trace.dbdj = function(j) {
          var j0 = Math.max(0, Math.min(b.length - 2, j));
          return b[j0 + 1] - b[j0];
        };
        trace.dxyda = function(i0, j0, u, v) {
          var dxydi = trace.dxydi(null, i0, j0, u, v);
          var dadi = trace.dadi(i0, u);
          return [dxydi[0] / dadi, dxydi[1] / dadi];
        };
        trace.dxydb = function(i0, j0, u, v) {
          var dxydj = trace.dxydj(null, i0, j0, u, v);
          var dbdj = trace.dbdj(j0, v);
          return [dxydj[0] / dbdj, dxydj[1] / dbdj];
        };
        trace.dxyda_rough = function(a2, b2, reldiff) {
          var h = arange * (reldiff || 0.1);
          var plus = trace.ab2xy(a2 + h, b2, true);
          var minus = trace.ab2xy(a2 - h, b2, true);
          return [
            (plus[0] - minus[0]) * 0.5 / h,
            (plus[1] - minus[1]) * 0.5 / h
          ];
        };
        trace.dxydb_rough = function(a2, b2, reldiff) {
          var h = brange * (reldiff || 0.1);
          var plus = trace.ab2xy(a2, b2 + h, true);
          var minus = trace.ab2xy(a2, b2 - h, true);
          return [
            (plus[0] - minus[0]) * 0.5 / h,
            (plus[1] - minus[1]) * 0.5 / h
          ];
        };
        trace.dpdx = function(xa) {
          return xa._m;
        };
        trace.dpdy = function(ya) {
          return ya._m;
        };
      };
    }
  });

  // src/traces/carpet/calc.js
  var require_calc38 = __commonJS({
    "src/traces/carpet/calc.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var isArray1D = require_lib().isArray1D;
      var cheaterBasis = require_cheater_basis();
      var arrayMinmax = require_array_minmax();
      var calcGridlines = require_calc_gridlines();
      var calcLabels = require_calc_labels();
      var calcClipPath = require_calc_clippath();
      var clean2dArray = require_clean_2d_array();
      var smoothFill2dArray = require_smooth_fill_2d_array();
      var convertColumnData = require_convert_column_xyz();
      var setConvert = require_set_convert2();
      module.exports = function calc(gd, trace) {
        var xa = Axes.getFromId(gd, trace.xaxis);
        var ya = Axes.getFromId(gd, trace.yaxis);
        var aax = trace.aaxis;
        var bax = trace.baxis;
        var x = trace.x;
        var y = trace.y;
        var cols = [];
        if (x && isArray1D(x)) cols.push("x");
        if (y && isArray1D(y)) cols.push("y");
        if (cols.length) {
          convertColumnData(trace, aax, bax, "a", "b", cols);
        }
        var a = trace._a = trace._a || trace.a;
        var b = trace._b = trace._b || trace.b;
        x = trace._x || trace.x;
        y = trace._y || trace.y;
        var t = {};
        if (trace._cheater) {
          var avals = aax.cheatertype === "index" ? a.length : a;
          var bvals = bax.cheatertype === "index" ? b.length : b;
          x = cheaterBasis(avals, bvals, trace.cheaterslope);
        }
        trace._x = x = clean2dArray(x);
        trace._y = y = clean2dArray(y);
        smoothFill2dArray(x, a, b);
        smoothFill2dArray(y, a, b);
        setConvert(trace);
        trace.setScale();
        var xrange = arrayMinmax(x);
        var yrange = arrayMinmax(y);
        var dx = 0.5 * (xrange[1] - xrange[0]);
        var xc = 0.5 * (xrange[1] + xrange[0]);
        var dy = 0.5 * (yrange[1] - yrange[0]);
        var yc = 0.5 * (yrange[1] + yrange[0]);
        var grow = 1.3;
        xrange = [xc - dx * grow, xc + dx * grow];
        yrange = [yc - dy * grow, yc + dy * grow];
        trace._extremes[xa._id] = Axes.findExtremes(xa, xrange, { padded: true });
        trace._extremes[ya._id] = Axes.findExtremes(ya, yrange, { padded: true });
        calcGridlines(trace, "a", "b");
        calcGridlines(trace, "b", "a");
        calcLabels(trace, aax);
        calcLabels(trace, bax);
        t.clipsegments = calcClipPath(trace._xctrl, trace._yctrl, aax, bax);
        t.x = x;
        t.y = y;
        t.a = a;
        t.b = b;
        return [t];
      };
    }
  });

  // src/traces/carpet/index.js
  var require_carpet = __commonJS({
    "src/traces/carpet/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes63(),
        supplyDefaults: require_defaults59(),
        plot: require_plot32(),
        calc: require_calc38(),
        animatable: true,
        isContainer: true,
        // so carpet traces get `calc` before other traces
        moduleType: "trace",
        name: "carpet",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "carpet", "carpetAxis", "notLegendIsolatable", "noMultiCategory", "noHover", "noSortingByValue"],
        meta: {}
      };
    }
  });

  // lib/carpet.js
  var require_carpet2 = __commonJS({
    "lib/carpet.js"(exports, module) {
      "use strict";
      module.exports = require_carpet();
    }
  });

  // src/traces/scattercarpet/attributes.js
  var require_attributes64 = __commonJS({
    "src/traces/scattercarpet/attributes.js"(exports, module) {
      "use strict";
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterAttrs = require_attributes12();
      var baseAttrs = require_attributes2();
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var colorScaleAttrs = require_attributes8();
      var extendFlat = require_extend().extendFlat;
      var scatterMarkerAttrs = scatterAttrs.marker;
      var scatterLineAttrs = scatterAttrs.line;
      var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
      module.exports = {
        carpet: {
          valType: "string",
          editType: "calc"
        },
        a: {
          valType: "data_array",
          editType: "calc"
        },
        b: {
          valType: "data_array",
          editType: "calc"
        },
        mode: extendFlat({}, scatterAttrs.mode, { dflt: "markers" }),
        text: extendFlat({}, scatterAttrs.text, {}),
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["a", "b", "text"] }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
        line: {
          color: scatterLineAttrs.color,
          width: scatterLineAttrs.width,
          dash: scatterLineAttrs.dash,
          backoff: scatterLineAttrs.backoff,
          shape: extendFlat({}, scatterLineAttrs.shape, { values: ["linear", "spline"] }),
          smoothing: scatterLineAttrs.smoothing,
          editType: "calc"
        },
        connectgaps: scatterAttrs.connectgaps,
        fill: extendFlat({}, scatterAttrs.fill, {
          values: ["none", "toself", "tonext"],
          dflt: "none"
        }),
        fillcolor: makeFillcolorAttr(),
        marker: extendFlat(
          {
            symbol: scatterMarkerAttrs.symbol,
            opacity: scatterMarkerAttrs.opacity,
            maxdisplayed: scatterMarkerAttrs.maxdisplayed,
            angle: scatterMarkerAttrs.angle,
            angleref: scatterMarkerAttrs.angleref,
            standoff: scatterMarkerAttrs.standoff,
            size: scatterMarkerAttrs.size,
            sizeref: scatterMarkerAttrs.sizeref,
            sizemin: scatterMarkerAttrs.sizemin,
            sizemode: scatterMarkerAttrs.sizemode,
            line: extendFlat(
              {
                width: scatterMarkerLineAttrs.width,
                dash: scatterMarkerLineAttrs.dash,
                editType: "calc"
              },
              colorScaleAttrs("marker.line")
            ),
            gradient: scatterMarkerAttrs.gradient,
            editType: "calc"
          },
          colorScaleAttrs("marker")
        ),
        textfont: scatterAttrs.textfont,
        textposition: scatterAttrs.textposition,
        selected: scatterAttrs.selected,
        unselected: scatterAttrs.unselected,
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["a", "b", "text", "name"]
        }),
        hoveron: scatterAttrs.hoveron,
        hovertemplate: hovertemplateAttrs(),
        hovertemplatefallback: templatefallbackAttrs(),
        zorder: scatterAttrs.zorder
      };
    }
  });

  // src/traces/scattercarpet/defaults.js
  var require_defaults60 = __commonJS({
    "src/traces/scattercarpet/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var constants = require_constants8();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleLineShapeDefaults = require_line_shape_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var attributes = require_attributes64();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        coerce("carpet");
        traceOut.xaxis = "x";
        traceOut.yaxis = "y";
        var a = coerce("a");
        var b = coerce("b");
        var len = Math.min(a.length, b.length);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        traceOut._length = len;
        coerce("text");
        coerce("texttemplate");
        coerce("texttemplatefallback");
        coerce("hovertext");
        var defaultMode = len < constants.PTS_LINESONLY ? "lines+markers" : "lines";
        coerce("mode", defaultMode);
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { gradient: true });
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, { backoff: true });
          handleLineShapeDefaults(traceIn, traceOut, coerce);
          coerce("connectgaps");
        }
        if (subTypes.hasText(traceOut)) {
          handleTextDefaults(traceIn, traceOut, layout, coerce);
        }
        var dfltHoverOn = [];
        if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
          coerce("marker.maxdisplayed");
          dfltHoverOn.push("points");
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
          if (!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
        }
        if (traceOut.fill === "tonext" || traceOut.fill === "toself") {
          dfltHoverOn.push("fills");
        }
        var hoverOn = coerce("hoveron", dfltHoverOn.join("+") || "points");
        if (hoverOn !== "fills") {
          coerce("hovertemplate");
          coerce("hovertemplatefallback");
        }
        coerce("zorder");
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/scattercarpet/format_labels.js
  var require_format_labels7 = __commonJS({
    "src/traces/scattercarpet/format_labels.js"(exports, module) {
      "use strict";
      module.exports = function formatLabels(cdi, trace) {
        var labels = {};
        var carpet = trace._carpet;
        var ij = carpet.ab2ij([cdi.a, cdi.b]);
        var i0 = Math.floor(ij[0]);
        var ti = ij[0] - i0;
        var j0 = Math.floor(ij[1]);
        var tj = ij[1] - j0;
        var xy = carpet.evalxy([], i0, j0, ti, tj);
        labels.yLabel = xy[1].toFixed(3);
        return labels;
      };
    }
  });

  // src/traces/carpet/lookup_carpetid.js
  var require_lookup_carpetid = __commonJS({
    "src/traces/carpet/lookup_carpetid.js"(exports, module) {
      "use strict";
      module.exports = function(gd, trace) {
        var n = gd._fullData.length;
        var firstAxis;
        for (var i = 0; i < n; i++) {
          var maybeCarpet = gd._fullData[i];
          if (maybeCarpet.index === trace.index) continue;
          if (maybeCarpet.type === "carpet") {
            if (!firstAxis) {
              firstAxis = maybeCarpet;
            }
            if (maybeCarpet.carpet === trace.carpet) {
              return maybeCarpet;
            }
          }
        }
        return firstAxis;
      };
    }
  });

  // src/traces/scattercarpet/calc.js
  var require_calc39 = __commonJS({
    "src/traces/scattercarpet/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var calcColorscale = require_colorscale_calc();
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcSelection = require_calc_selection();
      var calcMarkerSize = require_calc3().calcMarkerSize;
      var lookupCarpet = require_lookup_carpetid();
      module.exports = function calc(gd, trace) {
        var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
        if (!carpet || !carpet.visible || carpet.visible === "legendonly") return;
        var i;
        trace.xaxis = carpet.xaxis;
        trace.yaxis = carpet.yaxis;
        var serieslen = trace._length;
        var cd = new Array(serieslen);
        var a, b;
        var needsCull = false;
        for (i = 0; i < serieslen; i++) {
          a = trace.a[i];
          b = trace.b[i];
          if (isNumeric(a) && isNumeric(b)) {
            var xy = carpet.ab2xy(+a, +b, true);
            var visible = carpet.isVisible(+a, +b);
            if (!visible) needsCull = true;
            cd[i] = { x: xy[0], y: xy[1], a, b, vis: visible };
          } else cd[i] = { x: false, y: false };
        }
        trace._needsCull = needsCull;
        cd[0].carpet = carpet;
        cd[0].trace = trace;
        calcMarkerSize(trace, serieslen);
        calcColorscale(gd, trace);
        arraysToCalcdata(cd, trace);
        calcSelection(cd, trace);
        return cd;
      };
    }
  });

  // src/traces/scattercarpet/plot.js
  var require_plot33 = __commonJS({
    "src/traces/scattercarpet/plot.js"(exports, module) {
      "use strict";
      var scatterPlot = require_plot();
      var Axes = require_axes();
      var Drawing = require_drawing();
      module.exports = function plot(gd, plotinfoproxy, data, layer) {
        var i, trace, node;
        var carpet = data[0][0].carpet;
        var xaxis = Axes.getFromId(gd, carpet.xaxis || "x");
        var yaxis = Axes.getFromId(gd, carpet.yaxis || "y");
        var plotinfo = {
          xaxis,
          yaxis,
          plot: plotinfoproxy.plot
        };
        for (i = 0; i < data.length; i++) {
          trace = data[i][0].trace;
          trace._xA = xaxis;
          trace._yA = yaxis;
        }
        scatterPlot(gd, plotinfo, data, layer);
        for (i = 0; i < data.length; i++) {
          trace = data[i][0].trace;
          node = layer.selectAll("g.trace" + trace.uid + " .js-line");
          Drawing.setClipUrl(node, data[i][0].carpet._clipPathId, gd);
        }
      };
    }
  });

  // src/traces/scattercarpet/hover.js
  var require_hover22 = __commonJS({
    "src/traces/scattercarpet/hover.js"(exports, module) {
      "use strict";
      var scatterHover = require_hover2();
      var fillText = require_lib().fillText;
      module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
        var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
        if (!scatterPointData || scatterPointData[0].index === false) return;
        var newPointData = scatterPointData[0];
        if (newPointData.index === void 0) {
          var yFracUp = 1 - newPointData.y0 / pointData.ya._length;
          var xLen = pointData.xa._length;
          var xMin = xLen * yFracUp / 2;
          var xMax = xLen - xMin;
          newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
          newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
          return scatterPointData;
        }
        var cdi = newPointData.cd[newPointData.index];
        newPointData.a = cdi.a;
        newPointData.b = cdi.b;
        newPointData.xLabelVal = void 0;
        newPointData.yLabelVal = void 0;
        var trace = newPointData.trace;
        var carpet = trace._carpet;
        var labels = trace._module.formatLabels(cdi, trace);
        newPointData.yLabel = labels.yLabel;
        delete newPointData.text;
        var text = [];
        function textPart(ax, val) {
          var prefix;
          if (ax.labelprefix && ax.labelprefix.length > 0) {
            prefix = ax.labelprefix.replace(/ = $/, "");
          } else {
            prefix = ax._hovertitle;
          }
          text.push(prefix + ": " + val.toFixed(3) + ax.labelsuffix);
        }
        if (!trace.hovertemplate) {
          var hoverinfo = cdi.hi || trace.hoverinfo;
          var parts = hoverinfo.split("+");
          if (parts.indexOf("all") !== -1) parts = ["a", "b", "text"];
          if (parts.indexOf("a") !== -1) textPart(carpet.aaxis, cdi.a);
          if (parts.indexOf("b") !== -1) textPart(carpet.baxis, cdi.b);
          text.push("y: " + newPointData.yLabel);
          if (parts.indexOf("text") !== -1) {
            fillText(cdi, trace, text);
          }
          newPointData.extraText = text.join("<br>");
        }
        return scatterPointData;
      };
    }
  });

  // src/traces/scattercarpet/event_data.js
  var require_event_data15 = __commonJS({
    "src/traces/scattercarpet/event_data.js"(exports, module) {
      "use strict";
      module.exports = function eventData(out, pt, trace, cd, pointNumber) {
        var cdi = cd[pointNumber];
        out.a = cdi.a;
        out.b = cdi.b;
        out.y = cdi.y;
        return out;
      };
    }
  });

  // src/traces/scattercarpet/index.js
  var require_scattercarpet = __commonJS({
    "src/traces/scattercarpet/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes64(),
        supplyDefaults: require_defaults60(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels7(),
        calc: require_calc39(),
        plot: require_plot33(),
        style: require_style2().style,
        styleOnSelect: require_style2().styleOnSelect,
        hoverPoints: require_hover22(),
        selectPoints: require_select2(),
        eventData: require_event_data15(),
        moduleType: "trace",
        name: "scattercarpet",
        basePlotModule: require_cartesian(),
        categories: ["svg", "carpet", "symbols", "showLegend", "carpetDependent", "zoomScale"],
        meta: {}
      };
    }
  });

  // lib/scattercarpet.js
  var require_scattercarpet2 = __commonJS({
    "lib/scattercarpet.js"(exports, module) {
      "use strict";
      module.exports = require_scattercarpet();
    }
  });

  // src/traces/contourcarpet/attributes.js
  var require_attributes65 = __commonJS({
    "src/traces/contourcarpet/attributes.js"(exports, module) {
      "use strict";
      var heatmapAttrs = require_attributes25();
      var contourAttrs = require_attributes28();
      var colorScaleAttrs = require_attributes8();
      var extendFlat = require_extend().extendFlat;
      var contourContourAttrs = contourAttrs.contours;
      module.exports = extendFlat(
        {
          carpet: {
            valType: "string",
            editType: "calc"
          },
          z: heatmapAttrs.z,
          a: heatmapAttrs.x,
          a0: heatmapAttrs.x0,
          da: heatmapAttrs.dx,
          b: heatmapAttrs.y,
          b0: heatmapAttrs.y0,
          db: heatmapAttrs.dy,
          text: heatmapAttrs.text,
          hovertext: heatmapAttrs.hovertext,
          transpose: heatmapAttrs.transpose,
          atype: heatmapAttrs.xtype,
          btype: heatmapAttrs.ytype,
          fillcolor: contourAttrs.fillcolor,
          autocontour: contourAttrs.autocontour,
          ncontours: contourAttrs.ncontours,
          contours: {
            type: contourContourAttrs.type,
            start: contourContourAttrs.start,
            end: contourContourAttrs.end,
            size: contourContourAttrs.size,
            coloring: {
              // from contourAttrs.contours.coloring but no 'heatmap' option
              valType: "enumerated",
              values: ["fill", "lines", "none"],
              dflt: "fill",
              editType: "calc"
            },
            showlines: contourContourAttrs.showlines,
            showlabels: contourContourAttrs.showlabels,
            labelfont: contourContourAttrs.labelfont,
            labelformat: contourContourAttrs.labelformat,
            operation: contourContourAttrs.operation,
            value: contourContourAttrs.value,
            editType: "calc",
            impliedEdits: { autocontour: false }
          },
          line: {
            color: contourAttrs.line.color,
            width: contourAttrs.line.width,
            dash: contourAttrs.line.dash,
            smoothing: contourAttrs.line.smoothing,
            editType: "plot"
          },
          zorder: contourAttrs.zorder
        },
        colorScaleAttrs("", {
          cLetter: "z",
          autoColorDflt: false
        })
      );
    }
  });

  // src/traces/contourcarpet/defaults.js
  var require_defaults61 = __commonJS({
    "src/traces/contourcarpet/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleXYZDefaults = require_xyz_defaults();
      var attributes = require_attributes65();
      var handleConstraintDefaults = require_constraint_defaults();
      var handleContoursDefaults = require_contours_defaults();
      var handleStyleDefaults = require_style_defaults3();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        function coerce2(attr) {
          return Lib.coerce2(traceIn, traceOut, attributes, attr);
        }
        coerce("carpet");
        if (traceIn.a && traceIn.b) {
          var len = handleXYZDefaults(traceIn, traceOut, coerce, layout, "a", "b");
          if (!len) {
            traceOut.visible = false;
            return;
          }
          coerce("text");
          var isConstraint = coerce("contours.type") === "constraint";
          if (isConstraint) {
            handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, { hasHover: false });
          } else {
            handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
            handleStyleDefaults(traceIn, traceOut, coerce, layout, { hasHover: false });
          }
        } else {
          traceOut._defaultColor = defaultColor;
          traceOut._length = null;
        }
        coerce("zorder");
      };
    }
  });

  // src/traces/contourcarpet/calc.js
  var require_calc40 = __commonJS({
    "src/traces/contourcarpet/calc.js"(exports, module) {
      "use strict";
      var colorscaleCalc = require_calc();
      var Lib = require_lib();
      var convertColumnData = require_convert_column_xyz();
      var clean2dArray = require_clean_2d_array();
      var interp2d = require_interp2d();
      var findEmpties = require_find_empties();
      var makeBoundArray = require_make_bound_array();
      var supplyDefaults = require_defaults61();
      var lookupCarpet = require_lookup_carpetid();
      var setContours = require_set_contours();
      module.exports = function calc(gd, trace) {
        var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
        if (!carpet || !carpet.visible || carpet.visible === "legendonly") return;
        if (!trace.a || !trace.b) {
          var carpetdata = gd.data[carpet.index];
          var tracedata = gd.data[trace.index];
          if (!tracedata.a) tracedata.a = carpetdata.a;
          if (!tracedata.b) tracedata.b = carpetdata.b;
          supplyDefaults(tracedata, trace, trace._defaultColor, gd._fullLayout);
        }
        var cd = heatmappishCalc(gd, trace);
        setContours(trace, trace._z);
        return cd;
      };
      function heatmappishCalc(gd, trace) {
        var carpet = trace._carpetTrace;
        var aax = carpet.aaxis;
        var bax = carpet.baxis;
        var a, a0, da, b, b0, db, z;
        aax._minDtick = 0;
        bax._minDtick = 0;
        if (Lib.isArray1D(trace.z)) convertColumnData(trace, aax, bax, "a", "b", ["z"]);
        a = trace._a = trace._a || trace.a;
        b = trace._b = trace._b || trace.b;
        a = a ? aax.makeCalcdata(trace, "_a") : [];
        b = b ? bax.makeCalcdata(trace, "_b") : [];
        a0 = trace.a0 || 0;
        da = trace.da || 1;
        b0 = trace.b0 || 0;
        db = trace.db || 1;
        z = trace._z = clean2dArray(trace._z || trace.z, trace.transpose);
        trace._emptypoints = findEmpties(z);
        interp2d(z, trace._emptypoints);
        var xlen = Lib.maxRowLength(z);
        var xIn = trace.xtype === "scaled" ? "" : a;
        var xArray = makeBoundArray(trace, xIn, a0, da, xlen, aax);
        var yIn = trace.ytype === "scaled" ? "" : b;
        var yArray = makeBoundArray(trace, yIn, b0, db, z.length, bax);
        var cd0 = {
          a: xArray,
          b: yArray,
          z
        };
        if (trace.contours.type === "levels" && trace.contours.coloring !== "none") {
          colorscaleCalc(gd, trace, {
            vals: z,
            containerStr: "",
            cLetter: "z"
          });
        }
        return [cd0];
      }
    }
  });

  // src/traces/carpet/axis_aligned_line.js
  var require_axis_aligned_line = __commonJS({
    "src/traces/carpet/axis_aligned_line.js"(exports, module) {
      "use strict";
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      module.exports = function(carpet, carpetcd, a, b) {
        var idx, tangent, tanIsoIdx, tanIsoPar, segment, refidx;
        var p0, p1, v0, v1, start, end, range;
        var axis = isArrayOrTypedArray(a) ? "a" : "b";
        var ax = axis === "a" ? carpet.aaxis : carpet.baxis;
        var smoothing = ax.smoothing;
        var toIdx = axis === "a" ? carpet.a2i : carpet.b2j;
        var pt = axis === "a" ? a : b;
        var iso = axis === "a" ? b : a;
        var n = axis === "a" ? carpetcd.a.length : carpetcd.b.length;
        var m = axis === "a" ? carpetcd.b.length : carpetcd.a.length;
        var isoIdx = Math.floor(axis === "a" ? carpet.b2j(iso) : carpet.a2i(iso));
        var xy = axis === "a" ? function(value) {
          return carpet.evalxy([], value, isoIdx);
        } : function(value) {
          return carpet.evalxy([], isoIdx, value);
        };
        if (smoothing) {
          tanIsoIdx = Math.max(0, Math.min(m - 2, isoIdx));
          tanIsoPar = isoIdx - tanIsoIdx;
          tangent = axis === "a" ? function(i, ti) {
            return carpet.dxydi([], i, tanIsoIdx, ti, tanIsoPar);
          } : function(j, tj) {
            return carpet.dxydj([], tanIsoIdx, j, tanIsoPar, tj);
          };
        }
        var vstart = toIdx(pt[0]);
        var vend = toIdx(pt[1]);
        var dir = vstart < vend ? 1 : -1;
        var tol = (vend - vstart) * 1e-8;
        var dirfloor = dir > 0 ? Math.floor : Math.ceil;
        var dirceil = dir > 0 ? Math.ceil : Math.floor;
        var dirmin = dir > 0 ? Math.min : Math.max;
        var dirmax = dir > 0 ? Math.max : Math.min;
        var idx0 = dirfloor(vstart + tol);
        var idx1 = dirceil(vend - tol);
        p0 = xy(vstart);
        var segments = [[p0]];
        for (idx = idx0; idx * dir < idx1 * dir; idx += dir) {
          segment = [];
          start = dirmax(vstart, idx);
          end = dirmin(vend, idx + dir);
          range = end - start;
          refidx = Math.max(0, Math.min(n - 2, Math.floor(0.5 * (start + end))));
          p1 = xy(end);
          if (smoothing) {
            v0 = tangent(refidx, start - refidx);
            v1 = tangent(refidx, end - refidx);
            segment.push([
              p0[0] + v0[0] / 3 * range,
              p0[1] + v0[1] / 3 * range
            ]);
            segment.push([
              p1[0] - v1[0] / 3 * range,
              p1[1] - v1[1] / 3 * range
            ]);
          }
          segment.push(p1);
          segments.push(segment);
          p0 = p1;
        }
        return segments;
      };
    }
  });

  // src/traces/contourcarpet/plot.js
  var require_plot34 = __commonJS({
    "src/traces/contourcarpet/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var map1dArray = require_map_1d_array();
      var makepath = require_makepath();
      var Drawing = require_drawing();
      var Lib = require_lib();
      var makeCrossings = require_make_crossings();
      var findAllPaths = require_find_all_paths();
      var contourPlot = require_plot6();
      var constants = require_constants16();
      var convertToConstraints = require_convert_to_constraints();
      var emptyPathinfo = require_empty_pathinfo();
      var closeBoundaries = require_close_boundaries();
      var lookupCarpet = require_lookup_carpetid();
      var axisAlignedLine = require_axis_aligned_line();
      module.exports = function plot(gd, plotinfo, cdcontours, contourcarpetLayer) {
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;
        Lib.makeTraceGroups(contourcarpetLayer, cdcontours, "contour").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var trace = cd0.trace;
          var carpet = trace._carpetTrace = lookupCarpet(gd, trace);
          var carpetcd = gd.calcdata[carpet.index][0];
          if (!carpet.visible || carpet.visible === "legendonly") return;
          var a = cd0.a;
          var b = cd0.b;
          var contours = trace.contours;
          var pathinfo = emptyPathinfo(contours, plotinfo, cd0);
          var isConstraint = contours.type === "constraint";
          var operation = contours._operation;
          var coloring = isConstraint ? operation === "=" ? "lines" : "fill" : contours.coloring;
          function ab2p(ab) {
            var pt = carpet.ab2xy(ab[0], ab[1], true);
            return [xa.c2p(pt[0]), ya.c2p(pt[1])];
          }
          var perimeter = [
            [a[0], b[b.length - 1]],
            [a[a.length - 1], b[b.length - 1]],
            [a[a.length - 1], b[0]],
            [a[0], b[0]]
          ];
          makeCrossings(pathinfo);
          var atol = (a[a.length - 1] - a[0]) * 1e-8;
          var btol = (b[b.length - 1] - b[0]) * 1e-8;
          findAllPaths(pathinfo, atol, btol);
          var fillPathinfo = pathinfo;
          if (contours.type === "constraint") {
            fillPathinfo = convertToConstraints(pathinfo, operation);
          }
          mapPathinfo(pathinfo, ab2p);
          var seg, xp, yp, i;
          var segs = [];
          for (i = carpetcd.clipsegments.length - 1; i >= 0; i--) {
            seg = carpetcd.clipsegments[i];
            xp = map1dArray([], seg.x, xa.c2p);
            yp = map1dArray([], seg.y, ya.c2p);
            xp.reverse();
            yp.reverse();
            segs.push(makepath(xp, yp, seg.bicubic));
          }
          var boundaryPath = "M" + segs.join("L") + "Z";
          makeBackground(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring);
          makeFills(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath);
          makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours, plotinfo, carpet);
          Drawing.setClipUrl(plotGroup, carpet._clipPathId, gd);
        });
      };
      function mapPathinfo(pathinfo, map) {
        var i, j, k, pi, pedgepaths, ppaths, pedgepath, ppath, path;
        for (i = 0; i < pathinfo.length; i++) {
          pi = pathinfo[i];
          pedgepaths = pi.pedgepaths = [];
          ppaths = pi.ppaths = [];
          for (j = 0; j < pi.edgepaths.length; j++) {
            path = pi.edgepaths[j];
            pedgepath = [];
            for (k = 0; k < path.length; k++) {
              pedgepath[k] = map(path[k]);
            }
            pedgepaths.push(pedgepath);
          }
          for (j = 0; j < pi.paths.length; j++) {
            path = pi.paths[j];
            ppath = [];
            for (k = 0; k < path.length; k++) {
              ppath[k] = map(path[k]);
            }
            ppaths.push(ppath);
          }
        }
      }
      function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) {
        var isStatic = gd._context.staticPlot;
        var lineContainer = Lib.ensureSingle(plotgroup, "g", "contourlines");
        var showLines = contours.showlines !== false;
        var showLabels = contours.showlabels;
        var clipLinesForLabels = showLines && showLabels;
        var linegroup = contourPlot.createLines(lineContainer, showLines || showLabels, pathinfo, isStatic);
        var lineClip = contourPlot.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);
        var labelGroup = plotgroup.selectAll("g.contourlabels").data(showLabels ? [0] : []);
        labelGroup.exit().remove();
        labelGroup.enter().append("g").classed("contourlabels", true);
        if (showLabels) {
          var xa = plotinfo.xaxis;
          var ya = plotinfo.yaxis;
          var xLen = xa._length;
          var yLen = ya._length;
          var labelClipPathData = [[
            [0, 0],
            [xLen, 0],
            [xLen, yLen],
            [0, yLen]
          ]];
          var labelData = [];
          Lib.clearLocationCache();
          var contourFormat = contourPlot.labelFormatter(gd, cd0);
          var dummyText = Drawing.tester.append("text").attr("data-notex", 1).call(Drawing.font, contours.labelfont);
          var bounds = {
            left: 0,
            right: xLen,
            center: xLen / 2,
            top: 0,
            bottom: yLen,
            middle: yLen / 2
          };
          var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);
          var normLength = constants.LABELDISTANCE * plotDiagonal / Math.max(1, pathinfo.length / constants.LABELINCREASE);
          linegroup.each(function(d) {
            var textOpts = contourPlot.calcTextOpts(d.level, contourFormat, dummyText, gd);
            d3.select(this).selectAll("path").each(function(pathData) {
              var path = this;
              var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
              if (!pathBounds) return;
              constrainToCarpet(path, pathData, d, pathBounds, carpet, textOpts.height);
              if (pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;
              var maxLabels = Math.min(
                Math.ceil(pathBounds.len / normLength),
                constants.LABELMAX
              );
              for (var i = 0; i < maxLabels; i++) {
                var loc = contourPlot.findBestTextLocation(
                  path,
                  pathBounds,
                  textOpts,
                  labelData,
                  bounds
                );
                if (!loc) break;
                contourPlot.addLabelData(loc, textOpts, labelData, labelClipPathData);
              }
            });
          });
          dummyText.remove();
          contourPlot.drawLabels(
            labelGroup,
            labelData,
            gd,
            lineClip,
            clipLinesForLabels ? labelClipPathData : null
          );
        }
        if (showLabels && !showLines) linegroup.remove();
      }
      function constrainToCarpet(path, pathData, levelData, pathBounds, carpet, textHeight) {
        var pathABData;
        for (var i = 0; i < levelData.pedgepaths.length; i++) {
          if (pathData === levelData.pedgepaths[i]) {
            pathABData = levelData.edgepaths[i];
          }
        }
        if (!pathABData) return;
        var aMin = carpet.a[0];
        var aMax = carpet.a[carpet.a.length - 1];
        var bMin = carpet.b[0];
        var bMax = carpet.b[carpet.b.length - 1];
        function getOffset(abPt, pathVector) {
          var offset = 0;
          var edgeVector;
          var dAB = 0.1;
          if (Math.abs(abPt[0] - aMin) < dAB || Math.abs(abPt[0] - aMax) < dAB) {
            edgeVector = normalizeVector(carpet.dxydb_rough(abPt[0], abPt[1], dAB));
            offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
          }
          if (Math.abs(abPt[1] - bMin) < dAB || Math.abs(abPt[1] - bMax) < dAB) {
            edgeVector = normalizeVector(carpet.dxyda_rough(abPt[0], abPt[1], dAB));
            offset = Math.max(offset, textHeight * vectorTan(pathVector, edgeVector) / 2);
          }
          return offset;
        }
        var startVector = getUnitVector(path, 0, 1);
        var endVector = getUnitVector(path, pathBounds.total, pathBounds.total - 1);
        var minStart = getOffset(pathABData[0], startVector);
        var maxEnd = pathBounds.total - getOffset(pathABData[pathABData.length - 1], endVector);
        if (pathBounds.min < minStart) pathBounds.min = minStart;
        if (pathBounds.max > maxEnd) pathBounds.max = maxEnd;
        pathBounds.len = pathBounds.max - pathBounds.min;
      }
      function getUnitVector(path, p0, p1) {
        var pt0 = path.getPointAtLength(p0);
        var pt1 = path.getPointAtLength(p1);
        var dx = pt1.x - pt0.x;
        var dy = pt1.y - pt0.y;
        var len = Math.sqrt(dx * dx + dy * dy);
        return [dx / len, dy / len];
      }
      function normalizeVector(v) {
        var len = Math.sqrt(v[0] * v[0] + v[1] * v[1]);
        return [v[0] / len, v[1] / len];
      }
      function vectorTan(v0, v1) {
        var cos = Math.abs(v0[0] * v1[0] + v0[1] * v1[1]);
        var sin = Math.sqrt(1 - cos * cos);
        return sin / cos;
      }
      function makeBackground(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) {
        var seg, xp, yp, i;
        var bggroup = Lib.ensureSingle(plotgroup, "g", "contourbg");
        var bgfill = bggroup.selectAll("path").data(coloring === "fill" && !isConstraint ? [0] : []);
        bgfill.enter().append("path");
        bgfill.exit().remove();
        var segs = [];
        for (i = 0; i < clipsegments.length; i++) {
          seg = clipsegments[i];
          xp = map1dArray([], seg.x, xaxis.c2p);
          yp = map1dArray([], seg.y, yaxis.c2p);
          segs.push(makepath(xp, yp, seg.bicubic));
        }
        bgfill.attr("d", "M" + segs.join("L") + "Z").style("stroke", "none");
      }
      function makeFills(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) {
        var hasFills = coloring === "fill";
        if (hasFills) {
          closeBoundaries(pathinfo, trace.contours);
        }
        var fillgroup = Lib.ensureSingle(plotgroup, "g", "contourfill");
        var fillitems = fillgroup.selectAll("path").data(hasFills ? pathinfo : []);
        fillitems.enter().append("path");
        fillitems.exit().remove();
        fillitems.each(function(pi) {
          var fullpath = (pi.prefixBoundary ? boundaryPath : "") + joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya);
          if (!fullpath) {
            d3.select(this).remove();
          } else {
            d3.select(this).attr("d", fullpath).style("stroke", "none");
          }
        });
      }
      function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) {
        var i;
        var fullpath = "";
        var startsleft = pi.edgepaths.map(function(v, i2) {
          return i2;
        });
        var newloop = true;
        var endpt, newendpt, cnt, nexti, possiblei, addpath;
        var atol = Math.abs(perimeter[0][0] - perimeter[2][0]) * 1e-4;
        var btol = Math.abs(perimeter[0][1] - perimeter[2][1]) * 1e-4;
        function istop(pt) {
          return Math.abs(pt[1] - perimeter[0][1]) < btol;
        }
        function isbottom(pt) {
          return Math.abs(pt[1] - perimeter[2][1]) < btol;
        }
        function isleft(pt) {
          return Math.abs(pt[0] - perimeter[0][0]) < atol;
        }
        function isright(pt) {
          return Math.abs(pt[0] - perimeter[2][0]) < atol;
        }
        function pathto(pt0, pt1) {
          var i2, j, segments, axis;
          var path = "";
          if (istop(pt0) && !isright(pt0) || isbottom(pt0) && !isleft(pt0)) {
            axis = carpet.aaxis;
            segments = axisAlignedLine(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1]));
          } else {
            axis = carpet.baxis;
            segments = axisAlignedLine(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]);
          }
          for (i2 = 1; i2 < segments.length; i2++) {
            path += axis.smoothing ? "C" : "L";
            for (j = 0; j < segments[i2].length; j++) {
              var pt = segments[i2][j];
              path += [xa.c2p(pt[0]), ya.c2p(pt[1])] + " ";
            }
          }
          return path;
        }
        i = 0;
        endpt = null;
        while (startsleft.length) {
          var startpt = pi.edgepaths[i][0];
          if (endpt) {
            fullpath += pathto(endpt, startpt);
          }
          addpath = Drawing.smoothopen(pi.edgepaths[i].map(ab2p), pi.smoothing);
          fullpath += newloop ? addpath : addpath.replace(/^M/, "L");
          startsleft.splice(startsleft.indexOf(i), 1);
          endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
          nexti = -1;
          for (cnt = 0; cnt < 4; cnt++) {
            if (!endpt) {
              Lib.log("Missing end?", i, pi);
              break;
            }
            if (istop(endpt) && !isright(endpt)) {
              newendpt = perimeter[1];
            } else if (isleft(endpt)) {
              newendpt = perimeter[0];
            } else if (isbottom(endpt)) {
              newendpt = perimeter[3];
            } else if (isright(endpt)) {
              newendpt = perimeter[2];
            }
            for (possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
              var ptNew = pi.edgepaths[possiblei][0];
              if (Math.abs(endpt[0] - newendpt[0]) < atol) {
                if (Math.abs(endpt[0] - ptNew[0]) < atol && (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
                  newendpt = ptNew;
                  nexti = possiblei;
                }
              } else if (Math.abs(endpt[1] - newendpt[1]) < btol) {
                if (Math.abs(endpt[1] - ptNew[1]) < btol && (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
                  newendpt = ptNew;
                  nexti = possiblei;
                }
              } else {
                Lib.log("endpt to newendpt is not vert. or horz.", endpt, newendpt, ptNew);
              }
            }
            if (nexti >= 0) break;
            fullpath += pathto(endpt, newendpt);
            endpt = newendpt;
          }
          if (nexti === pi.edgepaths.length) {
            Lib.log("unclosed perimeter path");
            break;
          }
          i = nexti;
          newloop = startsleft.indexOf(i) === -1;
          if (newloop) {
            i = startsleft[0];
            fullpath += pathto(endpt, newendpt) + "Z";
            endpt = null;
          }
        }
        for (i = 0; i < pi.paths.length; i++) {
          fullpath += Drawing.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing);
        }
        return fullpath;
      }
    }
  });

  // src/traces/contourcarpet/index.js
  var require_contourcarpet = __commonJS({
    "src/traces/contourcarpet/index.js"(exports, module) {
      "use strict";
      module.exports = {
        attributes: require_attributes65(),
        supplyDefaults: require_defaults61(),
        colorbar: require_colorbar3(),
        calc: require_calc40(),
        plot: require_plot34(),
        style: require_style7(),
        moduleType: "trace",
        name: "contourcarpet",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "carpet", "contour", "symbols", "showLegend", "hasLines", "carpetDependent", "noHover", "noSortingByValue"],
        meta: {}
      };
    }
  });

  // lib/contourcarpet.js
  var require_contourcarpet2 = __commonJS({
    "lib/contourcarpet.js"(exports, module) {
      "use strict";
      module.exports = require_contourcarpet();
    }
  });

  // src/traces/ohlc/attributes.js
  var require_attributes66 = __commonJS({
    "src/traces/ohlc/attributes.js"(exports, module) {
      "use strict";
      var extendFlat = require_lib().extendFlat;
      var scatterAttrs = require_attributes12();
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var dash = require_attributes4().dash;
      var fxAttrs = require_attributes();
      var delta = require_delta();
      var INCREASING_COLOR = delta.INCREASING.COLOR;
      var DECREASING_COLOR = delta.DECREASING.COLOR;
      var lineAttrs = scatterAttrs.line;
      function directionAttrs(lineColorDefault) {
        return {
          line: {
            color: extendFlat({}, lineAttrs.color, { dflt: lineColorDefault }),
            width: lineAttrs.width,
            dash,
            editType: "style"
          },
          editType: "style"
        };
      }
      module.exports = {
        xperiod: scatterAttrs.xperiod,
        xperiod0: scatterAttrs.xperiod0,
        xperiodalignment: scatterAttrs.xperiodalignment,
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        x: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        open: {
          valType: "data_array",
          editType: "calc"
        },
        high: {
          valType: "data_array",
          editType: "calc"
        },
        low: {
          valType: "data_array",
          editType: "calc"
        },
        close: {
          valType: "data_array",
          editType: "calc"
        },
        line: {
          width: extendFlat({}, lineAttrs.width, {}),
          dash: extendFlat({}, dash, {}),
          editType: "style"
        },
        increasing: directionAttrs(INCREASING_COLOR),
        decreasing: directionAttrs(DECREASING_COLOR),
        text: {
          valType: "string",
          dflt: "",
          arrayOk: true,
          editType: "calc"
        },
        hovertext: {
          valType: "string",
          dflt: "",
          arrayOk: true,
          editType: "calc"
        },
        hovertemplate: hovertemplateAttrs(
          {},
          {
            keys: ["open", "high", "low", "close"]
          }
        ),
        hovertemplatefallback: templatefallbackAttrs(),
        tickwidth: {
          valType: "number",
          min: 0,
          max: 0.5,
          dflt: 0.3,
          editType: "calc"
        },
        hoverlabel: extendFlat({}, fxAttrs.hoverlabel, {
          split: {
            valType: "boolean",
            dflt: false,
            editType: "style"
          }
        }),
        zorder: scatterAttrs.zorder
      };
    }
  });

  // src/traces/ohlc/ohlc_defaults.js
  var require_ohlc_defaults = __commonJS({
    "src/traces/ohlc/ohlc_defaults.js"(exports, module) {
      "use strict";
      var Registry = require_registry();
      var Lib = require_lib();
      module.exports = function handleOHLC(traceIn, traceOut, coerce, layout) {
        var x = coerce("x");
        var open = coerce("open");
        var high = coerce("high");
        var low = coerce("low");
        var close = coerce("close");
        coerce("hoverlabel.split");
        var handleCalendarDefaults = Registry.getComponentMethod("calendars", "handleTraceDefaults");
        handleCalendarDefaults(traceIn, traceOut, ["x"], layout);
        if (!(open && high && low && close)) return;
        var len = Math.min(open.length, high.length, low.length, close.length);
        if (x) len = Math.min(len, Lib.minRowLength(x));
        traceOut._length = len;
        return len;
      };
    }
  });

  // src/traces/ohlc/defaults.js
  var require_defaults62 = __commonJS({
    "src/traces/ohlc/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleOHLC = require_ohlc_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var attributes = require_attributes66();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleOHLC(traceIn, traceOut, coerce, layout);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce, { x: true });
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("line.width");
        coerce("line.dash");
        handleDirection(traceIn, traceOut, coerce, "increasing");
        handleDirection(traceIn, traceOut, coerce, "decreasing");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("tickwidth");
        layout._requestRangeslider[traceOut.xaxis] = true;
        coerce("zorder");
      };
      function handleDirection(traceIn, traceOut, coerce, direction) {
        coerce(direction + ".line.color");
        coerce(direction + ".line.width", traceOut.line.width);
        coerce(direction + ".line.dash", traceOut.line.dash);
      }
    }
  });

  // src/traces/ohlc/calc.js
  var require_calc41 = __commonJS({
    "src/traces/ohlc/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var _ = Lib._;
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var BADNUM = require_numerical().BADNUM;
      function calc(gd, trace) {
        var xa = Axes.getFromId(gd, trace.xaxis);
        var ya = Axes.getFromId(gd, trace.yaxis);
        var tickLen = convertTickWidth(gd, xa, trace);
        var minDiff = trace._minDiff;
        trace._minDiff = null;
        var origX = trace._origX;
        trace._origX = null;
        var x = trace._xcalc;
        trace._xcalc = null;
        var cd = calcCommon(gd, trace, origX, x, ya, ptFunc);
        trace._extremes[xa._id] = Axes.findExtremes(xa, x, { vpad: minDiff / 2 });
        if (cd.length) {
          Lib.extendFlat(cd[0].t, {
            wHover: minDiff / 2,
            tickLen
          });
          return cd;
        } else {
          return [{ t: { empty: true } }];
        }
      }
      function ptFunc(o, h, l, c) {
        return {
          o,
          h,
          l,
          c
        };
      }
      function calcCommon(gd, trace, origX, x, ya, ptFunc2) {
        var o = ya.makeCalcdata(trace, "open");
        var h = ya.makeCalcdata(trace, "high");
        var l = ya.makeCalcdata(trace, "low");
        var c = ya.makeCalcdata(trace, "close");
        var hasTextArray = Lib.isArrayOrTypedArray(trace.text);
        var hasHovertextArray = Lib.isArrayOrTypedArray(trace.hovertext);
        var increasing = true;
        var cPrev = null;
        var hasPeriod = !!trace.xperiodalignment;
        var cd = [];
        for (var i = 0; i < x.length; i++) {
          var xi = x[i];
          var oi = o[i];
          var hi = h[i];
          var li = l[i];
          var ci = c[i];
          if (xi !== BADNUM && oi !== BADNUM && hi !== BADNUM && li !== BADNUM && ci !== BADNUM) {
            if (ci === oi) {
              if (cPrev !== null && ci !== cPrev) increasing = ci > cPrev;
            } else increasing = ci > oi;
            cPrev = ci;
            var pt = ptFunc2(oi, hi, li, ci);
            pt.pos = xi;
            pt.yc = (oi + ci) / 2;
            pt.i = i;
            pt.dir = increasing ? "increasing" : "decreasing";
            pt.x = pt.pos;
            pt.y = [li, hi];
            if (hasPeriod) pt.orig_p = origX[i];
            if (hasTextArray) pt.tx = trace.text[i];
            if (hasHovertextArray) pt.htx = trace.hovertext[i];
            cd.push(pt);
          } else {
            cd.push({ pos: xi, empty: true });
          }
        }
        trace._extremes[ya._id] = Axes.findExtremes(ya, Lib.concat(l, h), { padded: true });
        if (cd.length) {
          cd[0].t = {
            labels: {
              open: _(gd, "open:") + " ",
              high: _(gd, "high:") + " ",
              low: _(gd, "low:") + " ",
              close: _(gd, "close:") + " "
            }
          };
        }
        return cd;
      }
      function convertTickWidth(gd, xa, trace) {
        var minDiff = trace._minDiff;
        if (!minDiff) {
          var fullData = gd._fullData;
          var ohlcTracesOnThisXaxis = [];
          minDiff = Infinity;
          var i;
          for (i = 0; i < fullData.length; i++) {
            var tracei = fullData[i];
            if (tracei.type === "ohlc" && tracei.visible === true && tracei.xaxis === xa._id) {
              ohlcTracesOnThisXaxis.push(tracei);
              var origX = xa.makeCalcdata(tracei, "x");
              tracei._origX = origX;
              var xcalc = alignPeriod(trace, xa, "x", origX).vals;
              tracei._xcalc = xcalc;
              var _minDiff = Lib.distinctVals(xcalc).minDiff;
              if (_minDiff && isFinite(_minDiff)) {
                minDiff = Math.min(minDiff, _minDiff);
              }
            }
          }
          if (minDiff === Infinity) minDiff = 1;
          for (i = 0; i < ohlcTracesOnThisXaxis.length; i++) {
            ohlcTracesOnThisXaxis[i]._minDiff = minDiff;
          }
        }
        return minDiff * trace.tickwidth;
      }
      module.exports = {
        calc,
        calcCommon
      };
    }
  });

  // src/traces/ohlc/plot.js
  var require_plot35 = __commonJS({
    "src/traces/ohlc/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Lib = require_lib();
      module.exports = function plot(gd, plotinfo, cdOHLC, ohlcLayer) {
        var ya = plotinfo.yaxis;
        var xa = plotinfo.xaxis;
        var posHasRangeBreaks = !!xa.rangebreaks;
        Lib.makeTraceGroups(ohlcLayer, cdOHLC, "trace ohlc").each(function(cd) {
          var plotGroup = d3.select(this);
          var cd0 = cd[0];
          var t = cd0.t;
          var trace = cd0.trace;
          if (trace.visible !== true || t.empty) {
            plotGroup.remove();
            return;
          }
          var tickLen = t.tickLen;
          var paths = plotGroup.selectAll("path").data(Lib.identity);
          paths.enter().append("path");
          paths.exit().remove();
          paths.attr("d", function(d) {
            if (d.empty) return "M0,0Z";
            var xo = xa.c2p(d.pos - tickLen, true);
            var xc = xa.c2p(d.pos + tickLen, true);
            var x = posHasRangeBreaks ? (xo + xc) / 2 : xa.c2p(d.pos, true);
            var yo = ya.c2p(d.o, true);
            var yh = ya.c2p(d.h, true);
            var yl = ya.c2p(d.l, true);
            var yc = ya.c2p(d.c, true);
            return "M" + xo + "," + yo + "H" + x + "M" + x + "," + yh + "V" + yl + "M" + xc + "," + yc + "H" + x;
          });
        });
      };
    }
  });

  // src/traces/ohlc/style.js
  var require_style19 = __commonJS({
    "src/traces/ohlc/style.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var Drawing = require_drawing();
      var Color2 = require_color();
      module.exports = function style(gd, cd, sel) {
        var s = sel ? sel : d3.select(gd).selectAll("g.ohlclayer").selectAll("g.trace");
        s.style("opacity", function(d) {
          return d[0].trace.opacity;
        });
        s.each(function(d) {
          var trace = d[0].trace;
          d3.select(this).selectAll("path").each(function(di) {
            if (di.empty) return;
            var dirLine = trace[di.dir].line;
            d3.select(this).style("fill", "none").call(Color2.stroke, dirLine.color).call(Drawing.dashLine, dirLine.dash, dirLine.width).style("opacity", trace.selectedpoints && !di.selected ? 0.3 : 1);
          });
        });
      };
    }
  });

  // src/traces/ohlc/hover.js
  var require_hover23 = __commonJS({
    "src/traces/ohlc/hover.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      var Lib = require_lib();
      var Fx = require_fx();
      var Color2 = require_color();
      var fillText = require_lib().fillText;
      var delta = require_delta();
      var DIRSYMBOL = {
        increasing: delta.INCREASING.SYMBOL,
        decreasing: delta.DECREASING.SYMBOL
      };
      function hoverPoints(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        if (trace.hoverlabel.split) {
          return hoverSplit(pointData, xval, yval, hovermode);
        }
        return hoverOnPoints(pointData, xval, yval, hovermode);
      }
      function _getClosestPoint(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var xa = pointData.xa;
        var trace = cd[0].trace;
        var t = cd[0].t;
        var type = trace.type;
        var minAttr = type === "ohlc" ? "l" : "min";
        var maxAttr = type === "ohlc" ? "h" : "max";
        var hoverPseudoDistance, spikePseudoDistance;
        var centerShift = t.bPos || 0;
        var shiftPos = function(di2) {
          return di2.pos + centerShift - xval;
        };
        var displayHalfWidth = t.bdPos || t.tickLen;
        var hoverHalfWidth = t.wHover;
        var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0])));
        hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
        spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;
        function dx(di2) {
          var pos = shiftPos(di2);
          return Fx.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance);
        }
        function dy(di2) {
          var min = di2[minAttr];
          var max = di2[maxAttr];
          return min === max || Fx.inbox(min - yval, max - yval, hoverPseudoDistance);
        }
        function dxy(di2) {
          return (dx(di2) + dy(di2)) / 2;
        }
        var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
        Fx.getClosest(cd, distfn, pointData);
        if (pointData.index === false) return null;
        var di = cd[pointData.index];
        if (di.empty) return null;
        var dir = di.dir;
        var container = trace[dir];
        var lc = container.line.color;
        if (Color2.opacity(lc) && container.line.width) pointData.color = lc;
        else pointData.color = container.fillcolor;
        pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true);
        pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true);
        pointData.xLabelVal = di.orig_p !== void 0 ? di.orig_p : di.pos;
        pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
        pointData.xSpike = xa.c2p(di.pos, true);
        return pointData;
      }
      function hoverSplit(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var ya = pointData.ya;
        var trace = cd[0].trace;
        var t = cd[0].t;
        var closeBoxData = [];
        var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode);
        if (!closestPoint) return [];
        var di = cd[closestPoint.index];
        var hoverinfo = di.hi || trace.hoverinfo || "";
        if (hoverinfo === "none" || hoverinfo === "skip") return [];
        var attrs = ["high", "open", "close", "low"];
        var usedVals = {};
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          var val = trace[attr][closestPoint.index];
          var valPx = ya.c2p(val, true);
          var pointData2;
          if (val in usedVals) {
            pointData2 = usedVals[val];
            pointData2.yLabel += "<br>" + t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat);
          } else {
            pointData2 = Lib.extendFlat({}, closestPoint);
            pointData2.y0 = pointData2.y1 = valPx;
            pointData2.yLabelVal = val;
            pointData2.yLabel = t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat);
            pointData2.name = "";
            closeBoxData.push(pointData2);
            usedVals[val] = pointData2;
          }
        }
        return closeBoxData;
      }
      function hoverOnPoints(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var ya = pointData.ya;
        var trace = cd[0].trace;
        var t = cd[0].t;
        var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode);
        if (!closestPoint) return [];
        var cdIndex = closestPoint.index;
        var di = cd[cdIndex];
        var i = closestPoint.index = di.i;
        var dir = di.dir;
        function getLabelLine(attr) {
          return t.labels[attr] + Axes.hoverLabelText(ya, trace[attr][i], trace.yhoverformat);
        }
        var hoverinfo = di.hi || trace.hoverinfo || "";
        var hoverParts = hoverinfo.split("+");
        var isAll = hoverinfo === "all";
        var hasY = isAll || hoverParts.indexOf("y") !== -1;
        var hasText = isAll || hoverParts.indexOf("text") !== -1;
        var textParts = hasY ? [
          getLabelLine("open"),
          getLabelLine("high"),
          getLabelLine("low"),
          getLabelLine("close") + "  " + DIRSYMBOL[dir]
        ] : [];
        if (hasText) fillText(di, trace, textParts);
        closestPoint.extraText = textParts.join("<br>");
        closestPoint.y0 = closestPoint.y1 = ya.c2p(di.yc, true);
        return [closestPoint];
      }
      module.exports = {
        hoverPoints,
        hoverSplit,
        hoverOnPoints
      };
    }
  });

  // src/traces/ohlc/select.js
  var require_select12 = __commonJS({
    "src/traces/ohlc/select.js"(exports, module) {
      "use strict";
      module.exports = function selectPoints(searchInfo, selectionTester) {
        var cd = searchInfo.cd;
        var xa = searchInfo.xaxis;
        var ya = searchInfo.yaxis;
        var selection = [];
        var i;
        var posOffset = cd[0].t.bPos || 0;
        if (selectionTester === false) {
          for (i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
          }
        } else {
          for (i = 0; i < cd.length; i++) {
            var di = cd[i];
            if (selectionTester.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)], null, di.i, searchInfo)) {
              selection.push({
                pointNumber: di.i,
                x: xa.c2d(di.pos),
                y: ya.c2d(di.yc)
              });
              di.selected = 1;
            } else {
              di.selected = 0;
            }
          }
        }
        return selection;
      };
    }
  });

  // src/traces/ohlc/index.js
  var require_ohlc = __commonJS({
    "src/traces/ohlc/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "ohlc",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "showLegend"],
        meta: {},
        attributes: require_attributes66(),
        supplyDefaults: require_defaults62(),
        calc: require_calc41().calc,
        plot: require_plot35(),
        style: require_style19(),
        hoverPoints: require_hover23().hoverPoints,
        selectPoints: require_select12()
      };
    }
  });

  // lib/ohlc.js
  var require_ohlc2 = __commonJS({
    "lib/ohlc.js"(exports, module) {
      "use strict";
      module.exports = require_ohlc();
    }
  });

  // src/traces/candlestick/attributes.js
  var require_attributes67 = __commonJS({
    "src/traces/candlestick/attributes.js"(exports, module) {
      "use strict";
      var extendFlat = require_lib().extendFlat;
      var axisHoverFormat = require_axis_format_attributes().axisHoverFormat;
      var OHLCattrs = require_attributes66();
      var boxAttrs = require_attributes24();
      function directionAttrs(lineColorDefault) {
        return {
          line: {
            color: extendFlat({}, boxAttrs.line.color, { dflt: lineColorDefault }),
            width: boxAttrs.line.width,
            editType: "style"
          },
          fillcolor: boxAttrs.fillcolor,
          editType: "style"
        };
      }
      module.exports = {
        xperiod: OHLCattrs.xperiod,
        xperiod0: OHLCattrs.xperiod0,
        xperiodalignment: OHLCattrs.xperiodalignment,
        xhoverformat: axisHoverFormat("x"),
        yhoverformat: axisHoverFormat("y"),
        x: OHLCattrs.x,
        open: OHLCattrs.open,
        high: OHLCattrs.high,
        low: OHLCattrs.low,
        close: OHLCattrs.close,
        line: {
          width: extendFlat({}, boxAttrs.line.width, {}),
          editType: "style"
        },
        increasing: directionAttrs(OHLCattrs.increasing.line.color.dflt),
        decreasing: directionAttrs(OHLCattrs.decreasing.line.color.dflt),
        text: OHLCattrs.text,
        hovertext: OHLCattrs.hovertext,
        hovertemplate: OHLCattrs.hovertemplate,
        hovertemplatefallback: OHLCattrs.hovertemplatefallback,
        whiskerwidth: extendFlat({}, boxAttrs.whiskerwidth, { dflt: 0 }),
        hoverlabel: OHLCattrs.hoverlabel,
        zorder: boxAttrs.zorder
      };
    }
  });

  // src/traces/candlestick/defaults.js
  var require_defaults63 = __commonJS({
    "src/traces/candlestick/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var handleOHLC = require_ohlc_defaults();
      var handlePeriodDefaults = require_period_defaults();
      var attributes = require_attributes67();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleOHLC(traceIn, traceOut, coerce, layout);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        handlePeriodDefaults(traceIn, traceOut, layout, coerce, { x: true });
        coerce("xhoverformat");
        coerce("yhoverformat");
        coerce("line.width");
        handleDirection(traceIn, traceOut, coerce, "increasing");
        handleDirection(traceIn, traceOut, coerce, "decreasing");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        coerce("whiskerwidth");
        layout._requestRangeslider[traceOut.xaxis] = true;
        coerce("zorder");
      };
      function handleDirection(traceIn, traceOut, coerce, direction) {
        var lineColor = coerce(direction + ".line.color");
        coerce(direction + ".line.width", traceOut.line.width);
        coerce(direction + ".fillcolor", Color2.addOpacity(lineColor, 0.5));
      }
    }
  });

  // src/traces/candlestick/calc.js
  var require_calc42 = __commonJS({
    "src/traces/candlestick/calc.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      var alignPeriod = require_align_period();
      var calcCommon = require_calc41().calcCommon;
      module.exports = function(gd, trace) {
        var fullLayout = gd._fullLayout;
        var xa = Axes.getFromId(gd, trace.xaxis);
        var ya = Axes.getFromId(gd, trace.yaxis);
        var origX = xa.makeCalcdata(trace, "x");
        var x = alignPeriod(trace, xa, "x", origX).vals;
        var cd = calcCommon(gd, trace, origX, x, ya, ptFunc);
        if (cd.length) {
          Lib.extendFlat(cd[0].t, {
            num: fullLayout._numBoxes,
            dPos: Lib.distinctVals(x).minDiff / 2,
            posLetter: "x",
            valLetter: "y"
          });
          fullLayout._numBoxes++;
          return cd;
        } else {
          return [{ t: { empty: true } }];
        }
      };
      function ptFunc(o, h, l, c) {
        return {
          min: l,
          q1: Math.min(o, c),
          med: c,
          q3: Math.max(o, c),
          max: h
        };
      }
    }
  });

  // src/traces/candlestick/index.js
  var require_candlestick = __commonJS({
    "src/traces/candlestick/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "candlestick",
        basePlotModule: require_cartesian(),
        categories: ["cartesian", "svg", "showLegend", "candlestick", "boxLayout"],
        meta: {},
        attributes: require_attributes67(),
        layoutAttributes: require_layout_attributes7(),
        supplyLayoutDefaults: require_layout_defaults6().supplyLayoutDefaults,
        crossTraceCalc: require_cross_trace_calc3().crossTraceCalc,
        supplyDefaults: require_defaults63(),
        calc: require_calc42(),
        plot: require_plot4().plot,
        layerName: "boxlayer",
        style: require_style5().style,
        hoverPoints: require_hover23().hoverPoints,
        selectPoints: require_select12()
      };
    }
  });

  // lib/candlestick.js
  var require_candlestick2 = __commonJS({
    "lib/candlestick.js"(exports, module) {
      "use strict";
      module.exports = require_candlestick();
    }
  });

  // src/plots/polar/set_convert.js
  var require_set_convert3 = __commonJS({
    "src/plots/polar/set_convert.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var setConvertCartesian = require_set_convert();
      var deg2rad = Lib.deg2rad;
      var rad2deg = Lib.rad2deg;
      module.exports = function setConvert(ax, polarLayout, fullLayout) {
        setConvertCartesian(ax, fullLayout);
        switch (ax._id) {
          case "x":
          case "radialaxis":
            setConvertRadial(ax, polarLayout);
            break;
          case "angularaxis":
            setConvertAngular(ax, polarLayout);
            break;
        }
      };
      function setConvertRadial(ax, polarLayout) {
        var subplot = polarLayout._subplot;
        ax.setGeometry = function() {
          var rl0 = ax._rl[0];
          var rl1 = ax._rl[1];
          var b = subplot.innerRadius;
          var m = (subplot.radius - b) / (rl1 - rl0);
          var b2 = b / m;
          var rFilter = rl0 > rl1 ? function(v) {
            return v <= 0;
          } : function(v) {
            return v >= 0;
          };
          ax.c2g = function(v) {
            var r = ax.c2l(v) - rl0;
            return (rFilter(r) ? r : 0) + b2;
          };
          ax.g2c = function(v) {
            return ax.l2c(v + rl0 - b2);
          };
          ax.g2p = function(v) {
            return v * m;
          };
          ax.c2p = function(v) {
            return ax.g2p(ax.c2g(v));
          };
        };
      }
      function toRadians(v, unit) {
        return unit === "degrees" ? deg2rad(v) : v;
      }
      function fromRadians(v, unit) {
        return unit === "degrees" ? rad2deg(v) : v;
      }
      function setConvertAngular(ax, polarLayout) {
        var axType = ax.type;
        if (axType === "linear") {
          var _d2c = ax.d2c;
          var _c2d = ax.c2d;
          ax.d2c = function(v, unit) {
            return toRadians(_d2c(v), unit);
          };
          ax.c2d = function(v, unit) {
            return _c2d(fromRadians(v, unit));
          };
        }
        ax.makeCalcdata = function(trace, coord) {
          var arrayIn = trace[coord];
          var len = trace._length;
          var arrayOut, i;
          var _d2c2 = function(v) {
            return ax.d2c(v, trace.thetaunit);
          };
          if (arrayIn) {
            arrayOut = new Array(len);
            for (i = 0; i < len; i++) {
              arrayOut[i] = _d2c2(arrayIn[i]);
            }
          } else {
            var coord0 = coord + "0";
            var dcoord = "d" + coord;
            var v0 = coord0 in trace ? _d2c2(trace[coord0]) : 0;
            var dv = trace[dcoord] ? _d2c2(trace[dcoord]) : (ax.period || 2 * Math.PI) / len;
            arrayOut = new Array(len);
            for (i = 0; i < len; i++) {
              arrayOut[i] = v0 + i * dv;
            }
          }
          return arrayOut;
        };
        ax.setGeometry = function() {
          var sector = polarLayout.sector;
          var sectorInRad = sector.map(deg2rad);
          var dir = { clockwise: -1, counterclockwise: 1 }[ax.direction];
          var rot = deg2rad(ax.rotation);
          var rad2g = function(v) {
            return dir * v + rot;
          };
          var g2rad = function(v) {
            return (v - rot) / dir;
          };
          var rad2c, c2rad;
          var rad2t, t2rad;
          switch (axType) {
            case "linear":
              c2rad = rad2c = Lib.identity;
              t2rad = deg2rad;
              rad2t = rad2deg;
              ax.range = Lib.isFullCircle(sectorInRad) ? [sector[0], sector[0] + 360] : sectorInRad.map(g2rad).map(rad2deg);
              break;
            case "category":
              var catLen = ax._categories.length;
              var _period = ax.period ? Math.max(ax.period, catLen) : catLen;
              if (_period === 0) _period = 1;
              c2rad = t2rad = function(v) {
                return v * 2 * Math.PI / _period;
              };
              rad2c = rad2t = function(v) {
                return v * _period / Math.PI / 2;
              };
              ax.range = [0, _period];
              break;
          }
          ax.c2g = function(v) {
            return rad2g(c2rad(v));
          };
          ax.g2c = function(v) {
            return rad2c(g2rad(v));
          };
          ax.t2g = function(v) {
            return rad2g(t2rad(v));
          };
          ax.g2t = function(v) {
            return rad2t(g2rad(v));
          };
        };
      }
    }
  });

  // src/plots/polar/constants.js
  var require_constants33 = __commonJS({
    "src/plots/polar/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        attr: "subplot",
        name: "polar",
        axisNames: ["angularaxis", "radialaxis"],
        axisName2dataArray: { angularaxis: "theta", radialaxis: "r" },
        layerNames: [
          "draglayer",
          "plotbg",
          "backplot",
          "angular-grid",
          "radial-grid",
          "frontplot",
          "angular-line",
          "radial-line",
          "angular-axis",
          "radial-axis"
        ],
        radialDragBoxSize: 50,
        angularDragBoxSize: 30,
        cornerLen: 25,
        cornerHalfWidth: 2,
        // pixels to move mouse before you stop clamping to starting point
        MINDRAG: 8,
        // smallest radial distance [px] allowed for a zoombox
        MINZOOM: 20,
        // distance [px] off (r=0) or (r=radius) where we transition
        // from single-sided to two-sided radial zoom
        OFFEDGE: 20
      };
    }
  });

  // src/plots/polar/helpers.js
  var require_helpers19 = __commonJS({
    "src/plots/polar/helpers.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var polygonTester = require_polygon().tester;
      var findIndexOfMin = Lib.findIndexOfMin;
      var isAngleInsideSector = Lib.isAngleInsideSector;
      var angleDelta = Lib.angleDelta;
      var angleDist = Lib.angleDist;
      function isPtInsidePolygon(r, a, rBnds, aBnds, vangles) {
        if (!isAngleInsideSector(a, aBnds)) return false;
        var r0, r1;
        if (rBnds[0] < rBnds[1]) {
          r0 = rBnds[0];
          r1 = rBnds[1];
        } else {
          r0 = rBnds[1];
          r1 = rBnds[0];
        }
        var polygonIn = polygonTester(makePolygon(r0, aBnds[0], aBnds[1], vangles));
        var polygonOut = polygonTester(makePolygon(r1, aBnds[0], aBnds[1], vangles));
        var xy = [r * Math.cos(a), r * Math.sin(a)];
        return polygonOut.contains(xy) && !polygonIn.contains(xy);
      }
      function findIntersectionXY(v0, v1, a, xpyp) {
        var xstar, ystar;
        var xp = xpyp[0];
        var yp = xpyp[1];
        var dsin = clampTiny(Math.sin(v1) - Math.sin(v0));
        var dcos = clampTiny(Math.cos(v1) - Math.cos(v0));
        var tanA = Math.tan(a);
        var cotanA = clampTiny(1 / tanA);
        var m = dsin / dcos;
        var b = yp - m * xp;
        if (cotanA) {
          if (dsin && dcos) {
            xstar = b / (tanA - m);
            ystar = tanA * xstar;
          } else if (dcos) {
            xstar = yp * cotanA;
            ystar = yp;
          } else {
            xstar = xp;
            ystar = xp * tanA;
          }
        } else {
          if (dsin && dcos) {
            xstar = 0;
            ystar = b;
          } else if (dcos) {
            xstar = 0;
            ystar = yp;
          } else {
            xstar = ystar = NaN;
          }
        }
        return [xstar, ystar];
      }
      function findXYatLength(l, m, xp, yp) {
        var t = -m * xp;
        var a = m * m + 1;
        var b = 2 * (m * t - xp);
        var c = t * t + xp * xp - l * l;
        var del = Math.sqrt(b * b - 4 * a * c);
        var x0 = (-b + del) / (2 * a);
        var x1 = (-b - del) / (2 * a);
        return [
          [x0, m * x0 + t + yp],
          [x1, m * x1 + t + yp]
        ];
      }
      function makeRegularPolygon(r, vangles) {
        var len = vangles.length;
        var vertices = new Array(len + 1);
        var i;
        for (i = 0; i < len; i++) {
          var va = vangles[i];
          vertices[i] = [r * Math.cos(va), r * Math.sin(va)];
        }
        vertices[i] = vertices[0].slice();
        return vertices;
      }
      function makeClippedPolygon(r, a0, a1, vangles) {
        var len = vangles.length;
        var vertices = [];
        var i, j;
        function a2xy(a) {
          return [r * Math.cos(a), r * Math.sin(a)];
        }
        function findXY(va0, va1, s) {
          return findIntersectionXY(va0, va1, s, a2xy(va0));
        }
        function cycleIndex(ind) {
          return Lib.mod(ind, len);
        }
        function isInside(v) {
          return isAngleInsideSector(v, [a0, a1]);
        }
        var i0 = findIndexOfMin(vangles, function(v) {
          return isInside(v) ? angleDist(v, a0) : Infinity;
        });
        var xy0 = findXY(vangles[i0], vangles[cycleIndex(i0 - 1)], a0);
        vertices.push(xy0);
        for (i = i0, j = 0; j < len; i++, j++) {
          var va = vangles[cycleIndex(i)];
          if (!isInside(va)) break;
          vertices.push(a2xy(va));
        }
        var iN = findIndexOfMin(vangles, function(v) {
          return isInside(v) ? angleDist(v, a1) : Infinity;
        });
        var xyN = findXY(vangles[iN], vangles[cycleIndex(iN + 1)], a1);
        vertices.push(xyN);
        vertices.push([0, 0]);
        vertices.push(vertices[0].slice());
        return vertices;
      }
      function makePolygon(r, a0, a1, vangles) {
        return Lib.isFullCircle([a0, a1]) ? makeRegularPolygon(r, vangles) : makeClippedPolygon(r, a0, a1, vangles);
      }
      function findPolygonOffset(r, a0, a1, vangles) {
        var minX = Infinity;
        var minY = Infinity;
        var vertices = makePolygon(r, a0, a1, vangles);
        for (var i = 0; i < vertices.length; i++) {
          var v = vertices[i];
          minX = Math.min(minX, v[0]);
          minY = Math.min(minY, -v[1]);
        }
        return [minX, minY];
      }
      function findEnclosingVertexAngles(a, vangles) {
        var minFn = function(v) {
          var adelta = angleDelta(v, a);
          return adelta > 0 ? adelta : Infinity;
        };
        var i0 = findIndexOfMin(vangles, minFn);
        var i1 = Lib.mod(i0 + 1, vangles.length);
        return [vangles[i0], vangles[i1]];
      }
      function clampTiny(v) {
        return Math.abs(v) > 1e-10 ? v : 0;
      }
      function transformForSVG(pts0, cx, cy) {
        cx = cx || 0;
        cy = cy || 0;
        var len = pts0.length;
        var pts1 = new Array(len);
        for (var i = 0; i < len; i++) {
          var pt = pts0[i];
          pts1[i] = [cx + pt[0], cy - pt[1]];
        }
        return pts1;
      }
      function pathPolygon(r, a0, a1, vangles, cx, cy) {
        var poly = makePolygon(r, a0, a1, vangles);
        return "M" + transformForSVG(poly, cx, cy).join("L");
      }
      function pathPolygonAnnulus(r0, r1, a0, a1, vangles, cx, cy) {
        var rStart, rEnd;
        if (r0 < r1) {
          rStart = r0;
          rEnd = r1;
        } else {
          rStart = r1;
          rEnd = r0;
        }
        var inner = transformForSVG(makePolygon(rStart, a0, a1, vangles), cx, cy);
        var outer = transformForSVG(makePolygon(rEnd, a0, a1, vangles), cx, cy);
        return "M" + outer.reverse().join("L") + "M" + inner.join("L");
      }
      module.exports = {
        isPtInsidePolygon,
        findPolygonOffset,
        findEnclosingVertexAngles,
        findIntersectionXY,
        findXYatLength,
        clampTiny,
        pathPolygon,
        pathPolygonAnnulus
      };
    }
  });

  // src/plots/smith/helpers.js
  var require_helpers20 = __commonJS({
    "src/plots/smith/helpers.js"(exports, module) {
      "use strict";
      function sign(x) {
        return x < 0 ? -1 : x > 0 ? 1 : 0;
      }
      function smith(a) {
        var R = a[0];
        var X = a[1];
        if (!isFinite(R) || !isFinite(X)) return [1, 0];
        var D2 = (R + 1) * (R + 1) + X * X;
        return [(R * R + X * X - 1) / D2, 2 * X / D2];
      }
      function transform(subplot, a) {
        var x = a[0];
        var y = a[1];
        return [
          x * subplot.radius + subplot.cx,
          -y * subplot.radius + subplot.cy
        ];
      }
      function scale(subplot, r) {
        return r * subplot.radius;
      }
      function reactanceArc(subplot, X, R1, R2) {
        var t12 = transform(subplot, smith([R1, X]));
        var x1 = t12[0];
        var y1 = t12[1];
        var t22 = transform(subplot, smith([R2, X]));
        var x2 = t22[0];
        var y2 = t22[1];
        if (X === 0) {
          return [
            "M" + x1 + "," + y1,
            "L" + x2 + "," + y2
          ].join(" ");
        }
        var r = scale(subplot, 1 / Math.abs(X));
        return [
          "M" + x1 + "," + y1,
          "A" + r + "," + r + " 0 0," + (X < 0 ? 1 : 0) + " " + x2 + "," + y2
        ].join(" ");
      }
      function resistanceArc(subplot, R, X1, X2) {
        var r = scale(subplot, 1 / (R + 1));
        var t12 = transform(subplot, smith([R, X1]));
        var x1 = t12[0];
        var y1 = t12[1];
        var t22 = transform(subplot, smith([R, X2]));
        var x2 = t22[0];
        var y2 = t22[1];
        if (sign(X1) !== sign(X2)) {
          var t02 = transform(subplot, smith([R, 0]));
          var x0 = t02[0];
          var y0 = t02[1];
          return [
            "M" + x1 + "," + y1,
            "A" + r + "," + r + " 0 0," + (0 < X1 ? 0 : 1) + " " + x0 + "," + y0,
            "A" + r + "," + r + " 0 0," + (X2 < 0 ? 0 : 1) + x2 + "," + y2
          ].join(" ");
        }
        return [
          "M" + x1 + "," + y1,
          "A" + r + "," + r + " 0 0," + (X2 < X1 ? 0 : 1) + " " + x2 + "," + y2
        ].join(" ");
      }
      module.exports = {
        smith,
        reactanceArc,
        resistanceArc,
        smithTransform: transform
      };
    }
  });

  // src/plots/polar/polar.js
  var require_polar = __commonJS({
    "src/plots/polar/polar.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var tinycolor = require_tinycolor();
      var Registry = require_registry();
      var Lib = require_lib();
      var strRotate = Lib.strRotate;
      var strTranslate = Lib.strTranslate;
      var Color2 = require_color();
      var Drawing = require_drawing();
      var Plots = require_plots();
      var Axes = require_axes();
      var setConvertCartesian = require_set_convert();
      var setConvertPolar = require_set_convert3();
      var doAutoRange = require_autorange().doAutoRange;
      var dragBox = require_dragbox();
      var dragElement = require_dragelement();
      var Fx = require_fx();
      var Titles = require_titles();
      var prepSelect = require_selections().prepSelect;
      var selectOnClick = require_selections().selectOnClick;
      var clearOutline = require_selections().clearOutline;
      var setCursor = require_setcursor();
      var clearGlCanvases = require_clear_gl_canvases();
      var redrawReglTraces = require_subroutines().redrawReglTraces;
      var MID_SHIFT = require_alignment().MID_SHIFT;
      var constants = require_constants33();
      var helpers = require_helpers19();
      var smithHelpers = require_helpers20();
      var smith = smithHelpers.smith;
      var reactanceArc = smithHelpers.reactanceArc;
      var resistanceArc = smithHelpers.resistanceArc;
      var smithTransform = smithHelpers.smithTransform;
      var _ = Lib._;
      var mod = Lib.mod;
      var deg2rad = Lib.deg2rad;
      var rad2deg = Lib.rad2deg;
      function Polar(gd, id, isSmith) {
        this.isSmith = isSmith || false;
        this.id = id;
        this.gd = gd;
        this._hasClipOnAxisFalse = null;
        this.vangles = null;
        this.radialAxisAngle = null;
        this.traceHash = {};
        this.layers = {};
        this.clipPaths = {};
        this.clipIds = {};
        this.viewInitial = {};
        var fullLayout = gd._fullLayout;
        var clipIdBase = "clip" + fullLayout._uid + id;
        this.clipIds.forTraces = clipIdBase + "-for-traces";
        this.clipPaths.forTraces = fullLayout._clips.append("clipPath").attr("id", this.clipIds.forTraces);
        this.clipPaths.forTraces.append("path");
        this.framework = fullLayout["_" + (isSmith ? "smith" : "polar") + "layer"].append("g").attr("class", id);
        this.getHole = function(s) {
          return this.isSmith ? 0 : s.hole;
        };
        this.getSector = function(s) {
          return this.isSmith ? [0, 360] : s.sector;
        };
        this.getRadial = function(s) {
          return this.isSmith ? s.realaxis : s.radialaxis;
        };
        this.getAngular = function(s) {
          return this.isSmith ? s.imaginaryaxis : s.angularaxis;
        };
        if (!isSmith) {
          this.radialTickLayout = null;
          this.angularTickLayout = null;
        }
      }
      var proto = Polar.prototype;
      module.exports = function createPolar(gd, id, isSmith) {
        return new Polar(gd, id, isSmith);
      };
      proto.plot = function(polarCalcData, fullLayout) {
        var _this = this;
        var polarLayout = fullLayout[_this.id];
        var found = false;
        for (var i = 0; i < polarCalcData.length; i++) {
          var trace = polarCalcData[i][0].trace;
          if (trace.cliponaxis === false) {
            found = true;
            break;
          }
        }
        _this._hasClipOnAxisFalse = found;
        _this.updateLayers(fullLayout, polarLayout);
        _this.updateLayout(fullLayout, polarLayout);
        Plots.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout);
        _this.updateFx(fullLayout, polarLayout);
        if (_this.isSmith) {
          delete polarLayout.realaxis.range;
          delete polarLayout.imaginaryaxis.range;
        }
      };
      proto.updateLayers = function(fullLayout, polarLayout) {
        var _this = this;
        var isSmith = _this.isSmith;
        var layers = _this.layers;
        var radialLayout = _this.getRadial(polarLayout);
        var angularLayout = _this.getAngular(polarLayout);
        var layerNames = constants.layerNames;
        var frontPlotIndex = layerNames.indexOf("frontplot");
        var layerData = layerNames.slice(0, frontPlotIndex);
        var isAngularAxisBelowTraces = angularLayout.layer === "below traces";
        var isRadialAxisBelowTraces = radialLayout.layer === "below traces";
        if (isAngularAxisBelowTraces) layerData.push("angular-line");
        if (isRadialAxisBelowTraces) layerData.push("radial-line");
        if (isAngularAxisBelowTraces) layerData.push("angular-axis");
        if (isRadialAxisBelowTraces) layerData.push("radial-axis");
        layerData.push("frontplot");
        if (!isAngularAxisBelowTraces) layerData.push("angular-line");
        if (!isRadialAxisBelowTraces) layerData.push("radial-line");
        if (!isAngularAxisBelowTraces) layerData.push("angular-axis");
        if (!isRadialAxisBelowTraces) layerData.push("radial-axis");
        var subLayer = (isSmith ? "smith" : "polar") + "sublayer";
        var join = _this.framework.selectAll("." + subLayer).data(layerData, String);
        join.enter().append("g").attr("class", function(d) {
          return subLayer + " " + d;
        }).each(function(d) {
          var sel = layers[d] = d3.select(this);
          switch (d) {
            case "frontplot":
              if (!isSmith) {
                sel.append("g").classed("barlayer", true);
              }
              sel.append("g").classed("scatterlayer", true);
              break;
            case "backplot":
              sel.append("g").classed("maplayer", true);
              break;
            case "plotbg":
              layers.bg = sel.append("path");
              break;
            case "radial-grid":
              sel.style("fill", "none");
              break;
            case "angular-grid":
              sel.style("fill", "none");
              break;
            case "radial-line":
              sel.append("line").style("fill", "none");
              break;
            case "angular-line":
              sel.append("path").style("fill", "none");
              break;
          }
        });
        join.order();
      };
      proto.updateLayout = function(fullLayout, polarLayout) {
        var _this = this;
        var layers = _this.layers;
        var gs = fullLayout._size;
        var radialLayout = _this.getRadial(polarLayout);
        var angularLayout = _this.getAngular(polarLayout);
        var xDomain = polarLayout.domain.x;
        var yDomain = polarLayout.domain.y;
        _this.xOffset = gs.l + gs.w * xDomain[0];
        _this.yOffset = gs.t + gs.h * (1 - yDomain[1]);
        var xLength = _this.xLength = gs.w * (xDomain[1] - xDomain[0]);
        var yLength = _this.yLength = gs.h * (yDomain[1] - yDomain[0]);
        var sector = _this.getSector(polarLayout);
        _this.sectorInRad = sector.map(deg2rad);
        var sectorBBox = _this.sectorBBox = computeSectorBBox(sector);
        var dxSectorBBox = sectorBBox[2] - sectorBBox[0];
        var dySectorBBox = sectorBBox[3] - sectorBBox[1];
        var arDomain = yLength / xLength;
        var arSector = Math.abs(dySectorBBox / dxSectorBBox);
        var xLength2, yLength2;
        var xDomain2, yDomain2;
        var gap;
        if (arDomain > arSector) {
          xLength2 = xLength;
          yLength2 = xLength * arSector;
          gap = (yLength - yLength2) / gs.h / 2;
          xDomain2 = [xDomain[0], xDomain[1]];
          yDomain2 = [yDomain[0] + gap, yDomain[1] - gap];
        } else {
          xLength2 = yLength / arSector;
          yLength2 = yLength;
          gap = (xLength - xLength2) / gs.w / 2;
          xDomain2 = [xDomain[0] + gap, xDomain[1] - gap];
          yDomain2 = [yDomain[0], yDomain[1]];
        }
        _this.xLength2 = xLength2;
        _this.yLength2 = yLength2;
        _this.xDomain2 = xDomain2;
        _this.yDomain2 = yDomain2;
        var xOffset2 = _this.xOffset2 = gs.l + gs.w * xDomain2[0];
        var yOffset2 = _this.yOffset2 = gs.t + gs.h * (1 - yDomain2[1]);
        var radius = _this.radius = xLength2 / dxSectorBBox;
        var innerRadius = _this.innerRadius = _this.getHole(polarLayout) * radius;
        var cx = _this.cx = xOffset2 - radius * sectorBBox[0];
        var cy = _this.cy = yOffset2 + radius * sectorBBox[3];
        var cxx = _this.cxx = cx - xOffset2;
        var cyy = _this.cyy = cy - yOffset2;
        var side = radialLayout.side;
        var trueSide;
        if (side === "counterclockwise") {
          trueSide = side;
          side = "top";
        } else if (side === "clockwise") {
          trueSide = side;
          side = "bottom";
        }
        _this.radialAxis = _this.mockAxis(fullLayout, polarLayout, radialLayout, {
          // make this an 'x' axis to make positioning (especially rotation) easier
          _id: "x",
          // convert to 'x' axis equivalent
          side,
          // keep track of real side
          _trueSide: trueSide,
          // spans length 1 radius
          domain: [innerRadius / gs.w, radius / gs.w]
        });
        _this.angularAxis = _this.mockAxis(fullLayout, polarLayout, angularLayout, {
          side: "right",
          // to get auto nticks right
          domain: [0, Math.PI],
          // don't pass through autorange logic
          autorange: false
        });
        _this.doAutoRange(fullLayout, polarLayout);
        _this.updateAngularAxis(fullLayout, polarLayout);
        _this.updateRadialAxis(fullLayout, polarLayout);
        _this.updateRadialAxisTitle(fullLayout, polarLayout);
        _this.xaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
          _id: "x",
          domain: xDomain2
        });
        _this.yaxis = _this.mockCartesianAxis(fullLayout, polarLayout, {
          _id: "y",
          domain: yDomain2
        });
        var dPath = _this.pathSubplot();
        _this.clipPaths.forTraces.select("path").attr("d", dPath).attr("transform", strTranslate(cxx, cyy));
        layers.frontplot.attr("transform", strTranslate(xOffset2, yOffset2)).call(Drawing.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.forTraces, _this.gd);
        layers.bg.attr("d", dPath).attr("transform", strTranslate(cx, cy)).call(Color2.fill, polarLayout.bgcolor);
      };
      proto.mockAxis = function(fullLayout, polarLayout, axLayout, opts) {
        var ax = Lib.extendFlat({}, axLayout, opts);
        setConvertPolar(ax, polarLayout, fullLayout);
        return ax;
      };
      proto.mockCartesianAxis = function(fullLayout, polarLayout, opts) {
        var _this = this;
        var isSmith = _this.isSmith;
        var axId = opts._id;
        var ax = Lib.extendFlat({ type: "linear" }, opts);
        setConvertCartesian(ax, fullLayout);
        var bboxIndices = {
          x: [0, 2],
          y: [1, 3]
        };
        ax.setRange = function() {
          var sectorBBox = _this.sectorBBox;
          var ind = bboxIndices[axId];
          var rl = _this.radialAxis._rl;
          var drl = (rl[1] - rl[0]) / (1 - _this.getHole(polarLayout));
          ax.range = [sectorBBox[ind[0]] * drl, sectorBBox[ind[1]] * drl];
        };
        ax.isPtWithinRange = axId === "x" && !isSmith ? function(d) {
          return _this.isPtInside(d);
        } : function() {
          return true;
        };
        ax.setRange();
        ax.setScale();
        return ax;
      };
      proto.doAutoRange = function(fullLayout, polarLayout) {
        var _this = this;
        var gd = _this.gd;
        var radialAxis = _this.radialAxis;
        var radialLayout = _this.getRadial(polarLayout);
        doAutoRange(gd, radialAxis);
        var rng = radialAxis.range;
        radialLayout.range = rng.slice();
        radialLayout._input.range = rng.slice();
        radialAxis._rl = [
          radialAxis.r2l(rng[0], null, "gregorian"),
          radialAxis.r2l(rng[1], null, "gregorian")
        ];
        if (radialAxis.minallowed !== void 0) {
          var minallowed = radialAxis.r2l(radialAxis.minallowed);
          if (radialAxis._rl[0] > radialAxis._rl[1]) {
            radialAxis._rl[1] = Math.max(radialAxis._rl[1], minallowed);
          } else {
            radialAxis._rl[0] = Math.max(radialAxis._rl[0], minallowed);
          }
        }
        if (radialAxis.maxallowed !== void 0) {
          var maxallowed = radialAxis.r2l(radialAxis.maxallowed);
          if (radialAxis._rl[0] < radialAxis._rl[1]) {
            radialAxis._rl[1] = Math.min(radialAxis._rl[1], maxallowed);
          } else {
            radialAxis._rl[0] = Math.min(radialAxis._rl[0], maxallowed);
          }
        }
      };
      proto.updateRadialAxis = function(fullLayout, polarLayout) {
        var _this = this;
        var gd = _this.gd;
        var layers = _this.layers;
        var radius = _this.radius;
        var innerRadius = _this.innerRadius;
        var cx = _this.cx;
        var cy = _this.cy;
        var radialLayout = _this.getRadial(polarLayout);
        var a0 = mod(_this.getSector(polarLayout)[0], 360);
        var ax = _this.radialAxis;
        var hasRoomForIt = innerRadius < radius;
        var isSmith = _this.isSmith;
        if (!isSmith) {
          _this.fillViewInitialKey("radialaxis.angle", radialLayout.angle);
          _this.fillViewInitialKey("radialaxis.range", ax.range.slice());
          ax.setGeometry();
        }
        if (ax.tickangle === "auto" && (a0 > 90 && a0 <= 270)) {
          ax.tickangle = 180;
        }
        var transFn = isSmith ? function(d) {
          var t = smithTransform(_this, smith([d.x, 0]));
          return strTranslate(t[0] - cx, t[1] - cy);
        } : function(d) {
          return strTranslate(ax.l2p(d.x) + innerRadius, 0);
        };
        var gridPathFn = isSmith ? function(d) {
          return resistanceArc(_this, d.x, -Infinity, Infinity);
        } : function(d) {
          return _this.pathArc(ax.r2p(d.x) + innerRadius);
        };
        var newTickLayout = strTickLayout(radialLayout);
        if (_this.radialTickLayout !== newTickLayout) {
          layers["radial-axis"].selectAll(".xtick").remove();
          _this.radialTickLayout = newTickLayout;
        }
        if (hasRoomForIt) {
          ax.setScale();
          var labelShift = 0;
          var vals = isSmith ? (ax.tickvals || []).filter(function(x) {
            return x >= 0;
          }).map(function(x) {
            return Axes.tickText(ax, x, true, false);
          }) : Axes.calcTicks(ax);
          var valsClipped = isSmith ? vals : Axes.clipEnds(ax, vals);
          var tickSign = Axes.getTickSigns(ax)[2];
          if (isSmith) {
            if (ax.ticks === "top" && ax.side === "bottom" || ax.ticks === "bottom" && ax.side === "top") {
              tickSign = -tickSign;
            }
            if (ax.ticks === "top" && ax.side === "top") labelShift = -ax.ticklen;
            if (ax.ticks === "bottom" && ax.side === "bottom") labelShift = ax.ticklen;
          }
          Axes.drawTicks(gd, ax, {
            vals,
            layer: layers["radial-axis"],
            path: Axes.makeTickPath(ax, 0, tickSign),
            transFn,
            crisp: false
          });
          Axes.drawGrid(gd, ax, {
            vals: valsClipped,
            layer: layers["radial-grid"],
            path: gridPathFn,
            transFn: Lib.noop,
            crisp: false
          });
          Axes.drawLabels(gd, ax, {
            vals,
            layer: layers["radial-axis"],
            transFn,
            labelFns: Axes.makeLabelFns(ax, labelShift)
          });
        }
        var angle = _this.radialAxisAngle = _this.vangles ? rad2deg(snapToVertexAngle(deg2rad(radialLayout.angle), _this.vangles)) : radialLayout.angle;
        var tLayer = strTranslate(cx, cy);
        var tLayer2 = tLayer + strRotate(-angle);
        updateElement(
          layers["radial-axis"],
          hasRoomForIt && (radialLayout.showticklabels || radialLayout.ticks),
          { transform: tLayer2 }
        );
        updateElement(
          layers["radial-grid"],
          hasRoomForIt && radialLayout.showgrid,
          { transform: isSmith ? "" : tLayer }
        );
        updateElement(
          layers["radial-line"].select("line"),
          hasRoomForIt && radialLayout.showline,
          {
            x1: isSmith ? -radius : innerRadius,
            y1: 0,
            x2: radius,
            y2: 0,
            transform: tLayer2
          }
        ).attr("stroke-width", radialLayout.linewidth).call(Color2.stroke, radialLayout.linecolor);
      };
      proto.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) {
        if (this.isSmith) return;
        var _this = this;
        var gd = _this.gd;
        var radius = _this.radius;
        var cx = _this.cx;
        var cy = _this.cy;
        var radialLayout = _this.getRadial(polarLayout);
        var titleClass = _this.id + "title";
        var pad = 0;
        if (radialLayout.title) {
          var h = Drawing.bBox(_this.layers["radial-axis"].node()).height;
          var ts = radialLayout.title.font.size;
          var side = radialLayout.side;
          pad = side === "top" ? ts : side === "counterclockwise" ? -(h + ts * 0.4) : h + ts * 0.8;
        }
        var angle = _angle !== void 0 ? _angle : _this.radialAxisAngle;
        var angleRad = deg2rad(angle);
        var cosa = Math.cos(angleRad);
        var sina = Math.sin(angleRad);
        var x = cx + radius / 2 * cosa + pad * sina;
        var y = cy - radius / 2 * sina + pad * cosa;
        _this.layers["radial-axis-title"] = Titles.draw(gd, titleClass, {
          propContainer: radialLayout,
          propName: _this.id + ".radialaxis.title.text",
          placeholder: _(gd, "Click to enter radial axis title"),
          attributes: {
            x,
            y,
            "text-anchor": "middle"
          },
          transform: { rotate: -angle }
        });
      };
      proto.updateAngularAxis = function(fullLayout, polarLayout) {
        var _this = this;
        var gd = _this.gd;
        var layers = _this.layers;
        var radius = _this.radius;
        var innerRadius = _this.innerRadius;
        var cx = _this.cx;
        var cy = _this.cy;
        var angularLayout = _this.getAngular(polarLayout);
        var ax = _this.angularAxis;
        var isSmith = _this.isSmith;
        if (!isSmith) {
          _this.fillViewInitialKey("angularaxis.rotation", angularLayout.rotation);
          ax.setGeometry();
          ax.setScale();
        }
        var t2g = isSmith ? function(d) {
          var t = smithTransform(_this, smith([0, d.x]));
          return Math.atan2(t[0] - cx, t[1] - cy) - Math.PI / 2;
        } : function(d) {
          return ax.t2g(d.x);
        };
        if (ax.type === "linear" && ax.thetaunit === "radians") {
          ax.tick0 = rad2deg(ax.tick0);
          ax.dtick = rad2deg(ax.dtick);
        }
        var _transFn = function(rad) {
          return strTranslate(cx + radius * Math.cos(rad), cy - radius * Math.sin(rad));
        };
        var transFn = isSmith ? function(d) {
          var t = smithTransform(_this, smith([0, d.x]));
          return strTranslate(t[0], t[1]);
        } : function(d) {
          return _transFn(t2g(d));
        };
        var transFn2 = isSmith ? function(d) {
          var t = smithTransform(_this, smith([0, d.x]));
          var rad = Math.atan2(t[0] - cx, t[1] - cy) - Math.PI / 2;
          return strTranslate(t[0], t[1]) + strRotate(-rad2deg(rad));
        } : function(d) {
          var rad = t2g(d);
          return _transFn(rad) + strRotate(-rad2deg(rad));
        };
        var gridPathFn = isSmith ? function(d) {
          return reactanceArc(_this, d.x, 0, Infinity);
        } : function(d) {
          var rad = t2g(d);
          var cosRad = Math.cos(rad);
          var sinRad = Math.sin(rad);
          return "M" + [cx + innerRadius * cosRad, cy - innerRadius * sinRad] + "L" + [cx + radius * cosRad, cy - radius * sinRad];
        };
        var out = Axes.makeLabelFns(ax, 0);
        var labelStandoff = out.labelStandoff;
        var labelFns = {};
        labelFns.xFn = function(d) {
          var rad = t2g(d);
          return Math.cos(rad) * labelStandoff;
        };
        labelFns.yFn = function(d) {
          var rad = t2g(d);
          var ff = Math.sin(rad) > 0 ? 0.2 : 1;
          return -Math.sin(rad) * (labelStandoff + d.fontSize * ff) + Math.abs(Math.cos(rad)) * (d.fontSize * MID_SHIFT);
        };
        labelFns.anchorFn = function(d) {
          var rad = t2g(d);
          var cos = Math.cos(rad);
          return Math.abs(cos) < 0.1 ? "middle" : cos > 0 ? "start" : "end";
        };
        labelFns.heightFn = function(d, a, h) {
          var rad = t2g(d);
          return -0.5 * (1 + Math.sin(rad)) * h;
        };
        var newTickLayout = strTickLayout(angularLayout);
        if (_this.angularTickLayout !== newTickLayout) {
          layers["angular-axis"].selectAll("." + ax._id + "tick").remove();
          _this.angularTickLayout = newTickLayout;
        }
        var vals = isSmith ? [Infinity].concat(ax.tickvals || []).map(function(x) {
          return Axes.tickText(ax, x, true, false);
        }) : Axes.calcTicks(ax);
        if (isSmith) {
          vals[0].text = "\u221E";
          vals[0].fontSize *= 1.75;
        }
        var vangles;
        if (polarLayout.gridshape === "linear") {
          vangles = vals.map(t2g);
          if (Lib.angleDelta(vangles[0], vangles[1]) < 0) {
            vangles = vangles.slice().reverse();
          }
        } else {
          vangles = null;
        }
        _this.vangles = vangles;
        if (ax.type === "category") {
          vals = vals.filter(function(d) {
            return Lib.isAngleInsideSector(t2g(d), _this.sectorInRad);
          });
        }
        if (ax.visible) {
          var tickSign = ax.ticks === "inside" ? -1 : 1;
          var pad = (ax.linewidth || 1) / 2;
          Axes.drawTicks(gd, ax, {
            vals,
            layer: layers["angular-axis"],
            path: "M" + tickSign * pad + ",0h" + tickSign * ax.ticklen,
            transFn: transFn2,
            crisp: false
          });
          Axes.drawGrid(gd, ax, {
            vals,
            layer: layers["angular-grid"],
            path: gridPathFn,
            transFn: Lib.noop,
            crisp: false
          });
          Axes.drawLabels(gd, ax, {
            vals,
            layer: layers["angular-axis"],
            repositionOnUpdate: true,
            transFn,
            labelFns
          });
        }
        updateElement(layers["angular-line"].select("path"), angularLayout.showline, {
          d: _this.pathSubplot(),
          transform: strTranslate(cx, cy)
        }).attr("stroke-width", angularLayout.linewidth).call(Color2.stroke, angularLayout.linecolor);
      };
      proto.updateFx = function(fullLayout, polarLayout) {
        if (!this.gd._context.staticPlot) {
          var hasDrag = !this.isSmith;
          if (hasDrag) {
            this.updateAngularDrag(fullLayout);
            this.updateRadialDrag(fullLayout, polarLayout, 0);
            this.updateRadialDrag(fullLayout, polarLayout, 1);
          }
          this.updateHoverAndMainDrag(fullLayout);
        }
      };
      proto.updateHoverAndMainDrag = function(fullLayout) {
        var _this = this;
        var isSmith = _this.isSmith;
        var gd = _this.gd;
        var layers = _this.layers;
        var zoomlayer = fullLayout._zoomlayer;
        var MINZOOM = constants.MINZOOM;
        var OFFEDGE = constants.OFFEDGE;
        var radius = _this.radius;
        var innerRadius = _this.innerRadius;
        var cx = _this.cx;
        var cy = _this.cy;
        var cxx = _this.cxx;
        var cyy = _this.cyy;
        var sectorInRad = _this.sectorInRad;
        var vangles = _this.vangles;
        var radialAxis = _this.radialAxis;
        var clampTiny = helpers.clampTiny;
        var findXYatLength = helpers.findXYatLength;
        var findEnclosingVertexAngles = helpers.findEnclosingVertexAngles;
        var chw = constants.cornerHalfWidth;
        var chl = constants.cornerLen / 2;
        var scaleX;
        var scaleY;
        var mainDrag = dragBox.makeDragger(layers, "path", "maindrag", fullLayout.dragmode === false ? "none" : "crosshair");
        d3.select(mainDrag).attr("d", _this.pathSubplot()).attr("transform", strTranslate(cx, cy));
        mainDrag.onmousemove = function(evt) {
          Fx.hover(gd, evt, _this.id);
          gd._fullLayout._lasthover = mainDrag;
          gd._fullLayout._hoversubplot = _this.id;
        };
        mainDrag.onmouseout = function(evt) {
          if (gd._dragging) return;
          dragElement.unhover(gd, evt);
        };
        var dragOpts = {
          element: mainDrag,
          gd,
          subplot: _this.id,
          plotinfo: {
            id: _this.id,
            xaxis: _this.xaxis,
            yaxis: _this.yaxis
          },
          xaxes: [_this.xaxis],
          yaxes: [_this.yaxis]
        };
        var x0, y0;
        var r0, r1;
        var path0, dimmed, lum;
        var zb, corners;
        function norm(x, y) {
          return Math.sqrt(x * x + y * y);
        }
        function xy2r(x, y) {
          return norm(x - cxx, y - cyy);
        }
        function xy2a(x, y) {
          return Math.atan2(cyy - y, x - cxx);
        }
        function ra2xy(r, a) {
          return [r * Math.cos(a), r * Math.sin(-a)];
        }
        function pathCorner(r, a) {
          if (r === 0) return _this.pathSector(2 * chw);
          var da = chl / r;
          var am = a - da;
          var ap = a + da;
          var rb = Math.max(0, Math.min(r, radius));
          var rm = rb - chw;
          var rp = rb + chw;
          return "M" + ra2xy(rm, am) + "A" + [rm, rm] + " 0,0,0 " + ra2xy(rm, ap) + "L" + ra2xy(rp, ap) + "A" + [rp, rp] + " 0,0,1 " + ra2xy(rp, am) + "Z";
        }
        function pathCornerForPolygons(r, va0, va1) {
          if (r === 0) return _this.pathSector(2 * chw);
          var xy0 = ra2xy(r, va0);
          var xy1 = ra2xy(r, va1);
          var x = clampTiny((xy0[0] + xy1[0]) / 2);
          var y = clampTiny((xy0[1] + xy1[1]) / 2);
          var innerPts, outerPts;
          if (x && y) {
            var m = y / x;
            var mperp = -1 / m;
            var midPts = findXYatLength(chw, m, x, y);
            innerPts = findXYatLength(chl, mperp, midPts[0][0], midPts[0][1]);
            outerPts = findXYatLength(chl, mperp, midPts[1][0], midPts[1][1]);
          } else {
            var dx, dy;
            if (y) {
              dx = chl;
              dy = chw;
            } else {
              dx = chw;
              dy = chl;
            }
            innerPts = [[x - dx, y - dy], [x + dx, y - dy]];
            outerPts = [[x - dx, y + dy], [x + dx, y + dy]];
          }
          return "M" + innerPts.join("L") + "L" + outerPts.reverse().join("L") + "Z";
        }
        function zoomPrep() {
          r0 = null;
          r1 = null;
          path0 = _this.pathSubplot();
          dimmed = false;
          var polarLayoutNow = gd._fullLayout[_this.id];
          lum = tinycolor(polarLayoutNow.bgcolor).getLuminance();
          zb = dragBox.makeZoombox(zoomlayer, lum, cx, cy, path0);
          zb.attr("fill-rule", "evenodd");
          corners = dragBox.makeCorners(zoomlayer, cx, cy);
          clearOutline(gd);
        }
        function clampAndSetR0R1(rr0, rr1) {
          rr1 = Math.max(Math.min(rr1, radius), innerRadius);
          if (rr0 < OFFEDGE) rr0 = 0;
          else if (radius - rr0 < OFFEDGE) rr0 = radius;
          else if (rr1 < OFFEDGE) rr1 = 0;
          else if (radius - rr1 < OFFEDGE) rr1 = radius;
          if (Math.abs(rr1 - rr0) > MINZOOM) {
            if (rr0 < rr1) {
              r0 = rr0;
              r1 = rr1;
            } else {
              r0 = rr1;
              r1 = rr0;
            }
            return true;
          } else {
            r0 = null;
            r1 = null;
            return false;
          }
        }
        function applyZoomMove(path1, cpath) {
          path1 = path1 || path0;
          cpath = cpath || "M0,0Z";
          zb.attr("d", path1);
          corners.attr("d", cpath);
          dragBox.transitionZoombox(zb, corners, dimmed, lum);
          dimmed = true;
          var updateObj = {};
          computeZoomUpdates(updateObj);
          gd.emit("plotly_relayouting", updateObj);
        }
        function zoomMove(dx, dy) {
          dx = dx * scaleX;
          dy = dy * scaleY;
          var x1 = x0 + dx;
          var y1 = y0 + dy;
          var rr0 = xy2r(x0, y0);
          var rr1 = Math.min(xy2r(x1, y1), radius);
          var a0 = xy2a(x0, y0);
          var path1;
          var cpath;
          if (clampAndSetR0R1(rr0, rr1)) {
            path1 = path0 + _this.pathSector(r1);
            if (r0) path1 += _this.pathSector(r0);
            cpath = pathCorner(r0, a0) + pathCorner(r1, a0);
          }
          applyZoomMove(path1, cpath);
        }
        function findPolygonRadius(x, y, va0, va1) {
          var xy = helpers.findIntersectionXY(va0, va1, va0, [x - cxx, cyy - y]);
          return norm(xy[0], xy[1]);
        }
        function zoomMoveForPolygons(dx, dy) {
          var x1 = x0 + dx;
          var y1 = y0 + dy;
          var a0 = xy2a(x0, y0);
          var a1 = xy2a(x1, y1);
          var vangles0 = findEnclosingVertexAngles(a0, vangles);
          var vangles1 = findEnclosingVertexAngles(a1, vangles);
          var rr0 = findPolygonRadius(x0, y0, vangles0[0], vangles0[1]);
          var rr1 = Math.min(findPolygonRadius(x1, y1, vangles1[0], vangles1[1]), radius);
          var path1;
          var cpath;
          if (clampAndSetR0R1(rr0, rr1)) {
            path1 = path0 + _this.pathSector(r1);
            if (r0) path1 += _this.pathSector(r0);
            cpath = [
              pathCornerForPolygons(r0, vangles0[0], vangles0[1]),
              pathCornerForPolygons(r1, vangles0[0], vangles0[1])
            ].join(" ");
          }
          applyZoomMove(path1, cpath);
        }
        function zoomDone() {
          dragBox.removeZoombox(gd);
          if (r0 === null || r1 === null) return;
          var updateObj = {};
          computeZoomUpdates(updateObj);
          dragBox.showDoubleClickNotifier(gd);
          Registry.call("_guiRelayout", gd, updateObj);
        }
        function computeZoomUpdates(update) {
          var rl = radialAxis._rl;
          var m = (rl[1] - rl[0]) / (1 - innerRadius / radius) / radius;
          var newRng = [
            rl[0] + (r0 - innerRadius) * m,
            rl[0] + (r1 - innerRadius) * m
          ];
          update[_this.id + ".radialaxis.range"] = newRng;
        }
        function zoomClick(numClicks, evt) {
          var clickMode = gd._fullLayout.clickmode;
          dragBox.removeZoombox(gd);
          if (numClicks === 2) {
            var updateObj = {};
            for (var k in _this.viewInitial) {
              updateObj[_this.id + "." + k] = _this.viewInitial[k];
            }
            gd.emit("plotly_doubleclick", null);
            Registry.call("_guiRelayout", gd, updateObj);
          }
          if (clickMode.indexOf("select") > -1 && numClicks === 1) {
            selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOpts);
          }
          if (clickMode.indexOf("event") > -1) {
            Fx.click(gd, evt, _this.id);
          }
        }
        dragOpts.prepFn = function(evt, startX, startY) {
          var dragModeNow = gd._fullLayout.dragmode;
          var bbox = mainDrag.getBoundingClientRect();
          gd._fullLayout._calcInverseTransform(gd);
          var inverse = gd._fullLayout._invTransform;
          scaleX = gd._fullLayout._invScaleX;
          scaleY = gd._fullLayout._invScaleY;
          var transformedCoords = Lib.apply3DTransform(inverse)(startX - bbox.left, startY - bbox.top);
          x0 = transformedCoords[0];
          y0 = transformedCoords[1];
          if (vangles) {
            var offset = helpers.findPolygonOffset(radius, sectorInRad[0], sectorInRad[1], vangles);
            x0 += cxx + offset[0];
            y0 += cyy + offset[1];
          }
          switch (dragModeNow) {
            case "zoom":
              dragOpts.clickFn = zoomClick;
              if (!isSmith) {
                if (vangles) {
                  dragOpts.moveFn = zoomMoveForPolygons;
                } else {
                  dragOpts.moveFn = zoomMove;
                }
                dragOpts.doneFn = zoomDone;
                zoomPrep(evt, startX, startY);
              }
              break;
            case "select":
            case "lasso":
              prepSelect(evt, startX, startY, dragOpts, dragModeNow);
              break;
          }
        };
        dragElement.init(dragOpts);
      };
      proto.updateRadialDrag = function(fullLayout, polarLayout, rngIndex) {
        var _this = this;
        var gd = _this.gd;
        var layers = _this.layers;
        var radius = _this.radius;
        var innerRadius = _this.innerRadius;
        var cx = _this.cx;
        var cy = _this.cy;
        var radialAxis = _this.radialAxis;
        var bl = constants.radialDragBoxSize;
        var bl2 = bl / 2;
        if (!radialAxis.visible) return;
        var angle0 = deg2rad(_this.radialAxisAngle);
        var rl = radialAxis._rl;
        var rl0 = rl[0];
        var rl1 = rl[1];
        var rbase = rl[rngIndex];
        var m = 0.75 * (rl[1] - rl[0]) / (1 - _this.getHole(polarLayout)) / radius;
        var tx, ty, className;
        if (rngIndex) {
          tx = cx + (radius + bl2) * Math.cos(angle0);
          ty = cy - (radius + bl2) * Math.sin(angle0);
          className = "radialdrag";
        } else {
          tx = cx + (innerRadius - bl2) * Math.cos(angle0);
          ty = cy - (innerRadius - bl2) * Math.sin(angle0);
          className = "radialdrag-inner";
        }
        var radialDrag = dragBox.makeRectDragger(layers, className, "crosshair", -bl2, -bl2, bl, bl);
        var dragOpts = { element: radialDrag, gd };
        if (fullLayout.dragmode === false) {
          dragOpts.dragmode = false;
        }
        updateElement(d3.select(radialDrag), radialAxis.visible && innerRadius < radius, {
          transform: strTranslate(tx, ty)
        });
        var moveFn2;
        var angle1;
        var rprime;
        function moveFn(dx, dy) {
          if (moveFn2) {
            moveFn2(dx, dy);
          } else {
            var dvec = [dx, -dy];
            var rvec = [Math.cos(angle0), Math.sin(angle0)];
            var comp = Math.abs(Lib.dot(dvec, rvec) / Math.sqrt(Lib.dot(dvec, dvec)));
            if (!isNaN(comp)) {
              moveFn2 = comp < 0.5 ? rotateMove : rerangeMove;
            }
          }
          var update = {};
          computeRadialAxisUpdates(update);
          gd.emit("plotly_relayouting", update);
        }
        function computeRadialAxisUpdates(update) {
          if (angle1 !== null) {
            update[_this.id + ".radialaxis.angle"] = angle1;
          } else if (rprime !== null) {
            update[_this.id + ".radialaxis.range[" + rngIndex + "]"] = rprime;
          }
        }
        function doneFn() {
          if (angle1 !== null) {
            Registry.call("_guiRelayout", gd, _this.id + ".radialaxis.angle", angle1);
          } else if (rprime !== null) {
            Registry.call("_guiRelayout", gd, _this.id + ".radialaxis.range[" + rngIndex + "]", rprime);
          }
        }
        function rotateMove(dx, dy) {
          if (rngIndex === 0) return;
          var x1 = tx + dx;
          var y1 = ty + dy;
          angle1 = Math.atan2(cy - y1, x1 - cx);
          if (_this.vangles) angle1 = snapToVertexAngle(angle1, _this.vangles);
          angle1 = rad2deg(angle1);
          var transform = strTranslate(cx, cy) + strRotate(-angle1);
          layers["radial-axis"].attr("transform", transform);
          layers["radial-line"].select("line").attr("transform", transform);
          var fullLayoutNow = _this.gd._fullLayout;
          var polarLayoutNow = fullLayoutNow[_this.id];
          _this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, angle1);
        }
        function rerangeMove(dx, dy) {
          var dr = Lib.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]);
          rprime = rbase - m * dr;
          if (m > 0 !== (rngIndex ? rprime > rl0 : rprime < rl1)) {
            rprime = null;
            return;
          }
          var fullLayoutNow = gd._fullLayout;
          var polarLayoutNow = fullLayoutNow[_this.id];
          radialAxis.range[rngIndex] = rprime;
          radialAxis._rl[rngIndex] = rprime;
          _this.updateRadialAxis(fullLayoutNow, polarLayoutNow);
          _this.xaxis.setRange();
          _this.xaxis.setScale();
          _this.yaxis.setRange();
          _this.yaxis.setScale();
          var hasRegl = false;
          for (var traceType in _this.traceHash) {
            var moduleCalcData = _this.traceHash[traceType];
            var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
            var _module = moduleCalcData[0][0].trace._module;
            _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
            if (Registry.traceIs(traceType, "gl") && moduleCalcDataVisible.length) hasRegl = true;
          }
          if (hasRegl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
          }
        }
        dragOpts.prepFn = function() {
          moveFn2 = null;
          angle1 = null;
          rprime = null;
          dragOpts.moveFn = moveFn;
          dragOpts.doneFn = doneFn;
          clearOutline(gd);
        };
        dragOpts.clampFn = function(dx, dy) {
          if (Math.sqrt(dx * dx + dy * dy) < constants.MINDRAG) {
            dx = 0;
            dy = 0;
          }
          return [dx, dy];
        };
        dragElement.init(dragOpts);
      };
      proto.updateAngularDrag = function(fullLayout) {
        var _this = this;
        var gd = _this.gd;
        var layers = _this.layers;
        var radius = _this.radius;
        var angularAxis = _this.angularAxis;
        var cx = _this.cx;
        var cy = _this.cy;
        var cxx = _this.cxx;
        var cyy = _this.cyy;
        var dbs = constants.angularDragBoxSize;
        var angularDrag = dragBox.makeDragger(layers, "path", "angulardrag", fullLayout.dragmode === false ? "none" : "move");
        var dragOpts = { element: angularDrag, gd };
        if (fullLayout.dragmode === false) {
          dragOpts.dragmode = false;
        } else {
          d3.select(angularDrag).attr("d", _this.pathAnnulus(radius, radius + dbs)).attr("transform", strTranslate(cx, cy)).call(setCursor, "move");
        }
        function xy2a(x, y) {
          return Math.atan2(cyy + dbs - y, x - cxx - dbs);
        }
        var scatterTraces = layers.frontplot.select(".scatterlayer").selectAll(".trace");
        var scatterPoints = scatterTraces.selectAll(".point");
        var scatterTextPoints = scatterTraces.selectAll(".textpoint");
        var x0, y0;
        var rot0, rot1;
        var rrot1;
        var a0;
        function moveFn(dx, dy) {
          var fullLayoutNow = _this.gd._fullLayout;
          var polarLayoutNow = fullLayoutNow[_this.id];
          var x1 = x0 + dx * fullLayout._invScaleX;
          var y1 = y0 + dy * fullLayout._invScaleY;
          var a1 = xy2a(x1, y1);
          var da = rad2deg(a1 - a0);
          rot1 = rot0 + da;
          layers.frontplot.attr(
            "transform",
            strTranslate(_this.xOffset2, _this.yOffset2) + strRotate([-da, cxx, cyy])
          );
          if (_this.vangles) {
            rrot1 = _this.radialAxisAngle + da;
            var trans = strTranslate(cx, cy) + strRotate(-da);
            var trans2 = strTranslate(cx, cy) + strRotate(-rrot1);
            layers.bg.attr("transform", trans);
            layers["radial-grid"].attr("transform", trans);
            layers["radial-axis"].attr("transform", trans2);
            layers["radial-line"].select("line").attr("transform", trans2);
            _this.updateRadialAxisTitle(fullLayoutNow, polarLayoutNow, rrot1);
          } else {
            _this.clipPaths.forTraces.select("path").attr(
              "transform",
              strTranslate(cxx, cyy) + strRotate(da)
            );
          }
          scatterPoints.each(function() {
            var sel = d3.select(this);
            var xy = Drawing.getTranslate(sel);
            sel.attr("transform", strTranslate(xy.x, xy.y) + strRotate([da]));
          });
          scatterTextPoints.each(function() {
            var sel = d3.select(this);
            var tx = sel.select("text");
            var xy = Drawing.getTranslate(sel);
            sel.attr("transform", strRotate([da, tx.attr("x"), tx.attr("y")]) + strTranslate(xy.x, xy.y));
          });
          angularAxis.rotation = Lib.modHalf(rot1, 360);
          _this.updateAngularAxis(fullLayoutNow, polarLayoutNow);
          if (_this._hasClipOnAxisFalse && !Lib.isFullCircle(_this.sectorInRad)) {
            scatterTraces.call(Drawing.hideOutsideRangePoints, _this);
          }
          var hasRegl = false;
          for (var traceType in _this.traceHash) {
            if (Registry.traceIs(traceType, "gl")) {
              var moduleCalcData = _this.traceHash[traceType];
              var moduleCalcDataVisible = Lib.filterVisible(moduleCalcData);
              var _module = moduleCalcData[0][0].trace._module;
              _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow);
              if (moduleCalcDataVisible.length) hasRegl = true;
            }
          }
          if (hasRegl) {
            clearGlCanvases(gd);
            redrawReglTraces(gd);
          }
          var update = {};
          computeRotationUpdates(update);
          gd.emit("plotly_relayouting", update);
        }
        function computeRotationUpdates(updateObj) {
          updateObj[_this.id + ".angularaxis.rotation"] = rot1;
          if (_this.vangles) {
            updateObj[_this.id + ".radialaxis.angle"] = rrot1;
          }
        }
        function doneFn() {
          scatterTextPoints.select("text").attr("transform", null);
          var updateObj = {};
          computeRotationUpdates(updateObj);
          Registry.call("_guiRelayout", gd, updateObj);
        }
        dragOpts.prepFn = function(evt, startX, startY) {
          var polarLayoutNow = fullLayout[_this.id];
          rot0 = polarLayoutNow.angularaxis.rotation;
          var bbox = angularDrag.getBoundingClientRect();
          x0 = startX - bbox.left;
          y0 = startY - bbox.top;
          gd._fullLayout._calcInverseTransform(gd);
          var transformedCoords = Lib.apply3DTransform(fullLayout._invTransform)(x0, y0);
          x0 = transformedCoords[0];
          y0 = transformedCoords[1];
          a0 = xy2a(x0, y0);
          dragOpts.moveFn = moveFn;
          dragOpts.doneFn = doneFn;
          clearOutline(gd);
        };
        if (_this.vangles && !Lib.isFullCircle(_this.sectorInRad)) {
          dragOpts.prepFn = Lib.noop;
          setCursor(d3.select(angularDrag), null);
        }
        dragElement.init(dragOpts);
      };
      proto.isPtInside = function(d) {
        if (this.isSmith) return true;
        var sectorInRad = this.sectorInRad;
        var vangles = this.vangles;
        var thetag = this.angularAxis.c2g(d.theta);
        var radialAxis = this.radialAxis;
        var r = radialAxis.c2l(d.r);
        var rl = radialAxis._rl;
        var fn = vangles ? helpers.isPtInsidePolygon : Lib.isPtInsideSector;
        return fn(r, thetag, rl, sectorInRad, vangles);
      };
      proto.pathArc = function(r) {
        var sectorInRad = this.sectorInRad;
        var vangles = this.vangles;
        var fn = vangles ? helpers.pathPolygon : Lib.pathArc;
        return fn(r, sectorInRad[0], sectorInRad[1], vangles);
      };
      proto.pathSector = function(r) {
        var sectorInRad = this.sectorInRad;
        var vangles = this.vangles;
        var fn = vangles ? helpers.pathPolygon : Lib.pathSector;
        return fn(r, sectorInRad[0], sectorInRad[1], vangles);
      };
      proto.pathAnnulus = function(r0, r1) {
        var sectorInRad = this.sectorInRad;
        var vangles = this.vangles;
        var fn = vangles ? helpers.pathPolygonAnnulus : Lib.pathAnnulus;
        return fn(r0, r1, sectorInRad[0], sectorInRad[1], vangles);
      };
      proto.pathSubplot = function() {
        var r0 = this.innerRadius;
        var r1 = this.radius;
        return r0 ? this.pathAnnulus(r0, r1) : this.pathSector(r1);
      };
      proto.fillViewInitialKey = function(key, val) {
        if (!(key in this.viewInitial)) {
          this.viewInitial[key] = val;
        }
      };
      function strTickLayout(axLayout) {
        var out = axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
        if ("side" in axLayout) out += axLayout.side;
        return out;
      }
      function computeSectorBBox(sector) {
        var s0 = sector[0];
        var s1 = sector[1];
        var arc = s1 - s0;
        var a0 = mod(s0, 360);
        var a1 = a0 + arc;
        var ax0 = Math.cos(deg2rad(a0));
        var ay0 = Math.sin(deg2rad(a0));
        var ax1 = Math.cos(deg2rad(a1));
        var ay1 = Math.sin(deg2rad(a1));
        var x0, y0, x1, y1;
        if (a0 <= 90 && a1 >= 90 || a0 > 90 && a1 >= 450) {
          y1 = 1;
        } else if (ay0 <= 0 && ay1 <= 0) {
          y1 = 0;
        } else {
          y1 = Math.max(ay0, ay1);
        }
        if (a0 <= 180 && a1 >= 180 || a0 > 180 && a1 >= 540) {
          x0 = -1;
        } else if (ax0 >= 0 && ax1 >= 0) {
          x0 = 0;
        } else {
          x0 = Math.min(ax0, ax1);
        }
        if (a0 <= 270 && a1 >= 270 || a0 > 270 && a1 >= 630) {
          y0 = -1;
        } else if (ay0 >= 0 && ay1 >= 0) {
          y0 = 0;
        } else {
          y0 = Math.min(ay0, ay1);
        }
        if (a1 >= 360) {
          x1 = 1;
        } else if (ax0 <= 0 && ax1 <= 0) {
          x1 = 0;
        } else {
          x1 = Math.max(ax0, ax1);
        }
        return [x0, y0, x1, y1];
      }
      function snapToVertexAngle(a, vangles) {
        var fn = function(v) {
          return Lib.angleDist(a, v);
        };
        var ind = Lib.findIndexOfMin(vangles, fn);
        return vangles[ind];
      }
      function updateElement(sel, showAttr, attrs) {
        if (showAttr) {
          sel.attr("display", null);
          sel.attr(attrs);
        } else if (sel) {
          sel.attr("display", "none");
        }
        return sel;
      }
    }
  });

  // src/plots/polar/layout_attributes.js
  var require_layout_attributes21 = __commonJS({
    "src/plots/polar/layout_attributes.js"(exports, module) {
      "use strict";
      var colorAttrs = require_attributes3();
      var axesAttrs = require_layout_attributes4();
      var domainAttrs = require_domain().attributes;
      var extendFlat = require_lib().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var axisLineGridAttr = overrideAll({
        color: axesAttrs.color,
        showline: extendFlat({}, axesAttrs.showline, { dflt: true }),
        linecolor: axesAttrs.linecolor,
        linewidth: axesAttrs.linewidth,
        showgrid: extendFlat({}, axesAttrs.showgrid, { dflt: true }),
        gridcolor: axesAttrs.gridcolor,
        gridwidth: axesAttrs.gridwidth,
        griddash: axesAttrs.griddash
        // TODO add spike* attributes down the road
        // should we add zeroline* attributes?
      }, "plot", "from-root");
      var axisTickAttrs = overrideAll({
        tickmode: axesAttrs.minor.tickmode,
        nticks: axesAttrs.nticks,
        tick0: axesAttrs.tick0,
        dtick: axesAttrs.dtick,
        tickvals: axesAttrs.tickvals,
        ticktext: axesAttrs.ticktext,
        ticks: axesAttrs.ticks,
        ticklen: axesAttrs.ticklen,
        tickwidth: axesAttrs.tickwidth,
        tickcolor: axesAttrs.tickcolor,
        ticklabelstep: axesAttrs.ticklabelstep,
        showticklabels: axesAttrs.showticklabels,
        labelalias: axesAttrs.labelalias,
        minorloglabels: axesAttrs.minorloglabels,
        showtickprefix: axesAttrs.showtickprefix,
        tickprefix: axesAttrs.tickprefix,
        showticksuffix: axesAttrs.showticksuffix,
        ticksuffix: axesAttrs.ticksuffix,
        showexponent: axesAttrs.showexponent,
        exponentformat: axesAttrs.exponentformat,
        minexponent: axesAttrs.minexponent,
        separatethousands: axesAttrs.separatethousands,
        tickfont: axesAttrs.tickfont,
        tickangle: axesAttrs.tickangle,
        tickformat: axesAttrs.tickformat,
        tickformatstops: axesAttrs.tickformatstops,
        layer: axesAttrs.layer
      }, "plot", "from-root");
      var radialAxisAttrs = {
        visible: extendFlat({}, axesAttrs.visible, { dflt: true }),
        type: extendFlat({}, axesAttrs.type, {
          values: ["-", "linear", "log", "date", "category"]
        }),
        autotypenumbers: axesAttrs.autotypenumbers,
        autorangeoptions: {
          minallowed: axesAttrs.autorangeoptions.minallowed,
          maxallowed: axesAttrs.autorangeoptions.maxallowed,
          clipmin: axesAttrs.autorangeoptions.clipmin,
          clipmax: axesAttrs.autorangeoptions.clipmax,
          include: axesAttrs.autorangeoptions.include,
          editType: "plot"
        },
        autorange: extendFlat({}, axesAttrs.autorange, { editType: "plot" }),
        rangemode: {
          valType: "enumerated",
          values: ["tozero", "nonnegative", "normal"],
          dflt: "tozero",
          editType: "calc"
        },
        minallowed: extendFlat({}, axesAttrs.minallowed, { editType: "plot" }),
        maxallowed: extendFlat({}, axesAttrs.maxallowed, { editType: "plot" }),
        range: extendFlat({}, axesAttrs.range, {
          items: [
            { valType: "any", editType: "plot", impliedEdits: { "^autorange": false } },
            { valType: "any", editType: "plot", impliedEdits: { "^autorange": false } }
          ],
          editType: "plot"
        }),
        categoryorder: axesAttrs.categoryorder,
        categoryarray: axesAttrs.categoryarray,
        angle: {
          valType: "angle",
          editType: "plot"
        },
        autotickangles: axesAttrs.autotickangles,
        side: {
          valType: "enumerated",
          // TODO add 'center' for `showline: false` radial axes
          values: ["clockwise", "counterclockwise"],
          dflt: "clockwise",
          editType: "plot"
        },
        title: {
          // radial title is not gui-editable at the moment,
          // so it needs dflt: '', similar to carpet axes.
          text: extendFlat({}, axesAttrs.title.text, { editType: "plot", dflt: "" }),
          font: extendFlat({}, axesAttrs.title.font, { editType: "plot" }),
          // TODO
          // - might need a 'titleside' and even 'titledirection' down the road
          // - what about standoff ??
          editType: "plot"
        },
        hoverformat: axesAttrs.hoverformat,
        uirevision: {
          valType: "any",
          editType: "none"
        },
        editType: "calc"
      };
      extendFlat(
        radialAxisAttrs,
        // N.B. radialaxis grid lines are circular,
        // but radialaxis lines are straight from circle center to outer bound
        axisLineGridAttr,
        axisTickAttrs
      );
      var angularAxisAttrs = {
        visible: extendFlat({}, axesAttrs.visible, { dflt: true }),
        type: {
          valType: "enumerated",
          // 'linear' should maybe be called 'angle' or 'angular' here
          // to make clear that axis here is periodic and more tightly match
          // `thetaunit`?
          //
          // skip 'date' for first push
          // no 'log' for now
          values: ["-", "linear", "category"],
          dflt: "-",
          editType: "calc",
          _noTemplating: true
        },
        autotypenumbers: axesAttrs.autotypenumbers,
        categoryorder: axesAttrs.categoryorder,
        categoryarray: axesAttrs.categoryarray,
        thetaunit: {
          valType: "enumerated",
          values: ["radians", "degrees"],
          dflt: "degrees",
          editType: "calc"
        },
        period: {
          valType: "number",
          editType: "calc",
          min: 0
          // Examples for date axes:
          //
          // - period that equals the timeseries length
          //  http://flowingdata.com/2017/01/24/one-dataset-visualized-25-ways/18-polar-coordinates/
          // - and 1-year periods (focusing on seasonal change0
          //  http://otexts.org/fpp2/seasonal-plots.html
          //  https://blogs.scientificamerican.com/sa-visual/why-are-so-many-babies-born-around-8-00-a-m/
          //  http://www.seasonaladjustment.com/2012/09/05/clock-plot-visualising-seasonality-using-r-and-ggplot2-part-3/
          //  https://i.pinimg.com/736x/49/b9/72/49b972ccb3206a1a6d6f870dac543280.jpg
          //  https://www.climate-lab-book.ac.uk/spirals/
        },
        direction: {
          valType: "enumerated",
          values: ["counterclockwise", "clockwise"],
          dflt: "counterclockwise",
          editType: "calc"
        },
        rotation: {
          valType: "angle",
          editType: "calc"
        },
        hoverformat: axesAttrs.hoverformat,
        uirevision: {
          valType: "any",
          editType: "none"
        },
        editType: "calc"
      };
      extendFlat(
        angularAxisAttrs,
        // N.B. angular grid lines are straight lines from circle center to outer bound
        // the angular line is circular bounding the polar plot area.
        axisLineGridAttr,
        // N.B. ticksuffix defaults to '°' for angular axes with `thetaunit: 'degrees'`
        axisTickAttrs
      );
      module.exports = {
        // TODO for x/y/zoom system for paper-based zooming:
        // x: {},
        // y: {},
        // zoom: {},
        domain: domainAttrs({ name: "polar", editType: "plot" }),
        sector: {
          valType: "info_array",
          items: [
            { valType: "number", editType: "plot" },
            { valType: "number", editType: "plot" }
          ],
          dflt: [0, 360],
          editType: "plot"
        },
        hole: {
          valType: "number",
          min: 0,
          max: 1,
          dflt: 0,
          editType: "plot"
        },
        bgcolor: {
          valType: "color",
          editType: "plot",
          dflt: colorAttrs.background
        },
        radialaxis: radialAxisAttrs,
        angularaxis: angularAxisAttrs,
        gridshape: {
          valType: "enumerated",
          values: ["circular", "linear"],
          dflt: "circular",
          editType: "plot"
        },
        // TODO maybe?
        // annotations:
        uirevision: {
          valType: "any",
          editType: "none"
        },
        editType: "calc"
      };
    }
  });

  // src/plots/polar/layout_defaults.js
  var require_layout_defaults19 = __commonJS({
    "src/plots/polar/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var Template = require_plot_template();
      var handleSubplotDefaults = require_subplot_defaults();
      var getSubplotData = require_get_data().getSubplotData;
      var handleTickValueDefaults = require_tick_value_defaults();
      var handleTickMarkDefaults = require_tick_mark_defaults();
      var handleTickLabelDefaults = require_tick_label_defaults();
      var handlePrefixSuffixDefaults = require_prefix_suffix_defaults();
      var handleCategoryOrderDefaults = require_category_order_defaults();
      var handleLineGridDefaults = require_line_grid_defaults();
      var handleAutorangeOptionsDefaults = require_autorange_options_defaults();
      var autoType = require_axis_autotype();
      var layoutAttributes = require_layout_attributes21();
      var setConvert = require_set_convert3();
      var constants = require_constants33();
      var axisNames = constants.axisNames;
      function handleDefaults(contIn, contOut, coerce, opts) {
        var bgColor = coerce("bgcolor");
        opts.bgColor = Color2.combine(bgColor, opts.paper_bgcolor);
        var sector = coerce("sector");
        coerce("hole");
        var subplotData = getSubplotData(opts.fullData, constants.name, opts.id);
        var layoutOut = opts.layoutOut;
        var axName;
        function coerceAxis(attr, dflt) {
          return coerce(axName + "." + attr, dflt);
        }
        for (var i = 0; i < axisNames.length; i++) {
          axName = axisNames[i];
          if (!Lib.isPlainObject(contIn[axName])) {
            contIn[axName] = {};
          }
          var axIn = contIn[axName];
          var axOut = Template.newContainer(contOut, axName);
          axOut._id = axOut._name = axName;
          axOut._attr = opts.id + "." + axName;
          axOut._traceIndices = subplotData.map(function(t) {
            return t.index;
          });
          var dataAttr = constants.axisName2dataArray[axName];
          var axType = handleAxisTypeDefaults(axIn, axOut, coerceAxis, subplotData, dataAttr, opts);
          handleCategoryOrderDefaults(axIn, axOut, coerceAxis, {
            axData: subplotData,
            dataAttr
          });
          var visible = coerceAxis("visible");
          setConvert(axOut, contOut, layoutOut);
          coerceAxis("uirevision", contOut.uirevision);
          axOut._m = 1;
          switch (axName) {
            case "radialaxis":
              coerceAxis("minallowed");
              coerceAxis("maxallowed");
              var range = coerceAxis("range");
              var autorangeDflt = axOut.getAutorangeDflt(range);
              var autorange = coerceAxis("autorange", autorangeDflt);
              var shouldAutorange;
              if (range && (range[0] === null && range[1] === null || (range[0] === null || range[1] === null) && (autorange === "reversed" || autorange === true) || range[0] !== null && (autorange === "min" || autorange === "max reversed") || range[1] !== null && (autorange === "max" || autorange === "min reversed"))) {
                range = void 0;
                delete axOut.range;
                axOut.autorange = true;
                shouldAutorange = true;
              }
              if (!shouldAutorange) {
                autorangeDflt = axOut.getAutorangeDflt(range);
                autorange = coerceAxis("autorange", autorangeDflt);
              }
              axIn.autorange = autorange;
              if (autorange) {
                handleAutorangeOptionsDefaults(coerceAxis, autorange, range);
                if (axType === "linear" || axType === "-") coerceAxis("rangemode");
                if (axOut.isReversed()) axOut._m = -1;
              }
              axOut.cleanRange("range", { dfltRange: [0, 1] });
              break;
            case "angularaxis":
              if (axType === "date") {
                Lib.log("Polar plots do not support date angular axes yet.");
                for (var j = 0; j < subplotData.length; j++) {
                  subplotData[j].visible = false;
                }
                axType = axIn.type = axOut.type = "linear";
              }
              if (axType === "linear") {
                coerceAxis("thetaunit");
              } else {
                coerceAxis("period");
              }
              var direction = coerceAxis("direction");
              coerceAxis("rotation", { counterclockwise: 0, clockwise: 90 }[direction]);
              break;
          }
          handlePrefixSuffixDefaults(axIn, axOut, coerceAxis, axOut.type, {
            tickSuffixDflt: axOut.thetaunit === "degrees" ? "\xB0" : void 0
          });
          if (visible) {
            var dfltColor;
            var dfltFontColor;
            var dfltFontSize;
            var dfltFontFamily;
            var dfltFontWeight;
            var dfltFontStyle;
            var dfltFontVariant;
            var dfltFontTextcase;
            var dfltFontLineposition;
            var dfltFontShadow;
            var font = opts.font || {};
            dfltColor = coerceAxis("color");
            dfltFontColor = dfltColor === axIn.color ? dfltColor : font.color;
            dfltFontSize = font.size;
            dfltFontFamily = font.family;
            dfltFontWeight = font.weight;
            dfltFontStyle = font.style;
            dfltFontVariant = font.variant;
            dfltFontTextcase = font.textcase;
            dfltFontLineposition = font.lineposition;
            dfltFontShadow = font.shadow;
            handleTickValueDefaults(axIn, axOut, coerceAxis, axOut.type);
            handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, {
              font: {
                weight: dfltFontWeight,
                style: dfltFontStyle,
                variant: dfltFontVariant,
                textcase: dfltFontTextcase,
                lineposition: dfltFontLineposition,
                shadow: dfltFontShadow,
                color: dfltFontColor,
                size: dfltFontSize,
                family: dfltFontFamily
              },
              noAutotickangles: axName === "angularaxis",
              noTicklabelshift: true,
              noTicklabelstandoff: true
            });
            handleTickMarkDefaults(axIn, axOut, coerceAxis, { outerTicks: true });
            handleLineGridDefaults(axIn, axOut, coerceAxis, {
              dfltColor,
              bgColor: opts.bgColor,
              // default grid color is darker here (60%, vs cartesian default ~91%)
              // because the grid is not square so the eye needs heavier cues to follow
              blend: 60,
              showLine: true,
              showGrid: true,
              noZeroLine: true,
              attributes: layoutAttributes[axName]
            });
            coerceAxis("layer");
            if (axName === "radialaxis") {
              coerceAxis("side");
              coerceAxis("angle", sector[0]);
              coerceAxis("title.text");
              Lib.coerceFont(coerceAxis, "title.font", {
                weight: dfltFontWeight,
                style: dfltFontStyle,
                variant: dfltFontVariant,
                textcase: dfltFontTextcase,
                lineposition: dfltFontLineposition,
                shadow: dfltFontShadow,
                color: dfltFontColor,
                size: Lib.bigFont(dfltFontSize),
                family: dfltFontFamily
              });
            }
          }
          if (axType !== "category") coerceAxis("hoverformat");
          axOut._input = axIn;
        }
        if (contOut.angularaxis.type === "category") {
          coerce("gridshape");
        }
      }
      function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr, options) {
        var autotypenumbers = coerce("autotypenumbers", options.autotypenumbersDflt);
        var axType = coerce("type");
        if (axType === "-") {
          var trace;
          for (var i = 0; i < subplotData.length; i++) {
            if (subplotData[i].visible) {
              trace = subplotData[i];
              break;
            }
          }
          if (trace && trace[dataAttr]) {
            axOut.type = autoType(trace[dataAttr], "gregorian", {
              noMultiCategory: true,
              autotypenumbers
            });
          }
          if (axOut.type === "-") {
            axOut.type = "linear";
          } else {
            axIn.type = axOut.type;
          }
        }
        return axOut.type;
      }
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        handleSubplotDefaults(layoutIn, layoutOut, fullData, {
          type: constants.name,
          attributes: layoutAttributes,
          handleDefaults,
          font: layoutOut.font,
          autotypenumbersDflt: layoutOut.autotypenumbers,
          paper_bgcolor: layoutOut.paper_bgcolor,
          fullData,
          layoutOut
        });
      };
    }
  });

  // src/plots/polar/index.js
  var require_polar2 = __commonJS({
    "src/plots/polar/index.js"(exports, module) {
      "use strict";
      var getSubplotCalcData = require_get_data().getSubplotCalcData;
      var counterRegex = require_lib().counterRegex;
      var createPolar = require_polar();
      var constants = require_constants33();
      var attr = constants.attr;
      var name2 = constants.name;
      var counter = counterRegex(name2);
      var attributes = {};
      attributes[attr] = {
        valType: "subplotid",
        dflt: name2,
        editType: "calc"
      };
      function plot(gd) {
        var fullLayout = gd._fullLayout;
        var calcData = gd.calcdata;
        var subplotIds = fullLayout._subplots[name2];
        for (var i = 0; i < subplotIds.length; i++) {
          var id = subplotIds[i];
          var subplotCalcData = getSubplotCalcData(calcData, name2, id);
          var subplot = fullLayout[id]._subplot;
          if (!subplot) {
            subplot = createPolar(gd, id);
            fullLayout[id]._subplot = subplot;
          }
          subplot.plot(subplotCalcData, fullLayout, gd._promises);
        }
      }
      function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldIds = oldFullLayout._subplots[name2] || [];
        var hadGl = oldFullLayout._has && oldFullLayout._has("gl");
        var hasGl = newFullLayout._has && newFullLayout._has("gl");
        var mustCleanScene = hadGl && !hasGl;
        for (var i = 0; i < oldIds.length; i++) {
          var id = oldIds[i];
          var oldSubplot = oldFullLayout[id]._subplot;
          if (!newFullLayout[id] && !!oldSubplot) {
            oldSubplot.framework.remove();
            oldSubplot.layers["radial-axis-title"].remove();
            for (var k in oldSubplot.clipPaths) {
              oldSubplot.clipPaths[k].remove();
            }
          }
          if (mustCleanScene && oldSubplot._scene) {
            oldSubplot._scene.destroy();
            oldSubplot._scene = null;
          }
        }
      }
      module.exports = {
        attr,
        name: name2,
        idRoot: name2,
        idRegex: counter,
        attrRegex: counter,
        attributes,
        layoutAttributes: require_layout_attributes21(),
        supplyLayoutDefaults: require_layout_defaults19(),
        plot,
        clean,
        toSVG: require_cartesian().toSVG
      };
    }
  });

  // src/traces/scatterpolar/attributes.js
  var require_attributes68 = __commonJS({
    "src/traces/scatterpolar/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var extendFlat = require_extend().extendFlat;
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterAttrs = require_attributes12();
      var baseAttrs = require_attributes2();
      var lineAttrs = scatterAttrs.line;
      module.exports = {
        mode: scatterAttrs.mode,
        r: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        theta: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        r0: {
          valType: "any",
          dflt: 0,
          editType: "calc+clearAxisTypes"
        },
        dr: {
          valType: "number",
          dflt: 1,
          editType: "calc"
        },
        theta0: {
          valType: "any",
          dflt: 0,
          editType: "calc+clearAxisTypes"
        },
        dtheta: {
          valType: "number",
          editType: "calc"
        },
        thetaunit: {
          valType: "enumerated",
          values: ["radians", "degrees", "gradians"],
          dflt: "degrees",
          editType: "calc+clearAxisTypes"
        },
        text: scatterAttrs.text,
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["r", "theta", "text"] }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: scatterAttrs.hovertext,
        line: {
          color: lineAttrs.color,
          width: lineAttrs.width,
          dash: lineAttrs.dash,
          backoff: lineAttrs.backoff,
          shape: extendFlat({}, lineAttrs.shape, {
            values: ["linear", "spline"]
          }),
          smoothing: lineAttrs.smoothing,
          editType: "calc"
        },
        connectgaps: scatterAttrs.connectgaps,
        marker: scatterAttrs.marker,
        cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, { dflt: false }),
        textposition: scatterAttrs.textposition,
        textfont: scatterAttrs.textfont,
        fill: extendFlat({}, scatterAttrs.fill, {
          values: ["none", "toself", "tonext"],
          dflt: "none"
        }),
        fillcolor: makeFillcolorAttr(),
        // TODO error bars
        // https://stackoverflow.com/a/26597487/4068492
        // error_x (error_r, error_theta)
        // error_y
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["r", "theta", "text", "name"]
        }),
        hoveron: scatterAttrs.hoveron,
        hovertemplate: hovertemplateAttrs(),
        hovertemplatefallback: templatefallbackAttrs(),
        selected: scatterAttrs.selected,
        unselected: scatterAttrs.unselected
      };
    }
  });

  // src/traces/scatterpolar/defaults.js
  var require_defaults64 = __commonJS({
    "src/traces/scatterpolar/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleLineShapeDefaults = require_line_shape_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var PTS_LINESONLY = require_constants8().PTS_LINESONLY;
      var attributes = require_attributes68();
      function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        coerce("thetaunit");
        coerce("mode", len < PTS_LINESONLY ? "lines+markers" : "lines");
        coerce("text");
        coerce("hovertext");
        if (traceOut.hoveron !== "fills") {
          coerce("hovertemplate");
          coerce("hovertemplatefallback");
        }
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { gradient: true });
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, { backoff: true });
          handleLineShapeDefaults(traceIn, traceOut, coerce);
          coerce("connectgaps");
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce);
        }
        var dfltHoverOn = [];
        if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
          coerce("cliponaxis");
          coerce("marker.maxdisplayed");
          dfltHoverOn.push("points");
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
          if (!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
        }
        if (traceOut.fill === "tonext" || traceOut.fill === "toself") {
          dfltHoverOn.push("fills");
        }
        coerce("hoveron", dfltHoverOn.join("+") || "points");
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      }
      function handleRThetaDefaults(traceIn, traceOut, layout, coerce) {
        var r = coerce("r");
        var theta = coerce("theta");
        if (Lib.isTypedArray(r)) {
          traceOut.r = r = Array.from(r);
        }
        if (Lib.isTypedArray(theta)) {
          traceOut.theta = theta = Array.from(theta);
        }
        var len;
        if (r) {
          if (theta) {
            len = Math.min(r.length, theta.length);
          } else {
            len = r.length;
            coerce("theta0");
            coerce("dtheta");
          }
        } else {
          if (!theta) return 0;
          len = traceOut.theta.length;
          coerce("r0");
          coerce("dr");
        }
        traceOut._length = len;
        return len;
      }
      module.exports = {
        handleRThetaDefaults,
        supplyDefaults
      };
    }
  });

  // src/traces/scatterpolar/format_labels.js
  var require_format_labels8 = __commonJS({
    "src/traces/scatterpolar/format_labels.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Axes = require_axes();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var labels = {};
        var subplot = fullLayout[trace.subplot]._subplot;
        var radialAxis;
        var angularAxis;
        if (!subplot) {
          subplot = fullLayout[trace.subplot];
          radialAxis = subplot.radialaxis;
          angularAxis = subplot.angularaxis;
        } else {
          radialAxis = subplot.radialAxis;
          angularAxis = subplot.angularAxis;
        }
        var rVal = radialAxis.c2l(cdi.r);
        labels.rLabel = Axes.tickText(radialAxis, rVal, true).text;
        var thetaVal = angularAxis.thetaunit === "degrees" ? Lib.rad2deg(cdi.theta) : cdi.theta;
        labels.thetaLabel = Axes.tickText(angularAxis, thetaVal, true).text;
        return labels;
      };
    }
  });

  // src/traces/scatterpolar/calc.js
  var require_calc43 = __commonJS({
    "src/traces/scatterpolar/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var BADNUM = require_numerical().BADNUM;
      var Axes = require_axes();
      var calcColorscale = require_colorscale_calc();
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcSelection = require_calc_selection();
      var calcMarkerSize = require_calc3().calcMarkerSize;
      module.exports = function calc(gd, trace) {
        var fullLayout = gd._fullLayout;
        var subplotId = trace.subplot;
        var radialAxis = fullLayout[subplotId].radialaxis;
        var angularAxis = fullLayout[subplotId].angularaxis;
        var rArray = radialAxis.makeCalcdata(trace, "r");
        var thetaArray = angularAxis.makeCalcdata(trace, "theta");
        var len = trace._length;
        var cd = new Array(len);
        for (var i = 0; i < len; i++) {
          var r = rArray[i];
          var theta = thetaArray[i];
          var cdi = cd[i] = {};
          if (isNumeric(r) && isNumeric(theta)) {
            cdi.r = r;
            cdi.theta = theta;
          } else {
            cdi.r = BADNUM;
          }
        }
        var ppad = calcMarkerSize(trace, len);
        trace._extremes.x = Axes.findExtremes(radialAxis, rArray, { ppad });
        calcColorscale(gd, trace);
        arraysToCalcdata(cd, trace);
        calcSelection(cd, trace);
        return cd;
      };
    }
  });

  // src/traces/scatterpolar/plot.js
  var require_plot36 = __commonJS({
    "src/traces/scatterpolar/plot.js"(exports, module) {
      "use strict";
      var scatterPlot = require_plot();
      var BADNUM = require_numerical().BADNUM;
      module.exports = function plot(gd, subplot, moduleCalcData) {
        var mlayer = subplot.layers.frontplot.select("g.scatterlayer");
        var xa = subplot.xaxis;
        var ya = subplot.yaxis;
        var plotinfo = {
          xaxis: xa,
          yaxis: ya,
          plot: subplot.framework,
          layerClipId: subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null
        };
        var radialAxis = subplot.radialAxis;
        var angularAxis = subplot.angularAxis;
        for (var i = 0; i < moduleCalcData.length; i++) {
          var cdi = moduleCalcData[i];
          for (var j = 0; j < cdi.length; j++) {
            if (j === 0) {
              cdi[0].trace._xA = xa;
              cdi[0].trace._yA = ya;
            }
            var cd = cdi[j];
            var r = cd.r;
            if (r === BADNUM) {
              cd.x = cd.y = BADNUM;
            } else {
              var rg = radialAxis.c2g(r);
              var thetag = angularAxis.c2g(cd.theta);
              cd.x = rg * Math.cos(thetag);
              cd.y = rg * Math.sin(thetag);
            }
          }
        }
        scatterPlot(gd, plotinfo, moduleCalcData, mlayer);
      };
    }
  });

  // src/traces/scatterpolar/hover.js
  var require_hover24 = __commonJS({
    "src/traces/scatterpolar/hover.js"(exports, module) {
      "use strict";
      var scatterHover = require_hover2();
      function hoverPoints(pointData, xval, yval, hovermode) {
        var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
        if (!scatterPointData || scatterPointData[0].index === false) return;
        var newPointData = scatterPointData[0];
        if (newPointData.index === void 0) {
          return scatterPointData;
        }
        var subplot = pointData.subplot;
        var cdi = newPointData.cd[newPointData.index];
        var trace = newPointData.trace;
        if (!subplot.isPtInside(cdi)) return;
        newPointData.xLabelVal = void 0;
        newPointData.yLabelVal = void 0;
        makeHoverPointText(cdi, trace, subplot, newPointData);
        newPointData.hovertemplate = trace.hovertemplate;
        return scatterPointData;
      }
      function makeHoverPointText(cdi, trace, subplot, pointData) {
        var radialAxis = subplot.radialAxis;
        var angularAxis = subplot.angularAxis;
        radialAxis._hovertitle = "r";
        angularAxis._hovertitle = "\u03B8";
        var fullLayout = {};
        fullLayout[trace.subplot] = { _subplot: subplot };
        var labels = trace._module.formatLabels(cdi, trace, fullLayout);
        pointData.rLabel = labels.rLabel;
        pointData.thetaLabel = labels.thetaLabel;
        var hoverinfo = cdi.hi || trace.hoverinfo;
        var text = [];
        function textPart(ax, val) {
          text.push(ax._hovertitle + ": " + val);
        }
        if (!trace.hovertemplate) {
          var parts = hoverinfo.split("+");
          if (parts.indexOf("all") !== -1) parts = ["r", "theta", "text"];
          if (parts.indexOf("r") !== -1) textPart(radialAxis, pointData.rLabel);
          if (parts.indexOf("theta") !== -1) textPart(angularAxis, pointData.thetaLabel);
          if (parts.indexOf("text") !== -1 && pointData.text) {
            text.push(pointData.text);
            delete pointData.text;
          }
          pointData.extraText = text.join("<br>");
        }
      }
      module.exports = {
        hoverPoints,
        makeHoverPointText
      };
    }
  });

  // src/traces/scatterpolar/index.js
  var require_scatterpolar = __commonJS({
    "src/traces/scatterpolar/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "scatterpolar",
        basePlotModule: require_polar2(),
        categories: ["polar", "symbols", "showLegend", "scatter-like"],
        attributes: require_attributes68(),
        supplyDefaults: require_defaults64().supplyDefaults,
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels8(),
        calc: require_calc43(),
        plot: require_plot36(),
        style: require_style2().style,
        styleOnSelect: require_style2().styleOnSelect,
        hoverPoints: require_hover24().hoverPoints,
        selectPoints: require_select2(),
        meta: {}
      };
    }
  });

  // lib/scatterpolar.js
  var require_scatterpolar2 = __commonJS({
    "lib/scatterpolar.js"(exports, module) {
      "use strict";
      module.exports = require_scatterpolar();
    }
  });

  // src/traces/scatterpolargl/attributes.js
  var require_attributes69 = __commonJS({
    "src/traces/scatterpolargl/attributes.js"(exports, module) {
      "use strict";
      var _a = require_attributes68(), { cliponaxis, hoveron } = _a, scatterPolarAttrs = __objRest(_a, ["cliponaxis", "hoveron"]);
      var {
        connectgaps,
        line: { color: color2, dash, width },
        fill,
        fillcolor,
        marker,
        textfont,
        textposition
      } = require_attributes50();
      module.exports = __spreadProps(__spreadValues({}, scatterPolarAttrs), {
        connectgaps,
        fill,
        fillcolor,
        line: { color: color2, dash, editType: "calc", width },
        marker,
        textfont,
        textposition
      });
    }
  });

  // src/traces/scatterpolargl/defaults.js
  var require_defaults65 = __commonJS({
    "src/traces/scatterpolargl/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subTypes = require_subtypes();
      var handleRThetaDefaults = require_defaults64().handleRThetaDefaults;
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var PTS_LINESONLY = require_constants8().PTS_LINESONLY;
      var attributes = require_attributes69();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        coerce("thetaunit");
        coerce("mode", len < PTS_LINESONLY ? "lines+markers" : "lines");
        coerce("text");
        coerce("hovertext");
        if (traceOut.hoveron !== "fills") {
          coerce("hovertemplate");
          coerce("hovertemplatefallback");
        }
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
            noAngleRef: true,
            noLineDash: true,
            noStandOff: true
          });
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
          coerce("connectgaps");
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce, {
            noFontShadow: true,
            noFontLineposition: true,
            noFontTextcase: true
          });
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        }
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/scatterpolargl/format_labels.js
  var require_format_labels9 = __commonJS({
    "src/traces/scatterpolargl/format_labels.js"(exports, module) {
      "use strict";
      var scatterPolarFormatLabels = require_format_labels8();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var i = cdi.i;
        if (!("r" in cdi)) cdi.r = trace._r[i];
        if (!("theta" in cdi)) cdi.theta = trace._theta[i];
        return scatterPolarFormatLabels(cdi, trace, fullLayout);
      };
    }
  });

  // src/traces/scatterpolargl/calc.js
  var require_calc44 = __commonJS({
    "src/traces/scatterpolargl/calc.js"(exports, module) {
      "use strict";
      var calcColorscale = require_colorscale_calc();
      var calcMarkerSize = require_calc3().calcMarkerSize;
      var convert = require_convert10();
      var Axes = require_axes();
      var TOO_MANY_POINTS = require_constants23().TOO_MANY_POINTS;
      module.exports = function calc(gd, trace) {
        var fullLayout = gd._fullLayout;
        var subplotId = trace.subplot;
        var radialAxis = fullLayout[subplotId].radialaxis;
        var angularAxis = fullLayout[subplotId].angularaxis;
        var rArray = trace._r = radialAxis.makeCalcdata(trace, "r");
        var thetaArray = trace._theta = angularAxis.makeCalcdata(trace, "theta");
        var len = trace._length;
        var stash = {};
        if (len < rArray.length) rArray = rArray.slice(0, len);
        if (len < thetaArray.length) thetaArray = thetaArray.slice(0, len);
        stash.r = rArray;
        stash.theta = thetaArray;
        calcColorscale(gd, trace);
        var opts = stash.opts = convert.style(gd, trace);
        var ppad;
        if (len < TOO_MANY_POINTS) {
          ppad = calcMarkerSize(trace, len);
        } else if (opts.marker) {
          ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3));
        }
        trace._extremes.x = Axes.findExtremes(radialAxis, rArray, { ppad });
        return [{ x: false, y: false, t: stash, trace }];
      };
    }
  });

  // src/traces/scatterpolargl/hover.js
  var require_hover25 = __commonJS({
    "src/traces/scatterpolargl/hover.js"(exports, module) {
      "use strict";
      var hover = require_hover16();
      var makeHoverPointText = require_hover24().makeHoverPointText;
      function hoverPoints(pointData, xval, yval, hovermode) {
        var cd = pointData.cd;
        var stash = cd[0].t;
        var rArray = stash.r;
        var thetaArray = stash.theta;
        var scatterPointData = hover.hoverPoints(pointData, xval, yval, hovermode);
        if (!scatterPointData || scatterPointData[0].index === false) return;
        var newPointData = scatterPointData[0];
        if (newPointData.index === void 0) {
          return scatterPointData;
        }
        var subplot = pointData.subplot;
        var cdi = newPointData.cd[newPointData.index];
        var trace = newPointData.trace;
        cdi.r = rArray[newPointData.index];
        cdi.theta = thetaArray[newPointData.index];
        if (!subplot.isPtInside(cdi)) return;
        newPointData.xLabelVal = void 0;
        newPointData.yLabelVal = void 0;
        makeHoverPointText(cdi, trace, subplot, newPointData);
        return scatterPointData;
      }
      module.exports = {
        hoverPoints
      };
    }
  });

  // src/traces/scatterpolargl/base_index.js
  var require_base_index4 = __commonJS({
    "src/traces/scatterpolargl/base_index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "scatterpolargl",
        basePlotModule: require_polar2(),
        categories: ["gl", "regl", "polar", "symbols", "showLegend", "scatter-like"],
        attributes: require_attributes69(),
        supplyDefaults: require_defaults65(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels9(),
        calc: require_calc44(),
        hoverPoints: require_hover25().hoverPoints,
        selectPoints: require_select7(),
        meta: {}
      };
    }
  });

  // src/traces/scatterpolargl/plot.js
  var require_plot37 = __commonJS({
    "src/traces/scatterpolargl/plot.js"(exports, module) {
      "use strict";
      var cluster = require_point_cluster();
      var isNumeric = require_fast_isnumeric();
      var scatterglPlot = require_plot19();
      var sceneUpdate = require_scene_update();
      var convert = require_convert10();
      var Lib = require_lib();
      var TOO_MANY_POINTS = require_constants23().TOO_MANY_POINTS;
      var reglPrecompiled = {};
      module.exports = function plot(gd, subplot, cdata) {
        if (!cdata.length) return;
        var radialAxis = subplot.radialAxis;
        var angularAxis = subplot.angularAxis;
        var scene = sceneUpdate(gd, subplot);
        cdata.forEach(function(cdscatter) {
          if (!cdscatter || !cdscatter[0] || !cdscatter[0].trace) return;
          var cd = cdscatter[0];
          var trace = cd.trace;
          var stash = cd.t;
          var len = trace._length;
          var rArray = stash.r;
          var thetaArray = stash.theta;
          var opts = stash.opts;
          var i;
          var subRArray = rArray.slice();
          var subThetaArray = thetaArray.slice();
          for (i = 0; i < rArray.length; i++) {
            if (!subplot.isPtInside({ r: rArray[i], theta: thetaArray[i] })) {
              subRArray[i] = NaN;
              subThetaArray[i] = NaN;
            }
          }
          var positions = new Array(len * 2);
          var x = Array(len);
          var y = Array(len);
          for (i = 0; i < len; i++) {
            var r = subRArray[i];
            var xx, yy;
            if (isNumeric(r)) {
              var rg = radialAxis.c2g(r);
              var thetag = angularAxis.c2g(subThetaArray[i], trace.thetaunit);
              xx = rg * Math.cos(thetag);
              yy = rg * Math.sin(thetag);
            } else {
              xx = yy = NaN;
            }
            x[i] = positions[i * 2] = xx;
            y[i] = positions[i * 2 + 1] = yy;
          }
          stash.tree = cluster(positions);
          if (opts.marker && len >= TOO_MANY_POINTS) {
            opts.marker.cluster = stash.tree;
          }
          if (opts.marker) {
            opts.markerSel.positions = opts.markerUnsel.positions = opts.marker.positions = positions;
          }
          if (opts.line && positions.length > 1) {
            Lib.extendFlat(
              opts.line,
              convert.linePositions(gd, trace, positions)
            );
          }
          if (opts.text) {
            Lib.extendFlat(
              opts.text,
              { positions },
              convert.textPosition(gd, trace, opts.text, opts.marker)
            );
            Lib.extendFlat(
              opts.textSel,
              { positions },
              convert.textPosition(gd, trace, opts.text, opts.markerSel)
            );
            Lib.extendFlat(
              opts.textUnsel,
              { positions },
              convert.textPosition(gd, trace, opts.text, opts.markerUnsel)
            );
          }
          if (opts.fill && !scene.fill2d) scene.fill2d = true;
          if (opts.marker && !scene.scatter2d) scene.scatter2d = true;
          if (opts.line && !scene.line2d) scene.line2d = true;
          if (opts.text && !scene.glText) scene.glText = true;
          scene.lineOptions.push(opts.line);
          scene.fillOptions.push(opts.fill);
          scene.markerOptions.push(opts.marker);
          scene.markerSelectedOptions.push(opts.markerSel);
          scene.markerUnselectedOptions.push(opts.markerUnsel);
          scene.textOptions.push(opts.text);
          scene.textSelectedOptions.push(opts.textSel);
          scene.textUnselectedOptions.push(opts.textUnsel);
          scene.selectBatch.push([]);
          scene.unselectBatch.push([]);
          stash.x = x;
          stash.y = y;
          stash.rawx = x;
          stash.rawy = y;
          stash.r = rArray;
          stash.theta = thetaArray;
          stash.positions = positions;
          stash._scene = scene;
          stash.index = scene.count;
          scene.count++;
        });
        return scatterglPlot(gd, subplot, cdata);
      };
      module.exports.reglPrecompiled = reglPrecompiled;
    }
  });

  // src/traces/scatterpolargl/index.js
  var require_scatterpolargl = __commonJS({
    "src/traces/scatterpolargl/index.js"(exports, module) {
      "use strict";
      var index = require_base_index4();
      index.plot = require_plot37();
      module.exports = index;
    }
  });

  // lib/scatterpolargl.js
  var require_scatterpolargl2 = __commonJS({
    "lib/scatterpolargl.js"(exports, module) {
      "use strict";
      module.exports = require_scatterpolargl();
    }
  });

  // src/traces/barpolar/attributes.js
  var require_attributes70 = __commonJS({
    "src/traces/barpolar/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var extendFlat = require_extend().extendFlat;
      var scatterPolarAttrs = require_attributes68();
      var barAttrs = require_attributes23();
      module.exports = {
        r: scatterPolarAttrs.r,
        theta: scatterPolarAttrs.theta,
        r0: scatterPolarAttrs.r0,
        dr: scatterPolarAttrs.dr,
        theta0: scatterPolarAttrs.theta0,
        dtheta: scatterPolarAttrs.dtheta,
        thetaunit: scatterPolarAttrs.thetaunit,
        // orientation: {
        //     valType: 'enumerated',
        //     values: ['radial', 'angular'],
        //     editType: 'calc+clearAxisTypes',
        //
        // },
        base: extendFlat({}, barAttrs.base, {}),
        offset: extendFlat({}, barAttrs.offset, {}),
        width: extendFlat({}, barAttrs.width, {}),
        text: extendFlat({}, barAttrs.text, {}),
        hovertext: extendFlat({}, barAttrs.hovertext, {}),
        // textposition: {},
        // textfont: {},
        // insidetextfont: {},
        // outsidetextfont: {},
        // constraintext: {},
        // cliponaxis: extendFlat({}, barAttrs.cliponaxis, {dflt: false}),
        marker: barPolarMarker(),
        hoverinfo: scatterPolarAttrs.hoverinfo,
        hovertemplate: hovertemplateAttrs(),
        hovertemplatefallback: templatefallbackAttrs(),
        selected: barAttrs.selected,
        unselected: barAttrs.unselected
        // error_x (error_r, error_theta)
        // error_y
      };
      function barPolarMarker() {
        var marker = extendFlat({}, barAttrs.marker);
        delete marker.cornerradius;
        return marker;
      }
    }
  });

  // src/traces/barpolar/layout_attributes.js
  var require_layout_attributes22 = __commonJS({
    "src/traces/barpolar/layout_attributes.js"(exports, module) {
      "use strict";
      module.exports = {
        barmode: {
          valType: "enumerated",
          values: ["stack", "overlay"],
          dflt: "stack",
          editType: "calc"
        },
        bargap: {
          valType: "number",
          dflt: 0.1,
          min: 0,
          max: 1,
          editType: "calc"
        }
      };
    }
  });

  // src/traces/barpolar/defaults.js
  var require_defaults66 = __commonJS({
    "src/traces/barpolar/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var handleRThetaDefaults = require_defaults64().handleRThetaDefaults;
      var handleStyleDefaults = require_style_defaults();
      var attributes = require_attributes70();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleRThetaDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        coerce("thetaunit");
        coerce("base");
        coerce("offset");
        coerce("width");
        coerce("text");
        coerce("hovertext");
        coerce("hovertemplate");
        coerce("hovertemplatefallback");
        handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
    }
  });

  // src/traces/barpolar/layout_defaults.js
  var require_layout_defaults20 = __commonJS({
    "src/traces/barpolar/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var attrs = require_layout_attributes22();
      module.exports = function(layoutIn, layoutOut, fullData) {
        var subplotsDone = {};
        var sp;
        function coerce(attr, dflt) {
          return Lib.coerce(layoutIn[sp] || {}, layoutOut[sp], attrs, attr, dflt);
        }
        for (var i = 0; i < fullData.length; i++) {
          var trace = fullData[i];
          if (trace.type === "barpolar" && trace.visible === true) {
            sp = trace.subplot;
            if (!subplotsDone[sp]) {
              coerce("barmode");
              coerce("bargap");
              subplotsDone[sp] = 1;
            }
          }
        }
      };
    }
  });

  // src/traces/barpolar/calc.js
  var require_calc45 = __commonJS({
    "src/traces/barpolar/calc.js"(exports, module) {
      "use strict";
      var hasColorscale = require_helpers().hasColorscale;
      var colorscaleCalc = require_calc();
      var isArrayOrTypedArray = require_lib().isArrayOrTypedArray;
      var arraysToCalcdata = require_arrays_to_calcdata2();
      var setGroupPositions = require_cross_trace_calc().setGroupPositions;
      var calcSelection = require_calc_selection();
      var traceIs = require_registry().traceIs;
      var extendFlat = require_lib().extendFlat;
      function calc(gd, trace) {
        var fullLayout = gd._fullLayout;
        var subplotId = trace.subplot;
        var radialAxis = fullLayout[subplotId].radialaxis;
        var angularAxis = fullLayout[subplotId].angularaxis;
        var rArray = radialAxis.makeCalcdata(trace, "r");
        var thetaArray = angularAxis.makeCalcdata(trace, "theta");
        var len = trace._length;
        var cd = new Array(len);
        var sArray = rArray;
        var pArray = thetaArray;
        for (var i = 0; i < len; i++) {
          cd[i] = { p: pArray[i], s: sArray[i] };
        }
        function d2c(attr) {
          var val = trace[attr];
          if (val !== void 0) {
            trace["_" + attr] = isArrayOrTypedArray(val) ? angularAxis.makeCalcdata(trace, attr) : angularAxis.d2c(val, trace.thetaunit);
          }
        }
        if (angularAxis.type === "linear") {
          d2c("width");
          d2c("offset");
        }
        if (hasColorscale(trace, "marker")) {
          colorscaleCalc(gd, trace, {
            vals: trace.marker.color,
            containerStr: "marker",
            cLetter: "c"
          });
        }
        if (hasColorscale(trace, "marker.line")) {
          colorscaleCalc(gd, trace, {
            vals: trace.marker.line.color,
            containerStr: "marker.line",
            cLetter: "c"
          });
        }
        arraysToCalcdata(cd, trace);
        calcSelection(cd, trace);
        return cd;
      }
      function crossTraceCalc(gd, polarLayout, subplotId) {
        var calcdata = gd.calcdata;
        var barPolarCd = [];
        for (var i = 0; i < calcdata.length; i++) {
          var cdi = calcdata[i];
          var trace = cdi[0].trace;
          if (trace.visible === true && traceIs(trace, "bar") && trace.subplot === subplotId) {
            barPolarCd.push(cdi);
          }
        }
        var rAxis = extendFlat({}, polarLayout.radialaxis, { _id: "x" });
        var aAxis = polarLayout.angularaxis;
        setGroupPositions(gd, aAxis, rAxis, barPolarCd, {
          mode: polarLayout.barmode,
          norm: polarLayout.barnorm,
          gap: polarLayout.bargap,
          groupgap: polarLayout.bargroupgap
        });
      }
      module.exports = {
        calc,
        crossTraceCalc
      };
    }
  });

  // src/traces/barpolar/plot.js
  var require_plot38 = __commonJS({
    "src/traces/barpolar/plot.js"(exports, module) {
      "use strict";
      var d3 = require_d3();
      var isNumeric = require_fast_isnumeric();
      var Lib = require_lib();
      var Drawing = require_drawing();
      var helpers = require_helpers19();
      module.exports = function plot(gd, subplot, cdbar) {
        var isStatic = gd._context.staticPlot;
        var xa = subplot.xaxis;
        var ya = subplot.yaxis;
        var radialAxis = subplot.radialAxis;
        var angularAxis = subplot.angularAxis;
        var pathFn = makePathFn(subplot);
        var barLayer = subplot.layers.frontplot.select("g.barlayer");
        Lib.makeTraceGroups(barLayer, cdbar, "trace bars").each(function() {
          var plotGroup = d3.select(this);
          var pointGroup = Lib.ensureSingle(plotGroup, "g", "points");
          var bars = pointGroup.selectAll("g.point").data(Lib.identity);
          bars.enter().append("g").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").style("stroke-miterlimit", 2).classed("point", true);
          bars.exit().remove();
          bars.each(function(di) {
            var bar = d3.select(this);
            var rp0 = di.rp0 = radialAxis.c2p(di.s0);
            var rp1 = di.rp1 = radialAxis.c2p(di.s1);
            var thetag0 = di.thetag0 = angularAxis.c2g(di.p0);
            var thetag1 = di.thetag1 = angularAxis.c2g(di.p1);
            var dPath;
            if (!isNumeric(rp0) || !isNumeric(rp1) || !isNumeric(thetag0) || !isNumeric(thetag1) || rp0 === rp1 || thetag0 === thetag1) {
              dPath = "M0,0Z";
            } else {
              var rg1 = radialAxis.c2g(di.s1);
              var thetagMid = (thetag0 + thetag1) / 2;
              di.ct = [
                xa.c2p(rg1 * Math.cos(thetagMid)),
                ya.c2p(rg1 * Math.sin(thetagMid))
              ];
              dPath = pathFn(rp0, rp1, thetag0, thetag1);
            }
            Lib.ensureSingle(bar, "path").attr("d", dPath);
          });
          Drawing.setClipUrl(
            plotGroup,
            subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null,
            gd
          );
        });
      };
      function makePathFn(subplot) {
        var cxx = subplot.cxx;
        var cyy = subplot.cyy;
        if (subplot.vangles) {
          return function(r0, r1, _a0, _a1) {
            var a0, a1;
            if (Lib.angleDelta(_a0, _a1) > 0) {
              a0 = _a0;
              a1 = _a1;
            } else {
              a0 = _a1;
              a1 = _a0;
            }
            var va0 = helpers.findEnclosingVertexAngles(a0, subplot.vangles)[0];
            var va1 = helpers.findEnclosingVertexAngles(a1, subplot.vangles)[1];
            var vaBar = [va0, (a0 + a1) / 2, va1];
            return helpers.pathPolygonAnnulus(r0, r1, a0, a1, vaBar, cxx, cyy);
          };
        }
        return function(r0, r1, a0, a1) {
          return Lib.pathAnnulus(r0, r1, a0, a1, cxx, cyy);
        };
      }
    }
  });

  // src/traces/barpolar/hover.js
  var require_hover26 = __commonJS({
    "src/traces/barpolar/hover.js"(exports, module) {
      "use strict";
      var Fx = require_fx();
      var Lib = require_lib();
      var getTraceColor = require_hover3().getTraceColor;
      var fillText = Lib.fillText;
      var makeHoverPointText = require_hover24().makeHoverPointText;
      var isPtInsidePolygon = require_helpers19().isPtInsidePolygon;
      module.exports = function hoverPoints(pointData, xval, yval) {
        var cd = pointData.cd;
        var trace = cd[0].trace;
        var subplot = pointData.subplot;
        var radialAxis = subplot.radialAxis;
        var angularAxis = subplot.angularAxis;
        var vangles = subplot.vangles;
        var inboxFn = vangles ? isPtInsidePolygon : Lib.isPtInsideSector;
        var maxHoverDistance = pointData.maxHoverDistance;
        var period = angularAxis._period || 2 * Math.PI;
        var rVal = Math.abs(radialAxis.g2p(Math.sqrt(xval * xval + yval * yval)));
        var thetaVal = Math.atan2(yval, xval);
        if (radialAxis.range[0] > radialAxis.range[1]) {
          thetaVal += Math.PI;
        }
        var distFn = function(di) {
          if (inboxFn(rVal, thetaVal, [di.rp0, di.rp1], [di.thetag0, di.thetag1], vangles)) {
            return maxHoverDistance + // add a little to the pseudo-distance for wider bars, so that like scatter,
            // if you are over two overlapping bars, the narrower one wins.
            Math.min(1, Math.abs(di.thetag1 - di.thetag0) / period) - 1 + // add a gradient so hovering near the end of a
            // bar makes it a little closer match
            (di.rp1 - rVal) / (di.rp1 - di.rp0) - 1;
          } else {
            return Infinity;
          }
        };
        Fx.getClosest(cd, distFn, pointData);
        if (pointData.index === false) return;
        var index = pointData.index;
        var cdi = cd[index];
        pointData.x0 = pointData.x1 = cdi.ct[0];
        pointData.y0 = pointData.y1 = cdi.ct[1];
        var _cdi = Lib.extendFlat({}, cdi, { r: cdi.s, theta: cdi.p });
        fillText(cdi, trace, pointData);
        makeHoverPointText(_cdi, trace, subplot, pointData);
        pointData.hovertemplate = trace.hovertemplate;
        pointData.color = getTraceColor(trace, cdi);
        pointData.xLabelVal = pointData.yLabelVal = void 0;
        if (cdi.s < 0) {
          pointData.idealAlign = "left";
        }
        return [pointData];
      };
    }
  });

  // src/traces/barpolar/index.js
  var require_barpolar = __commonJS({
    "src/traces/barpolar/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "barpolar",
        basePlotModule: require_polar2(),
        categories: ["polar", "bar", "showLegend"],
        attributes: require_attributes70(),
        layoutAttributes: require_layout_attributes22(),
        supplyDefaults: require_defaults66(),
        supplyLayoutDefaults: require_layout_defaults20(),
        calc: require_calc45().calc,
        crossTraceCalc: require_calc45().crossTraceCalc,
        plot: require_plot38(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels8(),
        style: require_style4().style,
        styleOnSelect: require_style4().styleOnSelect,
        hoverPoints: require_hover26(),
        selectPoints: require_select3(),
        meta: {}
      };
    }
  });

  // lib/barpolar.js
  var require_barpolar2 = __commonJS({
    "lib/barpolar.js"(exports, module) {
      "use strict";
      module.exports = require_barpolar();
    }
  });

  // src/plots/smith/constants.js
  var require_constants34 = __commonJS({
    "src/plots/smith/constants.js"(exports, module) {
      "use strict";
      module.exports = {
        attr: "subplot",
        name: "smith",
        axisNames: [
          "realaxis",
          "imaginaryaxis"
          // imaginary axis should be second here so that the `tickvals` defaults could be inherited from realaxis
        ],
        axisName2dataArray: { imaginaryaxis: "imag", realaxis: "real" }
      };
    }
  });

  // src/plots/smith/layout_attributes.js
  var require_layout_attributes23 = __commonJS({
    "src/plots/smith/layout_attributes.js"(exports, module) {
      "use strict";
      var colorAttrs = require_attributes3();
      var axesAttrs = require_layout_attributes4();
      var domainAttrs = require_domain().attributes;
      var extendFlat = require_lib().extendFlat;
      var overrideAll = require_edit_types().overrideAll;
      var axisLineGridAttr = overrideAll({
        color: axesAttrs.color,
        showline: extendFlat({}, axesAttrs.showline, { dflt: true }),
        linecolor: axesAttrs.linecolor,
        linewidth: axesAttrs.linewidth,
        showgrid: extendFlat({}, axesAttrs.showgrid, { dflt: true }),
        gridcolor: axesAttrs.gridcolor,
        gridwidth: axesAttrs.gridwidth,
        griddash: axesAttrs.griddash
      }, "plot", "from-root");
      var axisTickAttrs = overrideAll({
        ticklen: axesAttrs.ticklen,
        tickwidth: extendFlat({}, axesAttrs.tickwidth, { dflt: 2 }),
        tickcolor: axesAttrs.tickcolor,
        showticklabels: axesAttrs.showticklabels,
        labelalias: axesAttrs.labelalias,
        showtickprefix: axesAttrs.showtickprefix,
        tickprefix: axesAttrs.tickprefix,
        showticksuffix: axesAttrs.showticksuffix,
        ticksuffix: axesAttrs.ticksuffix,
        tickfont: axesAttrs.tickfont,
        tickformat: axesAttrs.tickformat,
        hoverformat: axesAttrs.hoverformat,
        layer: axesAttrs.layer
      }, "plot", "from-root");
      var realAxisAttrs = extendFlat({
        visible: extendFlat({}, axesAttrs.visible, { dflt: true }),
        tickvals: {
          dflt: [0.2, 0.5, 1, 2, 5],
          valType: "data_array",
          editType: "plot"
        },
        tickangle: extendFlat({}, axesAttrs.tickangle, { dflt: 90 }),
        ticks: {
          valType: "enumerated",
          values: ["top", "bottom", ""],
          editType: "ticks"
        },
        side: {
          valType: "enumerated",
          values: ["top", "bottom"],
          dflt: "top",
          editType: "plot"
        },
        editType: "calc"
      }, axisLineGridAttr, axisTickAttrs);
      var imaginaryAxisAttrs = extendFlat({
        visible: extendFlat({}, axesAttrs.visible, { dflt: true }),
        tickvals: {
          valType: "data_array",
          editType: "plot"
        },
        ticks: axesAttrs.ticks,
        editType: "calc"
      }, axisLineGridAttr, axisTickAttrs);
      module.exports = {
        domain: domainAttrs({ name: "smith", editType: "plot" }),
        bgcolor: {
          valType: "color",
          editType: "plot",
          dflt: colorAttrs.background
        },
        realaxis: realAxisAttrs,
        imaginaryaxis: imaginaryAxisAttrs,
        editType: "calc"
      };
    }
  });

  // src/plots/smith/layout_defaults.js
  var require_layout_defaults21 = __commonJS({
    "src/plots/smith/layout_defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var Color2 = require_color();
      var Template = require_plot_template();
      var handleSubplotDefaults = require_subplot_defaults();
      var getSubplotData = require_get_data().getSubplotData;
      var handlePrefixSuffixDefaults = require_prefix_suffix_defaults();
      var handleTickLabelDefaults = require_tick_label_defaults();
      var handleLineGridDefaults = require_line_grid_defaults();
      var setConvertCartesian = require_set_convert();
      var layoutAttributes = require_layout_attributes23();
      var constants = require_constants34();
      var axisNames = constants.axisNames;
      var makeImagDflt = memoize(function(realTickvals) {
        if (Lib.isTypedArray(realTickvals)) realTickvals = Array.from(realTickvals);
        return realTickvals.slice().reverse().map(function(x) {
          return -x;
        }).concat([0]).concat(realTickvals);
      }, String);
      function handleDefaults(contIn, contOut, coerce, opts) {
        var bgColor = coerce("bgcolor");
        opts.bgColor = Color2.combine(bgColor, opts.paper_bgcolor);
        var subplotData = getSubplotData(opts.fullData, constants.name, opts.id);
        var layoutOut = opts.layoutOut;
        var axName;
        function coerceAxis(attr, dflt) {
          return coerce(axName + "." + attr, dflt);
        }
        for (var i = 0; i < axisNames.length; i++) {
          axName = axisNames[i];
          if (!Lib.isPlainObject(contIn[axName])) {
            contIn[axName] = {};
          }
          var axIn = contIn[axName];
          var axOut = Template.newContainer(contOut, axName);
          axOut._id = axOut._name = axName;
          axOut._attr = opts.id + "." + axName;
          axOut._traceIndices = subplotData.map(function(t) {
            return t.index;
          });
          var visible = coerceAxis("visible");
          axOut.type = "linear";
          setConvertCartesian(axOut, layoutOut);
          handlePrefixSuffixDefaults(axIn, axOut, coerceAxis, axOut.type);
          if (visible) {
            var isRealAxis = axName === "realaxis";
            if (isRealAxis) coerceAxis("side");
            if (isRealAxis) {
              coerceAxis("tickvals");
            } else {
              var imagTickvalsDflt = makeImagDflt(
                contOut.realaxis.tickvals || layoutAttributes.realaxis.tickvals.dflt
              );
              coerceAxis("tickvals", imagTickvalsDflt);
            }
            if (Lib.isTypedArray(axOut.tickvals)) axOut.tickvals = Array.from(axOut.tickvals);
            var dfltColor;
            var dfltFontColor;
            var dfltFontSize;
            var dfltFontFamily;
            var font = opts.font || {};
            if (visible) {
              dfltColor = coerceAxis("color");
              dfltFontColor = dfltColor === axIn.color ? dfltColor : font.color;
              dfltFontSize = font.size;
              dfltFontFamily = font.family;
            }
            handleTickLabelDefaults(axIn, axOut, coerceAxis, axOut.type, {
              noAutotickangles: true,
              noTicklabelshift: true,
              noTicklabelstandoff: true,
              noTicklabelstep: true,
              noAng: !isRealAxis,
              noExp: true,
              font: {
                color: dfltFontColor,
                size: dfltFontSize,
                family: dfltFontFamily
              }
            });
            Lib.coerce2(contIn, contOut, layoutAttributes, axName + ".ticklen");
            Lib.coerce2(contIn, contOut, layoutAttributes, axName + ".tickwidth");
            Lib.coerce2(contIn, contOut, layoutAttributes, axName + ".tickcolor", contOut.color);
            var showTicks = coerceAxis("ticks");
            if (!showTicks) {
              delete contOut[axName].ticklen;
              delete contOut[axName].tickwidth;
              delete contOut[axName].tickcolor;
            }
            handleLineGridDefaults(axIn, axOut, coerceAxis, {
              dfltColor,
              bgColor: opts.bgColor,
              // default grid color is darker here (60%, vs cartesian default ~91%)
              // because the grid is not square so the eye needs heavier cues to follow
              blend: 60,
              showLine: true,
              showGrid: true,
              noZeroLine: true,
              attributes: layoutAttributes[axName]
            });
            coerceAxis("layer");
          }
          coerceAxis("hoverformat");
          delete axOut.type;
          axOut._input = axIn;
        }
      }
      module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
        handleSubplotDefaults(layoutIn, layoutOut, fullData, {
          noUirevision: true,
          type: constants.name,
          attributes: layoutAttributes,
          handleDefaults,
          font: layoutOut.font,
          paper_bgcolor: layoutOut.paper_bgcolor,
          fullData,
          layoutOut
        });
      };
      function memoize(fn, keyFn) {
        var cache = {};
        return function(val) {
          var newKey = keyFn ? keyFn(val) : val;
          if (newKey in cache) {
            return cache[newKey];
          }
          var out = fn(val);
          cache[newKey] = out;
          return out;
        };
      }
    }
  });

  // src/plots/smith/index.js
  var require_smith = __commonJS({
    "src/plots/smith/index.js"(exports, module) {
      "use strict";
      var getSubplotCalcData = require_get_data().getSubplotCalcData;
      var counterRegex = require_lib().counterRegex;
      var createPolar = require_polar();
      var constants = require_constants34();
      var attr = constants.attr;
      var name2 = constants.name;
      var counter = counterRegex(name2);
      var attributes = {};
      attributes[attr] = {
        valType: "subplotid",
        dflt: name2,
        editType: "calc"
      };
      function plot(gd) {
        var fullLayout = gd._fullLayout;
        var calcData = gd.calcdata;
        var subplotIds = fullLayout._subplots[name2];
        for (var i = 0; i < subplotIds.length; i++) {
          var id = subplotIds[i];
          var subplotCalcData = getSubplotCalcData(calcData, name2, id);
          var subplot = fullLayout[id]._subplot;
          if (!subplot) {
            subplot = createPolar(gd, id, true);
            fullLayout[id]._subplot = subplot;
          }
          subplot.plot(subplotCalcData, fullLayout, gd._promises);
        }
      }
      function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
        var oldIds = oldFullLayout._subplots[name2] || [];
        for (var i = 0; i < oldIds.length; i++) {
          var id = oldIds[i];
          var oldSubplot = oldFullLayout[id]._subplot;
          if (!newFullLayout[id] && !!oldSubplot) {
            oldSubplot.framework.remove();
            for (var k in oldSubplot.clipPaths) {
              oldSubplot.clipPaths[k].remove();
            }
          }
        }
      }
      module.exports = {
        attr,
        name: name2,
        idRoot: name2,
        idRegex: counter,
        attrRegex: counter,
        attributes,
        layoutAttributes: require_layout_attributes23(),
        supplyLayoutDefaults: require_layout_defaults21(),
        plot,
        clean,
        toSVG: require_cartesian().toSVG
      };
    }
  });

  // src/traces/scattersmith/attributes.js
  var require_attributes71 = __commonJS({
    "src/traces/scattersmith/attributes.js"(exports, module) {
      "use strict";
      var { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require_template_attributes();
      var extendFlat = require_extend().extendFlat;
      var makeFillcolorAttr = require_fillcolor_attribute();
      var scatterAttrs = require_attributes12();
      var baseAttrs = require_attributes2();
      var lineAttrs = scatterAttrs.line;
      module.exports = {
        mode: scatterAttrs.mode,
        real: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        imag: {
          valType: "data_array",
          editType: "calc+clearAxisTypes"
        },
        text: scatterAttrs.text,
        texttemplate: texttemplateAttrs({ editType: "plot" }, { keys: ["real", "imag", "text"] }),
        texttemplatefallback: templatefallbackAttrs({ editType: "plot" }),
        hovertext: scatterAttrs.hovertext,
        line: {
          color: lineAttrs.color,
          width: lineAttrs.width,
          dash: lineAttrs.dash,
          backoff: lineAttrs.backoff,
          shape: extendFlat({}, lineAttrs.shape, {
            values: ["linear", "spline"]
          }),
          smoothing: lineAttrs.smoothing,
          editType: "calc"
        },
        connectgaps: scatterAttrs.connectgaps,
        marker: scatterAttrs.marker,
        cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, { dflt: false }),
        textposition: scatterAttrs.textposition,
        textfont: scatterAttrs.textfont,
        fill: extendFlat({}, scatterAttrs.fill, {
          values: ["none", "toself", "tonext"],
          dflt: "none"
        }),
        fillcolor: makeFillcolorAttr(),
        hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
          flags: ["real", "imag", "text", "name"]
        }),
        hoveron: scatterAttrs.hoveron,
        hovertemplate: hovertemplateAttrs(),
        hovertemplatefallback: templatefallbackAttrs(),
        selected: scatterAttrs.selected,
        unselected: scatterAttrs.unselected
      };
    }
  });

  // src/traces/scattersmith/defaults.js
  var require_defaults67 = __commonJS({
    "src/traces/scattersmith/defaults.js"(exports, module) {
      "use strict";
      var Lib = require_lib();
      var subTypes = require_subtypes();
      var handleMarkerDefaults = require_marker_defaults();
      var handleLineDefaults = require_line_defaults();
      var handleLineShapeDefaults = require_line_shape_defaults();
      var handleTextDefaults = require_text_defaults();
      var handleFillColorDefaults = require_fillcolor_defaults();
      var PTS_LINESONLY = require_constants8().PTS_LINESONLY;
      var attributes = require_attributes71();
      module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
        function coerce(attr, dflt) {
          return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
        }
        var len = handleRealImagDefaults(traceIn, traceOut, layout, coerce);
        if (!len) {
          traceOut.visible = false;
          return;
        }
        coerce("mode", len < PTS_LINESONLY ? "lines+markers" : "lines");
        coerce("text");
        coerce("hovertext");
        if (traceOut.hoveron !== "fills") {
          coerce("hovertemplate");
          coerce("hovertemplatefallback");
        }
        if (subTypes.hasMarkers(traceOut)) {
          handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, { gradient: true });
        }
        if (subTypes.hasLines(traceOut)) {
          handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, { backoff: true });
          handleLineShapeDefaults(traceIn, traceOut, coerce);
          coerce("connectgaps");
        }
        if (subTypes.hasText(traceOut)) {
          coerce("texttemplate");
          coerce("texttemplatefallback");
          handleTextDefaults(traceIn, traceOut, layout, coerce);
        }
        var dfltHoverOn = [];
        if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
          coerce("cliponaxis");
          coerce("marker.maxdisplayed");
          dfltHoverOn.push("points");
        }
        coerce("fill");
        if (traceOut.fill !== "none") {
          handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
          if (!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
        }
        if (traceOut.fill === "tonext" || traceOut.fill === "toself") {
          dfltHoverOn.push("fills");
        }
        coerce("hoveron", dfltHoverOn.join("+") || "points");
        Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
      };
      function handleRealImagDefaults(traceIn, traceOut, layout, coerce) {
        var real = coerce("real");
        var imag = coerce("imag");
        var len;
        if (real && imag) {
          len = Math.min(real.length, imag.length);
        }
        if (Lib.isTypedArray(real)) {
          traceOut.real = real = Array.from(real);
        }
        if (Lib.isTypedArray(imag)) {
          traceOut.imag = imag = Array.from(imag);
        }
        traceOut._length = len;
        return len;
      }
    }
  });

  // src/traces/scattersmith/format_labels.js
  var require_format_labels10 = __commonJS({
    "src/traces/scattersmith/format_labels.js"(exports, module) {
      "use strict";
      var Axes = require_axes();
      module.exports = function formatLabels(cdi, trace, fullLayout) {
        var labels = {};
        var subplot = fullLayout[trace.subplot]._subplot;
        labels.realLabel = Axes.tickText(subplot.radialAxis, cdi.real, true).text;
        labels.imagLabel = Axes.tickText(subplot.angularAxis, cdi.imag, true).text;
        return labels;
      };
    }
  });

  // src/traces/scattersmith/calc.js
  var require_calc46 = __commonJS({
    "src/traces/scattersmith/calc.js"(exports, module) {
      "use strict";
      var isNumeric = require_fast_isnumeric();
      var BADNUM = require_numerical().BADNUM;
      var calcColorscale = require_colorscale_calc();
      var arraysToCalcdata = require_arrays_to_calcdata();
      var calcSelection = require_calc_selection();
      var calcMarkerSize = require_calc3().calcMarkerSize;
      module.exports = function calc(gd, trace) {
        var fullLayout = gd._fullLayout;
        var subplotId = trace.subplot;
        var realAxis = fullLayout[subplotId].realaxis;
        var imaginaryAxis = fullLayout[subplotId].imaginaryaxis;
        var realArray = realAxis.makeCalcdata(trace, "real");
        var imagArray = imaginaryAxis.makeCalcdata(trace, "imag");
        var len = trace._length;
        var cd = new Array(len);
        for (var i = 0; i < len; i++) {
          var real = realArray[i];
          var imag = imagArray[i];
          var cdi = cd[i] = {};
          if (isNumeric(real) && isNumeric(imag)) {
            cdi.real = real;
            cdi.imag = imag;
          } else {
            cdi.real = BADNUM;
          }
        }
        calcMarkerSize(trace, len);
        calcColorscale(gd, trace);
        arraysToCalcdata(cd, trace);
        calcSelection(cd, trace);
        return cd;
      };
    }
  });

  // src/traces/scattersmith/plot.js
  var require_plot39 = __commonJS({
    "src/traces/scattersmith/plot.js"(exports, module) {
      "use strict";
      var scatterPlot = require_plot();
      var BADNUM = require_numerical().BADNUM;
      var helpers = require_helpers20();
      var smith = helpers.smith;
      module.exports = function plot(gd, subplot, moduleCalcData) {
        var mlayer = subplot.layers.frontplot.select("g.scatterlayer");
        var xa = subplot.xaxis;
        var ya = subplot.yaxis;
        var plotinfo = {
          xaxis: xa,
          yaxis: ya,
          plot: subplot.framework,
          layerClipId: subplot._hasClipOnAxisFalse ? subplot.clipIds.forTraces : null
        };
        for (var i = 0; i < moduleCalcData.length; i++) {
          var cdi = moduleCalcData[i];
          for (var j = 0; j < cdi.length; j++) {
            if (j === 0) {
              cdi[0].trace._xA = xa;
              cdi[0].trace._yA = ya;
            }
            var cd = cdi[j];
            var real = cd.real;
            if (real === BADNUM) {
              cd.x = cd.y = BADNUM;
            } else {
              var t = smith([real, cd.imag]);
              cd.x = t[0];
              cd.y = t[1];
            }
          }
        }
        scatterPlot(gd, plotinfo, moduleCalcData, mlayer);
      };
    }
  });

  // src/traces/scattersmith/hover.js
  var require_hover27 = __commonJS({
    "src/traces/scattersmith/hover.js"(exports, module) {
      "use strict";
      var scatterHover = require_hover2();
      function hoverPoints(pointData, xval, yval, hovermode) {
        var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
        if (!scatterPointData || scatterPointData[0].index === false) return;
        var newPointData = scatterPointData[0];
        if (newPointData.index === void 0) {
          return scatterPointData;
        }
        var subplot = pointData.subplot;
        var cdi = newPointData.cd[newPointData.index];
        var trace = newPointData.trace;
        if (!subplot.isPtInside(cdi)) return;
        newPointData.xLabelVal = void 0;
        newPointData.yLabelVal = void 0;
        makeHoverPointText(cdi, trace, subplot, newPointData);
        newPointData.hovertemplate = trace.hovertemplate;
        return scatterPointData;
      }
      function makeHoverPointText(cdi, trace, subplot, pointData) {
        var realAxis = subplot.radialAxis;
        var imaginaryAxis = subplot.angularAxis;
        realAxis._hovertitle = "real";
        imaginaryAxis._hovertitle = "imag";
        var fullLayout = {};
        fullLayout[trace.subplot] = { _subplot: subplot };
        var labels = trace._module.formatLabels(cdi, trace, fullLayout);
        pointData.realLabel = labels.realLabel;
        pointData.imagLabel = labels.imagLabel;
        var hoverinfo = cdi.hi || trace.hoverinfo;
        var text = [];
        function textPart(ax, val) {
          text.push(ax._hovertitle + ": " + val);
        }
        if (!trace.hovertemplate) {
          var parts = hoverinfo.split("+");
          if (parts.indexOf("all") !== -1) parts = ["real", "imag", "text"];
          if (parts.indexOf("real") !== -1) textPart(realAxis, pointData.realLabel);
          if (parts.indexOf("imag") !== -1) textPart(imaginaryAxis, pointData.imagLabel);
          if (parts.indexOf("text") !== -1 && pointData.text) {
            text.push(pointData.text);
            delete pointData.text;
          }
          pointData.extraText = text.join("<br>");
        }
      }
      module.exports = {
        hoverPoints,
        makeHoverPointText
      };
    }
  });

  // src/traces/scattersmith/index.js
  var require_scattersmith = __commonJS({
    "src/traces/scattersmith/index.js"(exports, module) {
      "use strict";
      module.exports = {
        moduleType: "trace",
        name: "scattersmith",
        basePlotModule: require_smith(),
        categories: ["smith", "symbols", "showLegend", "scatter-like"],
        attributes: require_attributes71(),
        supplyDefaults: require_defaults67(),
        colorbar: require_marker_colorbar(),
        formatLabels: require_format_labels10(),
        calc: require_calc46(),
        plot: require_plot39(),
        style: require_style2().style,
        styleOnSelect: require_style2().styleOnSelect,
        hoverPoints: require_hover27().hoverPoints,
        selectPoints: require_select2(),
        meta: {}
      };
    }
  });

  // lib/scattersmith.js
  var require_scattersmith2 = __commonJS({
    "lib/scattersmith.js"(exports, module) {
      "use strict";
      module.exports = require_scattersmith();
    }
  });

  // node_modules/world-calendars/dist/main.js
  var require_main = __commonJS({
    "node_modules/world-calendars/dist/main.js"(exports, module) {
      var assign = require_object_assign();
      function Calendars() {
        this.regionalOptions = [];
        this.regionalOptions[""] = {
          invalidCalendar: "Calendar {0} not found",
          invalidDate: "Invalid {0} date",
          invalidMonth: "Invalid {0} month",
          invalidYear: "Invalid {0} year",
          differentCalendars: "Cannot mix {0} and {1} dates"
        };
        this.local = this.regionalOptions[""];
        this.calendars = {};
        this._localCals = {};
      }
      assign(Calendars.prototype, {
        /** Obtain a calendar implementation and localisation.
            @memberof Calendars
            @param [name='gregorian'] {string} The name of the calendar, e.g. 'gregorian', 'persian', 'islamic'.
            @param [language=''] {string} The language code to use for localisation (default is English).
            @return {Calendar} The calendar and localisation.
            @throws Error if calendar not found. */
        instance: function(name2, language) {
          name2 = (name2 || "gregorian").toLowerCase();
          language = language || "";
          var cal = this._localCals[name2 + "-" + language];
          if (!cal && this.calendars[name2]) {
            cal = new this.calendars[name2](language);
            this._localCals[name2 + "-" + language] = cal;
          }
          if (!cal) {
            throw (this.local.invalidCalendar || this.regionalOptions[""].invalidCalendar).replace(/\{0\}/, name2);
          }
          return cal;
        },
        /** Create a new date - for today if no other parameters given.
            @memberof Calendars
            @param year {CDate|number} The date to copy or the year for the date.
            @param [month] {number} The month for the date.
            @param [day] {number} The day for the date.
            @param [calendar='gregorian'] {BaseCalendar|string} The underlying calendar or the name of the calendar.
            @param [language=''] {string} The language to use for localisation (default English).
            @return {CDate} The new date.
            @throws Error if an invalid date. */
        newDate: function(year, month, day, calendar, language) {
          calendar = (year != null && year.year ? year.calendar() : typeof calendar === "string" ? this.instance(calendar, language) : calendar) || this.instance();
          return calendar.newDate(year, month, day);
        },
        /** A simple digit substitution function for localising numbers via the Calendar digits option.
            @member Calendars
            @param digits {string[]} The substitute digits, for 0 through 9.
            @return {function} The substitution function. */
        substituteDigits: function(digits) {
          return function(value) {
            return (value + "").replace(/[0-9]/g, function(digit) {
              return digits[digit];
            });
          };
        },
        /** Digit substitution function for localising Chinese style numbers via the Calendar digits option.
            @member Calendars
            @param digits {string[]} The substitute digits, for 0 through 9.
            @param powers {string[]} The characters denoting powers of 10, i.e. 1, 10, 100, 1000.
            @return {function} The substitution function. */
        substituteChineseDigits: function(digits, powers) {
          return function(value) {
            var localNumber = "";
            var power = 0;
            while (value > 0) {
              var units = value % 10;
              localNumber = (units === 0 ? "" : digits[units] + powers[power]) + localNumber;
              power++;
              value = Math.floor(value / 10);
            }
            if (localNumber.indexOf(digits[1] + powers[1]) === 0) {
              localNumber = localNumber.substr(1);
            }
            return localNumber || digits[0];
          };
        }
      });
      function CDate(calendar, year, month, day) {
        this._calendar = calendar;
        this._year = year;
        this._month = month;
        this._day = day;
        if (this._calendar._validateLevel === 0 && !this._calendar.isValid(this._year, this._month, this._day)) {
          throw (_exports.local.invalidDate || _exports.regionalOptions[""].invalidDate).replace(/\{0\}/, this._calendar.local.name);
        }
      }
      function pad(value, length) {
        value = "" + value;
        return "000000".substring(0, length - value.length) + value;
      }
      assign(CDate.prototype, {
        /** Create a new date.
            @memberof CDate
            @param [year] {CDate|number} The date to copy or the year for the date (default this date).
            @param [month] {number} The month for the date.
            @param [day] {number} The day for the date.
            @return {CDate} The new date.
            @throws Error if an invalid date. */
        newDate: function(year, month, day) {
          return this._calendar.newDate(year == null ? this : year, month, day);
        },
        /** Set or retrieve the year for this date.
            @memberof CDate
            @param [year] {number} The year for the date.
            @return {number|CDate} The date's year (if no parameter) or the updated date.
            @throws Error if an invalid date. */
        year: function(year) {
          return arguments.length === 0 ? this._year : this.set(year, "y");
        },
        /** Set or retrieve the month for this date.
            @memberof CDate
            @param [month] {number} The month for the date.
            @return {number|CDate} The date's month (if no parameter) or the updated date.
            @throws Error if an invalid date. */
        month: function(month) {
          return arguments.length === 0 ? this._month : this.set(month, "m");
        },
        /** Set or retrieve the day for this date.
            @memberof CDate
            @param [day] {number} The day for the date.
            @return {number|CData} The date's day (if no parameter) or the updated date.
            @throws Error if an invalid date. */
        day: function(day) {
          return arguments.length === 0 ? this._day : this.set(day, "d");
        },
        /** Set new values for this date.
            @memberof CDate
            @param year {number} The year for the date.
            @param month {number} The month for the date.
            @param day {number} The day for the date.
            @return {CDate} The updated date.
            @throws Error if an invalid date. */
        date: function(year, month, day) {
          if (!this._calendar.isValid(year, month, day)) {
            throw (_exports.local.invalidDate || _exports.regionalOptions[""].invalidDate).replace(/\{0\}/, this._calendar.local.name);
          }
          this._year = year;
          this._month = month;
          this._day = day;
          return this;
        },
        /** Determine whether this date is in a leap year.
            @memberof CDate
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not. */
        leapYear: function() {
          return this._calendar.leapYear(this);
        },
        /** Retrieve the epoch designator for this date, e.g. BCE or CE.
            @memberof CDate
            @return {string} The current epoch. */
        epoch: function() {
          return this._calendar.epoch(this);
        },
        /** Format the year, if not a simple sequential number.
            @memberof CDate
            @return {string} The formatted year. */
        formatYear: function() {
          return this._calendar.formatYear(this);
        },
        /** Retrieve the month of the year for this date,
            i.e. the month's position within a numbered year.
            @memberof CDate
            @return {number} The month of the year: <code>minMonth</code> to months per year. */
        monthOfYear: function() {
          return this._calendar.monthOfYear(this);
        },
        /** Retrieve the week of the year for this date.
            @memberof CDate
            @return {number} The week of the year: 1 to weeks per year. */
        weekOfYear: function() {
          return this._calendar.weekOfYear(this);
        },
        /** Retrieve the number of days in the year for this date.
            @memberof CDate
            @return {number} The number of days in this year. */
        daysInYear: function() {
          return this._calendar.daysInYear(this);
        },
        /** Retrieve the day of the year for this date.
            @memberof CDate
            @return {number} The day of the year: 1 to days per year. */
        dayOfYear: function() {
          return this._calendar.dayOfYear(this);
        },
        /** Retrieve the number of days in the month for this date.
            @memberof CDate
            @return {number} The number of days. */
        daysInMonth: function() {
          return this._calendar.daysInMonth(this);
        },
        /** Retrieve the day of the week for this date.
            @memberof CDate
            @return {number} The day of the week: 0 to number of days - 1. */
        dayOfWeek: function() {
          return this._calendar.dayOfWeek(this);
        },
        /** Determine whether this date is a week day.
            @memberof CDate
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not. */
        weekDay: function() {
          return this._calendar.weekDay(this);
        },
        /** Retrieve additional information about this date.
            @memberof CDate
            @return {object} Additional information - contents depends on calendar. */
        extraInfo: function() {
          return this._calendar.extraInfo(this);
        },
        /** Add period(s) to a date.
            @memberof CDate
            @param offset {number} The number of periods to adjust by.
            @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
            @return {CDate} The updated date. */
        add: function(offset, period) {
          return this._calendar.add(this, offset, period);
        },
        /** Set a portion of the date.
            @memberof CDate
            @param value {number} The new value for the period.
            @param period {string} One of 'y' for year, 'm' for month, 'd' for day.
            @return {CDate} The updated date.
            @throws Error if not a valid date. */
        set: function(value, period) {
          return this._calendar.set(this, value, period);
        },
        /** Compare this date to another date.
            @memberof CDate
            @param date {CDate} The other date.
            @return {number} -1 if this date is before the other date,
                    0 if they are equal, or +1 if this date is after the other date. */
        compareTo: function(date) {
          if (this._calendar.name !== date._calendar.name) {
            throw (_exports.local.differentCalendars || _exports.regionalOptions[""].differentCalendars).replace(/\{0\}/, this._calendar.local.name).replace(/\{1\}/, date._calendar.local.name);
          }
          var c = this._year !== date._year ? this._year - date._year : this._month !== date._month ? this.monthOfYear() - date.monthOfYear() : this._day - date._day;
          return c === 0 ? 0 : c < 0 ? -1 : 1;
        },
        /** Retrieve the calendar backing this date.
            @memberof CDate
            @return {BaseCalendar} The calendar implementation. */
        calendar: function() {
          return this._calendar;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof CDate
            @return {number} The equivalent Julian date. */
        toJD: function() {
          return this._calendar.toJD(this);
        },
        /** Create a new date from a Julian date.
            @memberof CDate
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          return this._calendar.fromJD(jd);
        },
        /** Convert this date to a standard (Gregorian) JavaScript Date.
            @memberof CDate
            @return {Date} The equivalent JavaScript date. */
        toJSDate: function() {
          return this._calendar.toJSDate(this);
        },
        /** Create a new date from a standard (Gregorian) JavaScript Date.
            @memberof CDate
            @param jsd {Date} The JavaScript date to convert.
            @return {CDate} The equivalent date. */
        fromJSDate: function(jsd) {
          return this._calendar.fromJSDate(jsd);
        },
        /** Convert to a string for display.
            @memberof CDate
            @return {string} This date as a string. */
        toString: function() {
          return (this.year() < 0 ? "-" : "") + pad(Math.abs(this.year()), 4) + "-" + pad(this.month(), 2) + "-" + pad(this.day(), 2);
        }
      });
      function BaseCalendar() {
        this.shortYearCutoff = "+10";
      }
      assign(BaseCalendar.prototype, {
        _validateLevel: 0,
        // "Stack" to turn validation on/off
        /** Create a new date within this calendar - today if no parameters given.
            @memberof BaseCalendar
            @param year {CDate|number} The date to duplicate or the year for the date.
            @param [month] {number} The month for the date.
            @param [day] {number} The day for the date.
            @return {CDate} The new date.
            @throws Error if not a valid date or a different calendar used. */
        newDate: function(year, month, day) {
          if (year == null) {
            return this.today();
          }
          if (year.year) {
            this._validate(
              year,
              month,
              day,
              _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
            );
            day = year.day();
            month = year.month();
            year = year.year();
          }
          return new CDate(this, year, month, day);
        },
        /** Create a new date for today.
            @memberof BaseCalendar
            @return {CDate} Today's date. */
        today: function() {
          return this.fromJSDate(/* @__PURE__ */ new Date());
        },
        /** Retrieve the epoch designator for this date.
            @memberof BaseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {string} The current epoch.
            @throws Error if an invalid year or a different calendar used. */
        epoch: function(year) {
          var date = this._validate(
            year,
            this.minMonth,
            this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[""].invalidYear
          );
          return date.year() < 0 ? this.local.epochs[0] : this.local.epochs[1];
        },
        /** Format the year, if not a simple sequential number
            @memberof BaseCalendar
            @param year {CDate|number} The date to format or the year to format.
            @return {string} The formatted year.
            @throws Error if an invalid year or a different calendar used. */
        formatYear: function(year) {
          var date = this._validate(
            year,
            this.minMonth,
            this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[""].invalidYear
          );
          return (date.year() < 0 ? "-" : "") + pad(Math.abs(date.year()), 4);
        },
        /** Retrieve the number of months in a year.
            @memberof BaseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of months.
            @throws Error if an invalid year or a different calendar used. */
        monthsInYear: function(year) {
          this._validate(
            year,
            this.minMonth,
            this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[""].invalidYear
          );
          return 12;
        },
        /** Calculate the month's ordinal position within the year -
            for those calendars that don't start at month 1!
            @memberof BaseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param month {number} The month to examine.
            @return {number} The ordinal position, starting from <code>minMonth</code>.
            @throws Error if an invalid year/month or a different calendar used. */
        monthOfYear: function(year, month) {
          var date = this._validate(
            year,
            month,
            this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[""].invalidMonth
          );
          return (date.month() + this.monthsInYear(date) - this.firstMonth) % this.monthsInYear(date) + this.minMonth;
        },
        /** Calculate actual month from ordinal position, starting from minMonth.
            @memberof BaseCalendar
            @param year {number} The year to examine.
            @param ord {number} The month's ordinal position.
            @return {number} The month's number.
            @throws Error if an invalid year/month. */
        fromMonthOfYear: function(year, ord) {
          var m = (ord + this.firstMonth - 2 * this.minMonth) % this.monthsInYear(year) + this.minMonth;
          this._validate(
            year,
            m,
            this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[""].invalidMonth
          );
          return m;
        },
        /** Retrieve the number of days in a year.
            @memberof BaseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of days.
            @throws Error if an invalid year or a different calendar used. */
        daysInYear: function(year) {
          var date = this._validate(
            year,
            this.minMonth,
            this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[""].invalidYear
          );
          return this.leapYear(date) ? 366 : 365;
        },
        /** Retrieve the day of the year for a date.
            @memberof BaseCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The day of the year.
            @throws Error if an invalid date or a different calendar used. */
        dayOfYear: function(year, month, day) {
          var date = this._validate(
            year,
            month,
            day,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          return date.toJD() - this.newDate(
            date.year(),
            this.fromMonthOfYear(date.year(), this.minMonth),
            this.minDay
          ).toJD() + 1;
        },
        /** Retrieve the number of days in a week.
            @memberof BaseCalendar
            @return {number} The number of days. */
        daysInWeek: function() {
          return 7;
        },
        /** Retrieve the day of the week for a date.
            @memberof BaseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The day of the week: 0 to number of days - 1.
            @throws Error if an invalid date or a different calendar used. */
        dayOfWeek: function(year, month, day) {
          var date = this._validate(
            year,
            month,
            day,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          return (Math.floor(this.toJD(date)) + 2) % this.daysInWeek();
        },
        /** Retrieve additional information about a date.
            @memberof BaseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {object} Additional information - contents depends on calendar.
            @throws Error if an invalid date or a different calendar used. */
        extraInfo: function(year, month, day) {
          this._validate(
            year,
            month,
            day,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          return {};
        },
        /** Add period(s) to a date.
            Cater for no year zero.
            @memberof BaseCalendar
            @param date {CDate} The starting date.
            @param offset {number} The number of periods to adjust by.
            @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
            @return {CDate} The updated date.
            @throws Error if a different calendar used. */
        add: function(date, offset, period) {
          this._validate(
            date,
            this.minMonth,
            this.minDay,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          return this._correctAdd(date, this._add(date, offset, period), offset, period);
        },
        /** Add period(s) to a date.
            @memberof BaseCalendar
            @private
            @param date {CDate} The starting date.
            @param offset {number} The number of periods to adjust by.
            @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
            @return {CDate} The updated date. */
        _add: function(date, offset, period) {
          this._validateLevel++;
          if (period === "d" || period === "w") {
            var jd = date.toJD() + offset * (period === "w" ? this.daysInWeek() : 1);
            var d = date.calendar().fromJD(jd);
            this._validateLevel--;
            return [d.year(), d.month(), d.day()];
          }
          try {
            var y = date.year() + (period === "y" ? offset : 0);
            var m = date.monthOfYear() + (period === "m" ? offset : 0);
            var d = date.day();
            var resyncYearMonth = function(calendar) {
              while (m < calendar.minMonth) {
                y--;
                m += calendar.monthsInYear(y);
              }
              var yearMonths = calendar.monthsInYear(y);
              while (m > yearMonths - 1 + calendar.minMonth) {
                y++;
                m -= yearMonths;
                yearMonths = calendar.monthsInYear(y);
              }
            };
            if (period === "y") {
              if (date.month() !== this.fromMonthOfYear(y, m)) {
                m = this.newDate(y, date.month(), this.minDay).monthOfYear();
              }
              m = Math.min(m, this.monthsInYear(y));
              d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m)));
            } else if (period === "m") {
              resyncYearMonth(this);
              d = Math.min(d, this.daysInMonth(y, this.fromMonthOfYear(y, m)));
            }
            var ymd = [y, this.fromMonthOfYear(y, m), d];
            this._validateLevel--;
            return ymd;
          } catch (e) {
            this._validateLevel--;
            throw e;
          }
        },
        /** Correct a candidate date after adding period(s) to a date.
            Handle no year zero if necessary.
            @memberof BaseCalendar
            @private
            @param date {CDate} The starting date.
            @param ymd {number[]} The added date.
            @param offset {number} The number of periods to adjust by.
            @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
            @return {CDate} The updated date. */
        _correctAdd: function(date, ymd, offset, period) {
          if (!this.hasYearZero && (period === "y" || period === "m")) {
            if (ymd[0] === 0 || // In year zero
            date.year() > 0 !== ymd[0] > 0) {
              var adj = {
                y: [1, 1, "y"],
                m: [1, this.monthsInYear(-1), "m"],
                w: [this.daysInWeek(), this.daysInYear(-1), "d"],
                d: [1, this.daysInYear(-1), "d"]
              }[period];
              var dir = offset < 0 ? -1 : 1;
              ymd = this._add(date, offset * adj[0] + dir * adj[1], adj[2]);
            }
          }
          return date.date(ymd[0], ymd[1], ymd[2]);
        },
        /** Set a portion of the date.
            @memberof BaseCalendar
            @param date {CDate} The starting date.
            @param value {number} The new value for the period.
            @param period {string} One of 'y' for year, 'm' for month, 'd' for day.
            @return {CDate} The updated date.
            @throws Error if an invalid date or a different calendar used. */
        set: function(date, value, period) {
          this._validate(
            date,
            this.minMonth,
            this.minDay,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          var y = period === "y" ? value : date.year();
          var m = period === "m" ? value : date.month();
          var d = period === "d" ? value : date.day();
          if (period === "y" || period === "m") {
            d = Math.min(d, this.daysInMonth(y, m));
          }
          return date.date(y, m, d);
        },
        /** Determine whether a date is valid for this calendar.
            @memberof BaseCalendar
            @param year {number} The year to examine.
            @param month {number} The month to examine.
            @param day {number} The day to examine.
            @return {boolean} <code>true</code> if a valid date, <code>false</code> if not. */
        isValid: function(year, month, day) {
          this._validateLevel++;
          var valid = this.hasYearZero || year !== 0;
          if (valid) {
            var date = this.newDate(year, month, this.minDay);
            valid = month >= this.minMonth && month - this.minMonth < this.monthsInYear(date) && (day >= this.minDay && day - this.minDay < this.daysInMonth(date));
          }
          this._validateLevel--;
          return valid;
        },
        /** Convert the date to a standard (Gregorian) JavaScript Date.
            @memberof BaseCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {Date} The equivalent JavaScript date.
            @throws Error if an invalid date or a different calendar used. */
        toJSDate: function(year, month, day) {
          var date = this._validate(
            year,
            month,
            day,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          return _exports.instance().fromJD(this.toJD(date)).toJSDate();
        },
        /** Convert the date from a standard (Gregorian) JavaScript Date.
            @memberof BaseCalendar
            @param jsd {Date} The JavaScript date.
            @return {CDate} The equivalent calendar date. */
        fromJSDate: function(jsd) {
          return this.fromJD(_exports.instance().fromJSDate(jsd).toJD());
        },
        /** Check that a candidate date is from the same calendar and is valid.
            @memberof BaseCalendar
            @private
            @param year {CDate|number} The date to validate or the year to validate.
            @param [month] {number} The month to validate.
            @param [day] {number} The day to validate.
            @param error {string} Rrror message if invalid.
            @throws Error if different calendars used or invalid date. */
        _validate: function(year, month, day, error) {
          if (year.year) {
            if (this._validateLevel === 0 && this.name !== year.calendar().name) {
              throw (_exports.local.differentCalendars || _exports.regionalOptions[""].differentCalendars).replace(/\{0\}/, this.local.name).replace(/\{1\}/, year.calendar().local.name);
            }
            return year;
          }
          try {
            this._validateLevel++;
            if (this._validateLevel === 1 && !this.isValid(year, month, day)) {
              throw error.replace(/\{0\}/, this.local.name);
            }
            var date = this.newDate(year, month, day);
            this._validateLevel--;
            return date;
          } catch (e) {
            this._validateLevel--;
            throw e;
          }
        }
      });
      function GregorianCalendar(language) {
        this.local = this.regionalOptions[language] || this.regionalOptions[""];
      }
      GregorianCalendar.prototype = new BaseCalendar();
      assign(GregorianCalendar.prototype, {
        /** The calendar name.
            @memberof GregorianCalendar */
        name: "Gregorian",
        /** Julian date of start of Gregorian epoch: 1 January 0001 CE.
           @memberof GregorianCalendar */
        jdEpoch: 17214255e-1,
        /** Days per month in a common year.
           @memberof GregorianCalendar */
        daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
           @memberof GregorianCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof GregorianCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof GregorianCalendar */
        firstMonth: 1,
        /** The minimum day number.
           @memberof GregorianCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof GregorianCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Gregorian",
            epochs: ["BCE", "CE"],
            monthNames: [
              "January",
              "February",
              "March",
              "April",
              "May",
              "June",
              "July",
              "August",
              "September",
              "October",
              "November",
              "December"
            ],
            monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
            dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            digits: null,
            dateFormat: "mm/dd/yyyy",
            firstDay: 0,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof GregorianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(
            year,
            this.minMonth,
            this.minDay,
            _exports.local.invalidYear || _exports.regionalOptions[""].invalidYear
          );
          var year = date.year() + (date.year() < 0 ? 1 : 0);
          return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
        },
        /** Determine the week of the year for a date - ISO 8601.
            @memberof GregorianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year, starting from 1.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(4 - (checkDate.dayOfWeek() || 7), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a month.
            @memberof GregorianCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(
            year,
            month,
            this.minDay,
            _exports.local.invalidMonth || _exports.regionalOptions[""].invalidMonth
          );
          return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof GregorianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return (this.dayOfWeek(year, month, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof GregorianCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(
            year,
            month,
            day,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          year = date.year();
          month = date.month();
          day = date.day();
          if (year < 0) {
            year++;
          }
          if (month < 3) {
            month += 12;
            year--;
          }
          var a = Math.floor(year / 100);
          var b = 2 - a + Math.floor(a / 4);
          return Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day + b - 1524.5;
        },
        /** Create a new date from a Julian date.
            @memberof GregorianCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var z = Math.floor(jd + 0.5);
          var a = Math.floor((z - 186721625e-2) / 36524.25);
          a = z + 1 + a - Math.floor(a / 4);
          var b = a + 1524;
          var c = Math.floor((b - 122.1) / 365.25);
          var d = Math.floor(365.25 * c);
          var e = Math.floor((b - d) / 30.6001);
          var day = b - d - Math.floor(e * 30.6001);
          var month = e - (e > 13.5 ? 13 : 1);
          var year = c - (month > 2.5 ? 4716 : 4715);
          if (year <= 0) {
            year--;
          }
          return this.newDate(year, month, day);
        },
        /** Convert this date to a standard (Gregorian) JavaScript Date.
            @memberof GregorianCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {Date} The equivalent JavaScript date.
            @throws Error if an invalid date or a different calendar used. */
        toJSDate: function(year, month, day) {
          var date = this._validate(
            year,
            month,
            day,
            _exports.local.invalidDate || _exports.regionalOptions[""].invalidDate
          );
          var jsd = new Date(date.year(), date.month() - 1, date.day());
          jsd.setHours(0);
          jsd.setMinutes(0);
          jsd.setSeconds(0);
          jsd.setMilliseconds(0);
          jsd.setHours(jsd.getHours() > 12 ? jsd.getHours() + 2 : 0);
          return jsd;
        },
        /** Create a new date from a standard (Gregorian) JavaScript Date.
            @memberof GregorianCalendar
            @param jsd {Date} The JavaScript date to convert.
            @return {CDate} The equivalent date. */
        fromJSDate: function(jsd) {
          return this.newDate(jsd.getFullYear(), jsd.getMonth() + 1, jsd.getDate());
        }
      });
      var _exports = module.exports = new Calendars();
      _exports.cdate = CDate;
      _exports.baseCalendar = BaseCalendar;
      _exports.calendars.gregorian = GregorianCalendar;
    }
  });

  // node_modules/world-calendars/dist/plus.js
  var require_plus = __commonJS({
    "node_modules/world-calendars/dist/plus.js"() {
      var assign = require_object_assign();
      var main = require_main();
      assign(main.regionalOptions[""], {
        invalidArguments: "Invalid arguments",
        invalidFormat: "Cannot format a date from another calendar",
        missingNumberAt: "Missing number at position {0}",
        unknownNameAt: "Unknown name at position {0}",
        unexpectedLiteralAt: "Unexpected literal at position {0}",
        unexpectedText: "Additional text found at end"
      });
      main.local = main.regionalOptions[""];
      assign(main.cdate.prototype, {
        /** Format this date.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof CDate
            @param [format] {string} The date format to use (see <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a>).
            @param [settings] {object} Options for the <code>formatDate</code> function.
            @return {string} The formatted date. */
        formatDate: function(format, settings) {
          if (typeof format !== "string") {
            settings = format;
            format = "";
          }
          return this._calendar.formatDate(format || "", this, settings);
        }
      });
      assign(main.baseCalendar.prototype, {
        UNIX_EPOCH: main.instance().newDate(1970, 1, 1).toJD(),
        SECS_PER_DAY: 24 * 60 * 60,
        TICKS_EPOCH: main.instance().jdEpoch,
        // 1 January 0001 CE
        TICKS_PER_DAY: 24 * 60 * 60 * 1e7,
        /** Date form for ATOM (RFC 3339/ISO 8601).
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        ATOM: "yyyy-mm-dd",
        /** Date form for cookies.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        COOKIE: "D, dd M yyyy",
        /** Date form for full date.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        FULL: "DD, MM d, yyyy",
        /** Date form for ISO 8601.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        ISO_8601: "yyyy-mm-dd",
        /** Date form for Julian date.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        JULIAN: "J",
        /** Date form for RFC 822.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        RFC_822: "D, d M yy",
        /** Date form for RFC 850.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        RFC_850: "DD, dd-M-yy",
        /** Date form for RFC 1036.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        RFC_1036: "D, d M yy",
        /** Date form for RFC 1123.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        RFC_1123: "D, d M yyyy",
        /** Date form for RFC 2822.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        RFC_2822: "D, d M yyyy",
        /** Date form for RSS (RFC 822).
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        RSS: "D, d M yy",
        /** Date form for Windows ticks.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        TICKS: "!",
        /** Date form for Unix timestamp.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        TIMESTAMP: "@",
        /** Date form for W3c (ISO 8601).
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar */
        W3C: "yyyy-mm-dd",
        /** Format a date object into a string value.
            The format can be combinations of the following:
            <ul>
            <li>d  - day of month (no leading zero)</li>
            <li>dd - day of month (two digit)</li>
            <li>o  - day of year (no leading zeros)</li>
            <li>oo - day of year (three digit)</li>
            <li>D  - day name short</li>
            <li>DD - day name long</li>
            <li>w  - week of year (no leading zero)</li>
            <li>ww - week of year (two digit)</li>
            <li>m  - month of year (no leading zero)</li>
            <li>mm - month of year (two digit)</li>
            <li>M  - month name short</li>
            <li>MM - month name long</li>
            <li>yy - year (two digit)</li>
            <li>yyyy - year (four digit)</li>
            <li>YYYY - formatted year</li>
            <li>J  - Julian date (days since January 1, 4713 BCE Greenwich noon)</li>
            <li>@  - Unix timestamp (s since 01/01/1970)</li>
            <li>!  - Windows ticks (100ns since 01/01/0001)</li>
            <li>'...' - literal text</li>
            <li>'' - single quote</li>
            </ul>
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar
            @param [format] {string} The desired format of the date (defaults to calendar format).
            @param date {CDate} The date value to format.
            @param [settings] {object} Addition options, whose attributes include:
            @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
            @property [dayNames] {string[]} Names of the days from Sunday.
            @property [monthNamesShort] {string[]} Abbreviated names of the months.
            @property [monthNames] {string[]} Names of the months.
            @property [calculateWeek] {CalendarsPickerCalculateWeek} Function that determines week of the year.
            @property [localNumbers=false] {boolean} <code>true</code> to localise numbers (if available),
                      <code>false</code> to use normal Arabic numerals.
            @return {string} The date in the above format.
            @throws Errors if the date is from a different calendar. */
        formatDate: function(format, date, settings) {
          if (typeof format !== "string") {
            settings = date;
            date = format;
            format = "";
          }
          if (!date) {
            return "";
          }
          if (date.calendar() !== this) {
            throw main.local.invalidFormat || main.regionalOptions[""].invalidFormat;
          }
          format = format || this.local.dateFormat;
          settings = settings || {};
          var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort;
          var dayNames = settings.dayNames || this.local.dayNames;
          var monthNumbers = settings.monthNumbers || this.local.monthNumbers;
          var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort;
          var monthNames = settings.monthNames || this.local.monthNames;
          var calculateWeek = settings.calculateWeek || this.local.calculateWeek;
          var doubled = function(match, step) {
            var matches = 1;
            while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) {
              matches++;
            }
            iFormat += matches - 1;
            return Math.floor(matches / (step || 1)) > 1;
          };
          var formatNumber = function(match, value, len, step) {
            var num = "" + value;
            if (doubled(match, step)) {
              while (num.length < len) {
                num = "0" + num;
              }
            }
            return num;
          };
          var formatName = function(match, value, shortNames, longNames) {
            return doubled(match) ? longNames[value] : shortNames[value];
          };
          var calendar = this;
          var formatMonth = function(date2) {
            return typeof monthNumbers === "function" ? monthNumbers.call(calendar, date2, doubled("m")) : localiseNumbers(formatNumber("m", date2.month(), 2));
          };
          var formatMonthName = function(date2, useLongName) {
            if (useLongName) {
              return typeof monthNames === "function" ? monthNames.call(calendar, date2) : monthNames[date2.month() - calendar.minMonth];
            } else {
              return typeof monthNamesShort === "function" ? monthNamesShort.call(calendar, date2) : monthNamesShort[date2.month() - calendar.minMonth];
            }
          };
          var digits = this.local.digits;
          var localiseNumbers = function(value) {
            return settings.localNumbers && digits ? digits(value) : value;
          };
          var output = "";
          var literal = false;
          for (var iFormat = 0; iFormat < format.length; iFormat++) {
            if (literal) {
              if (format.charAt(iFormat) === "'" && !doubled("'")) {
                literal = false;
              } else {
                output += format.charAt(iFormat);
              }
            } else {
              switch (format.charAt(iFormat)) {
                case "d":
                  output += localiseNumbers(formatNumber("d", date.day(), 2));
                  break;
                case "D":
                  output += formatName(
                    "D",
                    date.dayOfWeek(),
                    dayNamesShort,
                    dayNames
                  );
                  break;
                case "o":
                  output += formatNumber("o", date.dayOfYear(), 3);
                  break;
                case "w":
                  output += formatNumber("w", date.weekOfYear(), 2);
                  break;
                case "m":
                  output += formatMonth(date);
                  break;
                case "M":
                  output += formatMonthName(date, doubled("M"));
                  break;
                case "y":
                  output += doubled("y", 2) ? date.year() : (date.year() % 100 < 10 ? "0" : "") + date.year() % 100;
                  break;
                case "Y":
                  doubled("Y", 2);
                  output += date.formatYear();
                  break;
                case "J":
                  output += date.toJD();
                  break;
                case "@":
                  output += (date.toJD() - this.UNIX_EPOCH) * this.SECS_PER_DAY;
                  break;
                case "!":
                  output += (date.toJD() - this.TICKS_EPOCH) * this.TICKS_PER_DAY;
                  break;
                case "'":
                  if (doubled("'")) {
                    output += "'";
                  } else {
                    literal = true;
                  }
                  break;
                default:
                  output += format.charAt(iFormat);
              }
            }
          }
          return output;
        },
        /** Parse a string value into a date object.
            See <a href="#formatDate"><code>formatDate</code></a> for the possible formats, plus:
            <ul>
            <li>* - ignore rest of string</li>
            </ul>
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar
            @param format {string} The expected format of the date ('' for default calendar format).
            @param value {string} The date in the above format.
            @param [settings] {object} Additional options whose attributes include:
            @property [shortYearCutoff] {number} The cutoff year for determining the century.
            @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
            @property [dayNames] {string[]} Names of the days from Sunday.
            @property [monthNamesShort] {string[]} Abbreviated names of the months.
            @property [monthNames] {string[]} Names of the months.
            @return {CDate} The extracted date value or <code>null</code> if value is blank.
            @throws Errors if the format and/or value are missing,
                    if the value doesn't match the format, or if the date is invalid. */
        parseDate: function(format, value, settings) {
          if (value == null) {
            throw main.local.invalidArguments || main.regionalOptions[""].invalidArguments;
          }
          value = typeof value === "object" ? value.toString() : value + "";
          if (value === "") {
            return null;
          }
          format = format || this.local.dateFormat;
          settings = settings || {};
          var shortYearCutoff = settings.shortYearCutoff || this.shortYearCutoff;
          shortYearCutoff = typeof shortYearCutoff !== "string" ? shortYearCutoff : this.today().year() % 100 + parseInt(shortYearCutoff, 10);
          var dayNamesShort = settings.dayNamesShort || this.local.dayNamesShort;
          var dayNames = settings.dayNames || this.local.dayNames;
          var parseMonth = settings.parseMonth || this.local.parseMonth;
          var monthNumbers = settings.monthNumbers || this.local.monthNumbers;
          var monthNamesShort = settings.monthNamesShort || this.local.monthNamesShort;
          var monthNames = settings.monthNames || this.local.monthNames;
          var jd = -1;
          var year = -1;
          var month = -1;
          var day = -1;
          var doy = -1;
          var shortYear = false;
          var literal = false;
          var doubled = function(match, step) {
            var matches = 1;
            while (iFormat + matches < format.length && format.charAt(iFormat + matches) === match) {
              matches++;
            }
            iFormat += matches - 1;
            return Math.floor(matches / (step || 1)) > 1;
          };
          var getNumber = function(match, step) {
            var isDoubled = doubled(match, step);
            var size = [2, 3, isDoubled ? 4 : 2, isDoubled ? 4 : 2, 10, 11, 20]["oyYJ@!".indexOf(match) + 1];
            var digits = new RegExp("^-?\\d{1," + size + "}");
            var num = value.substring(iValue).match(digits);
            if (!num) {
              throw (main.local.missingNumberAt || main.regionalOptions[""].missingNumberAt).replace(/\{0\}/, iValue);
            }
            iValue += num[0].length;
            return parseInt(num[0], 10);
          };
          var calendar = this;
          var getMonthNumber = function() {
            if (typeof monthNumbers === "function") {
              doubled("m");
              var month2 = monthNumbers.call(calendar, value.substring(iValue));
              iValue += month2.length;
              return month2;
            }
            return getNumber("m");
          };
          var getName = function(match, shortNames, longNames, step) {
            var names2 = doubled(match, step) ? longNames : shortNames;
            for (var i = 0; i < names2.length; i++) {
              if (value.substr(iValue, names2[i].length).toLowerCase() === names2[i].toLowerCase()) {
                iValue += names2[i].length;
                return i + calendar.minMonth;
              }
            }
            throw (main.local.unknownNameAt || main.regionalOptions[""].unknownNameAt).replace(/\{0\}/, iValue);
          };
          var getMonthName = function() {
            if (typeof monthNames === "function") {
              var month2 = doubled("M") ? monthNames.call(calendar, value.substring(iValue)) : monthNamesShort.call(calendar, value.substring(iValue));
              iValue += month2.length;
              return month2;
            }
            return getName("M", monthNamesShort, monthNames);
          };
          var checkLiteral = function() {
            if (value.charAt(iValue) !== format.charAt(iFormat)) {
              throw (main.local.unexpectedLiteralAt || main.regionalOptions[""].unexpectedLiteralAt).replace(/\{0\}/, iValue);
            }
            iValue++;
          };
          var iValue = 0;
          for (var iFormat = 0; iFormat < format.length; iFormat++) {
            if (literal) {
              if (format.charAt(iFormat) === "'" && !doubled("'")) {
                literal = false;
              } else {
                checkLiteral();
              }
            } else {
              switch (format.charAt(iFormat)) {
                case "d":
                  day = getNumber("d");
                  break;
                case "D":
                  getName("D", dayNamesShort, dayNames);
                  break;
                case "o":
                  doy = getNumber("o");
                  break;
                case "w":
                  getNumber("w");
                  break;
                case "m":
                  month = getMonthNumber();
                  break;
                case "M":
                  month = getMonthName();
                  break;
                case "y":
                  var iSave = iFormat;
                  shortYear = !doubled("y", 2);
                  iFormat = iSave;
                  year = getNumber("y", 2);
                  break;
                case "Y":
                  year = getNumber("Y", 2);
                  break;
                case "J":
                  jd = getNumber("J") + 0.5;
                  if (value.charAt(iValue) === ".") {
                    iValue++;
                    getNumber("J");
                  }
                  break;
                case "@":
                  jd = getNumber("@") / this.SECS_PER_DAY + this.UNIX_EPOCH;
                  break;
                case "!":
                  jd = getNumber("!") / this.TICKS_PER_DAY + this.TICKS_EPOCH;
                  break;
                case "*":
                  iValue = value.length;
                  break;
                case "'":
                  if (doubled("'")) {
                    checkLiteral();
                  } else {
                    literal = true;
                  }
                  break;
                default:
                  checkLiteral();
              }
            }
          }
          if (iValue < value.length) {
            throw main.local.unexpectedText || main.regionalOptions[""].unexpectedText;
          }
          if (year === -1) {
            year = this.today().year();
          } else if (year < 100 && shortYear) {
            year += shortYearCutoff === -1 ? 1900 : this.today().year() - this.today().year() % 100 - (year <= shortYearCutoff ? 0 : 100);
          }
          if (typeof month === "string") {
            month = parseMonth.call(this, year, month);
          }
          if (doy > -1) {
            month = 1;
            day = doy;
            for (var dim = this.daysInMonth(year, month); day > dim; dim = this.daysInMonth(year, month)) {
              month++;
              day -= dim;
            }
          }
          return jd > -1 ? this.fromJD(jd) : this.newDate(year, month, day);
        },
        /** A date may be specified as an exact value or a relative one.
            Found in the <code>jquery.calendars.plus.js</code> module.
            @memberof BaseCalendar
            @param dateSpec {CDate|number|string} The date as an object or string in the given format or
                    an offset - numeric days from today, or string amounts and periods, e.g. '+1m +2w'.
            @param defaultDate {CDate} The date to use if no other supplied, may be <code>null</code>.
            @param currentDate {CDate} The current date as a possible basis for relative dates,
                    if <code>null</code> today is used (optional)
            @param [dateFormat] {string} The expected date format - see <a href="#formatDate"><code>formatDate</code></a>.
            @param [settings] {object} Additional options whose attributes include:
            @property [shortYearCutoff] {number} The cutoff year for determining the century.
            @property [dayNamesShort] {string[]} Abbreviated names of the days from Sunday.
            @property [dayNames] {string[]} Names of the days from Sunday.
            @property [monthNamesShort] {string[]} Abbreviated names of the months.
            @property [monthNames] {string[]} Names of the months.
            @return {CDate} The decoded date. */
        determineDate: function(dateSpec, defaultDate, currentDate, dateFormat, settings) {
          if (currentDate && typeof currentDate !== "object") {
            settings = dateFormat;
            dateFormat = currentDate;
            currentDate = null;
          }
          if (typeof dateFormat !== "string") {
            settings = dateFormat;
            dateFormat = "";
          }
          var calendar = this;
          var offsetString = function(offset) {
            try {
              return calendar.parseDate(dateFormat, offset, settings);
            } catch (e) {
            }
            offset = offset.toLowerCase();
            var date = (offset.match(/^c/) && currentDate ? currentDate.newDate() : null) || calendar.today();
            var pattern = /([+-]?[0-9]+)\s*(d|w|m|y)?/g;
            var matches = pattern.exec(offset);
            while (matches) {
              date.add(parseInt(matches[1], 10), matches[2] || "d");
              matches = pattern.exec(offset);
            }
            return date;
          };
          defaultDate = defaultDate ? defaultDate.newDate() : null;
          dateSpec = dateSpec == null ? defaultDate : typeof dateSpec === "string" ? offsetString(dateSpec) : typeof dateSpec === "number" ? isNaN(dateSpec) || dateSpec === Infinity || dateSpec === -Infinity ? defaultDate : calendar.today().add(dateSpec, "d") : calendar.newDate(dateSpec);
          return dateSpec;
        }
      });
    }
  });

  // node_modules/world-calendars/dist/calendars/chinese.js
  var require_chinese = __commonJS({
    "node_modules/world-calendars/dist/calendars/chinese.js"() {
      var main = require_main();
      var assign = require_object_assign();
      var gregorianCalendar = main.instance();
      function ChineseCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      ChineseCalendar.prototype = new main.baseCalendar();
      assign(ChineseCalendar.prototype, {
        /** The calendar name.
            @memberof ChineseCalendar */
        name: "Chinese",
        /** Julian date of start of Gregorian epoch: 1 January 0001 CE.
           @memberof GregorianCalendar */
        jdEpoch: 17214255e-1,
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof ChineseCalendar */
        hasYearZero: false,
        /** The minimum month number.
            This calendar uses month indices to account for intercalary months. 
            @memberof ChineseCalendar */
        minMonth: 0,
        /** The first month in the year.
            This calendar uses month indices to account for intercalary months. 
            @memberof ChineseCalendar */
        firstMonth: 0,
        /** The minimum day number.
            @memberof ChineseCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof ChineseCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Chinese",
            epochs: ["BEC", "EC"],
            monthNumbers: function(date, padded) {
              if (typeof date === "string") {
                var match = date.match(MONTH_NUMBER_REGEXP);
                return match ? match[0] : "";
              }
              var year = this._validateYear(date);
              var monthIndex = date.month();
              var month = "" + this.toChineseMonth(year, monthIndex);
              if (padded && month.length < 2) {
                month = "0" + month;
              }
              if (this.isIntercalaryMonth(year, monthIndex)) {
                month += "i";
              }
              return month;
            },
            monthNames: function(date) {
              if (typeof date === "string") {
                var match = date.match(MONTH_NAME_REGEXP);
                return match ? match[0] : "";
              }
              var year = this._validateYear(date);
              var monthIndex = date.month();
              var month = this.toChineseMonth(year, monthIndex);
              var monthName = [
                "\u4E00\u6708",
                "\u4E8C\u6708",
                "\u4E09\u6708",
                "\u56DB\u6708",
                "\u4E94\u6708",
                "\u516D\u6708",
                "\u4E03\u6708",
                "\u516B\u6708",
                "\u4E5D\u6708",
                "\u5341\u6708",
                "\u5341\u4E00\u6708",
                "\u5341\u4E8C\u6708"
              ][month - 1];
              if (this.isIntercalaryMonth(year, monthIndex)) {
                monthName = "\u95F0" + monthName;
              }
              return monthName;
            },
            monthNamesShort: function(date) {
              if (typeof date === "string") {
                var match = date.match(MONTH_SHORT_NAME_REGEXP);
                return match ? match[0] : "";
              }
              var year = this._validateYear(date);
              var monthIndex = date.month();
              var month = this.toChineseMonth(year, monthIndex);
              var monthName = [
                "\u4E00",
                "\u4E8C",
                "\u4E09",
                "\u56DB",
                "\u4E94",
                "\u516D",
                "\u4E03",
                "\u516B",
                "\u4E5D",
                "\u5341",
                "\u5341\u4E00",
                "\u5341\u4E8C"
              ][month - 1];
              if (this.isIntercalaryMonth(year, monthIndex)) {
                monthName = "\u95F0" + monthName;
              }
              return monthName;
            },
            parseMonth: function(year, monthString) {
              year = this._validateYear(year);
              var month = parseInt(monthString);
              var isIntercalary;
              if (!isNaN(month)) {
                var i = monthString[monthString.length - 1];
                isIntercalary = i === "i" || i === "I";
              } else {
                if (monthString[0] === "\u95F0") {
                  isIntercalary = true;
                  monthString = monthString.substring(1);
                }
                if (monthString[monthString.length - 1] === "\u6708") {
                  monthString = monthString.substring(0, monthString.length - 1);
                }
                month = 1 + [
                  "\u4E00",
                  "\u4E8C",
                  "\u4E09",
                  "\u56DB",
                  "\u4E94",
                  "\u516D",
                  "\u4E03",
                  "\u516B",
                  "\u4E5D",
                  "\u5341",
                  "\u5341\u4E00",
                  "\u5341\u4E8C"
                ].indexOf(monthString);
              }
              var monthIndex = this.toMonthIndex(year, month, isIntercalary);
              return monthIndex;
            },
            dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
            dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            digits: null,
            dateFormat: "yyyy/mm/dd",
            firstDay: 1,
            isRTL: false
          }
        },
        /** Check that a candidate date is from the same calendar and is valid.
            @memberof BaseCalendar
            @private
            @param year {CDate|number} The date or the year to validate.
            @param error {string} Error message if invalid.
            @return {number} The year.
            @throws Error if year out of range. */
        _validateYear: function(year, error) {
          if (year.year) {
            year = year.year();
          }
          if (typeof year !== "number" || year < 1888 || year > 2111) {
            throw error.replace(/\{0\}/, this.local.name);
          }
          return year;
        },
        /** Retrieve the month index (i.e. accounting for intercalary months).
            @memberof ChineseCalendar
            @param year {number} The year.
            @param month {number} The month (1 for first month).
            @param [isIntercalary=false] {boolean} If month is intercalary.
            @return {number} The month index (0 for first month).
            @throws Error if an invalid month/year or a different calendar used. */
        toMonthIndex: function(year, month, isIntercalary) {
          var intercalaryMonth = this.intercalaryMonth(year);
          var invalidIntercalaryMonth = isIntercalary && month !== intercalaryMonth;
          if (invalidIntercalaryMonth || month < 1 || month > 12) {
            throw main.local.invalidMonth.replace(/\{0\}/, this.local.name);
          }
          var monthIndex;
          if (!intercalaryMonth) {
            monthIndex = month - 1;
          } else if (!isIntercalary && month <= intercalaryMonth) {
            monthIndex = month - 1;
          } else {
            monthIndex = month;
          }
          return monthIndex;
        },
        /** Retrieve the month (i.e. accounting for intercalary months).
            @memberof ChineseCalendar
            @param year {CDate|number} The date or the year to examine.
            @param monthIndex {number} The month index (0 for first month).
            @return {number} The month (1 for first month).
            @throws Error if an invalid month/year or a different calendar used. */
        toChineseMonth: function(year, monthIndex) {
          if (year.year) {
            year = year.year();
            monthIndex = year.month();
          }
          var intercalaryMonth = this.intercalaryMonth(year);
          var maxMonthIndex = intercalaryMonth ? 12 : 11;
          if (monthIndex < 0 || monthIndex > maxMonthIndex) {
            throw main.local.invalidMonth.replace(/\{0\}/, this.local.name);
          }
          var month;
          if (!intercalaryMonth) {
            month = monthIndex + 1;
          } else if (monthIndex < intercalaryMonth) {
            month = monthIndex + 1;
          } else {
            month = monthIndex;
          }
          return month;
        },
        /** Determine the intercalary month of a year (if any).
            @memberof ChineseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The intercalary month number, or 0 if none.
            @throws Error if an invalid year or a different calendar used. */
        intercalaryMonth: function(year) {
          year = this._validateYear(year);
          var monthDaysTable = LUNAR_MONTH_DAYS[year - LUNAR_MONTH_DAYS[0]];
          var intercalaryMonth = monthDaysTable >> 13;
          return intercalaryMonth;
        },
        /** Determine whether this date is an intercalary month.
            @memberof ChineseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [monthIndex] {number} The month index to examine.
            @return {boolean} <code>true</code> if this is an intercalary month, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        isIntercalaryMonth: function(year, monthIndex) {
          if (year.year) {
            year = year.year();
            monthIndex = year.month();
          }
          var intercalaryMonth = this.intercalaryMonth(year);
          return !!intercalaryMonth && intercalaryMonth === monthIndex;
        },
        /** Determine whether this date is in a leap year.
            @memberof ChineseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          return this.intercalaryMonth(year) !== 0;
        },
        /** Determine the week of the year for a date - ISO 8601.
            @memberof ChineseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [monthIndex] {number} The month index to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, monthIndex, day) {
          var validatedYear = this._validateYear(year, main.local.invalidyear);
          var packedDate = CHINESE_NEW_YEAR[validatedYear - CHINESE_NEW_YEAR[0]];
          var y = packedDate >> 9 & 4095;
          var m = packedDate >> 5 & 15;
          var d = packedDate & 31;
          var firstThursday;
          firstThursday = gregorianCalendar.newDate(y, m, d);
          firstThursday.add(4 - (firstThursday.dayOfWeek() || 7), "d");
          var offset = this.toJD(year, monthIndex, day) - firstThursday.toJD();
          return 1 + Math.floor(offset / 7);
        },
        /** Retrieve the number of months in a year.
            @memberof ChineseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of months.
            @throws Error if an invalid year or a different calendar used. */
        monthsInYear: function(year) {
          return this.leapYear(year) ? 13 : 12;
        },
        /** Retrieve the number of days in a month.
            @memberof ChineseCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [monthIndex] {number} The month index.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, monthIndex) {
          if (year.year) {
            monthIndex = year.month();
            year = year.year();
          }
          year = this._validateYear(year);
          var monthDaysTable = LUNAR_MONTH_DAYS[year - LUNAR_MONTH_DAYS[0]];
          var intercalaryMonth = monthDaysTable >> 13;
          var maxMonthIndex = intercalaryMonth ? 12 : 11;
          if (monthIndex > maxMonthIndex) {
            throw main.local.invalidMonth.replace(/\{0\}/, this.local.name);
          }
          var daysInMonth = monthDaysTable & 1 << 12 - monthIndex ? 30 : 29;
          return daysInMonth;
        },
        /** Determine whether this date is a week day.
            @memberof ChineseCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [monthIndex] {number} The month index to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, monthIndex, day) {
          return (this.dayOfWeek(year, monthIndex, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof ChineseCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [monthIndex] {number} The month index to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, monthIndex, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = this._validateYear(date.year());
          monthIndex = date.month();
          day = date.day();
          var isIntercalary = this.isIntercalaryMonth(year, monthIndex);
          var month = this.toChineseMonth(year, monthIndex);
          var solar = toSolar(year, month, day, isIntercalary);
          return gregorianCalendar.toJD(solar.year, solar.month, solar.day);
        },
        /** Create a new date from a Julian date.
            @memberof ChineseCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var date = gregorianCalendar.fromJD(jd);
          var lunar = toLunar(date.year(), date.month(), date.day());
          var monthIndex = this.toMonthIndex(
            lunar.year,
            lunar.month,
            lunar.isIntercalary
          );
          return this.newDate(lunar.year, monthIndex, lunar.day);
        },
        /** Create a new date from a string.
            @memberof ChineseCalendar
            @param dateString {string} String representing a Chinese date
            @return {CDate} The new date.
            @throws Error if an invalid date. */
        fromString: function(dateString) {
          var match = dateString.match(DATE_REGEXP);
          var year = this._validateYear(+match[1]);
          var month = +match[2];
          var isIntercalary = !!match[3];
          var monthIndex = this.toMonthIndex(year, month, isIntercalary);
          var day = +match[4];
          return this.newDate(year, monthIndex, day);
        },
        /** Add period(s) to a date.
            Cater for no year zero.
            @memberof ChineseCalendar
            @param date {CDate} The starting date.
            @param offset {number} The number of periods to adjust by.
            @param period {string} One of 'y' for year, 'm' for month, 'w' for week, 'd' for day.
            @return {CDate} The updated date.
            @throws Error if a different calendar used. */
        add: function(date, offset, period) {
          var year = date.year();
          var monthIndex = date.month();
          var isIntercalary = this.isIntercalaryMonth(year, monthIndex);
          var month = this.toChineseMonth(year, monthIndex);
          var cdate = Object.getPrototypeOf(ChineseCalendar.prototype).add.call(this, date, offset, period);
          if (period === "y") {
            var resultYear = cdate.year();
            var resultMonthIndex = cdate.month();
            var resultCanBeIntercalaryMonth = this.isIntercalaryMonth(resultYear, month);
            var correctedMonthIndex = isIntercalary && resultCanBeIntercalaryMonth ? this.toMonthIndex(resultYear, month, true) : this.toMonthIndex(resultYear, month, false);
            if (correctedMonthIndex !== resultMonthIndex) {
              cdate.month(correctedMonthIndex);
            }
          }
          return cdate;
        }
      });
      var DATE_REGEXP = /^\s*(-?\d\d\d\d|\d\d)[-/](\d?\d)([iI]?)[-/](\d?\d)/m;
      var MONTH_NUMBER_REGEXP = /^\d?\d[iI]?/m;
      var MONTH_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?月/m;
      var MONTH_SHORT_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?/m;
      main.calendars.chinese = ChineseCalendar;
      var LUNAR_MONTH_DAYS = [
        1887,
        5780,
        5802,
        19157,
        2742,
        50359,
        1198,
        2646,
        46378,
        7466,
        3412,
        30122,
        5482,
        67949,
        2396,
        5294,
        43597,
        6732,
        6954,
        36181,
        2772,
        4954,
        18781,
        2396,
        54427,
        5274,
        6730,
        47781,
        5800,
        6868,
        21210,
        4790,
        59703,
        2350,
        5270,
        46667,
        3402,
        3496,
        38325,
        1388,
        4782,
        18735,
        2350,
        52374,
        6804,
        7498,
        44457,
        2906,
        1388,
        29294,
        4700,
        63789,
        6442,
        6804,
        56138,
        5802,
        2772,
        38235,
        1210,
        4698,
        22827,
        5418,
        63125,
        3476,
        5802,
        43701,
        2484,
        5302,
        27223,
        2646,
        70954,
        7466,
        3412,
        54698,
        5482,
        2412,
        38062,
        5294,
        2636,
        32038,
        6954,
        60245,
        2772,
        4826,
        43357,
        2394,
        5274,
        39501,
        6730,
        72357,
        5800,
        5844,
        53978,
        4790,
        2358,
        38039,
        5270,
        87627,
        3402,
        3496,
        54708,
        5484,
        4782,
        43311,
        2350,
        3222,
        27978,
        7498,
        68965,
        2904,
        5484,
        45677,
        4700,
        6444,
        39573,
        6804,
        6986,
        19285,
        2772,
        62811,
        1210,
        4698,
        47403,
        5418,
        5780,
        38570,
        5546,
        76469,
        2420,
        5302,
        51799,
        2646,
        5414,
        36501,
        3412,
        5546,
        18869,
        2412,
        54446,
        5276,
        6732,
        48422,
        6822,
        2900,
        28010,
        4826,
        92509,
        2394,
        5274,
        55883,
        6730,
        6820,
        47956,
        5812,
        2778,
        18779,
        2358,
        62615,
        5270,
        5450,
        46757,
        3492,
        5556,
        27318,
        4718,
        67887,
        2350,
        3222,
        52554,
        7498,
        3428,
        38252,
        5468,
        4700,
        31022,
        6444,
        64149,
        6804,
        6986,
        43861,
        2772,
        5338,
        35421,
        2650,
        70955,
        5418,
        5780,
        54954,
        5546,
        2740,
        38074,
        5302,
        2646,
        29991,
        3366,
        61011,
        3412,
        5546,
        43445,
        2412,
        5294,
        35406,
        6732,
        72998,
        6820,
        6996,
        52586,
        2778,
        2396,
        38045,
        5274,
        6698,
        23333,
        6820,
        64338,
        5812,
        2746,
        43355,
        2358,
        5270,
        39499,
        5450,
        79525,
        3492,
        5548
      ];
      var CHINESE_NEW_YEAR = [
        1887,
        966732,
        967231,
        967733,
        968265,
        968766,
        969297,
        969798,
        970298,
        970829,
        971330,
        971830,
        972362,
        972863,
        973395,
        973896,
        974397,
        974928,
        975428,
        975929,
        976461,
        976962,
        977462,
        977994,
        978494,
        979026,
        979526,
        980026,
        980558,
        981059,
        981559,
        982091,
        982593,
        983124,
        983624,
        984124,
        984656,
        985157,
        985656,
        986189,
        986690,
        987191,
        987722,
        988222,
        988753,
        989254,
        989754,
        990286,
        990788,
        991288,
        991819,
        992319,
        992851,
        993352,
        993851,
        994383,
        994885,
        995385,
        995917,
        996418,
        996918,
        997450,
        997949,
        998481,
        998982,
        999483,
        1000014,
        1000515,
        1001016,
        1001548,
        1002047,
        1002578,
        1003080,
        1003580,
        1004111,
        1004613,
        1005113,
        1005645,
        1006146,
        1006645,
        1007177,
        1007678,
        1008209,
        1008710,
        1009211,
        1009743,
        1010243,
        1010743,
        1011275,
        1011775,
        1012306,
        1012807,
        1013308,
        1013840,
        1014341,
        1014841,
        1015373,
        1015874,
        1016404,
        1016905,
        1017405,
        1017937,
        1018438,
        1018939,
        1019471,
        1019972,
        1020471,
        1021002,
        1021503,
        1022035,
        1022535,
        1023036,
        1023568,
        1024069,
        1024568,
        1025100,
        1025601,
        1026102,
        1026633,
        1027133,
        1027666,
        1028167,
        1028666,
        1029198,
        1029699,
        1030199,
        1030730,
        1031231,
        1031763,
        1032264,
        1032764,
        1033296,
        1033797,
        1034297,
        1034828,
        1035329,
        1035830,
        1036362,
        1036861,
        1037393,
        1037894,
        1038394,
        1038925,
        1039427,
        1039927,
        1040459,
        1040959,
        1041491,
        1041992,
        1042492,
        1043023,
        1043524,
        1044024,
        1044556,
        1045057,
        1045558,
        1046090,
        1046590,
        1047121,
        1047622,
        1048122,
        1048654,
        1049154,
        1049655,
        1050187,
        1050689,
        1051219,
        1051720,
        1052220,
        1052751,
        1053252,
        1053752,
        1054284,
        1054786,
        1055285,
        1055817,
        1056317,
        1056849,
        1057349,
        1057850,
        1058382,
        1058883,
        1059383,
        1059915,
        1060415,
        1060947,
        1061447,
        1061947,
        1062479,
        1062981,
        1063480,
        1064012,
        1064514,
        1065014,
        1065545,
        1066045,
        1066577,
        1067078,
        1067578,
        1068110,
        1068611,
        1069112,
        1069642,
        1070142,
        1070674,
        1071175,
        1071675,
        1072207,
        1072709,
        1073209,
        1073740,
        1074241,
        1074741,
        1075273,
        1075773,
        1076305,
        1076807,
        1077308,
        1077839,
        1078340,
        1078840,
        1079372,
        1079871,
        1080403,
        1080904
      ];
      function toLunar(yearOrDate, monthOrResult, day, result) {
        var solarDate;
        var lunarDate;
        if (typeof yearOrDate === "object") {
          solarDate = yearOrDate;
          lunarDate = monthOrResult || {};
        } else {
          var isValidYear = typeof yearOrDate === "number" && yearOrDate >= 1888 && yearOrDate <= 2111;
          if (!isValidYear)
            throw new Error("Solar year outside range 1888-2111");
          var isValidMonth = typeof monthOrResult === "number" && monthOrResult >= 1 && monthOrResult <= 12;
          if (!isValidMonth)
            throw new Error("Solar month outside range 1 - 12");
          var isValidDay = typeof day === "number" && day >= 1 && day <= 31;
          if (!isValidDay)
            throw new Error("Solar day outside range 1 - 31");
          solarDate = {
            year: yearOrDate,
            month: monthOrResult,
            day
          };
          lunarDate = result || {};
        }
        var chineseNewYearPackedDate = CHINESE_NEW_YEAR[solarDate.year - CHINESE_NEW_YEAR[0]];
        var packedDate = solarDate.year << 9 | solarDate.month << 5 | solarDate.day;
        lunarDate.year = packedDate >= chineseNewYearPackedDate ? solarDate.year : solarDate.year - 1;
        chineseNewYearPackedDate = CHINESE_NEW_YEAR[lunarDate.year - CHINESE_NEW_YEAR[0]];
        var y = chineseNewYearPackedDate >> 9 & 4095;
        var m = chineseNewYearPackedDate >> 5 & 15;
        var d = chineseNewYearPackedDate & 31;
        var daysFromNewYear;
        var chineseNewYearJSDate = new Date(y, m - 1, d);
        var jsDate = new Date(solarDate.year, solarDate.month - 1, solarDate.day);
        daysFromNewYear = Math.round(
          (jsDate - chineseNewYearJSDate) / (24 * 3600 * 1e3)
        );
        var monthDaysTable = LUNAR_MONTH_DAYS[lunarDate.year - LUNAR_MONTH_DAYS[0]];
        var i;
        for (i = 0; i < 13; i++) {
          var daysInMonth = monthDaysTable & 1 << 12 - i ? 30 : 29;
          if (daysFromNewYear < daysInMonth) {
            break;
          }
          daysFromNewYear -= daysInMonth;
        }
        var intercalaryMonth = monthDaysTable >> 13;
        if (!intercalaryMonth || i < intercalaryMonth) {
          lunarDate.isIntercalary = false;
          lunarDate.month = 1 + i;
        } else if (i === intercalaryMonth) {
          lunarDate.isIntercalary = true;
          lunarDate.month = i;
        } else {
          lunarDate.isIntercalary = false;
          lunarDate.month = i;
        }
        lunarDate.day = 1 + daysFromNewYear;
        return lunarDate;
      }
      function toSolar(yearOrDate, monthOrResult, day, isIntercalaryOrResult, result) {
        var solarDate;
        var lunarDate;
        if (typeof yearOrDate === "object") {
          lunarDate = yearOrDate;
          solarDate = monthOrResult || {};
        } else {
          var isValidYear = typeof yearOrDate === "number" && yearOrDate >= 1888 && yearOrDate <= 2111;
          if (!isValidYear)
            throw new Error("Lunar year outside range 1888-2111");
          var isValidMonth = typeof monthOrResult === "number" && monthOrResult >= 1 && monthOrResult <= 12;
          if (!isValidMonth)
            throw new Error("Lunar month outside range 1 - 12");
          var isValidDay = typeof day === "number" && day >= 1 && day <= 30;
          if (!isValidDay)
            throw new Error("Lunar day outside range 1 - 30");
          var isIntercalary;
          if (typeof isIntercalaryOrResult === "object") {
            isIntercalary = false;
            solarDate = isIntercalaryOrResult;
          } else {
            isIntercalary = !!isIntercalaryOrResult;
            solarDate = result || {};
          }
          lunarDate = {
            year: yearOrDate,
            month: monthOrResult,
            day,
            isIntercalary
          };
        }
        var daysFromNewYear;
        daysFromNewYear = lunarDate.day - 1;
        var monthDaysTable = LUNAR_MONTH_DAYS[lunarDate.year - LUNAR_MONTH_DAYS[0]];
        var intercalaryMonth = monthDaysTable >> 13;
        var monthsFromNewYear;
        if (!intercalaryMonth) {
          monthsFromNewYear = lunarDate.month - 1;
        } else if (lunarDate.month > intercalaryMonth) {
          monthsFromNewYear = lunarDate.month;
        } else if (lunarDate.isIntercalary) {
          monthsFromNewYear = lunarDate.month;
        } else {
          monthsFromNewYear = lunarDate.month - 1;
        }
        for (var i = 0; i < monthsFromNewYear; i++) {
          var daysInMonth = monthDaysTable & 1 << 12 - i ? 30 : 29;
          daysFromNewYear += daysInMonth;
        }
        var packedDate = CHINESE_NEW_YEAR[lunarDate.year - CHINESE_NEW_YEAR[0]];
        var y = packedDate >> 9 & 4095;
        var m = packedDate >> 5 & 15;
        var d = packedDate & 31;
        var jsDate = new Date(y, m - 1, d + daysFromNewYear);
        solarDate.year = jsDate.getFullYear();
        solarDate.month = 1 + jsDate.getMonth();
        solarDate.day = jsDate.getDate();
        return solarDate;
      }
    }
  });

  // node_modules/world-calendars/dist/calendars/coptic.js
  var require_coptic = __commonJS({
    "node_modules/world-calendars/dist/calendars/coptic.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function CopticCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      CopticCalendar.prototype = new main.baseCalendar();
      assign(CopticCalendar.prototype, {
        /** The calendar name.
            @memberof CopticCalendar */
        name: "Coptic",
        /** Julian date of start of Coptic epoch: 29 August 284 CE (Gregorian).
            @memberof CopticCalendar */
        jdEpoch: 18250295e-1,
        /** Days per month in a common year.
            @memberof CopticCalendar */
        daysPerMonth: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 5],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof CopticCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof CopticCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof CopticCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof CopticCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof CopticCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Coptic",
            epochs: ["BAM", "AM"],
            monthNames: [
              "Thout",
              "Paopi",
              "Hathor",
              "Koiak",
              "Tobi",
              "Meshir",
              "Paremhat",
              "Paremoude",
              "Pashons",
              "Paoni",
              "Epip",
              "Mesori",
              "Pi Kogi Enavot"
            ],
            monthNamesShort: [
              "Tho",
              "Pao",
              "Hath",
              "Koi",
              "Tob",
              "Mesh",
              "Pat",
              "Pad",
              "Pash",
              "Pao",
              "Epi",
              "Meso",
              "PiK"
            ],
            dayNames: ["Tkyriaka", "Pesnau", "Pshoment", "Peftoou", "Ptiou", "Psoou", "Psabbaton"],
            dayNamesShort: ["Tky", "Pes", "Psh", "Pef", "Pti", "Pso", "Psa"],
            dayNamesMin: ["Tk", "Pes", "Psh", "Pef", "Pt", "Pso", "Psa"],
            digits: null,
            dateFormat: "dd/mm/yyyy",
            firstDay: 0,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof CopticCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          var year = date.year() + (date.year() < 0 ? 1 : 0);
          return year % 4 === 3 || year % 4 === -1;
        },
        /** Retrieve the number of months in a year.
            @memberof CopticCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of months.
            @throws Error if an invalid year or a different calendar used. */
        monthsInYear: function(year) {
          this._validate(
            year,
            this.minMonth,
            this.minDay,
            main.local.invalidYear || main.regionalOptions[""].invalidYear
          );
          return 13;
        },
        /** Determine the week of the year for a date.
            @memberof CopticCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number) the month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-checkDate.dayOfWeek(), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a month.
            @memberof CopticCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof CopticCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param month {number} The month to examine.
            @param day {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return (this.dayOfWeek(year, month, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof CopticCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number) the month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = date.year();
          if (year < 0) {
            year++;
          }
          return date.day() + (date.month() - 1) * 30 + (year - 1) * 365 + Math.floor(year / 4) + this.jdEpoch - 1;
        },
        /** Create a new date from a Julian date.
            @memberof CopticCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var c = Math.floor(jd) + 0.5 - this.jdEpoch;
          var year = Math.floor((c - Math.floor((c + 366) / 1461)) / 365) + 1;
          if (year <= 0) {
            year--;
          }
          c = Math.floor(jd) + 0.5 - this.newDate(year, 1, 1).toJD();
          var month = Math.floor(c / 30) + 1;
          var day = c - (month - 1) * 30 + 1;
          return this.newDate(year, month, day);
        }
      });
      main.calendars.coptic = CopticCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/discworld.js
  var require_discworld = __commonJS({
    "node_modules/world-calendars/dist/calendars/discworld.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function DiscworldCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      DiscworldCalendar.prototype = new main.baseCalendar();
      assign(DiscworldCalendar.prototype, {
        /** The calendar name.
            @memberof DiscworldCalendar */
        name: "Discworld",
        /** Julian date of start of Discworld epoch: 1 January 0001 CE.
            @memberof DiscworldCalendar */
        jdEpoch: 17214255e-1,
        /** Days per month in a common year.
            @memberof DiscworldCalendar */
        daysPerMonth: [16, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof DiscworldCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof DiscworldCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof DiscworldCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof DiscworldCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof DiscworldCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Discworld",
            epochs: ["BUC", "UC"],
            monthNames: [
              "Ick",
              "Offle",
              "February",
              "March",
              "April",
              "May",
              "June",
              "Grune",
              "August",
              "Spune",
              "Sektober",
              "Ember",
              "December"
            ],
            monthNamesShort: ["Ick", "Off", "Feb", "Mar", "Apr", "May", "Jun", "Gru", "Aug", "Spu", "Sek", "Emb", "Dec"],
            dayNames: ["Sunday", "Octeday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            dayNamesShort: ["Sun", "Oct", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
            dayNamesMin: ["Su", "Oc", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            digits: null,
            dateFormat: "yyyy/mm/dd",
            firstDay: 2,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return false;
        },
        /** Retrieve the number of months in a year.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of months.
            @throws Error if an invalid year or a different calendar used. */
        monthsInYear: function(year) {
          this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return 13;
        },
        /** Retrieve the number of days in a year.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of days.
            @throws Error if an invalid year or a different calendar used. */
        daysInYear: function(year) {
          this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return 400;
        },
        /** Determine the week of the year for a date.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-checkDate.dayOfWeek(), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 8) + 1;
        },
        /** Retrieve the number of days in a month.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1];
        },
        /** Retrieve the number of days in a week.
            @memberof DiscworldCalendar
            @return {number} The number of days. */
        daysInWeek: function() {
          return 8;
        },
        /** Retrieve the day of the week for a date.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The day of the week: 0 to number of days - 1.
            @throws Error if an invalid date or a different calendar used. */
        dayOfWeek: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          return (date.day() + 1) % 8;
        },
        /** Determine whether this date is a week day.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          var dow = this.dayOfWeek(year, month, day);
          return dow >= 2 && dow <= 6;
        },
        /** Retrieve additional information about a date.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {object} Additional information - contents depends on calendar.
            @throws Error if an invalid date or a different calendar used. */
        extraInfo: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          return { century: centuries[Math.floor((date.year() - 1) / 100) + 1] || "" };
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof DiscworldCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = date.year() + (date.year() < 0 ? 1 : 0);
          month = date.month();
          day = date.day();
          return day + (month > 1 ? 16 : 0) + (month > 2 ? (month - 2) * 32 : 0) + (year - 1) * 400 + this.jdEpoch - 1;
        },
        /** Create a new date from a Julian date.
            @memberof DiscworldCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          jd = Math.floor(jd + 0.5) - Math.floor(this.jdEpoch) - 1;
          var year = Math.floor(jd / 400) + 1;
          jd -= (year - 1) * 400;
          jd += jd > 15 ? 16 : 0;
          var month = Math.floor(jd / 32) + 1;
          var day = jd - (month - 1) * 32 + 1;
          return this.newDate(year <= 0 ? year - 1 : year, month, day);
        }
      });
      var centuries = {
        20: "Fruitbat",
        21: "Anchovy"
      };
      main.calendars.discworld = DiscworldCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/ethiopian.js
  var require_ethiopian = __commonJS({
    "node_modules/world-calendars/dist/calendars/ethiopian.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function EthiopianCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      EthiopianCalendar.prototype = new main.baseCalendar();
      assign(EthiopianCalendar.prototype, {
        /** The calendar name.
            @memberof EthiopianCalendar */
        name: "Ethiopian",
        /** Julian date of start of Ethiopian epoch: 27 August 8 CE (Gregorian).
            @memberof EthiopianCalendar */
        jdEpoch: 17242205e-1,
        /** Days per month in a common year.
            @memberof EthiopianCalendar */
        daysPerMonth: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 5],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof EthiopianCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof EthiopianCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof EthiopianCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof EthiopianCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof EthiopianCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Ethiopian",
            epochs: ["BEE", "EE"],
            monthNames: [
              "Meskerem",
              "Tikemet",
              "Hidar",
              "Tahesas",
              "Tir",
              "Yekatit",
              "Megabit",
              "Miazia",
              "Genbot",
              "Sene",
              "Hamle",
              "Nehase",
              "Pagume"
            ],
            monthNamesShort: [
              "Mes",
              "Tik",
              "Hid",
              "Tah",
              "Tir",
              "Yek",
              "Meg",
              "Mia",
              "Gen",
              "Sen",
              "Ham",
              "Neh",
              "Pag"
            ],
            dayNames: ["Ehud", "Segno", "Maksegno", "Irob", "Hamus", "Arb", "Kidame"],
            dayNamesShort: ["Ehu", "Seg", "Mak", "Iro", "Ham", "Arb", "Kid"],
            dayNamesMin: ["Eh", "Se", "Ma", "Ir", "Ha", "Ar", "Ki"],
            digits: null,
            dateFormat: "dd/mm/yyyy",
            firstDay: 0,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof EthiopianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          var year = date.year() + (date.year() < 0 ? 1 : 0);
          return year % 4 === 3 || year % 4 === -1;
        },
        /** Retrieve the number of months in a year.
            @memberof EthiopianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of months.
            @throws Error if an invalid year or a different calendar used. */
        monthsInYear: function(year) {
          this._validate(
            year,
            this.minMonth,
            this.minDay,
            main.local.invalidYear || main.regionalOptions[""].invalidYear
          );
          return 13;
        },
        /** Determine the week of the year for a date.
            @memberof EthiopianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-checkDate.dayOfWeek(), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a month.
            @memberof EthiopianCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof EthiopianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return (this.dayOfWeek(year, month, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof EthiopianCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = date.year();
          if (year < 0) {
            year++;
          }
          return date.day() + (date.month() - 1) * 30 + (year - 1) * 365 + Math.floor(year / 4) + this.jdEpoch - 1;
        },
        /** Create a new date from a Julian date.
            @memberof EthiopianCalendar
            @param jd {number} the Julian date to convert.
            @return {CDate} the equivalent date. */
        fromJD: function(jd) {
          var c = Math.floor(jd) + 0.5 - this.jdEpoch;
          var year = Math.floor((c - Math.floor((c + 366) / 1461)) / 365) + 1;
          if (year <= 0) {
            year--;
          }
          c = Math.floor(jd) + 0.5 - this.newDate(year, 1, 1).toJD();
          var month = Math.floor(c / 30) + 1;
          var day = c - (month - 1) * 30 + 1;
          return this.newDate(year, month, day);
        }
      });
      main.calendars.ethiopian = EthiopianCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/hebrew.js
  var require_hebrew = __commonJS({
    "node_modules/world-calendars/dist/calendars/hebrew.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function HebrewCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      HebrewCalendar.prototype = new main.baseCalendar();
      assign(HebrewCalendar.prototype, {
        /** The calendar name.
            @memberof HebrewCalendar */
        name: "Hebrew",
        /** Julian date of start of Hebrew epoch: 7 October 3761 BCE.
            @memberof HebrewCalendar */
        jdEpoch: 347995.5,
        /** Days per month in a common year.
            @memberof HebrewCalendar */
        daysPerMonth: [30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 29],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof HebrewCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof HebrewCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof HebrewCalendar */
        firstMonth: 7,
        /** The minimum day number.
            @memberof HebrewCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof HebrewCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Hebrew",
            epochs: ["BAM", "AM"],
            monthNames: [
              "Nisan",
              "Iyar",
              "Sivan",
              "Tammuz",
              "Av",
              "Elul",
              "Tishrei",
              "Cheshvan",
              "Kislev",
              "Tevet",
              "Shevat",
              "Adar",
              "Adar II"
            ],
            monthNamesShort: ["Nis", "Iya", "Siv", "Tam", "Av", "Elu", "Tis", "Che", "Kis", "Tev", "She", "Ada", "Ad2"],
            dayNames: ["Yom Rishon", "Yom Sheni", "Yom Shlishi", "Yom Revi'i", "Yom Chamishi", "Yom Shishi", "Yom Shabbat"],
            dayNamesShort: ["Ris", "She", "Shl", "Rev", "Cha", "Shi", "Sha"],
            dayNamesMin: ["Ri", "She", "Shl", "Re", "Ch", "Shi", "Sha"],
            digits: null,
            dateFormat: "dd/mm/yyyy",
            firstDay: 0,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof HebrewCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return this._leapYear(date.year());
        },
        /** Determine whether this date is in a leap year.
            @memberof HebrewCalendar
            @private
            @param year {number} The year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        _leapYear: function(year) {
          year = year < 0 ? year + 1 : year;
          return mod(year * 7 + 1, 19) < 7;
        },
        /** Retrieve the number of months in a year.
            @memberof HebrewCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of months.
            @throws Error if an invalid year or a different calendar used. */
        monthsInYear: function(year) {
          this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return this._leapYear(year.year ? year.year() : year) ? 13 : 12;
        },
        /** Determine the week of the year for a date.
            @memberof HebrewCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-checkDate.dayOfWeek(), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a year.
            @memberof HebrewCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of days.
            @throws Error if an invalid year or a different calendar used. */
        daysInYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          year = date.year();
          return this.toJD(year === -1 ? 1 : year + 1, 7, 1) - this.toJD(year, 7, 1);
        },
        /** Retrieve the number of days in a month.
            @memberof HebrewCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          if (year.year) {
            month = year.month();
            year = year.year();
          }
          this._validate(year, month, this.minDay, main.local.invalidMonth);
          return month === 12 && this.leapYear(year) ? 30 : (
            // Adar I
            month === 8 && mod(this.daysInYear(year), 10) === 5 ? 30 : (
              // Cheshvan in shlemah year
              month === 9 && mod(this.daysInYear(year), 10) === 3 ? 29 : (
                // Kislev in chaserah year
                this.daysPerMonth[month - 1]
              )
            )
          );
        },
        /** Determine whether this date is a week day.
            @memberof HebrewCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return this.dayOfWeek(year, month, day) !== 6;
        },
        /** Retrieve additional information about a date - year type.
            @memberof HebrewCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {object} Additional information - contents depends on calendar.
            @throws Error if an invalid date or a different calendar used. */
        extraInfo: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          return { yearType: (this.leapYear(date) ? "embolismic" : "common") + " " + ["deficient", "regular", "complete"][this.daysInYear(date) % 10 - 3] };
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof HebrewCalendar
            @param year {CDate)|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = date.year();
          month = date.month();
          day = date.day();
          var adjYear = year <= 0 ? year + 1 : year;
          var jd = this.jdEpoch + this._delay1(adjYear) + this._delay2(adjYear) + day + 1;
          if (month < 7) {
            for (var m = 7; m <= this.monthsInYear(year); m++) {
              jd += this.daysInMonth(year, m);
            }
            for (var m = 1; m < month; m++) {
              jd += this.daysInMonth(year, m);
            }
          } else {
            for (var m = 7; m < month; m++) {
              jd += this.daysInMonth(year, m);
            }
          }
          return jd;
        },
        /** Test for delay of start of new year and to avoid
            Sunday, Wednesday, or Friday as start of the new year.
            @memberof HebrewCalendar
            @private
            @param year {number} The year to examine.
            @return {number} The days to offset by. */
        _delay1: function(year) {
          var months = Math.floor((235 * year - 234) / 19);
          var parts = 12084 + 13753 * months;
          var day = months * 29 + Math.floor(parts / 25920);
          if (mod(3 * (day + 1), 7) < 3) {
            day++;
          }
          return day;
        },
        /** Check for delay in start of new year due to length of adjacent years.
            @memberof HebrewCalendar
            @private
            @param year {number} The year to examine.
            @return {number} The days to offset by. */
        _delay2: function(year) {
          var last = this._delay1(year - 1);
          var present = this._delay1(year);
          var next = this._delay1(year + 1);
          return next - present === 356 ? 2 : present - last === 382 ? 1 : 0;
        },
        /** Create a new date from a Julian date.
            @memberof HebrewCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          jd = Math.floor(jd) + 0.5;
          var year = Math.floor((jd - this.jdEpoch) * 98496 / 35975351) - 1;
          while (jd >= this.toJD(year === -1 ? 1 : year + 1, 7, 1)) {
            year++;
          }
          var month = jd < this.toJD(year, 1, 1) ? 7 : 1;
          while (jd > this.toJD(year, month, this.daysInMonth(year, month))) {
            month++;
          }
          var day = jd - this.toJD(year, month, 1) + 1;
          return this.newDate(year, month, day);
        }
      });
      function mod(a, b) {
        return a - b * Math.floor(a / b);
      }
      main.calendars.hebrew = HebrewCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/islamic.js
  var require_islamic = __commonJS({
    "node_modules/world-calendars/dist/calendars/islamic.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function IslamicCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      IslamicCalendar.prototype = new main.baseCalendar();
      assign(IslamicCalendar.prototype, {
        /** The calendar name.
            @memberof IslamicCalendar */
        name: "Islamic",
        /** Julian date of start of Islamic epoch: 16 July 622 CE.
            @memberof IslamicCalendar */
        jdEpoch: 19484395e-1,
        /** Days per month in a common year.
            @memberof IslamicCalendar */
        daysPerMonth: [30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof IslamicCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof IslamicCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof IslamicCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof IslamicCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof IslamicCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Islamic",
            epochs: ["BH", "AH"],
            monthNames: [
              "Muharram",
              "Safar",
              "Rabi' al-awwal",
              "Rabi' al-thani",
              "Jumada al-awwal",
              "Jumada al-thani",
              "Rajab",
              "Sha'aban",
              "Ramadan",
              "Shawwal",
              "Dhu al-Qi'dah",
              "Dhu al-Hijjah"
            ],
            monthNamesShort: ["Muh", "Saf", "Rab1", "Rab2", "Jum1", "Jum2", "Raj", "Sha'", "Ram", "Shaw", "DhuQ", "DhuH"],
            dayNames: [
              "Yawm al-ahad",
              "Yawm al-ithnayn",
              "Yawm ath-thulaathaa'",
              "Yawm al-arbi'aa'",
              "Yawm al-kham\u012Bs",
              "Yawm al-jum'a",
              "Yawm as-sabt"
            ],
            dayNamesShort: ["Aha", "Ith", "Thu", "Arb", "Kha", "Jum", "Sab"],
            dayNamesMin: ["Ah", "It", "Th", "Ar", "Kh", "Ju", "Sa"],
            digits: null,
            dateFormat: "yyyy/mm/dd",
            firstDay: 6,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof IslamicCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return (date.year() * 11 + 14) % 30 < 11;
        },
        /** Determine the week of the year for a date.
            @memberof IslamicCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-checkDate.dayOfWeek(), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a year.
            @memberof IslamicCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of days.
            @throws Error if an invalid year or a different calendar used. */
        daysInYear: function(year) {
          return this.leapYear(year) ? 355 : 354;
        },
        /** Retrieve the number of days in a month.
            @memberof IslamicCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof IslamicCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return this.dayOfWeek(year, month, day) !== 5;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof IslamicCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = date.year();
          month = date.month();
          day = date.day();
          year = year <= 0 ? year + 1 : year;
          return day + Math.ceil(29.5 * (month - 1)) + (year - 1) * 354 + Math.floor((3 + 11 * year) / 30) + this.jdEpoch - 1;
        },
        /** Create a new date from a Julian date.
            @memberof IslamicCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          jd = Math.floor(jd) + 0.5;
          var year = Math.floor((30 * (jd - this.jdEpoch) + 10646) / 10631);
          year = year <= 0 ? year - 1 : year;
          var month = Math.min(12, Math.ceil((jd - 29 - this.toJD(year, 1, 1)) / 29.5) + 1);
          var day = jd - this.toJD(year, month, 1) + 1;
          return this.newDate(year, month, day);
        }
      });
      main.calendars.islamic = IslamicCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/julian.js
  var require_julian = __commonJS({
    "node_modules/world-calendars/dist/calendars/julian.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function JulianCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      JulianCalendar.prototype = new main.baseCalendar();
      assign(JulianCalendar.prototype, {
        /** The calendar name.
            @memberof JulianCalendar */
        name: "Julian",
        /** Julian date of start of Julian epoch: 1 January 0001 AD = 30 December 0001 BCE.
            @memberof JulianCalendar */
        jdEpoch: 17214235e-1,
        /** Days per month in a common year.
            @memberof JulianCalendar */
        daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof JulianCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof JulianCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof JulianCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof JulianCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof JulianCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Julian",
            epochs: ["BC", "AD"],
            monthNames: [
              "January",
              "February",
              "March",
              "April",
              "May",
              "June",
              "July",
              "August",
              "September",
              "October",
              "November",
              "December"
            ],
            monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
            dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            digits: null,
            dateFormat: "mm/dd/yyyy",
            firstDay: 0,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof JulianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          var year = date.year() < 0 ? date.year() + 1 : date.year();
          return year % 4 === 0;
        },
        /** Determine the week of the year for a date - ISO 8601.
            @memberof JulianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(4 - (checkDate.dayOfWeek() || 7), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a month.
            @memberof JulianCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof JulianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} True if a week day, false if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return (this.dayOfWeek(year, month, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof JulianCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = date.year();
          month = date.month();
          day = date.day();
          if (year < 0) {
            year++;
          }
          if (month <= 2) {
            year--;
            month += 12;
          }
          return Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day - 1524.5;
        },
        /** Create a new date from a Julian date.
            @memberof JulianCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var a = Math.floor(jd + 0.5);
          var b = a + 1524;
          var c = Math.floor((b - 122.1) / 365.25);
          var d = Math.floor(365.25 * c);
          var e = Math.floor((b - d) / 30.6001);
          var month = e - Math.floor(e < 14 ? 1 : 13);
          var year = c - Math.floor(month > 2 ? 4716 : 4715);
          var day = b - d - Math.floor(30.6001 * e);
          if (year <= 0) {
            year--;
          }
          return this.newDate(year, month, day);
        }
      });
      main.calendars.julian = JulianCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/mayan.js
  var require_mayan = __commonJS({
    "node_modules/world-calendars/dist/calendars/mayan.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function MayanCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      MayanCalendar.prototype = new main.baseCalendar();
      assign(MayanCalendar.prototype, {
        /** The calendar name.
            @memberof MayanCalendar */
        name: "Mayan",
        /** Julian date of start of Mayan epoch: 11 August 3114 BCE.
            @memberof MayanCalendar */
        jdEpoch: 584282.5,
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof MayanCalendar */
        hasYearZero: true,
        /** The minimum month number.
            @memberof MayanCalendar */
        minMonth: 0,
        /** The first month in the year.
            @memberof MayanCalendar */
        firstMonth: 0,
        /** The minimum day number.
            @memberof MayanCalendar */
        minDay: 0,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof MayanCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left.
            @property haabMonths {string[]} The names of the Haab months.
            @property tzolkinMonths {string[]} The names of the Tzolkin months. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Mayan",
            epochs: ["", ""],
            monthNames: [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
              "15",
              "16",
              "17"
            ],
            monthNamesShort: [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
              "15",
              "16",
              "17"
            ],
            dayNames: [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
              "15",
              "16",
              "17",
              "18",
              "19"
            ],
            dayNamesShort: [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
              "15",
              "16",
              "17",
              "18",
              "19"
            ],
            dayNamesMin: [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
              "15",
              "16",
              "17",
              "18",
              "19"
            ],
            digits: null,
            dateFormat: "YYYY.m.d",
            firstDay: 0,
            isRTL: false,
            haabMonths: [
              "Pop",
              "Uo",
              "Zip",
              "Zotz",
              "Tzec",
              "Xul",
              "Yaxkin",
              "Mol",
              "Chen",
              "Yax",
              "Zac",
              "Ceh",
              "Mac",
              "Kankin",
              "Muan",
              "Pax",
              "Kayab",
              "Cumku",
              "Uayeb"
            ],
            tzolkinMonths: [
              "Imix",
              "Ik",
              "Akbal",
              "Kan",
              "Chicchan",
              "Cimi",
              "Manik",
              "Lamat",
              "Muluc",
              "Oc",
              "Chuen",
              "Eb",
              "Ben",
              "Ix",
              "Men",
              "Cib",
              "Caban",
              "Etznab",
              "Cauac",
              "Ahau"
            ]
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return false;
        },
        /** Format the year, if not a simple sequential number.
            @memberof MayanCalendar
            @param year {CDate|number} The date to format or the year to format.
            @return {string} The formatted year.
            @throws Error if an invalid year or a different calendar used. */
        formatYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          year = date.year();
          var baktun = Math.floor(year / 400);
          year = year % 400;
          year += year < 0 ? 400 : 0;
          var katun = Math.floor(year / 20);
          return baktun + "." + katun + "." + year % 20;
        },
        /** Convert from the formatted year back to a single number.
            @memberof MayanCalendar
            @param years {string} The year as n.n.n.
            @return {number} The sequential year.
            @throws Error if an invalid value is supplied. */
        forYear: function(years) {
          years = years.split(".");
          if (years.length < 3) {
            throw "Invalid Mayan year";
          }
          var year = 0;
          for (var i = 0; i < years.length; i++) {
            var y = parseInt(years[i], 10);
            if (Math.abs(y) > 19 || i > 0 && y < 0) {
              throw "Invalid Mayan year";
            }
            year = year * 20 + y;
          }
          return year;
        },
        /** Retrieve the number of months in a year.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of months.
            @throws Error if an invalid year or a different calendar used. */
        monthsInYear: function(year) {
          this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return 18;
        },
        /** Determine the week of the year for a date.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          this._validate(year, month, day, main.local.invalidDate);
          return 0;
        },
        /** Retrieve the number of days in a year.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of days.
            @throws Error if an invalid year or a different calendar used. */
        daysInYear: function(year) {
          this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return 360;
        },
        /** Retrieve the number of days in a month.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          this._validate(year, month, this.minDay, main.local.invalidMonth);
          return 20;
        },
        /** Retrieve the number of days in a week.
            @memberof MayanCalendar
            @return {number} The number of days. */
        daysInWeek: function() {
          return 5;
        },
        /** Retrieve the day of the week for a date.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The day of the week: 0 to number of days - 1.
            @throws Error if an invalid date or a different calendar used. */
        dayOfWeek: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          return date.day();
        },
        /** Determine whether this date is a week day.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          this._validate(year, month, day, main.local.invalidDate);
          return true;
        },
        /** Retrieve additional information about a date - Haab and Tzolkin equivalents.
            @memberof MayanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {object} Additional information - contents depends on calendar.
            @throws Error if an invalid date or a different calendar used. */
        extraInfo: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          var jd = date.toJD();
          var haab = this._toHaab(jd);
          var tzolkin = this._toTzolkin(jd);
          return {
            haabMonthName: this.local.haabMonths[haab[0] - 1],
            haabMonth: haab[0],
            haabDay: haab[1],
            tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1],
            tzolkinDay: tzolkin[0],
            tzolkinTrecena: tzolkin[1]
          };
        },
        /** Retrieve Haab date from a Julian date.
            @memberof MayanCalendar
            @private
            @param jd  {number} The Julian date.
            @return {number[]} Corresponding Haab month and day. */
        _toHaab: function(jd) {
          jd -= this.jdEpoch;
          var day = mod(jd + 8 + (18 - 1) * 20, 365);
          return [Math.floor(day / 20) + 1, mod(day, 20)];
        },
        /** Retrieve Tzolkin date from a Julian date.
            @memberof MayanCalendar
            @private
            @param jd {number} The Julian date.
            @return {number[]} Corresponding Tzolkin day and trecena. */
        _toTzolkin: function(jd) {
          jd -= this.jdEpoch;
          return [amod(jd + 20, 20), amod(jd + 4, 13)];
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof MayanCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          return date.day() + date.month() * 20 + date.year() * 360 + this.jdEpoch;
        },
        /** Create a new date from a Julian date.
            @memberof MayanCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          jd = Math.floor(jd) + 0.5 - this.jdEpoch;
          var year = Math.floor(jd / 360);
          jd = jd % 360;
          jd += jd < 0 ? 360 : 0;
          var month = Math.floor(jd / 20);
          var day = jd % 20;
          return this.newDate(year, month, day);
        }
      });
      function mod(a, b) {
        return a - b * Math.floor(a / b);
      }
      function amod(a, b) {
        return mod(a - 1, b) + 1;
      }
      main.calendars.mayan = MayanCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/nanakshahi.js
  var require_nanakshahi = __commonJS({
    "node_modules/world-calendars/dist/calendars/nanakshahi.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function NanakshahiCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      NanakshahiCalendar.prototype = new main.baseCalendar();
      var gregorian = main.instance("gregorian");
      assign(NanakshahiCalendar.prototype, {
        /** The calendar name.
            @memberof NanakshahiCalendar */
        name: "Nanakshahi",
        /** Julian date of start of Nanakshahi epoch: 14 March 1469 CE.
            @memberof NanakshahiCalendar */
        jdEpoch: 22576735e-1,
        /** Days per month in a common year.
            @memberof NanakshahiCalendar */
        daysPerMonth: [31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 30],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof NanakshahiCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof NanakshahiCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof NanakshahiCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof NanakshahiCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof NanakshahiCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Nanakshahi",
            epochs: ["BN", "AN"],
            monthNames: [
              "Chet",
              "Vaisakh",
              "Jeth",
              "Harh",
              "Sawan",
              "Bhadon",
              "Assu",
              "Katak",
              "Maghar",
              "Poh",
              "Magh",
              "Phagun"
            ],
            monthNamesShort: ["Che", "Vai", "Jet", "Har", "Saw", "Bha", "Ass", "Kat", "Mgr", "Poh", "Mgh", "Pha"],
            dayNames: ["Somvaar", "Mangalvar", "Budhvaar", "Veervaar", "Shukarvaar", "Sanicharvaar", "Etvaar"],
            dayNamesShort: ["Som", "Mangal", "Budh", "Veer", "Shukar", "Sanichar", "Et"],
            dayNamesMin: ["So", "Ma", "Bu", "Ve", "Sh", "Sa", "Et"],
            digits: null,
            dateFormat: "dd-mm-yyyy",
            firstDay: 0,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof NanakshahiCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(
            year,
            this.minMonth,
            this.minDay,
            main.local.invalidYear || main.regionalOptions[""].invalidYear
          );
          return gregorian.leapYear(date.year() + (date.year() < 1 ? 1 : 0) + 1469);
        },
        /** Determine the week of the year for a date.
            @memberof NanakshahiCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(1 - (checkDate.dayOfWeek() || 7), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a month.
            @memberof NanakshahiCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof NanakshahiCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return (this.dayOfWeek(year, month, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof NanakshahiCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidMonth);
          var year = date.year();
          if (year < 0) {
            year++;
          }
          var doy = date.day();
          for (var m = 1; m < date.month(); m++) {
            doy += this.daysPerMonth[m - 1];
          }
          return doy + gregorian.toJD(year + 1468, 3, 13);
        },
        /** Create a new date from a Julian date.
            @memberof NanakshahiCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          jd = Math.floor(jd + 0.5);
          var year = Math.floor((jd - (this.jdEpoch - 1)) / 366);
          while (jd >= this.toJD(year + 1, 1, 1)) {
            year++;
          }
          var day = jd - Math.floor(this.toJD(year, 1, 1) + 0.5) + 1;
          var month = 1;
          while (day > this.daysInMonth(year, month)) {
            day -= this.daysInMonth(year, month);
            month++;
          }
          return this.newDate(year, month, day);
        }
      });
      main.calendars.nanakshahi = NanakshahiCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/nepali.js
  var require_nepali = __commonJS({
    "node_modules/world-calendars/dist/calendars/nepali.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function NepaliCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      NepaliCalendar.prototype = new main.baseCalendar();
      assign(NepaliCalendar.prototype, {
        /** The calendar name.
            @memberof NepaliCalendar */
        name: "Nepali",
        /** Julian date of start of Nepali epoch: 14 April 57 BCE.
            @memberof NepaliCalendar */
        jdEpoch: 17007095e-1,
        /** Days per month in a common year.
            @memberof NepaliCalendar */
        daysPerMonth: [31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof NepaliCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof NepaliCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof NepaliCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof NepaliCalendar */
        minDay: 1,
        /** The number of days in the year.
            @memberof NepaliCalendar */
        daysPerYear: 365,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof NepaliCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Nepali",
            epochs: ["BBS", "ABS"],
            monthNames: [
              "Baisakh",
              "Jestha",
              "Ashadh",
              "Shrawan",
              "Bhadra",
              "Ashwin",
              "Kartik",
              "Mangsir",
              "Paush",
              "Mangh",
              "Falgun",
              "Chaitra"
            ],
            monthNamesShort: ["Bai", "Je", "As", "Shra", "Bha", "Ash", "Kar", "Mang", "Pau", "Ma", "Fal", "Chai"],
            dayNames: ["Aaitabaar", "Sombaar", "Manglbaar", "Budhabaar", "Bihibaar", "Shukrabaar", "Shanibaar"],
            dayNamesShort: ["Aaita", "Som", "Mangl", "Budha", "Bihi", "Shukra", "Shani"],
            dayNamesMin: ["Aai", "So", "Man", "Bu", "Bi", "Shu", "Sha"],
            digits: null,
            dateFormat: "dd/mm/yyyy",
            firstDay: 1,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof NepaliCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          return this.daysInYear(year) !== this.daysPerYear;
        },
        /** Determine the week of the year for a date.
            @memberof NepaliCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-checkDate.dayOfWeek(), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a year.
            @memberof NepaliCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of days.
            @throws Error if an invalid year or a different calendar used. */
        daysInYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          year = date.year();
          if (typeof this.NEPALI_CALENDAR_DATA[year] === "undefined") {
            return this.daysPerYear;
          }
          var daysPerYear = 0;
          for (var month_number = this.minMonth; month_number <= 12; month_number++) {
            daysPerYear += this.NEPALI_CALENDAR_DATA[year][month_number];
          }
          return daysPerYear;
        },
        /** Retrieve the number of days in a month.
            @memberof NepaliCalendar
            @param year {CDate|number| The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          if (year.year) {
            month = year.month();
            year = year.year();
          }
          this._validate(year, month, this.minDay, main.local.invalidMonth);
          return typeof this.NEPALI_CALENDAR_DATA[year] === "undefined" ? this.daysPerMonth[month - 1] : this.NEPALI_CALENDAR_DATA[year][month];
        },
        /** Determine whether this date is a week day.
            @memberof NepaliCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return this.dayOfWeek(year, month, day) !== 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof NepaliCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(nepaliYear, nepaliMonth, nepaliDay) {
          var date = this._validate(nepaliYear, nepaliMonth, nepaliDay, main.local.invalidDate);
          nepaliYear = date.year();
          nepaliMonth = date.month();
          nepaliDay = date.day();
          var gregorianCalendar = main.instance();
          var gregorianDayOfYear = 0;
          var nepaliMonthToCheck = nepaliMonth;
          var nepaliYearToCheck = nepaliYear;
          this._createMissingCalendarData(nepaliYear);
          var gregorianYear = nepaliYear - (nepaliMonthToCheck > 9 || nepaliMonthToCheck === 9 && nepaliDay >= this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0] ? 56 : 57);
          if (nepaliMonth !== 9) {
            gregorianDayOfYear = nepaliDay;
            nepaliMonthToCheck--;
          }
          while (nepaliMonthToCheck !== 9) {
            if (nepaliMonthToCheck <= 0) {
              nepaliMonthToCheck = 12;
              nepaliYearToCheck--;
            }
            gregorianDayOfYear += this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][nepaliMonthToCheck];
            nepaliMonthToCheck--;
          }
          if (nepaliMonth === 9) {
            gregorianDayOfYear += nepaliDay - this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0];
            if (gregorianDayOfYear < 0) {
              gregorianDayOfYear += gregorianCalendar.daysInYear(gregorianYear);
            }
          } else {
            gregorianDayOfYear += this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][9] - this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0];
          }
          return gregorianCalendar.newDate(gregorianYear, 1, 1).add(gregorianDayOfYear, "d").toJD();
        },
        /** Create a new date from a Julian date.
            @memberof NepaliCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var gregorianCalendar = main.instance();
          var gregorianDate = gregorianCalendar.fromJD(jd);
          var gregorianYear = gregorianDate.year();
          var gregorianDayOfYear = gregorianDate.dayOfYear();
          var nepaliYear = gregorianYear + 56;
          this._createMissingCalendarData(nepaliYear);
          var nepaliMonth = 9;
          var dayOfFirstJanInPaush = this.NEPALI_CALENDAR_DATA[nepaliYear][0];
          var daysSinceJanFirstToEndOfNepaliMonth = this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth] - dayOfFirstJanInPaush + 1;
          while (gregorianDayOfYear > daysSinceJanFirstToEndOfNepaliMonth) {
            nepaliMonth++;
            if (nepaliMonth > 12) {
              nepaliMonth = 1;
              nepaliYear++;
            }
            daysSinceJanFirstToEndOfNepaliMonth += this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth];
          }
          var nepaliDayOfMonth = this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth] - (daysSinceJanFirstToEndOfNepaliMonth - gregorianDayOfYear);
          return this.newDate(nepaliYear, nepaliMonth, nepaliDayOfMonth);
        },
        /** Creates missing data in the NEPALI_CALENDAR_DATA table.
            This data will not be correct but just give an estimated result. Mostly -/+ 1 day
            @private
            @param nepaliYear {number} The missing year number. */
        _createMissingCalendarData: function(nepaliYear) {
          var tmp_calendar_data = this.daysPerMonth.slice(0);
          tmp_calendar_data.unshift(17);
          for (var nepaliYearToCreate = nepaliYear - 1; nepaliYearToCreate < nepaliYear + 2; nepaliYearToCreate++) {
            if (typeof this.NEPALI_CALENDAR_DATA[nepaliYearToCreate] === "undefined") {
              this.NEPALI_CALENDAR_DATA[nepaliYearToCreate] = tmp_calendar_data;
            }
          }
        },
        NEPALI_CALENDAR_DATA: {
          // These data are from http://www.ashesh.com.np
          1970: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1971: [18, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
          1972: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
          1973: [19, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          1974: [19, 31, 31, 32, 30, 31, 31, 30, 29, 30, 29, 30, 30],
          1975: [18, 31, 31, 32, 32, 30, 31, 30, 29, 30, 29, 30, 30],
          1976: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          1977: [18, 31, 32, 31, 32, 31, 31, 29, 30, 29, 30, 29, 31],
          1978: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1979: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          1980: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          1981: [18, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
          1982: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1983: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          1984: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          1985: [18, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
          1986: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1987: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          1988: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          1989: [18, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          1990: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1991: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          // These data are from http://nepalicalendar.rat32.com/index.php
          1992: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          1993: [18, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          1994: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1995: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
          1996: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          1997: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1998: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          1999: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2e3: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2001: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2002: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2003: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2004: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2005: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2006: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2007: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2008: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
          2009: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2010: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2011: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2012: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
          2013: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2014: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2015: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2016: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
          2017: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2018: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2019: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2020: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          2021: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2022: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
          2023: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2024: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          2025: [18, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2026: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2027: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2028: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2029: [18, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
          2030: [17, 31, 32, 31, 32, 31, 30, 30, 30, 30, 30, 30, 31],
          2031: [17, 31, 32, 31, 32, 31, 31, 31, 31, 31, 31, 31, 31],
          2032: [17, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32],
          2033: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2034: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2035: [17, 30, 32, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
          2036: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2037: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2038: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2039: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
          2040: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2041: [18, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2042: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2043: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
          2044: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2045: [18, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2046: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2047: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          2048: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2049: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
          2050: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2051: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          2052: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2053: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
          2054: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2055: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 30, 29, 30],
          2056: [17, 31, 31, 32, 31, 32, 30, 30, 29, 30, 29, 30, 30],
          2057: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2058: [17, 30, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2059: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2060: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2061: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2062: [17, 30, 32, 31, 32, 31, 31, 29, 30, 29, 30, 29, 31],
          2063: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2064: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2065: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2066: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 29, 31],
          2067: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2068: [17, 31, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2069: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2070: [17, 31, 31, 31, 32, 31, 31, 29, 30, 30, 29, 30, 30],
          2071: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2072: [17, 31, 32, 31, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2073: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 31],
          2074: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          2075: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2076: [16, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
          2077: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 29, 31],
          2078: [17, 31, 31, 31, 32, 31, 31, 30, 29, 30, 29, 30, 30],
          2079: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 29, 30, 30],
          2080: [16, 31, 32, 31, 32, 31, 30, 30, 30, 29, 29, 30, 30],
          // These data are from http://www.ashesh.com.np/nepali-calendar/
          2081: [17, 31, 31, 32, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2082: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2083: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
          2084: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
          2085: [17, 31, 32, 31, 32, 31, 31, 30, 30, 29, 30, 30, 30],
          2086: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2087: [16, 31, 31, 32, 31, 31, 31, 30, 30, 29, 30, 30, 30],
          2088: [16, 30, 31, 32, 32, 30, 31, 30, 30, 29, 30, 30, 30],
          2089: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2090: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2091: [16, 31, 31, 32, 31, 31, 31, 30, 30, 29, 30, 30, 30],
          2092: [16, 31, 31, 32, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2093: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2094: [17, 31, 31, 32, 31, 31, 30, 30, 30, 29, 30, 30, 30],
          2095: [17, 31, 31, 32, 31, 31, 31, 30, 29, 30, 30, 30, 30],
          2096: [17, 30, 31, 32, 32, 31, 30, 30, 29, 30, 29, 30, 30],
          2097: [17, 31, 32, 31, 32, 31, 30, 30, 30, 29, 30, 30, 30],
          2098: [17, 31, 31, 32, 31, 31, 31, 29, 30, 29, 30, 30, 31],
          2099: [17, 31, 31, 32, 31, 31, 31, 30, 29, 29, 30, 30, 30],
          2100: [17, 31, 32, 31, 32, 30, 31, 30, 29, 30, 29, 30, 30]
        }
      });
      main.calendars.nepali = NepaliCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/persian.js
  var require_persian = __commonJS({
    "node_modules/world-calendars/dist/calendars/persian.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function PersianCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      function _leapYear(year) {
        var x = year - 475;
        if (year < 0) x++;
        var c = 0.242197;
        var v0 = c * x;
        var v1 = c * (x + 1);
        var r0 = v0 - Math.floor(v0);
        var r1 = v1 - Math.floor(v1);
        return r0 > r1;
      }
      PersianCalendar.prototype = new main.baseCalendar();
      assign(PersianCalendar.prototype, {
        /** The calendar name.
            @memberof PersianCalendar */
        name: "Persian",
        /** Julian date of start of Persian epoch: 19 March 622 CE.
            @memberof PersianCalendar */
        jdEpoch: 19483205e-1,
        /** Days per month in a common year.
            @memberof PersianCalendar */
        daysPerMonth: [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof PersianCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof PersianCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof PersianCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof PersianCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof PersianCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Persian",
            epochs: ["BP", "AP"],
            monthNames: [
              "Farvardin",
              "Ordibehesht",
              "Khordad",
              "Tir",
              "Mordad",
              "Shahrivar",
              "Mehr",
              "Aban",
              "Azar",
              "Dey",
              "Bahman",
              "Esfand"
            ],
            monthNamesShort: ["Far", "Ord", "Kho", "Tir", "Mor", "Sha", "Meh", "Aba", "Aza", "Dey", "Bah", "Esf"],
            dayNames: ["Yekshanbeh", "Doshanbeh", "Seshanbeh", "Chah\u0101rshanbeh", "Panjshanbeh", "Jom'eh", "Shanbeh"],
            dayNamesShort: ["Yek", "Do", "Se", "Cha", "Panj", "Jom", "Sha"],
            dayNamesMin: ["Ye", "Do", "Se", "Ch", "Pa", "Jo", "Sh"],
            digits: null,
            dateFormat: "yyyy/mm/dd",
            firstDay: 6,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof PersianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return _leapYear(date.year());
        },
        /** Determine the week of the year for a date.
            @memberof PersianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-((checkDate.dayOfWeek() + 1) % 7), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a month.
            @memberof PersianCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof PersianCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return this.dayOfWeek(year, month, day) !== 5;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof PersianCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          year = date.year();
          month = date.month();
          day = date.day();
          var nLeapYearsSince = 0;
          if (year > 0) {
            for (var i = 1; i < year; i++) {
              if (_leapYear(i)) nLeapYearsSince++;
            }
          } else if (year < 0) {
            for (var i = year; i < 0; i++) {
              if (_leapYear(i)) nLeapYearsSince--;
            }
          }
          return day + (month <= 7 ? (month - 1) * 31 : (month - 1) * 30 + 6) + (year > 0 ? year - 1 : year) * 365 + nLeapYearsSince + this.jdEpoch - 1;
        },
        /** Create a new date from a Julian date.
            @memberof PersianCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          jd = Math.floor(jd) + 0.5;
          var y = 475 + (jd - this.toJD(475, 1, 1)) / 365.242197;
          var year = Math.floor(y);
          if (year <= 0) year--;
          if (jd > this.toJD(year, 12, _leapYear(year) ? 30 : 29)) {
            year++;
            if (year === 0) year++;
          }
          var yday = jd - this.toJD(year, 1, 1) + 1;
          var month = yday <= 186 ? Math.ceil(yday / 31) : Math.ceil((yday - 6) / 30);
          var day = jd - this.toJD(year, month, 1) + 1;
          return this.newDate(year, month, day);
        }
      });
      main.calendars.persian = PersianCalendar;
      main.calendars.jalali = PersianCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/taiwan.js
  var require_taiwan = __commonJS({
    "node_modules/world-calendars/dist/calendars/taiwan.js"() {
      var main = require_main();
      var assign = require_object_assign();
      var gregorianCalendar = main.instance();
      function TaiwanCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      TaiwanCalendar.prototype = new main.baseCalendar();
      assign(TaiwanCalendar.prototype, {
        /** The calendar name.
            @memberof TaiwanCalendar */
        name: "Taiwan",
        /** Julian date of start of Taiwan epoch: 1 January 1912 CE (Gregorian).
            @memberof TaiwanCalendar */
        jdEpoch: 24194025e-1,
        /** Difference in years between Taiwan and Gregorian calendars.
            @memberof TaiwanCalendar */
        yearsOffset: 1911,
        /** Days per month in a common year.
            @memberof TaiwanCalendar */
        daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof TaiwanCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof TaiwanCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof TaiwanCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof TaiwanCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof TaiwanCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Taiwan",
            epochs: ["BROC", "ROC"],
            monthNames: [
              "January",
              "February",
              "March",
              "April",
              "May",
              "June",
              "July",
              "August",
              "September",
              "October",
              "November",
              "December"
            ],
            monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
            dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            digits: null,
            dateFormat: "yyyy/mm/dd",
            firstDay: 1,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof TaiwanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          var year = this._t2gYear(date.year());
          return gregorianCalendar.leapYear(year);
        },
        /** Determine the week of the year for a date - ISO 8601.
            @memberof TaiwanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          var year = this._t2gYear(date.year());
          return gregorianCalendar.weekOfYear(year, date.month(), date.day());
        },
        /** Retrieve the number of days in a month.
            @memberof TaiwanCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof TaiwanCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return (this.dayOfWeek(year, month, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof TaiwanCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          var year = this._t2gYear(date.year());
          return gregorianCalendar.toJD(year, date.month(), date.day());
        },
        /** Create a new date from a Julian date.
            @memberof TaiwanCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var date = gregorianCalendar.fromJD(jd);
          var year = this._g2tYear(date.year());
          return this.newDate(year, date.month(), date.day());
        },
        /** Convert Taiwanese to Gregorian year.
            @memberof TaiwanCalendar
            @private
            @param year {number} The Taiwanese year.
            @return {number} The corresponding Gregorian year. */
        _t2gYear: function(year) {
          return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0);
        },
        /** Convert Gregorian to Taiwanese year.
            @memberof TaiwanCalendar
            @private
            @param year {number} The Gregorian year.
            @return {number} The corresponding Taiwanese year. */
        _g2tYear: function(year) {
          return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0);
        }
      });
      main.calendars.taiwan = TaiwanCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/thai.js
  var require_thai = __commonJS({
    "node_modules/world-calendars/dist/calendars/thai.js"() {
      var main = require_main();
      var assign = require_object_assign();
      var gregorianCalendar = main.instance();
      function ThaiCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      ThaiCalendar.prototype = new main.baseCalendar();
      assign(ThaiCalendar.prototype, {
        /** The calendar name.
            @memberof ThaiCalendar */
        name: "Thai",
        /** Julian date of start of Thai epoch: 1 January 543 BCE (Gregorian).
            @memberof ThaiCalendar */
        jdEpoch: 15230985e-1,
        /** Difference in years between Thai and Gregorian calendars.
            @memberof ThaiCalendar */
        yearsOffset: 543,
        /** Days per month in a common year.
            @memberof ThaiCalendar */
        daysPerMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof ThaiCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof ThaiCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof ThaiCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof ThaiCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof ThaiCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Thai",
            epochs: ["BBE", "BE"],
            monthNames: [
              "January",
              "February",
              "March",
              "April",
              "May",
              "June",
              "July",
              "August",
              "September",
              "October",
              "November",
              "December"
            ],
            monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
            dayNamesMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
            digits: null,
            dateFormat: "dd/mm/yyyy",
            firstDay: 0,
            isRTL: false
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof ThaiCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          var year = this._t2gYear(date.year());
          return gregorianCalendar.leapYear(year);
        },
        /** Determine the week of the year for a date - ISO 8601.
            @memberof ThaiCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          var year = this._t2gYear(date.year());
          return gregorianCalendar.weekOfYear(year, date.month(), date.day());
        },
        /** Retrieve the number of days in a month.
            @memberof ThaiCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0);
        },
        /** Determine whether this date is a week day.
            @memberof ThaiCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return (this.dayOfWeek(year, month, day) || 7) < 6;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof ThaiCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          var year = this._t2gYear(date.year());
          return gregorianCalendar.toJD(year, date.month(), date.day());
        },
        /** Create a new date from a Julian date.
            @memberof ThaiCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var date = gregorianCalendar.fromJD(jd);
          var year = this._g2tYear(date.year());
          return this.newDate(year, date.month(), date.day());
        },
        /** Convert Thai to Gregorian year.
            @memberof ThaiCalendar
            @private
            @param year {number} The Thai year.
            @return {number} The corresponding Gregorian year. */
        _t2gYear: function(year) {
          return year - this.yearsOffset - (year >= 1 && year <= this.yearsOffset ? 1 : 0);
        },
        /** Convert Gregorian to Thai year.
            @memberof ThaiCalendar
            @private
            @param year {number} The Gregorian year.
            @return {number} The corresponding Thai year. */
        _g2tYear: function(year) {
          return year + this.yearsOffset + (year >= -this.yearsOffset && year <= -1 ? 1 : 0);
        }
      });
      main.calendars.thai = ThaiCalendar;
    }
  });

  // node_modules/world-calendars/dist/calendars/ummalqura.js
  var require_ummalqura = __commonJS({
    "node_modules/world-calendars/dist/calendars/ummalqura.js"() {
      var main = require_main();
      var assign = require_object_assign();
      function UmmAlQuraCalendar(language) {
        this.local = this.regionalOptions[language || ""] || this.regionalOptions[""];
      }
      UmmAlQuraCalendar.prototype = new main.baseCalendar();
      assign(UmmAlQuraCalendar.prototype, {
        /** The calendar name.
            @memberof UmmAlQuraCalendar */
        name: "UmmAlQura",
        //jdEpoch: 1948440, // Julian date of start of UmmAlQura epoch: 14 March 1937 CE
        //daysPerMonth: // Days per month in a common year, replaced by a method.
        /** <code>true</code> if has a year zero, <code>false</code> if not.
            @memberof UmmAlQuraCalendar */
        hasYearZero: false,
        /** The minimum month number.
            @memberof UmmAlQuraCalendar */
        minMonth: 1,
        /** The first month in the year.
            @memberof UmmAlQuraCalendar */
        firstMonth: 1,
        /** The minimum day number.
            @memberof UmmAlQuraCalendar */
        minDay: 1,
        /** Localisations for the plugin.
            Entries are objects indexed by the language code ('' being the default US/English).
            Each object has the following attributes.
            @memberof UmmAlQuraCalendar
            @property name {string} The calendar name.
            @property epochs {string[]} The epoch names.
            @property monthNames {string[]} The long names of the months of the year.
            @property monthNamesShort {string[]} The short names of the months of the year.
            @property dayNames {string[]} The long names of the days of the week.
            @property dayNamesShort {string[]} The short names of the days of the week.
            @property dayNamesMin {string[]} The minimal names of the days of the week.
            @property dateFormat {string} The date format for this calendar.
                    See the options on <a href="BaseCalendar.html#formatDate"><code>formatDate</code></a> for details.
            @property firstDay {number} The number of the first day of the week, starting at 0.
            @property isRTL {number} <code>true</code> if this localisation reads right-to-left. */
        regionalOptions: {
          // Localisations
          "": {
            name: "Umm al-Qura",
            epochs: ["BH", "AH"],
            monthNames: [
              "Al-Muharram",
              "Safar",
              "Rabi' al-awwal",
              "Rabi' Al-Thani",
              "Jumada Al-Awwal",
              "Jumada Al-Thani",
              "Rajab",
              "Sha'aban",
              "Ramadan",
              "Shawwal",
              "Dhu al-Qi'dah",
              "Dhu al-Hijjah"
            ],
            monthNamesShort: ["Muh", "Saf", "Rab1", "Rab2", "Jum1", "Jum2", "Raj", "Sha'", "Ram", "Shaw", "DhuQ", "DhuH"],
            dayNames: ["Yawm al-Ahad", "Yawm al-Ithnain", "Yawm al-Thal\u0101th\u0101\u2019", "Yawm al-Arba\u2018\u0101\u2019", "Yawm al-Kham\u012Bs", "Yawm al-Jum\u2018a", "Yawm al-Sabt"],
            dayNamesMin: ["Ah", "Ith", "Th", "Ar", "Kh", "Ju", "Sa"],
            digits: null,
            dateFormat: "yyyy/mm/dd",
            firstDay: 6,
            isRTL: true
          }
        },
        /** Determine whether this date is in a leap year.
            @memberof UmmAlQuraCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {boolean} <code>true</code> if this is a leap year, <code>false</code> if not.
            @throws Error if an invalid year or a different calendar used. */
        leapYear: function(year) {
          var date = this._validate(year, this.minMonth, this.minDay, main.local.invalidYear);
          return this.daysInYear(date.year()) === 355;
        },
        /** Determine the week of the year for a date.
            @memberof UmmAlQuraCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {number} The week of the year.
            @throws Error if an invalid date or a different calendar used. */
        weekOfYear: function(year, month, day) {
          var checkDate = this.newDate(year, month, day);
          checkDate.add(-checkDate.dayOfWeek(), "d");
          return Math.floor((checkDate.dayOfYear() - 1) / 7) + 1;
        },
        /** Retrieve the number of days in a year.
            @memberof UmmAlQuraCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @return {number} The number of days.
            @throws Error if an invalid year or a different calendar used. */
        daysInYear: function(year) {
          var daysCount = 0;
          for (var i = 1; i <= 12; i++) {
            daysCount += this.daysInMonth(year, i);
          }
          return daysCount;
        },
        /** Retrieve the number of days in a month.
            @memberof UmmAlQuraCalendar
            @param year {CDate|number} The date to examine or the year of the month.
            @param [month] {number} The month.
            @return {number} The number of days in this month.
            @throws Error if an invalid month/year or a different calendar used. */
        daysInMonth: function(year, month) {
          var date = this._validate(year, month, this.minDay, main.local.invalidMonth);
          var mcjdn = date.toJD() - 24e5 + 0.5;
          var index = 0;
          for (var i = 0; i < ummalqura_dat.length; i++) {
            if (ummalqura_dat[i] > mcjdn) {
              return ummalqura_dat[index] - ummalqura_dat[index - 1];
            }
            index++;
          }
          return 30;
        },
        /** Determine whether this date is a week day.
            @memberof UmmAlQuraCalendar
            @param year {CDate|number} The date to examine or the year to examine.
            @param [month] {number} The month to examine.
            @param [day] {number} The day to examine.
            @return {boolean} <code>true</code> if a week day, <code>false</code> if not.
            @throws Error if an invalid date or a different calendar used. */
        weekDay: function(year, month, day) {
          return this.dayOfWeek(year, month, day) !== 5;
        },
        /** Retrieve the Julian date equivalent for this date,
            i.e. days since January 1, 4713 BCE Greenwich noon.
            @memberof UmmAlQuraCalendar
            @param year {CDate|number} The date to convert or the year to convert.
            @param [month] {number} The month to convert.
            @param [day] {number} The day to convert.
            @return {number} The equivalent Julian date.
            @throws Error if an invalid date or a different calendar used. */
        toJD: function(year, month, day) {
          var date = this._validate(year, month, day, main.local.invalidDate);
          var index = 12 * (date.year() - 1) + date.month() - 15292;
          var mcjdn = date.day() + ummalqura_dat[index - 1] - 1;
          return mcjdn + 24e5 - 0.5;
        },
        /** Create a new date from a Julian date.
            @memberof UmmAlQuraCalendar
            @param jd {number} The Julian date to convert.
            @return {CDate} The equivalent date. */
        fromJD: function(jd) {
          var mcjdn = jd - 24e5 + 0.5;
          var index = 0;
          for (var i = 0; i < ummalqura_dat.length; i++) {
            if (ummalqura_dat[i] > mcjdn) break;
            index++;
          }
          var lunation = index + 15292;
          var ii = Math.floor((lunation - 1) / 12);
          var year = ii + 1;
          var month = lunation - 12 * ii;
          var day = mcjdn - ummalqura_dat[index - 1] + 1;
          return this.newDate(year, month, day);
        },
        /** Determine whether a date is valid for this calendar.
            @memberof UmmAlQuraCalendar
            @param year {number} The year to examine.
            @param month {number} The month to examine.
            @param day {number} The day to examine.
            @return {boolean} <code>true</code> if a valid date, <code>false</code> if not. */
        isValid: function(year, month, day) {
          var valid = main.baseCalendar.prototype.isValid.apply(this, arguments);
          if (valid) {
            year = year.year != null ? year.year : year;
            valid = year >= 1276 && year <= 1500;
          }
          return valid;
        },
        /** Check that a candidate date is from the same calendar and is valid.
            @memberof UmmAlQuraCalendar
            @private
            @param year {CDate|number} The date to validate or the year to validate.
            @param month {number} The month to validate.
            @param day {number} The day to validate.
            @param error {string} Error message if invalid.
            @throws Error if different calendars used or invalid date. */
        _validate: function(year, month, day, error) {
          var date = main.baseCalendar.prototype._validate.apply(this, arguments);
          if (date.year < 1276 || date.year > 1500) {
            throw error.replace(/\{0\}/, this.local.name);
          }
          return date;
        }
      });
      main.calendars.ummalqura = UmmAlQuraCalendar;
      var ummalqura_dat = [
        20,
        50,
        79,
        109,
        138,
        168,
        197,
        227,
        256,
        286,
        315,
        345,
        374,
        404,
        433,
        463,
        492,
        522,
        551,
        581,
        611,
        641,
        670,
        700,
        729,
        759,
        788,
        818,
        847,
        877,
        906,
        936,
        965,
        995,
        1024,
        1054,
        1083,
        1113,
        1142,
        1172,
        1201,
        1231,
        1260,
        1290,
        1320,
        1350,
        1379,
        1409,
        1438,
        1468,
        1497,
        1527,
        1556,
        1586,
        1615,
        1645,
        1674,
        1704,
        1733,
        1763,
        1792,
        1822,
        1851,
        1881,
        1910,
        1940,
        1969,
        1999,
        2028,
        2058,
        2087,
        2117,
        2146,
        2176,
        2205,
        2235,
        2264,
        2294,
        2323,
        2353,
        2383,
        2413,
        2442,
        2472,
        2501,
        2531,
        2560,
        2590,
        2619,
        2649,
        2678,
        2708,
        2737,
        2767,
        2796,
        2826,
        2855,
        2885,
        2914,
        2944,
        2973,
        3003,
        3032,
        3062,
        3091,
        3121,
        3150,
        3180,
        3209,
        3239,
        3268,
        3298,
        3327,
        3357,
        3386,
        3416,
        3446,
        3476,
        3505,
        3535,
        3564,
        3594,
        3623,
        3653,
        3682,
        3712,
        3741,
        3771,
        3800,
        3830,
        3859,
        3889,
        3918,
        3948,
        3977,
        4007,
        4036,
        4066,
        4095,
        4125,
        4155,
        4185,
        4214,
        4244,
        4273,
        4303,
        4332,
        4362,
        4391,
        4421,
        4450,
        4480,
        4509,
        4539,
        4568,
        4598,
        4627,
        4657,
        4686,
        4716,
        4745,
        4775,
        4804,
        4834,
        4863,
        4893,
        4922,
        4952,
        4981,
        5011,
        5040,
        5070,
        5099,
        5129,
        5158,
        5188,
        5218,
        5248,
        5277,
        5307,
        5336,
        5366,
        5395,
        5425,
        5454,
        5484,
        5513,
        5543,
        5572,
        5602,
        5631,
        5661,
        5690,
        5720,
        5749,
        5779,
        5808,
        5838,
        5867,
        5897,
        5926,
        5956,
        5985,
        6015,
        6044,
        6074,
        6103,
        6133,
        6162,
        6192,
        6221,
        6251,
        6281,
        6311,
        6340,
        6370,
        6399,
        6429,
        6458,
        6488,
        6517,
        6547,
        6576,
        6606,
        6635,
        6665,
        6694,
        6724,
        6753,
        6783,
        6812,
        6842,
        6871,
        6901,
        6930,
        6960,
        6989,
        7019,
        7048,
        7078,
        7107,
        7137,
        7166,
        7196,
        7225,
        7255,
        7284,
        7314,
        7344,
        7374,
        7403,
        7433,
        7462,
        7492,
        7521,
        7551,
        7580,
        7610,
        7639,
        7669,
        7698,
        7728,
        7757,
        7787,
        7816,
        7846,
        7875,
        7905,
        7934,
        7964,
        7993,
        8023,
        8053,
        8083,
        8112,
        8142,
        8171,
        8201,
        8230,
        8260,
        8289,
        8319,
        8348,
        8378,
        8407,
        8437,
        8466,
        8496,
        8525,
        8555,
        8584,
        8614,
        8643,
        8673,
        8702,
        8732,
        8761,
        8791,
        8821,
        8850,
        8880,
        8909,
        8938,
        8968,
        8997,
        9027,
        9056,
        9086,
        9115,
        9145,
        9175,
        9205,
        9234,
        9264,
        9293,
        9322,
        9352,
        9381,
        9410,
        9440,
        9470,
        9499,
        9529,
        9559,
        9589,
        9618,
        9648,
        9677,
        9706,
        9736,
        9765,
        9794,
        9824,
        9853,
        9883,
        9913,
        9943,
        9972,
        10002,
        10032,
        10061,
        10090,
        10120,
        10149,
        10178,
        10208,
        10237,
        10267,
        10297,
        10326,
        10356,
        10386,
        10415,
        10445,
        10474,
        10504,
        10533,
        10562,
        10592,
        10621,
        10651,
        10680,
        10710,
        10740,
        10770,
        10799,
        10829,
        10858,
        10888,
        10917,
        10947,
        10976,
        11005,
        11035,
        11064,
        11094,
        11124,
        11153,
        11183,
        11213,
        11242,
        11272,
        11301,
        11331,
        11360,
        11389,
        11419,
        11448,
        11478,
        11507,
        11537,
        11567,
        11596,
        11626,
        11655,
        11685,
        11715,
        11744,
        11774,
        11803,
        11832,
        11862,
        11891,
        11921,
        11950,
        11980,
        12010,
        12039,
        12069,
        12099,
        12128,
        12158,
        12187,
        12216,
        12246,
        12275,
        12304,
        12334,
        12364,
        12393,
        12423,
        12453,
        12483,
        12512,
        12542,
        12571,
        12600,
        12630,
        12659,
        12688,
        12718,
        12747,
        12777,
        12807,
        12837,
        12866,
        12896,
        12926,
        12955,
        12984,
        13014,
        13043,
        13072,
        13102,
        13131,
        13161,
        13191,
        13220,
        13250,
        13280,
        13310,
        13339,
        13368,
        13398,
        13427,
        13456,
        13486,
        13515,
        13545,
        13574,
        13604,
        13634,
        13664,
        13693,
        13723,
        13752,
        13782,
        13811,
        13840,
        13870,
        13899,
        13929,
        13958,
        13988,
        14018,
        14047,
        14077,
        14107,
        14136,
        14166,
        14195,
        14224,
        14254,
        14283,
        14313,
        14342,
        14372,
        14401,
        14431,
        14461,
        14490,
        14520,
        14550,
        14579,
        14609,
        14638,
        14667,
        14697,
        14726,
        14756,
        14785,
        14815,
        14844,
        14874,
        14904,
        14933,
        14963,
        14993,
        15021,
        15051,
        15081,
        15110,
        15140,
        15169,
        15199,
        15228,
        15258,
        15287,
        15317,
        15347,
        15377,
        15406,
        15436,
        15465,
        15494,
        15524,
        15553,
        15582,
        15612,
        15641,
        15671,
        15701,
        15731,
        15760,
        15790,
        15820,
        15849,
        15878,
        15908,
        15937,
        15966,
        15996,
        16025,
        16055,
        16085,
        16114,
        16144,
        16174,
        16204,
        16233,
        16262,
        16292,
        16321,
        16350,
        16380,
        16409,
        16439,
        16468,
        16498,
        16528,
        16558,
        16587,
        16617,
        16646,
        16676,
        16705,
        16734,
        16764,
        16793,
        16823,
        16852,
        16882,
        16912,
        16941,
        16971,
        17001,
        17030,
        17060,
        17089,
        17118,
        17148,
        17177,
        17207,
        17236,
        17266,
        17295,
        17325,
        17355,
        17384,
        17414,
        17444,
        17473,
        17502,
        17532,
        17561,
        17591,
        17620,
        17650,
        17679,
        17709,
        17738,
        17768,
        17798,
        17827,
        17857,
        17886,
        17916,
        17945,
        17975,
        18004,
        18034,
        18063,
        18093,
        18122,
        18152,
        18181,
        18211,
        18241,
        18270,
        18300,
        18330,
        18359,
        18388,
        18418,
        18447,
        18476,
        18506,
        18535,
        18565,
        18595,
        18625,
        18654,
        18684,
        18714,
        18743,
        18772,
        18802,
        18831,
        18860,
        18890,
        18919,
        18949,
        18979,
        19008,
        19038,
        19068,
        19098,
        19127,
        19156,
        19186,
        19215,
        19244,
        19274,
        19303,
        19333,
        19362,
        19392,
        19422,
        19452,
        19481,
        19511,
        19540,
        19570,
        19599,
        19628,
        19658,
        19687,
        19717,
        19746,
        19776,
        19806,
        19836,
        19865,
        19895,
        19924,
        19954,
        19983,
        20012,
        20042,
        20071,
        20101,
        20130,
        20160,
        20190,
        20219,
        20249,
        20279,
        20308,
        20338,
        20367,
        20396,
        20426,
        20455,
        20485,
        20514,
        20544,
        20573,
        20603,
        20633,
        20662,
        20692,
        20721,
        20751,
        20780,
        20810,
        20839,
        20869,
        20898,
        20928,
        20957,
        20987,
        21016,
        21046,
        21076,
        21105,
        21135,
        21164,
        21194,
        21223,
        21253,
        21282,
        21312,
        21341,
        21371,
        21400,
        21430,
        21459,
        21489,
        21519,
        21548,
        21578,
        21607,
        21637,
        21666,
        21696,
        21725,
        21754,
        21784,
        21813,
        21843,
        21873,
        21902,
        21932,
        21962,
        21991,
        22021,
        22050,
        22080,
        22109,
        22138,
        22168,
        22197,
        22227,
        22256,
        22286,
        22316,
        22346,
        22375,
        22405,
        22434,
        22464,
        22493,
        22522,
        22552,
        22581,
        22611,
        22640,
        22670,
        22700,
        22730,
        22759,
        22789,
        22818,
        22848,
        22877,
        22906,
        22936,
        22965,
        22994,
        23024,
        23054,
        23083,
        23113,
        23143,
        23173,
        23202,
        23232,
        23261,
        23290,
        23320,
        23349,
        23379,
        23408,
        23438,
        23467,
        23497,
        23527,
        23556,
        23586,
        23616,
        23645,
        23674,
        23704,
        23733,
        23763,
        23792,
        23822,
        23851,
        23881,
        23910,
        23940,
        23970,
        23999,
        24029,
        24058,
        24088,
        24117,
        24147,
        24176,
        24206,
        24235,
        24265,
        24294,
        24324,
        24353,
        24383,
        24413,
        24442,
        24472,
        24501,
        24531,
        24560,
        24590,
        24619,
        24648,
        24678,
        24707,
        24737,
        24767,
        24796,
        24826,
        24856,
        24885,
        24915,
        24944,
        24974,
        25003,
        25032,
        25062,
        25091,
        25121,
        25150,
        25180,
        25210,
        25240,
        25269,
        25299,
        25328,
        25358,
        25387,
        25416,
        25446,
        25475,
        25505,
        25534,
        25564,
        25594,
        25624,
        25653,
        25683,
        25712,
        25742,
        25771,
        25800,
        25830,
        25859,
        25888,
        25918,
        25948,
        25977,
        26007,
        26037,
        26067,
        26096,
        26126,
        26155,
        26184,
        26214,
        26243,
        26272,
        26302,
        26332,
        26361,
        26391,
        26421,
        26451,
        26480,
        26510,
        26539,
        26568,
        26598,
        26627,
        26656,
        26686,
        26715,
        26745,
        26775,
        26805,
        26834,
        26864,
        26893,
        26923,
        26952,
        26982,
        27011,
        27041,
        27070,
        27099,
        27129,
        27159,
        27188,
        27218,
        27248,
        27277,
        27307,
        27336,
        27366,
        27395,
        27425,
        27454,
        27484,
        27513,
        27542,
        27572,
        27602,
        27631,
        27661,
        27691,
        27720,
        27750,
        27779,
        27809,
        27838,
        27868,
        27897,
        27926,
        27956,
        27985,
        28015,
        28045,
        28074,
        28104,
        28134,
        28163,
        28193,
        28222,
        28252,
        28281,
        28310,
        28340,
        28369,
        28399,
        28428,
        28458,
        28488,
        28517,
        28547,
        28577,
        // From 1356
        28607,
        28636,
        28665,
        28695,
        28724,
        28754,
        28783,
        28813,
        28843,
        28872,
        28901,
        28931,
        28960,
        28990,
        29019,
        29049,
        29078,
        29108,
        29137,
        29167,
        29196,
        29226,
        29255,
        29285,
        29315,
        29345,
        29375,
        29404,
        29434,
        29463,
        29492,
        29522,
        29551,
        29580,
        29610,
        29640,
        29669,
        29699,
        29729,
        29759,
        29788,
        29818,
        29847,
        29876,
        29906,
        29935,
        29964,
        29994,
        30023,
        30053,
        30082,
        30112,
        30141,
        30171,
        30200,
        30230,
        30259,
        30289,
        30318,
        30348,
        30378,
        30408,
        30437,
        30467,
        30496,
        30526,
        30555,
        30585,
        30614,
        30644,
        30673,
        30703,
        30732,
        30762,
        30791,
        30821,
        30850,
        30880,
        30909,
        30939,
        30968,
        30998,
        31027,
        31057,
        31086,
        31116,
        31145,
        31175,
        31204,
        31234,
        31263,
        31293,
        31322,
        31352,
        31381,
        31411,
        31441,
        31471,
        31500,
        31530,
        31559,
        31589,
        31618,
        31648,
        31676,
        31706,
        31736,
        31766,
        31795,
        31825,
        31854,
        31884,
        31913,
        31943,
        31972,
        32002,
        32031,
        32061,
        32090,
        32120,
        32150,
        32180,
        32209,
        32239,
        32268,
        32298,
        32327,
        32357,
        32386,
        32416,
        32445,
        32475,
        32504,
        32534,
        32563,
        32593,
        32622,
        32652,
        32681,
        32711,
        32740,
        32770,
        32799,
        32829,
        32858,
        32888,
        32917,
        32947,
        32976,
        33006,
        33035,
        33065,
        33094,
        33124,
        33153,
        33183,
        33213,
        33243,
        33272,
        33302,
        33331,
        33361,
        33390,
        33420,
        33450,
        33479,
        33509,
        33539,
        33568,
        33598,
        33627,
        33657,
        33686,
        33716,
        33745,
        33775,
        33804,
        33834,
        33863,
        33893,
        33922,
        33952,
        33981,
        34011,
        34040,
        34069,
        34099,
        34128,
        34158,
        34187,
        34217,
        34247,
        34277,
        34306,
        34336,
        34365,
        34395,
        34424,
        34454,
        34483,
        34512,
        34542,
        34571,
        34601,
        34631,
        34660,
        34690,
        34719,
        34749,
        34778,
        34808,
        34837,
        34867,
        34896,
        34926,
        34955,
        34985,
        35015,
        35044,
        35074,
        35103,
        35133,
        35162,
        35192,
        35222,
        35251,
        35280,
        35310,
        35340,
        35370,
        35399,
        35429,
        35458,
        35488,
        35517,
        35547,
        35576,
        35605,
        35635,
        35665,
        35694,
        35723,
        35753,
        35782,
        35811,
        35841,
        35871,
        35901,
        35930,
        35960,
        35989,
        36019,
        36048,
        36078,
        36107,
        36136,
        36166,
        36195,
        36225,
        36254,
        36284,
        36314,
        36343,
        36373,
        36403,
        36433,
        36462,
        36492,
        36521,
        36551,
        36580,
        36610,
        36639,
        36669,
        36698,
        36728,
        36757,
        36786,
        36816,
        36845,
        36875,
        36904,
        36934,
        36963,
        36993,
        37022,
        37052,
        37081,
        37111,
        37141,
        37170,
        37200,
        37229,
        37259,
        37288,
        37318,
        37347,
        37377,
        37406,
        37436,
        37465,
        37495,
        37524,
        37554,
        37584,
        37613,
        37643,
        37672,
        37701,
        37731,
        37760,
        37790,
        37819,
        37849,
        37878,
        37908,
        37938,
        37967,
        37997,
        38027,
        38056,
        38085,
        38115,
        38144,
        38174,
        38203,
        38233,
        38262,
        38292,
        38322,
        38351,
        38381,
        38410,
        38440,
        38469,
        38499,
        38528,
        38558,
        38587,
        38617,
        38646,
        38676,
        38705,
        38735,
        38764,
        38794,
        38823,
        38853,
        38882,
        38912,
        38941,
        38971,
        39001,
        39030,
        39059,
        39089,
        39118,
        39148,
        39178,
        39208,
        39237,
        39267,
        39297,
        39326,
        39355,
        39385,
        39414,
        39444,
        39473,
        39503,
        39532,
        39562,
        39592,
        39621,
        39650,
        39680,
        39709,
        39739,
        39768,
        39798,
        39827,
        39857,
        39886,
        39916,
        39946,
        39975,
        40005,
        40035,
        40064,
        40094,
        40123,
        40153,
        40182,
        40212,
        40241,
        40271,
        40300,
        40330,
        40359,
        40389,
        40418,
        40448,
        40477,
        40507,
        40536,
        40566,
        40595,
        40625,
        40655,
        40685,
        40714,
        40744,
        40773,
        40803,
        40832,
        40862,
        40892,
        40921,
        40951,
        40980,
        41009,
        41039,
        41068,
        41098,
        41127,
        41157,
        41186,
        41216,
        41245,
        41275,
        41304,
        41334,
        41364,
        41393,
        41422,
        41452,
        41481,
        41511,
        41540,
        41570,
        41599,
        41629,
        41658,
        41688,
        41718,
        41748,
        41777,
        41807,
        41836,
        41865,
        41894,
        41924,
        41953,
        41983,
        42012,
        42042,
        42072,
        42102,
        42131,
        42161,
        42190,
        42220,
        42249,
        42279,
        42308,
        42337,
        42367,
        42397,
        42426,
        42456,
        42485,
        42515,
        42545,
        42574,
        42604,
        42633,
        42662,
        42692,
        42721,
        42751,
        42780,
        42810,
        42839,
        42869,
        42899,
        42929,
        42958,
        42988,
        43017,
        43046,
        43076,
        43105,
        43135,
        43164,
        43194,
        43223,
        43253,
        43283,
        43312,
        43342,
        43371,
        43401,
        43430,
        43460,
        43489,
        43519,
        43548,
        43578,
        43607,
        43637,
        43666,
        43696,
        43726,
        43755,
        43785,
        43814,
        43844,
        43873,
        43903,
        43932,
        43962,
        43991,
        44021,
        44050,
        44080,
        44109,
        44139,
        44169,
        44198,
        44228,
        44258,
        44287,
        44317,
        44346,
        44375,
        44405,
        44434,
        44464,
        44493,
        44523,
        44553,
        44582,
        44612,
        44641,
        44671,
        44700,
        44730,
        44759,
        44788,
        44818,
        44847,
        44877,
        44906,
        44936,
        44966,
        44996,
        45025,
        45055,
        45084,
        45114,
        45143,
        45172,
        45202,
        45231,
        45261,
        45290,
        45320,
        45350,
        45380,
        45409,
        45439,
        45468,
        45498,
        45527,
        45556,
        45586,
        45615,
        45644,
        45674,
        45704,
        45733,
        45763,
        45793,
        45823,
        45852,
        45882,
        45911,
        45940,
        45970,
        45999,
        46028,
        46058,
        46088,
        46117,
        46147,
        46177,
        46206,
        46236,
        46265,
        46295,
        46324,
        46354,
        46383,
        46413,
        46442,
        46472,
        46501,
        46531,
        46560,
        46590,
        46620,
        46649,
        46679,
        46708,
        46738,
        46767,
        46797,
        46826,
        46856,
        46885,
        46915,
        46944,
        46974,
        47003,
        47033,
        47063,
        47092,
        47122,
        47151,
        47181,
        47210,
        47240,
        47269,
        47298,
        47328,
        47357,
        47387,
        47417,
        47446,
        47476,
        47506,
        47535,
        47565,
        47594,
        47624,
        47653,
        47682,
        47712,
        47741,
        47771,
        47800,
        47830,
        47860,
        47890,
        47919,
        47949,
        47978,
        48008,
        48037,
        48066,
        48096,
        48125,
        48155,
        48184,
        48214,
        48244,
        48273,
        48303,
        48333,
        48362,
        48392,
        48421,
        48450,
        48480,
        48509,
        48538,
        48568,
        48598,
        48627,
        48657,
        48687,
        48717,
        48746,
        48776,
        48805,
        48834,
        48864,
        48893,
        48922,
        48952,
        48982,
        49011,
        49041,
        49071,
        49100,
        49130,
        49160,
        49189,
        49218,
        49248,
        49277,
        49306,
        49336,
        49365,
        49395,
        49425,
        49455,
        49484,
        49514,
        49543,
        49573,
        49602,
        49632,
        49661,
        49690,
        49720,
        49749,
        49779,
        49809,
        49838,
        49868,
        49898,
        49927,
        49957,
        49986,
        50016,
        50045,
        50075,
        50104,
        50133,
        50163,
        50192,
        50222,
        50252,
        50281,
        50311,
        50340,
        50370,
        50400,
        50429,
        50459,
        50488,
        50518,
        50547,
        50576,
        50606,
        50635,
        50665,
        50694,
        50724,
        50754,
        50784,
        50813,
        50843,
        50872,
        50902,
        50931,
        50960,
        50990,
        51019,
        51049,
        51078,
        51108,
        51138,
        51167,
        51197,
        51227,
        51256,
        51286,
        51315,
        51345,
        51374,
        51403,
        51433,
        51462,
        51492,
        51522,
        51552,
        51582,
        51611,
        51641,
        51670,
        51699,
        51729,
        51758,
        51787,
        51816,
        51846,
        51876,
        51906,
        51936,
        51965,
        51995,
        52025,
        52054,
        52083,
        52113,
        52142,
        52171,
        52200,
        52230,
        52260,
        52290,
        52319,
        52349,
        52379,
        52408,
        52438,
        52467,
        52497,
        52526,
        52555,
        52585,
        52614,
        52644,
        52673,
        52703,
        52733,
        52762,
        52792,
        52822,
        52851,
        52881,
        52910,
        52939,
        52969,
        52998,
        53028,
        53057,
        53087,
        53116,
        53146,
        53176,
        53205,
        53235,
        53264,
        53294,
        53324,
        53353,
        53383,
        53412,
        53441,
        53471,
        53500,
        53530,
        53559,
        53589,
        53619,
        53648,
        53678,
        53708,
        53737,
        53767,
        53796,
        53825,
        53855,
        53884,
        53913,
        53943,
        53973,
        54003,
        54032,
        54062,
        54092,
        54121,
        54151,
        54180,
        54209,
        54239,
        54268,
        54297,
        54327,
        54357,
        54387,
        54416,
        54446,
        54476,
        54505,
        54535,
        54564,
        54593,
        54623,
        54652,
        54681,
        54711,
        54741,
        54770,
        54800,
        54830,
        54859,
        54889,
        54919,
        54948,
        54977,
        55007,
        55036,
        55066,
        55095,
        55125,
        55154,
        55184,
        55213,
        55243,
        55273,
        55302,
        55332,
        55361,
        55391,
        55420,
        55450,
        55479,
        55508,
        55538,
        55567,
        55597,
        55627,
        55657,
        55686,
        55716,
        55745,
        55775,
        55804,
        55834,
        55863,
        55892,
        55922,
        55951,
        55981,
        56011,
        56040,
        56070,
        56100,
        56129,
        56159,
        56188,
        56218,
        56247,
        56276,
        56306,
        56335,
        56365,
        56394,
        56424,
        56454,
        56483,
        56513,
        56543,
        56572,
        56601,
        56631,
        56660,
        56690,
        56719,
        56749,
        56778,
        56808,
        56837,
        56867,
        56897,
        56926,
        56956,
        56985,
        57015,
        57044,
        57074,
        57103,
        57133,
        57162,
        57192,
        57221,
        57251,
        57280,
        57310,
        57340,
        57369,
        57399,
        57429,
        57458,
        57487,
        57517,
        57546,
        57576,
        57605,
        57634,
        57664,
        57694,
        57723,
        57753,
        57783,
        57813,
        57842,
        57871,
        57901,
        57930,
        57959,
        57989,
        58018,
        58048,
        58077,
        58107,
        58137,
        58167,
        58196,
        58226,
        58255,
        58285,
        58314,
        58343,
        58373,
        58402,
        58432,
        58461,
        58491,
        58521,
        58551,
        58580,
        58610,
        58639,
        58669,
        58698,
        58727,
        58757,
        58786,
        58816,
        58845,
        58875,
        58905,
        58934,
        58964,
        58994,
        59023,
        59053,
        59082,
        59111,
        59141,
        59170,
        59200,
        59229,
        59259,
        59288,
        59318,
        59348,
        59377,
        59407,
        59436,
        59466,
        59495,
        59525,
        59554,
        59584,
        59613,
        59643,
        59672,
        59702,
        59731,
        59761,
        59791,
        59820,
        59850,
        59879,
        59909,
        59939,
        59968,
        59997,
        60027,
        60056,
        60086,
        60115,
        60145,
        60174,
        60204,
        60234,
        60264,
        60293,
        60323,
        60352,
        60381,
        60411,
        60440,
        60469,
        60499,
        60528,
        60558,
        60588,
        60618,
        60648,
        60677,
        60707,
        60736,
        60765,
        60795,
        60824,
        60853,
        60883,
        60912,
        60942,
        60972,
        61002,
        61031,
        61061,
        61090,
        61120,
        61149,
        61179,
        61208,
        61237,
        61267,
        61296,
        61326,
        61356,
        61385,
        61415,
        61445,
        61474,
        61504,
        61533,
        61563,
        61592,
        61621,
        61651,
        61680,
        61710,
        61739,
        61769,
        61799,
        61828,
        61858,
        61888,
        61917,
        61947,
        61976,
        62006,
        62035,
        62064,
        62094,
        62123,
        62153,
        62182,
        62212,
        62242,
        62271,
        62301,
        62331,
        62360,
        62390,
        62419,
        62448,
        62478,
        62507,
        62537,
        62566,
        62596,
        62625,
        62655,
        62685,
        62715,
        62744,
        62774,
        62803,
        62832,
        62862,
        62891,
        62921,
        62950,
        62980,
        63009,
        63039,
        63069,
        63099,
        63128,
        63157,
        63187,
        63216,
        63246,
        63275,
        63305,
        63334,
        63363,
        63393,
        63423,
        63453,
        63482,
        63512,
        63541,
        63571,
        63600,
        63630,
        63659,
        63689,
        63718,
        63747,
        63777,
        63807,
        63836,
        63866,
        63895,
        63925,
        63955,
        63984,
        64014,
        64043,
        64073,
        64102,
        64131,
        64161,
        64190,
        64220,
        64249,
        64279,
        64309,
        64339,
        64368,
        64398,
        64427,
        64457,
        64486,
        64515,
        64545,
        64574,
        64603,
        64633,
        64663,
        64692,
        64722,
        64752,
        64782,
        64811,
        64841,
        64870,
        64899,
        64929,
        64958,
        64987,
        65017,
        65047,
        65076,
        65106,
        65136,
        65166,
        65195,
        65225,
        65254,
        65283,
        65313,
        65342,
        65371,
        65401,
        65431,
        65460,
        65490,
        65520,
        65549,
        65579,
        65608,
        65638,
        65667,
        65697,
        65726,
        65755,
        65785,
        65815,
        65844,
        65874,
        65903,
        65933,
        65963,
        65992,
        66022,
        66051,
        66081,
        66110,
        66140,
        66169,
        66199,
        66228,
        66258,
        66287,
        66317,
        66346,
        66376,
        66405,
        66435,
        66465,
        66494,
        66524,
        66553,
        66583,
        66612,
        66641,
        66671,
        66700,
        66730,
        66760,
        66789,
        66819,
        66849,
        66878,
        66908,
        66937,
        66967,
        66996,
        67025,
        67055,
        67084,
        67114,
        67143,
        67173,
        67203,
        67233,
        67262,
        67292,
        67321,
        67351,
        67380,
        67409,
        67439,
        67468,
        67497,
        67527,
        67557,
        67587,
        67617,
        67646,
        67676,
        67705,
        67735,
        67764,
        67793,
        67823,
        67852,
        67882,
        67911,
        67941,
        67971,
        68e3,
        68030,
        68060,
        68089,
        68119,
        68148,
        68177,
        68207,
        68236,
        68266,
        68295,
        68325,
        68354,
        68384,
        68414,
        68443,
        68473,
        68502,
        68532,
        68561,
        68591,
        68620,
        68650,
        68679,
        68708,
        68738,
        68768,
        68797,
        68827,
        68857,
        68886,
        68916,
        68946,
        68975,
        69004,
        69034,
        69063,
        69092,
        69122,
        69152,
        69181,
        69211,
        69240,
        69270,
        69300,
        69330,
        69359,
        69388,
        69418,
        69447,
        69476,
        69506,
        69535,
        69565,
        69595,
        69624,
        69654,
        69684,
        69713,
        69743,
        69772,
        69802,
        69831,
        69861,
        69890,
        69919,
        69949,
        69978,
        70008,
        70038,
        70067,
        70097,
        70126,
        70156,
        70186,
        70215,
        70245,
        70274,
        70303,
        70333,
        70362,
        70392,
        70421,
        70451,
        70481,
        70510,
        70540,
        70570,
        70599,
        70629,
        70658,
        70687,
        70717,
        70746,
        70776,
        70805,
        70835,
        70864,
        70894,
        70924,
        70954,
        70983,
        71013,
        71042,
        71071,
        71101,
        71130,
        71159,
        71189,
        71218,
        71248,
        71278,
        71308,
        71337,
        71367,
        71397,
        71426,
        71455,
        71485,
        71514,
        71543,
        71573,
        71602,
        71632,
        71662,
        71691,
        71721,
        71751,
        71781,
        71810,
        71839,
        71869,
        71898,
        71927,
        71957,
        71986,
        72016,
        72046,
        72075,
        72105,
        72135,
        72164,
        72194,
        72223,
        72253,
        72282,
        72311,
        72341,
        72370,
        72400,
        72429,
        72459,
        72489,
        72518,
        72548,
        72577,
        72607,
        72637,
        72666,
        72695,
        72725,
        72754,
        72784,
        72813,
        72843,
        72872,
        72902,
        72931,
        72961,
        72991,
        73020,
        73050,
        73080,
        73109,
        73139,
        73168,
        73197,
        73227,
        73256,
        73286,
        73315,
        73345,
        73375,
        73404,
        73434,
        73464,
        73493,
        73523,
        73552,
        73581,
        73611,
        73640,
        73669,
        73699,
        73729,
        73758,
        73788,
        73818,
        73848,
        73877,
        73907,
        73936,
        73965,
        73995,
        74024,
        74053,
        74083,
        74113,
        74142,
        74172,
        74202,
        74231,
        74261,
        74291,
        74320,
        74349,
        74379,
        74408,
        74437,
        74467,
        74497,
        74526,
        74556,
        74586,
        74615,
        74645,
        74675,
        74704,
        74733,
        74763,
        74792,
        74822,
        74851,
        74881,
        74910,
        74940,
        74969,
        74999,
        75029,
        75058,
        75088,
        75117,
        75147,
        75176,
        75206,
        75235,
        75264,
        75294,
        75323,
        75353,
        75383,
        75412,
        75442,
        75472,
        75501,
        75531,
        75560,
        75590,
        75619,
        75648,
        75678,
        75707,
        75737,
        75766,
        75796,
        75826,
        75856,
        75885,
        75915,
        75944,
        75974,
        76003,
        76032,
        76062,
        76091,
        76121,
        76150,
        76180,
        76210,
        76239,
        76269,
        76299,
        76328,
        76358,
        76387,
        76416,
        76446,
        76475,
        76505,
        76534,
        76564,
        76593,
        76623,
        76653,
        76682,
        76712,
        76741,
        76771,
        76801,
        76830,
        76859,
        76889,
        76918,
        76948,
        76977,
        77007,
        77036,
        77066,
        77096,
        77125,
        77155,
        77185,
        77214,
        77243,
        77273,
        77302,
        77332,
        77361,
        77390,
        77420,
        77450,
        77479,
        77509,
        77539,
        77569,
        77598,
        77627,
        77657,
        77686,
        77715,
        77745,
        77774,
        77804,
        77833,
        77863,
        77893,
        77923,
        77952,
        77982,
        78011,
        78041,
        78070,
        78099,
        78129,
        78158,
        78188,
        78217,
        78247,
        78277,
        78307,
        78336,
        78366,
        78395,
        78425,
        78454,
        78483,
        78513,
        78542,
        78572,
        78601,
        78631,
        78661,
        78690,
        78720,
        78750,
        78779,
        78808,
        78838,
        78867,
        78897,
        78926,
        78956,
        78985,
        79015,
        79044,
        79074,
        79104,
        79133,
        79163,
        79192,
        79222,
        79251,
        79281,
        79310,
        79340,
        79369,
        79399,
        79428,
        79458,
        79487,
        79517,
        79546,
        79576,
        79606,
        79635,
        79665,
        79695,
        79724,
        79753,
        79783,
        79812,
        79841,
        79871,
        79900,
        79930,
        79960,
        79990
      ];
    }
  });

  // src/components/calendars/calendars.js
  var require_calendars = __commonJS({
    "src/components/calendars/calendars.js"(exports, module) {
      "use strict";
      module.exports = require_main();
      require_plus();
      require_chinese();
      require_coptic();
      require_discworld();
      require_ethiopian();
      require_hebrew();
      require_islamic();
      require_julian();
      require_mayan();
      require_nanakshahi();
      require_nepali();
      require_persian();
      require_taiwan();
      require_thai();
      require_ummalqura();
    }
  });

  // src/components/calendars/index.js
  var require_calendars2 = __commonJS({
    "src/components/calendars/index.js"(exports, module) {
      "use strict";
      var calendars = require_calendars();
      var Lib = require_lib();
      var constants = require_numerical();
      var EPOCHJD = constants.EPOCHJD;
      var ONEDAY = constants.ONEDAY;
      var attributes = {
        valType: "enumerated",
        values: Lib.sortObjectKeys(calendars.calendars),
        editType: "calc",
        dflt: "gregorian"
      };
      var handleDefaults = function(contIn, contOut, attr, dflt) {
        var attrs = {};
        attrs[attr] = attributes;
        return Lib.coerce(contIn, contOut, attrs, attr, dflt);
      };
      var handleTraceDefaults = function(traceIn, traceOut, coords, layout) {
        for (var i = 0; i < coords.length; i++) {
          handleDefaults(traceIn, traceOut, coords[i] + "calendar", layout.calendar);
        }
      };
      var CANONICAL_TICK = {
        chinese: "2000-01-01",
        coptic: "2000-01-01",
        discworld: "2000-01-01",
        ethiopian: "2000-01-01",
        hebrew: "5000-01-01",
        islamic: "1000-01-01",
        julian: "2000-01-01",
        mayan: "5000-01-01",
        nanakshahi: "1000-01-01",
        nepali: "2000-01-01",
        persian: "1000-01-01",
        jalali: "1000-01-01",
        taiwan: "1000-01-01",
        thai: "2000-01-01",
        ummalqura: "1400-01-01"
      };
      var CANONICAL_SUNDAY = {
        chinese: "2000-01-02",
        coptic: "2000-01-03",
        discworld: "2000-01-03",
        ethiopian: "2000-01-05",
        hebrew: "5000-01-01",
        islamic: "1000-01-02",
        julian: "2000-01-03",
        mayan: "5000-01-01",
        nanakshahi: "1000-01-05",
        nepali: "2000-01-05",
        persian: "1000-01-01",
        jalali: "1000-01-01",
        taiwan: "1000-01-04",
        thai: "2000-01-04",
        ummalqura: "1400-01-06"
      };
      var DFLTRANGE = {
        chinese: ["2000-01-01", "2001-01-01"],
        coptic: ["1700-01-01", "1701-01-01"],
        discworld: ["1800-01-01", "1801-01-01"],
        ethiopian: ["2000-01-01", "2001-01-01"],
        hebrew: ["5700-01-01", "5701-01-01"],
        islamic: ["1400-01-01", "1401-01-01"],
        julian: ["2000-01-01", "2001-01-01"],
        mayan: ["5200-01-01", "5201-01-01"],
        nanakshahi: ["0500-01-01", "0501-01-01"],
        nepali: ["2000-01-01", "2001-01-01"],
        persian: ["1400-01-01", "1401-01-01"],
        jalali: ["1400-01-01", "1401-01-01"],
        taiwan: ["0100-01-01", "0101-01-01"],
        thai: ["2500-01-01", "2501-01-01"],
        ummalqura: ["1400-01-01", "1401-01-01"]
      };
      var UNKNOWN = "##";
      var d3ToWorldCalendars = {
        d: { 0: "dd", "-": "d" },
        // 2-digit or unpadded day of month
        e: { 0: "d", "-": "d" },
        // alternate, always unpadded day of month
        a: { 0: "D", "-": "D" },
        // short weekday name
        A: { 0: "DD", "-": "DD" },
        // full weekday name
        j: { 0: "oo", "-": "o" },
        // 3-digit or unpadded day of the year
        W: { 0: "ww", "-": "w" },
        // 2-digit or unpadded week of the year (Monday first)
        m: { 0: "mm", "-": "m" },
        // 2-digit or unpadded month number
        b: { 0: "M", "-": "M" },
        // short month name
        B: { 0: "MM", "-": "MM" },
        // full month name
        y: { 0: "yy", "-": "yy" },
        // 2-digit year (map unpadded to zero-padded)
        Y: { 0: "yyyy", "-": "yyyy" },
        // 4-digit year (map unpadded to zero-padded)
        U: UNKNOWN,
        // Sunday-first week of the year
        w: UNKNOWN,
        // day of the week [0(sunday),6]
        // combined format, we replace the date part with the world-calendar version
        // and the %X stays there for d3 to handle with time parts
        c: { 0: "D M d %X yyyy", "-": "D M d %X yyyy" },
        x: { 0: "mm/dd/yyyy", "-": "mm/dd/yyyy" }
      };
      function worldCalFmt(fmt, x, calendar) {
        var dateJD = Math.floor((x + 0.05) / ONEDAY) + EPOCHJD;
        var cDate = getCal(calendar).fromJD(dateJD);
        var i = 0;
        var modifier, directive, directiveLen, directiveObj, replacementPart;
        while ((i = fmt.indexOf("%", i)) !== -1) {
          modifier = fmt.charAt(i + 1);
          if (modifier === "0" || modifier === "-" || modifier === "_") {
            directiveLen = 3;
            directive = fmt.charAt(i + 2);
            if (modifier === "_") modifier = "-";
          } else {
            directive = modifier;
            modifier = "0";
            directiveLen = 2;
          }
          directiveObj = d3ToWorldCalendars[directive];
          if (!directiveObj) {
            i += directiveLen;
          } else {
            if (directiveObj === UNKNOWN) replacementPart = UNKNOWN;
            else replacementPart = cDate.formatDate(directiveObj[modifier]);
            fmt = fmt.slice(0, i) + replacementPart + fmt.slice(i + directiveLen);
            i += replacementPart.length;
          }
        }
        return fmt;
      }
      var allCals = {};
      function getCal(calendar) {
        var calendarObj = allCals[calendar];
        if (calendarObj) return calendarObj;
        calendarObj = allCals[calendar] = calendars.instance(calendar);
        return calendarObj;
      }
      function makeAttrs(description) {
        return Lib.extendFlat({}, attributes, { description });
      }
      function makeTraceAttrsDescription(coord) {
        return "Sets the calendar system to use with `" + coord + "` date data.";
      }
      var xAttrs = {
        xcalendar: makeAttrs(makeTraceAttrsDescription("x"))
      };
      var xyAttrs = Lib.extendFlat({}, xAttrs, {
        ycalendar: makeAttrs(makeTraceAttrsDescription("y"))
      });
      var xyzAttrs = Lib.extendFlat({}, xyAttrs, {
        zcalendar: makeAttrs(makeTraceAttrsDescription("z"))
      });
      var axisAttrs = makeAttrs([
        "Sets the calendar system to use for `range` and `tick0`",
        "if this is a date axis. This does not set the calendar for",
        "interpreting data on this axis, that's specified in the trace",
        "or via the global `layout.calendar`"
      ].join(" "));
      module.exports = {
        moduleType: "component",
        name: "calendars",
        schema: {
          traces: {
            scatter: xyAttrs,
            bar: xyAttrs,
            box: xyAttrs,
            heatmap: xyAttrs,
            contour: xyAttrs,
            histogram: xyAttrs,
            histogram2d: xyAttrs,
            histogram2dcontour: xyAttrs,
            scatter3d: xyzAttrs,
            surface: xyzAttrs,
            mesh3d: xyzAttrs,
            scattergl: xyAttrs,
            ohlc: xAttrs,
            candlestick: xAttrs
          },
          layout: {
            calendar: makeAttrs([
              "Sets the default calendar system to use for interpreting and",
              "displaying dates throughout the plot."
            ].join(" "))
          },
          subplots: {
            xaxis: { calendar: axisAttrs },
            yaxis: { calendar: axisAttrs },
            scene: {
              xaxis: { calendar: axisAttrs },
              // TODO: it's actually redundant to include yaxis and zaxis here
              // because in the scene attributes these are the same object so merging
              // into one merges into them all. However, I left them in for parity with
              // cartesian, where yaxis is unused until we Plotschema.get() when we
              // use its presence or absence to determine whether to delete attributes
              // from yaxis if they only apply to x (rangeselector/rangeslider)
              yaxis: { calendar: axisAttrs },
              zaxis: { calendar: axisAttrs }
            },
            polar: {
              radialaxis: { calendar: axisAttrs }
            }
          }
        },
        layoutAttributes: attributes,
        handleDefaults,
        handleTraceDefaults,
        CANONICAL_SUNDAY,
        CANONICAL_TICK,
        DFLTRANGE,
        getCal,
        worldCalFmt
      };
    }
  });

  // lib/calendars.js
  var require_calendars3 = __commonJS({
    "lib/calendars.js"(exports, module) {
      "use strict";
      module.exports = require_calendars2();
    }
  });

  // lib/index.js
  var require_index = __commonJS({
    "lib/index.js"(exports, module) {
      var Plotly = require_core2();
      Plotly.register([
        // traces
        require_bar2(),
        require_box2(),
        require_heatmap2(),
        require_histogram2(),
        require_histogram2d2(),
        require_histogram2dcontour2(),
        require_contour2(),
        require_scatterternary2(),
        require_violin2(),
        require_funnel2(),
        require_waterfall2(),
        require_image2(),
        require_pie2(),
        require_sunburst2(),
        require_treemap2(),
        require_icicle2(),
        require_funnelarea2(),
        require_scatter3d2(),
        require_surface2(),
        require_isosurface2(),
        require_volume2(),
        require_mesh3d2(),
        require_cone2(),
        require_streamtube2(),
        require_scattergeo2(),
        require_choropleth2(),
        require_scattergl2(),
        require_splom2(),
        require_parcoords3(),
        require_parcats3(),
        require_scattermapbox2(),
        require_choroplethmapbox2(),
        require_densitymapbox2(),
        require_scattermap2(),
        require_choroplethmap2(),
        require_densitymap2(),
        require_sankey2(),
        require_indicator2(),
        require_table2(),
        require_carpet2(),
        require_scattercarpet2(),
        require_contourcarpet2(),
        require_ohlc2(),
        require_candlestick2(),
        require_scatterpolar2(),
        require_scatterpolargl2(),
        require_barpolar2(),
        require_scattersmith2(),
        // components
        require_calendars3()
      ]);
      module.exports = Plotly;
    }
  });
  return require_index();
})();
/*!
 * pad-left <https://github.com/jonschlinkert/pad-left>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT license.
 */
/*!
 * repeat-string <https://github.com/jonschlinkert/repeat-string>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/*!
 * Determine if an object is a Buffer
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/*! Bundled license information:

native-promise-only/lib/npo.src.js:
  (*! Native Promise Only
      v0.8.1 (c) Kyle Simpson
      MIT License: http://getify.mit-license.org
  *)

polybooljs/index.js:
  (*
   * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc
   * @license MIT
   * @preserve Project Home: https://github.com/voidqk/polybooljs
   *)

ieee754/index.js:
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)

buffer/index.js:
  (*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   *)

safe-buffer/index.js:
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)

assert/build/internal/util/comparisons.js:
  (*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
   * @license  MIT
   *)

object-assign/index.js:
  (*
  object-assign
  (c) Sindre Sorhus
  @license MIT
  *)

maplibre-gl/dist/maplibre-gl.js:
  (**
   * MapLibre GL JS
   * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v4.7.1/LICENSE.txt
   *)
*/

window.Plotly = Plotly;
return Plotly;
}));